ctxtop 0.0.0-stage → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (262) hide show
  1. package/.antigravity-plugin/plugin.json +36 -0
  2. package/.claude-plugin/plugin.json +18 -0
  3. package/CHECKSUMS.sha256 +166 -0
  4. package/LICENSE +27 -0
  5. package/README.md +350 -2
  6. package/SECURITY.md +22 -0
  7. package/agents/ah-flash-scout.md +25 -0
  8. package/assets/advanced_view_loaded_420px.png +0 -0
  9. package/assets/hero-demo.svg +188 -0
  10. package/assets/logo.svg +19 -0
  11. package/assets/simple_view_lean_420px.png +0 -0
  12. package/assets/simple_view_loaded_420px.png +0 -0
  13. package/assets/social-preview.svg +72 -0
  14. package/assets/zone_c_step3_shield_full.png +0 -0
  15. package/bin/ah-statusline.mjs +175 -0
  16. package/bin/cli.mjs +3 -0
  17. package/bin/ctxtop.mjs +1799 -0
  18. package/commands/cost-radar.md +11 -0
  19. package/commands/evolve.md +10 -0
  20. package/commands/handoff.md +10 -0
  21. package/commands/horizon.md +10 -0
  22. package/commands/inspect.md +10 -0
  23. package/commands/precheck.md +10 -0
  24. package/config/default_flightcheck.json +133 -0
  25. package/config/modelCatalog.json +785 -0
  26. package/config/platformQuirks.json +19 -0
  27. package/hooks/handlers/compact-lifecycle.mjs +577 -0
  28. package/hooks/handlers/config-change.mjs +402 -0
  29. package/hooks/handlers/hookIo.mjs +311 -0
  30. package/hooks/handlers/hookIpcClient.mjs +83 -0
  31. package/hooks/handlers/post-model-switch.mjs +111 -0
  32. package/hooks/handlers/post-tool-use.mjs +366 -0
  33. package/hooks/handlers/pre-model-switch.mjs +1048 -0
  34. package/hooks/handlers/pre-tool-use.mjs +632 -0
  35. package/hooks/handlers/stop-gate.mjs +526 -0
  36. package/hooks/handlers/user-prompt-submit.mjs +367 -0
  37. package/hooks/hooks.json +131 -0
  38. package/hooks/post_invocation.mjs +13 -0
  39. package/hooks/post_tool_use.mjs +25 -0
  40. package/hooks/pre_invocation.mjs +14 -0
  41. package/hooks/pre_tool_use.mjs +97 -0
  42. package/hooks/register.js +726 -0
  43. package/hooks/session_start.mjs +24 -0
  44. package/hooks/stop.mjs +23 -0
  45. package/hooks.json +56 -0
  46. package/package.json +110 -4
  47. package/packages/antigravity/package.json +14 -0
  48. package/packages/antigravity/src/index.mjs +1 -0
  49. package/packages/claude-code/package.json +14 -0
  50. package/packages/claude-code/src/index.mjs +2 -0
  51. package/packages/core/package.json +14 -0
  52. package/packages/core/src/index.mjs +1 -0
  53. package/packages/engine-node/package.json +14 -0
  54. package/packages/engine-node/src/index.mjs +1 -0
  55. package/packages/mcp/package.json +17 -0
  56. package/packages/mcp/src/server.mjs +396 -0
  57. package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
  58. package/packages/pro/README-SIGNING.md +30 -0
  59. package/packages/pro/package.json +16 -0
  60. package/packages/pro/src/index.mjs +3 -0
  61. package/packages/pro/src/team_finops_pack.mjs +241 -0
  62. package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
  63. package/plugin.json +36 -0
  64. package/rules/AGENTS.md +10 -0
  65. package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
  66. package/sidecars/horizon-daemon/server.mjs +2038 -0
  67. package/sidecars/horizon-daemon/sidecar.json +19 -0
  68. package/skills/cost-radar/SKILL.md +21 -0
  69. package/skills/evolve/SKILL.md +21 -0
  70. package/skills/handoff/SKILL.md +50 -0
  71. package/skills/horizon/SKILL.md +17 -0
  72. package/skills/inspect/SKILL.md +18 -0
  73. package/skills/precheck/SKILL.md +44 -0
  74. package/src/adapters/antigravity/index.mjs +109 -0
  75. package/src/adapters/claude-code/index.mjs +194 -0
  76. package/src/cli/cost_radar.mjs +70 -0
  77. package/src/cli/doctor.mjs +351 -0
  78. package/src/cli/horizon_hud.mjs +888 -0
  79. package/src/cli/init.mjs +425 -0
  80. package/src/cli/postmortem.mjs +515 -0
  81. package/src/coach/cacheGravityRouter.mjs +12 -0
  82. package/src/config/modelCatalog.json +704 -0
  83. package/src/config/platformQuirks.json +19 -0
  84. package/src/core/action_queue.mjs +264 -0
  85. package/src/core/ag_bridge.mjs +346 -0
  86. package/src/core/atomic_io.mjs +124 -0
  87. package/src/core/baseline.mjs +607 -0
  88. package/src/core/blindspot_sensors.mjs +399 -0
  89. package/src/core/bucket_b_runtime.mjs +1200 -0
  90. package/src/core/classifier.mjs +1757 -0
  91. package/src/core/coach/circuit_breakers.mjs +650 -0
  92. package/src/core/coach/contradiction_auditor.mjs +239 -0
  93. package/src/core/coach/effort_advisor.mjs +143 -0
  94. package/src/core/coach/handoff_hydrator.mjs +483 -0
  95. package/src/core/coach/progressive_checkpointer.mjs +551 -0
  96. package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
  97. package/src/core/coach/reflector_queue.mjs +505 -0
  98. package/src/core/coach/saved_quota_ledger.mjs +615 -0
  99. package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
  100. package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
  101. package/src/core/coach/task_quota_router.mjs +955 -0
  102. package/src/core/coach/turn_zero_gate.mjs +574 -0
  103. package/src/core/compaction_coach.mjs +1126 -0
  104. package/src/core/config.mjs +214 -0
  105. package/src/core/constants.mjs +1987 -0
  106. package/src/core/detectors_det01_to_16.mjs +1523 -0
  107. package/src/core/doc_indexer.mjs +338 -0
  108. package/src/core/episodic_memory.mjs +135 -0
  109. package/src/core/fts5_output_compressor.mjs +359 -0
  110. package/src/core/git_ledger.mjs +189 -0
  111. package/src/core/handoff_audit.mjs +558 -0
  112. package/src/core/history.mjs +221 -0
  113. package/src/core/hook_diagnostics.mjs +158 -0
  114. package/src/core/horizon_classifier.mjs +326 -0
  115. package/src/core/horizon_config.mjs +802 -0
  116. package/src/core/host_watchdog.mjs +200 -0
  117. package/src/core/layer5_hygiene.mjs +1084 -0
  118. package/src/core/log_resolver.mjs +231 -0
  119. package/src/core/mcp_auditor.mjs +138 -0
  120. package/src/core/micro_skills_store.mjs +91 -0
  121. package/src/core/offenders.mjs +161 -0
  122. package/src/core/parser.mjs +1997 -0
  123. package/src/core/path_canonicalizer.mjs +73 -0
  124. package/src/core/paths.mjs +311 -0
  125. package/src/core/prefix_cache_shield.mjs +386 -0
  126. package/src/core/pro_license.mjs +385 -0
  127. package/src/core/prompt_rubric.mjs +518 -0
  128. package/src/core/pruner.mjs +433 -0
  129. package/src/core/quota.mjs +1860 -0
  130. package/src/core/rsi_instinct_engine.mjs +1197 -0
  131. package/src/core/rsl_clash_auditor.mjs +423 -0
  132. package/src/core/rsl_distiller.mjs +372 -0
  133. package/src/core/rsl_ledger.mjs +969 -0
  134. package/src/core/rsl_triage.mjs +909 -0
  135. package/src/core/sanitizer.mjs +121 -0
  136. package/src/core/session_auditor.mjs +658 -0
  137. package/src/core/session_forensics.mjs +303 -0
  138. package/src/core/session_timeline.mjs +358 -0
  139. package/src/core/settings.mjs +99 -0
  140. package/src/core/shared/detectors.mjs +1342 -0
  141. package/src/core/shared/fnv1a64.mjs +85 -0
  142. package/src/core/shared/handoff_schema.mjs +123 -0
  143. package/src/core/shared/index.mjs +5 -0
  144. package/src/core/shared/ipi_sanitizer.mjs +165 -0
  145. package/src/core/shared/micro_skills.mjs +1 -0
  146. package/src/core/shared/plugin_validator.mjs +202 -0
  147. package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
  148. package/src/core/shield_manager.mjs +1417 -0
  149. package/src/core/sidecar_store.mjs +302 -0
  150. package/src/core/sprint_metrics.mjs +366 -0
  151. package/src/core/sqlite_client.mjs +283 -0
  152. package/src/core/storage_doctor.mjs +358 -0
  153. package/src/core/subagents.mjs +609 -0
  154. package/src/core/swarm_topology.mjs +360 -0
  155. package/src/core/task_quota_router.mjs +1656 -0
  156. package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
  157. package/src/core/telemetry/scope_lock_registry.mjs +578 -0
  158. package/src/core/telemetry/shadow_file_detector.mjs +291 -0
  159. package/src/core/telemetry/trajectory_watcher.mjs +259 -0
  160. package/src/core/timeline_svg.mjs +236 -0
  161. package/src/core/tool_surgeon.mjs +305 -0
  162. package/src/core/trajectory_stitcher.mjs +645 -0
  163. package/src/core/u_shaped_optimizer.mjs +789 -0
  164. package/src/core/wal_hygiene.mjs +233 -0
  165. package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
  166. package/src/core-isomorphic/catalog/index.mjs +1 -0
  167. package/src/core-isomorphic/coach/cacheGravityRouter.mjs +1547 -0
  168. package/src/core-isomorphic/coach/microSkills.mjs +1 -0
  169. package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
  170. package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
  171. package/src/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
  172. package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
  173. package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +305 -0
  174. package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
  175. package/src/core-isomorphic/coach/ttlWatchdog.mjs +464 -0
  176. package/src/core-isomorphic/config/anthropicModelCatalog.json +606 -0
  177. package/src/core-isomorphic/config/catalogLoader.mjs +1268 -0
  178. package/src/core-isomorphic/config/horizonConfig.mjs +1055 -0
  179. package/src/core-isomorphic/control/callTree.mjs +338 -0
  180. package/src/core-isomorphic/control/coachLatches.mjs +126 -0
  181. package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
  182. package/src/core-isomorphic/control/index.mjs +49 -0
  183. package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
  184. package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
  185. package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
  186. package/src/core-isomorphic/diagnostics/index.mjs +9 -0
  187. package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
  188. package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +888 -0
  189. package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
  190. package/src/core-isomorphic/economics/cacheGravity.mjs +369 -0
  191. package/src/core-isomorphic/economics/cliffBreaker.mjs +256 -0
  192. package/src/core-isomorphic/economics/driftLatency.mjs +433 -0
  193. package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
  194. package/src/core-isomorphic/economics/index.mjs +47 -0
  195. package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
  196. package/src/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
  197. package/src/core-isomorphic/guards/bucketBGamma.mjs +442 -0
  198. package/src/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
  199. package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
  200. package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1184 -0
  201. package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +572 -0
  202. package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +913 -0
  203. package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
  204. package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +317 -0
  205. package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
  206. package/src/core-isomorphic/index.js +27 -0
  207. package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
  208. package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
  209. package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
  210. package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
  211. package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1156 -0
  212. package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
  213. package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
  214. package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
  215. package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1237 -0
  216. package/src/core-isomorphic/ui/modViews.mjs +1504 -0
  217. package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
  218. package/src/core-isomorphic/ustf/index.mjs +7 -0
  219. package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
  220. package/src/core-isomorphic/ustf/schema.mjs +186 -0
  221. package/src/core-isomorphic/utils/runtime.mjs +962 -0
  222. package/src/demo/synthetic_states.mjs +661 -0
  223. package/src/diagnostics/bugReportGenerator.mjs +253 -0
  224. package/src/diagnostics/claudeHookCapabilities.mjs +396 -0
  225. package/src/diagnostics/doctorEngine.mjs +295 -0
  226. package/src/engine-node/db/index.mjs +58 -0
  227. package/src/engine-node/db/jsonl_fallback.mjs +184 -0
  228. package/src/engine-node/db/probe.mjs +342 -0
  229. package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
  230. package/src/engine-node/index.mjs +12 -0
  231. package/src/engine-node/ipc/client.mjs +447 -0
  232. package/src/engine-node/ipc/index.mjs +22 -0
  233. package/src/engine-node/ipc/protocol.mjs +177 -0
  234. package/src/engine-node/ipc/server.mjs +445 -0
  235. package/src/engine-node/offloader/index.mjs +6 -0
  236. package/src/engine-node/offloader/tool_offloader.mjs +241 -0
  237. package/src/engine-node/sensors/blindspots.mjs +376 -0
  238. package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
  239. package/src/engine-node/sensors/index.mjs +7 -0
  240. package/src/hooks/antigravity_rsl_hook.mjs +250 -0
  241. package/src/hooks/claude_rsl_hook.mjs +288 -0
  242. package/src/hooks/portfolio_runtime.mjs +858 -0
  243. package/src/hooks/post_invocation.mjs +611 -0
  244. package/src/hooks/pre_invocation.mjs +1725 -0
  245. package/src/hooks/session_start.mjs +199 -0
  246. package/src/shims/agy_cli_compressor.mjs +705 -0
  247. package/src/shims/agy_git_guard.mjs +749 -0
  248. package/src/shims/ah_log_query.mjs +39 -0
  249. package/src/ui/costRadarSvg.mjs +6 -0
  250. package/src/ui/horizonGrid.mjs +1 -0
  251. package/src/ui/horizonPanelHtml.mjs +1 -0
  252. package/src/ui/horizon_panel.css +167 -0
  253. package/src/ui/horizon_panel.js +212 -0
  254. package/src/ui/modViews.mjs +1 -0
  255. package/src/utils/modelSwitchTelemetry.mjs +308 -0
  256. package/src/utils/nodeIo.mjs +59 -0
  257. package/src/utils/runtime.mjs +1 -0
  258. package/src/utils/sessionCalibration.mjs +657 -0
  259. package/src/webview/advanced_view.html +1808 -0
  260. package/src/webview/horizon_panel.html +12397 -0
  261. package/src/webview/registry.mjs +80 -0
  262. package/src/webview/simple_view.html +1370 -0
