vibecheck-ai 2.0.1 → 5.0.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 (456) hide show
  1. package/bin/.generated +25 -0
  2. package/bin/_deprecations.js +463 -0
  3. package/bin/_router.js +46 -0
  4. package/bin/cli-hygiene.js +241 -0
  5. package/bin/dev/run-v2-torture.js +30 -0
  6. package/bin/registry.js +656 -0
  7. package/bin/runners/CLI_REFACTOR_SUMMARY.md +229 -0
  8. package/bin/runners/ENHANCEMENT_GUIDE.md +121 -0
  9. package/bin/runners/REPORT_AUDIT.md +64 -0
  10. package/bin/runners/cli-utils.js +1070 -0
  11. package/bin/runners/context/ai-task-decomposer.js +337 -0
  12. package/bin/runners/context/analyzer.js +513 -0
  13. package/bin/runners/context/api-contracts.js +427 -0
  14. package/bin/runners/context/context-diff.js +342 -0
  15. package/bin/runners/context/context-pruner.js +291 -0
  16. package/bin/runners/context/dependency-graph.js +414 -0
  17. package/bin/runners/context/generators/claude.js +107 -0
  18. package/bin/runners/context/generators/codex.js +108 -0
  19. package/bin/runners/context/generators/copilot.js +119 -0
  20. package/bin/runners/context/generators/cursor-enhanced.js +2525 -0
  21. package/bin/runners/context/generators/cursor.js +514 -0
  22. package/bin/runners/context/generators/mcp.js +169 -0
  23. package/bin/runners/context/generators/windsurf.js +180 -0
  24. package/bin/runners/context/git-context.js +304 -0
  25. package/bin/runners/context/index.js +1110 -0
  26. package/bin/runners/context/insights.js +173 -0
  27. package/bin/runners/context/mcp-server/generate-rules.js +337 -0
  28. package/bin/runners/context/mcp-server/index.js +1176 -0
  29. package/bin/runners/context/mcp-server/package.json +24 -0
  30. package/bin/runners/context/memory.js +200 -0
  31. package/bin/runners/context/monorepo.js +215 -0
  32. package/bin/runners/context/multi-repo-federation.js +404 -0
  33. package/bin/runners/context/patterns.js +253 -0
  34. package/bin/runners/context/proof-context.js +1264 -0
  35. package/bin/runners/context/security-scanner.js +541 -0
  36. package/bin/runners/context/semantic-search.js +350 -0
  37. package/bin/runners/context/shared.js +264 -0
  38. package/bin/runners/context/team-conventions.js +336 -0
  39. package/bin/runners/lib/__tests__/entitlements-v2.test.js +295 -0
  40. package/bin/runners/lib/agent-firewall/ai/false-positive-analyzer.js +474 -0
  41. package/bin/runners/lib/agent-firewall/change-packet/builder.js +488 -0
  42. package/bin/runners/lib/agent-firewall/change-packet/schema.json +228 -0
  43. package/bin/runners/lib/agent-firewall/change-packet/store.js +200 -0
  44. package/bin/runners/lib/agent-firewall/claims/claim-types.js +21 -0
  45. package/bin/runners/lib/agent-firewall/claims/extractor.js +303 -0
  46. package/bin/runners/lib/agent-firewall/claims/patterns.js +24 -0
  47. package/bin/runners/lib/agent-firewall/critic/index.js +151 -0
  48. package/bin/runners/lib/agent-firewall/critic/judge.js +432 -0
  49. package/bin/runners/lib/agent-firewall/critic/prompts.js +305 -0
  50. package/bin/runners/lib/agent-firewall/enforcement/gateway.js +1059 -0
  51. package/bin/runners/lib/agent-firewall/enforcement/index.js +98 -0
  52. package/bin/runners/lib/agent-firewall/enforcement/mode.js +318 -0
  53. package/bin/runners/lib/agent-firewall/enforcement/orchestrator.js +484 -0
  54. package/bin/runners/lib/agent-firewall/enforcement/proof-artifact.js +418 -0
  55. package/bin/runners/lib/agent-firewall/enforcement/schemas/change-event.schema.json +173 -0
  56. package/bin/runners/lib/agent-firewall/enforcement/schemas/intent.schema.json +181 -0
  57. package/bin/runners/lib/agent-firewall/enforcement/schemas/verdict.schema.json +222 -0
  58. package/bin/runners/lib/agent-firewall/enforcement/verdict-v2.js +333 -0
  59. package/bin/runners/lib/agent-firewall/evidence/auth-evidence.js +88 -0
  60. package/bin/runners/lib/agent-firewall/evidence/contract-evidence.js +75 -0
  61. package/bin/runners/lib/agent-firewall/evidence/env-evidence.js +127 -0
  62. package/bin/runners/lib/agent-firewall/evidence/resolver.js +102 -0
  63. package/bin/runners/lib/agent-firewall/evidence/route-evidence.js +213 -0
  64. package/bin/runners/lib/agent-firewall/evidence/side-effect-evidence.js +145 -0
  65. package/bin/runners/lib/agent-firewall/fs-hook/daemon.js +19 -0
  66. package/bin/runners/lib/agent-firewall/fs-hook/installer.js +87 -0
  67. package/bin/runners/lib/agent-firewall/fs-hook/watcher.js +184 -0
  68. package/bin/runners/lib/agent-firewall/git-hook/pre-commit.js +163 -0
  69. package/bin/runners/lib/agent-firewall/ide-extension/cursor.js +107 -0
  70. package/bin/runners/lib/agent-firewall/ide-extension/vscode.js +68 -0
  71. package/bin/runners/lib/agent-firewall/ide-extension/windsurf.js +66 -0
  72. package/bin/runners/lib/agent-firewall/index.js +200 -0
  73. package/bin/runners/lib/agent-firewall/integration/index.js +20 -0
  74. package/bin/runners/lib/agent-firewall/integration/ship-gate.js +437 -0
  75. package/bin/runners/lib/agent-firewall/intent/alignment-engine.js +634 -0
  76. package/bin/runners/lib/agent-firewall/intent/auto-detect.js +426 -0
  77. package/bin/runners/lib/agent-firewall/intent/index.js +102 -0
  78. package/bin/runners/lib/agent-firewall/intent/schema.js +352 -0
  79. package/bin/runners/lib/agent-firewall/intent/store.js +283 -0
  80. package/bin/runners/lib/agent-firewall/interception/fs-interceptor.js +502 -0
  81. package/bin/runners/lib/agent-firewall/interception/index.js +23 -0
  82. package/bin/runners/lib/agent-firewall/interceptor/base.js +308 -0
  83. package/bin/runners/lib/agent-firewall/interceptor/cursor.js +35 -0
  84. package/bin/runners/lib/agent-firewall/interceptor/vscode.js +35 -0
  85. package/bin/runners/lib/agent-firewall/interceptor/windsurf.js +34 -0
  86. package/bin/runners/lib/agent-firewall/lawbook/distributor.js +465 -0
  87. package/bin/runners/lib/agent-firewall/lawbook/evaluator.js +604 -0
  88. package/bin/runners/lib/agent-firewall/lawbook/index.js +304 -0
  89. package/bin/runners/lib/agent-firewall/lawbook/registry.js +514 -0
  90. package/bin/runners/lib/agent-firewall/lawbook/schema.js +420 -0
  91. package/bin/runners/lib/agent-firewall/logger.js +141 -0
  92. package/bin/runners/lib/agent-firewall/policy/default-policy.json +90 -0
  93. package/bin/runners/lib/agent-firewall/policy/engine.js +103 -0
  94. package/bin/runners/lib/agent-firewall/policy/loader.js +451 -0
  95. package/bin/runners/lib/agent-firewall/policy/rules/auth-drift.js +50 -0
  96. package/bin/runners/lib/agent-firewall/policy/rules/contract-drift.js +50 -0
  97. package/bin/runners/lib/agent-firewall/policy/rules/fake-success.js +79 -0
  98. package/bin/runners/lib/agent-firewall/policy/rules/ghost-env.js +227 -0
  99. package/bin/runners/lib/agent-firewall/policy/rules/ghost-route.js +191 -0
  100. package/bin/runners/lib/agent-firewall/policy/rules/scope.js +93 -0
  101. package/bin/runners/lib/agent-firewall/policy/rules/unsafe-side-effect.js +57 -0
  102. package/bin/runners/lib/agent-firewall/policy/schema.json +183 -0
  103. package/bin/runners/lib/agent-firewall/policy/verdict.js +54 -0
  104. package/bin/runners/lib/agent-firewall/proposal/extractor.js +394 -0
  105. package/bin/runners/lib/agent-firewall/proposal/index.js +212 -0
  106. package/bin/runners/lib/agent-firewall/proposal/schema.js +251 -0
  107. package/bin/runners/lib/agent-firewall/proposal/validator.js +386 -0
  108. package/bin/runners/lib/agent-firewall/reality/index.js +332 -0
  109. package/bin/runners/lib/agent-firewall/reality/state.js +625 -0
  110. package/bin/runners/lib/agent-firewall/reality/watcher.js +322 -0
  111. package/bin/runners/lib/agent-firewall/risk/index.js +173 -0
  112. package/bin/runners/lib/agent-firewall/risk/scorer.js +328 -0
  113. package/bin/runners/lib/agent-firewall/risk/thresholds.js +322 -0
  114. package/bin/runners/lib/agent-firewall/risk/vectors.js +421 -0
  115. package/bin/runners/lib/agent-firewall/session/collector.js +451 -0
  116. package/bin/runners/lib/agent-firewall/session/index.js +26 -0
  117. package/bin/runners/lib/agent-firewall/simulator/diff-simulator.js +472 -0
  118. package/bin/runners/lib/agent-firewall/simulator/import-resolver.js +346 -0
  119. package/bin/runners/lib/agent-firewall/simulator/index.js +181 -0
  120. package/bin/runners/lib/agent-firewall/simulator/route-validator.js +380 -0
  121. package/bin/runners/lib/agent-firewall/time-machine/incident-correlator.js +661 -0
  122. package/bin/runners/lib/agent-firewall/time-machine/index.js +267 -0
  123. package/bin/runners/lib/agent-firewall/time-machine/replay-engine.js +436 -0
  124. package/bin/runners/lib/agent-firewall/time-machine/state-reconstructor.js +490 -0
  125. package/bin/runners/lib/agent-firewall/time-machine/timeline-builder.js +530 -0
  126. package/bin/runners/lib/agent-firewall/truthpack/index.js +67 -0
  127. package/bin/runners/lib/agent-firewall/truthpack/loader.js +137 -0
  128. package/bin/runners/lib/agent-firewall/unblock/planner.js +337 -0
  129. package/bin/runners/lib/agent-firewall/utils/ignore-checker.js +118 -0
  130. package/bin/runners/lib/ai-bridge.js +416 -0
  131. package/bin/runners/lib/analysis-core.js +309 -0
  132. package/bin/runners/lib/analyzers.js +2500 -0
  133. package/bin/runners/lib/api-client.js +269 -0
  134. package/bin/runners/lib/approve-output.js +235 -0
  135. package/bin/runners/lib/artifact-envelope.js +540 -0
  136. package/bin/runners/lib/assets/vibecheck-logo.png +0 -0
  137. package/bin/runners/lib/audit-bridge.js +391 -0
  138. package/bin/runners/lib/auth-shared.js +977 -0
  139. package/bin/runners/lib/auth-truth.js +193 -0
  140. package/bin/runners/lib/auth.js +215 -0
  141. package/bin/runners/lib/authority-badge.js +425 -0
  142. package/bin/runners/lib/backup.js +62 -0
  143. package/bin/runners/lib/billing.js +107 -0
  144. package/bin/runners/lib/checkpoint.js +941 -0
  145. package/bin/runners/lib/claims.js +118 -0
  146. package/bin/runners/lib/classify-output.js +204 -0
  147. package/bin/runners/lib/cleanup/engine.js +571 -0
  148. package/bin/runners/lib/cleanup/index.js +53 -0
  149. package/bin/runners/lib/cleanup/output.js +375 -0
  150. package/bin/runners/lib/cleanup/rules.js +1060 -0
  151. package/bin/runners/lib/cli-output.js +400 -0
  152. package/bin/runners/lib/cli-ui.js +540 -0
  153. package/bin/runners/lib/compliance-bridge-new.js +0 -0
  154. package/bin/runners/lib/compliance-bridge.js +165 -0
  155. package/bin/runners/lib/contracts/auth-contract.js +202 -0
  156. package/bin/runners/lib/contracts/env-contract.js +181 -0
  157. package/bin/runners/lib/contracts/external-contract.js +206 -0
  158. package/bin/runners/lib/contracts/guard.js +168 -0
  159. package/bin/runners/lib/contracts/index.js +89 -0
  160. package/bin/runners/lib/contracts/plan-validator.js +311 -0
  161. package/bin/runners/lib/contracts/route-contract.js +199 -0
  162. package/bin/runners/lib/contracts.js +804 -0
  163. package/bin/runners/lib/default-config.js +127 -0
  164. package/bin/runners/lib/detect.js +89 -0
  165. package/bin/runners/lib/detectors-v2.js +622 -0
  166. package/bin/runners/lib/doctor/autofix.js +254 -0
  167. package/bin/runners/lib/doctor/diagnosis-receipt.js +454 -0
  168. package/bin/runners/lib/doctor/failure-signatures.js +526 -0
  169. package/bin/runners/lib/doctor/fix-script.js +336 -0
  170. package/bin/runners/lib/doctor/index.js +37 -0
  171. package/bin/runners/lib/doctor/modules/build-tools.js +453 -0
  172. package/bin/runners/lib/doctor/modules/dependencies.js +325 -0
  173. package/bin/runners/lib/doctor/modules/index.js +105 -0
  174. package/bin/runners/lib/doctor/modules/network.js +250 -0
  175. package/bin/runners/lib/doctor/modules/os-quirks.js +706 -0
  176. package/bin/runners/lib/doctor/modules/project.js +312 -0
  177. package/bin/runners/lib/doctor/modules/repo-integrity.js +485 -0
  178. package/bin/runners/lib/doctor/modules/runtime.js +224 -0
  179. package/bin/runners/lib/doctor/modules/security.js +350 -0
  180. package/bin/runners/lib/doctor/modules/system.js +213 -0
  181. package/bin/runners/lib/doctor/modules/vibecheck.js +394 -0
  182. package/bin/runners/lib/doctor/reporter.js +262 -0
  183. package/bin/runners/lib/doctor/safe-repair.js +384 -0
  184. package/bin/runners/lib/doctor/service.js +262 -0
  185. package/bin/runners/lib/doctor/types.js +113 -0
  186. package/bin/runners/lib/doctor/ui.js +263 -0
  187. package/bin/runners/lib/doctor-enhanced.js +233 -0
  188. package/bin/runners/lib/doctor-output.js +226 -0
  189. package/bin/runners/lib/doctor-v2.js +608 -0
  190. package/bin/runners/lib/drift.js +425 -0
  191. package/bin/runners/lib/enforcement.js +72 -0
  192. package/bin/runners/lib/engine/ast-cache.js +210 -0
  193. package/bin/runners/lib/engine/auth-extractor.js +211 -0
  194. package/bin/runners/lib/engine/billing-extractor.js +112 -0
  195. package/bin/runners/lib/engine/enforcement-extractor.js +100 -0
  196. package/bin/runners/lib/engine/env-extractor.js +207 -0
  197. package/bin/runners/lib/engine/express-extractor.js +208 -0
  198. package/bin/runners/lib/engine/extractors.js +849 -0
  199. package/bin/runners/lib/engine/index.js +207 -0
  200. package/bin/runners/lib/engine/repo-index.js +514 -0
  201. package/bin/runners/lib/engine/types.js +124 -0
  202. package/bin/runners/lib/engines/accessibility-engine.js +190 -0
  203. package/bin/runners/lib/engines/api-consistency-engine.js +162 -0
  204. package/bin/runners/lib/engines/ast-cache.js +99 -0
  205. package/bin/runners/lib/engines/attack-detector.js +1192 -0
  206. package/bin/runners/lib/engines/code-quality-engine.js +255 -0
  207. package/bin/runners/lib/engines/console-logs-engine.js +115 -0
  208. package/bin/runners/lib/engines/cross-file-analysis-engine.js +268 -0
  209. package/bin/runners/lib/engines/dead-code-engine.js +198 -0
  210. package/bin/runners/lib/engines/deprecated-api-engine.js +226 -0
  211. package/bin/runners/lib/engines/empty-catch-engine.js +150 -0
  212. package/bin/runners/lib/engines/file-filter.js +131 -0
  213. package/bin/runners/lib/engines/hardcoded-secrets-engine.js +251 -0
  214. package/bin/runners/lib/engines/mock-data-engine.js +272 -0
  215. package/bin/runners/lib/engines/parallel-processor.js +71 -0
  216. package/bin/runners/lib/engines/performance-issues-engine.js +265 -0
  217. package/bin/runners/lib/engines/security-vulnerabilities-engine.js +243 -0
  218. package/bin/runners/lib/engines/todo-fixme-engine.js +115 -0
  219. package/bin/runners/lib/engines/type-aware-engine.js +152 -0
  220. package/bin/runners/lib/engines/unsafe-regex-engine.js +225 -0
  221. package/bin/runners/lib/engines/vibecheck-engines/README.md +53 -0
  222. package/bin/runners/lib/engines/vibecheck-engines/index.js +15 -0
  223. package/bin/runners/lib/engines/vibecheck-engines/lib/ast-cache.js +164 -0
  224. package/bin/runners/lib/engines/vibecheck-engines/lib/code-quality-engine.js +291 -0
  225. package/bin/runners/lib/engines/vibecheck-engines/lib/console-logs-engine.js +83 -0
  226. package/bin/runners/lib/engines/vibecheck-engines/lib/dead-code-engine.js +198 -0
  227. package/bin/runners/lib/engines/vibecheck-engines/lib/deprecated-api-engine.js +275 -0
  228. package/bin/runners/lib/engines/vibecheck-engines/lib/empty-catch-engine.js +167 -0
  229. package/bin/runners/lib/engines/vibecheck-engines/lib/file-filter.js +217 -0
  230. package/bin/runners/lib/engines/vibecheck-engines/lib/hardcoded-secrets-engine.js +139 -0
  231. package/bin/runners/lib/engines/vibecheck-engines/lib/mock-data-engine.js +140 -0
  232. package/bin/runners/lib/engines/vibecheck-engines/lib/parallel-processor.js +164 -0
  233. package/bin/runners/lib/engines/vibecheck-engines/lib/performance-issues-engine.js +234 -0
  234. package/bin/runners/lib/engines/vibecheck-engines/lib/type-aware-engine.js +217 -0
  235. package/bin/runners/lib/engines/vibecheck-engines/lib/unsafe-regex-engine.js +78 -0
  236. package/bin/runners/lib/engines/vibecheck-engines/package.json +13 -0
  237. package/bin/runners/lib/enterprise-detect.js +603 -0
  238. package/bin/runners/lib/enterprise-init.js +942 -0
  239. package/bin/runners/lib/entitlements-v2.js +265 -0
  240. package/bin/runners/lib/entitlements.generated.js +0 -0
  241. package/bin/runners/lib/entitlements.js +340 -0
  242. package/bin/runners/lib/env-resolver.js +417 -0
  243. package/bin/runners/lib/env-template.js +66 -0
  244. package/bin/runners/lib/env.js +189 -0
  245. package/bin/runners/lib/error-handler.js +368 -0
  246. package/bin/runners/lib/error-messages.js +289 -0
  247. package/bin/runners/lib/evidence-pack.js +684 -0
  248. package/bin/runners/lib/exit-codes.js +275 -0
  249. package/bin/runners/lib/extractors/client-calls.js +990 -0
  250. package/bin/runners/lib/extractors/fastify-route-dump.js +573 -0
  251. package/bin/runners/lib/extractors/fastify-routes.js +426 -0
  252. package/bin/runners/lib/extractors/index.js +363 -0
  253. package/bin/runners/lib/extractors/next-routes.js +524 -0
  254. package/bin/runners/lib/extractors/proof-graph.js +431 -0
  255. package/bin/runners/lib/extractors/route-matcher.js +451 -0
  256. package/bin/runners/lib/extractors/truthpack-v2.js +377 -0
  257. package/bin/runners/lib/extractors/ui-bindings.js +547 -0
  258. package/bin/runners/lib/finding-id.js +69 -0
  259. package/bin/runners/lib/finding-sorter.js +89 -0
  260. package/bin/runners/lib/findings-schema.js +281 -0
  261. package/bin/runners/lib/fingerprint.js +377 -0
  262. package/bin/runners/lib/firewall-prompt.js +50 -0
  263. package/bin/runners/lib/fix-output.js +228 -0
  264. package/bin/runners/lib/global-flags.js +250 -0
  265. package/bin/runners/lib/graph/graph-builder.js +265 -0
  266. package/bin/runners/lib/graph/html-renderer.js +413 -0
  267. package/bin/runners/lib/graph/index.js +32 -0
  268. package/bin/runners/lib/graph/runtime-collector.js +215 -0
  269. package/bin/runners/lib/graph/static-extractor.js +518 -0
  270. package/bin/runners/lib/help-formatter.js +413 -0
  271. package/bin/runners/lib/html-proof-report.js +913 -0
  272. package/bin/runners/lib/html-report.js +650 -0
  273. package/bin/runners/lib/init-wizard.js +601 -0
  274. package/bin/runners/lib/interactive-menu.js +1496 -0
  275. package/bin/runners/lib/json-output.js +76 -0
  276. package/bin/runners/lib/llm.js +75 -0
  277. package/bin/runners/lib/logger.js +38 -0
  278. package/bin/runners/lib/meter.js +61 -0
  279. package/bin/runners/lib/missions/briefing.js +427 -0
  280. package/bin/runners/lib/missions/checkpoint.js +753 -0
  281. package/bin/runners/lib/missions/evidence.js +126 -0
  282. package/bin/runners/lib/missions/hardening.js +851 -0
  283. package/bin/runners/lib/missions/plan.js +648 -0
  284. package/bin/runners/lib/missions/safety-gates.js +645 -0
  285. package/bin/runners/lib/missions/schema.js +478 -0
  286. package/bin/runners/lib/missions/templates.js +317 -0
  287. package/bin/runners/lib/next-action.js +560 -0
  288. package/bin/runners/lib/packs/bundle.js +675 -0
  289. package/bin/runners/lib/packs/evidence-pack.js +671 -0
  290. package/bin/runners/lib/packs/pack-factory.js +837 -0
  291. package/bin/runners/lib/packs/permissions-pack.js +686 -0
  292. package/bin/runners/lib/packs/proof-graph-pack.js +779 -0
  293. package/bin/runners/lib/patch.js +40 -0
  294. package/bin/runners/lib/permissions/auth-model.js +213 -0
  295. package/bin/runners/lib/permissions/idor-prover.js +205 -0
  296. package/bin/runners/lib/permissions/index.js +45 -0
  297. package/bin/runners/lib/permissions/matrix-builder.js +198 -0
  298. package/bin/runners/lib/pkgjson.js +28 -0
  299. package/bin/runners/lib/policy.js +295 -0
  300. package/bin/runners/lib/polish/accessibility.js +62 -0
  301. package/bin/runners/lib/polish/analyzer.js +93 -0
  302. package/bin/runners/lib/polish/backend.js +87 -0
  303. package/bin/runners/lib/polish/configuration.js +83 -0
  304. package/bin/runners/lib/polish/documentation.js +83 -0
  305. package/bin/runners/lib/polish/frontend.js +817 -0
  306. package/bin/runners/lib/polish/index.js +27 -0
  307. package/bin/runners/lib/polish/infrastructure.js +80 -0
  308. package/bin/runners/lib/polish/internationalization.js +85 -0
  309. package/bin/runners/lib/polish/libraries.js +180 -0
  310. package/bin/runners/lib/polish/observability.js +75 -0
  311. package/bin/runners/lib/polish/performance.js +64 -0
  312. package/bin/runners/lib/polish/privacy.js +110 -0
  313. package/bin/runners/lib/polish/resilience.js +92 -0
  314. package/bin/runners/lib/polish/security.js +78 -0
  315. package/bin/runners/lib/polish/seo.js +71 -0
  316. package/bin/runners/lib/polish/styles.js +62 -0
  317. package/bin/runners/lib/polish/utils.js +104 -0
  318. package/bin/runners/lib/preflight.js +142 -0
  319. package/bin/runners/lib/prerequisites.js +149 -0
  320. package/bin/runners/lib/prove-output.js +220 -0
  321. package/bin/runners/lib/reality/correlation-detectors.js +359 -0
  322. package/bin/runners/lib/reality/index.js +318 -0
  323. package/bin/runners/lib/reality/request-hashing.js +416 -0
  324. package/bin/runners/lib/reality/request-mapper.js +453 -0
  325. package/bin/runners/lib/reality/safety-rails.js +463 -0
  326. package/bin/runners/lib/reality/semantic-snapshot.js +408 -0
  327. package/bin/runners/lib/reality/toast-detector.js +393 -0
  328. package/bin/runners/lib/reality-findings.js +84 -0
  329. package/bin/runners/lib/reality-output.js +231 -0
  330. package/bin/runners/lib/receipts.js +179 -0
  331. package/bin/runners/lib/redact.js +29 -0
  332. package/bin/runners/lib/replay/capsule-manager.js +154 -0
  333. package/bin/runners/lib/replay/index.js +263 -0
  334. package/bin/runners/lib/replay/player.js +348 -0
  335. package/bin/runners/lib/replay/recorder.js +331 -0
  336. package/bin/runners/lib/report-engine.js +626 -0
  337. package/bin/runners/lib/report-html.js +1233 -0
  338. package/bin/runners/lib/report-output.js +366 -0
  339. package/bin/runners/lib/report-templates.js +967 -0
  340. package/bin/runners/lib/report.js +135 -0
  341. package/bin/runners/lib/route-detection.js +1209 -0
  342. package/bin/runners/lib/route-truth.js +1322 -0
  343. package/bin/runners/lib/safelist/index.js +96 -0
  344. package/bin/runners/lib/safelist/integration.js +334 -0
  345. package/bin/runners/lib/safelist/matcher.js +696 -0
  346. package/bin/runners/lib/safelist/schema.js +948 -0
  347. package/bin/runners/lib/safelist/store.js +438 -0
  348. package/bin/runners/lib/sandbox/index.js +59 -0
  349. package/bin/runners/lib/sandbox/proof-chain.js +399 -0
  350. package/bin/runners/lib/sandbox/sandbox-runner.js +205 -0
  351. package/bin/runners/lib/sandbox/worktree.js +174 -0
  352. package/bin/runners/lib/scan-cache.js +330 -0
  353. package/bin/runners/lib/scan-output-schema.js +344 -0
  354. package/bin/runners/lib/scan-output.js +631 -0
  355. package/bin/runners/lib/scan-runner.js +135 -0
  356. package/bin/runners/lib/schema-validator.js +350 -0
  357. package/bin/runners/lib/schemas/ajv-validator.js +464 -0
  358. package/bin/runners/lib/schemas/contracts.schema.json +160 -0
  359. package/bin/runners/lib/schemas/error-envelope.schema.json +105 -0
  360. package/bin/runners/lib/schemas/finding-v3.schema.json +151 -0
  361. package/bin/runners/lib/schemas/finding.schema.json +100 -0
  362. package/bin/runners/lib/schemas/mission-pack.schema.json +206 -0
  363. package/bin/runners/lib/schemas/proof-graph.schema.json +176 -0
  364. package/bin/runners/lib/schemas/reality-report.schema.json +162 -0
  365. package/bin/runners/lib/schemas/report-artifact.schema.json +120 -0
  366. package/bin/runners/lib/schemas/run-request.schema.json +108 -0
  367. package/bin/runners/lib/schemas/share-pack.schema.json +180 -0
  368. package/bin/runners/lib/schemas/ship-manifest.schema.json +251 -0
  369. package/bin/runners/lib/schemas/ship-report.schema.json +117 -0
  370. package/bin/runners/lib/schemas/truthpack-v2.schema.json +303 -0
  371. package/bin/runners/lib/schemas/validator.js +465 -0
  372. package/bin/runners/lib/schemas/verdict.schema.json +140 -0
  373. package/bin/runners/lib/score-history.js +282 -0
  374. package/bin/runners/lib/security-bridge.js +249 -0
  375. package/bin/runners/lib/server-usage.js +513 -0
  376. package/bin/runners/lib/share-pack.js +239 -0
  377. package/bin/runners/lib/ship-gate.js +832 -0
  378. package/bin/runners/lib/ship-manifest.js +1153 -0
  379. package/bin/runners/lib/ship-output-enterprise.js +239 -0
  380. package/bin/runners/lib/ship-output.js +1128 -0
  381. package/bin/runners/lib/snippets.js +67 -0
  382. package/bin/runners/lib/status-output.js +340 -0
  383. package/bin/runners/lib/terminal-ui.js +356 -0
  384. package/bin/runners/lib/truth.js +1691 -0
  385. package/bin/runners/lib/ui.js +562 -0
  386. package/bin/runners/lib/unified-cli-output.js +947 -0
  387. package/bin/runners/lib/unified-output.js +197 -0
  388. package/bin/runners/lib/upsell.js +410 -0
  389. package/bin/runners/lib/usage.js +153 -0
  390. package/bin/runners/lib/validate-patch.js +156 -0
  391. package/bin/runners/lib/verdict-engine.js +628 -0
  392. package/bin/runners/lib/verification.js +345 -0
  393. package/bin/runners/lib/why-tree.js +650 -0
  394. package/bin/runners/reality/engine.js +917 -0
  395. package/bin/runners/reality/flows.js +122 -0
  396. package/bin/runners/reality/report.js +378 -0
  397. package/bin/runners/reality/session.js +193 -0
  398. package/bin/runners/runAIAgent.js +229 -0
  399. package/bin/runners/runAgent.d.ts +5 -0
  400. package/bin/runners/runAgent.js +161 -0
  401. package/bin/runners/runAllowlist.js +418 -0
  402. package/bin/runners/runApprove.js +320 -0
  403. package/bin/runners/runAudit.js +692 -0
  404. package/bin/runners/runAuth.js +731 -0
  405. package/bin/runners/runCI.js +353 -0
  406. package/bin/runners/runCheckpoint.js +530 -0
  407. package/bin/runners/runClassify.js +928 -0
  408. package/bin/runners/runCleanup.js +343 -0
  409. package/bin/runners/runContext.d.ts +4 -0
  410. package/bin/runners/runContext.js +175 -0
  411. package/bin/runners/runDoctor.js +877 -0
  412. package/bin/runners/runEvidencePack.js +362 -0
  413. package/bin/runners/runFirewall.d.ts +5 -0
  414. package/bin/runners/runFirewall.js +134 -0
  415. package/bin/runners/runFirewallHook.d.ts +5 -0
  416. package/bin/runners/runFirewallHook.js +56 -0
  417. package/bin/runners/runFix.js +1355 -0
  418. package/bin/runners/runForge.js +451 -0
  419. package/bin/runners/runGuard.js +262 -0
  420. package/bin/runners/runInit.js +1927 -0
  421. package/bin/runners/runIntent.js +906 -0
  422. package/bin/runners/runKickoff.js +878 -0
  423. package/bin/runners/runLabs.js +424 -0
  424. package/bin/runners/runLaunch.js +2000 -0
  425. package/bin/runners/runLink.js +785 -0
  426. package/bin/runners/runMcp.js +1875 -0
  427. package/bin/runners/runPacks.js +2089 -0
  428. package/bin/runners/runPolish.d.ts +4 -0
  429. package/bin/runners/runPolish.js +390 -0
  430. package/bin/runners/runPromptFirewall.js +211 -0
  431. package/bin/runners/runProve.js +1411 -0
  432. package/bin/runners/runQuickstart.js +531 -0
  433. package/bin/runners/runReality.js +2260 -0
  434. package/bin/runners/runReport.js +726 -0
  435. package/bin/runners/runRuntime.js +110 -0
  436. package/bin/runners/runSafelist.js +1190 -0
  437. package/bin/runners/runScan.js +688 -0
  438. package/bin/runners/runShield.js +1282 -0
  439. package/bin/runners/runShip.js +1660 -0
  440. package/bin/runners/runTruth.d.ts +5 -0
  441. package/bin/runners/runTruth.js +101 -0
  442. package/bin/runners/runValidate.js +179 -0
  443. package/bin/runners/runWatch.js +478 -0
  444. package/bin/runners/utils.js +360 -0
  445. package/bin/scan.js +617 -0
  446. package/bin/vibecheck.js +1617 -0
  447. package/dist/guardrail/index.d.ts +2405 -0
  448. package/dist/guardrail/index.js +9747 -0
  449. package/dist/guardrail/index.js.map +1 -0
  450. package/dist/scanner/index.d.ts +282 -0
  451. package/dist/scanner/index.js +3395 -0
  452. package/dist/scanner/index.js.map +1 -0
  453. package/package.json +123 -104
  454. package/README.md +0 -491
  455. package/dist/index.js +0 -99711
  456. package/dist/index.js.map +0 -1
