lurqrun 0.1.5 → 0.1.7
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 +23 -13
- package/dist/auditHandler-JCOJSUYW.js +23 -0
- package/dist/bin/lurq.js +3085 -17723
- package/dist/browserAuth-B6G27USY.js +95 -0
- package/dist/cache-DKI34SVS.js +12 -0
- package/dist/check-2FDGUOV7.js +192 -0
- package/dist/checkUpgrade-F2WESBPM.js +103 -0
- package/dist/chunk-2VMOWSRY.js +300 -0
- package/dist/chunk-3GHJR7XR.js +2049 -0
- package/dist/chunk-3N3Q3DSW.js +214 -0
- package/dist/chunk-4ESO33J6.js +34 -0
- package/dist/chunk-4F7ZESPO.js +132 -0
- package/dist/chunk-4KCPOMG6.js +68 -0
- package/dist/chunk-4ZYCIMY4.js +155 -0
- package/dist/chunk-63MUJNZL.js +318 -0
- package/dist/chunk-6AAEVQ7I.js +6336 -0
- package/dist/chunk-6EQ3ARXA.js +304 -0
- package/dist/chunk-6L3U7DZ5.js +23 -0
- package/dist/chunk-AHBP533R.js +220 -0
- package/dist/chunk-B43LCXBM.js +223 -0
- package/dist/chunk-BCANRN5B.js +33 -0
- package/dist/chunk-BUALU27S.js +123 -0
- package/dist/chunk-BULZAX2U.js +1554 -0
- package/dist/chunk-BV32UNLL.js +154 -0
- package/dist/chunk-C6GLE626.js +160 -0
- package/dist/chunk-CIDWNUAP.js +145 -0
- package/dist/chunk-CUP36ND3.js +2126 -0
- package/dist/chunk-CW5HJ3LX.js +96 -0
- package/dist/chunk-DB2VF5UD.js +315 -0
- package/dist/chunk-DWAGCNEL.js +210 -0
- package/dist/chunk-EA3DP5HG.js +293 -0
- package/dist/chunk-ELGCAM7P.js +184 -0
- package/dist/chunk-FW6BD2NO.js +1915 -0
- package/dist/chunk-GE37NVLN.js +15 -0
- package/dist/chunk-GPTKSNR6.js +171 -0
- package/dist/chunk-GRJXQBQZ.js +793 -0
- package/dist/chunk-HWBBVLOT.js +92 -0
- package/dist/chunk-I2JUKN6Z.js +24 -0
- package/dist/chunk-I3M2KJXB.js +56 -0
- package/dist/chunk-IQ4SDKKY.js +733 -0
- package/dist/chunk-J5FZYN4A.js +116 -0
- package/dist/chunk-L6N4JFW2.js +263 -0
- package/dist/chunk-LBFGSSF2.js +126 -0
- package/dist/chunk-LEGPB7DO.js +81 -0
- package/dist/chunk-LO35HLQZ.js +219 -0
- package/dist/chunk-LRD4GBYE.js +73 -0
- package/dist/chunk-LUAKDHLZ.js +40 -0
- package/dist/chunk-LYMPYETA.js +965 -0
- package/dist/chunk-M6NYEXCW.js +38 -0
- package/dist/chunk-MHUEVBVO.js +35 -0
- package/dist/chunk-MYGSLK44.js +37 -0
- package/dist/chunk-NH5I4KHH.js +201 -0
- package/dist/chunk-OQS4GUSI.js +1391 -0
- package/dist/chunk-PSX3GIAN.js +176 -0
- package/dist/chunk-Q5VPF4WI.js +26 -0
- package/dist/chunk-QKGYDMWB.js +7409 -0
- package/dist/chunk-QSL6QN5X.js +115 -0
- package/dist/chunk-SHCEBP3J.js +107 -0
- package/dist/chunk-SJOVFF7B.js +201 -0
- package/dist/chunk-ST2X2GYN.js +373 -0
- package/dist/chunk-TNTXWSYA.js +19 -0
- package/dist/chunk-U5AT3TD4.js +2128 -0
- package/dist/chunk-UDVNA7EA.js +483 -0
- package/dist/chunk-VL2E5T2A.js +109 -0
- package/dist/chunk-VLRHFMGJ.js +58 -0
- package/dist/chunk-WHX2ZFCG.js +4048 -0
- package/dist/chunk-WQ23REYT.js +37 -0
- package/dist/chunk-XBIDMHSK.js +15425 -0
- package/dist/chunk-Y5GI7RL3.js +66 -0
- package/dist/client-IRKAMDYZ.js +15 -0
- package/dist/commands-FIL5ET6P.js +911 -0
- package/dist/compat-R3UTFQ5Q.js +201 -0
- package/dist/dashboardIssue-WYYMBFIB.js +192 -0
- package/dist/diff-GZA2774U.js +13 -0
- package/dist/dist-4XXIXHHZ.js +12945 -0
- package/dist/e2b-FVPHDULZ.js +172 -0
- package/dist/extract-NKGKLIVT.js +444 -0
- package/dist/fetch-QYTUJVG2.js +22 -0
- package/dist/firstTouch-QQTJH4QX.js +55 -0
- package/dist/handlers-GEJAVZDK.js +53 -0
- package/dist/http-ETPYMBGD.js +5360 -0
- package/dist/ingestQueue-VKN4KBIF.js +35 -0
- package/dist/install-EK3W2COX.js +20 -0
- package/dist/installSkill-VQJWJVCL.js +52 -0
- package/dist/inventory-5AWSLJYU.js +31 -0
- package/dist/local-XPZMRH5R.js +13 -0
- package/dist/mcp-3JHD5SUZ.js +472 -0
- package/dist/mcpHandlers-QFN4MCFL.js +22 -0
- package/dist/mcpScan-QZHWENIP.js +1871 -0
- package/dist/mcpScanWorkflow-JPYCBGC4.js +81 -0
- package/dist/mcpStack-BYJCZNIV.js +20 -0
- package/dist/packages-THVFMWFP.js +42 -0
- package/dist/plan-V4OEI3J4.js +463 -0
- package/dist/planView-JRXGCG2N.js +79 -0
- package/dist/policy-3P6BGRDN.js +115 -0
- package/dist/references-6N7VEPHT.js +14 -0
- package/dist/release-4U4ABNSJ.js +128 -0
- package/dist/remote-YGCXYI4V.js +32 -0
- package/dist/reportRuns-CKQQYLY4.js +64 -0
- package/dist/sandbox-MEZLAODF.js +39 -0
- package/dist/server-KFUD5X57.js +55 -0
- package/dist/surface-V62GE554.js +141 -0
- package/dist/surface-YL6O67W3.js +36 -0
- package/dist/surfaceHandlers-X2IZKA3E.js +20 -0
- package/dist/typecheck-X7U5ELMR.js +268 -0
- package/dist/types-M5JP2W3D.js +10 -0
- package/dist/uninstall-P7RGBX6G.js +174 -0
- package/dist/upgrade-NQ5IWFZB.js +596 -0
- package/dist/upgradePlan-A4LRKLEG.js +146 -0
- package/dist/userConfig-Z3GQE776.js +20 -0
- package/dist/watch-DGFMWUDL.js +214 -0
- package/package.json +41 -26
- package/templates/agent-rules.md +4 -4
- package/templates/skill-instructions.md +18 -14
- package/dist/bin/lurq.js.map +0 -1
- package/dist/index.d.ts +0 -764
- package/dist/index.js +0 -17992
- package/dist/index.js.map +0 -1
- package/drizzle/0000_confused_fabian_cortez.sql +0 -54
- package/drizzle/0001_aspiring_timeslip.sql +0 -15
- package/drizzle/0002_lyrical_lila_cheney.sql +0 -14
- package/drizzle/0003_violet_giant_girl.sql +0 -14
- package/drizzle/0004_slim_valeria_richards.sql +0 -15
- package/drizzle/0005_petite_luke_cage.sql +0 -12
- package/drizzle/0006_calm_nighthawk.sql +0 -3
- package/drizzle/0007_slimy_naoko.sql +0 -1
- package/drizzle/0008_peaceful_tigra.sql +0 -1
- package/drizzle/0009_smooth_harrier.sql +0 -10
- package/drizzle/0010_curved_amphibian.sql +0 -2
- package/drizzle/0011_compat_provenance_closures.sql +0 -11
- package/drizzle/0012_api_surfaces.sql +0 -9
- package/drizzle/0013_nice_thanos.sql +0 -1
- package/drizzle/0014_luxuriant_malcolm_colcord.sql +0 -10
- package/drizzle/0015_past_fat_cobra.sql +0 -11
- package/drizzle/0016_futuristic_junta.sql +0 -50
- package/drizzle/0017_absent_grandmaster.sql +0 -20
- package/drizzle/0018_rainy_proemial_gods.sql +0 -1
- package/drizzle/0019_dashing_korvac.sql +0 -11
- package/drizzle/0020_normal_vulture.sql +0 -3
- package/drizzle/0021_dazzling_blue_shield.sql +0 -17
- package/drizzle/0022_massive_ghost_rider.sql +0 -24
- package/drizzle/0023_next_shatterstar.sql +0 -1
- package/drizzle/0024_dusty_maelstrom.sql +0 -15
- package/drizzle/0025_gifted_harpoon.sql +0 -5
- package/drizzle/0026_awesome_mordo.sql +0 -1
- package/drizzle/0027_charming_ulik.sql +0 -2
- package/drizzle/0028_romantic_loners.sql +0 -2
- package/drizzle/0029_busy_korvac.sql +0 -16
- package/drizzle/0030_steady_mathemanic.sql +0 -6
- package/drizzle/0031_redundant_maginty.sql +0 -2
- package/drizzle/0032_stack_resolutions.sql +0 -14
- package/drizzle/0033_graceful_tyger_tiger.sql +0 -3
- package/drizzle/0034_api_key_scopes.sql +0 -1
- package/drizzle/0035_policy_audit.sql +0 -21
- package/drizzle/meta/0000_snapshot.json +0 -370
- package/drizzle/meta/0001_snapshot.json +0 -482
- package/drizzle/meta/0002_snapshot.json +0 -575
- package/drizzle/meta/0003_snapshot.json +0 -667
- package/drizzle/meta/0004_snapshot.json +0 -769
- package/drizzle/meta/0005_snapshot.json +0 -864
- package/drizzle/meta/0006_snapshot.json +0 -882
- package/drizzle/meta/0007_snapshot.json +0 -876
- package/drizzle/meta/0008_snapshot.json +0 -882
- package/drizzle/meta/0009_snapshot.json +0 -948
- package/drizzle/meta/0010_snapshot.json +0 -969
- package/drizzle/meta/0011_snapshot.json +0 -1049
- package/drizzle/meta/0012_snapshot.json +0 -1115
- package/drizzle/meta/0013_snapshot.json +0 -1121
- package/drizzle/meta/0014_snapshot.json +0 -1190
- package/drizzle/meta/0015_snapshot.json +0 -1280
- package/drizzle/meta/0016_snapshot.json +0 -1683
- package/drizzle/meta/0017_snapshot.json +0 -1834
- package/drizzle/meta/0018_snapshot.json +0 -1834
- package/drizzle/meta/0019_snapshot.json +0 -1909
- package/drizzle/meta/0020_snapshot.json +0 -1921
- package/drizzle/meta/0021_snapshot.json +0 -2045
- package/drizzle/meta/0022_snapshot.json +0 -2246
- package/drizzle/meta/0023_snapshot.json +0 -2252
- package/drizzle/meta/0024_snapshot.json +0 -2375
- package/drizzle/meta/0025_snapshot.json +0 -2407
- package/drizzle/meta/0026_snapshot.json +0 -2413
- package/drizzle/meta/0027_snapshot.json +0 -2425
- package/drizzle/meta/0028_snapshot.json +0 -2438
- package/drizzle/meta/0029_snapshot.json +0 -2546
- package/drizzle/meta/0030_snapshot.json +0 -2586
- package/drizzle/meta/0031_snapshot.json +0 -2598
- package/drizzle/meta/0032_snapshot.json +0 -2699
- package/drizzle/meta/0033_snapshot.json +0 -2712
- package/drizzle/meta/0034_snapshot.json +0 -2719
- package/drizzle/meta/0035_snapshot.json +0 -2869
- package/drizzle/meta/_journal.json +0 -258
- package/src/data/seed.json +0 -253
package/dist/bin/lurq.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../node_modules/tsup/assets/esm_shims.js","../../package.json","../../src/core/constants.ts","../../src/core/logger.ts","../../src/core/paths.ts","../../src/core/userConfig.ts","../../src/cli/installSkill.ts","../../src/core/open.ts","../../src/cli/format.ts","../../src/cli/remote.ts","../../src/cli/browserAuth.ts","../../src/cli/install.ts","../../src/policy/enforce.ts","../../src/policy/parse.ts","../../src/cli/policy.ts","../../src/core/config.ts","../../src/core/types.ts","../../src/core/capabilities.ts","../../src/db/schema.ts","../../src/db/client.ts","../../src/db/packages.ts","../../src/core/cache.ts","../../src/db/compat.ts","../../src/db/stackResolutions.ts","../../src/pipeline/resolveCheck.ts","../../src/core/http.ts","../../src/ingestion/sources/npmRegistry.ts","../../src/ingestion/sources/npmSearch.ts","../../src/ingestion/sources/npmDownloads.ts","../../src/ingestion/sources/github.ts","../../src/ingestion/sources/depsDev.ts","../../src/ingestion/sources/bundlephobia.ts","../../src/ingestion/sources/index.ts","../../src/compat/members.ts","../../src/compat/peerCompat.ts","../../src/compat/check.ts","../../src/usage/diff.ts","../../src/core/concurrency.ts","../../src/db/apiSurfaces.ts","../../src/usage/extract.ts","../../src/usage/service.ts","../../src/db/verification.ts","../../src/data/successors.json","../../src/core/successors.ts","../../src/db/outcomes.ts","../../src/ingestion/sources/githubReadme.ts","../../src/ingestion/summarize.ts","../../src/ingestion/collect.ts","../../src/search/categoryInference.ts","../../src/scoring/weights.ts","../../src/scoring/score.ts","../../src/scoring/index.ts","../../src/search/embeddings.ts","../../src/db/alerts.ts","../../src/github/types.ts","../../src/db/repos.ts","../../src/github/attribute.ts","../../src/ingestion/sources/osv.ts","../../src/pipeline/ingestQueue.ts","../../src/github/drift.ts","../../src/github/alerts.ts","../../src/core/runtimeTarget.ts","../../src/pipeline/sync.ts","../../src/pipeline/single.ts","../../src/search/recommend.ts","../../src/policy/types.ts","../../src/db/selectionPolicy.ts","../../src/security/verdict.ts","../../src/data/popular-packages.json","../../src/security/typosquat.ts","../../src/mcp/handlers.ts","../../src/compat/optimize.ts","../../src/mcp/diagram.ts","../../src/mcp/plan.ts","../../src/cli/planView.ts","../../src/db/discovery.ts","../../src/graph/types.ts","../../src/db/graph.ts","../../src/db/surface.ts","../../src/db/watch.ts","../../src/pipeline/watch.ts","../../src/sandbox/types.ts","../../src/sandbox/local.ts","../../src/sandbox/e2b.ts","../../src/sandbox/index.ts","../../src/pipeline/sandbox.ts","../../src/pipeline/compat.ts","../../src/surface/types.ts","../../src/surface/diff.ts","../../src/surface/mcp.ts","../../src/surface/mcpRegistry.ts","../../src/core/errors.ts","../../src/surface/resolve.ts","../../src/surface/extract.ts","../../src/surface/fetch.ts","../../src/pipeline/surface.ts","../../src/pipeline/firstTouch.ts","../../src/mcp/surfaceHandlers.ts","../../src/mcp/mcpHandlers.ts","../../src/graph/oracles/mcpServer.ts","../../src/pipeline/mcp.ts","../../src/audit/inventory.ts","../../src/compat/mcpStack.ts","../../src/audit/assess.ts","../../src/mcp/auditHandler.ts","../../src/audit/types.ts","../../src/cli/commands.ts","../../src/github/app.ts","../../src/github/workflow.ts","../../src/github/manifests.ts","../../src/cli/upgradePlan.ts","../../src/cli/reportRuns.ts","../../src/surface/references.ts","../../src/surface/upgrade.ts","../../src/cli/checkUpgrade.ts","../../src/surface/release.ts","../../src/api/diff.ts","../../src/api/openapi.ts","../../src/api/check.ts","../../src/mcp/metrics.ts","../../src/mcp/compact.ts","../../src/mcp/toolDescriptions.ts","../../src/db/usage.ts","../../src/core/analytics.ts","../../src/mcp/server.ts","../../src/auth/apiKeys.ts","../../src/policy/conformance.ts","../../src/core/plans.ts","../../src/db/subscriptions.ts","../../src/billing/stripe.ts","../../src/github/hops.ts","../../src/github/brief.ts","../../src/db/askSpend.ts","../../src/github/scope.ts","../../src/github/runs.ts","../../src/db/upgradeRuns.ts","../../src/github/publicScan.ts","../../src/github/webhook.ts","../../src/github/sbom.ts","../../src/pipeline/repoScan.ts","../../src/mcp/dashboardTools.ts","../../src/mcp/http.ts","../../src/bin/lurq.ts","../../src/cli/index.ts","../../src/core/gate.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","{\n \"name\": \"lurqrun\",\n \"version\": \"0.1.5\",\n \"description\": \"A continuously-updated, evidence-scored index of JS/TS frameworks and libraries, exposed as an MCP server, CLI, and agent skill — so AI coding assistants get fresh, objective dependency recommendations.\",\n \"type\": \"module\",\n \"license\": \"MIT\",\n \"author\": \"jadenryu\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/jadenryu/lurq.git\"\n },\n \"homepage\": \"https://github.com/jadenryu/lurq#readme\",\n \"bugs\": {\n \"url\": \"https://github.com/jadenryu/lurq/issues\"\n },\n \"keywords\": [\n \"mcp\",\n \"model-context-protocol\",\n \"npm\",\n \"dependencies\",\n \"recommendations\",\n \"claude-code\",\n \"ai-coding\"\n ],\n \"bin\": {\n \"lurq\": \"dist/bin/lurq.js\"\n },\n \"workspaces\": [\n \"apps/*\"\n ],\n \"files\": [\n \"dist\",\n \"src/data/seed.json\",\n \"templates\",\n \"drizzle\",\n \"README.md\"\n ],\n \"engines\": {\n \"node\": \">=20\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsx src/bin/lurq.ts\",\n \"lurq\": \"tsx src/bin/lurq.ts\",\n \"dev:apps\": \"npm run dev --workspace @lurq/docs & npm run dev --workspace @lurq/web\",\n \"benchmark:validate\": \"tsx src/bin/benchmark.ts validate\",\n \"benchmark:run\": \"tsx src/bin/benchmark.ts run\",\n \"start\": \"node dist/bin/lurq.js\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"typecheck\": \"tsc --noEmit\",\n \"lint\": \"eslint .\",\n \"format\": \"prettier --write .\",\n \"format:check\": \"prettier --check .\",\n \"db:generate\": \"drizzle-kit generate\",\n \"db:migrate\": \"tsx src/bin/operator.ts db migrate\",\n \"operator\": \"tsx src/bin/operator.ts\",\n \"operator:prod\": \"LURQ_ENV_FILE=.env.production tsx src/bin/operator.ts\",\n \"prepublishOnly\": \"npm test && npm run build\",\n \"content:drift\": \"tsx scripts/gen-drift.ts\",\n \"content:landing\": \"tsx scripts/build-landing-content.mts\",\n \"content:releases\": \"tsx scripts/gen-releases.ts\"\n },\n \"dependencies\": {\n \"@inquirer/prompts\": \"^8.5.2\",\n \"@modelcontextprotocol/sdk\": \"^1.29.0\",\n \"commander\": \"^12.1.0\",\n \"dotenv\": \"^16.4.5\",\n \"drizzle-orm\": \"^0.45.2\",\n \"express\": \"^5.2.1\",\n \"express-rate-limit\": \"^8.5.2\",\n \"helmet\": \"^8.2.0\",\n \"ioredis\": \"^5.11.1\",\n \"postgres\": \"^3.4.9\",\n \"rate-limit-redis\": \"^4.3.1\",\n \"semver\": \"^7.8.5\",\n \"stripe\": \"^22.6.0\",\n \"typescript\": \"^5.5.4\",\n \"update-notifier\": \"^7.3.1\",\n \"yaml\": \"^2.9.0\",\n \"zod\": \"^3.23.8\"\n },\n \"devDependencies\": {\n \"@eslint/js\": \"^9.9.0\",\n \"@types/express\": \"^5.0.6\",\n \"@types/node\": \"^22.5.0\",\n \"@types/semver\": \"^7.7.1\",\n \"drizzle-kit\": \"^0.31.10\",\n \"e2b\": \"^2.31.0\",\n \"eslint\": \"^9.9.0\",\n \"marked\": \"^18.0.9\",\n \"pdfjs-dist\": \"^6.2.108\",\n \"playwright\": \"^1.62.1\",\n \"prettier\": \"^3.3.3\",\n \"tsup\": \"^8.2.4\",\n \"tsx\": \"^4.19.0\",\n \"typescript-eslint\": \"^8.3.0\",\n \"vitest\": \"^2.0.5\"\n }\n}\n","/** Static identifiers shared across the CLI and MCP server. */\nimport pkg from '../../package.json' with { type: 'json' };\n\nexport const SERVER_NAME = 'lurq';\n/** Published npm package name (the CLI command and MCP nickname stay `lurq`).\n * Keep in sync with package.json \"name\". */\nexport const PACKAGE_NAME = 'lurqrun';\n/**\n * Read from package.json rather than restated, so a release bump cannot leave\n * it behind. This used to be a literal under a \"keep in sync\" comment, and it\n * drifted the moment someone bumped package.json alone: 0.0.9 shipped to npm\n * announcing itself as 0.0.8.\n *\n * That is not only cosmetic. github/workflow.ts defaults `cliSpec()` to this\n * value and bakes it into the `npx lurqrun@<v>` line of every workflow lurq\n * generates, so a stale constant writes users a CI job pinned to a version\n * other than the one that wrote it.\n *\n * The import is resolved at build time — esbuild inlines the JSON, so there is\n * no file read at runtime and no dependence on where the bundle sits on disk.\n * That last part is why this is an import and not a `readFileSync` of a path\n * relative to `import.meta.url`: the public bin lands at dist/bin/lurq.js and\n * the library entry at dist/index.js, so any relative path correct for one is\n * wrong for the other.\n */\nexport const VERSION: string = pkg.version;\n\n/** Default hosted endpoint the install wizard writes into agent configs. The\n * marketing site is `lurq.run`; the MCP service lives on the `api.` subdomain.\n * Overridable per-invocation with `lurq install --url …` or `LURQ_ENDPOINT`. */\nexport const DEFAULT_ENDPOINT = 'https://api.lurq.run/mcp';\n\n/** Prefix for issued API keys (the rest is high-entropy random). */\nexport const API_KEY_PREFIX = 'lurq_live_';\n\n/** Embedding vector dimensionality (OpenAI text-embedding-3-small). The local\n * fallback embedder produces vectors of the same length so the DB column and\n * pgvector index never need to change. */\nexport const EMBEDDING_DIM = 1536;\n\n/** A package row is flagged `stale: true` in tool responses once its data is\n * older than this (§17). */\nexport const STALENESS_DAYS = 7;\n\nconst HOUR = 60 * 60 * 1000;\nconst DAY = 24 * HOUR;\n\n/** Per-source persistent-cache TTLs (§17). */\nexport const CACHE_TTL = {\n npmRegistry: 6 * HOUR,\n npmDownloads: 12 * HOUR,\n github: 12 * HOUR,\n depsDev: 24 * HOUR,\n bundlephobia: 7 * DAY,\n} as const;\n","/**\n * Minimal leveled logger.\n *\n * IMPORTANT: all output goes to **stderr**. The MCP server communicates over\n * stdio (stdout is the protocol channel), so anything written to stdout would\n * corrupt the JSON-RPC stream. Never log to stdout.\n */\n\nconst LEVELS = { error: 0, warn: 1, info: 2, debug: 3 } as const;\nexport type LogLevel = keyof typeof LEVELS;\n\nfunction currentLevel(): number {\n const raw = process.env.LOG_LEVEL as LogLevel | undefined;\n return raw && raw in LEVELS ? LEVELS[raw] : LEVELS.info;\n}\n\nfunction emit(level: LogLevel, args: unknown[]): void {\n if (LEVELS[level] > currentLevel()) return;\n const parts = args.map((a) =>\n typeof a === 'string' ? a : a instanceof Error ? (a.stack ?? a.message) : safeStringify(a),\n );\n process.stderr.write(`[lurq] ${level.toUpperCase()} ${parts.join(' ')}\\n`);\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nexport const logger = {\n error: (...args: unknown[]) => emit('error', args),\n warn: (...args: unknown[]) => emit('warn', args),\n info: (...args: unknown[]) => emit('info', args),\n debug: (...args: unknown[]) => emit('debug', args),\n};\n","/**\n * Locate package-relative resources at runtime. Works in dev (tsx, source under\n * src/) and when published (bundled under dist/), by walking up from this module\n * until a directory containing package.json is found.\n */\nimport { existsSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nlet cachedRoot: string | undefined;\n\n/** Absolute path to the installed lurq package root (the dir with package.json). */\nexport function packageRoot(): string {\n if (cachedRoot) return cachedRoot;\n let dir = dirname(fileURLToPath(import.meta.url));\n // Walk up to the filesystem root looking for our package.json.\n for (;;) {\n if (existsSync(join(dir, 'package.json'))) {\n cachedRoot = dir;\n return dir;\n }\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n // Fallback: current working directory.\n cachedRoot = process.cwd();\n return cachedRoot;\n}\n\n/** Folder holding generated Drizzle migrations. */\nexport function migrationsDir(): string {\n return join(packageRoot(), 'drizzle');\n}\n\n/** The curated seed list shipped with the package. */\nexport function seedJsonPath(): string {\n return join(packageRoot(), 'src', 'data', 'seed.json');\n}\n\n/** User-level weight-override config (§4): `~/.config/lurq/weights.json`. */\nexport function userWeightsPath(): string {\n const base = process.env.XDG_CONFIG_HOME || join(homedir(), '.config');\n return join(base, 'lurq', 'weights.json');\n}\n\n/** Project-local weight-override config (§4): `.lurq/weights.json` in the cwd.\n * Takes precedence over the user-level file when present. */\nexport function projectWeightsPath(): string {\n return join(process.cwd(), '.lurq', 'weights.json');\n}\n","/**\n * Persistent per-user CLI credentials: `~/.lurq/config.json`.\n *\n * `lurq setup` writes the API key here once, and every later command reads it\n * back. That is what makes a global install usable in any\n * directory without exporting `LURQ_API_KEY` in a shell profile first. The key\n * is also written into each agent's MCP config, but those files belong to the\n * agents; this one belongs to the CLI.\n *\n * Nothing else lives here. Weights have their own file (`~/.config/lurq/\n * weights.json`), and server-side settings stay in the environment.\n */\nimport { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\n\nexport interface UserConfig {\n apiKey?: string;\n /** Only stored when it differs from the built-in default (self-hosted service). */\n endpoint?: string;\n}\n\n/** `~/.lurq`, also where the agent instruction template is copied. */\nexport function lurqHome(): string {\n return process.env.LURQ_HOME || join(homedir(), '.lurq');\n}\n\nexport function userConfigPath(): string {\n return join(lurqHome(), 'config.json');\n}\n\n/** Read the stored config. Returns `{}` when absent, empty, or corrupt: a\n * hand-mangled config file should not make every command throw. */\nexport function readUserConfig(): UserConfig {\n const path = userConfigPath();\n if (!existsSync(path)) return {};\n try {\n const parsed = JSON.parse(readFileSync(path, 'utf8'));\n return parsed && typeof parsed === 'object' ? (parsed as UserConfig) : {};\n } catch {\n return {};\n }\n}\n\n/**\n * Merge into the stored config and write it back at mode 0600.\n *\n * The file holds a live credential, so it is written owner-only and via\n * temp-file + rename: an interrupted write leaves the previous key intact\n * rather than a truncated file that reads as \"no key configured\". `chmod`\n * happens on the temp file, before the rename, so the key is never briefly\n * world-readable at its final path.\n */\nexport function writeUserConfig(patch: UserConfig): string {\n const path = userConfigPath();\n const next = { ...readUserConfig(), ...patch };\n mkdirSync(dirname(path), { recursive: true });\n const tmp = `${path}.${process.pid}.tmp`;\n try {\n writeFileSync(tmp, JSON.stringify(next, null, 2) + '\\n', { mode: 0o600 });\n chmodSync(tmp, 0o600);\n renameSync(tmp, path);\n } catch (err) {\n try {\n rmSync(tmp, { force: true });\n } catch {\n /* best-effort cleanup; report the original failure */\n }\n throw err;\n }\n return path;\n}\n\n/** Remove the stored credentials (`lurq logout`). Returns false if none existed. */\nexport function clearUserConfig(): boolean {\n const path = userConfigPath();\n if (!existsSync(path)) return false;\n rmSync(path, { force: true });\n return true;\n}\n\n/**\n * The API key to use, in precedence order: an explicit flag, then the\n * environment (CI sets `LURQ_API_KEY` as a secret), then the stored config.\n *\n * The environment deliberately beats the stored file so a CI runner or a\n * one-off `LURQ_API_KEY=… lurq …` overrides a developer's saved key rather than\n * being silently ignored.\n */\nexport function resolveApiKey(override?: string): string | undefined {\n return override?.trim() || process.env.LURQ_API_KEY?.trim() || readUserConfig().apiKey?.trim();\n}\n\n/** Same precedence as `resolveApiKey`, for the hosted endpoint URL. */\nexport function resolveEndpoint(override?: string): string | undefined {\n return override?.trim() || process.env.LURQ_ENDPOINT?.trim() || readUserConfig().endpoint?.trim();\n}\n","/**\n * Agent skill installer (§14). Registers lurq as an MCP server in supported\n * assistants by MERGING a single `lurq` entry into each agent's config — never\n * overwriting unrelated config — and drops the skill-instructions file.\n *\n * Two modes:\n * - **remote** (hosted, default for real users): writes a keyed HTTP entry\n * pointing at the lurq service. No DATABASE_URL ever touches a user's machine.\n * - **local** (self-host / contributors): writes the legacy stdio entry that\n * runs `lurq serve` locally against the user's own DB.\n *\n * MCP config formats move fast and differ per agent; this writes the current\n * widely-supported shapes and prints exactly what it did, so a stale path is\n * obvious rather than silent. Remote shapes verified against current agent docs\n * (2026-06): Claude Code / VS Code use `{ type:\"http\", url, headers }`; Cursor\n * and Kiro use `{ url, headers }`; Windsurf and Antigravity use\n * `{ serverUrl, headers }`; Gemini CLI uses `{ httpUrl, headers }` (`url` there\n * means SSE); Codex (TOML) uses `url` + an inline `http_headers` table.\n */\nimport { accessSync, constants, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';\nimport { copyFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { delimiter, dirname, join } from 'node:path';\nimport { DEFAULT_ENDPOINT, PACKAGE_NAME } from '../core/constants';\nimport { logger } from '../core/logger';\nimport { packageRoot } from '../core/paths';\nimport { lurqHome, resolveApiKey } from '../core/userConfig';\n\nconst ENV_KEYS = [\n 'DATABASE_URL',\n 'GITHUB_TOKEN',\n 'EMBEDDING_PROVIDER',\n 'EMBEDDING_API_KEY',\n 'EMBEDDING_MODEL',\n 'SUMMARY_PROVIDER',\n 'SUMMARY_API_KEY',\n 'SUMMARY_MODEL',\n] as const;\n\nexport type ConfigFormat = 'mcpServers' | 'servers' | 'toml';\n\n/**\n * How an agent picks up standing instructions, on top of the MCP entry.\n *\n * The MCP tool descriptions already tell an agent what each tool does; this is\n * what tells it *to reach for lurq at all* rather than answering about a package\n * from memory. Three shapes exist in the wild:\n *\n * - `skill`: Claude Code's `~/.claude/skills/<name>/SKILL.md`. Its own\n * directory, loaded on demand when the description matches, so it can carry\n * the full guide without costing context on every turn.\n * - `file`: a dedicated file in a directory the agent scans (Kiro steering,\n * VS Code prompt files). Also ours alone, so we write the full guide.\n * - `shared`: a single always-loaded context file the user also writes in\n * (GEMINI.md, AGENTS.md, Windsurf global rules). We own only a marked block\n * inside it, and keep that block short because it is in every prompt.\n */\ntype InstructionKind = 'skill' | 'file' | 'shared';\n\ninterface InstructionTarget {\n kind: InstructionKind;\n /** Absolute path of the file we write (or upsert a block into). */\n path: string;\n}\n\nexport interface AgentSpec {\n id: string;\n label: string;\n format: ConfigFormat;\n /** Absolute config file path. */\n path: string;\n /** Whether this agent appears installed (used by `--agent all` and the wizard). */\n detected: boolean;\n /** Where this agent reads standing instructions, when it has such a place. */\n instructions?: InstructionTarget;\n}\n\nfunction home(...p: string[]): string {\n return join(homedir(), ...p);\n}\n\n/**\n * VS Code's user-data directory, which is per-platform:\n * macOS ~/Library/Application Support/Code/User\n * Windows %APPDATA%\\Code\\User\n * Linux $XDG_CONFIG_HOME/Code/User (default ~/.config/Code/User)\n * Hardcoding the macOS path made detection always false elsewhere — and\n * `--agent copilot` write a config nobody reads.\n */\nfunction vscodeUserDir(): string {\n if (process.platform === 'darwin') return home('Library', 'Application Support', 'Code', 'User');\n if (process.platform === 'win32') {\n return join(process.env.APPDATA ?? home('AppData', 'Roaming'), 'Code', 'User');\n }\n return join(process.env.XDG_CONFIG_HOME || home('.config'), 'Code', 'User');\n}\n\nexport function agentSpecs(): AgentSpec[] {\n return [\n {\n id: 'claude-code',\n label: 'Claude Code',\n format: 'mcpServers',\n path: home('.claude.json'),\n detected: existsSync(home('.claude.json')) || existsSync(home('.claude')),\n // Personal skills are read from ~/.claude/skills/<name>/SKILL.md and apply\n // across every project, which is exactly the scope a global install wants.\n instructions: { kind: 'skill', path: home('.claude', 'skills', 'lurq', 'SKILL.md') },\n },\n {\n // No instructions target: Cursor's user-level rules live in its settings\n // UI, not a file on disk, and its `.cursor/rules/*.mdc` files are\n // per-project, so there is nothing a machine-wide install can write once.\n // The MCP tool descriptions carry the guidance here.\n id: 'cursor',\n label: 'Cursor',\n format: 'mcpServers',\n path: home('.cursor', 'mcp.json'),\n detected: existsSync(home('.cursor')),\n },\n {\n id: 'windsurf',\n label: 'Windsurf',\n format: 'mcpServers',\n path: home('.codeium', 'windsurf', 'mcp_config.json'),\n detected: existsSync(home('.codeium')),\n instructions: {\n kind: 'shared',\n path: home('.codeium', 'windsurf', 'memories', 'global_rules.md'),\n },\n },\n {\n // No instructions target, for two reasons that compound. A\n // `.instructions.md` file is only applied automatically when its\n // frontmatter carries an `applyTo` glob; without one, VS Code requires the\n // user to attach it to a request by hand. And the user-profile directory\n // that gets scanned is not a documented default at all: the workspace\n // default is `.github/instructions`, and profile-level folders come from\n // the `chat.instructionsFilesLocations` setting. Guessing the path would\n // write a file nobody reads while reporting success, which is the same\n // mistake the hardcoded macOS config path made above.\n id: 'copilot',\n label: 'VS Code / GitHub Copilot',\n format: 'servers',\n path: join(vscodeUserDir(), 'mcp.json'),\n detected: existsSync(vscodeUserDir()),\n },\n {\n id: 'codex',\n label: 'OpenAI Codex CLI',\n format: 'toml',\n path: home('.codex', 'config.toml'),\n detected: existsSync(home('.codex')),\n instructions: { kind: 'shared', path: home('.codex', 'AGENTS.md') },\n },\n {\n id: 'gemini-cli',\n label: 'Gemini CLI',\n format: 'mcpServers',\n path: home('.gemini', 'settings.json'),\n detected: existsSync(home('.gemini', 'settings.json')),\n // ~/.gemini/GEMINI.md is the global tier of the context hierarchy, loaded\n // ahead of any workspace file.\n instructions: { kind: 'shared', path: home('.gemini', 'GEMINI.md') },\n },\n {\n // Shares the ~/.gemini root with the Gemini CLI but keeps its own file, so\n // detection has to look at the file rather than at the directory. It reads\n // the same global GEMINI.md; upserting the block twice is a no-op, so\n // having both selected is harmless.\n id: 'antigravity',\n label: 'Google Antigravity',\n format: 'mcpServers',\n path: home('.gemini', 'config', 'mcp_config.json'),\n detected: existsSync(home('.gemini', 'config')),\n instructions: { kind: 'shared', path: home('.gemini', 'GEMINI.md') },\n },\n {\n id: 'kiro',\n label: 'Kiro',\n format: 'mcpServers',\n path: home('.kiro', 'settings', 'mcp.json'),\n detected: existsSync(home('.kiro')),\n // Steering files in ~/.kiro/steering apply to every workspace and are\n // always included.\n instructions: { kind: 'file', path: home('.kiro', 'steering', 'lurq.md') },\n },\n ];\n}\n\nexport const SUPPORTED_AGENTS = [\n 'claude-code',\n 'cursor',\n 'windsurf',\n 'copilot',\n 'codex',\n 'gemini-cli',\n 'antigravity',\n 'kiro',\n] as const;\n\n/** How to wire the lurq entry: hosted HTTP endpoint, or local stdio process. */\nexport type InstallMode =\n | { kind: 'remote'; url: string; apiKey: string }\n | { kind: 'local'; env: Record<string, string> };\n\nfunction collectEnv(): Record<string, string> {\n const env: Record<string, string> = {};\n for (const key of ENV_KEYS) {\n const value = process.env[key];\n if (value) env[key] = value;\n }\n return env;\n}\n\nexport interface InstallResult {\n agent: string;\n path: string;\n status: 'installed' | 'skipped' | 'error';\n message?: string;\n /** Where the standing-instructions file landed, when the agent supports one. */\n instructionsPath?: string;\n}\n\nfunction readJsonObject(path: string): Record<string, any> {\n if (!existsSync(path)) return {};\n const text = readFileSync(path, 'utf8').trim();\n if (!text) return {};\n return JSON.parse(text);\n}\n\n/**\n * Write via a temp file + rename, which is atomic within a directory. These are\n * the user's own agent configs — `~/.claude.json` holds Claude Code's entire\n * project state — and a crash partway through a plain write truncates the file.\n * A reader sees either the old config or the new one, never a half-written one.\n */\nfunction writeFileAtomic(path: string, contents: string): void {\n mkdirSync(dirname(path), { recursive: true });\n const tmp = `${path}.lurq-${process.pid}.tmp`;\n try {\n writeFileSync(tmp, contents, 'utf8');\n renameSync(tmp, path);\n } catch (err) {\n try {\n rmSync(tmp, { force: true });\n } catch {\n /* best-effort cleanup; report the original failure */\n }\n throw err;\n }\n}\n\nfunction writeJson(path: string, obj: unknown): void {\n writeFileAtomic(path, JSON.stringify(obj, null, 2) + '\\n');\n}\n\n/** Local (stdio) lurq server entry for JSON configs. */\nexport function buildServerEntry(env: Record<string, string>, withType: boolean): Record<string, any> {\n const entry: Record<string, any> = { command: 'npx', args: ['-y', PACKAGE_NAME, 'serve'] };\n if (withType) entry.type = 'stdio';\n if (Object.keys(env).length) entry.env = env;\n return entry;\n}\n\n/**\n * Remote (hosted) lurq server entry for JSON configs. Per-agent shape differs:\n * Claude Code & VS Code take `type:\"http\"`; the rest infer transport from which\n * URL field is set — `url` (Cursor, Kiro), `serverUrl` (Windsurf, Antigravity),\n * or `httpUrl` (Gemini CLI, where a plain `url` would be read as an SSE\n * endpoint and the streamable-HTTP handshake would never happen).\n */\nexport function buildRemoteServerEntry(\n agentId: string,\n opts: { url: string; apiKey: string },\n): Record<string, any> {\n const headers = { Authorization: `Bearer ${opts.apiKey}` };\n switch (agentId) {\n case 'cursor':\n case 'kiro':\n return { url: opts.url, headers };\n case 'windsurf':\n case 'antigravity':\n return { serverUrl: opts.url, headers };\n case 'gemini-cli':\n return { httpUrl: opts.url, headers };\n case 'claude-code':\n case 'copilot':\n default:\n return { type: 'http', url: opts.url, headers };\n }\n}\n\n/** Local (stdio) TOML block for the Codex config. */\nexport function buildTomlBlock(env: Record<string, string>): string {\n const lines = ['[mcp_servers.lurq]', 'command = \"npx\"', `args = [\"-y\", \"${PACKAGE_NAME}\", \"serve\"]`];\n if (Object.keys(env).length) {\n lines.push('', '[mcp_servers.lurq.env]');\n for (const [k, v] of Object.entries(env)) lines.push(`${k} = ${JSON.stringify(v)}`);\n }\n return lines.join('\\n') + '\\n';\n}\n\n/**\n * Remote (hosted) TOML block for the Codex config. Codex parses with\n * `deny_unknown_fields`: literal headers go in an inline `http_headers` table,\n * NOT a `[mcp_servers.lurq.headers]` subtable (verified against the openai/codex\n * StreamableHttp config schema).\n */\nexport function buildRemoteTomlBlock(opts: { url: string; apiKey: string }): string {\n return (\n [\n '[mcp_servers.lurq]',\n `url = ${JSON.stringify(opts.url)}`,\n `http_headers = { Authorization = ${JSON.stringify(`Bearer ${opts.apiKey}`)} }`,\n ].join('\\n') + '\\n'\n );\n}\n\nfunction installJsonEntry(spec: AgentSpec, entry: Record<string, any>): InstallResult {\n const key = spec.format === 'servers' ? 'servers' : 'mcpServers';\n const config = readJsonObject(spec.path);\n if (typeof config[key] !== 'object' || config[key] === null) config[key] = {};\n config[key].lurq = entry;\n writeJson(spec.path, config);\n return { agent: spec.id, path: spec.path, status: 'installed' };\n}\n\n/**\n * Drop the existing `[mcp_servers.lurq]` table (its header through the line\n * before the next top-level `[`), leaving every other table untouched. Enough\n * TOML awareness to replace our own block without taking a parser dependency:\n * we only ever need to find one section we wrote ourselves.\n */\nexport function stripTomlBlock(text: string, header = '[mcp_servers.lurq]'): string {\n const lines = text.split('\\n');\n const start = lines.findIndex((l) => l.trim() === header);\n if (start === -1) return text;\n let end = start + 1;\n // Sub-tables ([mcp_servers.lurq.env]) belong to the block; a sibling table ends it.\n while (end < lines.length) {\n const t = lines[end]!.trim();\n if (t.startsWith('[') && !t.startsWith(`${header.slice(0, -1)}.`)) break;\n end++;\n }\n return [...lines.slice(0, start), ...lines.slice(end)].join('\\n').replace(/\\n{3,}/g, '\\n\\n');\n}\n\nfunction installTomlBlock(spec: AgentSpec, block: string): InstallResult {\n const current = existsSync(spec.path) ? readFileSync(spec.path, 'utf8') : '';\n // Replace, never skip: skipping meant a re-run after a key rotation left\n // Codex pointed at the dead key while reporting success. Every other agent\n // upserts its entry, so this one does too.\n const existing = stripTomlBlock(current).replace(/\\s+$/, '');\n const sep = existing ? '\\n\\n' : '';\n writeFileAtomic(spec.path, existing + sep + block);\n return {\n agent: spec.id,\n path: spec.path,\n status: 'installed',\n message: current.includes('[mcp_servers.lurq]') ? 'replaced the existing lurq entry' : undefined,\n };\n}\n\n// ── Standing instructions ────────────────────────────────────────────────────\n\n/** Delimit the block we own inside a context file the user also writes in, so a\n * re-run replaces our text and leaves theirs alone. HTML comments render as\n * nothing in every markdown viewer these agents use. */\nconst BLOCK_START = '<!-- lurq:start -->';\nconst BLOCK_END = '<!-- lurq:end -->';\n\n/** One-line trigger description for the Claude Code skill's frontmatter. This is\n * the only part loaded on every turn, so it has to say when to reach for lurq\n * without the body. */\nconst SKILL_DESCRIPTION =\n 'Get current, evidence-scored facts about npm packages instead of recalling them. ' +\n 'Use before adding, choosing, comparing, or upgrading any JS/TS dependency, before ' +\n 'hand-rolling something a package may already do, and before writing code against a ' +\n \"package API that may have moved since training. Covers hallucinated and typosquatted \" +\n 'package names, advisories, version-exact export surfaces, and stack compatibility.';\n\nfunction template(name: string): string | null {\n const src = join(packageRoot(), 'templates', name);\n return existsSync(src) ? readFileSync(src, 'utf8') : null;\n}\n\n/**\n * Replace the `<!-- lurq:start -->…<!-- lurq:end -->` block in `text`, or append\n * one if it isn't there yet.\n *\n * Idempotent by construction: this is how a second `lurq setup` (or a key\n * rotation) updates a shared context file without stacking duplicate copies of\n * our instructions on top of the user's own rules. A start marker with no end\n * marker means someone edited the file by hand and cut it in half, so treat the\n * rest of the file as ours to replace rather than leaving an orphaned marker.\n */\nexport function upsertMarkedBlock(text: string, block: string): string {\n const wrapped = `${BLOCK_START}\\n${block.trim()}\\n${BLOCK_END}`;\n const start = text.indexOf(BLOCK_START);\n if (start === -1) {\n const existing = text.replace(/\\s+$/, '');\n return existing ? `${existing}\\n\\n${wrapped}\\n` : `${wrapped}\\n`;\n }\n const endAt = text.indexOf(BLOCK_END, start);\n const after = endAt === -1 ? '' : text.slice(endAt + BLOCK_END.length);\n return `${text.slice(0, start)}${wrapped}${after.replace(/^\\n*/, '\\n')}`;\n}\n\n/** The `~/.claude/skills/lurq/SKILL.md` body: frontmatter + the full guide. */\nexport function buildSkillFile(guide: string): string {\n return [\n '---',\n 'name: lurq',\n `description: ${SKILL_DESCRIPTION}`,\n '---',\n '',\n guide.trim(),\n '',\n ].join('\\n');\n}\n\n/**\n * Write the agent's standing-instructions file. Returns the path, or null when\n * the agent has no such place (Cursor) or the template is missing from the\n * install. Never throws for a missing directory: every target is created.\n */\nexport function installInstructions(spec: AgentSpec): string | null {\n const target = spec.instructions;\n if (!target) return null;\n\n if (target.kind === 'shared') {\n // Always-loaded file: keep it to the short brief, and merge rather than\n // overwrite, because the user's own global rules live in here too.\n const brief = template('agent-rules.md');\n if (!brief) return null;\n const current = existsSync(target.path) ? readFileSync(target.path, 'utf8') : '';\n writeFileAtomic(target.path, upsertMarkedBlock(current, brief));\n return target.path;\n }\n\n // Ours alone, and loaded on demand, so the full guide fits.\n const guide = template('skill-instructions.md');\n if (!guide) return null;\n writeFileAtomic(target.path, target.kind === 'skill' ? buildSkillFile(guide) : guide);\n return target.path;\n}\n\n/** Apply the lurq entry to one agent's config, in the given mode. */\nexport function installAgent(spec: AgentSpec, mode: InstallMode): InstallResult {\n try {\n const result =\n spec.format === 'toml'\n ? installTomlBlock(\n spec,\n mode.kind === 'remote' ? buildRemoteTomlBlock(mode) : buildTomlBlock(mode.env),\n )\n : installJsonEntry(\n spec,\n mode.kind === 'remote'\n ? buildRemoteServerEntry(spec.id, mode)\n : buildServerEntry(mode.env, spec.format === 'servers'),\n );\n // The MCP entry is the part that must land; a failure to write instructions\n // (a read-only rules file, say) degrades the install rather than voiding it.\n try {\n result.instructionsPath = installInstructions(spec) ?? undefined;\n } catch (err) {\n result.message = `MCP entry written; instructions file failed: ${\n err instanceof Error ? err.message : String(err)\n }`;\n }\n return result;\n } catch (err) {\n return {\n agent: spec.id,\n path: spec.path,\n status: 'error',\n message: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\n/** Copy the skill-instructions template to ~/.lurq. Returns the path, or null.\n * The canonical copy, for agents with no instructions target of their own and\n * for anyone who wants to read what was installed. */\nexport function installInstructionsFile(): string | null {\n const src = join(packageRoot(), 'templates', 'skill-instructions.md');\n if (!existsSync(src)) return null;\n const destDir = lurqHome();\n const dest = join(destDir, 'skill-instructions.md');\n mkdirSync(destDir, { recursive: true });\n copyFileSync(src, dest);\n return dest;\n}\n\n/** Resolve `--agent <id|all>` to the set of agent specs to write. */\nexport function resolveAgents(target: string): AgentSpec[] {\n const specs = agentSpecs();\n if (target === 'all') return specs.filter((s) => s.detected);\n const spec = specs.find((s) => s.id === target);\n if (!spec) {\n throw new Error(`Unknown agent \"${target}\". Supported: ${SUPPORTED_AGENTS.join(', ')}, all.`);\n }\n return [spec];\n}\n\n/** Print the per-agent registration report + next steps. Shared by both paths. */\n/**\n * How this user should invoke lurq from a terminal, decided by looking at PATH\n * rather than by what the wizard believes it did.\n *\n * Every route to \"no `lurq` command\" looks different from the inside — the\n * global install was declined, or it hit EACCES on a system-managed node, or\n * npm's prefix is not on PATH, or the user never ran the wizard from npx at\n * all — and they all land the user in the same place. Asking PATH once answers\n * all of them, and cannot disagree with reality the way a tracked flag can.\n *\n * A PATH scan rather than `spawnSync('lurq', ['--version'])`: the question is\n * whether the file exists and is executable, and spawning would load the whole\n * CLI bundle to find out, then hang if what is on PATH happens to be broken.\n */\nexport function lurqInvocation(): { command: string; onPath: boolean } {\n // On Windows the shim is `lurq.cmd`; the empty string covers the extensionless\n // shell script npm writes everywhere else.\n const candidates = process.platform === 'win32' ? ['.cmd', '.exe', ''] : [''];\n for (const dir of (process.env.PATH ?? '').split(delimiter)) {\n if (!dir) continue;\n for (const ext of candidates) {\n try {\n accessSync(join(dir, `lurq${ext}`), constants.X_OK);\n return { command: 'lurq', onPath: true };\n } catch {\n // Not here, or not executable. Keep looking.\n }\n }\n }\n return { command: `npx ${PACKAGE_NAME}`, onPath: false };\n}\n\nexport function printInstallReport(\n results: InstallResult[],\n instructionsPath: string | null,\n mode: InstallMode,\n): void {\n const specs = agentSpecs();\n const short = (p: string) => (p.startsWith(homedir()) ? `~${p.slice(homedir().length)}` : p);\n\n console.log('lurq MCP server registration:');\n for (const r of results) {\n const spec = specs.find((s) => s.id === r.agent)!;\n const mark = r.status === 'installed' ? '✓' : r.status === 'skipped' ? '•' : '✗';\n console.log(\n ` ${mark} ${spec.label.padEnd(26)} ${short(r.path)}${r.message ? ` (${r.message})` : ''}`,\n );\n }\n\n const withSkills = results.filter((r) => r.instructionsPath);\n if (withSkills.length) {\n console.log('\\nAgent instructions (so it reaches for lurq on its own):');\n for (const r of withSkills) {\n const spec = specs.find((s) => s.id === r.agent)!;\n console.log(` ✓ ${spec.label.padEnd(26)} ${short(r.instructionsPath!)}`);\n }\n }\n if (instructionsPath) console.log(`\\nFull guide: ${short(instructionsPath)}`);\n\n console.log('\\nNext steps:');\n if (mode.kind === 'local') {\n console.log(' 1. Ensure DATABASE_URL (and any API keys) are set in the config env above.');\n console.log(' 2. Restart the agent so it picks up the new MCP server.');\n } else {\n console.log(' 1. Restart the agent so it picks up the new MCP server.');\n }\n console.log(' • Ask it to recommend a library. It should call lurq.');\n // The invocation that actually works on THIS machine, not the one we wish\n // they had. Printing `lurq …` to someone who ran the wizard from npx and\n // declined the global install sends them straight to \"command not found\".\n const { command, onPath } = lurqInvocation();\n console.log(` • Or use the terminal directly: \\`${command} recommend \"a form library for React\"\\`.`);\n if (!onPath) {\n // No em dash: b7a6d1b took them out of everything a user reads.\n console.log(`\\n There is no \\`lurq\\` command on this machine yet. Everything above`);\n console.log(' worked and your agents are wired up; only the terminal shortcut is');\n console.log(` missing, so use \\`npx ${PACKAGE_NAME} <command>\\`. To get \\`lurq\\` itself:`);\n console.log(` npm install -g ${PACKAGE_NAME}`);\n }\n}\n\nexport interface InstallSkillOptions {\n agent?: string;\n /** Hosted endpoint URL (defaults to LURQ_ENDPOINT or the built-in default). */\n url?: string;\n /** API key for the hosted endpoint. Presence selects remote mode. */\n apiKey?: string;\n /** Force the legacy local/stdio entry (self-host). */\n local?: boolean;\n}\n\nexport async function runInstallSkill(opts: InstallSkillOptions): Promise<void> {\n const selected = resolveAgents(opts.agent ?? 'claude-code');\n if (selected.length === 0) {\n console.log('No supported agents detected on this machine.');\n return;\n }\n\n // Remote unless explicitly --local. Remote requires an API key.\n const remote = !opts.local;\n let mode: InstallMode;\n if (remote) {\n const apiKey = resolveApiKey(opts.apiKey);\n if (!apiKey) {\n throw new Error(\n 'An API key is required for a hosted install. Pass --api-key <key> (or set LURQ_API_KEY), ' +\n 'or run `lurq setup` for the guided setup, or --local to self-host.',\n );\n }\n const url = opts.url ?? process.env.LURQ_ENDPOINT ?? DEFAULT_ENDPOINT;\n mode = { kind: 'remote', url, apiKey };\n } else {\n const env = collectEnv();\n if (!env.DATABASE_URL) {\n logger.warn(\n 'DATABASE_URL is not set, the local server entry will have no DATABASE_URL. ' +\n 'Set it (in .env) and re-run, or edit the config.',\n );\n }\n mode = { kind: 'local', env };\n }\n\n const results = selected.map((spec) => installAgent(spec, mode));\n const instructionsPath = installInstructionsFile();\n printInstallReport(results, instructionsPath, mode);\n}\n","/**\n * Open a file or URL in the OS default application, cross-platform.\n *\n * No shell (so a target containing shell metacharacters can't inject a command);\n * on Windows `cmd /c start \"\" <target>` keeps spaced paths intact because Node\n * passes each argument separately. Best-effort by design: a headless box has no\n * browser to open, and the callers all print the URL as well.\n */\nimport { spawn } from 'node:child_process';\n\nexport function openInBrowser(target: string): void {\n const [cmd, args]: [string, string[]] =\n process.platform === 'darwin'\n ? ['open', [target]]\n : process.platform === 'win32'\n ? ['cmd', ['/c', 'start', '', target]]\n : ['xdg-open', [target]];\n try {\n spawn(cmd, args, { stdio: 'ignore', detached: true }).unref();\n } catch {\n /* no opener available (headless/CI); the caller prints the URL too */\n }\n}\n","/**\n * Dependency-free formatting helpers for human-facing CLI output. Compact tables\n * and labeled detail views; `--json` paths bypass these entirely.\n */\n\nconst ESC = '\u001b[';\nconst wrap = (code: string, s: string) => `${ESC}${code}m${s}${ESC}0m`;\n\nexport const bold = (s: string) => wrap('1', s);\nexport const dim = (s: string) => wrap('2', s);\nexport const red = (s: string) => wrap('31', s);\nexport const green = (s: string) => wrap('32', s);\nexport const yellow = (s: string) => wrap('33', s);\n\n// eslint-disable-next-line no-control-regex\nconst ANSI_RE = /\u001b\\[[0-9;]*m/g;\nconst width = (s: string) => s.replace(ANSI_RE, '').length;\n\n/** Render a simple aligned table. */\nexport function table(headers: string[], rows: string[][]): string {\n const widths = headers.map((h, i) => Math.max(width(h), ...rows.map((r) => width(r[i] ?? ''))));\n const pad = (s: string, w: number) => s + ' '.repeat(Math.max(0, w - width(s)));\n const line = (cells: string[]) => cells.map((c, i) => pad(c, widths[i]!)).join(' ');\n const out = [bold(line(headers)), dim(widths.map((w) => '─'.repeat(w)).join(' '))];\n for (const r of rows) out.push(line(r));\n return out.join('\\n');\n}\n\n/** Render a labeled key/value detail block. */\nexport function detail(pairs: [string, string][]): string {\n const labelWidth = Math.max(...pairs.map(([k]) => k.length));\n return pairs.map(([k, v]) => `${dim((k + ':').padEnd(labelWidth + 1))} ${v}`).join('\\n');\n}\n\n/** Compact number formatting: 1.2M, 34k, 950. */\nexport function formatNumber(n: number | null | undefined): string {\n if (n == null) return '-';\n if (n >= 1_000_000) return `${Math.round(n / 100_000) / 10}M`;\n if (n >= 1_000) return `${Math.round(n / 100) / 10}k`;\n return String(n);\n}\n\nexport function formatDate(iso: string | null): string {\n return iso ? iso.slice(0, 10) : '-';\n}\n\nexport function formatPercent(fraction: number | null | undefined): string {\n if (fraction == null) return '-';\n const pct = Math.round(fraction * 1000) / 10;\n return `${pct > 0 ? '+' : ''}${pct}%`;\n}\n\n/** Color a confidence label. */\nexport function confidenceLabel(c: string): string {\n if (c === 'proven') return green(c);\n if (c === 'emerging') return yellow(c);\n // `promising` (§1): high intrinsic quality, adoption-independent.\n if (c === 'promising') return green(c);\n return red(c);\n}\n","/**\n * Client for the hosted lurq API, used by the commands that run on a user's\n * machine or in their CI rather than against a local database.\n *\n * The rest of the CLI talks to Postgres directly (`withDb` in commands.ts); that\n * is right for the operator and wrong here — a GitHub Actions runner has an API\n * key and no database. This module is the whole client: two calls, no SDK.\n */\nimport { DEFAULT_ENDPOINT } from '../core/constants';\nimport { resolveApiKey, resolveEndpoint } from '../core/userConfig';\nimport type { SelectionPolicy } from '../policy/types';\n\nexport class RemoteError extends Error {\n constructor(\n message: string,\n readonly status: number,\n ) {\n super(message);\n this.name = 'RemoteError';\n }\n}\n\n/**\n * No key anywhere on this machine. Its own class, not a bare 401, because the\n * entry point answers it by offering setup, and a key the server *rejected*\n * must not trigger that: re-running setup will not fix a revoked key.\n */\nexport class MissingKeyError extends RemoteError {\n constructor(message = 'No API key configured. Run `lurq setup` to connect this machine.') {\n super(message, 401);\n this.name = 'MissingKeyError';\n }\n}\n\n/** Endpoint the CLI talks to, with the same precedence `setup` uses. */\nexport function endpoint(override?: string): string {\n const base = resolveEndpoint(override) ?? DEFAULT_ENDPOINT;\n // The published endpoint is the MCP path; the REST routes sit beside it.\n return base.replace(/\\/mcp\\/?$/, '').replace(/\\/$/, '');\n}\n\n/** The `/mcp` JSON-RPC endpoint, whatever spelling of the base URL we were given. */\nfunction mcpUrl(override?: string): string {\n return `${endpoint(override)}/mcp`;\n}\n\nexport function apiKey(override?: string): string {\n const key = resolveApiKey(override);\n if (!key) throw new MissingKeyError();\n return key;\n}\n\n/**\n * Pull a human-readable message out of an error body.\n *\n * The server speaks two envelopes and the client has to read both: the REST\n * handlers send `{ error: \"some text\" }`, but every auth and rate-limit\n * rejection goes through the JSON-RPC shape `{ error: { code, message } }`.\n * Reading `.error` as a string worked for the first and stringified the second\n * to `[object Object]`, which is what a user saw for every 401 the hosted API\n * has ever returned, i.e. exactly the case where the message mattered most.\n */\nfunction errorText(body: unknown): string | undefined {\n const err = (body as { error?: unknown })?.error;\n if (typeof err === 'string') return err;\n const message = (err as { message?: unknown })?.message;\n return typeof message === 'string' ? message : undefined;\n}\n\nexport interface RemoteOptions {\n url?: string;\n apiKey?: string;\n timeoutMs?: number;\n}\n\n/**\n * POST JSON with a timeout, mapping transport failures to RemoteError.\n *\n * Shared by the REST client and the MCP client below, which differ only in what\n * they send and how they read the reply. One copy means the \"timed out\" and\n * \"could not reach\" wording cannot drift apart, and the callers stay short\n * enough to see at a glance.\n */\nasync function postJson(\n url: string,\n body: unknown,\n headers: Record<string, string>,\n timeoutMs = 60_000,\n method: 'GET' | 'POST' | 'PUT' = 'POST',\n): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n return await fetch(url, {\n method,\n headers: { 'Content-Type': 'application/json', ...headers },\n // fetch rejects a GET that carries a body, even an empty one.\n body: method === 'GET' ? undefined : JSON.stringify(body),\n signal: controller.signal,\n });\n } catch (err) {\n const aborted = err instanceof Error && err.name === 'AbortError';\n throw new RemoteError(aborted ? `Timed out calling ${url}` : `Could not reach ${url}`, 0);\n } finally {\n clearTimeout(timer);\n }\n}\n\nconst post = <T>(path: string, body: unknown, opts: RemoteOptions = {}): Promise<T> =>\n request<T>('POST', path, body, opts);\n\nasync function request<T>(\n method: 'GET' | 'POST' | 'PUT',\n path: string,\n body: unknown,\n opts: RemoteOptions = {},\n): Promise<T> {\n const url = `${endpoint(opts.url)}${path}`;\n // `apiKey()` is evaluated here rather than inside postJson, so a missing key\n // throws before any request is built and needs no unwrapping downstream.\n const res = await postJson(\n url,\n body,\n { Authorization: `Bearer ${apiKey(opts.apiKey)}` },\n opts.timeoutMs,\n method,\n );\n\n if (!res.ok) {\n const detail = await res\n .json()\n .then(errorText)\n .catch(() => undefined);\n throw new RemoteError(detail ?? `${path} failed with HTTP ${res.status}`, res.status);\n }\n return (await res.json()) as T;\n}\n\n/**\n * Call one hosted MCP tool and return its parsed result.\n *\n * This is how the read commands work on a machine with no database. The hosted\n * `/mcp` route is stateless with JSON responses enabled (mcp/http.ts), so a bare\n * `tools/call` needs no `initialize` handshake, and every tool answers with a\n * single JSON text block: the exact object the local handler would have\n * returned, minus the null/empty fields `compact` strips. That is why the\n * renderers in commands.ts can format either source without knowing which\n * one produced the result.\n */\nexport async function callTool<T>(\n tool: string,\n args: Record<string, unknown>,\n opts: RemoteOptions = {},\n): Promise<T> {\n const url = mcpUrl(opts.url);\n const res = await postJson(\n url,\n { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: tool, arguments: args } },\n {\n // The streamable-HTTP transport rejects a request that doesn't accept\n // both, even when it has already decided to answer with plain JSON.\n Accept: 'application/json, text/event-stream',\n Authorization: `Bearer ${apiKey(opts.apiKey)}`,\n },\n opts.timeoutMs,\n );\n\n const body = parseRpcBody(await res.text());\n if (!res.ok) {\n throw new RemoteError(errorText(body) ?? `${tool} failed with HTTP ${res.status}`, res.status);\n }\n const message = errorText(body);\n if (message) throw new RemoteError(message, 200);\n\n const result = (body as { result?: { content?: { type: string; text?: string }[]; isError?: boolean } })\n ?.result;\n const text = result?.content?.find((c) => c.type === 'text')?.text;\n if (text === undefined) throw new RemoteError(`${tool} returned no content.`, 502);\n // A tool that threw server-side comes back as a normal result with isError\n // set and the message as its text, so surface it instead of parsing it as data.\n if (result?.isError) throw new RemoteError(text, 200);\n try {\n return JSON.parse(text) as T;\n } catch {\n throw new RemoteError(`${tool} returned a non-JSON result: ${text.slice(0, 200)}`, 502);\n }\n}\n\n/**\n * Read a JSON-RPC body, tolerating an SSE frame and a non-JSON error page.\n *\n * mcp/http.ts sets `enableJsonResponse`, so SSE does not happen today. The three\n * lines that handle it are what stop this file breaking silently if that flag is\n * ever flipped in the server it has no other link to.\n */\nfunction parseRpcBody(raw: string): unknown {\n const text = raw.trimStart().startsWith('{')\n ? raw\n : (raw.split('\\n').filter((l) => l.startsWith('data:')).pop() ?? '').slice(5);\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\n/** Response shape of `POST /upgrade-plan` — mirrors github/brief.ts. */\nexport interface RemoteUpgrade {\n package: string;\n fromVersion: string;\n toVersion: string;\n /** Manifests declaring it — every one needs bumping, not just the root. */\n declaredIn: { path: string; range: string }[];\n /** Migration sequence for a multi-major upgrade; empty when one hop suffices. */\n hops: {\n fromVersion: string;\n toVersion: string;\n verdict: RemoteUpgrade['verdict'];\n removed: string[];\n arityChanged: { path: string; from: number | null; to: number | null }[];\n }[];\n sequenceNote?: string;\n majorsBehind: number;\n advisories: number;\n deprecated: boolean;\n verdict: 'removes-exports' | 'arity-changed' | 'clean' | 'unknown';\n removed: string[];\n arityChanged: { path: string; from: number | null; to: number | null }[];\n typeOnlyRemoved: string[];\n newlyDeprecated: string[];\n inconclusive?: string;\n /**\n * May the agent attempt this one under the repo's policy? Absent from an older\n * server, and `!== false` is how every consumer reads it — an unannotated plan\n * must behave exactly as it did before scope enforcement shipped.\n */\n inScope?: boolean;\n /** Why not, when `inScope` is false. */\n scopeReason?: string;\n}\n\nexport interface RemotePlan {\n upgrades: RemoteUpgrade[];\n omitted: number;\n pending: number;\n /** Declared dependencies lurq has no index entry for. */\n untracked: number;\n /** The policy scope applied, and where it came from. Absent from an older server. */\n scope?: 'security' | 'blocking' | 'all';\n scopeSource?: 'repo-policy' | 'unconnected';\n outOfScope?: number;\n}\n\nexport function fetchUpgradePlan(\n deps: Record<string, string>,\n opts: RemoteOptions & { repo?: string | null } = {},\n): Promise<RemotePlan> {\n // `repo` is what lets the server find this repository's policy. Omitted when\n // unknown (a laptop, not a runner), which the server reads as \"ungoverned\".\n const body = opts.repo ? { deps, repo: opts.repo } : { deps };\n return post<RemotePlan>('/upgrade-plan', body, opts);\n}\n\nexport interface ReportedRun {\n repoFullName: string;\n packageName: string;\n fromVersion: string;\n toVersion: string;\n severity: 'blocking' | 'warning' | 'ok' | 'unverified';\n status: 'checked' | 'skipped' | 'edited' | 'pr_open' | 'merged' | 'failed';\n symbolsAffected?: string[];\n callSites?: number;\n callSiteFiles?: string[];\n filesChanged?: number;\n testsPassed?: boolean | null;\n prUrl?: string | null;\n runUrl?: string;\n}\n\n/**\n * Send what a CI check concluded, so the dashboard can show it.\n *\n * `rejected` is the server's count of rows it refused to parse. Surfaced rather\n * than swallowed: a payload shape that drifts from the server's validator would\n * otherwise look exactly like a repo with nothing to report.\n */\nexport function reportUpgradeRuns(\n runs: ReportedRun[],\n opts: RemoteOptions = {},\n): Promise<{ recorded: number; rejected: number }> {\n return post<{ recorded: number; rejected: number }>('/upgrade-runs', { runs }, opts);\n}\n\n/** The account's selection policy, as the dashboard would save it. */\nexport async function getPolicy(opts: RemoteOptions = {}): Promise<SelectionPolicy> {\n return (await request<{ policy: SelectionPolicy }>('GET', '/policy', undefined, opts)).policy;\n}\n\n/**\n * Replace the policy. The server rejects a key without policy:write (403).\n * `previous` is absent from a server older than policy history.\n */\nexport function putPolicy(\n policy: SelectionPolicy,\n opts: RemoteOptions = {},\n): Promise<{ policy: SelectionPolicy; previous?: SelectionPolicy }> {\n return request('PUT', '/policy', { policy }, opts);\n}\n\nexport interface RemotePolicyChange {\n actor: string;\n /** ISO timestamp. */\n at: string;\n changes: string[];\n}\n\nexport interface RemoteDecision {\n packageName: string;\n rule: string;\n action: 'blocked' | 'warned';\n count: number;\n lastDay: string;\n}\n\nexport async function getPolicyHistory(opts: RemoteOptions = {}): Promise<RemotePolicyChange[]> {\n return (await request<{ changes: RemotePolicyChange[] }>('GET', '/policy/history', undefined, opts))\n .changes;\n}\n\nexport async function getPolicyDecisions(\n days: number,\n opts: RemoteOptions = {},\n): Promise<RemoteDecision[]> {\n const path = `/policy/decisions?days=${encodeURIComponent(days)}`;\n return (await request<{ decisions: RemoteDecision[] }>('GET', path, undefined, opts)).decisions;\n}\n","/**\n * Get a key into the terminal without anyone copying and pasting one.\n *\n * The old setup flow: open the dashboard, sign in, click New key, select the\n * key, copy it, switch back to the terminal, paste, hope nothing mangled it.\n * Seven steps between \"I want to try this\" and \"it works\", six of them in a\n * different window from the one asking, and every one of them a place to give\n * up. It is the single longest stretch of the funnel with nothing happening in\n * it.\n *\n * This is the loopback flow every CLI that has solved this uses (`gh`, `vercel`,\n * `wrangler`): bind a one-shot HTTP server on a random localhost port, open the\n * browser at a page that knows the port, and let the page hand the key straight\n * back. The user signs in, and that is the whole interaction.\n *\n * WHAT MAKES IT SAFE ENOUGH.\n * - The listener is bound to 127.0.0.1, so nothing off this machine can reach it.\n * - The port is ephemeral and only the browser we just opened is told it.\n * - A nonce goes out in the URL and has to come back with the key, so a stray\n * local request cannot feed us a credential we did not ask for.\n * - It answers exactly one request and closes, and it gives up after a\n * deadline rather than sitting on a port forever.\n *\n * It is a best-effort optimisation, never a requirement: every failure path\n * here returns null and setup falls back to the paste prompt. SSH sessions,\n * headless boxes, locked-down browsers and firewalls all land there.\n */\nimport { randomBytes, timingSafeEqual } from 'node:crypto';\nimport { createServer, type IncomingMessage, type ServerResponse } from 'node:http';\nimport type { AddressInfo } from 'node:net';\n\nimport { openInBrowser } from '../core/open';\nimport { API_KEY_PREFIX } from '../core/constants';\n\n/** Where the handoff page lives. The apex redirects to www, which browsers follow. */\nconst WEB_ORIGIN = process.env.LURQ_WEB_URL ?? 'https://lurq.run';\n\n/** How long to hold the port before giving up and asking for a paste. */\nconst DEADLINE_MS = 3 * 60_000;\n\n/** Body cap. A key is ~50 bytes; anything near this is not one. */\nconst MAX_BODY = 4096;\n\nfunction equal(a: string, b: string): boolean {\n const left = Buffer.from(a);\n const right = Buffer.from(b);\n return left.length === right.length && timingSafeEqual(left, right);\n}\n\nasync function readBody(req: IncomingMessage): Promise<string> {\n let out = '';\n for await (const chunk of req) {\n out += chunk;\n if (out.length > MAX_BODY) return '';\n }\n return out;\n}\n\nexport interface BrowserAuthResult {\n key: string;\n /** Printed after the fact, so the user knows which key their machine now holds. */\n label: string | null;\n}\n\n/**\n * Open the browser and wait for it to hand back a key.\n *\n * `onUrl` receives the URL as soon as the port is known, so the caller can print\n * it: the browser may not have opened, and a URL nobody can see is a flow that\n * looks hung.\n */\nexport function keyViaBrowser(opts: {\n noOpen?: boolean;\n onUrl: (url: string) => void;\n}): Promise<BrowserAuthResult | null> {\n return new Promise((resolve) => {\n const nonce = randomBytes(18).toString('base64url');\n let settled = false;\n\n const finish = (value: BrowserAuthResult | null) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n server.close();\n resolve(value);\n };\n\n const server = createServer((req: IncomingMessage, res: ServerResponse) => {\n // The page is on https://lurq.run and we are http://127.0.0.1, so every\n // request is cross-origin. Chrome additionally treats a public page\n // reaching localhost as a private-network request and preflights it, and\n // refuses without the matching header.\n res.setHeader('Access-Control-Allow-Origin', WEB_ORIGIN);\n res.setHeader('Access-Control-Allow-Headers', 'Content-Type');\n res.setHeader('Access-Control-Allow-Private-Network', 'true');\n\n if (req.method === 'OPTIONS') {\n res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');\n res.writeHead(204).end();\n return;\n }\n if (req.method !== 'POST') {\n res.writeHead(405).end();\n return;\n }\n\n void readBody(req).then((raw) => {\n let key = '';\n let label: string | null = null;\n try {\n const body = JSON.parse(raw) as { nonce?: unknown; key?: unknown; label?: unknown };\n if (typeof body.nonce === 'string' && equal(body.nonce, nonce)) {\n if (typeof body.key === 'string' && body.key.startsWith('lurq_')) key = body.key;\n if (typeof body.label === 'string') label = body.label;\n }\n } catch {\n /* not JSON; falls through to the reject below */\n }\n\n if (!key) {\n res.writeHead(400, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({ ok: false }));\n return;\n }\n\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({ ok: true }));\n finish({ key, label });\n });\n });\n\n const timer = setTimeout(() => finish(null), DEADLINE_MS);\n // Never hold the process open on its own account: if something else has\n // already resolved setup, this must not keep node alive for three minutes.\n timer.unref?.();\n\n server.on('error', () => finish(null));\n server.listen(0, '127.0.0.1', () => {\n const { port } = server.address() as AddressInfo;\n const url = `${WEB_ORIGIN}/dashboard/cli?port=${port}&nonce=${encodeURIComponent(nonce)}`;\n opts.onUrl(url);\n if (!opts.noOpen) openInBrowser(url);\n });\n });\n}\n\n/** True for anything shaped like a key this CLI would accept. */\nexport function looksLikeKey(value: string): boolean {\n return value.startsWith('lurq_') || value.startsWith(API_KEY_PREFIX);\n}\n","/**\n * One-time machine setup (`lurq setup`, and bare `npx lurqrun`).\n *\n * The whole point of this command is that a user types one thing, `npx lurqrun`,\n * and is then done: `lurq` is on their PATH, the key is stored for the CLI\n * itself, and every detected assistant gets both an MCP entry and a\n * standing-instructions file. Nothing afterwards needs `npx`, a shell export,\n * or a second command.\n *\n * It opens the browser at a page that hands the key straight back to this\n * process over localhost, so nothing is copied or pasted: the user signs in and\n * that is the entire interaction. See browserAuth.ts. When that cannot work — an\n * SSH session, a headless box, a self-hosted endpoint our dashboard has never\n * issued a key for — it falls back to the old paste prompt, which still works.\n * Either way it validates the key against the endpoint and writes:\n * - `~/.lurq/config.json`: so `lurq recommend` &c. work in any directory\n * - each agent's MCP config: a keyed HTTP entry, no DATABASE_URL anywhere\n * - each agent's skill / rules file: so it reaches for lurq unprompted\n *\n * Fully non-interactive with `--yes` plus flags or env, for dotfiles and CI.\n */\nimport { spawnSync } from 'node:child_process';\n\nimport { DEFAULT_ENDPOINT, PACKAGE_NAME } from '../core/constants';\nimport { openInBrowser } from '../core/open';\nimport {\n readUserConfig,\n resolveApiKey,\n resolveEndpoint,\n writeUserConfig,\n} from '../core/userConfig';\nimport { bold, dim, green, yellow } from './format';\nimport {\n agentSpecs,\n installAgent,\n installInstructionsFile,\n lurqInvocation,\n printInstallReport,\n resolveAgents,\n type AgentSpec,\n type InstallMode,\n} from './installSkill';\nimport { MissingKeyError } from './remote';\n\n/**\n * Run a command; if it stops for want of a key, offer setup and run it again.\n *\n * Someone whose first command is `lurq evaluate zod` used to get an error and\n * exit 1 at the moment they were most curious. Now they sign in and see the\n * answer they asked for. One retry only: if setup ends without storing a key\n * (they cancelled), the retry throws the original error and that is the exit.\n *\n * Asks only in a real terminal. CI, pipes and `--json` keep the plain error,\n * because a prompt nobody can answer is a hang.\n */\nexport async function withSetupOnMissingKey(\n run: () => Promise<unknown>,\n ask: () => Promise<boolean> = askToConnect,\n setup: () => Promise<void> = () => runSetup({}),\n): Promise<void> {\n try {\n await run();\n } catch (err) {\n if (!(err instanceof MissingKeyError) || !(await ask())) throw err;\n await setup();\n await run();\n }\n}\n\nasync function askToConnect(): Promise<boolean> {\n const interactive =\n process.stdin.isTTY && process.stdout.isTTY && !process.env.CI && !process.argv.includes('--json');\n if (!interactive) return false;\n const { confirm } = await import('@inquirer/prompts');\n return confirm({ message: 'This machine has no lurq API key yet. Connect it now?', default: true });\n}\n\nexport interface WizardOptions {\n apiKey?: string;\n url?: string;\n agent?: string;\n yes?: boolean;\n /** Skip launching a browser (headless boxes, SSH sessions, CI). */\n noOpen?: boolean;\n}\n\n/** Where a signed-in user creates a key. */\nconst KEYS_URL = 'https://lurq.run/dashboard/keys';\n\n/**\n * Lightweight MCP `tools/list` ping to confirm the key authenticates.\n * Distinguishes a rejected key (401/403) from an unreachable endpoint so the\n * wizard can tell the user which one happened instead of blaming the key on a\n * flaky network.\n */\ntype KeyCheck = 'valid' | 'invalid' | 'unreachable';\n\nasync function validateKey(url: string, apiKey: string): Promise<KeyCheck> {\n try {\n const res = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json, text/event-stream',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }),\n });\n if (res.ok) return 'valid';\n if (res.status === 401 || res.status === 403) return 'invalid';\n return 'unreachable';\n } catch {\n return 'unreachable';\n }\n}\n\n/**\n * True when this process is running out of npm's throwaway npx cache\n * (`~/.npm/_npx/<hash>/node_modules/…`) rather than an installed copy.\n *\n * npm puts every `npx <pkg>` there, prunes it later, and leaves nothing on PATH,\n * so after the wizard exits the user would have a configured machine but no\n * `lurq` command. That is the one case worth offering a global install in.\n * Takes the URL as a parameter purely so it can be tested.\n */\nexport function runningFromNpx(moduleUrl: string = import.meta.url): boolean {\n // File URLs are slash-separated on every platform, Windows included.\n return moduleUrl.includes('/_npx/');\n}\n\n/**\n * Put `lurq` on PATH. Never fatal: the wizard's real work is the key and the\n * agent configs, and neither depends on this succeeding. A system-managed node\n * hands out EACCES here, and the right answer to that is a printed hint rather\n * than a dead setup: the user can keep using `npx lurqrun` in the meantime.\n */\nfunction installGlobally(): void {\n process.stdout.write(` Installing ${PACKAGE_NAME} globally… `);\n const res = spawnSync('npm', ['install', '--global', `${PACKAGE_NAME}@latest`], {\n stdio: ['ignore', 'ignore', 'pipe'],\n encoding: 'utf8',\n // npm is a .cmd shim on Windows, which is not directly executable.\n shell: process.platform === 'win32',\n });\n\n if (res.status === 0) {\n console.log(green('ok'));\n console.log(dim(' `lurq` now works in any terminal, no npx needed.'));\n return;\n }\n\n console.log(yellow('skipped'));\n const reason = (res.stderr || res.error?.message || '').trim().split('\\n').pop();\n if (reason) console.log(dim(` ${reason}`));\n console.log(dim(` Setup continues. Run \\`npm install -g ${PACKAGE_NAME}\\` later if you want it.`));\n}\n\nexport async function runSetup(opts: WizardOptions): Promise<void> {\n const interactive = !opts.yes;\n // Both of these fall back to what an earlier run stored, so re-running setup\n // to add a newly-installed editor neither asks for the key again nor quietly\n // moves a self-hoster off their own endpoint and back onto ours.\n const url = resolveEndpoint(opts.url) ?? DEFAULT_ENDPOINT;\n let apiKey = resolveApiKey(opts.apiKey);\n const selfHosted = url !== DEFAULT_ENDPOINT;\n\n if (interactive) {\n const { input, checkbox, confirm, select } = await import('@inquirer/prompts');\n\n console.log(`\\n ${bold('lurq setup')}: connect this machine to the package index.\\n`);\n // Always say which index, so a self-hoster can see at a glance that a\n // re-run did not quietly move them back onto the shared service.\n console.log(` Endpoint: ${url}${selfHosted ? dim(' (your own server)') : ''}\\n`);\n\n // Straight from npx: nothing was installed, so offer to put the command on\n // PATH first, while the user is still at the keyboard. Asked rather than\n // done silently, because it writes outside their project.\n if (runningFromNpx()) {\n const goGlobal = await confirm({\n message: `Install ${PACKAGE_NAME} globally, so \\`lurq\\` works without npx?`,\n default: true,\n });\n if (goGlobal) installGlobally();\n console.log('');\n }\n\n if (apiKey && !opts.apiKey) {\n const stored = readUserConfig().apiKey === apiKey;\n const reuse = await confirm({\n message: `Use the API key already configured${stored ? ' on this machine' : ' in your environment'}?`,\n default: true,\n });\n if (!reuse) apiKey = undefined;\n }\n\n // The browser hands the key back by itself. Tried first, and only for the\n // hosted service: a self-hoster's key comes from their own machine and our\n // dashboard has never seen it. See browserAuth.ts for why this is worth a\n // listener, and for every way it falls back to the paste below.\n if (!apiKey && !selfHosted) {\n const { keyViaBrowser } = await import('./browserAuth');\n console.log(' Sign in and this machine gets its key. Nothing to copy.\\n');\n process.stdout.write(' Waiting for the browser… ');\n const handoff = await keyViaBrowser({\n noOpen: opts.noOpen,\n // Printed rather than only opened: the browser may not have launched,\n // and a spinner pointing at a URL nobody can see is a hung flow.\n onUrl: (link) => console.log(`\\n\\n ${dim(link)}\\n`),\n });\n if (handoff) {\n apiKey = handoff.key;\n console.log(green(` ✓ key received${handoff.label ? dim(` (${handoff.label})`) : ''}\\n`));\n } else {\n console.log(yellow(' no response'));\n console.log(dim(' Falling back to pasting it in.\\n'));\n }\n }\n\n if (!apiKey) {\n if (selfHosted) {\n // Sending them to our dashboard would hand them a key their own server\n // has never issued and cannot validate.\n console.log(` Issue a key on the machine running ${url}:\\n`);\n console.log(` ${bold('lurq keys create --label my-laptop')}\\n`);\n console.log(' Then paste it below.\\n');\n } else {\n if (!opts.noOpen) {\n console.log(` Opening ${KEYS_URL}\\n`);\n openInBrowser(KEYS_URL);\n } else {\n console.log(` Open ${KEYS_URL}\\n`);\n }\n console.log(' 1. Sign in, or create an account. It takes a moment.');\n console.log(' 2. Create an API key and copy it.');\n console.log(' 3. Paste it below.\\n');\n }\n apiKey = (\n await input({\n message: 'Paste your lurq API key',\n validate: (v) =>\n v.trim().startsWith('lurq_') ? true : 'Keys look like lurq_live_… ',\n })\n ).trim();\n }\n\n process.stdout.write(' Validating key… ');\n const check = await validateKey(url, apiKey);\n console.log(\n check === 'valid' ? green('ok') : check === 'invalid' ? yellow('rejected') : yellow('could not reach endpoint'),\n );\n if (check !== 'valid') {\n const proceed = await confirm({\n message:\n check === 'invalid'\n ? `That key was rejected (401) by ${url}. Continue anyway?`\n : `Couldn't reach ${url} to validate the key. Continue anyway?`,\n default: false,\n });\n if (!proceed) {\n console.log('Aborted. No config was changed.');\n return;\n }\n }\n\n if (opts.agent) {\n await finish(resolveAgents(opts.agent), { url, apiKey });\n return;\n }\n\n const specs = agentSpecs();\n // Natural-language quick path: if we spot likely agents, offer a one-tap\n // connect before falling back to the full multi-select. \"Yes\" wires up EVERY\n // detected agent (the prior multi-select pre-checked them all), so a user\n // with two editors doesn't silently leave one unconnected.\n const detected = specs.filter((s) => s.detected);\n const primary = detected.find((s) => s.id === 'claude-code') ?? detected[0];\n if (primary) {\n const others = detected.length - 1;\n const choice = await select({\n message:\n others > 0\n ? `Looks like you have ${detected.map((s) => s.label).join(', ')}. Connect lurq to them?`\n : `Looks like you have ${primary.label}. Connect lurq to it?`,\n default: 'yes',\n choices: [\n {\n name: others > 0 ? `Yes, set up all ${detected.length} detected agents` : `Yes, set up ${primary.label} for me`,\n value: 'yes',\n },\n { name: 'No, let me choose which agent(s)', value: 'other' },\n { name: 'Cancel, change nothing', value: 'cancel' },\n ],\n });\n if (choice === 'cancel') {\n console.log('No problem. Nothing was changed; run `lurq setup` again anytime.');\n return;\n }\n if (choice === 'yes') {\n await finish(detected, { url, apiKey });\n return;\n }\n // 'other' falls through to the full multi-select below.\n }\n\n const ids = await checkbox({\n message: 'Which assistant(s) should I configure?',\n choices: specs.map((s) => ({\n name: `${s.label}${s.detected ? ' (detected)' : ''}`,\n value: s.id,\n checked: s.detected,\n })),\n });\n await finish(specs.filter((s) => ids.includes(s.id)), { url, apiKey });\n return;\n }\n\n // Non-interactive (--yes): require a key, use flags/env + detected agents.\n if (!apiKey) {\n throw new Error(\n 'No API key. Pass --api-key <key> or set LURQ_API_KEY (or drop --yes to be prompted).',\n );\n }\n const selected = opts.agent\n ? resolveAgents(opts.agent)\n : agentSpecs().filter((s) => s.detected);\n await finish(selected, { url, apiKey });\n}\n\n/**\n * Store the credential, wire up the selected agents, and report.\n *\n * The key is saved even when no agent was selected: on a machine with no editor\n * installed yet (a fresh container, a server) the CLI itself is still the point,\n * and making the user re-paste the key later would be the wrong lesson.\n */\nasync function finish(\n selected: AgentSpec[],\n remote: { url: string; apiKey: string },\n): Promise<void> {\n const configPath = writeUserConfig({\n apiKey: remote.apiKey,\n // Only persist a non-default endpoint. Storing the default would pin this\n // machine to today's URL and quietly ignore a later change to the built-in.\n endpoint: remote.url === DEFAULT_ENDPOINT ? undefined : remote.url,\n });\n console.log(`\\n${green('✓')} API key saved to ${configPath} ${dim('(mode 0600)')}`);\n console.log(\n `${green('✓')} Pointed at ${remote.url}${\n remote.url === DEFAULT_ENDPOINT ? '' : dim(' (your own server)')\n }`,\n );\n // Named with the invocation this machine actually has. This line used to say\n // `lurq …` unconditionally, which is false for anyone who ran the wizard from\n // npx and declined (or failed) the global install: setup reports total\n // success and the very next thing they type does not exist.\n const { command } = lurqInvocation();\n console.log(\n dim(` \\`${command} recommend\\`, \\`evaluate\\`, \\`compare\\`, \\`verify\\`, \\`usage\\` now work anywhere.`),\n );\n\n if (selected.length === 0) {\n console.log(\n '\\nNo agents selected or detected. Re-run `lurq setup --agent <id>` once your assistant is installed.',\n );\n return;\n }\n\n const mode: InstallMode = { kind: 'remote', ...remote };\n const results = selected.map((s) => installAgent(s, mode));\n const instructionsPath = installInstructionsFile();\n console.log('');\n printInstallReport(results, instructionsPath, mode);\n}\n","/**\n * Apply a selection policy to a candidate list.\n *\n * Pure: candidates and facts in, allowed and excluded out. No database, no\n * clock — the rules are the part worth testing exhaustively, and a pure function\n * is the only version of them that can be.\n */\nimport type { Advisory, AdvisorySeverity, Candidate, Confidence } from '../core/types';\nimport type { Exclusion, PolicyFacts, SelectionPolicy } from './types';\n\n/** Ordering for the `minConfidence` floor. Mirrors search/recommend. */\nconst CONFIDENCE_RANK: Record<Confidence, number> = {\n unproven: 0,\n promising: 1,\n emerging: 2,\n proven: 3,\n};\n\n/**\n * Worst tolerated → blocked. Ranked so `maxAdvisorySeverity: 'moderate'` reads\n * as \"moderate is fine, high and critical are not\", which is how the rule is\n * phrased in the UI and how teams say it out loud.\n */\nconst SEVERITY_RANK: Record<AdvisorySeverity, number> = {\n info: 0,\n low: 1,\n moderate: 2,\n high: 3,\n critical: 4,\n};\n\n/** The worst advisory on a package, or null when it carries none. */\nfunction worst(advisories: Advisory[] | null | undefined): Advisory | null {\n if (!advisories?.length) return null;\n return advisories.reduce((a, b) =>\n SEVERITY_RANK[b.severity] > SEVERITY_RANK[a.severity] ? b : a,\n );\n}\n\n/**\n * Does this policy actually rule on anything?\n *\n * The free path — no policy configured — must not pay for an extra query per\n * recommendation, and this is what lets the handler skip the fact lookup\n * entirely. `licenses: []` counts as a rule even though it allows nothing;\n * treating it as \"no rule\" would silently ignore a policy someone saved.\n */\nexport function hasRules(policy: SelectionPolicy): boolean {\n return (\n policy.deny.length > 0 ||\n policy.minConfidence !== null ||\n policy.licenses !== null ||\n policy.blockDeprecated ||\n policy.blockArchived ||\n policy.maxAdvisorySeverity !== null ||\n policy.minWeeklyDownloads !== null ||\n policy.maxStaleMonths !== null ||\n policy.maxBundleKb !== null ||\n policy.minPackageAgeDays !== null\n );\n}\n\n/**\n * The policy as enforced at `now`: exceptions past their expiry removed.\n *\n * Applied by the loader that owns the clock, never inside `check`, so the rules\n * stay a pure function. And never applied to what `GET /policy` returns: a pull\n * that silently dropped expired entries would delete them on the next push,\n * erasing the record that an exception existed and lapsed.\n */\nexport function withoutExpired(policy: SelectionPolicy, now: Date): SelectionPolicy {\n const today = now.toISOString().slice(0, 10);\n // `expires` is the first day the exception no longer applies. ISO dates\n // compare correctly as strings, which is why the parser insists on that form.\n return { ...policy, allow: policy.allow.filter((a) => !a.expires || a.expires > today) };\n}\n\n/**\n * One sentence per active rule, most severe first — what an agent reads before\n * it picks. Empty when nothing is enforced: an allowlist on its own exempts\n * packages from rules that do not exist, so it is not worth a line.\n */\nexport function describeRules(policy: SelectionPolicy): string[] {\n if (!hasRules(policy)) return [];\n const out: string[] = [];\n if (policy.mode === 'warn') {\n out.push('Warn only: packages that break these rules are reported, not refused.');\n }\n for (const a of policy.allow) {\n // \"expires\", not \"until\": the date is the first day it no longer applies.\n const expires = a.expires ? `, expires ${a.expires}` : '';\n out.push(`Always allowed: ${a.name}${a.reason ? ` (${a.reason})` : ''}${expires}.`);\n }\n for (const d of policy.deny) out.push(`Never use ${d.name}${d.reason ? `: ${d.reason}` : '.'}`);\n if (policy.maxAdvisorySeverity) {\n out.push(`No packages with a known advisory above ${policy.maxAdvisorySeverity}.`);\n }\n if (policy.minPackageAgeDays !== null) {\n out.push(`No packages first published less than ${policy.minPackageAgeDays} days ago.`);\n }\n if (policy.licenses) {\n out.push(\n policy.licenses.length\n ? `Licenses allowed: ${policy.licenses.join(', ')}.`\n : 'No license is allowed, so every package with a known license is refused.',\n );\n }\n if (policy.blockDeprecated) out.push('No deprecated packages.');\n if (policy.blockArchived) out.push('No packages whose repository is archived.');\n if (policy.minConfidence) out.push(`lurq confidence must be ${policy.minConfidence} or better.`);\n if (policy.minWeeklyDownloads !== null) {\n out.push(`At least ${policy.minWeeklyDownloads.toLocaleString('en-US')} weekly downloads.`);\n }\n if (policy.maxStaleMonths !== null) {\n out.push(`A release within the last ${policy.maxStaleMonths} months.`);\n }\n if (policy.maxBundleKb !== null) out.push(`Bundle size at most ${policy.maxBundleKb} KB min+gzip.`);\n return out;\n}\n\n/**\n * What changed between two policies, as `-`/`+` rule sentences.\n *\n * Diffed on the sentences rather than the JSON: a reviewer approving a policy\n * change reads \"- Never use request\" faster than a nested field path, and two\n * policies that describe the same rules are the same policy for that purpose.\n */\nexport function diffPolicies(before: SelectionPolicy, after: SelectionPolicy): string[] {\n const was = describeRules(before);\n const now = describeRules(after);\n return [\n ...was.filter((r) => !now.includes(r)).map((r) => `- ${r}`),\n ...now.filter((r) => !was.includes(r)).map((r) => `+ ${r}`),\n ];\n}\n\nexport interface PolicyResult {\n allowed: Candidate[];\n /** Refused. Always empty in warn mode. */\n excluded: Exclusion[];\n /** Would have been refused; kept in `allowed`. Always empty in enforce mode. */\n warned: Exclusion[];\n}\n\n/**\n * Split candidates into what the agent may use and what it may not.\n *\n * Order is preserved: the ranking upstream is the product of relevance and\n * evidence, and policy is a filter over it, never a re-rank.\n */\nexport function applyPolicy(\n policy: SelectionPolicy,\n candidates: Candidate[],\n facts: Map<string, PolicyFacts>,\n): PolicyResult {\n const allowed: Candidate[] = [];\n const excluded: Exclusion[] = [];\n const warned: Exclusion[] = [];\n const warnOnly = policy.mode === 'warn';\n\n for (const candidate of candidates) {\n const exclusion = check(policy, candidate, facts.get(candidate.name));\n if (!exclusion) allowed.push(candidate);\n else if (warnOnly) {\n warned.push(exclusion);\n allowed.push(candidate);\n } else excluded.push(exclusion);\n }\n\n return { allowed, excluded, warned };\n}\n\n/**\n * Evaluate one candidate. Returns the exclusion, or null when it passes.\n *\n * Rule order is deliberate: `allow` first, so an explicit exception always wins;\n * then `deny`, so a human's block beats every inferred rule; then the inferred\n * rules in descending severity. A package that trips several rules is reported\n * under the one a person would consider most serious, because the reason is what\n * the agent acts on and a list of four is a list it will summarise badly.\n */\nexport function check(\n policy: SelectionPolicy,\n // Structural, not `Candidate`: the rules read a name and an evidence grade and\n // nothing else, so `evaluate` can pass its own row without inventing the rest\n // of a Candidate to satisfy a type. Candidate still satisfies this shape.\n pkg: { name: string; confidence: Confidence },\n facts: PolicyFacts | undefined,\n): Exclusion | null {\n const { name } = pkg;\n\n if (policy.allow.some((a) => a.name === name)) return null;\n\n const denied = policy.deny.find((d) => d.name === name);\n if (denied) {\n return {\n name,\n rule: 'denied',\n reason: denied.reason ?? \"Blocked by your organisation's selection policy.\",\n };\n }\n\n // Absent facts never convict. An unindexed license cannot fail a license\n // rule — that turns \"we didn't look\" into a refusal, which is the same lie as\n // turning it into an all-clear, just pointed the other way. Every rule below\n // reads its fact through `?.` plus a null check for exactly that reason.\n\n // Security first: a known vulnerability outranks every judgement call under\n // it. A package that is also deprecated, huge and stale is still reported as\n // the security problem, because that is the one the agent must not route\n // around.\n if (policy.maxAdvisorySeverity) {\n const hit = worst(facts?.advisories);\n if (hit && SEVERITY_RANK[hit.severity] > SEVERITY_RANK[policy.maxAdvisorySeverity]) {\n return {\n name,\n rule: 'advisory',\n reason: `Known ${hit.severity} advisory (${hit.id}): ${hit.summary}. Your policy allows ${policy.maxAdvisorySeverity} and below.`,\n };\n }\n }\n\n // Next to security because it is security: a brand-new package is where\n // malware, account takeovers and squatted names a model hallucinated all live\n // before anyone has looked. Cheaper to wait out than to clean up.\n if (\n policy.minPackageAgeDays !== null &&\n facts?.daysSincePublished != null &&\n facts.daysSincePublished < policy.minPackageAgeDays\n ) {\n return {\n name,\n rule: 'age',\n reason: `First published ${facts.daysSincePublished} days ago; your policy requires ${policy.minPackageAgeDays}. New packages are where supply-chain attacks live before anyone notices.`,\n };\n }\n\n if (policy.blockDeprecated && facts?.deprecated) {\n return { name, rule: 'deprecated', reason: 'Marked deprecated on npm.' };\n }\n\n if (policy.blockArchived && facts?.archived) {\n return {\n name,\n rule: 'archived',\n reason: 'Its source repository is archived, so nothing will be fixed upstream.',\n };\n }\n\n if (policy.licenses && facts?.license && !policy.licenses.includes(facts.license)) {\n return {\n name,\n rule: 'license',\n reason: `License ${facts.license} is not in the allowed set (${policy.licenses.join(', ')}).`,\n };\n }\n\n if (policy.minConfidence) {\n if (CONFIDENCE_RANK[pkg.confidence] < CONFIDENCE_RANK[policy.minConfidence]) {\n return {\n name,\n rule: 'confidence',\n reason: `Evidence is ${pkg.confidence}; your policy requires ${policy.minConfidence} or better.`,\n };\n }\n }\n\n // Adoption, staleness and size are the three judgement calls, ordered by how\n // strong a claim each one makes. Downloads say \"nobody else runs this\"; a\n // release gap says \"nobody is minding it\"; size says \"it costs more than it is\n // worth\" — the weakest of the three, so it is reported last.\n if (\n policy.minWeeklyDownloads !== null &&\n facts?.weeklyDownloads != null &&\n facts.weeklyDownloads < policy.minWeeklyDownloads\n ) {\n return {\n name,\n rule: 'adoption',\n reason: `${facts.weeklyDownloads.toLocaleString('en-US')} weekly downloads is below your floor of ${policy.minWeeklyDownloads.toLocaleString('en-US')}.`,\n };\n }\n\n if (\n policy.maxStaleMonths !== null &&\n facts?.monthsSinceRelease != null &&\n facts.monthsSinceRelease > policy.maxStaleMonths\n ) {\n return {\n name,\n rule: 'stale',\n reason: `Last release was ${facts.monthsSinceRelease} months ago; your policy allows ${policy.maxStaleMonths}.`,\n };\n }\n\n if (policy.maxBundleKb !== null && facts?.bundleKb != null && facts.bundleKb > policy.maxBundleKb) {\n return {\n name,\n rule: 'size',\n reason: `${facts.bundleKb.toFixed(1)} KB min+gzip exceeds your ceiling of ${policy.maxBundleKb} KB.`,\n };\n }\n\n return null;\n}\n","/**\n * Parse untrusted JSON into a SelectionPolicy.\n *\n * A policy is a permission grant, so this rejects rather than repairs. Merging a\n * partial object over the default would let a malformed request silently drop a\n * rule someone is relying on — the failure mode is a package quietly becoming\n * installable again, which nobody would notice until it shipped.\n *\n * The one exception is `null` for the optional rules, which is a meaningful\n * value (\"no rule\") rather than a missing one.\n *\n * Rejections name the field and what was wrong with it. A policy is now a file\n * people edit by hand and push from CI, and \"not a valid policy\" on a 60-line\n * file sends them hunting.\n */\nimport type { AdvisorySeverity, Confidence } from '../core/types';\nimport type { AllowRule, DenyRule, PolicyMode, SelectionPolicy } from './types';\n\nconst CONFIDENCES: readonly Confidence[] = ['unproven', 'promising', 'emerging', 'proven'];\nconst SEVERITIES: readonly AdvisorySeverity[] = ['info', 'low', 'moderate', 'high', 'critical'];\nconst MODES: readonly PolicyMode[] = ['enforce', 'warn'];\n\n/** Bound on list length and entry size — a policy is hand-written, not generated. */\nconst MAX_ENTRIES = 500;\nconst MAX_LEN = 214; // npm's own package-name limit; reasons get the same ceiling.\n\n/**\n * Ceilings on the numeric rules.\n *\n * Not tidiness: these values are written straight into a rule that refuses\n * installs, so an unbounded number is a way to author a policy that blocks the\n * entire index by typo. Nobody ever means a floor of a billion weekly downloads\n * or a zero-KB bundle ceiling.\n */\nconst LIMITS = {\n minWeeklyDownloads: { min: 0, max: 100_000_000 },\n maxStaleMonths: { min: 1, max: 240 },\n maxBundleKb: { min: 1, max: 100_000 },\n minPackageAgeDays: { min: 1, max: 365 },\n} as const;\n\nclass Invalid extends Error {}\n\nfunction fail(message: string): never {\n throw new Invalid(message);\n}\n\n/**\n * A bounded, finite number, or `null` for \"no rule\".\n *\n * Rejects NaN, Infinity and out-of-range values rather than clamping them —\n * clamping silently saves a rule other than the one that was sent, which is the\n * whole failure mode this parser exists to prevent.\n */\nfunction bounded(input: unknown, field: keyof typeof LIMITS): number | null {\n if (input === null || input === undefined) return null;\n const { min, max } = LIMITS[field];\n if (typeof input !== 'number' || !Number.isFinite(input) || input < min || input > max) {\n fail(`${field} must be a number from ${min} to ${max}, or null for no rule.`);\n }\n return input;\n}\n\nfunction oneOf<T extends string>(input: unknown, field: string, options: readonly T[]): T | null {\n if (input === null || input === undefined) return null;\n if (!options.includes(input as T)) {\n fail(`${field} must be one of ${options.join(', ')}, or null for no rule.`);\n }\n return input as T;\n}\n\nfunction list(input: unknown, field: string): unknown[] {\n if (!Array.isArray(input)) fail(`${field} must be a list.`);\n if (input.length > MAX_ENTRIES) fail(`${field} has more than ${MAX_ENTRIES} entries.`);\n return input;\n}\n\nfunction name(input: unknown, where: string): string {\n if (typeof input !== 'string') fail(`${where} must be a string.`);\n const trimmed = input.trim();\n if (!trimmed || trimmed.length > MAX_LEN) fail(`${where} must be 1 to ${MAX_LEN} characters.`);\n return trimmed;\n}\n\n/** A trimmed reason, or undefined when absent or blank — a blank one is not stored. */\nfunction reason(input: unknown, where: string): string | undefined {\n if (input === null || input === undefined) return undefined;\n if (typeof input !== 'string' || input.length > MAX_LEN) {\n fail(`${where}.reason must be text of at most ${MAX_LEN} characters.`);\n }\n return input.trim() || undefined;\n}\n\nfunction entry(input: unknown, where: string): Record<string, unknown> {\n if (!input || typeof input !== 'object' || Array.isArray(input)) {\n fail(`${where} must be an object with a name.`);\n }\n return input as Record<string, unknown>;\n}\n\nfunction denyRules(input: unknown): DenyRule[] {\n return list(input, 'deny').map((item, i) => {\n const raw = entry(item, `deny[${i}]`);\n const rule: DenyRule = { name: name(raw.name, `deny[${i}].name`) };\n const why = reason(raw.reason, `deny[${i}]`);\n return why ? { ...rule, reason: why } : rule;\n });\n}\n\nfunction allowRules(input: unknown): AllowRule[] {\n return list(input, 'allow').map((item, i) => {\n const where = `allow[${i}]`;\n // A bare name is how exceptions were saved before they carried a reason or\n // an expiry. Still accepted, so an older client and older files keep working.\n if (typeof item === 'string') return { name: name(item, where) };\n const raw = entry(item, where);\n const rule: AllowRule = { name: name(raw.name, `${where}.name`) };\n const why = reason(raw.reason, where);\n if (why) rule.reason = why;\n if (raw.expires !== null && raw.expires !== undefined) {\n // Round-tripped through Date so 2026-02-31 is refused rather than read as\n // March 3rd. ISO form is required because enforcement compares as strings.\n const valid =\n typeof raw.expires === 'string' &&\n /^\\d{4}-\\d{2}-\\d{2}$/.test(raw.expires) &&\n !Number.isNaN(Date.parse(raw.expires)) &&\n new Date(raw.expires).toISOString().slice(0, 10) === raw.expires;\n if (!valid) fail(`${where}.expires must be a date like 2026-12-31.`);\n rule.expires = raw.expires as string;\n }\n return rule;\n });\n}\n\nfunction build(input: unknown): SelectionPolicy {\n if (!input || typeof input !== 'object' || Array.isArray(input)) fail('policy must be an object.');\n const raw = input as Record<string, unknown>;\n\n const allow = allowRules(raw.allow);\n const deny = denyRules(raw.deny);\n\n if (typeof raw.blockDeprecated !== 'boolean') fail('blockDeprecated must be true or false.');\n\n // `null` and `[]` are different policies: no rule at all, versus an allowlist\n // that permits nothing. Collapsing them would turn a saved empty allowlist\n // into an unenforced one.\n const licenses =\n raw.licenses === null || raw.licenses === undefined\n ? null\n : list(raw.licenses, 'licenses').map((item, i) => name(item, `licenses[${i}]`));\n\n // Fields added after the first release. `undefined` is accepted and means the\n // least restrictive reading — no rule, or enforce for `mode`, which is what a\n // policy meant before the field existed. An older client keeps working.\n if (raw.blockArchived !== undefined && typeof raw.blockArchived !== 'boolean') {\n fail('blockArchived must be true or false.');\n }\n if (raw.mode !== undefined && !MODES.includes(raw.mode as PolicyMode)) {\n fail(`mode must be ${MODES.join(' or ')}.`);\n }\n\n return {\n mode: (raw.mode as PolicyMode | undefined) ?? 'enforce',\n allow,\n deny,\n minConfidence: oneOf(raw.minConfidence, 'minConfidence', CONFIDENCES),\n licenses,\n blockDeprecated: raw.blockDeprecated,\n blockArchived: raw.blockArchived === true,\n maxAdvisorySeverity: oneOf(raw.maxAdvisorySeverity, 'maxAdvisorySeverity', SEVERITIES),\n minWeeklyDownloads: bounded(raw.minWeeklyDownloads, 'minWeeklyDownloads'),\n maxStaleMonths: bounded(raw.maxStaleMonths, 'maxStaleMonths'),\n maxBundleKb: bounded(raw.maxBundleKb, 'maxBundleKb'),\n minPackageAgeDays: bounded(raw.minPackageAgeDays, 'minPackageAgeDays'),\n };\n}\n\n/** The policy, or the first thing wrong with it, in words a person can fix. */\nexport function validateSelectionPolicy(\n input: unknown,\n): { policy: SelectionPolicy } | { error: string } {\n try {\n return { policy: build(input) };\n } catch (err) {\n if (err instanceof Invalid) return { error: err.message };\n throw err;\n }\n}\n\nexport function parseSelectionPolicy(input: unknown): SelectionPolicy | null {\n const result = validateSelectionPolicy(input);\n return 'policy' in result ? result.policy : null;\n}\n","/**\n * `lurq policy pull|push`: selection policy as a file in the repo.\n *\n * The point is review. A rule that refuses installs for a whole team should go\n * through a pull request like any other change to how the team builds, and a\n * dashboard form cannot be diffed. `push --check` is the PR gate; plain `push`\n * is the post-merge apply, and needs a policy:write key.\n */\nimport { readFileSync, writeFileSync } from 'node:fs';\nimport { resolveApiKey } from '../core/userConfig';\nimport { describeRules, diffPolicies } from '../policy/enforce';\nimport { validateSelectionPolicy } from '../policy/parse';\nimport type { SelectionPolicy } from '../policy/types';\nimport { getPolicy, getPolicyDecisions, getPolicyHistory, putPolicy, type RemoteOptions } from './remote';\n\nexport async function runPolicyPull(file: string | undefined, opts: RemoteOptions): Promise<void> {\n const text = `${JSON.stringify(await getPolicy(opts), null, 2)}\\n`;\n if (!file) {\n process.stdout.write(text);\n return;\n }\n writeFileSync(file, text);\n console.log(`wrote ${file}`);\n}\n\n/** The file as a policy, or null after printing what is wrong with it. */\nexport function readPolicyFile(file: string): SelectionPolicy | null {\n let raw: unknown;\n try {\n raw = JSON.parse(readFileSync(file, 'utf8'));\n } catch (err) {\n console.error(`${file}: ${err instanceof Error ? err.message : String(err)}`);\n return null;\n }\n // Same validator the server runs, so --check can never pass a file push rejects.\n const result = validateSelectionPolicy(raw);\n if ('error' in result) {\n console.error(`${file}: ${result.error}`);\n return null;\n }\n return result.policy;\n}\n\nfunction indent(lines: string[], empty: string): string {\n return lines.length ? lines.map((line) => ` ${line}`).join('\\n') : ` ${empty}`;\n}\n\nexport async function runPolicyPush(\n file: string,\n opts: RemoteOptions & { check?: boolean },\n): Promise<void> {\n const policy = readPolicyFile(file);\n if (!policy) {\n process.exitCode = 1;\n return;\n }\n\n if (opts.check) {\n console.log(`${file} is a valid policy.`);\n // With a key on hand, show the change merging this file would make: that is\n // what the person approving the PR is actually deciding. Without one (a\n // fork's PR has no secrets), validity is all that can honestly be said.\n if (!resolveApiKey(opts.apiKey)) {\n console.log(indent(describeRules(policy), 'no rules enforced.'));\n return;\n }\n console.log('pushing it would change:');\n console.log(indent(diffPolicies(await getPolicy(opts), policy), 'nothing.'));\n return;\n }\n\n const { previous } = await putPolicy(policy, opts);\n console.log('policy replaced.');\n console.log(\n previous\n ? indent(diffPolicies(previous, policy), 'no rule changes.')\n : indent(describeRules(policy), 'no rules enforced.'),\n );\n}\n\n/** Who changed the policy, from where, and what changed, newest first. */\nexport async function runPolicyHistory(opts: RemoteOptions & { json?: boolean }): Promise<void> {\n const changes = await getPolicyHistory(opts);\n if (opts.json) {\n console.log(JSON.stringify(changes, null, 2));\n return;\n }\n if (!changes.length) {\n console.log('no policy changes recorded yet.');\n return;\n }\n for (const change of changes) {\n console.log(`${change.at.slice(0, 16).replace('T', ' ')} UTC ${change.actor}`);\n console.log(indent(change.changes, 'saved with no rule changes.'));\n }\n}\n\n/** What the policy refused, or would have in warn mode, grouped by package and rule. */\nexport async function runPolicyLog(\n opts: RemoteOptions & { days?: string; json?: boolean },\n): Promise<void> {\n const days = opts.days === undefined ? 30 : Number(opts.days);\n const decisions = await getPolicyDecisions(days, opts);\n if (opts.json) {\n console.log(JSON.stringify(decisions, null, 2));\n return;\n }\n if (!decisions.length) {\n console.log(`nothing refused or warned about in the last ${days} days.`);\n return;\n }\n const width = Math.max(...decisions.map((d) => d.packageName.length));\n for (const d of decisions) {\n console.log(\n `${d.packageName.padEnd(width)} ${d.action.padEnd(7)} ${d.rule.padEnd(10)} ${String(d.count).padStart(4)}x last ${d.lastDay}`,\n );\n }\n}\n","/**\n * Environment configuration (§15). Validated with zod. Most vars are optional\n * so the CLI can run partially (e.g. `lurq --help`) without a full setup;\n * commands that need a specific var call `requireConfig` to fail fast with a\n * clear message.\n */\nimport { config as dotenvConfig } from 'dotenv';\nimport { z } from 'zod';\n\nlet envLoaded = false;\n\n/**\n * Load env into process.env exactly once. Safe to call repeatedly.\n *\n * Layering: if `LURQ_ENV_FILE` is set (e.g. `.env.production`), that file loads\n * *first* so its values win, then `.env` fills in the rest (dotenv never\n * overrides an already-set key). This is how the explicit prod path works —\n * `LURQ_ENV_FILE=.env.production` supplies the prod DATABASE_URL while `.env`\n * still provides shared secrets — without prod ever being the ambient default.\n */\nexport function loadEnv(): void {\n if (envLoaded) return;\n const overrideFile = process.env.LURQ_ENV_FILE;\n if (overrideFile) dotenvConfig({ path: overrideFile });\n dotenvConfig();\n envLoaded = true;\n}\n\nconst EnvSchema = z.object({\n DATABASE_URL: z.string().min(1).optional(),\n GITHUB_TOKEN: z.string().min(1).optional(),\n\n // 'openai' here means \"OpenAI-compatible\" — any provider exposing /v1/embeddings\n // + Bearer auth (OpenAI, Together, Fireworks, HF TEI, …). Point *_BASE_URL at it.\n EMBEDDING_PROVIDER: z.enum(['openai', 'local']).default('openai'),\n EMBEDDING_API_KEY: z.string().min(1).optional(),\n EMBEDDING_MODEL: z.string().min(1).default('text-embedding-3-small'),\n EMBEDDING_BASE_URL: z.string().url().default('https://api.openai.com/v1'),\n\n // 'openai' means \"OpenAI-compatible /v1/chat/completions\": OpenAI, Groq, Together,\n // Fireworks, xAI (Grok), etc. Swap provider by setting SUMMARY_BASE_URL + key + model.\n SUMMARY_PROVIDER: z.enum(['openai', 'none']).default('openai'),\n SUMMARY_API_KEY: z.string().min(1).optional(),\n SUMMARY_MODEL: z.string().min(1).default('gpt-4o-mini'),\n SUMMARY_BASE_URL: z.string().url().default('https://api.openai.com/v1'),\n\n /**\n * How many `npm install --package-lock-only` processes may run at once.\n *\n * Each one holds npm's arborist tree in memory — 200-500MB for a real stack —\n * so this is a memory cap wearing a concurrency hat. Eight concurrent resolves\n * is ~3GB and will OOM a small container; the work is network-bound anyway, so\n * raising it buys throughput only until the box runs out of RAM.\n */\n LURQ_RESOLVE_CONCURRENCY: z.coerce.number().int().positive().max(32).default(4),\n /**\n * Where npm keeps its metadata cache for stack resolution.\n *\n * Point this at a persistent volume in production. A warm cache is the\n * difference between 8.6s and 19.2s on a 15-package stack (measured), and an\n * ephemeral container filesystem means every redeploy pays cold cost again for\n * the first few hundred resolves. Unset = npm's default location.\n */\n LURQ_NPM_CACHE_DIR: z.string().min(1).optional(),\n /** Budget for one stack resolve. Past this the answer is `unknown`, never a\n * guess — and nothing is cached, so the next ask gets a real attempt. */\n LURQ_RESOLVE_TIMEOUT_MS: z.coerce.number().int().positive().default(25_000),\n\n LURQ_SYNC_CONCURRENCY: z.coerce.number().int().positive().max(50).default(5),\n /** Stalest non-seed packages the daily sync refreshes on top of the seed list.\n * This is the rotation rate for everything discovery ingested: index size /\n * this = days to come all the way around. Raise it if the sync finishes well\n * inside the cron window; lower it if npm starts rate-limiting. 0 disables\n * the rotation (seeds only, the pre-rotation behaviour).\n *\n * It is also the discovery frontier's clock, which is why it is not a small\n * number. `graphChannel` re-expands a package only when its `latest_version`\n * moves, and nothing observes a version move except this rotation — so at 400\n * against a 20.8k index the graph channel could only re-arm on a 52-day lag\n * and had gone effectively silent. */\n LURQ_SYNC_REFRESH_CAP: z.coerce.number().int().min(0).max(25_000).default(2000),\n LOG_LEVEL: z.enum(['error', 'warn', 'info', 'debug']).default('info'),\n\n // Hosted HTTP service (`serve-http`). Server-side only.\n PORT: z.coerce.number().int().positive().default(8080),\n /** Per-API-key rate limit: max requests per window. */\n LURQ_RATE_LIMIT_MAX: z.coerce.number().int().positive().default(120),\n /** Coarser per-IP rate limit (blunts unauthenticated floods before auth). */\n LURQ_IP_RATE_LIMIT_MAX: z.coerce.number().int().positive().default(240),\n /** Per-IP limit for `POST /scan/public`, the one unauthenticated route that\n * reads GitHub, queries the database, and queues ingestion work. The coarse\n * IP limit is the wrong ceiling for it: 240 scans a minute is nothing for a\n * JSON-RPC caller and a great deal of somebody else's GitHub budget. */\n LURQ_SCAN_RATE_LIMIT_MAX: z.coerce.number().int().positive().default(10),\n /** Rate-limit window, milliseconds (applies to both limiters). */\n LURQ_RATE_LIMIT_WINDOW_MS: z.coerce.number().int().positive().default(60_000),\n /** Bearer token guarding `/metrics`. Unset → the endpoint is disabled (404). */\n LURQ_METRICS_TOKEN: z.string().min(1).optional(),\n /** Shared secret for self-serve key issuance (`POST /keys`). The Clerk-\n * authenticated web app presents it to mint a key for a signed-in user. Unset\n * → the endpoint is disabled (404). Keep it server-side, never in the client. */\n LURQ_ISSUER_SECRET: z.string().min(1).optional(),\n /** PostHog project token (the public `phc_…` one, same as the web app's).\n * Set → the hosted service sends account-keyed product events (key issued,\n * tool called) that join the web app's identified visitors. Unset → nothing\n * is sent, which is every local and stdio install. */\n LURQ_POSTHOG_KEY: z.string().min(1).optional(),\n\n // Billing (Stripe). Every secret here lives on this service and nowhere else:\n // the web app holds no Stripe credential and reaches checkout through the\n // issuer-secret routes, the same way it reaches key issuance. Unset →\n // /billing/* is disabled (404) and every account is served the free tier, so\n // a deployment without Stripe configured degrades to \"free for everyone\"\n // rather than to \"nobody can call anything\".\n STRIPE_SECRET_KEY: z.string().min(1).optional(),\n /** Signing secret for `POST /billing/webhook`. Unset → the endpoint is 404. */\n STRIPE_WEBHOOK_SECRET: z.string().min(1).optional(),\n /** Price id backing the Pro plan. Unset → Pro cannot be checked out. */\n /**\n * Whether Stripe Managed Payments applies to our Checkout Sessions: Stripe as\n * merchant of record, taking over indirect tax registration and remittance,\n * disputes and fraud — the half `automatic_tax` alone does not buy.\n *\n * ALWAYS SENT, in both directions, and that is the point. Managed Payments has\n * an account-level default (on, for accounts created since it shipped), so\n * omitting the parameter hands the decision to a dashboard toggle instead of\n * to config. That is action at a distance: the same deploy behaves differently\n * per account, and the failure it produces is a 400 at the moment someone\n * tries to pay. Sending it explicitly makes the deployment the authority.\n *\n * Defaults true to match the account default. Every product must carry an\n * eligible `tax_code` (see billing/provision.ts) or Stripe rejects the session,\n * so `false` is the one-variable escape hatch if eligibility is ever in doubt.\n */\n STRIPE_MANAGED_PAYMENTS: z\n .enum(['true', 'false'])\n .default('true')\n .transform((v) => v === 'true'),\n STRIPE_PRICE_PRO: z.string().min(1).optional(),\n /** Price id backing Enterprise. Normally unset: Enterprise is sold by\n * conversation, and `contactOnly` in core/plans.ts is what the page reads. */\n STRIPE_PRICE_ENTERPRISE: z.string().min(1).optional(),\n /** Absolute base URL the checkout returns to, e.g. https://lurq.run. */\n LURQ_WEB_URL: z.string().url().default('https://lurq.run'),\n\n // GitHub App (repo autopilot). Only the App itself holds repo access; lurq\n // never stores a user's personal token. Either unset → /repos is disabled (404).\n // The App *slug* is deliberately not here: only the web app needs it, to build\n // the install link, and it reads process.env directly.\n /** Numeric App ID from the GitHub App settings page. */\n LURQ_GITHUB_APP_ID: z.string().min(1).optional(),\n /** PEM private key. Accepts literal newlines or `\\n` escapes (Railway/Vercel). */\n LURQ_GITHUB_APP_PRIVATE_KEY: z.string().min(1).optional(),\n /** Webhook secret from the same App settings page, so repo changes made on\n * GitHub reach us. Unset → `POST /github/webhook` is disabled (404): an\n * unverified webhook is an open write endpoint, so no secret means no route. */\n LURQ_GITHUB_WEBHOOK_SECRET: z.string().min(1).optional(),\n\n // Client-side (install wizard / CLI talking to a remote endpoint).\n LURQ_ENDPOINT: z.string().url().optional(),\n LURQ_API_KEY: z.string().min(1).optional(),\n\n // Sandbox verification. With E2B_API_KEY set, package install + smoke-load\n // runs in an isolated E2B cloud sandbox (safe for UNTRUSTED packages);\n // without it, the local child-process driver is used (trusted packages only).\n E2B_API_KEY: z.string().min(1).optional(),\n // E2B template to launch. Must provide node + npm on PATH; omit for E2B's\n // default. Provision a Node-versioned template here for reproducible runs.\n E2B_TEMPLATE: z.string().min(1).optional(),\n\n // Lurq bakeoff testing toggle b/w local and prod DB\n USE_LIVE_API: z.string().min(1).optional(),\n});\n\nexport type Config = z.infer<typeof EnvSchema>;\n\nexport class ConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ConfigError';\n }\n}\n\nlet cached: Config | undefined;\n\n/** Parse + validate the environment. Throws ConfigError on malformed values. */\nexport function getConfig(): Config {\n if (cached) return cached;\n loadEnv();\n const parsed = EnvSchema.safeParse(process.env);\n if (!parsed.success) {\n const issues = parsed.error.issues\n .map((i) => ` - ${i.path.join('.')}: ${i.message}`)\n .join('\\n');\n throw new ConfigError(`Invalid environment configuration:\\n${issues}`);\n }\n cached = parsed.data;\n return cached;\n}\n\n/** For tests: clear the memoized config so a fresh getConfig() re-reads\n * process.env. Does not force a `.env` reload (loadEnv stays idempotent). */\nexport function resetConfigCache(): void {\n cached = undefined;\n}\n\n/**\n * Return the config but fail fast if any of the named required keys are absent.\n * Use in command handlers that genuinely need them (e.g. sync needs DATABASE_URL).\n */\nexport function requireConfig<K extends keyof Config>(keys: K[]): Config {\n const config = getConfig();\n const missing = keys.filter((k) => config[k] === undefined || config[k] === '');\n if (missing.length > 0) {\n throw new ConfigError(\n `Missing required environment variable(s): ${missing.join(', ')}.\\n` +\n `See .env.example for setup. Tip: copy it to .env and fill in the values.`,\n );\n }\n return config;\n}\n","/**\n * Shared domain types and the v1 category taxonomy (§8.3).\n * These are the stable contracts the rest of the system builds on.\n */\n\n/**\n * Which registry a package lives in.\n *\n * `npm` is the default everywhere — every read path defaults to it, so adding\n * this type changed no existing behaviour. What it buys is that a package name\n * is only unique WITHIN a registry: `requests`, `redis`, `click` and `attrs` all\n * exist on both npm and PyPI as entirely unrelated software, and keying on the\n * bare name would let one overwrite the other's evidence.\n *\n * PyPI names normalise before they are stored (PEP 503: `Flask`, `flask` and\n * `Flask_SQLAlchemy` are the same project); that belongs in the PyPI client at\n * the ingestion boundary, not here, so `name` always holds the canonical form.\n */\nexport const ECOSYSTEMS = ['npm', 'pypi'] as const;\nexport type Ecosystem = (typeof ECOSYSTEMS)[number];\n\n/**\n * The registry every existing caller means when it doesn't say.\n *\n * Every read helper takes `ecosystem` as a DEFAULTED parameter rather than a\n * required one. That is what let the composite key land as a pure no-op: not a\n * single call site changed, and npm behaviour is bit-identical. A PyPI caller\n * passes the argument; nobody else has to care.\n *\n * ponytail: only `packages` is keyed by registry so far. These are still keyed\n * by bare package name and WILL collide once PyPI rows exist — each one is safe\n * today only because nothing writes a PyPI row yet, so scope it in the phase\n * that first makes it multi-ecosystem, not speculatively now:\n *\n * package_versions → needed by PyPI compat (per-version requires-dist)\n * seed_packages → needed when a PyPI package can join the sync roster\n * discovery_queue → needed by PyPI discovery (classifiers + BigQuery seed)\n * api_surfaces,\n * surface_queue,\n * symbols, entities → needed by the Python surface worker\n * compat_edges,\n * resolved_closures → needed by the `uv` resolve-check\n *\n * The unscoped reads that go with them live in db/discovery.ts, db/apiSurfaces.ts\n * and pipeline/discovery.ts. Adding a PyPI write path without scoping the tables\n * it touches is how one registry starts answering for the other.\n *\n * RETRIEVAL IS THE ONE THIS DEFAULT CANNOT COVER, and it is the one that fails\n * quietly. A keyed lookup has a name to disambiguate, so a defaulted argument\n * resolves it. `search/recommend.ts` has no name — finding names IS the query —\n * so nothing here helps it, and the first PyPI row with an embedding puts\n * SQLAlchemy in the results for a TypeScript project. No error, just a wrong\n * answer. Retrieval has to take its ecosystem from the REQUEST (the repo whose\n * manifest was parsed, an explicit tool argument, or the stack the agent is\n * editing), never from a default.\n *\n * Two notes for whoever wires that up: filtering the HNSW index after the fact\n * loses recall — pre-filtered partial indexes per ecosystem keep it — and the\n * lexical `search_vector` needs the same treatment, or the hybrid's two halves\n * will disagree about which registry they are searching.\n */\nexport const DEFAULT_ECOSYSTEM: Ecosystem = 'npm';\n\n/** Category taxonomy for the JS/TS web stack (§8.3). `other` is the fallback. */\nexport const CATEGORIES = [\n 'framework',\n 'meta-framework',\n 'state-management',\n 'routing',\n 'orm',\n 'database-client',\n 'ui-component-library',\n 'styling',\n 'forms',\n 'validation',\n 'data-fetching',\n 'http-client',\n 'auth',\n 'testing',\n 'build-tool',\n 'bundler',\n 'linting',\n 'date-time',\n 'animation',\n 'charts',\n 'i18n',\n 'utility',\n 'other',\n] as const;\n\nexport type Category = (typeof CATEGORIES)[number];\n\nexport function isCategory(value: string): value is Category {\n return (CATEGORIES as readonly string[]).includes(value);\n}\n\n/** Provenance of a package's stored category (§2A). `curated` comes from the\n * seed file or a manual arg; `inferred` was assigned automatically at ingest\n * and is safe for a later curation pass to override. */\nexport type CategorySource = 'curated' | 'inferred';\n\n/** How a candidate entered the discovery queue (§2B). `dependency-graph` and\n * `recent` are the long-tail channels; `category-search` is keyword-seeded;\n * `reactive` is an on-demand query that wasn't tracked yet. */\nexport type DiscoverySource =\n | 'dependency-graph'\n | 'category-search'\n | 'recent'\n | 'reactive'\n /** Seen on npm's `_changes` replication feed — a name we had never heard of. */\n | 'npm-changes';\n\n/** Lifecycle of a discovery-queue candidate (§2B). */\nexport type DiscoveryStatus = 'pending' | 'ingested' | 'rejected';\n\n/**\n * Categories for which bundle size is meaningful and Bundlephobia is consulted\n * (§9.5). Backend-only categories get a null bundle size, and their efficiency\n * weight is redistributed (§10, see scoring).\n */\nexport const FRONTEND_CATEGORIES = [\n 'ui-component-library',\n 'styling',\n 'state-management',\n 'forms',\n 'validation',\n 'data-fetching',\n 'charts',\n 'animation',\n 'date-time',\n 'utility',\n] as const;\n\nexport function isFrontendCategory(category: Category | null | undefined): boolean {\n return category != null && (FRONTEND_CATEGORIES as readonly string[]).includes(category);\n}\n\n/**\n * Evidence-trustworthiness label, independent of the numeric score (§10, §1).\n * Two-dimensional: `proven`/`emerging` are adoption ladders; `promising` is\n * adoption-independent (high intrinsic quality, new package).\n */\nexport type Confidence = 'proven' | 'emerging' | 'promising' | 'unproven';\n\nexport type Runtime = 'browser' | 'node' | 'both';\n\n/** Result of co-installing two package versions in the sandbox (compat matrix). */\nexport type CompatStatus = 'compatible' | 'conflict';\n\n/**\n * Evidence class behind a compat edge (§3, §4B). Ordered weakest→strongest for\n * upsert precedence: a mined `observed` must never overwrite a sandbox `verified`\n * or `conflict`. `declared` = Tier-0 peer/engine semver; `observed` = co-resolved\n * in N real dependency graphs; `verified` = sandbox co-install passed; `conflict`\n * = declared conflict or a sandbox co-install failed.\n */\nexport type CompatProvenance = 'declared' | 'observed' | 'verified' | 'conflict';\n\n/** Upsert precedence: higher wins, so mining can't erase a proven verdict. */\nexport const PROVENANCE_RANK: Record<CompatProvenance, number> = {\n declared: 0,\n observed: 1,\n verified: 2,\n conflict: 3,\n};\n\n/** Coarse post-install result an agent reports back via `report_outcome` — never\n * source code, just whether the recommended package installed / compiled /\n * passed tests, or failed. Feeds the recommendation→outcome flywheel (§3.1). */\nexport type BuildSignal = 'installed' | 'compiled' | 'tests_passed' | 'failed';\n\n/** Sandbox verdict surfaced to agents: did this version actually install + load? */\nexport interface BuildVerified {\n version: string;\n installed: boolean;\n loaded: boolean | null;\n driver: string;\n ranAt: string;\n}\n\n/** A map of dependency/peer/engine name → semver range (from a manifest). */\nexport type DependencyRanges = Record<string, string>;\n/** `peerDependenciesMeta`: per-peer flags, notably `{ optional: true }`. */\nexport type PeerMeta = Record<string, { optional?: boolean }>;\n\n/** One incompatibility found across a set of packages. */\nexport interface CompatConflict {\n /** Where the conflict came from. `peer-deps`/`engines` are Tier-1 (metadata,\n * instant, deterministic); `resolve` is npm's own ERESOLVE on the whole set;\n * `sandbox` is the empirical co-install under VM isolation.\n *\n * A `resolve` conflict is about the SET, not a pair — npm reports that these\n * packages cannot coexist, not which two are at fault — so `packages` carries\n * every member and `enumeratePairs` deliberately does not attribute it. */\n source: 'peer-deps' | 'engines' | 'sandbox' | 'resolve';\n /** The packages involved in the conflict. */\n packages: string[];\n detail: string;\n /** The same fact as `detail`, structured, so a consumer can lay it out without\n * parsing prose. Present on peer-range violations; absent for engine and\n * sandbox conflicts, which aren't about a single declared range. */\n requirement?: {\n /** The peer being asked for. */\n peer: string;\n /** The range the requirer declares. */\n range: string;\n /** What the set actually resolves that peer to, when it is in the set. */\n resolved: string | null;\n };\n}\n\n/**\n * One unordered pair among the checked members.\n *\n * A verdict belongs to a pair, not to a package: the same package can sit in a\n * held pair and a conflicting one, so grading packages would either contradict\n * itself or paint the whole set red. `held` means no declared constraint between\n * the two was violated — it does not mean the pair was executed. Nothing here\n * has been executed.\n */\nexport interface CompatPair {\n a: string;\n b: string;\n status: 'held' | 'conflict';\n /** Only on `conflict` — the conflict's own detail string. */\n detail?: string;\n /** Only on `conflict`, and only for peer-range violations. */\n requirement?: CompatConflict['requirement'];\n}\n\n/** One stored compat edge surfaced to agents, with its evidence class (§4B). */\nexport interface CompatEvidence {\n packages: [string, string];\n versions: [string, string];\n status: CompatStatus;\n provenance: CompatProvenance;\n /** Distinct resolved graphs an `observed` edge was witnessed in (0 otherwise).\n * Only a newly-fetched closure accrues one; the daily re-mine re-reads closures\n * it has already counted and deliberately does not. NOTE: rows minted before\n * that fix carry an inflated count (one per sync run, ~16× on average) and are\n * only corrected by a backfill, which has not been run. */\n witnessCount: number;\n}\n\n/**\n * How the set-level verdict was established.\n *\n * `source` distinguishes a cache hit from a resolve we just ran, which matters\n * for a caller deciding whether the answer is worth re-checking: a cached entry\n * is exact for those versions and immutable, but it was minted at `at` and the\n * publish that would have invalidated it may not have been seen yet.\n */\nexport interface CompatResolution {\n source: 'cache' | 'resolved';\n /** True when npm produced a lockfile for the exact set. */\n resolved: boolean;\n /** 'ERESOLVE' for a proven conflict; null when it resolved. */\n reason: 'ERESOLVE' | null;\n /** npm's own message on a conflict — names the packages and ranges. */\n detail?: string;\n /** ISO timestamp the resolution was established. */\n at: string;\n}\n\n/**\n * `compat` output: whole-architecture compatibility for a set of packages.\n * Tier-1 peer-dependency/engine analysis + any Tier-2 sandbox conflicts.\n */\nexport interface CompatOutput {\n packages: string[];\n /** Verdict about the *set*, not its pairs:\n * - `conflict` — proven broken: a peer-range violation, a sandbox conflict,\n * or npm's own ERESOLVE on this exact set.\n * - `compatible` — npm resolved these exact versions together.\n * - `unknown` — genuinely undetermined: a member we have no version for, or\n * a resolve that could not complete. Never a hedge on a set\n * we did resolve.\n *\n * There is deliberately no `likely`. It meant \"no pair is known to be broken\",\n * which is a statement about our coverage rather than about the packages, and\n * it was the answer real stacks got almost every time. */\n overall: 'compatible' | 'conflict' | 'unknown';\n conflicts: CompatConflict[];\n /** Packages lurq has no compatibility metadata for (counted toward `unknown`). */\n unverified: string[];\n /** The exact members the check ran over, name + resolved version. Versions are\n * always surfaced here, and the structure is stable for later scraping. */\n checked: { name: string; version: string | null }[];\n /** Sandbox-established edges among these packages (verified/conflict) — the\n * one pairwise signal that is not derivable from a set resolution. */\n evidence: CompatEvidence[];\n /** How the set-level verdict was reached. Absent when a declared conflict made\n * a resolve unnecessary, or when a member had no version to key on. */\n resolution?: CompatResolution;\n /** Every unordered pair among `checked`, each with its own verdict — exactly\n * n(n−1)/2 entries. `conflicts` lists only what went wrong; this lists what\n * was compared, which is what lets a caller show coverage rather than just\n * failures. */\n pairs: CompatPair[];\n}\n\n// ── Usage axis D1: API signature drift (§4D) ─────────────────────────────────\n\n/** Kind of an exported symbol, from its `.d.ts` declaration. */\nexport type ExportKind =\n | 'function'\n | 'class'\n | 'interface'\n | 'type'\n | 'enum'\n | 'variable'\n | 'namespace'\n | 'unknown';\n\n/** One normalized exported symbol of a package version's public API surface. */\nexport interface ExportSymbol {\n name: string;\n kind: ExportKind;\n /** Single-line normalized signature (params/return for functions, etc.), or\n * null when the declaration carries no useful signature. */\n signature: string | null;\n}\n\n/** What changed between two API surfaces (§4D). Deltas are computed, not guessed. */\nexport interface SurfaceDelta {\n added: ExportSymbol[];\n removed: ExportSymbol[];\n /** A symbol that disappeared and a near-identical one that appeared — inferred\n * by signature similarity, so an agent sees a rename, not remove+add. */\n renamed: { from: ExportSymbol; to: ExportSymbol }[];\n /** Same name, changed signature. */\n changed: { name: string; before: string | null; after: string | null }[];\n}\n\n/** `usage` tool output: version-exact API surface + optional delta from a known\n * version the agent was trained/working on (§4D). */\nexport interface UsageOutput {\n package: string;\n version: string | null;\n /** Extracted export list, or null when types are unavailable (falls back to\n * the README, which is already fetched). */\n surface: ExportSymbol[] | null;\n available: boolean;\n /** Declared `engines` for this exact version (e.g. `{ node: \">=20\" }`), or null\n * when the manifest declares none. Independent of `available` — the runtime\n * floor matters even for untyped packages. */\n engines: Record<string, string> | null;\n /** Present when a `knownVersion` was supplied and both surfaces resolved. */\n delta?: SurfaceDelta & { fromVersion: string };\n /** Echo of a requested version the registry has never published. A structured\n * flag as well as prose, so an agent can branch on \"this release does not\n * exist\" without parsing `note` — it is a different answer from \"we have no\n * surface for it yet\", and only one of the two means stop. */\n unpublishedVersion?: string;\n /** Why a requested `knownVersion` delta is absent. Only set when one was asked\n * for and could not be produced — silence about a requested comparison reads\n * as \"no changes\", which is the one thing it never means. */\n deltaNote?: string;\n note?: string;\n}\n\nexport type AdvisorySeverity = 'critical' | 'high' | 'moderate' | 'low' | 'info';\n\nexport interface Advisory {\n id: string;\n severity: AdvisorySeverity;\n summary: string;\n}\n\n/** Sub-scores composing the health score (§10). `efficiency` is null when not\n * size-based (backend categories) — its weight is redistributed.\n * `quality` (§1) is a standalone, adoption-independent axis — it does NOT feed\n * the health composite; it blends with health only at ranking time. Null when\n * no manifest signals were available. */\nexport interface ScoreBreakdown {\n maintenance: number;\n adoption: number;\n reliability: number;\n efficiency: number | null;\n quality: number | null;\n /**\n * Field evidence (§3.1) — how this package actually fared after agents\n * installed it, from `recommendation_outcomes`. `null` means no reports yet\n * and the weight is redistributed, exactly like `efficiency`.\n *\n * Optional rather than required because it postdates the rows already in\n * `packages.score_breakdown`: a stored breakdown from before this shipped\n * decodes with the key absent, and `undefined` must read as \"no evidence\",\n * never as 0. Treating it as 0 would drop every un-reported package's health\n * the moment this deployed.\n */\n field?: number | null;\n}\n\n/**\n * Structured usage guide generated at ingest (product refinement: lurq explains,\n * not just ranks). Grounded in the package README/description — never fabricated.\n * Exact current API specifics are deferred to Context7 via `context7Hint`.\n */\nexport interface UsageGuide {\n whatItIs: string;\n whenToUse: string;\n whenNotToUse?: string;\n whereItFits: string;\n howToWireIn?: string;\n context7Hint?: string;\n}\n\n/** A single recommendation candidate (§12.3.1). Intentionally compact. */\nexport interface Candidate {\n name: string;\n category: Category | null;\n healthScore: number;\n qualityScore: number | null;\n confidence: Confidence;\n why: string;\n latestVersion: string | null;\n weeklyDownloads: number | null;\n lastReleaseAt: string | null;\n repoUrl: string | null;\n /**\n * The three facts that can reverse an install decision on their own.\n *\n * `recommend` is the call an agent makes *before* choosing a dependency, and\n * it carried none of them: a deprecated package could be returned with nothing\n * in the payload saying so, leaving `confidence` and a numeric score as the\n * only hints. Deprecation caps the maintenance component and bars `proven`,\n * but a low score reads as \"less good\", not \"do not install this\". `evaluate`\n * and `verify` have always carried these; the tool most likely to precede an\n * install should not be the one that hides them.\n *\n * Emitted even when false/zero — see mcp/compact, which keeps both on purpose,\n * so an agent never has to read meaning into an absent field.\n */\n deprecated: boolean;\n archived: boolean;\n advisories: number;\n}\n\n/** Full evidence read for one package (§12.3.2). */\nexport interface EvaluateOutput {\n dataAsOf: string;\n stale?: boolean;\n name: string;\n category: Category | null;\n healthScore: number;\n qualityScore: number | null;\n confidence: Confidence;\n scoreBreakdown: ScoreBreakdown;\n latestVersion: string | null;\n lastReleaseAt: string | null;\n weeklyDownloads: number | null;\n downloadGrowth90d: number | null;\n scorecard: number | null;\n bundleMinGzipKb: number | null;\n deprecated: boolean;\n archived: boolean;\n /** The shared safety call — identical to what `verify` and `audit` return. */\n verdict: SecurityVerdict;\n advisories: Advisory[];\n summary: string | null;\n usageGuide: UsageGuide | null;\n repoUrl: string | null;\n /** If this package is superseded, the recommended migration target (§1.2). */\n replacedBy?: { name: string; reason: string } | null;\n /** Latest sandbox verdict for this package, if one has been run. */\n buildVerified?: BuildVerified | null;\n}\n\n/** `verify` output (§12.3.4). */\n/** Supply-chain risk gate: high = review before installing (see security/risk). */\nexport type RiskLevel = 'low' | 'medium' | 'high';\n\nimport type { SecurityVerdict } from '../security/verdict';\n\nexport interface VerifyOutput {\n exists: boolean;\n tracked: boolean;\n deprecated: boolean;\n archived: boolean;\n latestVersion: string | null;\n weeklyDownloads: number | null;\n riskFlags: string[];\n /** Overall supply-chain risk, rolled up from riskFlags. */\n risk: RiskLevel;\n /** Suspected typosquat target — a popular package this name closely mimics. */\n typosquatOf: string | null;\n confidence: Confidence | null;\n /** Null when this package has never been analysed — NOT the same as zero. */\n advisoryCount: number | null;\n /** The shared safety call. Read `verdict.reassuring` before showing a tick. */\n verdict: SecurityVerdict;\n}\n","/**\n * What lurq can do, as data.\n *\n * lurq has eleven MCP tools, sixteen CLI commands and seven dashboard pages, and\n * the honest problem with that is nobody — human or agent — holds the map. An\n * agent with `verify` in its tool list still writes `npm install` and hopes; a\n * user staring at a drift number does not know `check-upgrade` is the thing that\n * tells them whether it matters. Both failures are the same failure: the\n * capability exists and is not findable at the moment it is needed.\n *\n * So the catalog is indexed by the *question*, not by the endpoint. Entries are\n * jobs (\"am I about to break my consumers?\"), and each one carries the exact\n * next move on every surface that can do it. A match is not an explanation, it\n * is a command to run or a tool to call.\n *\n * Deliberately not embeddings. The corpus is twenty entries of controlled\n * vocabulary that we write ourselves — a scorer over titles, questions and\n * aliases beats a vector search at this size, costs nothing, needs no key, and\n * returns the same answer every time. When the catalog outgrows a screen, or\n * when queries start arriving in words we never anticipated, revisit.\n * ponytail: token scorer; move to `src/search/embeddings` if recall drops.\n */\n\nexport type Surface = 'mcp' | 'cli' | 'dashboard';\n\nexport interface Capability {\n id: string;\n /** Imperative, five words or fewer. This is the palette row's headline. */\n title: string;\n /** The user's question in their words — what they'd type into the box. */\n question: string;\n /** One sentence on what lurq actually does, and what it will not claim. */\n answer: string;\n /** The MCP tool an agent should call. */\n mcp?: string;\n /** A runnable command, with placeholders in <angle brackets>. */\n cli?: string;\n /** A dashboard route, when a page is the better answer than a command. */\n page?: string;\n /** Extra vocabulary the title and question don't contain. */\n aliases?: string[];\n}\n\nexport const CAPABILITIES: Capability[] = [\n {\n id: 'verify',\n title: 'Check a package is real',\n question: 'Does this package actually exist, and is it safe to install?',\n answer:\n 'Checks the live registry for existence, deprecation, archival and advisories — the guard against a hallucinated or typosquatted name reaching package.json.',\n mcp: 'verify',\n cli: 'lurq verify <package>',\n aliases: ['hallucinated', 'typosquat', 'slopsquat', 'fake', 'malicious', 'safe', 'exists'],\n },\n {\n id: 'evaluate',\n title: 'Read the evidence on a package',\n question: 'Is this package healthy, maintained, and worth adopting?',\n answer:\n 'The full evidence read for one package: health and quality scores with the signals behind them, release cadence, advisories, and how to wire it up.',\n mcp: 'evaluate',\n cli: 'lurq evaluate <package>',\n aliases: ['health', 'maintained', 'abandoned', 'deprecated', 'score', 'quality'],\n },\n {\n id: 'compare',\n title: 'Compare packages side by side',\n question: 'Which of these two should I go with?',\n answer: 'Ranks 2–5 named packages against each other on the same scored evidence.',\n mcp: 'compare',\n cli: 'lurq compare <a> <b>',\n aliases: ['versus', 'vs', 'shootout', 'better'],\n },\n {\n id: 'compat',\n title: 'Check a stack fits together',\n question: 'Will these packages work together?',\n answer:\n 'Peer-dependency and engine checks across the whole set at once, plus any sandbox-verified conflicts on record. Returns the exact clashing constraints.',\n mcp: 'compat',\n cli: 'lurq compat <a> <b> <c>',\n aliases: ['peer', 'conflict', 'incompatible', 'engines', 'node version', 'together'],\n },\n {\n id: 'usage',\n title: 'See a version-exact API',\n question: 'What does this package actually export at this version?',\n answer:\n 'The exported symbols and signatures for one exact version, read from the shipped JS — plus the delta from a version you already know.',\n mcp: 'usage',\n cli: 'lurq usage <package> --target <version>',\n aliases: ['exports', 'symbols', 'api', 'signature', 'surface'],\n },\n {\n id: 'diff-surface',\n title: 'See what an upgrade removes',\n question: 'What breaks between these two versions?',\n answer:\n 'The symbol-level diff between two published versions: what was removed, what changed arity, what is new. Runtime breakage is reported separately from type-only breakage.',\n mcp: 'diff_surface',\n cli: 'lurq usage <package> --known <old> --target <new>',\n aliases: ['breaking', 'removed', 'changed', 'migration', 'major'],\n },\n {\n id: 'audit',\n title: 'Audit this whole project',\n question: 'What in this project is outdated, vulnerable, or drifting?',\n answer:\n 'Reads your manifests and agent configs locally, then assesses every dependency and MCP server in one call: outdated versions, deprecations, advisories against the exact installed version, and servers that need credentials or cannot be observed. Always prints how many items it actually answered for — anything it could not assess is reported as unassessed, never as clean.',\n mcp: 'audit',\n cli: 'lurq audit',\n aliases: ['scan', 'outdated', 'vulnerable', 'audit', 'health', 'project', 'dependencies', 'cve'],\n },\n {\n id: 'mcp-stack',\n title: 'Check your MCP servers coexist',\n question: 'Do the MCP servers I have wired up conflict with each other?',\n answer:\n 'Tool-name collisions across the servers configured into one agent. They are separate processes, so nothing resolves between them — they clash in the flat tool namespace the agent assembles, where two servers exposing the same name leave it unable to say which it means. Also reports the standing context cost of the whole set.',\n mcp: 'mcp_stack',\n cli: 'lurq mcp-stack',\n aliases: ['collision', 'conflict', 'namespace', 'mcp', 'tools', 'shadow', 'coexist'],\n },\n {\n id: 'mcp-surface',\n title: 'Read an MCP server\\'s tools',\n question: 'What tools does this MCP server actually expose, and what do they take?',\n answer:\n \"Every tool from a live `tools/list` handshake in a sandbox: required and optional parameters, and the behaviour annotations that say whether a tool writes, destroys, or reaches outside. Also returns the API keys and settings the server declares it needs, with a request you can put in front of the user. Declared contract only — that a tool is listed is not evidence that calling it succeeds.\",\n mcp: 'mcp_surface',\n cli: 'lurq mcp-surface <server>',\n aliases: ['mcp', 'tools', 'tool schema', 'inputSchema', 'agent tools', 'server'],\n },\n {\n id: 'mcp-drift',\n title: 'See what an MCP upgrade changes',\n question: 'Did this MCP server change its tool contract?',\n answer:\n 'The contract diff between two versions of an MCP server: tools removed, parameters that became required, types narrowed, and annotation flips. Reports silent drift (schema moved, description unchanged) and privilege widening (a tool that stopped being read-only) separately, because neither shows up in a changelog.',\n mcp: 'mcp_drift',\n cli: 'lurq mcp-drift <server> --from <old> --to <new>',\n aliases: ['mcp', 'schema drift', 'tool drift', 'readOnlyHint', 'breaking', 'agent'],\n },\n {\n id: 'diagram',\n title: 'Draw the stack',\n question: 'Can I see this as a diagram?',\n answer: 'Renders an existing stack as a Mermaid graph other tools can parse.',\n mcp: 'diagram',\n aliases: ['mermaid', 'visual', 'chart', 'architecture', 'graph'],\n },\n {\n id: 'upgrade-plan',\n title: 'Find what is behind',\n question: 'How far out of date is this project?',\n answer:\n 'Reads the local manifests and reports the gap between what is resolved and what is current, with what each upgrade removes from its API. Sends dependency ranges only, never source.',\n cli: 'lurq upgrade-plan',\n page: '/dashboard/repos',\n aliases: ['drift', 'outdated', 'behind', 'stale', 'update', 'upgrade', 'bump', 'dependencies'],\n },\n {\n id: 'check-upgrade',\n title: 'Check an upgrade against your code',\n question: 'Will this upgrade break my code specifically?',\n answer:\n 'Intersects what the upgrade removes with what your code actually references, and answers with file:line. Needs no test suite and no network to lurq.',\n cli: 'lurq check-upgrade --plan plan.json --exit-code',\n aliases: ['breaking', 'ci', 'gate', 'call sites', 'references', 'blocking'],\n },\n {\n id: 'check-release',\n title: 'Check your own version bump',\n question: 'Am I about to break my consumers?',\n answer:\n 'Compares the built working tree against your last published version and says whether the bump you are about to tag covers what actually changed. For package authors.',\n cli: 'lurq check-release --exit-code',\n aliases: ['publish', 'semver', 'release', 'major', 'prepublish', 'library author'],\n },\n {\n id: 'check-api',\n title: 'Check your own API for breaks',\n question: 'Will this change break the people calling my service?',\n answer:\n 'Diffs two git revisions of your OpenAPI document: removed operations, newly required parameters and body fields, removed response codes — and whether info.version was bumped enough. Reads git only, nothing leaves the machine.',\n cli: 'lurq check-api --against origin/main --exit-code',\n aliases: ['openapi', 'swagger', 'endpoint', 'consumers', 'callers', 'service', 'contract', 'rest'],\n },\n {\n id: 'autopilot',\n title: 'Keep a repo current automatically',\n question: 'Can lurq just do the upgrades for me?',\n answer:\n 'Connect a repo and lurq drafts the upgrade, names the call sites it breaks, and opens a PR from your own runner. lurq never gets write access to your code.',\n page: '/dashboard/repos',\n cli: 'lurq upgrade-plan --json',\n aliases: ['automate', 'pr', 'github', 'renovate', 'dependabot', 'autopilot', 'workflow'],\n },\n {\n id: 'policy',\n title: 'Set what agents may install',\n question: 'How do I stop agents adding packages we do not allow?',\n answer:\n 'An allow/deny list plus licence and confidence floors, enforced at the moment an agent reaches for a dependency — before it becomes a line in package.json.',\n page: '/dashboard/policy',\n aliases: ['allowlist', 'whitelist', 'deny', 'blocklist', 'licence', 'license', 'govern', 'standard'],\n },\n {\n id: 'alerts',\n title: 'Watch repos for new risk',\n question: 'Tell me when something I depend on goes bad',\n answer:\n 'Per-repo advisories and deprecations across the resolved tree, with the direct dependency responsible for each transitive finding.',\n page: '/dashboard/repos',\n aliases: ['advisory', 'cve', 'vulnerability', 'security', 'transitive', 'sbom', 'alert'],\n },\n {\n id: 'usage-dashboard',\n title: 'See how lurq is being used',\n question: 'Who on my team is calling lurq, and how much?',\n answer: 'Call volume by tool and by day, plus the outcomes reported back after a recommendation.',\n page: '/dashboard/usage',\n aliases: ['activity', 'analytics', 'volume', 'calls', 'team', 'adoption', 'heatmap'],\n },\n {\n id: 'setup',\n title: 'Connect lurq to an assistant',\n question: 'How do I get this into Claude Code / Cursor?',\n answer:\n 'One command detects every assistant on the machine and writes the MCP entry. No database credentials touch your machine.',\n cli: 'npx lurqrun',\n page: '/dashboard/keys',\n aliases: ['install', 'mcp', 'cursor', 'claude code', 'windsurf', 'copilot', 'api key', 'onboard'],\n },\n {\n id: 'weights',\n title: 'Change how scoring works',\n question: 'I disagree with the ranking — can I tune it?',\n answer:\n 'Show the weight model, or layer your own overrides on top of the defaults, per user or per project.',\n cli: 'lurq edit-weights --set composite.lambda=0.5',\n aliases: ['scoring', 'ranking', 'tune', 'bias', 'lambda', 'override'],\n },\n {\n id: 'report-outcome',\n title: 'Tell lurq how it went',\n question: 'How does lurq learn from what I picked?',\n answer:\n 'An opt-in report of whether you took the recommendation and whether it built. Coarse signal only — never source code.',\n mcp: 'report_outcome',\n aliases: ['feedback', 'outcome', 'accepted', 'flywheel', 'learn'],\n },\n];\n\n/** Words carrying no discriminating signal in a corpus of questions about lurq. */\nconst STOP = new Set([\n 'a', 'an', 'the', 'is', 'it', 'i', 'my', 'me', 'do', 'does', 'how', 'what', 'which', 'to', 'for',\n 'of', 'in', 'on', 'and', 'or', 'can', 'with', 'this', 'that', 'be', 'am', 'are', 'should', 'lurq',\n 'package', 'packages',\n]);\n\n/** Hyphens split: `check-upgrade` has to be findable by \"upgrade\" alone. */\nconst tokenize = (s: string): string[] =>\n s\n .toLowerCase()\n .split(/[^a-z0-9.@/]+/)\n .filter((t) => t.length > 1 && !STOP.has(t));\n\n/**\n * Crude stemming by shared prefix, at half weight. English inflection mostly\n * happens at the end of a word, and a five-character agreement catches the cases\n * that matter here — upgrading/upgrade, dependencies/dependency, breaking/breaks\n * — which a `startsWith` check does not (they diverge before the suffix). A real\n * stemmer is a dependency and a lookup table for twenty entries of vocabulary we\n * control; this is the rung below it that works.\n */\nconst STEM_LEN = 5;\nconst sameStem = (a: string, b: string): boolean =>\n a.length >= STEM_LEN && b.length >= STEM_LEN && a.slice(0, STEM_LEN) === b.slice(0, STEM_LEN);\n\n/**\n * Field weights. `aliases` outscores `answer` on purpose: an alias is a word we\n * chose *because* someone would search for it, whereas a hit in the answer prose\n * is often incidental.\n */\nconst FIELDS: { of: (c: Capability) => string; weight: number }[] = [\n { of: (c) => c.title, weight: 5 },\n { of: (c) => c.question, weight: 4 },\n { of: (c) => (c.aliases ?? []).join(' '), weight: 3 },\n { of: (c) => c.answer, weight: 1 },\n { of: (c) => [c.mcp, c.cli, c.page].filter(Boolean).join(' '), weight: 4 },\n];\n\nexport interface CapabilityMatch extends Capability {\n score: number;\n}\n\n/**\n * Rank capabilities against a free-text query.\n *\n * A prefix match counts at half weight so \"upgrading\" finds \"upgrade\" and\n * \"dependencies\" finds \"dependency\" without a stemmer. An empty or unmatched\n * query returns the catalog in declaration order rather than nothing — for a\n * palette that is the browse state, and for an agent it is the full menu, which\n * is a better answer to \"what can you do\" than silence.\n */\nexport function searchCapabilities(query: string, limit = 5): CapabilityMatch[] {\n const terms = tokenize(query ?? '');\n if (!terms.length) return CAPABILITIES.slice(0, limit).map((c) => ({ ...c, score: 0 }));\n\n const scored = CAPABILITIES.map((c) => {\n let score = 0;\n for (const { of, weight } of FIELDS) {\n const haystack = tokenize(of(c));\n for (const term of terms) {\n if (haystack.includes(term)) score += weight;\n else if (haystack.some((h) => sameStem(h, term))) score += weight / 2;\n }\n }\n return { ...c, score };\n }).filter((c) => c.score > 0);\n\n if (!scored.length) return CAPABILITIES.slice(0, limit).map((c) => ({ ...c, score: 0 }));\n return scored.sort((a, b) => b.score - a.score).slice(0, limit);\n}\n","/**\n * Drizzle schema (§8). One denormalized `packages` table feeds all reads (§8.2),\n * plus `sync_runs` (ingestion audit) and `seed_packages` (curated bootstrap list).\n *\n * The `vector` extension must exist before these migrations apply — `db migrate`\n * runs `CREATE EXTENSION IF NOT EXISTS vector` first (pgvector is not created\n * automatically by Drizzle).\n */\nimport { sql } from 'drizzle-orm';\nimport {\n bigint,\n boolean,\n customType,\n date,\n index,\n integer,\n jsonb,\n pgTable,\n primaryKey,\n real,\n serial,\n text,\n timestamp,\n uniqueIndex,\n vector,\n} from 'drizzle-orm/pg-core';\nimport { EMBEDDING_DIM } from '../core/constants';\nimport type { ExclusionRule, SelectionPolicy } from '../policy/types';\nimport type { RuntimeTarget } from '../core/runtimeTarget';\n\n/** Postgres full-text `tsvector` type for hybrid lexical search (§3). */\nconst tsvector = customType<{ data: string; driverData: string }>({\n dataType() {\n return 'tsvector';\n },\n});\nimport type {\n Advisory,\n BuildSignal,\n Category,\n CategorySource,\n CompatProvenance,\n CompatStatus,\n Confidence,\n DependencyRanges,\n DiscoverySource,\n DiscoveryStatus,\n Ecosystem,\n ExportSymbol,\n PeerMeta,\n ScoreBreakdown,\n UsageGuide,\n} from '../core/types';\nimport type { EntityKind, EvidenceClass, Verdict } from '../graph/types';\nimport type {\n RepoDrift,\n RepoManifest,\n RepoPolicy,\n UpgradeRunStatus,\n UpgradeSeverity,\n} from '../github/types';\nimport type { ExtractionTier, SymbolKind } from '../surface/types';\nimport type { Tier } from '../core/plans';\n\nconst ts = (name: string) => timestamp(name, { withTimezone: true, mode: 'date' });\n\n/**\n * One row per tracked package.\n *\n * Keyed by (ecosystem, name), never by name alone: `requests`, `redis`, `click`\n * and `attrs` are all real packages on BOTH npm and PyPI, and they are unrelated\n * software. A global unique on `name` would let whichever registry synced last\n * overwrite the other's scores, advisories and version timeline.\n */\nexport const packages = pgTable(\n 'packages',\n {\n id: serial('id').primaryKey(),\n name: text('name').notNull(),\n ecosystem: text('ecosystem').$type<Ecosystem>().notNull().default('npm'),\n\n // Classification + descriptive text\n category: text('category').$type<Category>(),\n /** Whether `category` was hand-curated or inferred at ingest (§2A). */\n categorySource: text('category_source').$type<CategorySource>(),\n description: text('description'),\n summary: text('summary'),\n repoUrl: text('repo_url'),\n homepage: text('homepage'),\n latestVersion: text('latest_version'),\n license: text('license'),\n\n // Lifecycle flags\n deprecated: boolean('deprecated').notNull().default(false),\n archived: boolean('archived').notNull().default(false),\n\n // Age / maintenance signals\n firstPublishedAt: ts('first_published_at'),\n lastReleaseAt: ts('last_release_at'),\n\n // Adoption signals\n weeklyDownloads: bigint('weekly_downloads', { mode: 'number' }),\n downloadGrowth90d: real('download_growth_90d'),\n stars: integer('stars'),\n /**\n * Dependent counts from deps.dev, kept split rather than summed.\n *\n * `direct_dependents` counts packages that name this one in their own\n * manifest; `indirect_dependents` counts those that inherited it through\n * someone else's tree. The ratio is what distinguishes a library a human\n * chose from plumbing npm dragged in — a distinction weekly downloads and\n * GitHub stars both fail to make, because a monorepo's internal utility\n * inherits its parent's stars and every sibling's download volume.\n */\n directDependents: integer('direct_dependents'),\n indirectDependents: integer('indirect_dependents'),\n openIssues: integer('open_issues'),\n closedIssues: integer('closed_issues'),\n\n // Reliability / efficiency signals\n scorecard: real('scorecard'),\n bundleMinGzipKb: real('bundle_min_gzip_kb'),\n advisories: jsonb('advisories').$type<Advisory[]>(),\n\n // Compatibility metadata (Tier-1): declared peer-deps + engines of the\n // latest version, so a whole-stack peer-range check is one indexed query.\n peerDependencies: jsonb('peer_dependencies').$type<DependencyRanges>(),\n peerDependenciesMeta: jsonb('peer_dependencies_meta').$type<PeerMeta>(),\n engines: jsonb('engines').$type<DependencyRanges>(),\n /** Where this package runs, classified from its own manifest at ingest.\n * Resolves the `framework` category's frontend/backend ambiguity for the\n * architecture diagram. Null = the manifest did not say clearly enough. */\n runtimeTarget: text('runtime_target').$type<RuntimeTarget>(),\n\n // Computed outputs\n healthScore: integer('health_score'),\n /** Intrinsic-quality axis (§1), adoption-independent. Blends with health at\n * ranking time (composite); never folded into health_score itself. */\n qualityScore: integer('quality_score'),\n confidence: text('confidence').$type<Confidence>(),\n scoreBreakdown: jsonb('score_breakdown').$type<ScoreBreakdown>(),\n usageGuide: jsonb('usage_guide').$type<UsageGuide>(),\n embedding: vector('embedding', { dimensions: EMBEDDING_DIM }),\n // Identity of the vector space `embedding` was produced in (e.g.\n // `openai:text-embedding-3-small`, `local`). Vector search filters on the\n // active provider so switching models can't compare incompatible spaces.\n embeddingProvider: text('embedding_provider'),\n\n // Lexical search vector (§3): name weighted highest (A), then category (B),\n // then summary/description (C). Generated + STORED so it stays in sync with\n // the row automatically; indexed with GIN for fast `@@` matching.\n searchVector: tsvector('search_vector').generatedAlwaysAs(\n sql`setweight(to_tsvector('english', coalesce(name, '')), 'A') || setweight(to_tsvector('english', coalesce(category, '')), 'B') || setweight(to_tsvector('english', coalesce(summary, description, '')), 'C')`,\n ),\n\n // Freshness + bookkeeping\n dataAsOf: timestamp('data_as_of', { withTimezone: true, mode: 'date' }),\n /** latest_version this package's direct deps were last expanded for by the\n * discovery graph channel (§2B). Discovery re-scans a package only when this\n * differs from latest_version — deps are version-pinned, so an unchanged\n * version has unchanged neighbors. NULL = never scanned. */\n graphScannedVersion: text('graph_scanned_version'),\n createdAt: ts('created_at').notNull().defaultNow(),\n updatedAt: ts('updated_at').notNull().defaultNow(),\n /** The individual account (api_keys.owner_id) whose on-demand query first\n * caused this package to be ingested — nobody had asked for it before them.\n * Null for crawler/_changes-created packages, or ones ingested before\n * dashboard accounts existed. Stamped once via a standalone WHERE ... IS NULL\n * update kept out of upsertPackage, so re-syncs can never clobber it. */\n firstRequestedByOwnerId: text('first_requested_by_owner_id'),\n },\n (table) => [\n uniqueIndex('packages_ecosystem_name_idx').on(table.ecosystem, table.name),\n index('packages_category_idx').on(table.category),\n index('packages_health_score_idx').on(table.healthScore),\n // pgvector HNSW index for cosine similarity search (§11).\n index('packages_embedding_idx').using('hnsw', table.embedding.op('vector_cosine_ops')),\n // GIN index for lexical full-text search (§3).\n index('packages_search_vector_idx').using('gin', table.searchVector),\n index('packages_first_requested_by_idx').on(table.firstRequestedByOwnerId),\n ],\n);\n\n/** Ingestion audit trail (§8.1). */\nexport const syncRuns = pgTable('sync_runs', {\n id: serial('id').primaryKey(),\n startedAt: ts('started_at').notNull().defaultNow(),\n finishedAt: ts('finished_at'),\n packagesSeen: integer('packages_seen').notNull().default(0),\n packagesUpdated: integer('packages_updated').notNull().default(0),\n errors: jsonb('errors').$type<SyncError[]>().notNull().default([]),\n status: text('status').$type<SyncStatus>().notNull().default('running'),\n /** Which deployment started this run, `<environment>/<service>`, or null when\n * the host injects neither (local runs). Diagnostic only: two rows in the\n * same minute with *different* origins is a duplicate scheduler — a second\n * environment or a second service tile running the same cron — which is\n * otherwise invisible from the data and doubles the outbound request rate\n * until npm starts answering 429. */\n origin: text('origin'),\n});\n\n/** Curated v1 seed list (§16), loaded from seed.json. */\nexport const seedPackages = pgTable('seed_packages', {\n name: text('name').primaryKey(),\n category: text('category').$type<Category>(),\n addedAt: ts('added_at').notNull().defaultNow(),\n});\n\n/**\n * Proactive-discovery candidate queue (§2B). Operator-side: the crawler enqueues\n * adjacency-graph / category-search / recent candidates here, a merit gate\n * pre-scores them on quality signals only (downloads excluded), and survivors\n * graduate to full ingestion. Keeps cost bounded and the DB free of toy packages.\n */\nexport const discoveryQueue = pgTable(\n 'discovery_queue',\n {\n id: serial('id').primaryKey(),\n name: text('name').notNull().unique(),\n discoveredVia: text('discovered_via').$type<DiscoverySource>().notNull(),\n /** Lightweight quality-only pre-score (§2B). Null until the gate runs. */\n preScore: integer('pre_score'),\n status: text('status').$type<DiscoveryStatus>().notNull().default('pending'),\n discoveredAt: ts('discovered_at').notNull().defaultNow(),\n },\n (table) => [index('discovery_queue_status_idx').on(table.status)],\n);\n\n/**\n * Demand-driven compat-verify queue (§4C). A `compat` query that finds an\n * unverified pair enqueues the set here (instant, off the query path); the worker\n * drains it and runs the sandbox co-install, so the matrix self-densifies from\n * real usage without ever blocking a user or running a VM in the HTTP process.\n */\nexport const compatVerifyQueue = pgTable(\n 'compat_verify_queue',\n {\n id: serial('id').primaryKey(),\n /** Canonical order-independent key of the package set — dedups pending requests. */\n setKey: text('set_key').notNull().unique(),\n /** The package names to co-install in the sandbox. */\n packages: jsonb('packages').$type<string[]>().notNull(),\n /** Failed drains bump this; the worker drops a set that keeps failing. */\n attempts: integer('attempts').notNull().default(0),\n requestedAt: ts('requested_at').notNull().defaultNow(),\n },\n (table) => [index('compat_verify_queue_requested_idx').on(table.requestedAt)],\n);\n\n/**\n * API keys for the hosted HTTP service (docs/lurq-hosted-deployment.md §5). Each\n * user gets a key; only its sha256 hash is persisted, so a DB leak never\n * exposes a usable key — the plaintext is shown exactly once at creation.\n * `ownerId` is the individual Clerk user id, set at self-serve issuance from\n * the web dashboard (no org/team concept — one identity per account).\n */\nexport const apiKeys = pgTable(\n 'api_keys',\n {\n id: serial('id').primaryKey(),\n /** sha256 hex of the full key — the only form persisted. */\n keyHash: text('key_hash').notNull().unique(),\n /** Identifiable display prefix, e.g. `lurq_live_ab12cd` (safe to show/log). */\n prefix: text('prefix').notNull(),\n /** Free-text label (owner / org / purpose). */\n label: text('label'),\n /** Reserved for self-serve issuance: maps to a Clerk user id. */\n ownerId: text('owner_id'),\n tier: text('tier').notNull().default('free'),\n /**\n * Permissions beyond the default read-and-call access (see KEY_SCOPES).\n * Empty by default: `lurq setup` writes a key into agent config files, and\n * a key an agent holds must never be able to loosen the rules it runs under.\n */\n scopes: text('scopes').array().notNull().default(sql`'{}'::text[]`),\n createdAt: ts('created_at').notNull().defaultNow(),\n lastUsedAt: ts('last_used_at'),\n revokedAt: ts('revoked_at'),\n },\n (table) => [index('api_keys_owner_idx').on(table.ownerId)],\n);\n\n/**\n * Per-package version timeline (versions + publish dates), ingested from the npm\n * packument on every sync. Foundation for upgrade/migration intelligence and the\n * compatibility matrix; refreshed reactively by the `_changes` follower.\n */\nexport const packageVersions = pgTable(\n 'package_versions',\n {\n packageName: text('package_name').notNull(),\n version: text('version').notNull(),\n publishedAt: ts('published_at'),\n /** Peers/engines declared by this exact version. Lifted from the registry\n * document at ingest (it already carries every version's manifest), so a\n * conflict check against the versions a repo actually RUNS is one indexed\n * query rather than a registry read per dependency. */\n peerDependencies: jsonb('peer_dependencies').$type<DependencyRanges>(),\n engines: jsonb('engines').$type<DependencyRanges>(),\n },\n (table) => [\n primaryKey({ columns: [table.packageName, table.version] }),\n index('package_versions_name_published_idx').on(table.packageName, table.publishedAt),\n ],\n);\n\n/** One row per replication feed: the cursor the npm `_changes` follower resumes\n * from, so a restart doesn't replay the whole registry history. */\nexport const watchState = pgTable('watch_state', {\n id: text('id').primaryKey(),\n seq: text('seq').notNull(),\n updatedAt: ts('updated_at'),\n});\n\n/**\n * Sandbox verification results: did this package version actually install and\n * load? Evidence beyond static signals. The query path reads the latest run.\n */\nexport const verificationRuns = pgTable(\n 'verification_runs',\n {\n id: serial('id').primaryKey(),\n packageName: text('package_name').notNull(),\n version: text('version').notNull(),\n driver: text('driver').notNull(),\n moduleSystem: text('module_system').notNull(),\n installed: boolean('installed').notNull(),\n imported: boolean('imported'),\n ranScripts: boolean('ran_scripts').notNull().default(false),\n durationMs: integer('duration_ms'),\n error: text('error'),\n ranAt: ts('ran_at'),\n },\n (table) => [index('verification_runs_pkg_idx').on(table.packageName, table.version)],\n);\n\n/**\n * Compatibility edges from co-installing two package versions in the sandbox.\n * A successful co-install is positive proof they coexist; a 2-package failure is\n * proof they conflict. Pairs are stored canonically (packageA name < packageB).\n */\nexport const compatEdges = pgTable(\n 'compat_edges',\n {\n id: serial('id').primaryKey(),\n packageA: text('package_a').notNull(),\n versionA: text('version_a').notNull(),\n packageB: text('package_b').notNull(),\n versionB: text('version_b').notNull(),\n status: text('status').$type<CompatStatus>().notNull(),\n /** Evidence class (§4B). Existing rows are sandbox co-installs, so the column\n * defaults to `verified` to preserve their meaning. */\n provenance: text('provenance').$type<CompatProvenance>().notNull().default('verified'),\n /** Distinct resolved graphs an `observed` edge was witnessed in (confidence).\n * Ignored for verified/conflict. Accumulates on conflict, never overwritten. */\n witnessCount: integer('witness_count').notNull().default(0),\n driver: text('driver').notNull(),\n ranAt: ts('ran_at'),\n },\n (table) => [\n uniqueIndex('compat_edges_pair_idx').on(\n table.packageA,\n table.versionA,\n table.packageB,\n table.versionB,\n ),\n ],\n);\n\n/**\n * Persisted immutable resolved dependency closures (§4B). A `package@version`\n * always resolves to the same tree, so we store it once at first ingest; the\n * daily re-mine pass reads these with NO network to mint `observed` edges for\n * nodes that became tracked after the closure was captured.\n */\nexport const resolvedClosures = pgTable(\n 'resolved_closures',\n {\n id: serial('id').primaryKey(),\n packageName: text('package_name').notNull(),\n version: text('version').notNull(),\n /** Full closure: [{ name, version }, …] — every node in node_modules. */\n nodes: jsonb('nodes').$type<{ name: string; version: string }[]>().notNull(),\n fetchedAt: ts('fetched_at').notNull().defaultNow(),\n },\n (table) => [uniqueIndex('resolved_closures_pkg_idx').on(table.packageName, table.version)],\n);\n\n/**\n * Extracted public API surface per `package@version` (§4D — usage axis D1).\n * Ground truth = the package's shipped `.d.ts`, parsed deterministically (no\n * LLM). Versions are immutable, so a surface is extracted once and cached\n * forever; `usage` serves it and diffs across versions for API drift.\n */\nexport const apiSurfaces = pgTable(\n 'api_surfaces',\n {\n id: serial('id').primaryKey(),\n packageName: text('package_name').notNull(),\n version: text('version').notNull(),\n /** Normalized export list: [{ name, kind, signature }, …]. */\n surface: jsonb('surface').$type<ExportSymbol[]>().notNull(),\n extractedAt: ts('extracted_at').notNull().defaultNow(),\n },\n (table) => [uniqueIndex('api_surfaces_pkg_idx').on(table.packageName, table.version)],\n);\n\n/**\n * Recommendation → outcome capture (§3.1): the flywheel asset. lurq sits inside\n * the agent loop at the choice moment, so a lightweight opt-in callback yields a\n * recommendation→outcome dataset no downstream scanner can reconstruct (they see\n * deployed deps, not the decision). Privacy: no source code — only which package,\n * accepted or not, and a coarse build signal. Cheap to capture, compounds with use.\n */\nexport const recommendationOutcomes = pgTable(\n 'recommendation_outcomes',\n {\n id: serial('id').primaryKey(),\n /** The individual user this outcome belongs to (api_keys.owner_id). Null for\n * anonymous/operator-issued keys. This is what turns the flywheel from a\n * global blob into a per-user asset — \"what did *this* person succeed\n * with.\" Server-injected from the authenticated key, never caller-supplied. */\n ownerId: text('owner_id'),\n packageName: text('package_name').notNull(),\n accepted: boolean('accepted').notNull(),\n buildSignal: text('build_signal').$type<BuildSignal>(),\n /** The original need text the recommendation was for — ties outcome back to\n * the ask. Optional, length-capped at the trust boundary; never source code. */\n need: text('need'),\n createdAt: ts('created_at').notNull().defaultNow(),\n },\n (table) => [\n index('recommendation_outcomes_pkg_idx').on(table.packageName),\n index('recommendation_outcomes_owner_idx').on(table.ownerId),\n ],\n);\n\n/**\n * Durable per-account spend on dashboard Ask, one row per UTC day.\n *\n * Deliberately NOT a column on `owner_usage_daily`. That table says of itself\n * that it is display-only and its writes are fire-and-forget, so an undercount\n * on a DB hiccup is acceptable there — and a budget that undercounts on a hiccup\n * is not a budget. Writes here are awaited and their failures propagate.\n *\n * Micro-dollars as an integer, not USD as a real: this column is only ever read\n * by adding to it, and a float accumulator drifts. 1_000_000 = $1.\n */\nexport const askSpendDaily = pgTable(\n 'ask_spend_daily',\n {\n ownerId: text('owner_id').notNull(),\n /** UTC day, 'YYYY-MM-DD'. */\n date: date('date').notNull(),\n usdMicros: bigint('usd_micros', { mode: 'number' }).notNull().default(0),\n },\n (table) => [primaryKey({ columns: [table.ownerId, table.date] })],\n);\n\n/**\n * Per-user, per-day, per-tool call counts for the dashboard usage view. Keyed by\n * ownerId (not per-key — a user can hold multiple keys; the dashboard is\n * per-individual). Display-only, not a billing ledger: writes are fire-and-forget\n * UPSERTs, so an undercount on a DB hiccup is acceptable. Skipped entirely when a\n * request has no ownerId (operator-issued keys with no dashboard account).\n */\nexport const ownerUsageDaily = pgTable(\n 'owner_usage_daily',\n {\n ownerId: text('owner_id').notNull(),\n /** UTC day, 'YYYY-MM-DD'. */\n date: date('date').notNull(),\n /** recommend | evaluate | compare | compat | verify | usage | diagram | plan | report_outcome */\n tool: text('tool').notNull(),\n count: integer('count').notNull().default(0),\n },\n (table) => [\n primaryKey({ columns: [table.ownerId, table.date, table.tool] }),\n index('owner_usage_daily_owner_date_idx').on(table.ownerId, table.date),\n ],\n);\n\n/**\n * A GitHub repository connected through the lurq App (repo autopilot).\n *\n * What is NOT here is the point: no source, no tokens, no clone. `manifests`\n * holds only declared dependency ranges, and access is re-minted per scan from\n * the App's own installation credentials, so revoking the install revokes\n * everything instantly and there is no long-lived secret to leak.\n */\nexport const repos = pgTable(\n 'repos',\n {\n id: serial('id').primaryKey(),\n /** Clerk user id — same identity as api_keys.owner_id. */\n ownerId: text('owner_id').notNull(),\n /** GitHub App installation this repo is reachable through. */\n installationId: bigint('installation_id', { mode: 'number' }).notNull(),\n /** `owner/name`. */\n fullName: text('full_name').notNull(),\n defaultBranch: text('default_branch'),\n isPrivate: boolean('is_private').notNull().default(false),\n policy: jsonb('policy').$type<RepoPolicy>().notNull(),\n manifests: jsonb('manifests').$type<RepoManifest[]>(),\n /** Install command detected from the lockfile at scan time, so the generated\n * workflow uses the repo's actual package manager instead of assuming npm. */\n installCommand: text('install_command'),\n drift: jsonb('drift').$type<RepoDrift>(),\n lastScanAt: ts('last_scan_at'),\n /** Last scan failure, surfaced in the dashboard. Null once a scan succeeds —\n * a stale error next to fresh drift numbers reads as a current outage. */\n lastScanError: text('last_scan_error'),\n createdAt: ts('created_at').notNull().defaultNow(),\n },\n (table) => [\n uniqueIndex('repos_owner_full_name_idx').on(table.ownerId, table.fullName),\n index('repos_installation_idx').on(table.installationId),\n ],\n);\n\n/**\n * One row per upgrade the CI loop considered — the observability spine of the\n * autopilot, and what the dashboard's impact figures are computed from.\n *\n * Written by the user's own workflow through an API key, so everything here is\n * caller-supplied and validated at the boundary. Deliberately narrow: symbol\n * names and counts, never file contents. `callSites` is a count and always\n * safe to send; `callSiteFiles` carries paths and is only populated when the\n * repo's policy opts in, because a file path is information about someone's\n * codebase even though it is not source.\n */\nexport const upgradeRuns = pgTable(\n 'upgrade_runs',\n {\n id: serial('id').primaryKey(),\n /** Resolved server-side from the authenticated API key. Never caller-supplied. */\n ownerId: text('owner_id').notNull(),\n /** Links to `repos` when the repo is also connected. Null when the workflow\n * runs somewhere lurq has no GitHub App installation — the CLI works\n * standalone, and losing those runs would bias every impact figure. */\n repoId: integer('repo_id'),\n /** `owner/name` from GITHUB_REPOSITORY. */\n repoFullName: text('repo_full_name').notNull(),\n packageName: text('package_name').notNull(),\n fromVersion: text('from_version').notNull(),\n toVersion: text('to_version').notNull(),\n severity: text('severity').$type<UpgradeSeverity>().notNull(),\n status: text('status').$type<UpgradeRunStatus>().notNull(),\n /** Referenced symbols the upgrade removes or re-shapes. */\n symbolsAffected: jsonb('symbols_affected').$type<string[]>().notNull().default([]),\n /** How many references those symbols have in the repo. */\n callSites: integer('call_sites').notNull().default(0),\n /** Distinct files containing them. Opt-in per repo policy. */\n callSiteFiles: jsonb('call_site_files').$type<string[]>(),\n filesChanged: integer('files_changed'),\n /** Null when the repo has no test script — distinct from `false`, which\n * means the suite ran and failed. */\n testsPassed: boolean('tests_passed'),\n prUrl: text('pr_url'),\n /**\n * The GitHub Actions run, so a dashboard row links back to real logs.\n * NOT NULL with an empty-string default rather than nullable: it is part of\n * the dedup key below, and Postgres treats NULLs as distinct — a nullable\n * column there would silently let every re-post insert a duplicate. Empty\n * means \"posted outside Actions\" (a local CLI run), which then dedups to one\n * row per package+target and updates in place.\n */\n runUrl: text('run_url').notNull().default(''),\n createdAt: ts('created_at').notNull().defaultNow(),\n },\n (table) => [\n index('upgrade_runs_owner_created_idx').on(table.ownerId, table.createdAt),\n index('upgrade_runs_repo_idx').on(table.repoId),\n // One row per package per Actions run: a re-post of the same run must update\n // rather than duplicate, or a retried job would double every impact figure.\n uniqueIndex('upgrade_runs_dedup_idx').on(\n table.ownerId,\n table.repoFullName,\n table.packageName,\n table.toVersion,\n table.runUrl,\n ),\n ],\n);\n\n/**\n * A breaking release that landed on a package a connected repo depends on.\n *\n * This is the reactive half of the autopilot. The nightly scan answers \"how far\n * behind is this repo\"; a row here answers \"something broke *just now*\", written\n * within seconds of the publish by the `_changes` follower rather than up to a\n * day later. The whole point is latency: a major that ships on Tuesday is no use\n * to anyone if the repo hears about it on Monday.\n *\n * Deliberately derived from the manifests already stored on `repos` — emitting an\n * alert costs one indexed query and zero GitHub calls, so a heavily-depended\n * package publishing cannot fan out into thousands of API requests.\n */\nexport const repoAlerts = pgTable(\n 'repo_alerts',\n {\n id: serial('id').primaryKey(),\n /** Clerk user id, copied from the repo — alerts are read owner-scoped. */\n ownerId: text('owner_id').notNull(),\n repoId: integer('repo_id').notNull(),\n /** Denormalized so the feed renders without a join, as in `upgrade_runs`. */\n repoFullName: text('repo_full_name').notNull(),\n packageName: text('package_name').notNull(),\n /** The range this repo declared when the release landed. */\n range: text('range').notNull(),\n /** What that range resolved to at the last scan. Null when the index had no\n * version timeline for the package yet — never guessed. */\n fromVersion: text('from_version'),\n /** The release that triggered this. */\n toVersion: text('to_version').notNull(),\n /**\n * True when the declared range already admits `toVersion` — i.e. the next\n * clean install silently takes the new major. That is the urgent case and the\n * one no drift number expresses: the repo is not \"behind\", it is about to\n * move on its own.\n */\n inRange: boolean('in_range').notNull(),\n createdAt: ts('created_at').notNull().defaultNow(),\n },\n (table) => [\n index('repo_alerts_owner_created_idx').on(table.ownerId, table.createdAt),\n // One alert per repo per release. A re-sync of the same version — and the\n // watcher re-syncs on every publish, including non-latest backports — must\n // not re-notify.\n uniqueIndex('repo_alerts_dedup_idx').on(table.repoId, table.packageName, table.toVersion),\n ],\n);\n\nexport type SyncStatus = 'running' | 'success' | 'partial' | 'failed';\n\nexport interface SyncError {\n package: string;\n source: string;\n message: string;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// v2 graph (docs/lurq-v2-spec.md §5). Generic entity/claim/observation model,\n// running ALONGSIDE the npm-specific tables above — not replacing them yet.\n//\n// This duplication is a deliberate, dated decision, not drift. The spec's M1\n// says migrate npm onto this model; its own kill condition is \"existing\n// functionality regresses\", and the npm path is the only thing with users.\n// Rewriting it to prove a schema no second consumer has exercised is the\n// highest-risk, lowest-information move available.\n//\n// TRIGGER TO MIGRATE: a second node type (per the plan, `mcp_server`) is\n// storing verdicts here in production. That is what turns \"the shape looks\n// right\" into \"the shape held for something that is not npm\". Until then the\n// cost of carrying both is a few hundred rows of overlap and this comment.\n//\n// See docs/lurq-v2-integration-plan.md §4.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Demand-driven surface-extraction queue (§6.1).\n *\n * A query for a package-version not in the graph IS a discovery event, and the\n * spec ranks it the highest-priority queue input because it is revealed demand\n * rather than a guess about what matters. Enqueueing is instant and off the\n * query path: extraction never runs synchronously inside a request (§8), so a\n * miss returns UNKNOWN and the worker fills it in.\n *\n * Same shape as compat_verify_queue, deliberately — that loop already works.\n */\nexport const surfaceQueue = pgTable(\n 'surface_queue',\n {\n id: serial('id').primaryKey(),\n packageName: text('package_name').notNull(),\n /** Null means \"whatever latest resolves to at extraction time\". */\n version: text('version'),\n /**\n * Which extractor services this row.\n *\n * One queue, two drains: `package_surface` rows are fetched as tarballs and\n * read statically, `mcp_server` rows are installed and probed over stdio.\n * The discriminator is not optional bookkeeping — without it the npm drain\n * picks up MCP rows and tries to extract exports from a server it should\n * have handshaked with, and the failure is silent because \"no exports\n * found\" is a legitimate answer for a package that has none.\n */\n kind: text('kind').$type<EntityKind>().notNull().default('package_surface'),\n /** Dedup key: `kind:name@version`. */\n specKey: text('spec_key').notNull().unique(),\n /** Failed drains bump this; the worker drops a spec that keeps failing. */\n attempts: integer('attempts').notNull().default(0),\n requestedAt: ts('requested_at').notNull().defaultNow(),\n },\n (table) => [index('surface_queue_requested_idx').on(table.kind, table.requestedAt)],\n);\n\n/** A node in the graph. Anything an agent depends on that an oracle can check. */\nexport const entities = pgTable(\n 'entities',\n {\n id: serial('id').primaryKey(),\n kind: text('kind').$type<EntityKind>().notNull(),\n /** Registry or authority: npm, api.stripe.com, … */\n namespace: text('namespace').notNull(),\n name: text('name').notNull(),\n /** Null for unversioned kinds. */\n version: text('version'),\n /** `kind:namespace:name:version` */\n canonicalKey: text('canonical_key').notNull(),\n /**\n * 0 = the public graph; a real id = a private deployment's tenant. The spec\n * models public as NULL, but Postgres UNIQUE treats NULLs as distinct, so\n * (key, NULL) would insert unlimited duplicates and the dedup silently fails.\n * A non-null sentinel is the cheap fix that works on every PG version.\n */\n tenantId: bigint('tenant_id', { mode: 'number' }).notNull().default(0),\n /** Tarball digest. THE extraction cache key: unchanged digest, no re-extraction.\n * This is what keeps cost sublinear as the index grows (§5, §6.5). */\n artifactHash: text('artifact_hash'),\n /** Dependent count. Drives sampling AND refresh priority — and note priority\n * is NOT popularity: the study found drift concentrates at LOW in-degree\n * (18.7% vs 8.3%), which is exactly where models have the weakest priors. */\n inDegree: integer('in_degree'),\n firstSeen: ts('first_seen').notNull().defaultNow(),\n },\n (table) => [\n uniqueIndex('entities_canonical_idx').on(table.canonicalKey, table.tenantId),\n index('entities_kind_idx').on(table.kind, table.namespace, table.name),\n index('entities_artifact_idx').on(table.artifactHash),\n ],\n);\n\n/**\n * One row per exported symbol of a package version (§5).\n *\n * `origin` and `tier` are not decoration — each exists because of a defect that\n * silently corrupted the drift study:\n * - `origin` (§6.4.1): a symbol re-exported from another package is not this\n * package's surface. Counting them made one package appear to delete 168\n * exports when the true figure was 0.\n * - `tier` (§6.4.3): surfaces extracted at different tiers are NOT comparable,\n * so the tier has to travel with every symbol or diffs go wrong quietly.\n */\nexport const symbols = pgTable(\n 'symbols',\n {\n id: serial('id').primaryKey(),\n entityId: integer('entity_id')\n .notNull()\n .references(() => entities.id),\n /** 'default', 'foo', 'foo.bar' */\n path: text('path').notNull(),\n /** function | class | object | primitive | type_only */\n kind: text('kind').$type<SymbolKind>().notNull(),\n /** `fn.length` equivalent; null when not statically determinable. */\n arity: integer('arity'),\n /** 'local' | 'external:<pkg>' */\n origin: text('origin').notNull().default('local'),\n deprecated: boolean('deprecated').notNull().default(false),\n tier: text('tier').$type<ExtractionTier>().notNull(),\n /** Full declaration text; tier C only (§6.2). */\n signature: text('signature'),\n sourceFile: text('source_file'),\n sourceLine: integer('source_line'),\n },\n // Keyed by TIER as well as path: a package version has one surface per tier and\n // they are not interchangeable (§6.4.3). Without the tier in the key, storing a\n // tier-C surface would silently overwrite the tier-A one that answers runtime\n // existence — replacing the authoritative answer with a type-level guess.\n (table) => [\n uniqueIndex('symbols_entity_path_tier_idx').on(table.entityId, table.path, table.tier),\n ],\n);\n\n/** The runtime a verdict holds in. Never a node — always a dimension (§2). */\nexport const environments = pgTable('environments', {\n id: serial('id').primaryKey(),\n os: text('os').notNull(),\n arch: text('arch').notNull(),\n runtime: text('runtime').notNull(),\n runtimeVer: text('runtime_ver').notNull(),\n resolver: text('resolver'),\n /** Hash of the above; the dedup key. */\n fingerprint: text('fingerprint').notNull().unique(),\n});\n\n/** A (subject, relation, object, environment) tuple awaiting observations. */\nexport const claims = pgTable(\n 'claims',\n {\n id: serial('id').primaryKey(),\n subjectId: integer('subject_id')\n .notNull()\n .references(() => entities.id),\n /** Null for unary claims (\"does this install at all\"). */\n objectId: integer('object_id').references(() => entities.id),\n relation: text('relation').notNull(),\n /** NULL for DECLARED claims: a shipped-JS surface reads the same on every\n * machine, so there is no environment to fingerprint. Executed claims\n * (co-install, conflict, behaviour) always carry one (§5). */\n environmentId: integer('environment_id').references(() => environments.id),\n tenantId: bigint('tenant_id', { mode: 'number' }).notNull().default(0),\n },\n (table) => [\n uniqueIndex('claims_tuple_idx').on(\n table.subjectId,\n table.objectId,\n table.relation,\n table.environmentId,\n table.tenantId,\n ),\n ],\n);\n\n/**\n * APPEND-ONLY. Verdicts are never mutated — the history is the product, and\n * `breaks_at` (the highest-value edge in the graph) is derived by scanning\n * observations across versions. `stale` is applied at READ time from the\n * oracle's TTL, never written by a background job.\n */\nexport const observations = pgTable(\n 'observations',\n {\n id: serial('id').primaryKey(),\n claimId: integer('claim_id')\n .notNull()\n .references(() => claims.id),\n verdict: text('verdict').$type<Verdict>().notNull(),\n /** What KIND of evidence backs the verdict (§4.1) — orthogonal to the verdict\n * itself. A declared surface fact must never read as behavioural proof. */\n class: text('class').$type<EvidenceClass>().notNull().default('executed'),\n /** Which extraction tier produced it; null for executed claims. */\n tier: text('tier').$type<ExtractionTier>(),\n /** Evidence that makes the verdict auditable. Null only for `unknown`. */\n evidence: text('evidence'),\n oracleId: text('oracle_id').notNull(),\n oracleVer: text('oracle_ver').notNull(),\n costMillis: integer('cost_millis'),\n observedAt: ts('observed_at').notNull().defaultNow(),\n },\n (table) => [index('observations_claim_idx').on(table.claimId, table.observedAt)],\n);\n\nexport type PackageRow = typeof packages.$inferSelect;\nexport type NewPackageRow = typeof packages.$inferInsert;\nexport type EntityRow = typeof entities.$inferSelect;\nexport type NewEntityRow = typeof entities.$inferInsert;\nexport type EnvironmentRow = typeof environments.$inferSelect;\nexport type ClaimRow = typeof claims.$inferSelect;\nexport type ObservationRow = typeof observations.$inferSelect;\nexport type SymbolRow = typeof symbols.$inferSelect;\nexport type SurfaceQueueRow = typeof surfaceQueue.$inferSelect;\nexport type NewSymbolRow = typeof symbols.$inferInsert;\nexport type NewObservationRow = typeof observations.$inferInsert;\nexport type SeedPackageRow = typeof seedPackages.$inferSelect;\n/**\n * Per-owner selection policy — the rules governing what an agent may *add*.\n *\n * One row per owner, keyed by the Clerk id already used by `api_keys.owner_id`\n * and `repos.owner_id`. Clerk namespaces ids by prefix, so when organisations\n * are switched on this column holds an `org_…` id with no migration and no\n * membership tables. See policy/types for why that is the right amount of\n * structure to build today.\n */\nexport const selectionPolicies = pgTable('selection_policies', {\n ownerId: text('owner_id').primaryKey(),\n policy: jsonb('policy').$type<SelectionPolicy>().notNull(),\n updatedAt: ts('updated_at').notNull().defaultNow(),\n});\n\n/**\n * Every replacement of a selection policy: who did it, from where, both sides.\n *\n * Append-only. A policy decides what a whole team's agents may install, and\n * \"who allowed this, and when\" is the first question after anything slips\n * through. Both sides are stored whole rather than as a diff, so the record\n * survives the rule sentences changing wording.\n */\nexport const selectionPolicyChanges = pgTable(\n 'selection_policy_changes',\n {\n id: serial('id').primaryKey(),\n ownerId: text('owner_id').notNull(),\n /** `dashboard`, or the display prefix of the API key that pushed it. */\n actor: text('actor').notNull(),\n before: jsonb('before').$type<SelectionPolicy>().notNull(),\n after: jsonb('after').$type<SelectionPolicy>().notNull(),\n createdAt: ts('created_at').notNull().defaultNow(),\n },\n (table) => [index('selection_policy_changes_owner_idx').on(table.ownerId, table.createdAt)],\n);\n\n/**\n * Each time a rule refused a package an agent reached for, or would have in\n * warn mode.\n *\n * Only refusals are written, never passes: the volume is bounded by how often\n * a policy bites, and a log of everything allowed is a usage log we already\n * keep. This is what makes warn mode worth switching on (what would this rule\n * have caught?) and what shows an account the policy is doing work.\n * ponytail: no retention job; add a created_at prune when a busy account's row\n * count matters.\n */\nexport const policyDecisions = pgTable(\n 'policy_decisions',\n {\n id: serial('id').primaryKey(),\n ownerId: text('owner_id').notNull(),\n packageName: text('package_name').notNull(),\n rule: text('rule').$type<ExclusionRule>().notNull(),\n /** `blocked` under enforce, `warned` under warn. */\n action: text('action').$type<'blocked' | 'warned'>().notNull(),\n /** The tool the agent called: recommend | evaluate. */\n tool: text('tool').notNull(),\n createdAt: ts('created_at').notNull().defaultNow(),\n },\n (table) => [index('policy_decisions_owner_idx').on(table.ownerId, table.createdAt)],\n);\n\nexport type SyncRunRow = typeof syncRuns.$inferSelect;\nexport type DiscoveryQueueRow = typeof discoveryQueue.$inferSelect;\nexport type CompatVerifyQueueRow = typeof compatVerifyQueue.$inferSelect;\nexport type ApiKeyRow = typeof apiKeys.$inferSelect;\nexport type NewApiKeyRow = typeof apiKeys.$inferInsert;\nexport type PackageVersionRow = typeof packageVersions.$inferSelect;\nexport type NewPackageVersionRow = typeof packageVersions.$inferInsert;\nexport type VerificationRunRow = typeof verificationRuns.$inferSelect;\nexport type NewVerificationRunRow = typeof verificationRuns.$inferInsert;\nexport type CompatEdgeRow = typeof compatEdges.$inferSelect;\nexport type NewCompatEdgeRow = typeof compatEdges.$inferInsert;\nexport type ResolvedClosureRow = typeof resolvedClosures.$inferSelect;\nexport type NewResolvedClosureRow = typeof resolvedClosures.$inferInsert;\nexport type ApiSurfaceRow = typeof apiSurfaces.$inferSelect;\nexport type NewApiSurfaceRow = typeof apiSurfaces.$inferInsert;\nexport type RecommendationOutcomeRow = typeof recommendationOutcomes.$inferSelect;\nexport type NewRecommendationOutcomeRow = typeof recommendationOutcomes.$inferInsert;\nexport type OwnerUsageDailyRow = typeof ownerUsageDaily.$inferSelect;\nexport type NewOwnerUsageDailyRow = typeof ownerUsageDaily.$inferInsert;\nexport type RepoRow = typeof repos.$inferSelect;\nexport type NewRepoRow = typeof repos.$inferInsert;\nexport type UpgradeRunRow = typeof upgradeRuns.$inferSelect;\nexport type NewUpgradeRunRow = typeof upgradeRuns.$inferInsert;\nexport type RepoAlertRow = typeof repoAlerts.$inferSelect;\nexport type NewRepoAlertRow = typeof repoAlerts.$inferInsert;\n/**\n * Billing state for one account, mirrored from Stripe.\n *\n * Stripe is the authority; this is a local read-replica of the two facts the\n * request path needs — which tier, and is it still being served — so a tool\n * call resolves entitlement from Postgres instead of a network hop to Stripe on\n * every request. Written only by the webhook.\n *\n * Keyed by `ownerId` (the Clerk user id), NOT by API key. Entitlement belongs to\n * the account: a user with four keys bought one subscription, and putting the\n * tier on `api_keys` would let them mint themselves a free upgrade by issuing a\n * new key. `api_keys.tier` predates this and is display-only.\n *\n * `tier` is derived from the Stripe Price at webhook time rather than stored on\n * the customer, so re-pricing a plan does not require a backfill.\n */\nexport const subscriptions = pgTable(\n 'subscriptions',\n {\n /** Clerk user id. One subscription per account. */\n ownerId: text('owner_id').primaryKey(),\n /** Stable across subscriptions: a customer who cancels and returns reuses it. */\n stripeCustomerId: text('stripe_customer_id').notNull().unique(),\n /** Null between creating a customer and completing a first checkout. */\n stripeSubscriptionId: text('stripe_subscription_id').unique(),\n tier: text('tier').$type<Tier>().notNull().default('free'),\n /** Raw Stripe subscription status. `null` = never subscribed. */\n status: text('status'),\n /** When the paid period lapses. Display only; `status` is what gates access. */\n currentPeriodEnd: ts('current_period_end'),\n /** Set when the user cancels but has paid through the period. */\n cancelAtPeriodEnd: boolean('cancel_at_period_end').notNull().default(false),\n /**\n * Stripe delivers out of order and retries, so a late duplicate of an older\n * event must not overwrite newer state. The webhook drops any event whose\n * timestamp is older than the one that produced the current row.\n */\n lastEventAt: ts('last_event_at'),\n createdAt: ts('created_at').notNull().defaultNow(),\n updatedAt: ts('updated_at').notNull().defaultNow(),\n },\n (table) => [index('subscriptions_customer_idx').on(table.stripeCustomerId)],\n);\n\nexport type SubscriptionRow = typeof subscriptions.$inferSelect;\nexport type NewSubscriptionRow = typeof subscriptions.$inferInsert;\n\nexport type SelectionPolicyRow = typeof selectionPolicies.$inferSelect;\nexport type NewSelectionPolicyRow = typeof selectionPolicies.$inferInsert;\n\n/**\n * A resolved stack — one row per distinct package set, keyed by exact versions.\n *\n * This replaces pairwise `compat_edges` as the compatibility mechanism, for two\n * reasons that are both about correctness before cost:\n *\n * 1. **npm resolves sets, not pairs.** Three packages can be compatible in\n * every pair and still fail together — a diamond dependency or a peer range\n * that only becomes unsatisfiable with all three present. A pairwise model\n * cannot express the conflicts npm actually reports, so it was answering a\n * different question than the one asked.\n * 2. **Pairs are quadratic, sets are not.** One row per asked stack instead of\n * C(n,2) per stack. Storage tracks *demand* — how many distinct stacks\n * humans assemble — instead of tracking the square of the catalog.\n *\n * `names` duplicates the names already in `packages` because invalidation asks\n * \"which stacks contain X?\" on every npm publish, and that has to be one indexed\n * lookup rather than a scan over jsonb.\n *\n * Only definitive results are ever written. A resolve that times out or fails on\n * the network is inconclusive and must not be cached — a stored non-answer would\n * poison that stack until something evicted it.\n */\nexport const stackResolutions = pgTable(\n 'stack_resolutions',\n {\n id: serial('id').primaryKey(),\n /** Canonical `name@version|name@version|…`, sorted. The cache key. */\n setKey: text('set_key').notNull().unique(),\n /** The exact members this verdict is about. */\n packages: jsonb('packages').$type<{ name: string; version: string }[]>().notNull(),\n /** Names only, for publish-driven invalidation. */\n names: text('names').array().notNull(),\n /** True when npm produced a lockfile for the set. */\n resolved: boolean('resolved').notNull(),\n /** 'ERESOLVE' for a proven conflict; null when it resolved. */\n reason: text('reason'),\n /** npm's own error text on a conflict — it names the packages and ranges. */\n detail: text('detail'),\n resolvedAt: ts('resolved_at').notNull().defaultNow(),\n },\n (table) => [\n index('stack_resolutions_names_idx').using('gin', table.names),\n index('stack_resolutions_resolved_at_idx').on(table.resolvedAt),\n ],\n);\n\nexport type StackResolutionRow = typeof stackResolutions.$inferSelect;\nexport type NewStackResolutionRow = typeof stackResolutions.$inferInsert;\n","/**\n * Database client factory. Uses postgres.js + Drizzle. Callers own the lifecycle:\n * create, use, then `await close()` (CLI commands are short-lived processes).\n */\nimport { drizzle, type PostgresJsDatabase } from 'drizzle-orm/postgres-js';\nimport postgres from 'postgres';\nimport { requireConfig } from '../core/config';\nimport * as schema from './schema';\n\nexport type Database = PostgresJsDatabase<typeof schema>;\n\nexport interface DbHandle {\n db: Database;\n /** Underlying postgres.js client, for raw SQL (e.g. CREATE EXTENSION). */\n sql: postgres.Sql;\n /** Close the connection pool. Always call when done. */\n close: () => Promise<void>;\n}\n\n/**\n * Server-side ceiling on a single query, in milliseconds.\n *\n * Without one, a query that never returns holds its connection forever. The\n * hosted server runs a pool of 20 against arbitrary user input, so a handful of\n * those is the whole pool gone and every later request queueing behind them —\n * an outage that looks like a hang rather than an error, and that a restart is\n * the only cure for. Postgres cancels past this and the driver raises, which\n * the route's own try/catch already turns into a 500.\n *\n * Generous on purpose: the slowest legitimate query here is the hybrid\n * vector+lexical search, and this is a backstop against pathology, not a\n * performance budget.\n */\nconst STATEMENT_TIMEOUT_MS = 15_000;\n\nexport function createDb(opts: { max?: number } = {}): DbHandle {\n const { DATABASE_URL } = requireConfig(['DATABASE_URL']);\n const sql = postgres(DATABASE_URL!, {\n max: opts.max ?? 10,\n // ponytail: Neon bills compute by the hour and only suspends when nothing is\n // connected. postgres.js holds idle connections forever by default, so a\n // long-lived process (serve-http, watch) pinned the compute awake 24/7 even\n // with zero traffic. Drop them after a minute; reconnect through the pooler\n // is cheap. Raise if reconnect latency ever shows up in p99.\n idle_timeout: 60,\n onnotice: () => {},\n connection: { statement_timeout: STATEMENT_TIMEOUT_MS },\n });\n const db = drizzle(sql, { schema });\n return { db, sql, close: () => sql.end() };\n}\n\nexport { schema };\n","/**\n * Read/write helpers for the `packages` table. All recommendation/eval reads use\n * this single denormalized table (§8.2).\n */\nimport { and, desc, eq, gte, inArray, isNotNull, isNull, lt, notExists, sql } from 'drizzle-orm';\nimport { logger } from '../core/logger';\nimport { DEFAULT_ECOSYSTEM, type Category, type Ecosystem } from '../core/types';\nimport type { VersionInfo } from '../ingestion/types';\nimport type { Database } from './client';\nimport {\n packageVersions,\n packages,\n seedPackages,\n syncRuns,\n type NewPackageRow,\n type SyncError,\n} from './schema';\n\n/** How many rows to insert per statement (stays well under Postgres' param cap). */\nconst VERSION_CHUNK = 500;\n\n/** How many names to bind per `IN` list, for the same reason. */\nconst NAME_CHUNK = 500;\n\nexport async function getSeedTargets(\n db: Database,\n): Promise<{ name: string; category: Category | null }[]> {\n const rows = await db\n .select({ name: seedPackages.name, category: seedPackages.category })\n .from(seedPackages);\n return rows.map((r) => ({ name: r.name, category: r.category ?? null }));\n}\n\n/**\n * The daily sync's rotation slice: the stalest tracked packages that aren't in\n * `seed_packages`. Discovery ingests thousands of packages `getSeedTargets`\n * never returns, so without this their scores — and their `latest_version` —\n * stay frozen at the moment they were ingested.\n *\n * A frozen `latest_version` also closes the discovery frontier: `graphChannel`\n * (§2B) only re-expands a package whose version moved, so a package that is\n * never refreshed can never re-arm, and the crawler flatlines once the initial\n * BFS converges. This rotation is what keeps it open.\n *\n * Only a `curated` category is carried through. An `inferred` one is left null\n * so the pipeline re-infers it — passing it back in would make the refresh\n * silently relabel it `curated`, and a later curation pass would then skip it.\n */\nexport async function getStaleRefreshTargets(\n db: Database,\n limit: number,\n): Promise<{ name: string; category: Category | null }[]> {\n if (limit <= 0) return [];\n const rows = await db\n .select({\n name: packages.name,\n category: sql<Category | null>`case when ${packages.categorySource} = 'curated' then ${packages.category} end`,\n })\n .from(packages)\n .where(\n notExists(\n db\n .select({ one: sql`1` })\n .from(seedPackages)\n .where(eq(seedPackages.name, packages.name)),\n ),\n )\n // Never-synced rows (null `data_as_of`) are the stalest of all, and ASC puts\n // nulls last in Postgres — so say it explicitly.\n .orderBy(sql`${packages.dataAsOf} asc nulls first`)\n .limit(limit);\n return rows.map((r) => ({ name: r.name, category: r.category ?? null }));\n}\n\nexport async function getPackageByName(\n db: Database,\n name: string,\n ecosystem: Ecosystem = DEFAULT_ECOSYSTEM,\n) {\n const rows = await db\n .select()\n .from(packages)\n .where(and(eq(packages.name, name), eq(packages.ecosystem, ecosystem)))\n .limit(1);\n return rows[0] ?? null;\n}\n\n/**\n * The stored `latest_version` for a set of names, in one query.\n *\n * Read *before* a sync pass overwrites them, so the pass can tell whether a\n * package moved onto a new major and alert the repos that depend on it. An\n * absent key means the package is not in the index yet — distinct from a present\n * key holding null, which means indexed with no known latest; neither is a\n * release event, so both are treated the same downstream.\n */\nexport async function latestVersionsFor(\n db: Database,\n names: string[],\n ecosystem: Ecosystem = DEFAULT_ECOSYSTEM,\n): Promise<Map<string, string | null>> {\n const out = new Map<string, string | null>();\n for (let i = 0; i < names.length; i += NAME_CHUNK) {\n const rows = await db\n .select({ name: packages.name, latestVersion: packages.latestVersion })\n .from(packages)\n .where(\n and(\n inArray(packages.name, names.slice(i, i + NAME_CHUNK)),\n eq(packages.ecosystem, ecosystem),\n ),\n );\n for (const row of rows) out.set(row.name, row.latestVersion);\n }\n return out;\n}\n\n/** Every tracked package name in one registry — the set a changes follower\n * filters against. Scoped because each registry has its own feed. */\nexport async function getAllPackageNames(\n db: Database,\n ecosystem: Ecosystem = DEFAULT_ECOSYSTEM,\n): Promise<string[]> {\n const rows = await db\n .select({ name: packages.name })\n .from(packages)\n .where(eq(packages.ecosystem, ecosystem));\n return rows.map((r) => r.name);\n}\n\n/** Names that became tracked at or after `since` — the only packages the daily\n * re-mine pass can produce new edges for (§4B trigger 2). */\nexport async function getPackageNamesCreatedSince(db: Database, since: Date): Promise<string[]> {\n const rows = await db\n .select({ name: packages.name })\n .from(packages)\n .where(gte(packages.createdAt, since));\n return rows.map((r) => r.name);\n}\n\n/**\n * Store a package's version timeline. Idempotent — versions are immutable on\n * npm, so existing rows are left untouched. Chunked to respect the param cap.\n */\nexport async function upsertPackageVersions(\n db: Database,\n name: string,\n versions: VersionInfo[],\n): Promise<void> {\n // An empty timeline means the registry fetch came back without one, not that\n // the package has no versions. Returning silently made that indistinguishable\n // from a successful write, so a package could sit with no history forever and\n // nothing in the logs would say why.\n if (versions.length === 0) {\n logger.debug(`no version timeline to store for ${name}: registry returned none`);\n return;\n }\n for (let i = 0; i < versions.length; i += VERSION_CHUNK) {\n const rows = versions.slice(i, i + VERSION_CHUNK).map((v) => ({\n packageName: name,\n version: v.version,\n publishedAt: v.publishedAt,\n peerDependencies: v.peerDependencies ?? null,\n engines: v.engines ?? null,\n }));\n await db.insert(packageVersions).values(rows).onConflictDoNothing();\n }\n}\n\n/** A package's stored version timeline, newest first. */\nexport async function getPackageVersions(\n db: Database,\n name: string,\n limit = 50,\n): Promise<VersionInfo[]> {\n const rows = await db\n .select({ version: packageVersions.version, publishedAt: packageVersions.publishedAt })\n .from(packageVersions)\n .where(eq(packageVersions.packageName, name))\n .orderBy(desc(packageVersions.publishedAt))\n .limit(limit);\n return rows.map((r) => ({ version: r.version, publishedAt: r.publishedAt }));\n}\n\n/**\n * The most-downloaded tracked packages — the reference set typosquat detection\n * compares a queried name against. Capped (default 1000) so the per-verify\n * distance scan stays cheap.\n */\nexport async function getTopPackageNames(db: Database, limit = 1000): Promise<string[]> {\n const rows = await db\n .select({ name: packages.name })\n .from(packages)\n .where(isNotNull(packages.weeklyDownloads))\n .orderBy(desc(packages.weeklyDownloads))\n .limit(limit);\n return rows.map((r) => r.name);\n}\n\n/**\n * Promote a package into the curated seed list so future `sync` runs keep it\n * fresh. Used by the on-demand path (§12.5) to make organically-discovered\n * packages durable. No-op if already seeded — preserves the original category\n * and `added_at` rather than overwriting a hand-curated entry.\n */\nexport async function ensureSeedEntry(\n db: Database,\n name: string,\n category: Category | null,\n): Promise<void> {\n await db\n .insert(seedPackages)\n .values({ name, category })\n .onConflictDoNothing({ target: seedPackages.name });\n}\n\n/**\n * Upsert a fully-computed package row, refreshing every field on conflict.\n *\n * The conflict target must name the SAME columns as the unique index or\n * Postgres rejects the statement outright (\"no unique or exclusion constraint\n * matching the ON CONFLICT specification\") — so this pair moves together with\n * `packages_ecosystem_name_idx` and cannot be changed independently of it.\n * `ecosystem` is excluded from the update set for the same reason `name` is: it\n * is half the identity of the row, not a mutable field.\n */\nexport async function upsertPackage(db: Database, row: NewPackageRow): Promise<void> {\n const { name: _name, ecosystem: _ecosystem, createdAt: _createdAt, ...mutable } = row;\n await db\n .insert(packages)\n .values(row)\n .onConflictDoUpdate({\n target: [packages.ecosystem, packages.name],\n set: { ...mutable, updatedAt: new Date() },\n });\n}\n\n/**\n * Credit the individual account whose on-demand query first caused `name` to be\n * ingested. A standalone, idempotent UPDATE guarded by `IS NULL` — kept OUT of\n * upsertPackage (which refreshes every field on conflict) so re-syncs and the\n * `_changes` watcher, which never pass an owner, can never clobber the credit.\n * The `IS NULL` guard is also the cross-process race tie-breaker: whichever\n * concurrent first-ingest commits first wins; the rest match zero rows.\n */\nexport async function stampFirstRequester(\n db: Database,\n name: string,\n ownerId: string,\n ecosystem: Ecosystem = DEFAULT_ECOSYSTEM,\n): Promise<void> {\n await db\n .update(packages)\n .set({ firstRequestedByOwnerId: ownerId })\n .where(\n and(\n eq(packages.name, name),\n eq(packages.ecosystem, ecosystem),\n isNull(packages.firstRequestedByOwnerId),\n ),\n );\n}\n\nexport interface Contribution {\n name: string;\n category: Category | null;\n healthScore: number | null;\n /** = packages.createdAt (immutable since first insert). */\n firstRequestedAt: Date;\n}\n\n/**\n * Packages this account first caused to be ingested (dashboard v1 phase 2),\n * newest first, plus the total for pagination. `firstRequestedAt` is the row's\n * immutable `createdAt`, so no separate timestamp column is needed.\n */\nexport async function getContributionsByOwner(\n db: Database,\n ownerId: string,\n opts: { limit?: number; offset?: number } = {},\n): Promise<{ total: number; packages: Contribution[] }> {\n const limit = opts.limit ?? 50;\n const offset = opts.offset ?? 0;\n const [rows, [countRow]] = await Promise.all([\n db\n .select({\n name: packages.name,\n category: packages.category,\n healthScore: packages.healthScore,\n firstRequestedAt: packages.createdAt,\n })\n .from(packages)\n .where(eq(packages.firstRequestedByOwnerId, ownerId))\n .orderBy(desc(packages.createdAt))\n .limit(limit)\n .offset(offset),\n db\n .select({ count: sql<number>`count(*)::int` })\n .from(packages)\n .where(eq(packages.firstRequestedByOwnerId, ownerId)),\n ]);\n return { total: countRow?.count ?? 0, packages: rows };\n}\n\n// ── sync_runs audit ─────────────────────────────────────────────────────────\n\n/** `<environment>/<service>` from the host's injected vars, or null when it\n * injects neither. Railway sets both on every deployment; nothing to configure. */\nfunction syncOrigin(): string | null {\n const env = process.env.RAILWAY_ENVIRONMENT_NAME;\n const service = process.env.RAILWAY_SERVICE_NAME;\n if (!env && !service) return null;\n return `${env ?? '?'}/${service ?? '?'}`;\n}\n\n/** How long a run may sit in `running` before a later run declares it dead.\n * Full syncs finish in about twenty minutes, so this is an order of magnitude\n * of headroom — the point is to reap abandoned rows, never to race a live one.\n * It must also stay clear of a concurrent sibling: two schedulers firing the\n * same cron start seconds apart, nowhere near this. */\nconst SYNC_STALE_MS = 6 * 60 * 60 * 1000;\n\n/**\n * Mark runs abandoned by a process that never came back.\n *\n * `runSync` writes a terminal status on both the success and the throw path, so\n * a row left at `running` means the process died where no handler could run:\n * OOM, SIGKILL, a container timeout. Nothing else can ever close those rows, and\n * without this they accumulate forever and quietly corrupt any \"when did the\n * index last sync cleanly\" read — a stuck `running` row is indistinguishable\n * from a sync in progress.\n */\nasync function reapAbandonedSyncRuns(db: Database): Promise<void> {\n await db\n .update(syncRuns)\n .set({\n status: 'failed',\n finishedAt: new Date(),\n errors: [\n {\n package: '*',\n source: 'pipeline',\n message: 'abandoned: the process died before writing a terminal status',\n },\n ],\n })\n .where(\n and(\n eq(syncRuns.status, 'running'),\n lt(syncRuns.startedAt, new Date(Date.now() - SYNC_STALE_MS)),\n ),\n );\n}\n\nexport async function startSyncRun(db: Database): Promise<number> {\n // Cheap, and this is the only moment we know a sweep is safe: any run still\n // `running` from six hours ago cannot be the one we are about to start.\n await reapAbandonedSyncRuns(db);\n const [row] = await db\n .insert(syncRuns)\n .values({ status: 'running', origin: syncOrigin() })\n .returning({ id: syncRuns.id });\n return row!.id;\n}\n\nexport async function finishSyncRun(\n db: Database,\n id: number,\n data: {\n packagesSeen: number;\n packagesUpdated: number;\n errors: SyncError[];\n status: 'success' | 'partial' | 'failed';\n },\n): Promise<void> {\n await db\n .update(syncRuns)\n .set({\n finishedAt: new Date(),\n packagesSeen: data.packagesSeen,\n packagesUpdated: data.packagesUpdated,\n errors: data.errors,\n status: data.status,\n })\n .where(eq(syncRuns.id, id));\n}\n","/**\n * Optional Redis response cache for the read-heavy tools (recommend / evaluate /\n * compare). The index only changes when `sync`/`rescore` run, so identical\n * queries can be served from Redis instead of re-running the hybrid search.\n *\n * Zero-config by design: with no `REDIS_URL` (the default, and every end-user's\n * machine), `cached()` is a transparent pass-through and `invalidateCache()` a\n * no-op — nothing to provision, nothing breaks. Point `REDIS_URL` at an Upstash\n * (or any) Redis on the hosted server to turn it on. Any Redis error degrades to\n * computing directly; the cache never takes the request path down.\n *\n * Invalidation is version-based on two axes: every key embeds the running\n * release AND a data version read from `lurq:cachever`. A successful sync\n * `INCR`s the latter, so all prior keys become unreachable at once (and age out\n * via TTL) — no SCAN/DEL sweep. The release covers the other half: a deploy that\n * changes how results are ranked invalidates rankings computed by the old code.\n */\nimport { VERSION } from './constants';\nimport { logger } from './logger';\n\ninterface RedisLike {\n get(key: string): Promise<string | null>;\n set(key: string, value: string, mode: 'EX', ttlSeconds: number): Promise<unknown>;\n incr(key: string): Promise<number>;\n}\n\nconst VERSION_KEY = 'lurq:cachever';\nconst DEFAULT_TTL_SEC = 3600;\n/** In-process memo for the namespace version, to avoid a round-trip per call.\n * Bounded so a sync's INCR is picked up within seconds. */\nconst VERSION_MEMO_MS = 10_000;\n\nlet clientPromise: Promise<RedisLike | null> | null = null;\nlet versionMemo: { value: string; at: number } | null = null;\n\nfunction ttlSeconds(): number {\n const n = Number(process.env.LURQ_CACHE_TTL_SEC);\n return Number.isFinite(n) && n > 0 ? n : DEFAULT_TTL_SEC;\n}\n\n/** Lazily connect to Redis once. Returns null (cache disabled) when REDIS_URL is\n * unset or the client can't be created. */\nasync function getClient(): Promise<RedisLike | null> {\n if (!process.env.REDIS_URL) return null;\n if (!clientPromise) {\n clientPromise = (async () => {\n try {\n const { default: Redis } = await import('ioredis');\n const client = new Redis(process.env.REDIS_URL!, {\n maxRetriesPerRequest: 1,\n enableOfflineQueue: false,\n lazyConnect: false,\n // Railway's private network (redis.railway.internal) is IPv6-only and\n // ioredis defaults to IPv4 — family:0 lets it resolve either stack, so\n // both the private URL and a public/Upstash URL work unchanged.\n family: 0,\n });\n client.on('error', (err: Error) => logger.warn(`redis: ${err.message}`));\n logger.info('Response cache enabled (REDIS_URL set).');\n return client as unknown as RedisLike;\n } catch (err) {\n logger.warn(`redis disabled (init failed): ${(err as Error).message}`);\n return null;\n }\n })();\n }\n return clientPromise;\n}\n\nasync function namespaceVersion(client: RedisLike): Promise<string> {\n if (versionMemo && Date.now() - versionMemo.at < VERSION_MEMO_MS) return versionMemo.value;\n const value = (await client.get(VERSION_KEY).catch(() => null)) ?? '0';\n versionMemo = { value, at: Date.now() };\n return value;\n}\n\n/**\n * The cached value depends on the CODE that produced it, not only on the data\n * it read, and the key used to ignore that half.\n *\n * `lurq:cachever` is bumped by sync, rescore and edit-weights — every path that\n * changes the *data*. A deploy that changes how results are *ranked* bumps\n * nothing, so cached responses computed by the previous ranking kept being\n * served for the rest of their hour. That happened for real: after shipping the\n * confidence-aware ranking, a previously-seen query still returned the old\n * order while a freshly-worded one returned the new — which reads exactly like\n * a deploy that silently did not take.\n *\n * Folding the release into the key makes a version bump self-invalidating.\n * A ranking change shipped WITHOUT a version bump still needs a manual\n * `INCR lurq:cachever`, and that is the honest limit of a one-line fix.\n */\nfunction codeVersion(): string {\n return VERSION;\n}\n\n/**\n * Get-or-compute with optional caching. When the cache is off or unreachable,\n * `compute()` runs directly. `skipCache(value)` lets the caller avoid caching\n * unhelpful results (e.g. empty recommendations or not-found lookups).\n */\nexport async function cached<T>(\n namespace: string,\n key: string,\n compute: () => Promise<T>,\n opts: { skipCache?: (value: T) => boolean } = {},\n): Promise<T> {\n const client = await getClient();\n if (!client) return compute();\n\n let fullKey: string;\n try {\n const version = await namespaceVersion(client);\n // namespace : release : data-version : query\n fullKey = `lurq:${namespace}:${codeVersion()}:${version}:${key}`;\n const hit = await client.get(fullKey);\n if (hit != null) return JSON.parse(hit) as T;\n } catch (err) {\n logger.warn(`redis read failed, bypassing cache: ${(err as Error).message}`);\n return compute();\n }\n\n const value = await compute();\n if (!opts.skipCache?.(value)) {\n // Fire-and-forget write; a cache-write failure must never affect the response.\n client.set(fullKey, JSON.stringify(value), 'EX', ttlSeconds()).catch(() => {});\n }\n return value;\n}\n\n/** Invalidate every cached read by bumping the namespace version. Call after a\n * successful sync/rescore. No-op when the cache is off. */\nexport async function invalidateCache(): Promise<void> {\n const client = await getClient();\n if (!client) return;\n try {\n await client.incr(VERSION_KEY);\n versionMemo = null; // force the next read to pick up the new version\n } catch (err) {\n logger.warn(`redis invalidate failed: ${(err as Error).message}`);\n }\n}\n","/** Read/write helpers for the compatibility matrix (`compat_edges`). */\nimport { and, eq, inArray, sql, type SQLWrapper } from 'drizzle-orm';\nimport {\n DEFAULT_ECOSYSTEM,\n type DependencyRanges,\n type Ecosystem,\n type PeerMeta,\n} from '../core/types';\nimport type { Database } from './client';\nimport {\n compatEdges,\n compatVerifyQueue,\n packages,\n type CompatEdgeRow,\n type CompatVerifyQueueRow,\n type NewCompatEdgeRow,\n} from './schema';\n\nexport interface CompatMetadataRow {\n name: string;\n latestVersion: string | null;\n peerDependencies: DependencyRanges | null;\n peerDependenciesMeta: PeerMeta | null;\n engines: DependencyRanges | null;\n}\n\n/** Tier-1 compatibility metadata for a set of packages — one indexed query. */\nexport async function getCompatMetadata(\n db: Database,\n names: string[],\n ecosystem: Ecosystem = DEFAULT_ECOSYSTEM,\n): Promise<CompatMetadataRow[]> {\n if (names.length === 0) return [];\n return db\n .select({\n name: packages.name,\n latestVersion: packages.latestVersion,\n peerDependencies: packages.peerDependencies,\n peerDependenciesMeta: packages.peerDependenciesMeta,\n engines: packages.engines,\n })\n .from(packages)\n .where(and(inArray(packages.name, names), eq(packages.ecosystem, ecosystem)));\n}\n\n/** Order a pair canonically by package name so (A,B) and (B,A) dedupe to one row. */\nexport function canonicalPair(\n a: { name: string; version: string },\n b: { name: string; version: string },\n): { packageA: string; versionA: string; packageB: string; versionB: string } {\n const [low, high] = a.name <= b.name ? [a, b] : [b, a];\n return { packageA: low.name, versionA: low.version, packageB: high.name, versionB: high.version };\n}\n\n/** Provenance rank as SQL, mirroring PROVENANCE_RANK (§4B). Higher wins. */\nfunction provenanceRank(col: SQLWrapper) {\n return sql`case ${col} when 'conflict' then 3 when 'verified' then 2 when 'observed' then 1 else 0 end`;\n}\n\n/** The provenance-precedence conflict SET, shared by single + batch upsert (§4B).\n * witness_count accumulates; status/provenance/driver/ranAt update only when the\n * incoming edge is at least as strong, so a mined `observed` never erases a\n * sandbox `verified`/`conflict`. Encodes conflict > verified > observed > declared. */\nfunction conflictSet() {\n const incomingWins = sql`${provenanceRank(sql`excluded.provenance`)} >= ${provenanceRank(compatEdges.provenance)}`;\n return {\n status: sql`case when ${incomingWins} then excluded.status else ${compatEdges.status} end`,\n provenance: sql`case when ${incomingWins} then excluded.provenance else ${compatEdges.provenance} end`,\n driver: sql`case when ${incomingWins} then excluded.driver else ${compatEdges.driver} end`,\n ranAt: sql`case when ${incomingWins} then excluded.ran_at else ${compatEdges.ranAt} end`,\n witnessCount: sql`${compatEdges.witnessCount} + excluded.witness_count`,\n };\n}\n\nconst CONFLICT_TARGET = [\n compatEdges.packageA,\n compatEdges.versionA,\n compatEdges.packageB,\n compatEdges.versionB,\n] as const;\n\nexport async function upsertCompatEdge(db: Database, edge: NewCompatEdgeRow): Promise<void> {\n await db\n .insert(compatEdges)\n .values(edge)\n .onConflictDoUpdate({ target: [...CONFLICT_TARGET], set: conflictSet() });\n}\n\n/**\n * Sandbox-established edges only — `verified` and `conflict`.\n *\n * These are the rows that are *not* derivable from anything else: a real\n * co-install that passed or failed under VM isolation. `observed` edges are\n * deliberately excluded, because the set-level resolve now answers the question\n * they were mined to answer, and answers it about the exact versions asked for\n * rather than whatever versions a third party's dependency tree happened to pin.\n *\n * Scoped by name, not by version: a sandbox conflict at neighbouring versions is\n * still the best information anyone has about the pair, and `checkCompat` labels\n * the version mismatch rather than hiding the row.\n */\nexport async function getSandboxEdges(db: Database, names: string[]): Promise<CompatEdgeRow[]> {\n if (names.length === 0) return [];\n return db\n .select()\n .from(compatEdges)\n .where(\n and(\n inArray(compatEdges.packageA, names),\n inArray(compatEdges.packageB, names),\n inArray(compatEdges.provenance, ['verified', 'conflict']),\n ),\n );\n}\n\n// ── Pure pair helpers (§4C) ──────────────────────────────────────────────────\n\n/** Canonical `a|b` key for a name pair, order-independent. */\nexport function pairKey(a: string, b: string): string {\n return a <= b ? `${a}|${b}` : `${b}|${a}`;\n}\n\n/** Canonical order-independent key for a whole package set (queue dedup). */\nexport function compatSetKey(names: string[]): string {\n return [...new Set(names)].sort().join('|');\n}\n\n// ── Demand-driven compat-verify queue (§4C) ──────────────────────────────────\n\n/** Queue a package set for background sandbox co-install. Deduped on the set key,\n * so repeated queries for the same unverified set enqueue exactly one run.\n * Returns true if a new row was inserted. */\nexport async function enqueueCompatVerify(db: Database, names: string[]): Promise<boolean> {\n const packages = [...new Set(names)].filter(Boolean);\n if (packages.length < 2) return false;\n const inserted = await db\n .insert(compatVerifyQueue)\n .values({ setKey: compatSetKey(packages), packages })\n .onConflictDoNothing({ target: compatVerifyQueue.setKey })\n .returning({ id: compatVerifyQueue.id });\n return inserted.length > 0;\n}\n\n/** Oldest-first pending verify requests (FIFO fairness). */\nexport async function getPendingCompatVerify(\n db: Database,\n limit: number,\n): Promise<CompatVerifyQueueRow[]> {\n return db\n .select()\n .from(compatVerifyQueue)\n .orderBy(compatVerifyQueue.requestedAt)\n .limit(limit);\n}\n\nexport async function deleteCompatVerify(db: Database, id: number): Promise<void> {\n await db.delete(compatVerifyQueue).where(eq(compatVerifyQueue.id, id));\n}\n\n/** Bump attempt count; returns the new count so the caller can drop a stuck set. */\nexport async function bumpCompatVerifyAttempt(db: Database, id: number): Promise<number> {\n const [row] = await db\n .update(compatVerifyQueue)\n .set({ attempts: sql`${compatVerifyQueue.attempts} + 1` })\n .where(eq(compatVerifyQueue.id, id))\n .returning({ attempts: compatVerifyQueue.attempts });\n return row?.attempts ?? 0;\n}\n","/**\n * The stack-resolution cache (§4C, revised).\n *\n * A compat answer is a fact about an exact set of `name@version`, so the cache\n * key is the whole set — not its pairs. There is no partial-credit read: a\n * partial answer about a stack is what `likely` used to be, and it is what this\n * replaces.\n *\n * Because the key pins versions, entries never go *wrong*, only unused. That is\n * why the only eviction here is an age sweep, and why a publish needs no hook —\n * see the notes on `invalidateStacksFor` and `pruneStackResolutions`.\n */\nimport { eq, sql } from 'drizzle-orm';\nimport type { Database } from './client';\nimport { stackResolutions } from './schema';\nimport type { StackResolutionRow } from './schema';\n\n/** A member under check: the exact version the verdict is about. */\nexport interface StackMember {\n name: string;\n version: string;\n}\n\n/**\n * Canonical cache key for a set of pinned members, order-independent.\n *\n * Versions are part of the key, not metadata beside it. An answer about\n * react@18 + next@14 is not an answer about react@19 + next@16 — that is the\n * same discipline `edgeMatchesVersions` enforced on the old pairwise reads, kept\n * here where it costs one sort instead of a post-filter over fetched rows.\n */\nexport function stackKey(members: StackMember[]): string {\n return [...members]\n .map((m) => `${m.name}@${m.version}`)\n .sort()\n .join('|');\n}\n\n/** The cached verdict for this exact set, or null if we have never resolved it. */\nexport async function getStackResolution(\n db: Database,\n key: string,\n): Promise<StackResolutionRow | null> {\n const [row] = await db\n .select()\n .from(stackResolutions)\n .where(eq(stackResolutions.setKey, key))\n .limit(1);\n return row ?? null;\n}\n\n/**\n * Persist a *definitive* verdict — resolved, or a proven ERESOLVE conflict.\n *\n * Never call this for a timeout or a network failure. Those are inconclusive,\n * and a cached inconclusive is worse than no cache at all: it turns a transient\n * blip into a permanent wrong answer for that stack, with nothing to evict it.\n *\n * Upserts rather than inserts because two concurrent asks for the same cold\n * stack will both resolve before either writes; the second is the same verdict\n * about the same immutable versions, so last-write-wins is correct and cheap.\n */\nexport async function recordStackResolution(\n db: Database,\n entry: {\n members: StackMember[];\n resolved: boolean;\n reason?: 'ERESOLVE' | null;\n detail?: string | null;\n },\n): Promise<void> {\n const key = stackKey(entry.members);\n await db\n .insert(stackResolutions)\n .values({\n setKey: key,\n packages: entry.members,\n names: entry.members.map((m) => m.name),\n resolved: entry.resolved,\n reason: entry.reason ?? null,\n detail: entry.detail ?? null,\n resolvedAt: new Date(),\n })\n .onConflictDoUpdate({\n target: stackResolutions.setKey,\n set: {\n resolved: sql`excluded.resolved`,\n reason: sql`excluded.reason`,\n detail: sql`excluded.detail`,\n resolvedAt: sql`excluded.resolved_at`,\n },\n });\n}\n\n/**\n * Drop every cached stack containing this package. One indexed GIN lookup on\n * `names`; returns how many rows went.\n *\n * NOT wired to publishes, and that is deliberate. Because the key pins exact\n * versions, a new release does not make any stored row *wrong* — the answer\n * about react@19.2.7 stays true about react@19.2.7 forever. The next ask simply\n * pins to 19.2.8, produces a different key, misses, and resolves. Stacks\n * auto-upgrade for free, and eager invalidation would only buy the same answer\n * sooner while doubling resolve volume on patch releases.\n *\n * What this is for is the case where a stored row is genuinely *false*: a version\n * unpublished within npm's 72-hour window, or a package pulled for a security\n * advisory. Then the cached verdict describes a version that no longer exists.\n */\nexport async function invalidateStacksFor(db: Database, packageName: string): Promise<number> {\n const gone = await db\n .delete(stackResolutions)\n .where(sql`${stackResolutions.names} @> ARRAY[${packageName}]::text[]`)\n .returning({ id: stackResolutions.id });\n return gone.length;\n}\n\n/**\n * Drop resolutions older than `maxAgeDays`. This is what actually bounds the\n * table, and it is garbage collection rather than invalidation: rows go stale by\n * ceasing to be asked for, not by becoming untrue.\n *\n * Evicting a stack that is still hot costs one resolve on the next ask, roughly\n * once per retention window — which is why a blunt age sweep beats tracking\n * last-read timestamps on every lookup just to be cleverer about it.\n */\nexport async function pruneStackResolutions(db: Database, maxAgeDays = 90): Promise<number> {\n const gone = await db\n .delete(stackResolutions)\n .where(sql`${stackResolutions.resolvedAt} < now() - make_interval(days => ${maxAgeDays})`)\n .returning({ id: stackResolutions.id });\n return gone.length;\n}\n","/**\n * Resolve-only compat check (§4C). Ask npm to *resolve* a package set without\n * installing it: `npm install --package-lock-only` builds the lockfile (or fails\n * with ERESOLVE) from registry metadata alone — no tarballs, no build, no VM.\n * This catches the version-conflict class (diamond deps, unsatisfiable peer\n * ranges) that Tier-0 declared analysis can't see, at a fraction of the\n * sandbox's cost. The sandbox is reserved for runtime proof only.\n *\n * **Why this is safe to run on our own container rather than in the sandbox.**\n * `--package-lock-only` never runs a lifecycle script — no preinstall, no\n * postinstall — because it never unpacks anything. It reads registry metadata\n * and does semver arithmetic. The one caller-controlled input that still reaches\n * the outside world is the *version specifier*: a non-semver value like\n * `git+ssh://host/repo` makes npm fetch that host's manifest. Callers must\n * therefore validate versions as semver at the trust boundary before they get\n * here (see the `compat` tool's input schema).\n */\nimport { execFile } from 'node:child_process';\nimport { mkdtemp, rm, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { promisify } from 'node:util';\nimport { getConfig } from '../core/config';\n\nconst execFileP = promisify(execFile);\n\nexport interface ResolveResult {\n /** True if npm produced a lockfile (the set co-resolves). */\n resolved: boolean;\n /** 'ERESOLVE' when a proven version conflict; null on success. */\n reason: 'ERESOLVE' | null;\n /** npm's own message on a conflict — it names the packages and ranges that\n * clash, which is strictly better than anything we could paraphrase. */\n detail?: string;\n}\n\n// ── Concurrency gate ─────────────────────────────────────────────────────────\n// npm holds its arborist tree in memory (200-500MB for a real stack), so\n// unbounded parallelism is an OOM, not a speedup. A slot is either held by a\n// runner or handed straight to the next waiter — never released into a gap where\n// a new caller could claim it as well and push us over the limit.\n\nlet active = 0;\nconst waiting: (() => void)[] = [];\n\nasync function acquire(limit: number): Promise<() => void> {\n if (active < limit) active++;\n else await new Promise<void>((resolve) => waiting.push(resolve));\n\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const next = waiting.shift();\n if (next) next();\n else active--;\n };\n}\n\n/** Pending + running resolves. Exported for the self-check. */\nexport function inFlight(): { active: number; queued: number } {\n return { active, queued: waiting.length };\n}\n\n/**\n * Resolve a package set without installing it. Returns resolved:false only for a\n * *proven* conflict (ERESOLVE); transient failures (network, timeout) throw so\n * the caller treats them as inconclusive and never records a false conflict.\n */\nexport async function resolveSet(\n specs: { name: string; version: string | null }[],\n opts: { timeoutMs?: number; concurrency?: number; cacheDir?: string } = {},\n): Promise<ResolveResult> {\n const config = getConfig();\n const release = await acquire(opts.concurrency ?? config.LURQ_RESOLVE_CONCURRENCY);\n const dir = await mkdtemp(join(tmpdir(), 'lurq-resolve-'));\n try {\n const dependencies: Record<string, string> = {};\n for (const s of specs) dependencies[s.name] = s.version ?? 'latest';\n await writeFile(\n join(dir, 'package.json'),\n // A version is required or npm reports `lurq-resolve@undefined` in its\n // error output, which then reads as if our scaffold were part of the\n // user's stack.\n JSON.stringify({ name: 'lurq-resolve', version: '0.0.0', private: true, dependencies }),\n );\n const args = ['install', '--package-lock-only', '--no-audit', '--no-fund'];\n // A persistent cache is the single highest-leverage setting here: warm, a\n // 15-package stack resolves in 8.6s; cold, 19.2s.\n const cacheDir = opts.cacheDir ?? config.LURQ_NPM_CACHE_DIR;\n if (cacheDir) args.push('--cache', cacheDir);\n // Default (non-legacy) peer resolution is exactly what we want: npm ERESOLVEs\n // on a genuine peer/version conflict instead of silently papering over it.\n await execFileP('npm', args, {\n cwd: dir,\n timeout: opts.timeoutMs ?? config.LURQ_RESOLVE_TIMEOUT_MS,\n });\n return { resolved: true, reason: null };\n } catch (err) {\n const msg = (err as { stderr?: string }).stderr ?? (err as Error).message ?? '';\n if (/ERESOLVE/i.test(msg)) {\n return { resolved: false, reason: 'ERESOLVE', detail: summarizeEresolve(msg) };\n }\n throw err; // network / timeout / other, inconclusive, not a proven conflict\n } finally {\n release();\n await rm(dir, { recursive: true, force: true }).catch(() => {});\n }\n}\n\n/**\n * Pull the useful part out of npm's ERESOLVE output.\n *\n * npm prints a wall of resolution trace plus advice about --force and\n * --legacy-peer-deps, none of which an agent should act on. The lines that\n * matter say what was found and what was required. Capped because this is\n * stored and returned over the wire.\n */\nexport function summarizeEresolve(stderr: string, maxChars = 600): string {\n const keep = stderr\n .split('\\n')\n .map((l) => l.replace(/^npm (error|ERR!)\\s*/, '').trim())\n .filter(\n (l) =>\n l.length > 0 &&\n // Our own scaffold is not part of anyone's stack; naming it in a verdict\n // just invites a reader to go looking for a package that does not exist.\n !l.startsWith('While resolving: lurq-resolve') &&\n /^(While resolving|Found|Could not resolve|Conflicting peer dependency|peer |dependency )/i.test(\n l,\n ),\n );\n const text = (keep.length > 0 ? keep : ['npm could not resolve this set']).join('; ');\n return text.length > maxChars ? `${text.slice(0, maxChars - 1)}…` : text;\n}\n","/**\n * Shared HTTP layer (§17). One wrapper for every external call:\n * - per-host rate limiting (max concurrency + minimum gap between starts),\n * - exponential backoff on 429 / 5xx (respecting Retry-After),\n * - in-run (memory) cache + persistent on-disk cache with per-source TTLs.\n *\n * Source clients pass a `ttlMs` (the per-source TTL from §17) and a `host`\n * bucket. `ttlMs: 0` disables caching (used for liveness checks like `verify`).\n */\nimport { createHash } from 'node:crypto';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { logger } from './logger';\n\nexport class HttpError extends Error {\n constructor(\n message: string,\n readonly status: number,\n readonly url: string,\n ) {\n super(message);\n this.name = 'HttpError';\n }\n}\n\nexport interface HttpOptions {\n /** Rate-limit bucket key, usually the hostname. */\n host: string;\n /** Persistent cache TTL in ms. 0 disables read+write caching. */\n ttlMs: number;\n method?: 'GET' | 'POST';\n headers?: Record<string, string>;\n body?: string;\n accept?: 'json' | 'text';\n timeoutMs?: number;\n retries?: number;\n /** Override the cache key (e.g. to keep auth tokens out of the key). */\n cacheKey?: string;\n /** Injected for tests. Defaults to global fetch. */\n fetchImpl?: typeof fetch;\n}\n\nexport interface HttpResponse<T> {\n status: number;\n data: T;\n fromCache: boolean;\n}\n\n// ── Per-host rate limiting ──────────────────────────────────────────────────\n\ninterface HostConfig {\n maxConcurrent: number;\n minIntervalMs: number;\n}\n\nconst DEFAULT_HOST_CONFIG: HostConfig = { maxConcurrent: 6, minIntervalMs: 0 };\n\nconst HOST_CONFIG: Record<string, HostConfig> = {\n 'api.github.com': { maxConcurrent: 4, minIntervalMs: 50 },\n 'registry.npmjs.org': { maxConcurrent: 4, minIntervalMs: 50 },\n // The downloads API rate-limits aggressively — serialize with a steady gap.\n // Weekly downloads go through the bulk endpoint; only growth hits this often.\n 'api.npmjs.org': { maxConcurrent: 1, minIntervalMs: 250 },\n 'api.deps.dev': { maxConcurrent: 4, minIntervalMs: 40 },\n 'raw.githubusercontent.com': { maxConcurrent: 4, minIntervalMs: 30 },\n // Bundlephobia is slow/flaky — be gentle (§9.5).\n 'bundlephobia.com': { maxConcurrent: 2, minIntervalMs: 200 },\n};\n\nclass HostLimiter {\n private active = 0;\n private nextAvailable = 0;\n private queue: Array<() => void> = [];\n\n constructor(private readonly config: HostConfig) {}\n\n async acquire(): Promise<void> {\n if (this.active >= this.config.maxConcurrent) {\n await new Promise<void>((resolve) => this.queue.push(resolve));\n }\n this.active++;\n const now = Date.now();\n const wait = Math.max(0, this.nextAvailable - now);\n this.nextAvailable = Math.max(now, this.nextAvailable) + this.config.minIntervalMs;\n if (wait > 0) await delay(wait);\n }\n\n release(): void {\n this.active--;\n const next = this.queue.shift();\n if (next) next();\n }\n}\n\nconst limiters = new Map<string, HostLimiter>();\n\nfunction limiterFor(host: string): HostLimiter {\n let limiter = limiters.get(host);\n if (!limiter) {\n limiter = new HostLimiter(HOST_CONFIG[host] ?? DEFAULT_HOST_CONFIG);\n limiters.set(host, limiter);\n }\n return limiter;\n}\n\n// ── Caching ─────────────────────────────────────────────────────────────────\n\ninterface CacheEntry {\n fetchedAt: number;\n status: number;\n body: string;\n}\n\n/**\n * In-run memo in front of the disk cache. Bounded: the hosted server fetches\n * packuments for arbitrary packages over a process lifetime measured in weeks,\n * and packument bodies run to megabytes — unbounded, this is the box's OOM.\n * Map preserves insertion order, so deleting the first key evicts the oldest\n * (re-inserting on hit makes it LRU rather than FIFO).\n * ponytail: count-bounded, not byte-bounded. Swap in a byte budget only if\n * profiling shows entry size, not entry count, is what runs the heap up.\n */\nconst MEMORY_CACHE_MAX = 500;\nconst memoryCache = new Map<string, CacheEntry>();\n\nfunction memoryCacheSet(key: string, entry: CacheEntry): void {\n memoryCache.delete(key);\n memoryCache.set(key, entry);\n if (memoryCache.size > MEMORY_CACHE_MAX) {\n const oldest = memoryCache.keys().next();\n if (!oldest.done) memoryCache.delete(oldest.value);\n }\n}\n\n/** When true, cache reads are skipped (writes still happen). Used by `sync --full`. */\nlet bypassCacheRead = false;\n\n/** Force fresh fetches (ignore cache TTLs) while still refreshing the cache. */\nexport function setCacheBypassRead(value: boolean): void {\n bypassCacheRead = value;\n}\n\nfunction cacheDir(): string {\n return process.env.LURQ_CACHE_DIR ?? join(homedir(), '.cache', 'lurq', 'http');\n}\n\nfunction cacheFile(key: string): string {\n const hash = createHash('sha256').update(key).digest('hex');\n return join(cacheDir(), `${hash}.json`);\n}\n\nasync function readCache(key: string, ttlMs: number): Promise<CacheEntry | undefined> {\n const now = Date.now();\n const mem = memoryCache.get(key);\n if (mem && now - mem.fetchedAt < ttlMs) {\n memoryCacheSet(key, mem); // touch: most-recently-used moves to the back\n return mem;\n }\n\n const file = cacheFile(key);\n if (!existsSync(file)) return undefined;\n try {\n const entry = JSON.parse(await readFile(file, 'utf8')) as CacheEntry;\n if (now - entry.fetchedAt < ttlMs) {\n memoryCacheSet(key, entry);\n return entry;\n }\n } catch {\n /* corrupt cache file — ignore and refetch */\n }\n return undefined;\n}\n\nasync function writeCache(key: string, entry: CacheEntry): Promise<void> {\n memoryCacheSet(key, entry);\n const file = cacheFile(key);\n try {\n await mkdir(dirname(file), { recursive: true });\n await writeFile(file, JSON.stringify(entry), 'utf8');\n } catch (err) {\n logger.debug(`http cache write failed: ${(err as Error).message}`);\n }\n}\n\n// ── Core request ────────────────────────────────────────────────────────────\n\nconst RETRYABLE = new Set([429, 500, 502, 503, 504]);\n\nexport async function httpRequest<T = unknown>(\n url: string,\n opts: HttpOptions,\n): Promise<HttpResponse<T>> {\n const {\n host,\n ttlMs,\n method = 'GET',\n headers = {},\n body,\n accept = 'json',\n timeoutMs = 15_000,\n retries = 3,\n fetchImpl = fetch,\n } = opts;\n const key = opts.cacheKey ?? `${method} ${url} ${body ?? ''}`;\n\n if (ttlMs > 0 && !bypassCacheRead) {\n const cached = await readCache(key, ttlMs);\n if (cached) {\n return { status: cached.status, data: decode<T>(cached.body, accept), fromCache: true };\n }\n }\n\n const limiter = limiterFor(host);\n let lastErr: unknown;\n\n for (let attempt = 0; attempt <= retries; attempt++) {\n await limiter.acquire();\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n const res = await fetchImpl(url, { method, headers, body, signal: controller.signal });\n const text = await res.text();\n\n if (res.ok) {\n if (ttlMs > 0) await writeCache(key, { fetchedAt: Date.now(), status: res.status, body: text });\n return { status: res.status, data: decode<T>(text, accept), fromCache: false };\n }\n\n // Non-2xx\n if (RETRYABLE.has(res.status) && attempt < retries) {\n const retryAfter = parseRetryAfter(res.headers.get('retry-after'));\n await delay(retryAfter ?? backoff(attempt));\n lastErr = new HttpError(`HTTP ${res.status} for ${url}`, res.status, url);\n continue;\n }\n throw new HttpError(`HTTP ${res.status} for ${url}`, res.status, url);\n } catch (err) {\n lastErr = err;\n const isAbort = err instanceof Error && err.name === 'AbortError';\n const isHttp = err instanceof HttpError;\n // Retry network/timeout errors; don't retry non-retryable HTTP statuses.\n if (isHttp && !RETRYABLE.has(err.status)) throw err;\n if (attempt < retries) {\n await delay(backoff(attempt));\n continue;\n }\n if (isAbort) throw new HttpError(`Timeout after ${timeoutMs}ms for ${url}`, 0, url);\n } finally {\n clearTimeout(timer);\n limiter.release();\n }\n }\n throw lastErr instanceof Error ? lastErr : new HttpError(`Request failed for ${url}`, 0, url);\n}\n\nexport async function httpGetJson<T = unknown>(\n url: string,\n opts: Omit<HttpOptions, 'accept' | 'method'>,\n): Promise<HttpResponse<T>> {\n return httpRequest<T>(url, { ...opts, method: 'GET', accept: 'json' });\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────────────\n\nfunction decode<T>(text: string, accept: 'json' | 'text'): T {\n if (accept === 'text') return text as unknown as T;\n return (text ? JSON.parse(text) : null) as T;\n}\n\nfunction backoff(attempt: number): number {\n const base = 500 * 2 ** attempt;\n return base + Math.floor(((attempt * 137) % 100) * 3); // small deterministic jitter\n}\n\nfunction parseRetryAfter(value: string | null): number | undefined {\n if (!value) return undefined;\n const seconds = Number(value);\n if (!Number.isNaN(seconds)) return seconds * 1000;\n const date = Date.parse(value);\n return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/** Test helper: clear the in-memory cache and per-host limiters. */\nexport function __resetHttpStateForTests(): void {\n memoryCache.clear();\n limiters.clear();\n}\n","/**\n * npm registry client (§9.1). Base metadata: version, description, license,\n * repository, publish times, deprecation, maintainers, README.\n */\nimport { CACHE_TTL } from '../../core/constants';\nimport { httpGetJson } from '../../core/http';\nimport type { NpmRegistryData, VersionInfo } from '../types';\n\nconst HOST = 'registry.npmjs.org';\n\n/** Encode a package name for a registry URL (scoped names need `/` → `%2F`). */\nexport function encodeNpmName(name: string): string {\n return name.startsWith('@') ? name.replace('/', '%2F') : name;\n}\n\n/** Extract `{ owner, repo }` from any GitHub repository URL form. */\nexport function parseGithubRepo(\n url: string | null | undefined,\n): { owner: string; repo: string } | null {\n if (!url) return null;\n const match = url.match(/github\\.com[/:]([^/]+)\\/([^/#?]+?)(?:\\.git)?(?:[/#?].*)?$/i);\n if (!match) return null;\n const owner = match[1];\n const repo = match[2];\n if (!owner || !repo) return null;\n return { owner, repo };\n}\n\nfunction normalizeRepoUrl(\n repository: unknown,\n homepage: string | null,\n): { repoUrl: string | null; repo: { owner: string; repo: string } | null } {\n let raw: string | null = null;\n if (typeof repository === 'string') raw = repository;\n else if (repository && typeof repository === 'object' && 'url' in repository) {\n raw = String((repository as { url: unknown }).url);\n }\n const repo = parseGithubRepo(raw) ?? parseGithubRepo(homepage);\n const repoUrl = repo ? `https://github.com/${repo.owner}/${repo.repo}` : (cleanUrl(raw) ?? null);\n return { repoUrl, repo };\n}\n\nfunction cleanUrl(url: string | null): string | null {\n if (!url) return null;\n return url\n .replace(/^git\\+/, '')\n .replace(/^git:\\/\\//, 'https://')\n .replace(/\\.git$/, '');\n}\n\nfunction pickLicense(value: unknown): string | null {\n if (!value) return null;\n if (typeof value === 'string') return value;\n if (typeof value === 'object' && 'type' in value) return String((value as { type: unknown }).type);\n return null;\n}\n\nfunction toDate(value: unknown): Date | null {\n if (typeof value !== 'string') return null;\n const ms = Date.parse(value);\n return Number.isNaN(ms) ? null : new Date(ms);\n}\n\nexport function parseNpmRegistry(json: any): NpmRegistryData {\n const latest: string | null = json?.['dist-tags']?.latest ?? null;\n const latestManifest = latest ? (json?.versions?.[latest] ?? {}) : {};\n const time = json?.time ?? {};\n\n const repository = json?.repository ?? latestManifest?.repository;\n const homepage = json?.homepage ?? latestManifest?.homepage ?? null;\n const { repoUrl, repo } = normalizeRepoUrl(repository, homepage);\n\n const deprecated = Boolean(latestManifest?.deprecated ?? json?.deprecated);\n const maintainers = Array.isArray(json?.maintainers) ? json.maintainers.length : null;\n const name: string = json?.name ?? '';\n\n return {\n name,\n description: json?.description ?? latestManifest?.description ?? null,\n latestVersion: latest,\n license: pickLicense(json?.license ?? latestManifest?.license),\n homepage,\n repo,\n repoUrl,\n firstPublishedAt: toDate(time?.created),\n lastReleaseAt: toDate(latest ? time?.[latest] : null) ?? toDate(time?.modified),\n deprecated,\n maintainersCount: maintainers,\n readme: typeof json?.readme === 'string' ? json.readme : null,\n keywords: parseKeywords(json?.keywords ?? latestManifest?.keywords),\n hasTypes: detectTypes(name, latestManifest),\n hasTestScript: detectTestScript(latestManifest),\n directDependenciesCount: countDeps(latestManifest?.dependencies),\n hasProvenance: detectProvenance(latestManifest),\n hasInstallScripts: detectInstallScripts(latestManifest),\n hasBrowserField: latestManifest?.browser != null,\n peerDependencies: parseDepMap(latestManifest?.peerDependencies),\n peerDependenciesMeta: parsePeerMeta(latestManifest?.peerDependenciesMeta),\n engines: parseDepMap(latestManifest?.engines),\n versionTimeline: parseVersionTimeline(json),\n };\n}\n\n/** A manifest dependency/engines map → a clean { name: range } record, or null. */\nfunction parseDepMap(value: unknown): Record<string, string> | null {\n if (!value || typeof value !== 'object') return null;\n const out: Record<string, string> = {};\n for (const [name, range] of Object.entries(value as Record<string, unknown>)) {\n if (typeof range === 'string' && range.trim() !== '') out[name] = range;\n }\n return Object.keys(out).length ? out : null;\n}\n\n/** `peerDependenciesMeta` → { name: { optional } }, or null. */\nfunction parsePeerMeta(value: unknown): Record<string, { optional?: boolean }> | null {\n if (!value || typeof value !== 'object') return null;\n const out: Record<string, { optional?: boolean }> = {};\n for (const [name, meta] of Object.entries(value as Record<string, unknown>)) {\n if (meta && typeof meta === 'object' && 'optional' in meta) {\n out[name] = { optional: Boolean((meta as { optional?: unknown }).optional) };\n }\n }\n return Object.keys(out).length ? out : null;\n}\n\n/** Lifecycle install hooks run arbitrary code at install time. We surface their\n * presence; deeper analysis belongs in the sandbox tier. */\nfunction detectInstallScripts(manifest: any): boolean {\n const scripts = manifest?.scripts;\n if (!scripts || typeof scripts !== 'object') return false;\n return ['preinstall', 'install', 'postinstall'].some(\n (hook) => typeof scripts[hook] === 'string' && scripts[hook].trim() !== '',\n );\n}\n\n/**\n * The published-version timeline from the packument: every key in `versions`\n * paired with its publish date from `time`, newest first. The `time` map also\n * holds `created`/`modified` sentinels, which we skip.\n */\nexport function parseVersionTimeline(json: any): VersionInfo[] {\n const versions = json?.versions;\n if (!versions || typeof versions !== 'object') return [];\n const time = json?.time ?? {};\n return Object.keys(versions)\n .map((version) => ({\n version,\n publishedAt: toDate(time?.[version]),\n // Already in this document — no second fetch, no per-version round trip.\n peerDependencies: parseDepMap(versions[version]?.peerDependencies),\n engines: parseDepMap(versions[version]?.engines),\n }))\n .sort((a, b) => (b.publishedAt?.getTime() ?? 0) - (a.publishedAt?.getTime() ?? 0));\n}\n\nfunction parseKeywords(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value.filter((k): k is string => typeof k === 'string');\n}\n\n/** Ships types if the manifest declares `types`/`typings`, or it IS an @types pkg. */\nfunction detectTypes(name: string, manifest: any): boolean {\n if (typeof manifest?.types === 'string' || typeof manifest?.typings === 'string') return true;\n if (name.startsWith('@types/')) return true;\n // `exports` map with a `types` condition (modern dual-package layout).\n const exportsField = manifest?.exports;\n if (exportsField && typeof exportsField === 'object') {\n const serialized = JSON.stringify(exportsField);\n if (serialized.includes('\"types\"')) return true;\n }\n return false;\n}\n\n/** A real test script — npm's `init` leaves a placeholder we must not count. */\nfunction detectTestScript(manifest: any): boolean {\n const test = manifest?.scripts?.test;\n if (typeof test !== 'string' || test.trim() === '') return false;\n return !/no test specified/i.test(test);\n}\n\nfunction countDeps(deps: unknown): number | null {\n if (!deps || typeof deps !== 'object') return 0;\n return Object.keys(deps as Record<string, unknown>).length;\n}\n\n/** npm provenance leaves a signed attestation on the published dist. */\nfunction detectProvenance(manifest: any): boolean {\n return Boolean(manifest?.dist?.attestations);\n}\n\nexport async function fetchNpmRegistry(\n name: string,\n fetchImpl?: typeof fetch,\n): Promise<NpmRegistryData> {\n const url = `https://${HOST}/${encodeNpmName(name)}`;\n const { data } = await httpGetJson<any>(url, {\n host: HOST,\n ttlMs: CACHE_TTL.npmRegistry,\n fetchImpl,\n });\n return parseNpmRegistry(data);\n}\n\n/**\n * Compat metadata for a specific published version (peers + engines).\n *\n * `latest` is used only when no version was requested. A version that was\n * requested but isn't published returns null rather than silently answering\n * about `latest` — otherwise `compat` would grade a different stack than the\n * caller pinned, and the caller would have no way to tell.\n */\nexport async function fetchNpmCompatAtVersion(\n name: string,\n version: string | null | undefined,\n fetchImpl?: typeof fetch,\n): Promise<{\n version: string | null;\n peerDependencies: Record<string, string> | null;\n peerDependenciesMeta: Record<string, { optional?: boolean }> | null;\n engines: Record<string, string> | null;\n} | null> {\n const url = `https://${HOST}/${encodeNpmName(name)}`;\n try {\n const { data } = await httpGetJson<any>(url, {\n host: HOST,\n ttlMs: CACHE_TTL.npmRegistry,\n fetchImpl,\n });\n const latest: string | null = data?.['dist-tags']?.latest ?? null;\n const wanted = version\n ? (data?.versions?.[version] ? version : null)\n : latest && data?.versions?.[latest]\n ? latest\n : null;\n if (!wanted) return null;\n const manifest = data.versions[wanted] ?? {};\n return {\n version: wanted,\n peerDependencies: parseDepMap(manifest.peerDependencies),\n peerDependenciesMeta: parsePeerMeta(manifest.peerDependenciesMeta),\n engines: parseDepMap(manifest.engines),\n };\n } catch {\n return null;\n }\n}\n\n/**\n * Is this exact version published? Tri-state on purpose.\n *\n * `false` (\"npm has this package and that version is not among its releases\")\n * and `null` (\"we could not ask\") lead to opposite messages: the first is a\n * typo'd or hallucinated version the caller must fix, the second is our outage\n * and must never be reported as the caller's mistake. A boolean would have to\n * pick one of those to be wrong about.\n *\n * Reads the same cached packument URL as the rest of this module, so calling it\n * before `fetchNpmCompatAtVersion` costs a cache hit, not a second round-trip.\n */\nexport async function npmVersionExists(\n name: string,\n version: string,\n fetchImpl?: typeof fetch,\n): Promise<boolean | null> {\n const url = `https://${HOST}/${encodeNpmName(name)}`;\n try {\n const { data } = await httpGetJson<any>(url, {\n host: HOST,\n ttlMs: CACHE_TTL.npmRegistry,\n fetchImpl,\n });\n // A packument with no `versions` map is a shape we don't understand, not a\n // package with no releases — don't call the version missing on that basis.\n if (!data?.versions || typeof data.versions !== 'object') return null;\n return Object.prototype.hasOwnProperty.call(data.versions, version);\n } catch {\n return null;\n }\n}\n\n/** Live existence check for `verify` (§12.3.4) — bypasses cache. */\nexport async function npmPackageExists(name: string, fetchImpl?: typeof fetch): Promise<boolean> {\n const url = `https://${HOST}/${encodeNpmName(name)}`;\n try {\n const { status } = await httpGetJson<any>(url, {\n host: HOST,\n ttlMs: 0,\n retries: 1,\n fetchImpl,\n });\n return status === 200;\n } catch (err) {\n if (err && typeof err === 'object' && 'status' in err && (err as any).status === 404) {\n return false;\n }\n throw err;\n }\n}\n","/**\n * npm registry search client (§2B). Seeds the discovery crawler's long-tail\n * channels: keyword/category search and a recently-published sweep. This is the\n * niche workhorse — the dependency graph structurally can't find niche\n * *alternatives* (a new package shares no edge with the incumbent it competes\n * with), so that job lives here.\n */\nimport { CACHE_TTL } from '../../core/constants';\nimport { httpGetJson } from '../../core/http';\n\nconst HOST = 'registry.npmjs.org';\n\nexport interface NpmSearchHit {\n name: string;\n /** ISO publish date of the matched version, if reported. */\n date: string | null;\n}\n\n/**\n * Run an npm registry search. `query` uses npm's search qualifier syntax, e.g.\n * `keywords:orm` or `orm typescript`. `from` is the rank offset — the search is\n * deterministic, so a caller that always passes 0 re-reads the same head of the\n * ranking on every call. Returns name + publish date per hit. Best-effort:\n * returns [] on any failure.\n */\nexport async function searchNpm(\n query: string,\n size = 20,\n from = 0,\n fetchImpl?: typeof fetch,\n): Promise<NpmSearchHit[]> {\n const url = `https://${HOST}/-/v1/search?text=${encodeURIComponent(query)}&size=${size}&from=${from}`;\n try {\n const { data } = await httpGetJson<any>(url, {\n host: HOST,\n ttlMs: CACHE_TTL.npmRegistry,\n fetchImpl,\n });\n const objects: any[] = Array.isArray(data?.objects) ? data.objects : [];\n return objects\n .map((o) => ({ name: o?.package?.name, date: o?.package?.date ?? null }))\n .filter((h): h is NpmSearchHit => typeof h.name === 'string');\n } catch {\n return [];\n }\n}\n","/**\n * npm downloads client (§9.2). Weekly downloads + 90-day growth.\n *\n * Weekly downloads is fetched in BULK at the pipeline level — npm's point API\n * accepts up to 128 comma-separated packages per call, which avoids the harsh\n * rate-limiting that per-package bursts trigger. The range (growth) API has no\n * bulk form, so growth is a per-package best-effort secondary signal.\n *\n * Bulk does not support scoped (@scope/name) packages; those are fetched singly.\n */\nimport { CACHE_TTL } from '../../core/constants';\nimport { httpGetJson, HttpError } from '../../core/http';\n\nconst HOST = 'api.npmjs.org';\nconst BULK_CHUNK = 128;\n\nexport function parseWeeklyDownloads(json: any): number | null {\n const value = json?.downloads;\n return typeof value === 'number' ? value : null;\n}\n\ninterface RangePoint {\n day: string;\n downloads: number;\n}\n\n/** Compute the 90d growth fraction from a daily-downloads range. */\nexport function parseDownloadGrowth(json: any): number | null {\n const points: RangePoint[] = Array.isArray(json?.downloads) ? json.downloads : [];\n if (points.length < 60) return null;\n const tail = points.slice(-60);\n const prior = tail.slice(0, 30);\n const recent = tail.slice(30);\n const sum = (arr: RangePoint[]) => arr.reduce((acc, p) => acc + (p.downloads || 0), 0);\n const priorAvg = sum(prior) / prior.length;\n const recentAvg = sum(recent) / recent.length;\n if (priorAvg <= 0) return recentAvg > 0 ? 1 : 0;\n // Round to 3 decimals: this is a best-effort secondary signal, so the float's\n // precision tail is meaningless — and it ships in every recommend/evaluate\n // response, where 19 chars of noise is tokens the calling agent pays for.\n return Math.round(((recentAvg - priorAvg) / priorAvg) * 1000) / 1000;\n}\n\n/** Format a Date as YYYY-MM-DD (UTC) for the npm range API. */\nfunction ymd(date: Date): string {\n return date.toISOString().slice(0, 10);\n}\n\n/** Build a `start:end` range string covering the last 90 days. */\nexport function last90DayRange(now: Date = new Date()): string {\n const end = now;\n const start = new Date(end.getTime() - 90 * 24 * 60 * 60 * 1000);\n return `${ymd(start)}:${ymd(end)}`;\n}\n\n/** Parse a bulk point response into a name→downloads map (handles single + multi forms). */\nexport function parseBulkWeekly(json: any, requested: string[]): Map<string, number | null> {\n const map = new Map<string, number | null>();\n // A single-package request returns the object directly, not keyed by name.\n if (json && typeof json.downloads === 'number' && typeof json.package === 'string') {\n map.set(json.package, json.downloads);\n return map;\n }\n for (const name of requested) {\n const entry = json?.[name];\n map.set(name, entry && typeof entry.downloads === 'number' ? entry.downloads : null);\n }\n return map;\n}\n\nfunction chunk<T>(items: T[], size: number): T[][] {\n const out: T[][] = [];\n for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));\n return out;\n}\n\n/** Single-package weekly downloads. 404 → null (no per-package data). */\nexport async function fetchWeeklyDownloads(\n name: string,\n fetchImpl?: typeof fetch,\n): Promise<number | null> {\n try {\n const { data } = await httpGetJson<any>(\n `https://${HOST}/downloads/point/last-week/${name}`,\n { host: HOST, ttlMs: CACHE_TTL.npmDownloads, retries: 5, fetchImpl },\n );\n return parseWeeklyDownloads(data);\n } catch (err) {\n if (err instanceof HttpError && err.status === 404) return null;\n throw err;\n }\n}\n\n/** Per-package 90d growth (best-effort secondary signal). */\nexport async function fetchDownloadGrowth(\n name: string,\n fetchImpl?: typeof fetch,\n): Promise<number | null> {\n try {\n const { data } = await httpGetJson<any>(\n `https://${HOST}/downloads/range/${last90DayRange()}/${name}`,\n { host: HOST, ttlMs: CACHE_TTL.npmDownloads, retries: 3, fetchImpl },\n );\n return parseDownloadGrowth(data);\n } catch {\n return null;\n }\n}\n\n/**\n * Bulk-fetch weekly downloads for many packages. Unscoped packages go through\n * the 128-at-a-time bulk endpoint; scoped packages are fetched individually.\n */\nexport async function fetchBulkWeeklyDownloads(\n names: string[],\n fetchImpl?: typeof fetch,\n): Promise<Map<string, number | null>> {\n const result = new Map<string, number | null>();\n const unscoped = names.filter((n) => !n.startsWith('@'));\n const scoped = names.filter((n) => n.startsWith('@'));\n\n for (const batch of chunk(unscoped, BULK_CHUNK)) {\n try {\n const { data } = await httpGetJson<any>(\n `https://${HOST}/downloads/point/last-week/${batch.join(',')}`,\n { host: HOST, ttlMs: CACHE_TTL.npmDownloads, retries: 5, fetchImpl },\n );\n for (const [k, v] of parseBulkWeekly(data, batch)) result.set(k, v);\n } catch {\n // Leave this batch absent; per-package fallback will retry it.\n }\n }\n\n for (const name of scoped) {\n try {\n result.set(name, await fetchWeeklyDownloads(name, fetchImpl));\n } catch {\n /* leave absent → per-package fallback */\n }\n }\n\n return result;\n}\n","/**\n * GitHub client (§9.3). One GraphQL call per repo fetches stars, issue counts,\n * archived flag, and recent releases (latest date + 12-month cadence).\n * Requires GITHUB_TOKEN; without it, the pipeline skips this source.\n */\nimport { CACHE_TTL } from '../../core/constants';\nimport { httpRequest } from '../../core/http';\nimport type { GithubRepoData } from '../types';\n\nconst HOST = 'api.github.com';\nconst ENDPOINT = `https://${HOST}/graphql`;\n\nconst QUERY = `query($owner:String!, $name:String!) {\n repository(owner:$owner, name:$name) {\n stargazerCount\n isArchived\n openIssues: issues(states:OPEN) { totalCount }\n closedIssues: issues(states:CLOSED) { totalCount }\n releases(first: 50, orderBy: {field: CREATED_AT, direction: DESC}) {\n nodes { createdAt }\n }\n }\n}`;\n\nconst ONE_YEAR_MS = 365 * 24 * 60 * 60 * 1000;\n\nexport function parseGithub(json: any, now: Date = new Date()): GithubRepoData | null {\n const repo = json?.data?.repository;\n if (!repo) return null;\n\n const releaseNodes: { createdAt: string }[] = repo.releases?.nodes ?? [];\n const releaseDates = releaseNodes\n .map((n) => Date.parse(n.createdAt))\n .filter((ms) => !Number.isNaN(ms));\n const cutoff = now.getTime() - ONE_YEAR_MS;\n\n return {\n stars: typeof repo.stargazerCount === 'number' ? repo.stargazerCount : null,\n openIssues: repo.openIssues?.totalCount ?? null,\n closedIssues: repo.closedIssues?.totalCount ?? null,\n archived: Boolean(repo.isArchived),\n lastReleaseAt: releaseDates.length ? new Date(Math.max(...releaseDates)) : null,\n releasesLast12mo: releaseDates.filter((ms) => ms >= cutoff).length,\n };\n}\n\nexport async function fetchGithubRepo(\n owner: string,\n repo: string,\n token: string,\n fetchImpl?: typeof fetch,\n): Promise<GithubRepoData | null> {\n const body = JSON.stringify({ query: QUERY, variables: { owner, name: repo } });\n const { data } = await httpRequest<any>(ENDPOINT, {\n host: HOST,\n ttlMs: CACHE_TTL.github,\n method: 'POST',\n headers: {\n Authorization: `bearer ${token}`,\n 'Content-Type': 'application/json',\n 'User-Agent': 'lurq',\n },\n body,\n // Keep the auth token out of the cache key.\n cacheKey: `POST ${ENDPOINT} ${owner}/${repo}`,\n fetchImpl,\n });\n return parseGithub(data);\n}\n","/**\n * deps.dev client (§9.4). Primary source for OpenSSF Scorecard and security\n * advisories.\n * - Scorecard comes from the project endpoint (keyed by github.com/owner/repo).\n * - Advisories: the version endpoint lists advisoryKeys; we fetch each (capped)\n * and derive a severity bucket from its CVSS score.\n */\nimport { CACHE_TTL } from '../../core/constants';\nimport { httpGetJson, type HttpResponse } from '../../core/http';\nimport type { Advisory, AdvisorySeverity } from '../../core/types';\nimport type { DependentCounts, DepsDevData } from '../types';\n\nconst HOST = 'api.deps.dev';\nconst MAX_ADVISORIES = 10;\n\nfunction encodeName(name: string): string {\n return encodeURIComponent(name);\n}\n\nexport function severityFromCvss(score: number | null | undefined): AdvisorySeverity {\n if (score == null) return 'moderate';\n if (score >= 9) return 'critical';\n if (score >= 7) return 'high';\n if (score >= 4) return 'moderate';\n if (score > 0) return 'low';\n return 'info';\n}\n\nexport function parseScorecard(json: any): number | null {\n const score = json?.scorecard?.overallScore;\n return typeof score === 'number' ? score : null;\n}\n\nexport function parseAdvisoryKeys(versionJson: any): string[] {\n const keys = versionJson?.advisoryKeys;\n if (!Array.isArray(keys)) return [];\n return keys\n .map((k: any) => (typeof k === 'string' ? k : k?.id))\n .filter((id: unknown): id is string => typeof id === 'string');\n}\n\nexport function parseAdvisoryDetail(json: any): Advisory {\n return {\n id: json?.advisoryKey?.id ?? json?.advisoryKey ?? 'unknown',\n severity: severityFromCvss(json?.cvss3Score),\n summary: json?.title ?? '',\n };\n}\n\nexport async function fetchScorecard(\n owner: string,\n repo: string,\n fetchImpl?: typeof fetch,\n): Promise<number | null> {\n const projectKey = encodeURIComponent(`github.com/${owner}/${repo}`);\n const url = `https://${HOST}/v3/projects/${projectKey}`;\n try {\n const { data } = await httpGetJson<any>(url, {\n host: HOST,\n ttlMs: CACHE_TTL.depsDev,\n fetchImpl,\n });\n return parseScorecard(data);\n } catch {\n return null;\n }\n}\n\nexport async function fetchAdvisories(\n name: string,\n version: string,\n fetchImpl?: typeof fetch,\n): Promise<Advisory[]> {\n const versionUrl = `https://${HOST}/v3/systems/npm/packages/${encodeName(name)}/versions/${encodeURIComponent(version)}`;\n let keys: string[] = [];\n try {\n const { data } = await httpGetJson<any>(versionUrl, {\n host: HOST,\n ttlMs: CACHE_TTL.depsDev,\n fetchImpl,\n });\n keys = parseAdvisoryKeys(data).slice(0, MAX_ADVISORIES);\n } catch {\n return [];\n }\n\n const details = await Promise.allSettled(\n keys.map((key) =>\n httpGetJson<any>(`https://${HOST}/v3/advisories/${encodeURIComponent(key)}`, {\n host: HOST,\n ttlMs: CACHE_TTL.depsDev,\n fetchImpl,\n }),\n ),\n );\n return details\n .filter(\n (d): d is PromiseFulfilledResult<HttpResponse<any>> => d.status === 'fulfilled',\n )\n .map((d) => parseAdvisoryDetail(d.value.data));\n}\n\n/**\n * Direct dependency names from the deps.dev graph (§2B). These are the packages\n * a seed is *built on* — the adjacent foundations. Best-effort: returns [] on any\n * failure. We deliberately do NOT rank by dependent count (that re-introduces the\n * popularity bias §2B exists to avoid); the caller gates on quality instead.\n */\nexport async function fetchDependencyNames(\n name: string,\n version: string,\n fetchImpl?: typeof fetch,\n): Promise<string[]> {\n const url = `https://${HOST}/v3/systems/npm/packages/${encodeName(name)}/versions/${encodeURIComponent(version)}:dependencies`;\n try {\n const { data } = await httpGetJson<any>(url, {\n host: HOST,\n ttlMs: CACHE_TTL.depsDev,\n fetchImpl,\n });\n const nodes: any[] = Array.isArray(data?.nodes) ? data.nodes : [];\n const names = nodes\n .map((n) => n?.versionKey?.name)\n .filter((n: unknown): n is string => typeof n === 'string' && n !== name);\n return [...new Set(names)];\n } catch {\n return [];\n }\n}\n\nexport interface ResolvedNode {\n name: string;\n version: string;\n}\n\n/**\n * The full resolved dependency closure for `name@version` (§4B) — every node npm\n * would put in node_modules, each with its exact resolved version. This is a\n * co-installation witness: the resolver found a working assignment including all\n * of them and the artifact shipped, so every pair inside provably co-resolves.\n * Best-effort: [] on any failure. Unlike `fetchDependencyNames`, keeps versions.\n */\nexport async function fetchResolvedGraph(\n name: string,\n version: string,\n fetchImpl?: typeof fetch,\n): Promise<ResolvedNode[]> {\n const url = `https://${HOST}/v3/systems/npm/packages/${encodeName(name)}/versions/${encodeURIComponent(version)}:dependencies`;\n try {\n const { data } = await httpGetJson<any>(url, {\n host: HOST,\n ttlMs: CACHE_TTL.depsDev,\n fetchImpl,\n });\n const nodes: any[] = Array.isArray(data?.nodes) ? data.nodes : [];\n const out: ResolvedNode[] = [];\n const seen = new Set<string>();\n for (const n of nodes) {\n const nm = n?.versionKey?.name;\n const ver = n?.versionKey?.version;\n if (typeof nm !== 'string' || typeof ver !== 'string') continue;\n const key = `${nm}@${ver}`;\n if (seen.has(key)) continue;\n seen.add(key);\n out.push({ name: nm, version: ver });\n }\n return out;\n } catch {\n return [];\n }\n}\n\n/**\n * Direct dependencies only (§4G BFS), with versions — the ~15 packages the author\n * deliberately chose, not the transitive plumbing. Reads the graph `edges`: a\n * node is direct iff an edge from the root (the `SELF` node) points to it. Falls\n * back to [] on failure. Enqueuing only these keeps discovery from re-introducing\n * the plumbing explosion one hop later.\n */\nexport async function fetchDirectDependencies(\n name: string,\n version: string,\n fetchImpl?: typeof fetch,\n): Promise<ResolvedNode[]> {\n const url = `https://${HOST}/v3/systems/npm/packages/${encodeName(name)}/versions/${encodeURIComponent(version)}:dependencies`;\n try {\n const { data } = await httpGetJson<any>(url, {\n host: HOST,\n ttlMs: CACHE_TTL.depsDev,\n fetchImpl,\n });\n const nodes: any[] = Array.isArray(data?.nodes) ? data.nodes : [];\n const edges: any[] = Array.isArray(data?.edges) ? data.edges : [];\n // Root is the SELF node; deps.dev conventionally places it at index 0.\n const rootIdx = nodes.findIndex((n) => n?.relation === 'SELF');\n const root = rootIdx >= 0 ? rootIdx : 0;\n const out: ResolvedNode[] = [];\n const seen = new Set<string>();\n for (const e of edges) {\n if (e?.fromNode !== root) continue;\n const target = nodes[e?.toNode];\n const nm = target?.versionKey?.name;\n const ver = target?.versionKey?.version;\n if (typeof nm !== 'string' || typeof ver !== 'string' || nm === name) continue;\n if (seen.has(nm)) continue;\n seen.add(nm);\n out.push({ name: nm, version: ver });\n }\n return out;\n } catch {\n return [];\n }\n}\n\n/**\n * Dependent counts, split into direct and indirect (§9.4).\n *\n * `directDependentCount` is the number of packages that name this one in their\n * own manifest — a human typed it into a package.json. `indirectDependentCount`\n * is everything that merely inherited it through someone else's tree.\n *\n * The RATIO between them is the useful part, and it is not a popularity signal.\n * `fetchDependencyNames` above notes that lurq deliberately does not rank by\n * dependent COUNT, because raw counts re-import the popularity bias that\n * discovery (§2B) exists to avoid. That reasoning holds and this does not\n * violate it: share and volume rank things oppositely. Measured on the live\n * index, `@radix-ui/rect` has 30,363 dependents — hugely popular — of which\n * 0.0% are direct, because nothing imports it on purpose; `ag-grid-react` has\n * 12 dependents of which 91.7% are direct. Volume says the first is a hundred\n * times more important. Share says only the second was ever chosen, which is\n * the question `recommend` is actually asking.\n *\n * Best-effort, like every other source here: null on any failure, never fatal.\n */\nexport async function fetchDependents(\n name: string,\n version: string,\n fetchImpl?: typeof fetch,\n): Promise<DependentCounts | null> {\n const url = `https://${HOST}/v3alpha/systems/npm/packages/${encodeName(name)}/versions/${encodeURIComponent(version)}:dependents`;\n try {\n const { data } = await httpGetJson<any>(url, {\n host: HOST,\n ttlMs: CACHE_TTL.depsDev,\n fetchImpl,\n });\n return parseDependents(data);\n } catch {\n return null;\n }\n}\n\n/** Split out for unit testing without a network round trip. */\nexport function parseDependents(json: any): DependentCounts | null {\n const direct = json?.directDependentCount;\n const indirect = json?.indirectDependentCount;\n if (typeof direct !== 'number' || typeof indirect !== 'number') return null;\n return { direct, indirect };\n}\n\nexport async function fetchDepsDev(\n name: string,\n version: string | null,\n repo: { owner: string; repo: string } | null,\n fetchImpl?: typeof fetch,\n): Promise<DepsDevData> {\n const [scorecard, advisories, dependents] = await Promise.all([\n repo ? fetchScorecard(repo.owner, repo.repo, fetchImpl) : Promise.resolve(null),\n version ? fetchAdvisories(name, version, fetchImpl) : Promise.resolve([]),\n version ? fetchDependents(name, version, fetchImpl) : Promise.resolve(null),\n ]);\n return { scorecard, advisories, dependents };\n}\n","/**\n * Bundlephobia client (§9.5). Minified + gzipped size for frontend packages.\n * Strictly best-effort: this API is slow and flaky, so failures degrade to null\n * and never block ingestion (per R1 build decision). Cached aggressively (7d).\n */\nimport { CACHE_TTL } from '../../core/constants';\nimport { httpGetJson } from '../../core/http';\nimport { isFrontendCategory, type Category } from '../../core/types';\nimport type { BundlephobiaData } from '../types';\n\nconst HOST = 'bundlephobia.com';\n\nexport function parseBundleSize(json: any): number | null {\n const gzipBytes = json?.gzip;\n if (typeof gzipBytes !== 'number') return null;\n return Math.round((gzipBytes / 1024) * 10) / 10; // KB, 1 decimal\n}\n\n/**\n * Fetch bundle size — only for frontend categories (§9.5); returns null for\n * backend-only packages without making a request.\n */\nexport async function fetchBundlephobia(\n name: string,\n category: Category | null,\n fetchImpl?: typeof fetch,\n): Promise<BundlephobiaData> {\n if (!isFrontendCategory(category)) return { bundleMinGzipKb: null };\n\n const url = `https://${HOST}/api/size?package=${encodeURIComponent(name)}`;\n try {\n const { data } = await httpGetJson<any>(url, {\n host: HOST,\n ttlMs: CACHE_TTL.bundlephobia,\n timeoutMs: 12_000,\n retries: 1,\n fetchImpl,\n });\n return { bundleMinGzipKb: parseBundleSize(data) };\n } catch {\n return { bundleMinGzipKb: null };\n }\n}\n","export * from './npmRegistry';\nexport * from './npmSearch';\nexport * from './npmDownloads';\nexport * from './github';\nexport * from './depsDev';\nexport * from './bundlephobia';\n","/**\n * Assemble compat members for a set of package names: the fast path reads\n * metadata straight from the DB in one query; any name not tracked is fetched\n * on-demand (the HTTP layer caches packuments) so a single untracked package\n * doesn't blind the whole-architecture check. Names that can't be resolved at\n * all are returned as `unverified` rather than guessed.\n *\n * When a pin differs from the indexed latest, peers/engines are loaded for that\n * exact published version so Tier-1 checks match the stack being installed.\n */\nimport type { Database } from '../db/client';\nimport { getCompatMetadata } from '../db/compat';\nimport { fetchNpmCompatAtVersion, fetchNpmRegistry } from '../ingestion/sources';\nimport type { CompatMember } from './peerCompat';\n\nexport interface CompatPackageRef {\n name: string;\n /** Exact version to check. Null/undefined → indexed latest (or registry latest). */\n version?: string | null;\n}\n\nexport async function assembleMembers(\n db: Database,\n refs: CompatPackageRef[] | string[],\n): Promise<{ members: CompatMember[]; unverified: string[] }> {\n const normalized: CompatPackageRef[] = refs.map((r) =>\n typeof r === 'string' ? { name: r, version: null } : r,\n );\n const names = [...new Set(normalized.map((r) => r.name))];\n const tracked = new Map((await getCompatMetadata(db, names)).map((r) => [r.name, r]));\n const members: CompatMember[] = [];\n const unverified: string[] = [];\n\n await Promise.all(\n normalized.map(async (ref) => {\n const row = tracked.get(ref.name);\n const pin = ref.version?.trim() || null;\n const canUseIndexed =\n row && (!pin || !row.latestVersion || pin === row.latestVersion);\n\n if (canUseIndexed && row) {\n members.push({\n name: ref.name,\n version: pin ?? row.latestVersion,\n peerDependencies: row.peerDependencies,\n peerDependenciesMeta: row.peerDependenciesMeta,\n engines: row.engines,\n });\n return;\n }\n\n // Pinned away from latest (or untracked): load that version's manifest.\n if (pin) {\n const at = await fetchNpmCompatAtVersion(ref.name, pin).catch(() => null);\n if (at) {\n members.push({\n name: ref.name,\n version: at.version,\n peerDependencies: at.peerDependencies,\n peerDependenciesMeta: at.peerDependenciesMeta,\n engines: at.engines,\n });\n return;\n }\n unverified.push(ref.name);\n return;\n }\n\n const reg = await fetchNpmRegistry(ref.name).catch(() => null);\n if (reg) {\n members.push({\n name: ref.name,\n version: reg.latestVersion,\n peerDependencies: reg.peerDependencies,\n peerDependenciesMeta: reg.peerDependenciesMeta,\n engines: reg.engines,\n });\n } else {\n unverified.push(ref.name);\n }\n }),\n );\n\n return { members, unverified };\n}\n","/**\n * Tier-1 compatibility: whole-architecture peer-dependency + engine analysis.\n *\n * Deterministic and instant — no install. Works over the *entire set* at once:\n * it collects every package's declared `peerDependencies`, groups them by peer,\n * and checks the declared semver ranges agree. Two plugins that need `eslint@8`\n * vs `eslint@9` conflict even if eslint isn't pinned in the set.\n *\n * Sparse data degrades safely: a package with no declared peers contributes no\n * constraints (which is correct — most packages declare none), so \"not fully\n * recorded\" never produces a false conflict. Genuinely-untracked packages are\n * reported as `unverified` by the caller, not guessed at.\n */\nimport semver from 'semver';\nimport type { CompatConflict, DependencyRanges, PeerMeta } from '../core/types';\n\nexport interface CompatMember {\n name: string;\n /** Pinned (latest) version, or null if unknown. */\n version: string | null;\n peerDependencies: DependencyRanges | null;\n peerDependenciesMeta: PeerMeta | null;\n engines: DependencyRanges | null;\n}\n\ninterface PeerConstraint {\n requirer: string;\n peer: string;\n range: string;\n optional: boolean;\n}\n\n/** null = can't assert (invalid version/range). */\nfunction satisfiesRange(version: string, range: string): boolean | null {\n if (!semver.validRange(range)) return null;\n const v = semver.valid(version) ? version : semver.coerce(version)?.version;\n if (!v) return null;\n return semver.satisfies(v, range, { includePrerelease: true });\n}\n\nfunction rangesIntersect(a: string, b: string): boolean | null {\n if (!semver.validRange(a) || !semver.validRange(b)) return null;\n try {\n return semver.intersects(a, b, { includePrerelease: true });\n } catch {\n return null;\n }\n}\n\n/** All peer/engine conflicts across the set (empty = no Tier-1 conflict found). */\nexport function resolveArchitectureCompat(members: CompatMember[]): CompatConflict[] {\n const conflicts: CompatConflict[] = [];\n const pinned = new Map<string, string>();\n for (const m of members) if (m.version) pinned.set(m.name, m.version);\n\n const constraints: PeerConstraint[] = [];\n for (const m of members) {\n if (!m.peerDependencies) continue;\n for (const [peer, range] of Object.entries(m.peerDependencies)) {\n constraints.push({\n requirer: m.name,\n peer,\n range,\n optional: Boolean(m.peerDependenciesMeta?.[peer]?.optional),\n });\n }\n }\n\n // (1) A peer that's pinned in the set must satisfy each declared range.\n for (const c of constraints) {\n const pv = pinned.get(c.peer);\n if (pv && satisfiesRange(pv, c.range) === false) {\n conflicts.push({\n source: 'peer-deps',\n packages: [c.requirer, c.peer],\n detail: `${c.requirer} needs peer ${c.peer}@${c.range}, but the stack uses ${c.peer}@${pv}`,\n requirement: { peer: c.peer, range: c.range, resolved: pv },\n });\n }\n }\n\n // (2) A peer required by ≥2 members but not pinned: their ranges must overlap.\n const byPeer = new Map<string, PeerConstraint[]>();\n for (const c of constraints) {\n if (pinned.has(c.peer) || c.optional) continue;\n const arr = byPeer.get(c.peer);\n if (arr) arr.push(c);\n else byPeer.set(c.peer, [c]);\n }\n for (const [peer, cs] of byPeer) {\n for (let i = 0; i < cs.length; i++) {\n for (let j = i + 1; j < cs.length; j++) {\n if (cs[i]!.range !== cs[j]!.range && rangesIntersect(cs[i]!.range, cs[j]!.range) === false) {\n conflicts.push({\n source: 'peer-deps',\n packages: [cs[i]!.requirer, cs[j]!.requirer],\n detail: `${cs[i]!.requirer} needs ${peer}@${cs[i]!.range} but ${cs[j]!.requirer} needs ${peer}@${cs[j]!.range}, no overlapping version`,\n // Two requirers disagreeing about a peer that isn't in the set: the\n // peer has no resolved version to report.\n requirement: { peer, range: cs[i]!.range, resolved: null },\n });\n }\n }\n }\n }\n\n // (3) Node engine ranges across the set must have a common solution.\n const nodeReqs = members\n .map((m) => ({ name: m.name, range: m.engines?.node }))\n .filter((r): r is { name: string; range: string } => typeof r.range === 'string');\n for (let i = 0; i < nodeReqs.length; i++) {\n for (let j = i + 1; j < nodeReqs.length; j++) {\n if (rangesIntersect(nodeReqs[i]!.range, nodeReqs[j]!.range) === false) {\n conflicts.push({\n source: 'engines',\n packages: [nodeReqs[i]!.name, nodeReqs[j]!.name],\n detail: `${nodeReqs[i]!.name} needs node ${nodeReqs[i]!.range} but ${nodeReqs[j]!.name} needs node ${nodeReqs[j]!.range}, no overlap`,\n });\n }\n }\n }\n\n return conflicts;\n}\n\n/**\n * Tier-1 check: each member's `engines.node` must satisfy the target runtime\n * (e.g. the benchmark / sandbox Node version). Sparse/missing engines are ignored.\n *\n * A bare major (`\"20\"`) means \"some Node 20\", not `20.0.0` — coercing it to the\n * .0.0 floor false-flagged every package with a modern engines floor (vite's\n * `^20.19.0 || >=22.12.0` \"conflicted\" with node 20). Partial versions are\n * therefore compared as *ranges* and only conflict when no Node in the target\n * line can satisfy the package; an exact version still gets an exact check.\n */\nexport function resolveRuntimeEngineConflicts(\n members: CompatMember[],\n nodeVersion: string,\n): CompatConflict[] {\n const runtime = normalizeNodeVersion(nodeVersion);\n if (!runtime) return [];\n\n const conflicts: CompatConflict[] = [];\n for (const m of members) {\n const range = m.engines?.node;\n if (!range) continue;\n const ok = runtime.exact\n ? satisfiesRange(runtime.value, range)\n : rangesIntersect(runtime.value, range);\n if (ok === false) {\n conflicts.push({\n source: 'engines',\n packages: [m.name],\n detail: `${m.name}@${m.version ?? '?'} needs node ${range}, but the runtime is node ${runtime.label}`,\n });\n }\n }\n return conflicts;\n}\n\n/** The target runtime as a semver *range*, plus whether the caller pinned an\n * exact version. `20` / `v20` → `20.x` (any Node 20); `20.20.2` → exact. */\ninterface TargetRuntime {\n /** Exact version, or a range covering the requested line. */\n value: string;\n exact: boolean;\n /** What the caller asked for, for the conflict message. */\n label: string;\n}\n\nfunction normalizeNodeVersion(raw: string): TargetRuntime | null {\n const trimmed = raw.trim().replace(/^v/i, '');\n if (!trimmed) return null;\n if (semver.valid(trimmed)) return { value: trimmed, exact: true, label: trimmed };\n // `20` or `20.19` — a version line, not a version. Widen to the whole line.\n if (/^\\d+(\\.\\d+)?$/.test(trimmed)) {\n return { value: `${trimmed}.x`, exact: false, label: trimmed };\n }\n const coerced = semver.coerce(trimmed);\n return coerced ? { value: coerced.version, exact: true, label: coerced.version } : null;\n}\n","/**\n * Whole-architecture compatibility check for a set of packages, shared by the\n * `compat` tool and `plan`.\n *\n * **The verdict is about the set, not its pairs.** npm resolves a whole\n * dependency graph at once, and three packages can be compatible in every pair\n * and still fail together — a diamond dependency, or a peer range that only\n * becomes unsatisfiable with all three present. The old pairwise model could not\n * express the conflicts npm actually reports, so it could only ever say \"no pair\n * is known to be broken\", which is what `likely` meant. That verdict is gone: a\n * caller now gets `compatible`, `conflict`, or an honest `unknown`.\n *\n * Three tiers, cheapest first, and the expensive one only runs when the cheap\n * ones are clean:\n *\n * 1. **Declared** (free) — peer ranges and engines off metadata already in the\n * index. A conflict here needs no network at all.\n * 2. **Cached resolution** (~1ms) — this exact set of `name@version` has been\n * resolved before, and the answer is immutable for those versions.\n * 3. **Live resolve** (~3-9s warm) — `npm install --package-lock-only`. Real\n * answer about the real versions, cached on the way out.\n */\nimport type {\n CompatConflict,\n CompatEvidence,\n CompatOutput,\n CompatPair,\n CompatResolution,\n} from '../core/types';\nimport type { Database } from '../db/client';\nimport { enqueueCompatVerify, getSandboxEdges, pairKey } from '../db/compat';\nimport {\n getStackResolution,\n recordStackResolution,\n stackKey,\n type StackMember,\n} from '../db/stackResolutions';\nimport { logger } from '../core/logger';\nimport { resolveSet } from '../pipeline/resolveCheck';\nimport { assembleMembers, type CompatPackageRef } from './members';\nimport { resolveArchitectureCompat, resolveRuntimeEngineConflicts } from './peerCompat';\n\n/**\n * Final verdict (pure). Three outcomes, all of them answers:\n *\n * - `conflict` — proven broken, by a declared range, a sandbox co-install,\n * or npm's own ERESOLVE.\n * - `compatible` — npm resolved this exact set of versions.\n * - `unknown` — we could not determine it: a member we have no version for,\n * or a resolve that timed out. Never a hedge on a set we did\n * successfully resolve.\n */\nexport function gradeOverall(args: {\n hasConflict: boolean;\n hasUnverifiedMember: boolean;\n resolution: 'resolved' | 'conflict' | 'inconclusive';\n}): CompatOutput['overall'] {\n if (args.hasConflict || args.resolution === 'conflict') return 'conflict';\n if (args.hasUnverifiedMember || args.resolution === 'inconclusive') return 'unknown';\n return 'compatible';\n}\n\nexport interface CheckCompatOptions {\n /** Exact versions to evaluate (name → version). Missing names use indexed latest. */\n versions?: Record<string, string | null | undefined>;\n /** Target Node runtime (e.g. \"20\" or \"20.20.2\"). Checks each package's engines.node. */\n node?: string | null;\n /** Skip the live resolve on a cache miss — cached answers only. `plan` uses\n * this: it checks many candidate sets and must not fire an npm process per\n * candidate. A miss there is `unknown`, which is the honest answer. */\n cachedOnly?: boolean;\n}\n\nexport async function checkCompat(\n db: Database,\n packages: string[],\n opts: CheckCompatOptions = {},\n): Promise<CompatOutput> {\n const names = [...new Set(packages)];\n const refs: CompatPackageRef[] = names.map((name) => ({\n name,\n version: opts.versions?.[name] ?? null,\n }));\n const { members, unverified } = await assembleMembers(db, refs);\n\n // ── Tier 1: declared constraints. Free, and it short-circuits the rest. ────\n const conflicts: CompatConflict[] = [\n ...resolveArchitectureCompat(members),\n ...(opts.node ? resolveRuntimeEngineConflicts(members, opts.node) : []),\n ];\n\n // Sandbox verdicts are the one pairwise thing that survives: a real co-install\n // under VM isolation is not derivable from any resolution.\n const edges = await getSandboxEdges(db, names);\n const versionOf = new Map(members.map((m) => [m.name, m.version]));\n const evidence: CompatEvidence[] = edges.map((edge) => ({\n packages: [edge.packageA, edge.packageB],\n versions: [edge.versionA, edge.versionB],\n status: edge.status,\n provenance: edge.provenance,\n witnessCount: edge.witnessCount,\n }));\n\n for (const edge of edges) {\n if (edge.status !== 'conflict') continue;\n // Reported whether or not the versions match. A failed co-install at\n // neighbouring versions is still the best information anyone has about this\n // pair, and the detail names the exact versions so a reader can see it is\n // not the pair they asked about. Suppressing it would be optimism.\n const at = edgeMatchesVersions(edge, versionOf)\n ? ''\n : ` (recorded at those versions; you are checking ${edge.packageA}@${versionOf.get(edge.packageA) ?? '?'} and ${edge.packageB}@${versionOf.get(edge.packageB) ?? '?'})`;\n conflicts.push({\n source: 'sandbox',\n packages: [edge.packageA, edge.packageB],\n detail: `${edge.packageA}@${edge.versionA} and ${edge.packageB}@${edge.versionB} failed to co-install in the sandbox${at}`,\n });\n }\n\n const checkedNames = members.map((m) => m.name);\n const { resolution, verdict } = await settle(db, members, {\n // A declared conflict is already proof. Paying npm to re-confirm it would be\n // seconds spent learning nothing.\n skip: conflicts.length > 0,\n cachedOnly: opts.cachedOnly === true,\n hasUnverified: unverified.length > 0,\n });\n\n if (resolution?.reason === 'ERESOLVE') {\n conflicts.push({\n source: 'resolve',\n packages: checkedNames,\n detail: resolution.detail ?? 'npm could not resolve this set together',\n });\n }\n\n return {\n packages: names,\n overall: gradeOverall({\n hasConflict: conflicts.length > 0,\n hasUnverifiedMember: unverified.length > 0,\n resolution: verdict,\n }),\n conflicts,\n unverified,\n checked: members.map((m) => ({ name: m.name, version: m.version })),\n evidence,\n ...(resolution ? { resolution } : {}),\n pairs: enumeratePairs(checkedNames, conflicts),\n };\n}\n\n/**\n * Get a resolution for this exact set: from cache, or by running npm.\n *\n * Only definitive outcomes are cached. A timeout or a network failure is\n * inconclusive, and writing one down would turn a transient blip into a\n * permanent wrong answer for that stack with nothing to evict it.\n */\nasync function settle(\n db: Database,\n members: { name: string; version: string | null }[],\n opts: { skip: boolean; cachedOnly: boolean; hasUnverified: boolean },\n): Promise<{ resolution: CompatResolution | null; verdict: 'resolved' | 'conflict' | 'inconclusive' }> {\n if (opts.skip) return { resolution: null, verdict: 'inconclusive' };\n\n // A member with no resolved version cannot be part of a cache key — the key is\n // the exact versions, and \"we don't know\" is not a version. Same discipline as\n // `unverified` everywhere else: not knowing is never evidence.\n const pinned: StackMember[] = [];\n for (const m of members) {\n if (!m.version) return { resolution: null, verdict: 'inconclusive' };\n pinned.push({ name: m.name, version: m.version });\n }\n if (pinned.length < 2) return { resolution: null, verdict: 'resolved' };\n\n const key = stackKey(pinned);\n const cached = await getStackResolution(db, key).catch(() => null);\n if (cached) {\n return {\n resolution: {\n source: 'cache',\n resolved: cached.resolved,\n reason: cached.reason === 'ERESOLVE' ? 'ERESOLVE' : null,\n ...(cached.detail ? { detail: cached.detail } : {}),\n at: cached.resolvedAt.toISOString(),\n },\n verdict: cached.resolved ? 'resolved' : 'conflict',\n };\n }\n if (opts.cachedOnly) return { resolution: null, verdict: 'inconclusive' };\n\n let result;\n try {\n result = await resolveSet(pinned);\n } catch (err) {\n // Network, timeout, npm blew up — inconclusive, and deliberately not cached.\n logger.warn(`compat: resolve inconclusive for ${key}: ${String(err)}`);\n return { resolution: null, verdict: 'inconclusive' };\n }\n\n await recordStackResolution(db, {\n members: pinned,\n resolved: result.resolved,\n reason: result.reason,\n detail: result.detail ?? null,\n }).catch((err) => logger.warn(`compat: caching resolution failed: ${String(err)}`));\n\n // A set that resolves is proven to *install*. Whether it actually *runs* is a\n // stronger claim that only the sandbox can make, so escalate it there —\n // deduped on the set key, never blocking, and only on a fresh resolve so a\n // cache hit does not re-queue work already pending.\n if (result.resolved) {\n await enqueueCompatVerify(\n db,\n pinned.map((m) => m.name),\n ).catch(() => {});\n }\n\n return {\n resolution: {\n source: 'resolved',\n resolved: result.resolved,\n reason: result.reason,\n ...(result.detail ? { detail: result.detail } : {}),\n at: new Date().toISOString(),\n },\n verdict: result.resolved ? 'resolved' : 'conflict',\n };\n}\n\n/**\n * Does a recorded sandbox edge describe the versions currently under check?\n *\n * A member with no resolved version cannot match anything: treating it as a\n * match would claim an edge is about a version we could not even name.\n */\nexport function edgeMatchesVersions(\n edge: { packageA: string; packageB: string; versionA: string; versionB: string },\n versionOf: Map<string, string | null>,\n): boolean {\n const a = versionOf.get(edge.packageA);\n const b = versionOf.get(edge.packageB);\n return a != null && b != null && a === edge.versionA && b === edge.versionB;\n}\n\n/**\n * Every unordered pair among the checked members, in reading order (row-major\n * over the lower triangle), each graded from the conflicts already found.\n *\n * `held` is the absence of a *found* conflict, which is weaker than \"these work\n * together\" — the set-level verdict is where positive proof lives. It is\n * reported anyway because \"we compared these ten pairs and two failed\" is a\n * different and more useful statement than \"two things failed\", and a caller can\n * only make the first one if it knows what the denominator was.\n */\nexport function enumeratePairs(names: string[], conflicts: CompatConflict[]): CompatPair[] {\n // First conflict wins a pair; a second one for the same two packages adds no\n // verdict, and the detail of the first is the one that was found first.\n const byPair = new Map<string, CompatConflict>();\n for (const c of conflicts) {\n // A resolve conflict is about the whole set, not one pair — it has no\n // business claiming a specific pair is the broken one.\n if (c.source === 'resolve') continue;\n const [a, b] = c.packages;\n if (!a || !b) continue;\n const key = pairKey(a, b);\n if (!byPair.has(key)) byPair.set(key, c);\n }\n\n const pairs: CompatPair[] = [];\n for (let i = 0; i < names.length; i++) {\n for (let j = 0; j < i; j++) {\n const a = names[i]!;\n const b = names[j]!;\n const hit = byPair.get(pairKey(a, b));\n pairs.push(\n hit\n ? {\n // Orient the pair the way the conflict states it, so `a` is the\n // package making the demand rather than whichever came first in\n // the argument list.\n a: hit.packages[0] ?? a,\n b: hit.packages[1] ?? b,\n status: 'conflict',\n detail: hit.detail,\n ...(hit.requirement ? { requirement: hit.requirement } : {}),\n }\n : { a, b, status: 'held' },\n );\n }\n }\n return pairs;\n}\n","/**\n * Surface delta (§4D). Pure: given two extracted API surfaces, compute what an\n * agent must change — added / removed / renamed / changed exports. Deltas are\n * computed, not guessed. `renamed` is inferred when a symbol disappears and a\n * near-identical one (same kind + signature) appears, so an agent sees a rename\n * rather than an unrelated remove + add.\n */\nimport type { ExportSymbol, SurfaceDelta } from '../core/types';\n\nfunction byName(surface: ExportSymbol[]): Map<string, ExportSymbol> {\n return new Map(surface.map((s) => [s.name, s]));\n}\n\n/** Two removed/added symbols are the \"same\" renamed export if kind + signature\n * match (signature-similarity heuristic from §4D). */\nfunction looksRenamed(a: ExportSymbol, b: ExportSymbol): boolean {\n return a.kind === b.kind && a.signature !== null && a.signature === b.signature;\n}\n\nexport function diffSurface(oldSurface: ExportSymbol[], newSurface: ExportSymbol[]): SurfaceDelta {\n const oldByName = byName(oldSurface);\n const newByName = byName(newSurface);\n\n const removed: ExportSymbol[] = oldSurface.filter((s) => !newByName.has(s.name));\n const added: ExportSymbol[] = newSurface.filter((s) => !oldByName.has(s.name));\n const changed: SurfaceDelta['changed'] = [];\n\n for (const oldSym of oldSurface) {\n const newSym = newByName.get(oldSym.name);\n if (newSym && oldSym.signature !== newSym.signature) {\n changed.push({ name: oldSym.name, before: oldSym.signature, after: newSym.signature });\n }\n }\n\n // Pair removed↔added by signature similarity → renames. Each side used once.\n const renamed: SurfaceDelta['renamed'] = [];\n const takenAdded = new Set<string>();\n const stillRemoved: ExportSymbol[] = [];\n for (const r of removed) {\n const match = added.find((a) => !takenAdded.has(a.name) && looksRenamed(r, a));\n if (match) {\n renamed.push({ from: r, to: match });\n takenAdded.add(match.name);\n } else {\n stillRemoved.push(r);\n }\n }\n\n return {\n added: added.filter((a) => !takenAdded.has(a.name)),\n removed: stillRemoved,\n renamed,\n changed,\n };\n}\n","/**\n * Resolve with `task`'s value, or `null` once `ms` elapses.\n *\n * The `clearTimeout` is the whole reason this is shared rather than written\n * inline at each call site. A pending `setTimeout` holds Node's event loop open,\n * so a version of this that skips the cleanup leaves a short-lived process — the\n * CLI — sitting idle for the remainder of the budget after the answer is already\n * printed. Two copies of this existed and only one cleared its timer; the other\n * cost `lurq usage` up to four seconds of dead wait per lookup.\n *\n * The task is deliberately NOT cancelled when the budget expires: callers use\n * this for read-through caches where the abandoned work is what warms the cache\n * for the next request.\n */\nexport function withBudget<T>(task: Promise<T>, ms: number): Promise<T | null> {\n let timer: NodeJS.Timeout;\n return Promise.race([\n task,\n new Promise<null>((resolve) => {\n timer = setTimeout(resolve, ms, null);\n }),\n ]).finally(() => clearTimeout(timer));\n}\n\n/** Map over items with bounded concurrency, preserving input order. */\nexport async function pMap<T, R>(\n items: readonly T[],\n mapper: (item: T, index: number) => Promise<R>,\n concurrency: number,\n): Promise<R[]> {\n const results = new Array<R>(items.length);\n let cursor = 0;\n const workerCount = Math.max(1, Math.min(concurrency, items.length));\n const workers = Array.from({ length: workerCount }, async () => {\n while (cursor < items.length) {\n const index = cursor++;\n results[index] = await mapper(items[index]!, index);\n }\n });\n await Promise.all(workers);\n return results;\n}\n","/** Read/write helpers for the API-surface cache (`api_surfaces`, §4D). */\nimport { and, eq, isNotNull, isNull, sql } from 'drizzle-orm';\nimport type { ExportSymbol } from '../core/types';\nimport type { Database } from './client';\nimport { apiSurfaces, packages } from './schema';\n\nexport async function getStoredSurface(\n db: Database,\n packageName: string,\n version: string,\n): Promise<ExportSymbol[] | null> {\n const [row] = await db\n .select({ surface: apiSurfaces.surface })\n .from(apiSurfaces)\n .where(and(eq(apiSurfaces.packageName, packageName), eq(apiSurfaces.version, version)))\n .limit(1);\n return row?.surface ?? null;\n}\n\n/**\n * Tracked packages whose latest version has no extracted surface yet — the\n * worker's extraction backlog (§4G).\n *\n * A package that ships no types extracts to nothing and stores nothing, so it\n * stays in this result set forever. Unordered, that meant the worker pulled the\n * same head rows every cycle and never reached the tail: 96 cycles a day × 50\n * rows produced 357 surfaces against 3,316 packages.\n *\n * ponytail: `random()` guarantees the pass advances without a schema change, at\n * the cost of re-attempting permanent failures. If that retry waste starts\n * mattering, the upgrade is an `attempts`/`last_attempt_at` column on `packages`\n * (or a negative-cache row) plus exponential backoff — same shape as\n * `surface_queue.attempts` already uses on the demand-driven path.\n */\nexport async function getPackagesMissingSurface(\n db: Database,\n limit: number,\n): Promise<{ name: string; version: string }[]> {\n const rows = await db\n .select({ name: packages.name, version: packages.latestVersion })\n .from(packages)\n .leftJoin(\n apiSurfaces,\n and(\n eq(apiSurfaces.packageName, packages.name),\n eq(apiSurfaces.version, packages.latestVersion),\n ),\n )\n .where(and(isNotNull(packages.latestVersion), isNull(apiSurfaces.id)))\n .orderBy(sql`random()`)\n .limit(limit);\n return rows.filter((r): r is { name: string; version: string } => r.version !== null);\n}\n\n/** Cache a version's surface. Versions are immutable, so a stored surface is\n * authoritative; on the rare conflict we refresh rather than error. */\nexport async function upsertSurface(\n db: Database,\n packageName: string,\n version: string,\n surface: ExportSymbol[],\n): Promise<void> {\n await db\n .insert(apiSurfaces)\n .values({ packageName, version, surface })\n .onConflictDoUpdate({\n target: [apiSurfaces.packageName, apiSurfaces.version],\n set: { surface, extractedAt: new Date() },\n });\n}\n\n/**\n * Tracked packages whose latest version *does* have a surface — the input to the\n * predecessor backfill, which needs somewhere to start from.\n *\n * Randomly sampled for the same reason as {@link getPackagesMissingSurface}: a\n * package whose latest release is also its first can never gain a predecessor\n * and so never leaves this set, and a stable ordering would let those rows sit\n * at the head forever while the tail is never reached.\n */\nexport async function getPackagesWithSurface(\n db: Database,\n limit = 100,\n): Promise<{ name: string; version: string }[]> {\n const rows = await db\n .select({ name: packages.name, version: packages.latestVersion })\n .from(packages)\n .innerJoin(\n apiSurfaces,\n and(\n eq(apiSurfaces.packageName, packages.name),\n eq(apiSurfaces.version, packages.latestVersion),\n ),\n )\n .where(isNotNull(packages.latestVersion))\n .orderBy(sql`random()`)\n .limit(limit);\n return rows.filter((r): r is { name: string; version: string } => r.version !== null);\n}\n","/**\n * API surface extraction (§4D — usage axis D1). Ground truth is the package's\n * shipped `.d.ts`, parsed deterministically (no LLM) into a normalized export\n * list. Types are the code's real contract, extracted from the *exact* version —\n * no prose lag, no hallucination surface.\n *\n * We fetch the resolved types entry directly from the jsDelivr CDN rather than\n * download + untar the tarball: a single-file *syntactic* parse (createSourceFile,\n * no type-checker, no module resolution) captures top-level export presence and\n * signatures — the dominant drift class — without pulling the whole dep graph or\n * adding a `tar` dependency.\n *\n * The parse is per-file, but the walk is not: a barrel entry that only forwards\n * (`export * from './lib'`) is followed a bounded number of hops and merged, so\n * the entry's shape doesn't decide whether a package has a surface.\n *\n * Entry resolution covers `types`/`typings`, the `exports` map's root entry and\n * `index.d.ts`, then `@types/<name>` for packages that ship no types at all —\n * the whole 14-package popular-library sample in scripts/surface-coverage.mts\n * now extracts, where 5 did before. This matters more than it used to: while\n * extraction was worker-only a miss was just a gap, but now that a miss extracts\n * on the request path (usage/service) it bounds how often `usage` can answer at\n * all. Run that script after changing anything here.\n *\n * ponytail: what still degrades to null is a package whose types are reachable\n * only through a subpath (`pkg/submodule`) with no root entry, and one whose\n * barrel chain runs deeper than MAX_HOPS. Both fall back to the README.\n *\n * The compiler is loaded LAZILY and non-fatally, and that is load-bearing for the\n * plane split (§4E): `typescript` is a devDependency, present in the operator\n * runtime but never installed for consumers of the published package (which ships\n * `dist` only). A static `import ts from 'typescript'` here is hoisted by esbuild\n * into a top-level import of the public bundle, so every `lurqrun` command — not\n * just `usage` — would die at startup with ERR_MODULE_NOT_FOUND. Deferring the\n * import to the first extraction keeps it out of the bundle's static graph, and a\n * compiler that won't load degrades to null exactly like an untyped package.\n */\nimport { posix } from 'node:path';\nimport type * as TSApi from 'typescript';\nimport { HttpError, httpRequest } from '../core/http';\nimport { CACHE_TTL } from '../core/constants';\nimport type { ExportKind, ExportSymbol } from '../core/types';\n\n/** The compiler module itself, threaded through the parse helpers as a value so\n * nothing in this file references `typescript` at module scope. */\ntype Compiler = typeof TSApi;\n\nconst CDN = 'cdn.jsdelivr.net';\n\n/** HTTP tuning for the CDN fetches. The read path passes a tighter budget than\n * the worker: on the serving path a slow CDN must not hold a request open for\n * the default 15s × 4 attempts. */\nexport interface ExtractOptions {\n timeoutMs?: number;\n retries?: number;\n /** Wall-clock ceiling on one extraction, after which no further fetches start.\n * `timeoutMs` bounds a single fetch, but a barrel walk issues up to MAX_FILES\n * of them across MAX_HOPS waves, so only this bounds the whole thing. Omitted\n * → unbounded, which is what the worker wants: a cold jsDelivr edge can take\n * a minute for a wide barrel, and that extraction is the one warming the cache\n * for everyone after. */\n deadlineMs?: number;\n}\n\n/** One extraction's options with its deadline resolved to an absolute instant,\n * so every fetch in the walk measures against the same clock. */\ninterface Walk extends ExtractOptions {\n expiresAt: number;\n}\n\nfunction startWalk(opts: ExtractOptions): Walk {\n return {\n ...opts,\n expiresAt: opts.deadlineMs === undefined ? Infinity : Date.now() + opts.deadlineMs,\n };\n}\n\nlet compiler: Promise<Compiler | null> | undefined;\n\n/**\n * Load `typescript` once per process, resolving null when it isn't installed.\n * Memoized on the promise so concurrent cold misses share one module load, and\n * so a missing compiler is only probed once.\n */\nexport function loadCompiler(): Promise<Compiler | null> {\n compiler ??= import('typescript')\n .then((m) => (m as { default?: Compiler }).default ?? (m as unknown as Compiler))\n .catch(() => null);\n return compiler;\n}\n\ninterface FetchResult {\n text: string | null;\n /** True when the file's existence is unknown — a timeout, 5xx or network error\n * rather than a 404. A surface is only as trustworthy as the completeness of\n * the walk that built it, and the store is cache-forever, so this is what\n * keeps a transient CDN failure from being frozen in as a package's API. */\n unknown: boolean;\n}\n\nasync function fetchFile(\n url: string,\n opts: Walk,\n // Versions are immutable, so a long TTL is safe. Callers resolving a floating\n // range pass a shorter one.\n ttlMs: number = CACHE_TTL.depsDev,\n): Promise<FetchResult> {\n // Out of time counts as unknown, not absent: the walk is then unsound and its\n // partial result is discarded rather than cached as the package's API.\n if (Date.now() >= opts.expiresAt) return { text: null, unknown: true };\n try {\n const { data } = await httpRequest<string>(url, {\n host: CDN,\n ttlMs,\n accept: 'text',\n ...(opts.timeoutMs !== undefined ? { timeoutMs: opts.timeoutMs } : {}),\n ...(opts.retries !== undefined ? { retries: opts.retries } : {}),\n });\n return { text: typeof data === 'string' ? data : null, unknown: false };\n } catch (err) {\n // jsDelivr answers 404 for a path a package doesn't ship, which is a real\n // answer: that candidate simply isn't the file.\n const missing = err instanceof HttpError && err.status === 404;\n return { text: null, unknown: !missing };\n }\n}\n\nasync function fetchText(url: string, opts: Walk): Promise<string | null> {\n return (await fetchFile(url, opts)).text;\n}\n\nconst DTS_EXT = /\\.d\\.[cm]?ts$/;\nconst JS_EXT = /\\.(m|c)?js$/;\n\n/** The declaration file pairing with a path: itself if it already is one, else\n * the `.d.ts`/`.d.mts`/`.d.cts` sitting beside the JS. Null for anything else.\n * This is the \"types next to the JS\" rule TypeScript itself resolves by. */\nfunction declarationFor(path: string): string | null {\n if (DTS_EXT.test(path)) return path;\n const js = JS_EXT.exec(path);\n return js ? path.replace(JS_EXT, `.d.${js[1] ?? ''}ts`) : null;\n}\n\n/** Strip the leading `./` a manifest path carries; CDN paths are root-relative. */\nfunction relativeToRoot(path: string): string {\n return path.replace(/^\\.?\\//, '');\n}\n\n/** Conditions walked when reading the root entry out of an `exports` map, in\n * precedence order: an explicit types condition first (Node requires it to be\n * declared first for exactly this reason), then the runtime targets, whose\n * declaration siblings are the entry when no types condition exists at all. */\nconst EXPORT_CONDITIONS = ['types', 'typings', 'node', 'import', 'require', 'default'];\n\n/**\n * The root (`\".\"`) target of an `exports` map, as a declaration path. Packages\n * that publish through `exports` alone (execa, ora) have no `types` field to\n * read, and some (uuid) name no types condition either — there the JS target's\n * declaration sibling is what TypeScript would resolve.\n */\nexport function typesFromExports(exports: unknown, depth = 0): string | null {\n if (depth > 4) return null; // Pathological nesting isn't worth chasing.\n if (typeof exports === 'string') return declarationFor(exports);\n if (!exports || typeof exports !== 'object') return null;\n if (Array.isArray(exports)) {\n for (const alt of exports) {\n const found = typesFromExports(alt, depth + 1);\n if (found) return found;\n }\n return null;\n }\n const map = exports as Record<string, unknown>;\n // A subpath map: only the root entry describes the package's main surface.\n if ('.' in map) return typesFromExports(map['.'], depth + 1);\n if (Object.keys(map).some((k) => k.startsWith('.'))) return null;\n for (const condition of EXPORT_CONDITIONS) {\n if (!(condition in map)) continue;\n const found = typesFromExports(map[condition], depth + 1);\n if (found) return found;\n }\n return null;\n}\n\n/**\n * The `.d.ts` entry paths to try, most authoritative first: `types`/`typings`,\n * then the `exports` map's root target, then the conventional `index.d.ts`.\n * Ordered rather than singular because a `types` field can point at a file the\n * package doesn't actually ship (or ships only under `exports`), and a 404 there\n * shouldn't end the extraction.\n */\nfunction typesEntries(pkgJson: string): string[] {\n const entries: string[] = [];\n try {\n const manifest = JSON.parse(pkgJson);\n const declared: unknown = manifest.types ?? manifest.typings;\n if (typeof declared === 'string') entries.push(relativeToRoot(declared));\n const fromExports = typesFromExports(manifest.exports);\n if (fromExports) entries.push(relativeToRoot(fromExports));\n } catch {\n /* fall through to the conventional entry */\n }\n entries.push('index.d.ts');\n return [...new Set(entries)];\n}\n\nfunction kindOf(ts: Compiler, node: TSApi.Node): ExportKind {\n if (ts.isFunctionDeclaration(node)) return 'function';\n if (ts.isClassDeclaration(node)) return 'class';\n if (ts.isInterfaceDeclaration(node)) return 'interface';\n if (ts.isTypeAliasDeclaration(node)) return 'type';\n if (ts.isEnumDeclaration(node)) return 'enum';\n if (ts.isModuleDeclaration(node)) return 'namespace';\n if (ts.isVariableStatement(node)) return 'variable';\n return 'unknown';\n}\n\n/** Collapse whitespace so signatures compare cleanly across formatting changes. */\nfunction normalize(text: string): string {\n return text.replace(/\\s+/g, ' ').trim();\n}\n\n/** A function's `(params): return` signature; other kinds keep their head line. */\nfunction signatureOf(ts: Compiler, node: TSApi.Node, src: TSApi.SourceFile): string | null {\n if (ts.isFunctionDeclaration(node)) {\n const params = node.parameters.map((p) => normalize(p.getText(src))).join(', ');\n const ret = node.type ? `: ${normalize(node.type.getText(src))}` : '';\n return `(${params})${ret}`;\n }\n if (ts.isTypeAliasDeclaration(node)) return normalize(node.type.getText(src));\n // For classes/interfaces/enums the name+kind is the stable contract; a full\n // body diff is noisy. Keep null so `changed` only fires on real signature drift.\n return null;\n}\n\nfunction hasExportModifier(ts: Compiler, node: TSApi.Node): boolean {\n return (\n ts.canHaveModifiers(node) &&\n (ts.getModifiers(node)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) ?? false)\n );\n}\n\n/** What a statement declares, as `[localName, kind, signature]` tuples — a\n * `var`/`const` statement can declare several names, most statements one, and\n * anonymous ones none. Used both for the local index and for the exported\n * declarations themselves, so a name means the same thing either way. */\nfunction declarationsIn(\n ts: Compiler,\n node: TSApi.Node,\n src: TSApi.SourceFile,\n): Array<[string, ExportKind, string | null]> {\n if (ts.isVariableStatement(node)) {\n const out: Array<[string, ExportKind, string | null]> = [];\n for (const decl of node.declarationList.declarations) {\n if (ts.isIdentifier(decl.name)) {\n out.push([\n decl.name.text,\n 'variable',\n decl.type ? normalize(decl.type.getText(src)) : null,\n ]);\n }\n }\n return out;\n }\n const named = node as TSApi.DeclarationStatement;\n if (named.name && ts.isIdentifier(named.name)) {\n return [[named.name.text, kindOf(ts, node), signatureOf(ts, node, src)]];\n }\n return [];\n}\n\n/** One parsed `.d.ts`: what it exports itself, plus the `export * from '…'`\n * specifiers whose exports it forwards without naming (see `collectSurface`). */\nexport interface ParsedModule {\n symbols: ExportSymbol[];\n stars: string[];\n}\n\n/** Parse `.d.ts` text into a normalized, name-sorted export surface. The compiler\n * is passed in (see `loadCompiler`) rather than imported at module scope. */\nexport function parseSurface(source: string, ts: Compiler): ExportSymbol[] {\n return parseModule(source, ts).symbols;\n}\n\n/** `parseSurface`, also reporting the star re-exports it could not resolve alone. */\nexport function parseModule(source: string, ts: Compiler): ParsedModule {\n const src = ts.createSourceFile('surface.d.ts', source, ts.ScriptTarget.Latest, true);\n const out = new Map<string, ExportSymbol>();\n const stars: string[] = [];\n\n const add = (name: string, kind: ExportKind, signature: string | null) => {\n if (!out.has(name)) out.set(name, { name, kind, signature });\n };\n\n // Index every top-level declaration by local name, exported or not. A `.d.ts`\n // rolled up by rollup-plugin-dts or api-extractor (vite, helmet, and most\n // bundled types) is a wall of bare `declare`s closed by ONE `export { … }`\n // block, so the statement carrying a name's kind and signature is almost never\n // the statement that exports it. Private declarations stay private: nothing\n // reaches `out` unless an export form below names it.\n const local = new Map<string, { kind: ExportKind; signature: string | null }>();\n const namespaces = new Map<string, TSApi.ModuleDeclaration>();\n for (const node of src.statements) {\n for (const [name, kind, signature] of declarationsIn(ts, node, src)) {\n if (!local.has(name)) local.set(name, { kind, signature });\n }\n if (\n ts.isModuleDeclaration(node) &&\n ts.isIdentifier(node.name) &&\n !namespaces.has(node.name.text)\n ) {\n namespaces.set(node.name.text, node);\n }\n }\n\n /** Lift an ambient namespace's members to the top level. Members of a `declare\n * namespace` are all exported, with or without the keyword. */\n const liftNamespace = (decl: TSApi.ModuleDeclaration) => {\n if (!decl.body || !ts.isModuleBlock(decl.body)) return;\n for (const stmt of decl.body.statements) {\n for (const [name, kind, signature] of declarationsIn(ts, stmt, src))\n add(name, kind, signature);\n }\n };\n\n for (const node of src.statements) {\n // `export { … }`, `export * from …`, `export = …`: the `export` keyword is\n // part of these statements' own syntax rather than a modifier, so they carry\n // no modifiers at all and must be matched BEFORE the modifier gate below.\n if (ts.isExportDeclaration(node)) {\n const clause = node.exportClause;\n if (!clause) {\n // `export * from './lib'` — this file names nothing; the exports are in\n // the target, which only the caller can fetch.\n if (node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) {\n stars.push(node.moduleSpecifier.text);\n }\n continue;\n }\n if (ts.isNamespaceExport(clause)) {\n // `export * as ns from './x'` binds the whole module under one name.\n add(clause.name.text, 'namespace', null);\n continue;\n }\n const reExport = node.moduleSpecifier !== undefined;\n for (const el of clause.elements) {\n // `export { Local as Public }` — the local binding holds the kind and\n // signature. A re-export from another module has neither, since a\n // single-file parse never sees that module's declarations.\n const decl = reExport ? undefined : local.get((el.propertyName ?? el.name).text);\n const typeOnly = node.isTypeOnly || el.isTypeOnly;\n add(el.name.text, decl?.kind ?? (typeOnly ? 'type' : 'unknown'), decl?.signature ?? null);\n }\n continue;\n }\n\n if (ts.isExportAssignment(node) && ts.isIdentifier(node.expression)) {\n const target = node.expression.text;\n const decl = local.get(target);\n // The exported value itself is `default`: that is the name an importing\n // agent binds it to, for both `export default x` and `export = x` under\n // esModuleInterop.\n if (decl) add('default', decl.kind, decl.signature);\n // `export = e` is the CommonJS shape (@types/express, @types/react): the\n // module's whole surface lives in a namespace merged onto `e`, so the\n // members ARE the public API, not properties of one exported symbol.\n const ns = node.isExportEquals ? namespaces.get(target) : undefined;\n if (ns) liftNamespace(ns);\n continue;\n }\n\n if (!hasExportModifier(ts, node)) continue;\n for (const [name, kind, signature] of declarationsIn(ts, node, src)) add(name, kind, signature);\n }\n\n return { symbols: [...out.values()].sort((a, b) => a.name.localeCompare(b.name)), stars };\n}\n\n/**\n * The `.d.ts` files a relative specifier could resolve to, most likely first.\n * Empty for anything this parse has no business fetching: a bare specifier names\n * another package, and a path climbing out of the version root isn't ours.\n */\nexport function dtsCandidates(fromFile: string, specifier: string): string[] {\n if (!specifier.startsWith('./') && !specifier.startsWith('../')) return [];\n const path = posix.normalize(posix.join(posix.dirname(fromFile), specifier));\n if (path.startsWith('..')) return [];\n // `export * from './table.js'` is the ESM `.d.ts` idiom (drizzle-orm).\n const paired = declarationFor(path);\n if (paired) return [paired];\n // Extensionless (zod's `export * from './lib'`): a sibling, else a directory\n // barrel. Ordered, not raced — the first almost always hits, so the second\n // costs a round-trip only for real directories.\n return [`${path}.d.ts`, `${path}/index.d.ts`];\n}\n\n/** How far a barrel chain is followed. zod needs all three hops: index.d.ts →\n * lib/index.d.ts → lib/external.d.ts → the leaves that actually declare things. */\nconst MAX_HOPS = 3;\n\n/** Ceiling on files fetched per extraction, across all hops. Bounds a wide\n * barrel (drizzle-orm forwards 14 modules from its entry, each of which\n * forwards more) so a request-path extraction can't fan out without limit. */\nconst MAX_FILES = 24;\n\n/**\n * Merge a barrel's chain into one surface: parse `source`, then follow whatever\n * `export * from` it defers to, breadth-first. Bounded on both axes — MAX_HOPS\n * deep, MAX_FILES wide — because this runs on the `usage` read path under a\n * wall-clock budget; each hop's fetches go out in parallel so the cost is hops,\n * not files. Shallowest definition wins, so a barrel's own naming of a symbol\n * beats one it forwards.\n *\n * `sound` is false if any followed file couldn't be fetched. Stopping at the\n * caps is deliberate and deterministic — the same package always yields the same\n * surface — but a timed-out hop yields an arbitrary subset, and the caller\n * caches forever, so that one must not be mistaken for a package's API.\n */\nasync function collectSurface(\n ts: Compiler,\n root: string,\n entry: string,\n source: string,\n opts: Walk,\n): Promise<{ symbols: ExportSymbol[]; sound: boolean }> {\n const merged = new Map<string, ExportSymbol>();\n const attempted = new Set<string>([entry]);\n let budget = MAX_FILES;\n let sound = true;\n\n /** Absorb one file's exports; hand back the candidate lists it defers to. */\n const absorb = (file: string, text: string): string[][] => {\n const { symbols, stars } = parseModule(text, ts);\n for (const s of symbols) if (!merged.has(s.name)) merged.set(s.name, s);\n return stars.map((spec) => dtsCandidates(file, spec)).filter((c) => c.length > 0);\n };\n\n /** Fetch the first candidate that exists. These are alternatives for ONE\n * specifier, so they're tried in order rather than raced. `attempted` doubles\n * as the cycle guard: a barrel that re-exports its own ancestor stops here. */\n const fetchFirst = async (candidates: string[]): Promise<[string, string] | null> => {\n for (const file of candidates) {\n if (attempted.has(file) || budget <= 0) continue;\n attempted.add(file);\n budget--;\n const { text, unknown } = await fetchFile(`${root}/${file}`, opts);\n if (text !== null) return [file, text];\n if (unknown) {\n sound = false;\n return null; // Don't read a 404 into the next candidate; we never got one.\n }\n }\n return null;\n };\n\n let frontier = absorb(entry, source);\n for (let hop = 0; hop < MAX_HOPS && frontier.length > 0 && budget > 0; hop++) {\n const fetched = await Promise.all(frontier.map(fetchFirst));\n frontier = fetched.flatMap((hit) => (hit ? absorb(hit[0], hit[1]) : []));\n }\n\n return { symbols: [...merged.values()].sort((a, b) => a.name.localeCompare(b.name)), sound };\n}\n\n/**\n * Walk one package version root: try its types entries in order, stopping at the\n * first that yields a surface. Tried in order and only as far as needed, so a\n * package whose `types` field resolves — the overwhelming majority — pays\n * nothing for the fallbacks behind it.\n */\nasync function surfaceFrom(\n ts: Compiler,\n root: string,\n pkgJson: string,\n opts: Walk,\n): Promise<ExportSymbol[] | null> {\n for (const entry of typesEntries(pkgJson)) {\n const dts = await fetchText(`${root}/${entry}`, opts);\n if (!dts) continue;\n const { symbols, sound } = await collectSurface(ts, root, entry, dts, opts);\n // An unsound walk degrades to null rather than to a partial surface: null\n // means \"fall back to the README\" and is retried on the next request, while\n // a stored surface is believed forever. Under the read path's tight fetch\n // ceiling that is the likely outcome for a wide barrel on a cold CDN edge —\n // the worker, with the default timeouts, extracts it in full later.\n if (sound && symbols.length > 0) return symbols;\n }\n return null;\n}\n\n/** DefinitelyTyped's package name for a library: a scoped `@scope/name` mangles\n * to `@types/scope__name`, since npm scopes don't nest. */\nexport function typesPackageName(name: string): string {\n return name.startsWith('@') ? `@types/${name.slice(1).replace('/', '__')}` : `@types/${name}`;\n}\n\n/**\n * The surface from DefinitelyTyped, for packages that ship no types of their own\n * (react, express, semver). Pinned to the MATCHING MAJOR, never to `latest`:\n * @types/react's latest types React 19, and storing that as react@18.3.1's API\n * would be a confident wrong answer rather than a missing one. Within the major\n * there is still skew — @types/semver@7.8.0 answers for semver@7.7.2 — which is\n * the approximation DefinitelyTyped's own versioning offers.\n */\nasync function typesPackageSurface(\n ts: Compiler,\n name: string,\n version: string,\n opts: Walk,\n): Promise<ExportSymbol[] | null> {\n const major = /^\\d+/.exec(version)?.[0];\n if (!major) return null;\n const dt = typesPackageName(name);\n // jsDelivr resolves the range and 404s when DefinitelyTyped has no matching\n // major. The manifest reports which version answered, and the file fetches\n // pin to it so a walk can't straddle two releases mid-flight.\n const { text: pkgJson } = await fetchFile(\n `https://${CDN}/npm/${dt}@${major}/package.json`,\n opts,\n CACHE_TTL.npmRegistry, // A floating range: don't hold it for a day.\n );\n if (!pkgJson) return null;\n let resolved: unknown;\n try {\n resolved = JSON.parse(pkgJson).version;\n } catch {\n return null;\n }\n if (typeof resolved !== 'string') return null;\n return surfaceFrom(ts, `https://${CDN}/npm/${dt}@${resolved}`, pkgJson, opts);\n}\n\n/**\n * Extract the public API surface for `name@version`, or null if types can't be\n * resolved. Deterministic and cache-forever (versions are immutable).\n *\n * The compiler is resolved *before* the CDN fetches so a runtime without\n * `typescript` costs nothing but the (memoized) failed import.\n */\nexport async function extractSurface(\n name: string,\n version: string,\n opts: ExtractOptions = {},\n): Promise<ExportSymbol[] | null> {\n const ts = await loadCompiler();\n if (!ts) return null;\n // The deadline starts after the compiler load, not before: that cost is paid\n // once per process and isn't what a per-extraction ceiling is guarding.\n const walk = startWalk(opts);\n const root = `https://${CDN}/npm/${name}@${version}`;\n const pkgJson = await fetchText(`${root}/package.json`, walk);\n // No manifest means no answer either way. Falling through to @types here would\n // turn an unreachable CDN into a surface attributed to a package we never\n // established ships none of its own.\n if (!pkgJson) return null;\n return (\n (await surfaceFrom(ts, root, pkgJson, walk)) ?? typesPackageSurface(ts, name, version, walk)\n );\n}\n","/** Usage-axis serving layer (§4D): read-through the surface cache, extracting\n * on a miss. Shared by the `usage` handler and the discovery worker (§4G). */\nimport { withBudget } from '../core/concurrency';\nimport type { ExportSymbol } from '../core/types';\nimport type { Database } from '../db/client';\nimport { getStoredSurface, upsertSurface } from '../db/apiSurfaces';\nimport { extractSurface, type ExtractOptions } from './extract';\n\n/** Block-on-first-touch budget for the `usage` read path, mirroring\n * FIRST_TOUCH_BUDGET_MS (§4A): past this the caller gets the README-fallback\n * note while the extraction finishes in the background, so the *next* request\n * for that version is a cache hit. */\nexport const USAGE_EXTRACT_BUDGET_MS = 4000;\n\n/** CDN fetch tuning for the read path. The http default (15s × 4 attempts) is\n * sized for the worker; on a request path a stuck jsDelivr must not outlive the\n * budget by minutes, since the abandoned extraction keeps holding one of the\n * 6 per-host connection slots.\n *\n * `deadlineMs` is what actually bounds that, now that resolving a package can\n * mean walking a barrel over many files rather than fetching two: `timeoutMs`\n * only bounds one fetch. It sits well past USAGE_EXTRACT_BUDGET_MS on purpose —\n * an extraction the caller has already given up waiting for is still the one\n * warming the cache for the next request, and cutting it at the budget would\n * mean a slow package never gets extracted on this path at all. */\nconst READ_PATH_FETCH: ExtractOptions = { timeoutMs: 3000, retries: 0, deadlineMs: 15_000 };\n\n/** A flood of distinct versions must not grow memory without limit (same reason\n * ingestQueue caps its backlog). Past the cap a miss degrades to the note. */\nconst MAX_INFLIGHT = 64;\n\n/** Extractions in progress, keyed `name@version`, so concurrent misses for the\n * same version share one CDN round-trip instead of N. */\nconst inFlight = new Map<string, Promise<ExportSymbol[] | null>>();\n\nexport interface SurfaceLookupOptions {\n /** Wall-clock budget for a cold-miss extraction. Omitted → wait for it (the\n * worker and the landing-content generator want the surface, not a fast no).\n * 0 → skip extraction entirely (cache-only). */\n budgetMs?: number;\n /** Override the CDN fetch timeout/retries. */\n fetch?: ExtractOptions;\n}\n\n/** Start (or join) the single extraction for `name@version`. */\nfunction extractOnce(\n db: Database,\n name: string,\n version: string,\n fetchOpts: ExtractOptions,\n): Promise<ExportSymbol[] | null> {\n const key = `${name}@${version}`;\n const existing = inFlight.get(key);\n if (existing) return existing;\n if (inFlight.size >= MAX_INFLIGHT) return Promise.resolve(null);\n\n const task = extractSurface(name, version, fetchOpts)\n .then(async (extracted) => {\n // Best-effort write: a database at its size limit must not turn a\n // successful extraction into a failed read.\n if (extracted) await upsertSurface(db, name, version, extracted).catch(() => {});\n return extracted;\n })\n .catch(() => null)\n .finally(() => inFlight.delete(key));\n\n inFlight.set(key, task);\n return task;\n}\n\n/**\n * The API surface for `name@version` from cache, or extract-and-store on a miss.\n * Returns null when types can't be resolved (caller falls back to README).\n * Cache-forever: versions are immutable.\n */\nexport async function getOrExtractSurface(\n db: Database,\n name: string,\n version: string,\n opts: SurfaceLookupOptions = {},\n): Promise<ExportSymbol[] | null> {\n const stored = await getStoredSurface(db, name, version);\n if (stored) return stored;\n if (opts.budgetMs === 0) return null;\n\n // A budget means a caller is waiting on a request path, which is also what\n // justifies the tighter fetch ceiling; the unbudgeted worker keeps the http\n // defaults so a slow-but-working CDN still yields a surface.\n const fetchOpts = opts.fetch ?? (opts.budgetMs === undefined ? {} : READ_PATH_FETCH);\n const task = extractOnce(db, name, version, fetchOpts);\n return opts.budgetMs === undefined ? task : withBudget(task, opts.budgetMs);\n}\n\n/** Test-only: drop memoized in-flight extractions. */\nexport function resetSurfaceInflight(): void {\n inFlight.clear();\n}\n","/** Read/write helpers for sandbox verification results (`verification_runs`). */\nimport { desc, eq } from 'drizzle-orm';\nimport type { Database } from './client';\nimport {\n verificationRuns,\n type NewVerificationRunRow,\n type VerificationRunRow,\n} from './schema';\n\nexport async function storeVerificationRun(\n db: Database,\n run: NewVerificationRunRow,\n): Promise<void> {\n await db.insert(verificationRuns).values(run);\n}\n\n/** Most recent run for a package (any version), if any — for the evaluate verdict. */\nexport async function getLatestVerificationByName(\n db: Database,\n packageName: string,\n): Promise<VerificationRunRow | null> {\n const rows = await db\n .select()\n .from(verificationRuns)\n .where(eq(verificationRuns.packageName, packageName))\n .orderBy(desc(verificationRuns.ranAt))\n .limit(1);\n return rows[0] ?? null;\n}\n","{\n \"moment\": {\n \"replacedBy\": \"dayjs\",\n \"reason\": \"In maintenance mode since 2020 (the maintainers recommend alternatives). dayjs is a ~2KB immutable library with a near-identical API.\"\n },\n \"request\": {\n \"replacedBy\": \"got\",\n \"reason\": \"Deprecated in 2020 and no longer maintained. Use the built-in fetch, or got for a full-featured HTTP client.\"\n },\n \"request-promise\": {\n \"replacedBy\": \"got\",\n \"reason\": \"Deprecated alongside request. got returns promises natively.\"\n },\n \"node-sass\": {\n \"replacedBy\": \"sass\",\n \"reason\": \"Deprecated; bindings break on new Node versions. sass is the Dart implementation (sass-embedded for speed).\"\n },\n \"tslint\": {\n \"replacedBy\": \"typescript-eslint\",\n \"reason\": \"Deprecated in 2019 in favor of ESLint. Use typescript-eslint to lint TypeScript.\"\n },\n \"enzyme\": {\n \"replacedBy\": \"@testing-library/react\",\n \"reason\": \"Unmaintained with no official React 17+/18 adapter. React Testing Library is the current standard.\"\n },\n \"protractor\": {\n \"replacedBy\": \"@playwright/test\",\n \"reason\": \"Reached end-of-life in 2023. Use Playwright (or Cypress) for browser E2E.\"\n },\n \"faker\": {\n \"replacedBy\": \"@faker-js/faker\",\n \"reason\": \"The original package was sabotaged and deprecated. @faker-js/faker is the community-maintained fork.\"\n },\n \"bower\": {\n \"replacedBy\": \"npm\",\n \"reason\": \"Deprecated; front-end packages ship on npm now. Use npm (or your package manager) directly.\"\n },\n \"popper.js\": {\n \"replacedBy\": \"@popperjs/core\",\n \"reason\": \"v1 is deprecated. @popperjs/core is the maintained v2 line.\"\n },\n \"create-react-app\": {\n \"replacedBy\": \"vite\",\n \"reason\": \"No longer recommended by the React team and effectively unmaintained. Vite is the current scaffolding standard.\"\n },\n \"babel-eslint\": {\n \"replacedBy\": \"@babel/eslint-parser\",\n \"reason\": \"Deprecated and renamed. Use @babel/eslint-parser.\"\n },\n \"istanbul\": {\n \"replacedBy\": \"nyc\",\n \"reason\": \"The istanbul package is legacy; nyc is its maintained CLI (or c8 for native V8 coverage).\"\n }\n}\n","/**\n * Deprecation → replacement map (§1.2). Agents confidently recommend dead\n * packages (moment, request, …) because their training data froze when those\n * were popular; lurq's freshness is exactly the corrective. This is the curated\n * seed the roadmap calls for — a small, high-confidence set of genuinely\n * superseded packages. Later this graph is learned from outcome data (§3.1);\n * for now it's hand-verified so `evaluate` never steers an agent wrong.\n */\nimport successors from '../data/successors.json';\n\nexport interface Successor {\n /** The package to migrate to. */\n name: string;\n /** Why the original is dead and this replaces it. */\n reason: string;\n}\n\nconst MAP = successors as Record<string, { replacedBy: string; reason: string }>;\n\n/**\n * Successions derived from outcome history, keyed by the superseded package.\n * Built by `buildLearnedSuccessors` and passed in rather than imported, so this\n * module stays pure and synchronous — the DB read belongs to the caller.\n */\nexport type LearnedSuccessors = Map<string, Successor>;\n\n/**\n * The recommended successor for a superseded package, or null if it isn't one.\n *\n * The curated map wins every collision. It is hand-verified, and the learned\n * layer is a statistical read of what other people did — when the two disagree\n * about a package we have deliberately checked, the check is worth more than the\n * crowd. Learned entries exist to cover the ecosystem the curated 13 never will,\n * not to overrule them.\n */\nexport function lookupSuccessor(name: string, learned?: LearnedSuccessors): Successor | null {\n const key = name.toLowerCase();\n const curated = MAP[key];\n if (curated) return { name: curated.replacedBy, reason: curated.reason };\n return learned?.get(key) ?? null;\n}\n\n/**\n * Shape observed successions into successor entries.\n *\n * Two guards beyond the owner threshold enforced in the query:\n *\n * · Only packages the index knows to be dead get a learned successor. A healthy\n * package that someone happened to swap out is a preference, not a succession,\n * and telling every agent that React \"was replaced by\" something because three\n * teams changed their minds is exactly the false authority this map must not\n * acquire.\n * · One winner per superseded package — the most-observed. Reporting a tie as\n * two successors gives an agent a choice it has no basis to make.\n */\nexport function buildLearnedSuccessors(\n observed: { from: string; to: string; owners: number; observations: number }[],\n isSuperseded: (name: string) => boolean,\n): LearnedSuccessors {\n const best = new Map<string, { to: string; owners: number; observations: number }>();\n\n for (const row of observed) {\n if (!isSuperseded(row.from)) continue;\n const key = row.from.toLowerCase();\n const current = best.get(key);\n // Owners first, observations as the tiebreak: breadth of agreement is\n // harder to manufacture than volume from a few accounts.\n const better =\n !current ||\n row.owners > current.owners ||\n (row.owners === current.owners && row.observations > current.observations);\n if (better) best.set(key, { to: row.to, owners: row.owners, observations: row.observations });\n }\n\n return new Map(\n [...best].map(([from, hit]) => [\n from,\n {\n name: hit.to,\n reason: `${hit.owners} teams moved here after ${from} failed for the same need`,\n },\n ]),\n );\n}\n","/** Read/write helpers for recommendation→outcome capture (`recommendation_outcomes`, §3.1). */\nimport { and, count, desc, eq, inArray, sql } from 'drizzle-orm';\nimport { DEFAULT_ECOSYSTEM } from '../core/types';\nimport { alias } from 'drizzle-orm/pg-core';\nimport { buildLearnedSuccessors, type LearnedSuccessors } from '../core/successors';\nimport type { FieldEvidence } from '../scoring/score';\nimport type { Database } from './client';\nimport {\n packages,\n recommendationOutcomes,\n type NewRecommendationOutcomeRow,\n type RecommendationOutcomeRow,\n} from './schema';\n\n/** Record one opt-in outcome. Insert-only — the dataset is append-only by design. */\nexport async function recordOutcome(\n db: Database,\n outcome: NewRecommendationOutcomeRow,\n): Promise<void> {\n await db.insert(recommendationOutcomes).values(outcome);\n}\n\n/**\n * A report counts as a success when the agent kept the package AND it did not\n * fail to build. `build_signal IS NULL` is a report with no build stage attached\n * — an acceptance on its own — and counts, because the alternative is treating\n * \"didn't say\" as \"broke\".\n */\nconst SUCCESS_PREDICATE = sql`${recommendationOutcomes.accepted} AND (${recommendationOutcomes.buildSignal} IS NULL OR ${recommendationOutcomes.buildSignal} <> 'failed')`;\n\n/**\n * Aggregate field evidence per package (§3.1) — the read side of the flywheel.\n *\n * One grouped scan, never one query per package: this runs inside ingest and\n * inside the rescore sweep, and a per-package round trip would make the sweep\n * O(index size) in network calls. `recommendation_outcomes_pkg_idx` covers the\n * grouping.\n *\n * Omit `names` to aggregate every package that has any report at all. That set\n * is small — outcomes are opt-in and sparse relative to the index — which is\n * exactly why the rescore sweep can afford to refresh all of them.\n */\nexport async function getFieldEvidence(\n db: Database,\n names?: string[],\n): Promise<Map<string, FieldEvidence>> {\n if (names && names.length === 0) return new Map();\n\n const rows = await db\n .select({\n packageName: recommendationOutcomes.packageName,\n reports: count(),\n successes: sql<number>`count(*) FILTER (WHERE ${SUCCESS_PREDICATE})`.mapWith(Number),\n })\n .from(recommendationOutcomes)\n .where(names ? inArray(recommendationOutcomes.packageName, names) : undefined)\n .groupBy(recommendationOutcomes.packageName);\n\n return new Map(\n rows.map((r) => [r.packageName, { reports: Number(r.reports), successes: r.successes }]),\n );\n}\n\n/**\n * Minimum distinct owners before a learned succession is believed.\n *\n * One person reporting \"X failed, then Y worked\" is an anecdote, and publishing\n * it as an index-wide claim would let any single key steer what every agent\n * recommends. Three unrelated accounts converging on the same substitution is a\n * pattern. Same discipline as the shrinkage prior in scoring: the signal has to\n * survive the cheapest way to fake it.\n */\nexport const MIN_SUCCESSION_OWNERS = 3;\n\n/** A substitution observed in the field, with the evidence behind it. */\nexport interface LearnedSuccession {\n from: string;\n to: string;\n owners: number;\n observations: number;\n}\n\n/**\n * Derive successor candidates from outcome history (§3.1).\n *\n * The observation: within one owner's work on one stated need, a package that\n * FAILED followed by a different package that SUCCEEDED is a substitution. It is\n * the only place lurq sees a replacement actually chosen under real constraints\n * rather than asserted in a changelog — and it needs no new data collection,\n * because `need` and `build_signal` have been captured since report_outcome\n * shipped.\n *\n * Ordered by `created_at`, so the direction is earned rather than assumed: Y\n * replaced X only if Y came after X failed. Without that clause the join would\n * happily report X replacing Y as well.\n */\nexport async function learnSuccessions(db: Database): Promise<LearnedSuccession[]> {\n const failed = alias(recommendationOutcomes, 'failed');\n const worked = alias(recommendationOutcomes, 'worked');\n\n const rows = await db\n .select({\n from: failed.packageName,\n to: worked.packageName,\n owners: sql<number>`count(DISTINCT ${failed.ownerId})`.mapWith(Number),\n observations: sql<number>`count(*)`.mapWith(Number),\n })\n .from(failed)\n .innerJoin(\n worked,\n sql`${worked.ownerId} = ${failed.ownerId}\n AND ${worked.need} = ${failed.need}\n AND ${worked.packageName} <> ${failed.packageName}\n AND ${worked.createdAt} > ${failed.createdAt}`,\n )\n .where(\n sql`${failed.need} IS NOT NULL\n AND ${failed.ownerId} IS NOT NULL\n AND NOT (${failed.accepted} AND (${failed.buildSignal} IS NULL OR ${failed.buildSignal} <> 'failed'))\n AND (${worked.accepted} AND (${worked.buildSignal} IS NULL OR ${worked.buildSignal} <> 'failed'))`,\n )\n .groupBy(failed.packageName, worked.packageName)\n .having(sql`count(DISTINCT ${failed.ownerId}) >= ${MIN_SUCCESSION_OWNERS}`);\n\n return rows.map((r) => ({\n from: r.from,\n to: r.to,\n owners: Number(r.owners),\n observations: Number(r.observations),\n }));\n}\n\n/**\n * The learned successor map, memoised in-process.\n *\n * The underlying self-join is not cheap and the answer moves on the order of\n * hours, so recomputing it per `evaluate` would be pure waste. A per-instance\n * memo is enough: instances disagreeing for a few minutes about a successor\n * hint is invisible, and the alternative is coordinating an invalidation across\n * the fleet for a field that is advisory by nature.\n *\n * ponytail: in-process TTL, no cross-instance coherence. Move to the Redis\n * cache if the recompute cost ever shows up in latency.\n */\nconst LEARNED_TTL_MS = 10 * 60 * 1000;\nlet learnedCache: { at: number; value: LearnedSuccessors } | null = null;\n\nexport async function loadLearnedSuccessors(\n db: Database,\n now: number = Date.now(),\n): Promise<LearnedSuccessors> {\n if (learnedCache && now - learnedCache.at < LEARNED_TTL_MS) return learnedCache.value;\n\n const observed = await learnSuccessions(db);\n if (observed.length === 0) {\n learnedCache = { at: now, value: new Map() };\n return learnedCache.value;\n }\n\n // Only packages the index already knows are dead may acquire a successor —\n // see buildLearnedSuccessors. One lookup for every candidate, not one each.\n const names = [...new Set(observed.map((o) => o.from))];\n const rows = await db\n .select({ name: packages.name, deprecated: packages.deprecated, archived: packages.archived })\n .from(packages)\n .where(and(inArray(packages.name, names), eq(packages.ecosystem, DEFAULT_ECOSYSTEM)));\n const dead = new Set(rows.filter((r) => r.deprecated || r.archived).map((r) => r.name));\n\n const value = buildLearnedSuccessors(observed, (name) => dead.has(name));\n learnedCache = { at: now, value };\n return value;\n}\n\n/** Drop the memo — for tests and for the worker after an ingest sweep. */\nexport function resetLearnedSuccessors(): void {\n learnedCache = null;\n}\n\n/** One owner's outcome history, newest first — powers the dashboard activity feed. */\nexport async function getOutcomesByOwner(\n db: Database,\n ownerId: string,\n opts: { limit?: number } = {},\n): Promise<RecommendationOutcomeRow[]> {\n return db\n .select()\n .from(recommendationOutcomes)\n .where(eq(recommendationOutcomes.ownerId, ownerId))\n .orderBy(desc(recommendationOutcomes.createdAt))\n .limit(opts.limit ?? 50);\n}\n","/**\n * GitHub raw README fallback (§9.6). The npm packument `readme` field is often\n * empty (e.g. zod), so we fetch the repo README directly when needed. Public\n * raw content needs no token.\n */\nimport { CACHE_TTL } from '../../core/constants';\nimport { httpRequest } from '../../core/http';\n\nconst HOST = 'raw.githubusercontent.com';\nconst CANDIDATES = ['README.md', 'readme.md', 'README.markdown', 'README'];\n\nexport async function fetchGithubReadme(\n owner: string,\n repo: string,\n fetchImpl?: typeof fetch,\n): Promise<string | null> {\n for (const file of CANDIDATES) {\n const url = `https://${HOST}/${owner}/${repo}/HEAD/${file}`;\n try {\n const { data } = await httpRequest<string>(url, {\n host: HOST,\n ttlMs: CACHE_TTL.github,\n accept: 'text',\n retries: 0,\n fetchImpl,\n });\n if (data && data.trim().length > 0) return data;\n } catch {\n /* try the next candidate */\n }\n }\n return null;\n}\n","/**\n * Summary + usage-guide generation (§9.6 + R1 explainer refinement).\n *\n * lurq generates its OWN guide grounded in the package's README/description —\n * it never depends on Context7. When a summary LLM key is configured we use it;\n * otherwise we fall back to the npm description + a category-derived guide,\n * fabricating nothing. The exact current API is deferred to Context7 via a hint.\n */\nimport { CATEGORIES, isCategory, type Category, type UsageGuide } from '../core/types';\nimport { getConfig } from '../core/config';\nimport { httpRequest } from '../core/http';\nimport { logger } from '../core/logger';\nimport { fetchGithubReadme } from './sources/githubReadme';\nimport type { RawPackageSignals } from './types';\n\nexport interface SummaryInput {\n name: string;\n description: string | null;\n category: Category | null;\n readme: string | null;\n repoUrl: string | null;\n}\n\nexport interface SummaryResult {\n summary: string | null;\n usageGuide: UsageGuide;\n /** Taxonomy category the LLM classified the package into (§2A), or null\n * (always null for the fallback provider — it does no classification). */\n inferredCategory: Category | null;\n}\n\nexport interface SummaryProvider {\n readonly kind: 'openai' | 'fallback';\n generate(input: SummaryInput): Promise<SummaryResult>;\n}\n\n/** Human-readable architectural role per category (generic — lurq has no code context). */\nconst CATEGORY_ROLE: Record<string, string> = {\n framework: 'the core application framework your app is built on',\n 'meta-framework': 'the full-stack framework wrapping routing, rendering, and build',\n 'state-management': 'the client state layer shared across components',\n routing: 'the routing layer mapping URLs to views',\n orm: 'the data-access layer between your code and the database',\n 'database-client': 'the low-level driver that talks to your database',\n 'ui-component-library': 'the prebuilt UI component layer',\n styling: 'the styling layer for your components',\n forms: 'form state and submission handling',\n validation: 'input/schema validation at your boundaries',\n 'data-fetching': 'the server-state/data-fetching layer',\n 'http-client': 'the HTTP request layer for calling APIs',\n auth: 'authentication and session handling',\n testing: 'the test tooling layer',\n 'build-tool': 'the build/dev pipeline',\n bundler: 'the module bundling step',\n linting: 'code-quality and formatting checks',\n 'date-time': 'date and time handling',\n animation: 'UI animation and motion',\n charts: 'data visualization and charts',\n i18n: 'internationalization and localization',\n utility: 'a focused helper you compose into your app',\n other: 'a supporting library in your app',\n};\n\nfunction context7Hint(name: string): string {\n return `For the exact current API of \"${name}\", resolve it via Context7 (resolve-library-id → query-docs).`;\n}\n\n/** Keep text to ~`max` sentences. */\nexport function truncateSentences(text: string, max = 3): string {\n const clean = text.replace(/\\s+/g, ' ').trim();\n if (!clean) return '';\n // Match full sentences, plus a trailing fragment with no terminal punctuation\n // (so descriptions without a period return the whole text, not just the last word).\n const sentences = clean.match(/[^.!?]+[.!?]+|[^.!?]+$/g) ?? [clean];\n return sentences\n .slice(0, max)\n .map((s) => s.trim())\n .join(' ')\n .trim();\n}\n\n// ── Fallback provider (no LLM key) ──────────────────────────────────────────\n\nexport class FallbackSummaryProvider implements SummaryProvider {\n readonly kind = 'fallback' as const;\n\n async generate(input: SummaryInput): Promise<SummaryResult> {\n const description = input.description?.trim() || null;\n const role = CATEGORY_ROLE[input.category ?? 'other'] ?? CATEGORY_ROLE.other!;\n const summary = description ? truncateSentences(description, 3) : null;\n const guide: UsageGuide = {\n whatItIs: description ? truncateSentences(description, 2) : input.name,\n whenToUse: `Reach for ${input.name} when you need ${role}.`,\n whereItFits: `Sits at ${role}.`,\n context7Hint: context7Hint(input.name),\n };\n return { summary, usageGuide: guide, inferredCategory: null };\n }\n}\n\n// ── OpenAI provider (raw fetch, no SDK dependency) ──────────────────────────\n\nconst SYSTEM_PROMPT =\n 'You summarize npm packages factually for an AI coding agent choosing dependencies. ' +\n 'Use ONLY the provided README/description. Never invent capabilities or APIs. ' +\n 'Be concise and concrete. Respond with a JSON object.';\n\nfunction buildUserPrompt(input: SummaryInput): string {\n const readme = (input.readme ?? '').slice(0, 4000);\n // Ask the model to classify only when we don't already have a curated category\n // (§2A) — otherwise the curated value wins and we save the model the choice.\n const needsCategory = input.category == null;\n return [\n `Package: ${input.name}`,\n `Category: ${input.category ?? 'unknown'}`,\n `Description: ${input.description ?? '(none)'}`,\n `README (truncated):\\n${readme || '(none)'}`,\n '',\n 'Return JSON with keys:',\n '- \"summary\": 2-3 sentences: what it is, when to use it, how it fits an app.',\n '- \"whatItIs\": one sentence.',\n '- \"whenToUse\": one sentence on the ideal use case.',\n '- \"whenNotToUse\": one sentence on when to pick something else (or \"\").',\n '- \"whereItFits\": one sentence on its architectural role.',\n '- \"howToWireIn\": one short sentence on the minimal setup (install + entry point), or \"\".',\n ...(needsCategory\n ? [`- \"category\": the single best fit from this list: ${CATEGORIES.join(', ')}.`]\n : []),\n ].join('\\n');\n}\n\nexport class OpenAISummaryProvider implements SummaryProvider {\n readonly kind = 'openai' as const;\n\n private readonly endpoint: string;\n private readonly host: string;\n\n constructor(\n private readonly apiKey: string,\n private readonly model: string,\n baseUrl: string,\n private readonly fetchImpl?: typeof fetch,\n ) {\n this.endpoint = `${baseUrl.replace(/\\/$/, '')}/chat/completions`;\n this.host = new URL(baseUrl).host;\n }\n\n async generate(input: SummaryInput): Promise<SummaryResult> {\n try {\n const body = JSON.stringify({\n model: this.model,\n messages: [\n { role: 'system', content: SYSTEM_PROMPT },\n { role: 'user', content: buildUserPrompt(input) },\n ],\n response_format: { type: 'json_object' },\n temperature: 0.2,\n });\n const { data } = await httpRequest<any>(this.endpoint, {\n host: this.host,\n method: 'POST',\n ttlMs: 30 * 24 * 60 * 60 * 1000, // cache summaries 30d to control cost\n cacheKey: `openai-summary ${this.model} ${input.name} ${(input.readme ?? '').length}`,\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n 'Content-Type': 'application/json',\n },\n body,\n fetchImpl: this.fetchImpl,\n });\n const content = data?.choices?.[0]?.message?.content;\n const parsed = content ? JSON.parse(content) : {};\n const guide: UsageGuide = {\n whatItIs: str(parsed.whatItIs) || input.name,\n whenToUse: str(parsed.whenToUse),\n whenNotToUse: str(parsed.whenNotToUse) || undefined,\n whereItFits: str(parsed.whereItFits),\n howToWireIn: str(parsed.howToWireIn) || undefined,\n context7Hint: context7Hint(input.name),\n };\n const rawCategory = str(parsed.category);\n const inferredCategory = rawCategory && isCategory(rawCategory) ? rawCategory : null;\n return {\n summary: str(parsed.summary) ? truncateSentences(parsed.summary, 3) : null,\n usageGuide: guide,\n inferredCategory,\n };\n } catch (err) {\n logger.warn(`summary LLM failed for ${input.name}, using fallback: ${(err as Error).message}`);\n return new FallbackSummaryProvider().generate(input);\n }\n }\n}\n\nfunction str(value: unknown): string {\n return typeof value === 'string' ? value.trim() : '';\n}\n\n// ── Factory + input assembly ────────────────────────────────────────────────\n\nexport function createSummaryProvider(fetchImpl?: typeof fetch): SummaryProvider {\n const config = getConfig();\n if (config.SUMMARY_PROVIDER === 'openai' && config.SUMMARY_API_KEY) {\n return new OpenAISummaryProvider(\n config.SUMMARY_API_KEY,\n config.SUMMARY_MODEL,\n config.SUMMARY_BASE_URL,\n fetchImpl,\n );\n }\n return new FallbackSummaryProvider();\n}\n\n/** Assemble the summary input, fetching the GitHub-raw README when npm's is empty. */\nexport async function buildSummaryInput(\n signals: RawPackageSignals,\n category: Category | null,\n fetchImpl?: typeof fetch,\n): Promise<SummaryInput> {\n const registry = signals.registry;\n let readme = registry?.readme?.trim() || null;\n if (!readme && registry?.repo) {\n readme = await fetchGithubReadme(registry.repo.owner, registry.repo.repo, fetchImpl).catch(\n () => null,\n );\n }\n return {\n name: signals.name,\n description: registry?.description ?? null,\n category,\n readme,\n repoUrl: registry?.repoUrl ?? null,\n };\n}\n","/**\n * Gather all source signals for one package (§9.7 steps 1–5). Fault-isolated:\n * each source is wrapped so a single failure records an error and degrades that\n * signal to null rather than failing the package (§17).\n */\nimport { logger } from '../core/logger';\nimport type { Category } from '../core/types';\nimport { fetchBundlephobia } from './sources/bundlephobia';\nimport { fetchDepsDev } from './sources/depsDev';\nimport { fetchGithubRepo } from './sources/github';\nimport { fetchDownloadGrowth, fetchWeeklyDownloads } from './sources/npmDownloads';\nimport { fetchNpmRegistry } from './sources/npmRegistry';\nimport type { NpmDownloadsData, RawPackageSignals } from './types';\n\nexport interface CollectDeps {\n githubToken?: string;\n fetchImpl?: typeof fetch;\n /**\n * Pre-fetched weekly downloads (from the bulk endpoint). When provided (even\n * as null), the per-package weekly fetch is skipped — avoiding the downloads\n * API's harsh rate limits during a full sync.\n */\n prefetchedWeekly?: number | null;\n}\n\nasync function attempt<T>(\n source: string,\n errors: { source: string; message: string }[],\n fn: () => Promise<T>,\n): Promise<T | null> {\n try {\n return await fn();\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n errors.push({ source, message });\n logger.debug(`[${source}] ${message}`);\n return null;\n }\n}\n\nexport async function collectSignals(\n name: string,\n category: Category | null,\n deps: CollectDeps = {},\n): Promise<RawPackageSignals> {\n const { githubToken, fetchImpl } = deps;\n const errors: { source: string; message: string }[] = [];\n\n // 1. Registry first — it provides the repo + version the other sources need.\n const registry = await attempt('npm-registry', errors, () => fetchNpmRegistry(name, fetchImpl));\n\n const repo = registry?.repo ?? null;\n const version = registry?.latestVersion ?? null;\n\n // 2–5. The rest run concurrently.\n const [downloads, github, depsDev, bundle] = await Promise.all([\n attempt('npm-downloads', errors, async (): Promise<NpmDownloadsData> => {\n const weeklyDownloads =\n deps.prefetchedWeekly !== undefined\n ? deps.prefetchedWeekly\n : await fetchWeeklyDownloads(name, fetchImpl);\n const downloadGrowth90d = await fetchDownloadGrowth(name, fetchImpl);\n return { weeklyDownloads, downloadGrowth90d };\n }),\n repo && githubToken\n ? attempt('github', errors, () => fetchGithubRepo(repo.owner, repo.repo, githubToken, fetchImpl))\n : Promise.resolve(null),\n attempt('deps-dev', errors, () => fetchDepsDev(name, version, repo, fetchImpl)),\n attempt('bundlephobia', errors, () => fetchBundlephobia(name, category, fetchImpl)),\n ]);\n\n return { name, registry, downloads, github, depsDev, bundle, errors };\n}\n","/**\n * Lightweight category inference (§11). Maps a natural-language need to a\n * taxonomy category via keyword matching. Returns null when uncertain, so the\n * caller searches across all categories rather than over-filtering.\n */\nimport type { Category } from '../core/types';\nimport type { RawPackageSignals } from '../ingestion/types';\n\nconst RULES: { category: Category; patterns: RegExp }[] = [\n { category: 'meta-framework', patterns: /\\b(meta-?framework|next\\.?js|nuxt|remix|astro|gatsby|sveltekit|full-?stack framework)\\b/ },\n { category: 'state-management', patterns: /\\b(state management|global state|store|redux|zustand|jotai|mobx|atoms?)\\b/ },\n { category: 'routing', patterns: /\\b(rout(e|er|ing)|navigation|url matching)\\b/ },\n { category: 'orm', patterns: /\\b(orm|object-?relational|query builder|prisma|drizzle|sequelize|typeorm)\\b/ },\n { category: 'database-client', patterns: /\\b(database (driver|client)|postgres|mysql|mongo(db)?|redis|sqlite|db driver)\\b/ },\n { category: 'ui-component-library', patterns: /\\b(component library|ui kit|ui components?|design system|buttons?|modal|dialog)\\b/ },\n { category: 'styling', patterns: /\\b(styl(e|ing)|css|tailwind|sass|scss|class ?names?|theme)\\b/ },\n { category: 'forms', patterns: /\\b(forms?|form (state|library|handling)|input handling)\\b/ },\n { category: 'validation', patterns: /\\b(validat(e|ion|or)|schema|parse input|type ?safe parsing)\\b/ },\n { category: 'data-fetching', patterns: /\\b(data fetching|server state|react query|swr|graphql client|caching queries)\\b/ },\n { category: 'http-client', patterns: /\\b(http client|fetch wrapper|rest client|make (a )?request|ajax|api calls?)\\b/ },\n { category: 'auth', patterns: /\\b(auth(entication|orization)?|login|session|jwt|oauth|password hashing)\\b/ },\n { category: 'testing', patterns: /\\b(test(ing|s)?|unit test|e2e|assertion|mocking|test runner)\\b/ },\n { category: 'bundler', patterns: /\\b(bundler|bundle (modules?|code)|webpack|rollup|esbuild|parcel)\\b/ },\n { category: 'build-tool', patterns: /\\b(build tool|dev server|monorepo|task runner|compile|transpile)\\b/ },\n // date-time precedes linting: \"date formatting\" must not be captured by linting's\n // bare \"formatting\" token before the date rule is reached (first-match-wins).\n { category: 'date-time', patterns: /\\b(dates?|date ?time|time(zone)?s?|calendar|parse dates?|format dates?)\\b/ },\n { category: 'linting', patterns: /\\b(lint(er|ing)?|formatter|formatting|code (quality|style|format)|prettier|eslint)\\b/ },\n { category: 'animation', patterns: /\\b(animat(e|ion)|motion|transition|spring|gsap|3d)\\b/ },\n { category: 'charts', patterns: /\\b(charts?|graphs?|data ?vis(ualization)?|plots?|dashboards?)\\b/ },\n { category: 'i18n', patterns: /\\b(i18n|internationali[sz]ation|localization|translat(e|ion)|locale)\\b/ },\n { category: 'framework', patterns: /\\b(framework|react|vue|svelte|angular|web server|backend framework)\\b/ },\n { category: 'utility', patterns: /\\b(debounce|throttle|deep ?clone|slugify|uuid|util(ity|ities)?|helper|lodash|retry)\\b/ },\n];\n\nexport function inferCategory(need: string): Category | null {\n const text = need.toLowerCase();\n for (const rule of RULES) {\n if (rule.patterns.test(text)) return rule.category;\n }\n return null;\n}\n\n/**\n * Categorize-on-ingest (§2A): infer a category from a package's *own* text —\n * name, keywords, description, and the README head — instead of a user query.\n * Keywords are repeated to give them extra weight (they're the most reliable\n * categorical signal). Returns null when no rule matches; the caller then falls\n * back to the LLM classifier or leaves the category null.\n */\nexport function inferCategoryFromSignals(signals: RawPackageSignals): Category | null {\n const r = signals.registry;\n const keywords = (r?.keywords ?? []).join(' ');\n const text = [\n signals.name,\n keywords,\n keywords, // weight keywords higher via repetition\n r?.description ?? '',\n (r?.readme ?? '').slice(0, 600),\n ]\n .filter(Boolean)\n .join(' ');\n return inferCategory(text);\n}\n","/**\n * All scoring weights and thresholds in one tunable file (§10).\n * Changing the model means editing this file only.\n */\n\n/** Composite health-score weights. Must sum to 1.0. */\nexport const HEALTH_WEIGHTS = {\n maintenance: 0.35,\n adoption: 0.3,\n reliability: 0.25,\n efficiency: 0.1,\n} as const;\n\n/**\n * Health↔Quality blend for the default composite sort (§1). Quality is a\n * standalone, adoption-independent axis — NOT a member of HEALTH_WEIGHTS. The\n * two only blend here, for ranking/sort: composite = (1−λ)·health + λ·quality.\n * λ is the single most impactful knob `edit-weights` exposes.\n */\nexport const COMPOSITE = {\n lambda: 0.35,\n} as const;\n\n/**\n * How `recommend` orders a retrieved candidate set (§3, §11).\n *\n * Three terms, because there are three different questions and the ranking used\n * to ask only two: how well does this match the need (relevance), how good is\n * it (composite), and **is there enough evidence to trust it at all**\n * (confidence).\n *\n * That third term is the one that was missing. `confidence` was computed,\n * stored, rendered, and offered as a filter — and had no effect whatsoever on\n * the default order. So on a large index, where hundreds of packages match a\n * need on text alone, a package with seventeen weekly downloads could take a\n * slot from Prisma purely by having a keyword-denser description. Measured on\n * the live index, \"an orm for postgres\" returned five packages of which none\n * was an ORM anyone uses.\n *\n * Relevance still leads: a proven package that does not answer the question is\n * not the right answer either, and the weights leave room for a genuinely\n * promising newcomer to outrank an established package it beats on fit.\n */\nexport const RANKING = {\n relevance: 0.45,\n composite: 0.35,\n confidence: 0.2,\n} as const;\n\n/**\n * Evidence tier → its contribution to the ranking's confidence term.\n *\n * Not linear across the ladder: the meaningful cliff is between \"we have\n * evidence this works at scale\" and everything else, so `proven` is worth\n * roughly double `emerging`. `promising` sits just under `emerging` rather than\n * at the bottom — it is the adoption-independent tier, and burying it would\n * undo the reason it exists (§1). `unproven` is not zeroed, so a package that\n * is the only real match for a need can still surface.\n */\nexport const CONFIDENCE_WEIGHT: Record<string, number> = {\n proven: 1,\n emerging: 0.55,\n promising: 0.45,\n unproven: 0.1,\n};\n\n/**\n * Quality sub-score component weights (of the *available* components — missing\n * signals are dropped, not zeroed, via weightedAverage). All inputs are\n * adoption-independent: they measure how well-built a package is, not how many\n * people use it.\n */\nexport const QUALITY_WEIGHTS = {\n types: 0.25,\n tests: 0.2,\n docs: 0.2,\n changelog: 0.1,\n deps: 0.1,\n license: 0.1,\n provenance: 0.05,\n} as const;\n\nexport const QUALITY = {\n /** README at/above this many characters scores full marks on doc length. */\n docsFullLengthChars: 1200,\n /** Direct-dependency count at/above this scores 0 on the deps component (log-scaled). */\n depsLogMax: 30,\n /** A license string present but not OSI-recognized scores this (vs 100 / 0). */\n licenseUnrecognizedScore: 60,\n} as const;\n\n/** Maintenance sub-score component weights (of the available components). */\nexport const MAINTENANCE_WEIGHTS = {\n recency: 0.5,\n cadence: 0.25,\n closeRatio: 0.25,\n} as const;\n\nexport const MAINTENANCE = {\n /** A release within this many days scores full recency. */\n freshDays: 30,\n /** Recency decays linearly to 0 by this many days (~24 months). */\n staleDays: 730,\n /** Releases/12mo at or above this cap full cadence. */\n cadenceCap: 12,\n /** deprecated/archived hard-cap maintenance at this value. */\n deadCap: 15,\n} as const;\n\nexport const ADOPTION = {\n /** log10(weekly downloads): this maps to 0. */\n downloadsLogMin: 1, // 10/wk\n /** log10(weekly downloads): this maps to 100. */\n downloadsLogMax: 7, // 10M/wk\n /** log10(stars) that maps to 100. */\n starsLogMax: 5, // 100k stars\n /** Weight of the stars component when available (downloads gets the rest). */\n starsWeight: 0.2,\n /** Growth bonus: growth fraction × this, clamped to ±cap. */\n growthMultiplier: 30,\n growthBonusCap: 20,\n} as const;\n\nexport const RELIABILITY = {\n /** Used when no Scorecard is available (unknown security posture). */\n neutralWhenUnknown: 50,\n /** Advisory penalties by severity. */\n penalty: {\n critical: 40,\n high: 20,\n moderate: 8,\n low: 3,\n info: 0,\n },\n} as const;\n\nexport const EFFICIENCY = {\n /** Bundle size at the category median maps to this score; smaller → higher. */\n medianScore: 50,\n} as const;\n\n/**\n * Field evidence (§3.1) — the outcome flywheel. Every other axis reads what the\n * ecosystem *says* about a package; this one reads what happened when an agent\n * actually installed it, which is the only signal here that no competitor can\n * derive from public data.\n *\n * `weight` sits OUTSIDE `HEALTH_WEIGHTS` and is added to the denominator only\n * when evidence exists. That is deliberate: the four existing weights keep\n * summing to 1.0, so a package with no reports scores exactly what it scored\n * before this shipped. A rebalance would have silently moved every score in the\n * index on deploy, and \"why did everything shift?\" is not a question worth\n * owing anyone.\n */\nexport const FIELD = {\n /** Weight when evidence exists — ~9% of the blend (0.10 / 1.10). */\n weight: 0.1,\n /**\n * Bayesian shrinkage strength: how many prior observations the neutral rate is\n * worth. One failed report out of one is not a 0-scoring package, and a raw\n * success rate would say it is. At m=12, a single failure lands near 69 rather\n * than 0, and it takes real volume to move the number far — which is the\n * correct epistemics for a signal users can trivially poison.\n */\n priorWeight: 12,\n /**\n * The prior success rate a package is assumed to have before anyone reports.\n * Set at the observed base rate of \"installs and builds fine\", not 0.5:\n * most packages do work, so 0.5 would penalise the first honest reporter.\n */\n priorRate: 0.75,\n /** Reports at or above this cap the confidence note as fully-evidenced. */\n wellEvidencedReports: 25,\n} as const;\n\n/** Proactive-discovery crawler tuning (§2B). The gate is quality-only — downloads\n * are deliberately excluded so merit, not popularity, decides what graduates. */\nexport const DISCOVERY = {\n /** A queued candidate must clear this quality pre-score to graduate to ingest. */\n minPreScore: 45,\n /** Max candidates fully ingested per crawler run (cost bound). */\n perRunCap: 25,\n /** npm-search hits to pull per category keyword. */\n searchSizePerCategory: 10,\n /** Max dependency-graph neighbors to enqueue per tracked seed. */\n graphNeighborsPerSeed: 20,\n} as const;\n\n// ── Tunable weight model: defaults ← user-config ← env (§4) ──────────────────\n\nimport { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport { projectWeightsPath, userWeightsPath } from '../core/paths';\n\n/** The user-tunable slice of the model (§4). Sub-component weights and\n * thresholds stay fixed; these are the knobs `edit-weights` exposes. */\nexport interface WeightConfig {\n health: {\n maintenance: number;\n adoption: number;\n reliability: number;\n efficiency: number;\n };\n /** Health↔Quality blend λ for the default sort composite. */\n composite: { lambda: number };\n}\n\nexport const DEFAULT_WEIGHTS: WeightConfig = {\n health: { ...HEALTH_WEIGHTS },\n composite: { ...COMPOSITE },\n};\n\nexport type WeightSource = 'defaults' | 'user-config' | 'project-config';\n\n/** Where overrides are read from, if anywhere — for `lurq weights` to report. */\nexport function activeWeightsPath(): { path: string; source: WeightSource } | null {\n if (existsSync(projectWeightsPath())) return { path: projectWeightsPath(), source: 'project-config' };\n if (existsSync(userWeightsPath())) return { path: userWeightsPath(), source: 'user-config' };\n return null;\n}\n\nlet cachedWeights: WeightConfig | undefined;\n\n/**\n * Resolve the effective weight model: defaults, overlaid by a config file\n * (project-local wins over user-level), overlaid by env (`LURQ_COMPOSITE_LAMBDA`).\n * Always returns a validated, sum-to-1 health block. Memoized; call\n * `resetWeightsCache()` after a write or in tests.\n */\nexport function loadWeights(): WeightConfig {\n if (cachedWeights) return cachedWeights;\n\n let merged: WeightConfig = structuredClone(DEFAULT_WEIGHTS);\n const active = activeWeightsPath();\n if (active) {\n try {\n const fromFile = JSON.parse(readFileSync(active.path, 'utf8')) as Partial<WeightConfig>;\n merged = mergeWeights(merged, fromFile);\n } catch {\n // A corrupt override file must never break scoring — fall back to defaults.\n }\n }\n\n const envLambda = process.env.LURQ_COMPOSITE_LAMBDA;\n if (envLambda !== undefined && envLambda !== '') {\n const n = Number(envLambda);\n if (Number.isFinite(n)) merged.composite.lambda = n;\n }\n\n cachedWeights = validateWeights(merged).weights;\n return cachedWeights;\n}\n\nexport function resetWeightsCache(): void {\n cachedWeights = undefined;\n}\n\nfunction mergeWeights(base: WeightConfig, over: Partial<WeightConfig>): WeightConfig {\n return {\n health: { ...base.health, ...(over.health ?? {}) },\n composite: { ...base.composite, ...(over.composite ?? {}) },\n };\n}\n\nexport interface WeightValidation {\n weights: WeightConfig;\n /** True if the health block was renormalized to sum to 1.0. */\n normalized: boolean;\n}\n\n/**\n * Clamp λ to [0,1] and renormalize the health block to sum to 1.0 (§4 invariant,\n * weights.ts:6). Returns the cleaned weights and whether normalization happened\n * so the CLI can report it.\n */\nexport function validateWeights(w: WeightConfig): WeightValidation {\n const lambda = Math.max(0, Math.min(1, w.composite.lambda));\n const h = w.health;\n const sum = h.maintenance + h.adoption + h.reliability + h.efficiency;\n let normalized = false;\n let health = h;\n if (sum <= 0) {\n health = { ...DEFAULT_WEIGHTS.health };\n normalized = true;\n } else if (Math.abs(sum - 1) > 1e-6) {\n health = {\n maintenance: h.maintenance / sum,\n adoption: h.adoption / sum,\n reliability: h.reliability / sum,\n efficiency: h.efficiency / sum,\n };\n normalized = true;\n }\n return { weights: { health, composite: { lambda } }, normalized };\n}\n\n/** Keys settable via `edit-weights --set` and their slot in the config. */\nconst SETTABLE: Record<string, (w: WeightConfig, v: number) => void> = {\n 'health.maintenance': (w, v) => (w.health.maintenance = v),\n 'health.adoption': (w, v) => (w.health.adoption = v),\n 'health.reliability': (w, v) => (w.health.reliability = v),\n 'health.efficiency': (w, v) => (w.health.efficiency = v),\n 'composite.lambda': (w, v) => (w.composite.lambda = v),\n};\n\nexport function settableKeys(): string[] {\n return Object.keys(SETTABLE);\n}\n\n/** Apply `key=value` overrides to a config, returning a new config. Throws on an\n * unknown key or non-numeric value. */\nexport function applyOverrides(base: WeightConfig, sets: string[]): WeightConfig {\n const next = structuredClone(base);\n for (const entry of sets) {\n const eq = entry.indexOf('=');\n if (eq < 0) throw new Error(`Invalid --set \"${entry}\" (expected key=value).`);\n const key = entry.slice(0, eq).trim();\n const value = Number(entry.slice(eq + 1).trim());\n const apply = SETTABLE[key];\n if (!apply) {\n throw new Error(`Unknown weight key \"${key}\". Settable: ${settableKeys().join(', ')}.`);\n }\n if (!Number.isFinite(value)) throw new Error(`Value for \"${key}\" must be a number.`);\n apply(next, value);\n }\n return next;\n}\n\n/** Persist a config to the override file and bust the cache. */\nexport function saveWeights(w: WeightConfig, scope: 'user' | 'project' = 'user'): string {\n const path = scope === 'project' ? projectWeightsPath() : userWeightsPath();\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, JSON.stringify(w, null, 2) + '\\n', 'utf8');\n resetWeightsCache();\n return path;\n}\n\n/** Remove any override files, restoring defaults. Returns the paths removed. */\nexport function resetWeights(): string[] {\n const removed: string[] = [];\n for (const path of [projectWeightsPath(), userWeightsPath()]) {\n if (existsSync(path)) {\n rmSync(path);\n removed.push(path);\n }\n }\n resetWeightsCache();\n return removed;\n}\n\n/** Human-readable explanation per health component / knob (§4 `--explain`). */\nexport const WEIGHT_EXPLANATIONS: Record<string, string> = {\n maintenance: 'release recency, cadence, and issue close-ratio (weights.ts MAINTENANCE_WEIGHTS).',\n adoption: 'weekly downloads (log-scaled), stars, and 90-day growth (weights.ts ADOPTION).',\n reliability: 'OpenSSF Scorecard scaled 0–100, minus advisory penalties (weights.ts RELIABILITY).',\n efficiency: 'bundle size vs the category median; frontend categories only (weights.ts EFFICIENCY).',\n quality:\n 'intrinsic, adoption-independent: types, tests, docs, changelog, deps, license, provenance (weights.ts QUALITY_WEIGHTS). A standalone axis, it does NOT feed health.',\n lambda: 'how much the default sort composite favors quality over health: (1−λ)·health + λ·quality.',\n};\n\n/** Confidence-label thresholds (§10, §1). */\nexport const CONFIDENCE = {\n proven: {\n minWeeklyDownloads: 100_000,\n minAgeMonths: 12,\n /**\n * Recency ceiling for the top tier.\n *\n * Was 6 months, which quietly punished stability. Because the stored label\n * is frozen at ingest, nothing surfaced it until confidence was re-derived\n * — at which point `p-limit` (273M weekly downloads, ten years old, last\n * release 6.2 months ago) dropped out of `proven`, along with\n * `@testing-library/react` at 6.7 months and 44M/wk. A mature utility that\n * has not needed a release is the most proven kind of package there is.\n *\n * Abandonment is already caught three other ways that do not confuse it\n * with maturity: `deprecated` and `archived` are hard-checked right here,\n * and the maintenance component of health decays to zero over 24 months\n * while carrying 35% of the health weight. Recency was the fourth penalty\n * on the same fact, and the strictest.\n */\n maxLastReleaseMonths: 18,\n },\n emerging: {\n minWeeklyDownloads: 5_000,\n strongGrowth: 0.5,\n /**\n * Absolute floor the growth path must also clear.\n *\n * Growth alone used to qualify a package for `emerging`, and a percentage\n * computed on a tiny base is noise: 4 → 17 weekly downloads is +325% and\n * cleared the bar outright. That is how `@podgres/pg` (17/wk) and\n * `@bungres/orm` (275/wk) came to wear the same evidence label as a package\n * with five thousand real installs, and — because `recommend` treats the\n * label as meaningful — outrank Prisma for \"an orm for postgres\".\n *\n * 1,000/wk is where a 50% swing stops being one CI pipeline changing its\n * schedule. Below it the growth signal is not measuring adoption.\n */\n minDownloadsForGrowth: 1_000,\n /** Same reasoning as `proven` above: 9 months demoted `@emotion/react`\n * (14.7M/wk, last release 9.2 months ago) to `unproven`. */\n maxLastReleaseMonths: 18,\n },\n /** `promising` (§1): new but intrinsically high-quality, regardless of adoption. */\n promising: {\n minQuality: 70,\n maxLastReleaseMonths: 12,\n },\n} as const;\n","/**\n * Scoring & confidence model (§10). All functions are pure and take an explicit\n * `now` for deterministic testing.\n *\n * Two-pass design: maintenance / adoption / reliability / confidence depend only\n * on a single package, so they're computed in pass 1. Efficiency needs the\n * category median bundle size (§10), so it — and the composite health score —\n * are computed in pass 2 once all packages are collected.\n */\nimport type { Advisory, Category, Confidence, ScoreBreakdown } from '../core/types';\nimport { isFrontendCategory } from '../core/types';\nimport type { RawPackageSignals } from '../ingestion/types';\nimport {\n ADOPTION,\n COMPOSITE,\n CONFIDENCE,\n EFFICIENCY,\n FIELD,\n HEALTH_WEIGHTS,\n MAINTENANCE,\n MAINTENANCE_WEIGHTS,\n QUALITY,\n QUALITY_WEIGHTS,\n RELIABILITY,\n} from './weights';\n\nexport interface ScoringInput {\n weeklyDownloads: number | null;\n downloadGrowth90d: number | null;\n stars: number | null;\n firstPublishedAt: Date | null;\n lastReleaseAt: Date | null;\n releasesLast12mo: number | null;\n openIssues: number | null;\n closedIssues: number | null;\n scorecard: number | null;\n /**\n * Dependent counts, split. Persisted now and deliberately NOT yet folded into\n * any score: the separation between chosen and inherited is measured (junk\n * median 36 direct, real-library median 1032), but how it should weigh is not,\n * and lurq has no retrieval eval to prove a weighting helps rather than just\n * moves the numbers. Collect first, score once it can be shown to work.\n */\n directDependents?: number | null;\n indirectDependents?: number | null;\n advisories: Advisory[];\n deprecated: boolean;\n archived: boolean;\n bundleMinGzipKb: number | null;\n category: Category | null;\n // ── Intrinsic-quality signals (§1), adoption-independent ──\n hasTypes: boolean | null;\n hasTestScript: boolean | null;\n readmeLength: number | null;\n hasExamples: boolean | null;\n hasHomepage: boolean | null;\n hasReleaseNotes: boolean | null;\n directDependenciesCount: number | null;\n license: string | null;\n hasProvenance: boolean | null;\n}\n\nconst DAY_MS = 24 * 60 * 60 * 1000;\nconst MONTH_MS = 30 * DAY_MS;\n\nconst clamp = (n: number, lo = 0, hi = 100): number => Math.max(lo, Math.min(hi, n));\nconst daysSince = (date: Date | null, now: Date): number | null =>\n date ? (now.getTime() - date.getTime()) / DAY_MS : null;\nconst monthsSince = (date: Date | null, now: Date): number | null =>\n date ? (now.getTime() - date.getTime()) / MONTH_MS : null;\n\n/** Build a ScoringInput from collected raw signals. */\nexport function toScoringInput(signals: RawPackageSignals, category: Category | null): ScoringInput {\n const { registry, downloads, github, depsDev, bundle } = signals;\n const readme = registry?.readme ?? null;\n return {\n weeklyDownloads: downloads?.weeklyDownloads ?? null,\n downloadGrowth90d: downloads?.downloadGrowth90d ?? null,\n stars: github?.stars ?? null,\n firstPublishedAt: registry?.firstPublishedAt ?? null,\n lastReleaseAt: github?.lastReleaseAt ?? registry?.lastReleaseAt ?? null,\n releasesLast12mo: github?.releasesLast12mo ?? null,\n openIssues: github?.openIssues ?? null,\n closedIssues: github?.closedIssues ?? null,\n scorecard: depsDev?.scorecard ?? null,\n directDependents: depsDev?.dependents?.direct ?? null,\n indirectDependents: depsDev?.dependents?.indirect ?? null,\n advisories: depsDev?.advisories ?? [],\n deprecated: registry?.deprecated ?? false,\n archived: github?.archived ?? false,\n bundleMinGzipKb: bundle?.bundleMinGzipKb ?? null,\n category,\n // Quality signals — null (not false) when the manifest itself is missing, so\n // weightedAverage drops the component rather than scoring it 0.\n hasTypes: registry ? registry.hasTypes : null,\n hasTestScript: registry ? registry.hasTestScript : null,\n readmeLength: readme !== null ? readme.length : null,\n hasExamples: readme !== null ? /```/.test(readme) : null,\n hasHomepage: registry ? registry.homepage !== null : null,\n hasReleaseNotes: github?.releasesLast12mo != null ? github.releasesLast12mo > 0 : null,\n directDependenciesCount: registry?.directDependenciesCount ?? null,\n license: registry?.license ?? null,\n hasProvenance: registry ? registry.hasProvenance : null,\n };\n}\n\n// ── Maintenance ─────────────────────────────────────────────────────────────\n\nexport function computeMaintenance(input: ScoringInput, now: Date): number {\n if (input.deprecated || input.archived) return MAINTENANCE.deadCap;\n\n const components: { value: number; weight: number }[] = [];\n\n const days = daysSince(input.lastReleaseAt, now);\n if (days !== null) {\n const recency =\n days <= MAINTENANCE.freshDays\n ? 100\n : clamp((100 * (MAINTENANCE.staleDays - days)) / (MAINTENANCE.staleDays - MAINTENANCE.freshDays));\n components.push({ value: recency, weight: MAINTENANCE_WEIGHTS.recency });\n }\n\n if (input.releasesLast12mo !== null) {\n const cadence = clamp((Math.min(input.releasesLast12mo, MAINTENANCE.cadenceCap) / MAINTENANCE.cadenceCap) * 100);\n components.push({ value: cadence, weight: MAINTENANCE_WEIGHTS.cadence });\n }\n\n if (input.openIssues !== null && input.closedIssues !== null) {\n const total = input.openIssues + input.closedIssues;\n if (total > 0) {\n components.push({ value: (input.closedIssues / total) * 100, weight: MAINTENANCE_WEIGHTS.closeRatio });\n }\n }\n\n return weightedAverage(components);\n}\n\n// ── Adoption ────────────────────────────────────────────────────────────────\n\nexport function computeAdoption(input: ScoringInput): number {\n const dl = input.weeklyDownloads ?? 0;\n const downloadsScore = clamp(\n ((Math.log10(Math.max(dl, 1)) - ADOPTION.downloadsLogMin) /\n (ADOPTION.downloadsLogMax - ADOPTION.downloadsLogMin)) *\n 100,\n );\n\n let base = downloadsScore;\n if (input.stars !== null) {\n const starsScore = clamp((Math.log10(Math.max(input.stars, 1)) / ADOPTION.starsLogMax) * 100);\n base = (1 - ADOPTION.starsWeight) * downloadsScore + ADOPTION.starsWeight * starsScore;\n }\n\n if (input.downloadGrowth90d !== null) {\n const bonus = clamp(\n input.downloadGrowth90d * ADOPTION.growthMultiplier,\n -ADOPTION.growthBonusCap,\n ADOPTION.growthBonusCap,\n );\n base += bonus;\n }\n\n return clamp(base);\n}\n\n// ── Reliability ─────────────────────────────────────────────────────────────\n\nexport function computeReliability(input: ScoringInput): number {\n const base = input.scorecard !== null ? input.scorecard * 10 : RELIABILITY.neutralWhenUnknown;\n const penalty = input.advisories.reduce(\n (sum, adv) => sum + (RELIABILITY.penalty[adv.severity] ?? 0),\n 0,\n );\n return clamp(base - penalty);\n}\n\n// ── Efficiency (pass 2 — needs the category median) ─────────────────────────\n\n/**\n * Efficiency for frontend categories: smaller-than-median bundle → higher score\n * (median maps to 50). Returns null for backend categories / missing data; the\n * null signals the composite to redistribute the efficiency weight (§10, R1).\n */\nexport function computeEfficiency(\n bundleMinGzipKb: number | null,\n category: Category | null,\n categoryMedian: number | null,\n): number | null {\n if (!isFrontendCategory(category) || bundleMinGzipKb === null || !categoryMedian || categoryMedian <= 0) {\n return null;\n }\n const ratio = bundleMinGzipKb / categoryMedian;\n return clamp(100 - ratio * EFFICIENCY.medianScore);\n}\n\n// ── Quality (pass 1 — intrinsic, adoption-independent §1) ────────────────────\n\n/** A small set of OSI-recognized SPDX license IDs (prefix-matched, case-insensitive). */\nconst RECOGNIZED_LICENSES = [\n 'mit',\n 'isc',\n 'apache-2.0',\n 'bsd-2-clause',\n 'bsd-3-clause',\n 'mpl-2.0',\n 'lgpl',\n 'gpl',\n 'agpl',\n 'unlicense',\n '0bsd',\n 'cc0-1.0',\n];\n\nexport function isRecognizedLicense(license: string | null): boolean {\n if (!license) return false;\n const id = license.trim().toLowerCase();\n return RECOGNIZED_LICENSES.some((l) => id === l || id.startsWith(l));\n}\n\n/**\n * Intrinsic-quality score (§1): how well-built a package is, independent of\n * adoption. A weighted average over the *available* components, so a missing\n * signal is dropped rather than penalized. Returns null only when no signal is\n * available at all (e.g. the registry manifest itself failed to load).\n */\nexport function computeQuality(input: ScoringInput): number | null {\n const components: { value: number; weight: number }[] = [];\n\n if (input.hasTypes !== null) {\n components.push({ value: input.hasTypes ? 100 : 0, weight: QUALITY_WEIGHTS.types });\n }\n if (input.hasTestScript !== null) {\n components.push({ value: input.hasTestScript ? 100 : 0, weight: QUALITY_WEIGHTS.tests });\n }\n if (input.readmeLength !== null || input.hasHomepage !== null) {\n const lenScore = Math.min((input.readmeLength ?? 0) / QUALITY.docsFullLengthChars, 1) * 60;\n const examples = input.hasExamples ? 25 : 0;\n const homepage = input.hasHomepage ? 15 : 0;\n components.push({ value: clamp(lenScore + examples + homepage), weight: QUALITY_WEIGHTS.docs });\n }\n if (input.hasReleaseNotes !== null) {\n components.push({ value: input.hasReleaseNotes ? 100 : 0, weight: QUALITY_WEIGHTS.changelog });\n }\n if (input.directDependenciesCount !== null) {\n const deps = input.directDependenciesCount;\n const depsScore = clamp(\n 100 - (Math.log10(deps + 1) / Math.log10(QUALITY.depsLogMax + 1)) * 100,\n );\n components.push({ value: depsScore, weight: QUALITY_WEIGHTS.deps });\n }\n if (input.license !== null) {\n components.push({\n value: isRecognizedLicense(input.license) ? 100 : QUALITY.licenseUnrecognizedScore,\n weight: QUALITY_WEIGHTS.license,\n });\n }\n // Provenance is a pure bonus — only counted when present, never penalizing.\n if (input.hasProvenance) {\n components.push({ value: 100, weight: QUALITY_WEIGHTS.provenance });\n }\n\n if (components.length === 0) return null;\n return weightedAverage(components);\n}\n\n// ── Composite ───────────────────────────────────────────────────────────────\n\n/**\n * Aggregated outcome reports for one package (§3.1). `successes` counts reports\n * the agent both kept AND that did not fail to build — see `isSuccess`.\n */\nexport interface FieldEvidence {\n reports: number;\n successes: number;\n}\n\n/**\n * Field-evidence score: the observed success rate, shrunk toward the prior by\n * `FIELD.priorWeight` pseudo-observations.\n *\n * score = 100 · (successes + m·p₀) / (reports + m)\n *\n * The shrinkage is the whole design. A raw rate makes the first report worth\n * everything — one failure would zero a package, and one success would crown an\n * unknown one — which is both statistically wrong and trivially gameable by\n * anyone holding an API key. As reports accumulate the prior washes out and the\n * number converges on the true rate, so volume, not noise, is what moves a\n * score.\n *\n * Returns `null` at zero reports rather than the prior itself: the prior is a\n * belief, not evidence, and scoring it as evidence would hand every un-reported\n * package a free 75 in an axis it has not participated in.\n */\nexport function computeFieldScore(evidence: FieldEvidence | null): number | null {\n if (!evidence || evidence.reports <= 0) return null;\n const { reports, successes } = evidence;\n const m = FIELD.priorWeight;\n return clamp(Math.round((100 * (successes + m * FIELD.priorRate)) / (reports + m)));\n}\n\n/**\n * Compose the health score, redistributing the weight of any axis that has no\n * data — `efficiency` for backend categories, `field` until someone reports.\n * Weights default to HEALTH_WEIGHTS but can be overridden (§4 rescore).\n *\n * `field` carries FIELD.weight from outside the overridable set: `edit-weights`\n * tunes the four public axes, and letting a user zero the flywheel by editing a\n * config would quietly disable the one signal that improves with use.\n */\nexport function computeHealthScore(\n breakdown: ScoreBreakdown,\n weights: typeof HEALTH_WEIGHTS | { maintenance: number; adoption: number; reliability: number; efficiency: number } = HEALTH_WEIGHTS,\n): number {\n const w = weights;\n return weightedAverage(\n [\n { value: breakdown.maintenance, weight: w.maintenance },\n { value: breakdown.adoption, weight: w.adoption },\n { value: breakdown.reliability, weight: w.reliability },\n { value: breakdown.efficiency, weight: w.efficiency },\n // `?? null` — a breakdown stored before field evidence shipped has the key\n // absent, and undefined must redistribute, not score 0.\n { value: breakdown.field ?? null, weight: FIELD.weight },\n ].filter((c): c is { value: number; weight: number } => c.value !== null),\n );\n}\n\n/**\n * Default sort composite (§1): blend the popularity-tilted health score with the\n * adoption-independent quality axis. `lambda` (default COMPOSITE.lambda) is the\n * tunable knob `edit-weights` exposes. Falls back to pure health when quality is\n * unavailable, so a missing manifest never drags a package down.\n */\nexport function computeComposite(\n healthScore: number,\n qualityScore: number | null,\n lambda: number = COMPOSITE.lambda,\n): number {\n if (qualityScore === null) return healthScore;\n return Math.round((1 - lambda) * healthScore + lambda * qualityScore);\n}\n\n// ── Confidence ──────────────────────────────────────────────────────────────\n\nexport function hasCriticalOrHighAdvisory(advisories: Advisory[]): boolean {\n return advisories.some((a) => a.severity === 'critical' || a.severity === 'high');\n}\n\nexport function computeConfidence(\n input: ScoringInput,\n now: Date,\n qualityScore: number | null = null,\n): Confidence {\n const dl = input.weeklyDownloads ?? 0;\n const ageMonths = monthsSince(input.firstPublishedAt, now);\n const lastReleaseMonths = monthsSince(input.lastReleaseAt, now);\n const growth = input.downloadGrowth90d ?? 0;\n\n const provenReleaseOk =\n lastReleaseMonths !== null && lastReleaseMonths <= CONFIDENCE.proven.maxLastReleaseMonths;\n const provenAgeOk = ageMonths !== null && ageMonths >= CONFIDENCE.proven.minAgeMonths;\n\n if (\n dl >= CONFIDENCE.proven.minWeeklyDownloads &&\n provenAgeOk &&\n provenReleaseOk &&\n !hasCriticalOrHighAdvisory(input.advisories) &&\n !input.deprecated &&\n !input.archived\n ) {\n return 'proven';\n }\n\n const emergingReleaseOk =\n lastReleaseMonths !== null && lastReleaseMonths <= CONFIDENCE.emerging.maxLastReleaseMonths;\n // Growth qualifies only above an absolute floor. A percentage on a tiny base\n // is noise, not traction — see CONFIDENCE.emerging.minDownloadsForGrowth.\n const emergingAdoptionOk =\n dl >= CONFIDENCE.emerging.minWeeklyDownloads ||\n (growth >= CONFIDENCE.emerging.strongGrowth &&\n dl >= CONFIDENCE.emerging.minDownloadsForGrowth);\n\n // `emerging` did not consider advisories at all, so a package with a critical\n // CVE could be labelled emerging and recommended on adoption alone. Every\n // other tier already excluded severe advisories; this one was the hole, and\n // it was the tier most likely to be applied to a fast-growing package nobody\n // has audited yet.\n if (\n emergingAdoptionOk &&\n emergingReleaseOk &&\n !hasCriticalOrHighAdvisory(input.advisories) &&\n !input.deprecated &&\n !input.archived\n ) {\n return 'emerging';\n }\n\n // `promising` (§1): adoption-independent — high intrinsic quality on a package\n // that hasn't yet earned adoption traction. This is how new-but-good packages\n // surface on merit instead of sinking to `unproven`.\n // A freshly published package may have no separate release date (registry and\n // GitHub both empty); fall back to first-publish recency so a new-but-good\n // package isn't locked to `unproven` — the exact case this tier targets.\n const promisingRecencyMonths = lastReleaseMonths ?? ageMonths;\n const promisingReleaseOk =\n promisingRecencyMonths !== null &&\n promisingRecencyMonths <= CONFIDENCE.promising.maxLastReleaseMonths;\n if (\n qualityScore !== null &&\n qualityScore >= CONFIDENCE.promising.minQuality &&\n promisingReleaseOk &&\n !hasCriticalOrHighAdvisory(input.advisories) &&\n !input.deprecated &&\n !input.archived\n ) {\n return 'promising';\n }\n\n return 'unproven';\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────────────\n\nfunction weightedAverage(components: { value: number; weight: number }[]): number {\n if (components.length === 0) return 0;\n const totalWeight = components.reduce((s, c) => s + c.weight, 0);\n if (totalWeight === 0) return 0;\n return Math.round(components.reduce((s, c) => s + c.value * c.weight, 0) / totalWeight);\n}\n\n/** Median of a numeric list, or null if empty. */\nexport function median(values: number[]): number | null {\n if (values.length === 0) return null;\n const sorted = [...values].sort((a, b) => a - b);\n const mid = Math.floor(sorted.length / 2);\n return sorted.length % 2 === 0 ? (sorted[mid - 1]! + sorted[mid]!) / 2 : sorted[mid]!;\n}\n","export * from './score';\nexport * from './weights';\n","/**\n * Embedding providers (§11). A pluggable interface with two implementations:\n * - OpenAI (`text-embedding-3-small`, 1536-dim) — the default when a key is set.\n * - Local deterministic embedder (no key) — a hashing bag-of-words that captures\n * lexical overlap. Crude but real: it makes `recommend` and tests work with\n * zero credentials (R1 decision). Both emit EMBEDDING_DIM-length unit vectors,\n * so the DB column and pgvector index never change.\n */\nimport { createHash } from 'node:crypto';\nimport { getConfig } from '../core/config';\nimport { EMBEDDING_DIM } from '../core/constants';\nimport { httpRequest } from '../core/http';\nimport { logger } from '../core/logger';\nimport type { Category } from '../core/types';\n\nexport interface EmbeddingProvider {\n readonly kind: 'openai' | 'local';\n readonly dimensions: number;\n /**\n * Stable identity of the vector space this provider produces (e.g.\n * `openai:text-embedding-3-small`, `local`). Stored per row so vector search\n * only compares vectors from the same space — switching providers then falls\n * back to lexical retrieval until rows are re-embedded, instead of silently\n * returning garbage from a cosine distance across incompatible spaces.\n */\n readonly id: string;\n embed(texts: string[]): Promise<number[][]>;\n}\n\n/** Normalized text blob embedded per package (§8.2). */\nexport function buildEmbeddingText(input: {\n name: string;\n category: Category | null;\n summary: string | null;\n description: string | null;\n}): string {\n const body = input.summary || input.description || '';\n return `${input.name}. ${input.category ?? ''}. ${body}`.trim();\n}\n\n// ── Local deterministic embedder ────────────────────────────────────────────\n\nfunction tokenize(text: string): string[] {\n return text\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((t) => t.length > 1);\n}\n\n/** FNV-1a 32-bit hash. */\nfunction fnv1a(str: string): number {\n let h = 0x811c9dc5;\n for (let i = 0; i < str.length; i++) {\n h ^= str.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return h >>> 0;\n}\n\nexport function localEmbed(text: string, dim = EMBEDDING_DIM): number[] {\n const vec = new Float64Array(dim);\n const tokens = tokenize(text);\n const add = (token: string, weight: number) => {\n const idx = fnv1a(token) % dim;\n const sign = fnv1a('s:' + token) & 1 ? 1 : -1;\n vec[idx]! += weight * sign;\n };\n for (const t of tokens) add(t, 1);\n for (let i = 0; i < tokens.length - 1; i++) add(`${tokens[i]} ${tokens[i + 1]}`, 0.5);\n\n // L2-normalize to a unit vector (cosine-friendly).\n let norm = 0;\n for (let i = 0; i < dim; i++) norm += vec[i]! * vec[i]!;\n norm = Math.sqrt(norm) || 1;\n const out = new Array<number>(dim);\n for (let i = 0; i < dim; i++) out[i] = vec[i]! / norm;\n return out;\n}\n\nexport class LocalEmbeddingProvider implements EmbeddingProvider {\n readonly kind = 'local' as const;\n readonly dimensions = EMBEDDING_DIM;\n readonly id = 'local';\n async embed(texts: string[]): Promise<number[][]> {\n return texts.map((t) => localEmbed(t));\n }\n}\n\n// ── OpenAI embedder ─────────────────────────────────────────────────────────\n\nconst OPENAI_BATCH = 96;\n\nexport class OpenAIEmbeddingProvider implements EmbeddingProvider {\n readonly kind = 'openai' as const;\n readonly dimensions = EMBEDDING_DIM;\n readonly id: string;\n\n private readonly endpoint: string;\n private readonly host: string;\n\n constructor(\n private readonly apiKey: string,\n private readonly model: string,\n baseUrl: string,\n private readonly fetchImpl?: typeof fetch,\n ) {\n this.id = `openai:${model}`;\n this.endpoint = `${baseUrl.replace(/\\/$/, '')}/embeddings`;\n this.host = new URL(baseUrl).host;\n }\n\n async embed(texts: string[]): Promise<number[][]> {\n const out: number[][] = [];\n for (let i = 0; i < texts.length; i += OPENAI_BATCH) {\n const batch = texts.slice(i, i + OPENAI_BATCH);\n // Pin the output dimension to the DB column width. Every text-embedding-3\n // model honors `dimensions`, so a larger model (e.g. -3-large, natively\n // 3072-dim) is projected to 1536 instead of overflowing the vector(1536)\n // column at insert time. ponytail: non-OpenAI providers may ignore\n // `dimensions`; the length check below fails loud if the space mismatches.\n const body = JSON.stringify({ model: this.model, input: batch, dimensions: EMBEDDING_DIM });\n const { data } = await httpRequest<any>(this.endpoint, {\n host: this.host,\n method: 'POST',\n ttlMs: 30 * 24 * 60 * 60 * 1000, // cache embeddings 30d to control cost\n cacheKey: `openai-embed ${this.model} ${createHash('sha256').update(body).digest('hex')}`,\n headers: { Authorization: `Bearer ${this.apiKey}`, 'Content-Type': 'application/json' },\n body,\n fetchImpl: this.fetchImpl,\n });\n const vectors: { embedding: number[]; index: number }[] = data?.data ?? [];\n vectors.sort((a, b) => a.index - b.index);\n for (const v of vectors) {\n // Fail loud on any dimension drift rather than silently storing vectors\n // that pgvector can't compare against the rest of the column.\n if (v.embedding.length !== EMBEDDING_DIM) {\n throw new Error(\n `OpenAI model ${this.model} returned ${v.embedding.length}-dim vectors; expected ${EMBEDDING_DIM}. Set EMBEDDING_MODEL to a text-embedding-3 model or update EMBEDDING_DIM.`,\n );\n }\n out.push(v.embedding);\n }\n }\n return out;\n }\n}\n\n// ── Factory ─────────────────────────────────────────────────────────────────\n\nexport function createEmbeddingProvider(fetchImpl?: typeof fetch): EmbeddingProvider {\n const config = getConfig();\n if (config.EMBEDDING_PROVIDER === 'openai' && config.EMBEDDING_API_KEY) {\n return new OpenAIEmbeddingProvider(\n config.EMBEDDING_API_KEY,\n config.EMBEDDING_MODEL,\n config.EMBEDDING_BASE_URL,\n fetchImpl,\n );\n }\n if (config.EMBEDDING_PROVIDER === 'openai' && !config.EMBEDDING_API_KEY) {\n logger.warn('EMBEDDING_API_KEY not set, falling back to the local embedder.');\n }\n return new LocalEmbeddingProvider();\n}\n","/**\n * Read/write helpers for publish alerts (`repo_alerts`).\n *\n * Same authorization rule as db/repos: every read is owner-scoped. The write is\n * not, because its caller is the registry watcher, which has no user context —\n * it derives the owner from the repo row it is writing against.\n */\nimport { and, desc, eq } from 'drizzle-orm';\nimport type { Database } from './client';\nimport { repoAlerts, type NewRepoAlertRow, type RepoAlertRow } from './schema';\n\n/** Alerts returned to the dashboard feed in one page. */\nexport const ALERT_FEED_LIMIT = 50;\n\n/**\n * Insert alerts, ignoring ones already recorded for the same repo + release.\n *\n * The conflict target is the dedup index, so a re-sync of an already-alerted\n * publish is a no-op rather than a duplicate row in someone's feed.\n */\nexport async function insertAlerts(\n db: Database,\n rows: NewRepoAlertRow[],\n): Promise<number> {\n if (rows.length === 0) return 0;\n const inserted = await db\n .insert(repoAlerts)\n .values(rows)\n .onConflictDoNothing({\n target: [repoAlerts.repoId, repoAlerts.packageName, repoAlerts.toVersion],\n })\n .returning({ id: repoAlerts.id });\n return inserted.length;\n}\n\n/** Newest first — the feed is \"what happened to my dependencies lately\". */\nexport async function listAlerts(\n db: Database,\n ownerId: string,\n limit = ALERT_FEED_LIMIT,\n): Promise<RepoAlertRow[]> {\n return db\n .select()\n .from(repoAlerts)\n .where(eq(repoAlerts.ownerId, ownerId))\n .orderBy(desc(repoAlerts.createdAt))\n .limit(Math.min(limit, ALERT_FEED_LIMIT));\n}\n\n/**\n * Drop a repo's alerts. Called from `deleteRepo`: there is no foreign key (none\n * of the dashboard tables use one), so disconnecting a repo would otherwise\n * leave its alerts orphaned in the owner's feed pointing at a repo that is gone.\n */\nexport async function deleteAlertsForRepo(\n db: Database,\n ownerId: string,\n repoId: number,\n): Promise<void> {\n await db\n .delete(repoAlerts)\n .where(and(eq(repoAlerts.ownerId, ownerId), eq(repoAlerts.repoId, repoId)));\n}\n","/**\n * Repo-autopilot types.\n *\n * Scope discipline: lurq reads *manifests*, never source. A `package.json`\n * dependency block is the minimum input needed to compute drift, and it is also\n * the most we can read without breaking the promise the rest of the product is\n * built on (\"lurq never sees your code\"). The agent that eventually edits code\n * runs in the user's own CI, on their runner — see docs/lurq-autopilot.md.\n */\nimport type { CompatConflict } from '../core/types';\n\n/** One `package.json` found in a repo. Monorepos yield several. */\nexport interface RepoManifest {\n /** Repo-relative path, e.g. `package.json` or `packages/api/package.json`. */\n path: string;\n /** Declared ranges, dependencies + devDependencies merged. */\n deps: Record<string, string>;\n}\n\n/** Where a dependency is declared. A monorepo declares the same package in\n * several workspaces, often at different ranges — and an agent editing the\n * upgrade needs the file list, not just the merged view. */\nexport interface DepDeclaration {\n /** Repo-relative manifest path. */\n path: string;\n range: string;\n}\n\n/** Per-dependency drift, computed against the lurq index. */\nexport interface DepDrift {\n name: string;\n /** Lowest range declared anywhere — the one that governs the repo's drift. */\n range: string;\n /** Every manifest declaring this package, with that manifest's own range. */\n declaredIn: DepDeclaration[];\n /** Highest indexed version the range admits — what a fresh install resolves to. */\n resolved: string | null;\n /** `packages.latest_version` at scan time. */\n latest: string | null;\n /** Major versions between `resolved` and `latest`. 0 = current. */\n majorsBehind: number;\n deprecated: boolean;\n /** Count of known advisories on the package. */\n advisories: number;\n}\n\n/** A resolved transitive dependency carrying a risk signal worth reporting. */\nexport interface TransitiveRisk {\n name: string;\n /** The exact installed version, from the resolved tree — no range guessing. */\n version: string;\n /** Latest known release, so \"how stale is this\" is answerable. */\n latest: string | null;\n /**\n * Advisories recorded against the PACKAGE, computed for its latest version and\n * NOT proven against `version`. Read it as \"this package has known\n * advisories\", never \"this install is vulnerable\" — `vulnerabilities` is the\n * field that answers the second question.\n */\n advisories: number;\n /**\n * OSV advisory ids matched to this EXACT version. An empty array is a real\n * all-clear: the package has a history, this install is not affected by it.\n *\n * `undefined` means the lookup did not complete, and must render as \"not\n * checked\" rather than as clean — same discipline as `transitive: null`. The\n * distinction matters most here, where a false all-clear is a security claim.\n */\n vulnerabilities?: string[];\n deprecated: boolean;\n /**\n * Direct dependencies whose tree pulls this in — the actual upgrade targets.\n *\n * Empty means the resolved tree carried no usable parentage, NOT that nothing\n * depends on this. Every node in a tree got there somehow, so an absence here\n * is always a gap in our data and the UI says so.\n */\n pulledInBy: string[];\n}\n\n/**\n * The resolved dependency tree beyond what `package.json` declares.\n *\n * Kept as its own block rather than folded into the direct-dependency counts,\n * because the two are fixed differently: a direct dependency you bump, a\n * transitive one you either wait for its parent or force an override. Adding\n * them together would produce a number nobody can act on.\n */\nexport interface TransitiveDrift {\n /** Total resolved npm nodes GitHub reported. */\n resolved: number;\n /** How many of those lurq has indexed — the rest carry no signal either way. */\n tracked: number;\n /** Indexed transitives whose package has known advisories. */\n advisoryPackages: number;\n /**\n * Installs OSV matched to a vulnerability at their exact resolved version —\n * the actionable count, as distinct from `advisoryPackages`, which counts\n * packages with any advisory history. The two are deliberately not merged:\n * one tells you to upgrade something, the other tells you a package has had\n * problems, and summing them would produce a number meaning neither.\n *\n * `undefined` when the OSV lookup could not complete. Never 0 in that case.\n */\n vulnerableInstalls?: number;\n /** Indexed transitives whose package is deprecated upstream. */\n deprecated: number;\n /** The worst of them, ranked. Capped — see TRANSITIVE_DETAIL_CAP. */\n risks: TransitiveRisk[];\n /** True when the tree exceeded the node cap and is therefore incomplete. */\n truncated: boolean;\n /** True when the SBOM carried usable DEPENDS_ON edges, so `pulledInBy` is\n * meaningful. False means blame paths were unavailable for the whole repo. */\n attributed: boolean;\n}\n\n/**\n * Repo-level drift summary, recomputed on every scan and stored denormalized so\n * the dashboard reads one row per repo instead of joining the whole index.\n */\nexport interface RepoDrift {\n /** Distinct dependencies declared across all manifests. */\n depsDeclared: number;\n /** How many of those lurq has indexed. The rest are `unknown` — never\n * silently counted as current (same discipline as `unverified` in\n * src/surface/upgrade.ts: not-looked-at must never read as fine). */\n depsTracked: number;\n /** Tracked deps at least one major behind. */\n majorDrift: number;\n /** Tracked deps behind at all (any semver level). */\n anyDrift: number;\n /** Tracked deps flagged deprecated upstream. */\n deprecated: number;\n /** Total advisories across tracked deps. */\n advisories: number;\n /** Per-dep detail, worst-drift first. Capped — see REPO_DRIFT_DETAIL_CAP. */\n deps: DepDrift[];\n /**\n * The resolved tree beyond the manifest. Null when the repo has no dependency\n * graph enabled — which is \"we could not look\", not \"nothing is there\", and\n * the dashboard renders the two differently.\n */\n transitive: TransitiveDrift | null;\n /**\n * Peer-dependency and engine conflicts across the tracked dependencies **at\n * their latest versions** — i.e. what breaks if the repo takes the upgrades in\n * its own migration brief. Not the state of the current install: that needs\n * each pinned version's own manifest, which is a registry read per dependency.\n *\n * `undefined` means the repo has not been scanned since this check shipped, and\n * is rendered as \"not checked\" rather than as a clean stack — same rule as\n * `transitive: null`. An empty array is a real all-clear.\n */\n conflictsAtLatest?: CompatConflict[];\n /**\n * Peer/engine conflicts in the versions the repo resolves TODAY — i.e. whether\n * this stack is broken right now, as opposed to whether the upgrades we are\n * recommending would land somewhere coherent.\n *\n * Same `undefined` discipline as `conflictsAtLatest`: absent means the repo has\n * not been scanned since this shipped and renders as \"not checked\", never as a\n * clean install. An empty array is a real all-clear.\n */\n conflictsAtCurrent?: CompatConflict[];\n}\n\n/** Per-repo autopilot policy. Set by the connect survey, edited in the dashboard. */\nexport interface RepoPolicy {\n /** Master switch. Connecting a repo does not arm it. */\n enabled: boolean;\n /**\n * Which upgrades the agent may attempt.\n * `security` — only deps with advisories\n * `blocking` — security, plus upgrades whose surface diff removes a symbol\n * the code references (the ones that break silently)\n * `all` — every drifted dependency\n */\n scope: 'security' | 'blocking' | 'all';\n /**\n * Merge the PR when the repo's own CI passes. Opt-in per repo, and it is the\n * only setting that lets lurq change a default branch. Default false, always.\n */\n autoMerge: boolean;\n}\n\nexport const DEFAULT_REPO_POLICY: RepoPolicy = {\n enabled: false,\n scope: 'blocking',\n autoMerge: false,\n};\n\n/**\n * What the CI check concluded about one upgrade, straight from `checkUpgrade`.\n * `unverified` is a first-class outcome and is never rolled into `ok` — a check\n * that could not run is not a check that passed.\n */\nexport type UpgradeSeverity = 'blocking' | 'warning' | 'ok' | 'unverified';\n\n/**\n * How far one upgrade got through the loop.\n * checked — analysed only (comment mode, or the agent step was not armed)\n * skipped — policy excluded it\n * edited — the agent changed code but the run stopped before a PR\n * pr_open — a pull request exists\n * merged — that PR landed\n * failed — the edit or the repo's own checks failed\n */\nexport type UpgradeRunStatus =\n | 'checked'\n | 'skipped'\n | 'edited'\n | 'pr_open'\n | 'merged'\n | 'failed';\n\nexport const UPGRADE_SEVERITIES: UpgradeSeverity[] = ['blocking', 'warning', 'ok', 'unverified'];\nexport const UPGRADE_RUN_STATUSES: UpgradeRunStatus[] = [\n 'checked',\n 'skipped',\n 'edited',\n 'pr_open',\n 'merged',\n 'failed',\n];\n\n/** Manifests scanned per repo. A monorepo with more workspaces than this reports\n * partial coverage rather than silently truncating — see scanRepo. */\nexport const REPO_MANIFEST_CAP = 25;\n\n/** Per-dep drift rows persisted. The summary counts are always exact; only the\n * detail list is capped, and the dashboard says so when it truncates. */\nexport const REPO_DRIFT_DETAIL_CAP = 200;\n\n/** Transitive risk rows persisted. Counts above the list stay exact. */\nexport const TRANSITIVE_DETAIL_CAP = 100;\n","/**\n * Read/write helpers for connected repositories.\n *\n * Every query is scoped by `ownerId`. That is the authorization boundary: the\n * HTTP layer authenticates the web app with the issuer secret and passes the\n * signed-in user's id, so a missing `ownerId` filter here would hand one user\n * another user's repos. There is deliberately no \"get by id\" without an owner.\n */\nimport { and, eq, sql } from 'drizzle-orm';\nimport type { Database } from './client';\nimport { deleteAlertsForRepo } from './alerts';\nimport { repos, type RepoRow } from './schema';\nimport { DEFAULT_REPO_POLICY, type RepoDrift, type RepoManifest, type RepoPolicy } from '../github/types';\n\nexport interface RepoUpsert {\n ownerId: string;\n installationId: number;\n fullName: string;\n defaultBranch: string | null;\n isPrivate: boolean;\n}\n\n/**\n * Register repos discovered from an installation.\n *\n * Idempotent, and deliberately does NOT touch `policy`, `drift`, or the scan\n * bookkeeping: re-running the connect flow (or GitHub replaying an installation\n * webhook) must never silently disarm a repo the user already configured.\n */\nexport async function upsertRepos(db: Database, rows: RepoUpsert[]): Promise<number> {\n if (rows.length === 0) return 0;\n await db\n .insert(repos)\n .values(\n rows.map((row) => ({\n ownerId: row.ownerId,\n installationId: row.installationId,\n fullName: row.fullName,\n defaultBranch: row.defaultBranch,\n isPrivate: row.isPrivate,\n policy: DEFAULT_REPO_POLICY,\n })),\n )\n .onConflictDoUpdate({\n target: [repos.ownerId, repos.fullName],\n set: {\n installationId: sql`excluded.installation_id`,\n defaultBranch: sql`excluded.default_branch`,\n isPrivate: sql`excluded.is_private`,\n },\n });\n return rows.length;\n}\n\nexport async function listRepos(db: Database, ownerId: string): Promise<RepoRow[]> {\n return db\n .select()\n .from(repos)\n .where(eq(repos.ownerId, ownerId))\n .orderBy(repos.fullName);\n}\n\n/**\n * Every connected repo, all owners. The one deliberately unscoped read — it\n * backs the nightly cron, which has no user context. Never reachable from an\n * HTTP route.\n */\nexport async function listAllRepos(db: Database): Promise<RepoRow[]> {\n return db.select().from(repos).orderBy(repos.installationId, repos.fullName);\n}\n\n/**\n * Every connected repo whose stored manifests declare `name`, across all owners.\n *\n * The other deliberately unscoped read (see `listAllRepos`): its caller is the\n * registry watcher reacting to a publish, which has no user context. Never\n * reachable from an HTTP route.\n *\n * `jsonb_exists` rather than the `?` operator: the function form is identical in\n * Postgres and does not collide with the driver's parameter placeholders. Only\n * scanned repos can match, since `manifests` is null until the first scan — an\n * unscanned repo has no declared set to compare against, which is correct.\n */\nexport async function reposDeclaring(db: Database, name: string): Promise<RepoRow[]> {\n return db\n .select()\n .from(repos)\n .where(\n sql`exists (\n select 1 from jsonb_array_elements(${repos.manifests}) as m\n where jsonb_exists(m -> 'deps', ${name})\n )`,\n );\n}\n\n/**\n * The lurq user an installation belongs to, or null when nothing links them.\n *\n * The third deliberately unscoped read, and the one that makes webhooks work:\n * GitHub tells us an installation id, never a Clerk user, so the existing rows\n * are the only mapping back to an owner. Unscoped by necessity — the caller has\n * no user context to scope by, and it returns an owner rather than any repo data.\n *\n * ponytail: the mapping lives in `repos`, so removing every repo from an\n * installation also forgets who owns it, and later webhook additions are ignored\n * until the user clicks \"Add repositories\" again. Give installations their own\n * table if that stops being an acceptable edge.\n */\nexport async function ownerForInstallation(\n db: Database,\n installationId: number,\n): Promise<string | null> {\n const rows = await db\n .select({ ownerId: repos.ownerId })\n .from(repos)\n .where(eq(repos.installationId, installationId))\n .limit(1);\n return rows[0]?.ownerId ?? null;\n}\n\n/**\n * Forget repos reachable through an installation — all of them, or just the\n * named ones. Returns how many rows went away.\n *\n * Routes every deletion through `deleteRepo` rather than issuing one bulk\n * `delete`: alerts carry no foreign key, and a bulk delete here would strand\n * them in the owner's feed pointing at rows that no longer exist.\n */\nexport async function deleteReposByInstallation(\n db: Database,\n installationId: number,\n fullNames?: string[],\n): Promise<number> {\n const only = fullNames ? new Set(fullNames) : null;\n const rows = await db\n .select({ id: repos.id, ownerId: repos.ownerId, fullName: repos.fullName })\n .from(repos)\n .where(eq(repos.installationId, installationId));\n let deleted = 0;\n for (const row of rows) {\n if (only && !only.has(row.fullName)) continue;\n if (await deleteRepo(db, row.ownerId, row.id)) deleted++;\n }\n return deleted;\n}\n\nexport async function getRepo(\n db: Database,\n ownerId: string,\n id: number,\n): Promise<RepoRow | null> {\n const rows = await db\n .select()\n .from(repos)\n .where(and(eq(repos.ownerId, ownerId), eq(repos.id, id)))\n .limit(1);\n return rows[0] ?? null;\n}\n\n/**\n * The policy governing `owner/name`, or null when this owner has not connected\n * that repo.\n *\n * Null is a first-class answer, not a failure: `upgrade-plan` runs in any\n * checkout, connected or not, and an unconnected one is simply ungoverned. The\n * caller must not substitute `DEFAULT_REPO_POLICY` here — that default has\n * `scope: 'blocking'`, so treating \"not connected\" as \"default policy\" would\n * silently narrow every unconnected workflow on deploy.\n */\nexport async function findPolicyByFullName(\n db: Database,\n ownerId: string,\n fullName: string,\n): Promise<RepoPolicy | null> {\n const rows = await db\n .select({ policy: repos.policy })\n .from(repos)\n .where(and(eq(repos.ownerId, ownerId), eq(repos.fullName, fullName)))\n .limit(1);\n return rows[0]?.policy ?? null;\n}\n\n/** Persist a successful scan. Clears `lastScanError` — see the schema comment. */\nexport async function saveScan(\n db: Database,\n id: number,\n scan: { manifests: RepoManifest[]; drift: RepoDrift; installCommand: string },\n): Promise<void> {\n await db\n .update(repos)\n .set({\n manifests: scan.manifests,\n drift: scan.drift,\n installCommand: scan.installCommand,\n lastScanAt: new Date(),\n lastScanError: null,\n })\n .where(eq(repos.id, id));\n}\n\n/**\n * Record a failed scan without discarding the last good drift numbers. Stale\n * data plus a visible error beats an empty table: the user can still see what\n * their repo looked like at the last successful read.\n */\nexport async function saveScanError(\n db: Database,\n id: number,\n message: string,\n): Promise<void> {\n await db\n .update(repos)\n .set({ lastScanAt: new Date(), lastScanError: message.slice(0, 500) })\n .where(eq(repos.id, id));\n}\n\nexport async function setRepoPolicy(\n db: Database,\n ownerId: string,\n id: number,\n policy: RepoPolicy,\n): Promise<boolean> {\n const updated = await db\n .update(repos)\n .set({ policy })\n .where(and(eq(repos.ownerId, ownerId), eq(repos.id, id)))\n .returning({ id: repos.id });\n return updated.length > 0;\n}\n\n/** Forget a repo. The GitHub App install itself is revoked on GitHub, not here. */\nexport async function deleteRepo(\n db: Database,\n ownerId: string,\n id: number,\n): Promise<boolean> {\n // Alerts first: they carry no foreign key, so leaving them would strand rows\n // in the owner's feed naming a repo that no longer exists.\n await deleteAlertsForRepo(db, ownerId, id);\n const deleted = await db\n .delete(repos)\n .where(and(eq(repos.ownerId, ownerId), eq(repos.id, id)))\n .returning({ id: repos.id });\n return deleted.length > 0;\n}\n","/**\n * Blame paths: which direct dependency pulls a transitive one in.\n *\n * Without this, a transitive advisory tells you *what* but not what to do — you\n * can see `minimist@1.2.5` is flagged and have no idea which of your own\n * dependencies is responsible. Walking the DEPENDS_ON graph upward turns that\n * into \"upgrade eslint\", which is an action.\n *\n * The whole module is written around one distinction: **\"nothing pulls this in\"\n * is never a true answer.** Every node in a resolved tree got there somehow. So\n * an empty result always means the graph could not tell us, and it is reported\n * as unattributed rather than as an absence of parents.\n */\nimport type { DependencyEdge, ResolvedDep } from './sbom';\n\n/**\n * Depth bound for the upward walk. Real npm trees nest deeply and contain\n * cycles; this caps the work per node without changing the answer for anything\n * a human would act on.\n */\nconst MAX_DEPTH = 24;\n\nexport interface AttributionIndex {\n /** True when the document carried usable DEPENDS_ON edges at all. */\n available: boolean;\n /** Direct dependency names reachable *above* a given package name. */\n parentsOf: Map<string, string[]>;\n}\n\n/**\n * Build the reverse index once per scan, then answer every risk from it.\n *\n * Done as one pass rather than a walk per risky package: a tree with thousands\n * of nodes and a hundred flagged packages would otherwise re-traverse the same\n * subgraphs a hundred times.\n */\nexport function buildAttribution(\n deps: ResolvedDep[],\n edges: DependencyEdge[],\n directNames: Set<string>,\n): AttributionIndex {\n if (edges.length === 0) return { available: false, parentsOf: new Map() };\n\n // SPDX ids are the edge vocabulary; names are what anyone can act on.\n const nameOf = new Map<string, string>();\n for (const dep of deps) {\n if (dep.spdxId) nameOf.set(dep.spdxId, dep.name);\n }\n\n // child id → parent ids. The SBOM gives parent → child; attribution walks up.\n const parentIds = new Map<string, string[]>();\n for (const edge of edges) {\n const list = parentIds.get(edge.child);\n if (list) list.push(edge.parent);\n else parentIds.set(edge.child, [edge.parent]);\n }\n\n // An SBOM whose only edges come from the document root gives every package the\n // same non-informative parent. Detect that and report it as unavailable rather\n // than attributing every transitive to a repo node nobody can upgrade.\n const informative = edges.some(\n (edge) => nameOf.has(edge.parent) && nameOf.has(edge.child),\n );\n if (!informative) return { available: false, parentsOf: new Map() };\n\n const parentsOf = new Map<string, string[]>();\n\n for (const dep of deps) {\n if (!dep.spdxId || directNames.has(dep.name)) continue;\n\n const roots = new Set<string>();\n const seen = new Set<string>([dep.spdxId]);\n let frontier = [dep.spdxId];\n\n for (let depth = 0; depth < MAX_DEPTH && frontier.length > 0; depth++) {\n const next: string[] = [];\n for (const id of frontier) {\n for (const parent of parentIds.get(id) ?? []) {\n if (seen.has(parent)) continue; // npm graphs contain cycles\n seen.add(parent);\n const parentName = nameOf.get(parent);\n if (parentName && directNames.has(parentName)) {\n // A direct dependency: stop climbing this branch. Anything above it\n // is the repo itself, which is not an upgrade target.\n roots.add(parentName);\n continue;\n }\n next.push(parent);\n }\n }\n frontier = next;\n }\n\n if (roots.size > 0) {\n parentsOf.set(dep.name, [...roots].sort());\n }\n }\n\n return { available: true, parentsOf };\n}\n","/**\n * OSV (osv.dev) — advisories matched to an EXACT installed version.\n *\n * Everywhere else lurq stores advisories against a package, computed for its\n * latest version. That is the right shape for scoring a package, and the wrong\n * shape for a resolved dependency tree: a repo running lodash@4.17.21 was being\n * told \"lodash has known advisories\" on the strength of an advisory that only\n * affects 4.17.20 and below. The honest phrasing for that data was \"packages\n * with known advisories\", never \"vulnerable installs\" — a number nobody can act\n * on, because acting on it means upgrading something already fixed.\n *\n * OSV answers the precise question directly. Rather than storing affected\n * ranges and re-implementing semver range matching per ecosystem, `querybatch`\n * takes (package, version) pairs and returns the vulnerabilities that actually\n * apply. OSV owns the matching, including the ecosystem-specific edge cases\n * (prereleases, `0.0.0-` sentinels, withdrawn advisories) that a hand-rolled\n * matcher gets wrong quietly.\n *\n * Best-effort throughout: this augments the existing package-level signal and\n * must never be able to fail a scan. On any error the caller keeps the coarser\n * answer it already had, which is why every failure path returns an empty map\n * rather than throwing.\n */\nimport { httpRequest } from '../../core/http';\n\nconst HOST = 'api.osv.dev';\nconst URL = `https://${HOST}/v1/querybatch`;\n\n/**\n * OSV accepts up to 1000 queries per batch. Chunked well under that: a resolved\n * tree for a large monorepo runs to thousands of packages, and a request that\n * large is slow enough to matter on a scheduled scan.\n */\nconst BATCH = 250;\n\n/** How many batches run at once. Enough to be quick, small enough to be polite. */\nconst CONCURRENCY = 4;\n\nexport interface VersionQuery {\n name: string;\n version: string;\n}\n\n/** `name@version` — the key both this module and its callers index by. */\nexport function installKey(name: string, version: string): string {\n return `${name}@${version}`;\n}\n\ninterface BatchResponse {\n results?: { vulns?: { id?: string }[] }[];\n}\n\n/**\n * Vulnerabilities affecting each exact (package, version).\n *\n * Returns a map keyed by `name@version` containing only the installs that are\n * actually affected — absent means \"OSV knows of nothing for this version\",\n * which is a real all-clear for the versions OSV covers.\n *\n * Callers must still treat a wholly empty result as \"could not establish\" when\n * the request failed, which is why `queryVulnerableInstalls` reports failure\n * separately rather than folding it into an empty map.\n */\nexport async function queryVulnerableInstalls(\n installs: VersionQuery[],\n fetchImpl?: typeof fetch,\n): Promise<{ affected: Map<string, string[]>; complete: boolean }> {\n const affected = new Map<string, string[]>();\n if (installs.length === 0) return { affected, complete: true };\n\n // One query per distinct install. A tree repeats the same version constantly.\n const unique = [...new Map(installs.map((i) => [installKey(i.name, i.version), i])).values()];\n\n const batches: VersionQuery[][] = [];\n for (let i = 0; i < unique.length; i += BATCH) batches.push(unique.slice(i, i + BATCH));\n\n let complete = true;\n\n // Bounded concurrency by walking a shared cursor — no queue library for what\n // is four workers over an array.\n let cursor = 0;\n const worker = async (): Promise<void> => {\n for (let i = cursor++; i < batches.length; i = cursor++) {\n const batch = batches[i]!;\n try {\n const { data } = await httpRequest<BatchResponse>(URL, {\n host: HOST,\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n queries: batch.map((q) => ({\n version: q.version,\n package: { name: q.name, ecosystem: 'npm' },\n })),\n }),\n // Uncached on purpose. The shared cache keys on the URL, and every\n // batch here posts to the same one with a different body — a cache hit\n // would answer one tree's question with another tree's vulnerabilities.\n ttlMs: 0,\n // Best-effort by contract: the caller keeps its coarser answer when\n // this fails, so exhausting the default retry ladder would only stall\n // a scheduled scan behind an outage nobody is waiting on.\n retries: 1,\n fetchImpl,\n });\n // Results are positional — index i of the response answers query i.\n // A short array means the response is not the one we asked for, so\n // aligning what did arrive would attribute vulns to the wrong package.\n const results = data?.results ?? [];\n if (results.length !== batch.length) {\n complete = false;\n continue;\n }\n results.forEach((result, j) => {\n const ids = (result?.vulns ?? [])\n .map((v) => v?.id)\n .filter((id): id is string => typeof id === 'string');\n if (ids.length === 0) return;\n const q = batch[j]!;\n affected.set(installKey(q.name, q.version), ids);\n });\n } catch {\n // One failed batch does not invalidate the others, but it does mean the\n // answer is partial — and a partial vulnerability answer that claims to\n // be complete is the failure this whole module exists to prevent.\n complete = false;\n }\n }\n };\n\n await Promise.all(Array.from({ length: Math.min(CONCURRENCY, batches.length) }, worker));\n\n return { affected, complete };\n}\n","/**\n * In-process background ingester for on-demand misses (§12.5). Keeps the heavy\n * fetch→score→embed→upsert OFF the request path: evaluate/compare/verify enqueue\n * an untracked-but-real package and return immediately (\"tracking, retry\n * shortly\"), while a bounded worker pool ingests it within seconds.\n *\n * Bounded on purpose — moving unbounded work off the request path just relocates\n * the problem. Dedup (a package already pending or in-flight is never queued\n * again) + a hard pending cap mean a flood of distinct names can't spawn\n * unbounded syncs or grow memory without limit. Process-local; each instance\n * drains its own queue. Durability is by self-heal: if the process dies with\n * work pending, the next request for that package re-enqueues it.\n */\nimport { logger } from '../core/logger';\nimport type { Database } from '../db/client';\nimport { ensureSeedEntry } from '../db/packages';\nimport type { PackageRow } from '../db/schema';\nimport { syncOnePackage } from './single';\n\nconst MAX_CONCURRENT = 3;\nconst MAX_PENDING = 500;\n\nconst pending: string[] = [];\nconst inFlight = new Set<string>();\nconst queuedNames = new Set<string>();\n/** First-requester ownerId per queued name (dashboard v1 phase 2 attribution).\n * Dedup stays keyed by name, so the first enqueue's owner is the one credited. */\nconst owners = new Map<string, string | null>();\nlet active = 0;\n\n/** Current backlog (pending + in-flight) — exposed for tests/observability. */\nexport function ingestQueueDepth(): number {\n return pending.length + inFlight.size;\n}\n\n/**\n * Wait for the backlog to clear.\n *\n * Only a ONE-SHOT process needs this. The queue's in-flight syncs hold the same\n * DB handle their caller opened, so a cron that returns from its command and\n * closes the pool pulls the floor out from under every ingest it just queued —\n * the nightly repo scan would discover hundreds of new dependencies and then\n * fail every one of them against a closed pool. The long-lived server never\n * calls this: there is nothing to wait for when the process outlives the work.\n *\n * Bounded, because a cron that cannot finish is worse than one that leaves work\n * for tomorrow. Whatever is still queued at the deadline is abandoned and the\n * next scan re-enqueues it — the same self-heal the queue already relies on for\n * a process that dies with work pending. Returns the count left behind.\n */\nexport async function drainIngestQueue(timeoutMs = 10 * 60_000): Promise<number> {\n const deadline = Date.now() + timeoutMs;\n while (ingestQueueDepth() > 0 && Date.now() < deadline) {\n await new Promise((resolve) => setTimeout(resolve, 250));\n }\n return ingestQueueDepth();\n}\n\n/** Test-only: clear all queue state. */\nexport function resetIngestQueue(): void {\n pending.length = 0;\n inFlight.clear();\n queuedNames.clear();\n owners.clear();\n active = 0;\n}\n\n/**\n * Schedule an untracked-but-real package for background ingestion. No-op if it's\n * already pending or in-flight, or if the queue is at capacity. Returns without\n * awaiting any network/DB work.\n */\nexport function enqueueIngest(\n db: Database,\n name: string,\n requestedByOwnerId: string | null = null,\n): void {\n if (queuedNames.has(name) || inFlight.has(name)) return;\n if (pending.length >= MAX_PENDING) {\n logger.warn(`ingest queue full (${MAX_PENDING}); dropping on-demand request for ${name}`);\n return;\n }\n queuedNames.add(name);\n owners.set(name, requestedByOwnerId);\n pending.push(name);\n pump(db);\n}\n\nfunction pump(db: Database): void {\n while (active < MAX_CONCURRENT && pending.length > 0) {\n const name = pending.shift()!;\n queuedNames.delete(name);\n const owner = owners.get(name) ?? null;\n owners.delete(name);\n inFlight.add(name);\n active += 1;\n void runIngest(db, name, owner).finally(() => {\n inFlight.delete(name);\n active -= 1;\n pump(db);\n });\n }\n}\n\n/**\n * Fetch→score→embed→upsert one package and, if it clears the roster-promotion\n * bar, seed it for future syncs. Returns the stored row, or null on failure.\n * Shared by the background queue and the block-on-first-touch path (§4A) so both\n * apply the same promotion rule.\n */\nexport async function runIngest(\n db: Database,\n name: string,\n requestedByOwnerId: string | null = null,\n): Promise<PackageRow | null> {\n try {\n const row = await syncOnePackage(db, name, { requestedByOwnerId });\n // Same roster-promotion bar as the old inline path: only genuinely-trackable\n // discoveries join the sync roster, so the on-demand tail can't inflate cost.\n if (row.confidence && row.confidence !== 'unproven') {\n await ensureSeedEntry(db, name, row.category).catch(() => {});\n }\n return row;\n } catch (err) {\n logger.warn(`on-demand ingest failed for ${name}: ${String(err)}`);\n return null;\n }\n}\n","/**\n * Drift computation: declared ranges → how far behind this repo actually is.\n *\n * \"Behind\" is measured against what a *fresh install today* would resolve to,\n * not against the range's floor. `^6.4.0` on a package now at 6.9.2 is current,\n * not five minors behind — reporting it as drift is how a dashboard trains its\n * user to ignore it. So `resolved` is `maxSatisfying(range)` and drift is the\n * gap from there to `latest`.\n *\n * Anything the index does not know stays out of the drift counts entirely and is\n * reported as `depsDeclared - depsTracked`. Same discipline as `unverified` in\n * src/surface/upgrade.ts: a dependency we did not look at must never be counted\n * as one we found nothing wrong with.\n */\nimport { and, eq, inArray, sql } from 'drizzle-orm';\nimport semver from 'semver';\nimport { logger } from '../core/logger';\nimport type { Database } from '../db/client';\nimport { packageVersions, packages } from '../db/schema';\nimport {\n REPO_DRIFT_DETAIL_CAP,\n TRANSITIVE_DETAIL_CAP,\n type DepDeclaration,\n type DepDrift,\n type RepoDrift,\n type RepoManifest,\n type TransitiveDrift,\n type TransitiveRisk,\n} from './types';\nimport { buildAttribution } from './attribute';\nimport { installKey, queryVulnerableInstalls } from '../ingestion/sources/osv';\nimport { assembleMembers } from '../compat/members';\nimport { resolveArchitectureCompat, type CompatMember } from '../compat/peerCompat';\nimport { DEFAULT_ECOSYSTEM, type CompatConflict, type Ecosystem } from '../core/types';\nimport type { DependencyEdge, ResolvedDep } from './sbom';\n\n/** Postgres caps bind parameters; chunk the `IN` lists well under it. */\nconst NAME_CHUNK = 500;\n\ninterface IndexedPackage {\n latestVersion: string | null;\n deprecated: boolean;\n advisories: number;\n}\n\nexport interface DeclaredDep {\n /** Lowest range declared anywhere — see below. */\n range: string;\n /** Every manifest that declares it, in manifest order (root first). */\n declaredIn: DepDeclaration[];\n}\n\n/**\n * Distinct dependencies across every manifest, with where each is declared.\n *\n * `range` is the *lowest* declared range, because that is the one whose upgrade\n * is furthest away and therefore governs the repo's real drift. `declaredIn`\n * keeps every site, because reporting drift and *editing* it need different\n * views: the merged range answers \"how far behind is this repo\", the file list\n * answers \"which package.json does the agent bump\".\n */\n/**\n * `semver.minVersion`, but null instead of a throw.\n *\n * A package.json range is whatever npm accepts, which is a strictly larger\n * language than semver ranges: `latest` and other dist-tags, `*`, `workspace:*`,\n * `catalog:`, `file:../x`, `link:`, `github:owner/repo`, git URLs, and\n * `npm:alias@^1`. `semver.minVersion` throws a TypeError on every one of them.\n *\n * That throw used to escape all the way to `scanRepo`, which catches it and\n * writes `last_scan_error` — so a single `\"dep\": \"latest\"` anywhere in a repo\n * discarded that repo's entire drift result. 91 of 155 connected repos had no\n * manifests stored, reporting `Invalid comparator: latest`.\n *\n * Null is the honest answer: a dependency pinned to a dist-tag or a local path\n * has no semver floor, so it has no computable drift. It is still a real\n * dependency and still counted — it just carries no version comparison.\n */\nexport function rangeFloor(range: string): string | null {\n try {\n return semver.minVersion(range)?.version ?? null;\n } catch {\n return null;\n }\n}\n\n/** `semver.maxSatisfying`, null instead of a throw. Same reason as {@link rangeFloor}. */\nexport function bestSatisfying(versions: string[], range: string): string | null {\n try {\n return semver.maxSatisfying(versions, range, { includePrerelease: false });\n } catch {\n return null;\n }\n}\n\nexport function declaredDeps(manifests: RepoManifest[]): Map<string, DeclaredDep> {\n const out = new Map<string, DeclaredDep>();\n for (const manifest of manifests) {\n for (const [name, range] of Object.entries(manifest.deps)) {\n const existing = out.get(name);\n if (!existing) {\n out.set(name, { range, declaredIn: [{ path: manifest.path, range }] });\n continue;\n }\n existing.declaredIn.push({ path: manifest.path, range });\n // A range with no semver floor cannot be compared, so it cannot win the\n // \"lowest declared range\" contest — but it must not throw either.\n const current = rangeFloor(existing.range);\n const candidate = rangeFloor(range);\n if (current && candidate && semver.lt(candidate, current)) existing.range = range;\n }\n }\n return out;\n}\n\nasync function loadIndexed(\n db: Database,\n names: string[],\n ecosystem: Ecosystem = DEFAULT_ECOSYSTEM,\n): Promise<Map<string, IndexedPackage>> {\n const out = new Map<string, IndexedPackage>();\n for (let i = 0; i < names.length; i += NAME_CHUNK) {\n const rows = await db\n .select({\n name: packages.name,\n latestVersion: packages.latestVersion,\n deprecated: packages.deprecated,\n advisories: packages.advisories,\n })\n .from(packages)\n .where(\n and(\n inArray(packages.name, names.slice(i, i + NAME_CHUNK)),\n eq(packages.ecosystem, ecosystem),\n ),\n );\n for (const row of rows) {\n out.set(row.name, {\n latestVersion: row.latestVersion,\n deprecated: row.deprecated,\n advisories: row.advisories?.length ?? 0,\n });\n }\n }\n return out;\n}\n\n/**\n * Versions the index knows for each name, so `maxSatisfying` answers what a real\n * install would pick rather than assuming the range's floor.\n *\n * Deliberately one query per chunk of names rather than per name: a repo with\n * 300 dependencies would otherwise open 300 round trips per scan.\n */\nexport async function loadVersions(\n db: Database,\n names: string[],\n): Promise<Map<string, string[]>> {\n const out = new Map<string, string[]>();\n for (let i = 0; i < names.length; i += NAME_CHUNK) {\n const rows = await db\n .select({ name: packageVersions.packageName, version: packageVersions.version })\n .from(packageVersions)\n .where(inArray(packageVersions.packageName, names.slice(i, i + NAME_CHUNK)));\n for (const row of rows) {\n const list = out.get(row.name);\n if (list) list.push(row.version);\n else out.set(row.name, [row.version]);\n }\n }\n return out;\n}\n\n/** Pure drift math for one dependency — the part worth testing in isolation. */\nexport function depDrift(\n name: string,\n declared: DeclaredDep,\n indexed: IndexedPackage,\n knownVersions: string[],\n): DepDrift {\n const { range } = declared;\n const latest = indexed.latestVersion;\n // `maxSatisfying` needs the candidate list; when the index has no timeline yet,\n // fall back to the range's own floor rather than reporting no drift at all.\n const resolved = bestSatisfying(knownVersions, range) ?? rangeFloor(range);\n\n let majorsBehind = 0;\n if (resolved && latest && semver.valid(resolved) && semver.valid(latest)) {\n majorsBehind = Math.max(0, semver.major(latest) - semver.major(resolved));\n }\n\n return {\n name,\n range,\n declaredIn: declared.declaredIn,\n resolved,\n latest,\n majorsBehind,\n deprecated: indexed.deprecated,\n advisories: indexed.advisories,\n };\n}\n\n/** True when `resolved` is behind `latest` at any semver level. */\nfunction isBehind(dep: DepDrift): boolean {\n if (!dep.resolved || !dep.latest) return false;\n if (!semver.valid(dep.resolved) || !semver.valid(dep.latest)) return false;\n return semver.lt(dep.resolved, dep.latest);\n}\n\n/**\n * Rank worst-first so the capped detail list keeps what matters: an advisory\n * outranks a major bump, which outranks a deprecation notice, which outranks a\n * minor. The summary counts above the list are always exact regardless of the cap.\n */\nfunction severity(dep: DepDrift): number {\n return (\n dep.advisories * 1000 +\n dep.majorsBehind * 100 +\n (dep.deprecated ? 50 : 0) +\n (isBehind(dep) ? 1 : 0)\n );\n}\n\n/**\n * Risk in the resolved tree, excluding what the manifest already declares.\n *\n * Deliberately reports *presence of advisories on the package*, not \"vulnerable\n * install\": lurq stores advisories without affected-version ranges, so claiming\n * a specific resolved version is affected would be an inference we cannot back.\n * `advisoryPackages` is named for what it actually counts.\n */\nexport async function computeTransitiveDrift(\n db: Database,\n resolved: ResolvedDep[],\n directNames: Set<string>,\n truncated: boolean,\n edges: DependencyEdge[] = [],\n): Promise<TransitiveDrift> {\n const transitives = resolved.filter((dep) => !directNames.has(dep.name));\n const attribution = buildAttribution(resolved, edges, directNames);\n const empty: TransitiveDrift = {\n resolved: transitives.length,\n tracked: 0,\n advisoryPackages: 0,\n deprecated: 0,\n risks: [],\n truncated,\n attributed: attribution.available,\n };\n if (transitives.length === 0) return empty;\n\n const indexed = await loadIndexed(db, [...new Set(transitives.map((d) => d.name))]);\n\n // Which of these EXACT installs is actually vulnerable. `row.advisories` is a\n // package-level count computed for the latest version, so on its own it says\n // \"this package has had advisories\", not \"yours is affected\" — and a tree full\n // of already-patched versions reads as a tree full of risk.\n const { affected, complete } = await queryVulnerableInstalls(\n transitives.map((d) => ({ name: d.name, version: d.version })),\n );\n\n const risks: TransitiveRisk[] = [];\n let tracked = 0;\n for (const dep of transitives) {\n const row = indexed.get(dep.name);\n if (!row) continue; // untracked, no signal either way, never counted as clean\n tracked++;\n const vulnIds = affected.get(installKey(dep.name, dep.version)) ?? [];\n if (row.advisories === 0 && !row.deprecated && vulnIds.length === 0) continue;\n risks.push({\n name: dep.name,\n version: dep.version,\n latest: row.latestVersion,\n advisories: row.advisories,\n deprecated: row.deprecated,\n // Empty when OSV cleared this version, which is the actionable difference\n // from `advisories`: the package has a history, this install does not.\n // Undefined when the lookup could not complete — never an empty array,\n // which would read as a clean bill of health nobody established.\n vulnerabilities: complete ? vulnIds : undefined,\n pulledInBy: attribution.parentsOf.get(dep.name) ?? [],\n });\n }\n\n // Advisories outrank deprecation: one is a security signal, the other is a\n // maintenance one, and a capped list should keep the former.\n risks.sort(\n (a, b) =>\n b.advisories - a.advisories ||\n Number(b.deprecated) - Number(a.deprecated) ||\n a.name.localeCompare(b.name),\n );\n\n return {\n resolved: transitives.length,\n tracked,\n advisoryPackages: risks.filter((r) => r.advisories > 0).length,\n // The number that can actually be acted on: installs OSV matched to a\n // vulnerability at their exact version. Undefined when the lookup did not\n // complete, so \"not checked\" never renders as zero.\n vulnerableInstalls: complete ? risks.filter((r) => r.vulnerabilities?.length).length : undefined,\n deprecated: risks.filter((r) => r.deprecated).length,\n risks: risks.slice(0, TRANSITIVE_DETAIL_CAP),\n truncated,\n attributed: attribution.available,\n };\n}\n\n/**\n * Peer/engine conflicts across the repo's tracked dependencies, evaluated at the\n * versions the index calls latest.\n *\n * Names are passed without pins on purpose. `assembleMembers` reads peers and\n * engines straight from the index for an unpinned name, so this costs one query;\n * pinning each dependency to its *resolved* version would instead fetch that\n * exact manifest from npm, one request per dependency, on every nightly scan of\n * every repo. The unpinned question is also the more useful one here — the\n * dashboard's job is to say whether the upgrades it is recommending land on a\n * stack that holds together.\n *\n * Capped like `deps`, and for a sharper reason. `resolveArchitectureCompat` emits\n * one conflict per PAIR of requirers of the same unpinned peer, so its output is\n * quadratic in that group's size. Its other caller is `compat`, which passes 2-5\n * packages; a repo passes every tracked direct dependency, and fifty plugins\n * disagreeing about one uninstalled peer is 1,225 rows. This result is persisted\n * whole into the `drift` JSONB column and re-served on every dashboard load, so\n * an unbounded array here is unbounded storage and an unbounded response.\n *\n * Its counterpart is `conflictsAtCurrent`, which asks the same question of the\n * versions the repo runs today. The two are kept separate because they answer\n * different things and a reader must not confuse them: this one is \"will the\n * upgrades we are recommending land somewhere coherent\", the other is \"is this\n * repo broken right now\".\n */\nasync function conflictsAtLatest(\n db: Database,\n names: string[],\n): Promise<CompatConflict[]> {\n if (names.length === 0) return [];\n const { members } = await assembleMembers(db, names);\n return resolveArchitectureCompat(members).slice(0, REPO_DRIFT_DETAIL_CAP);\n}\n\n/**\n * Peer/engine conflicts at the versions the repo actually resolves TODAY.\n *\n * Without this a repo could read entirely clean while being broken on disk:\n * every conflict lurq reported was about versions the repo had not installed\n * yet. \"Your upgrades are coherent\" is a useful sentence, but it is not the one\n * someone debugging a failing install needs.\n *\n * One indexed read over `package_versions`, which now carries each version's own\n * peers and engines — lifted from the registry document at ingest, where every\n * version's manifest already sits in the same payload the timeline came from.\n * That is what makes this affordable: the earlier note deferred this work until\n * the per-dependency registry read could be amortised, and storing the column\n * removes the read entirely rather than amortising it.\n *\n * A dependency whose resolved version is not in the index contributes nothing\n * rather than falling back to its latest — silently substituting a version the\n * repo does not run would produce conflicts about a stack nobody has.\n */\nasync function conflictsAtCurrent(\n db: Database,\n deps: DepDrift[],\n): Promise<CompatConflict[]> {\n const pinned = deps.filter((d): d is DepDrift & { resolved: string } => Boolean(d.resolved));\n if (pinned.length === 0) return [];\n\n const rows = await db\n .select({\n packageName: packageVersions.packageName,\n version: packageVersions.version,\n peerDependencies: packageVersions.peerDependencies,\n engines: packageVersions.engines,\n })\n .from(packageVersions)\n .where(\n inArray(\n sql`(${packageVersions.packageName}, ${packageVersions.version})`,\n pinned.map((d) => sql`(${d.name}, ${d.resolved})`),\n ),\n );\n\n const members: CompatMember[] = rows.map((r) => ({\n name: r.packageName,\n version: r.version,\n peerDependencies: r.peerDependencies,\n peerDependenciesMeta: null,\n engines: r.engines,\n }));\n\n return resolveArchitectureCompat(members).slice(0, REPO_DRIFT_DETAIL_CAP);\n}\n\n/**\n * Send every untracked declared dependency to the background ingester.\n *\n * This is the fix for the coverage asymmetry that makes a scan read \"9 tracked,\n * 36 unknown\": the index only ever held packages somebody had already asked\n * about, so a repo full of ordinary dependencies had nothing to diff against.\n * Feeding the misses back means the next scan of this repo is complete, and\n * across every connected repo the index converges on the set that actually\n * matters — what people really depend on — rather than what a seed list guessed.\n *\n * Fire-and-forget on purpose. `enqueueIngest` dedupes and is hard-capped, so a\n * flood drops its overflow with a warning and the following scan re-enqueues it;\n * nothing here can slow, block, or fail the scan that triggered it.\n *\n * Imported dynamically to break a real module cycle — ingestQueue → single →\n * github/alerts → github/drift. Nothing is lost by deferring it: the enqueue has\n * no return value and the caller never waits on it.\n *\n * ponytail: direct dependencies only. A resolved tree carries thousands of\n * transitives and would starve the queue of the names the dashboard actually\n * renders. Also no negative cache — a repo's private `@acme/*` packages will\n * miss on npm and be retried each scan, which costs one cached registry lookup\n * apiece. Add one if internal-heavy repos make that measurable.\n */\nfunction queueUntracked(db: Database, names: string[], ownerId: string | null): void {\n if (names.length === 0) return;\n void import('../pipeline/ingestQueue')\n .then(({ enqueueIngest }) => {\n for (const name of names) enqueueIngest(db, name, ownerId);\n })\n .catch((err) => {\n // Ingestion is an optimisation for the next scan; this one still reports.\n logger.debug(`untracked-dep enqueue failed: ${String(err)}`);\n });\n}\n\n/** Compute a repo's full drift summary from its manifests. */\nexport async function computeDrift(\n db: Database,\n manifests: RepoManifest[],\n resolvedTree: { deps: ResolvedDep[]; edges: DependencyEdge[]; truncated: boolean } | null = null,\n requestedByOwnerId: string | null = null,\n): Promise<RepoDrift> {\n const declared = declaredDeps(manifests);\n const names = [...declared.keys()];\n const directNames = new Set(names);\n const transitive = resolvedTree\n ? await computeTransitiveDrift(\n db,\n resolvedTree.deps,\n directNames,\n resolvedTree.truncated,\n resolvedTree.edges,\n )\n : null;\n\n if (names.length === 0) {\n return {\n depsDeclared: 0,\n depsTracked: 0,\n majorDrift: 0,\n anyDrift: 0,\n deprecated: 0,\n advisories: 0,\n deps: [],\n transitive,\n conflictsAtLatest: [],\n conflictsAtCurrent: [],\n };\n }\n\n const [indexed, versions] = await Promise.all([\n loadIndexed(db, names),\n loadVersions(db, names),\n ]);\n\n // Everything the index has never seen. Queue it now so the NEXT scan of this\n // repo can report on it instead of counting it as unknown.\n queueUntracked(\n db,\n names.filter((name) => !indexed.has(name)),\n requestedByOwnerId,\n );\n\n const deps: DepDrift[] = [];\n for (const [name, entry] of declared) {\n const row = indexed.get(name);\n if (!row) continue; // untracked, counted via depsDeclared - depsTracked\n deps.push(depDrift(name, entry, row, versions.get(name) ?? []));\n }\n\n deps.sort((a, b) => severity(b) - severity(a) || a.name.localeCompare(b.name));\n\n // Tracked names only. An untracked one would send `assembleMembers` to the npm\n // registry for its manifest, turning a one-query check into one request per\n // unindexed dependency on every scan.\n const [conflicts, currentConflicts] = await Promise.all([\n conflictsAtLatest(db, deps.map((d) => d.name)),\n conflictsAtCurrent(db, deps),\n ]);\n\n return {\n depsDeclared: declared.size,\n depsTracked: deps.length,\n majorDrift: deps.filter((d) => d.majorsBehind > 0).length,\n anyDrift: deps.filter(isBehind).length,\n deprecated: deps.filter((d) => d.deprecated).length,\n advisories: deps.reduce((sum, d) => sum + d.advisories, 0),\n deps: deps.slice(0, REPO_DRIFT_DETAIL_CAP),\n transitive,\n conflictsAtLatest: conflicts,\n conflictsAtCurrent: currentConflicts,\n };\n}\n","/**\n * Publish alerts: a breaking release lands, and the repos that depend on it hear\n * about it now rather than at the next nightly scan.\n *\n * lurq already learns of a publish within seconds — the `_changes` follower\n * re-syncs any tracked package the registry touches (src/pipeline/watch.ts) — and\n * it already knows which connected repos declare that package, because the last\n * scan stored their manifests. Those two facts never met: drift was recomputed on\n * a 24h cron and acted on by a weekly CI job, so a major that shipped on Tuesday\n * reached the repo up to a week later. This module is the join.\n *\n * Scope discipline, same as everywhere else in the repo autopilot: an alert is\n * computed from `repos.manifests` and the package row. No GitHub call, no source\n * read, no clone. That is not only a privacy property — it is what makes the\n * fan-out safe, because a package with a thousand dependents publishing is one\n * indexed query and one bulk insert, not a thousand API requests.\n *\n * What is deliberately NOT alerted on:\n * · minor and patch releases — that is drift, and the dashboard already has it;\n * · new advisories and deprecations — Dependabot and the nightly scan both\n * cover those, and duplicating them here would make the feed noise.\n * A new major is the one event that is (a) genuinely breaking, (b) invisible\n * until someone reads a changelog, and (c) something lurq can already narrow to\n * \"which exports actually disappear\" via the migration brief.\n */\nimport semver from 'semver';\nimport { logger } from '../core/logger';\nimport { insertAlerts } from '../db/alerts';\nimport type { Database } from '../db/client';\nimport { reposDeclaring } from '../db/repos';\nimport type { NewRepoAlertRow, RepoRow } from '../db/schema';\nimport { declaredDeps } from './drift';\n\n/** The subset of a package row that decides whether a publish is alertable. */\nexport interface PackageLatest {\n latestVersion: string | null;\n}\n\n/**\n * Did this sync move the package onto a new major?\n *\n * Returns the new version, or null. Null for a first-ever sync (no `before`),\n * because a package lurq has only just indexed has not \"shipped a breaking\n * change\" from anyone's point of view — it has simply appeared.\n *\n * Guarded against going backwards: the registry can hand back an older `latest`\n * during a deprecation or an unpublish, and reporting that as a major release\n * would fire an alert telling people to upgrade to a version behind the one they\n * were already warned about.\n */\nexport function newMajorRelease(\n before: PackageLatest | null | undefined,\n after: PackageLatest,\n): string | null {\n const from = before?.latestVersion;\n const to = after.latestVersion;\n if (!from || !to) return null;\n if (!semver.valid(from) || !semver.valid(to)) return null;\n if (semver.lte(to, from)) return null;\n return semver.major(to) > semver.major(from) ? to : null;\n}\n\n/**\n * The alert one repo gets for one release, or null if the repo does not declare\n * the package after all.\n *\n * `inRange` is the field that earns this feature its place next to the drift\n * numbers. A repo pinned `^18` is now one major behind — bad, but static, and the\n * dashboard would have said so tomorrow. A repo on `*` or `>=18` is not behind at\n * all: its next clean install picks the new major up on its own, and no drift\n * figure anywhere expresses that. Those are different emergencies and the row\n * records which one it is.\n */\nexport function draftAlert(\n repo: RepoRow,\n packageName: string,\n toVersion: string,\n): NewRepoAlertRow | null {\n const declared = declaredDeps(repo.manifests ?? []).get(packageName);\n if (!declared) return null;\n\n // What the last scan measured this repo as resolving to. Read from the stored\n // drift rather than recomputed: the detail list is capped, so a miss here means\n // \"not in the top N drifted deps\", which is a gap in our data and is recorded\n // as null rather than filled in with the range's floor.\n const fromVersion = repo.drift?.deps.find((d) => d.name === packageName)?.resolved ?? null;\n\n return {\n ownerId: repo.ownerId,\n repoId: repo.id,\n repoFullName: repo.fullName,\n packageName,\n range: declared.range,\n fromVersion,\n toVersion,\n // `satisfies` throws on the non-semver ranges npm accepts (`latest`,\n // `workspace:*`, `file:../x`), and this runs off the publish feed — one such\n // dependency would take down alerting for that release across every repo.\n //\n // False means \"we could not establish that this range admits the new\n // version\", not \"it is safe\". Same discipline as everywhere else here: not\n // knowing is never evidence.\n inRange: semver.validRange(declared.range)\n ? semver.satisfies(toVersion, declared.range, { includePrerelease: false })\n : false,\n };\n}\n\n/**\n * Fan a publish out to every connected repo that depends on the package.\n *\n * Best-effort by contract: the caller is an ingestion path, and failing to write\n * a notification must never fail the package sync that produced it. Returns how\n * many alerts were newly recorded, which is what the watcher logs.\n */\nexport async function emitPublishAlerts(\n db: Database,\n name: string,\n before: PackageLatest | null | undefined,\n after: PackageLatest,\n): Promise<number> {\n const toVersion = newMajorRelease(before, after);\n if (!toVersion) return 0;\n\n try {\n const affected = await reposDeclaring(db, name);\n if (affected.length === 0) return 0;\n\n const rows = affected\n .map((repo) => draftAlert(repo, name, toVersion))\n .filter((row): row is NewRepoAlertRow => row !== null);\n\n const written = await insertAlerts(db, rows);\n if (written > 0) {\n logger.info(`alerts: ${name}@${toVersion} is a new major, notified ${written} repo(s)`);\n }\n return written;\n } catch (err) {\n logger.warn(`alerts: could not fan out ${name}@${toVersion}: ${(err as Error).message}`);\n return 0;\n }\n}\n","/**\n * Where a package is meant to run.\n *\n * The taxonomy has one `framework` category, so `framework` alone cannot tell\n * Express from React, and the diagram used to resolve that with a hand-written\n * set of six backend framework names. That set is wrong by construction: it\n * degrades every time the ecosystem ships a new server framework, and the\n * failure is silent — an unlisted one gets drawn in the Presentation layer as\n * though it rendered UI.\n *\n * This replaces the name list with a signal derived from each package's own\n * manifest, so a framework published tomorrow classifies correctly without\n * anyone editing lurq. The curated overrides remain, but as a correction layer\n * over a generalising classifier rather than as the whole mechanism — the same\n * shape as the curated-vs-learned successor map.\n *\n * Returns `null` rather than guessing. An unplaceable package belongs in the\n * diagram's explicit `Unclassified` bucket; inventing a layer for it is how a\n * reference architecture quietly becomes fiction.\n */\n\nexport type RuntimeTarget = 'browser' | 'node';\n\n/**\n * Keywords that only make sense for something serving requests. Deliberately\n * excludes the genuinely ambiguous ones — `web`, `app`, `framework`, `json` —\n * which appear on both sides and would classify React as a server.\n */\nconst SERVER_KEYWORDS = new Set([\n 'server',\n 'http-server',\n 'backend',\n 'middleware',\n 'rest',\n 'restful',\n 'api',\n 'router',\n 'routing',\n 'orm',\n 'database',\n 'sql',\n 'graphql-server',\n 'microservice',\n 'websocket',\n 'rpc',\n]);\n\n/** Keywords that only make sense for something running in a document. */\nconst BROWSER_KEYWORDS = new Set([\n 'react',\n 'vue',\n 'svelte',\n 'angular',\n 'preact',\n 'solid',\n 'dom',\n 'browser',\n 'component',\n 'components',\n 'ui',\n 'css',\n 'styling',\n 'animation',\n 'frontend',\n 'client-side',\n 'jsx',\n 'hooks',\n]);\n\n/**\n * Peer dependencies that settle it: a package peering on a renderer is drawn by\n * that renderer, whatever its keywords claim.\n */\nconst RENDERER_PEERS = new Set(['react', 'react-dom', 'vue', 'svelte', '@angular/core', 'preact']);\n\n/**\n * Packages whose manifests do not describe them well enough, corrected by hand.\n *\n * Kept small and treated as a correction, not a mechanism. Anything added here\n * is an admission that the classifier missed, so the list growing is a signal to\n * fix the rules above rather than to keep appending.\n */\nconst OVERRIDES: Record<string, RuntimeTarget> = {\n express: 'node',\n fastify: 'node',\n koa: 'node',\n hono: 'node',\n '@nestjs/core': 'node',\n '@hapi/hapi': 'node',\n // Meta-frameworks run in both places; they are the server in an architecture\n // diagram, which is the question this answers.\n next: 'node',\n nuxt: 'node',\n '@remix-run/node': 'node',\n astro: 'node',\n};\n\nexport interface RuntimeTargetInput {\n name: string;\n /** The manifest declares a `browser` field — it ships a browser build. */\n hasBrowserField: boolean;\n keywords: string[];\n engines: Record<string, string> | null;\n peerDependencies: Record<string, string> | null;\n}\n\nexport function classifyRuntimeTarget(input: RuntimeTargetInput): RuntimeTarget | null {\n const override = OVERRIDES[input.name.toLowerCase()];\n if (override) return override;\n\n // A renderer peer is the strongest signal available and outranks keywords: a\n // component library tagged `api` is still drawn by React.\n const peers = Object.keys(input.peerDependencies ?? {});\n if (peers.some((p) => RENDERER_PEERS.has(p))) return 'browser';\n\n const keywords = input.keywords.map((k) => k.toLowerCase());\n const server = keywords.filter((k) => SERVER_KEYWORDS.has(k)).length;\n const browser = keywords.filter((k) => BROWSER_KEYWORDS.has(k)).length;\n\n // A `browser` field is proof the package ships a browser build, but plenty of\n // isomorphic libraries ship one too — so it breaks ties rather than deciding.\n if (browser > server) return 'browser';\n if (server > browser) return 'node';\n if (input.hasBrowserField) return 'browser';\n\n // Last resort: declaring a node engine and nothing browser-shaped at all.\n // Weak on its own, which is why it runs only after everything else tied at zero.\n if (input.engines?.node && !input.hasBrowserField && browser === 0) return 'node';\n\n return null;\n}\n","/**\n * `lurq sync` pipeline (§9.7). End-to-end ingestion for the seed list (or one\n * package): collect signals → score → summarize → upsert, recording a sync_runs\n * row. Idempotent, concurrent, and tolerant of individual source failures (§17).\n *\n * Two-pass for efficiency (§10): pass 1 collects + scores everything that's\n * per-package; then category medians are computed; pass 2 finalizes efficiency\n * and the composite health score. Embeddings are added in M4.\n */\nimport { invalidateCache } from '../core/cache';\nimport { getConfig } from '../core/config';\nimport { pMap } from '../core/concurrency';\nimport { setCacheBypassRead } from '../core/http';\nimport { logger } from '../core/logger';\nimport { classifyRuntimeTarget } from '../core/runtimeTarget';\nimport type { Category, CategorySource, ScoreBreakdown } from '../core/types';\nimport { collectSignals } from '../ingestion/collect';\nimport { fetchBulkWeeklyDownloads } from '../ingestion/sources/npmDownloads';\nimport { buildSummaryInput, createSummaryProvider } from '../ingestion/summarize';\nimport { inferCategoryFromSignals } from '../search/categoryInference';\nimport { buildEmbeddingText, createEmbeddingProvider } from '../search/embeddings';\nimport type { RawPackageSignals } from '../ingestion/types';\nimport {\n computeAdoption,\n computeConfidence,\n computeEfficiency,\n computeHealthScore,\n computeMaintenance,\n computeQuality,\n computeReliability,\n median,\n toScoringInput,\n type ScoringInput,\n} from '../scoring';\nimport { createDb, type Database } from '../db/client';\nimport {\n finishSyncRun,\n getSeedTargets,\n getStaleRefreshTargets,\n latestVersionsFor,\n startSyncRun,\n upsertPackage,\n upsertPackageVersions,\n} from '../db/packages';\nimport { emitPublishAlerts } from '../github/alerts';\nimport { isFrontendCategory } from '../core/types';\nimport type { NewPackageRow, SyncError } from '../db/schema';\n\nexport interface SyncOptions {\n full?: boolean;\n packageName?: string;\n}\n\nexport interface SyncSummary {\n seen: number;\n updated: number;\n errors: number;\n status: 'success' | 'partial' | 'failed';\n}\n\ninterface Target {\n name: string;\n category: Category | null;\n}\n\n/** Per-package state carried from pass 1 to pass 2. */\ninterface Computed {\n target: Target;\n /** Final resolved category (curated or inferred at ingest, §2A). */\n category: Category | null;\n categorySource: CategorySource | null;\n signals: RawPackageSignals;\n input: ScoringInput;\n maintenance: number;\n adoption: number;\n reliability: number;\n quality: number | null;\n confidence: ReturnType<typeof computeConfidence>;\n summary: string | null;\n usageGuide: NewPackageRow['usageGuide'];\n}\n\nexport async function runSync(opts: SyncOptions = {}): Promise<SyncSummary> {\n const config = getConfig();\n const now = new Date();\n if (opts.full) setCacheBypassRead(true);\n\n const handle = createDb({ max: Math.max(4, config.LURQ_SYNC_CONCURRENCY) });\n const provider = createSummaryProvider();\n logger.info(`Summary provider: ${provider.kind}`);\n if (!config.GITHUB_TOKEN) {\n logger.warn(\n 'GITHUB_TOKEN not set, GitHub signals (stars, issues, release cadence) will be ' +\n 'skipped, degrading maintenance/adoption scores. Set it for accurate scoring.',\n );\n }\n\n const runId = await startSyncRun(handle.db);\n const allErrors: SyncError[] = [];\n\n try {\n const targets = await resolveTargets(handle.db, opts, config.LURQ_SYNC_REFRESH_CAP);\n logger.info(`Syncing ${targets.length} package(s) with concurrency ${config.LURQ_SYNC_CONCURRENCY}…`);\n\n // Bulk-fetch weekly downloads up front (one call per 128 packages) to avoid\n // the downloads API rate limit that per-package bursts trigger.\n logger.info('Fetching weekly downloads in bulk…');\n const weeklyMap = await fetchBulkWeeklyDownloads(targets.map((t) => t.name));\n\n // ── Pass 1: collect + per-package scoring + summary ──────────────────────\n let done = 0;\n const computed = await pMap(\n targets,\n async (target): Promise<Computed | null> => {\n try {\n const signals = await collectSignals(target.name, target.category, {\n githubToken: config.GITHUB_TOKEN,\n prefetchedWeekly: weeklyMap.has(target.name) ? weeklyMap.get(target.name)! : undefined,\n });\n for (const e of signals.errors) allErrors.push({ package: target.name, ...e });\n\n const summaryInput = await buildSummaryInput(signals, target.category);\n const { summary, usageGuide, inferredCategory } = await provider.generate(summaryInput);\n\n // Categorize-on-ingest (§2A): curated category wins; otherwise infer\n // from the package's own text, then fall back to the LLM classifier.\n let category = target.category;\n let categorySource: CategorySource | null = target.category ? 'curated' : null;\n if (!category) {\n category = inferCategoryFromSignals(signals) ?? inferredCategory ?? null;\n categorySource = category ? 'inferred' : null;\n }\n\n const input = toScoringInput(signals, category);\n const quality = computeQuality(input);\n if (++done % 25 === 0) logger.info(` …${done}/${targets.length}`);\n return {\n target,\n category,\n categorySource,\n signals,\n input,\n maintenance: computeMaintenance(input, now),\n adoption: computeAdoption(input),\n reliability: computeReliability(input),\n quality,\n confidence: computeConfidence(input, now, quality),\n summary,\n usageGuide,\n };\n } catch (err) {\n allErrors.push({\n package: target.name,\n source: 'pipeline',\n message: err instanceof Error ? err.message : String(err),\n });\n return null;\n }\n },\n config.LURQ_SYNC_CONCURRENCY,\n );\n\n const ok = computed.filter((c): c is Computed => c !== null);\n\n // ── Category medians for efficiency (§10) ────────────────────────────────\n const medians = computeCategoryMedians(ok);\n\n // ── Embeddings (§11): embed the normalized text blob for each package ─────\n const embProvider = createEmbeddingProvider();\n logger.info(`Embedding provider: ${embProvider.kind}`);\n const embeddings = await embProvider.embed(\n ok.map((c) =>\n buildEmbeddingText({\n name: c.target.name,\n category: c.category,\n summary: c.summary,\n description: c.signals.registry?.description ?? null,\n }),\n ),\n );\n\n // ── Pass 2: efficiency + composite + upsert ──────────────────────────────\n //\n // Snapshot what the index currently calls `latest` before the upsert below\n // overwrites it. That \"before\" is the only way to tell a re-sync of a known\n // version from a package that has just shipped a new major, which is what\n // `emitPublishAlerts` notifies connected repos about. One query for the whole\n // pass, and it must be read *before* the loop, not inside it.\n const priorLatest = await latestVersionsFor(handle.db, ok.map((c) => c.target.name));\n let updated = 0;\n for (let i = 0; i < ok.length; i++) {\n const c = ok[i]!;\n const efficiency = computeEfficiency(\n c.input.bundleMinGzipKb,\n c.category,\n c.category ? (medians.get(c.category) ?? null) : null,\n );\n const breakdown: ScoreBreakdown = {\n maintenance: c.maintenance,\n adoption: c.adoption,\n reliability: c.reliability,\n efficiency,\n quality: c.quality,\n };\n const healthScore = computeHealthScore(breakdown);\n await upsertPackage(\n handle.db,\n assemblePackageRow({\n name: c.target.name,\n category: c.category,\n categorySource: c.categorySource,\n signals: c.signals,\n input: c.input,\n summary: c.summary,\n usageGuide: c.usageGuide,\n confidence: c.confidence,\n breakdown,\n healthScore,\n qualityScore: c.quality,\n embedding: embeddings[i] ?? null,\n embeddingProvider: embProvider.id,\n now,\n }),\n );\n // Record the version timeline. The on-demand path (pipeline/single.ts)\n // has always done this; the sync pass never did, so every package whose\n // only route into the index is the nightly cron — which is the entire\n // seed list — had a package row and no history behind it. Measured on\n // production before this line existed: 220 tracked packages with zero\n // versions, including react, chalk, commander, lodash, eslint and\n // esbuild, and 15 of the 100 most-installed packages in the index.\n //\n // Everything version-shaped reads that table, so the absence was not\n // quiet: the drift board's \"N% of packages have broken\" is computed over\n // a set that could not contain them, and `compat`, `usage` and the whole\n // upgrade path have nothing to say about a package with no timeline.\n //\n // Failure is logged rather than swallowed. single.ts catches this into a\n // bare `() => {}` — right that a history write must not fail a sync,\n // wrong that it should do so in silence, which is the other half of why\n // this went unnoticed.\n await upsertPackageVersions(\n handle.db,\n c.target.name,\n c.signals.registry?.versionTimeline ?? [],\n ).catch((err: unknown) => {\n logger.warn(`version timeline write failed for ${c.target.name}: ${String(err)}`);\n });\n // Tell the repos that depend on this package if the release it just picked\n // up is a new major. Cheap by construction: this returns immediately unless\n // the major actually moved, so a sync of 5,000 unchanged packages costs 5,000\n // version comparisons and no queries.\n await emitPublishAlerts(\n handle.db,\n c.target.name,\n { latestVersion: priorLatest.get(c.target.name) ?? null },\n { latestVersion: c.signals.registry?.latestVersion ?? null },\n );\n updated++;\n }\n\n // Compat edges are no longer mined here. A pairwise expansion of every\n // ingested closure was writing ~5.9M rows a day to answer a question the\n // set-level resolver now answers directly, about the exact versions asked\n // for rather than whatever a third party's tree happened to pin.\n\n const status: SyncSummary['status'] =\n updated === 0 ? 'failed' : allErrors.length > 0 ? 'partial' : 'success';\n await finishSyncRun(handle.db, runId, {\n packagesSeen: targets.length,\n packagesUpdated: updated,\n errors: allErrors,\n status,\n });\n\n logger.info(`Sync ${status}: ${updated}/${targets.length} updated, ${allErrors.length} source errors.`);\n // The index changed — drop cached reads so the next query sees fresh scores.\n if (updated > 0) await invalidateCache();\n return { seen: targets.length, updated, errors: allErrors.length, status };\n } catch (err) {\n await finishSyncRun(handle.db, runId, {\n packagesSeen: 0,\n packagesUpdated: 0,\n errors: [{ package: '*', source: 'pipeline', message: (err as Error).message }],\n status: 'failed',\n });\n throw err;\n } finally {\n if (opts.full) setCacheBypassRead(false);\n await handle.close();\n }\n}\n\n/**\n * Seeds every run, plus a rotation of the stalest discovered packages. Seeds are\n * ~9% of the index; syncing only those left the other ~91% frozen at their\n * ingest date (and, via `latest_version`, stalled discovery — see\n * `getStaleRefreshTargets`).\n */\nasync function resolveTargets(\n db: Database,\n opts: SyncOptions,\n refreshCap: number,\n): Promise<Target[]> {\n const seeds = await getSeedTargets(db);\n if (opts.packageName) {\n const found = seeds.find((s) => s.name === opts.packageName);\n return [{ name: opts.packageName, category: found?.category ?? null }];\n }\n const refresh = await getStaleRefreshTargets(db, refreshCap);\n logger.info(`Targets: ${seeds.length} seed(s) + ${refresh.length} stale refresh(es).`);\n return [...seeds, ...refresh];\n}\n\nfunction computeCategoryMedians(computed: Computed[]): Map<Category, number> {\n const byCategory = new Map<Category, number[]>();\n for (const c of computed) {\n const cat = c.category;\n const kb = c.input.bundleMinGzipKb;\n if (cat && isFrontendCategory(cat) && kb !== null) {\n const list = byCategory.get(cat) ?? [];\n list.push(kb);\n byCategory.set(cat, list);\n }\n }\n const medians = new Map<Category, number>();\n for (const [cat, list] of byCategory) {\n const m = median(list);\n if (m !== null) medians.set(cat, m);\n }\n return medians;\n}\n\n/** Assemble a fully-scored package row. Shared by the bulk sync and the\n * on-demand single-package path (§12.5). */\nexport function assemblePackageRow(p: {\n name: string;\n category: Category | null;\n categorySource: CategorySource | null;\n signals: RawPackageSignals;\n input: ScoringInput;\n summary: string | null;\n usageGuide: NewPackageRow['usageGuide'];\n confidence: NewPackageRow['confidence'];\n breakdown: ScoreBreakdown;\n healthScore: number;\n qualityScore: number | null;\n embedding: number[] | null;\n embeddingProvider: string | null;\n now: Date;\n}): NewPackageRow {\n const r = p.signals.registry;\n return {\n name: p.name,\n ecosystem: 'npm',\n category: p.category,\n categorySource: p.categorySource,\n description: r?.description ?? null,\n summary: p.summary,\n repoUrl: r?.repoUrl ?? null,\n homepage: r?.homepage ?? null,\n latestVersion: r?.latestVersion ?? null,\n license: r?.license ?? null,\n deprecated: p.input.deprecated,\n archived: p.input.archived,\n firstPublishedAt: p.input.firstPublishedAt,\n lastReleaseAt: p.input.lastReleaseAt,\n weeklyDownloads: p.input.weeklyDownloads,\n downloadGrowth90d: p.input.downloadGrowth90d,\n stars: p.input.stars,\n openIssues: p.input.openIssues,\n closedIssues: p.input.closedIssues,\n scorecard: p.input.scorecard,\n directDependents: p.input.directDependents ?? null,\n indirectDependents: p.input.indirectDependents ?? null,\n bundleMinGzipKb: p.input.bundleMinGzipKb,\n advisories: p.input.advisories,\n peerDependencies: r?.peerDependencies ?? null,\n peerDependenciesMeta: r?.peerDependenciesMeta ?? null,\n engines: r?.engines ?? null,\n runtimeTarget: r\n ? classifyRuntimeTarget({\n name: p.name,\n hasBrowserField: r.hasBrowserField,\n keywords: r.keywords,\n engines: r.engines,\n peerDependencies: r.peerDependencies,\n })\n : null,\n healthScore: p.healthScore,\n qualityScore: p.qualityScore,\n confidence: p.confidence,\n scoreBreakdown: p.breakdown,\n usageGuide: p.usageGuide,\n embedding: p.embedding,\n embeddingProvider: p.embedding ? p.embeddingProvider : null,\n dataAsOf: p.now,\n };\n}\n","/**\n * Single-package ingestion + the on-demand path (§12.5). When a queried package\n * isn't tracked but exists on npm, lurq fetches, scores, embeds, stores, and\n * returns it — organically growing coverage beyond the seed list.\n */\nimport { and, eq, isNotNull, sql } from 'drizzle-orm';\nimport { withBudget } from '../core/concurrency';\nimport { getConfig } from '../core/config';\nimport { logger } from '../core/logger';\nimport type { Category, CategorySource, ScoreBreakdown } from '../core/types';\nimport { collectSignals } from '../ingestion/collect';\nimport { fetchWeeklyDownloads, npmPackageExists } from '../ingestion/sources';\nimport { buildSummaryInput, createSummaryProvider } from '../ingestion/summarize';\nimport { inferCategoryFromSignals } from '../search/categoryInference';\nimport {\n computeAdoption,\n computeConfidence,\n computeEfficiency,\n computeFieldScore,\n computeHealthScore,\n computeMaintenance,\n computeQuality,\n computeReliability,\n toScoringInput,\n} from '../scoring';\nimport { buildEmbeddingText, createEmbeddingProvider } from '../search/embeddings';\nimport type { Database } from '../db/client';\nimport { getFieldEvidence } from '../db/outcomes';\nimport {\n getPackageByName,\n stampFirstRequester,\n upsertPackage,\n upsertPackageVersions,\n} from '../db/packages';\nimport { packages, seedPackages, type PackageRow } from '../db/schema';\nimport { emitPublishAlerts } from '../github/alerts';\nimport { assemblePackageRow } from './sync';\n// Safe module cycle: ingestQueue imports syncOnePackage from here, but both\n// bindings are used only at call time, never at module-eval, so ESM resolves it.\nimport { enqueueIngest, runIngest } from './ingestQueue';\n\n/** Block-on-first-touch budget for single-package tools (§4A). Past this the\n * in-flight ingest keeps running in the background and the caller gets the\n * \"retry shortly\" hint instead of a stalled request. */\nexport const FIRST_TOUCH_BUDGET_MS = 4000;\n\nasync function getSeedCategory(db: Database, name: string): Promise<Category | null> {\n const [row] = await db\n .select({ category: seedPackages.category })\n .from(seedPackages)\n .where(eq(seedPackages.name, name))\n .limit(1);\n return row?.category ?? null;\n}\n\n/** Median bundle size across already-tracked packages in a category (for efficiency). */\nasync function getCategoryMedianBundle(db: Database, category: Category): Promise<number | null> {\n const [row] = await db\n .select({\n m: sql<number | null>`percentile_cont(0.5) within group (order by ${packages.bundleMinGzipKb})`,\n })\n .from(packages)\n .where(and(eq(packages.category, category), isNotNull(packages.bundleMinGzipKb)));\n return row?.m ?? null;\n}\n\n/** Fetch, score, embed, and upsert a single package; returns the stored row. */\nexport async function syncOnePackage(\n db: Database,\n name: string,\n opts: { category?: Category | null; requestedByOwnerId?: string | null } = {},\n): Promise<PackageRow> {\n const config = getConfig();\n const now = new Date();\n\n const existing = await getPackageByName(db, name);\n // The curated category (from a manual arg or the seed list) wins. We resolve\n // the final category *after* ingest so a discovered package can be classified\n // from its own text rather than stored as a second-class `null` (§2A).\n const curatedCategory = opts.category ?? (await getSeedCategory(db, name)) ?? null;\n const initialCategory = curatedCategory ?? existing?.category ?? null;\n\n const prefetchedWeekly = await fetchWeeklyDownloads(name).catch(() => null);\n const signals = await collectSignals(name, initialCategory, {\n githubToken: config.GITHUB_TOKEN,\n prefetchedWeekly,\n });\n\n const summaryInput = await buildSummaryInput(signals, initialCategory);\n const { summary, usageGuide, inferredCategory } =\n await createSummaryProvider().generate(summaryInput);\n\n let category: Category | null;\n let categorySource: CategorySource | null;\n if (curatedCategory) {\n category = curatedCategory;\n categorySource = 'curated';\n } else if (existing?.category) {\n category = existing.category;\n categorySource = existing.categorySource ?? 'inferred';\n } else {\n category = inferCategoryFromSignals(signals) ?? inferredCategory ?? null;\n categorySource = category ? 'inferred' : null;\n }\n\n const input = toScoringInput(signals, category);\n\n const median = category ? await getCategoryMedianBundle(db, category) : null;\n const quality = computeQuality(input);\n const evidence = await getFieldEvidence(db, [name]);\n const breakdown: ScoreBreakdown = {\n maintenance: computeMaintenance(input, now),\n adoption: computeAdoption(input),\n reliability: computeReliability(input),\n efficiency: computeEfficiency(input.bundleMinGzipKb, category, median),\n quality,\n field: computeFieldScore(evidence.get(name) ?? null),\n };\n const healthScore = computeHealthScore(breakdown);\n const confidence = computeConfidence(input, now, quality);\n\n const embProvider = createEmbeddingProvider();\n const [embedding] = await embProvider.embed([\n buildEmbeddingText({ name, category, summary, description: signals.registry?.description ?? null }),\n ]);\n\n await upsertPackage(\n db,\n assemblePackageRow({\n name,\n category,\n categorySource,\n signals,\n input,\n summary,\n usageGuide,\n confidence,\n breakdown,\n healthScore,\n qualityScore: quality,\n embedding: embedding ?? null,\n embeddingProvider: embProvider.id,\n now,\n }),\n );\n // Attribution (dashboard v1 phase 2): if this call is the one that first\n // inserted the row, credit the requesting account. Standalone + IS NULL-guarded\n // (see stampFirstRequester) so re-syncs never clobber it and concurrent\n // first-touches resolve deterministically. Best-effort — never blocks the upsert.\n if (!existing && opts.requestedByOwnerId) {\n await stampFirstRequester(db, name, opts.requestedByOwnerId).catch(() => {});\n }\n // Record the version timeline (idempotent). Non-fatal: never block a\n // successful package upsert on the version-history write.\n await upsertPackageVersions(db, name, signals.registry?.versionTimeline ?? []).catch((err) =>\n // Swallowed but no longer invisible: this is the only write to\n // package_versions in the codebase, and drift reads that table, so a\n // failure here silently zeroes drift for the package.\n logger.warn(`version timeline write failed for ${name}: ${(err as Error).message}`),\n );\n const row = (await getPackageByName(db, name))!;\n // Every path that learns of a new release goes through here — the `_changes`\n // follower, the daily re-sync, and on-demand ingest — so this is the one place\n // that can tell connected repos a breaking version just landed. `existing` is\n // the pre-sync state and is null for a first ingest, which correctly alerts\n // nobody. Best-effort inside emitPublishAlerts: a notification must never fail\n // the sync that produced it.\n await emitPublishAlerts(db, name, existing, row);\n return row;\n}\n\nexport interface GetOrFetchResult {\n row: PackageRow | null;\n /** True if the package was already in the index before this call. */\n wasTracked: boolean;\n existsOnNpm: boolean;\n /** True if a real-but-untracked package was scheduled for background\n * ingestion this call — the caller should tell the agent to retry shortly. */\n queued?: boolean;\n}\n\n/**\n * Return a tracked package, or — if it's a real npm package not yet in the index\n * (§12.5) — fetch it. Two modes:\n *\n * - Default (async): schedule background ingestion and return row=null so a\n * multi-package fan-out never blocks on one slow package.\n * - `blockMs` set (§4A block-on-first-touch): await the ingest up to a budget\n * and return the real row on the *first* call. On timeout the ingest keeps\n * running in the background and the caller gets the \"retry shortly\" hint.\n *\n * Returns existsOnNpm=false when the name isn't a real package at all.\n */\nexport async function getOrFetchPackage(\n db: Database,\n name: string,\n opts: { blockMs?: number; requestedByOwnerId?: string | null } = {},\n): Promise<GetOrFetchResult> {\n const existing = await getPackageByName(db, name);\n if (existing) return { row: existing, wasTracked: true, existsOnNpm: true };\n\n const exists = await npmPackageExists(name);\n if (!exists) return { row: null, wasTracked: false, existsOnNpm: false };\n\n if (opts.blockMs && opts.blockMs > 0) {\n // Single-package tools await the ingest so the first call returns a real row\n // instead of a placeholder that reads as failure. On timeout the started\n // ingest keeps running (not cancelled) and lands within a few more seconds.\n // ponytail: inline ingest isn't queue-bounded; single-package request rate\n // is the natural cap. Route through enqueueIngest if a flood ever appears.\n const row = await withBudget(runIngest(db, name, opts.requestedByOwnerId ?? null), opts.blockMs);\n if (row) return { row, wasTracked: false, existsOnNpm: true };\n return { row: null, wasTracked: false, existsOnNpm: true, queued: true };\n }\n\n // Real but untracked: ingest off the request path. Bounded + deduped so a\n // flood of distinct names can't spawn unbounded work (the whole point of not\n // doing it inline). Roster promotion happens in the worker, same quality bar.\n enqueueIngest(db, name, opts.requestedByOwnerId ?? null);\n return { row: null, wasTracked: false, existsOnNpm: true, queued: true };\n}\n","/**\n * Hybrid recommendation (§3, §11). Two retrievals run over the same candidate\n * table — vector cosine (semantic) and `tsvector` lexical (exact name/keyword) —\n * fused with Reciprocal Rank Fusion (RRF), then re-ranked by a blend of fused\n * relevance and the quality-aware composite (§1). Pure vector search misses\n * exact-name hits (especially the keyless local embedder); the lexical leg fixes\n * that, and RRF avoids having to normalize two incomparable score scales.\n */\nimport { and, cosineDistance, eq, inArray, isNotNull, lte, sql } from 'drizzle-orm';\nimport type { Candidate, Category, Confidence } from '../core/types';\nimport type { Database } from '../db/client';\nimport { packages } from '../db/schema';\nimport { computeComposite } from '../scoring';\nimport { CONFIDENCE_WEIGHT, RANKING, loadWeights } from '../scoring/weights';\nimport { inferCategory } from './categoryInference';\nimport { createEmbeddingProvider, type EmbeddingProvider } from './embeddings';\nimport { logger } from '../core/logger';\n\nexport interface RecommendConstraints {\n license?: string;\n maxBundleKb?: number;\n minConfidence?: Confidence;\n}\n\nexport interface RecommendOptions {\n need: string;\n category?: Category;\n constraints?: RecommendConstraints;\n limit?: number;\n /**\n * Called when this search ran without its vector leg. The results are still\n * real, just weaker — callers that surface answers to an agent should pass\n * the reason along so nobody mistakes a degraded ranking for a confident one.\n */\n onDegraded?: (reason: string) => void;\n}\n\n/** Ladder ORDER, for the minConfidence filter only — not the ranking weight\n * (that is CONFIDENCE_WEIGHT in scoring/weights). */\nconst CONFIDENCE_ORDER: Record<Confidence, number> = {\n unproven: 0,\n promising: 1,\n emerging: 2,\n proven: 3,\n};\n/** RRF damping constant — standard value from the original RRF paper (§3). */\nconst RRF_K = 60;\n\n/**\n * Score one retrieved candidate (§3, §11).\n *\n * Exported so the ranking can be argued with numbers instead of adjectives —\n * see tests/ranking.test.ts, which feeds it real rows captured from the live\n * index. `relevance` is the RRF score normalised against the best in this\n * result set, so it is always 0..1 and the weights below are comparable.\n */\nexport function rankScore(\n row: Pick<Row, 'healthScore' | 'qualityScore' | 'confidence'>,\n relevance: number,\n lambda: number,\n): number {\n const composite = computeComposite(row.healthScore ?? 0, row.qualityScore, lambda) / 100;\n const confidence = CONFIDENCE_WEIGHT[row.confidence ?? 'unproven'] ?? 0;\n return (\n RANKING.relevance * relevance + RANKING.composite * composite + RANKING.confidence * confidence\n );\n}\n\nexport interface Row {\n name: string;\n category: Category | null;\n healthScore: number | null;\n qualityScore: number | null;\n confidence: Confidence | null;\n latestVersion: string | null;\n weeklyDownloads: number | null;\n lastReleaseAt: Date | null;\n repoUrl: string | null;\n deprecated: boolean | null;\n archived: boolean | null;\n advisories: number | null;\n}\n\nexport async function recommend(\n db: Database,\n opts: RecommendOptions,\n provider: EmbeddingProvider = createEmbeddingProvider(),\n): Promise<Candidate[]> {\n const limit = Math.min(Math.max(opts.limit ?? 3, 1), 5);\n\n // The embedding provider is a paid third party, so it WILL be unavailable\n // sometimes — an exhausted balance, a rate limit, an outage. Before this,\n // that turned into a raw HTTP error thrown at the agent from `recommend`,\n // and into \"every need unmatched\" from `plan` (whose safeRecommend swallows\n // the throw). The second is the dangerous one: an agent reads it as \"lurq\n // knows of no package for this\", which is a confident wrong answer.\n //\n // Lexical retrieval alone is materially worse than hybrid, but it is a real\n // answer from the same index. Degrade to it and say so, rather than\n // returning nothing and letting the caller infer the wrong thing.\n //\n // Note we do NOT fall back to the local embedder here: stored vectors live\n // in the provider's space, and a cosine distance across two embedding spaces\n // is noise wearing the costume of a ranking.\n let queryVec: number[] | null = null;\n try {\n queryVec = (await provider.embed([opts.need]))[0] ?? null;\n } catch (err) {\n queryVec = null;\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn(`recommend: vector retrieval unavailable (${reason}); using lexical only.`);\n opts.onDegraded?.(`vector retrieval unavailable: ${reason}`);\n }\n if (!queryVec) opts.onDegraded?.('vector retrieval unavailable');\n\n const category = opts.category ?? inferCategory(opts.need);\n const pool = Math.max(limit * 5, 25);\n\n // Primary search (category-filtered when we have one).\n let fused = await hybridSearch(db, queryVec, provider.id, opts.need, opts.constraints, category, pool);\n // If a category filter starved the results, broaden to all categories.\n if (category && fused.length < limit) {\n const broad = await hybridSearch(db, queryVec, provider.id, opts.need, opts.constraints, null, pool);\n const seen = new Set(fused.map((f) => f.row.name));\n fused = fused.concat(broad.filter((f) => !seen.has(f.row.name)));\n }\n if (fused.length === 0) return [];\n\n // Re-rank: fused relevance (RRF), the quality-aware composite (§1), and the\n // evidence tier. RRF already absorbs both retrieval legs, so the relevance\n // term rewards exact lexical hits the vector leg alone would miss.\n const lambda = loadWeights().composite.lambda;\n const maxRrf = Math.max(...fused.map((f) => f.rrf));\n const ranked = fused\n .map((f) => ({\n row: f.row,\n score: rankScore(f.row, maxRrf > 0 ? f.rrf / maxRrf : 0, lambda),\n }))\n .sort((a, b) => b.score - a.score)\n .slice(0, limit);\n\n return ranked.map(({ row }) => toCandidate(row));\n}\n\ninterface Fused {\n row: Row;\n rrf: number;\n}\n\n/**\n * Run the vector and lexical retrievals and fuse them with RRF (§3). Each leg\n * independently ranks the candidate set; a doc's fused score is the sum of\n * 1/(k+rank) across the legs it appears in — so documents both legs agree on\n * rise, and exact-name hits the vector leg ranks poorly still surface.\n */\nasync function hybridSearch(\n db: Database,\n /** null when the embedding provider is unavailable — lexical leg only. */\n queryVec: number[] | null,\n providerId: string,\n need: string,\n constraints: RecommendConstraints | undefined,\n category: Category | null,\n pool: number,\n): Promise<Fused[]> {\n const [vectorRows, lexicalRows] = await Promise.all([\n queryVec ? runVectorQuery(db, queryVec, providerId, constraints, category, pool) : [],\n runLexicalQuery(db, need, constraints, category, pool),\n ]);\n // rrfFuse is already N-ary, so an empty vector leg degrades to a pure\n // lexical ranking without a second code path.\n return rrfFuse([vectorRows, lexicalRows]);\n}\n\n/**\n * Reciprocal Rank Fusion over N ranked lists (§3). A document's fused score is\n * Σ 1/(k + rank) across the lists it appears in — using only ranks, never raw\n * scores, so two incomparable scales (cosine distance vs ts_rank) never need\n * normalizing. Generic over `{ name }` so the fusion math is unit-testable.\n */\nexport function rrfFuse<T extends { name: string }>(\n lists: T[][],\n k = RRF_K,\n): { row: T; rrf: number }[] {\n const fused = new Map<string, { row: T; rrf: number }>();\n for (const list of lists) {\n list.forEach((row, idx) => {\n const contribution = 1 / (k + idx + 1); // rank is 1-based\n const prev = fused.get(row.name);\n if (prev) prev.rrf += contribution;\n else fused.set(row.name, { row, rrf: contribution });\n });\n }\n return [...fused.values()].sort((a, b) => b.rrf - a.rrf);\n}\n\nconst ROW_COLUMNS = {\n name: packages.name,\n category: packages.category,\n healthScore: packages.healthScore,\n qualityScore: packages.qualityScore,\n confidence: packages.confidence,\n latestVersion: packages.latestVersion,\n weeklyDownloads: packages.weeklyDownloads,\n lastReleaseAt: packages.lastReleaseAt,\n repoUrl: packages.repoUrl,\n deprecated: packages.deprecated,\n archived: packages.archived,\n // The count, not the array: an agent shortlisting five packages needs to know\n // that one carries advisories, and `evaluate` is where it reads which. Pulling\n // the jsonb payload for every candidate would cost tokens on every call for\n // detail the next call already serves.\n advisories: sql<number>`coalesce(jsonb_array_length(${packages.advisories}), 0)`,\n} as const;\n\n/** Shared filter conditions (category + constraints) for both retrieval legs. */\nfunction buildConditions(\n constraints: RecommendConstraints | undefined,\n category: Category | null,\n) {\n const conditions = [];\n if (category) conditions.push(eq(packages.category, category));\n if (constraints?.license) conditions.push(eq(packages.license, constraints.license));\n if (constraints?.maxBundleKb !== undefined) {\n conditions.push(lte(packages.bundleMinGzipKb, constraints.maxBundleKb));\n }\n if (constraints?.minConfidence) {\n const allowed = (['proven', 'emerging', 'promising', 'unproven'] as Confidence[]).filter(\n (c) => CONFIDENCE_ORDER[c] >= CONFIDENCE_ORDER[constraints.minConfidence!],\n );\n // Parameterized: drizzle binds each value, closing the sql.raw interpolation\n // hole (safe today — validated enum — but no reason to keep a raw string).\n conditions.push(inArray(packages.confidence, allowed));\n }\n return conditions;\n}\n\n/** Semantic leg: pgvector cosine, ordered by ascending distance. */\nasync function runVectorQuery(\n db: Database,\n queryVec: number[],\n providerId: string,\n constraints: RecommendConstraints | undefined,\n category: Category | null,\n pool: number,\n): Promise<Row[]> {\n const distance = cosineDistance(packages.embedding, queryVec);\n // Only compare vectors produced in the same space as the query vector. Rows\n // embedded by a different provider/model are excluded (they get retrieved by\n // the lexical leg instead) rather than compared across incompatible spaces.\n const conditions = [\n isNotNull(packages.embedding),\n eq(packages.embeddingProvider, providerId),\n ...buildConditions(constraints, category),\n ];\n return db\n .select(ROW_COLUMNS)\n .from(packages)\n .where(and(...conditions))\n .orderBy(distance)\n .limit(pool);\n}\n\n/** Lexical leg: full-text `tsvector` match, ranked by `ts_rank` (§3). */\nasync function runLexicalQuery(\n db: Database,\n need: string,\n constraints: RecommendConstraints | undefined,\n category: Category | null,\n pool: number,\n): Promise<Row[]> {\n const tsquery = sql`websearch_to_tsquery('english', ${need})`;\n const rank = sql<number>`ts_rank(${packages.searchVector}, ${tsquery})`;\n const conditions = [sql`${packages.searchVector} @@ ${tsquery}`, ...buildConditions(constraints, category)];\n return db\n .select(ROW_COLUMNS)\n .from(packages)\n .where(and(...conditions))\n .orderBy(sql`${rank} desc`)\n .limit(pool);\n}\n\nexport function toCandidate(row: Row): Candidate {\n return {\n name: row.name,\n category: row.category,\n healthScore: row.healthScore ?? 0,\n qualityScore: row.qualityScore,\n confidence: row.confidence ?? 'unproven',\n why: buildWhy(row),\n latestVersion: row.latestVersion,\n weeklyDownloads: row.weeklyDownloads,\n lastReleaseAt: row.lastReleaseAt ? row.lastReleaseAt.toISOString() : null,\n repoUrl: row.repoUrl,\n deprecated: row.deprecated ?? false,\n archived: row.archived ?? false,\n advisories: Number(row.advisories ?? 0),\n };\n}\n\n/**\n * A ≤1-sentence rationale (§12.3.1).\n *\n * The disqualifying facts lead, and are worded as warnings rather than as\n * further attributes in the list. A consumer that renders only `why` — the CLI\n * table, a log line, an agent skimming — must not be able to miss that the\n * package it is about to install is dead.\n */\nfunction buildWhy(row: Row): string {\n const warnings: string[] = [];\n if (row.deprecated) warnings.push('DEPRECATED');\n if (row.archived) warnings.push('repo archived');\n if (row.advisories) {\n warnings.push(`${row.advisories} advisor${row.advisories === 1 ? 'y' : 'ies'}`);\n }\n\n const parts: string[] = [];\n if (row.confidence) parts.push(row.confidence);\n if (row.weeklyDownloads) parts.push(`${formatDownloads(row.weeklyDownloads)} weekly downloads`);\n if (row.healthScore !== null) parts.push(`health ${row.healthScore}`);\n const rationale = parts.join(', ') || 'tracked package';\n return warnings.length ? `${warnings.join(' + ')} — ${rationale}` : rationale;\n}\n\nfunction formatDownloads(n: number): string {\n if (n >= 1_000_000) return `${Math.round(n / 100_000) / 10}M`;\n if (n >= 1_000) return `${Math.round(n / 1_000)}k`;\n return String(n);\n}\n","/**\n * Selection policy — what an agent is allowed to *add*, as opposed to what it\n * is allowed to *upgrade*.\n *\n * `RepoPolicy` (github/types) governs upgrades to dependencies a repo already\n * has. This governs the other half: the packages an agent reaches for when it\n * writes new code. Nothing else in the ecosystem sits at that moment — Renovate,\n * Dependabot and Snyk all act on a manifest that already contains the choice.\n * lurq is in the agent's loop over MCP, so it is the one place a bad pick can be\n * caught before it becomes a line in package.json and, a month later, a\n * migration.\n *\n * Scoped by owner id, not by a new organisation entity. `api_keys.owner_id` and\n * `repos.owner_id` are already Clerk ids, and Clerk namespaces its ids by prefix\n * (`user_…` / `org_…`), so the day organisations are switched on this column\n * holds an org id with no migration and no membership tables. Building a\n * membership model before a single customer has asked for one is exactly the\n * speculative work this file should not contain.\n * ponytail: owner-scoped; when Clerk orgs land, `ownerId` holds `org_…`.\n */\nimport type { Advisory, AdvisorySeverity, Confidence } from '../core/types';\n\n/** One package the policy refuses, with the reason an agent can act on. */\nexport interface DenyRule {\n name: string;\n /** Shown verbatim to the agent — \"use our internal fork\" beats \"denied\". */\n reason?: string;\n}\n\n/**\n * A package every rule lets through.\n *\n * Carries a reason and an optional expiry because a permanent, unexplained\n * exception is how a policy rots: a year later nobody knows why the GPL parser\n * is allowed or whether the reason still holds. An expiry forces the question\n * to be asked again; the reason tells whoever asks it what was decided.\n */\nexport interface AllowRule {\n name: string;\n reason?: string;\n /** First day (YYYY-MM-DD, UTC) the exception no longer applies. Absent = permanent. */\n expires?: string;\n}\n\n/**\n * `enforce` refuses. `warn` reports what would have been refused and lets it\n * through, which is how a rule gets rolled out: see what it would catch across\n * real agent traffic before it is allowed to block anyone.\n */\nexport type PolicyMode = 'enforce' | 'warn';\n\nexport interface SelectionPolicy {\n mode: PolicyMode;\n /**\n * Always allowed, evaluated before every other rule. This is the escape hatch\n * for the package a team has deliberately accepted despite the rules — an\n * unmaintained-but-vendored parser, a GPL tool used only in a build step.\n * Without it, any rule strong enough to be useful is also strong enough to be\n * switched off entirely the first time it is inconvenient.\n */\n allow: AllowRule[];\n /** Never recommended. Beats everything except `allow`. */\n deny: DenyRule[];\n /**\n * Floor on lurq's own evidence confidence. `null` = no rule, which is the\n * default: a team that has not thought about this should not silently inherit\n * a bar that hides half the index from their agent.\n */\n minConfidence: Confidence | null;\n /**\n * SPDX identifiers the org accepts. `null` = no rule. Never `[]` for \"no\n * rule\" — an empty allowlist reads as \"allow nothing\", and the difference\n * between those two is a policy that blocks every package on the first save.\n */\n licenses: string[] | null;\n /** Refuse packages npm has marked deprecated. */\n blockDeprecated: boolean;\n /**\n * Refuse packages whose source repository is archived upstream.\n *\n * Distinct from `blockDeprecated` and worth its own rule: deprecation is a\n * publisher telling you to stop, archiving is a maintainer walking away\n * without telling anyone. Most packages that end up unmaintained never get a\n * deprecation notice at all, so a policy that only reads the npm flag catches\n * the polite half of the problem.\n */\n blockArchived: boolean;\n /**\n * Refuse packages carrying a known advisory at or above this severity.\n * `null` = no rule.\n *\n * The floor is expressed as the *worst tolerated* level, not the blocked one:\n * teams reason in \"nothing high or above\", and the inverse phrasing is the\n * kind that gets set backwards once and then trusted for a year.\n */\n maxAdvisorySeverity: AdvisorySeverity | null;\n /**\n * Adoption floor, in weekly npm downloads. `null` = no rule.\n *\n * A blunt instrument on purpose — it is the one signal every engineer already\n * has an intuition for, and it exists so a team can say \"nothing nobody else\n * runs in production\" without having to reason about our evidence grades.\n */\n minWeeklyDownloads: number | null;\n /**\n * Refuse packages with no release in this many months. `null` = no rule.\n *\n * Months, not days: this is a judgement about maintenance, and a rule set in\n * days invites a precision the underlying signal does not have. A stable,\n * finished library is the known false positive here, which is exactly what\n * `allow` is for.\n */\n maxStaleMonths: number | null;\n /**\n * Ceiling on minified+gzipped bundle size, in KB. `null` = no rule.\n *\n * Only meaningful for packages that ship to a browser, and the fact is absent\n * for the rest — which, per \"absent facts never convict\", means a backend\n * dependency is never refused by a size rule someone set for the frontend.\n */\n maxBundleKb: number | null;\n /**\n * Refuse packages first published fewer than this many days ago. `null` = no rule.\n *\n * A cool-down, as package firewalls call it. Malware, maintainer-account\n * takeovers and names squatted because a model hallucinated them are all\n * youngest in their first days on the registry, before anyone has looked.\n * Measured from the package's first publish, not its latest release: lurq\n * rules on which package to add, and a mature package's new patch is not\n * what this rule is about.\n */\n minPackageAgeDays: number | null;\n}\n\n/**\n * Off. Connecting a repo does not arm autopilot, and having an owner record\n * does not arm selection policy — the same rule, for the same reason. A policy\n * that starts enforcing rules nobody set is indistinguishable from a bug.\n */\nexport const DEFAULT_SELECTION_POLICY: SelectionPolicy = {\n mode: 'enforce',\n allow: [],\n deny: [],\n minConfidence: null,\n licenses: null,\n blockDeprecated: false,\n blockArchived: false,\n maxAdvisorySeverity: null,\n minWeeklyDownloads: null,\n maxStaleMonths: null,\n maxBundleKb: null,\n minPackageAgeDays: null,\n};\n\n/** Which rule refused a package. */\nexport type ExclusionRule =\n | 'denied'\n | 'advisory'\n | 'license'\n | 'deprecated'\n | 'archived'\n | 'confidence'\n | 'adoption'\n | 'stale'\n | 'size'\n | 'age';\n\n/**\n * A package the policy removed, and why.\n *\n * Excluded candidates are *reported*, never silently dropped. An agent told\n * \"here are 3 options\" when 5 were found will happily re-derive the blocked one\n * from its own training and install it directly; an agent told \"axios is denied:\n * use the internal http client\" routes around the rule correctly. The reason is\n * the part that does the work.\n */\nexport interface Exclusion {\n name: string;\n rule: ExclusionRule;\n reason: string;\n}\n\n/**\n * Package facts the policy needs that `Candidate` does not carry.\n *\n * Every field is nullable and every rule abstains on a null: the loader reports\n * what the index knows, and \"we have not established this\" must never read as\n * either a violation or an all-clear.\n *\n * `monthsSinceRelease` is derived by the loader rather than in `check` on\n * purpose — enforcement stays a pure function of (policy, package, facts) with\n * no clock, which is what makes the rules exhaustively testable. The clock\n * belongs to the layer that reads the row.\n */\nexport interface PolicyFacts {\n license: string | null;\n deprecated: boolean;\n archived?: boolean;\n /** Known advisories. Order is not assumed — `check` takes the worst. */\n advisories?: Advisory[] | null;\n weeklyDownloads?: number | null;\n /** Whole months between the last published release and the read. */\n monthsSinceRelease?: number | null;\n /** Minified + gzipped, in KB. Null for anything not size-measured. */\n bundleKb?: number | null;\n /** Whole days since the package was first published. */\n daysSincePublished?: number | null;\n}\n\n/**\n * What the policy says about one specific package.\n *\n * Present on `evaluate` only when a policy is in force. Its absence means \"no\n * rules configured\", never \"allowed\" — the two are different claims and an agent\n * reading a missing field as approval is exactly the failure this whole layer\n * exists to prevent.\n */\nexport type PolicyVerdict =\n // `warning` is set in warn mode: the package broke a rule that is not yet enforced.\n | { allowed: true; warning?: Exclusion }\n | ({ allowed: false } & Exclusion);\n","/**\n * Read/write helpers for selection policy, plus the package facts enforcement\n * needs.\n *\n * Same authorization rule as db/repos: every query is scoped by `ownerId`, and\n * there is deliberately no unscoped read. A policy leak is worse than a repo\n * leak — it discloses what a company has decided to ban and why.\n */\nimport { and, desc, eq, gte, inArray, sql } from 'drizzle-orm';\nimport type { Database } from './client';\nimport { packages, policyDecisions, selectionPolicies, selectionPolicyChanges } from './schema';\nimport { DEFAULT_ECOSYSTEM, type Ecosystem } from '../core/types';\nimport { diffPolicies, withoutExpired } from '../policy/enforce';\nimport {\n DEFAULT_SELECTION_POLICY,\n type AllowRule,\n type Exclusion,\n type PolicyFacts,\n type SelectionPolicy,\n} from '../policy/types';\n\n/**\n * The owner's policy, or the default when they have never set one.\n *\n * A null owner (anonymous or operator-issued key) gets the default rather than\n * an error: an unauthenticated caller has no organisation whose rules could\n * apply, and failing the whole recommendation over a missing policy would take\n * the free tier down with it.\n */\nexport async function getSelectionPolicy(\n db: Database,\n ownerId: string | null,\n): Promise<SelectionPolicy> {\n if (!ownerId) return DEFAULT_SELECTION_POLICY;\n const [row] = await db\n .select({ policy: selectionPolicies.policy })\n .from(selectionPolicies)\n .where(eq(selectionPolicies.ownerId, ownerId))\n .limit(1);\n // Merged over the default so a policy written before a rule existed does not\n // arrive with that field undefined — the enforcement code reads `null` as\n // \"no rule\" and `undefined` would slip past those checks unevaluated.\n if (!row) return DEFAULT_SELECTION_POLICY;\n const stored = { ...DEFAULT_SELECTION_POLICY, ...row.policy };\n // Rows saved before exceptions carried a reason or expiry hold bare names.\n // Normalised here so no reader downstream has to know both shapes existed.\n const allow = (stored.allow as (AllowRule | string)[]).map((a) =>\n typeof a === 'string' ? { name: a } : a,\n );\n return { ...stored, allow };\n}\n\n/**\n * The policy as enforcement applies it right now: lapsed exceptions removed.\n *\n * Every enforcement path reads through this; `GET /policy` and the dashboard\n * read `getSelectionPolicy`, so an expired exception stays visible (and in a\n * pulled file) until someone deletes it on purpose.\n */\nexport async function getEnforcedPolicy(\n db: Database,\n ownerId: string | null,\n): Promise<SelectionPolicy> {\n return withoutExpired(await getSelectionPolicy(db, ownerId), new Date());\n}\n\n/**\n * Create or replace the owner's policy, and record the change. Returns the\n * policy it replaced.\n *\n * `actor` is `dashboard` or the pushing key's display prefix. The write and its\n * history row commit together: a policy change with no record of who made it is\n * exactly the gap an audit trail exists to close.\n * ponytail: `previous` is read outside the transaction, so two saves racing for\n * one owner can record a stale `before`; lock the row if concurrent writers show up.\n */\nexport async function setSelectionPolicy(\n db: Database,\n ownerId: string,\n policy: SelectionPolicy,\n actor: string,\n): Promise<SelectionPolicy> {\n const previous = await getSelectionPolicy(db, ownerId);\n await db.transaction(async (tx) => {\n await tx\n .insert(selectionPolicies)\n .values({ ownerId, policy, updatedAt: new Date() })\n .onConflictDoUpdate({\n target: selectionPolicies.ownerId,\n set: { policy, updatedAt: new Date() },\n });\n await tx.insert(selectionPolicyChanges).values({ ownerId, actor, before: previous, after: policy });\n });\n return previous;\n}\n\nexport interface PolicyChange {\n actor: string;\n at: Date;\n /** `-`/`+` rule sentences, see diffPolicies. */\n changes: string[];\n before: SelectionPolicy;\n after: SelectionPolicy;\n}\n\n/** The owner's policy changes, newest first. */\nexport async function listPolicyChanges(\n db: Database,\n ownerId: string,\n limit = 20,\n): Promise<PolicyChange[]> {\n const rows = await db\n .select()\n .from(selectionPolicyChanges)\n .where(eq(selectionPolicyChanges.ownerId, ownerId))\n .orderBy(desc(selectionPolicyChanges.createdAt), desc(selectionPolicyChanges.id))\n .limit(limit);\n return rows.map((row) => ({\n actor: row.actor,\n at: row.createdAt,\n changes: diffPolicies(row.before, row.after),\n before: row.before,\n after: row.after,\n }));\n}\n\n/**\n * Log what a rule refused (or, in warn mode, would have).\n *\n * Fire-and-forget, the same idiom as recordUsage: a log write must never fail\n * the tool call an agent is waiting on.\n */\nexport async function recordDecisions(\n db: Database,\n ownerId: string | null,\n tool: string,\n exclusions: Exclusion[],\n action: 'blocked' | 'warned',\n): Promise<void> {\n if (!ownerId || exclusions.length === 0) return;\n try {\n await db.insert(policyDecisions).values(\n exclusions.map((e) => ({ ownerId, packageName: e.name, rule: e.rule, action, tool })),\n );\n } catch {\n // Display-only log: never let it break the request.\n }\n}\n\nexport interface DecisionSummary {\n packageName: string;\n rule: Exclusion['rule'];\n action: 'blocked' | 'warned';\n count: number;\n /** UTC day of the most recent hit, YYYY-MM-DD. */\n lastDay: string;\n}\n\n/**\n * Refusals grouped by package, rule and action over a trailing window, busiest\n * first. Grouped rather than raw: an agent retrying the same blocked package\n * twenty times is one finding, and the question being answered is \"what is this\n * policy catching\", not \"replay every call\".\n */\nexport async function summarizeDecisions(\n db: Database,\n ownerId: string,\n days: number,\n): Promise<DecisionSummary[]> {\n const count = sql<number>`count(*)::int`;\n return db\n .select({\n packageName: policyDecisions.packageName,\n rule: policyDecisions.rule,\n action: policyDecisions.action,\n count,\n lastDay: sql<string>`to_char(max(${policyDecisions.createdAt}) at time zone 'UTC', 'YYYY-MM-DD')`,\n })\n .from(policyDecisions)\n .where(\n and(\n eq(policyDecisions.ownerId, ownerId),\n // `::int` for the same reason usage.ts's windowStart casts: an uncast JS\n // number leaves Postgres to guess the operand type.\n gte(policyDecisions.createdAt, sql`now() - make_interval(days => ${days}::int)`),\n ),\n )\n .groupBy(policyDecisions.packageName, policyDecisions.rule, policyDecisions.action)\n .orderBy(desc(count))\n .limit(100);\n}\n\n/** Whole days from `date` to now; null when the date is unknown. */\nexport function daysSince(date: Date | null): number | null {\n if (!date) return null;\n return Math.max(0, Math.floor((Date.now() - date.getTime()) / (1000 * 60 * 60 * 24)));\n}\n\n/** Whole months from `date` to now; null when the date is unknown. */\nfunction monthsSince(date: Date | null): number | null {\n if (!date) return null;\n const ms = Date.now() - date.getTime();\n if (ms < 0) return 0;\n return Math.floor(ms / (1000 * 60 * 60 * 24 * 30.44));\n}\n\n/**\n * Every package fact the selection rules read, for the named packages.\n *\n * Kept out of the search queries on purpose. Adding these columns to both legs of\n * the hybrid retrieval would widen the hot path for every caller so that policy\n * — which most callers do not have — could read them. One keyed lookup over at\n * most five names is cheaper than that, and it keeps search unaware of policy.\n *\n * Names missing from the result are simply absent from the map. Enforcement\n * treats an absent fact as \"not established\", never as a violation.\n */\nexport async function loadPolicyFacts(\n db: Database,\n names: string[],\n ecosystem: Ecosystem = DEFAULT_ECOSYSTEM,\n): Promise<Map<string, PolicyFacts>> {\n const out = new Map<string, PolicyFacts>();\n if (names.length === 0) return out;\n const rows = await db\n .select({\n name: packages.name,\n license: packages.license,\n deprecated: packages.deprecated,\n archived: packages.archived,\n advisories: packages.advisories,\n weeklyDownloads: packages.weeklyDownloads,\n lastReleaseAt: packages.lastReleaseAt,\n bundleMinGzipKb: packages.bundleMinGzipKb,\n firstPublishedAt: packages.firstPublishedAt,\n })\n .from(packages)\n .where(and(inArray(packages.name, names), eq(packages.ecosystem, ecosystem)));\n for (const row of rows) {\n out.set(row.name, {\n license: row.license,\n deprecated: row.deprecated,\n archived: row.archived,\n advisories: row.advisories,\n weeklyDownloads: row.weeklyDownloads,\n // Resolved here, not in `check`: the rules stay a pure function with no\n // clock, which is what lets every one of them be tested exhaustively.\n monthsSinceRelease: monthsSince(row.lastReleaseAt),\n bundleKb: row.bundleMinGzipKb,\n daysSincePublished: daysSince(row.firstPublishedAt),\n });\n }\n return out;\n}\n","/**\n * The single answer to \"is it safe to install this?\".\n *\n * This exists because lurq had several. `verify` rolled risk flags into a\n * level, `evaluate` reported a health score and a confidence tier, and `audit`\n * emitted findings — three code paths deriving safety from overlapping inputs\n * and disagreeing about the same package. A tool that answers one question\n * three ways has not answered it, and the disagreement always surfaced at the\n * worst moment, because the paths diverge exactly where the evidence is thin.\n *\n * Every surface now calls this and renders what it returns. Adding a signal\n * means editing one file, and no caller can accidentally be more reassuring\n * than the evidence supports.\n *\n * Three rules, each of which was a real defect:\n *\n * 1. A SECURITY FINDING OVERRIDES QUALITY. A package with a known advisory is\n * not \"safe\" because it is popular and well maintained. The health score\n * stays a quality measure — it is not fudged — but it never sets the\n * verdict, and the verdict is what every surface leads with.\n *\n * 2. UNKNOWN IS NOT CLEAN. `advisories` is NULL until the package has been\n * analysed and `[]` once it has, and collapsing those with `?? []` reported\n * \"0 advisories\" for a package nobody had looked at yet. Missing evidence\n * is carried in `unknowns` and suppresses reassurance outright.\n *\n * 3. A NAME THAT DOES NOT EXIST IS NOT A RISK RATING. It is bad input, and\n * saying \"high risk\" invites the reader to weigh it against a benefit. There\n * is no package to weigh.\n */\nimport type { Advisory, RiskLevel } from '../core/types';\n\n/**\n * `invalid` is deliberately outside `RiskLevel`: it is a statement about the\n * INPUT, not about a package, and flattening it into `high` loses the only\n * thing the caller can act on — that there is nothing here to install.\n */\nexport type VerdictLevel = RiskLevel | 'invalid';\n\nexport interface SecurityVerdict {\n level: VerdictLevel;\n /** Why this is not clean, worst first. Empty only when nothing was found. */\n reasons: string[];\n /**\n * What was NOT established. Non-empty means `level` is provisional: it is the\n * worst we can currently justify, not the worst that is true.\n */\n unknowns: string[];\n /** Every input needed to justify a clean bill was present. */\n complete: boolean;\n /**\n * Safe to render as reassurance (\"looks safe\", a green tick).\n *\n * The one flag every renderer must consult. It requires a low level AND no\n * findings AND nothing unchecked, so a caller cannot produce a green tick\n * over a gap in the evidence by reading `level` alone.\n */\n reassuring: boolean;\n /** Advisories actually recorded. Null when none have been fetched yet. */\n advisoryCount: number | null;\n /**\n * WHICH version this verdict is about, in words a reader can act on.\n *\n * Without it the surfaces agree and still mislead. `verify vitest` answers\n * about the latest release and says \"no problems found\"; the audit answers\n * about the 2.1.9 you have installed and says \"vulnerable\". Both are correct\n * and they read as a contradiction, because neither said what it was talking\n * about. A clean bill for the newest version is not a clean bill for the one\n * running in your node_modules.\n */\n scope: string;\n}\n\nexport interface VerdictInput {\n /** False means the registry has no such package. */\n exists: boolean;\n /**\n * Advisories for the package. NULL means NOT YET CHECKED and must not be\n * passed as `[]` — that is the distinction this whole module protects.\n */\n advisories: Advisory[] | null;\n /** A popular package this name closely mimics. */\n typosquatOf?: string | null;\n installScripts?: boolean;\n brandNew?: boolean;\n /** Few or unknown downloads. */\n lowTrust?: boolean;\n deprecated?: boolean;\n archived?: boolean;\n singleMaintainer?: boolean;\n /** OSV ids matched to the EXACT installed version, when one was checked. */\n versionVulns?: string[] | null;\n /** False when a vulnerability lookup was attempted and did not complete. */\n vulnLookupComplete?: boolean;\n /** The version this verdict describes. */\n subjectVersion?: string | null;\n /** True when `subjectVersion` is what the user has installed, not the latest. */\n subjectInstalled?: boolean;\n}\n\nconst SEVERE = new Set(['critical', 'high']);\n\nfunction describeScope(i: VerdictInput): string {\n if (!i.exists) return 'this name';\n if (!i.subjectVersion) {\n return i.subjectInstalled ? 'the installed version' : 'the latest published version';\n }\n return i.subjectInstalled ? `the installed ${i.subjectVersion}` : `${i.subjectVersion} (latest)`;\n}\n\nexport function hasSevereAdvisory(advisories: Advisory[]): boolean {\n return advisories.some((a) => SEVERE.has(a.severity));\n}\n\nexport function assessVerdict(i: VerdictInput): SecurityVerdict {\n const reasons: string[] = [];\n const unknowns: string[] = [];\n\n // Bad input, answered as bad input. A name nobody publishes is not a package\n // with a high risk score; it is a name the caller should stop using, and very\n // often a hallucination or a typo the agent was one command from installing.\n if (!i.exists) {\n return {\n level: 'invalid',\n reasons: [\n i.typosquatOf\n ? `no such package on npm — the name closely mimics \"${i.typosquatOf}\", which is what a typosquat looks like. Do not install it; check the spelling you meant.`\n : 'no such package on npm. This name does not exist, so there is nothing to assess — check the spelling, or that you are not recalling a package that was never published.',\n ],\n unknowns: [],\n complete: true,\n reassuring: false,\n advisoryCount: null,\n scope: describeScope(i),\n };\n }\n\n // NULL is \"not analysed yet\", `[]` is \"analysed, nothing found\". Treating the\n // first as the second is how an unanalysed package reported a clean bill.\n const analysed = i.advisories !== null;\n const advisories = i.advisories ?? [];\n if (!analysed) {\n unknowns.push('advisories have not been checked for this package yet');\n }\n if (i.vulnLookupComplete === false) {\n unknowns.push('the vulnerability lookup did not complete, so results are partial');\n }\n\n const severe = hasSevereAdvisory(advisories);\n const versionVulns = i.versionVulns ?? [];\n\n if (i.typosquatOf) {\n reasons.push(`name closely mimics \"${i.typosquatOf}\" — possible typosquat`);\n }\n if (versionVulns.length) {\n reasons.push(\n `the installed version is affected by ${versionVulns.length} advisory(ies): ${versionVulns.slice(0, 4).join(', ')}`,\n );\n }\n if (severe) {\n const worst = advisories.filter((a) => SEVERE.has(a.severity));\n reasons.push(`${worst.length} critical/high advisory(ies) recorded against this package`);\n }\n // Classic malware fingerprint: brand-new, runs install hooks, nobody uses it.\n const malwarePattern = Boolean(i.installScripts && i.brandNew && i.lowTrust);\n if (malwarePattern) {\n reasons.push(\n 'published within the last 7 days, runs install scripts, and has almost no adoption — the shape of a malicious package',\n );\n }\n\n if (i.typosquatOf || versionVulns.length || severe || malwarePattern) {\n return {\n level: 'high',\n reasons,\n unknowns,\n complete: analysed && i.vulnLookupComplete !== false,\n reassuring: false,\n advisoryCount: analysed ? advisories.length : null,\n scope: describeScope(i),\n };\n }\n\n // A moderate or low advisory used to add a flag and leave the level at `low`,\n // so the same response said \"has-known-advisory\" and \"looks safe\". Any\n // recorded advisory is now at least a medium: it may not warrant refusing the\n // package, but it always warrants the reader knowing before they install.\n if (advisories.length > 0) {\n reasons.push(\n `${advisories.length} advisory(ies) recorded against this package (none critical or high)`,\n );\n }\n if (i.deprecated) reasons.push('the publisher has marked this package deprecated');\n if (i.archived) reasons.push('the source repository is archived');\n if (i.installScripts && (i.lowTrust || i.brandNew)) {\n reasons.push('runs install scripts and has little adoption or history');\n }\n if (i.lowTrust && i.singleMaintainer) {\n reasons.push('a single maintainer and very low adoption');\n }\n\n if (reasons.length > 0) {\n return {\n level: 'medium',\n reasons,\n unknowns,\n complete: analysed && i.vulnLookupComplete !== false,\n reassuring: false,\n advisoryCount: analysed ? advisories.length : null,\n scope: describeScope(i),\n };\n }\n\n const complete = analysed && i.vulnLookupComplete !== false;\n return {\n level: 'low',\n reasons: [],\n unknowns,\n complete,\n // The only path that produces a green tick, and it requires the evidence to\n // be complete. An unanalysed package reads as \"not checked yet\", never as\n // \"nothing wrong with it\".\n reassuring: complete,\n advisoryCount: analysed ? advisories.length : null,\n scope: describeScope(i),\n };\n}\n\n/** One line a renderer can print verbatim. Never reassuring unless it can be. */\nexport function verdictHeadline(v: SecurityVerdict): string {\n if (v.level === 'invalid') return 'NOT A REAL PACKAGE';\n if (v.level === 'high') return `do not install ${v.scope} without review`;\n if (v.level === 'medium') return `${v.scope}: usable, but read the findings first`;\n if (!v.complete) return `no problems found in ${v.scope}, but the check is incomplete`;\n return `no supply-chain problems found in ${v.scope}`;\n}\n","[\n \"react\", \"react-dom\", \"react-router\", \"react-router-dom\", \"next\", \"vue\",\n \"vue-router\", \"pinia\", \"vuex\", \"svelte\", \"solid-js\", \"preact\", \"angular\",\n \"@angular/core\", \"jquery\", \"lodash\", \"underscore\", \"ramda\", \"immer\", \"rxjs\",\n \"express\", \"koa\", \"fastify\", \"@nestjs/core\", \"hapi\", \"connect\", \"body-parser\",\n \"cookie-parser\", \"cors\", \"helmet\", \"morgan\", \"compression\", \"express-session\",\n \"express-rate-limit\", \"multer\", \"passport\", \"jsonwebtoken\", \"bcrypt\",\n \"bcryptjs\", \"axios\", \"node-fetch\", \"got\", \"undici\", \"superagent\", \"request\",\n \"cheerio\", \"puppeteer\", \"playwright\", \"cypress\", \"jsdom\", \"ws\", \"socket.io\",\n \"socket.io-client\", \"graphql\", \"@apollo/client\", \"apollo-server\", \"dataloader\",\n \"mongoose\", \"mongodb\", \"pg\", \"mysql2\", \"sequelize\", \"prisma\", \"knex\",\n \"drizzle-orm\", \"typeorm\", \"redis\", \"ioredis\", \"sqlite3\", \"better-sqlite3\",\n \"typescript\", \"eslint\", \"prettier\", \"tslint\", \"webpack\", \"vite\", \"rollup\",\n \"esbuild\", \"parcel\", \"@babel/core\", \"babel-core\", \"babel-loader\", \"ts-node\",\n \"tsx\", \"tsup\", \"nodemon\", \"concurrently\", \"npm-run-all\", \"jest\", \"vitest\",\n \"mocha\", \"chai\", \"sinon\", \"ava\", \"tape\", \"supertest\", \"@testing-library/react\",\n \"enzyme\", \"chalk\", \"colors\", \"kleur\", \"picocolors\", \"ansi-colors\", \"commander\",\n \"yargs\", \"meow\", \"minimist\", \"inquirer\", \"prompts\", \"ora\", \"boxen\", \"figlet\",\n \"cli-progress\", \"debug\", \"dotenv\", \"cross-env\", \"rimraf\", \"glob\", \"fast-glob\",\n \"chokidar\", \"fs-extra\", \"execa\", \"cross-spawn\", \"shelljs\", \"which\", \"semver\",\n \"uuid\", \"nanoid\", \"ulid\", \"moment\", \"dayjs\", \"date-fns\", \"luxon\", \"zod\", \"yup\",\n \"joi\", \"ajv\", \"validator\", \"class-validator\", \"winston\", \"pino\", \"bunyan\",\n \"nodemailer\", \"node-cron\", \"bull\", \"bullmq\", \"kafkajs\", \"amqplib\", \"sharp\",\n \"jimp\", \"archiver\", \"tar\", \"adm-zip\", \"qs\", \"query-string\", \"form-data\",\n \"mime-types\", \"http-errors\", \"classnames\", \"clsx\", \"styled-components\",\n \"@emotion/react\", \"tailwindcss\", \"postcss\", \"autoprefixer\", \"sass\", \"less\",\n \"framer-motion\", \"three\", \"d3\", \"chart.js\", \"recharts\", \"gsap\", \"swiper\",\n \"leaflet\", \"mapbox-gl\", \"formik\", \"react-hook-form\", \"redux\", \"@reduxjs/toolkit\",\n \"zustand\", \"jotai\", \"mobx\", \"bootstrap\", \"@popperjs/core\", \"aws-sdk\",\n \"@aws-sdk/client-s3\", \"firebase\", \"firebase-admin\", \"stripe\", \"twilio\",\n \"openai\", \"@anthropic-ai/sdk\", \"googleapis\", \"bignumber.js\", \"decimal.js\",\n \"mathjs\", \"slugify\", \"faker\", \"@faker-js/faker\", \"puppeteer-core\"\n]\n","/**\n * Typosquat detection.\n *\n * A package whose name is a near-miss of a popular one (`crossenv` for\n * `cross-env`, `expres` for `express`) is the classic supply-chain attack: a\n * coding agent fat-fingers or hallucinates a name and installs the impostor.\n * We compare a queried name against the most-downloaded packages lurq already\n * tracks — a tiny edit distance to a popular name the package itself is NOT is\n * a strong signal.\n */\nimport popularPackages from '../data/popular-packages.json';\n\n/** Static baseline of well-known npm names. Unioned with the tracked corpus so\n * detection still works on a cold/thin index (fresh deploy, few syncs) and\n * catches squats of famous packages that aren't tracked yet. */\nconst POPULAR_BASELINE = popularPackages as string[];\n\n/** Tracked top-downloads names + the static baseline, de-duplicated. Pass the\n * result as the corpus to `detectTyposquat` so the guard is never silently off. */\nexport function typosquatCorpus(trackedTopNames: string[]): string[] {\n return [...new Set([...POPULAR_BASELINE, ...trackedTopNames])];\n}\n\n/** `@scope/name` → `name` so scope decoration doesn't dominate the distance. */\nfunction bareName(name: string): string {\n const slash = name.indexOf('/');\n return (slash >= 0 ? name.slice(slash + 1) : name).toLowerCase();\n}\n\n/**\n * Damerau-Levenshtein (optimal string alignment) edit distance — counts\n * insertions, deletions, substitutions, and adjacent transpositions.\n */\nexport function editDistance(a: string, b: string): number {\n const m = a.length;\n const n = b.length;\n if (m === 0) return n;\n if (n === 0) return m;\n\n // Rolling rows: prevPrev enables the adjacent-transposition check.\n let prevPrev = new Array<number>(n + 1).fill(0);\n let prev = Array.from({ length: n + 1 }, (_, j) => j);\n for (let i = 1; i <= m; i++) {\n const cur = new Array<number>(n + 1).fill(0);\n cur[0] = i;\n for (let j = 1; j <= n; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n let val = Math.min(\n (prev[j] ?? 0) + 1,\n (cur[j - 1] ?? 0) + 1,\n (prev[j - 1] ?? 0) + cost,\n );\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n val = Math.min(val, (prevPrev[j - 2] ?? 0) + 1);\n }\n cur[j] = val;\n }\n prevPrev = prev;\n prev = cur;\n }\n return prev[n] ?? 0;\n}\n\nexport type TyposquatHit = { target: string; distance: number };\n\n/**\n * Closest popular package within `maxDistance` edits, or null. The queried name\n * being popular itself is never a hit. Names shorter than 4 chars are skipped —\n * at that length a single edit is noise, not an attack signal.\n */\nexport function detectTyposquat(\n name: string,\n popular: readonly string[],\n maxDistance = 2,\n): TyposquatHit | null {\n const target = bareName(name);\n if (target.length < 4) return null;\n if (popular.some((p) => p.toLowerCase() === name.toLowerCase())) return null;\n\n let best: TyposquatHit | null = null;\n for (const p of popular) {\n const cand = bareName(p);\n if (cand === target) continue; // same bare name (e.g. a fork under a scope)\n if (Math.abs(cand.length - target.length) > maxDistance) continue; // can't be close\n const dist = editDistance(target, cand);\n if (dist >= 1 && dist <= maxDistance && (!best || dist < best.distance)) {\n best = { target: p, distance: dist };\n if (dist === 1) break; // nothing closer is possible\n }\n }\n return best;\n}\n","/**\n * MCP tool handlers (§12.3). Pure functions over a Database — the transport\n * layer (server.ts) just wires zod schemas to these. Responses are kept compact\n * (§12.4): summaries truncated, advisories capped, no raw payloads, always a\n * `dataAsOf` and a `stale` hint when data is old (§17).\n */\nimport { createHash } from 'node:crypto';\nimport { sql } from 'drizzle-orm';\nimport { cached } from '../core/cache';\nimport { STALENESS_DAYS } from '../core/constants';\nimport type {\n Advisory,\n AdvisorySeverity,\n BuildSignal,\n BuildVerified,\n Category,\n CompatOutput,\n Confidence,\n EvaluateOutput,\n UsageOutput,\n VerifyOutput,\n} from '../core/types';\nimport { checkCompat } from '../compat/check';\nimport type { Database } from '../db/client';\nimport { getPackageByName, getTopPackageNames } from '../db/packages';\nimport { diffSurface } from '../usage/diff';\nimport { getOrExtractSurface, USAGE_EXTRACT_BUDGET_MS } from '../usage/service';\nimport { getLatestVerificationByName } from '../db/verification';\nimport { loadLearnedSuccessors, recordOutcome } from '../db/outcomes';\nimport { lookupSuccessor, type LearnedSuccessors } from '../core/successors';\nimport type { VerificationRunRow } from '../db/schema';\nimport { packages, type PackageRow } from '../db/schema';\nimport {\n fetchNpmCompatAtVersion,\n fetchNpmRegistry,\n fetchWeeklyDownloads,\n npmPackageExists,\n npmVersionExists,\n} from '../ingestion/sources';\nimport { truncateSentences } from '../ingestion/summarize';\nimport { FIRST_TOUCH_BUDGET_MS, getOrFetchPackage } from '../pipeline/single';\nimport { hasCriticalOrHighAdvisory } from '../scoring/score';\nimport { recommend, type RecommendOptions } from '../search/recommend';\nimport { applyPolicy, describeRules, hasRules, check as checkPolicy } from '../policy/enforce';\nimport { getEnforcedPolicy, loadPolicyFacts, recordDecisions } from '../db/selectionPolicy';\nimport type { PolicyVerdict } from '../policy/types';\nimport { assessVerdict } from '../security/verdict';\nimport type { RiskLevel } from '../core/types';\nimport { detectTyposquat, typosquatCorpus } from '../security/typosquat';\n\nconst SEVERITY_RANK: Record<AdvisorySeverity, number> = {\n critical: 4,\n high: 3,\n moderate: 2,\n low: 1,\n info: 0,\n};\nconst DAY_MS = 24 * 60 * 60 * 1000;\n\nfunction isStale(dataAsOf: Date | null): boolean {\n if (!dataAsOf) return true;\n return Date.now() - dataAsOf.getTime() > STALENESS_DAYS * DAY_MS;\n}\n\n/** Re-derive the wall-clock `stale` hint (§17) on a (possibly cached) evaluate\n * row, so a cached response doesn't keep claiming fresh data after it ages past\n * the threshold between syncs. */\nfunction refreshStale(out: EvaluateOutput): EvaluateOutput {\n out.stale = isStale(out.dataAsOf ? new Date(out.dataAsOf) : null) || undefined;\n return out;\n}\n\nfunction withinDays(date: Date | null, days: number): boolean {\n return date ? Date.now() - date.getTime() <= days * DAY_MS : false;\n}\n\n/** Top advisories by severity, capped (§12.4). */\nfunction topAdvisories(advisories: Advisory[] | null, max = 5): Advisory[] {\n if (!advisories?.length) return [];\n return [...advisories]\n .sort((a, b) => SEVERITY_RANK[b.severity] - SEVERITY_RANK[a.severity])\n .slice(0, max);\n}\n\n/** Map a stored row to the compact EvaluateOutput shape (§12.3.2). */\nexport function rowToEvaluate(row: PackageRow, learned?: LearnedSuccessors): EvaluateOutput {\n const breakdown = row.scoreBreakdown ?? {\n maintenance: 0,\n adoption: 0,\n reliability: 0,\n efficiency: null,\n quality: null,\n };\n return {\n dataAsOf: (row.dataAsOf ?? new Date()).toISOString(),\n stale: isStale(row.dataAsOf) || undefined,\n name: row.name,\n category: row.category,\n healthScore: row.healthScore ?? 0,\n qualityScore: row.qualityScore ?? null,\n confidence: (row.confidence as Confidence) ?? 'unproven',\n scoreBreakdown: breakdown,\n latestVersion: row.latestVersion,\n lastReleaseAt: row.lastReleaseAt ? row.lastReleaseAt.toISOString() : null,\n weeklyDownloads: row.weeklyDownloads,\n downloadGrowth90d: row.downloadGrowth90d,\n scorecard: row.scorecard,\n bundleMinGzipKb: row.bundleMinGzipKb,\n deprecated: row.deprecated,\n archived: row.archived,\n advisories: topAdvisories(row.advisories),\n // The SAME call `verify` and `audit` make. A health score is a quality\n // measure and must never be read as a safety clearance, so the verdict\n // travels beside it — and because all three surfaces derive it here, they\n // can no longer disagree about the same package.\n verdict: assessVerdict({\n exists: true,\n advisories: row.advisories ?? null,\n deprecated: row.deprecated,\n archived: row.archived,\n lowTrust: (row.weeklyDownloads ?? 0) < 1000,\n subjectVersion: row.latestVersion,\n }),\n summary: row.summary ? truncateSentences(row.summary, 3) : null,\n usageGuide: row.usageGuide ?? null,\n repoUrl: row.repoUrl,\n replacedBy: lookupSuccessor(row.name, learned),\n };\n}\n\nexport async function latestDataAsOf(db: Database): Promise<string> {\n const [row] = await db\n .select({ m: sql<string | null>`max(${packages.dataAsOf})` })\n .from(packages);\n return new Date(row?.m ?? Date.now()).toISOString();\n}\n\n// ── recommend ───────────────────────────────────────────────────────────────\n\nexport interface RecommendInput {\n need: string;\n category?: Category;\n constraints?: RecommendOptions['constraints'];\n}\n\n/** Short, stable cache key from arbitrary input. */\nfunction cacheKey(parts: unknown): string {\n return createHash('sha1').update(JSON.stringify(parts)).digest('hex').slice(0, 24);\n}\n\nexport async function handleRecommend(\n db: Database,\n input: RecommendInput,\n ownerId: string | null = null,\n) {\n // The search itself is owner-independent, so it stays in the shared cache —\n // embeddings and hybrid retrieval are the expensive part and every owner asking\n // the same question deserves the same hit. Policy is applied *after* the cache,\n // over at most five candidates. Folding the owner into the cache key instead\n // would shard the cache per user to save a lookup that costs one indexed query.\n const base = await cached(\n 'rec',\n cacheKey([input.need, input.category ?? null, input.constraints ?? null]),\n async () => {\n let degraded: string | null = null;\n const candidates = await recommend(db, {\n need: input.need,\n category: input.category,\n constraints: input.constraints,\n limit: 5,\n onDegraded: (reason) => {\n degraded = reason;\n },\n });\n return { dataAsOf: await latestDataAsOf(db), candidates, degraded };\n },\n {\n // Don't cache empty results — the index may still be populating. Nor\n // degraded ones: a lexical-only ranking written into the shared cache\n // outlives the outage that produced it and gets served back long after\n // the vector leg recovers.\n skipCache: (r) => r.candidates.length === 0 || r.degraded !== null,\n },\n );\n\n const policy = await getEnforcedPolicy(db, ownerId);\n if (!hasRules(policy)) return base;\n\n const facts = await loadPolicyFacts(\n db,\n base.candidates.map((c) => c.name),\n );\n const { allowed, excluded, warned } = applyPolicy(policy, base.candidates, facts);\n void (policy.mode === 'warn'\n ? recordDecisions(db, ownerId, 'recommend', warned, 'warned')\n : recordDecisions(db, ownerId, 'recommend', excluded, 'blocked'));\n\n // `excluded` is always present once a policy is in force, even when empty —\n // an agent that sees the field knows the list was filtered and that silence\n // means nothing was refused, rather than that nothing was checked. In warn\n // mode nothing is filtered, and the would-be refusals ride along as\n // `policyWarnings` so the agent can still prefer a clean candidate.\n return policy.mode === 'warn'\n ? { ...base, candidates: allowed, policyWarnings: warned }\n : { ...base, candidates: allowed, excluded };\n}\n\n// ── policy ──────────────────────────────────────────────────────────────────\n\n/**\n * The owner's selection policy, as the sentences an agent acts on.\n *\n * Not the raw object: `compact` strips `[]` and `null`, and for `licenses` those\n * mean opposite things (allow nothing vs no rule). One line per active rule\n * survives compaction intact and costs fewer tokens than the JSON would.\n */\nexport async function handlePolicy(db: Database, ownerId: string | null) {\n if (!ownerId) {\n return {\n enforced: false,\n rules: [],\n note: 'No lurq account on this connection, so no policy applies. Connect with `lurq setup`.',\n };\n }\n const rules = describeRules(await getEnforcedPolicy(db, ownerId));\n return { enforced: rules.length > 0, rules };\n}\n\n// ── evaluate ────────────────────────────────────────────────────────────────\n\nexport async function handleEvaluate(\n db: Database,\n input: { package: string },\n ownerId: string | null = null,\n): Promise<(EvaluateOutput & { policy?: PolicyVerdict }) | { tracked: false; suggestion: string }> {\n const out = await cached(\n 'eval',\n cacheKey([input.package]),\n async () => {\n // Block-on-first-touch (§4A): a single-package eval awaits the ingest so\n // the first call returns real evidence, not a \"retry shortly\" placeholder.\n const { row, existsOnNpm } = await getOrFetchPackage(db, input.package, {\n blockMs: FIRST_TOUCH_BUDGET_MS,\n requestedByOwnerId: ownerId,\n });\n if (!row) {\n return {\n tracked: false as const,\n suggestion: existsOnNpm\n ? `🎉 Congrats, you're the first to add \"${input.package}\" to lurq's registry! It's being fetched and scored now; retry in a few seconds for the full evidence read.`\n : `\"${input.package}\" was not found on the npm registry. Check the package name.`,\n };\n }\n // Only a dead package can carry a successor, so the map is worth loading\n // only for one. It is memoised, but skipping the call entirely keeps the\n // common path — evaluating a healthy package — free.\n const learned = row.deprecated || row.archived ? await loadLearnedSuccessors(db) : undefined;\n const evaluated = rowToEvaluate(row, learned);\n const verification = await getLatestVerificationByName(db, row.name);\n return verification\n ? { ...evaluated, buildVerified: toBuildVerified(verification) }\n : evaluated;\n },\n // Don't cache \"not found / not scored yet\" — it may resolve on a later fetch.\n { skipCache: (r) => 'tracked' in r },\n );\n if ('tracked' in out) return out;\n // Re-derive the time-based stale hint, which a cached row would otherwise freeze.\n const evaluated = refreshStale(out);\n\n // Policy verdict on a package the agent has usually already chosen. This is\n // the higher-leverage half of enforcement: `recommend` shapes a list the agent\n // asked lurq to build, but `evaluate` is the call it makes about a package it\n // found on its own — from training, a blog post, or a human's suggestion — and\n // it is the last point before the install where a rule can still apply.\n const policy = await getEnforcedPolicy(db, ownerId);\n if (!hasRules(policy)) return evaluated;\n\n const facts = await loadPolicyFacts(db, [evaluated.name]);\n const exclusion = checkPolicy(\n policy,\n { name: evaluated.name, confidence: evaluated.confidence },\n facts.get(evaluated.name),\n );\n if (!exclusion) return { ...evaluated, policy: { allowed: true } };\n void recordDecisions(\n db,\n ownerId,\n 'evaluate',\n [exclusion],\n policy.mode === 'warn' ? 'warned' : 'blocked',\n );\n return {\n ...evaluated,\n policy:\n policy.mode === 'warn' ? { allowed: true, warning: exclusion } : { allowed: false, ...exclusion },\n };\n}\n\n// ── compare ─────────────────────────────────────────────────────────────────\n\n/**\n * One sentence per cause, so a response carrying both is unambiguous about which\n * name is which. The not-found clause leads: it is the actionable one, and an\n * agent that reads only the first sentence must read the warning, not the party.\n */\nfunction comparisonNote(notFound: string[], pending: string[]): string {\n return [\n notFound.length\n ? `Not found on the npm registry: ${notFound.join(', ')}. Check the name(s) before installing — these do not exist.`\n : null,\n pending.length\n ? `🎉 You're the first to add ${pending.join(', ')} to lurq's registry! They're being scored now; retry shortly for the full comparison.`\n : null,\n ]\n .filter(Boolean)\n .join(' ');\n}\n\nexport async function handleCompare(\n db: Database,\n input: { packages: string[] },\n ownerId: string | null = null,\n) {\n // Key on the exact input — the response echoes the caller's own names/order in\n // `missing`, so a normalized key would serve another caller's casing.\n const out = await cached(\n 'cmp',\n cacheKey(input.packages),\n async () => {\n const results = await Promise.all(\n input.packages.map((name) => getOrFetchPackage(db, name, { requestedByOwnerId: ownerId })),\n );\n const rows = results\n .map((r) => r.row)\n .filter((row): row is PackageRow => row !== null)\n // Not point-free: rowToEvaluate takes a second parameter now, and `.map`\n // would hand it the index.\n .map((row) => rowToEvaluate(row))\n .sort((a, b) => b.healthScore - a.healthScore);\n\n // A missing row has two completely different causes and they must never\n // share a message. `getOrFetchPackage` returns row=null both for a name\n // that is not on npm at all and for a real package whose ingest is still\n // running — collapsing them told an agent comparing a hallucinated name\n // that it was real and \"being scored now\", which is the exact failure\n // `verify` exists to prevent. Split them at the source.\n const missing: string[] = [];\n const notFound: string[] = [];\n const pending: string[] = [];\n input.packages.forEach((name, i) => {\n const result = results[i]!;\n if (result.row) return;\n missing.push(name);\n (result.existsOnNpm ? pending : notFound).push(name);\n });\n\n return {\n dataAsOf: await latestDataAsOf(db),\n rows,\n // `missing` stays the union, in the caller's own order, so a client\n // pinned to an older lurq keeps printing its \"not found\" line.\n ...(missing.length ? { missing } : {}),\n ...(notFound.length ? { notFound } : {}),\n ...(pending.length ? { pending } : {}),\n ...(missing.length ? { note: comparisonNote(notFound, pending) } : {}),\n };\n },\n // Don't cache a miss: a pending ingest lands within seconds, and a name that\n // is not on npm today may be published tomorrow.\n { skipCache: (r) => Boolean((r as { missing?: string[] }).missing?.length) },\n );\n out.rows = out.rows.map(refreshStale);\n return out;\n}\n\n// ── compat ──────────────────────────────────────────────────────────────────\n\nfunction toBuildVerified(v: VerificationRunRow): BuildVerified {\n return {\n version: v.version,\n installed: v.installed,\n loaded: v.imported,\n driver: v.driver,\n ranAt: v.ranAt ? v.ranAt.toISOString() : '',\n };\n}\n\n/**\n * Whole-architecture compatibility for a set of packages: Tier-1 peer/engine\n * analysis + recorded Tier-2 sandbox conflicts (see compat/check).\n *\n * Optional `versions` pins peer/engine metadata to exact publishes (not just\n * indexed latest). Optional `node` checks each package's engines.node against\n * the target runtime.\n */\nexport async function handleCompat(\n db: Database,\n input: {\n packages: string[];\n versions?: Record<string, string | null | undefined>;\n node?: string | null;\n },\n): Promise<CompatOutput> {\n return checkCompat(db, input.packages, {\n versions: input.versions,\n node: input.node,\n });\n}\n\n// ── verify ──────────────────────────────────────────────────────────────────\n\nexport async function handleVerify(\n db: Database,\n input: { package: string },\n ownerId: string | null = null,\n): Promise<VerifyOutput> {\n const name = input.package;\n const exists = await npmPackageExists(name);\n if (!exists) {\n // A name that doesn't exist but closely mimics a popular one is a squat the\n // agent was about to fall for — surface the suspected target.\n const typo = detectTyposquat(\n name,\n typosquatCorpus(await getTopPackageNames(db).catch(() => [])),\n );\n return {\n exists: false,\n tracked: false,\n deprecated: false,\n archived: false,\n latestVersion: null,\n weeklyDownloads: null,\n riskFlags: typo\n ? ['not-found-on-registry', `possible-typosquat-of:${typo.target}`]\n : ['not-found-on-registry'],\n risk: 'high',\n // `invalid`, not `high`: this is a statement about the INPUT. Calling it\n // a risk level invites the reader to weigh it against a benefit, and\n // there is no package here to weigh.\n verdict: assessVerdict({\n exists: false,\n advisories: null,\n typosquatOf: typo?.target ?? null,\n }),\n typosquatOf: typo?.target ?? null,\n confidence: null,\n advisoryCount: null,\n };\n }\n\n const [registry, { row, wasTracked }, popular] = await Promise.all([\n fetchNpmRegistry(name).catch(() => null),\n // Block-on-first-touch (§4A): verify is single-package, so await the ingest\n // for a real confidence/tracked read on the first call.\n getOrFetchPackage(db, name, { blockMs: FIRST_TOUCH_BUDGET_MS, requestedByOwnerId: ownerId }),\n getTopPackageNames(db).catch(() => [] as string[]),\n ]);\n\n // On-demand ingestion is now async, so an untracked package has no row yet.\n // Fetch weekly downloads live (one cheap call) rather than let the risk flags\n // falsely trip 'zero-downloads' on a popular package the index hasn't caught up\n // to. Only pays the extra call on the untracked path.\n const weeklyDownloads =\n row?.weeklyDownloads ?? (await fetchWeeklyDownloads(name).catch(() => null));\n // NOT `?? []`. Null means this package has never been analysed, and\n // collapsing it to an empty array reported \"0 advisories\" — a clean bill —\n // for a package nobody had looked at yet.\n const advisories = row?.advisories ?? null;\n const advisoryCount = advisories?.length ?? null;\n const deprecated = Boolean(row?.deprecated || registry?.deprecated);\n const archived = Boolean(row?.archived);\n const brandNew = withinDays(registry?.firstPublishedAt ?? null, 7);\n const lowTrust = weeklyDownloads === null || weeklyDownloads < 1000;\n const installScripts = registry?.hasInstallScripts ?? false;\n const typo = detectTyposquat(name, typosquatCorpus(popular));\n\n const riskFlags: string[] = [];\n if (typo) riskFlags.push(`possible-typosquat-of:${typo.target}`);\n if (weeklyDownloads === null || weeklyDownloads === 0) riskFlags.push('zero-downloads');\n else if (weeklyDownloads < 1000) riskFlags.push('low-downloads');\n if (brandNew) riskFlags.push('published-within-7-days');\n if (registry?.maintainersCount === 1) riskFlags.push('single-maintainer');\n if (installScripts) riskFlags.push('runs-install-scripts');\n if (advisoryCount === null) riskFlags.push('advisories-not-yet-checked');\n else if (advisoryCount > 0) riskFlags.push('has-known-advisory');\n if (deprecated) riskFlags.push('deprecated');\n if (archived) riskFlags.push('archived');\n\n // One authority for the safety call, shared with evaluate and audit so the\n // three cannot disagree about the same package.\n const verdict = assessVerdict({\n exists: true,\n advisories,\n typosquatOf: typo?.target ?? null,\n installScripts,\n brandNew,\n lowTrust,\n deprecated,\n archived,\n singleMaintainer: registry?.maintainersCount === 1,\n subjectVersion: registry?.latestVersion ?? row?.latestVersion ?? null,\n });\n\n return {\n exists: true,\n tracked: wasTracked,\n deprecated,\n archived,\n latestVersion: registry?.latestVersion ?? row?.latestVersion ?? null,\n weeklyDownloads,\n riskFlags,\n // `invalid` cannot occur here (exists is true), so the cast is total.\n risk: verdict.level as RiskLevel,\n verdict,\n typosquatOf: typo?.target ?? null,\n confidence: (row?.confidence as Confidence) ?? null,\n advisoryCount,\n };\n}\n\n// ── usage (§4D — API signature drift) ─────────────────────────────────────────\n\n/**\n * Resolve the version to serve: explicit request → tracked latest → npm latest.\n *\n * An explicitly requested version is checked against the registry before it is\n * used. It used to be trusted verbatim, so `usage react --target 999.0.0` ran a\n * surface lookup that could only miss and answered \"no extracted API surface for\n * this version yet; fall back to the README\" — which reads as \"lurq has no data\"\n * when the truth is \"that version does not exist\". An agent acting on the first\n * message writes code against an imaginary release; the whole point of this tool\n * is that it never does that. `unpublished` is the version-level twin of\n * `verify`'s not-found-on-registry answer.\n */\ntype ResolvedVersion = { version: string | null; unpublished?: boolean };\n\nasync function resolveVersion(\n db: Database,\n name: string,\n requested?: string,\n): Promise<ResolvedVersion> {\n if (requested) {\n // null = we could not reach npm to check. Serve the request rather than\n // accusing the caller of a bad version during our own outage; the surface\n // lookup below then degrades to its normal \"no surface\" note.\n const exists = await npmVersionExists(name, requested);\n return exists === false ? { version: null, unpublished: true } : { version: requested };\n }\n const row = await getPackageByName(db, name);\n if (row?.latestVersion) return { version: row.latestVersion };\n const reg = await fetchNpmRegistry(name).catch(() => null);\n return { version: reg?.latestVersion ?? null };\n}\n\nexport interface UsageInput {\n package: string;\n version?: string;\n /** The version the agent already knows (e.g. its training-cutoff version) —\n * when given, the response includes the delta the agent must account for. */\n knownVersion?: string;\n}\n\n/**\n * Version-exact API surface + optional migration delta (§4D). The surface is the\n * package's real contract, extracted from the shipped `.d.ts` — no prose lag, no\n * hallucination.\n *\n * Read-through (§4A block-on-first-touch): a stored surface is served as-is, and\n * a miss extracts from the CDN-hosted `.d.ts` within USAGE_EXTRACT_BUDGET_MS and\n * stores it, so the first request for a package populates the cache instead of\n * turning agents away. Past the budget the extraction keeps running in the\n * background and the caller gets the README-fallback note — the same answer the\n * stored-only path gave, so a slow or unreachable CDN only ever costs latency.\n *\n * The TypeScript compiler needed to parse the `.d.ts` is loaded lazily and\n * non-fatally (see usage/extract), which is what lets the public plane call this\n * without `typescript` in its dependency tree: where it isn't installed, every\n * miss simply degrades to the note.\n *\n * `knownVersion` shares ONE deadline with the primary lookup rather than getting\n * its own, so a two-version cold miss can't double the worst-case latency.\n */\nexport async function handleUsage(db: Database, input: UsageInput): Promise<UsageOutput> {\n const resolved = await resolveVersion(db, input.package, input.version);\n const version = resolved.version;\n if (!version) {\n return {\n package: input.package,\n version: null,\n surface: null,\n available: false,\n engines: null,\n note: resolved.unpublished\n ? `\"${input.package}\" has no published version ${input.version}. That release does not exist on the npm registry — check the version before writing code against it.`\n : `Could not resolve a version for \"${input.package}\" on npm.`,\n ...(resolved.unpublished ? { unpublishedVersion: input.version } : {}),\n };\n }\n\n // Both halves of the answer at once. The surface comes through the\n // read-through path (a miss extracts within the budget rather than turning the\n // caller away); `engines` is a registry read that shares none of that state,\n // so serialising them would add its latency to every request for nothing.\n const deadline = Date.now() + USAGE_EXTRACT_BUDGET_MS;\n const [surface, compat] = await Promise.all([\n getOrExtractSurface(db, input.package, version, {\n budgetMs: USAGE_EXTRACT_BUDGET_MS,\n }),\n fetchNpmCompatAtVersion(input.package, version).catch(() => null),\n ]);\n const out: UsageOutput = {\n package: input.package,\n version,\n surface,\n available: surface !== null,\n engines: compat?.engines ?? null,\n note: surface\n ? undefined\n : 'No extracted API surface for this version yet; fall back to the README.',\n };\n\n if (input.knownVersion && input.knownVersion !== version && surface) {\n // Whatever the primary lookup left of the budget. Never below zero: a\n // budgetMs of 0 means cache-only, which is the right call once we're out of\n // time — the delta is an enrichment, not the answer.\n const known = await getOrExtractSurface(db, input.package, input.knownVersion, {\n budgetMs: Math.max(0, deadline - Date.now()),\n });\n if (known) out.delta = { ...diffSurface(known, surface), fromVersion: input.knownVersion };\n // A caller who asked for a delta and gets a response with no `delta` field\n // has to guess whether the two versions are identical, whether we timed out,\n // or whether the version they named is fiction. Say which. The existence\n // check is paid only here, on the path where we are already about to omit\n // what was asked for, and hits the packument cache the lookup above warmed.\n else {\n const knownExists = await npmVersionExists(input.package, input.knownVersion);\n out.deltaNote =\n knownExists === false\n ? `No delta: \"${input.package}\" has no published version ${input.knownVersion}. That release does not exist on the npm registry.`\n : `No delta: no API surface extracted for ${input.package}@${input.knownVersion} yet. Retry shortly, or compare against a version that has been indexed.`;\n }\n }\n return out;\n}\n\n// ── report_outcome ────────────────────────────────────────────────────────────\n\nexport interface ReportOutcomeInput {\n package: string;\n accepted: boolean;\n buildSignal?: BuildSignal;\n need?: string;\n}\n\n/**\n * Capture an opt-in recommendation outcome (§3.1). Append-only, no source code —\n * just which package, accepted or not, and a coarse build signal. Not cached (a\n * write), and cheap enough that the per-key rate limiter is the only guard needed.\n * `ownerId` is server-injected from the authenticated key, attributing the\n * outcome to an org so the flywheel accrues per-customer, not to a global pool.\n */\nexport async function handleReportOutcome(\n db: Database,\n input: ReportOutcomeInput,\n ownerId: string | null = null,\n): Promise<{ recorded: true }> {\n await recordOutcome(db, {\n ownerId,\n packageName: input.package,\n accepted: input.accepted,\n buildSignal: input.buildSignal ?? null,\n need: input.need ?? null,\n });\n return { recorded: true };\n}\n","/**\n * Global stack optimizer.\n *\n * Branch-and-bound over each slot's ranked candidates to find the highest-quality\n * combination that's compatible — the globally optimal coherent stack, not the\n * greedy local one. \"Quality\" is rank-regret: each candidate's index in its slot\n * (0 = the top pick), so the objective is to deviate from the ideal ranking as\n * little as possible while staying conflict-free.\n *\n * The feasibility oracle is instant (Tier-1 peer/engine math + pre-loaded sandbox\n * conflict edges), so the search runs purely in memory. Two prunes keep the tree\n * tiny: feasibility (a partial pick that already conflicts can never un-conflict)\n * and bound (a branch whose regret already exceeds the best feasible stack can't\n * win). Both are provably safe, so within the search budget the result is\n * order-independent — the optimum.\n *\n * A node budget caps pathological search spaces (many slots × many candidates).\n * If it's hit the search returns the best stack found so far and sets\n * `bounded: true` — best-effort, no longer a proof of optimality. At realistic\n * stack sizes the budget is never approached.\n */\nimport type { CompatConflict } from '../core/types';\nimport { resolveArchitectureCompat, type CompatMember } from './peerCompat';\n\nexport interface OptimizeResult {\n /** Chosen candidate index per slot (0 = top pick; higher = more regret). */\n selection: number[];\n conflicts: CompatConflict[];\n /** Sum of chosen indices — how far the stack drifted from the ideal ranking. */\n regret: number;\n /** True if the node budget was exhausted: the result is best-effort, not a\n * proven optimum. False (the normal case) means the search completed. */\n bounded: boolean;\n}\n\n/** Conflicts for a (partial) selection: Tier-1 peer/engine + cached sandbox edges. */\nfunction conflictsFor(members: CompatMember[], sandboxConflicts: Set<string>): CompatConflict[] {\n const out = resolveArchitectureCompat(members);\n for (let i = 0; i < members.length; i++) {\n for (let j = i + 1; j < members.length; j++) {\n const a = members[i]!.name;\n const b = members[j]!.name;\n const key = a <= b ? `${a}|${b}` : `${b}|${a}`;\n if (sandboxConflicts.has(key)) {\n out.push({\n source: 'sandbox',\n packages: [a, b],\n detail: `${a} and ${b} are recorded as incompatible (sandbox)`,\n });\n }\n }\n }\n return out;\n}\n\n/**\n * Pick one candidate per slot to minimise total rank-regret subject to\n * compatibility. `slots[i]` is slot i's candidates in preference order.\n */\nexport function optimizeStack(\n slots: CompatMember[][],\n sandboxConflicts: Set<string> = new Set(),\n): OptimizeResult {\n // Every slot must offer at least one candidate — otherwise the non-null\n // indexing below (`slots[s]![idx]!`) yields undefined and crashes in\n // conflictsFor. Callers pre-filter, but keep the exported fn safe to reuse.\n if (slots.some((s) => s.length === 0)) {\n throw new Error('optimizeStack: every slot must have at least one candidate');\n }\n\n const n = slots.length;\n const budget = 50_000;\n let nodes = 0;\n let exhausted = false;\n\n // Incumbent: top pick of every slot. Only a *feasible* stack bounds the search.\n let bestSelection = new Array<number>(n).fill(0);\n let bestRegret = conflictsFor(\n slots.map((c) => c[0]).filter((m): m is CompatMember => Boolean(m)),\n sandboxConflicts,\n ).length === 0\n ? 0\n : Infinity;\n\n const chosen = new Array<number>(n).fill(0);\n const dfs = (slot: number, regret: number): void => {\n if (nodes++ > budget) {\n exhausted = true;\n return;\n }\n if (regret >= bestRegret) return; // bound prune\n if (slot === n) {\n bestSelection = chosen.slice();\n bestRegret = regret;\n return;\n }\n const candidates = slots[slot]!;\n for (let i = 0; i < candidates.length; i++) {\n chosen[slot] = i;\n // Feasibility prune: a conflict among assigned members is permanent, so a\n // partial pick that already conflicts can never become compatible.\n const assigned = chosen.slice(0, slot + 1).map((idx, s) => slots[s]![idx]!);\n if (conflictsFor(assigned, sandboxConflicts).length === 0) {\n dfs(slot + 1, regret + i);\n }\n if (nodes > budget) {\n exhausted = true;\n return;\n }\n }\n };\n dfs(0, 0);\n\n const members = bestSelection.map((idx, s) => slots[s]![idx]!);\n return {\n selection: bestSelection,\n conflicts: conflictsFor(members, sandboxConflicts),\n regret: bestRegret === Infinity ? bestSelection.reduce((a, b) => a + b, 0) : bestRegret,\n bounded: exhausted,\n };\n}\n","/**\n * Optional `diagram` tool (§12.3.5). Emits a reference-architecture Mermaid\n * diagram for a stack the caller has *already chosen* (package names), using\n * built-in layer patterns. Input is stack-only by design: inferring an\n * architecture from a freeform description is the \"architecture oracle\" behavior\n * that the master spec (§4) and roadmap (§1) declare a non-goal. lurq labels a\n * stack you name; it does not design one. A starting point, not a validator.\n *\n * Honesty over completeness:\n * - A package we can't classify (not in the index AND no category match) is\n * placed in an explicit `Unclassified` bucket — never silently dropped into a\n * default layer. The note lists what couldn't be placed. Partial, not\n * authoritative.\n * - Front/back framework ambiguity is resolved by `packages.runtime_target`, a\n * flag classified from each package's own manifest at ingest (see\n * core/runtimeTarget). This replaced a hand-maintained set of six backend\n * framework names that mis-drew every server framework nobody had added to it.\n * A package whose manifest does not settle the question classifies as null and\n * keeps the Presentation default, which is the safe direction: `framework` is\n * a UI-leaning category to begin with.\n */\nimport { and, eq, inArray } from 'drizzle-orm';\nimport { DEFAULT_ECOSYSTEM } from '../core/types';\nimport type { Category } from '../core/types';\nimport { inferCategory } from '../search/categoryInference';\nimport { classifyRuntimeTarget, type RuntimeTarget } from '../core/runtimeTarget';\nimport type { Database } from '../db/client';\nimport { packages } from '../db/schema';\n\n/** Bucket for packages we cannot place: unknown category, or a category with no\n * real architectural home (e.g. `other`). Rendered, but kept out of the flow. */\nconst UNCLASSIFIED = 'Unclassified';\n\n/** Which architectural layer each category sits in. Categories with no honest\n * architectural home (e.g. `other`) are intentionally absent: layerFor routes\n * anything unmapped to UNCLASSIFIED rather than faking a layer. */\nconst LAYER_OF: Partial<Record<Category, string>> = {\n framework: 'Presentation',\n 'meta-framework': 'Presentation',\n 'ui-component-library': 'Presentation',\n styling: 'Presentation',\n animation: 'Presentation',\n charts: 'Presentation',\n 'state-management': 'Client Logic',\n routing: 'Client Logic',\n forms: 'Client Logic',\n validation: 'Client Logic',\n 'data-fetching': 'Client Logic',\n 'http-client': 'Client Logic',\n i18n: 'Client Logic',\n 'date-time': 'Client Logic',\n utility: 'Client Logic',\n auth: 'Backend',\n orm: 'Data',\n 'database-client': 'Data',\n 'build-tool': 'Tooling',\n bundler: 'Tooling',\n linting: 'Tooling',\n testing: 'Tooling',\n};\n\nconst FLOW_LAYERS = ['Presentation', 'Client Logic', 'Backend', 'Data'];\n\n\nexport interface Item {\n label: string;\n /** null = could not be classified (not in index, no category match). */\n category: Category | null;\n /**\n * Where the package runs, classified from its own manifest at ingest\n * (core/runtimeTarget). This is what resolves `framework`'s frontend/backend\n * ambiguity; null means the manifest did not say clearly enough, and a\n * `framework` we cannot place stays in Presentation — the historical default,\n * and the safe one, since the category itself is a UI-leaning guess.\n */\n runtimeTarget?: RuntimeTarget | null;\n}\n\nexport function layerFor(item: Item): string {\n if (!item.category) return UNCLASSIFIED;\n // The one category that spans two layers. Everything else has exactly one\n // architectural home, so asking about runtime for e.g. `styling` would be\n // noise at best and a way to mis-place a known-good mapping at worst.\n if (item.category === 'framework' && item.runtimeTarget === 'node') return 'Backend';\n return LAYER_OF[item.category] ?? UNCLASSIFIED;\n}\n\nfunction nodeId(label: string, i: number): string {\n return `n${i}_${label.replace(/[^a-zA-Z0-9]/g, '_')}`;\n}\n\nexport function buildMermaid(items: Item[]): string {\n const byLayer = new Map<string, Item[]>();\n for (const item of items) {\n const layer = layerFor(item);\n const list = byLayer.get(layer) ?? [];\n list.push(item);\n byLayer.set(layer, list);\n }\n\n const lines = ['flowchart TD', ' user([User])'];\n const ids = new Map<string, string>(); // label → node id\n let counter = 0;\n const repNode = new Map<string, string>(); // layer → first node id\n\n const emitLayer = (layer: string) => {\n const list = byLayer.get(layer);\n if (!list?.length) return;\n lines.push(` subgraph ${layer.replace(/\\s+/g, '_')}[\"${layer}\"]`);\n for (const item of list) {\n const id = nodeId(item.label, counter++);\n ids.set(item.label, id);\n if (!repNode.has(layer)) repNode.set(layer, id);\n // Unclassified nodes carry no category prefix — we don't claim one we lack.\n const text = layer === UNCLASSIFIED ? item.label : `${item.category}: ${item.label}`;\n lines.push(` ${id}[\"${text}\"]`);\n }\n lines.push(' end');\n };\n\n for (const layer of FLOW_LAYERS) emitLayer(layer);\n emitLayer('Tooling');\n emitLayer(UNCLASSIFIED);\n\n // Connect the flow layers that are present, top to bottom.\n const present = FLOW_LAYERS.filter((l) => byLayer.has(l));\n let prev = 'user';\n for (const layer of present) {\n lines.push(` ${prev} --> ${repNode.get(layer)}`);\n prev = repNode.get(layer)!;\n }\n if (byLayer.has('Data')) lines.push(` ${repNode.get('Data')} --> db[(Database)]`);\n\n return lines.join('\\n');\n}\n\nexport interface DiagramInput {\n stack?: string[];\n}\n\nexport async function handleDiagram(\n db: Database,\n input: DiagramInput,\n): Promise<{ mermaid: string; note: string }> {\n if (!input.stack?.length) {\n return {\n mermaid: 'flowchart TD\\n user([User]) --> app[Application]',\n note: 'Provide a `stack` of package names to diagram. lurq labels a stack you choose; it does not infer an architecture from a description.',\n };\n }\n\n const rows = await db\n .select({\n name: packages.name,\n category: packages.category,\n runtimeTarget: packages.runtimeTarget,\n })\n .from(packages)\n .where(\n and(inArray(packages.name, input.stack), eq(packages.ecosystem, DEFAULT_ECOSYSTEM)),\n );\n const known = new Map(rows.map((r) => [r.name, r]));\n // inferCategory is best-effort on a bare package name (it was built for NL\n // needs); a miss yields null, not a faked category. No silent 'other'.\n const items: Item[] = input.stack.map((name) => {\n const row = known.get(name);\n return {\n label: name,\n category: row?.category ?? inferCategory(name),\n // Fall back to the name-only classifier for a package that predates the\n // column or is not indexed at all: the curated overrides still resolve the\n // frameworks people actually diagram, and an unclassifiable one keeps the\n // old Presentation default rather than moving on a null.\n runtimeTarget:\n row?.runtimeTarget ??\n classifyRuntimeTarget({\n name,\n hasBrowserField: false,\n keywords: [],\n engines: null,\n peerDependencies: null,\n }),\n };\n });\n\n const unclassified = items.filter((i) => layerFor(i) === UNCLASSIFIED).map((i) => i.label);\n const note = unclassified.length\n ? `Reference pattern derived from the provided stack: partial, not authoritative. Could not place ${unclassified.length} package(s): ${unclassified.join(', ')} (not in lurq's index and no category match), shown under Unclassified, outside the flow.`\n : 'Reference pattern derived from the provided stack. A labeled starting point, not a validated architecture.';\n\n return { mermaid: buildMermaid(items), note };\n}\n","/**\n * `plan` tool — turn a described program into an evidence-scored build plan.\n *\n * This is NOT the \"architecture oracle\" non-goal (master-spec §4): it does not\n * invent an architecture from a one-line prompt. It takes a program the caller\n * has *already described in detail* (a spec/README) — or a pre-decomposed list\n * of needs — and runs lurq's normal `recommend` engine slot-by-slot, returning\n * real packages from the index with their scores. lurq still \"supplies building\n * blocks slot-by-slot; the agent assembles the architecture\" (§1.3). The rich\n * input is what removes the guesswork the spec warned against; the §20 roadmap\n * item (\"architecture recommendation … once data can ground it\") is honored\n * because every recommendation is grounded in the scored index.\n *\n * Decomposition (document → needs) follows Option C:\n * - a caller-supplied `needs[]` is used as-is (the agent already read the doc — the\n * fast, zero-LLM path, and the cleanest companion-model division of labor); else\n * - a raw `document` is decomposed server-side: by the summary LLM when a key is\n * configured, otherwise by a transparent heading/keyword heuristic. The heuristic\n * is honest-but-coarse, and the response note says so.\n */\nimport { createHash } from 'node:crypto';\nimport { and, eq, inArray } from 'drizzle-orm';\nimport { DEFAULT_ECOSYSTEM } from '../core/types';\nimport { getConfig } from '../core/config';\nimport { httpRequest } from '../core/http';\nimport { checkCompat } from '../compat/check';\nimport { assembleMembers } from '../compat/members';\nimport { optimizeStack } from '../compat/optimize';\nimport type { CompatMember } from '../compat/peerCompat';\nimport { getSandboxEdges } from '../db/compat';\nimport { logger } from '../core/logger';\nimport {\n isCategory,\n type Candidate,\n type Category,\n type CompatConflict,\n type CompatOutput,\n} from '../core/types';\nimport type { Database } from '../db/client';\nimport { packages } from '../db/schema';\nimport { inferCategory } from '../search/categoryInference';\nimport { recommend } from '../search/recommend';\nimport { getOrFetchPackage } from '../pipeline/single';\nimport type { PackageRow } from '../db/schema';\nimport { buildMermaid, layerFor } from './diagram';\nimport { latestDataAsOf } from './handlers';\n\n/** A pinned package the user chose, resolved to a fixed single-candidate slot. */\nfunction packageToCandidate(row: PackageRow): Candidate {\n return {\n name: row.name,\n category: row.category,\n healthScore: row.healthScore ?? 0,\n qualityScore: row.qualityScore,\n confidence: row.confidence ?? 'unproven',\n why: 'pinned by you',\n latestVersion: row.latestVersion,\n weeklyDownloads: row.weeklyDownloads,\n lastReleaseAt: row.lastReleaseAt ? row.lastReleaseAt.toISOString() : null,\n repoUrl: row.repoUrl,\n // A pin is the one slot lurq did not choose, which makes these MORE worth\n // saying, not less: the user picked it, so nobody else is going to notice\n // that it has been deprecated since they did.\n deprecated: row.deprecated,\n archived: row.archived,\n advisories: row.advisories?.length ?? 0,\n };\n}\n\n/**\n * Resolve user-pinned packages into fixed slots (one candidate, no alternatives)\n * so the optimizer routes the recommended slots around them.\n *\n * A pin that yields no row is reported in one of two buckets, never one. Without\n * a `blockMs` budget `getOrFetchPackage` returns row=null for a real package\n * whose ingest is still running just as it does for a name that is not on npm,\n * and folding those together made plan tell users that a package they had\n * already installed \"was not found on npm\" — a false statement about the half of\n * the input they were most sure of. (`compare` had the same bug in the opposite\n * direction; see handleCompare.)\n */\nexport async function resolvePins(\n db: Database,\n using: string[] | undefined,\n recommendedNames: Set<string>,\n requestedByOwnerId: string | null = null,\n): Promise<{ slots: PlanSlot[]; notFound: string[]; pending: string[] }> {\n const slots: PlanSlot[] = [];\n const notFound: string[] = [];\n const pending: string[] = [];\n // Dedupe, and skip a pin the recommender already picked (avoid double slots).\n for (const name of new Set(using ?? [])) {\n if (recommendedNames.has(name)) continue;\n const { row, existsOnNpm } = await getOrFetchPackage(db, name, { requestedByOwnerId });\n if (!row) {\n (existsOnNpm ? pending : notFound).push(name);\n continue;\n }\n slots.push({\n need: `using ${name}`,\n category: row.category,\n layer: layerFor({ label: name, category: row.category }),\n recommended: packageToCandidate(row),\n alternatives: [], // fixed: the user chose this, so it never gets swapped\n note: 'pinned by you',\n });\n }\n return { slots, notFound, pending };\n}\n\n/** A single component/slot to recommend a package for. */\nexport interface PlanNeed {\n need: string;\n category?: Category;\n}\n\nexport interface PlanInput {\n /** Detailed description of the program (spec/README). lurq decomposes it. */\n document?: string;\n /** Pre-decomposed needs (e.g. the calling agent already read the doc). */\n needs?: PlanNeed[];\n /** Packages the user has already chosen. Pinned as fixed slots; lurq\n * recommends only the remaining needs and plans the stack around these. */\n using?: string[];\n /** Ranking bias. 'speed' prefers the lightest-bundle option among the top\n * candidates for a slot; 'balanced' (default) uses the normal ranking. */\n optimize?: 'speed' | 'balanced';\n}\n\nexport interface PlanSlot {\n need: string;\n category: Category | null;\n layer: string;\n recommended: Candidate | null;\n alternatives: Candidate[];\n note?: string;\n /** Picked packages this slot's pick still conflicts with, if it couldn't be\n * auto-resolved with the available alternatives (residual conflict). */\n conflictsWith?: string[];\n /** If plan swapped this slot's pick to keep the stack compatible, the name of\n * the original (higher-ranked) pick it replaced. */\n swappedFrom?: string;\n}\n\nexport interface PlanOutput {\n dataAsOf: string;\n optimize: 'speed' | 'balanced';\n /** Where the slots came from: caller-supplied needs, lurq's LLM, or the heuristic. */\n source: 'needs' | 'llm' | 'heuristic';\n /** The framework/meta-framework that anchored the plan, if one was found. Every\n * other slot was recommended in this ecosystem's context. null = no framework\n * in the spec, so slots were recommended independently. */\n framework: string | null;\n slots: PlanSlot[];\n /** Needs for which no tracked package matched. */\n unmatched: string[];\n mermaid: string;\n note: string;\n /** Whole-stack compatibility of the picked packages (peer-deps/engines +\n * recorded sandbox conflicts). Evidence-backed, with name@version of each\n * member; null if the check couldn't run. */\n compatibility: CompatOutput | null;\n}\n\n/** Candidates to surface per slot: the pick plus a couple of alternatives. */\nconst PER_SLOT = 3;\n/** Cap on slots so a huge document can't fan out into hundreds of queries. */\nconst MAX_SLOTS = 24;\n\nexport async function handlePlan(\n db: Database,\n input: PlanInput,\n ownerId: string | null = null,\n): Promise<PlanOutput | { note: string }> {\n const optimize = input.optimize ?? 'balanced';\n\n const decomposed = input.needs?.length\n ? { needs: dedupeNeeds(input.needs), source: 'needs' as const }\n : input.document?.trim()\n ? await decompose(input.document)\n : null;\n\n const hasPins = Boolean(input.using?.length);\n if ((!decomposed || decomposed.needs.length === 0) && !hasPins) {\n return {\n note: 'Provide a `document` (a detailed description of your program), a `needs` array, or a `using` list of packages you have already chosen. lurq recommends evidence-scored packages per component, it does not invent an architecture from a bare prompt.',\n };\n }\n\n const needs = (decomposed?.needs ?? []).slice(0, MAX_SLOTS);\n const source = decomposed?.source ?? 'needs';\n\n // Retrieval can degrade to lexical-only when the embedding provider is\n // unavailable. That must reach the caller: `unmatched` reads to an agent as\n // \"no package exists for this need\", which is a very different claim from\n // \"lurq's search was running on one leg\".\n let degradedReason: string | null = null;\n const safeRecommend = (need: string, category: Category | undefined) =>\n recommend(db, {\n need,\n category,\n limit: PER_SLOT,\n onDegraded: (reason) => {\n degradedReason ??= reason;\n },\n }).catch((err) => {\n logger.warn(`plan: recommend failed for \"${need}\": ${(err as Error).message}`);\n return [] as Candidate[];\n });\n // Effective category per slot — the decomposition hint, else inferred from the\n // ORIGINAL need text (before any framework context is appended, so the word we\n // inject below can never misclassify the slot).\n const effCat = (n: PlanNeed): Category | undefined => n.category ?? inferCategory(n.need) ?? undefined;\n\n // Detect the framework family from the WHOLE spec (document + need texts), so the\n // plan stays coherent even when decomposition doesn't emit a framework slot.\n // This drives the coherence re-rank below.\n const anchorFamily = familyOf(`${input.document ?? ''} ${needs.map((n) => n.need).join(' ')}`);\n\n // Phase 1: if a framework/meta-framework component exists, resolve it first to\n // name the concrete package (a meta-framework like Next wins over a bare\n // framework); otherwise the detected family is the context word.\n const metaIdx = needs.findIndex((n) => effCat(n) === 'meta-framework');\n const anchorIdx = metaIdx >= 0 ? metaIdx : needs.findIndex((n) => effCat(n) === 'framework');\n\n const recs: Candidate[][] = new Array(needs.length);\n let framework: string | null = anchorFamily;\n if (anchorIdx >= 0) {\n recs[anchorIdx] = await safeRecommend(needs[anchorIdx]!.need, effCat(needs[anchorIdx]!));\n framework = recs[anchorIdx]![0]?.name ?? anchorFamily;\n }\n\n // Phase 2: recommend the remaining slots concurrently, weaving the chosen\n // framework into each query so sibling libraries stay in-ecosystem. The slot's\n // category is passed explicitly, so the injected framework word only sways\n // relevance — never the category filter. Framework-agnostic slots (e.g.\n // date/time) are unaffected since their candidates don't mention the framework.\n const [, dataAsOf] = await Promise.all([\n Promise.all(\n needs.map(async (n, i) => {\n if (i === anchorIdx) return;\n const need = framework ? `${n.need} (for a ${framework} app)` : n.need;\n recs[i] = await safeRecommend(need, effCat(n));\n }),\n ),\n latestDataAsOf(db),\n ]);\n\n // Re-rank each slot's candidates: keep the architecture coherent (cross-\n // framework bindings last), then — for 'speed' — prefer the lightest bundle,\n // otherwise preserve recommend's relevance order. One batched lookup keeps\n // `recommend` itself untouched.\n const bundleByName = optimize === 'speed' ? await bundleSizes(db, recs.flat()) : new Map<string, number>();\n\n // Adjacent needs often retrieve the same package (an \"auth\" slot and a\n // \"session\" slot both landing on the same library). Emitting it twice reads as\n // \"install this twice\" and double-counts it in the compat check, so a slot\n // whose top pick is already taken falls through to its best free alternative.\n const taken = new Set<string>();\n const recSlots: PlanSlot[] = needs.map((n, i) => {\n const candidates = orderCandidates(recs[i]!, anchorFamily, optimize, bundleByName);\n const free = candidates.filter((c) => !taken.has(c.name));\n const recommended = free[0] ?? null;\n if (recommended) taken.add(recommended.name);\n const category = n.category ?? recommended?.category ?? inferCategory(n.need);\n return {\n need: n.need,\n category,\n layer: layerFor({ label: recommended?.name ?? n.need, category }),\n recommended,\n alternatives: free.slice(1),\n note: recommended\n ? undefined\n : candidates.length\n ? 'every match for this need is already in the stack for another slot'\n : 'no tracked package matched this need yet',\n };\n });\n\n // Pin the user's chosen packages as fixed slots, then plan the rest around\n // them. Pins lead so they anchor the stack; the optimizer can only move the\n // recommended slots, so it routes them to stay compatible with the pins.\n const recommendedNames = new Set(\n recSlots.map((s) => s.recommended?.name).filter((n): n is string => Boolean(n)),\n );\n const {\n slots: pinnedSlots,\n notFound: pinsNotFound,\n pending: pinsPending,\n } = await resolvePins(db, input.using, recommendedNames, ownerId);\n const slots = [...pinnedSlots, ...recSlots];\n\n // Auto-resolve compatibility: actually make the picked stack coherent by\n // swapping a conflicting slot's pick for an alternative that resolves it.\n // Runs before the diagram/output so everything below reflects the final stack.\n const compatibility = await resolveCompat(db, slots);\n\n const unmatched = [\n ...slots.filter((s) => !s.recommended).map((s) => s.need),\n ...pinsNotFound.map((n) => `${n} (pinned, but not on the npm registry)`),\n // A pin that exists and is merely being ingested is not an unmatched need —\n // it just has no scores yet. Saying so keeps the user from \"fixing\" a name\n // that was correct all along.\n ...pinsPending.map((n) => `${n} (pinned; being scored now, retry shortly)`),\n ];\n const mermaid = buildMermaid(\n slots\n .filter((s) => s.recommended)\n .map((s) => ({ label: s.recommended!.name, category: s.category })),\n );\n\n return {\n dataAsOf,\n optimize,\n source,\n framework,\n slots,\n unmatched,\n mermaid,\n note: planNote(source, unmatched.length, optimize, framework, degradedReason),\n compatibility,\n };\n}\n\n/** Map each slot (by need) to the other picked packages its pick conflicts with. */\nexport function flagSlotConflicts(\n picks: { need: string; name: string | null }[],\n conflicts: CompatConflict[],\n): Map<string, string[]> {\n const out = new Map<string, string[]>();\n for (const c of conflicts) {\n for (const p of picks) {\n if (p.name && c.packages.includes(p.name)) {\n const others = c.packages.filter((n) => n !== p.name);\n out.set(p.need, [...new Set([...(out.get(p.need) ?? []), ...others])]);\n }\n }\n }\n return out;\n}\n\nconst NO_META = (c: Candidate): CompatMember => ({\n name: c.name,\n version: c.latestVersion,\n peerDependencies: null,\n peerDependenciesMeta: null,\n engines: null,\n});\n\n/**\n * Make the picked stack compatible by *globally optimising* the slot choices:\n * pre-load every candidate's metadata + cached sandbox edges once, then run a\n * branch-and-bound that picks the highest-quality (lowest rank-regret) compatible\n * combination. The chosen alternative is promoted to `recommended` (original\n * demoted, recorded via `swappedFrom`); residual conflicts are flagged per slot.\n * The search is pure/in-memory; only the final report re-reads the DB.\n * Best-effort — never throws.\n */\nasync function resolveCompat(db: Database, slots: PlanSlot[]): Promise<CompatOutput | null> {\n const eligible = slots.filter((s) => s.recommended);\n if (eligible.length < 2) return null;\n\n try {\n // One pass: metadata for every candidate across all slots → pure search.\n const allNames = [\n ...new Set(eligible.flatMap((s) => [s.recommended!, ...s.alternatives].map((c) => c.name))),\n ];\n const [{ members }, edges] = await Promise.all([\n assembleMembers(db, allNames),\n getSandboxEdges(db, allNames),\n ]);\n const metaByName = new Map(members.map((m) => [m.name, m]));\n const sandboxConflicts = new Set(\n edges.filter((e) => e.status === 'conflict').map((e) => `${e.packageA}|${e.packageB}`),\n );\n const slotCandidates = eligible.map((s) =>\n [s.recommended!, ...s.alternatives].map((c) => metaByName.get(c.name) ?? NO_META(c)),\n );\n\n const { selection } = optimizeStack(slotCandidates, sandboxConflicts);\n\n // Apply the optimal selection: promote the chosen candidate per slot.\n eligible.forEach((s, i) => {\n const idx = selection[i] ?? 0;\n if (idx <= 0) return;\n const all = [s.recommended!, ...s.alternatives];\n const chosen = all[idx];\n if (!chosen) return;\n s.recommended = chosen;\n s.alternatives = all.filter((c) => c.name !== chosen.name);\n s.swappedFrom = all[0]!.name;\n });\n } catch (err) {\n logger.warn(`plan: compat optimization failed: ${String(err)}`);\n }\n\n // Authoritative report on the final picks, and flag any residual conflicts.\n const compat = await checkCompat(\n db,\n eligible.map((s) => s.recommended!.name),\n ).catch(() => null);\n if (compat) {\n const flags = flagSlotConflicts(\n slots.map((s) => ({ need: s.need, name: s.recommended?.name ?? null })),\n compat.conflicts,\n );\n for (const s of slots) {\n const cw = flags.get(s.need);\n s.conflictsWith = cw?.length ? cw : undefined;\n }\n }\n return compat;\n}\n\nfunction planNote(\n source: PlanOutput['source'],\n unmatched: number,\n optimize: string,\n framework: string | null,\n degraded: string | null,\n): string {\n const base =\n source === 'heuristic'\n ? 'Components were extracted from your document with a keyword heuristic (no summary LLM configured), coarse; pass a `needs` array or set SUMMARY_API_KEY for sharper decomposition.'\n : source === 'llm'\n ? 'Components were extracted from your document by the summary model.'\n : 'Components taken from the supplied needs.';\n const grounding =\n ' Each package is recommended from lurq’s scored index, a labeled, evidence-backed starting point, not a validated architecture.';\n const ctx = framework\n ? ` Anchored to the ${framework} ecosystem so sibling libraries stay coherent across the stack.`\n : '';\n const tail = unmatched ? ` ${unmatched} need(s) had no tracked match (listed in \\`unmatched\\`).` : '';\n const opt = optimize === 'speed' ? ' Ranking favored the lightest-bundle option per slot.' : '';\n // Leads the note rather than trailing it: if the ranking is degraded, that is\n // the first thing a reader needs to know about every pick below it.\n const degradedWarning = degraded\n ? `DEGRADED: semantic search was unavailable (${degraded}), so these picks come from keyword matching alone and are materially less reliable than usual. Treat them as a shortlist to verify, and re-run when search recovers. `\n : '';\n return degradedWarning + base + grounding + ctx + opt + tail;\n}\n\n/** Merge duplicate needs (same text), keeping the first category hint seen. */\nfunction dedupeNeeds(needs: PlanNeed[]): PlanNeed[] {\n const seen = new Map<string, PlanNeed>();\n for (const n of needs) {\n const key = n.need.trim().toLowerCase();\n if (!key) continue;\n if (!seen.has(key)) seen.set(key, { need: n.need.trim(), category: n.category });\n }\n return [...seen.values()];\n}\n\n/** The framework \"family\" a package name belongs to (by naming convention), or\n * null if framework-agnostic. Lets the plan stay in one ecosystem — never\n * surface a different framework's binding (e.g. vue-router in a React app). */\nconst FAMILY_TOKENS: { family: string; re: RegExp }[] = [\n { family: 'react', re: /\\breact\\b|preact/ },\n { family: 'vue', re: /\\bvue\\b|nuxt/ },\n { family: 'angular', re: /angular/ },\n { family: 'svelte', re: /svelte/ },\n { family: 'solid', re: /\\bsolid(-?js)?\\b/ },\n];\n\nexport function familyOf(name: string): string | null {\n const n = name.toLowerCase();\n for (const f of FAMILY_TOKENS) if (f.re.test(n)) return f.family;\n return null;\n}\n\n/**\n * Order a slot's candidates: in-ecosystem first and cross-framework bindings\n * last (when an anchor framework was found), then — for 'speed' — lightest\n * bundle, otherwise preserving recommend's relevance ranking (V8's sort is\n * stable, so equal-key candidates keep their incoming order).\n */\nexport function orderCandidates(\n cands: Candidate[],\n anchorFamily: string | null,\n optimize: 'speed' | 'balanced',\n bundleByName: Map<string, number>,\n): Candidate[] {\n // +1 same ecosystem, −1 a competing framework, 0 framework-agnostic.\n const coherence = (c: Candidate): number => {\n const fam = familyOf(c.name);\n if (!fam) return 0;\n return fam === anchorFamily ? 1 : -1;\n };\n return [...cands].sort((a, b) => {\n if (anchorFamily) {\n const d = coherence(b) - coherence(a);\n if (d) return d;\n }\n if (optimize === 'speed') {\n return (bundleByName.get(a.name) ?? Infinity) - (bundleByName.get(b.name) ?? Infinity);\n }\n return 0;\n });\n}\n\n/** Batched bundle-size lookup for the 'speed' re-rank. */\nasync function bundleSizes(db: Database, candidates: Candidate[]): Promise<Map<string, number>> {\n const names = [...new Set(candidates.map((c) => c.name))];\n if (names.length === 0) return new Map();\n const rows = await db\n .select({ name: packages.name, bundle: packages.bundleMinGzipKb })\n .from(packages)\n // Bundle size is a JS concept; the 'speed' re-rank is npm-only by nature.\n .where(and(inArray(packages.name, names), eq(packages.ecosystem, DEFAULT_ECOSYSTEM)));\n return new Map(rows.filter((r) => r.bundle != null).map((r) => [r.name, r.bundle as number]));\n}\n\n// ── Decomposition (document → needs) ─────────────────────────────────────────\n\nasync function decompose(document: string): Promise<{ needs: PlanNeed[]; source: 'llm' | 'heuristic' }> {\n const config = getConfig();\n if (config.SUMMARY_PROVIDER === 'openai' && config.SUMMARY_API_KEY) {\n const llm = await decomposeWithLlm(\n document,\n config.SUMMARY_API_KEY,\n config.SUMMARY_MODEL,\n config.SUMMARY_BASE_URL,\n ).catch((err) => {\n logger.warn(`plan: LLM decomposition failed, using heuristic: ${(err as Error).message}`);\n return null;\n });\n if (llm?.length) return { needs: dedupeNeeds(llm), source: 'llm' };\n }\n return { needs: decomposeHeuristic(document), source: 'heuristic' };\n}\n\nconst DECOMPOSE_SYSTEM =\n 'You break a software project description into the distinct technical components that each need a library. ' +\n 'Return ONLY components the project actually requires, grounded in the description. Respond with a JSON object.';\n\nasync function decomposeWithLlm(\n document: string,\n apiKey: string,\n model: string,\n baseUrl: string,\n): Promise<PlanNeed[]> {\n const prompt = [\n 'Project description:',\n document.slice(0, 8000),\n '',\n 'Return JSON: { \"needs\": [ { \"need\": \"<one phrase describing a component that needs a library>\", \"category\": \"<optional taxonomy hint or empty>\" } ] }.',\n 'One entry per distinct component (e.g. routing, validation, ORM, HTTP client). Omit anything not implied by the description.',\n ].join('\\n');\n const { data } = await httpRequest<any>(`${baseUrl.replace(/\\/$/, '')}/chat/completions`, {\n host: new URL(baseUrl).host,\n method: 'POST',\n ttlMs: 24 * 60 * 60 * 1000,\n // Hash the FULL document — length + a 64-char prefix collide for same-length\n // edits or shared templated headers, which would serve a stale decomposition.\n cacheKey: `openai-plan ${model} ${createHash('sha1').update(document).digest('hex')}`,\n headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },\n body: JSON.stringify({\n model,\n messages: [\n { role: 'system', content: DECOMPOSE_SYSTEM },\n { role: 'user', content: prompt },\n ],\n response_format: { type: 'json_object' },\n temperature: 0.2,\n }),\n });\n const content = data?.choices?.[0]?.message?.content;\n const parsed = content ? JSON.parse(content) : {};\n const raw = Array.isArray(parsed?.needs) ? parsed.needs : [];\n return raw\n .map((n: any): PlanNeed | null => {\n const need = typeof n?.need === 'string' ? n.need.trim() : '';\n if (!need) return null;\n const cat = typeof n?.category === 'string' && isCategory(n.category) ? n.category : undefined;\n return { need, category: cat };\n })\n .filter(Boolean) as PlanNeed[];\n}\n\n/**\n * Heuristic fallback: scan the document line-by-line, infer a category per line,\n * and emit one need per distinct category (first matching line as the phrase).\n * Coarse by design — it only surfaces components whose category lurq can name.\n */\nexport function decomposeHeuristic(document: string): PlanNeed[] {\n const byCategory = new Map<Category, string>();\n for (const rawLine of document.split('\\n')) {\n // Strip markdown headings/blockquotes/bullets, then an ordered-list \"12. \"\n // marker — but NOT bare leading digits, so \"2FA auth\" stays intact.\n const line = rawLine.replace(/^[#>*\\-\\s]+/, '').replace(/^\\d+\\.\\s+/, '').trim();\n if (line.length < 3) continue;\n const category = inferCategory(line);\n if (category && !byCategory.has(category)) {\n byCategory.set(category, line.slice(0, 120));\n }\n }\n return [...byCategory.entries()].map(([category, need]) => ({ need, category }));\n}\n","/**\n * Render a `plan` result as a self-contained HTML page: the Mermaid roadmap\n * rendered visually, plus the scored slot table. Mermaid is pulled from a CDN at\n * view time, so the file is a single portable artifact (no build step, no deps\n * added to the CLI). Used by `lurq plan --html <path>` / `--open`.\n */\nimport type { PlanOutput } from '../mcp/plan';\n\nfunction esc(s: string): string {\n return s.replace(/[&<>\"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '\"': '"' })[c]!);\n}\n\nfunction slotRows(plan: PlanOutput): string {\n return plan.slots\n .map((s) => {\n const rec = s.recommended;\n const name = rec\n ? rec.repoUrl\n ? `<a href=\"${esc(rec.repoUrl)}\" target=\"_blank\" rel=\"noreferrer\">${esc(rec.name)}</a>`\n : esc(rec.name)\n : '<span class=\"muted\">no match</span>';\n const alts = s.alternatives.map((a) => esc(a.name)).join(', ') || '<span class=\"muted\">-</span>';\n return `<tr>\n <td>${esc(s.need)}</td>\n <td><span class=\"layer\">${esc(s.layer)}</span></td>\n <td class=\"pkg\">${name}</td>\n <td class=\"num\">${rec ? rec.healthScore : '-'}</td>\n <td>${rec ? esc(rec.confidence) : '-'}</td>\n <td class=\"alts\">${alts}</td>\n </tr>`;\n })\n .join('\\n');\n}\n\nexport function renderPlanHtml(plan: PlanOutput): string {\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<title>lurq plan: roadmap</title>\n<style>\n :root { color-scheme: dark; }\n * { box-sizing: border-box; }\n body { margin: 0; font: 15px/1.5 ui-sans-serif, system-ui, -apple-system, sans-serif;\n background: #0b0b0f; color: #e7e7ea; padding: 2.5rem clamp(1rem, 5vw, 4rem); }\n h1 { font-size: 1.5rem; margin: 0 0 .25rem; }\n h2 { font-size: 1rem; text-transform: uppercase; letter-spacing: .08em; color: #9a9aa6; margin: 2.5rem 0 .75rem; }\n .sub { color: #9a9aa6; margin: 0 0 1rem; max-width: 70ch; }\n .diagram { background: #141419; border: 1px solid #26262e; border-radius: 14px; padding: 1.5rem; overflow: auto; }\n table { width: 100%; border-collapse: collapse; margin-top: .5rem; }\n th, td { text-align: left; padding: .55rem .75rem; border-bottom: 1px solid #1e1e25; vertical-align: top; }\n th { font-size: .78rem; text-transform: uppercase; letter-spacing: .05em; color: #9a9aa6; }\n .pkg a { color: #d98cff; text-decoration: none; } .pkg a:hover { text-decoration: underline; }\n .num { text-align: right; font-variant-numeric: tabular-nums; }\n .muted { color: #6a6a76; } .alts { color: #b8b8c2; font-size: .92rem; }\n .layer { font-size: .8rem; color: #8ad; background: #15202b; border-radius: 6px; padding: .1rem .45rem; }\n footer { margin-top: 2.5rem; color: #6a6a76; font-size: .85rem; }\n</style>\n</head>\n<body>\n <h1>lurq plan <span class=\"muted\">· ${esc(plan.optimize)} · ${esc(plan.source)}${plan.framework ? ` · ${esc(plan.framework)} ecosystem` : ''}</span></h1>\n <p class=\"sub\">${esc(plan.note)}</p>\n\n <h2>Roadmap</h2>\n <div class=\"diagram\"><pre class=\"mermaid\">${esc(plan.mermaid)}</pre></div>\n\n <h2>Components</h2>\n <table>\n <thead><tr><th>Component</th><th>Layer</th><th>Recommended</th><th>Health</th><th>Confidence</th><th>Alternatives</th></tr></thead>\n <tbody>\n${slotRows(plan)}\n </tbody>\n </table>\n\n <footer>data as of ${esc(plan.dataAsOf)} · generated by lurq</footer>\n\n <script type=\"module\">\n import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';\n mermaid.initialize({ startOnLoad: true, theme: 'dark' });\n </script>\n</body>\n</html>\n`;\n}\n","/**\n * Read/write helpers for the `discovery_queue` table (§2B). The crawler enqueues\n * candidates here; the merit gate pre-scores and graduates them.\n */\nimport { eq } from 'drizzle-orm';\nimport type { DiscoverySource, DiscoveryStatus } from '../core/types';\nimport type { Database } from './client';\nimport { discoveryQueue, packages, type DiscoveryQueueRow } from './schema';\n\nexport interface DiscoveryCandidate {\n name: string;\n via: DiscoverySource;\n}\n\n/** Names already tracked (in `packages`) or already queued — never re-enqueue. */\nexport async function getKnownNames(db: Database): Promise<Set<string>> {\n const [tracked, queued] = await Promise.all([\n db.select({ name: packages.name }).from(packages),\n db.select({ name: discoveryQueue.name }).from(discoveryQueue),\n ]);\n return new Set([...tracked.map((r) => r.name), ...queued.map((r) => r.name)]);\n}\n\n/** Names already sitting in the queue, at any status. The changes-feed follower\n * keeps this in memory so a package republishing twenty times in an hour costs\n * one insert attempt, not twenty — `onConflictDoNothing` would swallow the rest,\n * but each rejected row still burns a sequence value and an index probe. */\nexport async function getQueuedNames(db: Database): Promise<Set<string>> {\n const rows = await db.select({ name: discoveryQueue.name }).from(discoveryQueue);\n return new Set(rows.map((r) => r.name));\n}\n\n/** Insert new candidates, ignoring any that race in concurrently. Returns count inserted. */\nexport async function enqueueCandidates(\n db: Database,\n candidates: DiscoveryCandidate[],\n): Promise<number> {\n if (candidates.length === 0) return 0;\n const rows = candidates.map((c) => ({ name: c.name, discoveredVia: c.via }));\n const inserted = await db\n .insert(discoveryQueue)\n .values(rows)\n .onConflictDoNothing({ target: discoveryQueue.name })\n .returning({ id: discoveryQueue.id });\n return inserted.length;\n}\n\nexport async function getPendingCandidates(\n db: Database,\n limit: number,\n): Promise<DiscoveryQueueRow[]> {\n return db.select().from(discoveryQueue).where(eq(discoveryQueue.status, 'pending')).limit(limit);\n}\n\nexport async function setDiscoveryStatus(\n db: Database,\n name: string,\n data: { status: DiscoveryStatus; preScore?: number | null },\n): Promise<void> {\n await db\n .update(discoveryQueue)\n .set({\n status: data.status,\n ...(data.preScore !== undefined ? { preScore: data.preScore } : {}),\n })\n .where(eq(discoveryQueue.name, name));\n}\n","/**\n * v2 graph primitives (docs/lurq-v2-spec.md §2–§4).\n *\n * The load-bearing idea is the Oracle Rule: a node type may enter the graph only\n * if you can name the command that verifies it and what failure looks like. That\n * is a function signature, and this file is it. Adding a node type means writing\n * an `Oracle` and registering it — nothing downstream (preflight, breaks_at,\n * private mode) needs to know which oracle produced an observation.\n *\n * This runs ALONGSIDE the v1 npm tables, deliberately. v1's package path is the\n * only thing with users; migrating it onto this model to prove the shape is the\n * highest-risk/lowest-information move available. Migrate after a second node\n * type has shown the abstraction holds.\n */\nimport type { Sandbox } from '../sandbox/types';\n\n/** Node types. Extend only when the Oracle Rule is satisfiable for the new kind. */\nexport type EntityKind =\n /** P0 */\n | 'package_version'\n /** P0 — the central node type: highest query volume, and what breaks (§2). */\n | 'package_surface'\n /** P1 */\n | 'mcp_server'\n | 'mcp_tool'\n /** P2 */\n | 'api_spec'\n | 'schema_provider';\n\n/**\n * §4.1. The distinction between `verified_false` and `unknown` is the most\n * important thing in the API: an agent must always be able to tell \"we checked\n * and it does not work\" from \"we have not checked\".\n *\n * `unverifiable` must NEVER collapse into `verified_false` — an upstream rate\n * limit or a sandbox crash is not evidence about the subject. A single false\n * `verified_false` costs more trust than a hundred `unknown`s.\n */\nexport type Verdict =\n | 'verified_true'\n | 'verified_false'\n | 'unknown'\n | 'stale'\n /** Entity ships no usable artifact for this claim. NOT the same as absence:\n * 3.0% of study extractions resolved at no tier, and reporting those as\n * \"no exports\" would be a false removal. */\n | 'undeclared'\n | 'unverifiable';\n\n/**\n * §4.1. Orthogonal to the verdict: a verdict says what we concluded, a class says\n * what kind of evidence backs it.\n *\n * The rule that matters: a DERIVED claim inherits the WEAKEST class among its\n * inputs, and a DECLARED surface fact must never be presented as behavioural\n * evidence. \"This symbol is exported\" and \"this symbol works\" are different\n * claims and conflating them is how an index starts lying.\n */\nexport type EvidenceClass = 'declared' | 'executed' | 'derived';\n\n/** Identity of a node, before it has a database id. */\nexport interface EntityRef {\n kind: EntityKind;\n /** Registry or authority: 'npm', 'api.stripe.com', … */\n namespace: string;\n name: string;\n /** Null for kinds that aren't versioned. */\n version?: string | null;\n}\n\n/** `kind:namespace:name:version` — the dedup key. */\nexport function canonicalKey(ref: EntityRef): string {\n return `${ref.kind}:${ref.namespace}:${ref.name}:${ref.version ?? ''}`;\n}\n\n/**\n * §2. `runtime_env` is deliberately not a verifiable node — it is a fingerprint\n * attached to every verdict. \"Incompatible\" is meaningless without it: the same\n * pair resolves cleanly on one runtime and fails on another.\n */\nexport interface Environment {\n os: string;\n arch: string;\n runtime: string;\n runtimeVer: string;\n /** 'npm@10', 'uv@0.5', … Null when the oracle doesn't resolve dependencies. */\n resolver?: string | null;\n}\n\n/** One fact an oracle established, plus the evidence that established it. */\nexport interface OracleObservation {\n /** Subject is implied by the oracle's target; object is set for binary claims. */\n object?: EntityRef;\n /** `resolves_with`, `provides`, `conflicts_with`, … (§3) */\n relation: string;\n verdict: Verdict;\n /** Exit code, stderr tail, schema diff — whatever makes the verdict auditable. */\n evidence?: string;\n}\n\nexport interface OracleResult {\n observations: OracleObservation[];\n /** Child nodes discovered while verifying (e.g. the tools an MCP server lists). */\n discovered?: EntityRef[];\n costMillis: number;\n}\n\n/**\n * The Oracle Rule as a type. `run` must never throw for a subject-side failure —\n * that is a `verified_false` observation with evidence. Throw only when the\n * oracle itself could not run, and the caller records `unverifiable`.\n */\nexport interface Oracle<T extends EntityRef = EntityRef> {\n /** Stable id, e.g. 'mcp_server.handshake'. */\n readonly id: string;\n /** Bump when the oracle's semantics change; invalidates prior observations. */\n readonly version: string;\n readonly kind: EntityKind;\n /** Past this age an observation reads as `stale` (§4.1, applied at read time). */\n readonly ttlHours: number;\n /** One sentence: what we run, and what failure looks like. Enforced by review. */\n readonly rule: string;\n run(target: T, env: Environment, sandbox: Sandbox): Promise<OracleResult>;\n}\n","/**\n * Read/write helpers for the v2 graph (entities / environments / claims /\n * observations). See docs/lurq-v2-spec.md §5.\n *\n * The only invariant that matters here: `observations` is APPEND-ONLY. Nothing\n * in this file updates a verdict, and nothing should ever be added that does —\n * `breaks_at` is derived by scanning the history, so overwriting destroys the\n * product. `stale` is computed at read time from the oracle's TTL.\n */\nimport { and, eq, isNull } from 'drizzle-orm';\nimport { createHash } from 'node:crypto';\nimport type { Database } from './client';\nimport { claims, entities, environments, observations } from './schema';\nimport type { ClaimRow, EntityRow, EnvironmentRow } from './schema';\nimport {\n canonicalKey,\n type Environment,\n type EntityRef,\n type EvidenceClass,\n type Verdict,\n} from '../graph/types';\nimport type { ExtractionTier } from '../surface/types';\n\n/** Stable hash of the runtime dimensions — the environment dedup key. */\nexport function fingerprint(env: Environment): string {\n const parts = [env.os, env.arch, env.runtime, env.runtimeVer, env.resolver ?? ''];\n return createHash('sha256').update(parts.join('\\0')).digest('hex').slice(0, 32);\n}\n\nexport async function upsertEnvironment(db: Database, env: Environment): Promise<EnvironmentRow> {\n const fp = fingerprint(env);\n const [row] = await db\n .insert(environments)\n .values({ ...env, resolver: env.resolver ?? null, fingerprint: fp })\n .onConflictDoUpdate({\n target: environments.fingerprint,\n // No-op update so the RETURNING clause yields the existing row.\n set: { fingerprint: fp },\n })\n .returning();\n return row!;\n}\n\nexport async function upsertEntity(\n db: Database,\n ref: EntityRef,\n tenantId = 0,\n): Promise<EntityRow> {\n const key = canonicalKey(ref);\n const [row] = await db\n .insert(entities)\n .values({\n kind: ref.kind,\n namespace: ref.namespace,\n name: ref.name,\n version: ref.version ?? null,\n canonicalKey: key,\n tenantId,\n })\n .onConflictDoUpdate({\n target: [entities.canonicalKey, entities.tenantId],\n set: { canonicalKey: key },\n })\n .returning();\n return row!;\n}\n\nexport async function upsertClaim(\n db: Database,\n args: {\n subjectId: number;\n objectId?: number | null;\n relation: string;\n /** Null for declared claims — they hold in every environment (§5). */\n environmentId?: number | null;\n tenantId?: number;\n },\n): Promise<ClaimRow> {\n const objectId = args.objectId ?? null;\n const envId = args.environmentId ?? null;\n const tenantId = args.tenantId ?? 0;\n const existing = await db\n .select()\n .from(claims)\n .where(\n and(\n eq(claims.subjectId, args.subjectId),\n objectId === null ? isNull(claims.objectId) : eq(claims.objectId, objectId),\n eq(claims.relation, args.relation),\n envId === null ? isNull(claims.environmentId) : eq(claims.environmentId, envId),\n eq(claims.tenantId, tenantId),\n ),\n )\n .limit(1);\n if (existing[0]) return existing[0];\n\n // The unique index can't dedup NULL object_id or environment_id (Postgres\n // treats NULLs as distinct), so the select above is the real guard and this\n // insert races benignly: a duplicate claim costs one redundant row, never a\n // wrong verdict. Fully-populated tuples are protected by the index.\n const [row] = await db\n .insert(claims)\n .values({ subjectId: args.subjectId, objectId, relation: args.relation, environmentId: envId, tenantId })\n .returning();\n return row!;\n}\n\nexport async function recordObservation(\n db: Database,\n args: {\n claimId: number;\n verdict: Verdict;\n /** What kind of evidence backs it (§4.1). Defaults to executed for oracles. */\n class?: EvidenceClass;\n /** Extraction tier, for declared claims; null for executed ones (§6.2). */\n tier?: ExtractionTier | null;\n evidence?: string | null;\n oracleId: string;\n oracleVer: string;\n costMillis?: number | null;\n },\n): Promise<void> {\n await db.insert(observations).values({\n claimId: args.claimId,\n verdict: args.verdict,\n class: args.class ?? 'executed',\n tier: args.tier ?? null,\n evidence: args.evidence ?? null,\n oracleId: args.oracleId,\n oracleVer: args.oracleVer,\n costMillis: args.costMillis ?? null,\n });\n}\n\n/**\n * §4.1, applied at READ time — never written by a background job.\n *\n * A verdict past its oracle's TTL reads as `stale`, never as its original value.\n * `unknown` never goes stale (there is nothing to expire), and it must stay\n * distinguishable from `verified_false`: \"we have not checked\" is a different\n * answer from \"we checked and it does not work\".\n */\nexport function applyTtl(\n verdict: Verdict,\n observedAt: Date,\n ttlHours: number,\n now = Date.now(),\n): Verdict {\n if (verdict === 'unknown' || verdict === 'unverifiable' || verdict === 'undeclared')\n return verdict;\n const ageHours = (now - observedAt.getTime()) / 3_600_000;\n return ageHours > ttlHours ? 'stale' : verdict;\n}\n","/**\n * Surface persistence (§5, §6.5).\n *\n * Two responsibilities:\n * 1. Store an extracted surface as `symbols` + an `observation` recording how\n * it was established (class + tier), never overwriting history.\n * 2. Skip re-extraction when the artifact digest is unchanged — the content-\n * addressed cache that keeps cost sublinear as the index grows.\n *\n * Nothing here executes package code; extraction upstream is static (§9.2).\n */\nimport { and, desc, eq, isNotNull, isNull, sql } from 'drizzle-orm';\nimport type { Database } from './client';\nimport { claims, entities, observations, packages, surfaceQueue, symbols } from './schema';\nimport type { SurfaceQueueRow } from './schema';\nimport { recordObservation, upsertClaim, upsertEntity } from './graph';\nimport { canonicalKey, type EntityKind, type EntityRef } from '../graph/types';\nimport type { ExtractedSurface, ExtractionTier } from '../surface/types';\n\n/** The entity ref for a package version's surface. */\nexport function surfaceRef(pkg: string, version: string | null): EntityRef {\n return { kind: 'package_surface', namespace: 'npm', name: pkg, version };\n}\n\n/**\n * The entity ref for an MCP server's tool surface.\n *\n * A DIFFERENT node kind, not a different namespace: `express` the npm package\n * and `express` an MCP server published under the same name are different\n * things with different contracts, and `canonicalKey` puts `kind` first\n * precisely so the two can coexist without one answering for the other. The\n * namespace stays `npm` because that is still where the artifact is fetched\n * from — it is the registry, not the unit type.\n */\nexport function mcpSurfaceRef(server: string, version: string | null): EntityRef {\n return { kind: 'mcp_server', namespace: 'npm', name: server, version };\n}\n\n/**\n * Is a stored surface still good, or does it need extracting again?\n *\n * This compared the tarball digest alone, and a published tarball never\n * changes — so once a package was extracted it was cached forever and no\n * improvement to the extractor could ever reach stored data. Two landed the\n * same day: the ESM-first entry fallback (date-fns and vitest had no readable\n * surface) and namespace member resolution (zod presented as one symbol). A\n * full re-extraction over 2,780 packages reported success and changed nothing,\n * because every call returned 'cached'.\n *\n * The extractor version was already being recorded — `storeSurface` writes it\n * as the observation's `oracleVer` — it was simply never read back. A cache key\n * has to contain everything the value depends on, and the surface depends on\n * the code that produced it as much as on the bytes it was produced from.\n */\nexport async function isExtractionCached(\n db: Database,\n ref: EntityRef,\n artifactHash: string,\n extractorVersion: string,\n tier: ExtractionTier = 'shipped_js_ast',\n tenantId = 0,\n): Promise<boolean> {\n const row = await upsertEntity(db, ref, tenantId);\n if (row.artifactHash !== artifactHash) return false;\n const existing = await db\n .select({ id: symbols.id })\n .from(symbols)\n .where(and(eq(symbols.entityId, row.id), eq(symbols.tier, tier)))\n .limit(1);\n if (existing.length === 0) return false;\n\n // Extracted by which version of the extractor? Anything but the current one\n // is stale by definition, however unchanged the tarball is.\n const seen = await db\n .select({ oracleVer: observations.oracleVer })\n .from(observations)\n .innerJoin(claims, eq(claims.id, observations.claimId))\n .where(\n and(\n eq(claims.subjectId, row.id),\n eq(claims.relation, 'exposes'),\n eq(observations.tier, tier),\n ),\n )\n .orderBy(desc(observations.observedAt))\n .limit(1);\n return seen[0]?.oracleVer === extractorVersion;\n}\n\n/**\n * Persist an extracted surface.\n *\n * An empty surface is recorded as `undeclared` with the extractor's stated\n * reason — never as \"this package exports nothing\" (§4.2, §6.4.2). That\n * distinction is the difference between a measurement gap and a false removal.\n */\nexport async function storeSurface(\n db: Database,\n surface: ExtractedSurface,\n opts: {\n artifactHash?: string | null;\n extractorVersion: string;\n tenantId?: number;\n /** Defaults to the npm package-surface ref. Non-npm units pass their own. */\n ref?: EntityRef;\n /** Which oracle established this. Defaults to the tier-A extractor. */\n oracleId?: string;\n } = {\n extractorVersion: '1',\n },\n): Promise<{ entityId: number; symbolsWritten: number; verdict: string }> {\n const tenantId = opts.tenantId ?? 0;\n const ref = opts.ref ?? surfaceRef(surface.package, surface.version);\n const entity = await upsertEntity(db, ref, tenantId);\n\n if (opts.artifactHash) {\n await db\n .update(entities)\n .set({ artifactHash: opts.artifactHash })\n .where(eq(entities.id, entity.id));\n }\n\n const claim = await upsertClaim(db, {\n subjectId: entity.id,\n relation: 'exposes',\n // Declared claims are environment-independent: a shipped-JS surface reads\n // identically on every machine, so no fingerprint is attached (§5).\n environmentId: null,\n tenantId,\n });\n\n const undeclared = surface.symbols.length === 0;\n await recordObservation(db, {\n claimId: claim.id,\n verdict: undeclared ? 'undeclared' : 'verified_true',\n class: 'declared',\n tier: surface.tier,\n evidence: undeclared\n ? (surface.undeclaredReason ?? 'no symbols extracted')\n : `${surface.symbols.length} symbols from ${surface.filesWalked} file(s), entry ${surface.entry}`,\n oracleId: opts.oracleId ?? 'surface.tier_a',\n oracleVer: opts.extractorVersion,\n });\n\n if (undeclared) return { entityId: entity.id, symbolsWritten: 0, verdict: 'undeclared' };\n\n // Replace only THIS tier's rows: a tier-C surface must never clear the tier-A\n // one, since they answer different questions (§6.4.3). Symbols snapshot an\n // immutable artifact; the history that matters lives in `observations`.\n await db\n .delete(symbols)\n .where(and(eq(symbols.entityId, entity.id), eq(symbols.tier, surface.tier)));\n const rows = surface.symbols.map((s) => ({\n entityId: entity.id,\n path: s.path,\n kind: s.kind,\n arity: s.arity,\n origin: s.origin,\n deprecated: s.deprecated,\n tier: s.tier,\n signature: s.signature ?? null,\n sourceFile: s.sourceRef?.file ?? null,\n sourceLine: s.sourceRef?.line ?? null,\n }));\n for (let i = 0; i < rows.length; i += 500) {\n await db\n .insert(symbols)\n .values(rows.slice(i, i + 500))\n .onConflictDoNothing();\n }\n\n return { entityId: entity.id, symbolsWritten: rows.length, verdict: 'verified_true' };\n}\n\n/**\n * Dedup key for the extraction queue.\n *\n * The npm form is left exactly as it was and the kind is prefixed only for\n * everything else — the same defaulted-parameter trick `ecosystem` uses. Keying\n * every row would have been tidier and would also have orphaned every spec\n * already sitting in the queue, re-enqueueing the whole backlog under new keys\n * for no gain.\n */\nexport function specKey(\n pkg: string,\n version: string | null,\n kind: EntityKind = 'package_surface',\n): string {\n const base = `${pkg}@${version ?? 'latest'}`;\n return kind === 'package_surface' ? base : `${kind}:${base}`;\n}\n\n/**\n * Record a query miss (§6.1). Instant, deduped, and never blocking — the query\n * path returns UNKNOWN and the worker does the work.\n */\n/**\n * Packages whose LATEST version has no surface in the graph store.\n *\n * Deliberately distinct from `getPackagesMissingSurface` in `db/apiSurfaces`,\n * and the difference is the whole reason this exists. There are two surface\n * stores serving two different questions:\n *\n * api_surfaces — a flat export list per version, backing `usage`. Filled by\n * the worker's proactive pass, ~26.9k packages covered.\n * entities + — structured symbols (kind, arity, origin, deprecation),\n * symbols backing `resolve_surface` and `diff_surface`. Only a diff\n * can be computed from these, and only ~2.9k are covered.\n *\n * The proactive pass selected its targets with the api_surfaces query and wrote\n * to api_surfaces, so nothing ever proactively filled the graph store — it grew\n * only from demand-driven queue misses at ten per cycle. A package already in\n * api_surfaces was invisible to every backfill even though the diffable store\n * had never seen it, which is why coverage of the differentiated tools sat an\n * order of magnitude below coverage of the cheap one.\n *\n * Sampled at random rather than ordered, for the same reason the sibling query\n * is: a package that repeatedly fails extraction would otherwise sit at the head\n * of every batch forever and starve the rest of the index.\n */\nexport async function getPackagesMissingGraphSurface(\n db: Database,\n limit: number,\n opts: { byDownloads?: boolean } = {},\n): Promise<{ name: string; version: string }[]> {\n // Random is the right default for eventual full coverage — it stops a\n // repeatedly-failing package from sitting at the head of every batch and\n // starving the tail. `byDownloads` is for closing the gap that matters to a\n // user: a real package.json is made of popular packages, so covering the head\n // of the distribution first is what turns `check-upgrade` from a demo into a\n // tool that answers on the dependencies someone actually has.\n const order = opts.byDownloads ? sql`${packages.weeklyDownloads} desc nulls last` : sql`random()`;\n const rows = await db\n .select({ name: packages.name, version: packages.latestVersion })\n .from(packages)\n .leftJoin(\n entities,\n and(\n eq(entities.kind, 'package_surface'),\n eq(entities.name, packages.name),\n eq(entities.version, packages.latestVersion),\n ),\n )\n .where(and(isNotNull(packages.latestVersion), isNull(entities.id)))\n .orderBy(order)\n .limit(limit);\n return rows.filter((r): r is { name: string; version: string } => r.version !== null);\n}\n\nexport async function enqueueSurface(\n db: Database,\n pkg: string,\n version: string | null,\n kind: EntityKind = 'package_surface',\n): Promise<void> {\n await db\n .insert(surfaceQueue)\n .values({ packageName: pkg, version, kind, specKey: specKey(pkg, version, kind) })\n .onConflictDoNothing();\n}\n\n/**\n * Oldest pending specs for ONE extractor, for the worker drain.\n *\n * Filtered by kind rather than returning everything: the two drains do\n * completely different work (static tarball read vs. sandboxed stdio handshake)\n * and handing an MCP spec to the npm drain produces a confident wrong answer\n * rather than an error.\n */\nexport async function getPendingSurfaces(\n db: Database,\n limit = 10,\n kind: EntityKind = 'package_surface',\n): Promise<SurfaceQueueRow[]> {\n return db\n .select()\n .from(surfaceQueue)\n .where(eq(surfaceQueue.kind, kind))\n .orderBy(surfaceQueue.requestedAt)\n .limit(limit);\n}\n\nexport async function dropSurfaceQueue(db: Database, id: number): Promise<void> {\n await db.delete(surfaceQueue).where(eq(surfaceQueue.id, id));\n}\n\nexport async function bumpSurfaceAttempt(db: Database, id: number): Promise<void> {\n await db\n .update(surfaceQueue)\n .set({ attempts: sql`${surfaceQueue.attempts} + 1` })\n .where(eq(surfaceQueue.id, id));\n}\n\n/**\n * Is a surface already stored for this exact `package@version`?\n *\n * Read-only on purpose: `isExtractionCached` goes through `upsertEntity` and so\n * *creates* the entity as a side effect of asking about it, which is fine when\n * you are about to extract but wrong when you are only deciding whether to\n * enqueue. Asking \"do we have this?\" must not bring it into existence.\n */\nexport async function hasStoredSurface(\n db: Database,\n pkg: string,\n version: string,\n tier: ExtractionTier = 'shipped_js_ast',\n tenantId = 0,\n kind: EntityKind = 'package_surface',\n): Promise<boolean> {\n const key = canonicalKey(\n kind === 'mcp_server' ? mcpSurfaceRef(pkg, version) : surfaceRef(pkg, version),\n );\n const [row] = await db\n .select({ id: entities.id })\n .from(entities)\n .where(and(eq(entities.canonicalKey, key), eq(entities.tenantId, tenantId)))\n .limit(1);\n if (!row) return false;\n const [sym] = await db\n .select({ id: symbols.id })\n .from(symbols)\n .where(and(eq(symbols.entityId, row.id), eq(symbols.tier, tier)))\n .limit(1);\n return sym !== undefined;\n}\n\n/**\n * Make `version` diffable by ensuring its predecessor is also extracted.\n *\n * A surface on its own answers \"what does this export\". The question that\n * actually bites — \"what did this release remove or rename\" — needs two adjacent\n * versions, and that is exactly what a model trained before the release cannot\n * know. Coverage was one version deep for all but 4.5% of packages, which is why\n * the diff existed but almost never had anything to compare.\n *\n * Bounded on purpose: N-1 only, never the whole timeline. One extra extraction\n * per package, once, and thereafter the publish feed keeps the pair rolling\n * forward on its own. Full history would be 91 versions per package for a\n * question nobody asks — people upgrade from the version they are on.\n */\nexport async function enqueuePreviousSurface(\n db: Database,\n pkg: string,\n version: string,\n history: { version: string }[],\n kind: EntityKind = 'package_surface',\n): Promise<boolean> {\n const previous = previousVersion(history, version);\n if (previous === null) return false;\n const tier: ExtractionTier = kind === 'mcp_server' ? 'mcp_tools_list' : 'shipped_js_ast';\n if (await hasStoredSurface(db, pkg, previous, tier, 0, kind)) return false;\n await enqueueSurface(db, pkg, previous, kind);\n return true;\n}\n\n/**\n * The version published immediately before `version`, given a newest-first\n * timeline. Null when there is nothing to compare against.\n *\n * Ordering comes from `published_at`, not from semver, and that is deliberate:\n * a backport releasing 3.9.2 after 4.0.0 shipped means the predecessor by time\n * is not the predecessor by number. The question a diff answers is \"what changed\n * when this was released\", so publication order is the honest one.\n */\nexport function previousVersion(history: { version: string }[], version: string): string | null {\n const idx = history.findIndex((h) => h.version === version);\n // Not in the timeline, or already the oldest we know: nothing to compare to.\n if (idx === -1 || idx + 1 >= history.length) return null;\n return history[idx + 1]!.version ?? null;\n}\n\n/**\n * Every npm package we have ever probed as an MCP server.\n *\n * The MCP roster, derived rather than curated: a server enters it the first\n * time anything asks about it, so the set grows with real demand instead of\n * with someone remembering to maintain a list. The publish feed intersects it\n * with the tracked set to decide which publishes deserve a re-probe.\n */\nexport async function getMcpServerNames(db: Database, tenantId = 0): Promise<string[]> {\n const rows = await db\n .selectDistinct({ name: entities.name })\n .from(entities)\n .where(and(eq(entities.kind, 'mcp_server'), eq(entities.tenantId, tenantId)));\n return rows.map((r) => r.name);\n}\n","/**\n * Cursor persistence for the npm `_changes` follower (one row per feed in\n * `watch_state`), so a restart resumes from the last processed sequence instead\n * of replaying the registry from the beginning.\n */\nimport { eq } from 'drizzle-orm';\nimport type { Database } from './client';\nimport { watchState } from './schema';\n\nexport async function getWatchCursor(db: Database, id: string): Promise<string | null> {\n const rows = await db\n .select({ seq: watchState.seq })\n .from(watchState)\n .where(eq(watchState.id, id))\n .limit(1);\n return rows[0]?.seq ?? null;\n}\n\nexport async function setWatchCursor(db: Database, id: string, seq: string): Promise<void> {\n await db\n .insert(watchState)\n .values({ id, seq, updatedAt: new Date() })\n .onConflictDoUpdate({ target: watchState.id, set: { seq, updatedAt: new Date() } });\n}\n","/**\n * npm `_changes` follower — the registry's publish log.\n *\n * Two jobs, one stream:\n *\n * 1. A *tracked* package publishes → re-sync it, so scores, advisories and the\n * version timeline stay fresh without a full crawl.\n * 2. An *unknown* name appears → queue it as a discovery candidate.\n *\n * (2) is the only growth channel that scales. The other two are bounded by\n * construction: `graphChannel` can only reach packages adjacent to ones we\n * already have, and `searchChannel` can only reach what npm's ranking will\n * paginate. Both had run dry — the discovery queue was sitting at zero pending\n * while the crawler had capacity for ~9,600 ingests a day. This feed is npm\n * telling us about every publish as it happens, and the follower used to drop\n * every unrecognised name on the floor.\n *\n * Candidates are only *queued* here, never ingested: the §2B merit gate still\n * pre-scores each one on quality signals and rejects the vast majority. The feed\n * supplies volume; the gate keeps the index honest.\n *\n * **Polled, not streamed.** This followed `?feed=continuous&since=now` as an\n * NDJSON stream, which the registry now answers with a flat 400 — as it does for\n * `feed=normal` and any non-numeric `since`. Whatever this was tested against is\n * gone; what is served today is a batched page, `?since=<seq>&limit=<n>` →\n * `{results, last_seq}`, so the follower pages forward and idles when it catches\n * up. Resumable either way: the cursor is a sequence number in `watch_state`, and\n * with none stored it starts from the head rather than replaying all of npm.\n */\nimport { logger } from '../core/logger';\nimport type { Database } from '../db/client';\nimport { enqueueCandidates, getQueuedNames } from '../db/discovery';\nimport { getAllPackageNames } from '../db/packages';\nimport { enqueueSurface, getMcpServerNames } from '../db/surface';\nimport { getWatchCursor, setWatchCursor } from '../db/watch';\nimport { syncOnePackage } from './single';\n\nconst FEED_ID = 'npm-changes';\nconst FEED_URL = 'https://replicate.npmjs.com/_changes';\n/** Changes per request. The registry serves 10k happily; 1k keeps a single\n * failed page cheap to retry and the memory flat while catching up. */\nconst PAGE_SIZE = 1000;\n/** Wait this long after a page that did not fill — we are at the head. */\nconst IDLE_POLL_MS = 30_000;\nconst TRACKED_REFRESH_MS = 5 * 60_000; // re-read the membership sets this often\nconst MAX_BACKOFF_MS = 30_000;\n/** Buffered new names flushed per insert, so a busy page is one round-trip. */\nconst ENQUEUE_BATCH = 200;\n\nexport interface ChangeRecord {\n seq: number | string;\n id: string;\n deleted: boolean;\n}\n\n/** Coerce one entry of the `results` array; null for anything malformed. */\nexport function parseChange(obj: unknown): ChangeRecord | null {\n if (typeof obj !== 'object' || obj === null) return null;\n const rec = obj as { seq?: unknown; id?: unknown; deleted?: unknown };\n if (typeof rec.id !== 'string' || rec.seq == null) return null;\n if (typeof rec.seq !== 'number' && typeof rec.seq !== 'string') return null;\n return { seq: rec.seq, id: rec.id, deleted: Boolean(rec.deleted) };\n}\n\nexport interface ChangesPage {\n changes: ChangeRecord[];\n lastSeq: string | null;\n}\n\n/** Coerce a `_changes` response body. A page we cannot read is an empty page,\n * never a crash — the caller backs off and retries the same cursor. */\nexport function parseChangesPage(body: unknown): ChangesPage {\n if (typeof body !== 'object' || body === null) return { changes: [], lastSeq: null };\n const { results, last_seq: lastSeq } = body as { results?: unknown; last_seq?: unknown };\n const changes = Array.isArray(results)\n ? results.map(parseChange).filter((c): c is ChangeRecord => c !== null)\n : [];\n return {\n changes,\n lastSeq: typeof lastSeq === 'number' || typeof lastSeq === 'string' ? String(lastSeq) : null,\n };\n}\n\n/** What the follower does with one change record. */\nexport type ChangeRoute = 'resync' | 'enqueue' | 'skip';\n\n/**\n * Decide the fate of a single change. Pure, so the routing rule is testable\n * without a feed, a database or a clock — this is the branch the whole growth\n * channel hangs off, and it used to send everything but `resync` to `skip`.\n */\nexport function routeChange(\n change: ChangeRecord,\n tracked: Set<string>,\n queued: Set<string>,\n): ChangeRoute {\n if (change.deleted) return 'skip'; // unpublished: nothing to sync, nothing worth queueing\n if (tracked.has(change.id)) return 'resync';\n if (queued.has(change.id)) return 'skip'; // already waiting on the merit gate\n return 'enqueue';\n}\n\nexport interface WatchOptions {\n signal?: AbortSignal;\n /** Sequence to start from when no cursor is stored. Default: the current head,\n * i.e. only changes published from now on. */\n since?: string;\n /** Injected for tests. Defaults to global fetch. */\n fetchImpl?: typeof fetch;\n}\n\nasync function getJson(url: string, fetchImpl: typeof fetch, signal?: AbortSignal) {\n const res = await fetchImpl(url, { signal });\n if (!res.ok) throw new Error(`feed responded ${res.status}`);\n return res.json();\n}\n\n/** The newest sequence the registry knows about, for a first-ever start. */\nexport async function fetchHeadSeq(\n fetchImpl: typeof fetch = fetch,\n signal?: AbortSignal,\n): Promise<string | null> {\n const body = await getJson(`${FEED_URL}?descending=true&limit=1`, fetchImpl, signal);\n return parseChangesPage(body).lastSeq;\n}\n\n/** The membership sets the loop decides against: what we already track (→\n * re-sync on publish), what is already queued (→ skip, the gate will get to\n * it), and which of the tracked names are MCP servers (→ also re-probe the\n * tool contract). Read together so a refresh can never leave them from\n * different moments. */\nasync function loadSeenSets(\n db: Database,\n): Promise<[Set<string>, Set<string>, Set<string>]> {\n const [tracked, queued, mcp] = await Promise.all([\n getAllPackageNames(db),\n getQueuedNames(db),\n // Derived from what has actually been probed, so the roster grows with real\n // demand instead of with a curated list somebody has to maintain. Failure\n // is non-fatal: the npm half of the loop must keep running regardless.\n getMcpServerNames(db).catch(() => [] as string[]),\n ]);\n return [new Set(tracked), queued, new Set(mcp)];\n}\n\nexport async function watchNpmChanges(db: Database, opts: WatchOptions = {}): Promise<void> {\n const { signal, fetchImpl = fetch } = opts;\n let backoff = 1000;\n\n let [tracked, queued, mcpServers] = await loadSeenSets(db);\n let seenAt = Date.now();\n\n let cursor =\n (await getWatchCursor(db, FEED_ID)) ??\n opts.since ??\n (await fetchHeadSeq(fetchImpl, signal).catch(() => null));\n if (cursor == null) {\n logger.warn('watch: could not establish a starting sequence; giving up.');\n return;\n }\n logger.info(\n `watch: following from seq=${cursor} (${tracked.size} tracked, ${queued.size} queued, ${mcpServers.size} mcp)`,\n );\n\n while (!signal?.aborted) {\n try {\n const url = `${FEED_URL}?since=${encodeURIComponent(cursor)}&limit=${PAGE_SIZE}`;\n const { changes, lastSeq } = parseChangesPage(await getJson(url, fetchImpl, signal));\n backoff = 1000; // healthy response, reset\n\n if (Date.now() - seenAt > TRACKED_REFRESH_MS) {\n [tracked, queued, mcpServers] = await loadSeenSets(db);\n seenAt = Date.now();\n }\n\n const buffered: string[] = [];\n const flush = async (): Promise<void> => {\n if (buffered.length === 0) return;\n const batch = buffered.map((name) => ({ name, via: 'npm-changes' as const }));\n const inserted = await enqueueCandidates(db, batch).catch((err) => {\n // Keep following the feed; these names come back on their next publish,\n // and the other discovery channels still run.\n logger.warn(`watch: enqueue of ${batch.length} candidate(s) failed: ${String(err)}`);\n return 0;\n });\n if (inserted > 0) logger.info(`watch: queued ${inserted} new discovery candidate(s)`);\n buffered.length = 0;\n };\n\n let resynced = 0;\n let mcpQueued = 0;\n for (const change of changes) {\n if (signal?.aborted) break;\n const route = routeChange(change, tracked, queued);\n if (route === 'resync') {\n await syncOnePackage(db, change.id).catch((err) =>\n logger.warn(`watch: re-sync failed for ${change.id}: ${String(err)}`),\n );\n resynced++;\n // A publish is the only moment a new API surface exists, and this feed\n // is the only place we learn about one within seconds of it landing.\n //\n // This is what makes surface coverage dynamic instead of a curated\n // list. It follows npm rather than choosing packages, so the long tail\n // — half of all publish volume, and per the drift study the place\n // models have the weakest priors (18.7% vs 8.3% at low in-degree) — is\n // covered by construction rather than by remembering to add it.\n //\n // Null version means \"whatever latest resolves to at extraction time\",\n // which is what the re-sync above just moved it to. Deduped by\n // spec_key, so a package publishing twenty times an hour costs one\n // pending row, and never blocking: the worker does the work.\n await enqueueSurface(db, change.id, null).catch((err) =>\n logger.warn(`watch: surface enqueue failed for ${change.id}: ${String(err)}`),\n );\n\n // If this package is also an MCP server, its TOOL CONTRACT may have\n // moved — a different artifact from its exports, and one a published\n // tarball's immutability says nothing about.\n //\n // This is the line that turns MCP drift from something a user has to\n // go and ask about into something lurq notices. Without it a server\n // was re-read only when somebody ran `audit --probe` by hand, which\n // is exactly the upkeep npm packages have always had and MCP servers\n // did not.\n if (mcpServers.has(change.id)) {\n await enqueueSurface(db, change.id, null, 'mcp_server').catch((err) =>\n logger.warn(`watch: mcp probe enqueue failed for ${change.id}: ${String(err)}`),\n );\n mcpQueued++;\n }\n } else if (route === 'enqueue') {\n // Record it locally as we buffer, so the same package publishing twenty\n // times in an hour costs one insert attempt rather than twenty.\n queued.add(change.id);\n buffered.push(change.id);\n if (buffered.length >= ENQUEUE_BATCH) await flush();\n }\n }\n\n // Flush BEFORE advancing the cursor, never after. A crash between the two\n // replays a page, which `onConflictDoNothing` absorbs; a crash the other\n // way drops names the cursor already claims we handled, and nothing would\n // ever go back for them.\n await flush();\n if (lastSeq !== null && lastSeq !== cursor) {\n cursor = lastSeq;\n await setWatchCursor(db, FEED_ID, cursor);\n }\n if (changes.length > 0) {\n logger.info(\n `watch: ${changes.length} change(s), ${resynced} re-synced` +\n (mcpQueued ? `, ${mcpQueued} mcp re-probe(s)` : '') +\n `, seq=${cursor}`,\n );\n }\n\n // A page that did not fill means we are at the head — stop hammering.\n if (changes.length < PAGE_SIZE) await sleep(IDLE_POLL_MS, signal);\n } catch (err) {\n if (signal?.aborted) break;\n logger.warn(`watch: ${String(err)}, retrying in ${backoff}ms`);\n await sleep(backoff, signal);\n backoff = Math.min(backoff * 2, MAX_BACKOFF_MS);\n }\n }\n logger.info('watch: stopped.');\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n const timer = setTimeout(resolve, ms);\n signal?.addEventListener(\n 'abort',\n () => {\n clearTimeout(timer);\n resolve();\n },\n { once: true },\n );\n });\n}\n","/**\n * Sandbox driver contract.\n *\n * Verification runs an install + smoke-load of a package version in an isolated\n * environment and reports whether it *actually* installs and loads — evidence no\n * static signal (downloads, stars) can provide.\n *\n * The interface is deliberately small so the runner is swappable: a local\n * child-process driver for dev/operator use, and a VM-isolated driver (E2B /\n * Firecracker / gVisor) for verifying UNTRUSTED packages at scale. Callers\n * depend only on this contract, never on a concrete driver.\n */\n\nexport type ModuleSystem = 'esm' | 'cjs';\n\nexport interface SandboxTarget {\n /** Node major the run targets. The local driver uses the host Node and just\n * records this; a VM driver provisions it. */\n node: string;\n moduleSystem: ModuleSystem;\n}\n\nexport interface SandboxVerifyOptions {\n target?: SandboxTarget;\n /** Run lifecycle install scripts (preinstall/install/postinstall). Off by\n * default: running untrusted scripts needs VM isolation, not a bare driver. */\n allowScripts?: boolean;\n timeoutMs?: number;\n signal?: AbortSignal;\n /** When set, only these packages are smoke-loaded after install. The full\n * install list is still co-installed. Defaults to the install list itself.\n * Use this to install all packages but smoke-load only runtime ones. */\n smokePackages?: SandboxPackage[];\n}\n\nexport interface SandboxResult {\n /** Provenance tag for the driver that produced this ('local', 'e2b', ...). */\n driver: string;\n moduleSystem: ModuleSystem;\n /** `npm install` succeeded. */\n installed: boolean;\n /** Package loaded (import/require without throwing). null = not attempted\n * because the install failed. */\n imported: boolean | null;\n /** Whether install scripts were allowed to run for this result. */\n ranScripts: boolean;\n durationMs: number;\n /** Condensed first line(s) of the failure, if any. */\n error: string | null;\n}\n\nexport interface SandboxPackage {\n name: string;\n version: string | null;\n}\n\nexport interface SandboxSetResult {\n driver: string;\n moduleSystem: ModuleSystem;\n /** Co-install of the whole set succeeded. */\n installed: boolean;\n /** Per-package smoke-load (null = not attempted because the install failed). */\n loaded: { name: string; loaded: boolean | null }[];\n durationMs: number;\n error: string | null;\n}\n\nexport interface ExecResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nexport interface ExecOptions {\n timeoutMs?: number;\n signal?: AbortSignal;\n /** Install these before running the command (same flags as a verify install). */\n install?: SandboxPackage[];\n allowScripts?: boolean;\n}\n\nexport interface Sandbox {\n /** Provenance tag stored with each result. */\n readonly name: string;\n /**\n * Run an arbitrary command in a throwaway sandbox, optionally after installing\n * packages. This is the generic escape hatch every non-npm oracle needs — an\n * MCP handshake, a `--help` probe, a container smoke test. A non-zero exit is\n * a RESULT, not an error: it resolves with the exit code so the oracle can\n * decide whether that means `verified_false`. Only infrastructure failures\n * (the sandbox itself dying) throw.\n */\n exec(command: string, opts?: ExecOptions): Promise<ExecResult>;\n verify(\n pkg: string,\n version: string | null,\n opts?: SandboxVerifyOptions,\n ): Promise<SandboxResult>;\n /** Co-install a set of packages and smoke-load a subset (or all).\n * `packages` are all co-installed; `opts.smokePackages` controls which are\n * smoke-loaded (defaults to `packages`). A successful co-install proves\n * the set coexists. */\n verifySet(\n packages: SandboxPackage[],\n opts?: SandboxVerifyOptions,\n ): Promise<SandboxSetResult>;\n /** Retrieve the node and npm versions running inside this sandbox. */\n getRuntimeInfo(): Promise<{ nodeVersion: string; npmVersion: string }>;\n}\n\nexport const DEFAULT_TARGET: SandboxTarget = {\n node: '20',\n moduleSystem: 'cjs',\n};\n","/**\n * Local child-process sandbox driver.\n *\n * Installs package(s) into a throwaway temp dir and smoke-loads them, reporting\n * whether they install and load. Fast and dependency-free (just npm + node).\n *\n * NOT an isolation boundary: loading a package executes its top-level code on\n * the host, so use this only for packages you already trust (operator/dev).\n * Verify UNTRUSTED packages with a VM driver. Install scripts stay OFF unless\n * `allowScripts` is set, since the whole point of the security tier is to not\n * execute untrusted install hooks.\n */\nimport { execFile } from 'node:child_process';\nimport { mkdtemp, rm, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { promisify } from 'node:util';\nimport {\n DEFAULT_TARGET,\n type ExecOptions,\n type ExecResult,\n type Sandbox,\n type SandboxPackage,\n type SandboxResult,\n type SandboxSetResult,\n type SandboxVerifyOptions,\n} from './types';\n\nconst execFileAsync = promisify(execFile);\nconst INSTALL_TIMEOUT_MS = 120_000;\nconst SMOKE_TIMEOUT_MS = 30_000;\nconst ERROR_MAX = 500;\nconst EXEC_MAX_BUFFER = 8 * 1024 * 1024;\n\n/** npm args for a throwaway install of one or more specs into the sandbox dir. */\nexport function npmInstallArgs(specs: string[], opts: { allowScripts: boolean }): string[] {\n // A spec beginning with `-` would be parsed as an npm flag (e.g.\n // `--registry=evil`), not a package. Legitimate names/specs never start with\n // one, so reject rather than smuggle it into the install command.\n const bad = specs.find((s) => s.startsWith('-'));\n if (bad) throw new Error(`Invalid package spec: ${bad}`);\n const args = ['install', ...specs, '--no-audit', '--no-fund', '--no-package-lock', '--no-save'];\n if (!opts.allowScripts) args.push('--ignore-scripts');\n return args;\n}\n\n/**\n * Load the package the way that works for both module systems.\n *\n * This used to branch on the target's `moduleSystem`, which nothing ever\n * derived from the package — DEFAULT_TARGET hardcodes 'cjs', so every smoke\n * load was a `require()`. An ESM-only package therefore came back\n * ERR_REQUIRE_ESM and was recorded as failing to load. Measured: nanoid@6.0.1,\n * a package that works perfectly, reported `installed: yes, loaded: no`.\n *\n * That verdict is not cosmetic — it feeds `verify` and the recommendation path,\n * so lurq was calling a large and growing share of the modern registry broken.\n * chalk, node-fetch, execa, got, ora and nanoid have all gone ESM-only.\n *\n * `import()` handles both: Node wraps a CJS module and hands back its exports\n * as `default`. So there is nothing to detect and no branch to get wrong, and\n * \"does `import` work\" is the right definition of loading in 2026 anyway.\n */\nexport function smokeScript(pkg: string): string[] {\n return ['--input-type=module', '-e', `await import(${JSON.stringify(pkg)})`];\n}\n\nfunction condense(s: string): string {\n return s.replace(/\\s+/g, ' ').trim().slice(0, ERROR_MAX);\n}\n\nfunction stderrOf(err: unknown): string {\n if (err && typeof err === 'object') {\n const e = err as { stderr?: unknown; message?: unknown };\n if (typeof e.stderr === 'string' && e.stderr.trim()) return e.stderr;\n if (typeof e.message === 'string') return e.message;\n }\n return String(err);\n}\n\nconst toSpec = (p: SandboxPackage): string => (p.version ? `${p.name}@${p.version}` : p.name);\n\nexport class LocalSandbox implements Sandbox {\n readonly name = 'local';\n\n async verify(\n pkg: string,\n version: string | null,\n opts: SandboxVerifyOptions = {},\n ): Promise<SandboxResult> {\n const set = await this.verifySet([{ name: pkg, version }], opts);\n return {\n driver: this.name,\n moduleSystem: set.moduleSystem,\n installed: set.installed,\n imported: set.loaded[0]?.loaded ?? null,\n ranScripts: opts.allowScripts ?? false,\n durationMs: set.durationMs,\n error: set.error,\n };\n }\n\n async verifySet(\n packages: SandboxPackage[],\n opts: SandboxVerifyOptions = {},\n ): Promise<SandboxSetResult> {\n const target = opts.target ?? DEFAULT_TARGET;\n const allowScripts = opts.allowScripts ?? false;\n const specs = packages.map(toSpec);\n const dir = await mkdtemp(join(tmpdir(), 'lurq-sandbox-'));\n const started = Date.now();\n const smokeTargets = opts.smokePackages ?? packages;\n const loaded = smokeTargets.map((p) => ({ name: p.name, loaded: null as boolean | null }));\n let installed = false;\n let error: string | null = null;\n\n try {\n await writeFile(\n join(dir, 'package.json'),\n JSON.stringify({ name: 'lurq-sandbox', version: '0.0.0', private: true }),\n );\n await execFileAsync('npm', npmInstallArgs(specs, { allowScripts }), {\n cwd: dir,\n timeout: opts.timeoutMs ?? INSTALL_TIMEOUT_MS,\n signal: opts.signal,\n });\n installed = true;\n\n for (let i = 0; i < smokeTargets.length; i++) {\n try {\n await execFileAsync('node', smokeScript(smokeTargets[i]!.name), {\n cwd: dir,\n timeout: SMOKE_TIMEOUT_MS,\n signal: opts.signal,\n });\n loaded[i]!.loaded = true;\n } catch (err) {\n loaded[i]!.loaded = false;\n if (!error) error = condense(stderrOf(err));\n }\n }\n } catch (err) {\n error = condense(stderrOf(err));\n } finally {\n await rm(dir, { recursive: true, force: true }).catch(() => {});\n }\n\n return {\n driver: this.name,\n moduleSystem: target.moduleSystem,\n installed,\n loaded,\n durationMs: Date.now() - started,\n error,\n };\n }\n\n async exec(command: string, opts: ExecOptions = {}): Promise<ExecResult> {\n const dir = await mkdtemp(join(tmpdir(), 'lurq-exec-'));\n try {\n await writeFile(\n join(dir, 'package.json'),\n JSON.stringify({ name: 'lurq-sandbox', version: '0.0.0', private: true }),\n );\n if (opts.install?.length) {\n // `timeoutMs` budgets the COMMAND, never the install that precedes it.\n // Applying it to both meant a caller asking for a 45s handshake also\n // cut its own install budget from 120s to 45s, so a server with a large\n // dependency tree timed out during `npm install` and was reported as a\n // server that would not start. The E2B driver always kept these\n // separate; this is the local driver catching up to it.\n await execFileAsync(\n 'npm',\n npmInstallArgs(opts.install.map(toSpec), { allowScripts: opts.allowScripts ?? false }),\n { cwd: dir, timeout: INSTALL_TIMEOUT_MS, signal: opts.signal },\n );\n }\n const { stdout, stderr } = await execFileAsync('sh', ['-c', command], {\n cwd: dir,\n timeout: opts.timeoutMs ?? SMOKE_TIMEOUT_MS,\n signal: opts.signal,\n maxBuffer: EXEC_MAX_BUFFER,\n });\n return { exitCode: 0, stdout, stderr };\n } catch (err) {\n // A non-zero exit is a result the oracle interprets, not a thrown error.\n const e = err as { code?: unknown; stdout?: unknown; stderr?: unknown };\n if (typeof e?.code === 'number') {\n return {\n exitCode: e.code,\n stdout: typeof e.stdout === 'string' ? e.stdout : '',\n stderr: typeof e.stderr === 'string' ? e.stderr : stderrOf(err),\n };\n }\n throw err; // timeout / spawn failure, infrastructure, not the subject\n } finally {\n await rm(dir, { recursive: true, force: true }).catch(() => {});\n }\n }\n\n async getRuntimeInfo(): Promise<{ nodeVersion: string; npmVersion: string }> {\n let nodeVersion = 'unknown';\n let npmVersion = 'unknown';\n try {\n const nodeOut = await execFileAsync('node', ['--version']);\n nodeVersion = nodeOut.stdout.trim() || 'unknown';\n const npmOut = await execFileAsync('npm', ['--version']);\n npmVersion = npmOut.stdout.trim() || 'unknown';\n } catch { /* ignore */ }\n return { nodeVersion, npmVersion };\n }\n}\n","/**\n * E2B cloud-sandbox driver.\n *\n * Installs package(s) and smoke-loads them inside an isolated E2B microVM, so\n * top-level package code (and, with allowScripts, install hooks) runs OFF the\n * host. This is the isolation boundary the local driver deliberately lacks —\n * use it to verify UNTRUSTED packages at scale.\n *\n * Requires E2B_API_KEY. The launched template must have node + npm on PATH\n * (see E2B_TEMPLATE). Like the local driver, target.node is recorded but not\n * provisioned — pin a Node-versioned template for reproducible majors.\n */\nimport { getConfig } from '../core/config';\nimport {\n DEFAULT_TARGET,\n type ExecOptions,\n type ExecResult,\n type Sandbox as SandboxDriver,\n type SandboxPackage,\n type SandboxResult,\n type SandboxSetResult,\n type SandboxVerifyOptions,\n} from './types';\n\nconst INSTALL_TIMEOUT_MS = 120_000;\nconst SMOKE_TIMEOUT_MS = 30_000;\nconst ERROR_MAX = 500;\nconst WORKDIR = '/home/user';\n\n/** POSIX single-quote: safe for any arg (specs may carry `^`, `>`, spaces). */\nexport function shQuote(s: string): string {\n return `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n\n/** Shell command that installs the specs into WORKDIR. */\nexport function installCommand(specs: string[], allowScripts: boolean): string {\n const bad = specs.find((s) => s.startsWith('-'));\n if (bad) throw new Error(`Invalid package spec: ${bad}`);\n const flags = ['--no-audit', '--no-fund', '--no-package-lock', '--no-save'];\n if (!allowScripts) flags.push('--ignore-scripts');\n return `npm install ${specs.map(shQuote).join(' ')} ${flags.join(' ')}`;\n}\n\n/** Shell command that loads a package and exits non-zero if it throws.\n * Always `import()` — it handles ESM and CJS alike; see smokeScript in\n * local.ts for why branching on a module system nobody derived was wrong. */\nexport function smokeCommand(pkg: string): string {\n return `node --input-type=module -e ${shQuote(`await import(${JSON.stringify(pkg)})`)}`;\n}\n\nfunction condense(s: string): string {\n return s.replace(/\\s+/g, ' ').trim().slice(0, ERROR_MAX);\n}\n\nfunction errText(err: unknown): string {\n if (err && typeof err === 'object') {\n const e = err as { stderr?: unknown; message?: unknown };\n if (typeof e.stderr === 'string' && e.stderr.trim()) return e.stderr;\n if (typeof e.message === 'string') return e.message;\n }\n return String(err);\n}\n\nconst toSpec = (p: SandboxPackage): string => (p.version ? `${p.name}@${p.version}` : p.name);\n\nexport class E2BSandbox implements SandboxDriver {\n readonly name = 'e2b';\n\n async verify(\n pkg: string,\n version: string | null,\n opts: SandboxVerifyOptions = {},\n ): Promise<SandboxResult> {\n const set = await this.verifySet([{ name: pkg, version }], opts);\n return {\n driver: this.name,\n moduleSystem: set.moduleSystem,\n installed: set.installed,\n imported: set.loaded[0]?.loaded ?? null,\n ranScripts: opts.allowScripts ?? false,\n durationMs: set.durationMs,\n error: set.error,\n };\n }\n\n async verifySet(\n packages: SandboxPackage[],\n opts: SandboxVerifyOptions = {},\n ): Promise<SandboxSetResult> {\n const config = getConfig();\n const target = opts.target ?? DEFAULT_TARGET;\n const allowScripts = opts.allowScripts ?? false;\n const specs = packages.map(toSpec);\n const installTimeout = opts.timeoutMs ?? INSTALL_TIMEOUT_MS;\n const started = Date.now();\n const smokeTargets = opts.smokePackages ?? packages;\n const loaded = smokeTargets.map((p) => ({ name: p.name, loaded: null as boolean | null }));\n let installed = false;\n let error: string | null = null;\n\n // Build install command up front so a bad spec fails before we spend a VM.\n const install = installCommand(specs, allowScripts);\n\n // Lazy-load e2b: its CJS build does require('chalk'), and chalk@5 is\n // ESM-only, which crashes require(esm) on some Node 22.x versions. Keeping\n // it off the import graph means the crash can only ever reach `verify`,\n // never `lurq` startup. (tsup would otherwise hoist a static top-level\n // `import` even though sandbox/index.ts loads this module dynamically.)\n const { default: Sandbox } = await import('e2b');\n\n // Sandbox lifetime must outlast install + every smoke run, plus buffer.\n const createOpts = {\n apiKey: config.E2B_API_KEY,\n timeoutMs: installTimeout + SMOKE_TIMEOUT_MS * packages.length + 30_000,\n };\n const sandbox = config.E2B_TEMPLATE\n ? await Sandbox.create(config.E2B_TEMPLATE, createOpts)\n : await Sandbox.create(createOpts);\n\n try {\n await sandbox.files.write(\n `${WORKDIR}/package.json`,\n JSON.stringify({ name: 'lurq-sandbox', version: '0.0.0', private: true }),\n );\n await sandbox.commands.run(install, { cwd: WORKDIR, timeoutMs: installTimeout });\n installed = true;\n\n for (let i = 0; i < smokeTargets.length; i++) {\n try {\n await sandbox.commands.run(smokeCommand(smokeTargets[i]!.name), {\n cwd: WORKDIR,\n timeoutMs: SMOKE_TIMEOUT_MS,\n });\n loaded[i]!.loaded = true;\n } catch (err) {\n loaded[i]!.loaded = false;\n if (!error) error = condense(errText(err));\n }\n }\n } catch (err) {\n error = condense(errText(err));\n } finally {\n await sandbox.kill().catch(() => {});\n }\n\n return {\n driver: this.name,\n moduleSystem: target.moduleSystem,\n installed,\n loaded,\n durationMs: Date.now() - started,\n error,\n };\n }\n\n async exec(command: string, opts: ExecOptions = {}): Promise<ExecResult> {\n const config = getConfig();\n const timeoutMs = opts.timeoutMs ?? SMOKE_TIMEOUT_MS;\n // Build the install command first so a bad spec fails before we spend a VM.\n const install = opts.install?.length\n ? installCommand(opts.install.map(toSpec), opts.allowScripts ?? false)\n : null;\n\n const { default: Sandbox } = await import('e2b');\n const createOpts = {\n apiKey: config.E2B_API_KEY,\n timeoutMs: (install ? INSTALL_TIMEOUT_MS : 0) + timeoutMs + 30_000,\n };\n const sandbox = config.E2B_TEMPLATE\n ? await Sandbox.create(config.E2B_TEMPLATE, createOpts)\n : await Sandbox.create(createOpts);\n\n try {\n await sandbox.files.write(\n `${WORKDIR}/package.json`,\n JSON.stringify({ name: 'lurq-sandbox', version: '0.0.0', private: true }),\n );\n if (install) {\n await sandbox.commands.run(install, { cwd: WORKDIR, timeoutMs: INSTALL_TIMEOUT_MS });\n }\n const out = await sandbox.commands.run(command, { cwd: WORKDIR, timeoutMs });\n return { exitCode: out.exitCode ?? 0, stdout: out.stdout ?? '', stderr: out.stderr ?? '' };\n } catch (err) {\n // A non-zero exit is a result the oracle interprets, not a thrown error.\n const e = err as { exitCode?: unknown; stdout?: unknown; stderr?: unknown };\n if (typeof e?.exitCode === 'number') {\n return {\n exitCode: e.exitCode,\n stdout: typeof e.stdout === 'string' ? e.stdout : '',\n stderr: typeof e.stderr === 'string' ? e.stderr : errText(err),\n };\n }\n throw err; // VM/timeout failure, infrastructure, not the subject\n } finally {\n await sandbox.kill().catch(() => {});\n }\n }\n\n async getRuntimeInfo(): Promise<{ nodeVersion: string; npmVersion: string }> {\n let nodeVersion = 'unknown';\n let npmVersion = 'unknown';\n const config = getConfig();\n try {\n const { default: Sandbox } = await import('e2b');\n const createOpts = { apiKey: config.E2B_API_KEY, timeoutMs: 30_000 };\n const sandbox = config.E2B_TEMPLATE\n ? await Sandbox.create(config.E2B_TEMPLATE, createOpts)\n : await Sandbox.create(createOpts);\n try {\n const nodeOut = await sandbox.commands.run('node --version');\n nodeVersion = (nodeOut.stdout ?? '').trim() || 'unknown';\n const npmOut = await sandbox.commands.run('npm --version');\n npmVersion = (npmOut.stdout ?? '').trim() || 'unknown';\n } finally {\n await sandbox.kill().catch(() => {});\n }\n } catch { /* ignore */ }\n return { nodeVersion, npmVersion };\n }\n}\n","/**\n * Sandbox driver selection. With E2B_API_KEY set, the VM-isolated E2B driver is\n * used (safe for untrusted packages); otherwise the local child-process driver\n * (trusted packages only). The E2B module is imported lazily so its heavy SDK\n * never loads on the CLI/install path when isolation isn't configured.\n */\nimport { getConfig } from '../core/config';\nimport { LocalSandbox } from './local';\nimport type { Sandbox } from './types';\n\nexport async function getSandbox(): Promise<Sandbox> {\n if (getConfig().E2B_API_KEY) {\n const { E2BSandbox } = await import('./e2b');\n return new E2BSandbox();\n }\n return new LocalSandbox();\n}\n\nexport * from './types';\nexport { LocalSandbox, npmInstallArgs, smokeScript } from './local';\n","/**\n * Run a package version through the sandbox and persist the result. Decoupled\n * from the query path: an operator/cron drives this in the background and the\n * stored verdict is read instantly at recommend/verify time.\n */\nimport type { Database } from '../db/client';\nimport { storeVerificationRun } from '../db/verification';\nimport { getSandbox } from '../sandbox';\nimport type { SandboxResult, SandboxVerifyOptions } from '../sandbox/types';\n\nexport async function verifyPackageInSandbox(\n db: Database,\n pkg: string,\n version: string | null,\n opts: SandboxVerifyOptions = {},\n): Promise<SandboxResult> {\n const result = await (await getSandbox()).verify(pkg, version, opts);\n // Persist for the query path. Non-fatal: never fail the run on a write error.\n await storeVerificationRun(db, {\n packageName: pkg,\n version: version ?? 'latest',\n driver: result.driver,\n moduleSystem: result.moduleSystem,\n installed: result.installed,\n imported: result.imported,\n ranScripts: result.ranScripts,\n durationMs: result.durationMs,\n error: result.error,\n ranAt: new Date(),\n }).catch(() => {});\n return result;\n}\n","/**\n * Compatibility verification: co-install a set of packages in the sandbox and\n * record pairwise edges. A successful co-install proves the set coexists (every\n * pair compatible); a 2-package failure proves that pair conflicts. A larger\n * failed set can't pin the culprit, so no edge is asserted (set-level report).\n */\nimport type { CompatStatus } from '../core/types';\nimport { logger } from '../core/logger';\nimport type { Database } from '../db/client';\nimport {\n bumpCompatVerifyAttempt,\n canonicalPair,\n deleteCompatVerify,\n getPendingCompatVerify,\n upsertCompatEdge,\n} from '../db/compat';\nimport { getStackResolution, recordStackResolution, stackKey } from '../db/stackResolutions';\nimport { getPackageByName, getTopPackageNames } from '../db/packages';\nimport { getSandbox } from '../sandbox';\nimport type { SandboxSetResult } from '../sandbox/types';\nimport { resolveSet } from './resolveCheck';\n\n// Re-exported: the pure pair helper lives in the light db layer (so the query\n// path can use it without pulling in the sandbox), but it was minted here.\nexport { pairKey } from '../db/compat';\n\nexport interface CompatEdge {\n a: string;\n aVersion: string;\n b: string;\n bVersion: string;\n status: CompatStatus;\n}\n\ninterface Resolved {\n name: string;\n version: string;\n}\n\n/**\n * Pairwise edges from a set-level outcome. Pure, shared by every tier (sandbox\n * co-install, resolve-only): a success proves the whole set coexists → every pair\n * compatible; a failed *pair* is precise → conflict; a larger failed set can't\n * attribute the culprit → no edge.\n */\nfunction pairwiseEdges(resolved: Resolved[], success: boolean): CompatEdge[] {\n const edges: CompatEdge[] = [];\n if (success) {\n for (let i = 0; i < resolved.length; i++) {\n for (let j = i + 1; j < resolved.length; j++) {\n edges.push({\n a: resolved[i]!.name,\n aVersion: resolved[i]!.version,\n b: resolved[j]!.name,\n bVersion: resolved[j]!.version,\n status: 'compatible',\n });\n }\n }\n } else if (resolved.length === 2) {\n edges.push({\n a: resolved[0]!.name,\n aVersion: resolved[0]!.version,\n b: resolved[1]!.name,\n bVersion: resolved[1]!.version,\n status: 'conflict',\n });\n }\n return edges;\n}\n\n/** Derive pairwise edges from a sandbox set co-install result. Pure. */\nexport function deriveCompatEdges(resolved: Resolved[], result: SandboxSetResult): CompatEdge[] {\n return pairwiseEdges(resolved, result.installed && result.loaded.every((l) => l.loaded === true));\n}\n\nexport interface CompatRunResult {\n result: SandboxSetResult;\n edges: CompatEdge[];\n /** A set-level conflict that couldn't be pinned to a specific pair. */\n unattributedConflict: boolean;\n}\n\nexport async function verifyCompatibility(\n db: Database,\n packages: string[],\n opts: { allowScripts?: boolean } = {},\n): Promise<CompatRunResult> {\n const resolved: Resolved[] = await Promise.all(\n packages.map(async (name) => ({\n name,\n version: (await getPackageByName(db, name))?.latestVersion ?? 'latest',\n })),\n );\n\n const result = await (await getSandbox()).verifySet(\n resolved.map((r) => ({ name: r.name, version: r.version === 'latest' ? null : r.version })),\n { allowScripts: opts.allowScripts },\n );\n\n const edges = deriveCompatEdges(resolved, result);\n await persistCompatEdges(db, edges, 'verified', result.driver);\n\n const failed = !result.installed || !result.loaded.every((l) => l.loaded === true);\n return { result, edges, unattributedConflict: failed && edges.length === 0 };\n}\n\n/** Upsert derived edges with a given evidence class. A compatible edge carries the\n * caller's provenance (`verified` for sandbox runtime proof, `observed` for a\n * resolve-only co-resolution witness); a conflict is always the proven-negative\n * `conflict`. Provenance precedence means a weaker tier never erases a stronger. */\nasync function persistCompatEdges(\n db: Database,\n edges: CompatEdge[],\n compatibleProvenance: 'verified' | 'observed',\n driver: string,\n): Promise<void> {\n const now = new Date();\n for (const e of edges) {\n const pair = canonicalPair(\n { name: e.a, version: e.aVersion },\n { name: e.b, version: e.bVersion },\n );\n await upsertCompatEdge(db, {\n ...pair,\n status: e.status,\n provenance: e.status === 'conflict' ? 'conflict' : compatibleProvenance,\n // Witness accrues for co-resolution evidence (`observed`); ignored otherwise.\n witnessCount: e.status === 'compatible' && compatibleProvenance === 'observed' ? 1 : 0,\n driver,\n ranAt: now,\n }).catch(() => {});\n }\n}\n\nexport interface ResolveCompatResult {\n edges: CompatEdge[];\n /** True if the set co-resolves; false only on a proven ERESOLVE conflict. */\n resolved: boolean;\n}\n\n/**\n * Tier-2 resolve-only verify: resolve a package set with npm (no install, no VM)\n * and record the verdict against the exact set.\n *\n * This used to fan the result out into pairwise `observed` edges. It no longer\n * does, and the reason is not just storage: a set resolving is a fact about the\n * *set*. Splitting it into C(n,2) pairs asserts something npm never said — that\n * each pair independently works — and loses the only thing that made the run\n * worth doing, which is that these packages resolve *together*.\n *\n * Inconclusive resolves (network, timeout) throw so the caller can retry rather\n * than record a false result. Nothing is cached on that path.\n */\nasync function resolveVerifyCompatibility(\n db: Database,\n packages: string[],\n): Promise<ResolveCompatResult> {\n const resolved: Resolved[] = await Promise.all(\n packages.map(async (name) => ({\n name,\n version: (await getPackageByName(db, name))?.latestVersion ?? 'latest',\n })),\n );\n const res = await resolveSet(\n resolved.map((r) => ({ name: r.name, version: r.version === 'latest' ? null : r.version })),\n );\n // A member we could not pin has no place in a version-keyed cache entry.\n const pinned = resolved.filter((r) => r.version !== 'latest');\n if (pinned.length === resolved.length && pinned.length >= 2) {\n await recordStackResolution(db, {\n members: pinned.map((r) => ({ name: r.name, version: r.version })),\n resolved: res.resolved,\n reason: res.reason,\n detail: res.detail ?? null,\n }).catch((err: unknown) => logger.warn(`compat: caching resolution failed: ${String(err)}`));\n }\n return { edges: pairwiseEdges(resolved, res.resolved), resolved: res.resolved };\n}\n\n// ── Targeted backfill (§4C) ───────────────────────────────────────────────────\n\n/**\n * Has this exact set already been resolved? The backfill skips it if so.\n *\n * Set-level, where the old check was pairwise. That is a real narrowing: a batch\n * whose pairs were each seen in some *other* combination used to count as\n * covered, which is precisely the inference npm's resolver does not support —\n * pairwise coverage never proved the batch resolves together. Now a batch is\n * skipped only when this batch, at these versions, actually resolved.\n */\nasync function alreadyResolved(db: Database, names: string[]): Promise<boolean> {\n const members: { name: string; version: string }[] = [];\n for (const name of [...new Set(names)]) {\n const version = (await getPackageByName(db, name))?.latestVersion;\n if (!version) return false; // cannot key on it, so treat as uncovered\n members.push({ name, version });\n }\n if (members.length < 2) return true;\n return (await getStackResolution(db, stackKey(members)).catch(() => null)) !== null;\n}\n\nexport interface BackfillResult {\n batches: number;\n verified: number;\n skipped: number;\n}\n\ntype BatchRunner = (db: Database, batch: string[]) => Promise<{ edges: CompatEdge[] }>;\n\n/**\n * Batch the top-N popular tracked packages and settle each batch with `runner`.\n * Batches already resolved at these versions are skipped — no wasted run. The\n * runner is the tier: sandbox (runtime proof, expensive) or resolve-only\n * (co-resolution, cheap).\n *\n * `batchSize` is worth raising well above its default before running this in\n * anger. npm's cost is dominated by fetching packuments rather than by how many\n * packages are in the set, so a batch of 20 measured ~31ms per covered pair\n * against ~450ms at a batch of 5.\n */\nasync function runBackfill(\n db: Database,\n opts: { topN?: number; batchSize?: number },\n runner: BatchRunner,\n label: string,\n): Promise<BackfillResult> {\n const topN = opts.topN ?? 50;\n const batchSize = Math.max(2, opts.batchSize ?? 5);\n const names = await getTopPackageNames(db, topN);\n\n let verified = 0;\n let batches = 0;\n let skipped = 0;\n for (let i = 0; i < names.length; i += batchSize) {\n const batch = names.slice(i, i + batchSize);\n if (batch.length < 2) continue;\n if (await alreadyResolved(db, batch)) {\n skipped++;\n continue;\n }\n logger.info(`${label}: ${batch.join(', ')}`);\n const { edges } = await runner(db, batch).catch((err) => {\n logger.warn(`${label} batch failed (${batch.join(', ')}): ${String(err)}`);\n return { edges: [] as CompatEdge[] };\n });\n verified += edges.length;\n batches++;\n }\n logger.info(`${label}: ${verified} edges across ${batches} runs, ${skipped} batches skipped`);\n return { batches, verified, skipped };\n}\n\n/** Sandbox backfill (Tier-3, runtime proof) — reserve E2B for where it buys most. */\nexport async function backfillVerify(\n db: Database,\n opts: { topN?: number; batchSize?: number } = {},\n): Promise<BackfillResult> {\n return runBackfill(db, opts, verifyCompatibility, 'backfill(sandbox)');\n}\n\n/** Resolve-only backfill (Tier-2, no VM) — cheap enough to pre-warm the whole\n * corpus before launch; escalate ambiguous pairs to `backfillVerify` later. */\nexport async function resolveBackfill(\n db: Database,\n opts: { topN?: number; batchSize?: number } = {},\n): Promise<BackfillResult> {\n return runBackfill(db, opts, resolveVerifyCompatibility, 'backfill(resolve)');\n}\n\n// ── Demand-driven self-heal drain (§4C) ───────────────────────────────────────\n\nconst MAX_COMPAT_VERIFY_ATTEMPTS = 3;\n\nexport interface DrainResult {\n processed: number;\n verified: number;\n dropped: number;\n}\n\n/**\n * Drain the compat-verify queue: pop the oldest pending sets (capped) and settle\n * each in the *sandbox* — a real co-install under VM isolation.\n *\n * The queue's job changed. It used to hold sets whose verdict was unknown, so a\n * cheap resolve could turn the next ask from `likely` into an answer. `compat`\n * now resolves inline, so by the time anything lands here the set has already\n * been proven to *install*. What is left unproven is whether it actually *runs*,\n * and that is exactly what the sandbox tier establishes — the one claim neither\n * a resolution nor a dependency graph can make.\n *\n * A set resolved since it was queued is dropped without work; a set that keeps\n * failing (network/timeout — never a proven conflict) is dropped after MAX\n * attempts so a bad request cannot wedge the queue.\n */\nexport async function drainCompatVerifyQueue(\n db: Database,\n opts: { limit?: number } = {},\n): Promise<DrainResult> {\n const limit = Math.max(1, opts.limit ?? 10);\n const pending = await getPendingCompatVerify(db, limit);\n let verified = 0;\n let dropped = 0;\n for (const req of pending) {\n const names = req.packages;\n if (await alreadyResolved(db, names)) {\n await deleteCompatVerify(db, req.id);\n continue;\n }\n try {\n const { edges } = await verifyCompatibility(db, names, {});\n verified += edges.length;\n await deleteCompatVerify(db, req.id);\n } catch (err) {\n logger.warn(`compat-verify drain failed for ${names.join(', ')}: ${String(err)}`);\n const attempts = await bumpCompatVerifyAttempt(db, req.id);\n if (attempts >= MAX_COMPAT_VERIFY_ATTEMPTS) {\n await deleteCompatVerify(db, req.id);\n dropped++;\n }\n }\n }\n logger.info(\n `compat-verify(sandbox): ${verified} edge(s) from ${pending.length} queued set(s), ${dropped} dropped`,\n );\n return { processed: pending.length, verified, dropped };\n}\n","/**\n * Normalized surface IR (v1 spec §6.3).\n *\n * Deliberately ecosystem-agnostic: this shape is what makes a second ecosystem\n * cheap instead of linear, so nothing npm-specific belongs here. Per-ecosystem\n * detail goes in a sidecar, never forced into the common shape.\n */\n\n/**\n * §6.2. Ordered by authority for RUNTIME-existence claims. Tier A is primary\n * (89.3% coverage in the study); C is type-level only and must never answer\n * \"does this symbol exist at runtime\" — a removed type breaks `tsc`, a removed\n * runtime symbol breaks `node`.\n */\nexport type ExtractionTier =\n | 'shipped_js_ast' // A, primary\n | 'runtime_import' // B, sandboxed require/import; the cost driver\n | 'bundled_dts' // C, secondary, signatures + deprecation only\n | 'types_package' // D, DefinitelyTyped; drifts from the real package\n | 'jsdoc_generated' // E, rarely reached\n /**\n * MCP `tools/list`. Not on the A–E authority ladder at all: those tiers rank\n * ways of reading ONE artifact (a package's shipped code), and this reads a\n * different artifact entirely. It is listed here so §6.4.3's cross-tier guard\n * refuses to diff a tool list against a package surface — the guard is the\n * reason this belongs in the shared enum rather than a parallel one.\n */\n | 'mcp_tools_list';\n\nexport type SymbolKind = 'function' | 'class' | 'object' | 'primitive' | 'type_only';\n\n/**\n * `origin` exists because of defect §6.4.1: `export { X } from \"@scope/other\"`\n * re-exports a symbol this package does not own. Counting those as local surface\n * made one package look like it deleted 168 exports when the true figure was 0.\n * Anything `external:*` is excluded from removal counts.\n */\nexport type SymbolOrigin = 'local' | `external:${string}`;\n\nexport interface SurfaceSymbol {\n /** 'default', 'foo', 'foo.bar' */\n path: string;\n kind: SymbolKind;\n /** `fn.length` equivalent; null when not statically determinable. */\n arity: number | null;\n origin: SymbolOrigin;\n deprecated: boolean;\n tier: ExtractionTier;\n /** Full declaration text. Tier C only — tier A cannot see types, and an\n * overload set collapses to one symbol whose signature lists each overload. */\n signature?: string;\n sourceRef?: { file: string; line: number };\n}\n\nexport interface ExtractedSurface {\n package: string;\n version: string | null;\n tier: ExtractionTier;\n entry: string | null;\n symbols: SurfaceSymbol[];\n /** Files walked through the package-internal module graph (§6.4.5). */\n filesWalked: number;\n /** Specifiers that resolved outside the package — their names are external. */\n externalReExports: string[];\n /** Set when nothing could be extracted; the caller records UNDECLARED, not absence. */\n undeclaredReason?: string;\n}\n\n/** Runtime-existence symbols only: `type_only` never counts (§6.4.4). */\nexport function runtimeSymbols(surface: ExtractedSurface): SurfaceSymbol[] {\n return surface.symbols.filter((s) => s.kind !== 'type_only' && s.origin === 'local');\n}\n","/**\n * Surface diff (§8.1 `diff_surface`, §3 `removed_at` / `arity_changed`).\n *\n * The highest-value output in the spec and the cheapest: \"when did this stop\n * working\" falls out of a static comparison of two extracted surfaces, with no\n * oracle executed across a version matrix.\n *\n * Three guards, each for a defect that silently corrupted the study (§6.4):\n * - cross-tier diffs are refused outright (§6.4.3)\n * - `type_only` never counts as runtime breakage (§6.4.4)\n * - `external:*` re-exports are never counted as this package's removals (§6.4.1)\n *\n * The fourth guard lives here too: a diff against an EMPTY surface is refused\n * (§6.4.2). An empty extraction is a measurement failure, and treating it as\n * \"everything was removed\" is exactly the bug that reported 100% precision on a\n * harness that had loaded nothing.\n */\nimport { runtimeSymbols, type ExtractedSurface, type SurfaceSymbol } from './types';\n\nexport interface ArityChange {\n path: string;\n from: number | null;\n to: number | null;\n}\n\nexport interface SignatureChange {\n path: string;\n from: string;\n to: string;\n}\n\nexport interface SurfaceDiff {\n package: string;\n fromVersion: string | null;\n toVersion: string | null;\n tier: ExtractedSurface['tier'];\n /** Runtime symbols present in `from` and absent from `to`. Breaks `node`. */\n removed: SurfaceSymbol[];\n added: SurfaceSymbol[];\n arityChanged: ArityChange[];\n /** Signature drift. Tier C only — tier A cannot see types at all, so an empty\n * list from a tier-A diff means \"not measurable\", not \"nothing changed\". */\n signatureChanged: SignatureChange[];\n /** Type-level removals — break `tsc`, NOT `node`. Reported separately (§8.1). */\n typeOnlyRemoved: SurfaceSymbol[];\n deprecated: SurfaceSymbol[];\n /** Set when no comparison could be made; callers must not read the arrays. */\n inconclusive?: string;\n}\n\nconst empty = (\n from: ExtractedSurface,\n to: ExtractedSurface,\n reason: string,\n): SurfaceDiff => ({\n package: from.package,\n fromVersion: from.version,\n toVersion: to.version,\n tier: from.tier,\n removed: [],\n added: [],\n arityChanged: [],\n signatureChanged: [],\n typeOnlyRemoved: [],\n deprecated: [],\n inconclusive: reason,\n});\n\nexport function diffSurfaces(from: ExtractedSurface, to: ExtractedSurface): SurfaceDiff {\n // §6.4.3 — a tier-A surface and a tier-C surface are not comparable.\n if (from.tier !== to.tier) {\n return empty(from, to, `cross-tier comparison refused: ${from.tier} vs ${to.tier}`);\n }\n // §6.4.2 — never issue a verdict from an empty surface. Mandatory guard.\n if (from.symbols.length === 0) {\n return empty(from, to, 'source surface is empty, extraction failed, not a removal');\n }\n if (to.symbols.length === 0) {\n return empty(from, to, 'target surface is empty, extraction failed, not a removal');\n }\n\n const fromRuntime = new Map(runtimeSymbols(from).map((s) => [s.path, s]));\n const toRuntime = new Map(runtimeSymbols(to).map((s) => [s.path, s]));\n\n const removed = [...fromRuntime.values()].filter((s) => !toRuntime.has(s.path));\n const added = [...toRuntime.values()].filter((s) => !fromRuntime.has(s.path));\n\n const arityChanged: ArityChange[] = [];\n for (const [path, a] of fromRuntime) {\n const b = toRuntime.get(path);\n if (!b) continue;\n if (a.arity !== null && b.arity !== null && a.arity !== b.arity) {\n arityChanged.push({ path, from: a.arity, to: b.arity });\n }\n }\n\n // §6.4.4 — reported, but as a separate class so a caller can tell a `tsc`\n // break from a `node` break.\n const typeOnlyFrom = from.symbols.filter((s) => s.kind === 'type_only');\n const toPaths = new Set(to.symbols.map((s) => s.path));\n const typeOnlyRemoved = typeOnlyFrom.filter((s) => !toPaths.has(s.path));\n\n // Signatures exist only at tier C. Comparing them on a tier-A diff would\n // report \"no changes\" for something never measured.\n const signatureChanged: SignatureChange[] = [];\n if (from.tier === 'bundled_dts') {\n const fromAll = new Map(from.symbols.map((s) => [s.path, s]));\n for (const b of to.symbols) {\n const a = fromAll.get(b.path);\n if (a?.signature && b.signature && a.signature !== b.signature) {\n signatureChanged.push({ path: b.path, from: a.signature, to: b.signature });\n }\n }\n }\n\n const deprecated = [...toRuntime.values()].filter(\n (s) => s.deprecated && !fromRuntime.get(s.path)?.deprecated,\n );\n\n return {\n package: from.package,\n fromVersion: from.version,\n toVersion: to.version,\n tier: from.tier,\n removed,\n added,\n arityChanged,\n signatureChanged,\n typeOnlyRemoved,\n deprecated,\n };\n}\n","/**\n * MCP tool-surface normalization and drift (tier `mcp_tools_list`).\n *\n * An MCP server's `tools/list` response IS its contract: the agent validates and\n * constructs every call against the schema it was handed at registration, and\n * the server enforces its own copy when the call lands. When the two diverge the\n * agent gets no error it can reason about — it gets a malformed request that\n * reads as a model failure. That is the same class of defect `diff_surface`\n * exists for on npm, on a surface that ships no tarball.\n *\n * Everything here normalizes into the shared IR in `./types` so `diffSurfaces`\n * does the removed/added work with its four guards intact, and the MCP-only\n * dimensions layer on top. Per §6.3 the ecosystem-specific detail rides in a\n * sidecar — here, the `ToolContract` serialized into `SurfaceSymbol.signature`\n * — rather than being forced into the common shape.\n *\n * Three things make this tier different from npm, and each one is a field below:\n *\n * 1. `tools/list` is PAGINATED. A partial drain is a measurement failure that\n * looks exactly like mass tool removal (§6.4.2's guard, new failure mode).\n * 2. Prose and contract change independently. A server can rewrite a\n * description without touching a schema (cosmetic), or — the documented\n * 2026 failure — change a parameter fingerprint while the description stays\n * byte-identical. The second is invisible to any human reading a changelog.\n * 3. Annotations carry PRIVILEGE. `readOnlyHint: true → false` is not a\n * breaking change; it is a tool the agent was approved to call freely\n * quietly becoming one that writes. npm has no analogue.\n */\nimport { createHash } from 'node:crypto';\nimport { diffSurfaces } from './diff';\nimport type { ExtractedSurface, SurfaceSymbol } from './types';\n\n/** The tier tag. Distinct so §6.4.3's cross-tier guard refuses to diff an MCP\n * surface against a package's shipped-JS surface — they are not comparable. */\nexport const MCP_TIER = 'mcp_tools_list' as const;\n\n/** A tool exactly as `tools/list` returns it (spec rev 2025-11-25 / 2026-07-28). */\nexport interface McpTool {\n name: string;\n title?: string;\n description?: string;\n inputSchema?: unknown;\n outputSchema?: unknown;\n annotations?: Record<string, unknown>;\n}\n\n/**\n * Keys carrying prose or metadata rather than contract.\n *\n * Stripped before hashing so a docs edit does not read as a schema change — and,\n * more importantly, so a schema change with an UNCHANGED description still\n * does. `$schema` is here because servers add and drop the dialect declaration\n * without changing what they accept.\n */\nconst PROSE_KEYS = new Set(['description', 'title', '$comment', 'examples', '$schema']);\n\n/**\n * Canonical form of a JSON Schema subtree: prose removed, keys sorted, and the\n * spellings JSON Schema treats as equivalent collapsed to one.\n *\n * Without the collapse, `type: \"string\"` and `type: [\"string\"]` — the same\n * schema, and a spelling servers flip between when they change SDK version —\n * would diff as a type change on every tool at once.\n */\nexport function canonicalize(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(canonicalize);\n if (value === null || typeof value !== 'object') return value;\n\n const src = value as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n for (const k of Object.keys(src).sort()) {\n if (PROSE_KEYS.has(k)) continue;\n const v = canonicalize(src[k]);\n if (v === undefined) continue;\n out[k] = v;\n }\n\n // `type: [\"string\"]` ≡ `type: \"string\"`. Guarded on Array so a user-defined\n // property literally named `type` (legal inside `properties`) is untouched.\n if (Array.isArray(out.type) && out.type.every((t) => typeof t === 'string')) {\n const t = [...new Set(out.type as string[])].sort();\n out.type = t.length === 1 ? t[0] : t;\n }\n // `required: []` ≡ no `required`.\n if (Array.isArray(out.required) && out.required.every((r) => typeof r === 'string')) {\n const r = [...new Set(out.required as string[])].sort();\n if (r.length === 0) delete out.required;\n else out.required = r;\n }\n return out;\n}\n\n/** Canonical JSON string for a schema subtree. Stable across key order. */\nexport function stable(value: unknown): string {\n return JSON.stringify(canonicalize(value) ?? null);\n}\n\n/**\n * Annotation defaults, from the spec. These are not all `false`, which is the\n * whole reason this function exists: comparing raw `annotations` objects would\n * report a flip every time a server started stating a hint explicitly that it\n * had been inheriting. `destructiveHint` and `openWorldHint` default TRUE.\n */\nexport const ANNOTATION_DEFAULTS = {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: true,\n} as const;\n\nexport type AnnotationHint = keyof typeof ANNOTATION_DEFAULTS;\n\nexport type ResolvedAnnotations = Record<AnnotationHint, boolean>;\n\nexport function resolveAnnotations(a?: Record<string, unknown> | null): ResolvedAnnotations {\n const out = {} as ResolvedAnnotations;\n for (const k of Object.keys(ANNOTATION_DEFAULTS) as AnnotationHint[]) {\n const v = a?.[k];\n out[k] = typeof v === 'boolean' ? v : ANNOTATION_DEFAULTS[k];\n }\n return out;\n}\n\n/**\n * Which direction of each hint hands the agent MORE power than it was approved\n * for. A flip this way is a security event even though nothing \"broke\".\n */\nconst WIDENS_WHEN_FALSE: Record<AnnotationHint, boolean> = {\n readOnlyHint: true, // true → false: the tool started writing\n destructiveHint: false, // false → true: the tool started destroying\n idempotentHint: true, // true → false: retries are no longer safe\n openWorldHint: false, // false → true: the tool started reaching outside\n};\n\n/**\n * The stored contract for one tool — what goes into `SurfaceSymbol.signature`.\n *\n * `prose` is a digest rather than the text: the diff only ever asks \"did the\n * human-readable part change\", and storing full descriptions for every tool of\n * every version would bloat the symbol table for a question that is one bit.\n */\nexport interface ToolContract {\n input: unknown;\n output: unknown;\n annotations: ResolvedAnnotations;\n prose: string;\n}\n\nconst sha = (s: string): string => createHash('sha256').update(s).digest('hex');\n\nexport function toolContract(t: McpTool): ToolContract {\n return {\n input: canonicalize(t.inputSchema ?? null),\n output: canonicalize(t.outputSchema ?? null),\n annotations: resolveAnnotations(t.annotations),\n prose: sha(`${t.title ?? ''}\u0000${t.description ?? ''}`).slice(0, 16),\n };\n}\n\n/** Object of `{ paramName: canonicalSchema }` for a contract's input. */\nfunction properties(c: ToolContract | null): Record<string, unknown> {\n const input = c?.input;\n if (!input || typeof input !== 'object') return {};\n const props = (input as Record<string, unknown>).properties;\n return props && typeof props === 'object' ? (props as Record<string, unknown>) : {};\n}\n\nfunction requiredSet(c: ToolContract | null): Set<string> {\n const input = c?.input;\n if (!input || typeof input !== 'object') return new Set();\n const req = (input as Record<string, unknown>).required;\n return new Set(Array.isArray(req) ? req.filter((r): r is string => typeof r === 'string') : []);\n}\n\n/** Top-level parameter names a caller may pass. */\nexport function paramNames(t: McpTool): string[] {\n return Object.keys(properties(toolContract(t)));\n}\n\n/** Parameters a caller MUST pass — the arity analogue for a tool. */\nexport function requiredParams(t: McpTool): string[] {\n return [...requiredSet(toolContract(t))].sort();\n}\n\n/**\n * Deprecation is prose-sniffed, and deliberately anchored.\n *\n * MCP has no deprecation field, so the only available evidence is the server\n * saying so in the description. Anchoring at the start is what keeps \"replaces\n * the deprecated foo API\" from marking a healthy tool as dying — an unanchored\n * substring match gets that wrong, and a false deprecation is the kind of wrong\n * answer that costs more trust than staying silent.\n *\n * ponytail: heuristic on declared prose, not evidence. Drop it if servers ever\n * get a real deprecation field.\n */\nconst DEPRECATED_RE = /^\\s*[[(]?\\s*(?:@)?deprecated\\b/i;\n\nexport function looksDeprecated(t: McpTool): boolean {\n return DEPRECATED_RE.test(t.description ?? '') || DEPRECATED_RE.test(t.title ?? '');\n}\n\n/** One tool → one symbol in the shared IR. */\nexport function toolToSymbol(t: McpTool): SurfaceSymbol {\n return {\n path: t.name,\n kind: 'function',\n arity: requiredParams(t).length,\n // MCP has no re-export mechanism: every tool a server lists is its own.\n origin: 'local',\n deprecated: looksDeprecated(t),\n tier: MCP_TIER,\n signature: JSON.stringify(toolContract(t)),\n };\n}\n\n/**\n * A server's full tool list → the shared surface IR.\n *\n * An empty list is recorded with `undeclaredReason`, never as a surface, so\n * `storeSurface` files it as UNDECLARED and `diffSurfaces` refuses to read\n * \"removed everything\" out of it.\n */\nexport function mcpSurface(\n server: string,\n version: string | null,\n tools: McpTool[],\n): ExtractedSurface {\n return {\n package: server,\n version,\n tier: MCP_TIER,\n entry: null,\n symbols: tools.map(toolToSymbol),\n filesWalked: 0,\n externalReExports: [],\n ...(tools.length === 0 ? { undeclaredReason: 'server listed no tools' } : {}),\n };\n}\n\n/**\n * Content address for a tool list — the extraction-cache key, standing in for\n * the tarball digest npm surfaces use. Unchanged list, no re-probe; and because\n * a probe costs a sandbox spawn rather than a download, this cache saves\n * meaningfully more here than it does on npm.\n */\nexport function surfaceHash(tools: McpTool[]): string {\n const canon = [...tools]\n .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))\n .map((t) => [t.name, toolContract(t)]);\n return sha(JSON.stringify(canon));\n}\n\n/** Parse the contract back out of a stored symbol. Null when unreadable. */\nexport function contractOf(s: SurfaceSymbol): ToolContract | null {\n if (!s.signature) return null;\n try {\n return JSON.parse(s.signature) as ToolContract;\n } catch {\n return null;\n }\n}\n\nexport interface ParamChange {\n tool: string;\n params: string[];\n}\n\nexport interface TypeChange {\n tool: string;\n param: string;\n from: string;\n to: string;\n /** The new schema accepts everything the old one did. Not breaking. */\n widened: boolean;\n}\n\nexport interface AnnotationFlip {\n tool: string;\n hint: AnnotationHint;\n from: boolean;\n to: boolean;\n /** The flip grants the agent more power than it was approved for. */\n widensPrivilege: boolean;\n}\n\nexport interface McpDrift {\n server: string;\n fromVersion: string | null;\n toVersion: string | null;\n tier: typeof MCP_TIER;\n /** Tools the agent can no longer call at all. */\n removedTools: string[];\n addedTools: string[];\n /** Now-mandatory parameters. Every existing call site omitting one fails. */\n requiredAdded: ParamChange[];\n requiredRelaxed: ParamChange[];\n /** Accepted before, rejected (or silently dropped) now. */\n paramsRemoved: ParamChange[];\n paramsAdded: ParamChange[];\n typeChanged: TypeChange[];\n /** Tools whose `outputSchema` moved — breaks callers parsing structured results. */\n outputChanged: string[];\n annotationFlips: AnnotationFlip[];\n /**\n * The silent case: contract moved, description byte-identical. Invisible to\n * anyone reading a changelog, and the reason this tier exists.\n */\n silentDrift: string[];\n /** Description moved, contract identical. Cosmetic — never breaking. */\n prosePolished: string[];\n deprecated: string[];\n breaking: boolean;\n /** Set when no comparison could be made; callers must not read the arrays. */\n inconclusive?: string;\n}\n\nconst emptyDrift = (from: ExtractedSurface, to: ExtractedSurface, reason: string): McpDrift => ({\n server: from.package,\n fromVersion: from.version,\n toVersion: to.version,\n tier: MCP_TIER,\n removedTools: [],\n addedTools: [],\n requiredAdded: [],\n requiredRelaxed: [],\n paramsRemoved: [],\n paramsAdded: [],\n typeChanged: [],\n outputChanged: [],\n annotationFlips: [],\n silentDrift: [],\n prosePolished: [],\n deprecated: [],\n breaking: false,\n inconclusive: reason,\n});\n\n/** Type names a schema accepts; null means unconstrained (accepts anything). */\nfunction typeSet(p: Record<string, unknown>): Set<string> | null {\n const t = p.type;\n if (typeof t === 'string') return new Set([t]);\n if (Array.isArray(t)) return new Set(t.filter((x): x is string => typeof x === 'string'));\n return null;\n}\n\nfunction enumSet(p: Record<string, unknown>): Set<string> | null {\n return Array.isArray(p.enum) ? new Set(p.enum.map((v) => JSON.stringify(v))) : null;\n}\n\n/** `b` accepts everything `a` did. null (unconstrained) is the widest value. */\nfunction accepts(a: Set<string> | null, b: Set<string> | null): boolean {\n if (b === null) return true;\n if (a === null) return false;\n return [...a].every((v) => b.has(v));\n}\n\n/** Keywords whose change can still be permissive. Everything else must match. */\nconst RELAXABLE = new Set([\n 'type',\n 'enum',\n 'additionalProperties',\n 'required',\n 'properties',\n 'items',\n]);\n\n/**\n * Is this change purely permissive — does `b` accept every value `a` did?\n *\n * Recursive, and deliberately narrow. It can prove widening for exactly five\n * moves, each one seen in a real server:\n *\n * - a type or enum gaining members, or losing its constraint entirely\n * - `additionalProperties: false` being dropped or opened\n * - a nested `required` entry becoming optional\n * - a new OPTIONAL property appearing\n * - any of the above inside `items` or `properties`\n *\n * Anything it does not understand — a changed `pattern`, `minimum`, `format`,\n * `oneOf` — returns false, which reports the change as breaking. That asymmetry\n * is chosen: calling a real break \"widened\" hides it, while calling a\n * relaxation \"breaking\" costs the reader one look at the before/after JSON that\n * every `TypeChange` already carries.\n *\n * ponytail: not a JSON Schema subsumption checker. If servers start relaxing\n * numeric bounds or composition keywords often enough to matter, replace this\n * with a real one rather than growing the special cases.\n */\nexport function isWidening(a: unknown, b: unknown): boolean {\n if (JSON.stringify(a) === JSON.stringify(b)) return true;\n if (!a || typeof a !== 'object' || !b || typeof b !== 'object') return false;\n if (Array.isArray(a) || Array.isArray(b)) return false;\n const pa = a as Record<string, unknown>;\n const pb = b as Record<string, unknown>;\n\n // Every keyword outside the relaxable set has to be identical.\n for (const k of new Set([...Object.keys(pa), ...Object.keys(pb)])) {\n if (RELAXABLE.has(k)) continue;\n if (JSON.stringify(pa[k]) !== JSON.stringify(pb[k])) return false;\n }\n\n if (!accepts(typeSet(pa), typeSet(pb))) return false;\n if (!accepts(enumSet(pa), enumSet(pb))) return false;\n\n // Closing an open object rejects payloads that used to pass; opening a closed\n // one cannot. Any other change to the keyword is a shape we do not model.\n if (JSON.stringify(pa.additionalProperties) !== JSON.stringify(pb.additionalProperties)) {\n if (pa.additionalProperties !== false) return false;\n }\n\n // `b` may require less than `a`, never more.\n const ra = new Set(Array.isArray(pa.required) ? (pa.required as string[]) : []);\n const rb = new Set(Array.isArray(pb.required) ? (pb.required as string[]) : []);\n for (const k of rb) if (!ra.has(k)) return false;\n\n const propsA = (pa.properties ?? {}) as Record<string, unknown>;\n const propsB = (pb.properties ?? {}) as Record<string, unknown>;\n for (const k of Object.keys(propsA)) {\n // A property `b` stopped declaring is only permissive if `b` accepts\n // undeclared keys — otherwise the value that used to validate now cannot.\n if (!(k in propsB)) {\n if (pb.additionalProperties === false) return false;\n continue;\n }\n if (!isWidening(propsA[k], propsB[k])) return false;\n }\n // New properties are fine: the required check above already caught the case\n // where one of them is mandatory.\n\n if ('items' in pa || 'items' in pb) {\n if (!isWidening(pa.items ?? {}, pb.items ?? {})) return false;\n }\n return true;\n}\n\n/**\n * Classify what moved between two MCP tool surfaces.\n *\n * Delegates removed/added to `diffSurfaces` so the four guards (cross-tier,\n * empty-source, empty-target, type-only) hold here exactly as they do for npm,\n * then adds the parameter, output, annotation and prose dimensions the shared\n * IR has no place for.\n */\nexport function diffMcpSurfaces(from: ExtractedSurface, to: ExtractedSurface): McpDrift {\n const base = diffSurfaces(from, to);\n if (base.inconclusive) return emptyDrift(from, to, base.inconclusive);\n\n const drift = emptyDrift(from, to, '');\n delete drift.inconclusive;\n drift.removedTools = base.removed.map((s) => s.path).sort();\n drift.addedTools = base.added.map((s) => s.path).sort();\n drift.deprecated = base.deprecated.map((s) => s.path).sort();\n\n const fromByName = new Map(from.symbols.map((s) => [s.path, s]));\n\n for (const toSym of to.symbols) {\n const fromSym = fromByName.get(toSym.path);\n if (!fromSym) continue; // an added tool has nothing to drift from\n\n const a = contractOf(fromSym);\n const b = contractOf(toSym);\n // No stored contract on one side means this pair was written by an older\n // extractor. Report nothing rather than guessing — the tool-level\n // added/removed answer above is still sound.\n if (!a || !b) continue;\n\n const tool = toSym.path;\n const pa = properties(a);\n const pb = properties(b);\n const ra = requiredSet(a);\n const rb = requiredSet(b);\n\n const gone = Object.keys(pa)\n .filter((k) => !(k in pb))\n .sort();\n const fresh = Object.keys(pb)\n .filter((k) => !(k in pa))\n .sort();\n if (gone.length) drift.paramsRemoved.push({ tool, params: gone });\n if (fresh.length) drift.paramsAdded.push({ tool, params: fresh });\n\n // Newly-required counts only for parameters that already existed: a brand\n // new required parameter is reported once, as requiredAdded, not twice.\n const nowRequired = [...rb].filter((k) => !ra.has(k)).sort();\n const nowOptional = [...ra].filter((k) => !rb.has(k) && k in pb).sort();\n if (nowRequired.length) drift.requiredAdded.push({ tool, params: nowRequired });\n if (nowOptional.length) drift.requiredRelaxed.push({ tool, params: nowOptional });\n\n for (const param of Object.keys(pb)) {\n if (!(param in pa)) continue;\n const before = JSON.stringify(pa[param]);\n const after = JSON.stringify(pb[param]);\n if (before === after) continue;\n drift.typeChanged.push({\n tool,\n param,\n from: before,\n to: after,\n widened: isWidening(pa[param], pb[param]),\n });\n }\n\n if (JSON.stringify(a.output) !== JSON.stringify(b.output)) drift.outputChanged.push(tool);\n\n for (const hint of Object.keys(ANNOTATION_DEFAULTS) as AnnotationHint[]) {\n if (a.annotations[hint] === b.annotations[hint]) continue;\n drift.annotationFlips.push({\n tool,\n hint,\n from: a.annotations[hint],\n to: b.annotations[hint],\n widensPrivilege: b.annotations[hint] === !WIDENS_WHEN_FALSE[hint],\n });\n }\n\n // Prose and contract move independently, and which one moved is the whole\n // question: identical prose over a changed contract is the failure no\n // changelog reader can catch.\n const contractMoved =\n JSON.stringify(a.input) !== JSON.stringify(b.input) ||\n JSON.stringify(a.output) !== JSON.stringify(b.output) ||\n JSON.stringify(a.annotations) !== JSON.stringify(b.annotations);\n const proseMoved = a.prose !== b.prose;\n if (contractMoved && !proseMoved) drift.silentDrift.push(tool);\n if (proseMoved && !contractMoved) drift.prosePolished.push(tool);\n }\n\n drift.breaking =\n drift.removedTools.length > 0 ||\n drift.requiredAdded.length > 0 ||\n drift.paramsRemoved.length > 0 ||\n drift.typeChanged.some((c) => !c.widened);\n\n return drift;\n}\n","/**\n * The official MCP registry, read for what a server DECLARES about itself.\n *\n * A probe can only observe a server it can start, and a large share of useful\n * servers refuse to start without credentials. Treating that as a failed\n * handshake is the §4.1 mistake in its purest form: \"we could not check\" is not\n * \"we checked and it does not work\", and a server that wants a `GITHUB_TOKEN`\n * is not broken.\n *\n * `server.json` carries the answer as data. Every published server declares its\n * `environmentVariables` — name, description, required, secret — plus its\n * transport and any launch arguments. So lurq can tell an agent exactly what\n * the server needs BEFORE spending a sandbox on a probe that was always going\n * to fail, and the agent can turn that into a specific request to its user\n * rather than a shrug.\n *\n * Best-effort by design. The registry is a third party on the network, and its\n * being down must never turn into a verdict about a server: every failure here\n * returns null and the caller proceeds exactly as it did before this file\n * existed.\n */\nimport { logger } from '../core/logger';\n\nconst REGISTRY = 'https://registry.modelcontextprotocol.io/v0.1';\nconst TIMEOUT_MS = 8_000;\n\n/** One environment variable a server declares, straight from `server.json`. */\nexport interface RequiredConfig {\n name: string;\n description: string | null;\n /** The server will not start without it. */\n required: boolean;\n /** A credential. Never log it, never put it in evidence, never cache a value. */\n secret: boolean;\n format: string | null;\n}\n\nexport interface McpServerManifest {\n /** Reverse-DNS registry name, e.g. `io.github.acme/weather`. */\n registryName: string;\n npmPackage: string;\n version: string | null;\n /** `stdio`, `streamable-http`, … Null when the package declares none. */\n transport: string | null;\n env: RequiredConfig[];\n /** Positional/flag arguments the server needs at launch. */\n args: string[];\n /** The server is published ONLY as a remote endpoint — nothing to install. */\n remoteOnly: boolean;\n}\n\nexport interface RegistryPackage {\n registryType?: string;\n identifier?: string;\n version?: string;\n transport?: { type?: string };\n environmentVariables?: {\n name?: string;\n description?: string;\n isRequired?: boolean;\n isSecret?: boolean;\n format?: string;\n }[];\n runtimeArguments?: { value?: string; name?: string }[];\n packageArguments?: { value?: string; name?: string }[];\n}\n\nexport interface RegistryServer {\n name?: string;\n version?: string;\n packages?: RegistryPackage[];\n remotes?: { type?: string; url?: string }[];\n}\n\n/**\n * In-process memo, including negative results.\n *\n * Most servers are not in the registry, and re-asking on every probe would add\n * a network round-trip to the miss path — the common path. A null is as worth\n * remembering as a hit.\n */\nconst memo = new Map<string, McpServerManifest | null>();\n\nasync function getJson(url: string): Promise<unknown | null> {\n const ctl = new AbortController();\n const timer = setTimeout(() => ctl.abort(), TIMEOUT_MS);\n try {\n const res = await fetch(url, { signal: ctl.signal, headers: { accept: 'application/json' } });\n if (!res.ok) return null;\n return await res.json();\n } catch (err) {\n // Network trouble is ours, not the server's. Never escalate it to a verdict.\n logger.debug?.({ url, err: String(err) }, 'mcp registry unreachable');\n return null;\n } finally {\n clearTimeout(timer);\n }\n}\n\nexport function toManifest(server: RegistryServer, npmPackage: string): McpServerManifest | null {\n const pkg = (server.packages ?? []).find(\n (p) => p.registryType === 'npm' && p.identifier === npmPackage,\n );\n const remoteOnly = !pkg && (server.remotes ?? []).length > 0;\n if (!pkg && !remoteOnly) return null;\n\n const args = [...(pkg?.runtimeArguments ?? []), ...(pkg?.packageArguments ?? [])]\n .map((a) => a.value ?? a.name)\n .filter((a): a is string => typeof a === 'string' && a.length > 0);\n\n return {\n registryName: server.name ?? npmPackage,\n npmPackage,\n version: pkg?.version ?? server.version ?? null,\n transport: pkg?.transport?.type ?? (remoteOnly ? (server.remotes?.[0]?.type ?? null) : null),\n env: (pkg?.environmentVariables ?? [])\n .map((e) => ({\n name: e.name ?? '',\n description: e.description ?? null,\n required: e.isRequired === true,\n secret: e.isSecret === true,\n format: e.format ?? null,\n }))\n .filter((e) => e.name.length > 0),\n args,\n remoteOnly,\n };\n}\n\n/**\n * What does this npm-published MCP server declare it needs?\n *\n * Looked up by npm package name rather than registry name, because that is the\n * identifier every caller already has — an entry in someone's MCP config names\n * the package, not the reverse-DNS registry id.\n *\n * Null means \"the registry has nothing for this\", which is the common case and\n * carries no implication about the server.\n */\nexport async function fetchServerManifest(npmPackage: string): Promise<McpServerManifest | null> {\n const hit = memo.get(npmPackage);\n if (hit !== undefined) return hit;\n\n const body = (await getJson(\n `${REGISTRY}/servers?search=${encodeURIComponent(npmPackage)}&limit=20`,\n )) as { servers?: { server?: RegistryServer }[] } | null;\n\n let found: McpServerManifest | null = null;\n for (const row of body?.servers ?? []) {\n // Search is fuzzy, so the identifier has to be matched exactly — otherwise\n // `server-memory` picks up whatever else mentions memory and lurq starts\n // reporting another project's credential requirements as this one's.\n const m = row.server ? toManifest(row.server, npmPackage) : null;\n if (m) {\n found = m;\n break;\n }\n }\n memo.set(npmPackage, found);\n return found;\n}\n\n/** Required, unsatisfied config for this server — what an agent must ask for. */\nexport function missingConfig(\n manifest: McpServerManifest | null,\n env: NodeJS.ProcessEnv = process.env,\n): RequiredConfig[] {\n return (manifest?.env ?? []).filter((e) => e.required && !env[e.name]);\n}\n\n/** One line an agent can put in front of a user, naming what it needs and why. */\nexport function configRequestLine(server: string, missing: RequiredConfig[]): string {\n if (missing.length === 0) return '';\n const items = missing\n .map((m) => `${m.name}${m.description ? ` (${m.description})` : ''}`)\n .join('; ');\n return (\n `${server} declares ${missing.length} required setting(s) before it will start: ${items}. ` +\n `Ask the user to supply ${missing.some((m) => m.secret) ? 'these values (at least one is a credential — take it from the user, never from a log or a guess)' : 'these values'}, ` +\n `then re-run the probe with them set.`\n );\n}\n\n/** Test seam: drop memoized lookups. */\nexport function clearManifestCache(): void {\n memo.clear();\n}\n","/**\n * Compact error formatting for logs. Drizzle stuffs full SQL + every bind param\n * into `err.message`, which can be megabytes for a fat batch insert — and the\n * real Postgres reason lives on `err.cause`, which bare `err.message` drops.\n */\n\nconst DEFAULT_MAX = 300;\n\nfunction truncate(text: string, max: number): string {\n if (text.length <= max) return text;\n return `${text.slice(0, max)}…`;\n}\n\nfunction causeText(cause: unknown): string | null {\n if (cause == null) return null;\n if (cause instanceof Error) {\n const code =\n 'code' in cause && (typeof cause.code === 'string' || typeof cause.code === 'number')\n ? String(cause.code)\n : null;\n const msg = truncate(cause.message, DEFAULT_MAX);\n return code ? `${code}: ${msg}` : msg;\n }\n if (typeof cause === 'object' && cause !== null && 'message' in cause) {\n const msg = truncate(String((cause as { message: unknown }).message), DEFAULT_MAX);\n const code =\n 'code' in cause ? String((cause as { code: unknown }).code) : null;\n return code ? `${code}: ${msg}` : msg;\n }\n return truncate(String(cause), DEFAULT_MAX);\n}\n\n/** Truncated message + optional Postgres/Drizzle cause for safe logging. */\nexport function formatError(err: unknown, max = DEFAULT_MAX): string {\n const message =\n err instanceof Error ? truncate(err.message, max) : truncate(String(err), max);\n const cause = err instanceof Error ? causeText(err.cause) : null;\n return cause ? `${message} (cause: ${cause})` : message;\n}\n","/**\n * Entry-point and specifier resolution for tier-A extraction (§6.2).\n *\n * Two jobs, both boring and both load-bearing:\n * 1. Find the file `require('pkg')` actually loads: exports map → main → index.js\n * 2. Decide whether a specifier stays inside the package (recurse into it) or\n * leaves it (record as external, per defect §6.4.1)\n */\nimport { existsSync, readFileSync, statSync } from 'node:fs';\nimport { dirname, join, resolve as resolvePath, sep } from 'node:path';\n\nconst EXTENSIONS = ['.js', '.cjs', '.mjs', '.json'];\n\nexport interface PackageManifest {\n name?: string;\n version?: string;\n main?: string;\n module?: string;\n types?: string;\n typings?: string;\n exports?: unknown;\n peerDependencies?: Record<string, string>;\n}\n\nexport function readManifest(pkgDir: string): PackageManifest | null {\n const p = join(pkgDir, 'package.json');\n if (!existsSync(p)) return null;\n try {\n return JSON.parse(readFileSync(p, 'utf8')) as PackageManifest;\n } catch {\n return null;\n }\n}\n\n\n/** The conditions tier A will read an entry from, best first. */\nconst CONDITIONS = ['require', 'node', 'default', 'import', 'module'] as const;\n\n/** A subpath map keys entries by path (`\".\"`, `\"./pg-core\"`); a condition map\n * keys them by condition (`\"require\"`, `\"import\"`). One dot tells them apart. */\nfunction isSubpathMap(o: Record<string, unknown>): boolean {\n return Object.keys(o).some((k) => k.startsWith('.'));\n}\n\n/**\n * Match a subpath key against an `exports` pattern containing one `*`.\n * `./pg-core` against `./*` captures `pg-core`; the capture is substituted back\n * into the target, which is how `\"./*\": \"./dist/*.js\"` resolves.\n */\nfunction matchWildcard(pattern: string, key: string): string | null {\n const star = pattern.indexOf('*');\n if (star === -1) return null;\n const pre = pattern.slice(0, star);\n const post = pattern.slice(star + 1);\n if (key.length < pre.length + post.length) return null;\n if (!key.startsWith(pre) || !key.endsWith(post)) return null;\n return key.slice(pre.length, key.length - post.length);\n}\n\n/**\n * Every entry an `exports` map offers for one subpath key, in condition order.\n *\n * Collecting rather than short-circuiting, so a caller whose first choice\n * extracted nothing has the remaining conditions to try. Duplicates are fine\n * here — resolveEntryCandidates dedupes on the resolved path, which is what\n * actually has to be distinct.\n *\n * `key` is `\".\"` for the package root and `\"./pg-core\"` for a subpath. Without\n * it this could only ever answer for the root, which is why\n * `drizzle-orm/pg-core` had no surface to compare against and every symbol\n * imported from it went unchecked.\n */\nfunction pickAllFromExports(exp: unknown, key = '.', depth = 0): string[] {\n if (depth > 8) return [];\n // A bare string `exports` declares the root entry and nothing else.\n if (typeof exp === 'string') return key === '.' ? [exp] : [];\n if (Array.isArray(exp)) return exp.flatMap((e) => pickAllFromExports(e, key, depth + 1));\n if (!exp || typeof exp !== 'object') return [];\n const o = exp as Record<string, unknown>;\n\n if (isSubpathMap(o)) {\n if (key in o) return pickAllFromExports(o[key], '.', depth + 1);\n // Longest matching pattern wins, as Node does: `./lib/*` beats `./*`.\n const patterns = Object.keys(o)\n .filter((k) => k.includes('*'))\n .sort((a, b) => b.length - a.length);\n for (const p of patterns) {\n const capture = matchWildcard(p, key);\n if (capture === null) continue;\n const targets = pickAllFromExports(o[p], '.', depth + 1);\n if (targets.length) return targets.map((t) => t.split('*').join(capture));\n }\n return [];\n }\n return CONDITIONS.filter((c) => c in o).flatMap((c) => pickAllFromExports(o[c], key, depth + 1));\n}\n\n/** Resolve a file path, trying extensions and directory index files. */\nexport function resolveFile(candidate: string): string | null {\n if (existsSync(candidate)) {\n try {\n if (statSync(candidate).isFile()) return candidate;\n // directory → index.*\n for (const ext of EXTENSIONS) {\n const idx = join(candidate, `index${ext}`);\n if (existsSync(idx) && statSync(idx).isFile()) return idx;\n }\n } catch {\n return null;\n }\n }\n for (const ext of EXTENSIONS) {\n const withExt = `${candidate}${ext}`;\n if (existsSync(withExt)) return withExt;\n }\n return null;\n}\n\n/**\n * The file `require('<pkg>')` loads, or `require('<pkg>/<subpath>')` when a\n * subpath is given. Null when the package ships no usable JS entry there.\n */\nexport function resolveEntry(\n pkgDir: string,\n manifest?: PackageManifest | null,\n subpath?: string,\n): string | null {\n return resolveEntryCandidates(pkgDir, manifest, subpath)[0] ?? null;\n}\n\n/**\n * Every entry this package could reasonably be read from, best first.\n *\n * `resolveEntry` returns only the winner, which is right until the winner turns\n * out to be unreadable. An ESM-first package ships a `require` condition that is\n * a thin CJS wrapper — it re-exports through a runtime call the AST walker\n * cannot follow, so extraction resolves an entry, walks one file, and finds zero\n * exports. date-fns and vitest both did exactly that, and the result was not an\n * error: `usage` and `diff_surface` returned an empty surface for two packages\n * with hundreds of exports between them, which reads as \"this package has no\n * API\" rather than \"we could not read it\".\n *\n * So the caller gets the whole ordered list and can move on when a candidate\n * comes back empty. The order is unchanged — `require` still wins for the CJS\n * packages it was chosen for, and nothing that already extracted cleanly takes a\n * different path. This only adds somewhere to go when the first door is shut.\n *\n * With a `subpath`, the same list for that entry point instead. A subpath entry\n * has its own export surface, unrelated to the root's: `drizzle-orm/pg-core`\n * exports `pgTable`, which `drizzle-orm` does not. Scoring one against the other\n * reports every symbol missing on correct code, so those references used to be\n * dropped instead, which reported nothing missing on broken code. Both\n * directions are wrong; resolving the real entry is the only answer, and it\n * inherits the same unreadable-candidate fallback the root gets.\n */\nexport function resolveEntryCandidates(\n pkgDir: string,\n manifest?: PackageManifest | null,\n subpath?: string,\n): string[] {\n const m = manifest ?? readManifest(pkgDir);\n if (!m) return [];\n const sub = subpath?.replace(/^\\.?\\//, '').replace(/\\/$/, '');\n const specifiers = (\n sub\n ? // An `exports` map is a hard boundary in Node: a subpath it does not\n // list cannot be imported, so guessing at a file would invent a surface\n // the runtime refuses to load. The bare path is offered only for the\n // legacy main/index layout, where any real file is genuinely reachable.\n m.exports !== undefined\n ? pickAllFromExports(m.exports, `./${sub}`)\n : [`./${sub}`]\n : [\n ...(m.exports !== undefined ? pickAllFromExports(m.exports) : []),\n m.main ?? null,\n m.module ?? null,\n './index.js',\n ]\n ).filter((c): c is string => typeof c === 'string' && c.length > 0);\n\n const out: string[] = [];\n for (const c of specifiers) {\n const hit = resolveFile(resolvePath(pkgDir, c));\n if (hit && !out.includes(hit)) out.push(hit);\n }\n return out;\n}\n\n/**\n * Does this specifier stay inside the package?\n *\n * Relative specifiers do. A bare specifier (`@smithy/types`, `lodash`) does not,\n * and its names must be recorded with `origin: external:*` rather than counted as\n * this package's runtime surface — defect §6.4.1, the one that produced a phantom\n * 168-export deletion.\n */\nexport function resolvesInsidePackage(spec: string): boolean {\n return spec.startsWith('./') || spec.startsWith('../') || spec === '.' || spec === '..';\n}\n\n/** Resolve a relative specifier from `fromFile`, refusing to escape `pkgDir`. */\nexport function resolveInternal(\n fromFile: string,\n spec: string,\n pkgDir: string,\n): string | null {\n const target = resolvePath(dirname(fromFile), spec);\n const root = resolvePath(pkgDir);\n // Escaping the package root means it isn't this package's surface.\n if (target !== root && !target.startsWith(root + sep)) return null;\n return resolveFile(target);\n}\n","/**\n * Tier A — shipped-JS surface extraction via module-graph AST (§6.2).\n *\n * Answers \"does this symbol exist at runtime\", which is what decides whether an\n * import throws. Never executes the subject's code — that property is what makes\n * enterprise extraction against a customer's private registry reviewable (§9.2).\n *\n * The single most important behaviour here is that it RECURSES through the\n * package-internal module graph. `module.exports = require('./lib/x')` is\n * ubiquitous; a single-file parse returns zero exports for express, debug, and\n * react (defect §6.4.5). Coverage on the study's 12-package smoke test went 9/12\n * with two total failures → 12/12 once the graph walk landed.\n *\n * Parser: the `typescript` package, which is already a devDependency and parses\n * plain JS fine. It stays on the operator plane — see 192ca3f for why it must\n * never enter the public bundle.\n */\nimport { readFileSync } from 'node:fs';\nimport { relative } from 'node:path';\nimport ts from 'typescript';\nimport {\n readManifest,\n resolveEntryCandidates,\n resolveInternal,\n resolvesInsidePackage,\n type PackageManifest,\n} from './resolve';\nimport type { ExtractedSurface, SurfaceSymbol, SymbolKind } from './types';\n\nconst TIER = 'shipped_js_ast' as const;\nconst MAX_FILES = 400; // cycle guard is exact; this bounds pathological graphs\n\ninterface WalkCtx {\n pkgDir: string;\n visited: Set<string>;\n filesWalked: number;\n external: Set<string>;\n truncated: boolean;\n}\n\n/** Classify an expression into the IR's kind + arity. */\nfunction classify(node: ts.Node): { kind: SymbolKind; arity: number | null } {\n if (ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isFunctionDeclaration(node)) {\n return { kind: 'function', arity: arityOf(node) };\n }\n if (ts.isClassExpression(node) || ts.isClassDeclaration(node)) return { kind: 'class', arity: null };\n if (ts.isObjectLiteralExpression(node)) return { kind: 'object', arity: null };\n if (\n ts.isStringLiteral(node) ||\n ts.isNumericLiteral(node) ||\n node.kind === ts.SyntaxKind.TrueKeyword ||\n node.kind === ts.SyntaxKind.FalseKeyword ||\n node.kind === ts.SyntaxKind.NullKeyword\n ) {\n return { kind: 'primitive', arity: null };\n }\n return { kind: 'object', arity: null };\n}\n\n/**\n * `fn.length` semantics: parameters before the first one with a default or rest.\n * Matching the runtime definition matters because arity drift is compared against\n * values captured at tier B, where it really is `fn.length`.\n */\nfunction arityOf(fn: ts.SignatureDeclarationBase): number {\n let n = 0;\n for (const p of fn.parameters) {\n if (p.initializer || p.dotDotDotToken) break;\n n++;\n }\n return n;\n}\n\nfunction lineOf(sf: ts.SourceFile, node: ts.Node): number {\n return sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;\n}\n\nfunction put(\n out: Map<string, SurfaceSymbol>,\n sym: SurfaceSymbol,\n): void {\n // First writer wins: the entry file's own binding outranks a later re-export.\n if (!out.has(sym.path)) out.set(sym.path, sym);\n}\n\n/** Resolve an identifier to its initializer within the same file, if declared there. */\nfunction localBinding(sf: ts.SourceFile, name: string): ts.Node | null {\n let found: ts.Node | null = null;\n for (const stmt of sf.statements) {\n if (ts.isVariableStatement(stmt)) {\n for (const d of stmt.declarationList.declarations) {\n if (ts.isIdentifier(d.name) && d.name.text === name && d.initializer) found = d.initializer;\n }\n } else if (ts.isFunctionDeclaration(stmt) && stmt.name?.text === name) {\n found = stmt;\n } else if (ts.isClassDeclaration(stmt) && stmt.name?.text === name) {\n found = stmt;\n }\n }\n return found;\n}\n\nfunction isModuleExports(e: ts.Expression): boolean {\n return (\n ts.isPropertyAccessExpression(e) &&\n ts.isIdentifier(e.expression) &&\n e.expression.text === 'module' &&\n e.name.text === 'exports'\n );\n}\n\n/** `module.exports.X` / `exports.X` → \"X\"; null if it isn't an exports write. */\nfunction exportTargetName(e: ts.Expression): string | null {\n if (!ts.isPropertyAccessExpression(e)) return null;\n if (ts.isIdentifier(e.expression) && e.expression.text === 'exports') return e.name.text;\n if (isModuleExports(e.expression)) return e.name.text;\n return null;\n}\n\nfunction hasDeprecatedTag(sf: ts.SourceFile, node: ts.Node): boolean {\n const full = node.getFullText(sf);\n const lead = full.slice(0, full.length - node.getText(sf).length);\n return /@deprecated/i.test(lead);\n}\n\n/**\n * Top-level statements plus those nested in control flow.\n *\n * `debug` ships `if (…) { module.exports = require('./browser.js') } else { … }`\n * — a top-level-only scan returns zero exports for it, which is defect §6.4.5.\n * Function and class bodies are deliberately NOT descended into: an assignment\n * inside a function is not the module's surface.\n */\nfunction flattenStatements(\n stmts: readonly ts.Statement[],\n depth = 0,\n): ts.Statement[] {\n if (depth > 6) return [...stmts];\n const out: ts.Statement[] = [];\n for (const s of stmts) {\n out.push(s);\n if (ts.isBlock(s)) out.push(...flattenStatements(s.statements, depth + 1));\n else if (ts.isIfStatement(s)) {\n const branches = [s.thenStatement, s.elseStatement].filter(Boolean) as ts.Statement[];\n for (const b of branches) {\n out.push(...flattenStatements(ts.isBlock(b) ? b.statements : [b], depth + 1));\n }\n } else if (ts.isTryStatement(s)) {\n out.push(...flattenStatements(s.tryBlock.statements, depth + 1));\n if (s.catchClause) out.push(...flattenStatements(s.catchClause.block.statements, depth + 1));\n if (s.finallyBlock) out.push(...flattenStatements(s.finallyBlock.statements, depth + 1));\n } else if (ts.isSwitchStatement(s)) {\n for (const c of s.caseBlock.clauses) {\n out.push(...flattenStatements(c.statements, depth + 1));\n }\n }\n }\n return out;\n}\n\nfunction walk(file: string, ctx: WalkCtx, out: Map<string, SurfaceSymbol>): void {\n if (ctx.visited.has(file)) return; // cycle guard (§6.2)\n if (ctx.filesWalked >= MAX_FILES) {\n ctx.truncated = true;\n return;\n }\n ctx.visited.add(file);\n ctx.filesWalked++;\n\n let text: string;\n try {\n text = readFileSync(file, 'utf8');\n } catch {\n return;\n }\n const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);\n const rel = relative(ctx.pkgDir, file);\n\n const add = (path: string, node: ts.Node, over: Partial<SurfaceSymbol> = {}) => {\n const { kind, arity } = classify(node);\n put(out, {\n path,\n kind,\n arity,\n origin: 'local',\n deprecated: hasDeprecatedTag(sf, node),\n tier: TIER,\n sourceRef: { file: rel, line: lineOf(sf, node) },\n ...over,\n });\n };\n\n /**\n * A re-export specifier: recurse if internal, record as external if not\n * (§6.4.1).\n *\n * `picks` carries the named subset for `export { a, b as c } from './x'`.\n * Honouring it is not optional: `uuid` re-exports one `default` per internal\n * file (`export { default as MAX } from './max.js'`), so merging the target's\n * whole surface both INVENTS its internal helpers as package exports and LOSES\n * the renamed ones. Measured at 3/10 baseline precision before this — the\n * worst class of error we can make, since it claims symbols that do not exist.\n */\n const reExport = (\n spec: string,\n names: string[] | null,\n picks?: { from: string; as: string }[],\n ): void => {\n if (resolvesInsidePackage(spec)) {\n const target = resolveInternal(file, spec, ctx.pkgDir);\n if (!target) return;\n if (!picks) {\n walk(target, ctx, out); // `export * from`, the whole surface is correct\n return;\n }\n // Selective: resolve the target's surface separately, then take only what\n // was asked for, under the name it was asked for.\n const sub = new Map<string, SurfaceSymbol>();\n walk(target, { ...ctx, visited: new Set(ctx.visited) }, sub);\n for (const pick of picks) {\n const found = sub.get(pick.from);\n if (found) put(out, { ...found, path: pick.as });\n else put(out, { path: pick.as, kind: 'object', arity: null, origin: 'local', deprecated: false, tier: TIER, sourceRef: { file: rel, line: 1 } });\n }\n return;\n }\n ctx.external.add(spec);\n for (const n of names ?? []) {\n put(out, {\n path: n,\n kind: 'object',\n arity: null,\n origin: `external:${spec}`,\n deprecated: false,\n tier: TIER,\n sourceRef: { file: rel, line: 1 },\n });\n }\n };\n\n for (const stmt of flattenStatements(sf.statements)) {\n // ── ESM ────────────────────────────────────────────────────────────────\n if (ts.isExportDeclaration(stmt)) {\n const spec =\n stmt.moduleSpecifier && ts.isStringLiteral(stmt.moduleSpecifier)\n ? stmt.moduleSpecifier.text\n : null;\n const isTypeOnly = stmt.isTypeOnly;\n if (stmt.exportClause && ts.isNamedExports(stmt.exportClause)) {\n const names = stmt.exportClause.elements.map((el) => el.name.text);\n if (spec) {\n reExport(\n spec,\n names,\n stmt.exportClause.elements.map((el) => ({\n from: el.propertyName?.text ?? el.name.text,\n as: el.name.text,\n })),\n );\n } else {\n for (const el of stmt.exportClause.elements) {\n const local = el.propertyName?.text ?? el.name.text;\n const decl = localBinding(sf, local);\n if (isTypeOnly || el.isTypeOnly) {\n put(out, {\n path: el.name.text,\n kind: 'type_only',\n arity: null,\n origin: 'local',\n deprecated: false,\n tier: TIER,\n sourceRef: { file: rel, line: lineOf(sf, el) },\n });\n } else if (decl) {\n add(el.name.text, decl);\n } else {\n add(el.name.text, el);\n }\n }\n }\n } else if (spec) {\n // `export * from '<spec>'`\n reExport(spec, null);\n }\n continue;\n }\n\n // `export const X` / `export function X` / `export class X`\n const mods = ts.canHaveModifiers(stmt) ? ts.getModifiers(stmt) : undefined;\n const exported = mods?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword);\n if (exported) {\n if (ts.isVariableStatement(stmt)) {\n for (const d of stmt.declarationList.declarations) {\n if (ts.isIdentifier(d.name)) add(d.name.text, d.initializer ?? d);\n }\n } else if (ts.isFunctionDeclaration(stmt) && stmt.name) {\n add(stmt.name.text, stmt);\n } else if (ts.isClassDeclaration(stmt) && stmt.name) {\n add(stmt.name.text, stmt);\n } else if (ts.isInterfaceDeclaration(stmt) || ts.isTypeAliasDeclaration(stmt)) {\n // §6.4.4: type-only. Never counted in runtime-surface diffs.\n put(out, {\n path: stmt.name.text,\n kind: 'type_only',\n arity: null,\n origin: 'local',\n deprecated: false,\n tier: TIER,\n sourceRef: { file: rel, line: lineOf(sf, stmt) },\n });\n }\n continue;\n }\n\n if (ts.isExportAssignment(stmt)) {\n // `export default <expr>`\n const target = ts.isIdentifier(stmt.expression)\n ? (localBinding(sf, stmt.expression.text) ?? stmt.expression)\n : stmt.expression;\n add('default', target);\n continue;\n }\n\n // ── CommonJS ───────────────────────────────────────────────────────────\n if (ts.isExpressionStatement(stmt)) {\n const e = stmt.expression;\n\n // Object.defineProperty(exports, \"name\", { get() {…} }) — Babel's CJS\n // output, and older tsc's. Extremely common on npm: uuid@9 declares its\n // entire surface this way, and without this branch every Babel-compiled\n // package extracts as zero exports and lands as UNDECLARED.\n if (\n ts.isCallExpression(e) &&\n ts.isPropertyAccessExpression(e.expression) &&\n ts.isIdentifier(e.expression.expression) &&\n e.expression.expression.text === 'Object' &&\n e.expression.name.text === 'defineProperty' &&\n e.arguments.length >= 2\n ) {\n const targetArg = e.arguments[0]!;\n const isExportsTarget =\n (ts.isIdentifier(targetArg) && targetArg.text === 'exports') ||\n isModuleExports(targetArg as ts.Expression);\n const nameArg = e.arguments[1]!;\n if (isExportsTarget && ts.isStringLiteral(nameArg) && nameArg.text !== '__esModule') {\n // The descriptor's getter usually forwards to another module\n // (`return _nil.default`), so the VALUE is not statically known — but\n // existence is, and existence is what tier A is for.\n put(out, {\n path: nameArg.text,\n kind: 'object',\n arity: null,\n origin: 'local',\n deprecated: hasDeprecatedTag(sf, stmt),\n tier: TIER,\n sourceRef: { file: rel, line: lineOf(sf, stmt) },\n });\n continue;\n }\n }\n\n // Object.assign(module.exports, X, …) / __exportStar(require('x'), …)\n if (ts.isCallExpression(e)) {\n const callee = e.expression;\n const isObjectAssign =\n ts.isPropertyAccessExpression(callee) &&\n ts.isIdentifier(callee.expression) &&\n callee.expression.text === 'Object' &&\n callee.name.text === 'assign' &&\n e.arguments.length > 0 &&\n isModuleExports(e.arguments[0]!);\n // esbuild emits `__reExport(target, require('./x'), module.exports)`, tsc\n // emits `__exportStar(require('./x'), exports)`. Helper names and argument\n // order both vary, so match the family and scan every argument for a\n // require() rather than assuming a slot.\n const isExportStar =\n ts.isIdentifier(callee) && /^_{0,2}(exportStar|reExport|export)$/i.test(callee.text);\n\n if (isObjectAssign || isExportStar) {\n for (const arg of e.arguments.slice(isObjectAssign ? 1 : 0)) {\n const spec = requireSpecifier(arg);\n if (spec) reExport(spec, null);\n else if (ts.isObjectLiteralExpression(arg)) {\n for (const p of arg.properties) {\n if (p.name && ts.isIdentifier(p.name)) {\n add(p.name.text, ts.isPropertyAssignment(p) ? p.initializer : p);\n }\n }\n } else if (ts.isIdentifier(arg)) {\n const b = localBinding(sf, arg.text);\n if (b && ts.isObjectLiteralExpression(b)) {\n for (const p of b.properties) {\n if (p.name && ts.isIdentifier(p.name)) {\n add(p.name.text, ts.isPropertyAssignment(p) ? p.initializer : p);\n }\n }\n }\n }\n }\n continue;\n }\n }\n\n if (!ts.isBinaryExpression(e) || e.operatorToken.kind !== ts.SyntaxKind.EqualsToken) continue;\n const lhs = e.left;\n const rhs = e.right;\n\n // module.exports = <expr>\n if (isModuleExports(lhs)) {\n const spec = requireSpecifier(rhs);\n if (spec) {\n reExport(spec, null);\n continue;\n }\n if (ts.isObjectLiteralExpression(rhs)) {\n for (const p of rhs.properties) {\n if (p.name && ts.isIdentifier(p.name)) {\n add(p.name.text, ts.isPropertyAssignment(p) ? p.initializer : p);\n }\n }\n continue;\n }\n if (ts.isIdentifier(rhs)) {\n // `const N = {…}; module.exports = N` — resolve the binding (§6.2)\n const b = localBinding(sf, rhs.text);\n if (b && ts.isObjectLiteralExpression(b)) {\n for (const p of b.properties) {\n if (p.name && ts.isIdentifier(p.name)) {\n add(p.name.text, ts.isPropertyAssignment(p) ? p.initializer : p);\n }\n }\n continue;\n }\n if (b) {\n add('default', b);\n continue;\n }\n }\n add('default', rhs);\n continue;\n }\n\n // module.exports.X = <expr> / exports.X = <expr>\n const name = exportTargetName(lhs);\n if (name) {\n const spec = requireSpecifier(rhs);\n if (spec && !resolvesInsidePackage(spec)) {\n ctx.external.add(spec);\n put(out, {\n path: name,\n kind: 'object',\n arity: null,\n origin: `external:${spec}`,\n deprecated: false,\n tier: TIER,\n sourceRef: { file: rel, line: lineOf(sf, stmt) },\n });\n continue;\n }\n const target = ts.isIdentifier(rhs) ? (localBinding(sf, rhs.text) ?? rhs) : rhs;\n add(name, target, { deprecated: hasDeprecatedTag(sf, stmt) });\n }\n }\n }\n}\n\n/** `require('x')` → 'x', including `require('x').y`. Null otherwise. */\nfunction requireSpecifier(node: ts.Node): string | null {\n let n: ts.Node = node;\n if (ts.isPropertyAccessExpression(n)) n = n.expression;\n if (\n ts.isCallExpression(n) &&\n ts.isIdentifier(n.expression) &&\n n.expression.text === 'require' &&\n n.arguments.length === 1 &&\n ts.isStringLiteral(n.arguments[0]!)\n ) {\n return (n.arguments[0] as ts.StringLiteral).text;\n }\n return null;\n}\n\n/**\n * Did this entry give us anything a consumer could name?\n *\n * Empty is the obvious failure. A lone `default` is the same failure wearing a\n * result: `module.exports = require('./impl')(globalThis)` parses, produces\n * exactly one symbol, and tells you nothing about the API behind it. Both mean\n * \"try the next condition\" — and a package whose surface genuinely is one\n * default export loses nothing, because no other candidate will read better and\n * the first attempt is what gets reported.\n */\nfunction isReadable(symbols: SurfaceSymbol[]): boolean {\n if (symbols.length === 0) return false;\n return !(symbols.length === 1 && symbols[0]!.path === 'default');\n}\n\n/**\n * Extract the tier-A runtime surface of an installed package directory.\n * Never throws for a subject-side problem — a package with no resolvable entry\n * returns `undeclaredReason`, which the caller records as UNDECLARED, not as\n * absence (§4.2).\n */\nexport function extractSurface(\n pkgDir: string,\n opts: { manifest?: PackageManifest | null; subpath?: string } = {},\n): ExtractedSurface {\n const manifest = opts.manifest ?? readManifest(pkgDir);\n const candidates = resolveEntryCandidates(pkgDir, manifest, opts.subpath);\n const base: ExtractedSurface = {\n package: manifest?.name ?? pkgDir,\n version: manifest?.version ?? null,\n tier: TIER,\n entry: null,\n symbols: [],\n filesWalked: 0,\n externalReExports: [],\n };\n if (!candidates.length) {\n return {\n ...base,\n undeclaredReason: opts.subpath\n ? `no resolvable JS entry point for subpath ./${opts.subpath}`\n : 'no resolvable JS entry point',\n };\n }\n\n // Try each entry until one yields a readable surface. An ESM-first package's\n // `require` condition is often a wrapper that re-exports through a runtime\n // call, which the AST walker cannot follow: it resolves, walks one file, and\n // reports nothing usable. Reporting that as the package's surface is the\n // dangerous outcome — an empty surface reads as \"no API\" and makes every\n // later diff look like the package deleted everything.\n //\n // The first candidate that reads wins, so the require-first preference is\n // intact for the CJS packages it was chosen for. When no candidate reads, the\n // first attempt is what we report, because that is the entry a consumer would\n // actually load and \"we could not read this one\" is the honest answer.\n const attempts: { entry: string; symbols: SurfaceSymbol[]; walked: number; external: string[] }[] = [];\n for (const entry of candidates) {\n const ctx: WalkCtx = {\n pkgDir,\n visited: new Set(),\n filesWalked: 0,\n external: new Set(),\n truncated: false,\n };\n const out = new Map<string, SurfaceSymbol>();\n walk(entry, ctx, out);\n attempts.push({\n entry,\n symbols: [...out.values()].sort((a, b) => a.path.localeCompare(b.path)),\n walked: ctx.filesWalked,\n external: [...ctx.external].sort(),\n });\n if (isReadable(attempts[attempts.length - 1]!.symbols)) break;\n }\n const attempt = attempts.find((a) => isReadable(a.symbols)) ?? attempts[0]!;\n\n return {\n ...base,\n entry: relative(pkgDir, attempt.entry),\n symbols: attempt.symbols,\n filesWalked: attempt.walked,\n externalReExports: attempt.external,\n ...(attempt.symbols.length === 0\n ? { undeclaredReason: 'entry resolved but no exports found' }\n : {}),\n };\n}\n","/**\n * Fetch stage (§6.1): pull a package tarball, hash it, extract its tier-A\n * surface, and hand it back for storage.\n *\n * The digest is the cache key. An unchanged tarball must never pay for\n * extraction twice — that is what keeps cost sublinear as breadth grows (§6.5),\n * and breadth is exactly when cost starts to matter.\n *\n * Nothing here executes package code. The tarball is unpacked and parsed; no\n * install runs, no lifecycle script fires. That property is load-bearing for\n * §9.2: \"we read the shipped JS in your registry\" survives a security review\n * that \"we run your packages in our sandbox\" does not.\n */\nimport { execFile } from 'node:child_process';\nimport { createHash } from 'node:crypto';\nimport { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { promisify } from 'node:util';\nimport { encodeNpmName } from '../ingestion/sources/npmRegistry';\nimport type { ExtractedSurface } from './types';\n\nconst execFileP = promisify(execFile);\nconst FETCH_TIMEOUT_MS = 60_000;\nconst MAX_TARBALL_BYTES = 64 * 1024 * 1024;\n\nexport interface FetchedSurface {\n surface: ExtractedSurface;\n /**\n * Surfaces of the subpath entry points named in `opts.subpaths`, keyed by\n * subpath (`pg-core`). Extracted from the same unpacked tarball as the root,\n * because a package with four used entry points would otherwise cost four\n * downloads of the same archive.\n */\n subpathSurfaces?: Record<string, ExtractedSurface>;\n /** sha256 of the tarball — the extraction cache key. */\n artifactHash: string;\n resolvedVersion: string;\n}\n\ninterface DistInfo {\n tarball: string;\n version: string;\n}\n\n/** Resolve a version spec to a concrete tarball URL via the registry. */\nexport async function resolveTarball(\n name: string,\n version: string | null,\n fetchImpl: typeof fetch = fetch,\n): Promise<DistInfo | null> {\n const spec = version ?? 'latest';\n const url = `https://registry.npmjs.org/${encodeNpmName(name)}/${encodeURIComponent(spec)}`;\n const res = await fetchImpl(url, { headers: { accept: 'application/json' } });\n if (!res.ok) return null;\n const body = (await res.json()) as { version?: string; dist?: { tarball?: string } };\n if (!body?.dist?.tarball || !body.version) return null;\n return { tarball: body.dist.tarball, version: body.version };\n}\n\n/**\n * Download, hash, unpack, and extract. Throws only on infrastructure failure —\n * the caller records UNVERIFIABLE and requeues rather than condemning the\n * package, because a rate limit is not evidence about a package (§4.2).\n */\nexport async function fetchAndExtract(\n name: string,\n version: string | null,\n opts: { fetchImpl?: typeof fetch; subpaths?: string[] } = {},\n): Promise<FetchedSurface | null> {\n const fetchImpl = opts.fetchImpl ?? fetch;\n const dist = await resolveTarball(name, version, fetchImpl);\n if (!dist) return null;\n\n const res = await fetchImpl(dist.tarball);\n if (!res.ok) throw new Error(`tarball fetch failed: ${res.status} ${dist.tarball}`);\n const buf = Buffer.from(await res.arrayBuffer());\n if (buf.byteLength > MAX_TARBALL_BYTES) {\n throw new Error(`tarball exceeds ${MAX_TARBALL_BYTES} bytes: ${name}@${dist.version}`);\n }\n const artifactHash = createHash('sha256').update(buf).digest('hex');\n\n const dir = await mkdtemp(join(tmpdir(), 'lurq-surface-'));\n try {\n const tgz = join(dir, 'pkg.tgz');\n const pkgDir = join(dir, 'pkg');\n await mkdir(pkgDir, { recursive: true });\n await writeFile(tgz, buf);\n // `tar` only unpacks; it never executes anything from the archive.\n //\n // --strip-components=1 rather than assuming a `package/` root: npm tarballs\n // USUALLY root there, but not always — @types/* roots at the type name\n // (`node/`, not `package/`), so a hardcoded path fails extraction outright\n // for all of DefinitelyTyped. Stripping the first component normalizes any\n // root name.\n await execFileP('tar', ['xzf', tgz, '--strip-components=1', '-C', pkgDir], {\n timeout: FETCH_TIMEOUT_MS,\n });\n\n // A tarball with no readable manifest is a fact ABOUT THE PACKAGE, not an\n // infrastructure failure — it must surface as UNDECLARED rather than throw,\n // or the drain will treat a type-only package as our own outage and retry\n // it forever (§4.2).\n try {\n await readFile(join(pkgDir, 'package.json'), 'utf8');\n } catch {\n return {\n surface: {\n package: name,\n version: dist.version,\n tier: 'shipped_js_ast',\n entry: null,\n symbols: [],\n filesWalked: 0,\n externalReExports: [],\n undeclaredReason: 'tarball contains no readable package.json',\n },\n artifactHash,\n resolvedVersion: dist.version,\n };\n }\n\n // Loaded here, not at module scope: `extractSurface` pulls in the TypeScript\n // compiler, which is an operator-only dependency. A static edge put it in\n // every bundle chunk that reaches this file, so `sync` (which never\n // extracts) refused to boot without it.\n const { extractSurface } = await import('./extract');\n const surface = extractSurface(pkgDir);\n const subpathSurfaces: Record<string, ExtractedSurface> = {};\n for (const sub of new Set(opts.subpaths ?? [])) {\n subpathSurfaces[sub] = {\n ...extractSurface(pkgDir, { subpath: sub }),\n package: `${name}/${sub}`,\n version: dist.version,\n };\n }\n return {\n surface: { ...surface, package: name, version: dist.version },\n ...(opts.subpaths?.length ? { subpathSurfaces } : {}),\n artifactHash,\n resolvedVersion: dist.version,\n };\n } finally {\n await rm(dir, { recursive: true, force: true }).catch(() => {});\n }\n}\n","/**\n * Surface-extraction drain (§6.1).\n *\n * Services the demand-driven queue: fetch the tarball, check the digest against\n * the extraction cache, extract, store. Runs off the query path, which is what\n * lets a query answer UNKNOWN in milliseconds instead of blocking on a download.\n *\n * Failure handling follows §4.2: infrastructure problems bump the attempt count\n * and leave the spec queued, they never record a verdict about the package. A\n * rate limit is not evidence about anyone's API.\n */\nimport { formatError } from '../core/errors';\nimport { logger } from '../core/logger';\nimport type { Database } from '../db/client';\nimport {\n bumpSurfaceAttempt,\n dropSurfaceQueue,\n enqueuePreviousSurface,\n enqueueSurface,\n getPendingSurfaces,\n isExtractionCached,\n getPackagesMissingGraphSurface,\n storeSurface,\n surfaceRef,\n} from '../db/surface';\nimport { getPackageVersions } from '../db/packages';\nimport { getPackagesWithSurface } from '../db/apiSurfaces';\nimport { fetchAndExtract } from '../surface/fetch';\n\n/**\n * How far back to read the version timeline when locating a version's immediate\n * predecessor. Only the neighbour matters, but the timeline is newest-first and\n * a package can ship a burst of releases, so this is slack rather than a budget.\n */\nconst VERSION_LOOKBACK = 50;\n\n/**\n * Bumped whenever extraction can produce a different answer for the same\n * tarball. '2' covers the ESM-first entry fallback and namespace member\n * resolution — both change what a package's surface is, neither changes a byte\n * of the artifact, and isExtractionCached now compares this so a stored surface\n * from an older extractor is treated as stale.\n */\nconst EXTRACTOR_VERSION = '2';\nconst MAX_ATTEMPTS = 3;\n\nexport interface SurfaceDrainSummary {\n drained: number;\n stored: number;\n cached: number;\n undeclared: number;\n failed: number;\n /** Predecessor versions queued so this one becomes diffable. */\n backfilled: number;\n}\n\n/** Extract and store one package version. Returns what happened, for the log. */\nexport type SurfaceOutcome = 'stored' | 'cached' | 'undeclared' | 'missing';\n\n/**\n * Extract and persist one surface. Returns the outcome plus the version it\n * actually resolved to — the caller needs that to make the version *diffable*,\n * and `version` may have been null (\"whatever latest is\").\n */\nexport async function extractAndStore(\n db: Database,\n pkg: string,\n version: string | null,\n): Promise<{ outcome: SurfaceOutcome; version: string | null }> {\n const fetched = await fetchAndExtract(pkg, version);\n if (!fetched) return { outcome: 'missing', version: null };\n\n const resolved = fetched.resolvedVersion;\n const ref = surfaceRef(pkg, resolved);\n if (await isExtractionCached(db, ref, fetched.artifactHash, EXTRACTOR_VERSION))\n return { outcome: 'cached', version: resolved };\n\n const res = await storeSurface(db, fetched.surface, {\n artifactHash: fetched.artifactHash,\n extractorVersion: EXTRACTOR_VERSION,\n });\n return {\n outcome: res.verdict === 'undeclared' ? 'undeclared' : 'stored',\n version: resolved,\n };\n}\n\nexport async function drainSurfaceQueue(\n db: Database,\n opts: { limit?: number } = {},\n): Promise<SurfaceDrainSummary> {\n const pending = await getPendingSurfaces(db, opts.limit ?? 10);\n const s: SurfaceDrainSummary = {\n drained: 0,\n stored: 0,\n cached: 0,\n undeclared: 0,\n failed: 0,\n backfilled: 0,\n };\n\n for (const item of pending) {\n s.drained++;\n try {\n const { outcome, version } = await extractAndStore(db, item.packageName, item.version);\n if (outcome === 'stored') s.stored++;\n else if (outcome === 'cached') s.cached++;\n else if (outcome === 'undeclared') s.undeclared++;\n\n // Make this version diffable by pulling its predecessor in behind it. A\n // surface alone says what a package exports; only a pair says what a\n // release *removed*, which is the thing a model trained before the release\n // cannot know and the reason any of this is worth extracting.\n //\n // Best-effort and never fatal: failing to queue a backfill must not fail\n // the extraction that succeeded.\n if (version && (outcome === 'stored' || outcome === 'cached')) {\n await enqueuePreviousSurface(\n db,\n item.packageName,\n version,\n await getPackageVersions(db, item.packageName, VERSION_LOOKBACK),\n ).then(\n (queued) => {\n if (queued) s.backfilled++;\n },\n (err) =>\n logger.warn(\n { pkg: item.packageName, version, err: formatError(err) },\n 'surface: previous-version backfill could not be queued',\n ),\n );\n }\n // `missing` means the registry has no such version — drop it, since\n // requeueing a nonexistent spec would spin forever.\n await dropSurfaceQueue(db, item.id);\n } catch (err) {\n s.failed++;\n // Infrastructure failure. Leave it queued unless it keeps failing; never\n // record a verdict about the package from our own outage.\n if (item.attempts + 1 >= MAX_ATTEMPTS) await dropSurfaceQueue(db, item.id);\n else await bumpSurfaceAttempt(db, item.id);\n logger.warn(\n { spec: item.specKey, attempts: item.attempts + 1, err: formatError(err) },\n 'surface extraction failed',\n );\n }\n }\n return s;\n}\n\nexport interface BackfillSummary {\n scanned: number;\n /** Latest versions queued for packages that had no surface at all. */\n queuedLatest: number;\n /** Predecessors queued so an existing surface becomes diffable. */\n queuedPrevious: number;\n}\n\n/**\n * One-time backfill to give the existing catalog version depth.\n *\n * The publish hook in `watch` only sees releases from now on, so on its own it\n * would take as long as the catalog's release cadence to make anything\n * comparable. This walks what is already tracked and fills the two gaps behind\n * it: packages with no surface at all (half the catalog), and packages with one\n * surface and nothing to diff it against (all but ~4.5%).\n *\n * Enqueues only — it never fetches or extracts. The worker drains at whatever\n * rate its budget allows, so a backfill of the whole catalog cannot outrun the\n * registry or starve the demand-driven queue it shares.\n */\nexport async function backfillSurfaces(\n db: Database,\n opts: { limit?: number; byDownloads?: boolean } = {},\n): Promise<BackfillSummary> {\n const limit = opts.limit ?? 500;\n const s: BackfillSummary = { scanned: 0, queuedLatest: 0, queuedPrevious: 0 };\n\n // Gap 1: no surface in the GRAPH store, which is what `resolve_surface` and\n // `diff_surface` read. This deliberately does NOT use the api_surfaces query:\n // that table is the flat per-version export list behind `usage`, and the\n // proactive worker pass both selects on it and writes to it. A package already\n // covered there was therefore invisible to this backfill even when the\n // diffable store had never seen it — which is exactly how graph coverage ended\n // up an order of magnitude below api_surfaces coverage while every pass\n // reported itself healthy.\n const missing = await getPackagesMissingGraphSurface(db, limit, { byDownloads: opts.byDownloads });\n for (const row of missing) {\n s.scanned++;\n await enqueueSurface(db, row.name, row.version).then(\n () => {\n s.queuedLatest++;\n },\n (err: unknown) =>\n logger.warn({ pkg: row.name, err: formatError(err) }, 'backfill: could not queue latest'),\n );\n }\n\n // Gap 2: a surface exists but has no predecessor, so it cannot be diffed.\n // Sampled rather than ordered, for the same reason `getPackagesMissingSurface`\n // is: a package that can never gain a predecessor (its first ever release)\n // stays in this set forever, and a stable ordering would let the head of it\n // starve the tail indefinitely.\n const withSurface = await getPackagesWithSurface(db, limit);\n for (const row of withSurface) {\n s.scanned++;\n await enqueuePreviousSurface(\n db,\n row.name,\n row.version,\n await getPackageVersions(db, row.name, VERSION_LOOKBACK),\n ).then(\n (queued) => {\n if (queued) s.queuedPrevious++;\n },\n (err: unknown) =>\n logger.warn(\n { pkg: row.name, err: formatError(err) },\n 'backfill: could not queue predecessor',\n ),\n );\n }\n return s;\n}\n","/**\n * Block-on-first-touch for the graph surface store.\n *\n * `resolve_surface` and `diff_surface` read the entities/symbols store, and on a\n * miss they used to enqueue the package and return `unknown` immediately. Every\n * other read path in lurq does the opposite: `evaluate` and `verify` ingest\n * synchronously within a budget, and `usage` extracts within\n * USAGE_EXTRACT_BUDGET_MS. So the two tools with no npm equivalent — the ones\n * `check-upgrade` is built on — were the only ones that answered \"I don't know\"\n * to a question they could have answered in half a second.\n *\n * The consequence was structural, not incidental. A store that only fills from\n * queue drains grows at the rate of the drain; a store that fills from demand\n * grows at the rate of demand. That is the whole reason `api_surfaces` reached\n * 26.9k packages while this store sat at 2.9k, on the same extractor at 0.52s a\n * package.\n *\n * This mirrors `usage/service.ts` deliberately rather than inventing a second\n * policy: same in-flight join, same bounded map, same \"the caller gave up but\n * the extraction keeps going so the next request is a hit\" behaviour. Where it\n * differs is the writer — `extractAndStore` populates entities/claims/\n * observations/symbols, which is what makes a surface *diffable* rather than\n * just listable.\n */\nimport { withBudget } from '../core/concurrency';\nimport type { Database } from '../db/client';\nimport { logger } from '../core/logger';\n\n/**\n * Wall-clock ceiling for a cold miss on a request path.\n *\n * Sized against measured throughput (0.52s per extraction) with room for a slow\n * CDN, and deliberately larger than a single extraction because `diff_surface`\n * needs two and races them together. A caller that exceeds it still leaves the\n * extraction running — the cost has already been paid, and abandoning the write\n * would mean a slow package is never extracted on this path at all.\n */\nexport const SURFACE_FIRST_TOUCH_BUDGET_MS = 4000;\n\n/**\n * Cap on concurrent extractions started from the request path.\n *\n * A flood of distinct versions must not grow memory without bound — the same\n * reason `usage` and the ingest queue cap theirs. Past the cap a miss degrades\n * to the existing queued-and-unknown response, which is a correct answer, just\n * a slower one.\n */\nconst MAX_INFLIGHT = 64;\n\n/** Extractions in progress, keyed `name@version`, so N concurrent misses for the\n * same version share one tarball fetch instead of starting N. */\nconst inFlight = new Map<string, Promise<string | null>>();\n\n/**\n * Start, or join, the single extraction for this package version.\n *\n * Returns the resolved version on success and null on any failure. Failure is\n * never fatal here: the caller falls back to the queued-and-unknown response it\n * would have returned anyway, so a broken CDN degrades this path to exactly the\n * old behaviour rather than to an error.\n */\nfunction extractOnce(db: Database, pkg: string, version: string | null): Promise<string | null> {\n const key = `${pkg}@${version ?? 'latest'}`;\n const existing = inFlight.get(key);\n if (existing) return existing;\n if (inFlight.size >= MAX_INFLIGHT) return Promise.resolve(null);\n\n const task = (async () => {\n // Imported lazily and on purpose. Extraction pulls in the TypeScript\n // compiler, and a static import here would put it on the boot path of every\n // command that touches the MCP handlers — the same trap `worker.ts`\n // documents for `extractSurfacesPass`.\n const { extractAndStore } = await import('./surface');\n const { outcome, version: resolved } = await extractAndStore(db, pkg, version);\n // 'missing' means no artifact to read; 'undeclared' means a real artifact\n // that exports nothing this tier can see. Neither is a stored surface, and\n // reporting either as success would make the caller re-read and find\n // nothing, converting a slow answer into a wrong one.\n return outcome === 'stored' || outcome === 'cached' ? resolved : null;\n })()\n .catch((err) => {\n logger.warn(\n `surface first-touch failed for ${key}: ${err instanceof Error ? err.message : String(err)}`,\n );\n return null;\n })\n .finally(() => {\n inFlight.delete(key);\n });\n\n inFlight.set(key, task);\n return task;\n}\n\n/**\n * Extract one surface into the graph store, bounded by a budget.\n *\n * `null` means \"not available within the budget\" — which covers a genuine\n * failure and a slow-but-still-running extraction identically, because the\n * caller's next move is the same either way: return the honest unknown and let\n * the warmed cache serve the retry.\n */\nexport function firstTouchSurface(\n db: Database,\n pkg: string,\n version: string | null,\n budgetMs: number = SURFACE_FIRST_TOUCH_BUDGET_MS,\n): Promise<string | null> {\n const task = extractOnce(db, pkg, version);\n return budgetMs <= 0 ? Promise.resolve(null) : withBudget(task, budgetMs).then((v) => v ?? null);\n}\n\n/**\n * Extract both sides of a diff under ONE shared budget.\n *\n * Sequential extraction would let a slow `from` consume the whole budget and\n * leave `to` unstarted, so the pair is raced together: both are in flight\n * immediately and the budget bounds the pair rather than each half. Returns\n * whether both sides landed, since a diff with one side missing is not a diff —\n * it is the empty-surface comparison the diff guards already refuse.\n */\nexport async function firstTouchPair(\n db: Database,\n pkg: string,\n fromVersion: string | null,\n toVersion: string | null,\n budgetMs: number = SURFACE_FIRST_TOUCH_BUDGET_MS,\n): Promise<boolean> {\n if (budgetMs <= 0) return false;\n const pair = Promise.all([extractOnce(db, pkg, fromVersion), extractOnce(db, pkg, toVersion)]);\n const settled = await withBudget(pair, budgetMs);\n return Boolean(settled && settled[0] && settled[1]);\n}\n\n/** Test-only: drop memoized in-flight extractions between cases. */\nexport function resetSurfaceFirstTouch(): void {\n inFlight.clear();\n}\n","/**\n * `resolve_surface` and `diff_surface` (§8.1) — the two tools the v1 thesis\n * rests on. `diff_surface` is the demo.\n *\n * Response discipline (§8.2) is enforced here rather than left to callers: every\n * response carries `verdict`, `class`, `tier`, `observedAt`, and a coverage note.\n * A bare answer without provenance is indistinguishable from the model's own\n * guess, which is the thing these tools exist to correct.\n *\n * Extraction NEVER runs inside a query (§8). A miss returns UNKNOWN and enqueues;\n * the worker fills it in. That is what keeps the p99 target reachable, and it is\n * also why the miss path has to be honest rather than optimistic.\n */\nimport { createHash } from 'node:crypto';\nimport { and, desc, eq } from 'drizzle-orm';\nimport { cached } from '../core/cache';\nimport type { Database } from '../db/client';\nimport { claims, entities, observations, symbols } from '../db/schema';\nimport type { SymbolRow } from '../db/schema';\nimport { enqueueSurface, mcpSurfaceRef, surfaceRef } from '../db/surface';\nimport { canonicalKey, type EntityKind, type Verdict } from '../graph/types';\nimport { diffSurfaces } from '../surface/diff';\nimport type { ExtractedSurface, ExtractionTier, SurfaceSymbol } from '../surface/types';\n\nexport interface ResolveSurfaceInput {\n package: string;\n version?: string | null;\n}\n\nexport interface SurfaceResponse {\n package: string;\n version: string | null;\n verdict: Verdict;\n class: 'declared' | 'executed' | 'derived' | null;\n tier: ExtractionTier | null;\n symbols: { path: string; kind: string; arity: number | null; deprecated: boolean }[];\n /** Always populated: a caller must be able to tell a thin answer from a full one. */\n coverageNote: string;\n observedAt: string | null;\n}\n\n/** Stored rows → the extractor's IR, so the diff logic has exactly one implementation. */\nexport function rowsToSurface(\n pkg: string,\n version: string | null,\n rows: SymbolRow[],\n tier: ExtractionTier,\n): ExtractedSurface {\n const symbolsOut: SurfaceSymbol[] = rows.map((r) => ({\n path: r.path,\n kind: r.kind,\n arity: r.arity,\n origin: r.origin as SurfaceSymbol['origin'],\n deprecated: r.deprecated,\n tier: r.tier,\n // The signature was dropped on the way back out of the database, so every\n // diff computed from STORED rows saw `signature: undefined` on both sides\n // and reported no signature drift — for tier C, where signatures are the\n // only thing that tier can report, and for the MCP tier, where the entire\n // tool contract is serialized into this field.\n ...(r.signature !== null ? { signature: r.signature } : {}),\n ...(r.sourceFile ? { sourceRef: { file: r.sourceFile, line: r.sourceLine ?? 0 } } : {}),\n }));\n return {\n package: pkg,\n version,\n tier,\n entry: null,\n symbols: symbolsOut,\n filesWalked: 0,\n externalReExports: [],\n };\n}\n\nexport interface StoredSurface {\n entityId: number;\n rows: SymbolRow[];\n verdict: Verdict;\n class: SurfaceResponse['class'];\n tier: ExtractionTier | null;\n observedAt: string | null;\n}\n\n/**\n * Look up a stored surface plus the observation that established it.\n *\n * `kind` selects the unit type: an npm package's extracted exports, or an MCP\n * server's tool list. They live in the same two tables and are told apart by the\n * node kind, which is the first segment of `canonicalKey` for exactly this\n * reason — a package and a server published under the same name are different\n * subjects with different contracts.\n */\nexport async function loadStored(\n db: Database,\n pkg: string,\n version: string | null,\n tenantId = 0,\n kind: EntityKind = 'package_surface',\n): Promise<StoredSurface | null> {\n // Surfaces are always STORED under a concrete resolved version, so a query\n // with no version can never match by canonical key. An agent asking \"what does\n // zod export?\" without pinning is the common call, so fall back to the most\n // recently observed version of that package.\n let entity;\n if (version === null) {\n const rows = await db\n .select({ e: entities, at: observations.observedAt })\n .from(entities)\n .innerJoin(claims, eq(claims.subjectId, entities.id))\n .innerJoin(observations, eq(observations.claimId, claims.id))\n .where(and(eq(entities.kind, kind), eq(entities.name, pkg)))\n .orderBy(desc(observations.observedAt))\n .limit(1);\n entity = rows.find((r) => r.e.tenantId === tenantId)?.e;\n } else {\n const key = canonicalKey(\n kind === 'mcp_server' ? mcpSurfaceRef(pkg, version) : surfaceRef(pkg, version),\n );\n const ents = await db.select().from(entities).where(eq(entities.canonicalKey, key)).limit(2);\n entity = ents.find((e) => e.tenantId === tenantId);\n }\n if (!entity) return null;\n\n const obs = await db\n .select({ o: observations })\n .from(observations)\n .innerJoin(claims, eq(observations.claimId, claims.id))\n .where(eq(claims.subjectId, entity.id))\n .orderBy(desc(observations.observedAt))\n .limit(1);\n const latest = obs[0]?.o ?? null;\n const rows = await db.select().from(symbols).where(eq(symbols.entityId, entity.id));\n\n return {\n entityId: entity.id,\n rows,\n verdict: latest?.verdict ?? 'unknown',\n class: latest?.class ?? null,\n tier: latest?.tier ?? null,\n observedAt: latest?.observedAt ? latest.observedAt.toISOString() : null,\n };\n}\n\nconst MISS: Omit<SurfaceResponse, 'package' | 'version'> = {\n verdict: 'unknown',\n class: null,\n tier: null,\n symbols: [],\n coverageNote: 'not yet extracted, queued; retry shortly. This is NOT evidence of absence.',\n observedAt: null,\n};\n\n/** Short stable cache key. */\nfunction ckey(parts: unknown): string {\n return createHash('sha1').update(JSON.stringify(parts)).digest('hex').slice(0, 24);\n}\n\n/**\n * §8 requires p99 < 150 ms for cached reads, so the read path is cached — but a\n * MISS is never cached. The worker is about to fill it in, and a cached UNKNOWN\n * would keep answering \"not extracted\" long after it was.\n */\nexport async function handleResolveSurface(\n db: Database,\n input: ResolveSurfaceInput,\n): Promise<SurfaceResponse> {\n return cached(\n 'resolve_surface',\n ckey([input.package, input.version ?? null]),\n () => resolveSurfaceUncached(db, input),\n { skipCache: (v) => v.verdict === 'unknown' },\n );\n}\n\nasync function resolveSurfaceUncached(\n db: Database,\n input: ResolveSurfaceInput,\n): Promise<SurfaceResponse> {\n const version = input.version ?? null;\n let stored = await loadStored(db, input.package, version);\n\n // §8 said never extract inside a query. That rule is relaxed here\n // deliberately, not by accident.\n //\n // What it protected against was unbounded work on a request path. What it\n // cost was that the only store able to answer \"what changed between these two\n // versions\" grew solely at the rate of a queue drain, while `usage` — which\n // does extract inside a query, within a budget — filled itself to nearly ten\n // times the coverage using the same extractor at half a second a package.\n //\n // The original concern is addressed rather than ignored: the wait is bounded\n // by a wall-clock budget, concurrent misses for one version share a single\n // fetch, in-flight extractions are capped, and every failure path falls\n // through to exactly the enqueue-and-answer-honestly behaviour below. A\n // caller waits at most the budget; it never waits on unbounded work.\n if (!stored || (stored.verdict === 'unknown' && stored.rows.length === 0)) {\n const { firstTouchSurface } = await import('../pipeline/firstTouch');\n if (await firstTouchSurface(db, input.package, version)) {\n stored = await loadStored(db, input.package, version);\n }\n }\n\n if (!stored || (stored.verdict === 'unknown' && stored.rows.length === 0)) {\n // Nothing within the budget. Queue it so a retry is a cache hit, and answer\n // honestly — the extraction may still be running and will warm the cache.\n await enqueueSurface(db, input.package, version).catch(() => {});\n return { package: input.package, version, ...MISS };\n }\n\n if (stored.verdict === 'undeclared') {\n return {\n package: input.package,\n version,\n verdict: 'undeclared',\n class: stored.class,\n tier: stored.tier,\n symbols: [],\n coverageNote:\n 'package ships no artifact this tier can read, UNDECLARED, which is a measurement gap, not an empty API',\n observedAt: stored.observedAt,\n };\n }\n\n // Runtime surface only: type-only exports break `tsc`, not `node`, and an\n // external re-export is not this package's surface (§6.4.1, §6.4.4).\n const runtime = stored.rows.filter((r) => r.kind !== 'type_only' && r.origin === 'local');\n const excluded = stored.rows.length - runtime.length;\n\n return {\n package: input.package,\n version,\n verdict: stored.verdict,\n class: stored.class,\n tier: stored.tier,\n symbols: runtime.map((r) => ({\n path: r.path,\n kind: r.kind,\n arity: r.arity,\n deprecated: r.deprecated,\n })),\n coverageNote:\n `${runtime.length} runtime symbol(s)` +\n (excluded ? `; ${excluded} excluded as type-only or re-exported from another package` : '') +\n (stored.tier === 'shipped_js_ast'\n ? '. Runtime existence only, signatures require tier C.'\n : ''),\n observedAt: stored.observedAt,\n };\n}\n\nexport interface DiffSurfaceInput {\n package: string;\n fromVersion: string;\n toVersion: string;\n}\n\nexport async function handleDiffSurface(db: Database, input: DiffSurfaceInput) {\n return cached(\n 'diff_surface',\n ckey([input.package, input.fromVersion, input.toVersion]),\n () => diffSurfaceUncached(db, input),\n { skipCache: (v) => v.verdict === 'unknown' },\n );\n}\n\nasync function diffSurfaceUncached(db: Database, input: DiffSurfaceInput) {\n let [a, b] = await Promise.all([\n loadStored(db, input.package, input.fromVersion),\n loadStored(db, input.package, input.toVersion),\n ]);\n\n // Both halves are raced under ONE shared budget (see firstTouch.ts): a diff\n // needs both, so extracting sequentially would let a slow `from` eat the\n // budget and leave `to` unstarted.\n if (!a || !b || a.rows.length === 0 || b.rows.length === 0) {\n const { firstTouchPair } = await import('../pipeline/firstTouch');\n if (await firstTouchPair(db, input.package, input.fromVersion, input.toVersion)) {\n [a, b] = await Promise.all([\n loadStored(db, input.package, input.fromVersion),\n loadStored(db, input.package, input.toVersion),\n ]);\n }\n }\n\n const missing: string[] = [];\n if (!a || a.rows.length === 0) missing.push(input.fromVersion);\n if (!b || b.rows.length === 0) missing.push(input.toVersion);\n if (missing.length) {\n for (const v of missing) await enqueueSurface(db, input.package, v).catch(() => {});\n return {\n package: input.package,\n fromVersion: input.fromVersion,\n toVersion: input.toVersion,\n verdict: 'unknown' as const,\n inconclusive: `no extracted surface for ${missing.join(', ')}, queued; retry shortly. NOT evidence that symbols were removed.`,\n removed: [],\n added: [],\n arityChanged: [],\n typeOnlyRemoved: [],\n // Present-but-empty like every other list above, so a miss and a hit have\n // the same shape and callers never have to branch on which one they got.\n deprecated: [],\n observedAt: null,\n };\n }\n\n const diff = diffSurfaces(\n rowsToSurface(input.package, input.fromVersion, a!.rows, a!.tier ?? 'shipped_js_ast'),\n rowsToSurface(input.package, input.toVersion, b!.rows, b!.tier ?? 'shipped_js_ast'),\n );\n\n return {\n package: input.package,\n fromVersion: input.fromVersion,\n toVersion: input.toVersion,\n verdict: (diff.inconclusive ? 'unknown' : 'verified_true') as Verdict,\n class: 'derived' as const,\n tier: diff.tier,\n ...(diff.inconclusive ? { inconclusive: diff.inconclusive } : {}),\n /** Breaks `node`. */\n removed: diff.removed.map((s) => ({ path: s.path, kind: s.kind, arity: s.arity })),\n added: diff.added.map((s) => ({ path: s.path, kind: s.kind })),\n arityChanged: diff.arityChanged,\n /** Breaks `tsc`, NOT `node` — returned separately on purpose (§8.1). */\n typeOnlyRemoved: diff.typeOnlyRemoved.map((s) => s.path),\n deprecated: diff.deprecated.map((s) => s.path),\n observedAt: b!.observedAt,\n };\n}\n","/**\n * `mcp_surface` and `mcp_drift` — the tool-contract half of §8.1.\n *\n * Same two questions `resolve_surface` and `diff_surface` answer for npm, asked\n * of a different unit: what does this thing expose, and what moved. Same\n * response discipline — every answer carries `verdict`, `class`, `tier`,\n * `observedAt` and a coverage note, because a bare answer with no provenance is\n * indistinguishable from the model's own guess.\n *\n * One rule is STRICTER here than on the npm path. `resolve_surface` relaxed\n * \"never extract inside a query\" because a tarball read is sub-second and can be\n * budgeted. A probe cannot: it installs a package and handshakes with someone\n * else's program over stdio, with a 45-second ceiling. So a miss here always\n * queues and answers UNKNOWN, and never blocks the caller.\n */\nimport { createHash } from 'node:crypto';\nimport { cached } from '../core/cache';\nimport type { Database } from '../db/client';\nimport { enqueueSurface } from '../db/surface';\nimport type { Verdict } from '../graph/types';\nimport {\n contractOf,\n diffMcpSurfaces,\n MCP_TIER,\n type AnnotationHint,\n type McpDrift,\n} from '../surface/mcp';\nimport {\n configRequestLine,\n fetchServerManifest,\n missingConfig,\n type RequiredConfig,\n} from '../surface/mcpRegistry';\nimport { loadStored, rowsToSurface, type StoredSurface } from './surfaceHandlers';\n\nexport interface McpSurfaceInput {\n server: string;\n version?: string | null;\n}\n\nexport interface McpToolView {\n name: string;\n /** Parameters a caller MUST pass. */\n required: string[];\n /** Every top-level parameter the tool accepts. */\n params: string[];\n annotations: Record<AnnotationHint, boolean>;\n /** The tool declares a structured result an agent can parse. */\n hasOutputSchema: boolean;\n deprecated: boolean;\n}\n\nexport interface McpSurfaceResponse {\n server: string;\n version: string | null;\n verdict: Verdict;\n class: 'declared' | 'executed' | 'derived' | null;\n tier: string | null;\n tools: McpToolView[];\n /**\n * Settings the server declares it needs. Present whether or not the probe\n * succeeded: an agent wiring up a working server still has to know it wants a\n * token before the first call fails in front of a user.\n */\n requires: RequiredConfig[];\n /**\n * A ready-made request an agent can put in front of its user when `requires`\n * contains something the environment does not have. Null when nothing is\n * missing. Names the settings and why; never contains a value.\n */\n configRequest: string | null;\n coverageNote: string;\n observedAt: string | null;\n}\n\n/** Short stable cache key. */\nfunction ckey(parts: unknown): string {\n return createHash('sha1').update(JSON.stringify(parts)).digest('hex').slice(0, 24);\n}\n\nconst MISS = (server: string, version: string | null): McpSurfaceResponse => ({\n server,\n version,\n verdict: 'unknown',\n class: null,\n tier: null,\n tools: [],\n requires: [],\n configRequest: null,\n coverageNote:\n 'not yet probed, queued; retry shortly. This is NOT evidence that the server exposes no tools.',\n observedAt: null,\n});\n\n/** Stored rows → the view an agent reads. */\nfunction toolViews(stored: StoredSurface): McpToolView[] {\n const surface = rowsToSurface('', null, stored.rows, MCP_TIER);\n return surface.symbols\n .map((s) => {\n const c = contractOf(s);\n const input = (c?.input ?? null) as Record<string, unknown> | null;\n const props = input && typeof input.properties === 'object' ? input.properties : {};\n const required = Array.isArray(input?.required) ? (input.required as string[]) : [];\n return {\n name: s.path,\n required: [...required].sort(),\n params: Object.keys(props ?? {}).sort(),\n annotations: c?.annotations ?? {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: true,\n },\n hasOutputSchema: c?.output != null,\n deprecated: s.deprecated,\n };\n })\n .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));\n}\n\nexport async function handleMcpSurface(\n db: Database,\n input: McpSurfaceInput,\n): Promise<McpSurfaceResponse> {\n return cached(\n 'mcp_surface',\n ckey([input.server, input.version ?? null]),\n () => mcpSurfaceUncached(db, input),\n { skipCache: (v) => v.verdict === 'unknown' },\n );\n}\n\nasync function mcpSurfaceUncached(\n db: Database,\n input: McpSurfaceInput,\n): Promise<McpSurfaceResponse> {\n const version = input.version ?? null;\n const [stored, manifest] = await Promise.all([\n loadStored(db, input.server, version, 0, 'mcp_server'),\n // Best-effort and never fatal: the registry being down must not change what\n // we say about a server.\n fetchServerManifest(input.server).catch(() => null),\n ]);\n\n const requires = manifest?.env ?? [];\n const missing = missingConfig(manifest);\n const configRequest = missing.length ? configRequestLine(input.server, missing) : null;\n const base = { server: input.server, version, requires, configRequest };\n\n // Declared settings we do not have. Reported BEFORE anything else and without\n // queueing: a probe would fail for a reason that says nothing about the\n // server, and the honest answer — plus the request an agent can act on — is\n // already available from the manifest.\n if (missing.length > 0 && (!stored || stored.rows.length === 0)) {\n return {\n ...base,\n verdict: 'unverifiable',\n class: null,\n tier: null,\n tools: [],\n coverageNote:\n 'server declares required settings this environment does not have, so it was not probed. UNVERIFIABLE, not a fault: nothing here is evidence about whether the server works. Supply the values in `requires` and ask again.',\n observedAt: null,\n };\n }\n\n if (manifest?.remoteOnly) {\n return {\n ...base,\n verdict: 'unverifiable',\n class: null,\n tier: null,\n tools: [],\n coverageNote: `server is published only as a remote ${manifest.transport ?? 'endpoint'}; there is no package to install, so this stdio probe does not apply to it`,\n observedAt: null,\n };\n }\n\n // Probed, and it would not run. A settled negative, so it is reported as one\n // rather than re-queueing a 45-second probe of a server already known broken.\n if (stored?.verdict === 'verified_false') {\n return {\n ...base,\n verdict: 'verified_false',\n class: stored.class,\n tier: stored.tier,\n tools: [],\n coverageNote:\n 'server was probed and did not complete the MCP handshake, so it exposes no callable tools in a clean install. This is a verdict about the server, not a gap in our coverage.',\n observedAt: stored.observedAt,\n };\n }\n\n if (!stored || stored.rows.length === 0) {\n // Probing is a sandbox spawn — queue it, never run it here.\n await enqueueSurface(db, input.server, version, 'mcp_server').catch(() => {});\n return { ...MISS(input.server, version), requires, configRequest };\n }\n\n if (stored.verdict === 'undeclared') {\n return {\n ...base,\n verdict: 'undeclared',\n class: stored.class,\n tier: stored.tier,\n tools: [],\n coverageNote:\n 'server started and completed the handshake but listed no tools; UNDECLARED, which is a measurement gap, not proof it has none',\n observedAt: stored.observedAt,\n };\n }\n\n const tools = toolViews(stored);\n const noContract = tools.filter((t) => t.params.length === 0 && t.required.length === 0).length;\n\n return {\n ...base,\n verdict: stored.verdict,\n class: stored.class,\n tier: stored.tier,\n tools,\n coverageNote:\n `${tools.length} tool(s) read from tools/list` +\n (noContract\n ? `; ${noContract} declare no input parameters (either genuinely nullary, or probed before schemas were captured)`\n : '') +\n (requires.length\n ? `; the server declares ${requires.length} setting(s) in \\`requires\\` that a caller must supply`\n : '') +\n '. Declared contract only: that a tool is listed is not evidence that calling it succeeds.',\n observedAt: stored.observedAt,\n };\n}\n\nexport interface McpDriftInput {\n server: string;\n fromVersion: string;\n toVersion: string;\n}\n\nexport interface McpDriftResponse extends Omit<McpDrift, 'tier'> {\n verdict: Verdict;\n class: 'derived' | null;\n tier: string;\n /** One line an agent can act on without reading the arrays. */\n summary: string;\n observedAt: string | null;\n}\n\nexport async function handleMcpDrift(\n db: Database,\n input: McpDriftInput,\n): Promise<McpDriftResponse> {\n return cached(\n 'mcp_drift',\n ckey([input.server, input.fromVersion, input.toVersion]),\n () => mcpDriftUncached(db, input),\n { skipCache: (v) => v.verdict === 'unknown' },\n );\n}\n\n/**\n * Human-readable verdict line.\n *\n * Ordered by what costs the reader most, and privilege widening is listed FIRST\n * even though it is not a breaking change. A tool that quietly stopped being\n * read-only is a worse thing to miss than one that gained a required parameter:\n * the second fails loudly on the next call, the first succeeds and writes.\n */\nexport function summarize(d: McpDrift): string {\n const alarming: string[] = [];\n const benign: string[] = [];\n\n const widened = d.annotationFlips.filter((f) => f.widensPrivilege);\n if (widened.length) {\n alarming.push(\n `${widened.length} privilege widening(s): ` +\n widened.map((f) => `${f.tool}.${f.hint} ${f.from}→${f.to}`).join(', '),\n );\n }\n if (d.removedTools.length) alarming.push(`${d.removedTools.length} tool(s) removed`);\n if (d.requiredAdded.length) {\n alarming.push(`${d.requiredAdded.length} tool(s) gained required params`);\n }\n if (d.paramsRemoved.length) alarming.push(`${d.paramsRemoved.length} tool(s) dropped params`);\n const narrowed = d.typeChanged.filter((c) => !c.widened);\n if (narrowed.length) alarming.push(`${narrowed.length} param type(s) narrowed`);\n if (d.silentDrift.length) {\n alarming.push(\n `${d.silentDrift.length} SILENT change(s) (contract moved, description unchanged): ${d.silentDrift.join(', ')}`,\n );\n }\n\n // Compatible movement still has to be NAMED. Reporting only the breaking half\n // made a release that reshaped five parameters and nine output schemas print\n // \"no contract change\" — true about breakage, and false about the contract,\n // which is the word in the sentence.\n if (d.addedTools.length) benign.push(`${d.addedTools.length} tool(s) added`);\n const relaxed = d.typeChanged.length - narrowed.length;\n if (relaxed) benign.push(`${relaxed} param type(s) relaxed`);\n if (d.requiredRelaxed.length) {\n benign.push(`${d.requiredRelaxed.length} tool(s) made params optional`);\n }\n if (d.paramsAdded.length) benign.push(`${d.paramsAdded.length} tool(s) gained optional params`);\n if (d.outputChanged.length) benign.push(`${d.outputChanged.length} output schema(s) changed`);\n const safeFlips = d.annotationFlips.length - widened.length;\n if (safeFlips) benign.push(`${safeFlips} annotation(s) narrowed`);\n if (d.deprecated.length) benign.push(`${d.deprecated.length} tool(s) newly deprecated`);\n if (d.prosePolished.length) benign.push(`${d.prosePolished.length} description(s) edited`);\n\n if (alarming.length) return alarming.join('; ');\n if (benign.length) return `compatible: ${benign.join(', ')}`;\n return 'no contract change';\n}\n\nasync function mcpDriftUncached(db: Database, input: McpDriftInput): Promise<McpDriftResponse> {\n const [a, b] = await Promise.all([\n loadStored(db, input.server, input.fromVersion, 0, 'mcp_server'),\n loadStored(db, input.server, input.toVersion, 0, 'mcp_server'),\n ]);\n\n const missing: string[] = [];\n if (!a || a.rows.length === 0) missing.push(input.fromVersion);\n if (!b || b.rows.length === 0) missing.push(input.toVersion);\n\n if (missing.length) {\n for (const v of missing) {\n await enqueueSurface(db, input.server, v, 'mcp_server').catch(() => {});\n }\n const blank = diffMcpSurfaces(\n {\n package: input.server,\n version: input.fromVersion,\n tier: MCP_TIER,\n entry: null,\n symbols: [],\n filesWalked: 0,\n externalReExports: [],\n },\n {\n package: input.server,\n version: input.toVersion,\n tier: MCP_TIER,\n entry: null,\n symbols: [],\n filesWalked: 0,\n externalReExports: [],\n },\n );\n return {\n ...blank,\n inconclusive: `no probed surface for ${missing.join(', ')}, queued; retry shortly. NOT evidence that tools were removed.`,\n verdict: 'unknown',\n class: null,\n summary: 'unknown: not yet probed',\n observedAt: null,\n };\n }\n\n const drift = diffMcpSurfaces(\n rowsToSurface(input.server, input.fromVersion, a!.rows, MCP_TIER),\n rowsToSurface(input.server, input.toVersion, b!.rows, MCP_TIER),\n );\n\n return {\n ...drift,\n verdict: (drift.inconclusive ? 'unknown' : 'verified_true') as Verdict,\n class: drift.inconclusive ? null : ('derived' as const),\n summary: drift.inconclusive ?? summarize(drift),\n observedAt: b!.observedAt,\n };\n}\n","/**\n * `mcp_server` oracle (spec §2, build sequence M2).\n *\n * RULE: install the server package into a clean sandbox, speak MCP over stdio —\n * `initialize` → `notifications/initialized` → `tools/list` (drained across every\n * page) — and record what it actually exposes. Failure looks like: install\n * failure, no response to initialize within the timeout, a malformed/JSON-RPC-\n * error reply, or a tools list that doesn't match the declared schema.\n *\n * We speak the wire protocol directly rather than importing the MCP SDK, because\n * the probe runs INSIDE the sandbox where only the server package is installed.\n * Pulling the SDK in would mean installing it alongside every server under test,\n * which changes the dependency tree we're trying to observe.\n *\n * Every tool the server lists becomes an `mcp_tool` child entity linked by a\n * `provides` edge — the \"skills\" node type is not a separate thing, it is this.\n *\n * The probe returns each tool WHOLE — `inputSchema`, `outputSchema` and\n * `annotations`, not just name and description. Those three fields are the\n * contract an agent builds calls against; dropping them leaves the graph knowing\n * that a tool exists but not what calling it requires, which is the half that\n * actually breaks.\n */\nimport type { Sandbox } from '../../sandbox/types';\nimport type { McpTool } from '../../surface/mcp';\nimport type { Environment, EntityRef, Oracle, OracleObservation, OracleResult } from '../types';\n\n/**\n * Protocol version we advertise.\n *\n * The CURRENT revision, not the oldest one that works. The spec requires a\n * server to answer with a version it does support rather than erroring, so\n * advertising forward costs nothing and is how newer response fields\n * (`ttlMs`, `cacheScope`, richer tool metadata) reach us as servers adopt them.\n * Verified against three published servers: all three negotiated down to\n * 2025-11-25 and returned identical tool lists.\n *\n * The version that actually gets negotiated is recorded in the observation\n * evidence, so a surface always says which dialect it was read in.\n */\nconst PROTOCOL_VERSION = '2026-07-28';\nconst HANDSHAKE_TIMEOUT_MS = 45_000;\nconst EVIDENCE_MAX = 800;\n\n/**\n * Pagination ceiling. `tools/list` is a paginated result and a server is free to\n * hand back cursors indefinitely; a runaway feed must terminate rather than hang\n * the sandbox. Hitting it sets `truncated`, which the caller MUST treat as a\n * measurement failure — a partially-drained list is indistinguishable from a\n * server that deleted the tools on the pages we never asked for.\n */\nconst MAX_PAGES = 50;\n\nexport interface ProbeOutput {\n ok: boolean;\n stage: 'spawn' | 'initialize' | 'tools/list' | 'done';\n error?: string;\n serverInfo?: { name?: string; version?: string };\n protocolVersion?: string;\n tools?: McpTool[];\n /** How many `tools/list` pages were drained. */\n pages?: number;\n /** A cursor was still outstanding at MAX_PAGES: the list is INCOMPLETE. */\n truncated?: boolean;\n}\n\n/**\n * The probe, as a self-contained script run inside the sandbox. Resolves the\n * server's bin, spawns it over stdio, performs the handshake, drains every page\n * of `tools/list`, prints one JSON line.\n *\n * Kept as a string (not a module) so it can be shipped to any sandbox driver\n * with no bundling step — the E2B driver has no filesystem sync for our source.\n */\nexport function probeScript(\n pkg: string,\n launchArgs: string[] = [],\n env: Record<string, string> = {},\n): string {\n return `\nconst { spawn } = require('node:child_process');\nconst { readFileSync } = require('node:fs');\nconst { join, basename } = require('node:path');\n\nconst PKG = ${JSON.stringify(pkg)};\nconst EXTRA_ARGS = ${JSON.stringify(launchArgs)};\nconst EXTRA_ENV = ${JSON.stringify(env)};\n\n/**\n * Resolve the server's entry point from its installed manifest.\n *\n * The package name is NOT the bin name often enough to matter —\n * @modelcontextprotocol/server-filesystem ships 'mcp-server-filesystem' — so\n * 'npx <pkg>' misses, and the miss looks exactly like a server that fails to\n * start. Read node_modules directly rather than require.resolve: an \"exports\"\n * map is allowed to hide ./package.json, and a fresh install always has the\n * flat path.\n */\nfunction launch() {\n let manifest;\n try {\n manifest = JSON.parse(readFileSync(join(process.cwd(), 'node_modules', PKG, 'package.json'), 'utf8'));\n } catch {\n return { command: 'npx', args: ['--no-install', PKG] };\n }\n let rel = null;\n if (typeof manifest.bin === 'string') rel = manifest.bin;\n else if (manifest.bin && typeof manifest.bin === 'object') {\n const keys = Object.keys(manifest.bin);\n rel = manifest.bin[basename(PKG)] || manifest.bin[keys[0]];\n }\n if (!rel) rel = manifest.main;\n if (!rel) return { command: 'npx', args: ['--no-install', PKG] };\n return { command: process.execPath, args: [join(process.cwd(), 'node_modules', PKG, rel)] };\n}\n\nconst { command, args } = launch();\n// Extra arguments go AFTER the resolved entry point. A large share of servers\n// ship a multi-command CLI where MCP is one verb, so launching the bin bare\n// prints a help banner and exits — which is indistinguishable from a server\n// that cannot start unless the verb is supplied.\n// Env is embedded in the script rather than plumbed through the sandbox\n// interface, so both drivers get it with no contract change.\nconst child = spawn(command, args.concat(EXTRA_ARGS), {\n stdio: ['pipe', 'pipe', 'pipe'],\n env: Object.assign({}, process.env, EXTRA_ENV),\n});\n\nlet buf = '', done = false, stderr = '';\n/**\n * Emit the single result line and stop.\n *\n * The write callback is load-bearing. process.exit() abandons whatever has not\n * yet drained from a pipe-backed stdout, and Node's pipe writes are async — so\n * exiting on the next line silently truncates the payload at the pipe buffer\n * (8 KiB on Linux and macOS). A 13-tool server fits and a 9-tool server with\n * large nested schemas does not, which turned \"this server documents its inputs\n * thoroughly\" into \"this server is unreachable\": the truncated JSON fails to\n * parse and the caller records verified_false about a server that answered\n * perfectly. Exit only once the bytes are actually gone.\n */\nconst out = (o) => {\n if (done) return;\n done = true;\n try { child.kill('SIGKILL'); } catch {}\n process.stdout.write(JSON.stringify(o) + '\\\\n', () => process.exit(0));\n};\nconst timer = setTimeout(() => out({ ok: false, stage: 'initialize', error: 'timeout awaiting handshake' }), ${HANDSHAKE_TIMEOUT_MS - 5000});\nconst send = (msg) => { try { child.stdin.write(JSON.stringify(msg) + '\\\\n'); } catch (e) { out({ ok: false, stage: 'spawn', error: 'stdin closed: ' + String(e && e.message || e) }); } };\n\nlet serverInfo, protocolVersion;\nlet tools = [], pages = 0, nextId = 2;\n\n// Pull every page. A single unpaginated read is the difference between \"this\n// server exposes 12 tools\" and \"this server exposes the first 12 of 40\" — and\n// the second, diffed against a full read, reports 28 tools as removed.\nconst listTools = (cursor) => send({\n jsonrpc: '2.0', id: nextId, method: 'tools/list',\n params: cursor ? { cursor: cursor } : {},\n});\n\nchild.on('error', (e) => out({ ok: false, stage: 'spawn', error: String(e && e.message || e) }));\nchild.stderr.on('data', (d) => { stderr += d.toString().slice(0, 2000); });\n\nchild.stdout.on('data', (d) => {\n buf += d.toString();\n let i;\n while ((i = buf.indexOf('\\\\n')) >= 0) {\n const line = buf.slice(0, i).trim();\n buf = buf.slice(i + 1);\n if (!line) continue;\n let msg;\n try { msg = JSON.parse(line); } catch { continue; } // servers log non-JSON to stdout\n if (msg.id === 1) {\n if (msg.error) return out({ ok: false, stage: 'initialize', error: JSON.stringify(msg.error) });\n serverInfo = msg.result && msg.result.serverInfo;\n protocolVersion = msg.result && msg.result.protocolVersion;\n send({ jsonrpc: '2.0', method: 'notifications/initialized' });\n listTools(null);\n } else if (msg.id === nextId) {\n if (msg.error) return out({ ok: false, stage: 'tools/list', error: JSON.stringify(msg.error), serverInfo, protocolVersion });\n const result = msg.result || {};\n pages++;\n for (const t of result.tools || []) {\n tools.push({\n name: t.name,\n title: t.title,\n description: t.description,\n inputSchema: t.inputSchema,\n outputSchema: t.outputSchema,\n annotations: t.annotations,\n });\n }\n if (result.nextCursor && pages < ${MAX_PAGES}) { nextId++; listTools(result.nextCursor); return; }\n clearTimeout(timer);\n return out({\n ok: true, stage: 'done', serverInfo, protocolVersion, tools, pages,\n truncated: Boolean(result.nextCursor),\n });\n }\n }\n});\n\nchild.on('exit', (code) => out({ ok: false, stage: 'spawn', error: 'exited ' + code + (stderr ? ': ' + stderr.slice(0, 400) : '') }));\n\nsend({\n jsonrpc: '2.0', id: 1, method: 'initialize',\n params: {\n protocolVersion: ${JSON.stringify(PROTOCOL_VERSION)},\n capabilities: {},\n clientInfo: { name: 'lurq-oracle', version: '1' },\n },\n});\n`.trim();\n}\n\n/** Parse the probe's single JSON line out of whatever else landed on stdout. */\nexport function parseProbeOutput(stdout: string): ProbeOutput | null {\n const lines = stdout.trim().split('\\n').reverse();\n for (const line of lines) {\n const t = line.trim();\n if (!t.startsWith('{')) continue;\n try {\n const parsed = JSON.parse(t) as ProbeOutput;\n if (typeof parsed.ok === 'boolean') return parsed;\n } catch {\n /* keep scanning */\n }\n }\n return null;\n}\n\n/**\n * Install the server and probe it. Shared by the oracle (which turns the result\n * into observations) and the surface pipeline (which turns it into symbols), so\n * there is exactly one implementation of \"what does this server expose\".\n *\n * Throws ONLY on sandbox failure. A server that refuses to start resolves with\n * `ok: false` — that is evidence about the server, and the caller records it.\n */\n/**\n * Launch verbs to try when a bare start does not produce a handshake.\n *\n * Measured, not guessed: across 18 servers whose first probe returned a usage\n * banner, `mcp` recovered 7 and `serve` 1. They are tried in that order and\n * only after the bare launch has already failed, so a healthy server still\n * costs exactly one attempt.\n */\nexport const LAUNCH_VERBS = ['mcp', 'serve', '--stdio'];\n\nexport interface ProbeOptions {\n /** Declared launch arguments, e.g. from the server's registry manifest. */\n args?: string[];\n /**\n * Placeholder values for required environment variables.\n *\n * Servers gate on a variable being PRESENT at boot and only validate it on a\n * real tool call, which reading a contract never makes — so a placeholder\n * unlocks `tools/list` without a credential and without a network request.\n * Measured at 9 of 14 config-gated servers recovered.\n *\n * The result of such a probe is DECLARED evidence, never executed: a server\n * that boots on a fake key has not been shown to work.\n */\n env?: Record<string, string>;\n}\n\nasync function attempt(\n sandbox: Sandbox,\n pkg: string,\n version: string | null,\n args: string[],\n env: Record<string, string>,\n): Promise<{ probe: ProbeOutput | null; stderr: string }> {\n const res = await sandbox.exec(`node -e ${shellQuote(probeScript(pkg, args, env))}`, {\n install: [{ name: pkg, version }],\n timeoutMs: HANDSHAKE_TIMEOUT_MS,\n });\n return { probe: parseProbeOutput(res.stdout), stderr: res.stderr };\n}\n\nexport async function probeMcpServer(\n sandbox: Sandbox,\n pkg: string,\n version: string | null,\n opts: ProbeOptions = {},\n): Promise<{ probe: ProbeOutput | null; stderr: string; launchedWith: string[] }> {\n // Declared args first when the manifest supplies them, then a bare launch,\n // then the measured verbs. Ordered so the common case — a server that simply\n // starts — still costs one attempt.\n const ladder: string[][] = opts.args?.length ? [opts.args] : [[]];\n for (const verb of LAUNCH_VERBS) ladder.push([verb]);\n\n let last: { probe: ProbeOutput | null; stderr: string } = { probe: null, stderr: '' };\n for (const args of ladder) {\n try {\n const res = await attempt(sandbox, pkg, version, args, opts.env ?? {});\n if (res.probe?.ok) return { ...res, launchedWith: args };\n last = res;\n } catch (err) {\n // The sandbox itself failed. This is NOT evidence about the server —\n // recording verified_false here would be a false negative, which the spec\n // rates as costlier than a hundred unknowns. Stop the ladder: retrying\n // through a broken sandbox just multiplies the outage.\n throw new Error(`sandbox failure: ${String(err)}`);\n }\n }\n return { ...last, launchedWith: [] };\n}\n\nexport const mcpServerOracle: Oracle = {\n id: 'mcp_server.handshake',\n version: '2', // v2: full tool schemas + paginated tools/list\n kind: 'mcp_server',\n ttlHours: 24 * 14, // spec §2: on publish, else 14 days\n rule: 'Install the package, speak MCP over stdio (initialize → tools/list, all pages); failure is install error, handshake timeout, JSON-RPC error, or malformed tool list.',\n\n async run(target: EntityRef, _env: Environment, sandbox: Sandbox): Promise<OracleResult> {\n const started = Date.now();\n const { probe, stderr } = await probeMcpServer(sandbox, target.name, target.version ?? null);\n\n const observations: OracleObservation[] = [];\n const discovered: EntityRef[] = [];\n\n if (!probe) {\n observations.push({\n relation: 'initializes',\n verdict: 'verified_false',\n evidence: truncate(`no probe output. stderr: ${stderr}`),\n });\n return { observations, costMillis: Date.now() - started };\n }\n\n if (!probe.ok) {\n observations.push({\n relation: 'initializes',\n verdict: 'verified_false',\n evidence: truncate(`stage=${probe.stage} ${probe.error ?? ''}`),\n });\n return { observations, costMillis: Date.now() - started };\n }\n\n // A truncated list is a measurement failure, not a finding. Recording it as\n // a successful read would let a later full read diff against it and report\n // every tool on the undrained pages as removed.\n if (probe.truncated) {\n observations.push({\n relation: 'initializes',\n verdict: 'unverifiable',\n evidence: truncate(\n `tools/list still paginating after ${MAX_PAGES} pages (${probe.tools?.length ?? 0} tools read); list is incomplete`,\n ),\n });\n return { observations, costMillis: Date.now() - started };\n }\n\n observations.push({\n relation: 'initializes',\n verdict: 'verified_true',\n evidence: truncate(\n `serverInfo=${probe.serverInfo?.name ?? '?'}@${probe.serverInfo?.version ?? '?'} protocol=${probe.protocolVersion ?? '?'} tools=${probe.tools?.length ?? 0} pages=${probe.pages ?? 1}`,\n ),\n });\n\n for (const tool of probe.tools ?? []) {\n const ref: EntityRef = {\n kind: 'mcp_tool',\n namespace: target.namespace,\n name: `${target.name}#${tool.name}`,\n version: target.version ?? null,\n };\n discovered.push(ref);\n observations.push({\n object: ref,\n relation: 'provides',\n verdict: 'verified_true',\n evidence: truncate(tool.description ?? tool.name),\n });\n }\n\n return { observations, discovered, costMillis: Date.now() - started };\n },\n};\n\nfunction truncate(s: string): string {\n return s.replace(/\\s+/g, ' ').trim().slice(0, EVIDENCE_MAX);\n}\n\n/** POSIX single-quote — the script contains quotes, newlines, and backslashes. */\nexport function shellQuote(s: string): string {\n return `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n","/**\n * MCP tool-surface drain — the `mcp_server` half of the surface queue.\n *\n * Structurally the same as `./surface.ts` (drain → extract → store → backfill\n * the predecessor so the pair is diffable) with one difference that drives every\n * design choice here: extraction is not a download, it is a sandbox spawn plus\n * an stdio handshake with someone else's program. That costs seconds, not\n * milliseconds, so this drain runs at a much smaller per-cycle budget and leans\n * far harder on the content-addressed cache.\n *\n * `surfaceHash` stands in for the tarball digest. It is a strictly better cache\n * key than npm's, because a published tarball is immutable while a tool list is\n * not: the same `name@version` can hand back a different contract tomorrow, and\n * a changed hash on an unchanged version IS the drift signal rather than merely\n * a cache miss.\n *\n * Failure handling follows §4.2: infrastructure problems bump the attempt count\n * and leave the spec queued, they never record a verdict about the server.\n */\nimport { formatError } from '../core/errors';\nimport { logger } from '../core/logger';\nimport type { Database } from '../db/client';\nimport { getPackageVersions } from '../db/packages';\nimport {\n bumpSurfaceAttempt,\n dropSurfaceQueue,\n enqueuePreviousSurface,\n enqueueSurface,\n getPendingSurfaces,\n isExtractionCached,\n mcpSurfaceRef,\n storeSurface,\n} from '../db/surface';\nimport { recordObservation, upsertClaim, upsertEntity } from '../db/graph';\nimport { probeMcpServer, mcpServerOracle } from '../graph/oracles/mcpServer';\nimport { getSandbox } from '../sandbox/index';\nimport type { Sandbox } from '../sandbox/types';\nimport { MCP_TIER, mcpSurface, surfaceHash, type McpTool } from '../surface/mcp';\nimport {\n configRequestLine,\n fetchServerManifest,\n missingConfig,\n type RequiredConfig,\n} from '../surface/mcpRegistry';\n\n/** See `./surface.ts` — the timeline is newest-first and releases arrive in bursts. */\nconst VERSION_LOOKBACK = 50;\n\n/**\n * Bumped whenever probing can produce a different answer for the same server.\n * '1' is the first version that captures full tool schemas and drains every\n * `tools/list` page; anything stored before that is a name-only list and is\n * treated as stale rather than reused.\n */\nconst EXTRACTOR_VERSION = '2'; // v2: launch-verb ladder + placeholder config\n\n/**\n * Stand-in for a required credential.\n *\n * Deliberately self-describing: if it ever escapes into a log, an error message\n * or someone's terminal, it says exactly what it is and that it authenticates\n * nothing.\n */\nconst PLACEHOLDER_VALUE = 'lurq-placeholder-not-a-real-credential';\nconst MAX_ATTEMPTS = 3;\n\n/**\n * Far below the npm drain's budget, and deliberately.\n *\n * Each item here installs a package and runs a foreign program to handshake\n * timeout (45s worst case). Ten per cycle would let one slow server stall the\n * whole worker loop.\n */\nexport const MCP_PER_CYCLE = 3;\n\nexport type McpOutcome =\n | 'stored'\n | 'cached'\n /** Server listed no tools — a measurement gap, recorded as UNDECLARED. */\n | 'undeclared'\n /** Server would not start or refused the handshake. Evidence about the server. */\n | 'unreachable'\n /**\n * Server declares configuration it did not get. NOT a defect, and never\n * `verified_false` — we could not check, which is a different claim.\n */\n | 'needs_config'\n /** Published only as a remote endpoint; there is no package to install. */\n | 'not_stdio'\n /** The list was still paginating at the ceiling; NOT a surface. */\n | 'truncated';\n\nexport interface McpExtractResult {\n outcome: McpOutcome;\n tools: McpTool[];\n /** Why the probe produced no usable surface. Null on success. */\n reason: string | null;\n /** Declared settings the server needs and did not have. */\n missing?: RequiredConfig[];\n}\n\n/**\n * A handshake failure that reads like a missing setting rather than a defect.\n *\n * Only consulted when the registry has nothing to say, and deliberately narrow:\n * it must see a SHOUTY_ENV_NAME next to a word about being required. A server\n * whose real crash merely mentions an environment variable should not be\n * excused as unconfigured, because excusing a genuine failure hides it.\n *\n * ponytail: heuristic on someone else's error text. The registry manifest is\n * the real answer; delete this when enough servers publish one.\n */\nconst ENV_COMPLAINT =\n /\\b([A-Z][A-Z0-9]{2,}(?:_[A-Z0-9]+)+)\\b[^.\\n]{0,60}?\\b(required|must be set|not set|missing|is not defined)\\b|\\b(required|must be set|missing)\\b[^.\\n]{0,60}?\\b([A-Z][A-Z0-9]{2,}(?:_[A-Z0-9]+)+)\\b/;\n\nexport function sniffMissingEnv(text: string): string | null {\n const m = ENV_COMPLAINT.exec(text);\n return m ? (m[1] ?? m[4] ?? null) : null;\n}\n\n/**\n * Probe one MCP server and persist its tool surface.\n *\n * Every non-success path returns WITHOUT storing a surface. Writing an empty\n * one for a server that failed to boot would make the next successful probe\n * report every tool as newly added — and would let a reader mistake \"we could\n * not start it\" for \"it exposes no tools\". Those are not the same claim, and\n * neither is \"it wanted an API key we did not have\".\n */\nexport async function extractAndStoreMcp(\n db: Database,\n server: string,\n version: string | null,\n opts: { sandbox?: Sandbox; env?: NodeJS.ProcessEnv } = {},\n): Promise<McpExtractResult> {\n const ref = mcpSurfaceRef(server, version);\n\n // Ask what the server says it needs before spending a sandbox on it. A probe\n // that was always going to fail costs ~45s and yields a misleading answer;\n // the manifest costs one cached HTTP call and yields a request an agent can\n // put in front of its user.\n const manifest = await fetchServerManifest(server);\n if (manifest?.remoteOnly) {\n return {\n outcome: 'not_stdio',\n tools: [],\n reason: `published only as a remote ${manifest.transport ?? 'endpoint'}; there is no package to install and probe`,\n };\n }\n const missing = missingConfig(manifest, opts.env);\n\n // A missing credential used to end the probe. It no longer does.\n //\n // Servers gate on the variable being PRESENT at boot and only validate it on\n // a real tool call — which reading a contract never makes. So a placeholder\n // gets us `tools/list` with no credential, no network request, and no\n // pretence: measured at 9 of 14 config-gated servers recovered, including one\n // that yielded 120 tools.\n //\n // What this buys is the contract. What it does NOT buy is a working server,\n // so the result is marked `declared` rather than `executed` and the missing\n // settings are still reported for the user to supply.\n const placeholders: Record<string, string> = {};\n for (const m of missing) placeholders[m.name] = PLACEHOLDER_VALUE;\n\n const sandbox = opts.sandbox ?? (await getSandbox());\n const { probe, stderr } = await probeMcpServer(sandbox, server, version, {\n args: manifest?.args ?? [],\n env: placeholders,\n });\n\n // Still no handshake after every lever: report what the server needs rather\n // than calling it broken.\n if (missing.length > 0 && !probe?.ok) {\n return {\n outcome: 'needs_config',\n tools: [],\n reason: configRequestLine(server, missing),\n missing,\n };\n }\n\n if (!probe || !probe.ok) {\n const reason = probe\n ? `stage=${probe.stage} ${probe.error ?? ''}`.slice(0, 300)\n : `no probe output: ${stderr.slice(0, 200)}`;\n\n // The registry knew nothing, but the server's own error may still be a\n // request for configuration rather than a fault.\n const sniffed = sniffMissingEnv(`${probe?.error ?? ''} ${stderr}`);\n if (sniffed) {\n const inferred: RequiredConfig[] = [\n { name: sniffed, description: null, required: true, secret: true, format: null },\n ];\n return {\n outcome: 'needs_config',\n tools: [],\n reason: `server did not start and its output names ${sniffed} as required (inferred from the server's own error, not a published manifest)`,\n missing: inferred,\n };\n }\n\n await recordUnreachable(db, ref, reason);\n return { outcome: 'unreachable', tools: [], reason };\n }\n if (probe.truncated) {\n // OUR ceiling, not the server's fault — no verdict is recorded, so a later\n // probe with more headroom starts from a clean slate rather than from a\n // stored claim that this server does not work.\n return {\n outcome: 'truncated',\n tools: probe.tools ?? [],\n reason: 'tools/list still paginating at the page ceiling; list incomplete',\n };\n }\n\n const tools = probe.tools ?? [];\n const hash = surfaceHash(tools);\n\n if (await isExtractionCached(db, ref, hash, EXTRACTOR_VERSION, MCP_TIER)) {\n return { outcome: 'cached', tools, reason: null };\n }\n\n const res = await storeSurface(db, mcpSurface(server, version, tools), {\n artifactHash: hash,\n extractorVersion: EXTRACTOR_VERSION,\n ref,\n oracleId: mcpServerOracle.id,\n });\n\n // An MCP server IS an npm package, so it belongs in the npm index like any\n // other. This one line connects the two halves: once tracked it gains a\n // latest version, advisories, deprecation and a release timeline, `audit` can\n // finally say whether a pinned server is behind, and the publish feed starts\n // re-probing it on release without anyone asking. Until now the MCP path was\n // a read-only island — it could describe what a server exposes today and say\n // nothing about whether that was current.\n await queueNpmIngest(db, server);\n\n return {\n outcome: res.verdict === 'undeclared' ? 'undeclared' : 'stored',\n tools,\n reason: res.verdict === 'undeclared' ? 'server listed no tools' : null,\n };\n}\n\n/**\n * Record that a server refused to start, as a claim about the server.\n *\n * Without this the read path had no way to tell \"not probed yet\" from \"probed,\n * and it would not run\": both looked like an empty surface, so every query\n * answered UNKNOWN and re-queued a 45-second probe of a server already known to\n * be broken, forever. A settled negative is evidence and belongs in the graph.\n *\n * NOT written for a sandbox failure — that throws before reaching here — and\n * not for a truncated list, which is our measurement gap rather than the\n * server's defect.\n */\nasync function recordUnreachable(\n db: Database,\n ref: ReturnType<typeof mcpSurfaceRef>,\n reason: string,\n) {\n const entity = await upsertEntity(db, ref, 0);\n const claim = await upsertClaim(db, {\n subjectId: entity.id,\n relation: 'initializes',\n environmentId: null,\n tenantId: 0,\n });\n await recordObservation(db, {\n claimId: claim.id,\n verdict: 'verified_false',\n class: 'executed',\n tier: MCP_TIER,\n evidence: reason,\n oracleId: mcpServerOracle.id,\n oracleVer: EXTRACTOR_VERSION,\n });\n}\n\n/**\n * Put an MCP server into the npm index.\n *\n * Awaited rather than fired and forgotten, for the reason `audit` learned the\n * hard way: `void import(...)` lands the enqueue a microtask later, so a caller\n * that queues and then drains finds an empty queue. Only the module load is\n * awaited — `enqueueIngest` itself returns without touching the network.\n */\nasync function queueNpmIngest(db: Database, name: string): Promise<void> {\n try {\n const { enqueueIngest } = await import('./ingestQueue');\n enqueueIngest(db, name, null);\n } catch (err) {\n // The surface was stored; indexing it only improves the next read.\n logger.debug(`mcp: npm ingest enqueue failed for ${name}: ${formatError(err)}`);\n }\n}\n\nexport interface McpDrainSummary {\n drained: number;\n stored: number;\n cached: number;\n undeclared: number;\n unreachable: number;\n needs_config: number;\n not_stdio: number;\n truncated: number;\n failed: number;\n /** Predecessor versions queued so this one becomes diffable. */\n backfilled: number;\n}\n\nexport async function drainMcpQueue(\n db: Database,\n opts: { limit?: number; sandbox?: Sandbox } = {},\n): Promise<McpDrainSummary> {\n const pending = await getPendingSurfaces(db, opts.limit ?? MCP_PER_CYCLE, 'mcp_server');\n const s: McpDrainSummary = {\n drained: 0,\n stored: 0,\n cached: 0,\n undeclared: 0,\n unreachable: 0,\n needs_config: 0,\n not_stdio: 0,\n truncated: 0,\n failed: 0,\n backfilled: 0,\n };\n\n for (const item of pending) {\n s.drained++;\n try {\n const { outcome, reason } = await extractAndStoreMcp(db, item.packageName, item.version, {\n sandbox: opts.sandbox,\n });\n s[outcome]++;\n\n if (reason) {\n logger.info(\n { server: item.packageName, version: item.version, outcome, reason },\n 'mcp: no surface stored',\n );\n }\n\n // Pull the predecessor in behind a successful read, for the same reason\n // the npm drain does: one surface says what a server exposes, only a pair\n // says what a release took away.\n if (item.version && (outcome === 'stored' || outcome === 'cached')) {\n await enqueuePreviousSurface(\n db,\n item.packageName,\n item.version,\n await getPackageVersions(db, item.packageName, VERSION_LOOKBACK),\n 'mcp_server',\n ).then(\n (queued) => {\n if (queued) s.backfilled++;\n },\n (err) =>\n logger.warn(\n { server: item.packageName, err: formatError(err) },\n 'mcp: predecessor backfill could not be queued',\n ),\n );\n }\n\n // A server that cannot start is a settled answer about that version, not\n // a transient one — drop it rather than retrying the same failure every\n // cycle. A truncated list, by contrast, means our own ceiling was too low.\n await dropSurfaceQueue(db, item.id);\n } catch (err) {\n s.failed++;\n // The sandbox itself failed. Never a verdict about the server (§4.2).\n if (item.attempts + 1 >= MAX_ATTEMPTS) await dropSurfaceQueue(db, item.id);\n else await bumpSurfaceAttempt(db, item.id);\n logger.warn(\n { spec: item.specKey, attempts: item.attempts + 1, err: formatError(err) },\n 'mcp surface probe failed',\n );\n }\n }\n return s;\n}\n\n/** Queue an MCP server for probing. Thin wrapper so callers never pass the kind. */\nexport async function enqueueMcpServer(\n db: Database,\n server: string,\n version: string | null,\n): Promise<void> {\n await enqueueSurface(db, server, version, 'mcp_server');\n}\n","/**\n * Local discovery: what does this project actually depend on?\n *\n * Runs entirely on the user's machine and reads only manifests and agent\n * configs. No source file is opened and nothing but names and versions ever\n * leaves — the same rule `check-upgrade` holds, and the reason an audit can be\n * run against the hosted index without anyone having to think about it.\n *\n * Two inventories, because a project's dependencies live in two unrelated\n * places. npm packages are declared in `package.json` and resolved in a\n * lockfile. MCP servers are declared in agent configs that are not in the\n * repository at all — `~/.claude.json`, `~/.cursor/mcp.json`, a project\n * `.mcp.json` — which is why a repo scan alone can never see them.\n */\nimport { existsSync, readFileSync, readdirSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { isAbsolute, join, relative, resolve } from 'node:path';\nimport { parse as parseYaml } from 'yaml';\nimport type {\n Inventory,\n InventoryMcpServer,\n InventoryPackage,\n ItemSource,\n McpKind,\n TransitiveInstall,\n} from './types';\n\n/** Dependency sections worth auditing. `peerDependencies` is the host's problem. */\nconst DEP_SECTIONS = ['dependencies', 'devDependencies', 'optionalDependencies'] as const;\n\n/**\n * Ceiling on discovered items.\n *\n * A monorepo can declare thousands of dependencies, and an audit that takes a\n * minute is an audit nobody runs twice. Anything past the cap is reported as\n * `truncated` rather than dropped — see the coverage rule in `./types`.\n */\nexport const MAX_ITEMS = 600;\n\n/**\n * Separate, much larger ceiling for the resolved tree.\n *\n * Transitives are never rendered unless something is wrong with them, so their\n * cost is one OSV batch per hundred rather than a line of output each — a\n * budget that buys far more safety per unit than the display cap does.\n */\nexport const MAX_TRANSITIVES = 4000;\n\nfunction readJson(path: string): unknown | null {\n try {\n return JSON.parse(readFileSync(path, 'utf8'));\n } catch {\n return null;\n }\n}\n\n/**\n * Split an npm spec into name and version.\n *\n * The leading `@` of a scope is not a separator, so the split is on the last\n * `@` that is not at index 0. `pkg@latest` and `pkg@next` carry a dist-tag\n * rather than a version, and a tag is not something that can be diffed — they\n * come back as unpinned, which is the truth about them.\n */\nexport function splitSpec(spec: string): { name: string; version: string | null } {\n const at = spec.lastIndexOf('@');\n if (at <= 0) return { name: spec, version: null };\n const name = spec.slice(0, at);\n const version = spec.slice(at + 1);\n if (!/^\\d/.test(version)) return { name, version: null }; // dist-tag, not a version\n return { name, version };\n}\n\n/** Package-manager runners that fetch from npm, and the flags to step over. */\nconst NPM_RUNNERS = new Set(['npx', 'bunx', 'pnpx']);\nconst RUNNER_FLAGS = new Set(['-y', '--yes', '--no-install', '--silent', '-q', '--quiet', '-p']);\n/** Runners for registries lurq does not index. */\nconst OTHER_RUNNERS = new Set(['uvx', 'pipx', 'uv', 'pip', 'python', 'python3', 'go', 'cargo']);\n\ninterface RawServer {\n command?: unknown;\n args?: unknown;\n url?: unknown;\n type?: unknown;\n}\n\n/**\n * Classify one MCP server entry.\n *\n * The important output is honesty about what lurq can and cannot read. A remote\n * endpoint has no package to install; a `uvx` server is PyPI; a bare path is\n * someone's local build. Reporting any of those as \"not in the index\" would be\n * misleading — they are out of scope for a different reason in each case, and\n * the reason is what a reader needs.\n */\nexport function classifyServer(alias: string, raw: RawServer): Omit<InventoryMcpServer, 'sources'> {\n const base = { alias, packageName: null, version: null, endpoint: null };\n\n if (typeof raw.url === 'string' && raw.url) {\n let endpoint = raw.url;\n try {\n endpoint = new URL(raw.url).host;\n } catch {\n /* keep the raw string; a malformed url is still worth showing */\n }\n return { ...base, kind: 'remote' as McpKind, endpoint };\n }\n\n const command = typeof raw.command === 'string' ? raw.command : '';\n const args = Array.isArray(raw.args)\n ? raw.args.filter((a): a is string => typeof a === 'string')\n : [];\n const bin = command.split(/[\\\\/]/).pop() ?? '';\n\n if (OTHER_RUNNERS.has(bin)) return { ...base, kind: 'other-registry' as McpKind };\n\n if (NPM_RUNNERS.has(bin) || (bin === 'pnpm' && args[0] === 'dlx')) {\n // First argument that is neither a flag nor a flag's value is the spec.\n const rest = bin === 'pnpm' ? args.slice(1) : args;\n const spec = rest.find((a) => !a.startsWith('-') && !RUNNER_FLAGS.has(a));\n if (!spec) return { ...base, kind: 'npm-stdio' as McpKind };\n const { name, version } = splitSpec(spec);\n return { ...base, kind: 'npm-stdio' as McpKind, packageName: name, version };\n }\n\n // `node ./dist/server.js` and friends: a real server, but not one that can be\n // resolved from a registry, so no version and nothing to diff against.\n return { ...base, kind: 'local' as McpKind };\n}\n\n/** Every MCP server declared in one config object, whatever the dialect. */\nexport function serversFromConfig(config: unknown, file: string): InventoryMcpServer[] {\n if (!config || typeof config !== 'object') return [];\n const out: InventoryMcpServer[] = [];\n // `mcpServers` is the Claude/Cursor/Windsurf spelling, `servers` is VS Code's.\n for (const section of ['mcpServers', 'servers']) {\n const block = (config as Record<string, unknown>)[section];\n if (!block || typeof block !== 'object') continue;\n for (const [alias, raw] of Object.entries(block as Record<string, unknown>)) {\n if (!raw || typeof raw !== 'object') continue;\n out.push({\n ...classifyServer(alias, raw as RawServer),\n sources: [{ file, section }],\n });\n }\n }\n return out;\n}\n\n/** Config files that may declare MCP servers, project-local first. */\nexport function mcpConfigPaths(root: string, home = homedir()): string[] {\n return [\n join(root, '.mcp.json'),\n join(root, '.cursor', 'mcp.json'),\n join(root, '.vscode', 'mcp.json'),\n join(root, '.windsurf', 'mcp.json'),\n join(home, '.claude.json'),\n join(home, '.cursor', 'mcp.json'),\n join(home, '.codeium', 'windsurf', 'mcp_config.json'),\n join(home, '.gemini', 'settings.json'),\n ];\n}\n\n/**\n * Resolved version for an installed package.\n *\n * `node_modules` is read before the lockfile because it is the ground truth for\n * what will actually load, and because it is one cheap stat per package against\n * parsing a multi-megabyte lockfile. The lockfile is the fallback for a project\n * that has not installed yet.\n */\nfunction installedFrom(root: string, name: string, lock: Map<string, string>): string | null {\n const pkgJson = join(root, 'node_modules', ...name.split('/'), 'package.json');\n if (existsSync(pkgJson)) {\n const m = readJson(pkgJson) as { version?: unknown } | null;\n if (m && typeof m.version === 'string') return m.version;\n }\n return lock.get(name) ?? null;\n}\n\ninterface LockEntry {\n version?: unknown;\n dependencies?: Record<string, unknown>;\n optionalDependencies?: Record<string, unknown>;\n}\n\n/**\n * The whole resolved tree: every exact install, plus who requires whom.\n *\n * Both halves come from one parse because both are needed together. The\n * installs answer \"is anything in my tree vulnerable\" — the question a\n * `package.json` cannot answer and the way most projects are actually exposed.\n * The edges answer \"and what do I upgrade to fix it\", which is the only half a\n * user can act on: nobody installed the vulnerable transitive on purpose.\n */\nexport function readLockTree(root: string): {\n installs: Map<string, string>;\n edges: Map<string, Set<string>>;\n present: boolean;\n} {\n const installs = new Map<string, string>();\n const edges = new Map<string, Set<string>>();\n const lock = readJson(join(root, 'package-lock.json')) as {\n packages?: Record<string, LockEntry>;\n dependencies?: Record<string, LockEntry>;\n } | null;\n if (!lock) return { installs, edges, present: false };\n\n const addEdge = (parent: string, child: string) => {\n if (!parent || !child || parent === child) return;\n const set = edges.get(parent);\n if (set) set.add(child);\n else edges.set(parent, new Set([child]));\n };\n\n for (const [path, entry] of Object.entries(lock.packages ?? {})) {\n // Keys look like `node_modules/foo`, `node_modules/a/node_modules/b`, or a\n // workspace path like `apps/web/node_modules/c`; the segment after the last\n // `node_modules/` is the package name.\n const idx = path.lastIndexOf('node_modules/');\n if (idx < 0) continue;\n const name = path.slice(idx + 'node_modules/'.length);\n if (!name) continue;\n // First wins: a hoisted root install is the one most things resolve to, and\n // it is listed before its nested duplicates.\n if (typeof entry?.version === 'string' && !installs.has(name))\n installs.set(name, entry.version);\n for (const dep of Object.keys(entry?.dependencies ?? {})) addEdge(name, dep);\n for (const dep of Object.keys(entry?.optionalDependencies ?? {})) addEdge(name, dep);\n }\n\n // Lockfile v1/v2 `dependencies` block, for older projects.\n for (const [name, entry] of Object.entries(lock.dependencies ?? {})) {\n if (typeof entry?.version === 'string' && !installs.has(name))\n installs.set(name, entry.version);\n for (const dep of Object.keys(entry?.dependencies ?? {})) addEdge(name, dep);\n }\n\n return { installs, edges, present: true };\n}\n\n/** `name -> version` from an npm v2/v3 lockfile. Empty map when there is none. */\nexport function readLockfile(root: string): Map<string, string> {\n return readLockTree(root).installs;\n}\n\n/**\n * Which direct dependencies lead to each package in the tree.\n *\n * One breadth-first pass per direct dependency rather than a walk per flagged\n * package: a tree with thousands of nodes and a handful of vulnerable ones would\n * otherwise re-traverse the same subgraphs repeatedly. `seen` is per-root so a\n * package reachable from three directs is credited to all three.\n */\nexport function attributeTree(\n directs: string[],\n edges: Map<string, Set<string>>,\n maxDepth = 12,\n): Map<string, string[]> {\n const via = new Map<string, string[]>();\n for (const root of directs) {\n const seen = new Set<string>([root]);\n let frontier = [root];\n for (let depth = 0; depth < maxDepth && frontier.length; depth++) {\n const next: string[] = [];\n for (const node of frontier) {\n for (const child of edges.get(node) ?? []) {\n if (seen.has(child)) continue;\n seen.add(child);\n next.push(child);\n const list = via.get(child);\n if (list) {\n if (!list.includes(root)) list.push(root);\n } else via.set(child, [root]);\n }\n }\n frontier = next;\n }\n }\n return via;\n}\n\n/** How deep a `**` pattern is walked. Deep enough for real monorepos, bounded\n * so a pathological tree cannot turn discovery into a filesystem crawl. */\nconst MAX_WORKSPACE_DEPTH = 5;\n\n/** Directories never worth descending into when expanding a workspace glob. */\nconst SKIP_DIRS = new Set(['node_modules', 'dist', 'build', 'coverage', '.git', '.next']);\n\n/**\n * Workspace patterns, from whichever manager this project uses.\n *\n * pnpm keeps them in `pnpm-workspace.yaml` rather than `package.json`, so a\n * pnpm monorepo declared zero workspaces to the npm-shaped reader and every\n * package under it went unaudited — silently, because a workspace that matches\n * nothing looks exactly like a project that has none.\n */\nexport function workspacePatterns(root: string): string[] {\n const m = readJson(join(root, 'package.json')) as { workspaces?: unknown } | null;\n const fromNpm = Array.isArray(m?.workspaces)\n ? m.workspaces\n : Array.isArray((m?.workspaces as { packages?: unknown } | undefined)?.packages)\n ? ((m!.workspaces as { packages: unknown[] }).packages as unknown[])\n : [];\n\n const pnpmPath = join(root, 'pnpm-workspace.yaml');\n let fromPnpm: unknown[] = [];\n if (existsSync(pnpmPath)) {\n try {\n // `yaml` is already a direct dependency; hand-rolling a reader for a field\n // that may be a flow sequence, a block sequence or quoted is not worth it.\n const doc = parseYaml(readFileSync(pnpmPath, 'utf8')) as { packages?: unknown } | null;\n if (Array.isArray(doc?.packages)) fromPnpm = doc.packages;\n } catch {\n /* a malformed workspace file is not fatal; nothing under it is audited */\n }\n }\n\n return [...fromNpm, ...fromPnpm].filter((p): p is string => typeof p === 'string');\n}\n\n/** Directories one level under `dir`, skipping build output and dot-dirs. */\nfunction childDirs(dir: string): string[] {\n try {\n return readdirSync(dir, { withFileTypes: true })\n .filter((e) => e.isDirectory() && !SKIP_DIRS.has(e.name) && !e.name.startsWith('.'))\n .map((e) => join(dir, e.name));\n } catch {\n return [];\n }\n}\n\n/**\n * Expand workspace patterns to the manifests they match.\n *\n * Handles the three shapes that actually appear — an exact path, `dir/*` and\n * `dir/**` — plus `!` exclusions, which monorepos use to keep examples and\n * fixtures out of the workspace. A full glob engine would mean depending on\n * something that is only a transitive here; this is the subset real manifests\n * use, and anything it cannot match is simply not audited, which the report's\n * file list makes visible rather than hiding.\n */\nexport function expandWorkspaces(root: string, patterns: string[]): string[] {\n const includes = patterns.filter((p) => !p.startsWith('!'));\n const excludes = patterns\n .filter((p) => p.startsWith('!'))\n .map((p) => resolve(root, p.slice(1).replace(/\\/\\*+$/, '')));\n\n const dirs = new Set<string>();\n for (const pattern of includes) {\n const deep = /\\/\\*\\*$/.test(pattern);\n const shallow = !deep && /\\/\\*$/.test(pattern);\n const base = resolve(root, pattern.replace(/\\/\\*+$/, ''));\n if (!existsSync(base)) continue;\n\n if (!deep && !shallow) {\n dirs.add(base);\n continue;\n }\n let frontier = childDirs(base);\n for (const d of frontier) dirs.add(d);\n if (!deep) continue;\n for (let depth = 1; depth < MAX_WORKSPACE_DEPTH && frontier.length; depth++) {\n const next = frontier.flatMap(childDirs);\n for (const d of next) dirs.add(d);\n frontier = next;\n }\n }\n\n const out: string[] = [];\n for (const dir of dirs) {\n if (excludes.some((x) => dir === x || dir.startsWith(`${x}/`))) continue;\n const manifest = join(dir, 'package.json');\n if (existsSync(manifest)) out.push(manifest);\n }\n return out.sort();\n}\n\nexport interface InventoryOptions {\n /** Override the home directory, for tests. */\n home?: string;\n /** Skip user-level agent configs — project files only. */\n projectOnly?: boolean;\n maxItems?: number;\n}\n\n/**\n * Read a directory into an inventory.\n *\n * Never throws for a malformed or unreadable file: discovery problems are\n * appended to `notes`, because an audit that dies on one bad config tells the\n * user nothing about the forty things that were fine.\n */\nexport function collectInventory(root: string, opts: InventoryOptions = {}): Inventory {\n const abs = resolve(root);\n const max = opts.maxItems ?? MAX_ITEMS;\n const filesRead: string[] = [];\n const notes: string[] = [];\n const rel = (p: string) => (isAbsolute(p) && p.startsWith(abs) ? relative(abs, p) || '.' : p);\n\n // ---- npm packages -------------------------------------------------------\n const byName = new Map<string, InventoryPackage>();\n const rootManifest = join(abs, 'package.json');\n const manifests: string[] = [];\n if (existsSync(rootManifest)) {\n manifests.push(rootManifest);\n manifests.push(...expandWorkspaces(abs, workspacePatterns(abs)));\n } else {\n notes.push(`no package.json at ${abs}; npm half of the audit is empty`);\n }\n\n const tree = readLockTree(abs);\n const lock = tree.installs;\n for (const path of manifests) {\n const m = readJson(path) as Record<string, unknown> | null;\n if (!m) {\n notes.push(`could not parse ${rel(path)}`);\n continue;\n }\n filesRead.push(rel(path));\n for (const section of DEP_SECTIONS) {\n const block = m[section];\n if (!block || typeof block !== 'object') continue;\n for (const [name, range] of Object.entries(block as Record<string, unknown>)) {\n if (typeof range !== 'string') continue;\n const src: ItemSource = { file: rel(path), section };\n const seen = byName.get(name);\n if (seen) {\n seen.sources.push(src);\n continue;\n }\n byName.set(name, {\n name,\n range,\n installed: installedFrom(abs, name, lock),\n sources: [src],\n });\n }\n }\n }\n\n // ---- MCP servers --------------------------------------------------------\n const byAlias = new Map<string, InventoryMcpServer>();\n for (const path of mcpConfigPaths(abs, opts.home)) {\n if (opts.projectOnly && !path.startsWith(abs)) continue;\n if (!existsSync(path)) continue;\n const cfg = readJson(path);\n if (!cfg) {\n notes.push(`could not parse ${rel(path)}`);\n continue;\n }\n const found = serversFromConfig(cfg, rel(path));\n if (found.length) filesRead.push(rel(path));\n for (const s of found) {\n // Key on the package (or endpoint) rather than the alias: the same server\n // configured in three agents is one thing to check, not three, and\n // reporting it three times is how a report earns being ignored.\n const key = s.packageName ?? s.endpoint ?? `${s.kind}:${s.alias}`;\n const seen = byAlias.get(key);\n if (seen) {\n seen.sources.push(...s.sources);\n seen.version ??= s.version;\n continue;\n }\n byAlias.set(key, s);\n }\n }\n\n const packages = [...byName.values()];\n const mcpServers = [...byAlias.values()];\n\n // Everything in the resolved tree that is not a direct dependency. Bounded\n // separately and much higher than the display cap: these are not rendered\n // unless something is wrong with them, so the cost is one OSV batch per\n // hundred rather than a line of output per package.\n const directNames = new Set(byName.keys());\n const via = attributeTree([...directNames], tree.edges);\n const transitives: TransitiveInstall[] = [];\n for (const [name, version] of tree.installs) {\n if (directNames.has(name)) continue;\n if (transitives.length >= MAX_TRANSITIVES) {\n notes.push(\n `resolved tree exceeds ${MAX_TRANSITIVES} installs; the remainder were not checked for vulnerabilities`,\n );\n break;\n }\n transitives.push({ name, version, via: via.get(name) ?? [] });\n }\n if (!tree.present && packages.length > 0) {\n notes.push(\n 'no package-lock.json, so the dependency tree below your manifest was never read — transitive vulnerabilities are NOT covered by this run',\n );\n }\n\n const total = packages.length + mcpServers.length;\n if (total > max) {\n notes.push(\n `${total} items discovered, auditing the first ${max}; the remainder are reported as truncated rather than dropped`,\n );\n }\n\n return {\n root: abs,\n packages: packages.slice(0, max),\n mcpServers: mcpServers.slice(0, Math.max(0, max - packages.length)),\n transitives,\n filesRead,\n notes,\n };\n}\n","/**\n * Stack compatibility for MCP servers.\n *\n * The npm question — \"will these install together\" — does not apply here.\n * Servers are separate processes; nothing resolves between them and there are\n * no peer ranges to clash. They conflict somewhere npm has no equivalent for:\n * the agent sees ONE FLAT TOOL NAMESPACE assembled from all of them, and two\n * servers exposing the same tool name put the agent in a position where it\n * cannot express which one it means.\n *\n * That failure is silent in the worst way. Depending on the client, one tool\n * shadows the other or the later registration wins — either way the agent calls\n * `search` and reaches a server the user did not intend, with the arguments of\n * the one they did. No error is raised, because nothing is broken; the names\n * are simply ambiguous and something has to pick.\n *\n * The second cost is emergent rather than a clash: every tool's schema is in\n * the agent's context on every single request, so a stack is also a standing\n * token bill the user never sees itemised.\n *\n * Same verdict discipline as `checkCompat`: `unknown` when a member could not\n * be read, never a hedge on a set that WAS read. A collision check that\n * silently skips the server it could not probe would report a clean namespace\n * for a stack it never assembled.\n */\nimport type { Database } from '../db/client';\nimport { loadStored, rowsToSurface } from '../mcp/surfaceHandlers';\nimport { contractOf, MCP_TIER } from '../surface/mcp';\n\nexport type McpStackVerdict = 'conflict' | 'compatible' | 'unknown';\n\nexport interface McpToolRef {\n server: string;\n version: string | null;\n}\n\nexport interface McpCollision {\n /** The tool name two or more servers both expose. */\n tool: string;\n servers: string[];\n /**\n * True when at least one of the colliding tools can modify something.\n *\n * A shadowed read is a wrong answer; a shadowed write is a wrong answer that\n * changes somebody's data, so the two do not deserve the same severity.\n */\n writes: boolean;\n}\n\nexport interface McpStackMember {\n server: string;\n version: string | null;\n /** Null when the server has never been probed. */\n tools: number | null;\n /** Tools that can modify something, by their own annotations. */\n writes: number;\n destroys: number;\n}\n\nexport interface McpStackReport {\n overall: McpStackVerdict;\n members: McpStackMember[];\n collisions: McpCollision[];\n /** Every tool the agent will be handed. Null when any member was unread. */\n totalTools: number | null;\n /** Rough tokens these schemas occupy in EVERY request. Null when unread. */\n estimatedContextTokens: number | null;\n /** Servers with no stored surface — why `overall` can be `unknown`. */\n unread: string[];\n note: string;\n}\n\n/**\n * Rough token cost of one tool definition.\n *\n * A deliberate order-of-magnitude figure, not a measurement: name, description\n * and a JSON Schema, as most clients serialize them. It exists so a user with\n * forty tools sees that the standing cost is real, and it is described as\n * approximate everywhere it surfaces rather than dressed up as precision we do\n * not have.\n *\n * ponytail: a constant. Count real tokens per tool if anyone starts making\n * budget decisions on this number.\n */\nconst TOKENS_PER_TOOL = 250;\n\n/** Total tools past which a stack is worth trimming rather than growing. */\nconst CROWDED_TOOL_COUNT = 60;\n\nexport async function checkMcpStack(\n db: Database,\n servers: McpToolRef[],\n tenantId = 0,\n): Promise<McpStackReport> {\n const members: McpStackMember[] = [];\n const unread: string[] = [];\n /** tool name → servers exposing it, in configuration order. */\n const byTool = new Map<string, { servers: string[]; writes: boolean }>();\n\n for (const s of servers) {\n const stored = await loadStored(db, s.server, s.version, tenantId, 'mcp_server');\n if (!stored || stored.rows.length === 0 || stored.verdict === 'verified_false') {\n unread.push(s.server);\n members.push({ server: s.server, version: s.version, tools: null, writes: 0, destroys: 0 });\n continue;\n }\n const surface = rowsToSurface(s.server, s.version, stored.rows, MCP_TIER);\n let writes = 0;\n let destroys = 0;\n for (const sym of surface.symbols) {\n const ann = contractOf(sym)?.annotations;\n // Absent annotations resolve to the spec defaults, which are NOT benign:\n // a tool that declares nothing is assumed to write and to destroy.\n const canWrite = ann ? !ann.readOnlyHint : true;\n const canDestroy = ann ? ann.destructiveHint : true;\n if (canWrite) writes++;\n if (canDestroy) destroys++;\n\n const seen = byTool.get(sym.path);\n if (seen) {\n if (!seen.servers.includes(s.server)) seen.servers.push(s.server);\n seen.writes ||= canWrite;\n } else {\n byTool.set(sym.path, { servers: [s.server], writes: canWrite });\n }\n }\n members.push({\n server: s.server,\n version: s.version,\n tools: surface.symbols.length,\n writes,\n destroys,\n });\n }\n\n const collisions: McpCollision[] = [...byTool.entries()]\n .filter(([, v]) => v.servers.length > 1)\n .map(([tool, v]) => ({ tool, servers: v.servers, writes: v.writes }))\n .sort((a, b) => (a.tool < b.tool ? -1 : 1));\n\n const readMembers = members.filter((m) => m.tools !== null);\n const totalTools = unread.length ? null : readMembers.reduce((n, m) => n + (m.tools ?? 0), 0);\n\n const overall: McpStackVerdict =\n collisions.length > 0 ? 'conflict' : unread.length > 0 ? 'unknown' : 'compatible';\n\n const note =\n collisions.length > 0\n ? `${collisions.length} tool name(s) are exposed by more than one server; the agent has no way to say which one it means`\n : unread.length > 0\n ? `${unread.length} server(s) have not been probed, so the namespace was only partly assembled — this is NOT a clean bill`\n : `${totalTools} tool(s) across ${readMembers.length} server(s), no name collisions`;\n\n return {\n overall,\n members,\n collisions,\n totalTools,\n estimatedContextTokens: totalTools === null ? null : totalTools * TOKENS_PER_TOOL,\n unread,\n note,\n };\n}\n\n/** Is this stack large enough that its standing context cost is worth naming? */\nexport function isCrowded(report: McpStackReport): boolean {\n return (report.totalTools ?? 0) >= CROWDED_TOOL_COUNT;\n}\n\nexport { CROWDED_TOOL_COUNT, TOKENS_PER_TOOL };\n","/**\n * Assessment: an inventory in, a findings report out.\n *\n * Runs where the index is — locally against Postgres, or on the hosted server\n * behind the `audit` tool. Either way it takes the WHOLE inventory at once,\n * because the alternative (a call per dependency) turns a forty-package project\n * into forty round trips and is the reason this is one tool rather than a loop\n * over `evaluate`.\n *\n * Everything here is batched: one indexed read for every package name, one OSV\n * post per hundred installs, one stored-surface read per MCP server. Cost grows\n * with the size of the user's project, which is the bound that makes the\n * feature affordable at all.\n *\n * The rule that governs every branch: an item we could not assess is reported\n * as unassessed, with a reason. Silence is never an all-clear.\n */\nimport { inArray } from 'drizzle-orm';\nimport semver from 'semver';\nimport { logger } from '../core/logger';\nimport type { Database } from '../db/client';\nimport type { Advisory } from '../core/types';\nimport { packages } from '../db/schema';\nimport { queryVulnerableInstalls } from '../ingestion/sources/osv';\nimport { assessVerdict } from '../security/verdict';\nimport { checkMcpStack, isCrowded } from '../compat/mcpStack';\nimport { contractOf, MCP_TIER } from '../surface/mcp';\nimport { fetchServerManifest, missingConfig } from '../surface/mcpRegistry';\nimport { loadStored, rowsToSurface } from '../mcp/surfaceHandlers';\nimport { enqueueSurface } from '../db/surface';\nimport type {\n AuditItem,\n AuditReport,\n Coverage,\n Finding,\n Inventory,\n InventoryMcpServer,\n InventoryPackage,\n} from './types';\n\n/** Postgres caps bind parameters; chunk `IN` lists well under it, as drift.ts does. */\nconst NAME_CHUNK = 500;\n\ninterface IndexRow {\n name: string;\n latestVersion: string | null;\n deprecated: boolean;\n advisories: Advisory[] | null;\n}\n\n/** One indexed read for every discovered package name. */\nasync function loadIndexed(db: Database, names: string[]): Promise<Map<string, IndexRow>> {\n const out = new Map<string, IndexRow>();\n for (let i = 0; i < names.length; i += NAME_CHUNK) {\n const chunk = names.slice(i, i + NAME_CHUNK);\n const rows = await db\n .select({\n name: packages.name,\n latestVersion: packages.latestVersion,\n deprecated: packages.deprecated,\n advisories: packages.advisories,\n })\n .from(packages)\n .where(inArray(packages.name, chunk));\n for (const r of rows) out.set(r.name, r as IndexRow);\n }\n return out;\n}\n\n/** How far behind, phrased the way a reader decides with. */\nfunction drift(installed: string, latest: string): Finding | null {\n const a = semver.coerce(installed);\n const b = semver.coerce(latest);\n if (!a || !b || semver.gte(a, b)) return null;\n const majors = b.major - a.major;\n if (majors > 0) {\n return {\n kind: 'outdated',\n severity: majors >= 2 ? 'moderate' : 'low',\n detail: `${installed} → ${latest} (${majors} major version${majors > 1 ? 's' : ''} behind; run \\`lurq usage\\` for the exact API delta before upgrading)`,\n };\n }\n if (b.minor > a.minor) {\n return {\n kind: 'outdated',\n severity: 'info',\n detail: `${installed} → ${latest} (minor versions behind)`,\n };\n }\n return {\n kind: 'outdated',\n severity: 'info',\n detail: `${installed} → ${latest} (patches behind)`,\n };\n}\n\nconst OSV_SEVERITY: Finding['severity'] = 'high';\n\nfunction assessPackage(\n pkg: InventoryPackage,\n idx: IndexRow | undefined,\n vulns: string[] | undefined,\n vulnLookupComplete: boolean,\n): AuditItem {\n const item: AuditItem = {\n name: pkg.name,\n unit: 'npm',\n installed: pkg.installed,\n latest: idx?.latestVersion ?? null,\n status: 'answered',\n findings: [],\n };\n\n // The SAME verdict `verify` and `evaluate` return, so the three surfaces\n // cannot disagree about one package. Vulnerabilities are evaluated here\n // independently of whether lurq has ever indexed it: OSV is keyed on name and\n // version alone, and gating it on an index hit suppressed the most dangerous\n // finding we produce behind an unrelated coverage gap.\n const verdict = assessVerdict({\n exists: true,\n // Null, not `[]`: an unindexed package has not been analysed, and saying\n // \"no advisories\" about it would be inventing an all-clear.\n advisories: idx ? (idx.advisories ?? null) : null,\n deprecated: idx?.deprecated ?? false,\n versionVulns: vulns ?? null,\n vulnLookupComplete,\n // The audit is always about what is INSTALLED, never about latest. Saying\n // so is what keeps it from reading as a contradiction of `verify`, which\n // answers about the newest release.\n subjectVersion: pkg.installed,\n subjectInstalled: true,\n });\n item.verdict = verdict;\n\n if (vulns?.length) {\n item.findings.push({\n kind: 'vulnerable',\n severity: OSV_SEVERITY,\n detail: `${pkg.installed} is affected by ${vulns.length} advisory(ies): ${vulns.slice(0, 4).join(', ')}${vulns.length > 4 ? ', …' : ''}`,\n });\n }\n\n if (!idx) {\n // The DRIFT question is unanswerable without the index — but \"queued\" now\n // means \"we could not tell you how current it is\", not \"we did not look at\n // it\", and any vulnerability above is already reported.\n item.status = 'queued';\n item.skipReason = 'not-in-index';\n return item;\n }\n\n if (idx.deprecated) {\n item.findings.push({\n kind: 'deprecated',\n severity: 'moderate',\n detail: 'the publisher has marked this package deprecated',\n });\n }\n\n // The index's `advisories` column is a package-level count, true of the\n // package rather than of any one version. It only speaks when there is no\n // install to run the exact-version check against.\n if (!pkg.installed && (idx.advisories?.length ?? 0) > 0) {\n item.findings.push({\n kind: 'vulnerable',\n severity: 'moderate',\n detail: `${idx.advisories!.length} advisory(ies) recorded against this package; nothing is installed, so no exact-version check was possible`,\n });\n }\n\n if (pkg.installed && idx.latestVersion) {\n const d = drift(pkg.installed, idx.latestVersion);\n if (d) item.findings.push(d);\n } else if (!pkg.installed) {\n item.status = 'skipped';\n item.skipReason = 'not-installed';\n }\n\n return item;\n}\n\n/** Tools whose declared behaviour lets them change something outside the agent. */\nfunction privilegeSummary(tools: { annotations: Record<string, boolean> }[]): {\n writes: number;\n destroys: number;\n} {\n return {\n writes: tools.filter((t) => !t.annotations.readOnlyHint).length,\n destroys: tools.filter((t) => t.annotations.destructiveHint).length,\n };\n}\n\nasync function assessMcpServer(\n db: Database,\n s: InventoryMcpServer,\n idx: IndexRow | undefined,\n): Promise<AuditItem> {\n const name = s.packageName ?? s.endpoint ?? s.alias;\n const item: AuditItem = {\n name,\n unit: 'mcp',\n installed: s.version,\n latest: null,\n status: 'answered',\n findings: [],\n };\n\n if (s.kind !== 'npm-stdio' || !s.packageName) {\n item.status = 'skipped';\n item.skipReason = 'not-npm';\n item.findings.push({\n kind: 'contract-drift',\n severity: 'info',\n detail:\n s.kind === 'remote'\n ? `hosted at ${s.endpoint ?? 'an endpoint'}; there is no package to install, so lurq's stdio probe does not apply and its contract can change with no version to observe`\n : s.kind === 'other-registry'\n ? 'launched from a registry lurq does not index (PyPI or similar)'\n : 'launched from a local path, so there is no published artifact to compare against',\n });\n return item;\n }\n\n // What the server declares it needs, whether or not it has been probed. An\n // agent about to use it wants this before the first call, not after.\n const manifest = await fetchServerManifest(s.packageName).catch(() => null);\n const missing = missingConfig(manifest);\n if (missing.length) {\n item.findings.push({\n kind: 'needs-config',\n severity: 'moderate',\n detail: `needs ${missing.map((m) => m.name).join(', ')} before it will start${missing.some((m) => m.secret) ? ' (at least one is a credential — ask the user, never guess)' : ''}`,\n });\n }\n\n // Every npm signal applies to a server, because a server is an npm package.\n // Without this read the audit could report nine tools and their privilege\n // posture while saying nothing about the release being five versions old —\n // which is the question the user actually asked.\n item.latest = idx?.latestVersion ?? null;\n if (idx?.deprecated) {\n item.findings.push({\n kind: 'deprecated',\n severity: 'moderate',\n detail: 'the publisher has marked this server deprecated',\n });\n }\n if ((idx?.advisories?.length ?? 0) > 0) {\n item.findings.push({\n kind: 'vulnerable',\n severity: 'high',\n detail: `${idx!.advisories!.length} advisory(ies) recorded against this server`,\n });\n }\n if (s.version && idx?.latestVersion) {\n const d = drift(s.version, idx.latestVersion);\n // Behind on a server is worse than behind on a library: the tool contract\n // your agent is holding was built against a release that has since moved,\n // and `mcp_drift` can name exactly what changed.\n if (d) {\n item.findings.push({\n ...d,\n detail:\n `${s.version} → ${idx.latestVersion}; run ` +\n `\\`lurq mcp-drift ${s.packageName} --from ${s.version} --to ${idx.latestVersion}\\` ` +\n `for the contract delta`,\n });\n }\n } else if (!idx) {\n item.skipReason ??= 'not-in-index';\n }\n\n const stored = await loadStored(db, s.packageName, s.version, 0, 'mcp_server');\n if (!stored || stored.rows.length === 0) {\n await enqueueSurface(db, s.packageName, s.version, 'mcp_server').catch(() => {});\n item.status = 'queued';\n item.skipReason = 'never-probed';\n return item;\n }\n if (stored.verdict === 'verified_false') {\n item.findings.push({\n kind: 'contract-drift',\n severity: 'high',\n detail: 'probed and it did not complete the MCP handshake in a clean install',\n });\n return item;\n }\n\n const surface = rowsToSurface(s.packageName, s.version, stored.rows, MCP_TIER);\n const annotated = surface.symbols.map((sym) => ({\n annotations: contractOf(sym)?.annotations ?? {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: true,\n },\n }));\n const { writes, destroys } = privilegeSummary(annotated);\n if (destroys > 0) {\n item.findings.push({\n kind: 'privilege',\n severity: 'low',\n detail: `${surface.symbols.length} tool(s); ${writes} can write and ${destroys} declare destructive effects`,\n });\n }\n\n // The version question, answered honestly. An unpinned server floats to\n // whatever latest is at spawn time, so there is no \"your version\" to compare\n // and the only sound statement is that the contract is unobservable.\n if (!s.version) {\n item.skipReason = 'unpinned';\n item.findings.push({\n kind: 'contract-drift',\n severity: 'moderate',\n detail:\n 'launched unpinned, so every start may fetch a different build; lurq cannot tell you what changed because your config never named a version. Pin it to make drift observable.',\n });\n }\n\n return item;\n}\n\nexport interface AssessOptions {\n /** Injected for tests; defaults to the real OSV client. */\n vulnLookup?: typeof queryVulnerableInstalls;\n}\n\nexport async function assessInventory(\n db: Database,\n inv: Inventory,\n opts: AssessOptions = {},\n): Promise<AuditReport> {\n const lookup = opts.vulnLookup ?? queryVulnerableInstalls;\n // One indexed read covering BOTH halves. Server package names go into the\n // same query rather than a lookup each: eight servers should cost one round\n // trip, not eight.\n const names = [\n ...inv.packages.map((p) => p.name),\n ...inv.mcpServers.map((s) => s.packageName).filter((n): n is string => Boolean(n)),\n ];\n const indexed = await loadIndexed(db, names);\n\n // One OSV round trip for the WHOLE tree — directs and transitives together.\n // Transitives are where most real exposure lives and are invisible from a\n // manifest, so leaving them out would make a clean report mean very little.\n const installs = [\n ...inv.packages\n .filter((p): p is InventoryPackage & { installed: string } => p.installed !== null)\n .map((p) => ({ name: p.name, version: p.installed })),\n ...inv.transitives.map((t) => ({ name: t.name, version: t.version })),\n ];\n let affected = new Map<string, string[]>();\n let vulnComplete = true;\n try {\n const res = await lookup(installs);\n affected = res.affected;\n vulnComplete = res.complete;\n } catch (err) {\n // A failed lookup is NOT an all-clear. The flag is what stops the report\n // from printing \"0 vulnerabilities\" over a request that never landed.\n vulnComplete = false;\n logger.warn({ err: String(err) }, 'audit: vulnerability lookup failed');\n }\n\n const items: AuditItem[] = [];\n for (const p of inv.packages) {\n const item = assessPackage(\n p,\n indexed.get(p.name),\n p.installed ? affected.get(`${p.name}@${p.installed}`) : undefined,\n vulnComplete,\n );\n items.push(item);\n }\n\n // Transitives surface ONLY when something is wrong. A thousand healthy\n // inherited packages are not a finding, and listing them would bury the forty\n // direct dependencies the user can actually act on.\n for (const t of inv.transitives) {\n const vulns = affected.get(`${t.name}@${t.version}`);\n if (!vulns?.length) continue;\n items.push({\n name: t.name,\n unit: 'transitive',\n installed: t.version,\n latest: null,\n status: 'answered',\n via: t.via,\n findings: [\n {\n kind: 'vulnerable',\n severity: OSV_SEVERITY,\n detail:\n `${t.version} is affected by ${vulns.length} advisory(ies): ${vulns.slice(0, 4).join(', ')}${vulns.length > 4 ? ', …' : ''}` +\n // Without this the finding is unactionable: nobody installed the\n // transitive on purpose, so the fix is always at a direct dep.\n (t.via.length\n ? ` — pulled in via ${t.via.slice(0, 3).join(', ')}${t.via.length > 3 ? ` and ${t.via.length - 3} more` : ''}`\n : ' — no path recorded in the lockfile'),\n },\n ],\n });\n }\n\n for (const s of inv.mcpServers) {\n items.push(\n await assessMcpServer(db, s, s.packageName ? indexed.get(s.packageName) : undefined),\n );\n }\n\n // `discovered` counts what the user declared, not what the tree contains: the\n // answered fraction has to stay a statement about their dependencies, and a\n // thousand transitives would drown it.\n const declared = items.filter((i) => i.unit !== 'transitive');\n // Stack-level compatibility: the servers individually may be fine and still\n // collide when the agent flattens them into one tool namespace. Run once over\n // the probeable set rather than per-server, because a collision is a property\n // of the COMBINATION and no single server can see it.\n const stackNotes: string[] = [];\n const stdioServers = inv.mcpServers.filter((s) => s.kind === 'npm-stdio' && s.packageName);\n if (stdioServers.length > 1) {\n const stack = await checkMcpStack(\n db,\n stdioServers.map((s) => ({ server: s.packageName!, version: s.version })),\n ).catch(() => null);\n for (const c of stack?.collisions ?? []) {\n // Attached to every server involved: the user has to change one of them,\n // and which one is their call, not ours.\n for (const server of c.servers) {\n const item = items.find((i) => i.unit === 'mcp' && i.name === server);\n item?.findings.push({\n kind: 'contract-drift',\n severity: c.writes ? 'high' : 'moderate',\n detail:\n `tool name \"${c.tool}\" is also exposed by ${c.servers.filter((x) => x !== server).join(', ')}; ` +\n `the agent cannot say which it means` +\n (c.writes ? ' — and at least one of them can modify something' : ''),\n });\n }\n }\n if (stack && isCrowded(stack)) {\n stackNotes.push(\n `${stack.totalTools} MCP tools across ${stdioServers.length} servers (~${stack.estimatedContextTokens!.toLocaleString()} tokens of schema in every request) — worth trimming`,\n );\n }\n if (stack?.unread.length) {\n stackNotes.push(\n `tool-name collisions were only checked across the ${stdioServers.length - stack.unread.length} probed server(s); ${stack.unread.length} unprobed`,\n );\n }\n }\n\n const coverage: Coverage = {\n discovered: declared.length,\n answered: declared.filter((i) => i.status === 'answered').length,\n queued: declared.filter((i) => i.status === 'queued').length,\n skipped: declared.filter((i) => i.status === 'skipped').length,\n transitivesChecked: inv.transitives.length,\n treeRead: inv.transitives.length > 0,\n vulnComplete,\n };\n\n const notes = [...inv.notes, ...stackNotes];\n if (!vulnComplete) {\n notes.push(\n 'the vulnerability lookup did not complete, so vulnerability results are PARTIAL — absence of a finding here is not an all-clear',\n );\n }\n if (coverage.queued) {\n notes.push(\n `${coverage.queued} item(s) are not in the index yet and have been queued; re-run shortly for a complete answer`,\n );\n }\n\n return { root: inv.root, items, coverage, notes, dataAsOf: new Date().toISOString() };\n}\n\n/**\n * Feed the misses back into ingestion, so the next audit of this project is\n * more complete than this one.\n *\n * This is the mechanism behind the coverage promise. The index has only ever\n * held packages somebody already asked about, so an ordinary project's audit\n * starts out mostly \"not in the index\" — and stays that way unless the misses\n * are fed back. `github/drift.ts` solved the same problem for repo scans with\n * the same call; this is that fix applied to the local path.\n *\n * It must be `enqueueIngest`, NOT `enqueueSurface`. A surface is keyed to a\n * package the index already has, so queueing one for a package that was never\n * ingested schedules work against a row that does not exist — and the report\n * would say \"queued\" about something nothing was ever going to pick up. A\n * status the user can wait on has to be true.\n *\n * Fire-and-forget and hard-capped upstream: nothing here can slow or fail the\n * audit that triggered it.\n */\nexport async function queueUnknown(\n db: Database,\n report: AuditReport,\n ownerId: string | null = null,\n): Promise<number> {\n const names = report.items\n .filter((i) => i.unit !== 'transitive' && i.skipReason === 'not-in-index')\n .map((i) => i.name);\n if (names.length === 0) return 0;\n try {\n // The module load is awaited rather than fired and forgotten. With `void\n // import(...)` the enqueue happens a microtask later, so a caller that\n // queues and then drains finds an EMPTY queue, drains nothing, and reports\n // \"queued\" about work that was never scheduled. `enqueueIngest` itself\n // still returns without awaiting any network, so this costs the caller\n // nothing and makes the returned count true.\n const { enqueueIngest } = await import('../pipeline/ingestQueue');\n for (const name of names) enqueueIngest(db, name, ownerId);\n } catch (err) {\n // Ingestion improves the NEXT audit; this one still reports fully.\n logger.debug(`audit: untracked-dep enqueue failed: ${String(err)}`);\n return 0;\n }\n return names.length;\n}\n","/**\n * `audit` — assess a whole project in one call.\n *\n * The split matters. Discovery runs on the caller's machine (`src/audit/\n * inventory.ts`) and reads manifests and agent configs; what crosses the wire\n * is a list of names and versions, never a source file. This handler takes that\n * list and answers against the index.\n *\n * One call for the whole project rather than a loop over `evaluate`: a\n * forty-package repo is one round trip, and the batching inside `assess` keeps\n * it one indexed read plus one OSV post regardless of size.\n */\nimport type { Database } from '../db/client';\nimport { assessInventory, queueUnknown } from '../audit/assess';\nimport type { AuditReport, Inventory } from '../audit/types';\n\nexport interface AuditInput {\n packages?: { name: string; range?: string; installed?: string | null }[];\n transitives?: { name: string; version: string; via?: string[] }[];\n mcpServers?: {\n alias?: string;\n kind?: string;\n packageName?: string | null;\n version?: string | null;\n endpoint?: string | null;\n }[];\n notes?: string[];\n}\n\n/** Guard against a caller shipping an unbounded inventory. */\nconst MAX = 600;\n\nexport async function handleAudit(db: Database, input: AuditInput): Promise<AuditReport> {\n const notes = [...(input.notes ?? [])];\n const pkgs = (input.packages ?? []).slice(0, MAX);\n const servers = (input.mcpServers ?? []).slice(0, Math.max(0, MAX - pkgs.length));\n if ((input.packages?.length ?? 0) + (input.mcpServers?.length ?? 0) > MAX) {\n notes.push(`inventory exceeded ${MAX} items; the remainder were not assessed`);\n }\n\n const inv: Inventory = {\n root: '',\n packages: pkgs.map((p) => ({\n name: p.name,\n range: p.range ?? '*',\n installed: p.installed ?? null,\n sources: [],\n })),\n mcpServers: servers.map((s) => ({\n alias: s.alias ?? s.packageName ?? 'server',\n // Trust but bound: an unknown kind is treated as the least capable case\n // rather than assumed probeable, so a bad client cannot make lurq claim\n // it read something it did not.\n kind:\n s.kind === 'npm-stdio' ||\n s.kind === 'remote' ||\n s.kind === 'local' ||\n s.kind === 'other-registry'\n ? s.kind\n : 'local',\n packageName: s.packageName ?? null,\n version: s.version ?? null,\n endpoint: s.endpoint ?? null,\n sources: [],\n })),\n transitives: (input.transitives ?? []).slice(0, 4000).map((t) => ({\n name: t.name,\n version: t.version,\n via: t.via ?? [],\n })),\n filesRead: [],\n notes,\n };\n\n const report = await assessInventory(db, inv);\n await queueUnknown(db, report);\n // `root` is the caller's path and is not ours to echo back.\n return { ...report, root: null };\n}\n","/**\n * Shapes for `lurq audit` — the whole-project read.\n *\n * The organising idea is the DENOMINATOR. lurq's index covers a small fraction\n * of npm and a smaller fraction of the MCP registry, and chasing registry-wide\n * coverage is what kept the diffable store at ~2.9k packages while `usage` —\n * which answers on demand, within a budget — reached ten times that. So this\n * feature never asks \"how much of the world do we know\". It asks \"how much of\n * THIS project do we know\", which is forty-odd dependencies and a handful of\n * servers: bounded, affordable, and the only number the person asking can\n * actually perceive.\n *\n * Which makes the coverage accounting load-bearing rather than decorative.\n * Every discovered item lands in exactly one bucket — answered, queued, or\n * skipped with a stated reason — and the report prints the fractions. A\n * dependency we did not look at must never be counted as one we found nothing\n * wrong with; that is the same rule `github/drift.ts` and `surface/upgrade.ts`\n * already hold, applied to a surface the user sees directly.\n */\n\n/** Where a dependency came from, so a finding can be traced back to a file. */\nexport interface ItemSource {\n /** Path relative to the audited directory. */\n file: string;\n /** `dependencies`, `devDependencies`, `mcpServers`, … */\n section: string;\n}\n\n/** How an MCP server is launched, which decides whether lurq can read it. */\nexport type McpKind =\n /** `npx <pkg>` — an npm package lurq can install and probe. */\n | 'npm-stdio'\n /** A hosted endpoint. Nothing to install; the stdio probe does not apply. */\n | 'remote'\n /** A local binary or script path. Not reproducible from a registry. */\n | 'local'\n /** A package manager lurq does not index (uvx/pipx → PyPI, etc.). */\n | 'other-registry';\n\nexport interface InventoryPackage {\n name: string;\n /** The declared range, e.g. `^6.4.0`. */\n range: string;\n /**\n * What is actually installed, from the lockfile or node_modules.\n *\n * Null when nothing has been installed yet. This is the version that matters:\n * a range says what is permitted, an install says what runs, and a\n * vulnerability applies to the second.\n */\n installed: string | null;\n sources: ItemSource[];\n}\n\nexport interface InventoryMcpServer {\n /** The key in the config, e.g. `github`. Not necessarily the package name. */\n alias: string;\n kind: McpKind;\n /** npm package name, when `kind` is `npm-stdio`. */\n packageName: string | null;\n /**\n * Pinned version, when the config names one.\n *\n * Almost always null in practice: `npx -y <pkg>` floats to whatever latest is\n * at spawn time. That is why this feature cannot be built as \"you are on X,\n * latest is Y\" — for MCP there is usually no X.\n */\n version: string | null;\n /** Host, for a remote server. */\n endpoint: string | null;\n sources: ItemSource[];\n}\n\n/** An exact install somewhere in the resolved tree, direct or not. */\nexport interface TransitiveInstall {\n name: string;\n version: string;\n /**\n * Direct dependencies that lead here.\n *\n * The actionable half. \"lodash 4.17.11 is vulnerable\" is not something a user\n * can act on when they never installed lodash; \"via eslint\" is. Empty when\n * the lockfile recorded no edge reaching it.\n */\n via: string[];\n}\n\nexport interface Inventory {\n /** Absolute path that was audited. */\n root: string;\n packages: InventoryPackage[];\n mcpServers: InventoryMcpServer[];\n /**\n * Every other exact install in the resolved tree.\n *\n * Checked for vulnerabilities ONLY. A transitive cannot be upgraded directly,\n * so reporting it as \"2 majors behind\" is noise a reader cannot act on —\n * whereas a CVE in it is the single most common way a project is actually\n * exposed, and it is invisible from `package.json`.\n */\n transitives: TransitiveInstall[];\n /** Manifests and configs actually read, for the report's provenance line. */\n filesRead: string[];\n /** Discovery problems — a malformed config is reported, never swallowed. */\n notes: string[];\n}\n\nexport type Severity = 'critical' | 'high' | 'moderate' | 'low' | 'info';\n\n/** Why an item could not be assessed. Never absent when `status` is not `answered`. */\nexport type SkipReason =\n | 'not-in-index'\n | 'not-installed'\n | 'never-probed'\n | 'unpinned'\n | 'not-npm'\n | 'truncated';\n\nexport interface Finding {\n kind: 'outdated' | 'deprecated' | 'vulnerable' | 'contract-drift' | 'privilege' | 'needs-config';\n severity: Severity;\n /** One line, specific enough to act on without opening anything else. */\n detail: string;\n}\n\nexport interface AuditItem {\n name: string;\n /** `npm` direct, `transitive` inherited, `mcp` server. */\n unit: 'npm' | 'transitive' | 'mcp';\n installed: string | null;\n latest: string | null;\n status: 'answered' | 'queued' | 'skipped';\n skipReason?: SkipReason;\n /** Direct dependencies that pull in a transitive — what the user can act on. */\n via?: string[];\n /**\n * The shared safety call, identical to what `verify` and `evaluate` return\n * for the same package. Present so the audit cannot drift into its own\n * opinion about whether something is safe.\n */\n verdict?: import('../security/verdict').SecurityVerdict;\n findings: Finding[];\n}\n\n/**\n * The denominator, stated rather than implied.\n *\n * `vulnComplete` is separate on purpose: an OSV request that failed returns no\n * vulnerabilities, which is indistinguishable from a clean result unless the\n * report says so. Reporting \"0 vulnerabilities\" after a failed lookup is the\n * single most dangerous thing this feature could do.\n */\nexport interface Coverage {\n discovered: number;\n answered: number;\n queued: number;\n skipped: number;\n /**\n * Exact installs from the resolved tree checked for vulnerabilities.\n *\n * Counted apart from `discovered` on purpose: a thousand transitives would\n * otherwise swamp the forty direct dependencies and make the answered\n * fraction meaningless. They are a different question — \"is anything in my\n * tree vulnerable\" rather than \"is this dependency current\".\n */\n transitivesChecked: number;\n /** No lockfile, so the tree below the manifest was never seen. */\n treeRead: boolean;\n /** Every OSV batch came back. False means vulnerability results are partial. */\n vulnComplete: boolean;\n}\n\nexport interface AuditReport {\n root: string | null;\n items: AuditItem[];\n coverage: Coverage;\n notes: string[];\n dataAsOf: string;\n}\n\n/** Ordering for display: the thing that can hurt you goes first. */\nexport const SEVERITY_RANK: Record<Severity, number> = {\n critical: 0,\n high: 1,\n moderate: 2,\n low: 3,\n info: 4,\n};\n\nexport function worstSeverity(findings: Finding[]): Severity | null {\n if (findings.length === 0) return null;\n return findings.reduce(\n (worst, f) => (SEVERITY_RANK[f.severity] < SEVERITY_RANK[worst] ? f.severity : worst),\n findings[0]!.severity,\n );\n}\n","/**\n * Human-facing CLI command implementations (§13). Each gets a result from the\n * index (the hosted service, or a local database), then renders a compact\n * table/detail view, or raw JSON with `--json`.\n */\nimport semver from 'semver';\nimport { loadEnv, requireConfig } from '../core/config';\nimport { openInBrowser } from '../core/open';\nimport { resolveApiKey } from '../core/userConfig';\nimport { isCategory, type Category, type Confidence } from '../core/types';\nimport { searchCapabilities } from '../core/capabilities';\nimport { createDb } from '../db/client';\nimport { getPackageVersions } from '../db/packages';\nimport { handleCompare, handleEvaluate, handleRecommend, handleVerify } from '../mcp/handlers';\nimport { CONFIDENCE, QUALITY_WEIGHTS } from '../scoring/weights';\nimport {\n activeWeightsPath,\n applyOverrides,\n loadWeights,\n resetWeights,\n saveWeights,\n settableKeys,\n validateWeights,\n WEIGHT_EXPLANATIONS,\n} from '../scoring/weights';\nimport {\n bold,\n confidenceLabel,\n detail,\n dim,\n formatDate,\n formatNumber,\n formatPercent,\n green,\n red,\n table,\n yellow,\n} from './format';\nimport { MissingKeyError } from './remote';\n\nasync function withDb<T>(fn: (db: ReturnType<typeof createDb>['db']) => Promise<T>): Promise<T> {\n requireConfig(['DATABASE_URL']);\n const handle = createDb();\n try {\n return await fn(handle.db);\n } finally {\n await handle.close();\n }\n}\n\n/**\n * Which index a read command should answer from.\n *\n * An API key wins over DATABASE_URL, and that order is deliberate. dotenv loads\n * the `.env` of whatever directory the CLI is invoked in, so for a normal user\n * (someone who ran `lurq setup` and then typed `lurq recommend` inside their\n * own Postgres-backed app), DATABASE_URL is *their application's* database.\n * Checking it first would point package lookups at a schema that has never\n * heard of lurq and fail with a confusing SQL error. Operators and\n * self-hosters, who have a DATABASE_URL and no key, still get the local path;\n * anyone holding both can force it with LURQ_LOCAL=1.\n */\nexport function indexSource(): 'hosted' | 'local' {\n loadEnv();\n if (process.env.LURQ_LOCAL === '1') return 'local';\n if (resolveApiKey()) return 'hosted';\n if (process.env.DATABASE_URL) return 'local';\n throw new MissingKeyError(\n 'No API key configured. Run `lurq setup` to connect this machine, ' +\n 'or set DATABASE_URL to read from your own index.',\n );\n}\n\n/**\n * Run one read command against whichever index is configured.\n *\n * The hosted tools return exactly what the local handler returns (mcp/server.ts\n * wraps every handler result as a single JSON text block), so both paths hand\n * back the same shape and the caller renders it once. The one difference is\n * that the hosted path has been through `compact`, which drops null fields and\n * empty arrays, hence the `?? []` guards in the renderers below.\n */\nasync function fromIndex<T>(\n tool: string,\n args: Record<string, unknown>,\n local: (db: ReturnType<typeof createDb>['db']) => Promise<T>,\n): Promise<T> {\n if (indexSource() === 'local') return withDb(local);\n const { callTool } = await import('./remote');\n return callTool<T>(tool, args);\n}\n\nexport interface RecommendCliOpts {\n category?: string;\n minConfidence?: string;\n json?: boolean;\n}\n\n/**\n * The disqualifying facts about a candidate, or a dash.\n *\n * `—` here means \"checked, nothing wrong\", which is why the column is always\n * rendered rather than appearing only when something is flagged: a column that\n * comes and goes teaches the reader nothing when it is absent.\n */\nfunction candidateFlags(c: {\n deprecated?: boolean;\n archived?: boolean;\n advisories?: number;\n}): string {\n const flags = [\n c.deprecated && red('deprecated'),\n c.archived && yellow('archived'),\n c.advisories ? yellow(`${c.advisories} advisory`) : null,\n ].filter(Boolean) as string[];\n return flags.length ? flags.join(' ') : dim('—');\n}\n\nexport async function runRecommend(need: string, opts: RecommendCliOpts): Promise<void> {\n if (opts.category && !isCategory(opts.category)) {\n throw new Error(`Unknown category \"${opts.category}\".`);\n }\n const args = {\n need,\n category: opts.category as Category | undefined,\n constraints: opts.minConfidence\n ? { minConfidence: opts.minConfidence as Confidence }\n : undefined,\n };\n const res = await fromIndex('recommend', args, (db) => handleRecommend(db, args));\n\n if (opts.json) return console.log(JSON.stringify(res, null, 2));\n const candidates = res.candidates ?? [];\n if (candidates.length === 0) {\n console.log('No matching packages found.');\n return;\n }\n console.log(\n table(\n ['Package', 'Health', 'Quality', 'Confidence', 'Weekly', 'Latest', 'Category', 'Flags'],\n candidates.map((c) => [\n c.name,\n String(c.healthScore),\n c.qualityScore != null ? String(c.qualityScore) : '—',\n confidenceLabel(c.confidence),\n formatNumber(c.weeklyDownloads),\n c.latestVersion ?? '—',\n c.category ?? '—',\n // Last, and the only coloured cell: it is the column that can reverse\n // the decision the other seven are supporting, so it reads as a verdict\n // at the end of the row rather than as one more attribute among them.\n candidateFlags(c),\n ]),\n ),\n );\n printExclusions(res);\n console.log(dim(`\\ndata as of ${formatDate(res.dataAsOf)}`));\n}\n\n/**\n * Show what a selection policy refused, when one is in force.\n *\n * policy/types.ts is explicit that exclusions are reported and never silently\n * dropped, for a concrete reason: told \"here are 3 options\" when 5 were found,\n * an agent re-derives the blocked one from training and installs it directly.\n * The same holds for a person at a terminal. The hosted path is the one that\n * carries a verdict at all, since policy is owner-scoped and the local path\n * passes no owner.\n */\nfunction printExclusions(res: object): void {\n if (!('excluded' in res)) return;\n const excluded = (res.excluded ?? []) as { name: string; rule: string; reason: string }[];\n if (excluded.length === 0) return;\n console.log(yellow(`\\npolicy refused ${excluded.length}:`));\n for (const e of excluded) console.log(` ${e.name} ${dim(`${e.rule}: ${e.reason}`)}`);\n}\n\nexport async function runEvaluate(pkg: string, opts: { json?: boolean }): Promise<void> {\n const res = await fromIndex('evaluate', { package: pkg }, (db) =>\n handleEvaluate(db, { package: pkg }),\n );\n\n if (opts.json) return console.log(JSON.stringify(res, null, 2));\n if ('tracked' in res) {\n console.log(res.suggestion);\n return;\n }\n console.log(bold(res.name) + (res.category ? dim(` (${res.category})`) : ''));\n // A blocked verdict is the most actionable line in the whole output, so it\n // goes above the scores rather than after them. Absent means \"no rules\n // configured\", never \"allowed\": see PolicyVerdict in policy/types.ts.\n if (res.policy) {\n console.log(\n res.policy.allowed\n ? green('policy: allowed')\n : red(`policy: blocked (${res.policy.rule}): ${res.policy.reason}`),\n );\n }\n // Every component can be null for a barely-tracked package, and `compact`\n // drops the whole object once they are, so this is absent, not just empty.\n const b = res.scoreBreakdown ?? {};\n const advisories = res.advisories ?? [];\n console.log(\n detail([\n ['health', `${res.healthScore} ${confidenceLabel(res.confidence)}`],\n ['quality', res.qualityScore != null ? String(res.qualityScore) : '—'],\n [\n 'breakdown',\n `maint ${b.maintenance ?? '—'} · adopt ${b.adoption ?? '—'} · rel ${b.reliability ?? '—'} · eff ${b.efficiency ?? '—'} · qual ${b.quality ?? '—'}`,\n ],\n ['version', res.latestVersion ?? '—'],\n [\n 'weekly dl',\n `${formatNumber(res.weeklyDownloads)} (${formatPercent(res.downloadGrowth90d)} 90d)`,\n ],\n ['scorecard', res.scorecard != null ? String(res.scorecard) : '—'],\n ['bundle', res.bundleMinGzipKb != null ? `${res.bundleMinGzipKb} KB gzip` : '—'],\n ['released', formatDate(res.lastReleaseAt)],\n [\n 'flags',\n [res.deprecated && 'deprecated', res.archived && 'archived'].filter(Boolean).join(', ') ||\n 'none',\n ],\n [\n 'advisories',\n advisories.length ? advisories.map((a) => `${a.severity}`).join(', ') : 'none',\n ],\n ['repo', res.repoUrl ?? '—'],\n ]),\n );\n if (res.buildVerified) {\n const bv = res.buildVerified;\n const state = !bv.installed\n ? red('install failed')\n : bv.loaded === false\n ? yellow('installs, load failed')\n : green('installs and loads');\n console.log(`\\nsandbox: ${state} ${dim(`${bv.version} · ${bv.driver}`)}`);\n }\n if (res.summary) console.log('\\n' + res.summary);\n if (res.usageGuide) {\n const g = res.usageGuide;\n console.log(\n '\\n' +\n detail(\n [\n ['what', g.whatItIs],\n ['when', g.whenToUse],\n g.whenNotToUse ? (['when not', g.whenNotToUse] as [string, string]) : null,\n ['fits', g.whereItFits],\n g.howToWireIn ? (['wire-in', g.howToWireIn] as [string, string]) : null,\n ].filter(Boolean) as [string, string][],\n ),\n );\n }\n console.log(dim(`\\ndata as of ${formatDate(res.dataAsOf)}${res.stale ? ' (stale)' : ''}`));\n}\n\nexport async function runCompare(pkgs: string[], opts: { json?: boolean }): Promise<void> {\n const res = await fromIndex('compare', { packages: pkgs }, (db) =>\n handleCompare(db, { packages: pkgs }),\n );\n\n if (opts.json) return console.log(JSON.stringify(res, null, 2));\n console.log(\n table(\n ['Package', 'Health', 'Confidence', 'Weekly', '90d', 'Scorecard', 'Released'],\n (res.rows ?? []).map((r) => [\n r.name,\n String(r.healthScore),\n confidenceLabel(r.confidence),\n formatNumber(r.weeklyDownloads),\n formatPercent(r.downloadGrowth90d),\n r.scorecard != null ? String(r.scorecard) : '—',\n formatDate(r.lastReleaseAt),\n ]),\n ),\n );\n // Two causes, two lines. A name that is not on npm is a red flag the user has\n // to act on; a package still being ingested is a \"try again in a moment\". The\n // single dim line these used to share said \"not found\" for both.\n // `?? []` for the older-server case where only the union `missing` came back:\n // report it under the cautious heading rather than silently dropping it.\n const notFound = res.notFound ?? (res.pending ? [] : (res.missing ?? []));\n if (notFound.length) console.log(red(`\\nnot on npm: ${notFound.join(', ')}`));\n if (res.pending?.length) {\n console.log(dim(`\\nbeing scored now (retry shortly): ${res.pending.join(', ')}`));\n }\n console.log(dim(`data as of ${formatDate(res.dataAsOf)}`));\n}\n\n// ── weights / edit-weights (§4) ──────────────────────────────────────────────\n\n/** `lurq weights` — show + explain the score model (no DB needed). */\n/**\n * `lurq can <what you're trying to do>` — the catalog, searched.\n *\n * `--help` lists commands; it does not answer \"is there something in here for\n * the thing I'm stuck on\", because that question is asked in the user's words\n * and help is written in ours. This reads the same catalog the MCP\n * `capabilities` tool and the dashboard palette read, so all three stay in step.\n */\nexport function runCan(query: string, opts: { json?: boolean } = {}): void {\n const matches = searchCapabilities(query, 5);\n if (opts.json) {\n console.log(JSON.stringify(matches, null, 2));\n return;\n }\n if (!query.trim()) console.log(dim('Showing everything lurq does. Add words to narrow it.\\n'));\n for (const m of matches) {\n console.log(bold(m.title));\n console.log(` ${m.answer}`);\n if (m.cli) console.log(` ${green('$')} ${m.cli}`);\n if (m.mcp) console.log(dim(` agents: call the \\`${m.mcp}\\` tool`));\n if (m.page) console.log(dim(` dashboard: https://lurq.run${m.page}`));\n console.log('');\n }\n}\n\nexport function runWeights(opts: { json?: boolean } = {}): void {\n const w = loadWeights();\n const active = activeWeightsPath();\n if (opts.json) {\n console.log(JSON.stringify({ ...w, source: active?.source ?? 'defaults' }, null, 2));\n return;\n }\n const pct = (n: number) => n.toFixed(2);\n console.log(bold('Two axes, blended for default sort:'));\n console.log(` composite = (1−λ)·health + λ·quality λ = ${pct(w.composite.lambda)}\\n`);\n console.log(bold('Health (proven-ness) — weighted sum of 4 components:'));\n console.log(\n detail([\n [\n 'maintenance',\n `${pct(w.health.maintenance)} ${dim('— ' + WEIGHT_EXPLANATIONS.maintenance!)}`,\n ],\n ['adoption', `${pct(w.health.adoption)} ${dim('— ' + WEIGHT_EXPLANATIONS.adoption!)}`],\n [\n 'reliability',\n `${pct(w.health.reliability)} ${dim('— ' + WEIGHT_EXPLANATIONS.reliability!)}`,\n ],\n ['efficiency', `${pct(w.health.efficiency)} ${dim('— ' + WEIGHT_EXPLANATIONS.efficiency!)}`],\n ]),\n );\n console.log('\\n' + bold('Quality (intrinsic, adoption-independent):'));\n console.log(' ' + dim(Object.keys(QUALITY_WEIGHTS).join(', ')));\n console.log('\\n' + bold('Confidence thresholds:'));\n console.log(\n detail([\n [\n 'proven',\n `≥ ${formatNumber(CONFIDENCE.proven.minWeeklyDownloads)} weekly dl, ≥ ${CONFIDENCE.proven.minAgeMonths}mo old`,\n ],\n [\n 'emerging',\n `≥ ${formatNumber(CONFIDENCE.emerging.minWeeklyDownloads)} weekly dl OR ≥ ${CONFIDENCE.emerging.strongGrowth * 100}% 90d growth`,\n ],\n ['promising', `≥ ${CONFIDENCE.promising.minQuality} quality score (adoption-independent)`],\n ]),\n );\n console.log(\n dim(\n `\\nSource: ${active ? `${active.source} (${active.path})` : 'defaults (no user overrides)'}`,\n ),\n );\n}\n\nexport interface EditWeightsOpts {\n set?: string[];\n reset?: boolean;\n explain?: string;\n project?: boolean;\n json?: boolean;\n}\n\n/** `lurq edit-weights` — override / reset / explain the model (no DB needed).\n * A weight change alters ranking at read time, so invalidate the response cache\n * (no-op without REDIS_URL) when run where the index is served. */\nexport async function runEditWeights(opts: EditWeightsOpts): Promise<void> {\n const { invalidateCache } = await import('../core/cache');\n if (opts.reset) {\n const removed = resetWeights();\n console.log(\n removed.length\n ? `Removed overrides:\\n ${removed.join('\\n ')}`\n : 'No overrides to remove; already on defaults.',\n );\n if (removed.length) await invalidateCache();\n return;\n }\n\n if (opts.explain) {\n const key = opts.explain;\n const text = WEIGHT_EXPLANATIONS[key];\n if (!text) {\n throw new Error(\n `No explanation for \"${key}\". Known: ${Object.keys(WEIGHT_EXPLANATIONS).join(', ')}.`,\n );\n }\n console.log(`${bold(key)} — ${text}`);\n return;\n }\n\n if (opts.set && opts.set.length > 0) {\n const next = applyOverrides(loadWeights(), opts.set);\n const { weights, normalized } = validateWeights(next);\n const path = saveWeights(weights, opts.project ? 'project' : 'user');\n await invalidateCache();\n console.log(`Saved overrides to ${path}`);\n if (normalized) {\n console.log(\n yellow('Health weights did not sum to 1.0 — renormalized to: ') +\n `maint ${weights.health.maintenance.toFixed(3)}, adopt ${weights.health.adoption.toFixed(3)}, rel ${weights.health.reliability.toFixed(3)}, eff ${weights.health.efficiency.toFixed(3)}`,\n );\n }\n console.log(dim('\\nRun `lurq rescore` to apply the new health weights to the stored index.'));\n return;\n }\n\n // No action flags → behave like `lurq weights`.\n console.log(dim(`No changes. Settable keys: ${settableKeys().join(', ')}.\\n`));\n runWeights(opts);\n}\n\nexport interface PlanCliOpts {\n optimize?: string;\n json?: boolean;\n html?: string;\n open?: boolean;\n}\n\nexport async function runPlan(file: string, opts: PlanCliOpts): Promise<void> {\n const { readFileSync } = await import('node:fs');\n let document: string;\n try {\n document = readFileSync(file, 'utf8');\n } catch {\n throw new Error(`Could not read \"${file}\".`);\n }\n if (opts.optimize && opts.optimize !== 'speed' && opts.optimize !== 'balanced') {\n throw new Error(\"--optimize must be 'speed' or 'balanced'.\");\n }\n const args = { document, optimize: opts.optimize as 'speed' | 'balanced' | undefined };\n const res = await fromIndex('plan', args, async (db) => {\n const { handlePlan } = await import('../mcp/plan');\n return handlePlan(db, args);\n });\n\n if (opts.json) return console.log(JSON.stringify(res, null, 2));\n if (!('slots' in res)) {\n console.log(res.note);\n return;\n }\n\n // Visualization: render the roadmap to a portable HTML file and optionally open it.\n if (opts.html || opts.open) {\n const { writeFileSync } = await import('node:fs');\n const { tmpdir } = await import('node:os');\n const { join } = await import('node:path');\n const { renderPlanHtml } = await import('./planView');\n const out = opts.html ?? join(tmpdir(), `lurq-plan-${Date.now()}.html`);\n writeFileSync(out, renderPlanHtml(res), 'utf8');\n console.log(`Roadmap written to ${out}`);\n if (opts.open) openInBrowser(out);\n }\n\n console.log(\n table(\n ['Component', 'Layer', 'Recommended', 'Health', 'Confidence', 'Alternatives'],\n (res.slots ?? []).map((s) => [\n s.need.length > 32 ? s.need.slice(0, 31) + '…' : s.need,\n s.layer,\n s.recommended ? `${s.recommended.name}@${s.recommended.latestVersion ?? '?'}` : dim('—'),\n s.recommended ? String(s.recommended.healthScore) : '—',\n s.recommended ? confidenceLabel(s.recommended.confidence) : '—',\n (s.alternatives ?? []).map((a) => a.name).join(', ') || '—',\n ]),\n ),\n );\n if ((res.unmatched ?? []).length)\n console.log(yellow(`\\nNo match for: ${(res.unmatched ?? []).join(', ')}`));\n\n if (res.compatibility) {\n const c = res.compatibility;\n const col = c.overall === 'compatible' ? green : c.overall === 'conflict' ? red : dim;\n console.log('\\n' + bold('Compatibility: ') + col(c.overall));\n for (const s of res.slots ?? []) {\n if (s.swappedFrom && s.recommended) {\n console.log(\n green(` ✓ swapped ${s.swappedFrom} → ${s.recommended.name} for compatibility`),\n );\n }\n }\n for (const cf of c.conflicts ?? [])\n console.log(red(` ✗ ${cf.detail} (no compatible alternative)`));\n if (c.unverified?.length) console.log(dim(` unverified: ${c.unverified.join(', ')}`));\n }\n\n console.log('\\n' + bold('Roadmap (Mermaid):'));\n console.log(res.mermaid);\n console.log(dim(`\\n${res.note}`));\n console.log(dim(`data as of ${formatDate(res.dataAsOf)}`));\n}\n\nexport async function runVerify(pkg: string, opts: { json?: boolean }): Promise<void> {\n const res = await fromIndex('verify', { package: pkg }, (db) =>\n handleVerify(db, { package: pkg }),\n );\n\n if (opts.json) return console.log(JSON.stringify(res, null, 2));\n\n const v = res.verdict;\n // The tick is gated on `reassuring`, never on the level alone. A low level\n // over unchecked evidence is not a clean bill, and printing one was how an\n // unanalysed package came back \"✓ looks safe\".\n const headline =\n v.level === 'invalid'\n ? red('✗ NOT A REAL PACKAGE')\n : v.level === 'high'\n ? red(`✗ do not install ${v.scope} without review`)\n : v.level === 'medium'\n ? yellow('⚠ usable, but read the findings')\n : v.reassuring\n ? green(`✓ no supply-chain problems found in ${v.scope}`)\n : yellow(`? ${v.scope} is not fully checked yet`);\n console.log(`${bold(pkg)} ${headline}`);\n\n // Reasons before stats. Someone scanning this output stops at the first line\n // that tells them something, and a severity buried under a download count is\n // a severity that gets skipped.\n for (const r of v.reasons) console.log(` ${red('•')} ${r}`);\n for (const u of v.unknowns) console.log(` ${yellow('?')} ${u}`);\n\n if (v.level === 'invalid') return;\n\n const riskColor = v.level === 'high' ? red : v.level === 'medium' ? yellow : green;\n const riskFlags = res.riskFlags ?? [];\n console.log(\n detail([\n ['version', res.latestVersion ?? '—'],\n ['weekly dl', formatNumber(res.weeklyDownloads)],\n ['confidence', res.confidence ? confidenceLabel(res.confidence) : '—'],\n // Never \"0\" for something nobody has looked at.\n [\n 'advisories',\n res.advisoryCount === null ? yellow('not checked yet') : String(res.advisoryCount),\n ],\n ['risk', riskColor(v.level)],\n ['risk flags', riskFlags.length ? yellow(riskFlags.join(', ')) : 'none'],\n ]),\n );\n}\n\n/** The stored version timeline. Reads the table directly: there is no MCP tool\n * behind it, so unlike its neighbours this one is local-index only. */\nexport async function runVersions(\n pkg: string,\n opts: { json?: boolean; limit?: string },\n): Promise<void> {\n const limit = opts.limit ? Math.max(1, parseInt(opts.limit, 10) || 30) : 30;\n loadEnv();\n if (!process.env.DATABASE_URL) {\n throw new Error(\n '`lurq versions` reads a local index and needs DATABASE_URL. ' +\n 'On the hosted service, `lurq usage <pkg> --known <v>` gives the API delta between two versions.',\n );\n }\n await withDb(async (db) => {\n const versions = await getPackageVersions(db, pkg, limit);\n if (opts.json) return console.log(JSON.stringify(versions, null, 2));\n if (versions.length === 0) {\n console.log(`No stored versions for ${bold(pkg)}. Run \\`lurq sync --package ${pkg}\\` first.`);\n return;\n }\n console.log(bold(pkg));\n console.log(\n table(\n ['Version', 'Published'],\n versions.map((v) => [\n v.version,\n v.publishedAt ? v.publishedAt.toISOString().slice(0, 10) : '—',\n ]),\n ),\n );\n });\n}\n\n/** Long-running: follow the npm changes feed until interrupted (Ctrl-C). */\nexport async function runWatch(): Promise<void> {\n const { watchNpmChanges } = await import('../pipeline/watch');\n await withDb(async (db) => {\n const controller = new AbortController();\n const stop = () => controller.abort();\n process.once('SIGINT', stop);\n process.once('SIGTERM', stop);\n console.log(dim('watching npm for releases of tracked packages — Ctrl-C to stop'));\n try {\n await watchNpmChanges(db, { signal: controller.signal });\n } finally {\n process.off('SIGINT', stop);\n process.off('SIGTERM', stop);\n }\n });\n}\n\n/** Operator-side: install + smoke-load a package in the sandbox to verify it works. */\nexport async function runSandbox(\n pkg: string,\n version: string | undefined,\n opts: { esm?: boolean; allowScripts?: boolean; json?: boolean },\n): Promise<void> {\n if (opts.allowScripts) {\n console.error(\n yellow('warning: running install scripts and loading the package locally without isolation'),\n );\n }\n const { verifyPackageInSandbox } = await import('../pipeline/sandbox');\n await withDb(async (db) => {\n const result = await verifyPackageInSandbox(db, pkg, version ?? null, {\n target: { node: '20', moduleSystem: opts.esm ? 'esm' : 'cjs' },\n allowScripts: opts.allowScripts,\n });\n if (opts.json) return console.log(JSON.stringify(result, null, 2));\n const ok = result.installed && result.imported !== false;\n const label = version ? `${pkg}@${version}` : pkg;\n const verdict = ok ? green('✓ installs and loads') : red('✗ failed');\n console.log(\n `${bold(label)} ${verdict} ${dim(`(${result.durationMs}ms · ${result.driver})`)}`,\n );\n console.log(\n detail([\n ['installed', result.installed ? 'yes' : 'no'],\n ['loaded', result.imported === null ? '—' : result.imported ? 'yes' : 'no'],\n ['module', result.moduleSystem],\n ['scripts', result.ranScripts ? 'ran' : 'skipped'],\n ['error', result.error ?? 'none'],\n ]),\n );\n });\n}\n\n/** Version-exact API surface + drift from a known version (§4D). */\nexport async function runUsage(\n pkg: string,\n opts: { version?: string; known?: string; json?: boolean },\n): Promise<void> {\n const args = { package: pkg, version: opts.version, knownVersion: opts.known };\n const res = await fromIndex('usage', args, async (db) => {\n const { handleUsage } = await import('../mcp/handlers');\n return handleUsage(db, args);\n });\n\n if (opts.json) return console.log(JSON.stringify(res, null, 2));\n\n console.log(`${bold(res.package)}${res.version ? `@${res.version}` : ''}`);\n if (res.engines) {\n const reqs = Object.entries(res.engines)\n .map(([k, v]) => `${k} ${v}`)\n .join(', ');\n if (reqs) console.log(dim(`requires: ${reqs}`));\n }\n // A version npm never published is an error in the request, not a gap in our\n // index, so it gets the red treatment rather than the dim \"no data\" one.\n if (res.unpublishedVersion) return console.log(red(res.note ?? 'that version does not exist'));\n if (!res.available) return console.log(dim(res.note ?? 'no API surface available'));\n\n console.log(\n table(\n ['Export', 'Kind', 'Signature'],\n (res.surface ?? []).map((s) => [s.name, s.kind, s.signature ?? '']),\n ),\n );\n\n if (res.delta) {\n const d = res.delta;\n const removed = d.removed ?? [];\n const added = d.added ?? [];\n const renamed = d.renamed ?? [];\n const changed = d.changed ?? [];\n console.log(bold(`\\nΔ from ${res.package}@${d.fromVersion}:`));\n for (const s of removed) console.log(red(` - ${s.name}`));\n for (const s of added) console.log(green(` + ${s.name}`));\n for (const r of renamed) console.log(yellow(` ~ ${r.from.name} → ${r.to.name}`));\n for (const c of changed)\n console.log(yellow(` ! ${c.name}: ${c.before ?? '?'} → ${c.after ?? '?'}`));\n if (!removed.length && !added.length && !renamed.length && !changed.length) {\n console.log(dim(' no API changes'));\n }\n } else if (res.deltaNote) {\n console.log(yellow(`\\n${res.deltaNote}`));\n }\n}\n\n/** Operator: batched backfill of compat edges over the top-N packages (§4C).\n * `resolve` uses the cheap resolve-only tier (no VM); otherwise the sandbox. */\nexport async function runCompatBackfill(opts: {\n topN?: number;\n batchSize?: number;\n resolve?: boolean;\n}): Promise<void> {\n await withDb(async (db) => {\n const compat = await import('../pipeline/compat');\n if (opts.resolve) {\n console.error(yellow('resolve-only backfill (npm resolution, no install/VM)'));\n const res = await compat.resolveBackfill(db, opts);\n console.log(\n `${green('resolve backfill done')}: ${res.verified} edges across ${res.batches} runs, ${res.skipped} batches skipped`,\n );\n return;\n }\n console.error(\n yellow(\n 'co-installing top packages in the sandbox (loads package code locally without isolation unless E2B_API_KEY is set)',\n ),\n );\n const res = await compat.backfillVerify(db, opts);\n console.log(\n `${green('backfill done')}: ${res.verified} edges across ${res.batches} runs, ${res.skipped} batches skipped`,\n );\n });\n}\n\n/**\n * `--pin next=15.5.4` → `{ next: '15.5.4' }`.\n *\n * Exact versions only, and that restriction is load-bearing rather than lazy.\n * `fetchNpmCompatAtVersion` resolves a pin by exact key against the packument\n * and falls back to `latest` when the key is absent (see\n * ingestion/sources/npmRegistry.ts) — so `--pin next=15` would quietly check\n * next@16 and report it as the pinned answer. Refusing a range here is the\n * difference between \"no result\" and \"a confident wrong result\".\n */\nfunction parsePins(pins: string[] | undefined): Record<string, string> | undefined {\n if (!pins?.length) return undefined;\n const out: Record<string, string> = {};\n for (const raw of pins) {\n const at = raw.indexOf('=');\n const name = at === -1 ? '' : raw.slice(0, at).trim();\n const version = at === -1 ? '' : raw.slice(at + 1).trim();\n if (!name || !version) throw new Error(`--pin expects name=version, got \"${raw}\"`);\n if (!semver.valid(version)) {\n throw new Error(\n `--pin needs an exact published version, got \"${name}=${version}\". ` +\n `A range resolves to latest instead of erroring, which would report the wrong version as pinned.`,\n );\n }\n out[name] = version;\n }\n return out;\n}\n\n/** Read pairwise package compatibility (peer/engine constraints + recorded evidence). */\nexport async function runCompat(\n pkgs: string[],\n opts: { run?: boolean; json?: boolean; pin?: string[] },\n): Promise<void> {\n const versions = parsePins(opts.pin);\n const args = { packages: pkgs, versions };\n const read = async (db: ReturnType<typeof createDb>['db']) => {\n const { handleCompat } = await import('../mcp/handlers');\n return handleCompat(db, args);\n };\n // `compat-run` (operator plane) co-installs in the sandbox and records the\n // resulting edges before reading them back, so it always needs the local\n // database. Only the plain read can be served by the hosted index.\n const res = opts.run\n ? await withDb(async (db) => {\n console.error(\n yellow('co-installing in the sandbox (loads package code locally without isolation)'),\n );\n const { verifyCompatibility } = await import('../pipeline/compat');\n await verifyCompatibility(db, pkgs);\n return read(db);\n })\n : await fromIndex('compat', args, read);\n\n const conflicts = res.conflicts ?? [];\n const unverified = res.unverified ?? [];\n if (opts.json) return console.log(JSON.stringify(res, null, 2));\n const color = res.overall === 'compatible' ? green : res.overall === 'conflict' ? red : dim;\n console.log(`${bold((res.packages ?? pkgs).join(' + '))} ${color(res.overall)}`);\n if (conflicts.length) {\n console.log(\n table(\n ['Source', 'Detail'],\n conflicts.map((c) => [c.source, c.detail]),\n ),\n );\n } else if (res.overall === 'compatible') {\n console.log(dim('no peer-dependency or engine conflicts across the set'));\n }\n if (unverified.length) {\n console.log(dim(`\\nunverified (no metadata): ${unverified.join(', ')}`));\n }\n // Evidence strength (§4B): show co-install witnesses behind each pair.\n //\n // A pair can be both: tier-1 says the declared peer range is violated, and a\n // co-resolution witness says something out there installed them together\n // anyway. The declared constraint wins, which is the whole point of tier 1,\n // but printing a bare \"observed, 1 witness\" row directly under a red\n // `conflict` reads as the tool contradicting itself. Say which one lost.\n const conflicted = new Set(\n conflicts.flatMap((c) => (c.packages.length >= 2 ? [[...c.packages].sort().join('\\0')] : [])),\n );\n const isOverruled = (e: { packages: [string, string] }) =>\n conflicted.has([...e.packages].sort().join('\\0'));\n const compatEvidence = (res.evidence ?? []).filter((e) => e.status === 'compatible');\n if (compatEvidence.length) {\n console.log(\n table(\n ['Pair', 'Evidence', 'Witnesses'],\n compatEvidence.map((e) => [\n `${e.packages[0]} + ${e.packages[1]}`,\n isOverruled(e) ? `${e.provenance} (overruled)` : e.provenance,\n e.provenance === 'observed' ? String(e.witnessCount) : '—',\n ]),\n ),\n );\n if (compatEvidence.some(isOverruled)) {\n console.log(\n dim('overruled: a declared peer/engine constraint above beats the co-resolution witness'),\n );\n }\n }\n}\n\n/**\n * `lurq mcp-surface <server>` — what an MCP server exposes.\n *\n * The annotation column is the one worth reading and the reason this is not\n * just a tool list: `write`/`destroys`/`external` is what an agent is actually\n * being granted when it is pointed at a server, and it is nowhere in the README.\n */\nexport async function runMcpSurface(\n server: string,\n opts: { version?: string; json?: boolean },\n): Promise<void> {\n const args = { server, version: opts.version ?? null };\n const res = await fromIndex('mcp_surface', args, (db) =>\n import('../mcp/mcpHandlers').then((m) => m.handleMcpSurface(db, args)),\n );\n\n if (opts.json) return console.log(JSON.stringify(res, null, 2));\n\n console.log(`${bold(server)}${res.version ? dim(`@${res.version}`) : ''}`);\n\n // Printed before the verdict, and for a successful probe too. A server that\n // works and wants a token is the case where saying nothing costs most: the\n // agent wires it up, and the first real call fails in front of a user.\n const requires = res.requires ?? [];\n if (requires.length) {\n console.log(\n table(\n ['Needs', 'Required', 'Secret', 'What for'],\n requires.map((r) => [\n r.name,\n r.required ? red('yes') : dim('no'),\n r.secret ? yellow('yes') : dim('no'),\n r.description ?? '—',\n ]),\n ),\n );\n }\n if (res.configRequest) console.log(yellow(`\\n${res.configRequest}\\n`));\n\n if (res.verdict !== 'verified_true' || res.tools.length === 0) {\n console.log(yellow(`${res.verdict}: ${res.coverageNote}`));\n return;\n }\n\n console.log(\n table(\n ['Tool', 'Required', 'Optional', 'Behaviour'],\n res.tools.map((t) => {\n const optional = t.params.filter((p) => !t.required.includes(p));\n const a = t.annotations;\n // Only the powers that are ON are worth ink; an absent flag is the\n // benign default and printing it would bury the two that matter.\n const behaviour = [\n a.readOnlyHint ? green('read-only') : red('writes'),\n a.destructiveHint ? red('destroys') : null,\n a.openWorldHint ? yellow('external') : null,\n t.deprecated ? yellow('deprecated') : null,\n ]\n .filter(Boolean)\n .join(' ');\n return [t.name, t.required.join(', ') || '—', optional.join(', ') || '—', behaviour];\n }),\n ),\n );\n console.log(dim(res.coverageNote));\n}\n\n/**\n * `lurq mcp-drift <server> --from <a> --to <b>` — what the upgrade changes.\n *\n * Privilege widening prints above the breaking changes on purpose. A tool that\n * gained a required parameter fails loudly on the next call; a tool that quietly\n * stopped being read-only succeeds, and writes.\n */\nexport async function runMcpDrift(\n server: string,\n opts: { from: string; to: string; json?: boolean },\n): Promise<void> {\n const args = { server, fromVersion: opts.from, toVersion: opts.to };\n const res = await fromIndex('mcp_drift', args, (db) =>\n import('../mcp/mcpHandlers').then((m) => m.handleMcpDrift(db, args)),\n );\n\n if (opts.json) return console.log(JSON.stringify(res, null, 2));\n\n console.log(`${bold(server)} ${dim(`${opts.from} → ${opts.to}`)}`);\n if (res.inconclusive) {\n console.log(yellow(res.inconclusive));\n return;\n }\n\n const widened = res.annotationFlips.filter((f) => f.widensPrivilege);\n for (const f of widened) {\n console.log(red(`⚠ privilege ${f.tool}.${f.hint}: ${f.from} → ${f.to}`));\n }\n for (const t of res.silentDrift) {\n console.log(yellow(`⚠ silent ${t}: schema changed, description did not`));\n }\n for (const t of res.removedTools) console.log(red(`✗ removed ${t}`));\n for (const c of res.requiredAdded) {\n console.log(red(`✗ required ${c.tool}: ${c.params.join(', ')} now mandatory`));\n }\n for (const c of res.paramsRemoved) {\n console.log(red(`✗ dropped ${c.tool}: ${c.params.join(', ')}`));\n }\n for (const c of res.typeChanged.filter((x) => !x.widened)) {\n console.log(red(`✗ narrowed ${c.tool}.${c.param}`));\n }\n for (const t of res.addedTools) console.log(green(`+ added ${t}`));\n for (const c of res.requiredRelaxed) {\n console.log(green(`+ optional ${c.tool}: ${c.params.join(', ')}`));\n }\n for (const c of res.paramsAdded) {\n console.log(green(`+ params ${c.tool}: ${c.params.join(', ')}`));\n }\n // Compatible movement is printed too. The summary counts it, so leaving it\n // out of the body left the reader told that five parameters were relaxed and\n // unable to see which five.\n for (const c of res.typeChanged.filter((x) => x.widened)) {\n console.log(green(`+ relaxed ${c.tool}.${c.param}`));\n }\n for (const t of res.outputChanged) console.log(dim(`· output ${t}`));\n for (const f of res.annotationFlips.filter((x) => !x.widensPrivilege)) {\n console.log(dim(`· safer ${f.tool}.${f.hint}: ${f.from} → ${f.to}`));\n }\n for (const t of res.deprecated) console.log(yellow(`· deprecated ${t}`));\n for (const t of res.prosePolished) console.log(dim(`· docs only ${t}`));\n\n console.log(\n res.breaking ? red(`\\n${res.summary}`) : green(`\\n${res.summary || 'no contract change'}`),\n );\n}\n\n/**\n * `lurq audit [dir]` — what does this project actually depend on, and what is\n * wrong with it?\n *\n * Discovery is local and reads only manifests and agent configs; the assessment\n * takes names and versions, so running against the hosted index transmits no\n * source. That split is also why this is one call rather than a loop: forty\n * dependencies cost one round trip.\n *\n * The coverage line is not decoration. lurq's index does not cover all of npm\n * and covers less of the MCP registry, so the report has to say how much of\n * YOUR project it answered for — and anything it could not assess is printed as\n * unassessed rather than quietly omitted, which would read as a clean bill.\n */\n/**\n * Probe the MCP servers this project uses, before assessing them.\n *\n * Without this, an MCP server reports `queued` on the first run and stays that\n * way until a worker reaches it — three per cycle on the hosted service, and\n * never at all for someone running their own index with no worker. A user who\n * just asked about six servers is already waiting; spending a bounded amount of\n * that wait on the servers THEY named beats deferring to a queue whose priority\n * is not theirs.\n *\n * Bounded twice over: a wall-clock budget for the whole pass, and a hard skip\n * for anything already stored. Whatever does not fit stays queued and is\n * reported as queued, which is the same honest fallback as before.\n */\nasync function probeProjectServers(\n servers: { kind: string; packageName: string | null; version: string | null }[],\n budgetMs: number,\n): Promise<{ probed: number; skipped: number }> {\n const { createDb } = await import('../db/client');\n const { extractAndStoreMcp } = await import('../pipeline/mcp');\n const { hasStoredSurface } = await import('../db/surface');\n const { LocalSandbox } = await import('../sandbox/local');\n\n const targets = servers.filter((s) => s.kind === 'npm-stdio' && s.packageName);\n if (targets.length === 0) return { probed: 0, skipped: 0 };\n\n const handle = createDb({ max: 2 });\n const sandbox = new LocalSandbox();\n const deadline = Date.now() + budgetMs;\n let probed = 0;\n let skipped = 0;\n try {\n for (const s of targets) {\n if (Date.now() > deadline) {\n skipped++;\n continue;\n }\n const name = s.packageName!;\n if (\n s.version &&\n (await hasStoredSurface(handle.db, name, s.version, 'mcp_tools_list', 0, 'mcp_server'))\n ) {\n continue;\n }\n try {\n const r = await extractAndStoreMcp(handle.db, name, s.version, { sandbox });\n if (r.outcome === 'stored' || r.outcome === 'cached') probed++;\n } catch {\n // A probe failure is about that server, and the audit still reports.\n skipped++;\n }\n }\n } finally {\n await handle.close();\n }\n return { probed, skipped };\n}\n\nexport async function runAudit(\n dir: string | undefined,\n opts: { json?: boolean; projectOnly?: boolean; probe?: boolean; probeBudget?: string },\n): Promise<void> {\n const { collectInventory } = await import('../audit/inventory');\n const inv = collectInventory(dir ?? process.cwd(), { projectOnly: opts.projectOnly });\n\n let probeNote: string | null = null;\n if (opts.probe) {\n if (indexSource() !== 'local') {\n // Probing writes surfaces into an index, and a client must never be able\n // to write into the shared one — a poisoned tool list would be served to\n // everybody. Hosted callers get the worker's queue instead.\n probeNote =\n '--probe needs your own index (DATABASE_URL); on the hosted service the worker probes queued servers for you';\n } else {\n const budget = Math.max(5_000, Number(opts.probeBudget ?? 90) * 1000);\n const { probed, skipped } = await probeProjectServers(inv.mcpServers, budget);\n probeNote = `probed ${probed} MCP server(s)${skipped ? `, ${skipped} left queued (budget)` : ''}`;\n }\n }\n\n const payload = {\n packages: inv.packages.map((p) => ({ name: p.name, range: p.range, installed: p.installed })),\n transitives: inv.transitives.map((t) => ({ name: t.name, version: t.version, via: t.via })),\n mcpServers: inv.mcpServers.map((s) => ({\n alias: s.alias,\n kind: s.kind,\n packageName: s.packageName,\n version: s.version,\n endpoint: s.endpoint,\n })),\n notes: inv.notes,\n };\n const res = await fromIndex('audit', payload, (db) =>\n import('../mcp/auditHandler').then((m) => m.handleAudit(db, payload)),\n );\n\n if (opts.json) return console.log(JSON.stringify({ ...res, filesRead: inv.filesRead }, null, 2));\n\n const { SEVERITY_RANK, worstSeverity } = await import('../audit/types');\n const colour = (s: string) =>\n s === 'critical' || s === 'high' ? red : s === 'moderate' ? yellow : dim;\n\n console.log(bold(inv.root));\n console.log(dim(`read ${inv.filesRead.length} file(s): ${inv.filesRead.join(', ') || '—'}`));\n if (probeNote) console.log(dim(probeNote));\n\n const flagged = (res.items ?? [])\n .filter((i) => i.findings.length > 0)\n .sort(\n (a, b) =>\n SEVERITY_RANK[worstSeverity(a.findings)!] - SEVERITY_RANK[worstSeverity(b.findings)!],\n );\n\n if (flagged.length === 0) {\n console.log(green('\\nNothing flagged.'));\n } else {\n console.log('');\n for (const item of flagged) {\n const sev = worstSeverity(item.findings)!;\n const tag = item.unit === 'mcp' ? dim(' [mcp]') : '';\n const tag2 = item.unit === 'transitive' ? dim(' [transitive]') : tag;\n // The installed version is named on the line, so an audit finding cannot\n // be read as contradicting `verify`, which answers about the latest.\n const ver = item.installed ? dim(`@${item.installed}`) : '';\n console.log(`${colour(sev)(sev.padEnd(8))} ${bold(item.name)}${ver}${tag2}`);\n for (const f of item.findings) console.log(` ${f.detail}`);\n }\n }\n\n // The denominator, always printed — including when it is perfect, because a\n // coverage line that only appears when coverage is bad teaches the reader to\n // treat its absence as good news rather than as an unasked question.\n const c = res.coverage;\n console.log(\n `\\n${bold('coverage')} ${c.answered}/${c.discovered} declared dependencies answered` +\n (c.queued ? `, ${yellow(`${c.queued} queued`)}` : '') +\n (c.skipped ? `, ${dim(`${c.skipped} not assessable`)}` : ''),\n );\n // Printed even when it is zero. A tree line that appears only when something\n // was checked would let its absence read as \"nothing to check\" rather than\n // \"we never looked\", which is the distinction this whole report exists on.\n console.log(\n c.treeRead\n ? dim(` ${c.transitivesChecked} transitive install(s) checked for vulnerabilities`)\n : red(' no lockfile — the dependency tree was NOT checked for vulnerabilities'),\n );\n if (!c.vulnComplete) {\n console.log(\n red('vulnerability lookup incomplete — absence of a finding here is NOT an all-clear'),\n );\n }\n // The boundary of the whole report, stated once.\n //\n // Someone who asks \"is anything in my project out of date\" and sees a clean\n // result will read it as covering everything. It does not cover a REST API\n // version pinned in source (`apiVersion: '2023-10-16'`) or an endpoint called\n // by hand, because that is reading source code rather than reading artifacts\n // — a different engine, and one this deliberately does not have. Saying so is\n // cheaper than being quietly wrong about it, and for most projects the\n // question is answered anyway: an outdated SDK package above is what pins you\n // to an old API version.\n console.log(\n dim(\n ' scope: installed packages and configured MCP servers. API versions pinned in your own source are not read.',\n ),\n );\n for (const n of res.notes ?? []) console.log(dim(`· ${n}`));\n}\n\n/**\n * `lurq mcp-stack` — do the servers this project wires together actually\n * coexist?\n *\n * The npm question does not apply: servers are separate processes with nothing\n * to resolve between them. They clash in the one flat tool namespace the agent\n * assembles, where two servers exposing `search` leave it unable to say which\n * it means — and nothing errors, one simply shadows the other.\n */\nexport async function runMcpStack(\n dir: string | undefined,\n opts: { json?: boolean; projectOnly?: boolean },\n): Promise<void> {\n const { collectInventory } = await import('../audit/inventory');\n const { checkMcpStack, isCrowded } = await import('../compat/mcpStack');\n const inv = collectInventory(dir ?? process.cwd(), { projectOnly: opts.projectOnly });\n const servers = inv.mcpServers\n .filter((s) => s.kind === 'npm-stdio' && s.packageName)\n .map((s) => ({ server: s.packageName!, version: s.version }));\n\n if (servers.length === 0) {\n console.log(dim('no npm-launched MCP servers configured for this project'));\n return;\n }\n\n const report = await withDb((db) => checkMcpStack(db, servers));\n if (opts.json) return console.log(JSON.stringify(report, null, 2));\n\n const colour =\n report.overall === 'conflict' ? red : report.overall === 'unknown' ? yellow : green;\n console.log(`${bold(inv.root)} ${colour(report.overall)}`);\n\n for (const c of report.collisions) {\n const tag = c.writes ? red('writes') : yellow('read-only');\n console.log(`${red('✗')} ${bold(c.tool)} exposed by ${c.servers.join(' and ')} [${tag}]`);\n }\n\n console.log(\n table(\n ['Server', 'Version', 'Tools', 'Writes', 'Destroys'],\n report.members.map((m) => [\n m.server,\n m.version ?? dim('unpinned'),\n m.tools === null ? yellow('not probed') : String(m.tools),\n m.tools === null ? '—' : String(m.writes),\n m.tools === null ? '—' : m.destroys > 0 ? red(String(m.destroys)) : '0',\n ]),\n ),\n );\n console.log(dim(report.note));\n if (isCrowded(report)) {\n console.log(\n yellow(\n `~${report.estimatedContextTokens!.toLocaleString()} tokens of tool schema ride in every request — worth trimming`,\n ),\n );\n }\n}\n","/**\n * GitHub App authentication + REST access for the repo autopilot.\n *\n * Two-step, per GitHub's App auth model: sign a short-lived RS256 JWT with the\n * App's private key, exchange it for an *installation* access token, then call\n * the REST API as that installation. The JWT is the only thing derived from the\n * private key, and it lives ~9 minutes; the installation token lives an hour and\n * is scoped to exactly the repos the user selected at install time.\n *\n * No Octokit: the whole surface we need is three endpoints and an RS256 sign,\n * which `node:crypto` already does. Adding `@octokit/auth-app` + its transitive\n * tree to sign one JWT would be the expensive way to save fifteen lines.\n *\n * Token caching is in-memory and per-process only — deliberately never routed\n * through the shared on-disk `httpRequest` cache, which would write live repo\n * credentials to `~/.lurq`.\n */\nimport { createSign } from 'node:crypto';\nimport { getConfig } from '../core/config';\nimport { HttpError, httpRequest } from '../core/http';\n\nconst API_HOST = 'api.github.com';\nconst API = `https://${API_HOST}`;\n\n/** GitHub rejects a JWT with `exp` more than 10 minutes out; 9 leaves slack. */\nconst JWT_TTL_S = 9 * 60;\n/** Re-mint an installation token this long before it actually expires. */\nconst TOKEN_SKEW_MS = 60_000;\n\nexport class GithubAppError extends Error {\n constructor(\n message: string,\n readonly status: number,\n ) {\n super(message);\n this.name = 'GithubAppError';\n }\n}\n\nexport interface GithubAppCredentials {\n appId: string;\n privateKey: string;\n}\n\n/**\n * Read App credentials from config, or null when the App is not configured.\n *\n * Returning null rather than throwing is what lets `/repos` 404 cleanly on a\n * deployment that has not set the App up yet — the same shape `LURQ_ISSUER_SECRET`\n * uses for key issuance.\n */\nexport function githubAppCredentials(): GithubAppCredentials | null {\n const config = getConfig();\n const appId = config.LURQ_GITHUB_APP_ID;\n const rawKey = config.LURQ_GITHUB_APP_PRIVATE_KEY;\n if (!appId || !rawKey) return null;\n // Host env editors differ: Railway keeps real newlines, most CI secret fields\n // flatten them to a literal backslash-n. A PEM with the wrong one fails inside\n // crypto with an opaque error, so normalize here rather than debug it there.\n const privateKey = rawKey.includes('\\\\n') ? rawKey.replace(/\\\\n/g, '\\n') : rawKey;\n return { appId, privateKey };\n}\n\nfunction b64url(input: Buffer | string): string {\n return Buffer.from(input)\n .toString('base64')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n}\n\n/** Mint the App-level JWT. `iat` is backdated 60s to tolerate clock skew. */\nexport function appJwt(creds: GithubAppCredentials, now: Date = new Date()): string {\n const issued = Math.floor(now.getTime() / 1000) - 60;\n const header = b64url(JSON.stringify({ alg: 'RS256', typ: 'JWT' }));\n const payload = b64url(\n JSON.stringify({ iat: issued, exp: issued + JWT_TTL_S, iss: creds.appId }),\n );\n const signature = createSign('RSA-SHA256')\n .update(`${header}.${payload}`)\n .sign(creds.privateKey);\n return `${header}.${payload}.${b64url(signature)}`;\n}\n\ninterface CachedToken {\n token: string;\n expiresAt: number;\n}\n\nconst tokenCache = new Map<number, CachedToken>();\n\n/**\n * Exchange the App JWT for an installation access token.\n *\n * A 404 here means the installation is gone (user uninstalled the App), which is\n * a normal, expected state — callers surface it as \"reconnect\" rather than an error.\n */\nexport async function installationToken(installationId: number): Promise<string> {\n const cached = tokenCache.get(installationId);\n if (cached && cached.expiresAt - TOKEN_SKEW_MS > Date.now()) return cached.token;\n\n const creds = githubAppCredentials();\n if (!creds) throw new GithubAppError('GitHub App is not configured.', 503);\n\n let res;\n try {\n res = await httpRequest<{ token?: string; expires_at?: string }>(\n `${API}/app/installations/${installationId}/access_tokens`,\n {\n host: API_HOST,\n ttlMs: 0, // never cache credentials to disk\n method: 'POST',\n headers: {\n Authorization: `Bearer ${appJwt(creds)}`,\n Accept: 'application/vnd.github+json',\n 'X-GitHub-Api-Version': '2022-11-28',\n },\n },\n );\n } catch (err) {\n if (err instanceof HttpError && err.status === 404) {\n throw new GithubAppError('This GitHub installation no longer exists.', 404);\n }\n throw new GithubAppError(\n err instanceof Error ? err.message : 'Could not authenticate with GitHub.',\n 502,\n );\n }\n\n const token = res.data?.token;\n if (!token) throw new GithubAppError('GitHub returned no installation token.', 502);\n\n const expiresAt = res.data.expires_at ? Date.parse(res.data.expires_at) : NaN;\n tokenCache.set(installationId, {\n token,\n // A token with an unparseable expiry is still valid; treat it as short-lived\n // rather than caching it forever on a malformed timestamp.\n expiresAt: Number.isNaN(expiresAt) ? Date.now() + 5 * 60_000 : expiresAt,\n });\n return token;\n}\n\n/** Authenticated REST GET as an installation. */\nexport async function installationGet<T>(\n installationId: number,\n path: string,\n): Promise<T> {\n const token = await installationToken(installationId);\n const res = await httpRequest<T>(`${API}${path}`, {\n host: API_HOST,\n ttlMs: 0, // repo state changes under us; a cached manifest is a wrong answer\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: 'application/vnd.github+json',\n 'X-GitHub-Api-Version': '2022-11-28',\n },\n });\n return res.data;\n}\n","/**\n * The workflow file a user commits to arm the autopilot.\n *\n * Note what the analysis half costs: nothing but a lurq key. Planning the\n * upgrades and checking them against the codebase are plain CLI steps, so a repo\n * gets the full drift + breakage brief without any Anthropic credential at all.\n * That is only needed once someone switches the job to `pr` mode and wants code\n * actually rewritten — and then either an API key or an existing Claude\n * Pro/Max subscription token will do.\n *\n * Read the `permissions:` block first — it is the entire trust model. lurq's own\n * GitHub App is Contents:read-only and can never write to anyone's repository.\n * Every write in this loop is done by GitHub's own `GITHUB_TOKEN`: ephemeral,\n * scoped to the one repo, and limited to exactly what this file declares. The\n * user owns the file, so revoking the autopilot is `git rm`.\n *\n * Two more guardrails are structural rather than advisory:\n * · the agent's tool allowlist has no `git` and no network tool, so the model\n * edits files and the *workflow* does version control — a prompt injection\n * in a dependency's changelog cannot push a branch;\n * · the job defaults to `comment` mode, which analyses and reports without\n * touching a line. Editing is opt-in per repository.\n */\n\nimport { PACKAGE_NAME, VERSION } from '../core/constants';\n\nexport interface WorkflowOptions {\n /** Cron schedule. Default: Mondays 06:00 UTC. */\n cron?: string;\n /** Start in `pr` mode instead of the analyse-only default. */\n armed?: boolean;\n /** Package manager install command, detected from the lockfile. */\n installCommand?: string;\n /** Max upgrades attempted per run — the blast-radius cap. */\n maxUpgrades?: number;\n /**\n * Emit the auto-merge step, per `RepoPolicy.autoMerge`. Off unless the repo\n * has explicitly opted in — this is the only setting that lets lurq's loop\n * change a default branch, so it is never a default.\n */\n autoMerge?: boolean;\n}\n\nexport const WORKFLOW_PATH = '.github/workflows/lurq-upgrade.yml';\n\n/**\n * The CLI spec the generated workflow pins to.\n *\n * A bare `npx -y lurqrun` resolves to whatever is newest the moment the job\n * runs, in a file that otherwise pins everything (`actions/checkout@v6`,\n * `setup-node@v4`). That makes a bad publish an incident already executing in\n * every user's CI rather than one that can be held back — and the workflow lives\n * in *their* repository, so we cannot fix it for them.\n *\n * The range admits patches and stops before the first bump that is allowed to\n * break. Pre-1.0 that bump is the minor, not the major (semver §4: \"anything MAY\n * change at any time\" while 0.x), so the line to hold is `0.<minor>`; from 1.0\n * the major is enough, which is the same shape as the action pins above it.\n */\nexport function cliSpec(version: string = VERSION): string {\n const [major = '0', minor = '0'] = version.split('.');\n return major === '0' ? `${PACKAGE_NAME}@${major}.${minor}` : `${PACKAGE_NAME}@${major}`;\n}\n\nconst DEFAULT_CRON = '0 6 * * 1';\n\n/** Lockfile → install command. `npm ci` needs a lockfile, so fall back to install. */\nexport function detectInstallCommand(lockfiles: string[]): string {\n if (lockfiles.includes('pnpm-lock.yaml')) return 'pnpm install --frozen-lockfile';\n if (lockfiles.includes('yarn.lock')) return 'yarn install --frozen-lockfile';\n if (lockfiles.includes('bun.lockb') || lockfiles.includes('bun.lock')) return 'bun install';\n if (lockfiles.includes('package-lock.json')) return 'npm ci';\n return 'npm install';\n}\n\nexport function renderWorkflow(opts: WorkflowOptions = {}): string {\n const cron = opts.cron ?? DEFAULT_CRON;\n const install = opts.installCommand ?? 'npm ci';\n const max = opts.maxUpgrades ?? 3;\n const mode = opts.armed ? 'pr' : 'comment';\n const autoMerge = opts.autoMerge ?? false;\n const cli = cliSpec();\n\n return `# Managed by lurq, https://lurq.run\n#\n# Keeps this repository's dependencies current and rewrites the call sites an\n# upgrade breaks. lurq itself has read-only access to your code; every write\n# below is made by this workflow's own GITHUB_TOKEN, scoped by the permissions\n# block. Delete this file to turn the autopilot off.\nname: lurq upgrade\n\non:\n schedule:\n - cron: \"${cron}\"\n workflow_dispatch:\n inputs:\n mode:\n description: \"comment = analyse only · pr = open pull requests\"\n type: choice\n options: [comment, pr]\n default: ${mode}\n\n# The blast radius. \\`contents: write\\` permits pushing a BRANCH; branch\n# protection on your default branch is what stops anything landing unreviewed.\npermissions:\n contents: write\n pull-requests: write\n\nconcurrency:\n group: lurq-upgrade-\\${{ github.ref }}\n cancel-in-progress: true\n\njobs:\n upgrade:\n runs-on: ubuntu-latest\n env:\n LURQ_MODE: \\${{ inputs.mode || vars.LURQ_MODE || '${mode}' }}\n MAX_UPGRADES: \"${max}\"\n steps:\n - uses: actions/checkout@v6\n\n - uses: actions/setup-node@v4\n with:\n node-version: 22\n\n # 1. What is behind, and what does each upgrade remove from its API?\n # Sends only the dependency ranges already public in package.json.\n - name: Plan\n env:\n LURQ_API_KEY: \\${{ secrets.LURQ_API_KEY }}\n run: npx -y ${cli} upgrade-plan . --json > lurq-plan.json\n\n # 2. Narrow that to symbols THIS repo references. Runs entirely locally\n # against both versions' npm tarballs, no API key, no test suite.\n #\n # \\`--report\\` is the only part that talks to us, and it is additive: it\n # posts what this check concluded so your dashboard can show it. A\n # missing key or an unreachable API prints a line and changes nothing\n # else, so the gate keeps working exactly as it does without it.\n - name: Check against this codebase\n env:\n LURQ_API_KEY: \\${{ secrets.LURQ_API_KEY }}\n run: npx -y ${cli} check-upgrade . --plan lurq-plan.json --report --json > lurq-brief.json\n\n # The same report twice: once into the run summary, once as the body of\n # the pull request. Fenced, because the report is aligned plain text and\n # markdown would otherwise collapse its indentation into one paragraph.\n - name: Summarise\n run: |\n npx -y ${cli} check-upgrade . --plan lurq-plan.json > lurq-report.txt\n { echo '\\`\\`\\`'; cat lurq-report.txt; echo '\\`\\`\\`'; } > lurq-report.md\n cat lurq-report.md >> \"$\\{GITHUB_STEP_SUMMARY}\"\n\n # 3. Editing is opt-in. Until LURQ_MODE is 'pr', the job stops here having\n # changed nothing, the brief is in the run summary above, and no\n # Anthropic credential is needed to get this far.\n - name: Check agent credentials\n if: env.LURQ_MODE == 'pr'\n env:\n API_KEY: \\${{ secrets.ANTHROPIC_API_KEY }}\n OAUTH_TOKEN: \\${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}\n run: |\n if [ -z \"$API_KEY\" ] && [ -z \"$OAUTH_TOKEN\" ]; then\n echo \"::error::pr mode needs one of ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN in this repository's secrets. A Claude Pro/Max subscription token works for the latter. Set LURQ_MODE=comment to run analysis only.\"\n exit 1\n fi\n\n - name: Install dependencies\n if: env.LURQ_MODE == 'pr'\n run: ${install}\n\n - name: Apply upgrades\n if: env.LURQ_MODE == 'pr'\n uses: anthropics/claude-code-action@v1\n with:\n # Either credential works; set whichever you have. An API key bills\n # per token, an OAuth token uses an existing Claude Pro/Max plan.\n # Unset secrets resolve to empty and are ignored by the action.\n anthropic_api_key: \\${{ secrets.ANTHROPIC_API_KEY }}\n claude_code_oauth_token: \\${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}\n prompt: |\n REPO: \\${{ github.repository }}\n\n lurq-brief.json lists dependency upgrades this repository is behind\n on. For each entry under \"breaking\", the \"symbolsRemoved\" array names\n exports that DISAPPEAR at the target version, and each carries the\n exact file and line where this repository uses it.\n\n lurq-plan.json carries two more things per upgrade:\n · \"declaredIn\", EVERY package.json declaring that dependency.\n Bump all of them. Bumping only the root leaves a workspace\n pinned to the old major, which typechecks and breaks on install.\n · \"hops\", the migration sequence when the upgrade crosses two or\n more majors, with what each step removes. Work the steps in\n order; do not jump straight to the target version. When\n \"sequenceNote\" is present, the sequence could not be planned,\n treat that dependency as a migration and skip it.\n\n Take at most \\${{ env.MAX_UPGRADES }} entries, hardest first:\n\n 1. Bump the dependency's range in every manifest listed in\n \"declaredIn\".\n 2. Run \\`${install.split(' ')[0]} install\\` so node_modules holds the\n TARGET version. Until you do, the package on disk is the old one\n and anything you read from it describes the API you are leaving.\n 3. Rewrite every listed call site. \"newExports\" on each entry names\n the exports the target version ADDED, extracted from its shipped\n JavaScript: that is where the replacement for a removed symbol\n comes from. Confirm each one against the freshly installed package\n under node_modules before you call it. You have NO network access\n and no documentation: an API in neither the brief nor node_modules\n is one you cannot verify, and writing it anyway is the failure\n this whole job exists to prevent. Revert that dependency instead.\n 4. Run the repository's test script. If it fails and you cannot fix\n it from the upgrade itself, revert that dependency and move on,\n a reverted upgrade is a fine outcome, a broken build is not.\n 5. Leave the working tree with only the upgrades that pass.\n\n Do not touch unrelated files. Do not change CI configuration. Do not\n run git commands: the workflow handles version control.\n claude_args: |\n --allowedTools \"Read,Edit,Write,Bash(${install.split(' ')[0]}:*)\"\n\n # 4. The workflow does version control, never the model.\n - name: Open pull request\n id: pr\n if: env.LURQ_MODE == 'pr'\n uses: peter-evans/create-pull-request@v7\n with:\n branch: lurq/upgrades\n title: \"chore(deps): lurq dependency upgrades\"\n commit-message: \"chore(deps): upgrade dependencies and migrate call sites\"\n # The rendered report, not the raw JSON. A reviewer opening this PR\n # reads what was removed and where it is used; the JSON is the agent's\n # input, and pasting it here made the case for the change unreadable.\n body-path: lurq-report.md\n labels: dependencies\n delete-branch: true\n${autoMerge ? MERGE_STEP : ''}`;\n}\n\n/**\n * Auto-merge, emitted only when the repo's policy opts in.\n *\n * `--auto` is the load-bearing flag: it asks GitHub to merge **when the repo's\n * own required checks pass**, rather than merging now. lurq does not evaluate\n * anyone's CI and must never be the thing that decides a build was good enough —\n * branch protection stays the authority, and on a repo without it this is a\n * no-op that leaves the PR open rather than a silent landing.\n *\n * Emitting the step only under the policy — instead of always emitting it behind\n * an `if:` — means a user who has not opted in can read their own workflow file\n * and see that nothing in it can merge. The trust model is legible from the file\n * itself, which is the same reason the user commits it by hand.\n */\nconst MERGE_STEP = `\n # 5. Auto-merge, per this repository's lurq policy. GitHub merges only\n # once the repo's OWN required checks pass; lurq never makes that call.\n # Requires \"Allow auto-merge\" in repository settings.\n - name: Enable auto-merge\n if: env.LURQ_MODE == 'pr' && steps.pr.outputs.pull-request-number\n env:\n GH_TOKEN: \\${{ secrets.GITHUB_TOKEN }}\n run: gh pr merge --auto --squash \"\\${{ steps.pr.outputs.pull-request-number }}\"\n`;\n\n/**\n * GitHub's prefilled new-file URL. The dashboard links here instead of lurq\n * opening the PR itself — the user sees the exact file before committing it, and\n * lurq keeps zero write scope.\n */\nexport function newFileUrl(fullName: string, branch: string, content: string): string {\n const params = new URLSearchParams({ filename: WORKFLOW_PATH, value: content });\n return `https://github.com/${fullName}/new/${encodeURIComponent(branch)}?${params.toString()}`;\n}\n","/**\n * Repo inventory + manifest reading.\n *\n * Everything here reads exactly two things from a repository: the list of repos\n * the installation covers, and the dependency blocks of its `package.json`\n * files. File *names* come along in the tree listing — that is how the package\n * manager is detected — but no lockfile, source file, or history is ever read.\n * That is not a limitation we plan to lift server-side: the code-reading half of\n * the product runs in the user's own CI.\n */\nimport { installationGet } from './app';\nimport { detectInstallCommand } from './workflow';\nimport { REPO_MANIFEST_CAP, type RepoManifest } from './types';\nimport { logger } from '../core/logger';\nimport { HttpError } from '../core/http';\n\nexport interface InstallationRepo {\n fullName: string;\n defaultBranch: string;\n isPrivate: boolean;\n /** Last push, ISO-8601, or null when GitHub omits it. Ordering only — never stored. */\n pushedAt: string | null;\n}\n\ninterface ReposResponse {\n repositories?: {\n full_name: string;\n default_branch: string;\n private: boolean;\n pushed_at?: string | null;\n }[];\n}\n\n/** GitHub caps `per_page` at 100 for this endpoint. */\nconst PAGE_SIZE = 100;\n/** Stop paginating here. 20 pages = 2000 repos; past that the connect flow needs\n * repo selection in the UI, not a bigger loop. */\nconst MAX_PAGES = 20;\n\n/** Every repo the user granted the installation access to. */\nexport async function listInstallationRepos(\n installationId: number,\n): Promise<InstallationRepo[]> {\n const out: InstallationRepo[] = [];\n for (let page = 1; page <= MAX_PAGES; page++) {\n const data = await installationGet<ReposResponse>(\n installationId,\n `/installation/repositories?per_page=${PAGE_SIZE}&page=${page}`,\n );\n const batch = data.repositories ?? [];\n for (const repo of batch) {\n out.push({\n fullName: repo.full_name,\n defaultBranch: repo.default_branch,\n isPrivate: repo.private,\n pushedAt: repo.pushed_at ?? null,\n });\n }\n if (batch.length < PAGE_SIZE) break;\n }\n return out;\n}\n\ninterface TreeResponse {\n tree?: { path: string; type: string }[];\n truncated?: boolean;\n}\n\ninterface ContentsResponse {\n content?: string;\n encoding?: string;\n}\n\n/**\n * Paths of every `package.json` in the repo, root first.\n *\n * One recursive tree call instead of guessing workspace globs: it costs the same\n * as reading the root manifest alone, and it is the only way to find the real\n * layout of a monorepo without parsing `workspaces` patterns (which can be\n * globs, arrays, or a pnpm YAML file we would then also have to read).\n */\nexport function manifestPaths(tree: { path: string; type: string }[]): string[] {\n return tree\n .filter(\n (node) =>\n node.type === 'blob' &&\n (node.path === 'package.json' || node.path.endsWith('/package.json')) &&\n // A committed node_modules is rare but real, and its manifests are not\n // this project's dependencies — counting them would invent drift.\n !node.path.split('/').includes('node_modules'),\n )\n .sort((a, b) => a.path.split('/').length - b.path.split('/').length)\n .map((node) => node.path);\n}\n\n/** Merge `dependencies` + `devDependencies`, dropping non-registry specifiers. */\nexport function parseManifest(path: string, json: unknown): RepoManifest | null {\n if (!json || typeof json !== 'object') return null;\n const pkg = json as Record<string, unknown>;\n const deps: Record<string, string> = {};\n for (const block of ['dependencies', 'devDependencies']) {\n const entry = pkg[block];\n if (!entry || typeof entry !== 'object') continue;\n for (const [name, range] of Object.entries(entry as Record<string, unknown>)) {\n if (typeof range !== 'string') continue;\n // `file:`, `link:`, `workspace:`, `git+…`, and bare URLs never resolve to a\n // registry version, so they have no drift to report. Including them would\n // pad `depsDeclared` with rows that can only ever read \"unknown\".\n if (/^(file|link|workspace|git|github|https?|portal):/i.test(range)) continue;\n if (range.includes('/') && !range.startsWith('>') && !range.startsWith('<')) continue;\n deps[name] = range;\n }\n }\n return Object.keys(deps).length > 0 ? { path, deps } : null;\n}\n\nexport interface ManifestScan {\n manifests: RepoManifest[];\n /**\n * True when the repository has no commits at all.\n *\n * Distinct from `manifests: []`, which means \"there are commits, none of them\n * declare dependencies\". Both are successful scans, but only one of them is\n * something the user might want to act on, and telling a person their repo has\n * \"0 dependencies\" when it actually has no code yet is a confusing answer to a\n * question they did not ask.\n */\n empty: boolean;\n /** Install command for the repo's actual package manager, from its lockfile. */\n installCommand: string;\n /** True when the repo has more manifests than we read, or GitHub truncated the\n * tree. The dashboard says \"partial\" rather than reporting a low count as\n * complete — an undercount that looks authoritative is worse than a caveat. */\n partial: boolean;\n}\n\n/** Read every dependency block in a repo. */\nexport async function fetchManifests(\n installationId: number,\n fullName: string,\n branch: string,\n): Promise<ManifestScan> {\n let tree: TreeResponse;\n try {\n tree = await installationGet<TreeResponse>(\n installationId,\n `/repos/${fullName}/git/trees/${encodeURIComponent(branch)}?recursive=1`,\n );\n } catch (err) {\n // GitHub answers 409 for a repository with no commits. That is a fact about\n // the repo, not a failure of ours — a freshly created repo someone connected\n // before pushing anything is the common case. Treating it as an error left\n // `last_scan_error` set on a perfectly healthy repo, and the dashboard shows\n // that next to fresh numbers as though something were currently broken.\n if (err instanceof HttpError && err.status === 409) {\n return { manifests: [], installCommand: detectInstallCommand([]), partial: false, empty: true };\n }\n throw err;\n }\n const nodes = tree.tree ?? [];\n const allPaths = manifestPaths(nodes);\n // Root-level lockfiles only: a nested one belongs to a workspace, not to the\n // command that installs the whole repo.\n const lockfiles = nodes.filter((n) => !n.path.includes('/')).map((n) => n.path);\n const paths = allPaths.slice(0, REPO_MANIFEST_CAP);\n\n const manifests: RepoManifest[] = [];\n for (const path of paths) {\n try {\n const res = await installationGet<ContentsResponse>(\n installationId,\n `/repos/${fullName}/contents/${path.split('/').map(encodeURIComponent).join('/')}?ref=${encodeURIComponent(branch)}`,\n );\n if (!res.content || res.encoding !== 'base64') continue;\n const parsed = parseManifest(\n path,\n JSON.parse(Buffer.from(res.content, 'base64').toString('utf8')),\n );\n if (parsed) manifests.push(parsed);\n } catch (err) {\n // One malformed or unreadable manifest must not fail the whole repo scan —\n // the other workspaces still have real drift worth reporting.\n logger.debug(`manifest read failed for ${fullName}/${path}: ${(err as Error).message}`);\n }\n }\n\n return {\n manifests,\n installCommand: detectInstallCommand(lockfiles),\n partial: Boolean(tree.truncated) || allPaths.length > paths.length,\n empty: false,\n };\n}\n","/**\n * `lurq upgrade-plan` and the plan half of `lurq check-upgrade`.\n *\n * These run where the code is — a laptop or a CI runner — so they read manifests\n * from disk and ask the hosted index only \"what changed between these versions\".\n * Nothing about the source is sent: the request body is the dependency block\n * that is already public in any published package.json.\n */\nimport { readFileSync, readdirSync, statSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport { parseManifest } from '../github/manifests';\nimport type { RepoManifest } from '../github/types';\nimport { fetchUpgradePlan, type RemoteOptions, type RemotePlan, type RemoteUpgrade } from './remote';\n\n/** Directories never worth walking for a workspace manifest. */\nconst SKIP = new Set(['node_modules', '.git', 'dist', 'build', '.next', 'coverage', 'vendor']);\n\n/** Matches the server-side scan cap so local and CI plans agree. */\nconst MAX_MANIFESTS = 25;\nconst MAX_DEPTH = 4;\n\n/**\n * Find every `package.json` under `dir`, root first.\n *\n * Mirrors `manifestPaths` (which reads a GitHub tree) for the local filesystem.\n * The two deliberately apply the same rules — a plan computed in CI must match\n * what the dashboard reported, or the two views of one repo disagree.\n */\nexport function findManifests(dir: string, maxDepth = MAX_DEPTH): string[] {\n const found: string[] = [];\n\n const walk = (current: string, depth: number): void => {\n if (found.length >= MAX_MANIFESTS || depth > maxDepth) return;\n let entries: string[];\n try {\n entries = readdirSync(current);\n } catch {\n return; // unreadable directory: skip rather than abort the whole scan\n }\n if (entries.includes('package.json')) found.push(join(current, 'package.json'));\n for (const entry of entries) {\n if (SKIP.has(entry) || entry.startsWith('.')) continue;\n const child = join(current, entry);\n try {\n if (statSync(child).isDirectory()) walk(child, depth + 1);\n } catch {\n /* symlink loop or permission error — skip this entry */\n }\n }\n };\n\n walk(dir, 0);\n return found;\n}\n\n/** Read and parse every manifest under `dir`. */\nexport function readManifests(dir: string): RepoManifest[] {\n const out: RepoManifest[] = [];\n for (const file of findManifests(dir)) {\n try {\n const parsed = parseManifest(\n relative(dir, file) || 'package.json',\n JSON.parse(readFileSync(file, 'utf8')),\n );\n if (parsed) out.push(parsed);\n } catch {\n /* malformed manifest: the others still have real drift worth planning */\n }\n }\n return out;\n}\n\n/** Merge every manifest's ranges into one dependency map for the plan request. */\nexport function mergedDeps(manifests: RepoManifest[]): Record<string, string> {\n const out: Record<string, string> = {};\n for (const manifest of manifests) {\n for (const [name, range] of Object.entries(manifest.deps)) {\n out[name] ??= range;\n }\n }\n return out;\n}\n\nexport interface UpgradePlanResult extends RemotePlan {\n manifests: number;\n deps: number;\n}\n\n/**\n * Which repository this checkout is, for policy lookup.\n *\n * `GITHUB_REPOSITORY` is set by Actions on every run, so the generated workflow\n * needs no extra wiring and existing installs start being governed the moment\n * they connect the repo. Outside CI it is absent and the plan is ungoverned,\n * which is correct: a laptop is not a repository, and a policy the user set for\n * automation should not silently narrow what they asked for by hand.\n */\nexport function detectRepoFullName(explicit?: string | null): string | null {\n const value = explicit ?? process.env.GITHUB_REPOSITORY ?? null;\n return value && /^[\\w.-]+\\/[\\w.-]+$/.test(value) ? value : null;\n}\n\nexport async function buildUpgradePlan(\n dir: string,\n opts: RemoteOptions & { repo?: string | null } = {},\n): Promise<UpgradePlanResult> {\n const manifests = readManifests(dir);\n const deps = mergedDeps(manifests);\n if (Object.keys(deps).length === 0) {\n throw new Error(`No package.json with dependencies found under ${dir}`);\n }\n const plan = await fetchUpgradePlan(deps, { ...opts, repo: detectRepoFullName(opts.repo) });\n return { ...plan, manifests: manifests.length, deps: Object.keys(deps).length };\n}\n\nconst VERDICT_LABEL: Record<RemoteUpgrade['verdict'], string> = {\n 'removes-exports': 'REMOVES ',\n 'arity-changed': 'ARITY ',\n clean: 'CLEAN ',\n unknown: 'UNKNOWN ',\n};\n\n/** One-screen summary. Same shape as formatUpgradeReport so the two read alike. */\nexport function formatUpgradePlan(plan: UpgradePlanResult): string {\n const out: string[] = [\n `lurq upgrade plan (${plan.deps} dependencies across ${plan.manifests} manifest(s))`,\n ];\n // State the governing policy before listing anything. A reader who does not\n // know the scope cannot tell a short plan from a filtered one.\n if (plan.scopeSource === 'repo-policy') {\n out.push(\n `policy: scope=${plan.scope}` +\n (plan.outOfScope ? `, ${plan.outOfScope} upgrade(s) held back` : ', nothing held back'),\n );\n }\n out.push('');\n\n if (plan.upgrades.length === 0) {\n out.push('Everything lurq tracks is already on its latest release.');\n }\n\n for (const upgrade of plan.upgrades) {\n // Held-back upgrades stay listed and stay visible — marked, never dropped.\n // Hiding them would shrink the drift picture to whatever the current policy\n // happens to allow, which is how someone stops knowing they are behind.\n const held = upgrade.inScope === false ? ' [HELD]' : '';\n out.push(\n `${VERDICT_LABEL[upgrade.verdict]} ${upgrade.package} ${upgrade.fromVersion} → ${upgrade.toVersion}` +\n (upgrade.advisories ? ` (${upgrade.advisories} advisory)` : '') +\n held,\n );\n if (upgrade.scopeReason) out.push(` held: ${upgrade.scopeReason}`);\n if (upgrade.removed.length) {\n out.push(` removes ${upgrade.removed.length}: ${upgrade.removed.slice(0, 8).join(', ')}`);\n }\n for (const change of upgrade.arityChanged.slice(0, 5)) {\n out.push(` arity ${change.path}: ${change.from ?? '?'} → ${change.to ?? '?'}`);\n }\n // The migration sequence, when this crosses two or more majors. Ordering is\n // most of the work, and a single 6→8 line hides which step owns which break.\n if (upgrade.hops?.length) {\n out.push(` via ${[upgrade.fromVersion, ...upgrade.hops.map((h) => h.toVersion)].join(' → ')}`);\n for (const hop of upgrade.hops) {\n const detail = hop.removed.length\n ? `removes ${hop.removed.slice(0, 5).join(', ')}`\n : hop.verdict === 'unknown'\n ? 'not yet analysed'\n : 'no removals';\n out.push(` ${hop.fromVersion} → ${hop.toVersion}: ${detail}`);\n }\n }\n if (upgrade.sequenceNote) out.push(` ${upgrade.sequenceNote}`);\n // Only worth printing for a monorepo; a single root manifest is the default\n // assumption and saying so on every line would be noise.\n if (upgrade.declaredIn?.length > 1) {\n out.push(` declared in ${upgrade.declaredIn.map((d) => d.path).join(', ')}`);\n }\n if (upgrade.inconclusive) out.push(` ${upgrade.inconclusive}`);\n }\n\n // Never let a partial plan read as a complete one.\n const caveats: string[] = [];\n if (plan.untracked > 0) caveats.push(`${plan.untracked} dependency(ies) not in the lurq index`);\n if (plan.omitted > 0) caveats.push(`${plan.omitted} further upgrade(s) not shown`);\n if (plan.pending > 0) caveats.push(`${plan.pending} awaiting surface extraction`);\n if (caveats.length) out.push('', `NOT COVERED: ${caveats.join('; ')}.`);\n\n return out.join('\\n');\n}\n","/**\n * Turn a `check-upgrade` report into the rows the dashboard shows.\n *\n * `POST /upgrade-runs` has existed on the server, with validation, an upsert,\n * and an impact query behind it, since the autopilot shipped — and nothing ever\n * called it. The dashboard's \"Upgrade runs\" table and its whole impact row\n * (analysed / blocking / call sites) were therefore empty for every real\n * account; only the demo fixtures ever filled them. This module is the missing\n * client.\n *\n * The mapping is pure and lives apart from the posting so it can be tested\n * without a network: everything reported here is already in the report the CI\n * step just printed, so nothing is recomputed and the two can never disagree.\n *\n * What is NOT reported, deliberately: `filesChanged`, `testsPassed`, and the\n * `pr_open`/`merged` statuses. Those describe what the *agent* did after this\n * command ran, and the CLI cannot observe them without guessing. An upgrade the\n * model reverted would be posted as a PR that included it, which is exactly the\n * kind of overstatement `unverified` exists to prevent elsewhere in this file's\n * neighbourhood.\n * ponytail: `checked` only. To fill the PR/merge tiles honestly, a later step\n * would have to diff the opened PR's manifests and report per package.\n */\nimport type { UpgradeReport, UpgradeTarget } from '../surface/upgrade';\nimport type { ReportedRun } from './remote';\n\n/** Server cap (db/upgradeRuns.MAX_RUNS_PER_POST); trim here so a large repo's\n * post isn't silently truncated server-side. */\nconst MAX_RUNS = 100;\n\nexport interface RunContext {\n /** `owner/name`. */\n repoFullName: string;\n /** Permalink to the Actions run these rows came from. Part of the dedup key,\n * so re-running a job updates its rows instead of doubling every figure. */\n runUrl: string;\n}\n\n/** Every reference behind a finding, across removed symbols and arity changes. */\nfunction findingRefs(finding: UpgradeReport['breaking'][number]) {\n return [\n ...finding.symbolsRemoved.flatMap((s) => s.refs),\n ...finding.arityChanged.flatMap((a) => a.refs),\n ];\n}\n\n/**\n * Report rows for one checked upgrade set.\n *\n * Every target appears exactly once, in one of four severities. A package the\n * check could not establish comes back `unverified` rather than being dropped:\n * a dashboard that shows only what we managed to check reads as a clean bill of\n * health, and \"we did not look\" has to stay visible to be worth anything.\n */\nexport function buildRunReports(\n report: UpgradeReport,\n targets: UpgradeTarget[],\n ctx: RunContext,\n): ReportedRun[] {\n const versions = new Map(targets.map((t) => [t.package, t]));\n const base = (pkg: string) => {\n const target = versions.get(pkg);\n return {\n repoFullName: ctx.repoFullName,\n packageName: pkg,\n fromVersion: target?.fromVersion ?? '',\n toVersion: target?.toVersion ?? '',\n status: 'checked' as const,\n runUrl: ctx.runUrl,\n };\n };\n\n const rows: ReportedRun[] = [];\n\n for (const finding of report.breaking) {\n const refs = findingRefs(finding);\n rows.push({\n ...base(finding.package),\n // The finding carries its own versions; prefer them over the target map.\n fromVersion: finding.fromVersion,\n toVersion: finding.toVersion,\n severity: finding.severity,\n symbolsAffected: [\n ...finding.symbolsRemoved.map((s) => s.symbol),\n ...finding.arityChanged.map((a) => a.symbol),\n ],\n callSites: refs.length,\n callSiteFiles: [...new Set(refs.map((r) => r.file))],\n });\n }\n\n for (const pkg of report.ok) rows.push({ ...base(pkg), severity: 'ok' });\n for (const u of report.unverified) rows.push({ ...base(u.package), severity: 'unverified' });\n\n // A row with no versions cannot be deduped or displayed usefully, and the\n // server would reject it anyway (parseUpgradeRun requires both).\n return rows.filter((r) => r.fromVersion && r.toVersion).slice(0, MAX_RUNS);\n}\n\n/**\n * Where this run lives, from the Actions environment.\n *\n * Returns null off a runner. Reporting is for CI: on a laptop there is no run to\n * attribute rows to, and inventing one would put junk in the dedup key.\n */\nexport function runContextFromEnv(env: NodeJS.ProcessEnv = process.env): RunContext | null {\n const repoFullName = env.GITHUB_REPOSITORY?.trim();\n if (!repoFullName) return null;\n const server = env.GITHUB_SERVER_URL?.trim() || 'https://github.com';\n const runId = env.GITHUB_RUN_ID?.trim();\n // The run URL is part of the dedup key. Without a run id there is nothing\n // stable to key on, so leave it empty rather than fabricate a URL that would\n // make every job look like a different run and multiply the totals.\n return { repoFullName, runUrl: runId ? `${server}/${repoFullName}/actions/runs/${runId}` : '' };\n}\n","/**\n * Reference scanner (§9.1) — what symbols does this codebase actually use from\n * each dependency, and at which file:line.\n *\n * This is the half of `check_upgrade` that makes the check COVERAGE-INDEPENDENT,\n * and it is the whole wedge: Renovate and Dependabot gate an upgrade on your test\n * suite, so an uncovered path merges green and breaks later. Comparing what the\n * code *references* against what the target version *exports* needs no tests at\n * all.\n *\n * Static and conservative by construction. It resolves what an import binds and\n * which properties are read off it; it does not attempt dynamic access\n * (`pkg[name]`), which is reported nowhere rather than guessed at — a false\n * \"you use this\" is a false blocking result, and a CI check that cries wolf gets\n * disabled inside two weeks (§12 M3's kill condition).\n */\nimport { execFileSync } from 'node:child_process';\nimport { readdirSync, readFileSync, statSync } from 'node:fs';\nimport { extname, join, relative } from 'node:path';\nimport ts from 'typescript';\n\nconst SOURCE_EXT = new Set(['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs']);\nconst SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', 'out', '.next', 'coverage']);\n\n/**\n * How the symbol was reached — which decides whether it is a claim about the\n * MODULE'S EXPORT SURFACE or about a property of an exported value.\n *\n * named / destructured / namespace → a real export claim; tier A can verify\n * default → the module itself\n * default-member → a property of the default export's VALUE\n *\n * The last one is the important distinction. `chalk.bold` is correct chalk usage\n * but `bold` is not a module export, so scoring it against a tier-A surface\n * reports a miss on working code. Doing that in check_upgrade would block a PR\n * on valid code, which is how a CI gate gets switched off (§12 M3).\n */\nexport type ReferenceVia =\n | 'named'\n | 'destructured'\n | 'namespace'\n | 'default'\n | 'default-member'\n /**\n * A property read off a NAMED import: `import { z } from 'zod'` then\n * `z.string()`. Conditional, which is why it is not in SURFACE_CLAIM_KINDS.\n *\n * Some packages export a namespace-shaped object alongside the same names at\n * the top level, and zod is the canonical one: `z.string` and the top-level\n * `string` export are the same function. For those, the member IS checkable\n * against the module surface. For a named export that is merely an object\n * with its own unrelated properties, it is not, and conflating the two would\n * block a PR on correct code. The scorer decides using the parent's kind,\n * which only it can see; the scanner records the fact and the parent name.\n */\n | 'named-member'\n /** Erased by TypeScript before runtime — never a runtime-surface claim. */\n | 'type-only';\n\nexport interface SymbolReference {\n /** Exported name used from the package. 'default' for a default import. */\n symbol: string;\n via: ReferenceVia;\n /** Only on `named-member`: the named export the property was read from. */\n parent?: string;\n /**\n * The full import specifier. A subpath (`drizzle-orm/pg-core`) has its OWN\n * entry point and its own surface — scoring its symbols against the package\n * ROOT reports every one of them missing, on correct code.\n */\n specifier: string;\n file: string;\n line: number;\n}\n\n/** Kinds that assert something about the module's own export surface. */\nexport const SURFACE_CLAIM_KINDS: ReferenceVia[] = ['named', 'destructured', 'namespace'];\n\n/** True when the reference is against the package root rather than a subpath. */\nexport function isRootSpecifier(ref: SymbolReference, pkg: string): boolean {\n return ref.specifier === pkg;\n}\n\nexport interface PackageReferences {\n package: string;\n symbols: Map<string, SymbolReference[]>;\n}\n\n/** Bare specifier → package name (`@scope/pkg/sub` → `@scope/pkg`). */\nexport function packageOfSpecifier(spec: string): string | null {\n if (!spec || spec.startsWith('.') || spec.startsWith('/')) return null;\n if (spec.startsWith('node:')) return null;\n const parts = spec.split('/');\n return spec.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0]!;\n}\n\n/**\n * Source files, asking git rather than guessing at directory names.\n *\n * SKIP_DIRS is a fixed list — `dist`, `build`, `out` — and a build output\n * directory called anything else gets walked as if it were source. lurq's own\n * repo is the proof: tsup writes to `dist-operator` (tsup.config.ts), which is\n * not on the list, so scanning this project reported symbols at\n * `dist-operator/chunk-OX3TLAEA.js:12` — a generated file nobody edits, and a\n * citation nobody can act on. Reading tsconfig's `outDir` would not have caught\n * it either, since the path is declared by the bundler, not the compiler.\n *\n * Widening the list is the wrong repair: `lib`, `es` and `esm` are build output\n * in some projects and hand-written source in others, so any name-based guess\n * either misses output or silently drops real code. The second failure is much\n * worse than the first — a missed call site turns a blocking upgrade into a\n * clean one.\n *\n * `git ls-files --cached --others --exclude-standard` is exactly the question\n * being asked: the files this project treats as its own, tracked or newly\n * written, excluding everything its own ignore rules call generated. One\n * subprocess, no glob parsing, and it uses the project's declaration rather\n * than our guess about it.\n *\n * The walk stays as the fallback, because a directory that is not a git\n * checkout still has to be scannable.\n */\nfunction listSourceFiles(dir: string, limit = 5000): string[] {\n const tracked = gitSourceFiles(dir, limit);\n if (tracked) return tracked;\n\n const out: string[] = [];\n const walk = (d: string) => {\n if (out.length >= limit) return;\n let entries: string[];\n try {\n entries = readdirSync(d);\n } catch {\n return;\n }\n for (const e of entries) {\n if (out.length >= limit) return;\n if (SKIP_DIRS.has(e) || e.startsWith('.')) continue;\n const full = join(d, e);\n let st;\n try {\n st = statSync(full);\n } catch {\n continue;\n }\n if (st.isDirectory()) walk(full);\n else if (SOURCE_EXT.has(extname(e)) && !e.endsWith('.d.ts')) out.push(full);\n }\n };\n walk(dir);\n return out;\n}\n\n/** Source files per git, or null when `dir` is not a usable checkout. */\nfunction gitSourceFiles(dir: string, limit: number): string[] | null {\n let stdout: string;\n try {\n stdout = execFileSync('git', ['ls-files', '--cached', '--others', '--exclude-standard'], {\n cwd: dir,\n encoding: 'utf8',\n maxBuffer: 32 * 1024 * 1024,\n stdio: ['ignore', 'pipe', 'ignore'],\n });\n } catch {\n return null; // not a repo, or git is unavailable, walk instead\n }\n\n const out: string[] = [];\n for (const rel of stdout.split('\\n')) {\n if (!rel || out.length >= limit) break;\n if (!SOURCE_EXT.has(extname(rel)) || rel.endsWith('.d.ts')) continue;\n // node_modules can be committed; it is never the project's own source.\n if (rel.split('/').includes('node_modules')) continue;\n out.push(join(dir, rel));\n }\n return out;\n}\n\n/**\n * Scan a codebase for the symbols it uses from each bare-specifier import.\n *\n * Namespace and default bindings are tracked so member reads resolve to the\n * right package: `import fg from 'fast-glob'` + `fg.escapePath` records\n * `escapePath`, which is what makes the §9.0 report able to name a line.\n */\n\n/**\n * Identifiers that appear in VALUE position.\n *\n * TypeScript erases imports used only as types, so a named import that never\n * appears in a value position asserts nothing about the runtime surface. This\n * is a syntactic approximation — no type checker — which is the right bias:\n * treating a genuine value use as type-only would UNDER-report, and a missed\n * detection is far cheaper than a false \"this symbol does not exist\".\n */\nfunction collectValueIdentifiers(sf: ts.SourceFile): Set<string> {\n const out = new Set<string>();\n const visit = (node: ts.Node, inType: boolean): void => {\n const nowInType = inType || ts.isTypeNode(node) || ts.isTypeQueryNode(node);\n if (\n !nowInType &&\n ts.isIdentifier(node) &&\n node.parent &&\n !ts.isImportSpecifier(node.parent) &&\n !ts.isImportClause(node.parent) &&\n !ts.isNamespaceImport(node.parent) &&\n !ts.isPropertyAccessExpression(node.parent)\n ) {\n out.add(node.text);\n }\n // A property access still uses its OBJECT in value position.\n if (!nowInType && ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression)) {\n out.add(node.expression.text);\n }\n ts.forEachChild(node, (c) => visit(c, nowInType));\n };\n visit(sf, false);\n return out;\n}\n\nexport function scanReferences(rootDir: string, opts: { limit?: number } = {}): PackageReferences[] {\n const byPackage = new Map<string, Map<string, SymbolReference[]>>();\n\n const record = (\n pkg: string,\n symbol: string,\n via: ReferenceVia,\n specifier: string,\n file: string,\n line: number,\n parent?: string,\n ) => {\n let syms = byPackage.get(pkg);\n if (!syms) byPackage.set(pkg, (syms = new Map()));\n const list = syms.get(symbol);\n const ref: SymbolReference = { symbol, via, specifier, file, line, ...(parent ? { parent } : {}) };\n if (list) {\n // Same file:line can legitimately carry two different claims (`z` as a\n // named import, `z.string` as a member read off it), so the dedupe key\n // has to include how the symbol was reached.\n if (!list.some((r) => r.file === file && r.line === line && r.via === via)) list.push(ref);\n } else {\n syms.set(symbol, [ref]);\n }\n };\n\n for (const file of listSourceFiles(rootDir, opts.limit)) {\n let text: string;\n try {\n text = readFileSync(file, 'utf8');\n } catch {\n continue;\n }\n const rel = relative(rootDir, file);\n const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true);\n const lineOf = (n: ts.Node) => sf.getLineAndCharacterOfPosition(n.getStart(sf)).line + 1;\n\n // Two binding maps, because member reads mean different things:\n // a namespace/CJS binding IS the module's exports; a default binding is a\n // VALUE that happens to have properties.\n const nsBindings = new Map<string, { pkg: string; spec: string }>();\n const defaultBindings = new Map<string, { pkg: string; spec: string }>();\n // Named imports whose properties get read: `import { z } from 'zod'` then\n // `z.string()`. Tracked separately from the other two because whether the\n // member is a claim about the module surface depends on what the parent\n // export turns out to be, and only the scorer can see that.\n const namedBindings = new Map<string, { pkg: string; spec: string; exported: string }>();\n\n // Identifiers used in VALUE position. A named import used only in type\n // position (`(req: Request) => …`) is erased by TypeScript and never\n // reaches runtime, so it asserts nothing about the runtime surface.\n // `import express, { Request, Response } from 'express'` is correct code;\n // counting Request/Response as runtime symbols reports a miss on it.\n const valueUsed = collectValueIdentifiers(sf);\n\n const visit = (node: ts.Node): void => {\n // ── ESM imports ──\n if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {\n const pkg = packageOfSpecifier(node.moduleSpecifier.text);\n if (pkg) {\n const clause = node.importClause;\n if (clause?.name) {\n record(pkg, 'default', 'default', node.moduleSpecifier.text, rel, lineOf(clause.name));\n defaultBindings.set(clause.name.text, { pkg, spec: node.moduleSpecifier.text });\n }\n if (clause?.namedBindings) {\n if (ts.isNamespaceImport(clause.namedBindings)) {\n nsBindings.set(clause.namedBindings.name.text, { pkg, spec: node.moduleSpecifier.text });\n } else {\n for (const el of clause.namedBindings.elements) {\n const local = el.name.text;\n const exported = el.propertyName?.text ?? local;\n const typeOnly = clause.isTypeOnly || el.isTypeOnly || !valueUsed.has(local);\n record(\n pkg,\n exported,\n typeOnly ? 'type-only' : 'named',\n node.moduleSpecifier.text,\n rel,\n lineOf(el),\n );\n if (!typeOnly) {\n namedBindings.set(local, {\n pkg,\n spec: node.moduleSpecifier.text,\n exported,\n });\n }\n }\n }\n }\n }\n }\n\n // ── CJS require ──\n if (\n ts.isVariableDeclaration(node) &&\n node.initializer &&\n ts.isCallExpression(node.initializer) &&\n ts.isIdentifier(node.initializer.expression) &&\n node.initializer.expression.text === 'require' &&\n node.initializer.arguments.length === 1 &&\n ts.isStringLiteral(node.initializer.arguments[0]!)\n ) {\n const spec = (node.initializer.arguments[0] as ts.StringLiteral).text;\n const pkg = packageOfSpecifier(spec);\n if (pkg) {\n if (ts.isIdentifier(node.name)) {\n // In CJS the binding IS module.exports, so member reads are export\n // claims — unless module.exports is a bare value, which the scorer\n // detects from the surface shape rather than guessing here.\n nsBindings.set(node.name.text, { pkg, spec });\n record(pkg, 'default', 'default', spec, rel, lineOf(node.name));\n } else if (ts.isObjectBindingPattern(node.name)) {\n for (const el of node.name.elements) {\n const name = el.propertyName ?? el.name;\n if (ts.isIdentifier(name)) record(pkg, name.text, 'destructured', spec, rel, lineOf(el));\n }\n }\n }\n }\n\n // ── member reads on a bound namespace/default/named import ──\n if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression)) {\n const local = node.expression.text;\n const ns = nsBindings.get(local);\n const def = defaultBindings.get(local);\n const named = namedBindings.get(local);\n if (ns) record(ns.pkg, node.name.text, 'namespace', ns.spec, rel, lineOf(node));\n else if (def) record(def.pkg, node.name.text, 'default-member', def.spec, rel, lineOf(node));\n else if (named) {\n record(\n named.pkg,\n node.name.text,\n 'named-member',\n named.spec,\n rel,\n lineOf(node),\n named.exported,\n );\n }\n }\n\n ts.forEachChild(node, visit);\n };\n visit(sf);\n }\n\n return [...byPackage.entries()]\n .map(([pkg, symbols]) => ({ package: pkg, symbols }))\n .sort((a, b) => a.package.localeCompare(b.package));\n}\n","/**\n * `check_upgrade` (§8.1) — the team product's core call, and the first surface\n * with a plausible payer.\n *\n * The wedge, stated exactly: *Renovate and Dependabot catch what your tests\n * cover; lurq catches what your code references.* Existing tooling gates an\n * upgrade on a test suite, so if coverage misses the affected path the PR merges\n * green and breaks in production. This check needs no tests at all — it compares\n * the symbols the codebase actually references against the runtime surface of\n * the target version.\n *\n * Severity is deliberately blunt:\n * BLOCKING — a referenced symbol disappears. The code will throw.\n * WARNING — a referenced symbol changed arity. It may silently misbehave.\n * OK — nothing referenced is affected.\n *\n * Anything we could not establish is `unverified`, never folded into OK. A check\n * that reports \"safe\" when it simply did not look is worse than no check, and it\n * is how a CI gate loses its credibility in one incident.\n */\nimport { fetchAndExtract } from './fetch';\nimport { diffSurfaces } from './diff';\nimport { SURFACE_CLAIM_KINDS } from './references';\nimport type { PackageReferences, SymbolReference } from './references';\nimport { runtimeSymbols, type ExtractedSurface, type SymbolKind } from './types';\n\nexport interface UpgradeTarget {\n package: string;\n fromVersion: string;\n toVersion: string;\n}\n\nexport interface BreakingFinding {\n package: string;\n fromVersion: string;\n toVersion: string;\n severity: 'blocking' | 'warning';\n /** Referenced symbols removed at the target version. `specifier` names the\n * entry point they were imported from. Absent means the package root. */\n symbolsRemoved: { symbol: string; specifier?: string; refs: SymbolReference[] }[];\n arityChanged: {\n symbol: string;\n specifier?: string;\n from: number | null;\n to: number | null;\n refs: SymbolReference[];\n }[];\n /**\n * Runtime exports that exist at the target version and did not at the source\n * — the verified candidates for whatever replaced `symbolsRemoved`.\n *\n * This is the other half of the answer and it used to be computed and thrown\n * away. Knowing `renderToString` disappeared does not tell an agent to reach\n * for `renderToPipeableStream`; the agent that rewrites the call sites runs\n * with no network tool and no MCP access, so without this list its only source\n * for a replacement is the training data whose staleness is the entire reason\n * lurq exists. Extracted from the target's own shipped JS, so it is a fact\n * about the package rather than a recollection.\n *\n * Same-kind-as-something-removed first, then alphabetical, then capped: a\n * package can add hundreds of exports and this rides inside a brief a model\n * has to read.\n */\n newExports: { symbol: string; kind: SymbolKind; arity: number | null }[];\n}\n\n/** How many candidate replacements travel with one finding. Enough to contain\n * the real replacement, small enough to stay legible inside the brief. */\nconst NEW_EXPORT_CAP = 40;\n\nexport interface UpgradeReport {\n safe: boolean;\n breaking: BreakingFinding[];\n /** Packages checked with nothing referenced affected. */\n ok: string[];\n /** Could not be established — NEVER counted as safe. */\n unverified: { package: string; reason: string }[];\n}\n\n/**\n * Split a package's references by the entry point they were imported from.\n * The key is the subpath (`pg-core`), or `''` for the package root.\n *\n * This grouping is the whole of the subpath fix. `drizzle-orm/pg-core` is a\n * different module with a different export surface than `drizzle-orm`, and the\n * check used to keep only root-specifier references, so a repo importing\n * `pgTable` from the subpath had those symbols silently discarded, and a package\n * whose every use was a subpath import was compared against an empty reference\n * set and reported OK. In this repo that was 40% of all references.\n */\nfunction groupByEntry(\n refs: PackageReferences,\n pkg: string,\n): Map<string, Map<string, SymbolReference[]>> {\n const byEntry = new Map<string, Map<string, SymbolReference[]>>();\n for (const [sym, uses] of refs.symbols) {\n for (const use of uses) {\n if (use.specifier !== pkg && !use.specifier.startsWith(`${pkg}/`)) continue;\n const sub = use.specifier === pkg ? '' : use.specifier.slice(pkg.length + 1);\n let symbols = byEntry.get(sub);\n if (!symbols) byEntry.set(sub, (symbols = new Map()));\n const list = symbols.get(sym);\n if (list) list.push(use);\n else symbols.set(sym, [use]);\n }\n }\n return byEntry;\n}\n\n/** Runtime exports of `surface` whose value is a plain object. */\nfunction objectPaths(surface: ExtractedSurface): Set<string> {\n return new Set(\n runtimeSymbols(surface)\n .filter((s) => s.kind === 'object')\n .map((s) => s.path),\n );\n}\n\n/**\n * Does a `named-member` read assert something about the module's export surface?\n *\n * Exported and kept tiny because it is the money path: a wrong `true` here is a\n * BLOCKING result on correct code, which is the §12 M3 kill condition.\n *\n * True only for a namespace-shaped parent: an exported object that groups the\n * same names the module also exports at the top level. zod is the case that\n * drove this, and `z.string` and the top-level `string` are the same function.\n * Requiring `object` in BOTH versions keeps `vi.fn()` and `expect.any()` out,\n * since those parents are not object exports at all. The remaining guard is\n * implicit at the call site: only `diff.removed` is consulted, so a property\n * that was never a top-level export of the from-version cannot be reached.\n */\nexport function isNamespaceMemberClaim(\n ref: SymbolReference,\n fromObjects: Set<string>,\n toObjects: Set<string>,\n): boolean {\n if (ref.via !== 'named-member' || ref.parent === undefined) return false;\n return fromObjects.has(ref.parent) && toObjects.has(ref.parent);\n}\n\ninterface EntryComparison {\n symbolsRemoved: BreakingFinding['symbolsRemoved'];\n arityChanged: BreakingFinding['arityChanged'];\n candidates: BreakingFinding['newExports'];\n lostKinds: Set<SymbolKind>;\n}\n\n/** Compare one entry point's from/to surfaces against the symbols read from it. */\nfunction compareEntry(\n from: ExtractedSurface | undefined,\n to: ExtractedSurface | undefined,\n symbols: Map<string, SymbolReference[]>,\n specifier: string,\n isRoot: boolean,\n): EntryComparison | { unverified: string } {\n if (!from || !to) return { unverified: 'entry point not extracted' };\n if (from.undeclaredReason || to.undeclaredReason) {\n return { unverified: `no readable surface (${from.undeclaredReason ?? to.undeclaredReason})` };\n }\n\n const diff = diffSurfaces(from, to);\n if (diff.inconclusive) return { unverified: diff.inconclusive };\n\n // Only symbols claimed against the MODULE'S export surface can be \"removed\".\n // `chalk.bold` is a property of the default export's value — valid code that\n // tier A cannot see. Blocking a PR on that is the false positive that gets a\n // CI gate switched off inside two weeks (§12 M3 kill condition).\n const toSurface = new Set(runtimeSymbols(to).map((s) => s.path));\n const bareValue = toSurface.size <= 1 && toSurface.has('default');\n\n // ...and `z.string` can be one too, when the parent is namespace-shaped. See\n // isNamespaceMemberClaim for which parents qualify and why.\n const objectExports = objectPaths(from);\n const toObjects = objectPaths(to);\n const throughNamespaceObject = (r: SymbolReference): boolean =>\n isNamespaceMemberClaim(r, objectExports, toObjects);\n\n const referenced = new Set(\n [...symbols.entries()]\n .filter(\n ([sym, uses]) =>\n sym !== 'default' &&\n uses.some(\n (r) =>\n (SURFACE_CLAIM_KINDS.includes(r.via) && !(bareValue && r.via === 'namespace')) ||\n throughNamespaceObject(r),\n ),\n )\n .map(([sym]) => sym),\n );\n\n // `specifier` rides along only for subpaths, so root findings serialize\n // exactly as they did before this change.\n const tag = isRoot ? {} : { specifier };\n return {\n symbolsRemoved: diff.removed\n .filter((s) => referenced.has(s.path) && !toSurface.has(s.path))\n .map((s) => ({ symbol: s.path, ...tag, refs: symbols.get(s.path) ?? [] })),\n arityChanged: diff.arityChanged\n .filter((a) => referenced.has(a.path))\n .map((a) => ({\n symbol: a.path,\n ...tag,\n from: a.from,\n to: a.to,\n refs: symbols.get(a.path) ?? [],\n })),\n // The target's whole surface, not just what it added: a rename that shipped\n // the new name a major early leaves `diff.added` empty. `default` is never a\n // useful candidate, and the caller drops anything it just reported removed.\n candidates: runtimeSymbols(to)\n .filter((s) => s.path !== 'default')\n .map((s) => ({ symbol: s.path, kind: s.kind, arity: s.arity })),\n lostKinds: new Set(diff.removed.filter((s) => referenced.has(s.path)).map((s) => s.kind)),\n };\n}\n\n/**\n * Check one upgrade against what the codebase references.\n *\n * Only symbols the code actually uses are reported. A package can drop fifty\n * exports; if this codebase touches none of them, the upgrade is safe FOR THIS\n * CODEBASE, and saying otherwise trains people to ignore the check.\n *\n * Returns both channels rather than one of three, because a package can be\n * breaking on one entry point and unreadable on another: `drizzle-orm` can lose\n * a root symbol while `drizzle-orm/pg-core` fails to resolve. Collapsing that to\n * a single verdict has to discard one of the two facts, and discarding the\n * doubt is how the check ends up reporting safe when it did not look.\n */\nexport async function checkUpgradeOne(\n target: UpgradeTarget,\n refs: PackageReferences | undefined,\n): Promise<{ finding?: BreakingFinding; unverified?: string }> {\n if (!refs || refs.symbols.size === 0) return {};\n\n const byEntry = groupByEntry(refs, target.package);\n if (byEntry.size === 0) return {};\n const subpaths = [...byEntry.keys()].filter(Boolean);\n\n const [from, to] = await Promise.all([\n fetchAndExtract(target.package, target.fromVersion, { subpaths }),\n fetchAndExtract(target.package, target.toVersion, { subpaths }),\n ]);\n if (!from || !to) return { unverified: 'could not fetch one or both versions' };\n\n const symbolsRemoved: BreakingFinding['symbolsRemoved'] = [];\n const arityChanged: BreakingFinding['arityChanged'] = [];\n const candidates: BreakingFinding['newExports'] = [];\n const lostKinds = new Set<SymbolKind>();\n const blind: string[] = [];\n\n for (const [sub, symbols] of byEntry) {\n const specifier = sub ? `${target.package}/${sub}` : target.package;\n const res = compareEntry(\n sub ? from.subpathSurfaces?.[sub] : from.surface,\n sub ? to.subpathSurfaces?.[sub] : to.surface,\n symbols,\n specifier,\n !sub,\n );\n if ('unverified' in res) {\n blind.push(byEntry.size === 1 ? res.unverified : `${specifier}: ${res.unverified}`);\n continue;\n }\n symbolsRemoved.push(...res.symbolsRemoved);\n arityChanged.push(...res.arityChanged);\n candidates.push(...res.candidates);\n for (const k of res.lostKinds) lostKinds.add(k);\n }\n\n const unverified = blind.length ? blind.join('; ') : undefined;\n if (!symbolsRemoved.length && !arityChanged.length) {\n return unverified ? { unverified } : {};\n }\n\n // Candidates are what the TARGET exports, not what it added.\n //\n // This read `diff.added` — symbols present at the target and absent at the\n // source. That is right for \"the library grew a new API\" and wrong for the\n // commonest rename there is: ship the new name, let both live, remove the old\n // one a major later. cookie did exactly that. Going 1.1.1 → 2.0.1 removes\n // `parse` and `serialize`, and `parseCookie` and `stringifyCookie` — the\n // things you are supposed to call instead — had been exported since 1.x. So\n // `diff.added` was empty, and a caller holding a blocking finding got\n // `\"newExports\": []`: told what broke, told nothing about what to write.\n //\n // The model does the mapping, and does it well, given the candidates. It\n // cannot do it from an empty array. So this hands over the target's surface\n // and leaves the choice where it belongs; there is deliberately no matcher\n // here, because `parse(str, options?)` → `parseCookie(str, options?)` is not\n // a problem that needs one.\n //\n // Ranking survives as a retrieval filter rather than an answer. Surfaces run\n // to 129 exports for react-router and 240 for zod, so the cap is real and\n // what it keeps matters: symbols whose kind matches something this codebase\n // just lost come first, so a removed function is not pushed out by constants.\n //\n // Collected per entry point, so a package used through several of them offers\n // candidates from each. Deduped on the symbol name: `lostKinds` and the cap\n // both count distinct names, and two entry points can re-export one.\n const removedNames = new Set(symbolsRemoved.map((s) => s.symbol));\n const seen = new Set<string>();\n const newExports = candidates\n .filter((c) => !removedNames.has(c.symbol) && !seen.has(c.symbol) && seen.add(c.symbol))\n .sort(\n (a, b) =>\n Number(lostKinds.has(b.kind)) - Number(lostKinds.has(a.kind)) ||\n a.symbol.localeCompare(b.symbol),\n )\n .slice(0, NEW_EXPORT_CAP);\n\n return {\n finding: {\n package: target.package,\n fromVersion: target.fromVersion,\n toVersion: target.toVersion,\n severity: symbolsRemoved.length ? 'blocking' : 'warning',\n symbolsRemoved,\n arityChanged,\n newExports,\n },\n ...(unverified ? { unverified } : {}),\n };\n}\n\nexport async function checkUpgrade(\n targets: UpgradeTarget[],\n references: PackageReferences[],\n): Promise<UpgradeReport> {\n const byPkg = new Map(references.map((r) => [r.package, r]));\n const breaking: BreakingFinding[] = [];\n const ok: string[] = [];\n const unverified: UpgradeReport['unverified'] = [];\n\n for (const t of targets) {\n try {\n const res = await checkUpgradeOne(t, byPkg.get(t.package));\n if (res.finding) breaking.push(res.finding);\n if (res.unverified) unverified.push({ package: t.package, reason: res.unverified });\n if (!res.finding && !res.unverified) ok.push(t.package);\n } catch (err) {\n unverified.push({ package: t.package, reason: String(err).slice(0, 160) });\n }\n }\n\n return {\n // `safe` requires that nothing broke AND nothing was left unchecked.\n safe: breaking.length === 0 && unverified.length === 0,\n breaking,\n ok,\n unverified,\n };\n}\n\n/** Candidates listed in the text report. The full set stays in the JSON; this\n * keeps the report to the one screen §9.0 asks for. */\nconst REPORT_CANDIDATE_CAP = 8;\n\n/** The §9.0 report: fits on one screen, names files and lines. */\nexport function formatUpgradeReport(report: UpgradeReport, title = 'upgrade check'): string {\n const out: string[] = [`lurq, ${title}`, ''];\n\n for (const b of report.breaking.sort((a, z) => (a.severity === 'blocking' ? -1 : 1))) {\n const label = b.severity === 'blocking' ? 'BLOCKING' : 'WARNING ';\n out.push(`${label} ${b.package} ${b.fromVersion} → ${b.toVersion}`);\n if (b.symbolsRemoved.length) {\n out.push(` Removes ${b.symbolsRemoved.length} symbol(s) your code references:`);\n for (const s of b.symbolsRemoved) {\n const where = s.refs.map((r) => `${r.file}:${r.line}`).join(', ') || '(no location)';\n out.push(` · ${s.specifier ?? b.package}.${s.symbol} ${where}`);\n }\n }\n for (const a of b.arityChanged) {\n const where = a.refs.map((r) => `${r.file}:${r.line}`).join(', ') || '(no location)';\n out.push(` Arity change: ${a.specifier ?? b.package}.${a.symbol} ${a.from} → ${a.to} params`);\n out.push(` · ${where}`);\n }\n // The reader's next question is always \"replaced by what\", so answer it here\n // rather than making them open the JSON. Named as candidates, not as a\n // mapping: these are the exports the target version gained, and which one\n // replaces which is a judgement this diff cannot make.\n if (b.symbolsRemoved.length && b.newExports.length) {\n const shown = b.newExports.slice(0, REPORT_CANDIDATE_CAP);\n const more = b.newExports.length - shown.length;\n out.push(\n ` New at ${b.toVersion}, candidate replacements: ${shown.map((n) => n.symbol).join(', ')}${more > 0 ? ` (+${more} more)` : ''}`,\n );\n }\n out.push('');\n }\n\n if (report.unverified.length) {\n out.push(`UNVERIFIED ${report.unverified.length} package(s), not checked, NOT declared safe:`);\n for (const u of report.unverified) out.push(` · ${u.package}: ${u.reason}`);\n out.push('');\n }\n\n if (report.ok.length) {\n out.push(`OK ${report.ok.length} package(s), no referenced symbols removed`);\n }\n if (!report.breaking.length && !report.unverified.length) {\n out.push('', 'No referenced symbols are removed by these upgrades.');\n }\n return out.join('\\n');\n}\n","/**\n * `lurq check-upgrade` — the CI gate.\n *\n * Narrows an upgrade plan down to what this codebase actually references. The\n * plan says react-router 6→8 removes `useHistory`; this says whether *you* call\n * it, and where. That intersection is the product, and it deliberately runs\n * where the source already is: nothing read here is ever transmitted.\n *\n * It also needs no lurq API key and no test suite. Surfaces come straight from\n * the npm tarballs of both versions, so the gate keeps working when our API is\n * down, and it catches breakage in code no test covers — which is precisely the\n * gap that lets a green Dependabot PR fail in production.\n */\nimport { readFileSync } from 'node:fs';\nimport type { UpgradeTarget } from '../surface/upgrade';\n\n/** `pkg@from..to`, the repeatable `--upgrade` form. */\nexport function parseUpgradeSpec(spec: string): UpgradeTarget {\n const at = spec.lastIndexOf('@');\n const name = spec.slice(0, at);\n const [fromVersion, toVersion] = spec.slice(at + 1).split('..');\n if (!name || !fromVersion || !toVersion) {\n throw new Error(`bad --upgrade '${spec}', expected pkg@from..to`);\n }\n return { package: name, fromVersion, toVersion };\n}\n\n/** Shape of the `upgrade-plan --json` file, as far as this command cares. */\ninterface PlanFile {\n upgrades?: {\n package: string;\n fromVersion: string;\n toVersion: string;\n /** Repo-policy eligibility, when the plan was governed. */\n inScope?: boolean;\n }[];\n}\n\n/** Read targets from a plan produced by `lurq upgrade-plan --json`. */\nexport function targetsFromPlanFile(path: string): UpgradeTarget[] {\n // A plan file is written by one command and read by another, usually across\n // two CI steps. When step one fails the file is missing or empty, and the bare\n // `Unexpected end of JSON input` that fell out of JSON.parse named neither the\n // file nor the step that should have written it.\n let text: string;\n try {\n text = readFileSync(path, 'utf8');\n } catch (err) {\n const why = (err as NodeJS.ErrnoException).code === 'ENOENT' ? 'does not exist' : String(err);\n throw new Error(`plan file ${path} ${why}. Did \\`lurq upgrade-plan --json\\` run?`);\n }\n if (!text.trim()) {\n throw new Error(`plan file ${path} is empty. Did \\`lurq upgrade-plan --json\\` run?`);\n }\n let parsed: PlanFile;\n try {\n parsed = JSON.parse(text) as PlanFile;\n } catch (err) {\n throw new Error(`plan file ${path} is not valid JSON: ${(err as Error).message}`);\n }\n if (!Array.isArray(parsed.upgrades)) {\n throw new Error(`${path} is not an upgrade plan (no \"upgrades\" array)`);\n }\n return parsed.upgrades\n .filter((u) => u.package && u.fromVersion && u.toVersion)\n // `!== false` rather than a truthy test: a plan from a server that predates\n // scope enforcement has no `inScope` key at all, and an absent policy must\n // mean \"ungoverned\", never \"excluded\". Getting this backwards would empty\n // the brief on every older deployment.\n .filter((u) => u.inScope !== false)\n .map((u) => ({ package: u.package, fromVersion: u.fromVersion, toVersion: u.toVersion }));\n}\n\nexport interface CheckUpgradeOpts {\n upgrade?: string[];\n plan?: string;\n json?: boolean;\n exitCode?: boolean;\n /** Post what this run concluded to the dashboard (CI only; needs an API key). */\n report?: boolean;\n url?: string;\n apiKey?: string;\n}\n\n/**\n * Post the report, and never let doing so change the outcome of the check.\n *\n * Reporting is telemetry hung off a gate whose entire value is that it works\n * with no API key, no network to us, and no test suite. A failure here — no key,\n * our API down, a runner with no egress — must therefore degrade to a printed\n * line on stderr and nothing else. Failing the build because a dashboard write\n * did not land would trade the feature for the thing it is decorating.\n */\nasync function reportOutcome(\n report: Awaited<ReturnType<typeof import('../surface/upgrade')['checkUpgrade']>>,\n targets: UpgradeTarget[],\n opts: CheckUpgradeOpts,\n): Promise<void> {\n const { buildRunReports, runContextFromEnv } = await import('./reportRuns');\n const ctx = runContextFromEnv();\n if (!ctx) {\n console.error('--report: no $GITHUB_REPOSITORY, so there is no run to attribute this to. Skipped.');\n return;\n }\n const runs = buildRunReports(report, targets, ctx);\n if (runs.length === 0) return;\n try {\n const { reportUpgradeRuns } = await import('./remote');\n const { recorded, rejected } = await reportUpgradeRuns(runs, {\n url: opts.url,\n apiKey: opts.apiKey,\n });\n console.error(\n `reported ${recorded} upgrade result(s) to the lurq dashboard` +\n (rejected ? ` (${rejected} rejected)` : ''),\n );\n } catch (err) {\n // A missing key and an unreachable API are both non-fatal here, but they\n // need different sentences: one is \"add LURQ_API_KEY to your repo secrets\",\n // the other is \"nothing for you to do\". Reporting both as \"could not reach\"\n // is how a fixable setup mistake looks like our outage.\n const message = err instanceof Error ? err.message : String(err);\n const noKey = /no api key/i.test(message);\n console.error(\n noKey\n ? '--report: no API key, so there was nothing to report with. Set LURQ_API_KEY in this repository\\'s secrets to see these results on your dashboard. The check itself is unaffected.'\n : `--report: could not reach the lurq dashboard (${message}). The check itself is unaffected.`,\n );\n }\n}\n\nexport async function runCheckUpgrade(dir: string, opts: CheckUpgradeOpts): Promise<void> {\n const { scanReferences } = await import('../surface/references');\n const { checkUpgrade, formatUpgradeReport } = await import('../surface/upgrade');\n\n const targets = [\n ...(opts.plan ? targetsFromPlanFile(opts.plan) : []),\n ...(opts.upgrade ?? []).map(parseUpgradeSpec),\n ];\n if (targets.length === 0) {\n // An empty plan is a legitimate \"nothing to do\", not a usage error — CI must\n // not fail a scheduled run just because the repo is already up to date.\n if (opts.plan) {\n const empty = { safe: true, breaking: [], ok: [], unverified: [] };\n console.log(opts.json ? JSON.stringify(empty, null, 2) : 'Nothing to check.');\n return;\n }\n throw new Error('give --plan <file> or at least one --upgrade pkg@from..to');\n }\n\n const refs = scanReferences(dir);\n const report = await checkUpgrade(targets, refs);\n\n console.log(\n opts.json\n ? JSON.stringify(report, null, 2)\n : formatUpgradeReport(report, `upgrade check on ${dir}`),\n );\n // Before the exit code, so the report lands even on a run this gate fails —\n // a blocked upgrade is the single most useful row the dashboard can show.\n if (opts.report) await reportOutcome(report, targets, opts);\n if (opts.exitCode && !report.safe) process.exitCode = 1;\n}\n","/**\n * Release check — semver stated vs semver earned.\n *\n * Every other surface consumer in this tree points the diff *outward*: what did\n * a dependency remove, and does our code touch it. This points it at the author:\n * compare the working tree's built surface against the last version this package\n * published, and say whether the version number about to be tagged is honest.\n *\n * Nothing new is measured. `diffSurfaces` already answers \"what disappeared\n * between two surfaces\"; the only addition is that one side comes from a local\n * directory instead of a registry tarball, and that the answer is mapped onto a\n * semver level. A package author is the one person who can prevent a breaking\n * change from shipping as a patch, and today nothing tells them they are about\n * to — `npm publish` will happily tag a deleted export as 1.2.4.\n *\n * Runs entirely on the author's machine against a registry tarball: no API key,\n * no database, nothing about their code leaves the process.\n */\nimport semver from 'semver';\nimport { diffSurfaces, type ArityChange } from './diff';\nimport { fetchAndExtract } from './fetch';\nimport { readManifest } from './resolve';\nimport type { ExtractedSurface } from './types';\n\n/** Semver levels, ordered. `patch` is the floor: publishing needs *some* bump. */\nexport type Bump = 'patch' | 'minor' | 'major';\nconst RANK: Record<Bump, number> = { patch: 0, minor: 1, major: 2 };\n\nexport interface ReleaseCheck {\n package: string;\n /** The published version compared against — the baseline. */\n publishedVersion: string | null;\n /** The version in the working tree's package.json. */\n localVersion: string | null;\n /** The bump the version field claims, or null when it is not a bump at all. */\n declared: Bump | null;\n /** The smallest bump the surface change actually justifies. */\n required: Bump;\n verdict: 'ok' | 'understated' | 'inconclusive';\n /** Runtime exports present in the published version and gone locally. */\n removed: string[];\n /** Exports whose parameter count changed — a break for positional callers. */\n arityChanged: ArityChange[];\n /** Removed types. Breaks `tsc` for consumers, not `node`; still a major. */\n typeOnlyRemoved: string[];\n added: string[];\n /** Set when no verdict could be reached. Never read the arrays if present. */\n inconclusive?: string;\n}\n\n/**\n * The bump the two version strings describe, by their numeric components.\n *\n * Deliberately not `semver.diff`, which answers with `premajor`/`prepatch`/\n * `prerelease` for anything carrying a tag — `2.0.0-rc.1` declares a major and\n * has to be read as one, or every release candidate reports as understated.\n * Returns null when the local version is not ahead, which is its own defect\n * worth naming rather than folding into `patch`.\n */\nfunction declaredBump(from: string, to: string): Bump | null {\n if (!semver.gt(to, from)) return null;\n if (semver.major(to) !== semver.major(from)) return 'major';\n if (semver.minor(to) !== semver.minor(from)) return 'minor';\n return 'patch';\n}\n\n/**\n * Does `declared` cover `required`?\n *\n * Below 1.0.0 the channels shift down one: the ecosystem reads `0.x` minor as\n * the breaking channel (npm's own caret range encodes this — `^0.2.0` refuses\n * `0.3.0`), so a minor bump is a legitimate way to ship a break at 0.x. Applying\n * the 1.x rule there would flag most pre-1.0 releases and get the check muted.\n */\nfunction covers(declared: Bump, required: Bump, baselineMajor: number): boolean {\n if (baselineMajor === 0 && required === 'major') return RANK[declared] >= RANK.minor;\n return RANK[declared] >= RANK[required];\n}\n\n/**\n * The whole judgement, as a pure function of two version strings and the shape\n * of the diff. Split out from `checkRelease` because everything else in that\n * function is I/O — this is the part with rules in it, and the part worth a test\n * that does not need a registry.\n */\nexport function releaseVerdict(\n publishedVersion: string,\n localVersion: string,\n diff: {\n removed: unknown[];\n arityChanged: unknown[];\n typeOnlyRemoved: unknown[];\n added: unknown[];\n },\n): Pick<ReleaseCheck, 'declared' | 'required' | 'verdict'> {\n const required: Bump =\n diff.removed.length || diff.arityChanged.length || diff.typeOnlyRemoved.length\n ? 'major'\n : diff.added.length\n ? 'minor'\n : 'patch';\n const declared = declaredBump(publishedVersion, localVersion);\n const verdict =\n declared !== null && covers(declared, required, semver.major(publishedVersion))\n ? 'ok'\n : 'understated';\n return { declared, required, verdict };\n}\n\nconst inconclusive = (\n base: Pick<ReleaseCheck, 'package' | 'publishedVersion' | 'localVersion'>,\n reason: string,\n): ReleaseCheck => ({\n ...base,\n declared: null,\n required: 'patch',\n verdict: 'inconclusive',\n removed: [],\n arityChanged: [],\n typeOnlyRemoved: [],\n added: [],\n inconclusive: reason,\n});\n\n/**\n * Compare a working tree against its last published version.\n *\n * `extractSurface` reads the entry point the manifest declares, which for a\n * built package is `dist/` — so an unbuilt tree yields no entry and returns\n * inconclusive rather than an empty surface. That distinction is load-bearing:\n * an empty extraction compared against a real one would report every export as\n * removed, which is the §6.4.2 defect this codebase already refuses elsewhere.\n */\nexport async function checkRelease(\n dir: string,\n opts: { against?: string; fetchImpl?: typeof fetch } = {},\n): Promise<ReleaseCheck> {\n const manifest = readManifest(dir);\n const name = manifest?.name;\n const base = {\n package: name ?? dir,\n publishedVersion: null,\n localVersion: manifest?.version ?? null,\n };\n if (!name) return inconclusive(base, `no readable package.json in ${dir}`);\n if (!manifest.version) return inconclusive(base, 'package.json has no version field');\n\n const { extractSurface } = await import('./extract');\n const local: ExtractedSurface = extractSurface(dir, { manifest });\n if (local.undeclaredReason) {\n return inconclusive(base, `${local.undeclaredReason} — build the package first`);\n }\n\n const published = await fetchAndExtract(name, opts.against ?? 'latest', {\n fetchImpl: opts.fetchImpl,\n });\n if (!published) {\n return inconclusive(base, `${name} has no published version to compare against`);\n }\n\n const withVersion = { ...base, publishedVersion: published.resolvedVersion };\n const diff = diffSurfaces(published.surface, local);\n if (diff.inconclusive) return inconclusive(withVersion, diff.inconclusive);\n\n return {\n ...withVersion,\n ...releaseVerdict(published.resolvedVersion, manifest.version, diff),\n removed: diff.removed.map((s) => s.path),\n arityChanged: diff.arityChanged,\n typeOnlyRemoved: diff.typeOnlyRemoved.map((s) => s.path),\n added: diff.added.map((s) => s.path),\n };\n}\n\n/** Symbols listed before the report starts summarising. */\nconst LIST_CAP = 12;\n\nconst list = (label: string, items: string[]): string[] => {\n if (!items.length) return [];\n const shown = items.slice(0, LIST_CAP);\n const more = items.length - shown.length;\n return [\n ` ${label} (${items.length}):`,\n ...shown.map((s) => ` · ${s}`),\n ...(more > 0 ? [` … ${more} more`] : []),\n ];\n};\n\nexport function formatReleaseCheck(c: ReleaseCheck): string {\n const out = [`lurq, release check — ${c.package}`, ''];\n\n if (c.verdict === 'inconclusive') {\n out.push(`INCONCLUSIVE ${c.inconclusive}`, '', 'No verdict. This is not a pass.');\n return out.join('\\n');\n }\n\n const from = c.publishedVersion ?? '?';\n const to = c.localVersion ?? '?';\n out.push(\n c.verdict === 'ok'\n ? c.declared === c.required\n ? `OK ${from} → ${to} is a ${c.declared}, which is what this API change needs.`\n : `OK ${from} → ${to} is a ${c.declared}; this API change only needed a ${c.required}.`\n : c.declared === null\n ? `UNDERSTATED ${to} is not ahead of the published ${from}.`\n : `UNDERSTATED ${from} → ${to} is tagged ${c.declared}, but this API change is a ${c.required}.`,\n '',\n );\n\n out.push(...list('Removed exports', c.removed));\n if (c.arityChanged.length) {\n out.push(` Parameter count changed (${c.arityChanged.length}):`);\n for (const a of c.arityChanged.slice(0, LIST_CAP)) {\n out.push(` · ${a.path} ${a.from} → ${a.to}`);\n }\n }\n out.push(...list('Removed types (breaks tsc, not node)', c.typeOnlyRemoved));\n out.push(...list('Added exports', c.added));\n\n if (!c.removed.length && !c.arityChanged.length && !c.typeOnlyRemoved.length && !c.added.length) {\n out.push(' No change to the exported surface.');\n }\n return out.join('\\n');\n}\n","/**\n * Diff two OpenAPI surfaces and rule on the version.\n *\n * The package side of lurq answers \"will this upgrade break my code\". This is the\n * same question asked by the other party: will this change break the people\n * calling me. Nothing else in the ecosystem holds both halves, and the mechanics\n * are identical — reduce each side to the promises it makes, subtract, and\n * classify what disappeared.\n *\n * The classification is deliberately narrow. Only changes that break a caller who\n * did nothing wrong move the verdict; everything else is reported and ignored by\n * the ruling. A check that flags a new optional field as breaking gets switched\n * off within a week, and a switched-off check catches nothing.\n */\nimport semver from 'semver';\nimport type { ApiSurface, Operation } from './openapi';\n\nexport type ChangeKind =\n | 'operation-removed'\n | 'required-param-added'\n | 'param-now-required'\n | 'required-body-field-added'\n | 'response-removed'\n | 'operation-added'\n | 'optional-param-added'\n | 'response-added'\n | 'operation-deprecated';\n\n/** Which changes break a caller that changed nothing. The verdict reads only these. */\nconst BREAKING: ReadonlySet<ChangeKind> = new Set([\n 'operation-removed',\n 'required-param-added',\n 'param-now-required',\n 'required-body-field-added',\n 'response-removed',\n]);\n\nexport interface ApiChange {\n kind: ChangeKind;\n /** The operation this is about: `POST /v1/charges`. */\n operation: string;\n /** The parameter, field or status code, when the change is about one. */\n detail?: string;\n breaking: boolean;\n}\n\nexport interface ApiDiff {\n /** Changes that break existing callers. */\n breaking: ApiChange[];\n /** Additive and informational changes. Never moves the verdict. */\n other: ApiChange[];\n /** Set when no comparison could be made; the arrays are meaningless if present. */\n inconclusive?: string;\n}\n\nconst change = (kind: ChangeKind, operation: string, detail?: string): ApiChange => ({\n kind,\n operation,\n ...(detail ? { detail } : {}),\n breaking: BREAKING.has(kind),\n});\n\n/** Set difference, `a` minus `b`. */\nconst missing = (a: string[], b: string[]): string[] => {\n const has = new Set(b);\n return a.filter((x) => !has.has(x));\n};\n\nfunction compareOperation(before: Operation, after: Operation): ApiChange[] {\n const out: ApiChange[] = [];\n\n // A required parameter that was not there before breaks every existing caller,\n // whether it is genuinely new or was optional yesterday. The two are reported\n // as different kinds because the fix differs — one is a new field to send, the\n // other is a field they may already be sending.\n for (const param of missing(after.requiredParams, before.requiredParams)) {\n out.push(\n change(\n before.optionalParams.includes(param) ? 'param-now-required' : 'required-param-added',\n after.id,\n param,\n ),\n );\n }\n for (const param of missing(after.optionalParams, before.optionalParams)) {\n out.push(change('optional-param-added', after.id, param));\n }\n for (const field of missing(after.requiredBodyFields, before.requiredBodyFields)) {\n out.push(change('required-body-field-added', after.id, field));\n }\n for (const code of missing(before.responseCodes, after.responseCodes)) {\n out.push(change('response-removed', after.id, code));\n }\n for (const code of missing(after.responseCodes, before.responseCodes)) {\n out.push(change('response-added', after.id, code));\n }\n // Deprecation is a promise to remove, not a removal. Reported so it is visible\n // in the same place, never counted as a break.\n if (after.deprecated && !before.deprecated) out.push(change('operation-deprecated', after.id));\n\n return out;\n}\n\nexport function diffApiSurfaces(before: ApiSurface, after: ApiSurface): ApiDiff {\n // Never rule from a surface we could not read. An unreadable `before` compared\n // against a real `after` would report the entire API as newly added; the other\n // way round it reports the whole API as deleted. Both are measurement failures\n // wearing a verdict.\n if (before.unreadableReason) return { breaking: [], other: [], inconclusive: `previous revision: ${before.unreadableReason}` };\n if (after.unreadableReason) return { breaking: [], other: [], inconclusive: `current revision: ${after.unreadableReason}` };\n\n const changes: ApiChange[] = [];\n for (const [id, op] of before.operations) {\n const next = after.operations.get(id);\n if (!next) {\n changes.push(change('operation-removed', id));\n continue;\n }\n changes.push(...compareOperation(op, next));\n }\n for (const id of after.operations.keys()) {\n if (!before.operations.has(id)) changes.push(change('operation-added', id));\n }\n\n return {\n breaking: changes.filter((c) => c.breaking),\n other: changes.filter((c) => !c.breaking),\n };\n}\n\nexport type ApiVerdict = 'ok' | 'breaking' | 'inconclusive';\n\nexport interface ApiCheck {\n title: string | null;\n fromVersion: string | null;\n toVersion: string | null;\n verdict: ApiVerdict;\n /**\n * Whether `info.version` was bumped enough for what changed.\n *\n * `null` when it cannot be judged — either version is missing, or they are not\n * both semver. Plenty of real APIs version by date (`2026-08-16`) or not at\n * all, and inventing a semver reading of those would be a confident wrong\n * answer about the one field teams actually argue over.\n */\n versionCovers: boolean | null;\n diff: ApiDiff;\n}\n\nexport function checkApi(before: ApiSurface, after: ApiSurface): ApiCheck {\n const diff = diffApiSurfaces(before, after);\n const base = {\n title: after.title ?? before.title,\n fromVersion: before.version,\n toVersion: after.version,\n diff,\n };\n if (diff.inconclusive) {\n return { ...base, verdict: 'inconclusive', versionCovers: null };\n }\n\n const from = before.version && semver.valid(before.version);\n const to = after.version && semver.valid(after.version);\n const versionCovers =\n from && to\n ? diff.breaking.length > 0\n ? semver.major(to) > semver.major(from)\n : semver.gte(to, from)\n : null;\n\n return { ...base, verdict: diff.breaking.length > 0 ? 'breaking' : 'ok', versionCovers };\n}\n\nconst LIST_CAP = 15;\n\nconst LABEL: Record<ChangeKind, string> = {\n 'operation-removed': 'removed',\n 'required-param-added': 'new required param',\n 'param-now-required': 'now required',\n 'required-body-field-added': 'new required body field',\n 'response-removed': 'response removed',\n 'operation-added': 'added',\n 'optional-param-added': 'new optional param',\n 'response-added': 'response added',\n 'operation-deprecated': 'deprecated',\n};\n\nfunction renderChanges(changes: ApiChange[]): string[] {\n const shown = changes.slice(0, LIST_CAP);\n const lines = shown.map(\n (c) => ` · ${c.operation}${c.detail ? ` → ${c.detail}` : ''} ${LABEL[c.kind]}`,\n );\n if (changes.length > shown.length) lines.push(` … ${changes.length - shown.length} more`);\n return lines;\n}\n\nexport function formatApiCheck(check: ApiCheck, label = 'api check'): string {\n const out = [`lurq, ${label}${check.title ? ` — ${check.title}` : ''}`, ''];\n\n if (check.verdict === 'inconclusive') {\n out.push(`INCONCLUSIVE ${check.diff.inconclusive}`, '', 'No verdict. This is not a pass.');\n return out.join('\\n');\n }\n\n const versions =\n check.fromVersion && check.toVersion ? ` ${check.fromVersion} → ${check.toVersion}` : '';\n\n if (check.diff.breaking.length) {\n out.push(`BREAKING${versions}`, '');\n out.push(` ${check.diff.breaking.length} change(s) that break existing callers:`);\n out.push(...renderChanges(check.diff.breaking));\n } else {\n out.push(`OK${versions}`, '', ' Nothing here breaks an existing caller.');\n }\n\n if (check.diff.other.length) {\n out.push('', ` ${check.diff.other.length} other change(s):`);\n out.push(...renderChanges(check.diff.other));\n }\n\n if (check.versionCovers === false) {\n out.push(\n '',\n check.diff.breaking.length\n ? ` info.version went ${check.fromVersion} → ${check.toVersion}. A breaking change needs a major.`\n : ` info.version went ${check.fromVersion} → ${check.toVersion}, which is not ahead.`,\n );\n } else if (check.versionCovers === null && (check.fromVersion || check.toVersion)) {\n // Say so rather than staying silent: silence about the version reads as\n // approval of it.\n out.push('', ' info.version is not semver on both sides, so the bump was not judged.');\n }\n\n return out.join('\\n');\n}\n","/**\n * Normalized surface of an OpenAPI document.\n *\n * The same idea as `src/surface/extract.ts`, pointed at a service instead of a\n * package: reduce a document to the set of promises it makes to callers, so two\n * revisions can be compared without diffing YAML. What a consumer can break\n * against is a small, boring list — the operation exists, the fields I must send,\n * the statuses I switch on — and everything else in an OpenAPI file (summaries,\n * tags, examples, servers) is prose that must never move a verdict.\n *\n * Structural, not semantic: this reads the document as written. A `$ref` into\n * `components` is resolved one level so required-field lists are real, but no\n * remote refs are fetched and no document is validated against the spec. An\n * unreadable file is reported as unreadable, never as an empty API — the §6.4.2\n * discipline from the package side applies identically here, and for the same\n * reason: an empty surface diffed against a real one reports the whole API as\n * deleted.\n */\nimport { parse as parseYaml } from 'yaml';\n\n/** One promise the API makes: `GET /v1/customers/{id}`. */\nexport interface Operation {\n /** `METHOD path`, the identity a consumer codes against. */\n id: string;\n method: string;\n path: string;\n /** Parameters the caller MUST send. Adding one breaks every existing caller. */\n requiredParams: string[];\n optionalParams: string[];\n /** Required properties of the request body, flattened across content types. */\n requiredBodyFields: string[];\n /** Documented status codes. Callers switch on these, so a removal breaks them. */\n responseCodes: string[];\n deprecated: boolean;\n}\n\nexport interface ApiSurface {\n title: string | null;\n /** `info.version` as written — not always semver, so callers must not assume. */\n version: string | null;\n operations: Map<string, Operation>;\n /** Set when nothing could be read. Callers must not treat the map as empty. */\n unreadableReason?: string;\n}\n\nconst METHODS = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'];\n\ntype Doc = Record<string, unknown>;\n\nconst isRecord = (v: unknown): v is Doc => typeof v === 'object' && v !== null && !Array.isArray(v);\n\n/**\n * Resolve a local `$ref` (`#/components/schemas/Foo`) against the root document.\n *\n * Local only, and one hop at a time. Fetching a remote ref would make a CI check\n * depend on a network it has no reason to touch, and following a chain without a\n * seen-set is how a self-referential schema hangs the process; anything that does\n * not resolve is treated as \"not established\" rather than as an empty schema.\n */\nfunction deref(root: Doc, node: unknown, seen = new Set<string>()): Doc | null {\n if (!isRecord(node)) return null;\n const ref = node.$ref;\n if (typeof ref !== 'string') return node;\n if (!ref.startsWith('#/') || seen.has(ref)) return null;\n seen.add(ref);\n let cursor: unknown = root;\n for (const segment of ref.slice(2).split('/')) {\n if (!isRecord(cursor)) return null;\n cursor = cursor[segment.replace(/~1/g, '/').replace(/~0/g, '~')];\n }\n return deref(root, cursor, seen);\n}\n\n/** Parameter names split by whether the caller has to send them. */\nfunction readParams(\n root: Doc,\n shared: unknown,\n own: unknown,\n): { required: string[]; optional: string[] } {\n const required = new Set<string>();\n const optional = new Set<string>();\n // Path-level parameters apply to every operation under it, and an operation\n // may override one by name. Merging with the operation last is what makes an\n // override read as an override rather than as a duplicate.\n for (const list of [shared, own]) {\n if (!Array.isArray(list)) continue;\n for (const raw of list) {\n const param = deref(root, raw);\n const name = param?.name;\n if (typeof name !== 'string') continue;\n // Keyed by name and location: `id` in the path and `id` in the query are\n // different promises, and collapsing them hides a real move between the two.\n const key = `${name} (${typeof param?.in === 'string' ? param.in : 'unknown'})`;\n if (param?.required === true) {\n required.add(key);\n optional.delete(key);\n } else if (!required.has(key)) {\n optional.add(key);\n }\n }\n }\n return { required: [...required].sort(), optional: [...optional].sort() };\n}\n\n/**\n * Required request-body properties, unioned across content types.\n *\n * Unioned rather than per-media-type: a field required in the JSON body and\n * absent from the form encoding is still a field some callers must now send, and\n * reporting it once is what a reader can act on. A body that is itself optional\n * contributes nothing — its fields are only required *if* you send a body.\n */\nfunction readBodyFields(root: Doc, requestBody: unknown): string[] {\n const body = deref(root, requestBody);\n if (!body || body.required !== true) return [];\n const content = body.content;\n if (!isRecord(content)) return [];\n const out = new Set<string>();\n for (const media of Object.values(content)) {\n const schema = deref(root, isRecord(media) ? media.schema : null);\n const required = schema?.required;\n if (!Array.isArray(required)) continue;\n for (const field of required) if (typeof field === 'string') out.add(field);\n }\n return [...out].sort();\n}\n\n/**\n * Parse an OpenAPI document (JSON or YAML) into its surface.\n *\n * Never throws for a document-side problem: a malformed file returns\n * `unreadableReason`, which the caller reports as inconclusive rather than as an\n * API with no operations.\n */\nexport function extractApiSurface(source: string, label = 'document'): ApiSurface {\n const empty: ApiSurface = { title: null, version: null, operations: new Map() };\n\n let doc: unknown;\n try {\n // `yaml` parses JSON too — JSON is a YAML subset — so one path handles both\n // and there is no format sniffing to get wrong on a `.txt` or an extensionless\n // file piped in from git.\n doc = parseYaml(source);\n } catch (err) {\n return {\n ...empty,\n unreadableReason: `${label} is not valid YAML or JSON: ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n if (!isRecord(doc)) return { ...empty, unreadableReason: `${label} is not an object` };\n if (!doc.openapi && !doc.swagger) {\n return { ...empty, unreadableReason: `${label} has no openapi/swagger version field` };\n }\n\n const info = isRecord(doc.info) ? doc.info : {};\n const paths = isRecord(doc.paths) ? doc.paths : {};\n const operations = new Map<string, Operation>();\n\n for (const [path, rawItem] of Object.entries(paths)) {\n const item = deref(doc, rawItem);\n if (!item) continue;\n for (const method of METHODS) {\n const op = item[method];\n if (!isRecord(op)) continue;\n const { required, optional } = readParams(doc, item.parameters, op.parameters);\n const responses = isRecord(op.responses) ? Object.keys(op.responses).sort() : [];\n const id = `${method.toUpperCase()} ${path}`;\n operations.set(id, {\n id,\n method: method.toUpperCase(),\n path,\n requiredParams: required,\n optionalParams: optional,\n requiredBodyFields: readBodyFields(doc, op.requestBody),\n responseCodes: responses,\n deprecated: op.deprecated === true,\n });\n }\n }\n\n return {\n title: typeof info.title === 'string' ? info.title : null,\n version: typeof info.version === 'string' ? info.version : null,\n operations,\n ...(operations.size === 0\n ? { unreadableReason: `${label} declares no operations` }\n : {}),\n };\n}\n","/**\n * `lurq check-api` — read two revisions of a spec from git and rule on the diff.\n *\n * Runs entirely on the developer's machine or their CI runner, like\n * `check-upgrade` and `check-release`: git is the only thing it talks to, no API\n * key, no network to lurq. The spec is a description of a public interface and\n * still never leaves the process.\n */\nimport { execFile } from 'node:child_process';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { relative, resolve } from 'node:path';\nimport { promisify } from 'node:util';\nimport { checkApi, type ApiCheck } from './diff';\nimport { extractApiSurface } from './openapi';\n\nconst execFileP = promisify(execFile);\n\n/** Conventional spec filenames, in the order a repo usually means them. */\nconst CANDIDATES = [\n 'openapi.yaml',\n 'openapi.yml',\n 'openapi.json',\n 'swagger.yaml',\n 'swagger.yml',\n 'swagger.json',\n 'api/openapi.yaml',\n 'api/openapi.yml',\n 'api/openapi.json',\n 'docs/openapi.yaml',\n 'docs/openapi.yml',\n];\n\n/** The spec to check, when the user didn't name one. */\nexport function findSpec(dir: string): string | null {\n for (const candidate of CANDIDATES) {\n const full = resolve(dir, candidate);\n if (existsSync(full)) return full;\n }\n return null;\n}\n\n/**\n * The file's content at a git revision, or null when it did not exist there.\n *\n * A spec that is new in this revision is not a failure — it is an API with no\n * previous promises to break — so \"not in that revision\" has to be\n * distinguishable from \"git blew up\", which is why this returns null rather than\n * an empty string.\n */\nasync function showAtRevision(\n dir: string,\n rev: string,\n repoPath: string,\n): Promise<string | null> {\n try {\n const { stdout } = await execFileP('git', ['show', `${rev}:${repoPath}`], {\n cwd: dir,\n maxBuffer: 32 * 1024 * 1024,\n });\n return stdout;\n } catch {\n return null;\n }\n}\n\nexport interface ApiCheckResult extends ApiCheck {\n /** The spec that was read, relative to the working directory. */\n spec: string;\n /** The revision compared against. */\n against: string;\n}\n\n/**\n * Compare the working tree's spec against the same file at `against`.\n *\n * `HEAD` is the default because the common case is a change you have not\n * committed yet; CI passes the base branch instead.\n */\nexport async function runApiCheck(\n dir: string,\n opts: { spec?: string; against?: string } = {},\n): Promise<ApiCheckResult> {\n const against = opts.against ?? 'HEAD';\n const specPath = opts.spec ? resolve(dir, opts.spec) : findSpec(dir);\n const spec = specPath ? relative(dir, specPath) || specPath : '(none found)';\n const base = { spec, against, title: null, fromVersion: null, toVersion: null };\n\n if (!specPath) {\n return {\n ...base,\n verdict: 'inconclusive',\n versionCovers: null,\n diff: {\n breaking: [],\n other: [],\n inconclusive: `no OpenAPI document found in ${dir}. Name one: lurq check-api <file>`,\n },\n };\n }\n\n const current = extractApiSurface(readFileSync(specPath, 'utf8'), spec);\n const previousSource = await showAtRevision(dir, against, spec);\n if (previousSource === null) {\n return {\n ...base,\n title: current.title,\n toVersion: current.version,\n verdict: 'inconclusive',\n versionCovers: null,\n diff: {\n breaking: [],\n other: [],\n inconclusive: `${spec} does not exist at ${against}, so there is nothing to compare against`,\n },\n };\n }\n\n const previous = extractApiSurface(previousSource, `${spec} at ${against}`);\n return { ...base, ...checkApi(previous, current) };\n}\n","/**\n * Minimal per-tool metrics for the hosted MCP path — Prometheus text format, no\n * dependency. Counts calls, errors, and cumulative latency per tool so an\n * operator can see usage and error rates without wiring up an APM. Process-local\n * (a module singleton): each server instance exposes its own counters at\n * `/metrics`, which is exactly what a Prometheus scrape expects.\n */\ninterface Stat {\n calls: number;\n errors: number;\n totalMs: number;\n}\n\nconst stats = new Map<string, Stat>();\n\n/** Record one tool invocation. `ok=false` marks a handler that threw. */\nexport function recordToolCall(tool: string, ok: boolean, ms: number): void {\n const s = stats.get(tool) ?? { calls: 0, errors: 0, totalMs: 0 };\n s.calls += 1;\n if (!ok) s.errors += 1;\n s.totalMs += ms;\n stats.set(tool, s);\n}\n\n/** Time a tool handler and record the outcome, re-throwing any error unchanged. */\nexport async function timed<T>(tool: string, fn: () => Promise<T>): Promise<T> {\n const start = Date.now();\n let ok = false;\n try {\n const result = await fn();\n ok = true;\n return result;\n } finally {\n recordToolCall(tool, ok, Date.now() - start);\n }\n}\n\n/** Render current counters in Prometheus exposition format. */\nexport function renderPrometheus(): string {\n const lines = [\n '# HELP lurq_tool_calls_total Total MCP tool invocations.',\n '# TYPE lurq_tool_calls_total counter',\n '# HELP lurq_tool_errors_total MCP tool invocations that threw.',\n '# TYPE lurq_tool_errors_total counter',\n '# HELP lurq_tool_duration_ms_total Cumulative tool handler time in ms.',\n '# TYPE lurq_tool_duration_ms_total counter',\n ];\n for (const [tool, s] of stats) {\n const label = `{tool=\"${tool}\"}`;\n lines.push(`lurq_tool_calls_total${label} ${s.calls}`);\n lines.push(`lurq_tool_errors_total${label} ${s.errors}`);\n lines.push(`lurq_tool_duration_ms_total${label} ${s.totalMs}`);\n }\n return lines.join('\\n') + '\\n';\n}\n\n/** Test-only: clear all counters. */\nexport function resetMetrics(): void {\n stats.clear();\n}\n","/**\n * Compact MCP responses (§12.4). Every tool response is JSON injected straight\n * into the calling agent's context window, so each `\"field\":null` or empty\n * container is tokens the user pays for on every call — and noise that dilutes\n * the agent's attention. `compact()` recursively drops null/undefined values,\n * empty arrays, and objects that become empty, keeping only signal.\n *\n * Deliberately KEEPS `false` and `0`: `deprecated:false` and `weeklyDownloads:0`\n * carry meaning an agent shouldn't have to infer from a field's absence. Only\n * genuinely-absent data (null/undefined/empty) is stripped.\n */\n/** True only for a *plain* object with no keys. A Date has no own keys, so\n * without the instanceof guard every date field would be dropped as \"empty\". */\nfunction isEmptyObject(value: unknown): boolean {\n return (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n !(value instanceof Date) &&\n Object.keys(value).length === 0\n );\n}\n\nexport function compact<T>(value: T): T {\n // A Date is an object with no own keys, so the generic object walk below would\n // see `{}` and drop the field entirely. Handlers stringify their dates today;\n // this keeps the first one that forgets from silently losing data.\n if (value instanceof Date) return value;\n if (Array.isArray(value)) {\n return value\n .map((v) => compact(v))\n .filter((v) => v !== null && v !== undefined) as unknown as T;\n }\n if (value !== null && typeof value === 'object') {\n const out: Record<string, unknown> = {};\n for (const [key, raw] of Object.entries(value as Record<string, unknown>)) {\n if (raw === null || raw === undefined) continue;\n const cleaned = compact(raw);\n if (cleaned === null || cleaned === undefined) continue;\n if (Array.isArray(cleaned) && cleaned.length === 0) continue;\n if (isEmptyObject(cleaned)) continue;\n out[key] = cleaned;\n }\n return out as T;\n }\n return value;\n}\n","/**\n * The canonical descriptions for the three tools the benchmark's agent arms\n * expose, in one place because they were being written twice.\n *\n * server.ts is what real agents see. The benchmark participants each hand-wrote\n * their own paraphrase of the same three tools — once per vendor schema shape —\n * and those paraphrases drifted well below the originals. `compat` is the clear\n * case: production says \"across the whole set ... call before committing to a\n * multi-package stack\", the benchmark's copy said only \"check if packages are\n * compatible\", and the measured consequence was the model calling `compat` four\n * separate times on a two-need case instead of once with the whole set. Every\n * one of those extra turns resends the entire accumulated context, so a weaker\n * sentence here was costing real tokens and real latency.\n *\n * That made the benchmark measure a worse lurq than the one that ships — the\n * arm meant to show what the tools are worth was describing them badly. Hence\n * one source: a description improved for agents is now improved for the number\n * we publish about them, and neither can quietly fall behind the other.\n *\n * Only these three are extracted, not all nine tools on the server. The other\n * six have exactly one caller and gain nothing from the indirection.\n */\n\nexport const PLAN_DESCRIPTION =\n 'Turn a detailed program description (spec/README) or a list of component needs into an evidence-scored build plan: a real, lurq-scored package recommended per component, plus a Mermaid roadmap other agents can parse. Recommends building blocks slot-by-slot from the index, it does not invent an architecture from a bare prompt.';\n\nexport const VERIFY_DESCRIPTION =\n 'Confirm an npm package is real, healthy, and not risky before installing, guards against hallucinated or typosquatted dependency names. Checks the live registry.';\n\nexport const COMPAT_DESCRIPTION =\n 'Check whether a set of packages forms a coherent stack. Resolves the whole set the way npm would and returns a definitive verdict: compatible, conflict (with the exact clashing constraints), or unknown. Checks peer-dependency and engine ranges from declared metadata, plus any recorded sandbox conflicts. Read-only, never installs or executes package code. Call before committing to a multi-package stack.';\n\n/**\n * The `packages` parameter carries the batching instruction, not just the\n * bound. A model told the argument is a set checks the set; a model told only\n * that it is an array checks pairs, one round trip at a time, which is what it\n * actually did before this said otherwise.\n */\nexport const COMPAT_PACKAGES_DESCRIPTION =\n 'The full candidate stack to check together, 2–30 npm package names — a whole package.json dependency list is the intended input. Pass every package in one call: conflicts routinely appear only across the whole set (a peer range three packages deep), so checking pairs separately misses them and costs a round trip each.';\n\nexport const COMPAT_VERSIONS_DESCRIPTION =\n 'Optional exact versions keyed by package name, e.g. {\"react\":\"19.0.0\"} (use when not checking latest). Must be exact semver versions, not ranges.';\n\nexport const COMPAT_NODE_DESCRIPTION =\n 'Optional target Node runtime (e.g. \"20\" or \"20.20.2\") for engines.node checks';\n","/**\n * Dashboard usage counters (dashboard v1 phase 2). Per-owner, per-day, per-tool\n * call counts. Display-only, not a billing ledger — the write is a fire-and-forget\n * UPSERT that swallows its own errors, so a counter hiccup can never fail a tool\n * call (same idiom as stampLastUsed). Reads power the dashboard `/usage` view.\n */\nimport { and, desc, eq, gte, sql } from 'drizzle-orm';\nimport type { Database } from './client';\nimport { apiKeys, ownerUsageDaily } from './schema';\n\nexport interface UsagePoint {\n /** UTC day, 'YYYY-MM-DD'. */\n date: string;\n count: number;\n}\n\n/**\n * First day of a trailing `days`-day window, inclusive of today.\n *\n * The `::int` cast is load-bearing, not decoration. postgres.js's `inferType`\n * returns 0 (unspecified) for a plain JS number, so an uncast `CURRENT_DATE - $n`\n * lets Postgres resolve the operator as `date - date -> integer`; the surrounding\n * comparison then becomes `date >= integer` and the query dies with\n * `operator does not exist`. Shared by both readers so the cast can't drift.\n */\nexport function windowStart(days: number) {\n return sql`CURRENT_DATE - (${days}::int - 1)`;\n}\n\n/**\n * Increment today's counter for (owner, tool). No-op when ownerId is null/empty\n * (operator-issued keys with no dashboard account). Fire-and-forget: an undercount\n * on a transient DB failure is acceptable for a display-only counter.\n */\nexport async function recordUsage(\n db: Database,\n ownerId: string | null | undefined,\n tool: string,\n): Promise<void> {\n if (!ownerId) return;\n try {\n await db\n .insert(ownerUsageDaily)\n .values({ ownerId, date: sql`CURRENT_DATE`, tool, count: 1 })\n .onConflictDoUpdate({\n target: [ownerUsageDaily.ownerId, ownerUsageDaily.date, ownerUsageDaily.tool],\n set: { count: sql`${ownerUsageDaily.count} + 1` },\n });\n } catch {\n // Display-only counter: never let a usage write break the request.\n }\n}\n\n/**\n * Trailing-`days`-window daily totals (summed across tools), plus today's total.\n *\n * The window is generated DB-side with `generate_series` and LEFT JOINed, so the\n * result is **gap-free**: every day in the window is present, zero-count days\n * included. Callers can therefore plot it on a uniform time axis — a series that\n * only carried days-with-traffic would render equal-width bars for unequal time\n * spans and misstate the trend.\n */\nexport async function getUsageSummary(\n db: Database,\n ownerId: string,\n days: number,\n): Promise<{ today: number; series: UsagePoint[] }> {\n const rows = (await db.execute<{ date: string; count: number }>(sql`\n select\n to_char(d, 'YYYY-MM-DD') as date,\n coalesce(sum(u.count), 0)::int as count\n from generate_series(${windowStart(days)}, CURRENT_DATE, interval '1 day') as d\n left join ${ownerUsageDaily} u\n on u.date = d::date and u.owner_id = ${ownerId}\n group by d\n order by d\n `)) as unknown as { date: string; count: number }[];\n\n const series: UsagePoint[] = rows.map((r) => ({ date: String(r.date), count: Number(r.count) }));\n // The series ends at the database's CURRENT_DATE, which is the same clock the\n // counters are written against. Deriving \"today\" from the process's UTC date\n // instead would read 0 on any server not running in UTC.\n const today = series.at(-1)?.count ?? 0;\n return { today, series };\n}\n\n/** Trailing-`days`-window totals grouped by tool, busiest first. */\nexport async function getUsageByTool(\n db: Database,\n ownerId: string,\n days: number,\n): Promise<{ tool: string; count: number }[]> {\n const rows = await db\n .select({\n tool: ownerUsageDaily.tool,\n count: sql<number>`sum(${ownerUsageDaily.count})::int`,\n })\n .from(ownerUsageDaily)\n .where(\n and(\n eq(ownerUsageDaily.ownerId, ownerId),\n gte(ownerUsageDaily.date, windowStart(days)),\n ),\n )\n .groupBy(ownerUsageDaily.tool)\n .orderBy(desc(sql`sum(${ownerUsageDaily.count})`));\n\n return rows.map((r) => ({ tool: r.tool, count: Number(r.count) }));\n}\n\nexport interface ProductStats {\n days: number;\n /** Owners that minted a self-serve key: total ever, first key in the window,\n * and any tool call in the window. */\n accounts: { total: number; new: number; active: number };\n calls: { total: number; byTool: { tool: string; count: number }[] };\n}\n\n/**\n * Whole-product numbers across every account, for the operator `stats` command.\n *\n * An \"account\" here is an owner with at least one key, revoked ones included:\n * someone who signed up AND reached the dashboard. A Clerk sign-up that never\n * made a key exists only in Clerk. Calls on operator keys (no owner) never reach\n * owner_usage_daily, so they are not counted either.\n */\nexport async function getProductStats(db: Database, days: number): Promise<ProductStats> {\n const since = windowStart(days);\n const [accounts] = (await db.execute<{ total: number; new: number; active: number }>(sql`\n select\n count(*)::int as total,\n (count(*) filter (where first_at >= ${since}))::int as new,\n (select count(distinct owner_id)::int from ${ownerUsageDaily} where date >= ${since}) as active\n from (\n select min(${apiKeys.createdAt}) as first_at\n from ${apiKeys}\n where ${apiKeys.ownerId} is not null\n group by ${apiKeys.ownerId}\n ) firsts\n `)) as unknown as { total: number; new: number; active: number }[];\n\n const byTool = (\n await db\n .select({\n tool: ownerUsageDaily.tool,\n count: sql<number>`sum(${ownerUsageDaily.count})::int`,\n })\n .from(ownerUsageDaily)\n .where(gte(ownerUsageDaily.date, since))\n .groupBy(ownerUsageDaily.tool)\n .orderBy(desc(sql`sum(${ownerUsageDaily.count})`))\n ).map((r) => ({ tool: r.tool, count: Number(r.count) }));\n\n return {\n days,\n accounts: {\n total: Number(accounts?.total ?? 0),\n new: Number(accounts?.new ?? 0),\n active: Number(accounts?.active ?? 0),\n },\n calls: { total: byTool.reduce((n, r) => n + r.count, 0), byTool },\n };\n}\n\nexport interface UsageRetentionReport {\n /** Rows older than the cutoff. */\n stale: number;\n /** Rows kept. */\n retained: number;\n /** Oldest date still present, ISO 'YYYY-MM-DD'. Null when the table is empty. */\n oldest: string | null;\n /** True when rows were actually removed; false for a dry run. */\n applied: boolean;\n}\n\n/**\n * Report on — and optionally delete — usage counters older than `keepDays`.\n *\n * This table is the one that grows without bound as users arrive: one row per\n * owner, per day, per tool. At 10k users with 10% daily active that is ~3.3M\n * rows a year, and ~33M if they are all active daily. Left alone it becomes the\n * next `compat_edges`, and it holds display-only counters — its own schema\n * comment says an undercount on a DB hiccup is acceptable — so old rows are not\n * worth what they cost.\n *\n * DRY RUN BY DEFAULT. `apply` has to be passed explicitly, because this is the\n * only function in the codebase that removes production rows and a retention\n * sweep is not something that should be able to happen by accident, on a timer,\n * or as a side effect of calling something that sounds like a read.\n *\n * If a longer history is ever wanted, the upgrade is a monthly rollup table\n * written before the sweep, not a longer window on the daily rows.\n */\nexport async function pruneUsageCounters(\n db: Database,\n opts: { keepDays?: number; apply?: boolean } = {},\n): Promise<UsageRetentionReport> {\n const keepDays = opts.keepDays ?? 90;\n const applied = opts.apply === true;\n const cutoff = sql`(current_date - make_interval(days => ${keepDays}))::date`;\n\n const [counts] = await db\n .select({\n stale: sql<number>`count(*) filter (where ${ownerUsageDaily.date} < ${cutoff})::int`,\n retained: sql<number>`count(*) filter (where ${ownerUsageDaily.date} >= ${cutoff})::int`,\n oldest: sql<string | null>`min(${ownerUsageDaily.date})::text`,\n })\n .from(ownerUsageDaily);\n\n const report: UsageRetentionReport = {\n stale: counts?.stale ?? 0,\n retained: counts?.retained ?? 0,\n oldest: counts?.oldest ?? null,\n applied,\n };\n if (!applied || report.stale === 0) return report;\n\n await db.delete(ownerUsageDaily).where(sql`${ownerUsageDaily.date} < ${cutoff}`);\n return report;\n}\n","/**\n * Server-side product events for PostHog, sent over its public `/batch/` capture\n * API with plain `fetch`. No SDK on purpose: `serve-http` ships inside the\n * published `lurq` bundle, and every CLI install would otherwise carry a client\n * it never runs.\n *\n * Events are keyed by the Clerk user id, the same id the web app passes to\n * `posthog.identify`, so a visitor's landing → sign-up → key → first tool call\n * reads as one person. Only account-owned calls on the hosted service are sent:\n * no key configured or no owner (stdio, local, operator keys) means no event,\n * which keeps the privacy page's promise that the CLI sends no telemetry.\n *\n * Display analytics, not a ledger. A failed batch is dropped, never retried.\n */\nimport { getConfig } from './config';\nimport { logger } from './logger';\n\n// US cloud, matching the web app's /ingest rewrites in apps/web/next.config.ts.\nconst HOST = 'https://us.i.posthog.com';\nconst FLUSH_AT = 50;\nconst FLUSH_MS = 10_000;\n\ninterface QueuedEvent {\n event: string;\n properties: Record<string, unknown>;\n timestamp: string;\n}\n\nlet queue: QueuedEvent[] = [];\nlet timer: NodeJS.Timeout | null = null;\n\n/** Queue one event for `distinctId`. A no-op without an owner or a key. */\nexport function capture(\n distinctId: string | null | undefined,\n event: string,\n properties: Record<string, unknown> = {},\n): void {\n if (!distinctId || !getConfig().LURQ_POSTHOG_KEY) return;\n queue.push({\n event,\n properties: { ...properties, distinct_id: distinctId },\n timestamp: new Date().toISOString(),\n });\n if (queue.length >= FLUSH_AT) {\n void flush();\n } else if (!timer) {\n timer = setTimeout(() => void flush(), FLUSH_MS);\n timer.unref(); // pending analytics must never keep the process alive\n }\n}\n\n/** Send everything queued. Never throws; call it on shutdown to drain. */\nexport async function flush(): Promise<void> {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n const key = getConfig().LURQ_POSTHOG_KEY;\n if (!key || queue.length === 0) return;\n const batch = queue;\n queue = [];\n try {\n const res = await fetch(`${HOST}/batch/`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ api_key: key, batch }),\n signal: AbortSignal.timeout(5_000),\n });\n if (!res.ok) logger.warn(`posthog batch rejected (${res.status}), dropped ${batch.length} event(s)`);\n } catch (err) {\n logger.warn('posthog batch failed:', err instanceof Error ? err.message : String(err));\n }\n}\n","/**\n * MCP server (§12). Exposes recommend / evaluate / compare / verify over stdio.\n * Inputs are validated with zod; outputs are compact JSON text (§12.4).\n */\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { z } from 'zod';\nimport semver from 'semver';\nimport { SERVER_NAME, VERSION } from '../core/constants';\nimport { CATEGORIES, type Category } from '../core/types';\nimport { searchCapabilities } from '../core/capabilities';\nimport { createDb } from '../db/client';\nimport { logger } from '../core/logger';\nimport { handleDiffSurface, handleResolveSurface } from './surfaceHandlers';\nimport { handleMcpDrift, handleMcpSurface } from './mcpHandlers';\nimport { handleAudit } from './auditHandler';\nimport {\n handleCompare,\n handleCompat,\n handleEvaluate,\n handlePolicy,\n handleReportOutcome,\n handleUsage,\n handleVerify,\n} from './handlers';\nimport { handleDiagram } from './diagram';\nimport { timed } from './metrics';\nimport { compact } from './compact';\nimport {\n COMPAT_DESCRIPTION,\n COMPAT_NODE_DESCRIPTION,\n COMPAT_PACKAGES_DESCRIPTION,\n COMPAT_VERSIONS_DESCRIPTION,\n VERIFY_DESCRIPTION,\n} from './toolDescriptions';\nimport { recordUsage } from '../db/usage';\nimport { capture } from '../core/analytics';\n\nconst confidenceEnum = z.enum(['proven', 'emerging', 'promising', 'unproven']);\n\n// Validate package names at the trust boundary. A name flows straight into a\n// registry URL (`registry.npmjs.org/${name}`) and the response cache key, so\n// reject anything that isn't a legal npm name: this blocks path/query\n// injection (`/`, `?`, `#`, `%`), whitespace, and control characters. Case is\n// permitted for legacy packages; the char class is what closes the hole.\nexport const npmName = z\n .string()\n .trim()\n .min(1)\n .max(214)\n .regex(/^(?:@[a-z0-9-][a-z0-9-._]*\\/)?[a-z0-9-][a-z0-9-._]*$/i, 'Invalid npm package name');\n\n/**\n * An exact semver version, and nothing else.\n *\n * This is a trust boundary, not a formatting preference. A caller-supplied\n * version string ends up as a dependency value in the `package.json` that\n * `resolveSet` hands to npm. Anything that is not a semver version is a\n * different kind of specifier — `git+ssh://host/repo`, `file:../x`, a tarball\n * URL — and npm will dutifully go fetch it, which turns this parameter into\n * caller-directed network egress from our container. `semver.valid` accepts\n * exactly the versions `assembleMembers` can pin against and nothing else.\n */\nexport const exactVersion = z\n .string()\n .trim()\n .max(256)\n .refine((v) => semver.valid(v) !== null, 'Must be an exact semver version, e.g. \"19.0.0\"');\n\n// No `runtime` filter: lurq stores no per-package runtime signal, so the field\n// was accepted and silently ignored — an agent asking for browser-only packages\n// got the unfiltered list back. Restore it when ingestion records the manifest's\n// `browser` field / `exports` browser condition, not before.\nconst constraintsSchema = z\n .object({\n license: z.string().optional(),\n maxBundleKb: z.number().positive().optional(),\n minConfidence: confidenceEnum.optional(),\n })\n .optional();\n\n/** Wrap any result object as a compact MCP text response. `compact` strips\n * null/empty fields so the agent's context only carries signal (§12.4). */\nfunction json(obj: unknown) {\n return { content: [{ type: 'text' as const, text: JSON.stringify(compact(obj)) }] };\n}\n\n/**\n * Per-connection identity, resolved from the authenticated API key at the HTTP\n * boundary and threaded into the tools. This is the channel that lets lurq know\n * *who* is calling — stamped onto the data it collects (§3.1 flywheel) so it\n * accrues to an individual account instead of an anonymous pool. `ownerId` is\n * null on the stdio/local path and for operator-issued keys with no account.\n */\nexport interface ServerContext {\n ownerId?: string | null;\n}\n\nexport function buildMcpServer(\n db: ReturnType<typeof createDb>['db'],\n ctx: ServerContext = {},\n): McpServer {\n const server = new McpServer({ name: SERVER_NAME, version: VERSION });\n\n // Run a tool with Prometheus timing (metrics) AND a fire-and-forget per-user\n // usage counter for the dashboard (§ dashboard v1 phase 2). The counter is\n // recorded in a finally so an errored call still counts; recordUsage no-ops\n // when ctx.ownerId is null (stdio/local or operator keys with no account).\n // The PostHog event carries the tool name and outcome only, never arguments,\n // and no-ops under the same null-owner rule (src/core/analytics.ts).\n const run = <T>(tool: string, fn: () => Promise<T>): Promise<T> =>\n (async () => {\n let ok = false;\n try {\n const result = await timed(tool, fn);\n ok = true;\n return result;\n } finally {\n void recordUsage(db, ctx.ownerId ?? null, tool);\n capture(ctx.ownerId, 'tool_called', { tool, ok });\n }\n })();\n\n server.registerTool(\n 'evaluate',\n {\n title: 'Evaluate a package',\n description:\n 'Full evidence read for one npm package: scores, signals, advisories, summary, and a usage guide. Fetches & scores on demand if not yet tracked.',\n inputSchema: {\n package: npmName.describe('npm package name'),\n },\n },\n async (args) =>\n json(await run('evaluate', () => handleEvaluate(db, args, ctx.ownerId ?? null))),\n );\n\n // Read-only on purpose. There is no tool that writes policy: the agent being\n // governed must not be able to edit its own rules. People change policy in the\n // dashboard or with `lurq policy push` and a scoped key.\n server.registerTool(\n 'policy',\n {\n title: 'Read the dependency policy',\n description:\n \"The rules this account's selection policy enforces on which packages you may add: denied packages (with the reason), license allowlist, confidence, advisory, adoption, staleness and bundle-size floors. Read it once before choosing dependencies so you pick an allowed package first; recommend and evaluate already enforce it. Read-only.\",\n inputSchema: {},\n },\n async () => json(await run('policy', () => handlePolicy(db, ctx.ownerId ?? null))),\n );\n\n server.registerTool(\n 'compare',\n {\n title: 'Compare packages',\n description: 'Side-by-side comparison of 2–5 npm packages, ranked by health score.',\n inputSchema: {\n packages: z.array(npmName).min(2).max(5).describe('2–5 npm package names'),\n },\n },\n async (args) => json(await run('compare', () => handleCompare(db, args, ctx.ownerId ?? null))),\n );\n\n server.registerTool(\n 'compat',\n {\n title: 'Check package compatibility',\n description: COMPAT_DESCRIPTION,\n inputSchema: {\n packages: z.array(npmName).min(2).max(30).describe(COMPAT_PACKAGES_DESCRIPTION),\n versions: z.record(exactVersion).optional().describe(COMPAT_VERSIONS_DESCRIPTION),\n node: z.string().optional().describe(COMPAT_NODE_DESCRIPTION),\n },\n },\n async (args) => json(await run('compat', () => handleCompat(db, args))),\n );\n\n server.registerTool(\n 'verify',\n {\n title: 'Verify a package',\n description: VERIFY_DESCRIPTION,\n inputSchema: {\n package: npmName.describe('npm package name to verify'),\n },\n },\n async (args) => json(await run('verify', () => handleVerify(db, args, ctx.ownerId ?? null))),\n );\n\n server.registerTool(\n 'usage',\n {\n title: 'Version-exact API surface + drift',\n description:\n \"Get a package version's real public API, the exported symbols and signatures extracted from its shipped .d.ts, exact to the version, none of it in the model's training data. Pass knownVersion (e.g. the version you were trained on) to get the precise delta: what was added, removed, renamed, or changed. Also returns the version's declared engines (Node/runtime floor) so you don't write code against a version the target runtime cannot install. Use before writing code against a package whose API may have moved. For framework file/convention changes (not exported symbols), consult the official migration guide / Context7 instead.\",\n inputSchema: {\n package: npmName.describe('npm package name'),\n version: z.string().optional().describe('Target version (defaults to latest)'),\n knownVersion: z\n .string()\n .optional()\n .describe('A version you already know; returns the API delta from it to the target'),\n },\n },\n async (args) => json(await run('usage', () => handleUsage(db, args))),\n );\n\n server.registerTool(\n 'diagram',\n {\n title: 'Reference architecture diagram',\n description:\n 'Emit a reference-architecture Mermaid diagram for a stack you have already chosen (package names). A labeled starting point keyed by layer, not a validated architecture, and not an architecture designer.',\n inputSchema: {\n stack: z\n .array(npmName)\n .optional()\n .describe('Package names that make up the stack; omit or empty to get usage guidance'),\n },\n },\n async (args) => json(await run('diagram', () => handleDiagram(db, args))),\n );\n\n server.registerTool(\n 'resolve_surface',\n {\n title: 'Version-exact runtime surface',\n description:\n \"What a package version ACTUALLY exports at runtime, extracted from its shipped JavaScript rather than from documentation or the model's memory. Call before writing code against a package whose API may have moved. Runtime existence is what decides whether an import throws; a removed type breaks tsc, a removed runtime symbol breaks the program. A miss returns UNKNOWN and queues extraction, UNKNOWN never means the symbol is absent.\",\n inputSchema: {\n package: npmName.describe('npm package name'),\n version: z.string().optional().describe('Exact version; omit for the latest extracted'),\n },\n },\n async (args) => json(await run('resolve_surface', () => handleResolveSurface(db, args))),\n );\n\n server.registerTool(\n 'diff_surface',\n {\n title: 'Surface diff between two versions',\n description:\n 'What changed in a package\\'s runtime surface between two versions: symbols removed, added, and arity changes. Removals break `node`; type-only removals are returned separately because they break `tsc` instead. Answers \"when did this stop working\" from static comparison, with no install required. Use before an upgrade, and to explain a break after one.',\n inputSchema: {\n package: npmName.describe('npm package name'),\n fromVersion: z.string().describe('Version you are on'),\n toVersion: z.string().describe('Version you are moving to'),\n },\n },\n async (args) => json(await run('diff_surface', () => handleDiffSurface(db, args))),\n );\n\n server.registerTool(\n 'mcp_stack',\n {\n title: 'Do these MCP servers coexist?',\n description:\n \"Check whether a set of MCP servers can be wired into one agent together. The npm question does not apply — servers are separate processes with nothing to resolve between them. They clash in the single flat TOOL NAMESPACE the agent assembles from all of them: two servers exposing the same tool name leave the agent unable to express which it means, and nothing errors, one simply shadows the other. Also reports the standing context cost, since every tool's schema rides in every request. A server that has not been probed makes the answer UNKNOWN, never clean.\",\n inputSchema: {\n servers: z\n .array(\n z.object({\n server: npmName.describe('npm package name of the MCP server'),\n version: z.string().nullable().optional(),\n }),\n )\n .min(1)\n .max(50)\n .describe('The servers configured into one agent'),\n },\n },\n async (args) =>\n json(\n await run('mcp_stack', async () => {\n const { checkMcpStack } = await import('../compat/mcpStack');\n return checkMcpStack(\n db,\n args.servers.map((s) => ({ server: s.server, version: s.version ?? null })),\n );\n }),\n ),\n );\n\n server.registerTool(\n 'mcp_surface',\n {\n title: \"An MCP server's tool contract\",\n description:\n \"What an MCP server ACTUALLY exposes: every tool, its required and optional parameters, and its behaviour annotations, read from a live `tools/list` handshake in a sandbox rather than from a README or the model's memory. Call before wiring an agent to a server, or when a tool call is failing for reasons the error does not explain. Also returns `requires` — the API keys and settings the server declares it needs — and `configRequest`, a ready-made line to put in front of your user when something is missing, so 'it needs a token' never presents as 'it is broken'. A miss returns UNKNOWN and queues a probe; UNKNOWN never means the server has no tools.\",\n inputSchema: {\n server: npmName.describe('npm package name of the MCP server'),\n version: z.string().optional().describe('Exact version; omit for the latest probed'),\n },\n },\n async (args) => json(await run('mcp_surface', () => handleMcpSurface(db, args))),\n );\n\n server.registerTool(\n 'mcp_drift',\n {\n title: 'MCP tool-contract drift between two versions',\n description:\n \"What moved in an MCP server's tool contract between two versions: tools removed, parameters that became required, types narrowed, and annotation flips. Two findings here have no npm equivalent and are why this exists. SILENT DRIFT is a schema that changed while its description stayed byte-identical, invisible to anyone reading a changelog. PRIVILEGE WIDENING is a tool that stopped being read-only or started being destructive, which does not break anything and is worse than a break. Use before upgrading a server an agent depends on.\",\n inputSchema: {\n server: npmName.describe('npm package name of the MCP server'),\n fromVersion: z.string().describe('Version you are on'),\n toVersion: z.string().describe('Version you are moving to'),\n },\n },\n async (args) => json(await run('mcp_drift', () => handleMcpDrift(db, args))),\n );\n\n server.registerTool(\n 'audit',\n {\n title: 'Audit a whole project',\n description:\n \"Assess an entire project's dependencies in ONE call: which packages are outdated, deprecated or carry advisories for the exact installed version, and which configured MCP servers have drifted, need credentials, or cannot be observed at all. Send the inventory you read locally (names and versions only — never source). Returns a per-item verdict plus an explicit coverage count: how many were answered, how many are queued because the index has not seen them, and how many were skipped and why. An item lurq could not assess is reported as unassessed, never as clean.\",\n inputSchema: {\n packages: z\n .array(\n z.object({\n name: npmName,\n range: z.string().optional().describe('Declared range, e.g. ^6.4.0'),\n installed: z\n .string()\n .nullable()\n .optional()\n .describe(\n 'Resolved version from the lockfile or node_modules — what actually runs',\n ),\n }),\n )\n .max(600)\n .optional()\n .describe('npm dependencies read from package.json + lockfile'),\n mcpServers: z\n .array(\n z.object({\n alias: z.string().max(200).optional(),\n kind: z\n .enum(['npm-stdio', 'remote', 'local', 'other-registry'])\n .optional()\n .describe('How it launches; decides whether lurq can read its contract'),\n packageName: z.string().max(300).nullable().optional(),\n version: z.string().max(100).nullable().optional(),\n endpoint: z.string().max(300).nullable().optional(),\n }),\n )\n .max(200)\n .optional()\n .describe('MCP servers read from .mcp.json / agent configs'),\n },\n },\n async (args) => json(await run('audit', () => handleAudit(db, args))),\n );\n\n // Self-description, and the only tool that reads nothing. An agent holding\n // eleven lurq tools still has to guess which one answers the situation in\n // front of it; this turns that guess into a lookup, and returns the exact tool\n // name to call next rather than prose about it. No db, no key, no usage row —\n // asking what a tool does is not usage of it.\n server.registerTool(\n 'capabilities',\n {\n title: 'What lurq can do',\n description:\n \"Look up which lurq tool answers a situation, and what to run next. Call when you're unsure whether lurq covers something (an upgrade, a licence rule, a version's exact exports, publishing a package) instead of guessing or skipping it. Returns matching capabilities with the tool or command to use.\",\n inputSchema: {\n query: z\n .string()\n .max(300)\n .optional()\n .describe('What you are trying to do, in plain words. Omit for the full menu.'),\n },\n },\n async (args) => json({ capabilities: searchCapabilities(args.query ?? '', 6) }),\n );\n\n server.registerTool(\n 'report_outcome',\n {\n title: 'Report a recommendation outcome',\n description:\n 'Opt-in feedback after acting on a lurq recommendation: report whether you went with the package and whether it built. No source code, only the coarse decision + a build signal. Helps lurq learn which packages agents actually succeed with; safe to skip.',\n inputSchema: {\n package: npmName.describe('The package that was recommended'),\n accepted: z.boolean().describe('Did you go with this package?'),\n buildSignal: z\n .enum(['installed', 'compiled', 'tests_passed', 'failed'])\n .optional()\n .describe('Coarse post-install result, if known'),\n need: z\n .string()\n .max(500)\n .optional()\n .describe('The original need this was recommended for (no source code)'),\n },\n },\n // ownerId comes from the authenticated key (ctx), NOT the tool arguments —\n // a caller must never be able to attribute an outcome to another org.\n async (args) =>\n json(await run('report_outcome', () => handleReportOutcome(db, args, ctx.ownerId ?? null))),\n );\n\n return server;\n}\n\nexport async function startMcpServer(): Promise<void> {\n const { db, close } = createDb();\n const server = buildMcpServer(db);\n\n const shutdown = async () => {\n try {\n await close();\n } finally {\n process.exit(0);\n }\n };\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n\n const transport = new StdioServerTransport();\n await server.connect(transport);\n logger.info(`${SERVER_NAME} MCP server v${VERSION} running on stdio.`);\n}\n","/**\n * API-key generation, hashing, and lifecycle for the hosted HTTP service\n * (docs/lurq-hosted-deployment.md §5). Keys are high-entropy random strings; only\n * their sha256 hash is persisted, so a DB leak never exposes a usable key. The\n * plaintext is returned exactly once (at creation) and never stored or logged.\n */\nimport { createHash, randomBytes } from 'node:crypto';\nimport { and, desc, eq, isNull } from 'drizzle-orm';\nimport { API_KEY_PREFIX } from '../core/constants';\nimport type { Database } from '../db/client';\nimport { apiKeys, type ApiKeyRow } from '../db/schema';\nimport { logger } from '../core/logger';\n\n/** Chars of the random body kept in the display prefix (`lurq_live_<6>`). */\nconst DISPLAY_BODY = 6;\n\n/** sha256 hex of a key — the only form ever persisted or compared. */\nexport function hashKey(key: string): string {\n return createHash('sha256').update(key).digest('hex');\n}\n\nexport interface GeneratedKey {\n /** The full plaintext key — show once, never store. */\n key: string;\n /** sha256 hash to persist. */\n hash: string;\n /** Identifiable, safe-to-display prefix. */\n prefix: string;\n}\n\nexport function generateApiKey(): GeneratedKey {\n // 24 random bytes → 32-char base64url body: unbiased, URL/header-safe.\n const body = randomBytes(24).toString('base64url');\n const key = API_KEY_PREFIX + body;\n return { key, hash: hashKey(key), prefix: API_KEY_PREFIX + body.slice(0, DISPLAY_BODY) };\n}\n\n/**\n * Permissions a key can carry on top of the default (call tools, read its\n * owner's data). Opt-in per key, never inherited from the account.\n *\n * `policy:write` exists because keys live in agent MCP configs: a key that can\n * rewrite selection policy is a key the governed agent could use to allow the\n * package it was just refused. Only a key minted for a person or CI gets it.\n */\nexport const KEY_SCOPES = ['policy:write'] as const;\nexport type KeyScope = (typeof KEY_SCOPES)[number];\n\n/** Untrusted input → known scopes, deduped; null on anything unrecognised. */\nexport function parseScopes(input: unknown): KeyScope[] | null {\n if (input === undefined || input === null) return [];\n if (!Array.isArray(input)) return null;\n const out = new Set<KeyScope>();\n for (const item of input) {\n if (!KEY_SCOPES.includes(item as KeyScope)) return null;\n out.add(item as KeyScope);\n }\n return [...out];\n}\n\nexport function hasScope(row: Pick<ApiKeyRow, 'scopes'>, scope: KeyScope): boolean {\n return row.scopes.includes(scope);\n}\n\nexport interface CreateKeyInput {\n label?: string;\n tier?: string;\n ownerId?: string;\n scopes?: KeyScope[];\n}\n\n/** Create and persist a key. Returns the plaintext ONCE plus the stored row. */\nexport async function createKey(\n db: Database,\n input: CreateKeyInput = {},\n): Promise<{ key: string; row: ApiKeyRow }> {\n const { key, hash, prefix } = generateApiKey();\n const [row] = await db\n .insert(apiKeys)\n .values({\n keyHash: hash,\n prefix,\n label: input.label,\n tier: input.tier ?? 'free',\n ownerId: input.ownerId,\n scopes: input.scopes ?? [],\n })\n .returning();\n return { key, row: row! };\n}\n\n/**\n * Short-TTL cache of resolved keys. Auth runs on every hosted request, so an\n * uncached lookup means a SELECT (plus a lastUsedAt UPDATE) per call — pure load\n * on the DB, which is the scaling bottleneck. We cache only *valid* keys (the\n * hot path); unknown tokens always hit the DB so a flood of garbage tokens can't\n * bloat the map, and the per-IP limiter blunts that anyway. Trade-off: a revoked\n * key keeps working for up to AUTH_TTL_MS. Process-local; each instance caches\n * independently, which is fine for a bearer check.\n */\ninterface AuthEntry {\n row: ApiKeyRow;\n cachedAt: number;\n lastStampAt: number;\n}\nconst authCache = new Map<string, AuthEntry>();\nconst AUTH_TTL_MS = 60_000;\n/** lastUsedAt is analytics, not correctness — stamp at most this often per key. */\nconst STAMP_INTERVAL_MS = 60_000;\n\n/** Test-only: clear the auth cache so a fresh lookup re-reads the DB. */\nexport function resetAuthCache(): void {\n authCache.clear();\n}\n\n/** Fire-and-forget usage stamp, throttled per key. Never blocks the request. */\nfunction stampLastUsed(db: Database, entry: AuthEntry, now: number): void {\n if (now - entry.lastStampAt < STAMP_INTERVAL_MS) return;\n entry.lastStampAt = now;\n db.update(apiKeys)\n .set({ lastUsedAt: new Date(now) })\n .where(eq(apiKeys.id, entry.row.id))\n .then(undefined, (err) => logger.debug(`lastUsedAt stamp failed: ${String(err)}`));\n}\n\n/**\n * Look up an active (non-revoked) key by its plaintext form. Returns null if the\n * key is unknown or revoked. Cached for AUTH_TTL_MS; stamps `lastUsedAt`\n * best-effort (throttled) without blocking.\n */\nexport async function lookupActiveKey(db: Database, key: string): Promise<ApiKeyRow | null> {\n const hash = hashKey(key);\n const now = Date.now();\n\n const cached = authCache.get(hash);\n if (cached && now - cached.cachedAt < AUTH_TTL_MS) {\n stampLastUsed(db, cached, now);\n return cached.row;\n }\n\n const [row] = await db\n .select()\n .from(apiKeys)\n .where(and(eq(apiKeys.keyHash, hash), isNull(apiKeys.revokedAt)))\n .limit(1);\n if (!row) {\n authCache.delete(hash); // e.g. a key revoked since it was last cached\n return null;\n }\n const entry: AuthEntry = { row, cachedAt: now, lastStampAt: 0 };\n authCache.set(hash, entry);\n stampLastUsed(db, entry, now);\n return row;\n}\n\nexport async function listKeys(db: Database): Promise<ApiKeyRow[]> {\n return db.select().from(apiKeys).orderBy(desc(apiKeys.createdAt));\n}\n\n/** Keys belonging to one dashboard account (§ hosted dashboard), newest first. */\nexport async function listKeysForOwner(db: Database, ownerId: string): Promise<ApiKeyRow[]> {\n return db\n .select()\n .from(apiKeys)\n .where(eq(apiKeys.ownerId, ownerId))\n .orderBy(desc(apiKeys.createdAt));\n}\n\n/** Resolve a \"prefix or numeric id\" argument to a Drizzle equality filter. */\nfunction matchByPrefixOrId(prefixOrId: string) {\n const asId = Number(prefixOrId);\n return Number.isInteger(asId) && String(asId) === prefixOrId.trim()\n ? eq(apiKeys.id, asId)\n : eq(apiKeys.prefix, prefixOrId);\n}\n\n/**\n * Resolve a key by display prefix, scoped to one owner — the ownership check\n * the dashboard's revoke/rotate routes use before touching the row. Returns\n * null if no active key with that prefix belongs to this owner (never reveals\n * whether a key with that prefix exists for someone else).\n *\n * The owner is a WHERE condition, not a check on the row that came back. It used\n * to be the latter, and `LIMIT 1` over a prefix alone meant a collision handed\n * back somebody else's row, which then failed the JS comparison and returned\n * null — so the legitimate owner could never revoke or rotate their own key, on\n * a key they can see listed. The display prefix is only six characters of body\n * (mcp/http.ts says as much where it declines to rate-limit on it), so distinct\n * keys colliding is a birthday problem, not an impossibility.\n *\n * `orderBy(id)` makes the remaining ambiguity — one owner holding two active\n * keys with the same prefix — resolve to the same row every call, so a retry\n * cannot act on a different key than the request that preceded it.\n */\nexport async function findKeyForOwner(\n db: Database,\n args: { prefixOrId: string; ownerId: string },\n): Promise<ApiKeyRow | null> {\n const [row] = await db\n .select()\n .from(apiKeys)\n .where(\n and(\n matchByPrefixOrId(args.prefixOrId),\n eq(apiKeys.ownerId, args.ownerId),\n isNull(apiKeys.revokedAt),\n ),\n )\n .orderBy(apiKeys.id)\n .limit(1);\n return row ?? null;\n}\n\n/**\n * Revoke a key by display prefix or numeric id. Returns how many active keys were\n * revoked (0 if none matched or it was already revoked).\n *\n * NOT owner-scoped, deliberately: this is the operator primitive behind\n * `lurq keys revoke`, where revoking anyone's key is the point. Never hand it a\n * prefix that came from a user — the dashboard routes resolve one through\n * `findKeyForOwner` first and then pass the resulting numeric id, which is what\n * keeps a prefix collision from reaching across accounts.\n */\nexport async function revokeKey(db: Database, prefixOrId: string): Promise<number> {\n const rows = await db\n .update(apiKeys)\n .set({ revokedAt: new Date() })\n .where(and(matchByPrefixOrId(prefixOrId), isNull(apiKeys.revokedAt)))\n .returning({ id: apiKeys.id });\n return rows.length;\n}\n\n/**\n * Rotate (\"swap\") a key: issue a replacement carrying the old key's label, tier,\n * and owner, then revoke the original. Returns the new plaintext (once), the new\n * row, and the revoked row — or null if no active key matched.\n *\n * The new key is created BEFORE the old one is revoked, so a failure mid-rotation\n * leaves the caller with a working key (at worst two active keys, never zero).\n *\n * Owner-scoping is the caller's job here for the same reason as `revokeKey`:\n * operator plane by prefix, dashboard by an id `findKeyForOwner` already vouched\n * for.\n */\nexport async function rotateKey(\n db: Database,\n prefixOrId: string,\n): Promise<{ key: string; row: ApiKeyRow; previous: ApiKeyRow } | null> {\n const [previous] = await db\n .select()\n .from(apiKeys)\n .where(and(matchByPrefixOrId(prefixOrId), isNull(apiKeys.revokedAt)))\n .limit(1);\n if (!previous) return null;\n\n const { key, row } = await createKey(db, {\n label: previous.label ?? undefined,\n tier: previous.tier,\n ownerId: previous.ownerId ?? undefined,\n // Dropping these would silently break a CI job's `policy push` on rotation.\n scopes: parseScopes(previous.scopes) ?? [],\n });\n await db.update(apiKeys).set({ revokedAt: new Date() }).where(eq(apiKeys.id, previous.id));\n return { key, row, previous };\n}\n","/**\n * Selection policy, applied backwards: which repositories already break it.\n *\n * `enforce.ts` rules on a package an agent is *about to* add. That is the half\n * that prevents new drift from a standard, and it is useless against the code\n * already merged — a team that adopts a licence rule on Tuesday has no way to\n * learn that four services shipped an AGPL parser last spring. This answers\n * that: the same rules, run over every dependency every connected repo already\n * declares.\n *\n * Evaluated on read rather than stored at scan time. A policy edit has to change\n * the answer immediately — a conformance figure computed against a rule that has\n * since been relaxed is worse than no figure, because it reads as current. The\n * cost is one policy row and one keyed lookup over the union of declared names,\n * which is the same order of work as loading the repo list itself.\n *\n * Manifests, not the stored drift detail: `RepoDrift.deps` is capped at\n * REPO_DRIFT_DETAIL_CAP for transport, and ruling on a truncated list would\n * report a clean repo that simply had its violations cut off the end.\n */\nimport { and, eq, inArray } from 'drizzle-orm';\nimport { DEFAULT_ECOSYSTEM, type Advisory, type Confidence, type Ecosystem } from '../core/types';\nimport type { Database } from '../db/client';\nimport { packages, repos } from '../db/schema';\nimport { daysSince, getEnforcedPolicy } from '../db/selectionPolicy';\nimport { declaredDeps } from '../github/drift';\nimport { check, hasRules } from './enforce';\nimport type { Exclusion, SelectionPolicy } from './types';\n\n/** Postgres caps bind parameters; chunk the `IN` lists well under it. */\nconst NAME_CHUNK = 500;\n\n/** Violations carried per repo. The total is always reported separately, so a\n * truncated list can never be mistaken for the whole finding. */\nexport const VIOLATION_CAP = 50;\n\n/**\n * The facts one declared dependency is ruled against.\n *\n * `PolicyFacts` plus the evidence grade, which `check` takes on the package\n * argument rather than in facts. Kept as its own type because this loader reads\n * whole manifests (thousands of names) where the recommendation path reads at\n * most five, so the two are allowed to diverge in what they select.\n */\nexport interface RuleFacts {\n license: string | null;\n deprecated: boolean;\n confidence: Confidence | null;\n // Optional, exactly as on `PolicyFacts`: an absent fact abstains rather than\n // convicting, so a caller that never learned one is expressing \"not\n // established\" rather than omitting a required field.\n archived?: boolean;\n advisories?: Advisory[] | null;\n weeklyDownloads?: number | null;\n monthsSinceRelease?: number | null;\n bundleKb?: number | null;\n daysSincePublished?: number | null;\n}\n\nexport interface RepoConformance {\n repoId: number;\n fullName: string;\n /** Declared dependencies the rules could be applied to. */\n checked: number;\n /**\n * Declared, but absent from the index — so no rule was applied to them. Never\n * folded into `checked` and never counted as passing: \"we did not look\" is a\n * different claim from \"it is fine\", and merging them is the all-clear this\n * codebase refuses everywhere else.\n */\n unchecked: number;\n /**\n * Indexed but carrying no confidence grade, while a `minConfidence` floor is\n * set — so that one rule abstained on them. Zero when no floor is configured.\n * Reported because the alternative is a repo that passes a bar nothing was\n * measured against.\n */\n unscored: number;\n /** Every violation found, which may exceed `violations.length`. */\n total: number;\n violations: Exclusion[];\n}\n\nexport interface ConformanceReport {\n /**\n * Whether any rule was in force. False means nothing was evaluated — an empty\n * `repos` list under `enforcing: false` says \"no policy set\", and rendering it\n * as a clean bill of health would be a lie the UI tells on our behalf.\n */\n enforcing: boolean;\n repos: RepoConformance[];\n}\n\n/** Whole months from `date` to now; null when the date is unknown. */\nfunction monthsSince(date: Date | null): number | null {\n if (!date) return null;\n const ms = Date.now() - date.getTime();\n if (ms < 0) return 0;\n return Math.floor(ms / (1000 * 60 * 60 * 24 * 30.44));\n}\n\n/** Every fact the rules read, for the named packages, keyed by name. */\nasync function loadRuleFacts(\n db: Database,\n names: string[],\n ecosystem: Ecosystem = DEFAULT_ECOSYSTEM,\n): Promise<Map<string, RuleFacts>> {\n const out = new Map<string, RuleFacts>();\n for (let i = 0; i < names.length; i += NAME_CHUNK) {\n const rows = await db\n .select({\n name: packages.name,\n license: packages.license,\n deprecated: packages.deprecated,\n confidence: packages.confidence,\n archived: packages.archived,\n advisories: packages.advisories,\n weeklyDownloads: packages.weeklyDownloads,\n lastReleaseAt: packages.lastReleaseAt,\n bundleMinGzipKb: packages.bundleMinGzipKb,\n firstPublishedAt: packages.firstPublishedAt,\n })\n .from(packages)\n .where(\n and(\n inArray(packages.name, names.slice(i, i + NAME_CHUNK)),\n eq(packages.ecosystem, ecosystem),\n ),\n );\n for (const row of rows) {\n out.set(row.name, {\n license: row.license,\n deprecated: row.deprecated,\n confidence: row.confidence,\n archived: row.archived,\n advisories: row.advisories,\n weeklyDownloads: row.weeklyDownloads,\n monthsSinceRelease: monthsSince(row.lastReleaseAt),\n bundleKb: row.bundleMinGzipKb,\n daysSincePublished: daysSince(row.firstPublishedAt),\n });\n }\n }\n return out;\n}\n\n/**\n * Rule one repo's declared dependencies. Pure — names and facts in, counts and\n * violations out — because the abstention rules are the part worth testing\n * exhaustively and a database makes that expensive.\n */\nexport function ruleRepo(\n policy: SelectionPolicy,\n names: string[],\n facts: Map<string, RuleFacts>,\n): Omit<RepoConformance, 'repoId' | 'fullName'> {\n const violations: Exclusion[] = [];\n let checked = 0;\n let unchecked = 0;\n let unscored = 0;\n\n for (const name of names) {\n const fact = facts.get(name);\n // An unindexed package has no confidence grade and no licence on record, so\n // no rule can honestly convict or clear it.\n if (!fact) {\n unchecked += 1;\n continue;\n }\n checked += 1;\n if (policy.minConfidence !== null && fact.confidence === null) unscored += 1;\n const exclusion = check(\n policy,\n // `check` needs a grade and an unscored package has none. The top grade\n // makes the confidence floor abstain rather than convict on a fact never\n // established — \"absent facts never convict\", in enforce.ts — while the\n // licence and deprecation rules still apply normally. The abstention is\n // counted above rather than hidden.\n { name, confidence: fact.confidence ?? 'proven' },\n {\n license: fact.license,\n deprecated: fact.deprecated,\n archived: fact.archived,\n advisories: fact.advisories,\n weeklyDownloads: fact.weeklyDownloads,\n monthsSinceRelease: fact.monthsSinceRelease,\n bundleKb: fact.bundleKb,\n daysSincePublished: fact.daysSincePublished,\n },\n );\n if (exclusion) violations.push(exclusion);\n }\n\n return {\n checked,\n unchecked,\n unscored,\n total: violations.length,\n violations: violations.slice(0, VIOLATION_CAP),\n };\n}\n\n/** Worst first: most violations, then most unruled, then alphabetical. */\nfunction bySeverity(a: RepoConformance, z: RepoConformance): number {\n return z.total - a.total || z.unchecked - a.unchecked || a.fullName.localeCompare(z.fullName);\n}\n\n/**\n * Every connected repo, ruled against the owner's selection policy.\n *\n * Scoped by `ownerId` like every other repo read — the policy and the repos it\n * judges belong to the same account, and there is deliberately no unscoped form.\n */\nexport async function repoConformance(\n db: Database,\n ownerId: string,\n): Promise<ConformanceReport> {\n const policy = await getEnforcedPolicy(db, ownerId);\n // No rules means no work: skip the repo and package reads entirely rather than\n // computing an empty answer expensively.\n if (!hasRules(policy)) return { enforcing: false, repos: [] };\n\n const rows = await db\n .select({ id: repos.id, fullName: repos.fullName, manifests: repos.manifests })\n .from(repos)\n .where(eq(repos.ownerId, ownerId));\n if (!rows.length) return { enforcing: true, repos: [] };\n\n const declaredPerRepo = rows.map((r) => ({\n repoId: r.id,\n fullName: r.fullName,\n names: [...declaredDeps(r.manifests ?? []).keys()],\n }));\n\n // One lookup for the union across every repo: a monorepo fleet shares most of\n // its dependencies, so per-repo queries would re-read the same rows N times.\n const union = [...new Set(declaredPerRepo.flatMap((r) => r.names))];\n const facts = await loadRuleFacts(db, union);\n\n const report = declaredPerRepo.map(({ repoId, fullName, names }) => ({\n repoId,\n fullName,\n ...ruleRepo(policy, names, facts),\n }));\n\n return { enforcing: true, repos: report.sort(bySeverity) };\n}\n","/**\n * The plans: what they cost, what they include, and what they are allowed to\n * spend. ONE definition, imported by both sides.\n *\n * The pricing page reads this through the `@lurq/core/*` alias and the quota\n * enforcement in mcp/http.ts reads it directly, which is the entire point. The\n * previous pricing page carried its own copy of the numbers and opened with a\n * comment admitting they were placeholders that nothing enforced; a marketing\n * page and a 429 disagreeing about what you bought is the kind of bug you find\n * out about from a customer.\n *\n * `monthlyCalls: null` means uncapped. Free is deliberately usable without a\n * card: an index nobody can try is an index nobody adopts.\n *\n * Prices are in cents and exist here for display only. Stripe is the authority\n * on what anyone is actually charged, and the amount shown to a reader is not\n * the amount in the Price object unless someone keeps them in step, so treat a\n * change here as needing the matching change in the Stripe dashboard.\n */\n\nexport type Tier = 'free' | 'pro' | 'enterprise';\n\nexport const TIERS = ['free', 'pro', 'enterprise'] as const;\n\nexport interface Plan {\n tier: Tier;\n name: string;\n /** Display only. Stripe holds the real number. */\n priceCents: number;\n /** Hosted tool calls per calendar month. null = uncapped. */\n monthlyCalls: number | null;\n /** Per-minute burst ceiling, enforced by the express limiter. */\n ratePerMinute: number;\n /** One line under the price. Kept to a single clause. */\n tagline: string;\n /** Shown on the card. Lead with what changes from the tier below. */\n features: string[];\n /** Requires a Stripe subscription. Free never does. */\n paid: boolean;\n /** Priced on application rather than self-serve checkout. */\n contactOnly?: boolean;\n}\n\nexport const PLANS: Record<Tier, Plan> = {\n free: {\n tier: 'free',\n name: 'Free',\n priceCents: 0,\n monthlyCalls: 200,\n ratePerMinute: 60,\n tagline: 'Enough to find out whether the index is telling the truth.',\n features: [\n 'CLI and installable skill',\n '200 hosted calls a month',\n 'recommend, evaluate, verify',\n 'Daily refreshed index',\n 'Community support',\n ],\n paid: false,\n },\n pro: {\n tier: 'pro',\n name: 'Pro',\n priceCents: 500,\n monthlyCalls: 10_000,\n ratePerMinute: 120,\n tagline: 'For one developer who runs it on every install.',\n features: [\n '10,000 hosted calls a month',\n 'compare, diagram and plan',\n 'Repo autopilot and drift alerts',\n 'Priority index freshness',\n 'Email support',\n ],\n paid: true,\n },\n enterprise: {\n tier: 'enterprise',\n name: 'Enterprise',\n priceCents: 10_000,\n monthlyCalls: null,\n ratePerMinute: 600,\n tagline: 'For a team that needs the graph under its own controls.',\n features: [\n 'Uncapped hosted calls',\n 'SSO and audit logs',\n 'Private compatibility runs',\n 'Custom SLA',\n 'Dedicated support channel',\n ],\n paid: true,\n contactOnly: true,\n },\n};\n\nexport const PLAN_LIST: Plan[] = TIERS.map((t) => PLANS[t]);\n\n/** Unknown or malformed tier strings resolve to Free, never to unlimited. */\nexport function planFor(tier: string | null | undefined): Plan {\n return PLANS[(tier ?? 'free') as Tier] ?? PLANS.free;\n}\n\n/**\n * Whether a subscription in this Stripe status should still be served at its\n * paid tier.\n *\n * `past_due` deliberately counts. A card that failed at 03:00 is a dunning\n * problem, not a reason to start 429ing someone's CI mid-run; Stripe retries\n * for days and only then moves the subscription to `canceled`, which does not\n * count here. Cutting service on the first failed charge is how you turn an\n * expired card into a churned customer.\n */\nexport const SERVED_STATUSES = new Set(['active', 'trialing', 'past_due']);\n\nexport function isServed(status: string | null | undefined): boolean {\n return status != null && SERVED_STATUSES.has(status);\n}\n","/**\n * Reads and writes for `subscriptions`, plus the entitlement question the\n * request path actually asks: what is this account allowed to do right now.\n *\n * Two things write here: the Stripe webhook, and `grantPlan` for a plan sold\n * before a processor existed. Everything else reads.\n */\nimport { and, desc, eq, gte, isNull, like, lte, or, sql } from 'drizzle-orm';\nimport { isServed, planFor, type Plan, type Tier } from '../core/plans';\nimport type { Database } from './client';\nimport { ownerUsageDaily, subscriptions, type SubscriptionRow } from './schema';\n\n/**\n * Marks a row as hand-granted rather than Stripe-backed.\n *\n * `stripe_customer_id` is `not null unique`, and a manual grant has no Stripe\n * customer to put there. A synthetic id keyed on the owner satisfies both\n * constraints, cannot collide with a real `cus_...`, and makes every hand-issued\n * plan greppable in one `like` — which is what the expiry gate in\n * `entitlementFor` keys off.\n */\nconst MANUAL_PREFIX = 'manual:';\n\nexport const manualCustomerId = (ownerId: string) => `${MANUAL_PREFIX}${ownerId}`;\n\nexport function isManualGrant(sub: { stripeCustomerId: string }): boolean {\n return sub.stripeCustomerId.startsWith(MANUAL_PREFIX);\n}\n\n/** Past its end date. Only ever true of a manual grant; see `entitlementFor`. */\nexport function grantLapsed(sub: SubscriptionRow, now: Date): boolean {\n return (\n isManualGrant(sub) &&\n sub.currentPeriodEnd != null &&\n sub.currentPeriodEnd.getTime() <= now.getTime()\n );\n}\n\nexport async function getSubscription(\n db: Database,\n ownerId: string,\n): Promise<SubscriptionRow | null> {\n const rows = await db\n .select()\n .from(subscriptions)\n .where(eq(subscriptions.ownerId, ownerId))\n .limit(1);\n return rows[0] ?? null;\n}\n\nexport async function getSubscriptionByCustomer(\n db: Database,\n stripeCustomerId: string,\n): Promise<SubscriptionRow | null> {\n const rows = await db\n .select()\n .from(subscriptions)\n .where(eq(subscriptions.stripeCustomerId, stripeCustomerId))\n .limit(1);\n return rows[0] ?? null;\n}\n\n/** Link an account to its Stripe customer, before any subscription exists. */\nexport async function linkCustomer(\n db: Database,\n ownerId: string,\n stripeCustomerId: string,\n): Promise<void> {\n await db\n .insert(subscriptions)\n .values({ ownerId, stripeCustomerId })\n .onConflictDoUpdate({\n target: subscriptions.ownerId,\n set: { stripeCustomerId, updatedAt: new Date() },\n });\n}\n\nexport interface SubscriptionUpdate {\n tier: Tier;\n status: string | null;\n stripeSubscriptionId: string | null;\n currentPeriodEnd: Date | null;\n cancelAtPeriodEnd: boolean;\n eventAt: Date;\n}\n\n/**\n * Apply a webhook's view of a subscription.\n *\n * The `last_event_at` guard is the important part. Stripe does not promise\n * ordering and retries for up to three days, so a redelivered\n * `customer.subscription.updated` from before a cancellation can easily arrive\n * after it. Without the guard that resurrects a cancelled plan, and the customer\n * keeps being served something they stopped paying for until the next event\n * happens to correct it. Older events are dropped, not applied.\n */\nexport async function applySubscriptionEvent(\n db: Database,\n stripeCustomerId: string,\n update: SubscriptionUpdate,\n): Promise<boolean> {\n const result = await db\n .insert(subscriptions)\n .values({\n // A webhook can legitimately arrive for a customer we have no row for\n // (created in the Stripe dashboard, or our insert lost a race with\n // checkout). ownerId comes from customer metadata in that case; the\n // caller resolves it and passes a row that already exists, so this\n // conflict target is the customer, not the owner.\n ownerId: sql`coalesce(\n (select s.owner_id from subscriptions s where s.stripe_customer_id = ${stripeCustomerId}),\n ${'stripe:' + stripeCustomerId}\n )`,\n stripeCustomerId,\n stripeSubscriptionId: update.stripeSubscriptionId,\n tier: update.tier,\n status: update.status,\n currentPeriodEnd: update.currentPeriodEnd,\n cancelAtPeriodEnd: update.cancelAtPeriodEnd,\n lastEventAt: update.eventAt,\n updatedAt: new Date(),\n })\n .onConflictDoUpdate({\n target: subscriptions.stripeCustomerId,\n set: {\n stripeSubscriptionId: update.stripeSubscriptionId,\n tier: update.tier,\n status: update.status,\n currentPeriodEnd: update.currentPeriodEnd,\n cancelAtPeriodEnd: update.cancelAtPeriodEnd,\n lastEventAt: update.eventAt,\n updatedAt: new Date(),\n },\n // Typed operators, NOT a raw sql`` template. Drizzle applies a column's\n // type mapper only to values it can attribute to a column, so a Date\n // interpolated into sql`` reaches postgres.js unconverted and the driver\n // throws \"The \\\"string\\\" argument must be of type string ... Received an\n // instance of Date\". That threw on every event this table has ever seen:\n // the webhook 200s before doing the work, so Stripe recorded success,\n // never retried, and every paid account silently stayed on free.\n setWhere: or(\n isNull(subscriptions.lastEventAt),\n lte(subscriptions.lastEventAt, update.eventAt),\n ),\n })\n .returning({ ownerId: subscriptions.ownerId });\n return result.length > 0;\n}\n\n/**\n * Hand-grant a paid plan to an account, for money collected outside Stripe.\n *\n * `entitlementFor` reads tier and status and has no opinion about who collected,\n * so from the request path this is indistinguishable from a subscription.\n *\n * `months` is required and capped by the caller. A hand-granted plan has nobody\n * watching it: no webhook arrives when a card fails, when the customer cancels,\n * or when a month simply is not paid again. An open-ended grant is a free\n * account in perpetuity that nobody remembers creating, and it fails silently\n * and forever — so the end date is mandatory and enforced on read.\n *\n * Refuses to touch a Stripe-backed row. Overwriting a real subscription with a\n * manual one would orphan the Stripe customer: the webhook would keep arriving\n * for a `stripe_customer_id` no longer on the row, and the next event would\n * insert a duplicate account.\n *\n * ponytail: no `note` column, so the invoice number lives wherever you invoiced.\n * Add one (nullable text + migration) when \"who is this and why\" stops being\n * answerable from memory.\n */\nexport async function grantPlan(\n db: Database,\n opts: { ownerId: string; tier: Tier; months: number; now?: Date },\n): Promise<{ granted: true; until: Date } | { granted: false; reason: string }> {\n const now = opts.now ?? new Date();\n const until = new Date(now);\n until.setMonth(until.getMonth() + opts.months);\n\n const existing = await getSubscription(db, opts.ownerId);\n if (existing && !isManualGrant(existing)) {\n return { granted: false, reason: 'account has a Stripe subscription; manage it in Stripe' };\n }\n\n await db\n .insert(subscriptions)\n .values({\n ownerId: opts.ownerId,\n stripeCustomerId: manualCustomerId(opts.ownerId),\n tier: opts.tier,\n status: 'active',\n currentPeriodEnd: until,\n updatedAt: now,\n })\n .onConflictDoUpdate({\n target: subscriptions.ownerId,\n set: { tier: opts.tier, status: 'active', currentPeriodEnd: until, updatedAt: now },\n });\n\n return { granted: true, until };\n}\n\n/** End a hand-granted plan now. Stripe-backed rows are refused, not cancelled. */\nexport async function revokeGrant(\n db: Database,\n ownerId: string,\n now = new Date(),\n): Promise<{ revoked: boolean; reason?: string }> {\n const existing = await getSubscription(db, ownerId);\n if (!existing) return { revoked: false, reason: 'no subscription for that account' };\n if (!isManualGrant(existing)) {\n return { revoked: false, reason: 'Stripe-backed; cancel it in Stripe, not here' };\n }\n\n await db\n .update(subscriptions)\n .set({ status: 'canceled', currentPeriodEnd: now, updatedAt: now })\n .where(eq(subscriptions.ownerId, ownerId));\n return { revoked: true };\n}\n\n/**\n * Every hand-granted plan, soonest to lapse first.\n *\n * Lapsed grants stay listed rather than disappearing, so the date is visible\n * when it passes and can be renewed or chased.\n */\nexport async function listGrants(db: Database): Promise<SubscriptionRow[]> {\n return db\n .select()\n .from(subscriptions)\n .where(like(subscriptions.stripeCustomerId, `${MANUAL_PREFIX}%`))\n .orderBy(subscriptions.currentPeriodEnd, desc(subscriptions.updatedAt));\n}\n\n/** Calls this account has made in the current calendar month, all tools. */\nexport async function monthlyCallCount(db: Database, ownerId: string): Promise<number> {\n const rows = await db\n .select({ total: sql<string>`coalesce(sum(${ownerUsageDaily.count}), 0)` })\n .from(ownerUsageDaily)\n .where(\n and(\n eq(ownerUsageDaily.ownerId, ownerId),\n gte(ownerUsageDaily.date, sql`date_trunc('month', CURRENT_DATE)::date`),\n ),\n );\n return Number(rows[0]?.total ?? 0);\n}\n\nexport interface Entitlement {\n plan: Plan;\n /** Calls used this calendar month. */\n used: number;\n /** False once the monthly allowance is spent. Uncapped plans are always true. */\n withinQuota: boolean;\n}\n\n/**\n * What this account may do right now: the plan it is entitled to, and whether it\n * has spent the month's allowance.\n *\n * A subscription whose status Stripe no longer serves (`canceled`, `unpaid`,\n * `incomplete_expired`) falls back to Free rather than to nothing. Someone who\n * cancels keeps the free tier they would have had if they had never paid, which\n * is both the kinder behaviour and the one that does not break their CI on the\n * day their card expires.\n *\n * A hand-granted plan additionally lapses at its end date. Stripe-backed rows\n * are deliberately NOT gated this way: Stripe tells us when a subscription ends,\n * and gating on the date as well would drop a paying customer for the minutes\n * between a renewal and its webhook.\n */\nexport async function entitlementFor(\n db: Database,\n ownerId: string | null | undefined,\n): Promise<Entitlement> {\n // Operator-issued keys have no dashboard account. They are ours, not a\n // customer's, and are not metered.\n if (!ownerId) {\n return { plan: planFor('enterprise'), used: 0, withinQuota: true };\n }\n\n const [sub, used] = await Promise.all([\n getSubscription(db, ownerId),\n monthlyCallCount(db, ownerId),\n ]);\n\n const served = sub != null && isServed(sub.status) && !grantLapsed(sub, new Date());\n const plan = planFor(served ? sub!.tier : 'free');\n const withinQuota = plan.monthlyCalls === null || used < plan.monthlyCalls;\n return { plan, used, withinQuota };\n}\n","/**\n * Stripe, and the only place in the codebase that holds a Stripe credential.\n *\n * The web app has none. It reaches checkout and the portal through the\n * issuer-secret routes on this service, exactly the way it reaches key issuance,\n * so the surface that faces the internet keeps holding nothing worth stealing.\n *\n * The SDK is imported dynamically. `stripe` is a dependency of the published\n * `lurqrun` package only because this file lives in the same tree, and a static\n * import would make every CLI invocation — `lurq recommend` on someone's laptop\n * — pay to load a payments SDK it will never call. Same reason express and\n * helmet are dynamic in mcp/http.ts.\n */\nimport type Stripe from 'stripe';\nimport { getConfig } from '../core/config';\nimport { logger } from '../core/logger';\nimport { PLANS, type Tier } from '../core/plans';\nimport type { Database } from '../db/client';\nimport { applySubscriptionEvent, getSubscription, linkCustomer } from '../db/subscriptions';\n\n/**\n * Pinned deliberately. Stripe's API is versioned per-account, and letting the\n * SDK send whatever it defaults to means an SDK bump can silently change the\n * shape of the objects the webhook reads. Move this on purpose, after reading\n * the changelog, not as a side effect of `npm update`.\n */\nconst API_VERSION = '2025-03-31.basil';\n\nlet clientPromise: Promise<Stripe | null> | null = null;\n\n/** Null when STRIPE_SECRET_KEY is unset, which disables billing everywhere. */\nexport async function stripeClient(): Promise<Stripe | null> {\n const { STRIPE_SECRET_KEY } = getConfig();\n if (!STRIPE_SECRET_KEY) return null;\n if (!clientPromise) {\n clientPromise = (async () => {\n const { default: StripeCtor } = await import('stripe');\n return new StripeCtor(STRIPE_SECRET_KEY, {\n apiVersion: API_VERSION as Stripe.LatestApiVersion,\n // Retries on Stripe's side of a network blip. The default is 0, which\n // turns one dropped connection into a failed checkout for a real person.\n maxNetworkRetries: 2,\n timeout: 15_000,\n });\n })();\n }\n return clientPromise;\n}\n\nexport function billingEnabled(): boolean {\n return Boolean(getConfig().STRIPE_SECRET_KEY);\n}\n\n/** The configured Price id for a tier, or null if that tier is not self-serve. */\nexport function priceIdFor(tier: Tier): string | null {\n const config = getConfig();\n if (tier === 'pro') return config.STRIPE_PRICE_PRO ?? null;\n if (tier === 'enterprise') return config.STRIPE_PRICE_ENTERPRISE ?? null;\n return null;\n}\n\n/**\n * Reverse of {@link priceIdFor}: which tier a Stripe Price grants.\n *\n * Falls back to the tier stamped in subscription metadata at checkout, because\n * a Price can be swapped in the dashboard (a promo, a grandfathered rate) and an\n * unrecognised Price must not silently downgrade a paying customer to free.\n * Unknown and unstamped means free, which is the safe direction to be wrong in\n * for entitlement but the one to watch the logs for.\n */\nexport function tierForPrice(priceId: string | null, metadataTier?: string | null): Tier {\n const config = getConfig();\n if (priceId && priceId === config.STRIPE_PRICE_PRO) return 'pro';\n if (priceId && priceId === config.STRIPE_PRICE_ENTERPRISE) return 'enterprise';\n if (metadataTier && metadataTier in PLANS) return metadataTier as Tier;\n if (priceId) {\n logger.warn(`billing: price ${priceId} maps to no configured tier; treating as free`);\n }\n return 'free';\n}\n\n/**\n * The account's Stripe customer, created on first need.\n *\n * `ownerId` goes into customer metadata as well as our own table: a webhook for\n * a customer whose row we somehow lack can still be attributed, and a human\n * looking at the Stripe dashboard can tell who a customer is without a join.\n */\nexport async function customerFor(\n db: Database,\n ownerId: string,\n email?: string | null,\n): Promise<string | null> {\n const stripe = await stripeClient();\n if (!stripe) return null;\n\n const existing = await getSubscription(db, ownerId);\n if (existing?.stripeCustomerId) return existing.stripeCustomerId;\n\n const customer = await stripe.customers.create({\n ...(email ? { email } : {}),\n metadata: { ownerId },\n });\n await linkCustomer(db, ownerId, customer.id);\n return customer.id;\n}\n\nexport interface CheckoutRequest {\n ownerId: string;\n tier: Tier;\n email?: string | null;\n}\n\n/**\n * A hosted Checkout Session for a paid plan. Returns the URL to send the\n * browser to, or null when billing or that tier is not configured.\n *\n * Nothing is granted here. Since API version 2025-03-31.basil the subscription\n * is not even created until payment completes, so the success redirect proves\n * only that the customer reached the end of a form. Entitlement is written by\n * the webhook and nowhere else.\n */\nexport async function createCheckoutSession(\n db: Database,\n req: CheckoutRequest,\n): Promise<string | null> {\n const stripe = await stripeClient();\n if (!stripe) return null;\n\n const price = priceIdFor(req.tier);\n if (!price) return null;\n\n const customer = await customerFor(db, req.ownerId, req.email);\n if (!customer) return null;\n\n const config = getConfig();\n const base = config.LURQ_WEB_URL.replace(/\\/$/, '');\n const params: Stripe.Checkout.SessionCreateParams = {\n mode: 'subscription',\n customer,\n line_items: [{ price, quantity: 1 }],\n // Stripe substitutes the real id. The dashboard reads it to poll for the\n // webhook having landed, so the page after payment can say \"active\" rather\n // than \"we think so\".\n success_url: `${base}/dashboard/billing?checkout={CHECKOUT_SESSION_ID}`,\n cancel_url: `${base}/#pricing`,\n // Carried onto the Subscription so tierForPrice has a fallback if the Price\n // is later swapped out from under us.\n subscription_data: { metadata: { ownerId: req.ownerId, tier: req.tier } },\n metadata: { ownerId: req.ownerId, tier: req.tier },\n allow_promotion_codes: true,\n // Stripe Tax works out VAT/sales tax per the customer's address. On its own\n // that is only half of merchant-of-record: registration and remittance stay\n // ours. STRIPE_MANAGED_PAYMENTS below buys the other half when it is on.\n // Left enabled either way — it is what calculates tax when it is off, and\n // Managed Payments supersedes rather than conflicts with it when it is on.\n automatic_tax: { enabled: true },\n billing_address_collection: 'auto',\n };\n\n // Sent on every session, true or false, because Stripe applies an account-level\n // default when the parameter is absent — so omitting it would let a dashboard\n // toggle decide, and the symptom of that disagreeing with our products is a 400\n // in someone's checkout. Not in stripe@22.6.0's types yet, so it goes on via a\n // narrow cast rather than widening the whole params object (every other\n // parameter stays checked) and rather than bumping the SDK, which would move\n // the pinned API version's object shapes out from under handleEvent.\n (params as Record<string, unknown>).managed_payments = {\n enabled: config.STRIPE_MANAGED_PAYMENTS,\n };\n\n const session = await stripe.checkout.sessions.create(params);\n return session.url;\n}\n\n/** Stripe's own subscription-management UI. Null if the account has no customer. */\nexport async function createPortalSession(db: Database, ownerId: string): Promise<string | null> {\n const stripe = await stripeClient();\n if (!stripe) return null;\n\n const sub = await getSubscription(db, ownerId);\n if (!sub?.stripeCustomerId) return null;\n\n const base = getConfig().LURQ_WEB_URL.replace(/\\/$/, '');\n const session = await stripe.billingPortal.sessions.create({\n customer: sub.stripeCustomerId,\n return_url: `${base}/dashboard/billing`,\n });\n return session.url;\n}\n\n/** Verify a webhook payload. Throws when the signature does not check out. */\nexport async function constructEvent(\n raw: Buffer | string,\n signature: string | undefined,\n): Promise<Stripe.Event | null> {\n const stripe = await stripeClient();\n const secret = getConfig().STRIPE_WEBHOOK_SECRET;\n if (!stripe || !secret || !signature) return null;\n return stripe.webhooks.constructEvent(raw, signature, secret);\n}\n\n/** Events that move entitlement. Everything else is acknowledged and ignored. */\nconst HANDLED = new Set([\n 'checkout.session.completed',\n 'customer.subscription.created',\n 'customer.subscription.updated',\n 'customer.subscription.deleted',\n]);\n\nfunction periodEnd(sub: Stripe.Subscription): Date | null {\n // Basil moved current_period_end onto the subscription item. Read the item\n // first and fall back, so this survives both shapes rather than silently\n // recording null and showing \"renews —\" in the dashboard forever.\n const item = sub.items?.data?.[0] as { current_period_end?: number } | undefined;\n const raw =\n item?.current_period_end ??\n (sub as unknown as { current_period_end?: number }).current_period_end;\n return typeof raw === 'number' ? new Date(raw * 1000) : null;\n}\n\n/**\n * Apply one verified event. Returns what happened, for the log.\n *\n * Deliberately tolerant: an event we cannot attribute is a warning and a 200,\n * never a 500. Stripe retries a non-2xx for three days, so answering an\n * unattributable event with an error buys a retry storm and no new information.\n */\nexport async function handleEvent(db: Database, event: Stripe.Event): Promise<string> {\n if (!HANDLED.has(event.type)) return `ignored ${event.type}`;\n\n const stripe = await stripeClient();\n if (!stripe) return 'billing disabled';\n\n let subscription: Stripe.Subscription | null = null;\n\n if (event.type === 'checkout.session.completed') {\n const session = event.data.object as Stripe.Checkout.Session;\n const id =\n typeof session.subscription === 'string' ? session.subscription : session.subscription?.id;\n // A one-off or setup-mode session has no subscription. Nothing to grant.\n if (!id) return 'checkout completed with no subscription';\n subscription = await stripe.subscriptions.retrieve(id);\n } else {\n subscription = event.data.object as Stripe.Subscription;\n }\n\n const customerId =\n typeof subscription.customer === 'string' ? subscription.customer : subscription.customer?.id;\n if (!customerId) return 'event carried no customer';\n\n const priceId = subscription.items?.data?.[0]?.price?.id ?? null;\n // A deleted subscription grants nothing regardless of which Price it held.\n const tier: Tier =\n event.type === 'customer.subscription.deleted'\n ? 'free'\n : tierForPrice(priceId, subscription.metadata?.tier);\n\n const applied = await applySubscriptionEvent(db, customerId, {\n tier,\n status: event.type === 'customer.subscription.deleted' ? 'canceled' : subscription.status,\n stripeSubscriptionId: subscription.id,\n currentPeriodEnd: periodEnd(subscription),\n cancelAtPeriodEnd: Boolean(subscription.cancel_at_period_end),\n eventAt: new Date(event.created * 1000),\n });\n\n return applied\n ? `${event.type}: customer ${customerId} → ${tier} (${subscription.status})`\n : `${event.type}: superseded by a newer event, dropped`;\n}\n","/**\n * Migration hop planning.\n *\n * Nobody upgrades react-router 6.9.2 → 8.1.0 in one edit. They go 6 → 7, get the\n * codebase green, then 7 → 8. The brief has to say that, because the ordering is\n * most of the work and a single 6→8 diff hides which breakage belongs to which\n * step.\n *\n * The hop list is NOT how breakage is decided. The direct `from → to` diff stays\n * authoritative for \"will my code break\": a symbol removed at 7 and restored at\n * 8 is not a breakage, and unioning per-hop removals would report it as one.\n * Hops answer a different question — *in what order do I do this* — and the two\n * are kept separate on purpose (see `briefUpgrade`).\n */\nimport semver from 'semver';\n\n/** Hops past this are a rewrite, not an upgrade; the brief says so rather than\n * fanning out a dozen surface extractions nobody will read. */\nexport const MAX_HOPS = 4;\n\n/**\n * The highest non-prerelease release of each major between `from` and `to`.\n *\n * Prereleases are excluded throughout: `semver.maxSatisfying` with\n * `includePrerelease: false` is what an install resolves to, and routing a\n * migration through an alpha nobody shipped would be actively misleading.\n */\nexport function planHops(versions: string[], from: string, to: string): string[] {\n if (!semver.valid(from) || !semver.valid(to)) return [];\n if (!semver.gt(to, from)) return [];\n\n const fromMajor = semver.major(from);\n const toMajor = semver.major(to);\n // Same major, or adjacent majors: the direct diff already IS the single hop.\n if (toMajor - fromMajor < 2) return [];\n\n const stops: string[] = [];\n for (let major = fromMajor + 1; major < toMajor; major++) {\n const best = semver.maxSatisfying(versions, `${major}.x`, { includePrerelease: false });\n // A major with no known release is a gap in our version timeline, not a\n // major that does not exist. Skipping it silently would claim a shorter\n // migration than the real one, so the caller reports `truncated` instead.\n if (best) stops.push(best);\n }\n\n const path = [from, ...stops, to];\n return path.length > MAX_HOPS + 1 ? [] : path;\n}\n\n/** Consecutive pairs of a hop path — the diffs actually worth computing. */\nexport function hopPairs(path: string[]): { fromVersion: string; toVersion: string }[] {\n const pairs: { fromVersion: string; toVersion: string }[] = [];\n for (let i = 0; i < path.length - 1; i++) {\n pairs.push({ fromVersion: path[i]!, toVersion: path[i + 1]! });\n }\n return pairs;\n}\n\n/**\n * True when the majors between `from` and `to` exceed what we will plan.\n * Surfaced so the brief can say \"too far to sequence\" rather than quietly\n * presenting a one-shot diff as the whole story.\n */\nexport function tooFarToSequence(from: string, to: string): boolean {\n if (!semver.valid(from) || !semver.valid(to)) return false;\n return semver.major(to) - semver.major(from) > MAX_HOPS;\n}\n","/**\n * Migration brief: for each dependency a repo is behind on, what does the\n * upgrade actually remove from the public API?\n *\n * This is the half of the answer that can be computed without the source. It\n * says \"react-router 6.9.2 → 8.1.0 removes 14 runtime exports\", which is a fact\n * about the packages. It deliberately does NOT say \"this breaks your code\" —\n * that requires knowing which of those 14 the repo references, and the reference\n * scan runs in the user's own CI where the source already is. The CI half feeds\n * the same symbols into `checkUpgradeOne` (src/surface/upgrade.ts) to narrow\n * `removesExports` down to `symbolsRemoved`.\n *\n * Wording matters here and is load-bearing: a brief that overclaims once gets\n * the whole gate switched off (§12 M3). Every field name says what was measured.\n */\nimport type { Database } from '../db/client';\nimport { handleDiffSurface } from '../mcp/surfaceHandlers';\nimport { loadVersions } from './drift';\nimport { hopPairs, planHops, tooFarToSequence } from './hops';\nimport type { DepDeclaration, DepDrift, RepoDrift } from './types';\n\n/**\n * What the diff established about an upgrade.\n * `removes-exports` — runtime exports disappear. Whether THIS repo calls them\n * is the CI half; on its own this is a real hazard signal.\n * `arity-changed` — nothing removed, but a signature took a different count.\n * `clean` — surfaces compared, nothing removed or re-shaped.\n * `unknown` — one or both surfaces are not extracted yet. Queued by the\n * diff call itself. NEVER folded into `clean`.\n */\nexport type UpgradeVerdict = 'removes-exports' | 'arity-changed' | 'clean' | 'unknown';\n\n/** One step of a multi-major migration. */\nexport interface UpgradeHop {\n fromVersion: string;\n toVersion: string;\n verdict: UpgradeVerdict;\n removed: string[];\n arityChanged: { path: string; from: number | null; to: number | null }[];\n}\n\nexport interface UpgradeBrief {\n package: string;\n fromVersion: string;\n toVersion: string;\n /**\n * Every manifest declaring this package. A monorepo needs all of them: bumping\n * only the root leaves the workspace pinned to the old major and the upgrade\n * half-applied, which typechecks locally and breaks on install.\n */\n declaredIn: DepDeclaration[];\n majorsBehind: number;\n advisories: number;\n deprecated: boolean;\n verdict: UpgradeVerdict;\n /** Runtime exports present in `from` and gone in `to`. */\n removed: string[];\n /** Exports whose parameter count changed — silent misbehaviour, not a crash. */\n arityChanged: { path: string; from: number | null; to: number | null }[];\n /** Removed type-only exports. Breaks `tsc`, never `node` — separated on purpose. */\n typeOnlyRemoved: string[];\n /** Exports newly marked `@deprecated` at the target version. */\n newlyDeprecated: string[];\n /** Why the answer is `unknown`, when it is. */\n inconclusive?: string;\n /**\n * The migration sequence, when the upgrade crosses two or more majors. Empty\n * for a single-major bump, where the direct diff already is the only hop.\n *\n * These do NOT determine breakage — the fields above do, from the direct\n * from→to diff. A symbol dropped at 7 and restored at 8 appears in a hop and\n * correctly does not appear in `removed`.\n */\n hops: UpgradeHop[];\n /** Set when the sequence could not be planned, and why. Never left implicit:\n * an absent hop list would otherwise read as \"this is a one-step upgrade\". */\n sequenceNote?: string;\n}\n\nexport interface RepoBrief {\n upgrades: UpgradeBrief[];\n /** Drifted deps not briefed because of the cap — reported, never silent. */\n omitted: number;\n /** Upgrades whose surfaces are still being extracted. */\n pending: number;\n}\n\n/** Diffs per brief. Each is two indexed reads, but a 200-dep monorepo would\n * otherwise fan out to 200 of them on a page load. */\nexport const BRIEF_CAP = 25;\n\n/** Deps worth briefing: something changed between what they run and what's current. */\nfunction briefable(dep: DepDrift): boolean {\n return Boolean(dep.resolved && dep.latest && dep.resolved !== dep.latest);\n}\n\n/**\n * Rank by consequence, so a cap keeps what matters. Advisories first — an\n * upgrade you must do outranks one you might want to.\n */\nfunction rank(dep: DepDrift): number {\n return dep.advisories * 1000 + dep.majorsBehind * 100 + (dep.deprecated ? 50 : 0);\n}\n\nfunction verdictOf(\n removed: string[],\n arityChanged: unknown[],\n inconclusive: string | undefined,\n): UpgradeVerdict {\n if (inconclusive) return 'unknown';\n if (removed.length > 0) return 'removes-exports';\n if (arityChanged.length > 0) return 'arity-changed';\n return 'clean';\n}\n\n/** Brief one upgrade. Reuses the `diff_surface` handler so there is exactly one\n * implementation of the diff — including its enqueue-on-miss behaviour. */\nexport async function briefUpgrade(\n db: Database,\n dep: DepDrift,\n knownVersions: string[] = [],\n): Promise<UpgradeBrief> {\n const base = {\n package: dep.name,\n fromVersion: dep.resolved!,\n toVersion: dep.latest!,\n declaredIn: dep.declaredIn,\n majorsBehind: dep.majorsBehind,\n advisories: dep.advisories,\n deprecated: dep.deprecated,\n };\n\n // The direct diff is authoritative for breakage. Hops below are sequencing.\n const diff = await handleDiffSurface(db, {\n package: dep.name,\n fromVersion: base.fromVersion,\n toVersion: base.toVersion,\n });\n\n const removed = diff.removed.map((s) => s.path);\n const inconclusive = 'inconclusive' in diff ? (diff.inconclusive as string) : undefined;\n\n const { hops, sequenceNote } = await planSequence(db, dep, base, knownVersions);\n\n return {\n ...base,\n verdict: verdictOf(removed, diff.arityChanged, inconclusive),\n removed,\n arityChanged: diff.arityChanged,\n typeOnlyRemoved: diff.typeOnlyRemoved,\n newlyDeprecated: diff.deprecated ?? [],\n hops,\n ...(inconclusive ? { inconclusive } : {}),\n ...(sequenceNote ? { sequenceNote } : {}),\n };\n}\n\n/** Diff each step of a multi-major migration, so the work can be ordered. */\nasync function planSequence(\n db: Database,\n dep: DepDrift,\n base: { fromVersion: string; toVersion: string },\n knownVersions: string[],\n): Promise<{ hops: UpgradeHop[]; sequenceNote?: string }> {\n if (dep.majorsBehind < 2) return { hops: [] };\n\n if (tooFarToSequence(base.fromVersion, base.toVersion)) {\n return {\n hops: [],\n sequenceNote: `${dep.majorsBehind} majors behind, too far to sequence automatically. Treat this as a migration, not an upgrade.`,\n };\n }\n\n const path = planHops(knownVersions, base.fromVersion, base.toVersion);\n if (path.length === 0) {\n return {\n hops: [],\n sequenceNote: 'Intermediate releases are missing from the index, so the hop sequence could not be planned.',\n };\n }\n\n const hops: UpgradeHop[] = [];\n for (const pair of hopPairs(path)) {\n const hopDiff = await handleDiffSurface(db, { package: dep.name, ...pair });\n const hopRemoved = hopDiff.removed.map((s) => s.path);\n hops.push({\n ...pair,\n verdict: verdictOf(\n hopRemoved,\n hopDiff.arityChanged,\n 'inconclusive' in hopDiff ? (hopDiff.inconclusive as string) : undefined,\n ),\n removed: hopRemoved,\n arityChanged: hopDiff.arityChanged,\n });\n }\n return { hops };\n}\n\n/** Brief a repo's outstanding upgrades, worst-first. */\nexport async function briefRepo(\n db: Database,\n drift: RepoDrift | null,\n limit = BRIEF_CAP,\n): Promise<RepoBrief> {\n if (!drift) return { upgrades: [], omitted: 0, pending: 0 };\n\n const candidates = drift.deps.filter(briefable).sort((a, b) => rank(b) - rank(a));\n const selected = candidates.slice(0, Math.min(limit, BRIEF_CAP));\n\n // Sequential: each diff can enqueue an extraction, and a burst of parallel\n // misses on a fresh repo would queue the same specs from several callers at\n // once. There is no user-visible latency budget on a brief.\n // One version query for the whole brief rather than one per upgrade: hop\n // planning needs each package's release timeline, and 25 round trips on a\n // page load is the kind of cost that only shows up under real accounts.\n const versions = await loadVersions(db, selected.map((d) => d.name));\n\n const upgrades: UpgradeBrief[] = [];\n for (const dep of selected) {\n upgrades.push(await briefUpgrade(db, dep, versions.get(dep.name) ?? []));\n }\n\n // Hazards first, then unknowns — an unextracted surface should sit above a\n // clean one, because \"we haven't looked\" is a more actionable state than \"fine\".\n const order: Record<UpgradeVerdict, number> = {\n 'removes-exports': 0,\n 'arity-changed': 1,\n unknown: 2,\n clean: 3,\n };\n upgrades.sort(\n (a, b) => order[a.verdict] - order[b.verdict] || b.removed.length - a.removed.length,\n );\n\n return {\n upgrades,\n omitted: candidates.length - selected.length,\n pending: upgrades.filter((u) => u.verdict === 'unknown').length,\n };\n}\n","/**\n * The durable half of the Ask budget.\n *\n * The route also keeps an in-memory hourly ledger, which is a burst guard: it\n * lives on one serverless instance and resets on cold start. This is the part\n * that actually holds a daily ceiling, because it is the only copy that\n * survives a restart and is shared by every instance.\n *\n * Everything here is awaited and every failure propagates. That is the whole\n * difference between this and `db/usage.ts` next door, whose writes are\n * fire-and-forget because an undercounted display figure is harmless — an\n * undercounted budget is a budget that has stopped working, and the caller has\n * to be able to tell the difference between \"under the cap\" and \"could not\n * read the cap\".\n */\nimport { and, eq, sql } from 'drizzle-orm';\nimport type { Database } from './client';\nimport { askSpendDaily } from './schema';\n\n/** $1 as micro-dollars. Costs are integers here so a running total can't drift. */\nexport const MICROS_PER_USD = 1_000_000;\n\nexport function usdToMicros(usd: number): number {\n // Round rather than truncate: truncating every write biases the ledger low,\n // which over thousands of sub-cent calls quietly raises the real ceiling.\n return Math.max(0, Math.round(usd * MICROS_PER_USD));\n}\n\n/** What this account has spent on Ask today (UTC). Zero when it has no row. */\nexport async function getAskSpendToday(db: Database, ownerId: string): Promise<number> {\n const rows = await db\n .select({ usdMicros: askSpendDaily.usdMicros })\n .from(askSpendDaily)\n .where(and(eq(askSpendDaily.ownerId, ownerId), eq(askSpendDaily.date, sql`CURRENT_DATE`)))\n .limit(1);\n return rows[0]?.usdMicros ?? 0;\n}\n\n/**\n * Apply a signed delta to today's total and return the new value.\n *\n * Signed because the caller reserves before spending and settles after: a\n * question charges its worst case up front so a concurrent question cannot read\n * a total that ignores it, then refunds the difference once the real cost is\n * known. The refund is the negative case.\n *\n * The arithmetic happens in SQL, not by reading into the app and writing back.\n * Two questions answered concurrently on different instances would otherwise\n * both read the same total and the second would overwrite the first, losing a\n * charge every time the feature is actually busy — which is exactly when a\n * budget needs to be right.\n *\n * Clamped at zero on both paths. A refund larger than what is on the row is a\n * bug rather than an attack (this sits behind the issuer secret, so the caller\n * is our own server), but a negative balance would hand out budget that was\n * never spent, so the floor is enforced in the statement rather than trusted.\n */\nexport async function addAskSpend(\n db: Database,\n ownerId: string,\n micros: number,\n): Promise<number> {\n if (micros === 0) return getAskSpendToday(db, ownerId);\n const rows = await db\n .insert(askSpendDaily)\n .values({ ownerId, date: sql`CURRENT_DATE`, usdMicros: Math.max(0, micros) })\n .onConflictDoUpdate({\n target: [askSpendDaily.ownerId, askSpendDaily.date],\n set: { usdMicros: sql`greatest(0, ${askSpendDaily.usdMicros} + ${micros})` },\n })\n .returning({ usdMicros: askSpendDaily.usdMicros });\n return rows[0]?.usdMicros ?? Math.max(0, micros);\n}\n","/**\n * Upgrade selection under a repo's `RepoPolicy.scope`.\n *\n * The dashboard has offered these three settings since the connect survey\n * shipped, and until now nothing read them: a repo set to `security` was still\n * handed every drifted dependency. A control that persists and displays but does\n * not govern is worse than no control, because the user reasonably believes the\n * blast radius is smaller than it is.\n *\n * Why this is the enforcement point: the plan is what the agent edits FROM. Any\n * later gate (the prompt, the PR step) would leave the out-of-scope upgrades in\n * the brief the model reads, and a model handed an upgrade it was told not to\n * make will sometimes make it. Filtering at the source is the only version of\n * this that is structural rather than advisory.\n *\n * What this is NOT: a visibility filter. Out-of-scope upgrades stay in the\n * response and stay in the report — they are marked, not deleted. A user in\n * `security` scope still wants to SEE that they are four majors behind on\n * something; they just did not consent to an agent rewriting it. Dropping the\n * rows would silently shrink the drift picture and hide exactly the information\n * that makes someone widen their scope later.\n */\nimport type { UpgradeBrief } from './brief';\nimport type { RepoPolicy } from './types';\n\n/** Why an upgrade is not eligible for the agent, in words a user can act on. */\nexport type ScopeReason =\n | 'no advisory — scope is security-only'\n | 'nothing referenced breaks — scope is security + blocking'\n | 'surface not yet analysed — nothing for the agent to rewrite';\n\nexport interface ScopedUpgrade extends UpgradeBrief {\n /** May the agent attempt this one? */\n inScope: boolean;\n /** Set only when `inScope` is false. */\n scopeReason?: ScopeReason;\n}\n\n/**\n * An upgrade whose surface we could not diff carries an empty `removed`, so\n * there are no call sites for the agent to rewrite — attempting it would be a\n * blind version bump. Under `all` that is what the user asked for; under any\n * narrower scope it is precisely what they did not.\n */\nfunction isUnassessed(u: UpgradeBrief): boolean {\n return u.verdict === 'unknown';\n}\n\nfunction breaksSomething(u: UpgradeBrief): boolean {\n return u.verdict === 'removes-exports' || u.verdict === 'arity-changed';\n}\n\n/** Decide one upgrade against one scope. Pure — the whole policy is right here. */\nexport function scopeVerdict(\n u: UpgradeBrief,\n scope: RepoPolicy['scope'],\n): { inScope: true } | { inScope: false; reason: ScopeReason } {\n if (scope === 'all') return { inScope: true };\n\n // Security is the floor under every narrower scope: a repo that opted into\n // `blocking` is asking for MORE than advisories, never fewer.\n if (u.advisories > 0) return { inScope: true };\n\n if (scope === 'security') {\n return { inScope: false, reason: 'no advisory — scope is security-only' };\n }\n\n if (isUnassessed(u)) {\n return { inScope: false, reason: 'surface not yet analysed — nothing for the agent to rewrite' };\n }\n if (breaksSomething(u)) return { inScope: true };\n return { inScope: false, reason: 'nothing referenced breaks — scope is security + blocking' };\n}\n\nexport interface ScopedPlan {\n upgrades: ScopedUpgrade[];\n /** The scope actually applied, so CI can print it rather than assume it. */\n scope: RepoPolicy['scope'];\n /**\n * Where the scope came from. `unconnected` means no policy governs this\n * checkout, which is a real and supported state — `upgrade-plan` works in any\n * clone, and connecting a repo is what opts into policy, not a precondition\n * for the loop.\n */\n scopeSource: 'repo-policy' | 'unconnected';\n /** How many upgrades the policy holds back. Printed, never silent. */\n outOfScope: number;\n}\n\n/**\n * Annotate a brief's upgrades with policy eligibility.\n *\n * `policy === null` (an unconnected checkout) means everything is in scope —\n * the same behaviour this endpoint has always had. Enforcement arrives with the\n * connection, so no existing workflow changes behaviour on deploy.\n */\nexport function applyScope(upgrades: UpgradeBrief[], policy: RepoPolicy | null): ScopedPlan {\n if (!policy) {\n return {\n upgrades: upgrades.map((u) => ({ ...u, inScope: true })),\n scope: 'all',\n scopeSource: 'unconnected',\n outOfScope: 0,\n };\n }\n\n const scoped = upgrades.map((u): ScopedUpgrade => {\n const verdict = scopeVerdict(u, policy.scope);\n return verdict.inScope ? { ...u, inScope: true } : { ...u, inScope: false, scopeReason: verdict.reason };\n });\n\n return {\n upgrades: scoped,\n scope: policy.scope,\n scopeSource: 'repo-policy',\n outOfScope: scoped.filter((u) => !u.inScope).length,\n };\n}\n","/**\n * Validation for CI-reported upgrade runs.\n *\n * This is a trust boundary: the payload comes from a workflow running on a\n * machine we do not control, authenticated only by an API key. Everything is\n * parsed rather than trusted, unknown fields are dropped, and every string is\n * length-capped so a malformed (or hostile) post cannot write unbounded data.\n *\n * `ownerId` and `repoId` are NOT parsed here — the caller injects them from the\n * authenticated key. A payload that could name its own owner would let any key\n * write rows against any account.\n */\nimport {\n UPGRADE_RUN_STATUSES,\n UPGRADE_SEVERITIES,\n type UpgradeRunStatus,\n type UpgradeSeverity,\n} from './types';\n\n/** Package names, versions, and repo slugs are all short; paths can be longer. */\nconst MAX_NAME = 214; // npm's own package-name limit\nconst MAX_VERSION = 64;\nconst MAX_URL = 500;\nconst MAX_SYMBOLS = 200;\nconst MAX_FILES = 100;\nconst MAX_PATH = 400;\n\nexport interface ParsedUpgradeRun {\n repoFullName: string;\n packageName: string;\n fromVersion: string;\n toVersion: string;\n severity: UpgradeSeverity;\n status: UpgradeRunStatus;\n symbolsAffected: string[];\n callSites: number;\n callSiteFiles: string[] | null;\n filesChanged: number | null;\n testsPassed: boolean | null;\n prUrl: string | null;\n runUrl: string;\n}\n\nfunction str(value: unknown, max: number): string | null {\n if (typeof value !== 'string') return null;\n const trimmed = value.trim();\n return trimmed ? trimmed.slice(0, max) : null;\n}\n\nfunction strList(value: unknown, maxItems: number, maxLen: number): string[] {\n if (!Array.isArray(value)) return [];\n const out: string[] = [];\n for (const item of value) {\n const parsed = str(item, maxLen);\n if (parsed) out.push(parsed);\n if (out.length >= maxItems) break;\n }\n return out;\n}\n\n/** Non-negative integers only; anything else becomes null rather than NaN. */\nfunction count(value: unknown): number | null {\n const n = typeof value === 'number' ? value : Number(value);\n return Number.isInteger(n) && n >= 0 && n < 1_000_000 ? n : null;\n}\n\n/** Parse one reported run, or null when it is unusable. */\nexport function parseUpgradeRun(input: unknown): ParsedUpgradeRun | null {\n if (!input || typeof input !== 'object') return null;\n const raw = input as Record<string, unknown>;\n\n const repoFullName = str(raw.repoFullName, MAX_NAME);\n const packageName = str(raw.packageName, MAX_NAME);\n const fromVersion = str(raw.fromVersion, MAX_VERSION);\n const toVersion = str(raw.toVersion, MAX_VERSION);\n if (!repoFullName || !packageName || !fromVersion || !toVersion) return null;\n\n const severity = UPGRADE_SEVERITIES.find((s) => s === raw.severity);\n const status = UPGRADE_RUN_STATUSES.find((s) => s === raw.status);\n if (!severity || !status) return null;\n\n // Absent means \"not shared\", which is different from \"no files\" — keep null so\n // the dashboard can tell a repo that opted out from one with nothing to report.\n const files = raw.callSiteFiles === undefined ? null : strList(raw.callSiteFiles, MAX_FILES, MAX_PATH);\n\n return {\n repoFullName,\n packageName,\n fromVersion,\n toVersion,\n severity,\n status,\n symbolsAffected: strList(raw.symbolsAffected, MAX_SYMBOLS, MAX_NAME),\n callSites: count(raw.callSites) ?? 0,\n callSiteFiles: files,\n filesChanged: count(raw.filesChanged),\n testsPassed: typeof raw.testsPassed === 'boolean' ? raw.testsPassed : null,\n prUrl: str(raw.prUrl, MAX_URL),\n // Empty string, not null: it is part of the dedup key (see schema).\n runUrl: str(raw.runUrl, MAX_URL) ?? '',\n };\n}\n\n/** Parse a batch, dropping unusable entries and reporting how many were dropped. */\nexport function parseUpgradeRuns(\n input: unknown,\n max: number,\n): { runs: ParsedUpgradeRun[]; rejected: number } {\n if (!Array.isArray(input)) return { runs: [], rejected: 0 };\n const runs: ParsedUpgradeRun[] = [];\n let rejected = 0;\n for (const item of input.slice(0, max)) {\n const parsed = parseUpgradeRun(item);\n if (parsed) runs.push(parsed);\n else rejected++;\n }\n return { runs, rejected };\n}\n\n/**\n * `owner/name` posted by the workflow so the plan can be governed by that repo's\n * policy. Optional — an absent or malformed value simply means \"ungoverned\",\n * never an error, because `upgrade-plan` must keep working in any checkout.\n *\n * Shape-validated rather than trusted: it is used to look up a row, and the\n * lookup is owner-scoped, so the worst a forged value can do is match nothing.\n */\nexport function parseRepoFullName(input: unknown): string | null {\n const value = str(input, MAX_NAME * 2);\n if (!value) return null;\n return /^[\\w.-]+\\/[\\w.-]+$/.test(value) ? value : null;\n}\n\n/** Declared dependency ranges posted by the CLI for a plan. */\nexport function parseDepsInput(input: unknown): Record<string, string> {\n if (!input || typeof input !== 'object') return {};\n const out: Record<string, string> = {};\n for (const [name, range] of Object.entries(input as Record<string, unknown>)) {\n const key = str(name, MAX_NAME);\n const value = str(range, MAX_VERSION);\n if (key && value) out[key] = value;\n // A manifest with more entries than this is not a real project's direct\n // dependency list; stop rather than fan out unbounded index lookups.\n if (Object.keys(out).length >= 1000) break;\n }\n return out;\n}\n","/**\n * Read/write helpers for `upgrade_runs`.\n *\n * Writes come from users' CI through an API key, so `ownerId` is always resolved\n * from the authenticated key and never read off the request body. Reads are\n * owner-scoped for the same reason as `db/repos.ts`.\n */\nimport { and, desc, eq, gte, sql } from 'drizzle-orm';\nimport type { Database } from './client';\nimport { repos, upgradeRuns, type NewUpgradeRunRow, type UpgradeRunRow } from './schema';\n\n/** Cap on a single CI post. A run that proposes more than this is misconfigured,\n * not ambitious, and the limit keeps one request from writing unbounded rows. */\nexport const MAX_RUNS_PER_POST = 100;\n\n/**\n * Insert or refresh the rows for one Actions run.\n *\n * Upserts on the dedup key so a retried job updates its rows in place. Without\n * that, re-running a failed workflow would double every figure the impact view\n * reports — the most likely way for these numbers to quietly become wrong.\n */\nexport async function recordUpgradeRuns(\n db: Database,\n rows: NewUpgradeRunRow[],\n): Promise<number> {\n if (rows.length === 0) return 0;\n await db\n .insert(upgradeRuns)\n .values(rows)\n .onConflictDoUpdate({\n target: [\n upgradeRuns.ownerId,\n upgradeRuns.repoFullName,\n upgradeRuns.packageName,\n upgradeRuns.toVersion,\n upgradeRuns.runUrl,\n ],\n set: {\n severity: sql`excluded.severity`,\n status: sql`excluded.status`,\n symbolsAffected: sql`excluded.symbols_affected`,\n callSites: sql`excluded.call_sites`,\n callSiteFiles: sql`excluded.call_site_files`,\n filesChanged: sql`excluded.files_changed`,\n testsPassed: sql`excluded.tests_passed`,\n prUrl: sql`excluded.pr_url`,\n repoId: sql`excluded.repo_id`,\n },\n });\n return rows.length;\n}\n\n/** Resolve `owner/name` to a connected repo id, or null when it isn't connected. */\nexport async function findRepoIdByFullName(\n db: Database,\n ownerId: string,\n fullName: string,\n): Promise<number | null> {\n const rows = await db\n .select({ id: repos.id })\n .from(repos)\n .where(and(eq(repos.ownerId, ownerId), eq(repos.fullName, fullName)))\n .limit(1);\n return rows[0]?.id ?? null;\n}\n\nexport async function listRunsForRepo(\n db: Database,\n ownerId: string,\n repoId: number,\n limit = 50,\n): Promise<UpgradeRunRow[]> {\n return db\n .select()\n .from(upgradeRuns)\n .where(and(eq(upgradeRuns.ownerId, ownerId), eq(upgradeRuns.repoId, repoId)))\n .orderBy(desc(upgradeRuns.createdAt))\n .limit(limit);\n}\n\nexport interface UpgradeImpact {\n /** Upgrades analysed in the window. */\n analysed: number;\n /** Upgrades where a referenced symbol disappears — caught before merge. */\n blocking: number;\n /** Referenced call sites those upgrades would have broken. */\n callSites: number;\n prsOpened: number;\n merged: number;\n /** Analysed but not conclusively checked. Reported, never folded into \"clean\". */\n unverified: number;\n}\n\n/**\n * Impact totals for the dashboard.\n *\n * One aggregate query rather than pulling rows and reducing in JS: this is the\n * figure on the overview, and it should stay O(1) work for the web tier no\n * matter how many runs an account accumulates.\n */\nexport async function getUpgradeImpact(\n db: Database,\n ownerId: string,\n days = 30,\n): Promise<UpgradeImpact> {\n const since = new Date(Date.now() - days * 86_400_000);\n const rows = await db\n .select({\n analysed: sql<number>`count(*)::int`,\n blocking: sql<number>`count(*) filter (where ${upgradeRuns.severity} = 'blocking')::int`,\n callSites: sql<number>`coalesce(sum(${upgradeRuns.callSites}) filter (where ${upgradeRuns.severity} = 'blocking'), 0)::int`,\n prsOpened: sql<number>`count(*) filter (where ${upgradeRuns.status} in ('pr_open','merged'))::int`,\n merged: sql<number>`count(*) filter (where ${upgradeRuns.status} = 'merged')::int`,\n unverified: sql<number>`count(*) filter (where ${upgradeRuns.severity} = 'unverified')::int`,\n })\n .from(upgradeRuns)\n .where(and(eq(upgradeRuns.ownerId, ownerId), gte(upgradeRuns.createdAt, since)));\n\n return (\n rows[0] ?? {\n analysed: 0,\n blocking: 0,\n callSites: 0,\n prsOpened: 0,\n merged: 0,\n unverified: 0,\n }\n );\n}\n","/**\n * Scan a PUBLIC repo nobody has connected, from nothing but its name.\n *\n * The connected-repo path (manifests.ts → drift.ts) needs a GitHub App\n * installation, which needs an account, which needs a signup. That ordering is\n * backwards for a first-time visitor: the one thing that would make them sign\n * up is seeing their own dependencies in our numbers, and we were asking them\n * to sign up first. This reads a public repository over unauthenticated HTTP\n * and produces the same drift summary, so the landing page can show a person\n * their own stack before it asks them for anything.\n *\n * WHAT IT DELIBERATELY DOES NOT DO. No tree listing, so no workspace manifests:\n * a monorepo is read at its root package.json only. Fetching the tree costs an\n * authenticated API call per repo and the API's unauthenticated budget is 60 an\n * hour for the whole server, which one bored visitor exhausts for everybody.\n * The teaser is honest about being partial (`partial: true`) rather than\n * pretending the root is the whole repo.\n *\n * ponytail: root manifest only. Lift it to the full tree when this route has a\n * GITHUB_TOKEN in production and the API budget stops being the constraint.\n */\nimport { getConfig } from '../core/config';\nimport { logger } from '../core/logger';\nimport type { Database } from '../db/client';\nimport { computeDrift } from './drift';\nimport { parseManifest } from './manifests';\nimport { REPO_DRIFT_DETAIL_CAP, type DepDrift } from './types';\n\n/** What a visitor typed, resolved to something fetchable. */\nexport type ScanTarget =\n | { kind: 'repo'; owner: string; name: string }\n | { kind: 'user'; login: string };\n\n/** GitHub's own rule: alphanumerics and hyphens, no leading/trailing hyphen. */\nconst LOGIN = /^[a-z\\d](?:[a-z\\d]|-(?=[a-z\\d])){0,38}$/i;\n/**\n * Repo names are laxer: letters, digits, `.`, `_`, `-`. `.` and `..` are\n * excluded by name — a repo cannot be called either, and `owner/..` in a raw\n * URL normalizes away the owner segment, so it would scan whatever was left.\n * A leading dot is otherwise legal and real: `owner/.github` exists.\n */\nconst REPO = /^(?!\\.\\.?$)[\\w.-]{1,100}$/;\n\n/**\n * Read `owner/repo`, a github.com URL, a bare profile, or an `@handle`.\n *\n * Pure, and exported for its own test: this is the function that decides\n * whether a visitor's first interaction with lurq works, and every one of its\n * failure modes is a shrug rather than a throw.\n */\nexport function parseTarget(raw: string): ScanTarget | null {\n let input = raw.trim();\n if (!input) return null;\n\n // A pasted URL, with or without a scheme, with or without trailing path.\n input = input.replace(/^https?:\\/\\//i, '').replace(/^www\\./i, '');\n if (input.toLowerCase().startsWith('github.com/')) input = input.slice('github.com/'.length);\n input = input.replace(/^@/, '').replace(/\\.git$/i, '').replace(/\\/+$/, '');\n\n const [owner, name] = input.split('/');\n if (!owner || !LOGIN.test(owner)) return null;\n if (!name) return { kind: 'user', login: owner };\n if (!REPO.test(name)) return null;\n return { kind: 'repo', owner, name };\n}\n\nfunction headers(): Record<string, string> {\n const token = getConfig().GITHUB_TOKEN;\n return {\n Accept: 'application/vnd.github+json',\n 'User-Agent': 'lurq-public-scan',\n ...(token ? { Authorization: `Bearer ${token}` } : {}),\n };\n}\n\n/** Give up rather than hold a visitor's request open on a slow origin. */\nconst TIMEOUT_MS = 6_000;\n\nasync function getJson<T>(url: string, init?: RequestInit): Promise<T | null> {\n try {\n const res = await fetch(url, {\n ...init,\n headers: { ...headers(), ...(init?.headers ?? {}) },\n signal: AbortSignal.timeout(TIMEOUT_MS),\n });\n if (!res.ok) return null;\n return (await res.json()) as T;\n } catch {\n return null;\n }\n}\n\n/**\n * The root `package.json` of a public repo, or null.\n *\n * `HEAD` rather than `main`: it resolves to whatever the default branch is\n * called, which saves a lookup and is right for the repos still on `master`.\n * raw.githubusercontent.com is a separate budget from the REST API, which is\n * the whole reason this path avoids the API for the common case.\n */\nasync function rootManifest(owner: string, name: string): Promise<unknown | null> {\n return getJson<unknown>(\n `https://raw.githubusercontent.com/${owner}/${name}/HEAD/package.json`,\n { headers: { Accept: 'application/json' } },\n );\n}\n\n/** How many of a profile's repos to try before giving up on finding a JS one. */\nconst PROFILE_TRIES = 5;\n\ninterface UserRepo {\n name: string;\n fork: boolean;\n archived: boolean;\n stargazers_count: number;\n pushed_at: string | null;\n}\n\n/**\n * A profile's most interesting JS/TS repo.\n *\n * Ordered by stars and then by recency, because the point is to show the\n * visitor something they recognise as theirs. Their most-starred repo is the\n * one they would have typed if we had asked for a repo.\n */\nasync function pickRepo(login: string): Promise<{ name: string; manifest: unknown } | null> {\n const repos = await getJson<UserRepo[]>(\n `https://api.github.com/users/${login}/repos?sort=pushed&direction=desc&per_page=30&type=owner`,\n );\n if (!repos?.length) return null;\n\n const ranked = repos\n .filter((r) => !r.fork && !r.archived)\n .sort(\n (a, b) =>\n b.stargazers_count - a.stargazers_count ||\n (b.pushed_at ?? '').localeCompare(a.pushed_at ?? ''),\n )\n .slice(0, PROFILE_TRIES);\n\n for (const repo of ranked) {\n const manifest = await rootManifest(login, repo.name);\n if (manifest) return { name: repo.name, manifest };\n }\n return null;\n}\n\n/** The shape the landing page renders. Flat on purpose: it crosses two hops. */\nexport interface PublicScan {\n /** `owner/name`, always resolved even when a profile was typed. */\n repo: string;\n url: string;\n depsDeclared: number;\n depsTracked: number;\n majorDrift: number;\n anyDrift: number;\n deprecated: number;\n advisories: number;\n /** Peer/engine conflicts if the repo took every available upgrade. */\n conflicts: number;\n /** Worst-first, capped. The evidence under the counts. */\n deps: DepDrift[];\n /** Always true today: the root manifest is not the whole repo. */\n partial: boolean;\n}\n\n/** How many dependency rows the teaser returns. Enough to be evidence, not a report. */\nconst TEASER_DEPS = 8;\n\n/**\n * Public, unauthenticated scan of one repo or profile.\n *\n * Throws nothing a caller has to distinguish: `null` means \"could not read a\n * package.json for that\", which is the only failure a visitor can act on and\n * the only one worth a different message.\n */\nexport async function publicScan(db: Database, target: ScanTarget): Promise<PublicScan | null> {\n const resolved =\n target.kind === 'repo'\n ? await rootManifest(target.owner, target.name).then((manifest) =>\n manifest ? { owner: target.owner, name: target.name, manifest } : null,\n )\n : await pickRepo(target.login).then((hit) =>\n hit ? { owner: target.login, name: hit.name, manifest: hit.manifest } : null,\n );\n\n if (!resolved) return null;\n\n const manifest = parseManifest('package.json', resolved.manifest);\n const full = `${resolved.owner}/${resolved.name}`;\n const url = `https://github.com/${full}`;\n\n // A real repo with no registry dependencies. Not an error: it is a true and\n // slightly boring answer, and inventing a failure for it would send the\n // visitor looking for a typo they did not make.\n if (!manifest) {\n return {\n repo: full,\n url,\n depsDeclared: 0,\n depsTracked: 0,\n majorDrift: 0,\n anyDrift: 0,\n deprecated: 0,\n advisories: 0,\n conflicts: 0,\n deps: [],\n partial: true,\n };\n }\n\n const drift = await computeDrift(db, [manifest]);\n logger.debug(`public scan ${full}: ${drift.depsTracked}/${drift.depsDeclared} tracked`);\n\n return {\n repo: full,\n url,\n depsDeclared: drift.depsDeclared,\n depsTracked: drift.depsTracked,\n majorDrift: drift.majorDrift,\n anyDrift: drift.anyDrift,\n deprecated: drift.deprecated,\n advisories: drift.advisories,\n conflicts: drift.conflictsAtLatest?.length ?? 0,\n deps: drift.deps.slice(0, Math.min(TEASER_DEPS, REPO_DRIFT_DETAIL_CAP)),\n partial: true,\n };\n}\n","/**\n * GitHub App webhook: signature check + payload interpretation.\n *\n * Why this exists at all: the connect flow only ever takes a *snapshot* of an\n * installation. People manage app access from github.com/settings/installations,\n * not from our dashboard, so without a webhook a repo added there never appears\n * and the user concludes lurq is broken. (Removal degrades honestly on its own —\n * the next scan 404s and says \"reconnect\" — but an addition fails silently, and\n * silence is the worse failure.)\n *\n * Everything here is pure: verification takes bytes and a header, parsing takes\n * an event name and an object. The DB and GitHub calls stay in the route, so the\n * security-relevant half can be tested without either.\n *\n * The payload is fully attacker-controlled until the signature verifies, and even\n * after that its repo objects are minimal — `full_name` and `private`, no\n * `default_branch`. So names are all we take from it: the route re-reads the real\n * inventory from the API rather than trusting a webhook to describe a repo.\n */\nimport { createHmac, timingSafeEqual } from 'node:crypto';\n\n/** What a delivery means for us. Anything we don't act on is `ignored`. */\nexport type WebhookAction =\n | {\n kind: 'repos-changed';\n installationId: number;\n added: string[];\n removed: string[];\n }\n | { kind: 'uninstalled'; installationId: number }\n | { kind: 'ignored'; reason: string };\n\n/**\n * True when `body` was signed with `secret`, per `X-Hub-Signature-256`.\n *\n * Takes the raw bytes on purpose: GitHub signs what it sent, and a re-serialized\n * `JSON.parse` result is not byte-identical (key order, unicode escapes, spacing),\n * so verifying against a re-stringified object fails for legitimate deliveries.\n */\nexport function verifyWebhookSignature(\n secret: string,\n body: Buffer | string,\n header: string | undefined,\n): boolean {\n if (!header?.startsWith('sha256=')) return false;\n const presented = Buffer.from(header.slice(7), 'hex');\n const expected = createHmac('sha256', secret).update(body).digest();\n // A wrong-length hex string (or non-hex junk) is a mismatch, not a crash —\n // timingSafeEqual throws on unequal lengths.\n return presented.length === expected.length && timingSafeEqual(presented, expected);\n}\n\n/** Repo full names out of an untrusted `[{ full_name }]` array. */\nfunction fullNames(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value\n .map((entry) =>\n entry && typeof entry === 'object' && typeof (entry as { full_name?: unknown }).full_name === 'string'\n ? (entry as { full_name: string }).full_name\n : null,\n )\n .filter((name): name is string => name !== null);\n}\n\nfunction installationId(payload: Record<string, unknown>): number | null {\n const install = payload.installation;\n const id = install && typeof install === 'object' ? (install as { id?: unknown }).id : null;\n return typeof id === 'number' && Number.isInteger(id) && id > 0 ? id : null;\n}\n\n/**\n * Decide what a delivery asks us to do.\n *\n * `installation.created` is deliberately ignored: the post-install redirect is\n * the only place that knows *which lurq user* installed the app, and it upserts\n * the repos itself. Acting on `created` here would race it with no owner to\n * attribute the repos to. `suspend`/`unsuspend` are ignored too — suspension is\n * reversible and deleting the rows would throw away the user's autopilot policy\n * to save them a scan error that already reads correctly.\n */\nexport function parseWebhook(\n event: string | undefined,\n payload: unknown,\n): WebhookAction {\n if (!payload || typeof payload !== 'object') return { kind: 'ignored', reason: 'no payload' };\n const body = payload as Record<string, unknown>;\n const id = installationId(body);\n if (id === null) return { kind: 'ignored', reason: 'no installation id' };\n const action = typeof body.action === 'string' ? body.action : '';\n\n if (event === 'installation_repositories') {\n // Both arrays are always present, one of them empty. Reading both rather\n // than branching on `action` means a delivery carrying each cannot lose half.\n const added = fullNames(body.repositories_added);\n const removed = fullNames(body.repositories_removed);\n if (added.length === 0 && removed.length === 0) {\n return { kind: 'ignored', reason: 'no repository changes' };\n }\n return { kind: 'repos-changed', installationId: id, added, removed };\n }\n\n if (event === 'installation') {\n if (action === 'deleted') return { kind: 'uninstalled', installationId: id };\n if (action === 'added' || action === 'removed') {\n // Older deliveries put repo changes on the `installation` event.\n const added = fullNames(body.repositories_added);\n const removed = fullNames(body.repositories_removed);\n if (added.length || removed.length) {\n return { kind: 'repos-changed', installationId: id, added, removed };\n }\n }\n return { kind: 'ignored', reason: `installation.${action || 'unknown'}` };\n }\n\n return { kind: 'ignored', reason: `event ${event ?? 'unknown'}` };\n}\n","/**\n * Resolved dependency tree, via GitHub's dependency-graph SBOM.\n *\n * Everything else in this product reads declared ranges from `package.json`,\n * which makes the whole transitive tree invisible — and transitives are where\n * most advisories actually live. A repo can read \"0 advisories\" while shipping a\n * known-vulnerable package four levels down.\n *\n * We do NOT parse lockfiles to fix that. There are five formats across npm v1–v3,\n * yarn classic and berry, pnpm, and bun (binary), they run to megabytes, and\n * GitHub already resolves all of them into one SPDX document. One authenticated\n * call replaces a parser suite we would then own forever.\n *\n * The cost is a dependency on a repo feature: the dependency graph is on by\n * default for public repos but opt-in for private ones. A repo without it gets\n * `null`, reported as \"not available\" — never as \"no transitive risk\".\n */\nimport { HttpError } from '../core/http';\nimport { installationGet } from './app';\nimport { GithubAppError } from './app';\n\n/** One node of the resolved tree. */\nexport interface ResolvedDep {\n name: string;\n version: string;\n /** SPDX element id, the key the relationship edges are expressed in. */\n spdxId?: string;\n}\n\ninterface SpdxPackage {\n SPDXID?: string;\n name?: string;\n versionInfo?: string;\n externalRefs?: { referenceType?: string; referenceLocator?: string }[];\n}\n\ninterface SpdxRelationship {\n spdxElementId?: string;\n relationshipType?: string;\n relatedSpdxElement?: string;\n}\n\ninterface SbomResponse {\n sbom?: { packages?: SpdxPackage[]; relationships?: SpdxRelationship[] };\n}\n\n/** `parent DEPENDS_ON child`, in SPDX element ids. */\nexport interface DependencyEdge {\n parent: string;\n child: string;\n}\n\n/**\n * A real tree runs to a few thousand nodes; past this the repo is a monorepo of\n * monorepos and the summary is what matters, not the list. Reported, not silent.\n */\nexport const SBOM_NODE_CAP = 5000;\n\n/**\n * Parse an npm package identity out of a Package URL.\n *\n * Scoped names are the whole difficulty: producers emit `pkg:npm/%40babel/core`\n * (correctly percent-encoded) and `pkg:npm/@babel/core` (not) interchangeably,\n * and the version separator is the LAST `@`, which a naive split gets wrong for\n * every scoped package.\n */\nexport function parseNpmPurl(purl: string): ResolvedDep | null {\n if (!purl.startsWith('pkg:npm/')) return null;\n let body = purl.slice('pkg:npm/'.length);\n\n // Drop qualifiers and subpath: `pkg:npm/foo@1.0.0?arch=x64#sub`.\n const cut = body.search(/[?#]/);\n if (cut !== -1) body = body.slice(0, cut);\n\n const at = body.lastIndexOf('@');\n // `@` at index 0 is a scope marker, not a version separator.\n if (at <= 0) return null;\n\n const name = decodeURIComponent(body.slice(0, at));\n const version = decodeURIComponent(body.slice(at + 1));\n if (!name || !version) return null;\n return { name, version };\n}\n\n/** Extract every npm node from an SPDX document, deduped by name@version. */\nexport function parseSbom(json: unknown): ResolvedDep[] {\n const packages = (json as SbomResponse)?.sbom?.packages;\n if (!Array.isArray(packages)) return [];\n\n const seen = new Set<string>();\n const out: ResolvedDep[] = [];\n\n for (const pkg of packages) {\n const purl = pkg.externalRefs?.find((ref) => ref.referenceType === 'purl')?.referenceLocator;\n // The purl is authoritative. `name` is a display string whose format varies\n // by producer (\"npm:lodash\", \"lodash\"), so it is only a fallback — and then\n // only when `versionInfo` supplies the version the purl would have carried.\n const parsed = purl\n ? parseNpmPurl(purl)\n : pkg.name?.startsWith('npm:') && pkg.versionInfo\n ? { name: pkg.name.slice(4), version: pkg.versionInfo }\n : null;\n if (!parsed) continue;\n\n const key = `${parsed.name}@${parsed.version}`;\n if (seen.has(key)) continue;\n seen.add(key);\n out.push({ ...parsed, ...(pkg.SPDXID ? { spdxId: pkg.SPDXID } : {}) });\n if (out.length >= SBOM_NODE_CAP) break;\n }\n\n return out;\n}\n\n/**\n * `DEPENDS_ON` edges, the raw material for attributing a transitive back to the\n * direct dependency that pulls it in.\n *\n * GitHub does not guarantee a nested tree here — some documents carry only\n * `DESCRIBES` from the root, which yields no useful parentage at all. That is\n * why callers check whether any edges came back rather than assuming they did:\n * \"we could not attribute this\" and \"nothing depends on this\" are different\n * claims, and only the first one is ever true.\n */\nexport function parseRelationships(json: unknown): DependencyEdge[] {\n const relationships = (json as SbomResponse)?.sbom?.relationships;\n if (!Array.isArray(relationships)) return [];\n const out: DependencyEdge[] = [];\n for (const rel of relationships) {\n if (rel.relationshipType !== 'DEPENDS_ON') continue;\n if (!rel.spdxElementId || !rel.relatedSpdxElement) continue;\n out.push({ parent: rel.spdxElementId, child: rel.relatedSpdxElement });\n }\n return out;\n}\n\nexport interface SbomResult {\n deps: ResolvedDep[];\n edges: DependencyEdge[];\n /** True when the tree hit SBOM_NODE_CAP and is therefore incomplete. */\n truncated: boolean;\n}\n\n/**\n * Fetch the resolved tree, or null when the repo has no dependency graph.\n *\n * A 403 here means the feature is disabled for that repository, which is a\n * normal state and not an error — callers surface it as \"not available\" so the\n * dashboard never implies a clean tree it did not actually see.\n */\nexport async function fetchResolvedTree(\n installationId: number,\n fullName: string,\n): Promise<SbomResult | null> {\n try {\n const data = await installationGet<SbomResponse>(\n installationId,\n `/repos/${fullName}/dependency-graph/sbom`,\n );\n const deps = parseSbom(data);\n return {\n deps,\n edges: parseRelationships(data),\n truncated: deps.length >= SBOM_NODE_CAP,\n };\n } catch (err) {\n const status =\n err instanceof HttpError ? err.status : err instanceof GithubAppError ? err.status : 0;\n // 403: dependency graph disabled. 404: repo gone, or the endpoint is not\n // enabled for this installation. Neither is worth failing a scan over — the\n // direct-dependency drift above it is still correct and useful.\n if (status === 403 || status === 404) return null;\n throw err;\n }\n}\n","/**\n * Repo scan: read manifests from GitHub, compute drift against the index, store\n * the summary.\n *\n * Runs on connect, on demand from the dashboard, and once a day from the sync\n * cron. Scans are independent per repo and a failure is recorded rather than\n * thrown, so one archived or permission-revoked repository cannot stop the\n * nightly pass for everything else the user connected.\n *\n * Cost note: a scan is 1 tree call + N content calls per repo, no clone and no\n * npm traffic — the version data it diffs against is already in our own index.\n */\nimport { logger } from '../core/logger';\nimport type { Database } from '../db/client';\nimport { listAllRepos, saveScan, saveScanError } from '../db/repos';\nimport type { RepoRow } from '../db/schema';\nimport { GithubAppError } from '../github/app';\nimport { computeDrift } from '../github/drift';\nimport { fetchManifests, type InstallationRepo } from '../github/manifests';\nimport { fetchResolvedTree } from '../github/sbom';\n\nexport interface ScanResult {\n repoId: number;\n fullName: string;\n ok: boolean;\n depsTracked: number;\n majorDrift: number;\n partial: boolean;\n /** False when the repo has no dependency graph, so transitives were not read. */\n transitivesRead: boolean;\n /** The repository has no commits yet. A successful scan of nothing. */\n empty: boolean;\n error?: string;\n}\n\n/** Scan one repo. Never throws — failures land in `lastScanError`. */\nexport async function scanRepo(db: Database, repo: RepoRow): Promise<ScanResult> {\n const base = { repoId: repo.id, fullName: repo.fullName };\n try {\n const branch = repo.defaultBranch ?? 'main';\n const { manifests, installCommand, partial, empty } = await fetchManifests(\n repo.installationId,\n repo.fullName,\n branch,\n );\n // The resolved tree is where most advisories actually live, but it depends\n // on a repo feature that may be off. A null result degrades to\n // direct-dependency-only drift rather than failing the scan.\n const resolvedTree = await fetchResolvedTree(repo.installationId, repo.fullName);\n // ownerId is passed so any dependency this scan ingests for the first time\n // is attributed to the user whose repo surfaced it.\n const drift = await computeDrift(db, manifests, resolvedTree, repo.ownerId);\n await saveScan(db, repo.id, { manifests, drift, installCommand });\n return {\n ...base,\n ok: true,\n depsTracked: drift.depsTracked,\n majorDrift: drift.majorDrift,\n partial,\n transitivesRead: resolvedTree !== null,\n empty,\n };\n } catch (err) {\n // A revoked installation is the common case and deserves an actionable\n // message rather than a raw HTTP status the user can do nothing with.\n const message =\n err instanceof GithubAppError && err.status === 404\n ? 'GitHub access was revoked for this repo. Reconnect the lurq app.'\n : err instanceof Error\n ? err.message\n : 'Scan failed.';\n logger.warn(`repo scan failed for ${repo.fullName}: ${message}`);\n await saveScanError(db, repo.id, message).catch(() => {\n /* the scan already failed; a bookkeeping write failure must not mask it */\n });\n return {\n ...base,\n ok: false,\n depsTracked: 0,\n majorDrift: 0,\n partial: false,\n transitivesRead: false,\n empty: false,\n error: message,\n };\n }\n}\n\n/** Sequential on purpose: GitHub's rate limit is per installation and shared\n * across these calls, and a scan is a background job with nobody waiting on\n * latency. Parallelism here buys seconds and costs 403s. */\nexport async function scanRepos(db: Database, rows: RepoRow[]): Promise<ScanResult[]> {\n const results: ScanResult[] = [];\n for (const repo of rows) {\n results.push(await scanRepo(db, repo));\n }\n return results;\n}\n\n/**\n * Rows reordered most-recently-pushed first, using the inventory just read from\n * GitHub (`pushed_at` is not stored — it is only ever an ordering hint).\n *\n * This matters because `scanRepos` is sequential: on a 40-repo install the order\n * decides which row in a dashboard someone is actively watching stops saying\n * \"scanning…\" first. Alphabetical made that a coin flip; the repo they pushed to\n * this morning is the one they connected lurq for. Rows absent from the\n * inventory keep their incoming order at the end (`Array#sort` is stable).\n */\nexport function byRecentPush(rows: RepoRow[], inventory: InstallationRepo[]): RepoRow[] {\n const pushedAt = (repo: InstallationRepo): number => {\n const parsed = Date.parse(repo.pushedAt ?? '');\n // NaN would make the comparator inconsistent and the sort order arbitrary;\n // a repo with no timestamp sorts as oldest instead.\n return Number.isNaN(parsed) ? 0 : parsed;\n };\n const rank = new Map(\n [...inventory]\n .sort((a, b) => pushedAt(b) - pushedAt(a))\n .map((repo, index) => [repo.fullName, index] as const),\n );\n return [...rows].sort(\n (a, b) =>\n (rank.get(a.fullName) ?? Number.MAX_SAFE_INTEGER) -\n (rank.get(b.fullName) ?? Number.MAX_SAFE_INTEGER),\n );\n}\n\n/** Scan every connected repo across all owners — the daily cron entry point. */\nexport async function scanAllRepos(db: Database): Promise<ScanResult[]> {\n return scanRepos(db, await listAllRepos(db));\n}\n","/**\n * The package tools the dashboard's Ask may call, run through the real MCP server.\n *\n * Ask used to hold four account readers and nothing else, so \"should we take zod 4\"\n * got \"I don't have that tool\" from a product whose whole job is answering it. The\n * answers already exist as MCP tools; this reaches them over an in-memory transport\n * instead of re-declaring them, so Ask gets the same zod validation, the same\n * handlers and the same per-owner usage row as an agent holding an API key. A schema\n * change in server.ts cannot leave a second copy here drifting out of step.\n *\n * The allowlist is read-only lookups that need nothing but a package name. Not\n * `audit` (it wants a local inventory the dashboard does not have), not\n * `report_outcome` (a write attributed to an agent's decision), not the raw surface\n * dumps (`usage`, `resolve_surface`), whose size would spend a question's budget on\n * one result.\n */\nimport { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';\nimport type { createDb } from '../db/client';\nimport { buildMcpServer } from './server';\n\ntype Db = ReturnType<typeof createDb>['db'];\n\nexport const DASHBOARD_TOOLS: ReadonlySet<string> = new Set([\n 'evaluate',\n 'compare',\n 'verify',\n 'compat',\n 'diff_surface',\n 'mcp_surface',\n 'mcp_drift',\n 'mcp_stack',\n]);\n\nexport interface DashboardTool {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n}\n\nasync function connect(db: Db, ownerId: string | null) {\n const server = buildMcpServer(db, { ownerId });\n const client = new Client({ name: 'lurq-dashboard', version: '1.0.0' });\n const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();\n await server.connect(serverTransport);\n await client.connect(clientTransport);\n return { client, close: () => Promise.all([client.close(), server.close()]) };\n}\n\n// ponytail: memoised per process; the list only changes when this service deploys.\nlet listed: Promise<DashboardTool[]> | null = null;\n\nexport function listDashboardTools(db: Db): Promise<DashboardTool[]> {\n listed ??= (async () => {\n const { client, close } = await connect(db, null);\n try {\n const { tools } = await client.listTools();\n return tools\n .filter((t) => DASHBOARD_TOOLS.has(t.name))\n .map((t) => ({ name: t.name, description: t.description ?? '', inputSchema: t.inputSchema }));\n } finally {\n await close();\n }\n })().catch((err) => {\n listed = null; // a failed listing is retried next time, not cached\n throw err;\n });\n return listed;\n}\n\n/** Run one allowlisted tool as `ownerId`. The text is the tool's JSON, unparsed. */\nexport async function callDashboardTool(\n db: Db,\n ownerId: string,\n name: string,\n args: Record<string, unknown>,\n): Promise<{ isError: boolean; text: string }> {\n if (!DASHBOARD_TOOLS.has(name)) throw new Error(`Tool not available to Ask: ${name}`);\n const { client, close } = await connect(db, ownerId);\n try {\n const result = await client.callTool({ name, arguments: args });\n const text = (result.content as { type: string; text?: string }[])\n .flatMap((c) => (c.type === 'text' && c.text ? [c.text] : []))\n .join('\\n');\n return { isError: result.isError === true, text };\n } finally {\n await close();\n }\n}\n","/**\n * Hosted HTTP transport for the MCP server (docs/lurq-hosted-deployment.md §4–5).\n *\n * Stateless Streamable HTTP: one shared DB pool created at startup, a fresh MCP\n * server+transport per request, fronted by helmet + rate limiting + API-key auth.\n * The DB credentials stay server-side; users connect with only a URL + Bearer key.\n * `buildMcpServer` is reused verbatim from the stdio path — the tools are\n * transport-agnostic.\n *\n * express/helmet/express-rate-limit are imported dynamically so the CLI and the\n * install wizard never pull server-only deps into their startup path.\n */\nimport { createHash, timingSafeEqual } from 'node:crypto';\nimport type { NextFunction, Request, Response } from 'express';\nimport type { Store } from 'express-rate-limit';\nimport { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';\nimport { getConfig } from '../core/config';\nimport { logger } from '../core/logger';\nimport { capture, flush as flushAnalytics } from '../core/analytics';\nimport { formatError } from '../core/errors';\nimport { CAPABILITIES, searchCapabilities } from '../core/capabilities';\nimport {\n createKey,\n findKeyForOwner,\n hasScope,\n listKeysForOwner,\n lookupActiveKey,\n parseScopes,\n revokeKey,\n rotateKey,\n} from '../auth/apiKeys';\nimport { getOutcomesByOwner } from '../db/outcomes';\nimport { getContributionsByOwner } from '../db/packages';\nimport { listAlerts } from '../db/alerts';\nimport {\n deleteRepo,\n deleteReposByInstallation,\n findPolicyByFullName,\n getRepo,\n listRepos,\n ownerForInstallation,\n setRepoPolicy,\n upsertRepos,\n} from '../db/repos';\nimport {\n getSelectionPolicy,\n listPolicyChanges,\n setSelectionPolicy,\n summarizeDecisions,\n} from '../db/selectionPolicy';\nimport { validateSelectionPolicy } from '../policy/parse';\nimport { repoConformance } from '../policy/conformance';\nimport { getUsageByTool, getUsageSummary, recordUsage } from '../db/usage';\nimport {\n entitlementFor,\n getSubscription,\n getSubscriptionByCustomer,\n type Entitlement,\n} from '../db/subscriptions';\nimport {\n billingEnabled,\n constructEvent,\n createCheckoutSession,\n createPortalSession,\n handleEvent,\n} from '../billing/stripe';\nimport { PLANS, type Tier } from '../core/plans';\nimport { createDb } from '../db/client';\nimport { githubAppCredentials, GithubAppError } from '../github/app';\nimport { briefRepo } from '../github/brief';\nimport { computeDrift } from '../github/drift';\nimport { addAskSpend, getAskSpendToday } from '../db/askSpend';\nimport { applyScope } from '../github/scope';\nimport { parseDepsInput, parseRepoFullName, parseUpgradeRuns } from '../github/runs';\nimport {\n findRepoIdByFullName,\n getUpgradeImpact,\n listRunsForRepo,\n recordUpgradeRuns,\n MAX_RUNS_PER_POST,\n} from '../db/upgradeRuns';\nimport { listInstallationRepos } from '../github/manifests';\nimport { parseTarget, publicScan, type PublicScan } from '../github/publicScan';\nimport type { RepoPolicy } from '../github/types';\nimport { parseWebhook, verifyWebhookSignature } from '../github/webhook';\nimport { newFileUrl, renderWorkflow, WORKFLOW_PATH } from '../github/workflow';\nimport { byRecentPush, scanRepo, scanRepos } from '../pipeline/repoScan';\nimport type { ApiKeyRow, RepoRow } from '../db/schema';\nimport { buildMcpServer } from './server';\nimport { callDashboardTool, DASHBOARD_TOOLS, listDashboardTools } from './dashboardTools';\nimport { renderPrometheus } from './metrics';\n\ninterface AuthedRequest extends Request {\n lurqKey?: ApiKeyRow;\n entitlement?: Entitlement;\n}\n\n/** Raw request bytes, kept by the JSON parser for webhook signature checks. */\ninterface RawBodyRequest extends Request {\n rawBody?: Buffer;\n}\n\n/** JSON-RPC-shaped error envelope for HTTP-level rejections. */\nfunction rpcError(code: number, message: string) {\n return { jsonrpc: '2.0' as const, error: { code, message }, id: null };\n}\n\n/** One cached public scan: the answer, when it was taken, and how long it holds. */\nexport interface ScanCacheEntry {\n at: number;\n ttl: number;\n value: PublicScan | null;\n}\n\n/** A settled answer: every declared dependency was already in the index. */\nconst SCAN_TTL_MS = 15 * 60_000;\n/**\n * A PROVISIONAL answer, and the reason this is two constants rather than one.\n *\n * A scan of an unindexed repo queues its dependencies for ingestion, which\n * finishes in seconds, and then tells the visitor to try again in a few\n * minutes — while the fifteen-minute cache served them the same empty result\n * for the rest of the quarter hour. The advice was correct and the cache made\n * it a lie. Anything that queued work, and any target we could not read at all,\n * is held only long enough to blunt a refresh loop.\n */\nconst SCAN_PROVISIONAL_TTL_MS = 45_000;\n/** Bounded so a spray of one-off targets cannot grow the map without limit. */\nconst SCAN_CACHE_MAX = 500;\n\n/**\n * How long this particular answer stays true.\n *\n * A miss is provisional because the repo may be about to exist, be made public,\n * or gain a package.json. A partial read is provisional because the ingest\n * queue is, at that moment, making it less partial.\n */\nexport function scanTtl(scan: PublicScan | null): number {\n if (!scan) return SCAN_PROVISIONAL_TTL_MS;\n return scan.depsTracked < scan.depsDeclared ? SCAN_PROVISIONAL_TTL_MS : SCAN_TTL_MS;\n}\n\n/**\n * Make room without wiping the cache.\n *\n * `clear()` at the cap meant one unlucky request cost every other cached repo\n * its entry, so a busy minute re-scanned everything it had already answered.\n * Drop what has expired first, and only then the oldest entries — a Map\n * iterates in insertion order, so that is the front of it.\n */\nexport function evictScans(cache: Map<string, ScanCacheEntry>, max = SCAN_CACHE_MAX): void {\n const now = Date.now();\n for (const [k, v] of cache) if (now - v.at >= v.ttl) cache.delete(k);\n for (const k of cache.keys()) {\n if (cache.size < max) break;\n cache.delete(k);\n }\n}\n\n/** What body-parser and friends attach to the errors they throw. */\ntype RequestError = Error & { status?: number; type?: string };\n\n/**\n * Turn a thrown request error into the envelope the addressed surface speaks.\n *\n * Exported for its own sake: this is the branch that decides whether a caller\n * gets a readable reason or a shrug, and it is worth a test that does not need\n * a listening server and a database to run.\n *\n * `/mcp` speaks JSON-RPC and everything else speaks `{ error }`. Getting this\n * wrong is how the default Express handler used to answer a malformed body with\n * an HTML page: lurq's own client parses the reply as JSON-RPC, found nothing,\n * and reported a bare \"failed with HTTP 400\" — no reason, in the one case where\n * the reason is the entire diagnosis.\n *\n * Only body-parser faults (`type` starting `entity.`) get their cause echoed.\n * Any other throw is an unexpected server fault whose message may name internals,\n * so it collapses to \"Internal error.\" and goes to the log instead.\n */\nexport function errorEnvelope(\n err: RequestError,\n path: string,\n): { status: number; body: unknown; clientFault: boolean } {\n const clientFault = typeof err.type === 'string' && err.type.startsWith('entity.');\n const status =\n typeof err.status === 'number' && err.status >= 400 && err.status < 600 ? err.status : 500;\n const message = clientFault\n ? err.type === 'entity.too.large'\n ? 'Request body too large (limit 1mb).'\n : 'Request body is not valid JSON.'\n : 'Internal error.';\n const body =\n path === '/mcp'\n ? // -32700 is JSON-RPC's own \"parse error\"; -32603 is \"internal error\".\n rpcError(clientFault ? -32700 : -32603, message)\n : { error: message };\n return { status, body, clientFault };\n}\n\n/** Constant-time secret comparison (hash to a fixed length first, so length\n * never leaks and mismatched lengths don't throw). */\nexport function secretEquals(a: string, b: string): boolean {\n return timingSafeEqual(\n createHash('sha256').update(a).digest(),\n createHash('sha256').update(b).digest(),\n );\n}\n\nexport async function startHttpServer(opts: { port?: number } = {}): Promise<void> {\n const config = getConfig();\n const port = opts.port ?? config.PORT;\n\n const [{ default: express }, { default: helmet }, { rateLimit, ipKeyGenerator }] =\n await Promise.all([import('express'), import('helmet'), import('express-rate-limit')]);\n\n // The DB pool is the expensive resource — created once, shared by all requests.\n const { db, close: closeDb } = createDb({ max: 20 });\n\n // Without Redis the response cache is a pass-through, so every recommend/\n // evaluate/compare recomputes its search on the DB — fine for one box, but the\n // first thing that buckles under real traffic. Warn loudly on the hosted path.\n if (!process.env.REDIS_URL) {\n logger.warn(\n 'REDIS_URL not set, response caching is OFF; every request recomputes on the ' +\n 'database. Set REDIS_URL before serving real traffic (and it also backs the ' +\n 'rate limiter across instances).',\n );\n }\n\n // The public scan resolves a bare profile through api.github.com, whose\n // unauthenticated budget is 60 requests an hour FOR THE WHOLE SERVER. One\n // visitor typing usernames exhausts it for everybody, and the failure looks\n // like \"no public package.json found for that\" rather than like a quota. A\n // token lifts the same calls to 5,000/hour.\n if (!config.GITHUB_TOKEN) {\n logger.warn(\n 'GITHUB_TOKEN not set; /scan/public resolves profiles on the anonymous ' +\n 'GitHub budget (60/hour, server-wide) and will start reporting readable ' +\n 'repositories as unreadable once it runs out.',\n );\n }\n\n // Rate-limit store: Redis-backed when REDIS_URL is set, so limits are shared\n // and correct across horizontally-scaled instances. Without it the default\n // in-memory store is per-process — fine for one box, but N instances would\n // each enforce the full quota (N× the real limit). Each limiter gets its own\n // prefix so their counters don't collide in one Redis keyspace.\n let makeStore: ((prefix: string) => Store) | null = null;\n if (process.env.REDIS_URL) {\n const [{ default: Redis }, { default: RedisStore }] = await Promise.all([\n import('ioredis'),\n import('rate-limit-redis'),\n ]);\n const rlRedis = new Redis(process.env.REDIS_URL, { maxRetriesPerRequest: 1, family: 0 });\n rlRedis.on('error', (err: Error) => logger.warn(`rate-limit redis: ${err.message}`));\n makeStore = (prefix: string) =>\n new RedisStore({\n prefix,\n sendCommand: (...args: string[]) =>\n rlRedis.call(args[0]!, ...args.slice(1)) as Promise<never>,\n });\n }\n\n const app = express();\n app.set('trust proxy', 1); // Railway terminates TLS at the edge.\n app.use(helmet());\n // `verify` keeps the bytes the parser already had in hand. GitHub signs the raw\n // body, and a re-serialized parse result is not byte-identical, so the webhook\n // signature is uncheckable without this. Costs a reference, not a copy.\n app.use(\n express.json({\n limit: '1mb',\n verify: (req, _res, buf) => {\n (req as RawBodyRequest).rawBody = buf;\n },\n }),\n );\n\n // Unauthenticated, no DB hit — for Railway's healthcheck. Intentionally not\n // rate-limited: it's a static response with no backend cost, and limiting it\n // risks 429'ing Railway's own frequent healthcheck poll into a restart loop.\n app.get('/healthz', (_req: Request, res: Response) => {\n res.status(200).json({ status: 'ok' });\n });\n\n // Prometheus scrape of per-tool call/error/latency counters. Disabled (404)\n // unless LURQ_METRICS_TOKEN is set; when set, require it as a Bearer token so\n // the endpoint doesn't leak usage on a public host.\n app.get('/metrics', (req: Request, res: Response) => {\n const token = config.LURQ_METRICS_TOKEN;\n if (!token) {\n res.status(404).end();\n return;\n }\n const header = req.headers.authorization;\n const presented = header?.startsWith('Bearer ') ? header.slice(7).trim() : '';\n // secretEquals, not `!==`: `===` on strings short-circuits at the first\n // differing byte, which leaks the token prefix-by-prefix to anyone willing\n // to time the responses. The issuer-secret check below already does this;\n // this endpoint is guarded by a shared secret of exactly the same kind and\n // has no reason to be the weaker one.\n if (!secretEquals(presented, token)) {\n res.status(401).end();\n return;\n }\n res.type('text/plain').send(renderPrometheus());\n });\n\n // Coarse per-IP limiter to blunt unauthenticated floods before the auth lookup.\n const ipLimiter = rateLimit({\n windowMs: config.LURQ_RATE_LIMIT_WINDOW_MS,\n limit: config.LURQ_IP_RATE_LIMIT_MAX,\n standardHeaders: 'draft-7',\n legacyHeaders: false,\n ...(makeStore ? { store: makeStore('rl:ip:') } : {}),\n message: rpcError(-32029, 'Rate limit exceeded.'),\n });\n\n // The capability catalog, for the dashboard's search palette. Public and\n // unauthenticated on purpose: it is a static description of the product —\n // the same list the docs print — and holds nothing about any account. Behind\n // the IP limiter only, since it costs no backend work at all.\n app.get('/capabilities', ipLimiter, (req: Request, res: Response) => {\n const q = typeof req.query.q === 'string' ? req.query.q : '';\n const limit = Math.min(Number(req.query.limit) || 6, CAPABILITIES.length);\n res.json({ capabilities: q ? searchCapabilities(q, limit) : CAPABILITIES });\n });\n\n /**\n * Scan a public repo or profile for anyone, signed in or not.\n *\n * The only unauthenticated route that touches the database, and it exists\n * because the funnel was the wrong way round: the fastest way to explain what\n * lurq does is to show someone their own dependencies, and that was gated\n * behind a signup and a GitHub App install. This is the top of the funnel.\n *\n * Three things keep it from being a free scan API. It has a limiter of its\n * own, far tighter than the coarse IP limit the other unauthenticated routes\n * share; the result is capped to a handful of dependency rows, so the full\n * report is still a reason to sign up; and identical targets are served from\n * memory, so a refresh loop costs one scan rather than one per press.\n */\n const scanCache = new Map<string, ScanCacheEntry>();\n\n /**\n * The scan route's own limiter, ahead of the coarse one.\n *\n * One scan reads GitHub over a budget shared by every visitor, runs a\n * handful of indexed queries, and queues an ingest per unknown dependency.\n * At the coarse limit that is 240 of those a minute from a single IP, and\n * the web app's 6-a-minute hop does not apply to anyone calling this\n * endpoint directly. Redis-backed when REDIS_URL is set, so the ceiling is\n * the real one rather than per-instance.\n *\n * The body is `{ error }` rather than a JSON-RPC envelope: this route speaks\n * plain JSON to a browser, and the landing page renders `error` directly.\n */\n const scanLimiter = rateLimit({\n windowMs: config.LURQ_RATE_LIMIT_WINDOW_MS,\n limit: config.LURQ_SCAN_RATE_LIMIT_MAX,\n standardHeaders: 'draft-7',\n legacyHeaders: false,\n keyGenerator: (req: Request) => ipKeyGenerator(req.ip ?? '0.0.0.0'),\n ...(makeStore ? { store: makeStore('rl:scan:') } : {}),\n message: { error: \"That's a lot of scans. Give it a minute.\" },\n });\n\n app.post('/scan/public', ipLimiter, scanLimiter, async (req: Request, res: Response) => {\n const raw = (req.body ?? {}) as { target?: unknown };\n const target = typeof raw.target === 'string' ? parseTarget(raw.target) : null;\n if (!target) {\n res.status(400).json({ error: 'Give a GitHub repo (owner/name) or a profile.' });\n return;\n }\n\n const key = target.kind === 'repo' ? `${target.owner}/${target.name}` : `@${target.login}`;\n const hit = scanCache.get(key);\n if (hit && Date.now() - hit.at < hit.ttl) {\n if (!hit.value) {\n res.status(404).json({ error: 'No public package.json found for that.' });\n return;\n }\n res.json(hit.value);\n return;\n }\n\n try {\n const scan = await publicScan(db, target);\n if (scanCache.size >= SCAN_CACHE_MAX) evictScans(scanCache);\n scanCache.set(key, { at: Date.now(), ttl: scanTtl(scan), value: scan });\n if (!scan) {\n res.status(404).json({ error: 'No public package.json found for that.' });\n return;\n }\n res.json(scan);\n } catch (err) {\n logger.error('public scan failed:', formatError(err));\n res.status(502).json({ error: 'Could not read that repository.' });\n }\n });\n\n // Bearer API-key auth: resolve and attach the key, or 401.\n const auth = async (req: AuthedRequest, res: Response, next: NextFunction): Promise<void> => {\n const header = req.headers.authorization;\n const token = header?.startsWith('Bearer ') ? header.slice(7).trim() : '';\n if (!token) {\n res.status(401).json(rpcError(-32001, 'Missing API key. Pass Authorization: Bearer <key>.'));\n return;\n }\n try {\n const row = await lookupActiveKey(db, token);\n if (!row) {\n res.status(401).json(rpcError(-32001, 'Invalid or revoked API key.'));\n return;\n }\n req.lurqKey = row;\n next();\n } catch (err) {\n logger.error('auth lookup failed:', err instanceof Error ? err.message : String(err));\n res.status(500).json(rpcError(-32603, 'Internal error.'));\n }\n };\n\n /**\n * Monthly quota, resolved once per request after auth.\n *\n * Cached for a minute per account. The lookup is two indexed queries, which is\n * cheap once and silly on every tool call from an agent running a batch; a\n * minute of staleness means someone who just upgraded may spend up to sixty\n * more seconds on the old plan, and someone who has exhausted their quota may\n * get a handful of extra calls. Both are the right direction to be wrong in.\n * The webhook clears the entry on upgrade so the common case is instant.\n */\n const entitlementCache = new Map<string, { at: number; value: Entitlement }>();\n const ENTITLEMENT_TTL_MS = 60_000;\n\n const invalidateEntitlement = (ownerId: string) => entitlementCache.delete(ownerId);\n\n const resolveEntitlement = async (ownerId: string | null): Promise<Entitlement> => {\n if (!ownerId) return entitlementFor(db, null);\n const hit = entitlementCache.get(ownerId);\n if (hit && Date.now() - hit.at < ENTITLEMENT_TTL_MS) return hit.value;\n const value = await entitlementFor(db, ownerId);\n entitlementCache.set(ownerId, { at: Date.now(), value });\n return value;\n };\n\n // Per-key limiter (runs after auth so it can key on the resolved API key).\n const keyLimiter = rateLimit({\n windowMs: config.LURQ_RATE_LIMIT_WINDOW_MS,\n // The burst ceiling is the plan's, not one number for everybody. Read from\n // the cached entitlement when `quota` has already resolved it on a previous\n // request for this key, and otherwise from LURQ_RATE_LIMIT_MAX — the limiter\n // runs BEFORE `quota` in the chain, so the first request of a minute is\n // metered at the configured default and the rest at the plan's rate. Paying\n // for Enterprise should not leave you sharing the free tier's burst.\n limit: (req: Request) => {\n const ownerId = (req as AuthedRequest).lurqKey?.ownerId;\n const cached = ownerId ? entitlementCache.get(ownerId) : undefined;\n return cached?.value.plan.ratePerMinute ?? config.LURQ_RATE_LIMIT_MAX;\n },\n standardHeaders: 'draft-7',\n legacyHeaders: false,\n // Key on the resolved API key's unique row id (always present — auth runs\n // first). The display `prefix` is only 6 chars of body, so distinct keys\n // can collide on it and share a quota; the id cannot. The IP fallback uses\n // express-rate-limit's ipKeyGenerator so IPv6 addresses are normalized\n // correctly (v8 throws ERR_ERL_KEY_GEN_IPV6 on a raw req.ip).\n keyGenerator: (req: Request) => {\n const id = (req as AuthedRequest).lurqKey?.id;\n return id != null ? `key:${id}` : ipKeyGenerator(req.ip ?? '0.0.0.0');\n },\n ...(makeStore ? { store: makeStore('rl:key:') } : {}),\n message: rpcError(-32029, 'Rate limit exceeded.'),\n });\n\n /**\n * Enforce the plan's monthly allowance. Runs after `auth`, before the tool.\n *\n * 402 rather than 429: the caller is not going too fast, they are out of\n * allowance until the month turns, and a retry-after has nothing useful to say.\n * The body names the plan, the limit and where to change it, because an agent\n * relaying this to a developer should be relaying something actionable.\n *\n * Fails OPEN. If the entitlement lookup itself errors, the request is served:\n * a Postgres hiccup must not read as \"your subscription is invalid\" to every\n * paying customer at once. Over-serving during an outage is recoverable;\n * locking out the paid tier is the incident.\n */\n const quota = async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n const authed = req as AuthedRequest;\n const ownerId = authed.lurqKey?.ownerId ?? null;\n try {\n const ent = await resolveEntitlement(ownerId);\n authed.entitlement = ent;\n if (!ent.withinQuota) {\n res\n .status(402)\n .json(\n rpcError(\n -32002,\n `Monthly limit reached for the ${ent.plan.name} plan ` +\n `(${ent.used}/${ent.plan.monthlyCalls} calls). ` +\n `It resets when the month turns. Upgrade at ${config.LURQ_WEB_URL}/#pricing`,\n ),\n );\n return;\n }\n next();\n } catch (err) {\n logger.error(\n 'quota lookup failed, serving anyway:',\n err instanceof Error ? err.message : String(err),\n );\n next();\n }\n };\n\n // Dashboard-authenticated routes (§ identity): gated by the shared\n // LURQ_ISSUER_SECRET, never by a per-request API key. The Clerk-authenticated\n // web app presents the secret and supplies the signed-in user's `ownerId` in\n // the request body/query — the backend trusts the web app to have already\n // authenticated the user. NOT behind the per-IP limiter: all web-app calls\n // share one egress IP, so that would throttle every user together; the secret\n // + the web app's own per-user auth are the gate. Disabled (404) when the\n // secret is unset. This auth model never overlaps with the Bearer-API-key\n // `auth` middleware below: the two tokens live in disjoint namespaces (an\n // issued `lurq_live_...` key can never satisfy `secretEquals` against the\n // issuer secret, and the issuer secret is never looked up in `apiKeys`).\n const requireIssuerSecret = (req: Request, res: Response, next: NextFunction): void => {\n const secret = config.LURQ_ISSUER_SECRET;\n if (!secret) {\n res.status(404).end();\n return;\n }\n const header = req.headers.authorization;\n const token = header?.startsWith('Bearer ') ? header.slice(7).trim() : '';\n if (!token || !secretEquals(token, secret)) {\n res.status(401).json({ error: 'Invalid issuer secret.' });\n return;\n }\n next();\n };\n\n // Safe DTO for the dashboard's key list — never includes keyHash.\n const toDashboardKey = (row: ApiKeyRow) => ({\n id: row.id,\n prefix: row.prefix,\n label: row.label,\n tier: row.tier,\n scopes: row.scopes,\n createdAt: row.createdAt,\n lastUsedAt: row.lastUsedAt,\n revokedAt: row.revokedAt,\n });\n\n // ── Billing (§ Stripe) ─────────────────────────────────────────────────────\n // Checkout and portal are issuer-secret routes: the web app asks on behalf of\n // a Clerk-authenticated user and never holds a Stripe credential itself. The\n // webhook authenticates by Stripe's own signature instead, since Stripe is the\n // caller and knows nothing about our issuer secret.\n\n app.post('/billing/checkout', requireIssuerSecret, async (req: Request, res: Response) => {\n if (!billingEnabled()) {\n res.status(404).end();\n return;\n }\n const ownerId = typeof req.body?.ownerId === 'string' ? req.body.ownerId.trim() : '';\n const tier = typeof req.body?.tier === 'string' ? (req.body.tier as Tier) : 'pro';\n const email = typeof req.body?.email === 'string' ? req.body.email : null;\n if (!ownerId) {\n res.status(400).json({ error: 'ownerId is required.' });\n return;\n }\n if (!(tier in PLANS) || !PLANS[tier].paid) {\n res.status(400).json({ error: `${tier} is not a purchasable plan.` });\n return;\n }\n try {\n const url = await createCheckoutSession(db, { ownerId, tier, email });\n if (!url) {\n res.status(503).json({ error: 'That plan is not available for checkout yet.' });\n return;\n }\n res.status(200).json({ url });\n } catch (err) {\n logger.error('checkout failed:', formatError(err));\n res.status(502).json({ error: 'Could not start checkout.' });\n }\n });\n\n app.post('/billing/portal', requireIssuerSecret, async (req: Request, res: Response) => {\n if (!billingEnabled()) {\n res.status(404).end();\n return;\n }\n const ownerId = typeof req.body?.ownerId === 'string' ? req.body.ownerId.trim() : '';\n if (!ownerId) {\n res.status(400).json({ error: 'ownerId is required.' });\n return;\n }\n try {\n const url = await createPortalSession(db, ownerId);\n if (!url) {\n res.status(404).json({ error: 'No billing account for this user yet.' });\n return;\n }\n res.status(200).json({ url });\n } catch (err) {\n logger.error('portal failed:', formatError(err));\n res.status(502).json({ error: 'Could not open the billing portal.' });\n }\n });\n\n /** What the dashboard renders: the plan, its state, and the month so far. */\n /**\n * Daily Ask ceiling per account, in micro-dollars. Env-overridable because\n * the right number is a product decision that will move with pricing, and\n * moving it should not need a deploy of the web app too.\n */\n const ASK_DAILY_LIMIT_MICROS = Math.max(\n 0,\n Math.round(Number(process.env.LURQ_ASK_DAILY_USD ?? '3') * 1_000_000),\n );\n\n /**\n * The Ask budget, read and written by the dashboard's /api/ask.\n *\n * Lives here rather than in the web app because the web app has no database —\n * and because an in-process ledger is per-instance and resets on cold start,\n * which caps a burst but never a day. This is the copy that holds.\n *\n * The ceiling is served alongside the total rather than hardcoded in the web\n * app: the limit is a product decision that will change, and it should change\n * in one place that the thing enforcing it reads.\n */\n app.get('/ask-budget', requireIssuerSecret, async (req: Request, res: Response) => {\n const ownerId = typeof req.query.ownerId === 'string' ? req.query.ownerId.trim() : '';\n if (!ownerId) {\n res.status(400).json({ error: 'ownerId is required.' });\n return;\n }\n try {\n const spentMicros = await getAskSpendToday(db, ownerId);\n res.status(200).json({ spentMicros, limitMicros: ASK_DAILY_LIMIT_MICROS });\n } catch (err) {\n // Deliberately a 500, not a zero. A caller that cannot read the ledger\n // must fail closed, and it can only do that if this says \"unknown\"\n // instead of \"nothing spent\".\n logger.error('ask budget read failed:', err instanceof Error ? err.message : String(err));\n res.status(500).json({ error: 'Could not read the Ask budget.' });\n }\n });\n\n app.post('/ask-budget', requireIssuerSecret, async (req: Request, res: Response) => {\n const body = (req.body ?? {}) as { ownerId?: unknown; usdMicros?: unknown };\n const ownerId = typeof body.ownerId === 'string' ? body.ownerId.trim() : '';\n const micros = Number(body.usdMicros);\n if (!ownerId) {\n res.status(400).json({ error: 'ownerId is required.' });\n return;\n }\n // Signed: a caller reserves its worst case up front and refunds the unused\n // part after, so a refund is a legitimate negative. Bounded either way — a\n // single call may not move the ledger by more than a whole day's ceiling,\n // which turns a bug in the caller into a wrong number rather than a\n // bottomless credit.\n if (!Number.isFinite(micros) || Math.abs(micros) > ASK_DAILY_LIMIT_MICROS) {\n res.status(400).json({ error: \"usdMicros must be a finite delta within one day's limit.\" });\n return;\n }\n try {\n const spentMicros = await addAskSpend(db, ownerId, Math.round(micros));\n res.status(200).json({ spentMicros, limitMicros: ASK_DAILY_LIMIT_MICROS });\n } catch (err) {\n logger.error('ask budget write failed:', err instanceof Error ? err.message : String(err));\n res.status(500).json({ error: 'Could not record Ask spend.' });\n }\n });\n\n app.get('/billing/subscription', requireIssuerSecret, async (req: Request, res: Response) => {\n const ownerId = typeof req.query.ownerId === 'string' ? req.query.ownerId.trim() : '';\n if (!ownerId) {\n res.status(400).json({ error: 'ownerId is required.' });\n return;\n }\n try {\n const [sub, ent] = await Promise.all([\n getSubscription(db, ownerId),\n entitlementFor(db, ownerId),\n ]);\n res.status(200).json({\n tier: ent.plan.tier,\n planName: ent.plan.name,\n status: sub?.status ?? null,\n currentPeriodEnd: sub?.currentPeriodEnd?.toISOString() ?? null,\n cancelAtPeriodEnd: sub?.cancelAtPeriodEnd ?? false,\n used: ent.used,\n limit: ent.plan.monthlyCalls,\n billingEnabled: billingEnabled(),\n manageable: Boolean(sub?.stripeCustomerId),\n });\n } catch (err) {\n logger.error('subscription read failed:', err instanceof Error ? err.message : String(err));\n res.status(500).json({ error: 'Could not read the subscription.' });\n }\n });\n\n /**\n * Stripe's webhook. Signature-authenticated, so it is deliberately NOT behind\n * requireIssuerSecret or the IP limiter: Stripe calls it from its own ranges\n * and a burst of retries must not be throttled into looking like an outage.\n *\n * Answers 200 for anything it managed to verify, including events it does not\n * act on. A non-2xx makes Stripe retry for three days, so reserving failure\n * for \"we could not verify this at all\" is what keeps the retry queue honest.\n */\n app.post('/billing/webhook', async (req: Request, res: Response) => {\n const raw = (req as RawBodyRequest).rawBody;\n const signature = req.headers['stripe-signature'];\n let event;\n try {\n event = await constructEvent(\n raw ?? '',\n typeof signature === 'string' ? signature : undefined,\n );\n } catch (err) {\n logger.warn(\n `billing webhook: bad signature: ${err instanceof Error ? err.message : String(err)}`,\n );\n res.status(400).json({ error: 'Invalid signature.' });\n return;\n }\n if (!event) {\n res.status(404).end();\n return;\n }\n\n // Acknowledge before doing the work. Stripe times out at 20 seconds and a\n // retry of an already-applied event is wasted round trips on both sides.\n res.status(200).json({ received: true });\n try {\n const outcome = await handleEvent(db, event);\n logger.info(`billing webhook: ${outcome}`);\n // The plan just moved. Drop the cached entitlement so the next call sees\n // it immediately rather than up to a minute later — the one moment the\n // staleness would be felt is the moment someone has just paid.\n const object = event.data.object as { customer?: unknown };\n if (typeof object.customer === 'string') {\n const row = await getSubscriptionByCustomer(db, object.customer);\n if (row) invalidateEntitlement(row.ownerId);\n }\n } catch (err) {\n logger.error('billing webhook failed:', formatError(err));\n }\n });\n\n app.post('/keys', requireIssuerSecret, async (req: Request, res: Response) => {\n const body = (req.body ?? {}) as { ownerId?: unknown; label?: unknown; scopes?: unknown };\n const ownerId = typeof body.ownerId === 'string' ? body.ownerId.trim() : '';\n if (!ownerId) {\n res.status(400).json({ error: 'ownerId is required.' });\n return;\n }\n // Rejected, not filtered: silently dropping an unknown scope would hand back\n // a key that fails later, far from the request that asked for it.\n const scopes = parseScopes(body.scopes);\n if (!scopes) {\n res.status(400).json({ error: 'scopes must be a list of known scopes.' });\n return;\n }\n const label = typeof body.label === 'string' ? body.label.slice(0, 200) : undefined;\n try {\n const { key, row } = await createKey(db, { ownerId, label, tier: 'free', scopes });\n capture(ownerId, 'api_key_created', { tier: row.tier });\n res.status(201).json({ key, prefix: row.prefix, scopes: row.scopes });\n } catch (err) {\n logger.error('key issuance failed:', err instanceof Error ? err.message : String(err));\n res.status(500).json({ error: 'Could not issue key.' });\n }\n });\n\n app.get('/keys', requireIssuerSecret, async (req: Request, res: Response) => {\n const ownerId = typeof req.query.ownerId === 'string' ? req.query.ownerId.trim() : '';\n if (!ownerId) {\n res.status(400).json({ error: 'ownerId is required.' });\n return;\n }\n try {\n const rows = await listKeysForOwner(db, ownerId);\n res.status(200).json({ keys: rows.map(toDashboardKey) });\n } catch (err) {\n logger.error('key listing failed:', err instanceof Error ? err.message : String(err));\n res.status(500).json({ error: 'Could not list keys.' });\n }\n });\n\n app.post('/keys/:prefix/revoke', requireIssuerSecret, async (req: Request, res: Response) => {\n const prefix = req.params.prefix;\n const body = (req.body ?? {}) as { ownerId?: unknown };\n const ownerId = typeof body.ownerId === 'string' ? body.ownerId.trim() : '';\n if (typeof prefix !== 'string' || !ownerId) {\n res.status(400).json({ error: 'ownerId is required.' });\n return;\n }\n try {\n const row = await findKeyForOwner(db, { prefixOrId: prefix, ownerId });\n if (!row) {\n res.status(404).json({ error: 'Key not found.' });\n return;\n }\n await revokeKey(db, String(row.id));\n res.status(200).json({ revoked: true });\n } catch (err) {\n logger.error('key revoke failed:', err instanceof Error ? err.message : String(err));\n res.status(500).json({ error: 'Could not revoke key.' });\n }\n });\n\n app.post('/keys/:prefix/rotate', requireIssuerSecret, async (req: Request, res: Response) => {\n const prefix = req.params.prefix;\n const body = (req.body ?? {}) as { ownerId?: unknown };\n const ownerId = typeof body.ownerId === 'string' ? body.ownerId.trim() : '';\n if (typeof prefix !== 'string' || !ownerId) {\n res.status(400).json({ error: 'ownerId is required.' });\n return;\n }\n try {\n const row = await findKeyForOwner(db, { prefixOrId: prefix, ownerId });\n if (!row) {\n res.status(404).json({ error: 'Key not found.' });\n return;\n }\n const rotated = await rotateKey(db, String(row.id));\n if (!rotated) {\n res.status(404).json({ error: 'Key not found.' });\n return;\n }\n res.status(200).json({ key: rotated.key, prefix: rotated.row.prefix });\n } catch (err) {\n logger.error('key rotate failed:', err instanceof Error ? err.message : String(err));\n res.status(500).json({ error: 'Could not rotate key.' });\n }\n });\n\n app.get('/outcomes', requireIssuerSecret, async (req: Request, res: Response) => {\n const ownerId = typeof req.query.ownerId === 'string' ? req.query.ownerId.trim() : '';\n if (!ownerId) {\n res.status(400).json({ error: 'ownerId is required.' });\n return;\n }\n const limitRaw = typeof req.query.limit === 'string' ? Number(req.query.limit) : undefined;\n const limit =\n limitRaw && Number.isInteger(limitRaw) && limitRaw > 0 ? Math.min(limitRaw, 200) : undefined;\n try {\n const rows = await getOutcomesByOwner(db, ownerId, { limit });\n res.status(200).json({\n outcomes: rows.map((row) => ({\n packageName: row.packageName,\n accepted: row.accepted,\n buildSignal: row.buildSignal,\n need: row.need,\n createdAt: row.createdAt,\n })),\n });\n } catch (err) {\n logger.error('outcomes read failed:', err instanceof Error ? err.message : String(err));\n res.status(500).json({ error: 'Could not read outcomes.' });\n }\n });\n\n app.get('/usage', requireIssuerSecret, async (req: Request, res: Response) => {\n const ownerId = typeof req.query.ownerId === 'string' ? req.query.ownerId.trim() : '';\n if (!ownerId) {\n res.status(400).json({ error: 'ownerId is required.' });\n return;\n }\n const daysRaw = typeof req.query.days === 'string' ? Number(req.query.days) : NaN;\n const days = Number.isInteger(daysRaw) && daysRaw > 0 ? Math.min(daysRaw, 365) : 30;\n try {\n const [summary, byTool] = await Promise.all([\n getUsageSummary(db, ownerId, days),\n getUsageByTool(db, ownerId, days),\n ]);\n res.status(200).json({ today: summary.today, series: summary.series, byTool });\n } catch (err) {\n logger.error('usage read failed:', err instanceof Error ? err.message : String(err));\n res.status(500).json({ error: 'Could not read usage.' });\n }\n });\n\n /** Autopilot impact totals for the dashboard. Not gated on the GitHub App:\n * runs can arrive from any checkout via the CLI, connected or not. */\n app.get('/impact', requireIssuerSecret, async (req: Request, res: Response) => {\n const ownerId = typeof req.query.ownerId === 'string' ? req.query.ownerId.trim() : '';\n if (!ownerId) {\n res.status(400).json({ error: 'ownerId is required.' });\n return;\n }\n const daysRaw = typeof req.query.days === 'string' ? Number(req.query.days) : NaN;\n const days = Number.isInteger(daysRaw) && daysRaw > 0 ? Math.min(daysRaw, 365) : 30;\n try {\n res.status(200).json(await getUpgradeImpact(db, ownerId, days));\n } catch (err) {\n logger.error('impact read failed:', err instanceof Error ? err.message : String(err));\n res.status(500).json({ error: 'Could not read impact.' });\n }\n });\n\n app.get('/contributions', requireIssuerSecret, async (req: Request, res: Response) => {\n const ownerId = typeof req.query.ownerId === 'string' ? req.query.ownerId.trim() : '';\n if (!ownerId) {\n res.status(400).json({ error: 'ownerId is required.' });\n return;\n }\n const limitRaw = typeof req.query.limit === 'string' ? Number(req.query.limit) : NaN;\n const limit = Number.isInteger(limitRaw) && limitRaw > 0 ? Math.min(limitRaw, 200) : 50;\n const offsetRaw = typeof req.query.offset === 'string' ? Number(req.query.offset) : NaN;\n const offset = Number.isInteger(offsetRaw) && offsetRaw > 0 ? offsetRaw : 0;\n try {\n const { total, packages: rows } = await getContributionsByOwner(db, ownerId, {\n limit,\n offset,\n });\n res.status(200).json({ total, packages: rows });\n } catch (err) {\n logger.error('contributions read failed:', err instanceof Error ? err.message : String(err));\n res.status(500).json({ error: 'Could not read contributions.' });\n }\n });\n\n // ── Repo autopilot (dashboard-authenticated, same issuer-secret model) ──────\n\n /** 404 the whole surface when no GitHub App is configured, matching /keys. */\n const requireGithubApp = (_req: Request, res: Response, next: NextFunction): void => {\n if (!githubAppCredentials()) {\n res.status(404).end();\n return;\n }\n next();\n };\n\n /** Every repo route is owner-scoped; a missing ownerId is a 400, never a\n * wildcard read. See the header of src/db/repos.ts. */\n const ownerFrom = (req: Request): string => {\n const source = req.method === 'GET' ? req.query : (req.body ?? {});\n const raw = (source as Record<string, unknown>).ownerId;\n return typeof raw === 'string' ? raw.trim() : '';\n };\n\n /** Manifests are never sent to the browser — only the derived drift summary.\n * The dependency ranges are input to our computation, not dashboard content. */\n const toDashboardRepo = (row: RepoRow) => ({\n id: row.id,\n fullName: row.fullName,\n defaultBranch: row.defaultBranch,\n isPrivate: row.isPrivate,\n policy: row.policy,\n drift: row.drift\n ? {\n depsDeclared: row.drift.depsDeclared,\n depsTracked: row.drift.depsTracked,\n majorDrift: row.drift.majorDrift,\n anyDrift: row.drift.anyDrift,\n deprecated: row.drift.deprecated,\n advisories: row.drift.advisories,\n /** null = scanned before the check existed, so it was never run. Kept\n * distinct from 0 so the dashboard cannot render \"not checked\" as a\n * clean stack. */\n conflicts: row.drift.conflictsAtLatest?.length ?? null,\n transitive: row.drift.transitive\n ? {\n resolved: row.drift.transitive.resolved,\n tracked: row.drift.transitive.tracked,\n advisoryPackages: row.drift.transitive.advisoryPackages,\n deprecated: row.drift.transitive.deprecated,\n truncated: row.drift.transitive.truncated,\n attributed: row.drift.transitive.attributed,\n }\n : null,\n }\n : null,\n lastScanAt: row.lastScanAt,\n lastScanError: row.lastScanError,\n });\n\n /** Reject anything not matching RepoPolicy rather than merging partial input —\n * a policy is a permission grant, and a half-parsed one could arm a repo the\n * user meant to leave off. */\n function parsePolicy(input: unknown): RepoPolicy | null {\n if (!input || typeof input !== 'object') return null;\n const raw = input as Record<string, unknown>;\n if (typeof raw.enabled !== 'boolean') return null;\n if (typeof raw.autoMerge !== 'boolean') return null;\n if (raw.scope !== 'security' && raw.scope !== 'blocking' && raw.scope !== 'all') return null;\n return { enabled: raw.enabled, scope: raw.scope, autoMerge: raw.autoMerge };\n }\n\n /**\n * Register everything an installation currently covers, then scan in the\n * background. Returns the number of repos registered.\n *\n * Shared by the post-install redirect and the webhook so both agree on what\n * \"connected\" means, and so neither takes a repo's shape from a payload — the\n * inventory is always re-read from the API, which is the only source carrying\n * `default_branch` (a webhook's repo object does not, and defaulting it to\n * `main` would silently scan the wrong branch).\n *\n * `scanOnly` limits the background scan without limiting the registration: a\n * webhook that adds one repo to a 200-repo installation should register the\n * inventory it just read but not re-scan 199 repos nobody touched.\n */\n const syncInstallation = async (\n ownerId: string,\n installationId: number,\n scanOnly?: string[],\n ): Promise<number> => {\n const found = await listInstallationRepos(installationId);\n const connected = await upsertRepos(\n db,\n found.map((repo) => ({\n ownerId,\n installationId,\n fullName: repo.fullName,\n defaultBranch: repo.defaultBranch,\n isPrivate: repo.isPrivate,\n })),\n );\n // Deliberately not awaited: a first scan of a large account is minutes of\n // GitHub calls, and holding the request open for it would time out at the\n // edge and look like a failed install. Most-recently-pushed first, because\n // the scan is sequential and that order is what the user watching the\n // dashboard experiences as speed (see byRecentPush).\n void (async () => {\n const rows = byRecentPush(await listRepos(db, ownerId), found);\n const only = scanOnly ? new Set(scanOnly) : null;\n await scanRepos(db, only ? rows.filter((row) => only.has(row.fullName)) : rows);\n })().catch((err: unknown) => {\n logger.warn(`repo scan failed: ${err instanceof Error ? err.message : String(err)}`);\n });\n return connected;\n };\n\n app.post(\n '/repos/connect',\n requireIssuerSecret,\n requireGithubApp,\n async (req: Request, res: Response) => {\n const ownerId = ownerFrom(req);\n const installationRaw = (req.body ?? {}).installationId;\n const installationId = Number(installationRaw);\n if (!ownerId || !Number.isInteger(installationId) || installationId <= 0) {\n res.status(400).json({ error: 'ownerId and installationId are required.' });\n return;\n }\n try {\n res.status(200).json({ connected: await syncInstallation(ownerId, installationId) });\n } catch (err) {\n const status = err instanceof GithubAppError ? err.status : 502;\n logger.error('repo connect failed:', err instanceof Error ? err.message : String(err));\n res.status(status).json({ error: 'Could not read the GitHub installation.' });\n }\n },\n );\n\n /**\n * GitHub App webhook — the only route here authenticated by GitHub's signature\n * rather than by the issuer secret or an API key.\n *\n * Not behind `requireIssuerSecret` (GitHub cannot present it) and not behind the\n * per-IP limiter (GitHub's delivery IPs are shared, and 429-ing them drops\n * events silently). The HMAC over the raw body is the gate, and an unset secret\n * 404s the route rather than leaving it open.\n *\n * Acks before doing the work: GitHub retries on timeout, and a duplicate\n * delivery would re-run the sync — idempotent, but a wasted scan of the whole\n * installation each time.\n */\n app.post('/github/webhook', requireGithubApp, async (req: Request, res: Response) => {\n const secret = config.LURQ_GITHUB_WEBHOOK_SECRET;\n if (!secret) {\n res.status(404).end();\n return;\n }\n const raw = (req as RawBodyRequest).rawBody;\n const signature = req.headers['x-hub-signature-256'];\n if (\n !raw ||\n !verifyWebhookSignature(secret, raw, typeof signature === 'string' ? signature : undefined)\n ) {\n res.status(401).json({ error: 'Invalid signature.' });\n return;\n }\n\n const event = req.headers['x-github-event'];\n const action = parseWebhook(typeof event === 'string' ? event : undefined, req.body);\n res.status(202).end();\n if (action.kind === 'ignored') return;\n\n try {\n if (action.kind === 'uninstalled') {\n const forgotten = await deleteReposByInstallation(db, action.installationId);\n logger.info(`installation ${action.installationId} uninstalled, forgot ${forgotten} repos`);\n return;\n }\n\n // Removals first, and they need no owner lookup — the rows carry it. Doing\n // them before the owner check also means a user who removes their *last*\n // repo still gets it deleted, even though that erases the very mapping the\n // addition path depends on (see ownerForInstallation).\n if (action.removed.length > 0) {\n await deleteReposByInstallation(db, action.installationId, action.removed);\n }\n if (action.added.length === 0) return;\n\n const ownerId = await ownerForInstallation(db, action.installationId);\n if (!ownerId) {\n // An installation nobody has connected through the dashboard: there is no\n // lurq user to attribute these repos to, and guessing one would hand\n // someone else's repos to an account. Dropping it is correct.\n logger.warn(`webhook for unlinked installation ${action.installationId}, ignored`);\n return;\n }\n await syncInstallation(ownerId, action.installationId, action.added);\n } catch (err) {\n // The ack already went out; GitHub will not retry. Logged rather than\n // thrown, and the next nightly scan reconciles anything missed.\n logger.error(\n `webhook handling failed for installation ${action.installationId}:`,\n err instanceof Error ? err.message : String(err),\n );\n }\n });\n\n app.get('/repos', requireIssuerSecret, requireGithubApp, async (req: Request, res: Response) => {\n const ownerId = ownerFrom(req);\n if (!ownerId) {\n res.status(400).json({ error: 'ownerId is required.' });\n return;\n }\n try {\n const rows = await listRepos(db, ownerId);\n res.status(200).json({ repos: rows.map(toDashboardRepo) });\n } catch (err) {\n logger.error('repo list failed:', err instanceof Error ? err.message : String(err));\n res.status(500).json({ error: 'Could not list repos.' });\n }\n });\n\n // Must stay above `/repos/:id` — Express matches in registration order, and\n // `:id` would otherwise capture the literal \"alerts\" and 400 on Number('alerts').\n app.get(\n '/repos/alerts',\n requireIssuerSecret,\n requireGithubApp,\n async (req: Request, res: Response) => {\n const ownerId = ownerFrom(req);\n if (!ownerId) {\n res.status(400).json({ error: 'ownerId is required.' });\n return;\n }\n try {\n res.status(200).json({ alerts: await listAlerts(db, ownerId) });\n } catch (err) {\n logger.error('alert list failed:', err instanceof Error ? err.message : String(err));\n res.status(500).json({ error: 'Could not list alerts.' });\n }\n },\n );\n\n app.get(\n '/repos/:id',\n requireIssuerSecret,\n requireGithubApp,\n async (req: Request, res: Response) => {\n const ownerId = ownerFrom(req);\n const id = Number(req.params.id);\n if (!ownerId || !Number.isInteger(id)) {\n res.status(400).json({ error: 'ownerId and a numeric id are required.' });\n return;\n }\n try {\n const row = await getRepo(db, ownerId, id);\n if (!row) {\n res.status(404).json({ error: 'Repo not found.' });\n return;\n }\n const runs = await listRunsForRepo(db, ownerId, row.id);\n // The setup file is rendered per repo because it carries that repo's own\n // package manager and armed state. Shipped as text so the dashboard can\n // show exactly what will be committed before anything is.\n const workflow = renderWorkflow({\n installCommand: row.installCommand ?? undefined,\n armed: row.policy.enabled,\n autoMerge: row.policy.autoMerge,\n });\n res.status(200).json({\n repo: {\n ...toDashboardRepo(row),\n deps: row.drift?.deps ?? [],\n transitiveRisks: row.drift?.transitive?.risks ?? [],\n conflicts: row.drift?.conflictsAtLatest ?? null,\n runs,\n workflow,\n workflowPath: WORKFLOW_PATH,\n setupUrl: newFileUrl(row.fullName, row.defaultBranch ?? 'main', workflow),\n },\n });\n } catch (err) {\n logger.error('repo read failed:', err instanceof Error ? err.message : String(err));\n res.status(500).json({ error: 'Could not read repo.' });\n }\n },\n );\n\n app.get(\n '/repos/:id/brief',\n requireIssuerSecret,\n requireGithubApp,\n async (req: Request, res: Response) => {\n const ownerId = ownerFrom(req);\n const id = Number(req.params.id);\n if (!ownerId || !Number.isInteger(id)) {\n res.status(400).json({ error: 'ownerId and a numeric id are required.' });\n return;\n }\n try {\n const row = await getRepo(db, ownerId, id);\n if (!row) {\n res.status(404).json({ error: 'Repo not found.' });\n return;\n }\n res.status(200).json(await briefRepo(db, row.drift ?? null));\n } catch (err) {\n logger.error('repo brief failed:', err instanceof Error ? err.message : String(err));\n res.status(500).json({ error: 'Could not build the migration brief.' });\n }\n },\n );\n\n app.post(\n '/repos/:id/scan',\n requireIssuerSecret,\n requireGithubApp,\n async (req: Request, res: Response) => {\n const ownerId = ownerFrom(req);\n const id = Number(req.params.id);\n if (!ownerId || !Number.isInteger(id)) {\n res.status(400).json({ error: 'ownerId and a numeric id are required.' });\n return;\n }\n try {\n const row = await getRepo(db, ownerId, id);\n if (!row) {\n res.status(404).json({ error: 'Repo not found.' });\n return;\n }\n // One repo is a handful of GitHub calls — fast enough to await, so the\n // dashboard can render the new numbers instead of polling for them.\n const result = await scanRepo(db, row);\n res.status(200).json({ result });\n } catch (err) {\n logger.error('repo scan failed:', err instanceof Error ? err.message : String(err));\n res.status(500).json({ error: 'Could not scan repo.' });\n }\n },\n );\n\n app.patch(\n '/repos/:id',\n requireIssuerSecret,\n requireGithubApp,\n async (req: Request, res: Response) => {\n const ownerId = ownerFrom(req);\n const id = Number(req.params.id);\n const policy = parsePolicy((req.body ?? {}).policy);\n if (!ownerId || !Number.isInteger(id) || !policy) {\n res\n .status(400)\n .json({ error: 'ownerId, a numeric id, and a complete policy are required.' });\n return;\n }\n try {\n const updated = await setRepoPolicy(db, ownerId, id, policy);\n if (!updated) {\n res.status(404).json({ error: 'Repo not found.' });\n return;\n }\n res.status(200).json({ policy });\n } catch (err) {\n logger.error(\n 'repo policy update failed:',\n err instanceof Error ? err.message : String(err),\n );\n res.status(500).json({ error: 'Could not update policy.' });\n }\n },\n );\n\n app.delete(\n '/repos/:id',\n requireIssuerSecret,\n requireGithubApp,\n async (req: Request, res: Response) => {\n const ownerId = ownerFrom(req);\n const id = Number(req.params.id);\n if (!ownerId || !Number.isInteger(id)) {\n res.status(400).json({ error: 'ownerId and a numeric id are required.' });\n return;\n }\n try {\n const removed = await deleteRepo(db, ownerId, id);\n res\n .status(removed ? 200 : 404)\n .json(removed ? { removed: true } : { error: 'Repo not found.' });\n } catch (err) {\n logger.error('repo delete failed:', err instanceof Error ? err.message : String(err));\n res.status(500).json({ error: 'Could not disconnect repo.' });\n }\n },\n );\n\n // ── Selection policy (dashboard-authenticated) ─────────────────────────────\n //\n // Not behind `requireGithubApp`: selection policy governs what an agent may\n // install through MCP, which works with no repository connected at all.\n // Gating it on the GitHub App would make the rules unreachable for exactly the\n // users who have only wired up the MCP server.\n\n app.get('/selection-policy', requireIssuerSecret, async (req: Request, res: Response) => {\n const ownerId = ownerFrom(req);\n if (!ownerId) {\n res.status(400).json({ error: 'ownerId is required.' });\n return;\n }\n try {\n res.status(200).json({ policy: await getSelectionPolicy(db, ownerId) });\n } catch (err) {\n logger.error(\n 'selection policy read failed:',\n err instanceof Error ? err.message : String(err),\n );\n res.status(500).json({ error: 'Could not read policy.' });\n }\n });\n\n app.put('/selection-policy', requireIssuerSecret, async (req: Request, res: Response) => {\n const ownerId = ownerFrom(req);\n if (!ownerId) {\n res.status(400).json({ error: 'ownerId is required.' });\n return;\n }\n const parsed = validateSelectionPolicy((req.body ?? {}).policy);\n if ('error' in parsed) {\n res.status(400).json({ error: parsed.error });\n return;\n }\n try {\n const previous = await setSelectionPolicy(db, ownerId, parsed.policy, 'dashboard');\n res.status(200).json({ policy: parsed.policy, previous });\n } catch (err) {\n logger.error(\n 'selection policy write failed:',\n err instanceof Error ? err.message : String(err),\n );\n res.status(500).json({ error: 'Could not save policy.' });\n }\n });\n\n // The same policy, run backwards over the repos that already exist. Not gated\n // on the GitHub App: an owner with no connected repos gets an empty list, which\n // the dashboard renders as \"connect a repo\", not as a failure.\n app.get(\n '/selection-policy/conformance',\n requireIssuerSecret,\n async (req: Request, res: Response) => {\n const ownerId = ownerFrom(req);\n if (!ownerId) {\n res.status(400).json({ error: 'ownerId is required.' });\n return;\n }\n try {\n res.status(200).json(await repoConformance(db, ownerId));\n } catch (err) {\n logger.error('conformance read failed:', err instanceof Error ? err.message : String(err));\n res.status(500).json({ error: 'Could not read conformance.' });\n }\n },\n );\n\n // ── Ask's package tools (dashboard-authenticated) ─────────────────────────\n //\n // The dashboard holds no API key for its user, so it cannot reach /mcp. These\n // run the same tools for the signed-in owner the web app names, and count\n // against that owner's plan exactly like an agent's call would: Ask looking a\n // package up is a hosted call, not a free side door around the quota.\n\n app.get('/ask-tools', requireIssuerSecret, async (_req: Request, res: Response) => {\n try {\n res.status(200).json({ tools: await listDashboardTools(db) });\n } catch (err) {\n logger.error('ask tools list failed:', err instanceof Error ? err.message : String(err));\n res.status(500).json({ error: 'Could not list Ask tools.' });\n }\n });\n\n app.post('/ask-tools/call', requireIssuerSecret, async (req: Request, res: Response) => {\n const ownerId = ownerFrom(req);\n const body = (req.body ?? {}) as { name?: unknown; arguments?: unknown };\n const name = typeof body.name === 'string' ? body.name : '';\n if (!ownerId || !DASHBOARD_TOOLS.has(name)) {\n res.status(400).json({ error: 'ownerId and an Ask tool name are required.' });\n return;\n }\n const args =\n body.arguments && typeof body.arguments === 'object' && !Array.isArray(body.arguments)\n ? (body.arguments as Record<string, unknown>)\n : {};\n try {\n const ent = await resolveEntitlement(ownerId);\n if (!ent.withinQuota) {\n res.status(402).json({\n error: `Monthly limit reached for the ${ent.plan.name} plan (${ent.used}/${ent.plan.monthlyCalls} calls).`,\n });\n return;\n }\n } catch (err) {\n // Fails open, for the reason `quota` does: an entitlement hiccup must not\n // read as \"out of allowance\" to every account at once.\n logger.error(\n 'ask tool quota lookup failed, serving anyway:',\n err instanceof Error ? err.message : String(err),\n );\n }\n try {\n res.status(200).json(await callDashboardTool(db, ownerId, name, args));\n } catch (err) {\n logger.error('ask tool call failed:', err instanceof Error ? err.message : String(err));\n res.status(500).json({ error: 'Could not run that lookup.' });\n }\n });\n\n // ── Selection policy as code (API-key authenticated) ───────────────────────\n //\n // The same rules the dashboard edits, for `lurq policy pull/push` — so a team\n // can keep policy in a reviewed file and apply it from CI. Owner comes from the\n // key, never the body. Reads are open to any account key; writes need the\n // `policy:write` scope, which `lurq setup` never requests: the key sitting in an\n // agent's MCP config must not be able to loosen the policy that agent obeys.\n // Not behind `quota`: governing the agent should never compete with using it.\n\n // History and the decision log, shared by the key routes below and the\n // dashboard routes beside them: same reads, two ways of proving the owner.\n const sendPolicyHistory = async (ownerId: string, res: Response): Promise<void> => {\n try {\n res.status(200).json({ changes: await listPolicyChanges(db, ownerId) });\n } catch (err) {\n logger.error('policy history read failed:', err instanceof Error ? err.message : String(err));\n res.status(500).json({ error: 'Could not read policy history.' });\n }\n };\n\n const sendPolicyDecisions = async (ownerId: string, rawDays: unknown, res: Response) => {\n const days = rawDays === undefined ? 30 : Number(rawDays);\n if (!Number.isInteger(days) || days < 1 || days > 365) {\n res.status(400).json({ error: 'days must be a whole number from 1 to 365.' });\n return;\n }\n try {\n res.status(200).json({ days, decisions: await summarizeDecisions(db, ownerId, days) });\n } catch (err) {\n logger.error('policy decisions read failed:', err instanceof Error ? err.message : String(err));\n res.status(500).json({ error: 'Could not read policy decisions.' });\n }\n };\n\n app.get('/selection-policy/history', requireIssuerSecret, async (req: Request, res: Response) => {\n const ownerId = ownerFrom(req);\n if (!ownerId) {\n res.status(400).json({ error: 'ownerId is required.' });\n return;\n }\n await sendPolicyHistory(ownerId, res);\n });\n\n app.get('/selection-policy/decisions', requireIssuerSecret, async (req: Request, res: Response) => {\n const ownerId = ownerFrom(req);\n if (!ownerId) {\n res.status(400).json({ error: 'ownerId is required.' });\n return;\n }\n await sendPolicyDecisions(ownerId, req.query.days, res);\n });\n\n const keyOwner = (req: Request, res: Response): string | null => {\n const ownerId = (req as AuthedRequest).lurqKey?.ownerId ?? null;\n if (!ownerId) res.status(403).json({ error: 'This key has no account attached.' });\n return ownerId;\n };\n\n app.get('/policy', ipLimiter, auth, keyLimiter, async (req: Request, res: Response) => {\n const ownerId = keyOwner(req, res);\n if (!ownerId) return;\n try {\n res.status(200).json({ policy: await getSelectionPolicy(db, ownerId) });\n } catch (err) {\n logger.error('policy read failed:', err instanceof Error ? err.message : String(err));\n res.status(500).json({ error: 'Could not read policy.' });\n }\n });\n\n app.put('/policy', ipLimiter, auth, keyLimiter, async (req: Request, res: Response) => {\n const ownerId = keyOwner(req, res);\n if (!ownerId) return;\n if (!hasScope((req as AuthedRequest).lurqKey!, 'policy:write')) {\n res.status(403).json({\n error: 'This key cannot change policy. Create a key with the policy:write scope in the dashboard.',\n });\n return;\n }\n const parsed = validateSelectionPolicy((req.body ?? {}).policy);\n if ('error' in parsed) {\n res.status(400).json({ error: parsed.error });\n return;\n }\n try {\n // `previous` is what lets `lurq policy push` print the change it made,\n // diffed against what was actually replaced rather than a stale pull.\n const actor = `key ${(req as AuthedRequest).lurqKey!.prefix}`;\n const previous = await setSelectionPolicy(db, ownerId, parsed.policy, actor);\n res.status(200).json({ policy: parsed.policy, previous });\n } catch (err) {\n logger.error('policy write failed:', err instanceof Error ? err.message : String(err));\n res.status(500).json({ error: 'Could not save policy.' });\n }\n });\n\n app.get('/policy/history', ipLimiter, auth, keyLimiter, async (req: Request, res: Response) => {\n const ownerId = keyOwner(req, res);\n if (ownerId) await sendPolicyHistory(ownerId, res);\n });\n\n app.get('/policy/decisions', ipLimiter, auth, keyLimiter, async (req: Request, res: Response) => {\n const ownerId = keyOwner(req, res);\n if (ownerId) await sendPolicyDecisions(ownerId, req.query.days, res);\n });\n\n // ── Autopilot CI surface (API-key authenticated, same as /mcp) ─────────────\n //\n // These two are what the user's GitHub Actions workflow calls. They are keyed\n // on the API key, NOT the issuer secret: the workflow is the user's own\n // machine, so it holds a per-user key and never the web↔backend shared secret.\n //\n // Note there is no repo id in either path. The workflow sends the manifest it\n // already has on disk, so `upgrade-plan` works in any checkout — connecting a\n // repo to the dashboard adds visibility, it is not a precondition for the loop.\n\n app.post(\n '/upgrade-plan',\n ipLimiter,\n auth,\n keyLimiter,\n quota,\n async (req: Request, res: Response) => {\n const deps = parseDepsInput((req.body ?? {}).deps);\n if (Object.keys(deps).length === 0) {\n res.status(400).json({ error: 'deps is required: { \"package\": \"range\", … }' });\n return;\n }\n // Read up front rather than at the policy lookup below: computeDrift now\n // attributes any first-time ingest it triggers to this caller.\n const ownerId = (req as AuthedRequest).lurqKey?.ownerId ?? null;\n try {\n const drift = await computeDrift(db, [{ path: 'package.json', deps }], null, ownerId);\n const brief = await briefRepo(db, drift);\n\n // Policy enforcement, when the caller identifies a repo this owner has\n // connected. `repo` is optional by design: the endpoint has always worked\n // in any checkout, and connecting is what opts a repo into being governed.\n // An unconnected or unrecognised name yields a null policy and the\n // unfiltered behaviour this endpoint shipped with.\n const repoFullName = parseRepoFullName((req.body ?? {}).repo);\n const policy =\n ownerId && repoFullName ? await findPolicyByFullName(db, ownerId, repoFullName) : null;\n const scoped = applyScope(brief.upgrades, policy);\n\n res.status(200).json({\n ...brief,\n ...scoped,\n // Surfaced so CI can log what lurq had no opinion on. An upgrade we do\n // not know about must not look like an upgrade we cleared.\n untracked: Object.keys(deps).length - drift.depsTracked,\n });\n // Counted like any other tool call. Usage was recorded only inside the MCP\n // server, so a user whose whole relationship with lurq is the weekly\n // autopilot saw a dashboard reading zero calls — the one view meant to\n // show them they are getting value. Fire-and-forget, after the response.\n void recordUsage(db, ownerId, 'upgrade-plan');\n } catch (err) {\n logger.error('upgrade plan failed:', err instanceof Error ? err.message : String(err));\n res.status(500).json({ error: 'Could not build the upgrade plan.' });\n }\n },\n );\n\n app.post(\n '/upgrade-runs',\n ipLimiter,\n auth,\n keyLimiter,\n quota,\n async (req: Request, res: Response) => {\n const ownerId = (req as AuthedRequest).lurqKey?.ownerId ?? null;\n if (!ownerId) {\n // Operator-issued keys have no dashboard account to attribute runs to.\n res.status(403).json({ error: 'This key has no account attached.' });\n return;\n }\n const { runs, rejected } = parseUpgradeRuns((req.body ?? {}).runs, MAX_RUNS_PER_POST);\n if (runs.length === 0) {\n res.status(400).json({ error: 'runs must be a non-empty array of upgrade results.' });\n return;\n }\n try {\n // Resolve repo links once per distinct repo, not once per run.\n const repoIds = new Map<string, number | null>();\n for (const run of runs) {\n if (!repoIds.has(run.repoFullName)) {\n repoIds.set(\n run.repoFullName,\n await findRepoIdByFullName(db, ownerId, run.repoFullName),\n );\n }\n }\n const recorded = await recordUpgradeRuns(\n db,\n runs.map((run) => ({ ...run, ownerId, repoId: repoIds.get(run.repoFullName) ?? null })),\n );\n res.status(200).json({ recorded, rejected });\n void recordUsage(db, ownerId, 'upgrade-runs');\n } catch (err) {\n logger.error(\n 'upgrade run record failed:',\n err instanceof Error ? err.message : String(err),\n );\n res.status(500).json({ error: 'Could not record the upgrade runs.' });\n }\n },\n );\n\n app.post('/mcp', ipLimiter, auth, keyLimiter, quota, async (req: Request, res: Response) => {\n // Stateless: a fresh server+transport per request, sharing the one DB pool.\n // Thread the authenticated key's owner identity into the tools (§3.1).\n const server = buildMcpServer(db, { ownerId: (req as AuthedRequest).lurqKey?.ownerId ?? null });\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: undefined,\n enableJsonResponse: true,\n });\n res.on('close', () => {\n void transport.close();\n void server.close();\n });\n try {\n await server.connect(transport);\n await transport.handleRequest(req, res, req.body);\n } catch (err) {\n logger.error('mcp request failed:', err instanceof Error ? err.message : String(err));\n if (!res.headersSent) res.status(500).json(rpcError(-32603, 'Internal error'));\n }\n });\n\n // Stateless server: no session GET/DELETE handling.\n app.all('/mcp', (_req: Request, res: Response) => {\n res.status(405).json(rpcError(-32000, 'Method not allowed.'));\n });\n\n // Terminal error handler. Registered last so it catches everything upstream,\n // including the two `express.json()` rejections that never reach a route:\n // a malformed body (400) and one over the 1mb limit (413).\n //\n // Without it those fell through to Express's default handler, which answers\n // with an HTML error page. Every other rejection on this server is JSON, so a\n // client — including lurq's own parseRpcBody — got undefined where it expected\n // a message and reported a bare \"failed with HTTP 400\" with no reason. The\n // one case where the body is the whole diagnosis was the one case it was\n // unreadable.\n //\n // Four parameters, and `_next` must stay: Express identifies an error handler\n // by arity, and dropping it silently turns this back into normal middleware.\n app.use((err: RequestError, req: Request, res: Response, _next: NextFunction) => {\n const { status, body, clientFault } = errorEnvelope(err, req.path);\n // A client's malformed request is not a server incident; only log the rest.\n if (!clientFault) {\n logger.error(`unhandled request error (${req.method} ${req.path}):`, err.message);\n }\n if (res.headersSent) return;\n res.status(status).json(body);\n });\n\n const server = app.listen(port, () => {\n logger.info(`lurq HTTP MCP server listening on :${port}/mcp`);\n });\n // A port already in use emits 'error' on the server, which is an unhandled\n // 'error' event — a crash with a stack trace instead of a sentence.\n server.on('error', (err: Error) => {\n logger.error(`could not listen on :${port}: ${err.message}`);\n process.exit(1);\n });\n\n /**\n * Drain on SIGTERM, which is how every deploy ends.\n *\n * Railway sends SIGTERM and then SIGKILLs what is still alive. With no handler\n * the default is immediate death, so every request in flight at that moment\n * dies mid-response — on a redeploy that is a burst of failures for callers\n * doing nothing wrong, and the agent on the other end reads it as lurq being\n * unreliable rather than as us shipping.\n *\n * `server.close` stops accepting new connections and waits for the open ones,\n * then the pool closes. The timer is the backstop: a wedged connection must\n * not hold the process past the platform's own grace period, and it is\n * unref'd so it can never be the thing keeping us alive.\n */\n const FORCE_EXIT_MS = 10_000;\n let shuttingDown = false;\n const shutdown = (signal: string) => {\n if (shuttingDown) return; // a second SIGTERM must not race the first\n shuttingDown = true;\n logger.info(`${signal} received, draining…`);\n const force = setTimeout(() => {\n logger.warn('drain timed out, exiting anyway');\n process.exit(0);\n }, FORCE_EXIT_MS);\n force.unref();\n server.close(() => {\n // Queued PostHog events go before the pool; flush never throws.\n void flushAnalytics().then(closeDb).then(\n () => process.exit(0),\n () => process.exit(0),\n );\n });\n };\n process.on('SIGTERM', () => shutdown('SIGTERM'));\n process.on('SIGINT', () => shutdown('SIGINT'));\n}\n","#!/usr/bin/env node\n/**\n * lurq CLI entry point. Runnable via `npx lurq <command>` (§7, §13).\n */\nimport { readFileSync } from 'node:fs';\nimport updateNotifier from 'update-notifier';\nimport { buildProgram } from '../cli/index';\nimport { withSetupOnMissingKey } from '../cli/install';\nimport { loadEnv } from '../core/config';\nimport { enforceGate } from '../core/gate';\nimport { logger } from '../core/logger';\n\nloadEnv();\n\n// Private-preview gate: non-owners get a placeholder, the owner runs as usual.\n// Runs after loadEnv so LURQ_OWNER_KEY from a .env file is honored too.\nenforceGate(process.argv.slice(2));\n\nnotifyOnUpdate();\n\n// A fresh program per attempt: commander instances are single-use.\nwithSetupOnMissingKey(() => buildProgram().parseAsync(process.argv))\n .catch((err) => {\n logger.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n });\n\n/**\n * Check npm (at most once a day, in a detached background process) and print a\n * one-line \"update available\" banner on exit when a newer lurqrun is published.\n * Skipped in agent/machine contexts — MCP stdio servers and `--json` output —\n * so the protocol/output stream is never touched. update-notifier additionally\n * only prints in a TTY, so piped runs stay silent regardless. Any failure here\n * must never break the CLI, hence the broad guard.\n */\nfunction notifyOnUpdate(): void {\n const argv = process.argv.slice(2);\n const quiet =\n argv[0] === 'serve' || argv[0] === 'serve-http' || argv.includes('--json');\n if (quiet) return;\n\n try {\n const pkg = JSON.parse(\n readFileSync(new URL('../../package.json', import.meta.url), 'utf8'),\n ) as { name: string; version: string };\n updateNotifier({ pkg }).notify();\n } catch {\n // Offline, no config dir, malformed metadata — never fatal for the CLI.\n }\n}\n","/**\n * CLI command wiring (§13). Built with commander. Each command mirrors an MCP\n * tool or an operational task. Handlers are filled in across milestones M1–M7;\n * the command/option surface here is the final, stable shape.\n *\n * Every command supports `--json` for machine-readable output.\n */\nimport { Command, Option } from 'commander';\nimport { SERVER_NAME, VERSION } from '../core/constants';\nimport { SUPPORTED_AGENTS } from './installSkill';\n\n/**\n * Built from the installer's own list rather than typed out, so adding an agent\n * cannot leave `--help` advertising the old set. Safe to import eagerly:\n * installSkill pulls in node builtins only (the heavy prompt deps live in\n * ./install, which stays lazy).\n */\nconst AGENT_CHOICES = [...SUPPORTED_AGENTS, 'all'].join(' | ');\n\nexport function buildProgram(): Command {\n const program = new Command();\n\n program\n .name(SERVER_NAME)\n .description('lurq - a fresh, objectively-scored index of JS/TS packages for AI coding agents.')\n .version(VERSION, '-v, --version', 'output the lurq version')\n // Confine program-level flags to the slot before the subcommand name.\n // Without this, commander lets the program consume a `--version` written\n // *after* a subcommand, so `lurq usage pkg --version 24.14.0` printed the\n // lurq version and exited instead of running the command — shadowing the\n // per-command version options on `usage` and (operator plane) `oracle`.\n .enablePositionalOptions()\n .addHelpText(\n 'after',\n '\\nNew here? Run `lurq setup` once: it stores your API key and connects every\\n' +\n 'coding agent on this machine. Get a key at https://lurq.run/dashboard/keys\\n',\n );\n\n // Bare `npx lurqrun` (or a bare `lurq`) on an unconfigured machine runs setup.\n // That is the whole one-command install story: one thing to type, and the user\n // ends up with the command on their PATH, a stored key, and every agent wired.\n // Once a key exists, a bare `lurq` means \"what can this do?\" instead, so it\n // prints help rather than re-running a wizard nobody asked for.\n program.action(async () => {\n const { resolveApiKey } = await import('../core/userConfig');\n if (resolveApiKey()) {\n program.outputHelp();\n return;\n }\n const { runSetup } = await import('./install');\n await runSetup({});\n });\n\n // ── Setup ─────────────────────────────────────────────────────────────────\n // `install` and `login` are kept as aliases: `npx lurqrun install` is in\n // published docs, dashboard copy and people's notes, and silently breaking it\n // would be worse than carrying two extra words here.\n program\n .command('setup')\n .aliases(['install', 'login'])\n .description('one-time setup: store your API key, wire up your assistants and skills')\n .option('--api-key <key>', 'hosted API key (skips the prompt)')\n .option('--url <url>', 'hosted endpoint URL (defaults to the lurq service)')\n .option('--agent <agent>', AGENT_CHOICES)\n .option('--yes', 'non-interactive: use flags/env and detected agents without prompting')\n .option('--no-open', \"don't launch a browser (headless boxes, SSH, CI)\")\n .action(\n async (opts: {\n apiKey?: string;\n url?: string;\n agent?: string;\n yes?: boolean;\n open?: boolean;\n }) => {\n const { runSetup } = await import('./install');\n await runSetup({ ...opts, noOpen: opts.open === false });\n },\n );\n\n program\n .command('logout')\n .description('remove the stored API key from this machine')\n .action(async () => {\n const { clearUserConfig, userConfigPath } = await import('../core/userConfig');\n const path = userConfigPath();\n console.log(\n clearUserConfig()\n ? `Removed ${path}. Agent MCP configs still hold the key; re-run \\`lurq setup\\` to change them.`\n : 'No stored API key on this machine.',\n );\n });\n\n // Selection policy as a file in the repo: pull it, review changes in a PR,\n // push from CI. Pushing needs a key with the policy:write scope, which the key\n // `setup` stores never has.\n const policy = program\n .command('policy')\n .description('keep your selection policy in a file: pull it, review it, push it');\n\n policy\n .command('pull')\n .argument('[file]', 'write the policy here (default: stdout)')\n .description('download the policy your agents are held to')\n .option('--url <url>', 'hosted endpoint URL (defaults to the lurq service)')\n .option('--api-key <key>', 'hosted API key (defaults to $LURQ_API_KEY)')\n .action(async (file: string | undefined, opts: { url?: string; apiKey?: string }) => {\n const { runPolicyPull } = await import('./policy');\n await runPolicyPull(file, opts);\n });\n\n policy\n .command('push')\n .argument('<file>', 'policy JSON, as written by `lurq policy pull`')\n .description('replace the policy with this file (needs a policy:write key)')\n .option('--check', 'validate the file only; send nothing (for PR checks)')\n .option('--url <url>', 'hosted endpoint URL (defaults to the lurq service)')\n .option('--api-key <key>', 'hosted API key (defaults to $LURQ_API_KEY)')\n .action(\n async (file: string, opts: { check?: boolean; url?: string; apiKey?: string }) => {\n const { runPolicyPush } = await import('./policy');\n await runPolicyPush(file, opts);\n },\n );\n\n policy\n .command('history')\n .description('who changed the policy, from where, and what changed')\n .option('--json', 'output the changes as JSON')\n .option('--url <url>', 'hosted endpoint URL (defaults to the lurq service)')\n .option('--api-key <key>', 'hosted API key (defaults to $LURQ_API_KEY)')\n .action(async (opts: { json?: boolean; url?: string; apiKey?: string }) => {\n const { runPolicyHistory } = await import('./policy');\n await runPolicyHistory(opts);\n });\n\n policy\n .command('log')\n .description('packages the policy refused, or warned about, grouped by rule')\n .option('--days <n>', 'look back this many days, 1 to 365 (default 30)')\n .option('--json', 'output the log as JSON')\n .option('--url <url>', 'hosted endpoint URL (defaults to the lurq service)')\n .option('--api-key <key>', 'hosted API key (defaults to $LURQ_API_KEY)')\n .action(async (opts: { days?: string; json?: boolean; url?: string; apiKey?: string }) => {\n const { runPolicyLog } = await import('./policy');\n await runPolicyLog(opts);\n });\n\n // Answers \"can lurq do X\" without making anyone read `--help` twice. Local\n // and instant: the catalog ships in the binary, so this works before setup and\n // offline.\n program\n .command('can')\n .argument('[query...]', 'what you are trying to do, in plain words')\n .description('find the lurq capability for what you are trying to do')\n .option('--json', 'output matches as JSON')\n .action(async (query: string[], opts: { json?: boolean }) => {\n const { runCan } = await import('./commands');\n runCan(query.join(' '), opts);\n });\n\n // ── Asking about packages ─────────────────────────────────────────────────\n // Help lists commands in registration order, so the ones a user actually runs\n // come first and the server/scripting plumbing sits at the bottom.\n program\n .command('evaluate')\n .argument('<package>', 'npm package name')\n .description('full evidence read for one package (scores, signals, usage guide)')\n .option('--json', 'output JSON instead of a table')\n .action(async (pkg: string, opts: { json?: boolean }) => {\n const { runEvaluate } = await import('./commands');\n await runEvaluate(pkg, opts);\n });\n\n program\n .command('compare')\n .argument('<packages...>', '2–5 npm package names')\n .description('side-by-side comparison of packages, ranked by health')\n .option('--json', 'output JSON instead of a table')\n .action(async (pkgs: string[], opts: { json?: boolean }) => {\n const { runCompare } = await import('./commands');\n await runCompare(pkgs, opts);\n });\n\n program\n .command('verify')\n .argument('<package>', 'npm package name')\n .description('safety check: is this package real, healthy, and not risky?')\n .option('--json', 'output JSON instead of a table')\n .action(async (pkg: string, opts: { json?: boolean }) => {\n const { runVerify } = await import('./commands');\n await runVerify(pkg, opts);\n });\n\n program\n .command('usage')\n .argument('<package>', 'npm package name')\n .description(\n 'version-exact API surface (exported symbols/signatures) + drift from a known version',\n )\n .option('--target <v>', 'target version (defaults to latest)')\n // Historical spelling of --target, kept working but out of the help text so\n // only one spelling is advertised.\n .addOption(new Option('--version <v>', 'alias for --target').hideHelp())\n .option('--known <v>', 'a version you know; shows the API delta to the target')\n .option('--json', 'output JSON')\n .action(\n async (\n pkg: string,\n opts: { target?: string; version?: string; known?: string; json?: boolean },\n ) => {\n const { runUsage } = await import('./commands');\n await runUsage(pkg, {\n version: opts.target ?? opts.version,\n known: opts.known,\n json: opts.json,\n });\n },\n );\n\n program\n .command('versions')\n .argument('<package>', 'npm package name')\n .description('show the stored version timeline for a package')\n .option('--json', 'output JSON instead of a table')\n .option('-n, --limit <n>', 'how many versions to show (default 30)')\n .action(async (pkg: string, opts: { json?: boolean; limit?: string }) => {\n const { runVersions } = await import('./commands');\n await runVersions(pkg, opts);\n });\n\n program\n .command('compat')\n .argument('<packages...>', 'npm package names to check together')\n .description(\n 'check whether a set of packages forms a coherent stack (peer/engine + recorded evidence)',\n )\n // The checker has always taken exact versions (CheckCompatOptions.versions);\n // there was just no way to say so from the CLI. Arguments are bare names, so\n // `next@15` would look up a package called \"next@15\" and come back unknown.\n .option('--pin <name=version...>', 'evaluate an exact version, e.g. --pin next=15')\n .option('--json', 'output JSON')\n .action(async (pkgs: string[], opts: { json?: boolean; pin?: string[] }) => {\n const { runCompat } = await import('./commands');\n await runCompat(pkgs, opts);\n });\n\n // ── Upgrade autopilot ─────────────────────────────────────────────────────\n // These two run where the code is (a laptop or a CI runner), not against a\n // local database. `upgrade-plan` asks the index what changed between versions;\n // `check-upgrade` narrows that to what this codebase references, using nothing\n // but the two npm tarballs — no API key, no test suite, no network to us.\n\n program\n .command('upgrade-plan')\n .argument('[dir]', 'project directory (default: current)', '.')\n .description('what is behind in this project, and what each upgrade removes from its API')\n .option('--json', 'output the plan as JSON (feed to `check-upgrade --plan`)')\n .option('--url <url>', 'hosted endpoint URL (defaults to the lurq service)')\n .option('--api-key <key>', 'hosted API key (defaults to $LURQ_API_KEY)')\n .option('--repo <owner/name>', \"apply this repo's policy (defaults to $GITHUB_REPOSITORY)\")\n .action(\n async (\n dir: string,\n opts: { json?: boolean; url?: string; apiKey?: string; repo?: string },\n ) => {\n const { buildUpgradePlan, formatUpgradePlan } = await import('./upgradePlan');\n const plan = await buildUpgradePlan(dir, {\n url: opts.url,\n apiKey: opts.apiKey,\n repo: opts.repo,\n });\n console.log(opts.json ? JSON.stringify(plan, null, 2) : formatUpgradePlan(plan));\n },\n );\n\n program\n .command('check-upgrade')\n .argument('[dir]', 'project directory to scan (default: current)', '.')\n .description('do these upgrades remove symbols your code actually references?')\n .option('--plan <file>', 'targets from `upgrade-plan --json`')\n .option('--upgrade <spec...>', 'pkg@from..to (repeatable), e.g. commander@11.1.0..12.1.0')\n .option('--json', 'output the report as JSON')\n .option('--exit-code', 'exit 1 when the report is not safe (for CI)')\n // Opt-in, and never load-bearing: the check's whole point is that it needs\n // no key and no network to us, so this only adds a dashboard write on top.\n .option('--report', 'send the result to your lurq dashboard (CI; needs an API key)')\n .option('--url <url>', 'hosted endpoint URL (defaults to the lurq service)')\n .option('--api-key <key>', 'hosted API key (defaults to $LURQ_API_KEY)')\n .action(\n async (\n dir: string,\n opts: {\n plan?: string;\n upgrade?: string[];\n json?: boolean;\n exitCode?: boolean;\n report?: boolean;\n url?: string;\n apiKey?: string;\n },\n ) => {\n const { runCheckUpgrade } = await import('./checkUpgrade');\n await runCheckUpgrade(dir, opts);\n },\n );\n\n // The same diff, pointed at the author instead of the consumer: does the\n // version about to be published match what this release actually did to the\n // API? Needs no key and no network to us — just the registry tarball.\n program\n .command('check-release')\n .argument('[dir]', 'package directory (default: current)', '.')\n .description('is the version you are about to publish honest about what changed?')\n .option('--against <version>', 'compare with this published version (default: latest)')\n .option('--json', 'output the check as JSON')\n .option('--exit-code', 'exit 1 when the bump is understated (for CI / prepublish)')\n .action(async (dir: string, opts: { against?: string; json?: boolean; exitCode?: boolean }) => {\n const { checkRelease, formatReleaseCheck } = await import('../surface/release');\n const check = await checkRelease(dir, { against: opts.against });\n console.log(opts.json ? JSON.stringify(check, null, 2) : formatReleaseCheck(check));\n if (opts.exitCode && check.verdict !== 'ok') process.exitCode = 1;\n });\n\n // The same question as check-upgrade, asked by the other party: not \"will this\n // dependency break me\" but \"will this change break the people calling me\".\n // Reads two git revisions of an OpenAPI document — nothing leaves the machine.\n program\n .command('check-api')\n .argument('[spec]', 'OpenAPI document (default: the first one found)')\n .description('does this change break the callers of your own API?')\n .option('--against <rev>', 'git revision to compare with (default: HEAD)')\n .option('-C, --dir <dir>', 'repository directory (default: current)', '.')\n .option('--json', 'output the check as JSON')\n .option('--exit-code', 'exit 1 on a breaking change (for CI)')\n .action(\n async (\n spec: string | undefined,\n opts: { against?: string; dir?: string; json?: boolean; exitCode?: boolean },\n ) => {\n const { runApiCheck } = await import('../api/check');\n const { formatApiCheck } = await import('../api/diff');\n const check = await runApiCheck(opts.dir ?? '.', { spec, against: opts.against });\n console.log(\n opts.json\n ? JSON.stringify(check, null, 2)\n : formatApiCheck(check, `api check (vs ${check.against})`),\n );\n if (opts.exitCode && check.verdict !== 'ok') process.exitCode = 1;\n },\n );\n\n // ── Scoring model ─────────────────────────────────────────────────────────\n program\n .command('audit')\n .argument('[dir]', 'project directory (defaults to the current one)')\n .description('what this project depends on, and what is outdated, vulnerable or drifting')\n .option('--project-only', 'ignore user-level agent configs; read only files in the project')\n .option(\n '--probe',\n 'probe your MCP servers now instead of waiting for the worker (needs DATABASE_URL)',\n )\n .option('--probe-budget <seconds>', 'wall-clock ceiling for probing (default 90)')\n .option('--json', 'output JSON instead of a table')\n .action(\n async (\n dir: string | undefined,\n opts: { json?: boolean; projectOnly?: boolean; probe?: boolean; probeBudget?: string },\n ) => {\n const { runAudit } = await import('./commands');\n await runAudit(dir, opts);\n },\n );\n\n program\n .command('mcp-stack')\n .argument('[dir]', 'project directory (defaults to the current one)')\n .description('do your configured MCP servers coexist? checks for tool-name collisions')\n .option('--project-only', 'read only config files in the project')\n .option('--json', 'output JSON instead of a table')\n .action(async (dir: string | undefined, opts: { json?: boolean; projectOnly?: boolean }) => {\n const { runMcpStack } = await import('./commands');\n await runMcpStack(dir, opts);\n });\n\n program\n .command('mcp-surface')\n .argument('<server>', 'npm package name of the MCP server')\n .description(\"an MCP server's real tool contract: params and behaviour annotations\")\n .option('--version <v>', 'exact version (defaults to the latest probed)')\n .option('--json', 'output JSON instead of a table')\n .action(async (server: string, opts: { version?: string; json?: boolean }) => {\n const { runMcpSurface } = await import('./commands');\n await runMcpSurface(server, opts);\n });\n\n program\n .command('mcp-drift')\n .argument('<server>', 'npm package name of the MCP server')\n .description('what an MCP server changed between two versions (incl. silent + privilege drift)')\n .requiredOption('--from <v>', 'version you are on')\n .requiredOption('--to <v>', 'version you are moving to')\n .option('--json', 'output JSON instead of a table')\n .action(async (server: string, opts: { from: string; to: string; json?: boolean }) => {\n const { runMcpDrift } = await import('./commands');\n await runMcpDrift(server, opts);\n });\n\n program\n .command('weights')\n .description('show and explain the scoring weight model (health, quality, composite λ)')\n .option('--json', 'output the weight model as JSON')\n .action(async (opts: { json?: boolean }) => {\n const { runWeights } = await import('./commands');\n runWeights(opts);\n });\n\n program\n .command('edit-weights')\n .description('override, reset, or explain the scoring weights (layered over defaults)')\n .option(\n '--set <pair>',\n 'override key=value, e.g. composite.lambda=0.5 (repeatable)',\n (v: string, acc: string[]) => acc.concat(v),\n [],\n )\n .option('--reset', 'remove all overrides and restore defaults')\n .option('--explain <component>', 'explain a component (e.g. adoption, quality, lambda)')\n .option('--project', 'write to project-local .lurq/weights.json instead of the user config')\n .action(\n async (opts: { set?: string[]; reset?: boolean; explain?: string; project?: boolean }) => {\n const { runEditWeights } = await import('./commands');\n await runEditWeights(opts);\n },\n );\n\n // ── Plumbing ──────────────────────────────────────────────────────────────\n // Nobody types these to answer a question about a package: `install-skill` is\n // the scriptable half of setup, and the two servers are what a host runs.\n program\n .command('install-skill')\n .description('register lurq as an MCP server in supported AI assistants (scriptable)')\n .option('--agent <agent>', AGENT_CHOICES, 'claude-code')\n .option('--api-key <key>', 'hosted API key (remote install; default mode)')\n .option('--url <url>', 'hosted endpoint URL (defaults to the lurq service)')\n .option('--local', 'self-host: write a local stdio entry using your own DATABASE_URL')\n .action(async (opts: { agent?: string; apiKey?: string; url?: string; local?: boolean }) => {\n const { runInstallSkill } = await import('./installSkill');\n await runInstallSkill(opts);\n });\n\n program\n .command('serve')\n .description('start the MCP server over stdio (for agent integration)')\n .action(async () => {\n const { startMcpServer } = await import('../mcp/server');\n await startMcpServer();\n });\n\n program\n .command('serve-http')\n .description('start the hosted MCP server over HTTP with API-key auth')\n .option('--port <n>', 'port to listen on (default: $PORT or 8080)', (v) => parseInt(v, 10))\n .action(async (opts: { port?: number }) => {\n const { startHttpServer } = await import('../mcp/http');\n await startHttpServer({ port: opts.port });\n });\n\n return program;\n}\n","/**\n * Pre-launch access gate.\n *\n * While lurq is in private preview, anyone may `npm install lurqrun`, but only\n * the owner may run commands — everyone else gets a branded placeholder. The\n * owner proves identity by exporting `LURQ_OWNER_KEY` in their shell to the\n * secret whose SHA-256 is baked into `OWNER_HASH` below. The published bundle\n * carries only the hash, never the secret, so inspecting the source reveals\n * nothing usable.\n *\n * To lift the gate at public launch, flip `PRE_LAUNCH` to false (or delete the\n * `enforceGate()` call in bin/lurq.ts). The owner bypass keeps working either\n * way, so nothing else needs to change.\n */\nimport { createHash, timingSafeEqual } from 'node:crypto';\n\nimport { PACKAGE_NAME } from './constants';\n\n/** Master switch. Set to false to open lurq to everyone at launch. */\nconst PRE_LAUNCH = false;\n\n/**\n * SHA-256 of the owner secret. Regenerate after choosing a new secret with:\n * node -e \"console.log(require('node:crypto').createHash('sha256').update(process.argv[1]).digest('hex'))\" <secret>\n * and paste the result here. Keep the plaintext only in your shell env.\n */\nconst OWNER_HASH = '9675c37e56783e747e4a89ee3919d95d1364f2e5dd0f14501b0f878f8cc3682b';\n\n/**\n * Top-level commands that bypass the gate even for non-owners:\n * - `-v/--version/-h/--help/help` — harmless, expected by npm users.\n * - `serve`/`serve-http` — the MCP transports. The gate must NEVER write to the\n * stdio JSON-RPC channel (`serve`), and the hosted server must boot without\n * depending on the owner key (`serve-http`).\n * - `sync`/`discover`/`rescore`/`db`/`keys` — operator/infra commands that all\n * require DATABASE_URL, which a public installer never has. Gating them adds no\n * protection (a keyless user can't run them anyway) while risking the owner's\n * own deploy. The gate's real job is the user-facing commands (recommend,\n * evaluate, compare, verify, plan, install, install-skill, weights).\n */\nconst ALLOWED = new Set([\n '-v', '--version', '-h', '--help', 'help',\n 'serve', 'serve-http',\n 'sync', 'discover', 'rescore', 'db', 'keys',\n]);\n\n/** True when the caller has proven they are the owner via `LURQ_OWNER_KEY`. */\nexport function isOwner(): boolean {\n const key = process.env.LURQ_OWNER_KEY;\n if (!key) return false;\n const got = createHash('sha256').update(key).digest();\n const want = Buffer.from(OWNER_HASH, 'hex');\n // Equal-length buffers (both 32 bytes); timingSafeEqual guards against a\n // timing oracle on the comparison.\n return got.length === want.length && timingSafeEqual(got, want);\n}\n\n/**\n * Enforce the gate before any command runs. Returns normally when the caller is\n * the owner, the gate is lifted, or the invocation is a top-level help/version\n * query. Otherwise prints the placeholder and exits cleanly (code 0 — installing\n * early is not an error).\n */\nexport function enforceGate(argv: string[]): void {\n if (!PRE_LAUNCH || isOwner()) return;\n if (argv[0] && ALLOWED.has(argv[0])) return;\n\n printPlaceholder();\n process.exit(0);\n}\n\nfunction printPlaceholder(): void {\n const tty = process.stdout.isTTY;\n const bold = (s: string) => (tty ? `\\x1b[1m${s}\\x1b[0m` : s);\n const dim = (s: string) => (tty ? `\\x1b[2m${s}\\x1b[0m` : s);\n const accent = (s: string) => (tty ? `\\x1b[38;5;213m${s}\\x1b[0m` : s);\n\n process.stdout.write(\n [\n '',\n ` ${bold('lurq')} ${dim('evidence-scored package index for AI coding agents')}`,\n '',\n ` ${accent('◆ private preview')}`,\n '',\n ` lurq isn't open to the public yet, thanks for installing early.`,\n ` Join the waitlist and watch the demo at ${bold('https://lurq.run')}`,\n '',\n dim(` You'll be able to connect Claude Code, Cursor, and other agents`),\n dim(` the moment we open the gate.`),\n '',\n dim(` (${PACKAGE_NAME} is installed and ready, no further action needed.)`),\n '',\n '',\n ].join('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,CAAC,YAAY;AACzD,QAAM,SAAS,CAAC,MAAe,MAAM,iBAAiB,CAAC,YAAY;AAEnE,UAAQ,OAAO;AAAA,IACb;AAAA,MACE;AAAA,MACA,KAAKD,MAAK,MAAM,CAAC,IAAIC,KAAI,oDAAoD,CAAC;AAAA,MAC9E;AAAA,MACA,KAAK,OAAO,wBAAmB,CAAC;AAAA,MAChC;AAAA,MACA;AAAA,MACA,6CAA6CD,MAAK,kBAAkB,CAAC;AAAA,MACrE;AAAA,MACAC,KAAI,mEAAmE;AAAA,MACvEA,KAAI,gCAAgC;AAAA,MACpC;AAAA,MACAA,KAAI,MAAM,YAAY,qDAAqD;AAAA,MAC3E;AAAA,MACA;AAAA,IACF,EAAE,KAAK,IAAI;AAAA,EACb;AACF;;;AFrFA;AAEA,QAAQ;AAIR,YAAY,QAAQ,KAAK,MAAM,CAAC,CAAC;AAEjC,eAAe;AAGf,sBAAsB,MAAM,aAAa,EAAE,WAAW,QAAQ,IAAI,CAAC,EAChE,MAAM,CAAC,QAAQ;AACd,SAAO,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAC7D,UAAQ,KAAK,CAAC;AAChB,CAAC;AAUH,SAAS,iBAAuB;AAC9B,QAAM,OAAO,QAAQ,KAAK,MAAM,CAAC;AACjC,QAAM,QACJ,KAAK,CAAC,MAAM,WAAW,KAAK,CAAC,MAAM,gBAAgB,KAAK,SAAS,QAAQ;AAC3E,MAAI,MAAO;AAEX,MAAI;AACF,UAAM,MAAM,KAAK;AAAA,MACfC,eAAa,IAAI,IAAI,sBAAsB,YAAY,GAAG,GAAG,MAAM;AAAA,IACrE;AACA,mBAAe,EAAE,IAAI,CAAC,EAAE,OAAO;AAAA,EACjC,QAAQ;AAAA,EAER;AACF;","names":["fileURLToPath","existsSync","homedir","dirname","join","path","existsSync","mkdirSync","readFileSync","renameSync","rmSync","writeFileSync","homedir","dirname","join","path","text","entry","headers","sep","name","apiKey","headers","headers","timer","path","detail","text","resolve","finish","timer","apiKey","reason","keyViaBrowser","check","name","readFileSync","writeFileSync","text","empty","change","width","missing","name","table","sql","sql","name","cached","and","eq","inArray","sql","packages","eq","sql","entry","join","resolve","cacheDir","text","writeFile","existsSync","homedir","dirname","join","entry","headers","cached","attempt","timer","text","date","resolve","name","json","json","date","name","HOST","json","HOST","name","json","HOST","json","name","HOST","packages","name","cached","timer","resolve","and","eq","isNotNull","isNull","sql","missing","path","ts","text","name","entry","symbols","walk","name","desc","eq","name","init_successors","and","desc","eq","inArray","sql","name","init_successors","HOST","name","text","apiKey","name","text","existsSync","mkdirSync","readFileSync","rmSync","writeFileSync","dirname","active","entry","eq","path","date","createHash","tokenize","text","str","dim","apiKey","and","desc","eq","init_types","and","eq","sql","name","installationId","fullNames","init_types","list","name","URL","HOST","inFlight","resolve","active","name","and","eq","inArray","sql","semver","name","list","empty","enqueueIngest","entry","init_types","semver","name","init_alerts","init_alerts","and","eq","isNotNull","sql","name","median","init_alerts","and","eq","inArray","isNotNull","sql","reason","list","rank","init_types","and","desc","eq","gte","inArray","sql","count","daysSince","date","monthsSince","init_types","worst","name","createHash","sql","DAY_MS","date","SEVERITY_RANK","cached","reason","evaluated","pending","name","missing","typo","init_successors","and","eq","inArray","list","text","name","createHash","and","eq","inArray","pending","name","reason","apiKey","name","eq","init_types","and","eq","isNull","createHash","init_types","and","desc","eq","isNotNull","isNull","sql","init_types","eq","change","backoff","flush","name","resolve","timer","init_watch","init_types","execFile","mkdtemp","rm","writeFile","tmpdir","join","promisify","init_types","packages","condense","ERROR_MAX","INSTALL_TIMEOUT_MS","SMOKE_TIMEOUT_MS","toSpec","init_types","packages","E2BSandbox","init_types","init_sandbox","packages","name","pending","init_compat","init_types","path","init_diff","init_types","reason","createHash","drift","init_diff","reason","getJson","timer","missing","text","existsSync","readFileSync","dirname","join","post","capture","extractSurface","readFileSync","ts","name","MAX_FILES","text","path","symbols","entry","attempt","init_extract","execFile","createHash","mkdir","mkdtemp","readFile","rm","writeFile","tmpdir","join","promisify","name","execFileP","extractSurface","surface_exports","pending","missing","init_surface","extractOnce","inFlight","MAX_INFLIGHT","extractAndStore","createHash","and","desc","eq","rows","cached","firstTouchSurface","firstTouchPair","missing","init_types","init_diff","createHash","ckey","cached","missing","MISS","drift","attempt","truncate","observations","text","missing","reason","EXTRACTOR_VERSION","name","enqueueIngest","pending","VERSION_LOOKBACK","MAX_ATTEMPTS","init_mcp","existsSync","readFileSync","homedir","join","relative","path","name","alias","endpoint","home","entry","list","byName","rootManifest","packages","inArray","semver","loadIndexed","NAME_CHUNK","name","missing","enqueueIngest","SEVERITY_RANK","worst","init_types","semver","callTool","active","invalidateCache","text","path","readFileSync","handlePlan","writeFileSync","tmpdir","join","renderPlanHtml","watchNpmChanges","verifyPackageInSandbox","handleUsage","res","name","handleCompat","verifyCompatibility","createDb","extractAndStoreMcp","hasStoredSurface","LocalSandbox","collectInventory","SEVERITY_RANK","worstSeverity","checkMcpStack","isCrowded","installationId","cached","path","installationId","MAX_PAGES","PAGE_SIZE","path","json","entry","name","init_types","readFileSync","readdirSync","statSync","join","relative","MAX_DEPTH","walk","entry","name","change","detail","readdirSync","readFileSync","statSync","join","relative","ts","walk","SKIP_DIRS","list","text","lineOf","name","symbols","symbols","list","z","init_diff","init_types","readFileSync","name","path","text","buildRunReports","runContextFromEnv","reportUpgradeRuns","scanReferences","checkUpgrade","formatUpgradeReport","empty","semver","name","extractSurface","list","init_diff","reason","semver","LIST_CAP","check","init_diff","detail","parseYaml","list","name","empty","path","execFile","existsSync","readFileSync","relative","resolve","promisify","CANDIDATES","execFileP","init_check","init_diff","and","desc","eq","gte","sql","properties","HOST","z","semver","checkMcpStack","createHash","randomBytes","and","desc","eq","isNull","entry","cached","and","eq","inArray","monthsSince","date","NAME_CHUNK","daysSince","name","z","and","desc","eq","gte","isNull","lte","sql","clientPromise","semver","path","MAX_HOPS","inconclusive","path","drift","and","eq","sql","str","count","severity","MAX_FILES","name","init_types","and","desc","eq","gte","sql","name","getJson","TIMEOUT_MS","repos","manifest","drift","init_types","timingSafeEqual","entry","name","name","json","packages","installationId","installCommand","empty","drift","rank","index","name","text","createHash","timingSafeEqual","path","cached","installationId","name","drift","server","init_http","readFileSync","resolveApiKey","runSetup","clearUserConfig","userConfigPath","path","runPolicyPull","runPolicyPush","runPolicyHistory","runPolicyLog","runCan","runEvaluate","runCompare","runVerify","runUsage","runVersions","runCompat","buildUpgradePlan","formatUpgradePlan","runCheckUpgrade","checkRelease","formatReleaseCheck","check","runApiCheck","formatApiCheck","runAudit","runMcpStack","runMcpSurface","runMcpDrift","runWeights","runEditWeights","runInstallSkill","startMcpServer","startHttpServer","createHash","timingSafeEqual","bold","dim","readFileSync"]}
|