@@ -0,0 +1,551 @@
1
+ /**
2
+ * @file src/core-isomorphic/guards/slopsquatGate.mjs
3
+ * Guardrail #6 (`SLOPSQUAT_DEP_GATE`): Supply-Chain Slopsquatting & Conflation Gate.
4
+ *
5
+ * Pure isomorphic module (Mod Law 4 compliant: zero `node:*` imports, zero network I/O).
6
+ * - Phase 1 (`<5ms` offline): Parses `npm`/`pnpm`/`yarn`/`bun`/`pip`/`uv`/`poetry`/`cargo` install commands,
7
+ * auto-allows existing manifest/lockfile deps, `workspace:*`/`file:` protocols, and private `.npmrc` /
8
+ * `--index-url` scopes, and detects Damerau-Levenshtein-1 typos + empirical LLM package conflations.
9
+ * - Phase 2 (Optional metadata evaluation): Evaluates registry metadata with strict fail-open semantics
10
+ * on offline/timeout faults (`0%` false-deny on airgapped or private-registry environments).
11
+ */
12
+
13
+ /**
14
+ * Canonical high-traffic packages across npm, PyPI, and Crates used for distance-1 slopsquat detection.
15
+ */
16
+ export const POPULAR_ECOSYSTEM_PACKAGES = Object.freeze({
17
+ npm: Object.freeze([
18
+ 'react', 'react-dom', 'next', 'vue', 'svelte', 'angular', 'solid-js', 'preact',
19
+ 'express', 'fastify', 'koa', 'hono', 'nestjs', 'socket.io', 'ws', 'cors', 'helmet',
20
+ 'lodash', 'underscore', 'ramda', 'immer', 'rxjs', 'zustand', 'jotai', 'redux',
21
+ 'axios', 'node-fetch', 'undici', 'ky', 'got', 'superagent', 'graphql', 'apollo-server',
22
+ 'typescript', 'tslib', 'tsx', 'ts-node', 'esbuild', 'vite', 'rollup', 'webpack', 'parcel',
23
+ 'eslint', 'prettier', 'biome', 'stylelint', 'husky', 'lint-staged', 'jscodeshift',
24
+ 'vitest', 'jest', 'mocha', 'chai', 'sinon', 'playwright', 'cypress', 'puppeteer',
25
+ 'tailwindcss', 'postcss', 'autoprefixer', 'sass', 'less', 'clsx', 'classnames', 'tailwind-merge',
26
+ 'lucide-react', 'heroicons', 'framer-motion', 'radix-ui', 'cmdk', 'sonner', 'vaul',
27
+ 'zod', 'yup', 'joi', 'valibot', 'ajv', 'superstruct', 'typebox',
28
+ 'prisma', '@prisma/client', 'drizzle-orm', 'typeorm', 'sequelize', 'mongoose', 'knex', 'pg',
29
+ 'mysql2', 'sqlite3', 'better-sqlite3', 'ioredis', 'redis', 'mongodb',
30
+ 'dotenv', 'cross-env', 'chalk', 'picocolors', 'kleur', 'ora', 'inquirer', 'prompts',
31
+ 'commander', 'yargs', 'minimist', 'cac', 'arg', 'execa', 'zx', 'glob', 'fast-glob', 'chokidar',
32
+ 'date-fns', 'dayjs', 'moment', 'luxon', 'uuid', 'nanoid', 'ulid', 'semver', 'ms', 'debug',
33
+ 'jsonwebtoken', 'jose', 'bcrypt', 'bcryptjs', 'argon2', 'passport', 'next-auth', 'lucia',
34
+ 'stripe', 'openai', 'anthropic', 'langchain', 'ai', 'cheerio', 'jsdom', 'marked', 'shiki',
35
+ 'winston', 'pino', 'morgan', 'sentry', 'bullmq', 'nodemailer', 'resend', 'sharp', 'multer'
36
+ ]),
37
+ pypi: Object.freeze([
38
+ 'requests', 'urllib3', 'httpx', 'aiohttp', 'fastapi', 'uvicorn', 'starlette', 'flask',
39
+ 'django', 'gunicorn', 'celery', 'werkzeug', 'jinja2', 'itsdangerous', 'click', 'typer',
40
+ 'rich', 'tqdm', 'colorama', 'loguru', 'structlog', 'pydantic', 'pydantic-settings',
41
+ 'marshmallow', 'attrs', 'sqlalchemy', 'alembic', 'psycopg2', 'psycopg2-binary', 'asyncpg',
42
+ 'pymongo', 'redis', 'pymysql', 'aiosqlite', 'peewee', 'tortoise-orm', 'sqlmodel',
43
+ 'numpy', 'pandas', 'scipy', 'matplotlib', 'seaborn', 'plotly', 'polars', 'pyarrow',
44
+ 'scikit-learn', 'torch', 'torchvision', 'torchaudio', 'tensorflow', 'keras', 'jax',
45
+ 'transformers', 'datasets', 'accelerate', 'diffusers', 'tokenizers', 'huggingface-hub',
46
+ 'openai', 'anthropic', 'langchain', 'llama-index', 'tiktoken', 'chromadb', 'qdrant-client',
47
+ 'pytest', 'pytest-asyncio', 'pytest-cov', 'hypothesis', 'coverage', 'mypy', 'ruff', 'black',
48
+ 'isort', 'flake8', 'pylint', 'bandit', 'pre-commit', 'tox', 'nox', 'virtualenv', 'poetry',
49
+ 'boto3', 'botocore', 's3transfer', 'google-cloud-storage', 'azure-storage-blob',
50
+ 'cryptography', 'pyjwt', 'bcrypt', 'passlib', 'pynacl', 'certifi', 'charset-normalizer',
51
+ 'idna', 'pyyaml', 'toml', 'tomli', 'python-dotenv', 'python-multipart', 'python-dateutil',
52
+ 'pytz', 'arrow', 'pendulum', 'pillow', 'opencv-python', 'beautifulsoup4', 'lxml', 'scrapy',
53
+ 'selenium', 'playwright', 'paramiko', 'fabric', 'psutil', 'tenacity', 'orjson', 'ujson'
54
+ ]),
55
+ cargo: Object.freeze([
56
+ 'serde', 'serde_json', 'tokio', 'reqwest', 'clap', 'anyhow', 'thiserror', 'tracing',
57
+ 'tracing-subscriber', 'futures', 'async-trait', 'axum', 'actix-web', 'hyper', 'tower',
58
+ 'sqlx', 'diesel', 'rusqlite', 'redis', 'rand', 'regex', 'chrono', 'time', 'uuid',
59
+ 'itertools', 'rayon', 'crossbeam', 'parking_lot', 'once_cell', 'lazy_static', 'bytes',
60
+ 'log', 'env_logger', 'eyre', 'color-eyre', 'tempfile', 'proptest', 'criterion', 'syn',
61
+ 'quote', 'proc-macro2', 'bindgen', 'cc', 'sha2', 'hmac', 'base64', 'hex', 'url', 'dotenvy'
62
+ ])
63
+ });
64
+
65
+ /**
66
+ * Empirically observed LLM package hallucinations & cross-package conflations (USENIX / Socket / Phylum).
67
+ */
68
+ export const KNOWN_LLM_CONFLATIONS = Object.freeze({
69
+ 'react-codeshift': 'Conflation of `jscodeshift` and `react-codemod`',
70
+ 'unused-imports': 'Conflation of `eslint-plugin-unused-imports`',
71
+ 'nextjs-auth': 'Hallucinated conflation of `next-auth`',
72
+ 'tailwind-merge-classes': 'Hallucinated conflation of `tailwind-merge` + `clsx`',
73
+ 'zod-validator': 'Hallucinated wrapper around `zod`',
74
+ 'prisma-orm': 'Hallucinated alias for `prisma` / `@prisma/client`',
75
+ 'lucide-icons': 'Hallucinated conflation of `lucide-react`',
76
+ 'shadcn-ui-react': 'Hallucinated npm package (`shadcn` uses CLI component copy)',
77
+ 'express-jwt-auth': 'Hallucinated conflation of `express-jwt`',
78
+ 'axios-retry-client': 'Hallucinated conflation of `axios-retry`',
79
+ 'jest-dom-extended': 'Hallucinated conflation of `@testing-library/jest-dom`',
80
+ 'chalk-cli-colors': 'Hallucinated conflation of `chalk` + `cli-color`',
81
+ 'dotenv-safe-cli': 'Hallucinated conflation of `dotenv-safe` + `dotenv-cli`',
82
+ 'huggingface-cli': 'PyPI slopsquat for `huggingface-hub` (which provides the `huggingface-cli` binary)',
83
+ 'fastapi-cors': 'Hallucinated PyPI package (`CORSMiddleware` is built into `fastapi`)',
84
+ 'openai-whisper-api': 'Hallucinated conflation of `openai` + `openai-whisper`',
85
+ 'python-dotenv-cli': 'Hallucinated conflation of `python-dotenv`',
86
+ 'boto3-stubs-all': 'Hallucinated conflation of `boto3-stubs`',
87
+ 'urllib4': 'Hallucinated successor to `urllib3`',
88
+ 'sklearn-utils': 'Hallucinated companion to `scikit-learn`'
89
+ });
90
+
91
+ const FLAGS_WITH_VALUE = new Set([
92
+ '--registry',
93
+ '--index-url',
94
+ '--extra-index-url',
95
+ '-i',
96
+ '-r',
97
+ '--requirement',
98
+ '-c',
99
+ '--constraint',
100
+ '-w',
101
+ '--workspace',
102
+ '--filter',
103
+ '--prefix',
104
+ '-C',
105
+ '--dir',
106
+ '--features',
107
+ '--trusted-host',
108
+ '--target',
109
+ '-t',
110
+ '--cache-dir',
111
+ '--find-links',
112
+ '-f'
113
+ ]);
114
+
115
+ /**
116
+ * Computes optimal string alignment (Damerau-Levenshtein) distance with fast early exit for `> 1`.
117
+ *
118
+ * @param {string} a
119
+ * @param {string} b
120
+ * @returns {number} `0`, `1`, or `2` (`2` means distance `>= 2`)
121
+ */
122
+ export function damerauLevenshteinMax1(a = '', b = '') {
123
+ if (a === b) return 0;
124
+ const la = a.length;
125
+ const lb = b.length;
126
+ if (Math.abs(la - lb) > 1) return 2;
127
+
128
+ const prevPrev = new Array(lb + 1).fill(0);
129
+ const prev = new Array(lb + 1).fill(0);
130
+ const curr = new Array(lb + 1).fill(0);
131
+ for (let j = 0; j <= lb; j++) prev[j] = j;
132
+
133
+ for (let i = 1; i <= la; i++) {
134
+ curr[0] = i;
135
+ let rowMin = curr[0];
136
+ for (let j = 1; j <= lb; j++) {
137
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
138
+ let val = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost);
139
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
140
+ val = Math.min(val, prevPrev[j - 2] + 1);
141
+ }
142
+ curr[j] = val;
143
+ if (val < rowMin) rowMin = val;
144
+ }
145
+ if (rowMin > 1) return 2;
146
+ for (let j = 0; j <= lb; j++) {
147
+ prevPrev[j] = prev[j];
148
+ prev[j] = curr[j];
149
+ }
150
+ }
151
+ return prev[lb] <= 1 ? prev[lb] : 2;
152
+ }
153
+
154
+ /**
155
+ * Normalizes a package specifier token into `{ name, raw, isLocalOrProtocol, scope }`.
156
+ *
157
+ * @param {string} rawSpec
158
+ * @param {'npm' | 'pypi' | 'cargo'} ecosystem
159
+ */
160
+ export function normalizePackageSpec(rawSpec = '', ecosystem = 'npm') {
161
+ const raw = String(rawSpec || '').trim().replace(/^['"]|['"]$/g, '');
162
+ if (!raw) return null;
163
+
164
+ if (
165
+ raw === '.' ||
166
+ raw.startsWith('./') ||
167
+ raw.startsWith('../') ||
168
+ raw.startsWith('/') ||
169
+ raw.startsWith('workspace:') ||
170
+ raw.startsWith('file:') ||
171
+ raw.startsWith('link:') ||
172
+ raw.startsWith('portal:') ||
173
+ raw.startsWith('git+') ||
174
+ raw.startsWith('http://') ||
175
+ raw.startsWith('https://') ||
176
+ raw.startsWith('github:') ||
177
+ /\.(?:tgz|tar\.gz|whl|zip)$/i.test(raw)
178
+ ) {
179
+ return { raw, name: raw, scope: '', isLocalOrProtocol: true };
180
+ }
181
+
182
+ if (ecosystem === 'npm') {
183
+ if (raw.startsWith('@')) {
184
+ const slashIdx = raw.indexOf('/');
185
+ if (slashIdx <= 1) return null;
186
+ const scope = raw.slice(0, slashIdx).toLowerCase();
187
+ const rest = raw.slice(slashIdx + 1);
188
+ const atVerIdx = rest.indexOf('@');
189
+ const pkgPart = atVerIdx > 0 ? rest.slice(0, atVerIdx) : rest;
190
+ const verPart = atVerIdx > 0 ? rest.slice(atVerIdx + 1) : '';
191
+ if (verPart.startsWith('workspace:') || verPart.startsWith('file:') || verPart.startsWith('link:')) {
192
+ return { raw, name: `${scope}/${pkgPart}`.toLowerCase(), scope, isLocalOrProtocol: true };
193
+ }
194
+ return {
195
+ raw,
196
+ name: `${scope}/${pkgPart}`.toLowerCase(),
197
+ scope,
198
+ isLocalOrProtocol: false
199
+ };
200
+ }
201
+ const atIdx = raw.indexOf('@');
202
+ const name = (atIdx > 0 ? raw.slice(0, atIdx) : raw).toLowerCase();
203
+ const verPart = atIdx > 0 ? raw.slice(atIdx + 1) : '';
204
+ if (verPart.startsWith('workspace:') || verPart.startsWith('file:') || verPart.startsWith('link:')) {
205
+ return { raw, name, scope: '', isLocalOrProtocol: true };
206
+ }
207
+ return { raw, name, scope: '', isLocalOrProtocol: false };
208
+ }
209
+
210
+ if (ecosystem === 'pypi') {
211
+ // Strip extras `pkg[standard]` and PEP 440 version operators `==`, `>=`, `<=`, `~=`, `!=`, `<`, `>`
212
+ const base = raw.split(/[=<>~!;\s[]/)[0].trim().toLowerCase().replace(/_/g, '-');
213
+ if (!base) return null;
214
+ return { raw, name: base, scope: '', isLocalOrProtocol: false };
215
+ }
216
+
217
+ // cargo
218
+ const base = raw.split('@')[0].trim().toLowerCase();
219
+ return base ? { raw, name: base, scope: '', isLocalOrProtocol: false } : null;
220
+ }
221
+
222
+ /**
223
+ * Parses a shell command string to extract package-manager install invocations.
224
+ *
225
+ * @param {string} command
226
+ * @returns {Array<{ ecosystem: 'npm'|'pypi'|'cargo', manager: string, packages: Array<object>, hasCustomRegistry: boolean, isLockfileSyncOnly: boolean }>}
227
+ */
228
+ export function parsePackageInstallCommands(command = '') {
229
+ const cmdText = String(command || '').trim();
230
+ if (!cmdText) return [];
231
+
232
+ const segments = cmdText.split(/\s*(?:&&|\|\||;|\n)\s*/).filter(Boolean);
233
+ const invocations = [];
234
+
235
+ for (const seg of segments) {
236
+ const tokens = seg.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g) || [];
237
+ if (tokens.length === 0) continue;
238
+
239
+ // Strip leading env assignments `FOO=bar`
240
+ let idx = 0;
241
+ while (idx < tokens.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[idx])) idx += 1;
242
+ if (idx >= tokens.length) continue;
243
+
244
+ const bin = tokens[idx].replace(/^['"]|['"]$/g, '').toLowerCase();
245
+ let ecosystem = null;
246
+ let manager = bin;
247
+ let argStart = -1;
248
+ let isLockfileSyncOnly = false;
249
+
250
+ if (bin === 'npm' || bin === 'pnpm' || bin === 'yarn' || bin === 'bun') {
251
+ const sub = (tokens[idx + 1] || '').toLowerCase();
252
+ if (sub === 'ci' || sub === 'dedupe') {
253
+ invocations.push({
254
+ ecosystem: 'npm',
255
+ manager: bin,
256
+ packages: [],
257
+ hasCustomRegistry: false,
258
+ isLockfileSyncOnly: true
259
+ });
260
+ continue;
261
+ }
262
+ if (['install', 'i', 'add', 'in', 'ins'].includes(sub)) {
263
+ ecosystem = 'npm';
264
+ argStart = idx + 2;
265
+ } else if (bin === 'yarn' && !sub.startsWith('-') && tokens.length === idx + 1) {
266
+ isLockfileSyncOnly = true;
267
+ invocations.push({
268
+ ecosystem: 'npm',
269
+ manager: 'yarn',
270
+ packages: [],
271
+ hasCustomRegistry: false,
272
+ isLockfileSyncOnly
273
+ });
274
+ continue;
275
+ }
276
+ } else if (bin === 'pip' || bin === 'pip3') {
277
+ if ((tokens[idx + 1] || '').toLowerCase() === 'install') {
278
+ ecosystem = 'pypi';
279
+ argStart = idx + 2;
280
+ }
281
+ } else if ((bin === 'python' || bin === 'python3') && tokens[idx + 1] === '-m' && /^pip3?$/i.test(tokens[idx + 2] || '')) {
282
+ if ((tokens[idx + 3] || '').toLowerCase() === 'install') {
283
+ ecosystem = 'pypi';
284
+ manager = 'pip';
285
+ argStart = idx + 4;
286
+ }
287
+ } else if (bin === 'uv') {
288
+ const sub = (tokens[idx + 1] || '').toLowerCase();
289
+ if (sub === 'add') {
290
+ ecosystem = 'pypi';
291
+ argStart = idx + 2;
292
+ } else if (sub === 'pip' && (tokens[idx + 2] || '').toLowerCase() === 'install') {
293
+ ecosystem = 'pypi';
294
+ argStart = idx + 3;
295
+ }
296
+ } else if (bin === 'poetry' && (tokens[idx + 1] || '').toLowerCase() === 'add') {
297
+ ecosystem = 'pypi';
298
+ argStart = idx + 2;
299
+ } else if (bin === 'cargo' && (tokens[idx + 1] || '').toLowerCase() === 'add') {
300
+ ecosystem = 'cargo';
301
+ argStart = idx + 2;
302
+ }
303
+
304
+ if (!ecosystem || argStart < 0) continue;
305
+
306
+ let hasCustomRegistry = false;
307
+ let hasRequirementManifestFlag = false;
308
+ let hasCargoLocalOrGit = false;
309
+ const rawPkgSpecs = [];
310
+
311
+ for (let i = argStart; i < tokens.length; i++) {
312
+ const tok = tokens[i].replace(/^['"]|['"]$/g, '');
313
+ if (!tok) continue;
314
+
315
+ if (
316
+ tok.startsWith('--registry=') ||
317
+ tok.startsWith('--index-url=') ||
318
+ tok.startsWith('--extra-index-url=')
319
+ ) {
320
+ hasCustomRegistry = true;
321
+ continue;
322
+ }
323
+ if (tok === '--registry' || tok === '--index-url' || tok === '--extra-index-url' || tok === '-i') {
324
+ hasCustomRegistry = true;
325
+ i += 1;
326
+ continue;
327
+ }
328
+ if (tok === '-r' || tok === '--requirement' || tok.startsWith('--requirement=')) {
329
+ hasRequirementManifestFlag = true;
330
+ if (tok === '-r' || tok === '--requirement') i += 1;
331
+ continue;
332
+ }
333
+ if (tok === '-e' || tok === '--editable') {
334
+ const nextTok = (tokens[i + 1] || '').replace(/^['"]|['"]$/g, '');
335
+ if (nextTok.startsWith('.') || nextTok.startsWith('/')) {
336
+ i += 1;
337
+ continue;
338
+ }
339
+ }
340
+ if (ecosystem === 'cargo' && (tok === '--path' || tok === '--git')) {
341
+ hasCargoLocalOrGit = true;
342
+ i += 1;
343
+ continue;
344
+ }
345
+ if (FLAGS_WITH_VALUE.has(tok)) {
346
+ i += 1;
347
+ continue;
348
+ }
349
+ if (tok.startsWith('-')) continue;
350
+
351
+ const parsed = normalizePackageSpec(tok, ecosystem);
352
+ if (parsed) rawPkgSpecs.push(parsed);
353
+ }
354
+
355
+ if (hasCargoLocalOrGit && rawPkgSpecs.every((p) => !p.raw.includes('@'))) {
356
+ for (const p of rawPkgSpecs) p.isLocalOrProtocol = true;
357
+ }
358
+
359
+ invocations.push({
360
+ ecosystem,
361
+ manager,
362
+ packages: rawPkgSpecs,
363
+ hasCustomRegistry,
364
+ isLockfileSyncOnly: rawPkgSpecs.length === 0 && !hasRequirementManifestFlag
365
+ ? true
366
+ : rawPkgSpecs.length === 0 && hasRequirementManifestFlag
367
+ });
368
+ }
369
+
370
+ return invocations;
371
+ }
372
+
373
+ /**
374
+ * Evaluates Guardrail #6 (`SLOPSQUAT_DEP_GATE`) across Phase 1 (offline `<5ms`) and optional Phase 2 metadata.
375
+ *
376
+ * @param {object} input
377
+ * @param {string} input.command
378
+ * @param {Iterable<string>} [input.manifestDeps] - Existing manifest/lockfile package names
379
+ * @param {Iterable<string>} [input.workspacePackages] - Monorepo workspace package names
380
+ * @param {Iterable<string>} [input.privateScopes] - Private scopes from `.npmrc` (e.g. `['@corp', '@internal']`)
381
+ * @param {Record<string, { exists?: boolean, ageDays?: number, weeklyDownloads?: number, offline?: boolean, timedOut?: boolean, error?: string }>} [input.registryMetadata]
382
+ */
383
+ export function evaluateSlopsquatCommand(input = {}) {
384
+ const invocations = parsePackageInstallCommands(input.command || '');
385
+ if (invocations.length === 0) {
386
+ return {
387
+ triggered: false,
388
+ decision: 'allow',
389
+ reason: 'No package install invocation detected',
390
+ findings: [],
391
+ tokensSavedEst: 0
392
+ };
393
+ }
394
+
395
+ const manifestSet = new Set(
396
+ Array.from(input.manifestDeps || [], (d) => String(d).toLowerCase().replace(/_/g, '-'))
397
+ );
398
+ const workspaceSet = new Set(
399
+ Array.from(input.workspacePackages || [], (d) => String(d).toLowerCase())
400
+ );
401
+ const privateScopeSet = new Set(
402
+ Array.from(input.privateScopes || [], (s) =>
403
+ (String(s).startsWith('@') ? String(s) : `@${s}`).toLowerCase()
404
+ )
405
+ );
406
+ const registryMetaMap = input.registryMetadata || null;
407
+
408
+ const findings = [];
409
+
410
+ for (const inv of invocations) {
411
+ if (inv.isLockfileSyncOnly || inv.packages.length === 0) continue;
412
+
413
+ const canonicalList = POPULAR_ECOSYSTEM_PACKAGES[inv.ecosystem] || [];
414
+ const canonicalSet = new Set(canonicalList.map((p) => p.toLowerCase()));
415
+
416
+ for (const pkg of inv.packages) {
417
+ if (pkg.isLocalOrProtocol) continue;
418
+ const normalizedKey =
419
+ inv.ecosystem === 'pypi' ? pkg.name.replace(/_/g, '-') : pkg.name.toLowerCase();
420
+
421
+ // 1. Existing manifest / lockfile / monorepo workspace allowlist
422
+ if (
423
+ manifestSet.has(normalizedKey) ||
424
+ manifestSet.has(pkg.name) ||
425
+ workspaceSet.has(pkg.name)
426
+ ) {
427
+ continue;
428
+ }
429
+
430
+ // 2. Private `.npmrc` scope or custom `--registry` / `--index-url` allowlist (0% false-deny!)
431
+ if (pkg.scope && privateScopeSet.has(pkg.scope)) {
432
+ continue;
433
+ }
434
+ if (inv.hasCustomRegistry) {
435
+ continue;
436
+ }
437
+
438
+ // 3. Canonical popular package fast-allow
439
+ if (canonicalSet.has(normalizedKey)) {
440
+ continue;
441
+ }
442
+
443
+ // 4. Phase 1a: Known LLM package conflation / hallucination dictionary
444
+ if (Object.prototype.hasOwnProperty.call(KNOWN_LLM_CONFLATIONS, normalizedKey)) {
445
+ findings.push({
446
+ package: pkg.name,
447
+ ecosystem: inv.ecosystem,
448
+ phase: 1,
449
+ kind: 'LLM_CONFLATION',
450
+ detail: KNOWN_LLM_CONFLATIONS[normalizedKey]
451
+ });
452
+ continue;
453
+ }
454
+
455
+ // 5. Phase 1b: Damerau-Levenshtein distance == 1 against canonical ecosystem top list
456
+ let closestTarget = null;
457
+ if (normalizedKey.length >= 4) {
458
+ for (const popular of canonicalList) {
459
+ if (damerauLevenshteinMax1(normalizedKey, popular) === 1) {
460
+ closestTarget = popular;
461
+ break;
462
+ }
463
+ }
464
+ }
465
+ if (closestTarget) {
466
+ findings.push({
467
+ package: pkg.name,
468
+ ecosystem: inv.ecosystem,
469
+ phase: 1,
470
+ kind: 'TYPOSQUAT_DISTANCE_1',
471
+ suggestedPackage: closestTarget,
472
+ detail: `Edit-distance 1 from canonical \`${closestTarget}\``
473
+ });
474
+ continue;
475
+ }
476
+
477
+ // 6. Phase 1c: Suspicious LLM affix hallucination (`<popular>-official`, `python-<popular>` when canonical exists)
478
+ const strippedAffix = normalizedKey
479
+ .replace(/^(?:python-|py-|node-|npm-)/, '')
480
+ .replace(/(?:-official|-sdk-v2|-js-sdk|-py)$/, '');
481
+ if (
482
+ strippedAffix !== normalizedKey &&
483
+ strippedAffix.length >= 4 &&
484
+ canonicalSet.has(strippedAffix)
485
+ ) {
486
+ findings.push({
487
+ package: pkg.name,
488
+ ecosystem: inv.ecosystem,
489
+ phase: 1,
490
+ kind: 'AFFIX_HALLUCINATION',
491
+ suggestedPackage: strippedAffix,
492
+ detail: `Suspicious affix wrapper around canonical \`${strippedAffix}\``
493
+ });
494
+ continue;
495
+ }
496
+
497
+ // 7. Phase 2 (Opt-in / Mocked Registry Metadata): Fail-open on offline/timeout!
498
+ if (registryMetaMap && Object.prototype.hasOwnProperty.call(registryMetaMap, pkg.name)) {
499
+ const meta = registryMetaMap[pkg.name] || {};
500
+ if (meta.offline || meta.timedOut || meta.error) {
501
+ // Strict fail-open: never block or nag when offline or timed out on unflagged packages
502
+ continue;
503
+ }
504
+ if (meta.exists === false) {
505
+ findings.push({
506
+ package: pkg.name,
507
+ ecosystem: inv.ecosystem,
508
+ phase: 2,
509
+ kind: 'UNPUBLISHED_404_HALLUCINATION',
510
+ detail: `Package \`${pkg.name}\` returned 404 Not Found on ${inv.ecosystem} registry`
511
+ });
512
+ } else if (
513
+ typeof meta.ageDays === 'number' &&
514
+ meta.ageDays < 14 &&
515
+ typeof meta.weeklyDownloads === 'number' &&
516
+ meta.weeklyDownloads < 50
517
+ ) {
518
+ findings.push({
519
+ package: pkg.name,
520
+ ecosystem: inv.ecosystem,
521
+ phase: 2,
522
+ kind: 'LOW_REPUTATION_NEW_PACKAGE',
523
+ detail: `Newly published (${meta.ageDays}d old, ${meta.weeklyDownloads} weekly downloads)`
524
+ });
525
+ }
526
+ }
527
+ }
528
+ }
529
+
530
+ if (findings.length === 0) {
531
+ return {
532
+ triggered: false,
533
+ decision: 'allow',
534
+ reason: 'All package specifiers verified or allowlisted',
535
+ findings: [],
536
+ tokensSavedEst: 0
537
+ };
538
+ }
539
+
540
+ // Always use human-in-the-loop `ask` (never blind `deny` that blocks legitimate obscure packages)
541
+ return {
542
+ triggered: true,
543
+ decision: 'ask',
544
+ code: 'SLOPSQUAT_DEP_GATE',
545
+ reason: `[Quota & Supply-Chain Shield] Unverified package install (${findings
546
+ .map((f) => `${f.package}: ${f.detail}`)
547
+ .join('; ')}). Confirm package name before running install scripts.`,
548
+ findings,
549
+ tokensSavedEst: 1800
550
+ };
551
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * @file src/core-isomorphic/index.js
3
+ * Highbeam v4.0 Isomorphic Mod Core (`@ctxtop/core-isomorphic`).
4
+ *
5
+ * Pure JS / ESM with strictly 0 node:* imports, 0 dynamic imports, 0 CommonJS require.
6
+ * Adheres to Claude Mod Laws 1–5.
7
+ */
8
+
9
+ export * from './ustf/index.mjs';
10
+ export * from './catalog/index.mjs';
11
+ export * from './control/index.mjs';
12
+ export * from './economics/index.mjs';
13
+ export * from './diagnostics/index.mjs';
14
+ export * from './utils/runtime.mjs';
15
+ export * from './telemetry/telemetryBridge.mjs';
16
+ export * from './config/horizonConfig.mjs';
17
+ export * from './config/catalogLoader.mjs';
18
+ export * from './coach/cacheGravityRouter.mjs';
19
+ export * from './coach/ttlWatchdog.mjs';
20
+ export * from './coach/stateBatonHydrator.mjs';
21
+ export * from './coach/savedQuotaLedger.mjs';
22
+ export * from './guards/circuitBreakers.mjs';
23
+ export * from './guards/docIndexCore.mjs';
24
+ export * from './ui/modViews.mjs';
25
+ export * from './ui/horizonGrid.mjs';
26
+ export * from './ui/costRadarSvg.mjs';
27
+ export * from './ui/horizonPanelHtml.mjs';