@@ -0,0 +1,2405 @@
1
+ /**
2
+ * Core types for Guardrail system
3
+ */
4
+ interface GuardrailConfig {
5
+ projectRoot: string;
6
+ settings: {
7
+ strictMode: boolean;
8
+ autoRefresh: boolean;
9
+ refreshInterval: number;
10
+ maxContextTokens: number;
11
+ };
12
+ scanners: ScannerConfig;
13
+ firewall: FirewallConfig;
14
+ docguard: DocGuardConfig;
15
+ forge: ForgeConfig;
16
+ }
17
+ interface ScannerConfig {
18
+ routes: {
19
+ enabled: boolean;
20
+ frameworks: string[];
21
+ patterns: string[];
22
+ };
23
+ env: {
24
+ enabled: boolean;
25
+ files: string[];
26
+ };
27
+ auth: {
28
+ enabled: boolean;
29
+ patterns: string[];
30
+ };
31
+ contracts: {
32
+ enabled: boolean;
33
+ sources: string[];
34
+ };
35
+ }
36
+ interface FirewallConfig {
37
+ enabled: boolean;
38
+ strictMode: boolean;
39
+ allowPartialMatches: boolean;
40
+ maxClaimsPerRequest: number;
41
+ blockOnViolation: boolean;
42
+ }
43
+ interface DocGuardConfig {
44
+ enabled: boolean;
45
+ similarityThreshold: number;
46
+ minAnchors: number;
47
+ maxFluffRatio: number;
48
+ docDirectories: string[];
49
+ ignorePatterns: string[];
50
+ strictMode: boolean;
51
+ }
52
+ interface ForgeConfig {
53
+ enabled: boolean;
54
+ autoGenerate: boolean;
55
+ tier: 'minimal' | 'standard' | 'extended' | 'comprehensive';
56
+ baselineSkills: {
57
+ enabled: boolean;
58
+ skills: string[];
59
+ };
60
+ platforms: ('cursor' | 'windsurf')[];
61
+ }
62
+ interface TruthpackData {
63
+ routes: RouteInfo[];
64
+ envVars: EnvVarInfo[];
65
+ authRules: AuthRule[];
66
+ contracts: ContractInfo[];
67
+ meta: TruthpackMeta;
68
+ }
69
+ interface TruthpackMeta {
70
+ version: string;
71
+ generatedAt: string;
72
+ hash: string;
73
+ scannerVersions: Record<string, string>;
74
+ summary: {
75
+ routes: number;
76
+ envVars: number;
77
+ authRules: number;
78
+ contracts: number;
79
+ };
80
+ }
81
+ interface RouteInfo {
82
+ path: string;
83
+ method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD';
84
+ handler: string;
85
+ file: string;
86
+ line: number;
87
+ parameters: RouteParameter[];
88
+ middleware: string[];
89
+ auth?: {
90
+ required: boolean;
91
+ roles?: string[];
92
+ };
93
+ }
94
+ interface RouteParameter {
95
+ name: string;
96
+ type: string;
97
+ required: boolean;
98
+ in?: 'path' | 'query' | 'body' | 'header';
99
+ }
100
+ interface EnvVarInfo {
101
+ name: string;
102
+ file: string;
103
+ line: number;
104
+ hasDefault: boolean;
105
+ defaultValue?: string;
106
+ description?: string;
107
+ required: boolean;
108
+ sensitive: boolean;
109
+ }
110
+ interface AuthRule {
111
+ name: string;
112
+ type: 'role' | 'permission' | 'middleware';
113
+ description?: string;
114
+ file: string;
115
+ line: number;
116
+ }
117
+ interface ContractInfo {
118
+ name: string;
119
+ type: 'interface' | 'type' | 'schema' | 'enum';
120
+ file: string;
121
+ line: number;
122
+ properties?: PropertyInfo[];
123
+ source: 'typescript' | 'zod' | 'openapi';
124
+ }
125
+ interface PropertyInfo {
126
+ name: string;
127
+ type: string;
128
+ required: boolean;
129
+ description?: string;
130
+ }
131
+ interface GeneratedRule {
132
+ id: string;
133
+ name: string;
134
+ category: RuleCategory;
135
+ description: string;
136
+ content: string;
137
+ priority: number;
138
+ impact: number;
139
+ globs?: string[];
140
+ alwaysApply: boolean;
141
+ }
142
+ type RuleCategory = 'anti-hallucination' | 'architecture' | 'security' | 'testing' | 'conventions' | 'documentation' | 'performance' | 'accessibility';
143
+ interface GeneratedSubagent {
144
+ id: string;
145
+ name: string;
146
+ description: string;
147
+ capabilities: string[];
148
+ content: string;
149
+ }
150
+ interface GeneratedHook {
151
+ id: string;
152
+ name: string;
153
+ trigger: 'pre-commit' | 'post-commit' | 'pre-push' | 'save' | 'generate';
154
+ description: string;
155
+ content: string;
156
+ }
157
+ interface GeneratedSkill {
158
+ id: string;
159
+ name: string;
160
+ description: string;
161
+ trigger: string;
162
+ content: string;
163
+ references?: string[];
164
+ }
165
+ interface ConventionRule {
166
+ category: string;
167
+ rules: string[];
168
+ }
169
+ interface PatternDefinition {
170
+ name: string;
171
+ category: string;
172
+ description: string;
173
+ example: string;
174
+ antiPatterns: string[];
175
+ }
176
+ interface DuplicateCheckResult {
177
+ isDuplicate: boolean;
178
+ similarity: number;
179
+ existingFile?: string;
180
+ existingContent?: string;
181
+ suggestion?: 'merge' | 'update' | 'skip';
182
+ }
183
+ interface DocGuardResult {
184
+ valid: boolean;
185
+ score: number;
186
+ issues: DocGuardIssue[];
187
+ anchors: string[];
188
+ slopPhrases: string[];
189
+ fluffRatio: number;
190
+ }
191
+ interface DocGuardIssue {
192
+ type: 'missing-anchor' | 'slop-phrase' | 'high-fluff' | 'no-example' | 'duplicate';
193
+ message: string;
194
+ line?: number;
195
+ suggestion?: string;
196
+ }
197
+ interface WatcherEvent {
198
+ type: 'add' | 'change' | 'unlink';
199
+ path: string;
200
+ timestamp: Date;
201
+ }
202
+ interface RefreshResult {
203
+ rulesUpdated: number;
204
+ rulesAdded: number;
205
+ rulesRemoved: number;
206
+ conventionsLearned: string[];
207
+ patternsDetected: string[];
208
+ duration: number;
209
+ }
210
+
211
+ /**
212
+ * Guardrail Scanners
213
+ *
214
+ * Scan the codebase to build the Truthpack - ground truth data
215
+ * that AI agents use to verify their claims.
216
+ */
217
+
218
+ declare class TruthpackScanner {
219
+ private projectRoot;
220
+ private config;
221
+ constructor(projectRoot: string, config: ScannerConfig);
222
+ scan(): Promise<TruthpackData>;
223
+ private scanRoutes;
224
+ private extractRoutes;
225
+ private extractHandler;
226
+ private extractRouteParams;
227
+ private extractMiddleware;
228
+ private detectAuthRequirement;
229
+ private filePathToApiRoute;
230
+ private scanEnvVars;
231
+ private isSensitiveEnvVar;
232
+ private scanAuth;
233
+ private scanContracts;
234
+ private computeHash;
235
+ }
236
+ declare function scanTruthpack(projectRoot: string, config: ScannerConfig): Promise<TruthpackData>;
237
+ declare function saveTruthpack(projectRoot: string, data: TruthpackData): Promise<void>;
238
+ declare function loadTruthpack(projectRoot: string): Promise<TruthpackData | null>;
239
+
240
+ /**
241
+ * Large Codebase Scanner
242
+ *
243
+ * Optimized scanner for handling codebases with 1,000,000+ lines of code.
244
+ * Features:
245
+ * - Chunked file processing with configurable batch sizes
246
+ * - Incremental scanning with file hash caching
247
+ * - Parallel processing using worker threads
248
+ * - Memory-efficient streaming for large files
249
+ * - Progress reporting for UI integration
250
+ */
251
+
252
+ interface LargeScannerConfig extends ScannerConfig {
253
+ largeCodebase?: {
254
+ enabled: boolean;
255
+ chunkSize: number;
256
+ maxConcurrency: number;
257
+ incrementalScan: boolean;
258
+ memoryLimit: number;
259
+ streamLargeFiles: boolean;
260
+ largeFileThreshold: number;
261
+ };
262
+ }
263
+ interface ScanProgress {
264
+ phase: 'discovery' | 'scanning' | 'processing' | 'finalizing';
265
+ totalFiles: number;
266
+ processedFiles: number;
267
+ currentFile?: string;
268
+ estimatedTimeRemaining?: number;
269
+ memoryUsage?: number;
270
+ errors: ScanError[];
271
+ }
272
+ interface ScanError {
273
+ file: string;
274
+ error: string;
275
+ recoverable: boolean;
276
+ }
277
+ interface FileCache {
278
+ hash: string;
279
+ lastModified: number;
280
+ routes: RouteInfo[];
281
+ contracts: ContractInfo[];
282
+ authRules: AuthRule[];
283
+ }
284
+ type ProgressCallback = (progress: ScanProgress) => void;
285
+ declare class LargeCodebaseScanner {
286
+ private projectRoot;
287
+ private config;
288
+ private cache;
289
+ private cacheDir;
290
+ private progress;
291
+ private progressCallback?;
292
+ private startTime;
293
+ constructor(projectRoot: string, config: LargeScannerConfig, progressCallback?: ProgressCallback);
294
+ private normalizeConfig;
295
+ scan(): Promise<TruthpackData>;
296
+ private discoverFiles;
297
+ private processFilesInChunks;
298
+ private processChunkWithConcurrency;
299
+ private processFile;
300
+ private readLargeFile;
301
+ private extractRoutes;
302
+ private extractContracts;
303
+ private extractAuthRules;
304
+ private getLineNumber;
305
+ private extractHandler;
306
+ private extractRouteParams;
307
+ private extractMiddleware;
308
+ private detectAuthRequirement;
309
+ private filePathToApiRoute;
310
+ private scanEnvVars;
311
+ private isSensitiveEnvVar;
312
+ private computeFileHash;
313
+ private computeHash;
314
+ private chunkArray;
315
+ private checkMemory;
316
+ private updateProgress;
317
+ private loadCache;
318
+ private saveCache;
319
+ }
320
+ declare function scanLargeCodebase(projectRoot: string, config: LargeScannerConfig, progressCallback?: ProgressCallback): Promise<TruthpackData>;
321
+ declare function estimateCodebaseSize(projectRoot: string): Promise<{
322
+ fileCount: number;
323
+ estimatedLines: number;
324
+ isLarge: boolean;
325
+ recommendedChunkSize: number;
326
+ }>;
327
+
328
+ /**
329
+ * Guardrail Forge
330
+ *
331
+ * Auto-generates MDC rules, subagents, hooks, and skills based on
332
+ * codebase analysis. Learns project conventions and creates tailored
333
+ * guardrails to prevent AI drift.
334
+ */
335
+
336
+ interface ForgeResult {
337
+ rules: GeneratedRule[];
338
+ subagents: GeneratedSubagent[];
339
+ hooks: GeneratedHook[];
340
+ skills: GeneratedSkill[];
341
+ conventions: ConventionRule[];
342
+ patterns: PatternDefinition[];
343
+ }
344
+ declare class GuardrailForge {
345
+ private projectRoot;
346
+ private config;
347
+ private truthpack;
348
+ constructor(projectRoot: string, config: GuardrailConfig);
349
+ forge(): Promise<ForgeResult>;
350
+ private analyzeProject;
351
+ private detectFramework;
352
+ private detectArchitecture;
353
+ private hasDocumentation;
354
+ private learnConventions;
355
+ private analyzeNamingConventions;
356
+ private analyzeImportConventions;
357
+ private analyzeErrorHandling;
358
+ private detectPatterns;
359
+ private generateRules;
360
+ private createAntiHallucinationRule;
361
+ private createArchitectureRule;
362
+ private generateDirectoryGuidelines;
363
+ private createNextJsRule;
364
+ private createReactRule;
365
+ private createTypeScriptRule;
366
+ private createTestingRule;
367
+ private createApiRule;
368
+ private createAuthRule;
369
+ private generateSubagents;
370
+ private generateHooks;
371
+ private generateSkills;
372
+ private writeArtifacts;
373
+ private writeCursorRules;
374
+ }
375
+ declare function forge(projectRoot: string, config: GuardrailConfig): Promise<ForgeResult>;
376
+
377
+ /**
378
+ * Task Tracker - Ensures AI agents document remaining work
379
+ *
380
+ * WHAT NOBODY ELSE IS DOING:
381
+ * - Forces AI to document what's remaining before stopping
382
+ * - Creates checkpoints for task resumption
383
+ * - Tracks progress across sessions
384
+ * - Prevents abandoned incomplete work
385
+ */
386
+ interface TaskStep {
387
+ id: string;
388
+ description: string;
389
+ status: 'pending' | 'in_progress' | 'completed' | 'blocked' | 'skipped';
390
+ startedAt?: string;
391
+ completedAt?: string;
392
+ notes?: string;
393
+ blockedReason?: string;
394
+ filesModified?: string[];
395
+ dependencies?: string[];
396
+ }
397
+ interface TaskCheckpoint {
398
+ id: string;
399
+ taskId: string;
400
+ timestamp: string;
401
+ currentStep: number;
402
+ totalSteps: number;
403
+ completedSteps: string[];
404
+ remainingSteps: TaskStep[];
405
+ contextSnapshot: ContextSnapshot;
406
+ resumptionNotes: string;
407
+ canResume: boolean;
408
+ }
409
+ interface ContextSnapshot {
410
+ openFiles: string[];
411
+ lastModifiedFile?: string;
412
+ cursorPosition?: {
413
+ file: string;
414
+ line: number;
415
+ };
416
+ relevantVariables?: Record<string, string>;
417
+ environmentState?: Record<string, string>;
418
+ }
419
+ interface Task {
420
+ id: string;
421
+ title: string;
422
+ description: string;
423
+ createdAt: string;
424
+ updatedAt: string;
425
+ status: 'active' | 'paused' | 'completed' | 'abandoned';
426
+ steps: TaskStep[];
427
+ checkpoints: TaskCheckpoint[];
428
+ totalEstimatedSteps: number;
429
+ completionPercentage: number;
430
+ lastActiveAgent?: string;
431
+ tags?: string[];
432
+ }
433
+ interface TaskSummary {
434
+ completed: string[];
435
+ inProgress: string[];
436
+ remaining: string[];
437
+ blocked: string[];
438
+ estimatedRemainingWork: string;
439
+ nextSteps: string[];
440
+ warnings: string[];
441
+ }
442
+ interface StopValidation {
443
+ canStop: boolean;
444
+ mustDocument: string[];
445
+ warnings: string[];
446
+ suggestedCheckpoint: Partial<TaskCheckpoint>;
447
+ }
448
+ declare class TaskTracker {
449
+ private workspaceRoot;
450
+ private tasksPath;
451
+ private currentTask;
452
+ private tasks;
453
+ constructor(workspaceRoot: string);
454
+ /**
455
+ * Start a new task
456
+ */
457
+ startTask(title: string, description: string, estimatedSteps?: string[]): Task;
458
+ /**
459
+ * Add steps to current task
460
+ */
461
+ addSteps(steps: string[]): void;
462
+ /**
463
+ * Update step status
464
+ */
465
+ updateStep(stepId: string, status: TaskStep['status'], notes?: string): void;
466
+ /**
467
+ * Mark current step as in progress
468
+ */
469
+ startStep(stepId: string): void;
470
+ /**
471
+ * Complete current step
472
+ */
473
+ completeStep(stepId: string, notes?: string, filesModified?: string[]): void;
474
+ /**
475
+ * Mark step as blocked
476
+ */
477
+ blockStep(stepId: string, reason: string): void;
478
+ /**
479
+ * CRITICAL: Validate if agent can stop working
480
+ * This is the key feature - prevents stopping without documenting remaining work
481
+ */
482
+ validateStop(): StopValidation;
483
+ /**
484
+ * Create a checkpoint before stopping
485
+ * REQUIRED if task is incomplete
486
+ */
487
+ createCheckpoint(resumptionNotes: string, contextSnapshot?: Partial<ContextSnapshot>): TaskCheckpoint;
488
+ /**
489
+ * Generate a task summary for handoff or resumption
490
+ */
491
+ generateSummary(): TaskSummary;
492
+ /**
493
+ * Generate markdown summary for documentation
494
+ */
495
+ generateMarkdownSummary(): string;
496
+ /**
497
+ * Resume from a checkpoint
498
+ */
499
+ resumeFromCheckpoint(checkpointId: string): Task | null;
500
+ /**
501
+ * Resume the most recent paused task
502
+ */
503
+ resumeLatest(): Task | null;
504
+ /**
505
+ * Complete the current task
506
+ */
507
+ completeTask(): void;
508
+ /**
509
+ * Abandon task (with documentation)
510
+ */
511
+ abandonTask(reason: string): TaskCheckpoint;
512
+ /**
513
+ * Get current task
514
+ */
515
+ getCurrentTask(): Task | null;
516
+ /**
517
+ * Get all tasks
518
+ */
519
+ getAllTasks(): Task[];
520
+ /**
521
+ * Get paused tasks
522
+ */
523
+ getPausedTasks(): Task[];
524
+ /**
525
+ * Load task by ID
526
+ */
527
+ loadTask(taskId: string): Task | null;
528
+ private updateCompletionPercentage;
529
+ private loadTasks;
530
+ private saveTasks;
531
+ }
532
+ /**
533
+ * Create task tracker instance
534
+ */
535
+ declare function createTaskTracker(workspaceRoot: string): TaskTracker;
536
+
537
+ /**
538
+ * Completion Guard - Ensures tasks are properly completed
539
+ *
540
+ * WHAT NOBODY ELSE IS DOING:
541
+ * - Enforces documentation of remaining work before stopping
542
+ * - Validates task completion criteria
543
+ * - Generates handoff documentation automatically
544
+ * - Prevents silent task abandonment
545
+ */
546
+
547
+ interface CompletionCriteria {
548
+ requireAllStepsComplete: boolean;
549
+ requireNoBlockedSteps: boolean;
550
+ requireResumptionNotes: boolean;
551
+ minCompletionPercentage: number;
552
+ requireFilesDocumented: boolean;
553
+ requireNextStepsDocumented: boolean;
554
+ }
555
+ interface CompletionResult {
556
+ canComplete: boolean;
557
+ violations: string[];
558
+ suggestions: string[];
559
+ requiredActions: RequiredAction[];
560
+ handoffDocument?: string;
561
+ }
562
+ interface RequiredAction {
563
+ type: 'document' | 'complete' | 'unblock' | 'checkpoint';
564
+ description: string;
565
+ priority: 'critical' | 'high' | 'medium' | 'low';
566
+ targetStepId?: string;
567
+ }
568
+ interface HandoffDocument {
569
+ taskTitle: string;
570
+ summary: string;
571
+ completedWork: string[];
572
+ remainingWork: string[];
573
+ blockedItems: string[];
574
+ contextNotes: string;
575
+ resumptionInstructions: string;
576
+ filesModified: string[];
577
+ estimatedRemainingTime: string;
578
+ createdAt: string;
579
+ createdBy: string;
580
+ }
581
+ declare class CompletionGuard {
582
+ private workspaceRoot;
583
+ private taskTracker;
584
+ private criteria;
585
+ private handoffPath;
586
+ constructor(workspaceRoot: string, taskTracker: TaskTracker, criteria?: Partial<CompletionCriteria>);
587
+ /**
588
+ * Validate if work can be stopped
589
+ * This is the CRITICAL check before any AI agent stops working
590
+ */
591
+ validateCompletion(): CompletionResult;
592
+ /**
593
+ * Force create a handoff document before stopping
594
+ */
595
+ createHandoff(contextNotes: string, resumptionInstructions: string, agentId?: string): HandoffDocument;
596
+ /**
597
+ * Generate handoff documentation markdown
598
+ */
599
+ generateHandoffDocument(task: Task, summary: TaskSummary): string;
600
+ /**
601
+ * Validate and enforce completion with automatic handoff
602
+ */
603
+ enforceCompletion(contextNotes?: string, agentId?: string): {
604
+ allowed: boolean;
605
+ handoff?: HandoffDocument;
606
+ message: string;
607
+ };
608
+ /**
609
+ * Generate automatic resumption instructions
610
+ */
611
+ private generateResumptionInstructions;
612
+ /**
613
+ * Save handoff document to disk
614
+ */
615
+ private saveHandoff;
616
+ /**
617
+ * Get all handoff documents
618
+ */
619
+ getHandoffs(): HandoffDocument[];
620
+ /**
621
+ * Get latest handoff for a task
622
+ */
623
+ getLatestHandoff(taskId: string): HandoffDocument | null;
624
+ /**
625
+ * Update completion criteria
626
+ */
627
+ updateCriteria(criteria: Partial<CompletionCriteria>): void;
628
+ /**
629
+ * Get current criteria
630
+ */
631
+ getCriteria(): CompletionCriteria;
632
+ }
633
+ /**
634
+ * Create completion guard instance
635
+ */
636
+ declare function createCompletionGuard(workspaceRoot: string, taskTracker: TaskTracker, criteria?: Partial<CompletionCriteria>): CompletionGuard;
637
+
638
+ /**
639
+ * Guardrail DocGuard
640
+ *
641
+ * Documentation quality control system that prevents drift, detects slop,
642
+ * ensures documentation stays grounded in reality, and tracks task progress.
643
+ */
644
+
645
+ declare class DocGuard {
646
+ private projectRoot;
647
+ private config;
648
+ private documentRegistry;
649
+ constructor(projectRoot: string, config: DocGuardConfig);
650
+ /**
651
+ * Evaluate a document for quality
652
+ */
653
+ evaluate(content: string, filePath?: string): Promise<DocGuardResult>;
654
+ /**
655
+ * Quick slop check - fast validation
656
+ */
657
+ quickCheck(content: string): {
658
+ hasSop: boolean;
659
+ phrases: string[];
660
+ };
661
+ /**
662
+ * Check for duplicate content
663
+ */
664
+ checkDuplicate(content: string, filePath: string): Promise<DuplicateCheckResult>;
665
+ /**
666
+ * Scan all documentation and update registry
667
+ */
668
+ scanDocuments(): Promise<void>;
669
+ /**
670
+ * Find canonical document for a topic
671
+ */
672
+ findCanonical(topic: string): Promise<string | null>;
673
+ /**
674
+ * Get suggestion for where to place content
675
+ */
676
+ suggestLocation(topic: string): string;
677
+ /**
678
+ * Get registry statistics
679
+ */
680
+ getStats(): {
681
+ totalDocs: number;
682
+ avgScore: number;
683
+ duplicates: number;
684
+ };
685
+ private loadDocumentRegistry;
686
+ private computeSimHash;
687
+ }
688
+ /**
689
+ * Create a DocGuard instance
690
+ */
691
+ declare function createDocGuard(projectRoot: string, config: DocGuardConfig): DocGuard;
692
+ /**
693
+ * Quick evaluation of document content
694
+ */
695
+ declare function evaluateDoc(content: string, projectRoot: string, config: DocGuardConfig): Promise<DocGuardResult>;
696
+ /**
697
+ * Check if content should be blocked due to quality issues
698
+ */
699
+ declare function shouldBlock(result: DocGuardResult, strictMode: boolean): boolean;
700
+
701
+ /**
702
+ * Guardrail Watcher
703
+ *
704
+ * Continuously monitors the codebase for changes and triggers
705
+ * automatic re-analysis to keep guardrails up-to-date.
706
+ */
707
+
708
+ interface WatcherOptions {
709
+ projectRoot: string;
710
+ config: GuardrailConfig;
711
+ onRefresh?: (result: RefreshResult) => void;
712
+ onError?: (error: Error) => void;
713
+ debounceMs?: number;
714
+ }
715
+ declare class GuardrailWatcher {
716
+ private projectRoot;
717
+ private config;
718
+ private watcher;
719
+ private debounceTimer;
720
+ private debounceMs;
721
+ private pendingChanges;
722
+ private lastTruthpackHash;
723
+ private isRefreshing;
724
+ private onRefresh?;
725
+ private onError?;
726
+ constructor(options: WatcherOptions);
727
+ /**
728
+ * Start watching for changes
729
+ */
730
+ start(): Promise<void>;
731
+ /**
732
+ * Stop watching
733
+ */
734
+ stop(): Promise<void>;
735
+ /**
736
+ * Force a refresh now
737
+ */
738
+ forceRefresh(): Promise<RefreshResult>;
739
+ private handleChange;
740
+ private processChanges;
741
+ private categorizeChanges;
742
+ private doRefresh;
743
+ private refreshDocRules;
744
+ private schedulePeriodicRefresh;
745
+ private handleError;
746
+ }
747
+ /**
748
+ * Create and start a watcher
749
+ */
750
+ declare function startWatcher(options: WatcherOptions): Promise<GuardrailWatcher>;
751
+ /**
752
+ * Quick one-time refresh
753
+ */
754
+ declare function refreshGuardrails(projectRoot: string, config: GuardrailConfig): Promise<RefreshResult>;
755
+
756
+ /**
757
+ * Anti-Hallucination Type Definitions
758
+ */
759
+ interface CodeSuggestion {
760
+ id: string;
761
+ code: string;
762
+ language: string;
763
+ filePath?: string;
764
+ lineRange?: {
765
+ start: number;
766
+ end: number;
767
+ };
768
+ source: 'ai' | 'user' | 'template';
769
+ timestamp: number;
770
+ }
771
+ interface VerificationResult$1 {
772
+ valid: boolean;
773
+ confidence: number;
774
+ issues: VerificationIssue$1[];
775
+ suggestions: string[];
776
+ metrics: VerificationMetrics;
777
+ }
778
+ interface VerificationIssue$1 {
779
+ type: HallucinationType;
780
+ severity: 'error' | 'warning' | 'info';
781
+ message: string;
782
+ line?: number;
783
+ column?: number;
784
+ evidence?: string;
785
+ fix?: string;
786
+ }
787
+ type HallucinationType = 'fake_import' | 'invented_api' | 'wrong_signature' | 'type_mismatch' | 'nonexistent_file' | 'deprecated_api' | 'pattern_violation' | 'env_hallucination' | 'route_mismatch' | 'schema_violation' | 'security_antipattern' | 'stale_reference';
788
+ interface VerificationMetrics {
789
+ importVerification: number;
790
+ apiVerification: number;
791
+ typeVerification: number;
792
+ patternAlignment: number;
793
+ overallConfidence: number;
794
+ }
795
+ interface HallucinationFingerprint {
796
+ id: string;
797
+ pattern: string;
798
+ type: HallucinationType;
799
+ description: string;
800
+ examples: string[];
801
+ frequency: number;
802
+ falsePositiveRate: number;
803
+ }
804
+ interface ConfidenceFactors {
805
+ importFamiliarity: number;
806
+ patternSimilarity: number;
807
+ typeConsistency: number;
808
+ apiAccuracy: number;
809
+ contextRelevance: number;
810
+ historicalAccuracy: number;
811
+ }
812
+ interface PatternSignature {
813
+ id: string;
814
+ name: string;
815
+ category: 'naming' | 'structure' | 'import' | 'error_handling' | 'async' | 'testing' | 'api';
816
+ pattern: string;
817
+ examples: string[];
818
+ frequency: number;
819
+ lastSeen: string;
820
+ }
821
+ interface LearningFeedback {
822
+ suggestionId: string;
823
+ accepted: boolean;
824
+ editedBefore: boolean;
825
+ editDistance?: number;
826
+ timeToDecision: number;
827
+ context: string;
828
+ reason?: string;
829
+ }
830
+ interface ContextChunk {
831
+ id: string;
832
+ filePath: string;
833
+ content: string;
834
+ startLine: number;
835
+ endLine: number;
836
+ relevanceScore: number;
837
+ tokens: number;
838
+ type: 'definition' | 'usage' | 'import' | 'type' | 'test' | 'doc' | 'config';
839
+ }
840
+ interface OptimizedContext {
841
+ chunks: ContextChunk[];
842
+ totalTokens: number;
843
+ coverage: ContextCoverage;
844
+ strategy: string;
845
+ }
846
+ interface ContextCoverage {
847
+ definitions: number;
848
+ types: number;
849
+ usages: number;
850
+ tests: number;
851
+ }
852
+ interface CodebaseKnowledge {
853
+ imports: Map<string, ImportInfo>;
854
+ exports: Map<string, ExportInfo>;
855
+ types: Map<string, TypeInfo>;
856
+ functions: Map<string, AHFunctionInfo>;
857
+ patterns: PatternSignature[];
858
+ envVars: Set<string>;
859
+ routes: AHRouteInfo[];
860
+ }
861
+ interface ImportInfo {
862
+ source: string;
863
+ isLocal: boolean;
864
+ isNodeModule: boolean;
865
+ exports: string[];
866
+ usageCount: number;
867
+ lastUsed: string;
868
+ }
869
+ interface ExportInfo {
870
+ name: string;
871
+ type: 'function' | 'class' | 'const' | 'type' | 'interface' | 'enum';
872
+ filePath: string;
873
+ signature?: string;
874
+ usedBy: string[];
875
+ }
876
+ interface TypeInfo {
877
+ name: string;
878
+ filePath: string;
879
+ kind: 'interface' | 'type' | 'class' | 'enum';
880
+ properties?: AHPropertyInfo[];
881
+ methods?: AHMethodInfo[];
882
+ }
883
+ interface AHPropertyInfo {
884
+ name: string;
885
+ type: string;
886
+ optional: boolean;
887
+ }
888
+ interface AHMethodInfo {
889
+ name: string;
890
+ parameters: AHParameterInfo[];
891
+ returnType: string;
892
+ }
893
+ interface AHParameterInfo {
894
+ name: string;
895
+ type: string;
896
+ optional: boolean;
897
+ defaultValue?: string;
898
+ }
899
+ interface AHFunctionInfo {
900
+ name: string;
901
+ filePath: string;
902
+ parameters: AHParameterInfo[];
903
+ returnType: string;
904
+ isAsync: boolean;
905
+ isExported: boolean;
906
+ usageCount: number;
907
+ }
908
+ interface AHRouteInfo {
909
+ method: string;
910
+ path: string;
911
+ handler: string;
912
+ filePath: string;
913
+ parameters?: AHParameterInfo[];
914
+ responseType?: string;
915
+ }
916
+
917
+ /**
918
+ * Semantic Verification Engine
919
+ *
920
+ * WHAT NOBODY ELSE IS DOING:
921
+ * - Verifies AI suggestions against ACTUAL codebase state
922
+ * - Cross-references imports with real node_modules and local files
923
+ * - Validates function signatures against real definitions
924
+ * - Checks type compatibility with actual TypeScript types
925
+ */
926
+
927
+ declare class SemanticVerifier {
928
+ private workspaceRoot;
929
+ private knowledge;
930
+ private nodeModulesCache;
931
+ constructor(workspaceRoot: string);
932
+ private initializeKnowledge;
933
+ /**
934
+ * Main verification entry point
935
+ */
936
+ verify(suggestion: CodeSuggestion): Promise<VerificationResult$1>;
937
+ /**
938
+ * Extract import statements from code
939
+ */
940
+ private extractImports;
941
+ /**
942
+ * Extract function calls from code
943
+ */
944
+ private extractFunctionCalls;
945
+ /**
946
+ * Extract type references from code
947
+ */
948
+ private extractTypeReferences;
949
+ /**
950
+ * Extract environment variable references
951
+ */
952
+ private extractEnvReferences;
953
+ /**
954
+ * Verify imports against actual node_modules and local files
955
+ */
956
+ private verifyImports;
957
+ /**
958
+ * Verify API/function calls against known signatures
959
+ */
960
+ private verifyAPICalls;
961
+ /**
962
+ * Verify type references against defined types
963
+ */
964
+ private verifyTypes;
965
+ /**
966
+ * Verify environment variable references
967
+ */
968
+ private verifyEnvVars;
969
+ /**
970
+ * Resolve local import path
971
+ */
972
+ private resolveLocalImport;
973
+ /**
974
+ * Extract exports from a file
975
+ */
976
+ private extractExportsFromFile;
977
+ /**
978
+ * Check if a node module exists
979
+ */
980
+ private checkNodeModule;
981
+ /**
982
+ * Verify module exports (basic check for popular packages)
983
+ */
984
+ private verifyModuleExports;
985
+ /**
986
+ * Check for common API mistakes
987
+ */
988
+ private checkCommonAPIMistakes;
989
+ /**
990
+ * Load known environment variables from .env files
991
+ */
992
+ private loadKnownEnvVars;
993
+ /**
994
+ * Calculate verification metrics
995
+ */
996
+ private calculateMetrics;
997
+ /**
998
+ * Generate fix suggestions based on issues
999
+ */
1000
+ private generateFixSuggestions;
1001
+ /**
1002
+ * Update knowledge base with new information
1003
+ */
1004
+ updateKnowledge(knowledge: Partial<CodebaseKnowledge>): void;
1005
+ }
1006
+
1007
+ /**
1008
+ * Hallucination Fingerprint Detector
1009
+ *
1010
+ * WHAT NOBODY ELSE IS DOING:
1011
+ * - Detects common hallucination patterns before they cause issues
1012
+ * - Maintains a fingerprint database of known AI mistakes
1013
+ * - Uses pattern matching to catch fake packages, invented APIs
1014
+ * - Learns new patterns from user feedback
1015
+ */
1016
+
1017
+ interface DetectionResult {
1018
+ detected: boolean;
1019
+ fingerprints: HallucinationFingerprint[];
1020
+ issues: VerificationIssue$1[];
1021
+ riskScore: number;
1022
+ }
1023
+ declare class HallucinationDetector {
1024
+ private workspaceRoot;
1025
+ private fingerprints;
1026
+ private customFingerprints;
1027
+ private fingerprintPath;
1028
+ constructor(workspaceRoot: string);
1029
+ /**
1030
+ * Initialize built-in hallucination fingerprints
1031
+ * These are common patterns that AI models frequently get wrong
1032
+ */
1033
+ private initializeBuiltInFingerprints;
1034
+ /**
1035
+ * Load custom fingerprints from project
1036
+ */
1037
+ private loadCustomFingerprints;
1038
+ /**
1039
+ * Save custom fingerprints
1040
+ */
1041
+ private saveCustomFingerprints;
1042
+ /**
1043
+ * Detect hallucinations in code
1044
+ */
1045
+ detect(code: string): DetectionResult;
1046
+ /**
1047
+ * Detect hallucinations that require context
1048
+ */
1049
+ private detectContextualHallucinations;
1050
+ /**
1051
+ * Get severity based on fingerprint characteristics
1052
+ */
1053
+ private getSeverity;
1054
+ /**
1055
+ * Get fix suggestion for a detected fingerprint
1056
+ */
1057
+ private getFix;
1058
+ /**
1059
+ * Add a new fingerprint learned from user feedback
1060
+ */
1061
+ addFingerprint(fingerprint: Omit<HallucinationFingerprint, 'id'>): void;
1062
+ /**
1063
+ * Update fingerprint frequency based on detection
1064
+ */
1065
+ updateFrequency(fingerprintId: string, detected: boolean): void;
1066
+ /**
1067
+ * Get all fingerprints for analysis
1068
+ */
1069
+ getAllFingerprints(): HallucinationFingerprint[];
1070
+ /**
1071
+ * Get high-risk fingerprints
1072
+ */
1073
+ getHighRiskFingerprints(): HallucinationFingerprint[];
1074
+ }
1075
+
1076
+ /**
1077
+ * Confidence Scoring System
1078
+ *
1079
+ * WHAT NOBODY ELSE IS DOING:
1080
+ * - Multi-dimensional confidence scoring based on codebase familiarity
1081
+ * - Historical accuracy tracking per code pattern type
1082
+ * - Weighted scoring based on context relevance
1083
+ * - Adaptive thresholds that learn from feedback
1084
+ */
1085
+
1086
+ interface ConfidenceScore {
1087
+ overall: number;
1088
+ factors: ConfidenceFactors;
1089
+ grade: 'A' | 'B' | 'C' | 'D' | 'F';
1090
+ recommendation: 'accept' | 'review' | 'reject';
1091
+ reasoning: string[];
1092
+ }
1093
+ interface HistoricalAccuracy {
1094
+ category: string;
1095
+ totalSuggestions: number;
1096
+ accepted: number;
1097
+ acceptedWithEdits: number;
1098
+ rejected: number;
1099
+ averageEditDistance: number;
1100
+ lastUpdated: string;
1101
+ }
1102
+ declare class ConfidenceScorer {
1103
+ private workspaceRoot;
1104
+ private knowledge;
1105
+ private historicalAccuracy;
1106
+ private historyPath;
1107
+ private acceptThreshold;
1108
+ private reviewThreshold;
1109
+ constructor(workspaceRoot: string);
1110
+ /**
1111
+ * Calculate confidence score for a suggestion
1112
+ */
1113
+ score(suggestion: CodeSuggestion, knowledge?: CodebaseKnowledge): ConfidenceScore;
1114
+ /**
1115
+ * Calculate individual confidence factors
1116
+ */
1117
+ private calculateFactors;
1118
+ /**
1119
+ * Calculate how familiar the imports are to the codebase
1120
+ */
1121
+ private calculateImportFamiliarity;
1122
+ /**
1123
+ * Calculate pattern similarity to existing codebase
1124
+ */
1125
+ private calculatePatternSimilarity;
1126
+ /**
1127
+ * Calculate type consistency with codebase types
1128
+ */
1129
+ private calculateTypeConsistency;
1130
+ /**
1131
+ * Calculate API accuracy based on known function signatures
1132
+ */
1133
+ private calculateAPIAccuracy;
1134
+ /**
1135
+ * Calculate context relevance
1136
+ */
1137
+ private calculateContextRelevance;
1138
+ /**
1139
+ * Calculate based on historical accuracy for similar code
1140
+ */
1141
+ private calculateHistoricalAccuracy;
1142
+ /**
1143
+ * Calculate overall confidence score
1144
+ */
1145
+ private calculateOverall;
1146
+ /**
1147
+ * Calculate letter grade
1148
+ */
1149
+ private calculateGrade;
1150
+ /**
1151
+ * Get recommendation based on score and factors
1152
+ */
1153
+ private getRecommendation;
1154
+ /**
1155
+ * Generate human-readable reasoning
1156
+ */
1157
+ private generateReasoning;
1158
+ /**
1159
+ * Record feedback to improve future scoring
1160
+ */
1161
+ recordFeedback(suggestion: CodeSuggestion, accepted: boolean, edited: boolean, editDistance?: number): void;
1162
+ /**
1163
+ * Adapt thresholds based on accumulated feedback
1164
+ */
1165
+ private adaptThresholds;
1166
+ /**
1167
+ * Helper methods
1168
+ */
1169
+ private extractImports;
1170
+ private extractTypeReferences;
1171
+ private extractFunctionCalls;
1172
+ private categorizeCode;
1173
+ private isCommonPackage;
1174
+ private isPrimitiveType;
1175
+ private isBuiltInType;
1176
+ private isBuiltInFunction;
1177
+ private loadHistory;
1178
+ private saveHistory;
1179
+ /**
1180
+ * Update codebase knowledge
1181
+ */
1182
+ updateKnowledge(knowledge: CodebaseKnowledge): void;
1183
+ /**
1184
+ * Get current thresholds
1185
+ */
1186
+ getThresholds(): {
1187
+ accept: number;
1188
+ review: number;
1189
+ };
1190
+ /**
1191
+ * Get historical accuracy stats
1192
+ */
1193
+ getStats(): {
1194
+ categories: HistoricalAccuracy[];
1195
+ overall: {
1196
+ accepted: number;
1197
+ rejected: number;
1198
+ total: number;
1199
+ };
1200
+ };
1201
+ }
1202
+
1203
+ /**
1204
+ * Pattern Learning Engine
1205
+ *
1206
+ * WHAT NOBODY ELSE IS DOING:
1207
+ * - Learns coding patterns from user accept/reject decisions
1208
+ * - Builds a personalized model of what "good code" looks like
1209
+ * - Identifies anti-patterns from rejected suggestions
1210
+ * - Continuously improves pattern matching over time
1211
+ */
1212
+
1213
+ interface LearnedPattern {
1214
+ id: string;
1215
+ pattern: string;
1216
+ type: 'positive' | 'negative';
1217
+ category: PatternSignature['category'];
1218
+ confidence: number;
1219
+ examples: string[];
1220
+ frequency: number;
1221
+ acceptRate: number;
1222
+ rejectRate: number;
1223
+ lastSeen: string;
1224
+ }
1225
+ interface LearningStats {
1226
+ totalFeedback: number;
1227
+ patternsLearned: number;
1228
+ positivePatterns: number;
1229
+ negativePatterns: number;
1230
+ accuracyImprovement: number;
1231
+ }
1232
+ declare class PatternLearner {
1233
+ private workspaceRoot;
1234
+ private patterns;
1235
+ private feedbackHistory;
1236
+ private patternsPath;
1237
+ private minFrequencyForPattern;
1238
+ constructor(workspaceRoot: string);
1239
+ /**
1240
+ * Record feedback and learn from it
1241
+ */
1242
+ learn(feedback: LearningFeedback): void;
1243
+ /**
1244
+ * Extract patterns from code
1245
+ */
1246
+ private extractPatterns;
1247
+ /**
1248
+ * Extract API usage patterns
1249
+ */
1250
+ private extractAPIPatterns;
1251
+ /**
1252
+ * Extract naming convention patterns
1253
+ */
1254
+ private extractNamingPatterns;
1255
+ /**
1256
+ * Extract code structure patterns
1257
+ */
1258
+ private extractStructurePatterns;
1259
+ /**
1260
+ * Extract import patterns
1261
+ */
1262
+ private extractImportPatterns;
1263
+ /**
1264
+ * Extract error handling patterns
1265
+ */
1266
+ private extractErrorPatterns;
1267
+ /**
1268
+ * Extract async patterns
1269
+ */
1270
+ private extractAsyncPatterns;
1271
+ /**
1272
+ * Extract testing patterns
1273
+ */
1274
+ private extractTestingPatterns;
1275
+ /**
1276
+ * Update or create a pattern based on feedback
1277
+ */
1278
+ private updatePattern;
1279
+ /**
1280
+ * Prune low-value patterns
1281
+ */
1282
+ private prunePatterns;
1283
+ /**
1284
+ * Score a suggestion based on learned patterns
1285
+ */
1286
+ scorePatterns(suggestion: CodeSuggestion): {
1287
+ score: number;
1288
+ matchedPatterns: LearnedPattern[];
1289
+ };
1290
+ /**
1291
+ * Get suggestions for improving code based on learned patterns
1292
+ */
1293
+ getSuggestions(code: string): string[];
1294
+ /**
1295
+ * Get learning statistics
1296
+ */
1297
+ getStats(): LearningStats;
1298
+ /**
1299
+ * Get all learned patterns
1300
+ */
1301
+ getPatterns(): LearnedPattern[];
1302
+ /**
1303
+ * Get positive patterns (good patterns to follow)
1304
+ */
1305
+ getPositivePatterns(): LearnedPattern[];
1306
+ /**
1307
+ * Get negative patterns (anti-patterns to avoid)
1308
+ */
1309
+ getNegativePatterns(): LearnedPattern[];
1310
+ /**
1311
+ * Export patterns for backup or sharing
1312
+ */
1313
+ exportPatterns(): string;
1314
+ /**
1315
+ * Import patterns from backup
1316
+ */
1317
+ importPatterns(data: string): void;
1318
+ private loadPatterns;
1319
+ private savePatterns;
1320
+ }
1321
+
1322
+ /**
1323
+ * Context Window Optimizer
1324
+ *
1325
+ * WHAT NOBODY ELSE IS DOING:
1326
+ * - Smart context selection that maximizes relevant code in limited token budget
1327
+ * - Prioritizes definitions, types, and usage patterns that matter
1328
+ * - Uses semantic similarity and dependency graphs
1329
+ * - Adaptive chunking based on code structure
1330
+ */
1331
+
1332
+ interface ContextRequest {
1333
+ targetFile: string;
1334
+ targetLine?: number;
1335
+ intent: string;
1336
+ maxTokens: number;
1337
+ preferredTypes?: ContextChunk['type'][];
1338
+ }
1339
+ declare class ContextOptimizer {
1340
+ private workspaceRoot;
1341
+ private knowledge;
1342
+ private fileAnalysisCache;
1343
+ private avgCharsPerToken;
1344
+ constructor(workspaceRoot: string);
1345
+ /**
1346
+ * Optimize context selection for a request
1347
+ */
1348
+ optimize(request: ContextRequest): Promise<OptimizedContext>;
1349
+ /**
1350
+ * Analyze a file for imports, exports, types, functions
1351
+ */
1352
+ private analyzeFile;
1353
+ /**
1354
+ * Build candidate chunks with relevance scores
1355
+ */
1356
+ private buildCandidates;
1357
+ /**
1358
+ * Chunk a file into semantic segments
1359
+ */
1360
+ private chunkFile;
1361
+ /**
1362
+ * Create a context chunk
1363
+ */
1364
+ private createChunk;
1365
+ /**
1366
+ * Score chunk relevance based on multiple factors
1367
+ */
1368
+ private scoreRelevance;
1369
+ /**
1370
+ * Greedy selection with diversity
1371
+ */
1372
+ private greedySelect;
1373
+ /**
1374
+ * Calculate context coverage metrics
1375
+ */
1376
+ private calculateCoverage;
1377
+ /**
1378
+ * Describe the optimization strategy used
1379
+ */
1380
+ private describeStrategy;
1381
+ /**
1382
+ * Helper: Extract imports from content
1383
+ */
1384
+ private extractImports;
1385
+ /**
1386
+ * Helper: Extract exports from content
1387
+ */
1388
+ private extractExports;
1389
+ /**
1390
+ * Helper: Extract type references
1391
+ */
1392
+ private extractTypes;
1393
+ /**
1394
+ * Helper: Extract function names
1395
+ */
1396
+ private extractFunctions;
1397
+ /**
1398
+ * Find files containing type definitions
1399
+ */
1400
+ private findTypeFiles;
1401
+ /**
1402
+ * Find test file for a source file
1403
+ */
1404
+ private findTestFile;
1405
+ /**
1406
+ * Find files that import the target file
1407
+ */
1408
+ private findUsageFiles;
1409
+ /**
1410
+ * Get config file chunks
1411
+ */
1412
+ private getConfigChunks;
1413
+ /**
1414
+ * Update codebase knowledge
1415
+ */
1416
+ updateKnowledge(knowledge: CodebaseKnowledge): void;
1417
+ /**
1418
+ * Clear file analysis cache
1419
+ */
1420
+ clearCache(): void;
1421
+ }
1422
+
1423
+ /**
1424
+ * Vibecheck Verification System
1425
+ *
1426
+ * Adds provenance tracking to AI-generated code:
1427
+ * - Marks verified code with "Verified by Vibecheck" badge
1428
+ * - Tracks which context folders/files were used
1429
+ * - Generates verification metadata for audit trails
1430
+ * - Embeds verification comments in generated code
1431
+ */
1432
+ interface VerificationMetadata {
1433
+ id: string;
1434
+ timestamp: string;
1435
+ verified: boolean;
1436
+ confidenceScore: number;
1437
+ confidenceGrade: string;
1438
+ contextUsed: ContextSource[];
1439
+ issues: string[];
1440
+ checksum: string;
1441
+ }
1442
+ interface ContextSource {
1443
+ path: string;
1444
+ type: 'file' | 'folder';
1445
+ relevance: number;
1446
+ linesUsed?: {
1447
+ start: number;
1448
+ end: number;
1449
+ }[];
1450
+ }
1451
+ interface VerificationBadge {
1452
+ comment: string;
1453
+ metadata: VerificationMetadata;
1454
+ }
1455
+ interface VerificationOptions {
1456
+ addComment: boolean;
1457
+ commentStyle: 'block' | 'line' | 'jsdoc';
1458
+ includeTimestamp: boolean;
1459
+ includeChecksum: boolean;
1460
+ includeContextPaths: boolean;
1461
+ includeConfidence: boolean;
1462
+ minConfidenceForBadge: number;
1463
+ }
1464
+ declare class VibecheckVerifier {
1465
+ private workspaceRoot;
1466
+ private verificationLog;
1467
+ private logPath;
1468
+ constructor(workspaceRoot: string);
1469
+ /**
1470
+ * Generate a verification badge for code
1471
+ */
1472
+ generateBadge(code: string, confidenceScore: number, confidenceGrade: string, contextUsed: ContextSource[], issues: string[], options?: Partial<VerificationOptions>): VerificationBadge;
1473
+ /**
1474
+ * Add verification badge to code
1475
+ */
1476
+ addBadgeToCode(code: string, badge: VerificationBadge, language: string): string;
1477
+ /**
1478
+ * Check if code already has a Vibecheck badge
1479
+ */
1480
+ hasVibecheckBadge(code: string): boolean;
1481
+ /**
1482
+ * Extract verification metadata from code with badge
1483
+ */
1484
+ extractBadgeMetadata(code: string): VerificationMetadata | null;
1485
+ /**
1486
+ * Verify that code matches its checksum
1487
+ */
1488
+ verifyChecksum(code: string): {
1489
+ valid: boolean;
1490
+ metadata?: VerificationMetadata;
1491
+ };
1492
+ /**
1493
+ * Generate verification report for a file
1494
+ */
1495
+ generateReport(filePath: string): {
1496
+ hasVerification: boolean;
1497
+ metadata?: VerificationMetadata;
1498
+ checksumValid?: boolean;
1499
+ contextStillExists?: boolean;
1500
+ };
1501
+ /**
1502
+ * Get all verified files in workspace
1503
+ */
1504
+ getVerifiedFiles(): Promise<Array<{
1505
+ path: string;
1506
+ metadata: VerificationMetadata;
1507
+ status: 'valid' | 'modified' | 'context_missing';
1508
+ }>>;
1509
+ /**
1510
+ * Create verification metadata
1511
+ */
1512
+ private createMetadata;
1513
+ /**
1514
+ * Format the verification comment
1515
+ */
1516
+ private formatComment;
1517
+ /**
1518
+ * Wrap comment in language-appropriate comment syntax
1519
+ */
1520
+ private wrapInComment;
1521
+ /**
1522
+ * Remove Vibecheck badge from code
1523
+ */
1524
+ private removeBadge;
1525
+ /**
1526
+ * Generate unique verification ID
1527
+ */
1528
+ private generateId;
1529
+ /**
1530
+ * Generate checksum for code
1531
+ */
1532
+ private generateChecksum;
1533
+ /**
1534
+ * Load verification log from disk
1535
+ */
1536
+ private loadLog;
1537
+ /**
1538
+ * Save verification log to disk
1539
+ */
1540
+ private saveLog;
1541
+ /**
1542
+ * Get verification statistics
1543
+ */
1544
+ getStats(): {
1545
+ totalVerifications: number;
1546
+ verified: number;
1547
+ needsReview: number;
1548
+ avgConfidence: number;
1549
+ topContextSources: Array<{
1550
+ path: string;
1551
+ count: number;
1552
+ }>;
1553
+ };
1554
+ /**
1555
+ * Clear all verification history
1556
+ */
1557
+ clearHistory(): void;
1558
+ }
1559
+ /**
1560
+ * Generate a simple Vibecheck badge comment for quick use
1561
+ */
1562
+ declare function generateQuickBadge(language: string, confidenceScore: number, contextPaths: string[]): string;
1563
+
1564
+ /**
1565
+ * Anti-Hallucination Engine - Main Orchestrator
1566
+ *
1567
+ * This is the unified interface that combines all anti-hallucination features:
1568
+ * - Semantic Verification
1569
+ * - Hallucination Fingerprinting
1570
+ * - Confidence Scoring
1571
+ * - Pattern Learning
1572
+ * - Context Optimization
1573
+ *
1574
+ * WHAT MAKES THIS BEST IN THE WORLD:
1575
+ * 1. Multi-layer validation - catches hallucinations at multiple levels
1576
+ * 2. Learning system - gets better with every accept/reject
1577
+ * 3. Confidence-based gating - prevents low-quality suggestions
1578
+ * 4. Smart context - maximizes relevant code in prompts
1579
+ * 5. Real-time feedback loop - adapts to your codebase
1580
+ */
1581
+
1582
+ interface AnalysisResult {
1583
+ suggestion: CodeSuggestion;
1584
+ verification: VerificationResult$1;
1585
+ detection: DetectionResult;
1586
+ confidence: ConfidenceScore;
1587
+ patternScore: {
1588
+ score: number;
1589
+ matchedPatterns: any[];
1590
+ };
1591
+ shouldAccept: boolean;
1592
+ shouldReview: boolean;
1593
+ shouldReject: boolean;
1594
+ summary: AnalysisSummary;
1595
+ }
1596
+ interface AnalysisSummary {
1597
+ overallScore: number;
1598
+ grade: string;
1599
+ recommendation: 'accept' | 'review' | 'reject';
1600
+ topIssues: string[];
1601
+ topStrengths: string[];
1602
+ riskLevel: 'low' | 'medium' | 'high' | 'critical';
1603
+ }
1604
+ interface EngineStats {
1605
+ totalAnalyzed: number;
1606
+ accepted: number;
1607
+ rejected: number;
1608
+ reviewed: number;
1609
+ averageConfidence: number;
1610
+ hallucinationsDetected: number;
1611
+ patternsLearned: number;
1612
+ accuracyImprovement: number;
1613
+ }
1614
+ declare class AntiHallucinationEngine {
1615
+ private workspaceRoot;
1616
+ private verifier;
1617
+ private detector;
1618
+ private scorer;
1619
+ private learner;
1620
+ private optimizer;
1621
+ private vibecheckVerifier;
1622
+ private knowledge;
1623
+ private statsPath;
1624
+ private stats;
1625
+ private lastContextUsed;
1626
+ constructor(workspaceRoot: string);
1627
+ /**
1628
+ * Analyze a code suggestion through all anti-hallucination layers
1629
+ */
1630
+ analyze(suggestion: CodeSuggestion): Promise<AnalysisResult>;
1631
+ /**
1632
+ * Quick check - fast path for obvious cases
1633
+ */
1634
+ quickCheck(code: string): {
1635
+ pass: boolean;
1636
+ issues: string[];
1637
+ };
1638
+ /**
1639
+ * Record user feedback for learning
1640
+ */
1641
+ recordFeedback(feedback: LearningFeedback): void;
1642
+ /**
1643
+ * Get optimized context for a request and track it for Vibecheck badge
1644
+ */
1645
+ getOptimizedContext(request: ContextRequest): Promise<OptimizedContext>;
1646
+ /**
1647
+ * Analyze and generate verified code with "Verified by Vibecheck" badge
1648
+ * This is the main method AI agents should use
1649
+ */
1650
+ analyzeAndVerify(code: string, language: string, contextUsed?: ContextSource[]): Promise<{
1651
+ analysis: AnalysisResult;
1652
+ verifiedCode: string;
1653
+ badge: VerificationBadge;
1654
+ }>;
1655
+ /**
1656
+ * Generate a Vibecheck badge for already-analyzed code
1657
+ */
1658
+ generateVibecheckBadge(code: string, confidenceScore: number, confidenceGrade: string, contextUsed: ContextSource[], issues?: string[]): VerificationBadge;
1659
+ /**
1660
+ * Add Vibecheck badge to code
1661
+ */
1662
+ addVibecheckBadge(code: string, badge: VerificationBadge, language: string): string;
1663
+ /**
1664
+ * Check if code has a Vibecheck badge
1665
+ */
1666
+ hasVibecheckBadge(code: string): boolean;
1667
+ /**
1668
+ * Verify the integrity of a Vibecheck badge in code
1669
+ */
1670
+ verifyVibecheckBadge(code: string): {
1671
+ valid: boolean;
1672
+ metadata?: any;
1673
+ };
1674
+ /**
1675
+ * Get Vibecheck verification statistics
1676
+ */
1677
+ getVibecheckStats(): {
1678
+ totalVerifications: number;
1679
+ verified: number;
1680
+ needsReview: number;
1681
+ avgConfidence: number;
1682
+ topContextSources: Array<{
1683
+ path: string;
1684
+ count: number;
1685
+ }>;
1686
+ };
1687
+ /**
1688
+ * Update codebase knowledge (call after scanning)
1689
+ */
1690
+ updateKnowledge(knowledge: CodebaseKnowledge): void;
1691
+ /**
1692
+ * Generate analysis summary
1693
+ */
1694
+ private generateSummary;
1695
+ /**
1696
+ * Get engine statistics
1697
+ */
1698
+ getStats(): EngineStats;
1699
+ /**
1700
+ * Get detailed breakdown for dashboard
1701
+ */
1702
+ getDashboardData(): {
1703
+ stats: EngineStats;
1704
+ thresholds: {
1705
+ accept: number;
1706
+ review: number;
1707
+ };
1708
+ recentHallucinations: {
1709
+ type: string;
1710
+ count: number;
1711
+ }[];
1712
+ patternStats: LearningStats;
1713
+ confidenceHistory: {
1714
+ date: string;
1715
+ avgConfidence: number;
1716
+ }[];
1717
+ };
1718
+ /**
1719
+ * Get improvement suggestions
1720
+ */
1721
+ getImprovementSuggestions(): string[];
1722
+ /**
1723
+ * Export all learned data for backup
1724
+ */
1725
+ exportLearnedData(): string;
1726
+ /**
1727
+ * Reset learning (use with caution)
1728
+ */
1729
+ resetLearning(): void;
1730
+ private loadStats;
1731
+ private saveStats;
1732
+ }
1733
+ declare function createAntiHallucinationEngine(workspaceRoot: string): AntiHallucinationEngine;
1734
+
1735
+ /**
1736
+ * Code Quality Analyzer
1737
+ *
1738
+ * WHAT NOBODY ELSE IS DOING:
1739
+ * - Deep static analysis of AI-generated code
1740
+ * - Complexity metrics and maintainability scores
1741
+ * - Security vulnerability detection
1742
+ * - Best practices enforcement
1743
+ * - Code smell detection
1744
+ */
1745
+ interface QualityMetrics {
1746
+ complexity: ComplexityMetrics;
1747
+ maintainability: MaintainabilityMetrics;
1748
+ security: SecurityMetrics;
1749
+ bestPractices: BestPracticesMetrics;
1750
+ codeSmells: CodeSmell[];
1751
+ overallScore: number;
1752
+ grade: 'A' | 'B' | 'C' | 'D' | 'F';
1753
+ }
1754
+ interface ComplexityMetrics {
1755
+ cyclomaticComplexity: number;
1756
+ cognitiveComplexity: number;
1757
+ nestingDepth: number;
1758
+ linesOfCode: number;
1759
+ functionsCount: number;
1760
+ avgFunctionLength: number;
1761
+ score: number;
1762
+ }
1763
+ interface MaintainabilityMetrics {
1764
+ commentRatio: number;
1765
+ namingQuality: number;
1766
+ modularity: number;
1767
+ codeReuse: number;
1768
+ score: number;
1769
+ }
1770
+ interface SecurityMetrics {
1771
+ vulnerabilities: SecurityVulnerability[];
1772
+ riskLevel: 'low' | 'medium' | 'high' | 'critical';
1773
+ score: number;
1774
+ }
1775
+ interface SecurityVulnerability {
1776
+ type: string;
1777
+ severity: 'low' | 'medium' | 'high' | 'critical';
1778
+ line: number;
1779
+ message: string;
1780
+ fix?: string;
1781
+ }
1782
+ interface BestPracticesMetrics {
1783
+ violations: BestPracticeViolation[];
1784
+ adherenceScore: number;
1785
+ score: number;
1786
+ }
1787
+ interface BestPracticeViolation {
1788
+ rule: string;
1789
+ severity: 'info' | 'warning' | 'error';
1790
+ line: number;
1791
+ message: string;
1792
+ fix?: string;
1793
+ }
1794
+ interface CodeSmell {
1795
+ type: string;
1796
+ severity: 'minor' | 'major' | 'critical';
1797
+ location: {
1798
+ start: number;
1799
+ end: number;
1800
+ };
1801
+ description: string;
1802
+ suggestion: string;
1803
+ }
1804
+ declare class CodeQualityAnalyzer {
1805
+ private workspaceRoot;
1806
+ constructor(workspaceRoot: string);
1807
+ /**
1808
+ * Analyze code quality
1809
+ */
1810
+ analyze(code: string, language?: string): QualityMetrics;
1811
+ /**
1812
+ * Analyze code complexity
1813
+ */
1814
+ private analyzeComplexity;
1815
+ /**
1816
+ * Analyze maintainability
1817
+ */
1818
+ private analyzeMaintainability;
1819
+ /**
1820
+ * Analyze security vulnerabilities
1821
+ */
1822
+ private analyzeSecurity;
1823
+ /**
1824
+ * Analyze best practices
1825
+ */
1826
+ private analyzeBestPractices;
1827
+ /**
1828
+ * Detect code smells
1829
+ */
1830
+ private detectCodeSmells;
1831
+ /**
1832
+ * Calculate grade from score
1833
+ */
1834
+ private calculateGrade;
1835
+ /**
1836
+ * Generate quality report
1837
+ */
1838
+ generateReport(metrics: QualityMetrics): string;
1839
+ }
1840
+ declare function createCodeQualityAnalyzer(workspaceRoot: string): CodeQualityAnalyzer;
1841
+
1842
+ /**
1843
+ * Prompt Optimizer
1844
+ *
1845
+ * WHAT NOBODY ELSE IS DOING:
1846
+ * - Automatically improves AI prompts to reduce hallucinations
1847
+ * - Adds context anchors and constraints
1848
+ * - Learns from successful/failed prompts
1849
+ * - Generates codebase-aware prompt enhancements
1850
+ */
1851
+ interface PromptAnalysis {
1852
+ original: string;
1853
+ issues: PromptIssue[];
1854
+ suggestions: PromptSuggestion[];
1855
+ score: number;
1856
+ optimized: string;
1857
+ }
1858
+ interface PromptIssue {
1859
+ type: 'vague' | 'no_context' | 'no_constraints' | 'too_broad' | 'missing_examples' | 'ambiguous';
1860
+ severity: 'low' | 'medium' | 'high';
1861
+ description: string;
1862
+ location?: {
1863
+ start: number;
1864
+ end: number;
1865
+ };
1866
+ }
1867
+ interface PromptSuggestion {
1868
+ type: 'add_context' | 'add_constraint' | 'add_example' | 'be_specific' | 'add_format' | 'add_validation';
1869
+ priority: 'low' | 'medium' | 'high';
1870
+ suggestion: string;
1871
+ insertion?: string;
1872
+ }
1873
+ interface OptimizationOptions {
1874
+ addCodebaseContext: boolean;
1875
+ addTypeConstraints: boolean;
1876
+ addExamples: boolean;
1877
+ addValidation: boolean;
1878
+ maxContextTokens: number;
1879
+ style: 'minimal' | 'detailed' | 'comprehensive';
1880
+ }
1881
+ interface PromptTemplate {
1882
+ id: string;
1883
+ name: string;
1884
+ template: string;
1885
+ variables: string[];
1886
+ category: string;
1887
+ successRate: number;
1888
+ usageCount: number;
1889
+ }
1890
+ declare class PromptOptimizer {
1891
+ private workspaceRoot;
1892
+ private templates;
1893
+ private promptHistory;
1894
+ private historyPath;
1895
+ constructor(workspaceRoot: string);
1896
+ /**
1897
+ * Analyze and optimize a prompt
1898
+ */
1899
+ optimize(prompt: string, options?: Partial<OptimizationOptions>): PromptAnalysis;
1900
+ /**
1901
+ * Analyze prompt for issues
1902
+ */
1903
+ private analyzePrompt;
1904
+ /**
1905
+ * Generate optimization suggestions
1906
+ */
1907
+ private generateSuggestions;
1908
+ /**
1909
+ * Apply optimizations to prompt
1910
+ */
1911
+ private applyOptimizations;
1912
+ /**
1913
+ * Insert suggestion into prompt
1914
+ */
1915
+ private insertSuggestion;
1916
+ /**
1917
+ * Generate context insertion
1918
+ */
1919
+ private generateContextInsertion;
1920
+ /**
1921
+ * Generate constraint insertion
1922
+ */
1923
+ private generateConstraintInsertion;
1924
+ /**
1925
+ * Generate context header based on style
1926
+ */
1927
+ private generateContextHeader;
1928
+ /**
1929
+ * Generate constraints footer based on style
1930
+ */
1931
+ private generateConstraintsFooter;
1932
+ /**
1933
+ * Generate validation section
1934
+ */
1935
+ private generateValidationSection;
1936
+ /**
1937
+ * Calculate prompt quality score
1938
+ */
1939
+ private calculateScore;
1940
+ /**
1941
+ * Record prompt result for learning
1942
+ */
1943
+ recordResult(prompt: string, success: boolean): void;
1944
+ /**
1945
+ * Get prompt templates
1946
+ */
1947
+ getTemplates(category?: string): PromptTemplate[];
1948
+ /**
1949
+ * Apply a template
1950
+ */
1951
+ applyTemplate(templateId: string, variables: Record<string, string>): string;
1952
+ /**
1953
+ * Get prompt improvement suggestions based on history
1954
+ */
1955
+ getHistoricalInsights(): {
1956
+ successRate: number;
1957
+ commonIssues: string[];
1958
+ recommendations: string[];
1959
+ };
1960
+ /**
1961
+ * Initialize built-in templates
1962
+ */
1963
+ private initializeTemplates;
1964
+ private loadHistory;
1965
+ private saveHistory;
1966
+ }
1967
+ declare function createPromptOptimizer(workspaceRoot: string): PromptOptimizer;
1968
+
1969
+ /**
1970
+ * AST-Based Code Analyzer
1971
+ *
1972
+ * THE MOST COMPREHENSIVE HALLUCINATION DETECTION:
1973
+ * - Deep AST parsing for structural analysis
1974
+ * - Token-level validation
1975
+ * - Scope analysis for variable/function resolution
1976
+ * - Type inference and checking
1977
+ * - Import graph building and validation
1978
+ * - Dead code and unreachable path detection
1979
+ */
1980
+ interface ASTNode {
1981
+ type: string;
1982
+ name?: string;
1983
+ value?: any;
1984
+ children?: ASTNode[];
1985
+ location: {
1986
+ start: number;
1987
+ end: number;
1988
+ line: number;
1989
+ column: number;
1990
+ };
1991
+ scope?: ScopeInfo;
1992
+ metadata?: Record<string, any>;
1993
+ }
1994
+ interface ScopeInfo {
1995
+ id: string;
1996
+ type: 'global' | 'function' | 'block' | 'class' | 'module';
1997
+ parent?: string;
1998
+ variables: Map<string, VariableInfo>;
1999
+ functions: Map<string, FunctionInfo>;
2000
+ types: Map<string, ASTTypeInfo>;
2001
+ imports: Map<string, ASTImportInfo>;
2002
+ }
2003
+ interface VariableInfo {
2004
+ name: string;
2005
+ type: string;
2006
+ definedAt: number;
2007
+ usedAt: number[];
2008
+ isConst: boolean;
2009
+ isExported: boolean;
2010
+ value?: any;
2011
+ }
2012
+ interface FunctionInfo {
2013
+ name: string;
2014
+ params: ParamInfo[];
2015
+ returnType: string;
2016
+ isAsync: boolean;
2017
+ isGenerator: boolean;
2018
+ isExported: boolean;
2019
+ definedAt: number;
2020
+ calledAt: number[];
2021
+ complexity: number;
2022
+ }
2023
+ interface ParamInfo {
2024
+ name: string;
2025
+ type: string;
2026
+ optional: boolean;
2027
+ defaultValue?: string;
2028
+ rest: boolean;
2029
+ }
2030
+ interface ASTTypeInfo {
2031
+ name: string;
2032
+ kind: 'interface' | 'type' | 'class' | 'enum';
2033
+ properties: Map<string, {
2034
+ type: string;
2035
+ optional: boolean;
2036
+ }>;
2037
+ methods: Map<string, FunctionInfo>;
2038
+ extends?: string[];
2039
+ implements?: string[];
2040
+ }
2041
+ interface ASTImportInfo {
2042
+ source: string;
2043
+ specifiers: {
2044
+ name: string;
2045
+ alias?: string;
2046
+ isDefault: boolean;
2047
+ isNamespace: boolean;
2048
+ }[];
2049
+ isTypeOnly: boolean;
2050
+ resolvedPath?: string;
2051
+ exists: boolean;
2052
+ }
2053
+ interface ASTAnalysisResult {
2054
+ isValid: boolean;
2055
+ errors: ASTError[];
2056
+ warnings: ASTWarning[];
2057
+ scopes: Map<string, ScopeInfo>;
2058
+ imports: ASTImportInfo[];
2059
+ exports: string[];
2060
+ unresolvedReferences: UnresolvedReference[];
2061
+ suspiciousPatterns: SuspiciousPattern[];
2062
+ metrics: CodeMetrics;
2063
+ }
2064
+ interface ASTError {
2065
+ type: string;
2066
+ message: string;
2067
+ location: {
2068
+ line: number;
2069
+ column: number;
2070
+ };
2071
+ severity: 'error' | 'critical';
2072
+ fix?: string;
2073
+ }
2074
+ interface ASTWarning {
2075
+ type: string;
2076
+ message: string;
2077
+ location: {
2078
+ line: number;
2079
+ column: number;
2080
+ };
2081
+ confidence: number;
2082
+ }
2083
+ interface UnresolvedReference {
2084
+ name: string;
2085
+ type: 'variable' | 'function' | 'type' | 'import';
2086
+ location: {
2087
+ line: number;
2088
+ column: number;
2089
+ };
2090
+ possibleMatches: string[];
2091
+ }
2092
+ interface SuspiciousPattern {
2093
+ pattern: string;
2094
+ description: string;
2095
+ location: {
2096
+ line: number;
2097
+ column: number;
2098
+ };
2099
+ confidence: number;
2100
+ category: 'hallucination' | 'bug' | 'smell' | 'security';
2101
+ }
2102
+ interface CodeMetrics {
2103
+ lines: number;
2104
+ statements: number;
2105
+ functions: number;
2106
+ classes: number;
2107
+ imports: number;
2108
+ exports: number;
2109
+ complexity: number;
2110
+ depth: number;
2111
+ maintainabilityIndex: number;
2112
+ }
2113
+ declare class ASTAnalyzer {
2114
+ private workspaceRoot;
2115
+ private scopeStack;
2116
+ private globalScope;
2117
+ private currentScopeId;
2118
+ private knownGlobals;
2119
+ private knownBuiltins;
2120
+ constructor(workspaceRoot: string);
2121
+ /**
2122
+ * Analyze code and return comprehensive results
2123
+ */
2124
+ analyze(code: string, language?: string): ASTAnalysisResult;
2125
+ /**
2126
+ * Extract and validate imports
2127
+ */
2128
+ private extractImports;
2129
+ /**
2130
+ * Extract declarations from code
2131
+ */
2132
+ private extractDeclarations;
2133
+ /**
2134
+ * Analyze references and find unresolved ones
2135
+ */
2136
+ private analyzeReferences;
2137
+ /**
2138
+ * Detect suspicious patterns that may indicate hallucination
2139
+ */
2140
+ private detectSuspiciousPatterns;
2141
+ /**
2142
+ * Validate type consistency
2143
+ */
2144
+ private validateTypes;
2145
+ /**
2146
+ * Check for common hallucination patterns
2147
+ */
2148
+ private checkHallucinationPatterns;
2149
+ /**
2150
+ * Calculate code metrics
2151
+ */
2152
+ private calculateMetrics;
2153
+ private createScope;
2154
+ private initializeGlobals;
2155
+ private initializeBuiltins;
2156
+ private isKeyword;
2157
+ private validateImportSource;
2158
+ private isSuspiciousImport;
2159
+ private parseParams;
2160
+ private calculateFunctionComplexity;
2161
+ private getLocation;
2162
+ private getLineNumber;
2163
+ private findSimilarIdentifiers;
2164
+ private levenshteinDistance;
2165
+ private looksLikeReference;
2166
+ private guessReferenceType;
2167
+ private inferType;
2168
+ private typesCompatible;
2169
+ private suggestAlternative;
2170
+ }
2171
+ declare function createASTAnalyzer(workspaceRoot: string): ASTAnalyzer;
2172
+
2173
+ /**
2174
+ * Package & API Verifier
2175
+ *
2176
+ * THE MOST COMPREHENSIVE PACKAGE VERIFICATION:
2177
+ * - Verifies NPM packages exist
2178
+ * - Validates package exports
2179
+ * - Checks API signatures match documentation
2180
+ * - Detects deprecated APIs
2181
+ * - Validates version compatibility
2182
+ * - Maintains local cache of known packages
2183
+ */
2184
+ interface PackageInfo {
2185
+ name: string;
2186
+ version: string;
2187
+ exports: string[];
2188
+ types: string[];
2189
+ deprecated: boolean;
2190
+ lastVerified: string;
2191
+ }
2192
+ interface APISignature {
2193
+ name: string;
2194
+ type: 'function' | 'class' | 'constant' | 'type' | 'interface';
2195
+ params?: {
2196
+ name: string;
2197
+ type: string;
2198
+ optional: boolean;
2199
+ }[];
2200
+ returnType?: string;
2201
+ isAsync?: boolean;
2202
+ deprecated?: boolean;
2203
+ since?: string;
2204
+ }
2205
+ interface VerificationResult {
2206
+ valid: boolean;
2207
+ packageExists: boolean;
2208
+ exportExists: boolean;
2209
+ signatureMatches: boolean;
2210
+ issues: VerificationIssue[];
2211
+ suggestions: string[];
2212
+ }
2213
+ interface VerificationIssue {
2214
+ type: 'package_not_found' | 'export_not_found' | 'signature_mismatch' | 'deprecated' | 'version_incompatible';
2215
+ message: string;
2216
+ severity: 'error' | 'warning';
2217
+ fix?: string;
2218
+ }
2219
+ declare class PackageVerifier {
2220
+ private workspaceRoot;
2221
+ private packageCache;
2222
+ private knownPackages;
2223
+ private cachePath;
2224
+ constructor(workspaceRoot: string);
2225
+ /**
2226
+ * Verify an import statement
2227
+ */
2228
+ verifyImport(source: string, specifiers: string[]): VerificationResult;
2229
+ /**
2230
+ * Verify a function call matches expected signature
2231
+ */
2232
+ verifyAPICall(packageName: string, functionName: string, args: any[]): VerificationResult;
2233
+ /**
2234
+ * Get all exports for a package
2235
+ */
2236
+ getPackageExports(packageName: string): string[];
2237
+ /**
2238
+ * Check if a package export exists
2239
+ */
2240
+ exportExists(packageName: string, exportName: string): boolean;
2241
+ private verifyRelativeImport;
2242
+ private verifyKnownPackage;
2243
+ private verifyInstalledPackage;
2244
+ private verifyNodeBuiltin;
2245
+ private isNodeBuiltin;
2246
+ private getNodeBuiltinAPIs;
2247
+ private isKnownFakePackage;
2248
+ private suggestRealPackage;
2249
+ private findSimilarPackages;
2250
+ private findSimilarAPIs;
2251
+ private similarity;
2252
+ private levenshteinDistance;
2253
+ private initializeKnownPackages;
2254
+ private loadCache;
2255
+ private saveCache;
2256
+ }
2257
+ declare function createPackageVerifier(workspaceRoot: string): PackageVerifier;
2258
+
2259
+ /**
2260
+ * Cross-File Consistency Analyzer
2261
+ *
2262
+ * THE MOST COMPREHENSIVE CROSS-FILE VERIFICATION:
2263
+ * - Tracks type definitions across files
2264
+ * - Validates import/export consistency
2265
+ * - Detects circular dependencies
2266
+ * - Verifies interface implementations
2267
+ * - Checks for duplicate definitions
2268
+ * - Analyzes call graph for dead code
2269
+ */
2270
+ interface FileAnalysis {
2271
+ path: string;
2272
+ exports: CFExportInfo[];
2273
+ imports: CFImportInfo[];
2274
+ types: TypeDefinition[];
2275
+ functions: FunctionDefinition[];
2276
+ dependencies: string[];
2277
+ dependents: string[];
2278
+ }
2279
+ interface CFExportInfo {
2280
+ name: string;
2281
+ type: 'function' | 'class' | 'type' | 'interface' | 'const' | 'let' | 'var' | 'enum' | 'default';
2282
+ isReExport: boolean;
2283
+ originalSource?: string;
2284
+ line: number;
2285
+ }
2286
+ interface CFImportInfo {
2287
+ source: string;
2288
+ specifiers: {
2289
+ name: string;
2290
+ alias?: string;
2291
+ isDefault: boolean;
2292
+ }[];
2293
+ isTypeOnly: boolean;
2294
+ line: number;
2295
+ resolved: boolean;
2296
+ resolvedPath?: string;
2297
+ }
2298
+ interface TypeDefinition {
2299
+ name: string;
2300
+ kind: 'interface' | 'type' | 'class' | 'enum';
2301
+ properties: {
2302
+ name: string;
2303
+ type: string;
2304
+ optional: boolean;
2305
+ }[];
2306
+ methods: {
2307
+ name: string;
2308
+ params: string;
2309
+ returnType: string;
2310
+ }[];
2311
+ extends?: string[];
2312
+ implements?: string[];
2313
+ line: number;
2314
+ }
2315
+ interface FunctionDefinition {
2316
+ name: string;
2317
+ params: {
2318
+ name: string;
2319
+ type: string;
2320
+ optional: boolean;
2321
+ }[];
2322
+ returnType: string;
2323
+ isAsync: boolean;
2324
+ isExported: boolean;
2325
+ line: number;
2326
+ calls: string[];
2327
+ calledBy: string[];
2328
+ }
2329
+ interface ConsistencyIssue {
2330
+ type: 'missing_export' | 'missing_import' | 'type_mismatch' | 'circular_dependency' | 'duplicate_definition' | 'dead_code' | 'inconsistent_signature' | 'missing_implementation';
2331
+ severity: 'error' | 'warning' | 'info';
2332
+ file: string;
2333
+ line?: number;
2334
+ message: string;
2335
+ relatedFiles?: string[];
2336
+ fix?: string;
2337
+ }
2338
+ interface CrossFileAnalysisResult {
2339
+ files: Map<string, FileAnalysis>;
2340
+ issues: ConsistencyIssue[];
2341
+ dependencyGraph: Map<string, Set<string>>;
2342
+ circularDependencies: string[][];
2343
+ unusedExports: {
2344
+ file: string;
2345
+ export: string;
2346
+ }[];
2347
+ missingTypes: {
2348
+ file: string;
2349
+ type: string;
2350
+ referencedIn: string[];
2351
+ }[];
2352
+ duplicateDefinitions: {
2353
+ name: string;
2354
+ files: string[];
2355
+ }[];
2356
+ }
2357
+ declare class CrossFileAnalyzer {
2358
+ private workspaceRoot;
2359
+ private fileCache;
2360
+ private typeRegistry;
2361
+ private exportRegistry;
2362
+ constructor(workspaceRoot: string);
2363
+ /**
2364
+ * Analyze multiple files for cross-file consistency
2365
+ */
2366
+ analyzeProject(files: string[]): Promise<CrossFileAnalysisResult>;
2367
+ /**
2368
+ * Analyze a single file
2369
+ */
2370
+ analyzeFile(filePath: string): Promise<FileAnalysis>;
2371
+ /**
2372
+ * Validate code snippet against project context
2373
+ */
2374
+ validateSnippet(code: string, targetFile: string): ConsistencyIssue[];
2375
+ private extractExports;
2376
+ private extractImports;
2377
+ private extractTypes;
2378
+ private extractFunctions;
2379
+ private buildTypeRegistry;
2380
+ private buildExportRegistry;
2381
+ private buildDependencyGraph;
2382
+ private detectCircularDependencies;
2383
+ private validateImports;
2384
+ private findDuplicateDefinitions;
2385
+ private findUnusedExports;
2386
+ private findMissingTypes;
2387
+ private validateImplementations;
2388
+ private resolveImportPath;
2389
+ private getExportType;
2390
+ private getLineNumber;
2391
+ private extractBraceContent;
2392
+ private parseParams;
2393
+ private parseTypeProperties;
2394
+ private parseTypeMethods;
2395
+ private parseClassProperties;
2396
+ private parseClassMethods;
2397
+ private extractTypeReferences;
2398
+ private extractFunctionCalls;
2399
+ private isBuiltinType;
2400
+ private isBuiltinFunction;
2401
+ private isKeyword;
2402
+ }
2403
+ declare function createCrossFileAnalyzer(workspaceRoot: string): CrossFileAnalyzer;
2404
+
2405
+ export { type AHFunctionInfo, type AHMethodInfo, type AHParameterInfo, type AHPropertyInfo, type AHRouteInfo, type APISignature, type ASTAnalysisResult, ASTAnalyzer, type ASTError, type ASTImportInfo, type ASTNode, type ASTTypeInfo, type ASTWarning, type AnalysisResult, type AnalysisSummary, AntiHallucinationEngine, type AuthRule, type BestPracticeViolation, type BestPracticesMetrics, type CFExportInfo, type CFImportInfo, type CodeMetrics, CodeQualityAnalyzer, type CodeSmell, type CodeSuggestion, type CodebaseKnowledge, type CompletionCriteria, CompletionGuard, type CompletionResult, type ComplexityMetrics, type ConfidenceFactors, type ConfidenceScore, ConfidenceScorer, type ConsistencyIssue, type ContextChunk, type ContextCoverage, ContextOptimizer, type ContextRequest, type ContextSnapshot, type ContextSource, type ContractInfo, type ConventionRule, type CrossFileAnalysisResult, CrossFileAnalyzer, type DetectionResult, DocGuard, type DocGuardConfig, type DocGuardIssue, type DocGuardResult, type DuplicateCheckResult, type EngineStats, type EnvVarInfo, type ExportInfo, type FileAnalysis, type FileCache, type FirewallConfig, type ForgeConfig, type FunctionDefinition, type FunctionInfo, type GeneratedHook, type GeneratedRule, type GeneratedSkill, type GeneratedSubagent, type GuardrailConfig, GuardrailForge, GuardrailWatcher, HallucinationDetector, type HallucinationFingerprint, type HallucinationType, type HandoffDocument, type ImportInfo, LargeCodebaseScanner, type LargeScannerConfig, type LearnedPattern, type LearningFeedback, type LearningStats, type MaintainabilityMetrics, type OptimizationOptions, type OptimizedContext, type PackageInfo, PackageVerifier, type ParamInfo, type PatternDefinition, PatternLearner, type PatternSignature, type VerificationIssue as PkgVerificationIssue, type VerificationResult as PkgVerificationResult, type ProgressCallback, type PromptAnalysis, type PromptIssue, PromptOptimizer, type PromptSuggestion, type PromptTemplate, type PropertyInfo, type QualityMetrics, type RefreshResult, type RequiredAction, type RouteInfo, type RouteParameter, type RuleCategory, type ScanError, type ScanProgress, type ScannerConfig, type ScopeInfo, type SecurityMetrics, type SecurityVulnerability, SemanticVerifier, type StopValidation, type SuspiciousPattern, type Task, type TaskCheckpoint, type TaskStep, type TaskSummary, TaskTracker, type TruthpackData, type TruthpackMeta, TruthpackScanner, type TypeDefinition, type TypeInfo, type UnresolvedReference, type VariableInfo, type VerificationBadge, type VerificationIssue$1 as VerificationIssue, type VerificationMetadata, type VerificationMetrics, type VerificationOptions, type VerificationResult$1 as VerificationResult, VibecheckVerifier, type WatcherEvent, type WatcherOptions, createASTAnalyzer, createAntiHallucinationEngine, createCodeQualityAnalyzer, createCompletionGuard, createCrossFileAnalyzer, createDocGuard, createPackageVerifier, createPromptOptimizer, createTaskTracker, estimateCodebaseSize, evaluateDoc, forge, generateQuickBadge, loadTruthpack, refreshGuardrails, saveTruthpack, scanLargeCodebase, scanTruthpack, shouldBlock, startWatcher };