tribunal-kit 9.2.4 → 9.2.6

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 (1208) hide show
  1. package/.agent/.manifest.json +78 -78
  2. package/.agent/.shared/ui-ux-pro-max/README.md +4 -4
  3. package/.agent/.tribunal/session.jsonl +15 -15
  4. package/.agent/ADRs/ADR-001-system-architecture-intelligence.md +49 -0
  5. package/.agent/ARCHITECTURE.md +63 -63
  6. package/.agent/agents/accessibility-reviewer.md +109 -109
  7. package/.agent/agents/agent-shield-auditor.md +21 -18
  8. package/.agent/agents/ai-code-reviewer.md +223 -223
  9. package/.agent/agents/anti-pattern-reviewer.md +104 -104
  10. package/.agent/agents/anti-slop-auditor.md +79 -0
  11. package/.agent/agents/api-architect.md +94 -89
  12. package/.agent/agents/architecture-auditor.md +196 -0
  13. package/.agent/agents/backend-security-architect.md +115 -0
  14. package/.agent/agents/backend-specialist.md +242 -242
  15. package/.agent/agents/cloud-engineer.md +120 -120
  16. package/.agent/agents/code-archaeologist.md +186 -186
  17. package/.agent/agents/complexity-reviewer.md +76 -76
  18. package/.agent/agents/database-architect.md +206 -206
  19. package/.agent/agents/db-latency-auditor.md +237 -237
  20. package/.agent/agents/debugger.md +215 -215
  21. package/.agent/agents/dependency-reviewer.md +124 -124
  22. package/.agent/agents/devops-engineer.md +240 -240
  23. package/.agent/agents/documentation-writer.md +228 -228
  24. package/.agent/agents/explorer-agent.md +186 -186
  25. package/.agent/agents/frontend-reviewer.md +197 -195
  26. package/.agent/agents/frontend-specialist.md +123 -122
  27. package/.agent/agents/game-developer.md +68 -68
  28. package/.agent/agents/harness-manager.md +57 -49
  29. package/.agent/agents/human-gate-negotiator.md +26 -22
  30. package/.agent/agents/interaction-reviewer.md +123 -123
  31. package/.agent/agents/kernel-scheduler.md +60 -56
  32. package/.agent/agents/logic-reviewer.md +147 -147
  33. package/.agent/agents/memory-archivist.md +42 -37
  34. package/.agent/agents/minimalist-reviewer.md +104 -104
  35. package/.agent/agents/mobile-developer.md +216 -216
  36. package/.agent/agents/mobile-reviewer.md +180 -180
  37. package/.agent/agents/orchestrator.md +267 -268
  38. package/.agent/agents/penetration-tester.md +180 -180
  39. package/.agent/agents/performance-optimizer.md +202 -202
  40. package/.agent/agents/performance-reviewer.md +180 -180
  41. package/.agent/agents/pipeline-reviewer.md +144 -144
  42. package/.agent/agents/precedence-reviewer.md +266 -266
  43. package/.agent/agents/product-manager.md +167 -167
  44. package/.agent/agents/product-owner.md +103 -103
  45. package/.agent/agents/product-reviewer.md +103 -103
  46. package/.agent/agents/project-planner.md +180 -181
  47. package/.agent/agents/qa-automation-engineer.md +244 -244
  48. package/.agent/agents/resilience-reviewer.md +108 -108
  49. package/.agent/agents/schema-reviewer.md +87 -87
  50. package/.agent/agents/security-auditor.md +203 -204
  51. package/.agent/agents/seo-specialist.md +213 -213
  52. package/.agent/agents/sql-reviewer.md +180 -180
  53. package/.agent/agents/supervisor-agent.md +202 -202
  54. package/.agent/agents/swarm-worker-contracts.md +170 -170
  55. package/.agent/agents/swarm-worker-registry.md +99 -99
  56. package/.agent/agents/system-architect.md +274 -105
  57. package/.agent/agents/test-coverage-reviewer.md +181 -181
  58. package/.agent/agents/test-engineer.md +138 -138
  59. package/.agent/agents/throughput-optimizer.md +316 -316
  60. package/.agent/agents/type-safety-reviewer.md +202 -202
  61. package/.agent/agents/ui-ux-auditor.md +85 -80
  62. package/.agent/agents/ui-visual-auditor.md +107 -102
  63. package/.agent/agents/ux-reviewer.md +109 -109
  64. package/.agent/agents/visual-reviewer.md +103 -103
  65. package/.agent/agents/vitals-reviewer.md +245 -245
  66. package/.agent/config/claude.json +18 -18
  67. package/.agent/config/plugin.json +102 -102
  68. package/.agent/config/slash-commands.json +115 -115
  69. package/.agent/config/specialist-registry.json +415 -415
  70. package/.agent/config/system-prompt.md +258 -258
  71. package/.agent/history/arch-mapper-cache.json +6712 -0
  72. package/.agent/history/architecture-intelligence.html +794 -0
  73. package/.agent/history/architecture-model.json +16096 -0
  74. package/.agent/history/architecture-verification.json +22 -0
  75. package/.agent/history/architecture.idx.json +5746 -0
  76. package/.agent/history/integrity_manifest.json +369 -3158
  77. package/.agent/mcp_config.json +32 -32
  78. package/.agent/patterns/generator.md +11 -11
  79. package/.agent/patterns/inversion.md +14 -14
  80. package/.agent/patterns/pipeline.md +11 -11
  81. package/.agent/patterns/reviewer.md +15 -15
  82. package/.agent/patterns/tool-wrapper.md +11 -11
  83. package/.agent/plans/implementation_plan.md +55 -0
  84. package/.agent/plans/task.md +41 -0
  85. package/.agent/routing_index.json +1566 -286
  86. package/.agent/rules/GEMINI.md +437 -437
  87. package/.agent/rules/GEMINI_PLANNER.md +82 -82
  88. package/.agent/rules/kernel.md +89 -86
  89. package/.agent/scripts/_colors.js +210 -210
  90. package/.agent/scripts/_utils.js +378 -377
  91. package/.agent/scripts/ab_json_experiment.js +129 -0
  92. package/.agent/scripts/architecture_diff.js +260 -0
  93. package/.agent/scripts/architecture_extractor.js +753 -0
  94. package/.agent/scripts/architecture_health.js +256 -0
  95. package/.agent/scripts/architecture_mapper.js +691 -0
  96. package/.agent/scripts/architecture_verifier.js +270 -0
  97. package/.agent/scripts/architecture_visualizer.js +873 -0
  98. package/.agent/scripts/ast_context_loader.js +137 -137
  99. package/.agent/scripts/auto_preview.js +203 -203
  100. package/.agent/scripts/backend_audit.js +238 -0
  101. package/.agent/scripts/backend_report_generator.js +161 -0
  102. package/.agent/scripts/benchmark_suite.js +493 -0
  103. package/.agent/scripts/blast_radius_engine.js +234 -0
  104. package/.agent/scripts/browser_audit.js +102 -102
  105. package/.agent/scripts/bundle_analyzer.js +287 -287
  106. package/.agent/scripts/case_law_manager.js +887 -887
  107. package/.agent/scripts/checklist.js +304 -300
  108. package/.agent/scripts/cicd_validator.js +305 -305
  109. package/.agent/scripts/consolidation_experiment.js +543 -0
  110. package/.agent/scripts/context_broker.js +962 -962
  111. package/.agent/scripts/context_compiler.js +1174 -1112
  112. package/.agent/scripts/contract_engine.js +402 -402
  113. package/.agent/scripts/cross_agent_correlator.js +223 -0
  114. package/.agent/scripts/dependency_analyzer.js +335 -313
  115. package/.agent/scripts/evidence_verifier.js +171 -0
  116. package/.agent/scripts/finding_schema.js +104 -0
  117. package/.agent/scripts/findings_validator.js +147 -0
  118. package/.agent/scripts/graph_builder.js +384 -384
  119. package/.agent/scripts/graph_visualizer.js +390 -390
  120. package/.agent/scripts/graph_zoom.js +181 -181
  121. package/.agent/scripts/guardrail_engine.js +804 -785
  122. package/.agent/scripts/harness_manager.js +72 -60
  123. package/.agent/scripts/impact_classifier.js +193 -192
  124. package/.agent/scripts/inner_loop_validator.js +472 -472
  125. package/.agent/scripts/integrity_manifest.js +524 -484
  126. package/.agent/scripts/lint_runner.js +220 -218
  127. package/.agent/scripts/live_abc_benchmark.js +452 -0
  128. package/.agent/scripts/marathon_harness.js +986 -986
  129. package/.agent/scripts/mcp_server.js +203 -181
  130. package/.agent/scripts/memory_archivist.js +103 -97
  131. package/.agent/scripts/memory_consolidator.js +37 -37
  132. package/.agent/scripts/memory_engine.js +798 -782
  133. package/.agent/scripts/minify_context.js +111 -111
  134. package/.agent/scripts/minimal_change_engine.js +445 -445
  135. package/.agent/scripts/mutation_runner.js +307 -305
  136. package/.agent/scripts/payload_schemas.js +164 -164
  137. package/.agent/scripts/pipeline_engine.js +921 -906
  138. package/.agent/scripts/prompt_compiler.js +272 -272
  139. package/.agent/scripts/schema_validator.js +326 -326
  140. package/.agent/scripts/secret_redactor.js +119 -0
  141. package/.agent/scripts/security_scan.js +390 -390
  142. package/.agent/scripts/session_logger.js +115 -115
  143. package/.agent/scripts/session_manager.js +304 -299
  144. package/.agent/scripts/signal_detector.js +175 -175
  145. package/.agent/scripts/skill_evolution.js +997 -997
  146. package/.agent/scripts/skill_integrator.js +304 -304
  147. package/.agent/scripts/socratic_gate_policy.js +63 -63
  148. package/.agent/scripts/strengthen_skills.js +199 -199
  149. package/.agent/scripts/swarm_dispatcher.js +992 -979
  150. package/.agent/scripts/syscall_registry.js +110 -105
  151. package/.agent/scripts/test_runner.js +209 -209
  152. package/.agent/scripts/tier3_audit.js +195 -0
  153. package/.agent/scripts/token_budget_broker.js +165 -165
  154. package/.agent/scripts/trace_engine.js +126 -126
  155. package/.agent/scripts/validation_engine.js +236 -0
  156. package/.agent/scripts/verify_all.js +278 -276
  157. package/.agent/scripts/visual_audit.js +87 -87
  158. package/.agent/skill_topic_map.json +123 -96
  159. package/.agent/skills/12-principles-of-animation/SKILL.md +91 -21
  160. package/.agent/skills/60fps-animation/SKILL.md +118 -61
  161. package/.agent/skills/accessible-animation/SKILL.md +214 -152
  162. package/.agent/skills/adapt/SKILL.md +98 -28
  163. package/.agent/skills/adr-generation/SKILL.md +133 -0
  164. package/.agent/skills/advanced-rag-pipelines/SKILL.md +125 -64
  165. package/.agent/skills/agent-organizer/SKILL.md +142 -84
  166. package/.agent/skills/agent-syscall-guidelines/SKILL.md +88 -13
  167. package/.agent/skills/agentic-patterns/SKILL.md +314 -244
  168. package/.agent/skills/agentic-workflows-2026/SKILL.md +137 -65
  169. package/.agent/skills/agentshield-security/SKILL.md +74 -15
  170. package/.agent/skills/ai-app-hardening/SKILL.md +99 -27
  171. package/.agent/skills/ai-prompt-injection-defense/SKILL.md +191 -130
  172. package/.agent/skills/animation-on-scroll/SKILL.md +225 -163
  173. package/.agent/skills/animation-systems/SKILL.md +227 -165
  174. package/.agent/skills/antfu-conventions/SKILL.md +96 -26
  175. package/.agent/skills/anti-slop-enforcement/SKILL.md +118 -0
  176. package/.agent/skills/api-patterns/SKILL.md +247 -186
  177. package/.agent/skills/api-security-auditor/SKILL.md +204 -126
  178. package/.agent/skills/app-builder/SKILL.md +556 -501
  179. package/.agent/skills/app-builder/templates/SKILL.md +108 -108
  180. package/.agent/skills/app-builder/templates/astro-static/TEMPLATE.md +76 -76
  181. package/.agent/skills/app-builder/templates/chrome-extension/TEMPLATE.md +92 -92
  182. package/.agent/skills/app-builder/templates/cli-tool/TEMPLATE.md +88 -88
  183. package/.agent/skills/app-builder/templates/electron-desktop/TEMPLATE.md +88 -88
  184. package/.agent/skills/app-builder/templates/express-api/TEMPLATE.md +83 -83
  185. package/.agent/skills/app-builder/templates/flutter-app/TEMPLATE.md +90 -90
  186. package/.agent/skills/app-builder/templates/monorepo-turborepo/TEMPLATE.md +90 -90
  187. package/.agent/skills/app-builder/templates/nextjs-fullstack/TEMPLATE.md +126 -126
  188. package/.agent/skills/app-builder/templates/nextjs-saas/TEMPLATE.md +127 -127
  189. package/.agent/skills/app-builder/templates/nextjs-static/TEMPLATE.md +172 -172
  190. package/.agent/skills/app-builder/templates/nuxt-app/TEMPLATE.md +139 -139
  191. package/.agent/skills/app-builder/templates/python-fastapi/TEMPLATE.md +83 -83
  192. package/.agent/skills/app-builder/templates/react-native-app/TEMPLATE.md +122 -122
  193. package/.agent/skills/appflow-wireframe/SKILL.md +129 -69
  194. package/.agent/skills/apple-design/SKILL.md +130 -60
  195. package/.agent/skills/architecture/SKILL.md +216 -155
  196. package/.agent/skills/architecture-drift/SKILL.md +121 -0
  197. package/.agent/skills/architecture-intelligence/SKILL.md +53 -0
  198. package/.agent/skills/audit-and-fix/SKILL.md +133 -63
  199. package/.agent/skills/authentication-best-practices/SKILL.md +191 -121
  200. package/.agent/skills/autonomous-execution/SKILL.md +154 -0
  201. package/.agent/skills/backend-alembic/SKILL.md +91 -0
  202. package/.agent/skills/backend-architecture-auditor/SKILL.md +101 -0
  203. package/.agent/skills/backend-mongodb/SKILL.md +133 -0
  204. package/.agent/skills/backend-mysql/SKILL.md +84 -0
  205. package/.agent/skills/backend-performance-auditor/SKILL.md +100 -0
  206. package/.agent/skills/backend-postgresql/SKILL.md +117 -0
  207. package/.agent/skills/backend-redis/SKILL.md +122 -0
  208. package/.agent/skills/backend-security-expert/SKILL.md +111 -50
  209. package/.agent/skills/backend-sqlalchemy/SKILL.md +107 -0
  210. package/.agent/skills/backend-sqlite/SKILL.md +93 -0
  211. package/.agent/skills/backend-testing-auditor/SKILL.md +113 -0
  212. package/.agent/skills/baseline-ui/SKILL.md +99 -29
  213. package/.agent/skills/bash-linux/SKILL.md +164 -106
  214. package/.agent/skills/behavioral-modes/SKILL.md +235 -165
  215. package/.agent/skills/better-colors/SKILL.md +153 -83
  216. package/.agent/skills/better-typography/SKILL.md +137 -67
  217. package/.agent/skills/better-ui/SKILL.md +160 -99
  218. package/.agent/skills/bolder/SKILL.md +91 -21
  219. package/.agent/skills/brainstorming/SKILL.md +494 -434
  220. package/.agent/skills/browser-audit/SKILL.md +134 -64
  221. package/.agent/skills/browser-native-ai/SKILL.md +111 -41
  222. package/.agent/skills/build-primitive/SKILL.md +93 -23
  223. package/.agent/skills/building-native-ui/SKILL.md +191 -130
  224. package/.agent/skills/cicd-pro/SKILL.md +440 -379
  225. package/.agent/skills/clarify/SKILL.md +98 -28
  226. package/.agent/skills/clean-code/SKILL.md +395 -334
  227. package/.agent/skills/cloud-architect/SKILL.md +437 -376
  228. package/.agent/skills/cobejs/SKILL.md +120 -50
  229. package/.agent/skills/code-review-checklist/SKILL.md +198 -128
  230. package/.agent/skills/codebase-design/SKILL.md +109 -48
  231. package/.agent/skills/colorize/SKILL.md +100 -30
  232. package/.agent/skills/compact-landing/SKILL.md +93 -23
  233. package/.agent/skills/company-logos/SKILL.md +96 -26
  234. package/.agent/skills/config-validator/SKILL.md +151 -93
  235. package/.agent/skills/containerization-pro/SKILL.md +450 -389
  236. package/.agent/skills/context-engineering-pro/SKILL.md +113 -41
  237. package/.agent/skills/create-design-md/SKILL.md +128 -58
  238. package/.agent/skills/critique/SKILL.md +115 -45
  239. package/.agent/skills/csharp-developer/SKILL.md +512 -442
  240. package/.agent/skills/data-validation-schemas/SKILL.md +321 -263
  241. package/.agent/skills/database-design/SKILL.md +247 -186
  242. package/.agent/skills/delight/SKILL.md +88 -18
  243. package/.agent/skills/deployment-procedures/SKILL.md +159 -101
  244. package/.agent/skills/design-lab/SKILL.md +85 -15
  245. package/.agent/skills/devops-engineer/SKILL.md +339 -269
  246. package/.agent/skills/devops-incident-responder/SKILL.md +130 -72
  247. package/.agent/skills/diagnosing-bugs/SKILL.md +208 -138
  248. package/.agent/skills/distill/SKILL.md +88 -18
  249. package/.agent/skills/documentation-templates/SKILL.md +275 -217
  250. package/.agent/skills/domain-modeling/SKILL.md +101 -31
  251. package/.agent/skills/duckdb-analytical-sql/SKILL.md +100 -28
  252. package/.agent/skills/edge-ai-mobile/SKILL.md +92 -20
  253. package/.agent/skills/edge-computing/SKILL.md +168 -110
  254. package/.agent/skills/emil-design-eng/SKILL.md +170 -100
  255. package/.agent/skills/error-resilience/SKILL.md +431 -370
  256. package/.agent/skills/expo-router-v4/SKILL.md +126 -54
  257. package/.agent/skills/extract-design-system/SKILL.md +146 -88
  258. package/.agent/skills/fabel-protocol/SKILL.md +316 -246
  259. package/.agent/skills/failure-mode-analysis/SKILL.md +124 -0
  260. package/.agent/skills/fastapi-pro/SKILL.md +123 -0
  261. package/.agent/skills/fixing-accessibility/SKILL.md +129 -59
  262. package/.agent/skills/fixing-metadata/SKILL.md +130 -60
  263. package/.agent/skills/fixing-motion-performance/SKILL.md +115 -45
  264. package/.agent/skills/framer-motion-expert/SKILL.md +259 -204
  265. package/.agent/skills/frontend-design/SKILL.md +139 -69
  266. package/.agent/skills/frontend-security-expert/SKILL.md +94 -33
  267. package/.agent/skills/game-design-expert/SKILL.md +126 -68
  268. package/.agent/skills/game-engineering-expert/SKILL.md +135 -77
  269. package/.agent/skills/generative-ui-expert/SKILL.md +142 -72
  270. package/.agent/skills/geo-fundamentals/SKILL.md +134 -76
  271. package/.agent/skills/git-pro/SKILL.md +429 -368
  272. package/.agent/skills/github-operations/SKILL.md +329 -259
  273. package/.agent/skills/gpt-taste/SKILL.md +92 -22
  274. package/.agent/skills/graph-engineering/SKILL.md +104 -16
  275. package/.agent/skills/gsap-core/SKILL.md +312 -242
  276. package/.agent/skills/gsap-frameworks/SKILL.md +204 -134
  277. package/.agent/skills/gsap-performance/SKILL.md +130 -60
  278. package/.agent/skills/gsap-plugins/SKILL.md +476 -406
  279. package/.agent/skills/gsap-react/SKILL.md +248 -178
  280. package/.agent/skills/gsap-scrolltrigger/SKILL.md +347 -277
  281. package/.agent/skills/gsap-timeline/SKILL.md +157 -87
  282. package/.agent/skills/gsap-utils/SKILL.md +334 -264
  283. package/.agent/skills/harden/SKILL.md +97 -27
  284. package/.agent/skills/harness-protocol/SKILL.md +91 -21
  285. package/.agent/skills/hf-cli/SKILL.md +86 -6
  286. package/.agent/skills/hf-cloud-aws-context-discovery/SKILL.md +86 -8
  287. package/.agent/skills/hf-cloud-python-env-setup/SKILL.md +86 -8
  288. package/.agent/skills/hf-cloud-sagemaker-deployment-planner/SKILL.md +86 -8
  289. package/.agent/skills/hf-cloud-sagemaker-iam-preflight/SKILL.md +86 -8
  290. package/.agent/skills/hf-cloud-sagemaker-production-defaults/SKILL.md +86 -8
  291. package/.agent/skills/hf-cloud-serving-image-selection/SKILL.md +86 -8
  292. package/.agent/skills/hf-mem/SKILL.md +86 -6
  293. package/.agent/skills/huggingface-best/SKILL.md +86 -16
  294. package/.agent/skills/huggingface-community-evals/SKILL.md +86 -8
  295. package/.agent/skills/huggingface-datasets/SKILL.md +86 -8
  296. package/.agent/skills/huggingface-gradio/SKILL.md +86 -8
  297. package/.agent/skills/huggingface-llm-trainer/SKILL.md +86 -9
  298. package/.agent/skills/huggingface-local-models/SKILL.md +86 -8
  299. package/.agent/skills/huggingface-lora-space-builder/SKILL.md +86 -8
  300. package/.agent/skills/huggingface-paper-publisher/SKILL.md +86 -7
  301. package/.agent/skills/huggingface-papers/SKILL.md +86 -8
  302. package/.agent/skills/huggingface-spaces/SKILL.md +87 -9
  303. package/.agent/skills/huggingface-tool-builder/SKILL.md +86 -8
  304. package/.agent/skills/huggingface-trackio/SKILL.md +77 -8
  305. package/.agent/skills/huggingface-vision-trainer/SKILL.md +86 -8
  306. package/.agent/skills/huggingface-zerogpu/SKILL.md +86 -8
  307. package/.agent/skills/human-gate-negotiation/SKILL.md +83 -17
  308. package/.agent/skills/i18n-localization/SKILL.md +160 -102
  309. package/.agent/skills/impeccable/SKILL.md +95 -25
  310. package/.agent/skills/improve-codebase-architecture/SKILL.md +90 -20
  311. package/.agent/skills/improve-ui/SKILL.md +107 -37
  312. package/.agent/skills/intelligent-routing/SKILL.md +243 -180
  313. package/.agent/skills/knowledge-graph/SKILL.md +109 -39
  314. package/.agent/skills/landing-page/SKILL.md +106 -36
  315. package/.agent/skills/lint-and-validate/SKILL.md +249 -191
  316. package/.agent/skills/llm-engineering/SKILL.md +394 -324
  317. package/.agent/skills/local-first/SKILL.md +163 -105
  318. package/.agent/skills/local-first-architecture/SKILL.md +100 -39
  319. package/.agent/skills/lottie-animation/SKILL.md +109 -39
  320. package/.agent/skills/marquee-loop/SKILL.md +121 -51
  321. package/.agent/skills/masked-reveal/SKILL.md +267 -198
  322. package/.agent/skills/mcp-builder/SKILL.md +131 -73
  323. package/.agent/skills/micro-interaction/SKILL.md +281 -219
  324. package/.agent/skills/mobile-design/SKILL.md +274 -213
  325. package/.agent/skills/monorepo-management/SKILL.md +319 -261
  326. package/.agent/skills/morphing-icons/SKILL.md +379 -310
  327. package/.agent/skills/motion-engineering/SKILL.md +225 -164
  328. package/.agent/skills/nextjs-react-expert/SKILL.md +247 -186
  329. package/.agent/skills/nodejs-best-practices/SKILL.md +570 -509
  330. package/.agent/skills/observability/SKILL.md +337 -267
  331. package/.agent/skills/opentelemetry-observability/SKILL.md +106 -34
  332. package/.agent/skills/page-transition-animation/SKILL.md +130 -60
  333. package/.agent/skills/parallel-agents/SKILL.md +136 -78
  334. package/.agent/skills/performance-profiling/SKILL.md +263 -193
  335. package/.agent/skills/plan-writing/SKILL.md +156 -95
  336. package/.agent/skills/platform-engineer/SKILL.md +134 -76
  337. package/.agent/skills/platform-engineering-opentofu/SKILL.md +114 -42
  338. package/.agent/skills/playwright-ai-e2e/SKILL.md +100 -28
  339. package/.agent/skills/playwright-best-practices/SKILL.md +174 -116
  340. package/.agent/skills/polish/SKILL.md +90 -20
  341. package/.agent/skills/powershell-windows/SKILL.md +156 -86
  342. package/.agent/skills/pricing-page/SKILL.md +91 -21
  343. package/.agent/skills/product-aware-heuristics/SKILL.md +424 -354
  344. package/.agent/skills/progressive-blur/SKILL.md +122 -52
  345. package/.agent/skills/project-idioms/SKILL.md +125 -55
  346. package/.agent/skills/property-based-testing/SKILL.md +104 -32
  347. package/.agent/skills/python-patterns/SKILL.md +245 -187
  348. package/.agent/skills/python-pro/SKILL.md +333 -272
  349. package/.agent/skills/quieter/SKILL.md +91 -21
  350. package/.agent/skills/react-doctor/SKILL.md +93 -23
  351. package/.agent/skills/react-specialist/SKILL.md +309 -248
  352. package/.agent/skills/readme-builder/SKILL.md +294 -236
  353. package/.agent/skills/realtime-patterns/SKILL.md +317 -247
  354. package/.agent/skills/red-team-tactics/SKILL.md +220 -159
  355. package/.agent/skills/redesign-skill/SKILL.md +88 -18
  356. package/.agent/skills/review-animations/SKILL.md +91 -21
  357. package/.agent/skills/review-animations/STANDARDS.md +87 -87
  358. package/.agent/skills/rust-pro/SKILL.md +680 -619
  359. package/.agent/skills/semantic-filesystem-navigation/SKILL.md +69 -14
  360. package/.agent/skills/seo-fundamentals/SKILL.md +165 -107
  361. package/.agent/skills/server-management/SKILL.md +203 -145
  362. package/.agent/skills/session-log-interrogation/SKILL.md +70 -18
  363. package/.agent/skills/shadcn-ui-expert/SKILL.md +221 -163
  364. package/.agent/skills/shape/SKILL.md +96 -26
  365. package/.agent/skills/skill-creator/SKILL.md +213 -145
  366. package/.agent/skills/soft-skill/SKILL.md +95 -25
  367. package/.agent/skills/sounds-on-the-web/SKILL.md +115 -45
  368. package/.agent/skills/sql-pro/SKILL.md +653 -592
  369. package/.agent/skills/subagent-driven-development/SKILL.md +78 -18
  370. package/.agent/skills/supabase-postgres-best-practices/SKILL.md +93 -32
  371. package/.agent/skills/svg-animation/SKILL.md +388 -319
  372. package/.agent/skills/swiftui-expert/SKILL.md +190 -132
  373. package/.agent/skills/swiss-design/SKILL.md +87 -17
  374. package/.agent/skills/system-design-pro/SKILL.md +238 -294
  375. package/.agent/skills/systematic-debugging/SKILL.md +154 -96
  376. package/.agent/skills/systematic-debugging/condition-based-waiting.md +120 -120
  377. package/.agent/skills/systematic-debugging/defense-in-depth.md +128 -128
  378. package/.agent/skills/systematic-debugging/root-cause-tracing.md +183 -183
  379. package/.agent/skills/tailwind-patterns/SKILL.md +617 -547
  380. package/.agent/skills/taste-skill/SKILL.md +94 -24
  381. package/.agent/skills/tdd-workflow/SKILL.md +133 -72
  382. package/.agent/skills/test-result-analyzer/SKILL.md +304 -234
  383. package/.agent/skills/testing-patterns/SKILL.md +567 -497
  384. package/.agent/skills/thermo-nuclear-code-quality-review/SKILL.md +104 -34
  385. package/.agent/skills/thinking-protocol/SKILL.md +65 -7
  386. package/.agent/skills/to-spring-or-not-to-spring/SKILL.md +90 -20
  387. package/.agent/skills/train-sentence-transformers/SKILL.md +86 -8
  388. package/.agent/skills/transformers-js/SKILL.md +86 -15
  389. package/.agent/skills/transformers-js/references/CONFIGURATION.md +1 -1
  390. package/.agent/skills/transitions-dev/SKILL.md +136 -66
  391. package/.agent/skills/trend-researcher/SKILL.md +232 -162
  392. package/.agent/skills/tribunal-instincts-memory/SKILL.md +74 -19
  393. package/.agent/skills/trl-training/SKILL.md +86 -16
  394. package/.agent/skills/typescript-advanced/SKILL.md +334 -273
  395. package/.agent/skills/typeset/SKILL.md +101 -31
  396. package/.agent/skills/ui-reasoning-engine/SKILL.md +191 -121
  397. package/.agent/skills/ui-skill-packs/SKILL.md +95 -25
  398. package/.agent/skills/ui-skills-root/SKILL.md +118 -48
  399. package/.agent/skills/ui-ux-pro-max/SKILL.md +145 -75
  400. package/.agent/skills/ui-ux-researcher/SKILL.md +235 -165
  401. package/.agent/skills/vector-search-pgvector/SKILL.md +118 -46
  402. package/.agent/skills/verification-before-completion/SKILL.md +151 -79
  403. package/.agent/skills/vue-expert/SKILL.md +288 -227
  404. package/.agent/skills/vulnerability-scanner/SKILL.md +409 -342
  405. package/.agent/skills/web-accessibility-auditor/SKILL.md +204 -146
  406. package/.agent/skills/web-design-guidelines/SKILL.md +92 -22
  407. package/.agent/skills/web-quality-audit/SKILL.md +90 -20
  408. package/.agent/skills/webapp-testing/SKILL.md +152 -94
  409. package/.agent/skills/webgpu-performance/SKILL.md +126 -56
  410. package/.agent/skills/whimsy-injector/SKILL.md +339 -269
  411. package/.agent/skills/workflow-optimizer/SKILL.md +222 -152
  412. package/.agent/skills/zero-trust-passkeys/SKILL.md +135 -63
  413. package/.agent/skills_inventory.json +6922 -0
  414. package/.agent/templates/DESIGN.md +843 -843
  415. package/.agent/templates/design-tokens.json +140 -140
  416. package/.agent/templates/sdd/implementer-prompt.md +62 -62
  417. package/.agent/templates/sdd/re-review-prompt.md +36 -36
  418. package/.agent/templates/sdd/task-reviewer-prompt.md +78 -78
  419. package/.agent/workflows/acf.md +153 -153
  420. package/.agent/workflows/api-tester.md +189 -189
  421. package/.agent/workflows/arch.md +80 -0
  422. package/.agent/workflows/assimilate.md +24 -21
  423. package/.agent/workflows/audit-live.md +53 -53
  424. package/.agent/workflows/audit.md +171 -172
  425. package/.agent/workflows/brainstorm.md +157 -157
  426. package/.agent/workflows/changelog.md +152 -152
  427. package/.agent/workflows/compare-web.md +35 -35
  428. package/.agent/workflows/context.md +102 -102
  429. package/.agent/workflows/contract.md +79 -79
  430. package/.agent/workflows/create.md +182 -182
  431. package/.agent/workflows/debug.md +201 -201
  432. package/.agent/workflows/deploy.md +215 -215
  433. package/.agent/workflows/enhance.md +165 -165
  434. package/.agent/workflows/fix-ci.md +94 -94
  435. package/.agent/workflows/fix.md +149 -149
  436. package/.agent/workflows/generate.md +221 -216
  437. package/.agent/workflows/htop.md +26 -22
  438. package/.agent/workflows/marathon.md +290 -291
  439. package/.agent/workflows/migrate.md +198 -198
  440. package/.agent/workflows/minimal.md +101 -101
  441. package/.agent/workflows/orchestrate.md +205 -205
  442. package/.agent/workflows/performance-benchmarker.md +148 -148
  443. package/.agent/workflows/pipeline.md +165 -165
  444. package/.agent/workflows/plan.md +206 -206
  445. package/.agent/workflows/preview.md +116 -116
  446. package/.agent/workflows/refactor.md +207 -207
  447. package/.agent/workflows/resume.md +23 -20
  448. package/.agent/workflows/review-ai.md +139 -139
  449. package/.agent/workflows/review.md +155 -155
  450. package/.agent/workflows/sdd.md +137 -137
  451. package/.agent/workflows/session.md +135 -135
  452. package/.agent/workflows/skill-enhancement-engine.md +84 -84
  453. package/.agent/workflows/status.md +112 -112
  454. package/.agent/workflows/strengthen-skills.md +174 -174
  455. package/.agent/workflows/super-prompt.md +146 -146
  456. package/.agent/workflows/swarm.md +218 -218
  457. package/.agent/workflows/team-mode.md +25 -22
  458. package/.agent/workflows/test.md +224 -224
  459. package/.agent/workflows/tribunal-backend.md +161 -149
  460. package/.agent/workflows/tribunal-cicd.md +109 -109
  461. package/.agent/workflows/tribunal-database.md +142 -142
  462. package/.agent/workflows/tribunal-frontend.md +163 -157
  463. package/.agent/workflows/tribunal-full.md +156 -156
  464. package/.agent/workflows/tribunal-mobile.md +142 -142
  465. package/.agent/workflows/tribunal-performance.md +149 -149
  466. package/.agent/workflows/tribunal-speed.md +222 -222
  467. package/.agent/workflows/tribunal-ui.md +102 -97
  468. package/.agent/workflows/ui-ux-pro-max.md +103 -103
  469. package/.agents/skills/12-principles-of-animation/SKILL.md +91 -21
  470. package/.agents/skills/60fps-animation/SKILL.md +118 -61
  471. package/.agents/skills/accessible-animation/SKILL.md +214 -152
  472. package/.agents/skills/adapt/SKILL.md +98 -28
  473. package/.agents/skills/adr-generation/SKILL.md +133 -0
  474. package/.agents/skills/advanced-rag-pipelines/SKILL.md +125 -64
  475. package/.agents/skills/agent-organizer/SKILL.md +142 -84
  476. package/.agents/skills/agent-syscall-guidelines/SKILL.md +88 -13
  477. package/.agents/skills/agentic-patterns/SKILL.md +314 -244
  478. package/.agents/skills/agentic-workflows-2026/SKILL.md +137 -65
  479. package/.agents/skills/agentshield-security/SKILL.md +74 -15
  480. package/.agents/skills/ai-app-hardening/SKILL.md +99 -27
  481. package/.agents/skills/ai-prompt-injection-defense/SKILL.md +191 -130
  482. package/.agents/skills/animation-on-scroll/SKILL.md +225 -163
  483. package/.agents/skills/animation-systems/SKILL.md +227 -165
  484. package/.agents/skills/antfu-conventions/SKILL.md +96 -26
  485. package/.agents/skills/anti-slop-enforcement/SKILL.md +118 -0
  486. package/.agents/skills/api-patterns/SKILL.md +247 -186
  487. package/.agents/skills/api-security-auditor/SKILL.md +204 -126
  488. package/.agents/skills/app-builder/SKILL.md +556 -501
  489. package/.agents/skills/app-builder/templates/SKILL.md +108 -108
  490. package/.agents/skills/app-builder/templates/astro-static/TEMPLATE.md +76 -76
  491. package/.agents/skills/app-builder/templates/chrome-extension/TEMPLATE.md +92 -92
  492. package/.agents/skills/app-builder/templates/cli-tool/TEMPLATE.md +88 -88
  493. package/.agents/skills/app-builder/templates/electron-desktop/TEMPLATE.md +88 -88
  494. package/.agents/skills/app-builder/templates/express-api/TEMPLATE.md +83 -83
  495. package/.agents/skills/app-builder/templates/flutter-app/TEMPLATE.md +90 -90
  496. package/.agents/skills/app-builder/templates/monorepo-turborepo/TEMPLATE.md +90 -90
  497. package/.agents/skills/app-builder/templates/nextjs-fullstack/TEMPLATE.md +126 -126
  498. package/.agents/skills/app-builder/templates/nextjs-saas/TEMPLATE.md +127 -127
  499. package/.agents/skills/app-builder/templates/nextjs-static/TEMPLATE.md +172 -172
  500. package/.agents/skills/app-builder/templates/nuxt-app/TEMPLATE.md +139 -139
  501. package/.agents/skills/app-builder/templates/python-fastapi/TEMPLATE.md +83 -83
  502. package/.agents/skills/app-builder/templates/react-native-app/TEMPLATE.md +122 -122
  503. package/.agents/skills/appflow-wireframe/SKILL.md +129 -69
  504. package/.agents/skills/apple-design/SKILL.md +130 -60
  505. package/.agents/skills/architecture/SKILL.md +216 -155
  506. package/.agents/skills/architecture-drift/SKILL.md +121 -0
  507. package/.agents/skills/architecture-intelligence/SKILL.md +53 -0
  508. package/.agents/skills/audit-and-fix/SKILL.md +133 -63
  509. package/.agents/skills/authentication-best-practices/SKILL.md +191 -121
  510. package/.agents/skills/autonomous-execution/SKILL.md +154 -0
  511. package/.agents/skills/backend-alembic/SKILL.md +91 -0
  512. package/.agents/skills/backend-architecture-auditor/SKILL.md +101 -0
  513. package/.agents/skills/backend-mongodb/SKILL.md +133 -0
  514. package/.agents/skills/backend-mysql/SKILL.md +84 -0
  515. package/.agents/skills/backend-performance-auditor/SKILL.md +100 -0
  516. package/.agents/skills/backend-postgresql/SKILL.md +117 -0
  517. package/.agents/skills/backend-redis/SKILL.md +122 -0
  518. package/.agents/skills/backend-security-expert/SKILL.md +111 -50
  519. package/.agents/skills/backend-sqlalchemy/SKILL.md +107 -0
  520. package/.agents/skills/backend-sqlite/SKILL.md +93 -0
  521. package/.agents/skills/backend-testing-auditor/SKILL.md +113 -0
  522. package/.agents/skills/baseline-ui/SKILL.md +99 -29
  523. package/.agents/skills/bash-linux/SKILL.md +164 -106
  524. package/.agents/skills/behavioral-modes/SKILL.md +235 -165
  525. package/.agents/skills/better-colors/SKILL.md +153 -83
  526. package/.agents/skills/better-typography/SKILL.md +137 -67
  527. package/.agents/skills/better-ui/SKILL.md +160 -99
  528. package/.agents/skills/bolder/SKILL.md +91 -21
  529. package/.agents/skills/brainstorming/SKILL.md +494 -434
  530. package/.agents/skills/browser-audit/SKILL.md +134 -64
  531. package/.agents/skills/browser-native-ai/SKILL.md +111 -41
  532. package/.agents/skills/build-primitive/SKILL.md +93 -23
  533. package/.agents/skills/building-native-ui/SKILL.md +191 -130
  534. package/.agents/skills/cicd-pro/SKILL.md +440 -379
  535. package/.agents/skills/clarify/SKILL.md +98 -28
  536. package/.agents/skills/clean-code/SKILL.md +395 -334
  537. package/.agents/skills/cloud-architect/SKILL.md +437 -376
  538. package/.agents/skills/cobejs/SKILL.md +120 -50
  539. package/.agents/skills/code-review-checklist/SKILL.md +198 -128
  540. package/.agents/skills/codebase-design/SKILL.md +109 -48
  541. package/.agents/skills/colorize/SKILL.md +100 -30
  542. package/.agents/skills/compact-landing/SKILL.md +93 -23
  543. package/.agents/skills/company-logos/SKILL.md +96 -26
  544. package/.agents/skills/config-validator/SKILL.md +151 -93
  545. package/.agents/skills/containerization-pro/SKILL.md +450 -389
  546. package/.agents/skills/context-engineering-pro/SKILL.md +113 -41
  547. package/.agents/skills/create-design-md/SKILL.md +128 -58
  548. package/.agents/skills/critique/SKILL.md +115 -45
  549. package/.agents/skills/csharp-developer/SKILL.md +512 -442
  550. package/.agents/skills/data-validation-schemas/SKILL.md +321 -263
  551. package/.agents/skills/database-design/SKILL.md +247 -186
  552. package/.agents/skills/delight/SKILL.md +88 -18
  553. package/.agents/skills/deployment-procedures/SKILL.md +159 -101
  554. package/.agents/skills/design-lab/SKILL.md +85 -15
  555. package/.agents/skills/devops-engineer/SKILL.md +339 -269
  556. package/.agents/skills/devops-incident-responder/SKILL.md +130 -72
  557. package/.agents/skills/diagnosing-bugs/SKILL.md +208 -138
  558. package/.agents/skills/distill/SKILL.md +88 -18
  559. package/.agents/skills/documentation-templates/SKILL.md +275 -217
  560. package/.agents/skills/domain-modeling/SKILL.md +101 -31
  561. package/.agents/skills/duckdb-analytical-sql/SKILL.md +100 -28
  562. package/.agents/skills/edge-ai-mobile/SKILL.md +92 -20
  563. package/.agents/skills/edge-computing/SKILL.md +168 -110
  564. package/.agents/skills/emil-design-eng/SKILL.md +170 -100
  565. package/.agents/skills/error-resilience/SKILL.md +431 -370
  566. package/.agents/skills/expo-router-v4/SKILL.md +126 -54
  567. package/.agents/skills/extract-design-system/SKILL.md +146 -88
  568. package/.agents/skills/fabel-protocol/SKILL.md +316 -246
  569. package/.agents/skills/failure-mode-analysis/SKILL.md +124 -0
  570. package/.agents/skills/fastapi-pro/SKILL.md +123 -0
  571. package/.agents/skills/fixing-accessibility/SKILL.md +129 -59
  572. package/.agents/skills/fixing-metadata/SKILL.md +130 -60
  573. package/.agents/skills/fixing-motion-performance/SKILL.md +115 -45
  574. package/.agents/skills/framer-motion-expert/SKILL.md +259 -204
  575. package/.agents/skills/frontend-design/SKILL.md +139 -69
  576. package/.agents/skills/frontend-security-expert/SKILL.md +94 -33
  577. package/.agents/skills/game-design-expert/SKILL.md +126 -68
  578. package/.agents/skills/game-engineering-expert/SKILL.md +135 -77
  579. package/.agents/skills/generative-ui-expert/SKILL.md +142 -72
  580. package/.agents/skills/geo-fundamentals/SKILL.md +134 -76
  581. package/.agents/skills/git-pro/SKILL.md +429 -368
  582. package/.agents/skills/github-operations/SKILL.md +329 -259
  583. package/.agents/skills/gpt-taste/SKILL.md +92 -22
  584. package/.agents/skills/graph-engineering/SKILL.md +104 -16
  585. package/.agents/skills/gsap-core/SKILL.md +312 -242
  586. package/.agents/skills/gsap-frameworks/SKILL.md +204 -134
  587. package/.agents/skills/gsap-performance/SKILL.md +130 -60
  588. package/.agents/skills/gsap-plugins/SKILL.md +476 -406
  589. package/.agents/skills/gsap-react/SKILL.md +248 -178
  590. package/.agents/skills/gsap-scrolltrigger/SKILL.md +347 -277
  591. package/.agents/skills/gsap-timeline/SKILL.md +157 -87
  592. package/.agents/skills/gsap-utils/SKILL.md +334 -264
  593. package/.agents/skills/harden/SKILL.md +97 -27
  594. package/.agents/skills/harness-protocol/SKILL.md +91 -21
  595. package/.agents/skills/hf-cli/SKILL.md +86 -6
  596. package/.agents/skills/hf-cloud-aws-context-discovery/SKILL.md +86 -8
  597. package/.agents/skills/hf-cloud-python-env-setup/SKILL.md +86 -8
  598. package/.agents/skills/hf-cloud-sagemaker-deployment-planner/SKILL.md +86 -8
  599. package/.agents/skills/hf-cloud-sagemaker-iam-preflight/SKILL.md +86 -8
  600. package/.agents/skills/hf-cloud-sagemaker-production-defaults/SKILL.md +86 -8
  601. package/.agents/skills/hf-cloud-serving-image-selection/SKILL.md +86 -8
  602. package/.agents/skills/hf-mem/SKILL.md +86 -6
  603. package/.agents/skills/huggingface-best/SKILL.md +86 -16
  604. package/.agents/skills/huggingface-community-evals/SKILL.md +86 -8
  605. package/.agents/skills/huggingface-datasets/SKILL.md +86 -8
  606. package/.agents/skills/huggingface-gradio/SKILL.md +86 -8
  607. package/.agents/skills/huggingface-llm-trainer/SKILL.md +86 -9
  608. package/.agents/skills/huggingface-local-models/SKILL.md +86 -8
  609. package/.agents/skills/huggingface-lora-space-builder/SKILL.md +86 -8
  610. package/.agents/skills/huggingface-paper-publisher/SKILL.md +86 -7
  611. package/.agents/skills/huggingface-papers/SKILL.md +86 -8
  612. package/.agents/skills/huggingface-spaces/SKILL.md +87 -9
  613. package/.agents/skills/huggingface-tool-builder/SKILL.md +86 -8
  614. package/.agents/skills/huggingface-trackio/SKILL.md +77 -8
  615. package/.agents/skills/huggingface-vision-trainer/SKILL.md +86 -8
  616. package/.agents/skills/huggingface-zerogpu/SKILL.md +86 -8
  617. package/.agents/skills/human-gate-negotiation/SKILL.md +83 -17
  618. package/.agents/skills/i18n-localization/SKILL.md +160 -102
  619. package/.agents/skills/impeccable/SKILL.md +95 -25
  620. package/.agents/skills/improve-codebase-architecture/SKILL.md +90 -20
  621. package/.agents/skills/improve-ui/SKILL.md +107 -37
  622. package/.agents/skills/intelligent-routing/SKILL.md +243 -180
  623. package/.agents/skills/knowledge-graph/SKILL.md +109 -39
  624. package/.agents/skills/landing-page/SKILL.md +106 -36
  625. package/.agents/skills/lint-and-validate/SKILL.md +249 -191
  626. package/.agents/skills/llm-engineering/SKILL.md +394 -324
  627. package/.agents/skills/local-first/SKILL.md +163 -105
  628. package/.agents/skills/local-first-architecture/SKILL.md +100 -39
  629. package/.agents/skills/lottie-animation/SKILL.md +109 -39
  630. package/.agents/skills/marquee-loop/SKILL.md +121 -51
  631. package/.agents/skills/masked-reveal/SKILL.md +267 -198
  632. package/.agents/skills/mcp-builder/SKILL.md +131 -73
  633. package/.agents/skills/micro-interaction/SKILL.md +281 -219
  634. package/.agents/skills/mobile-design/SKILL.md +274 -213
  635. package/.agents/skills/monorepo-management/SKILL.md +319 -261
  636. package/.agents/skills/morphing-icons/SKILL.md +379 -310
  637. package/.agents/skills/motion-engineering/SKILL.md +225 -164
  638. package/.agents/skills/nextjs-react-expert/SKILL.md +247 -186
  639. package/.agents/skills/nodejs-best-practices/SKILL.md +570 -509
  640. package/.agents/skills/observability/SKILL.md +337 -267
  641. package/.agents/skills/opentelemetry-observability/SKILL.md +106 -34
  642. package/.agents/skills/page-transition-animation/SKILL.md +130 -60
  643. package/.agents/skills/parallel-agents/SKILL.md +136 -78
  644. package/.agents/skills/performance-profiling/SKILL.md +263 -193
  645. package/.agents/skills/plan-writing/SKILL.md +156 -95
  646. package/.agents/skills/platform-engineer/SKILL.md +134 -76
  647. package/.agents/skills/platform-engineering-opentofu/SKILL.md +114 -42
  648. package/.agents/skills/playwright-ai-e2e/SKILL.md +100 -28
  649. package/.agents/skills/playwright-best-practices/SKILL.md +174 -116
  650. package/.agents/skills/polish/SKILL.md +90 -20
  651. package/.agents/skills/powershell-windows/SKILL.md +156 -86
  652. package/.agents/skills/pricing-page/SKILL.md +91 -21
  653. package/.agents/skills/product-aware-heuristics/SKILL.md +424 -354
  654. package/.agents/skills/progressive-blur/SKILL.md +122 -52
  655. package/.agents/skills/project-idioms/SKILL.md +125 -55
  656. package/.agents/skills/property-based-testing/SKILL.md +104 -32
  657. package/.agents/skills/python-patterns/SKILL.md +245 -187
  658. package/.agents/skills/python-pro/SKILL.md +333 -272
  659. package/.agents/skills/quieter/SKILL.md +91 -21
  660. package/.agents/skills/react-doctor/SKILL.md +93 -23
  661. package/.agents/skills/react-specialist/SKILL.md +309 -248
  662. package/.agents/skills/readme-builder/SKILL.md +294 -236
  663. package/.agents/skills/realtime-patterns/SKILL.md +317 -247
  664. package/.agents/skills/red-team-tactics/SKILL.md +220 -159
  665. package/.agents/skills/redesign-skill/SKILL.md +88 -18
  666. package/.agents/skills/review-animations/SKILL.md +91 -21
  667. package/.agents/skills/review-animations/STANDARDS.md +87 -87
  668. package/.agents/skills/rust-pro/SKILL.md +680 -619
  669. package/.agents/skills/semantic-filesystem-navigation/SKILL.md +69 -14
  670. package/.agents/skills/seo-fundamentals/SKILL.md +165 -107
  671. package/.agents/skills/server-management/SKILL.md +203 -145
  672. package/.agents/skills/session-log-interrogation/SKILL.md +70 -18
  673. package/.agents/skills/shadcn-ui-expert/SKILL.md +221 -163
  674. package/.agents/skills/shape/SKILL.md +96 -26
  675. package/.agents/skills/skill-creator/SKILL.md +213 -145
  676. package/.agents/skills/soft-skill/SKILL.md +95 -25
  677. package/.agents/skills/sounds-on-the-web/SKILL.md +115 -45
  678. package/.agents/skills/sql-pro/SKILL.md +653 -592
  679. package/.agents/skills/subagent-driven-development/SKILL.md +78 -18
  680. package/.agents/skills/supabase-postgres-best-practices/SKILL.md +93 -32
  681. package/.agents/skills/svg-animation/SKILL.md +388 -319
  682. package/.agents/skills/swiftui-expert/SKILL.md +190 -132
  683. package/.agents/skills/swiss-design/SKILL.md +87 -17
  684. package/.agents/skills/system-design-pro/SKILL.md +238 -294
  685. package/.agents/skills/systematic-debugging/SKILL.md +154 -96
  686. package/.agents/skills/systematic-debugging/condition-based-waiting.md +120 -120
  687. package/.agents/skills/systematic-debugging/defense-in-depth.md +128 -128
  688. package/.agents/skills/systematic-debugging/root-cause-tracing.md +183 -183
  689. package/.agents/skills/tailwind-patterns/SKILL.md +617 -547
  690. package/.agents/skills/taste-skill/SKILL.md +94 -24
  691. package/.agents/skills/tdd-workflow/SKILL.md +133 -72
  692. package/.agents/skills/test-result-analyzer/SKILL.md +304 -234
  693. package/.agents/skills/testing-patterns/SKILL.md +567 -497
  694. package/.agents/skills/thermo-nuclear-code-quality-review/SKILL.md +104 -34
  695. package/.agents/skills/thinking-protocol/SKILL.md +65 -7
  696. package/.agents/skills/to-spring-or-not-to-spring/SKILL.md +90 -20
  697. package/.agents/skills/train-sentence-transformers/SKILL.md +86 -8
  698. package/.agents/skills/transformers-js/SKILL.md +86 -15
  699. package/.agents/skills/transformers-js/references/CONFIGURATION.md +1 -1
  700. package/.agents/skills/transitions-dev/SKILL.md +136 -66
  701. package/.agents/skills/trend-researcher/SKILL.md +232 -162
  702. package/.agents/skills/tribunal-instincts-memory/SKILL.md +74 -19
  703. package/.agents/skills/trl-training/SKILL.md +86 -16
  704. package/.agents/skills/typescript-advanced/SKILL.md +334 -273
  705. package/.agents/skills/typeset/SKILL.md +101 -31
  706. package/.agents/skills/ui-reasoning-engine/SKILL.md +191 -121
  707. package/.agents/skills/ui-skill-packs/SKILL.md +95 -25
  708. package/.agents/skills/ui-skills-root/SKILL.md +118 -48
  709. package/.agents/skills/ui-ux-pro-max/SKILL.md +145 -75
  710. package/.agents/skills/ui-ux-researcher/SKILL.md +235 -165
  711. package/.agents/skills/vector-search-pgvector/SKILL.md +118 -46
  712. package/.agents/skills/verification-before-completion/SKILL.md +151 -79
  713. package/.agents/skills/vue-expert/SKILL.md +288 -227
  714. package/.agents/skills/vulnerability-scanner/SKILL.md +409 -342
  715. package/.agents/skills/web-accessibility-auditor/SKILL.md +204 -146
  716. package/.agents/skills/web-design-guidelines/SKILL.md +92 -22
  717. package/.agents/skills/web-quality-audit/SKILL.md +90 -20
  718. package/.agents/skills/webapp-testing/SKILL.md +152 -94
  719. package/.agents/skills/webgpu-performance/SKILL.md +126 -56
  720. package/.agents/skills/whimsy-injector/SKILL.md +339 -269
  721. package/.agents/skills/workflow-optimizer/SKILL.md +222 -152
  722. package/.agents/skills/zero-trust-passkeys/SKILL.md +135 -63
  723. package/AGENTS.md +93 -93
  724. package/CLAUDE.md +444 -444
  725. package/CONTRIBUTING.md +134 -134
  726. package/README.md +264 -242
  727. package/SECURITY.md +58 -52
  728. package/bin/adapter-install.js +264 -264
  729. package/bin/global-store.js +48 -48
  730. package/bin/mcp-server.js +1662 -1653
  731. package/bin/proxy-server.js +122 -122
  732. package/bin/spawn-agent.js +45 -45
  733. package/bin/tk-proxy.js +34 -34
  734. package/bin/tribunal-kit.js +113 -113
  735. package/bin/wrapper.js +225 -211
  736. package/hooks/hooks-cursor.json +10 -10
  737. package/hooks/hooks.json +10 -10
  738. package/hooks/session-start.js +77 -77
  739. package/mcp_config.json +18 -18
  740. package/package.json +20 -31
  741. package/{.claude-plugin → plugins/claude}/marketplace.json +14 -14
  742. package/{.claude-plugin → plugins/claude}/plugin.json +26 -26
  743. package/{.codex-plugin → plugins/codex}/plugin.json +41 -41
  744. package/{plugin.json → plugins/core-plugin.json} +1 -1
  745. package/{.cursor-plugin → plugins/cursor}/plugin.json +26 -26
  746. package/{.devin-plugin → plugins/devin}/plugin.json +14 -14
  747. package/{gemini-extension.json → plugins/gemini/extension.json} +1 -1
  748. package/{.hermes-plugin → plugins/hermes}/__init__.py +102 -102
  749. package/{.hermes-plugin → plugins/hermes}/plugin.yaml +6 -6
  750. package/{.kimi-plugin → plugins/kimi}/plugin.json +34 -34
  751. package/{marketplace.json → plugins/marketplace.json} +14 -14
  752. package/{.opencode → plugins/opencode}/INSTALL.md +42 -42
  753. package/{.opencode → plugins/opencode}/plugins/tribunal.js +110 -110
  754. package/{.opencode → plugins/opencode}/rules.md +258 -258
  755. package/{.pi → plugins/pi}/extensions/tribunal.ts +130 -130
  756. package/skills/12-principles-of-animation/SKILL.md +91 -21
  757. package/skills/60fps-animation/SKILL.md +118 -61
  758. package/skills/accessible-animation/SKILL.md +214 -152
  759. package/skills/adapt/SKILL.md +98 -28
  760. package/skills/adr-generation/SKILL.md +133 -0
  761. package/skills/advanced-rag-pipelines/SKILL.md +125 -64
  762. package/skills/agent-organizer/SKILL.md +142 -84
  763. package/skills/agent-syscall-guidelines/SKILL.md +88 -13
  764. package/skills/agentic-patterns/SKILL.md +314 -244
  765. package/skills/agentic-workflows-2026/SKILL.md +137 -65
  766. package/skills/agentshield-security/SKILL.md +74 -15
  767. package/skills/ai-app-hardening/SKILL.md +99 -27
  768. package/skills/ai-prompt-injection-defense/SKILL.md +191 -130
  769. package/skills/animation-on-scroll/SKILL.md +225 -163
  770. package/skills/animation-systems/SKILL.md +227 -165
  771. package/skills/antfu-conventions/SKILL.md +96 -26
  772. package/skills/anti-slop-enforcement/SKILL.md +118 -0
  773. package/skills/api-patterns/SKILL.md +247 -186
  774. package/skills/api-security-auditor/SKILL.md +204 -126
  775. package/skills/app-builder/SKILL.md +556 -501
  776. package/skills/app-builder/templates/SKILL.md +108 -108
  777. package/skills/app-builder/templates/astro-static/TEMPLATE.md +76 -76
  778. package/skills/app-builder/templates/chrome-extension/TEMPLATE.md +92 -92
  779. package/skills/app-builder/templates/cli-tool/TEMPLATE.md +88 -88
  780. package/skills/app-builder/templates/electron-desktop/TEMPLATE.md +88 -88
  781. package/skills/app-builder/templates/express-api/TEMPLATE.md +83 -83
  782. package/skills/app-builder/templates/flutter-app/TEMPLATE.md +90 -90
  783. package/skills/app-builder/templates/monorepo-turborepo/TEMPLATE.md +90 -90
  784. package/skills/app-builder/templates/nextjs-fullstack/TEMPLATE.md +126 -126
  785. package/skills/app-builder/templates/nextjs-saas/TEMPLATE.md +127 -127
  786. package/skills/app-builder/templates/nextjs-static/TEMPLATE.md +172 -172
  787. package/skills/app-builder/templates/nuxt-app/TEMPLATE.md +139 -139
  788. package/skills/app-builder/templates/python-fastapi/TEMPLATE.md +83 -83
  789. package/skills/app-builder/templates/react-native-app/TEMPLATE.md +122 -122
  790. package/skills/appflow-wireframe/SKILL.md +129 -69
  791. package/skills/apple-design/SKILL.md +130 -60
  792. package/skills/architecture/SKILL.md +216 -155
  793. package/skills/architecture-drift/SKILL.md +121 -0
  794. package/skills/architecture-intelligence/SKILL.md +53 -0
  795. package/skills/audit-and-fix/SKILL.md +133 -63
  796. package/skills/authentication-best-practices/SKILL.md +191 -121
  797. package/skills/autonomous-execution/SKILL.md +154 -0
  798. package/skills/backend-alembic/SKILL.md +91 -0
  799. package/skills/backend-architecture-auditor/SKILL.md +101 -0
  800. package/skills/backend-mongodb/SKILL.md +133 -0
  801. package/skills/backend-mysql/SKILL.md +84 -0
  802. package/skills/backend-performance-auditor/SKILL.md +100 -0
  803. package/skills/backend-postgresql/SKILL.md +117 -0
  804. package/skills/backend-redis/SKILL.md +122 -0
  805. package/skills/backend-security-expert/SKILL.md +111 -50
  806. package/skills/backend-sqlalchemy/SKILL.md +107 -0
  807. package/skills/backend-sqlite/SKILL.md +93 -0
  808. package/skills/backend-testing-auditor/SKILL.md +113 -0
  809. package/skills/baseline-ui/SKILL.md +99 -29
  810. package/skills/bash-linux/SKILL.md +164 -106
  811. package/skills/behavioral-modes/SKILL.md +235 -165
  812. package/skills/better-colors/SKILL.md +153 -83
  813. package/skills/better-typography/SKILL.md +137 -67
  814. package/skills/better-ui/SKILL.md +160 -99
  815. package/skills/bolder/SKILL.md +91 -21
  816. package/skills/brainstorming/SKILL.md +494 -434
  817. package/skills/browser-audit/SKILL.md +134 -64
  818. package/skills/browser-native-ai/SKILL.md +111 -41
  819. package/skills/build-primitive/SKILL.md +93 -23
  820. package/skills/building-native-ui/SKILL.md +191 -130
  821. package/skills/cicd-pro/SKILL.md +440 -379
  822. package/skills/clarify/SKILL.md +98 -28
  823. package/skills/clean-code/SKILL.md +395 -334
  824. package/skills/cloud-architect/SKILL.md +437 -376
  825. package/skills/cobejs/SKILL.md +120 -50
  826. package/skills/code-review-checklist/SKILL.md +198 -128
  827. package/skills/codebase-design/SKILL.md +109 -48
  828. package/skills/colorize/SKILL.md +100 -30
  829. package/skills/compact-landing/SKILL.md +93 -23
  830. package/skills/company-logos/SKILL.md +96 -26
  831. package/skills/config-validator/SKILL.md +151 -93
  832. package/skills/containerization-pro/SKILL.md +450 -389
  833. package/skills/context-engineering-pro/SKILL.md +113 -41
  834. package/skills/create-design-md/SKILL.md +128 -58
  835. package/skills/critique/SKILL.md +115 -45
  836. package/skills/csharp-developer/SKILL.md +512 -442
  837. package/skills/data-validation-schemas/SKILL.md +321 -263
  838. package/skills/database-design/SKILL.md +247 -186
  839. package/skills/delight/SKILL.md +88 -18
  840. package/skills/deployment-procedures/SKILL.md +159 -101
  841. package/skills/design-lab/SKILL.md +85 -15
  842. package/skills/devops-engineer/SKILL.md +339 -269
  843. package/skills/devops-incident-responder/SKILL.md +130 -72
  844. package/skills/diagnosing-bugs/SKILL.md +208 -138
  845. package/skills/distill/SKILL.md +88 -18
  846. package/skills/documentation-templates/SKILL.md +275 -217
  847. package/skills/domain-modeling/SKILL.md +101 -31
  848. package/skills/duckdb-analytical-sql/SKILL.md +100 -28
  849. package/skills/edge-ai-mobile/SKILL.md +92 -20
  850. package/skills/edge-computing/SKILL.md +168 -110
  851. package/skills/emil-design-eng/SKILL.md +170 -100
  852. package/skills/error-resilience/SKILL.md +431 -370
  853. package/skills/expo-router-v4/SKILL.md +126 -54
  854. package/skills/extract-design-system/SKILL.md +146 -88
  855. package/skills/fabel-protocol/SKILL.md +316 -246
  856. package/skills/failure-mode-analysis/SKILL.md +124 -0
  857. package/skills/fastapi-pro/SKILL.md +123 -0
  858. package/skills/fixing-accessibility/SKILL.md +129 -59
  859. package/skills/fixing-metadata/SKILL.md +130 -60
  860. package/skills/fixing-motion-performance/SKILL.md +115 -45
  861. package/skills/framer-motion-expert/SKILL.md +259 -204
  862. package/skills/frontend-design/SKILL.md +139 -69
  863. package/skills/frontend-security-expert/SKILL.md +94 -33
  864. package/skills/game-design-expert/SKILL.md +126 -68
  865. package/skills/game-engineering-expert/SKILL.md +135 -77
  866. package/skills/generative-ui-expert/SKILL.md +142 -72
  867. package/skills/geo-fundamentals/SKILL.md +134 -76
  868. package/skills/git-pro/SKILL.md +429 -368
  869. package/skills/github-operations/SKILL.md +329 -259
  870. package/skills/gpt-taste/SKILL.md +92 -22
  871. package/skills/graph-engineering/SKILL.md +104 -16
  872. package/skills/gsap-core/SKILL.md +312 -242
  873. package/skills/gsap-frameworks/SKILL.md +204 -134
  874. package/skills/gsap-performance/SKILL.md +130 -60
  875. package/skills/gsap-plugins/SKILL.md +476 -406
  876. package/skills/gsap-react/SKILL.md +248 -178
  877. package/skills/gsap-scrolltrigger/SKILL.md +347 -277
  878. package/skills/gsap-timeline/SKILL.md +157 -87
  879. package/skills/gsap-utils/SKILL.md +334 -264
  880. package/skills/harden/SKILL.md +97 -27
  881. package/skills/harness-protocol/SKILL.md +91 -21
  882. package/skills/hf-cli/SKILL.md +86 -6
  883. package/skills/hf-cloud-aws-context-discovery/SKILL.md +86 -8
  884. package/skills/hf-cloud-python-env-setup/SKILL.md +86 -8
  885. package/skills/hf-cloud-sagemaker-deployment-planner/SKILL.md +86 -8
  886. package/skills/hf-cloud-sagemaker-iam-preflight/SKILL.md +86 -8
  887. package/skills/hf-cloud-sagemaker-production-defaults/SKILL.md +86 -8
  888. package/skills/hf-cloud-serving-image-selection/SKILL.md +86 -8
  889. package/skills/hf-mem/SKILL.md +86 -6
  890. package/skills/huggingface-best/SKILL.md +86 -16
  891. package/skills/huggingface-community-evals/SKILL.md +86 -8
  892. package/skills/huggingface-datasets/SKILL.md +86 -8
  893. package/skills/huggingface-gradio/SKILL.md +86 -8
  894. package/skills/huggingface-llm-trainer/SKILL.md +86 -9
  895. package/skills/huggingface-local-models/SKILL.md +86 -8
  896. package/skills/huggingface-lora-space-builder/SKILL.md +86 -8
  897. package/skills/huggingface-paper-publisher/SKILL.md +86 -7
  898. package/skills/huggingface-papers/SKILL.md +86 -8
  899. package/skills/huggingface-spaces/SKILL.md +87 -9
  900. package/skills/huggingface-tool-builder/SKILL.md +86 -8
  901. package/skills/huggingface-trackio/SKILL.md +77 -8
  902. package/skills/huggingface-vision-trainer/SKILL.md +86 -8
  903. package/skills/huggingface-zerogpu/SKILL.md +86 -8
  904. package/skills/human-gate-negotiation/SKILL.md +83 -17
  905. package/skills/i18n-localization/SKILL.md +160 -102
  906. package/skills/impeccable/SKILL.md +95 -25
  907. package/skills/improve-codebase-architecture/SKILL.md +90 -20
  908. package/skills/improve-ui/SKILL.md +107 -37
  909. package/skills/intelligent-routing/SKILL.md +243 -180
  910. package/skills/knowledge-graph/SKILL.md +109 -39
  911. package/skills/landing-page/SKILL.md +106 -36
  912. package/skills/lint-and-validate/SKILL.md +249 -191
  913. package/skills/llm-engineering/SKILL.md +394 -324
  914. package/skills/local-first/SKILL.md +163 -105
  915. package/skills/local-first-architecture/SKILL.md +100 -39
  916. package/skills/lottie-animation/SKILL.md +109 -39
  917. package/skills/marquee-loop/SKILL.md +121 -51
  918. package/skills/masked-reveal/SKILL.md +267 -198
  919. package/skills/mcp-builder/SKILL.md +131 -73
  920. package/skills/micro-interaction/SKILL.md +281 -219
  921. package/skills/mobile-design/SKILL.md +274 -213
  922. package/skills/monorepo-management/SKILL.md +319 -261
  923. package/skills/morphing-icons/SKILL.md +379 -310
  924. package/skills/motion-engineering/SKILL.md +225 -164
  925. package/skills/nextjs-react-expert/SKILL.md +247 -186
  926. package/skills/nodejs-best-practices/SKILL.md +570 -509
  927. package/skills/observability/SKILL.md +337 -267
  928. package/skills/opentelemetry-observability/SKILL.md +106 -34
  929. package/skills/page-transition-animation/SKILL.md +130 -60
  930. package/skills/parallel-agents/SKILL.md +136 -78
  931. package/skills/performance-profiling/SKILL.md +263 -193
  932. package/skills/plan-writing/SKILL.md +156 -95
  933. package/skills/platform-engineer/SKILL.md +134 -76
  934. package/skills/platform-engineering-opentofu/SKILL.md +114 -42
  935. package/skills/playwright-ai-e2e/SKILL.md +100 -28
  936. package/skills/playwright-best-practices/SKILL.md +174 -116
  937. package/skills/polish/SKILL.md +90 -20
  938. package/skills/powershell-windows/SKILL.md +156 -86
  939. package/skills/pricing-page/SKILL.md +91 -21
  940. package/skills/product-aware-heuristics/SKILL.md +424 -354
  941. package/skills/progressive-blur/SKILL.md +122 -52
  942. package/skills/project-idioms/SKILL.md +125 -55
  943. package/skills/property-based-testing/SKILL.md +104 -32
  944. package/skills/python-patterns/SKILL.md +245 -187
  945. package/skills/python-pro/SKILL.md +333 -272
  946. package/skills/quieter/SKILL.md +91 -21
  947. package/skills/react-doctor/SKILL.md +93 -23
  948. package/skills/react-specialist/SKILL.md +309 -248
  949. package/skills/readme-builder/SKILL.md +294 -236
  950. package/skills/realtime-patterns/SKILL.md +317 -247
  951. package/skills/red-team-tactics/SKILL.md +220 -159
  952. package/skills/redesign-skill/SKILL.md +88 -18
  953. package/skills/review-animations/SKILL.md +91 -21
  954. package/skills/review-animations/STANDARDS.md +87 -87
  955. package/skills/rust-pro/SKILL.md +680 -619
  956. package/skills/semantic-filesystem-navigation/SKILL.md +69 -14
  957. package/skills/seo-fundamentals/SKILL.md +165 -107
  958. package/skills/server-management/SKILL.md +203 -145
  959. package/skills/session-log-interrogation/SKILL.md +70 -18
  960. package/skills/shadcn-ui-expert/SKILL.md +221 -163
  961. package/skills/shape/SKILL.md +96 -26
  962. package/skills/skill-creator/SKILL.md +213 -145
  963. package/skills/soft-skill/SKILL.md +95 -25
  964. package/skills/sounds-on-the-web/SKILL.md +115 -45
  965. package/skills/sql-pro/SKILL.md +653 -592
  966. package/skills/subagent-driven-development/SKILL.md +78 -18
  967. package/skills/supabase-postgres-best-practices/SKILL.md +93 -32
  968. package/skills/svg-animation/SKILL.md +388 -319
  969. package/skills/swiftui-expert/SKILL.md +190 -132
  970. package/skills/swiss-design/SKILL.md +87 -17
  971. package/skills/system-design-pro/SKILL.md +238 -294
  972. package/skills/systematic-debugging/SKILL.md +154 -96
  973. package/skills/systematic-debugging/condition-based-waiting.md +120 -120
  974. package/skills/systematic-debugging/defense-in-depth.md +128 -128
  975. package/skills/systematic-debugging/root-cause-tracing.md +183 -183
  976. package/skills/tailwind-patterns/SKILL.md +617 -547
  977. package/skills/taste-skill/SKILL.md +94 -24
  978. package/skills/tdd-workflow/SKILL.md +133 -72
  979. package/skills/test-result-analyzer/SKILL.md +304 -234
  980. package/skills/testing-patterns/SKILL.md +567 -497
  981. package/skills/thermo-nuclear-code-quality-review/SKILL.md +104 -34
  982. package/skills/thinking-protocol/SKILL.md +65 -7
  983. package/skills/to-spring-or-not-to-spring/SKILL.md +90 -20
  984. package/skills/train-sentence-transformers/SKILL.md +86 -8
  985. package/skills/transformers-js/SKILL.md +86 -15
  986. package/skills/transformers-js/references/CONFIGURATION.md +1 -1
  987. package/skills/transitions-dev/SKILL.md +136 -66
  988. package/skills/trend-researcher/SKILL.md +232 -162
  989. package/skills/tribunal-instincts-memory/SKILL.md +74 -19
  990. package/skills/trl-training/SKILL.md +86 -16
  991. package/skills/typescript-advanced/SKILL.md +334 -273
  992. package/skills/typeset/SKILL.md +101 -31
  993. package/skills/ui-reasoning-engine/SKILL.md +191 -121
  994. package/skills/ui-skill-packs/SKILL.md +95 -25
  995. package/skills/ui-skills-root/SKILL.md +118 -48
  996. package/skills/ui-ux-pro-max/SKILL.md +145 -75
  997. package/skills/ui-ux-researcher/SKILL.md +235 -165
  998. package/skills/vector-search-pgvector/SKILL.md +118 -46
  999. package/skills/verification-before-completion/SKILL.md +151 -79
  1000. package/skills/vue-expert/SKILL.md +288 -227
  1001. package/skills/vulnerability-scanner/SKILL.md +409 -342
  1002. package/skills/web-accessibility-auditor/SKILL.md +204 -146
  1003. package/skills/web-design-guidelines/SKILL.md +92 -22
  1004. package/skills/web-quality-audit/SKILL.md +90 -20
  1005. package/skills/webapp-testing/SKILL.md +152 -94
  1006. package/skills/webgpu-performance/SKILL.md +126 -56
  1007. package/skills/whimsy-injector/SKILL.md +339 -269
  1008. package/skills/workflow-optimizer/SKILL.md +222 -152
  1009. package/skills/zero-trust-passkeys/SKILL.md +135 -63
  1010. package/{dist → src}/browser/audit.js +233 -229
  1011. package/{dist → src}/browser/case_bridge.js +190 -189
  1012. package/{dist → src}/browser/cdp.js +526 -513
  1013. package/{dist → src}/browser/compare.js +110 -110
  1014. package/{dist → src}/browser/discovery.js +150 -140
  1015. package/{dist → src}/browser/idpi.js +145 -142
  1016. package/{dist → src}/browser/index.js +89 -89
  1017. package/{dist → src}/browser/launcher.js +160 -154
  1018. package/{dist → src}/browser/sentinel.js +208 -202
  1019. package/{dist → src}/browser/synapse.js +251 -251
  1020. package/{dist → src}/browser/trimmer.js +219 -210
  1021. package/src/cli.js +430 -0
  1022. package/src/commands/align.js +208 -0
  1023. package/src/commands/arch.js +172 -0
  1024. package/{dist → src}/commands/audit-web.js +126 -112
  1025. package/{dist → src}/commands/browse.js +62 -56
  1026. package/src/commands/case.js +98 -0
  1027. package/{dist → src}/commands/compare-web.js +69 -61
  1028. package/src/commands/compile.js +97 -0
  1029. package/src/commands/context.js +156 -0
  1030. package/{dist → src}/commands/contract.js +423 -440
  1031. package/{dist → src}/commands/deconstruct.js +70 -58
  1032. package/src/commands/graph.js +52 -0
  1033. package/{dist → src}/commands/guardrail.js +247 -275
  1034. package/{dist → src}/commands/heal.js +109 -99
  1035. package/src/commands/hook.js +32 -0
  1036. package/src/commands/init.js +462 -0
  1037. package/src/commands/learn.js +195 -0
  1038. package/src/commands/marathon.js +68 -0
  1039. package/src/commands/memory.js +609 -0
  1040. package/src/commands/minimal.js +85 -0
  1041. package/src/commands/mutate.js +34 -0
  1042. package/src/commands/native.js +409 -0
  1043. package/src/commands/optimize.js +365 -0
  1044. package/src/commands/review.js +971 -0
  1045. package/src/commands/sdd.js +275 -0
  1046. package/{dist → src}/commands/status.js +76 -66
  1047. package/src/commands/sync.js +27 -0
  1048. package/src/commands/system1.js +312 -0
  1049. package/src/commands/uninstall.js +63 -0
  1050. package/src/commands/update.js +44 -0
  1051. package/{dist → src}/commands/validate.js +66 -58
  1052. package/src/context/ranker.js +339 -0
  1053. package/{dist → src}/esm/index.mjs +4 -2
  1054. package/src/evolution/engine.js +295 -0
  1055. package/src/mcp/server.js +8 -0
  1056. package/src/synthesis/claim_check_separator.js +271 -0
  1057. package/src/system1/laya-package-lock.json +303 -0
  1058. package/src/system1/laya-package.json +16 -0
  1059. package/src/system1/provider.js +127 -0
  1060. package/{dist → src}/tui/banner.js +1 -1
  1061. package/{dist → src}/tui/index.js +21 -21
  1062. package/{dist → src}/tui/reviewer-grid.js +86 -90
  1063. package/{dist → src}/tui/shimmer.js +89 -91
  1064. package/{dist → src}/tui/theme.js +130 -130
  1065. package/{dist → src}/tui/tree.js +93 -93
  1066. package/{dist → src}/tui/wizard.js +144 -148
  1067. package/{dist → src}/types.js +8 -8
  1068. package/src/utils/fs.js +103 -0
  1069. package/src/utils/hasher.js +144 -0
  1070. package/src/utils/helpers.js +52 -0
  1071. package/src/utils/logger.js +61 -0
  1072. package/src/utils/version.js +176 -0
  1073. package/.agent/history/README.md +0 -53
  1074. package/.agent/history/architecture-explorer.html +0 -352
  1075. package/.agent/history/architecture-graph.yaml +0 -619
  1076. package/.agent/history/case-law/cases/template-case.json +0 -19
  1077. package/.agent/history/graph-cache.json +0 -1042
  1078. package/.agent/history/memory/.memory.idx +0 -7596
  1079. package/.agent/history/memory/MEMORY.md +0 -512
  1080. package/.agent/history/memory.db +0 -0
  1081. package/.agent/history/snapshots/.opencode__plugins__tribunal.js.json +0 -12
  1082. package/.agent/history/snapshots/.pi__extensions__tribunal.ts.json +0 -12
  1083. package/.agent/history/snapshots/bin__adapter-install.js.json +0 -13
  1084. package/.agent/history/snapshots/bin__global-store.js.json +0 -15
  1085. package/.agent/history/snapshots/bin__mcp-server.js.json +0 -21
  1086. package/.agent/history/snapshots/bin__proxy-server.js.json +0 -20
  1087. package/.agent/history/snapshots/bin__spawn-agent.js.json +0 -12
  1088. package/.agent/history/snapshots/bin__tk-proxy.js.json +0 -21
  1089. package/.agent/history/snapshots/bin__tribunal-kit.js.json +0 -21
  1090. package/.agent/history/snapshots/bin__wrapper.js.json +0 -14
  1091. package/.agent/history/snapshots/eslint.config.js.json +0 -8
  1092. package/.agent/history/snapshots/hooks__session-start.js.json +0 -11
  1093. package/.agent/history/snapshots/scripts__apply-version.js.json +0 -11
  1094. package/.agent/history/snapshots/scripts__audit_skill_sdo.js.json +0 -11
  1095. package/.agent/history/snapshots/scripts__benchmark.js.json +0 -14
  1096. package/.agent/history/snapshots/scripts__changelog.js.json +0 -12
  1097. package/.agent/history/snapshots/scripts__clean-pycache.js.json +0 -11
  1098. package/.agent/history/snapshots/scripts__context_compiler.js.json +0 -17
  1099. package/.agent/history/snapshots/scripts__fix-vbc.js.json +0 -11
  1100. package/.agent/history/snapshots/scripts__modernize_skills.js.json +0 -11
  1101. package/.agent/history/snapshots/scripts__package-cores.js.json +0 -12
  1102. package/.agent/history/snapshots/scripts__skill_enhancement_engine.js.json +0 -11
  1103. package/.agent/history/snapshots/scripts__stress_benchmark.js.json +0 -15
  1104. package/.agent/history/snapshots/scripts__sync-skills.js.json +0 -11
  1105. package/.agent/history/snapshots/scripts__sync-version.js.json +0 -11
  1106. package/.agent/history/snapshots/scripts__telemetry_gc.js.json +0 -11
  1107. package/.agent/history/snapshots/scripts__validate-payload.js.json +0 -11
  1108. package/.agent/history/snapshots/scripts__visual_audit.js.json +0 -11
  1109. package/.agent/history/snapshots/test__integration__bridges.test.js.json +0 -13
  1110. package/.agent/history/snapshots/test__integration__browser_cli.test.js.json +0 -12
  1111. package/.agent/history/snapshots/test__integration__graceful_degradation.test.js.json +0 -12
  1112. package/.agent/history/snapshots/test__integration__init.test.js.json +0 -13
  1113. package/.agent/history/snapshots/test__integration__minimal_change_pipeline.test.js.json +0 -13
  1114. package/.agent/history/snapshots/test__integration__parallel_tribunal.test.js.json +0 -12
  1115. package/.agent/history/snapshots/test__integration__routing.test.js.json +0 -11
  1116. package/.agent/history/snapshots/test__integration__swarm_dispatcher.test.js.json +0 -13
  1117. package/.agent/history/snapshots/test__integration__sync_status.test.js.json +0 -13
  1118. package/.agent/history/snapshots/test__integration__wave2.test.js.json +0 -13
  1119. package/.agent/history/snapshots/test__integration__wrapper.test.js.json +0 -13
  1120. package/.agent/history/snapshots/test__unit__align.test.js.json +0 -10
  1121. package/.agent/history/snapshots/test__unit__args.test.js.json +0 -20
  1122. package/.agent/history/snapshots/test__unit__ast_context_loader.test.js.json +0 -12
  1123. package/.agent/history/snapshots/test__unit__audit_release.test.js.json +0 -16
  1124. package/.agent/history/snapshots/test__unit__browser_case_bridge.test.js.json +0 -11
  1125. package/.agent/history/snapshots/test__unit__browser_discovery.test.js.json +0 -10
  1126. package/.agent/history/snapshots/test__unit__browser_idpi.test.js.json +0 -10
  1127. package/.agent/history/snapshots/test__unit__browser_sentinel.test.js.json +0 -11
  1128. package/.agent/history/snapshots/test__unit__browser_synapse.test.js.json +0 -10
  1129. package/.agent/history/snapshots/test__unit__browser_trimmer.test.js.json +0 -10
  1130. package/.agent/history/snapshots/test__unit__case_law_manager.test.js.json +0 -10
  1131. package/.agent/history/snapshots/test__unit__cicd_validator.test.js.json +0 -12
  1132. package/.agent/history/snapshots/test__unit__compile.test.js.json +0 -10
  1133. package/.agent/history/snapshots/test__unit__context_broker.test.js.json +0 -10
  1134. package/.agent/history/snapshots/test__unit__context_compiler.test.js.json +0 -26
  1135. package/.agent/history/snapshots/test__unit__contract_engine.test.js.json +0 -13
  1136. package/.agent/history/snapshots/test__unit__copyDir.test.js.json +0 -23
  1137. package/.agent/history/snapshots/test__unit__graph_tools.test.js.json +0 -11
  1138. package/.agent/history/snapshots/test__unit__guardrail_engine.test.js.json +0 -10
  1139. package/.agent/history/snapshots/test__unit__impact_classifier.test.js.json +0 -12
  1140. package/.agent/history/snapshots/test__unit__init.test.js.json +0 -14
  1141. package/.agent/history/snapshots/test__unit__inner_loop_validator.test.js.json +0 -10
  1142. package/.agent/history/snapshots/test__unit__integrity_manifest.test.js.json +0 -13
  1143. package/.agent/history/snapshots/test__unit__learn.test.js.json +0 -11
  1144. package/.agent/history/snapshots/test__unit__marathon.test.js.json +0 -22
  1145. package/.agent/history/snapshots/test__unit__mcp_server.test.js.json +0 -16
  1146. package/.agent/history/snapshots/test__unit__memory.test.js.json +0 -13
  1147. package/.agent/history/snapshots/test__unit__minimal_change.test.js.json +0 -10
  1148. package/.agent/history/snapshots/test__unit__native.test.js.json +0 -10
  1149. package/.agent/history/snapshots/test__unit__optimize.test.js.json +0 -13
  1150. package/.agent/history/snapshots/test__unit__path_resolution.test.js.json +0 -14
  1151. package/.agent/history/snapshots/test__unit__platform_download_audit.test.js.json +0 -11
  1152. package/.agent/history/snapshots/test__unit__production_readiness_evidence.test.js.json +0 -21
  1153. package/.agent/history/snapshots/test__unit__prompt_compiler.test.js.json +0 -10
  1154. package/.agent/history/snapshots/test__unit__sdd_integration.test.js.json +0 -12
  1155. package/.agent/history/snapshots/test__unit__selfInstall.test.js.json +0 -23
  1156. package/.agent/history/snapshots/test__unit__semver.test.js.json +0 -20
  1157. package/.agent/history/snapshots/test__unit__skill_evolution.test.js.json +0 -11
  1158. package/.agent/history/snapshots/test__unit__stress.test.js.json +0 -15
  1159. package/.agent/history/snapshots/test__unit__swarm_dispatcher.test.js.json +0 -12
  1160. package/.agent/history/snapshots/test__unit__token_budget_broker.test.js.json +0 -10
  1161. package/.agent/history/snapshots/test__unit__tui.test.js.json +0 -10
  1162. package/.agent/history/snapshots/test__unit__utils.test.js.json +0 -10
  1163. package/.agents/plugins/marketplace.json +0 -20
  1164. package/.claude/CLAUDE.md +0 -442
  1165. package/dist/cli.js +0 -377
  1166. package/dist/commands/align.js +0 -201
  1167. package/dist/commands/case.js +0 -73
  1168. package/dist/commands/compile.js +0 -91
  1169. package/dist/commands/context.js +0 -71
  1170. package/dist/commands/graph.js +0 -44
  1171. package/dist/commands/hook.js +0 -28
  1172. package/dist/commands/init.js +0 -393
  1173. package/dist/commands/learn.js +0 -117
  1174. package/dist/commands/marathon.js +0 -45
  1175. package/dist/commands/memory.js +0 -508
  1176. package/dist/commands/minimal.js +0 -71
  1177. package/dist/commands/mutate.js +0 -30
  1178. package/dist/commands/native.js +0 -264
  1179. package/dist/commands/optimize.js +0 -328
  1180. package/dist/commands/sdd.js +0 -229
  1181. package/dist/commands/sync.js +0 -25
  1182. package/dist/commands/uninstall.js +0 -54
  1183. package/dist/commands/update.js +0 -37
  1184. package/dist/mcp/server.js +0 -8
  1185. package/dist/utils/fs.js +0 -102
  1186. package/dist/utils/hasher.js +0 -142
  1187. package/dist/utils/helpers.js +0 -53
  1188. package/dist/utils/logger.js +0 -54
  1189. package/dist/utils/version.js +0 -157
  1190. package/scripts/apply-version.js +0 -57
  1191. package/scripts/audit_skill_sdo.js +0 -89
  1192. package/scripts/benchmark.js +0 -231
  1193. package/scripts/build-graph.js +0 -71
  1194. package/scripts/changelog.js +0 -190
  1195. package/scripts/clean-pycache.js +0 -42
  1196. package/scripts/context_compiler.js +0 -1117
  1197. package/scripts/fix-vbc.js +0 -96
  1198. package/scripts/fix-vbc.ps1 +0 -3
  1199. package/scripts/modernize_skills.js +0 -268
  1200. package/scripts/package-cores.js +0 -116
  1201. package/scripts/skill_enhancement_engine.js +0 -608
  1202. package/scripts/stress_benchmark.js +0 -358
  1203. package/scripts/sync-skills.js +0 -61
  1204. package/scripts/sync-version.js +0 -177
  1205. package/scripts/telemetry_gc.js +0 -156
  1206. package/scripts/validate-payload.js +0 -73
  1207. package/scripts/visual_audit.js +0 -136
  1208. /package/{dist → src}/index.d.ts +0 -0
package/bin/mcp-server.js CHANGED
@@ -1,1653 +1,1662 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * Tribunal-Kit MCP Server (Performance-Optimized)
5
- *
6
- * This file exposes tribunal-kit tools via the Model Context Protocol (MCP)
7
- * over standard I/O, allowing AI clients (Cursor, Windsurf, Claude) to natively
8
- * invoke tribunal checks.
9
- *
10
- * In-process tools load reusable modules directly. Commands that depend on a
11
- * standalone CLI process remain isolated deliberately.
12
- *
13
- * Protocol: MCP 2024-11-05 over JSON-RPC 2.0 / stdio
14
- */
15
-
16
- const path = require('path');
17
- const { spawnSync } = require('child_process');
18
-
19
- const PKG = require(path.resolve(__dirname, '../package.json'));
20
-
21
- // Timeout for intentionally isolated child processes (30 seconds).
22
- const SPAWN_TIMEOUT_MS = 30000;
23
- const GENERAL_TOOL_TIMEOUT_MS = 60000;
24
-
25
- // --- DSH Guard: Cooperative Timeout ---
26
- async function withToolTimeout(fn, timeoutMs) {
27
- let timeoutId;
28
- const timeoutPromise = new Promise((_, reject) => {
29
- timeoutId = setTimeout(() => {
30
- reject(new Error('TOOL_TIMEOUT'));
31
- }, timeoutMs);
32
- });
33
-
34
- try {
35
- const result = await Promise.race([Promise.resolve().then(fn), timeoutPromise]);
36
- return result;
37
- } finally {
38
- clearTimeout(timeoutId);
39
- }
40
- }
41
-
42
- // --- DSH Guard: Loop Detection ---
43
- class ToolRepeatGuard {
44
- constructor() {
45
- this.history = new Map();
46
- }
47
-
48
- observe(toolName, argsObj) {
49
- const canonicalize = obj => {
50
- if (Array.isArray(obj)) return obj.map(canonicalize);
51
- if (obj !== null && typeof obj === 'object') {
52
- const sorted = {};
53
- for (const key of Object.keys(obj).sort()) {
54
- sorted[key] = canonicalize(obj[key]);
55
- }
56
- return sorted;
57
- }
58
- if (typeof obj === 'string') {
59
- return obj.trim().toLowerCase().replace(/\s+/g, ' ');
60
- }
61
- return obj;
62
- };
63
-
64
- const canonicalArgs = JSON.stringify(canonicalize(argsObj) || {});
65
- const key = `${toolName}::${canonicalArgs}`;
66
-
67
- const currentCount = (this.history.get(key) || 0) + 1;
68
- this.history.clear();
69
- this.history.set(key, currentCount);
70
-
71
- if (currentCount === 3) {
72
- return 'SYSTEM NOTIFICATION: You are repeating the exact same tool call with identical arguments. Carefully analyze the previous result before calling again: if the task is not complete, try a different approach or different arguments instead of repeating the call.';
73
- }
74
- if (currentCount >= 5) {
75
- return `SYSTEM NOTIFICATION: Repeated tool call detected:\n- tool: ${toolName}\n- consecutive_calls: ${currentCount}\n- arguments: ${canonicalArgs}\nThe repeated calls are not making progress. Do not call this tool with these exact arguments again. Inspect the latest result and choose a different action, different arguments, or finish the task.`;
76
- }
77
- return null;
78
- }
79
- }
80
- const repeatGuard = new ToolRepeatGuard();
81
-
82
- class RpcError extends Error {
83
- constructor(code, message) {
84
- super(message);
85
- this.code = code;
86
- this.name = 'RpcError';
87
- }
88
- }
89
-
90
- // Minimal JSON-RPC 2.0 over stdio
91
- const readline = require('readline');
92
-
93
- const rl = readline.createInterface({
94
- input: process.stdin,
95
- output: process.stdout,
96
- terminal: false,
97
- });
98
-
99
- /**
100
- * Run the workspace integrity audit without invoking the CLI schema validator.
101
- * The MCP audit is about Tribunal assets, while `tk validate` validates one
102
- * explicitly supplied payload and schema.
103
- */
104
- function runTribunalAudit() {
105
- const fs = require('fs');
106
- const projectRoot = process.cwd();
107
- const manifestScript = path.join(projectRoot, '.agent', 'scripts', 'integrity_manifest.js');
108
-
109
- if (!fs.existsSync(manifestScript)) {
110
- return 'Error: .agent/scripts/integrity_manifest.js was not found. Run `tk init` first.';
111
- }
112
-
113
- try {
114
- const { generateManifest } = require(manifestScript);
115
- const manifest = generateManifest(projectRoot);
116
- if (manifest.error) return `Error: ${manifest.error}`;
117
-
118
- const { integrity } = manifest;
119
- const lines = [
120
- 'Tribunal audit complete.',
121
- `Agents: ${manifest.agents.total} (${manifest.agents.reviewer_count} reviewers)`,
122
- `Skills: ${manifest.skills.total}`,
123
- `Scripts: ${manifest.scripts.total}`,
124
- `Workflows: ${manifest.workflows.total}`,
125
- `References: ${integrity.total_references}; phantom references: ${integrity.phantom_references}`,
126
- `Count claims: ${integrity.total_claims}; invalid claims: ${integrity.invalid_claims}`,
127
- ];
128
-
129
- if (integrity.phantom_references > 0 || integrity.invalid_claims > 0) {
130
- lines.push(
131
- 'Audit found integrity issues; run `tk guardrail --scan` for remediation details.',
132
- );
133
- } else {
134
- lines.push('All discovered references and global asset-count claims are valid.');
135
- }
136
- return lines.join('\n');
137
- } catch (error) {
138
- return `Audit failed: ${error.message}`;
139
- }
140
- }
141
-
142
- /**
143
- * Search case law in an isolated process because its CLI owns persistent state.
144
- */
145
- function searchCaseLaw(query) {
146
- const caseLawScript = path.resolve(__dirname, '../.agent/scripts/case_law_manager.js');
147
- // case_law_manager is a standalone stateful CLI, so retain its process boundary.
148
- const result = spawnSync(process.execPath, [caseLawScript, 'search-cases', '--query', query], {
149
- encoding: 'utf8',
150
- timeout: SPAWN_TIMEOUT_MS,
151
- });
152
- if (result.error) {
153
- if (result.error.code === 'ETIMEDOUT')
154
- return 'Error: Case law search timed out (exceeded 30s limit)';
155
- return `Error executing case law search: ${result.error.message}`;
156
- }
157
- return result.stdout || result.stderr || 'No results';
158
- }
159
-
160
- function stripBoilerplate(text) {
161
- if (!text) return text;
162
- let minified = text.replace(
163
- /AI coding assistants often fall into specific bad habits[\s\S]*$/g,
164
- '',
165
- );
166
- minified = minified.replace(/## 🤖 LLM-Specific Traps[\s\S]*$/g, '');
167
- minified = minified.replace(/## 🏛️ Tribunal Integration[\s\S]*$/g, '');
168
- minified = minified.replace(/## Pre-Flight Checklist[\s\S]*$/g, '');
169
- return minified.trim();
170
- }
171
-
172
- function getAgentDir() {
173
- const fs = require('fs');
174
- const local = path.join(process.cwd(), '.agent');
175
- if (fs.existsSync(local)) return local;
176
- return path.resolve(__dirname, '../.agent');
177
- }
178
-
179
- async function handleRequest(req) {
180
- const fs = require('fs');
181
- if (req.method === 'notifications/initialized' || req.method === 'notifications/cancelled') {
182
- return null;
183
- }
184
- if (req.method === 'ping') {
185
- return {};
186
- }
187
-
188
- // MCP spec: method names follow path-style convention
189
- if (req.method === 'initialize') {
190
- return {
191
- protocolVersion: '2025-03-26',
192
- capabilities: {
193
- tools: {},
194
- resources: { subscribe: false, listChanged: false },
195
- prompts: { listChanged: false },
196
- },
197
- serverInfo: {
198
- name: 'tribunal-kit-mcp',
199
- version: PKG.version,
200
- },
201
- };
202
- }
203
-
204
- if (req.method === 'resources/list') {
205
- const agentDir = getAgentDir();
206
- const resources = [];
207
-
208
- // Agents
209
- const agentsDir = path.join(agentDir, 'agents');
210
- if (fs.existsSync(agentsDir)) {
211
- const files = fs.readdirSync(agentsDir).filter(f => f.endsWith('.md'));
212
- for (const f of files) {
213
- const name = path.basename(f, '.md');
214
- resources.push({
215
- uri: `tribunal://agent/${name}`,
216
- name: `Agent: ${name}`,
217
- description: `Tribunal Specialist Agent rule file for ${name}`,
218
- mimeType: 'text/markdown',
219
- });
220
- }
221
- }
222
-
223
- // Skills
224
- const skillsDir = path.join(agentDir, 'skills');
225
- if (fs.existsSync(skillsDir)) {
226
- const dirs = fs.readdirSync(skillsDir, { withFileTypes: true });
227
- for (const d of dirs) {
228
- if (d.isDirectory()) {
229
- const skillFile = path.join(skillsDir, d.name, 'SKILL.md');
230
- if (fs.existsSync(skillFile)) {
231
- resources.push({
232
- uri: `tribunal://skill/${d.name}`,
233
- name: `Skill: ${d.name}`,
234
- description: `Tribunal Skill instruction file for ${d.name}`,
235
- mimeType: 'text/markdown',
236
- });
237
- }
238
- }
239
- }
240
- }
241
-
242
- // Workflows
243
- const workflowsDir = path.join(agentDir, 'workflows');
244
- if (fs.existsSync(workflowsDir)) {
245
- const files = fs.readdirSync(workflowsDir).filter(f => f.endsWith('.md'));
246
- for (const f of files) {
247
- const name = path.basename(f, '.md');
248
- resources.push({
249
- uri: `tribunal://workflow/${name}`,
250
- name: `Workflow: ${name}`,
251
- description: `Tribunal Workflow guide for ${name}`,
252
- mimeType: 'text/markdown',
253
- });
254
- }
255
- }
256
-
257
- return { resources };
258
- }
259
-
260
- if (req.method === 'resources/read') {
261
- const uri = req.params && req.params.uri;
262
- if (!uri) throw new Error('Missing uri parameter');
263
- const agentDir = getAgentDir();
264
- let filePath = null;
265
-
266
- if (uri.startsWith('tribunal://agent/')) {
267
- const name = uri.replace('tribunal://agent/', '');
268
- filePath = path.join(agentDir, 'agents', `${name}.md`);
269
- } else if (uri.startsWith('tribunal://skill/')) {
270
- const name = uri.replace('tribunal://skill/', '');
271
- filePath = path.join(agentDir, 'skills', name, 'SKILL.md');
272
- } else if (uri.startsWith('tribunal://workflow/')) {
273
- const name = uri.replace('tribunal://workflow/', '');
274
- filePath = path.join(agentDir, 'workflows', `${name}.md`);
275
- }
276
-
277
- if (!filePath || !fs.existsSync(filePath)) {
278
- throw new Error(`Resource not found: ${uri}`);
279
- }
280
-
281
- const text = fs.readFileSync(filePath, 'utf8');
282
- return {
283
- contents: [
284
- {
285
- uri,
286
- mimeType: 'text/markdown',
287
- text,
288
- },
289
- ],
290
- };
291
- }
292
-
293
- if (req.method === 'prompts/list') {
294
- const agentDir = getAgentDir();
295
- const prompts = [];
296
- const workflowsDir = path.join(agentDir, 'workflows');
297
-
298
- if (fs.existsSync(workflowsDir)) {
299
- const files = fs.readdirSync(workflowsDir).filter(f => f.endsWith('.md'));
300
- for (const f of files) {
301
- const name = path.basename(f, '.md');
302
- prompts.push({
303
- name,
304
- description: `Execute tribunal workflow /${name}`,
305
- arguments: [
306
- {
307
- name: 'task',
308
- description: 'The task or target file to execute the workflow against',
309
- required: false,
310
- },
311
- ],
312
- });
313
- }
314
- }
315
-
316
- return { prompts };
317
- }
318
-
319
- if (req.method === 'prompts/get') {
320
- const name = req.params && req.params.name;
321
- const task = (req.params && req.params.arguments && req.params.arguments.task) || '';
322
- if (!name) throw new Error('Missing prompt name parameter');
323
-
324
- const agentDir = getAgentDir();
325
- const workflowPath = path.join(agentDir, 'workflows', `${name}.md`);
326
- if (!fs.existsSync(workflowPath)) {
327
- throw new Error(`Prompt workflow not found: ${name}`);
328
- }
329
-
330
- const content = fs.readFileSync(workflowPath, 'utf8');
331
- const promptText = task ? `${content}\n\nTarget Task/File: ${task}` : content;
332
-
333
- return {
334
- messages: [
335
- {
336
- role: 'user',
337
- content: {
338
- type: 'text',
339
- text: promptText,
340
- },
341
- },
342
- ],
343
- };
344
- }
345
-
346
- if (req.method === 'tools/list') {
347
- return {
348
- tools: [
349
- {
350
- name: 'run_tribunal_audit',
351
- description: 'Runs a full anti-hallucination audit across the workspace.',
352
- inputSchema: {
353
- type: 'object',
354
- properties: {},
355
- additionalProperties: false,
356
- },
357
- },
358
- {
359
- name: 'sync_ide_bridges',
360
- description: 'Synchronize IDE bridge files with the current GEMINI.md rules.',
361
- inputSchema: {
362
- type: 'object',
363
- properties: {},
364
- additionalProperties: false,
365
- },
366
- },
367
- {
368
- name: 'search_case_law',
369
- description:
370
- 'Search historical code rejections and legal precedent. Use this before writing code to avoid past mistakes.',
371
- inputSchema: {
372
- type: 'object',
373
- properties: {
374
- query: {
375
- type: 'string',
376
- description: "Search query (e.g. 'useEffect state')",
377
- },
378
- },
379
- required: ['query'],
380
- additionalProperties: false,
381
- },
382
- },
383
- {
384
- name: 'list_tribunal_agents',
385
- description: 'List all available Tribunal Kit agents.',
386
- inputSchema: {
387
- type: 'object',
388
- properties: {},
389
- additionalProperties: false,
390
- },
391
- },
392
- {
393
- name: 'get_tribunal_agent',
394
- description: 'Get the full markdown rules for a specific Tribunal agent.',
395
- inputSchema: {
396
- type: 'object',
397
- properties: {
398
- name: { type: 'string', description: "The agent name (e.g. 'frontend-specialist')" },
399
- },
400
- required: ['name'],
401
- additionalProperties: false,
402
- },
403
- },
404
- {
405
- name: 'list_tribunal_skills',
406
- description: 'List all available Tribunal Kit skills.',
407
- inputSchema: {
408
- type: 'object',
409
- properties: {},
410
- additionalProperties: false,
411
- },
412
- },
413
- {
414
- name: 'get_tribunal_skill',
415
- description: 'Get the full markdown instructions for a specific Tribunal skill.',
416
- inputSchema: {
417
- type: 'object',
418
- properties: {
419
- name: { type: 'string', description: "The skill name (e.g. 'react-specialist')" },
420
- },
421
- required: ['name'],
422
- additionalProperties: false,
423
- },
424
- },
425
- {
426
- name: 'recall_memory',
427
- description:
428
- 'Budget-constrained memory recall from the 4-Type Taxonomy Persistent Memory Engine. Returns the most relevant memories that fit within the token budget, ranked by relevance × recency × priority. Use this BEFORE writing code to recall project guidelines without bloating context.',
429
- inputSchema: {
430
- type: 'object',
431
- properties: {
432
- query: {
433
- type: 'string',
434
- description: "Search query (e.g. 'database', 'auth', 'deploy')",
435
- },
436
- budget: {
437
- type: 'number',
438
- description:
439
- 'Maximum token budget for recall (default: 2000). Only the top-ranked memories that fit within this budget are returned.',
440
- },
441
- },
442
- required: ['query'],
443
- additionalProperties: false,
444
- },
445
- },
446
- {
447
- name: 'store_memory',
448
- description:
449
- 'Store a new memory entry in the 4-Type Taxonomy Persistent Memory Engine. Memories are schema-validated and persisted across sessions. Types: semantic (permanent facts), procedural (how-to recipes), episodic (30-day TTL events), working (session scratch).',
450
- inputSchema: {
451
- type: 'object',
452
- properties: {
453
- type: {
454
- type: 'string',
455
- enum: ['semantic', 'procedural', 'episodic', 'working'],
456
- description:
457
- 'Memory type: semantic (facts), procedural (recipes), episodic (events), working (scratch)',
458
- },
459
- content: {
460
- type: 'string',
461
- description: 'The memory content to store',
462
- },
463
- tags: {
464
- type: 'array',
465
- items: { type: 'string' },
466
- description: 'Searchable tags for this memory',
467
- },
468
- },
469
- required: ['type', 'content'],
470
- additionalProperties: false,
471
- },
472
- },
473
- {
474
- name: 'get_sparse_context',
475
- description:
476
- 'Get a JIT, token-optimized context prompt tailored to the active task and files. Uses the Context Density Broker to score and select relevant skills, stripping duplicate boilerplate and saving up to 85% in prompt tokens.',
477
- inputSchema: {
478
- type: 'object',
479
- properties: {
480
- task: {
481
- type: 'string',
482
- description: "The user task description (e.g. 'JWT auth API')",
483
- },
484
- files: {
485
- type: 'array',
486
- items: { type: 'string' },
487
- description: "List of files being touched (e.g. ['src/auth.js'])",
488
- },
489
- model: {
490
- type: 'string',
491
- enum: ['large', 'small'],
492
- description:
493
- 'Model tier: large (default, includes key rules of supplementary skills) or small (essential skills only)',
494
- },
495
- },
496
- required: ['task'],
497
- additionalProperties: false,
498
- },
499
- },
500
- {
501
- name: 'align_output',
502
- description:
503
- 'Align model outputs to Fabel-5 constraints: strips conversational introductions and conclusions, collapses single/double bullet items to prose, and checks for code traps (unawaited dynamic functions in Next.js 15, deprecated hooks in React 19, or non-existent models).',
504
- inputSchema: {
505
- type: 'object',
506
- properties: {
507
- text: {
508
- type: 'string',
509
- description: 'The raw output text generated by the model to be aligned.',
510
- },
511
- },
512
- required: ['text'],
513
- additionalProperties: false,
514
- },
515
- },
516
- {
517
- name: 'verify_contracts',
518
- description:
519
- 'Verify proposed code changes against project behavioral contracts. Use BEFORE writing code to ensure compliance with team conventions.',
520
- inputSchema: {
521
- type: 'object',
522
- properties: {
523
- file: {
524
- type: 'string',
525
- description: "Relative or absolute file path to verify (e.g. 'src/api/user.ts')",
526
- },
527
- content: {
528
- type: 'string',
529
- description: 'Proposed file content to verify against loaded contracts',
530
- },
531
- },
532
- required: ['file', 'content'],
533
- additionalProperties: false,
534
- },
535
- },
536
- {
537
- name: 'query_semantic_graph',
538
- description:
539
- 'Query the Ahead-of-Time (AOT) Semantic Context Graph to quickly resolve function signatures, dependencies, and file structures without inflating context windows.',
540
- inputSchema: {
541
- type: 'object',
542
- properties: {
543
- targetPath: {
544
- type: 'string',
545
- description: 'The directory to query (defaults to current workspace).',
546
- },
547
- },
548
- additionalProperties: false,
549
- },
550
- },
551
- {
552
- name: 'exit_plan_mode',
553
- description:
554
- 'Present your finished plan for human reviewed designing your approach. Execution will suspend until the user approves or requests changes.',
555
- inputSchema: {
556
- type: 'object',
557
- properties: {
558
- plan_content: {
559
- type: 'string',
560
- description: 'The markdown content of your proposed plan.',
561
- },
562
- },
563
- required: ['plan_content'],
564
- additionalProperties: false,
565
- },
566
- },
567
- {
568
- name: 'tk_browser_navigate',
569
- description:
570
- 'Token-efficient browser navigation. Navigates headlessly to a URL, prunes HTML using htmltrim (< 4,000 bytes / ~1,000 tokens), enforces IDPI prompt injection defense, and returns compact semantic markdown with an interactive elements tree.',
571
- inputSchema: {
572
- type: 'object',
573
- properties: {
574
- url: {
575
- type: 'string',
576
- description:
577
- 'The target URL to inspect (e.g. http://localhost:3000 or https://example.com)',
578
- },
579
- },
580
- required: ['url'],
581
- additionalProperties: false,
582
- },
583
- },
584
- {
585
- name: 'tk_browser_audit',
586
- description:
587
- 'Live web quality, accessibility, console error, and Core Web Vitals auditor. Navigates headlessly to a URL, checks WCAG 2.2 contrast/aria, network failures, uncaught exceptions, and security headers. Returns structured audit report.',
588
- inputSchema: {
589
- type: 'object',
590
- properties: {
591
- url: {
592
- type: 'string',
593
- description: 'The target URL to audit (e.g. http://localhost:3000)',
594
- },
595
- },
596
- required: ['url'],
597
- additionalProperties: false,
598
- },
599
- },
600
- {
601
- name: 'tk_browser_compare',
602
- description:
603
- 'Visual regression differ. Captures synchronized screenshots of two URLs (e.g. localhost dev server vs production) and computes pixel mismatch percentage to verify layout integrity before release.',
604
- inputSchema: {
605
- type: 'object',
606
- properties: {
607
- url1: {
608
- type: 'string',
609
- description: 'Baseline or staging URL (e.g. http://localhost:3000)',
610
- },
611
- url2: {
612
- type: 'string',
613
- description: 'Production or target URL to compare against',
614
- },
615
- maxDiffPercent: {
616
- type: 'number',
617
- description:
618
- 'Maximum allowable difference percentage before failing (default: 1.0)',
619
- },
620
- },
621
- required: ['url1', 'url2'],
622
- additionalProperties: false,
623
- },
624
- },
625
- {
626
- name: 'tk_browser_screenshot',
627
- description: 'Captures a viewport screenshot of a target URL as base64 PNG data.',
628
- inputSchema: {
629
- type: 'object',
630
- properties: {
631
- url: {
632
- type: 'string',
633
- description: 'The URL to screenshot',
634
- },
635
- },
636
- required: ['url'],
637
- additionalProperties: false,
638
- },
639
- },
640
- {
641
- name: 'tk_deconstruct_component',
642
- description:
643
- 'Reverse-engineers a live web element into a production React TSX component with Tailwind CSS classes by inspecting computed CSSOM (geometry, typography, elevation, transitions).',
644
- inputSchema: {
645
- type: 'object',
646
- properties: {
647
- url: {
648
- type: 'string',
649
- description: 'The URL hosting the target element',
650
- },
651
- selector: {
652
- type: 'string',
653
- description:
654
- 'CSS selector matching the element (e.g. button.primary or #pricing-card)',
655
- },
656
- name: {
657
- type: 'string',
658
- description: 'Optional PascalCase component name (e.g. PricingCard)',
659
- },
660
- },
661
- required: ['url', 'selector'],
662
- additionalProperties: false,
663
- },
664
- },
665
- {
666
- name: 'tk_heal_runtime_errors',
667
- description:
668
- 'Runtime Sentinel error hunter. Scans a live web page or dev server for uncaught exceptions, React boundary errors, and framework overlays, localizing them to workspace source files.',
669
- inputSchema: {
670
- type: 'object',
671
- properties: {
672
- url: {
673
- type: 'string',
674
- description: 'The dev server or web page URL (e.g. http://localhost:3000)',
675
- },
676
- verify: {
677
- type: 'boolean',
678
- description:
679
- 'If true, verifies whether previously reported runtime errors have cleared',
680
- },
681
- },
682
- required: ['url'],
683
- additionalProperties: false,
684
- },
685
- },
686
- {
687
- name: 'tk_codify_browser_audit',
688
- description:
689
- 'Audits a target URL and automatically codifies detected WCAG accessibility failures, missing security headers, and console errors into binding Case Law precedents.',
690
- inputSchema: {
691
- type: 'object',
692
- properties: {
693
- url: {
694
- type: 'string',
695
- description: 'The URL to audit and codify',
696
- },
697
- },
698
- required: ['url'],
699
- additionalProperties: false,
700
- },
701
- },
702
- {
703
- name: 'tribunal_get_context',
704
- description:
705
- "Generate or retrieve an elite Flight Data HUD context dossier for any file, multi-file pair, or directory. Automatically extracts public API contracts, callers, Chesterton's Fences, invariants, and test recipes. Supports drift checking and living vault sync.",
706
- inputSchema: {
707
- type: 'object',
708
- properties: {
709
- target: {
710
- type: 'string',
711
- description: 'File path, folder path, or primary file to analyze.',
712
- },
713
- compareWith: {
714
- type: 'string',
715
- description: 'Optional secondary file for multi-file interface bridge analysis.',
716
- },
717
- write: {
718
- type: 'boolean',
719
- description:
720
- 'Whether to write the generated dossier to docs/context/ and update INDEX.md (default: true).',
721
- },
722
- check: {
723
- type: 'boolean',
724
- description: 'Run vault-wide semantic drift check instead of analyzing a target.',
725
- },
726
- },
727
- additionalProperties: false,
728
- },
729
- },
730
- ],
731
- };
732
- }
733
-
734
- if (req.method === 'tools/call') {
735
- const toolName = req.params && req.params.name;
736
- const argsObj = req.params && req.params.arguments;
737
- if (!toolName) {
738
- throw new RpcError(-32602, 'Missing required parameter: params.name');
739
- }
740
-
741
- const reminder = repeatGuard.observe(toolName, argsObj);
742
-
743
- const executeTool = async () => {
744
- if (toolName === 'tribunal_get_context') {
745
- const target = req.params?.arguments?.target;
746
- const compareWith = req.params?.arguments?.compareWith;
747
- const write = req.params?.arguments?.write !== false;
748
- const check = req.params?.arguments?.check;
749
-
750
- try {
751
- const workspaceRoot = process.cwd();
752
-
753
- if (check) {
754
- const { spawn } = require('child_process');
755
- const result = await new Promise((resolve, reject) => {
756
- const child = spawn(process.execPath, [path.join(__dirname, '../scripts/context_compiler.js'), '--check', '--json'], { cwd: workspaceRoot, encoding: 'utf8' });
757
- let out = '';
758
- child.stdout.on('data', d => out += d);
759
- child.stderr.on('data', d => out += d);
760
- child.on('close', _code => resolve(out));
761
- child.on('error', reject);
762
- });
763
- return {
764
- content: [
765
- {
766
- type: 'text',
767
- text: result,
768
- },
769
- ],
770
- };
771
- }
772
-
773
- if (!target) {
774
- throw new RpcError(
775
- -32602,
776
- 'Missing required argument: target (file or directory path)',
777
- );
778
- }
779
-
780
- // We use scripts/context_compiler.js to parse AST without blocking the event loop
781
- const { spawn } = require('child_process');
782
- const args = [path.join(__dirname, '../scripts/context_compiler.js')];
783
-
784
- if (compareWith) {
785
- args.push('--multi', target, compareWith);
786
- } else {
787
- args.push(target);
788
- }
789
-
790
- if (write) {
791
- args.push('--write');
792
- }
793
-
794
- const result = await new Promise((resolve, reject) => {
795
- const child = spawn(process.execPath, args, { cwd: workspaceRoot, encoding: 'utf8' });
796
- let out = '';
797
- child.stdout.on('data', d => out += d);
798
- child.stderr.on('data', d => out += d);
799
- child.on('close', _code => {
800
- resolve(out);
801
- });
802
- child.on('error', reject);
803
- });
804
-
805
- return {
806
- content: [{ type: 'text', text: result }],
807
- };
808
- } catch (e) {
809
- return {
810
- content: [{ type: 'text', text: `Context Compiler Error: ${e.message}` }],
811
- isError: true,
812
- };
813
- }
814
- }
815
-
816
- if (toolName === 'exit_plan_mode') {
817
- const planContent = req.params?.arguments?.plan_content;
818
- if (typeof planContent !== 'string') {
819
- throw new RpcError(-32602, 'Missing or invalid required argument: plan_content (string)');
820
- }
821
- // The wrapper CLI can intercept this, but for the LLM context, we explicitly tell it to wait.
822
- return {
823
- content: [
824
- {
825
- type: 'text',
826
- text: 'PLAN_SUBMITTED_FOR_REVIEW: The plan has been presented to the human. Please suspend execution and wait for the human to approve or provide feedback in the next turn. Do not call any further tools until you receive a response.',
827
- },
828
- ],
829
- };
830
- }
831
-
832
- if (toolName === 'tk_browser_navigate') {
833
- const url = req.params?.arguments?.url;
834
- if (!url || typeof url !== 'string') {
835
- throw new RpcError(-32602, 'Missing required argument: url (string)');
836
- }
837
- try {
838
- const { browse } = require('../dist/browser');
839
- const result = await browse(url);
840
- return {
841
- content: [
842
- {
843
- type: 'text',
844
- text: result.sandboxed,
845
- },
846
- ],
847
- };
848
- } catch (e) {
849
- return {
850
- content: [{ type: 'text', text: `Browser navigation error: ${e.message}` }],
851
- isError: true,
852
- };
853
- }
854
- }
855
-
856
- if (toolName === 'tk_browser_audit') {
857
- const url = req.params?.arguments?.url;
858
- if (!url || typeof url !== 'string') {
859
- throw new RpcError(-32602, 'Missing required argument: url (string)');
860
- }
861
- try {
862
- const { auditURL } = require('../dist/browser');
863
- const report = await auditURL(url);
864
- return {
865
- content: [
866
- {
867
- type: 'text',
868
- text: JSON.stringify(report, null, 2),
869
- },
870
- ],
871
- };
872
- } catch (e) {
873
- return {
874
- content: [{ type: 'text', text: `Browser audit error: ${e.message}` }],
875
- isError: true,
876
- };
877
- }
878
- }
879
-
880
- if (toolName === 'tk_browser_compare') {
881
- const url1 = req.params?.arguments?.url1;
882
- const url2 = req.params?.arguments?.url2;
883
- const maxDiffPercent = req.params?.arguments?.maxDiffPercent;
884
- if (!url1 || !url2) {
885
- throw new RpcError(-32602, 'Missing required arguments: url1 and url2 (strings)');
886
- }
887
- try {
888
- const { compareURLs } = require('../dist/browser');
889
- const result = await compareURLs(url1, url2, { maxDiffPercent });
890
- return {
891
- content: [
892
- {
893
- type: 'text',
894
- text: JSON.stringify(result, null, 2),
895
- },
896
- ],
897
- };
898
- } catch (e) {
899
- return {
900
- content: [{ type: 'text', text: `Browser compare error: ${e.message}` }],
901
- isError: true,
902
- };
903
- }
904
- }
905
-
906
- if (toolName === 'tk_browser_screenshot') {
907
- const url = req.params?.arguments?.url;
908
- if (!url || typeof url !== 'string') {
909
- throw new RpcError(-32602, 'Missing required argument: url (string)');
910
- }
911
- try {
912
- const { launchBrowser, CdpClient, createNewTab, closeTab } = require('../dist/browser');
913
- const browser = await launchBrowser();
914
- let client = null;
915
- let tab = null;
916
- try {
917
- tab = await createNewTab(browser.port);
918
- client = new CdpClient();
919
- await client.connect(tab.webSocketDebuggerUrl);
920
- await client.initDomains();
921
- await client.navigate(url);
922
- const shot = await client.captureScreenshot('png');
923
- return {
924
- content: [
925
- {
926
- type: 'text',
927
- text: `Screenshot captured successfully for ${url} (${Buffer.byteLength(shot, 'base64')} bytes base64 PNG).`,
928
- },
929
- ],
930
- };
931
- } finally {
932
- if (client) client.close();
933
- if (tab && browser) await closeTab(tab.id, browser.port);
934
- await browser.close();
935
- }
936
- } catch (e) {
937
- return {
938
- content: [{ type: 'text', text: `Screenshot error: ${e.message}` }],
939
- isError: true,
940
- };
941
- }
942
- }
943
-
944
- if (toolName === 'tk_deconstruct_component') {
945
- const url = req.params?.arguments?.url;
946
- const selector = req.params?.arguments?.selector;
947
- const name = req.params?.arguments?.name;
948
- if (!url || !selector) {
949
- throw new RpcError(-32602, 'Missing required arguments: url and selector (strings)');
950
- }
951
- try {
952
- const { deconstructElement } = require('../dist/browser');
953
- const result = await deconstructElement(url, selector, { name });
954
- return {
955
- content: [
956
- {
957
- type: 'text',
958
- text: result.code,
959
- },
960
- ],
961
- };
962
- } catch (e) {
963
- return {
964
- content: [{ type: 'text', text: `Component deconstruction error: ${e.message}` }],
965
- isError: true,
966
- };
967
- }
968
- }
969
-
970
- if (toolName === 'tk_heal_runtime_errors') {
971
- const url = req.params?.arguments?.url;
972
- const verify = req.params?.arguments?.verify;
973
- if (!url) {
974
- throw new RpcError(-32602, 'Missing required argument: url (string)');
975
- }
976
- try {
977
- const { captureRuntimeErrors, verifyRuntimeFix } = require('../dist/browser');
978
- const result = verify ? await verifyRuntimeFix(url) : await captureRuntimeErrors(url);
979
- return {
980
- content: [
981
- {
982
- type: 'text',
983
- text: JSON.stringify(result, null, 2),
984
- },
985
- ],
986
- };
987
- } catch (e) {
988
- return {
989
- content: [{ type: 'text', text: `Runtime Sentinel error: ${e.message}` }],
990
- isError: true,
991
- };
992
- }
993
- }
994
-
995
- if (toolName === 'tk_codify_browser_audit') {
996
- const url = req.params?.arguments?.url;
997
- if (!url) {
998
- throw new RpcError(-32602, 'Missing required argument: url (string)');
999
- }
1000
- try {
1001
- const { auditURL, codifyAuditViolations } = require('../dist/browser');
1002
- const report = await auditURL(url);
1003
- const codified = codifyAuditViolations(report);
1004
- return {
1005
- content: [
1006
- {
1007
- type: 'text',
1008
- text: JSON.stringify({ report, codified }, null, 2),
1009
- },
1010
- ],
1011
- };
1012
- } catch (e) {
1013
- return {
1014
- content: [{ type: 'text', text: `Audit & codify error: ${e.message}` }],
1015
- isError: true,
1016
- };
1017
- }
1018
- }
1019
-
1020
- if (toolName === 'dispatch_swarm') {
1021
- const payload = req.params?.arguments?.payload;
1022
- const file = req.params?.arguments?.file;
1023
- const workspace = req.params?.arguments?.workspace || '.';
1024
- const mode = req.params?.arguments?.mode || 'legacy';
1025
- const useTui = req.params?.arguments?.use_tui || false;
1026
-
1027
- if (!payload && !file) {
1028
- throw new RpcError(
1029
- -32602,
1030
- 'Missing required argument: either payload or file must be provided',
1031
- );
1032
- }
1033
-
1034
- if (payload && file) {
1035
- throw new RpcError(-32602, 'Invalid arguments: provide either payload or file, not both');
1036
- }
1037
-
1038
- const agentDir = getAgentDir();
1039
- const fs = require('fs');
1040
- if (!fs.existsSync(agentDir)) {
1041
- return {
1042
- content: [
1043
- { type: 'text', text: 'Error: .agent/ directory not found. Run `tk init` first.' },
1044
- ],
1045
- };
1046
- }
1047
-
1048
- try {
1049
- let _payloadData;
1050
- if (file) {
1051
- const filePath = path.resolve(workspace, file);
1052
- if (!fs.existsSync(filePath)) {
1053
- throw new Error(`File not found: ${filePath}`);
1054
- }
1055
- _payloadData = JSON.parse(fs.readFileSync(filePath, 'utf8'));
1056
- } else {
1057
- _payloadData = JSON.parse(payload);
1058
- }
1059
-
1060
- // Import swarm dispatcher functions
1061
- const _swarmDispatcher = require(path.join(agentDir, 'scripts', 'swarm_dispatcher.js'));
1062
-
1063
- // Execute the swarm dispatcher
1064
- const originalArgv = process.argv;
1065
- process.argv = ['node', 'swarm_dispatcher.js', '--mode', mode, '--workspace', workspace];
1066
-
1067
- if (useTui) {
1068
- process.argv.push('--tui');
1069
- }
1070
-
1071
- if (file) {
1072
- process.argv.push('--file');
1073
- process.argv.push(file);
1074
- } else if (payload) {
1075
- process.argv.push('--payload');
1076
- process.argv.push(payload);
1077
- }
1078
-
1079
- // Capture output
1080
- const { spawnSync } = require('child_process');
1081
- const result = spawnSync(
1082
- process.execPath,
1083
- [path.join(agentDir, 'scripts', 'swarm_dispatcher.js'), ...process.argv.slice(2)],
1084
- {
1085
- encoding: 'utf8',
1086
- timeout: 30000,
1087
- },
1088
- );
1089
-
1090
- // Restore argv
1091
- process.argv = originalArgv;
1092
-
1093
- if (result.error) {
1094
- throw result.error;
1095
- }
1096
-
1097
- return {
1098
- content: [
1099
- { type: 'text', text: result.stdout || result.stderr || 'Swarm dispatch completed' },
1100
- ],
1101
- };
1102
- } catch (e) {
1103
- return {
1104
- content: [{ type: 'text', text: `Swarm dispatch failed: ${e.message}` }],
1105
- };
1106
- }
1107
- }
1108
-
1109
- if (toolName === 'get_ast_context') {
1110
- const targetPath = req.params?.arguments?.targetPath || process.cwd();
1111
- try {
1112
- const result = spawnSync(
1113
- 'node',
1114
- [path.join(__dirname, '../scripts/build-graph.js'), targetPath],
1115
- {
1116
- encoding: 'utf8',
1117
- timeout: 10000,
1118
- },
1119
- );
1120
- if (result.error) throw result.error;
1121
- return { content: [{ type: 'text', text: result.stdout || result.stderr }] };
1122
- } catch (e) {
1123
- return { content: [{ type: 'text', text: `Failed to query graph: ${e.message}` }] };
1124
- }
1125
- }
1126
-
1127
- if (toolName === 'validate_payload') {
1128
- const payloadStr = req.params?.arguments?.payload;
1129
- const schemaType = req.params?.arguments?.schemaType;
1130
-
1131
- if (!payloadStr || typeof payloadStr !== 'string') {
1132
- throw new RpcError(-32602, 'Missing or invalid required argument: payload (string)');
1133
- }
1134
- if (!schemaType || typeof schemaType !== 'string') {
1135
- throw new RpcError(-32602, 'Missing or invalid required argument: schemaType (string)');
1136
- }
1137
-
1138
- const agentDir = getAgentDir();
1139
- const fs = require('fs');
1140
- if (!fs.existsSync(agentDir)) {
1141
- return {
1142
- content: [
1143
- { type: 'text', text: 'Error: .agent/ directory not found. Run `tk init` first.' },
1144
- ],
1145
- };
1146
- }
1147
-
1148
- try {
1149
- const payloadData = JSON.parse(payloadStr);
1150
- const {
1151
- WorkerRequestSchema,
1152
- WorkerResultSchema,
1153
- SwarmPayloadSchema,
1154
- validatePayloadOrThrow,
1155
- } = require(path.join(agentDir, 'scripts', 'payload_schemas.js'));
1156
-
1157
- let schema;
1158
- switch (schemaType) {
1159
- case 'worker-request':
1160
- schema = WorkerRequestSchema;
1161
- break;
1162
- case 'worker-result':
1163
- schema = WorkerResultSchema;
1164
- break;
1165
- case 'swarm-payload':
1166
- schema = SwarmPayloadSchema;
1167
- break;
1168
- default:
1169
- throw new RpcError(
1170
- -32602,
1171
- `Invalid schemaType: ${schemaType}. Must be one of: worker-request, worker-result, swarm-payload`,
1172
- );
1173
- }
1174
-
1175
- const validatedData = validatePayloadOrThrow(payloadData, schema);
1176
- return {
1177
- content: [
1178
- {
1179
- type: 'text',
1180
- text: `Payload validation successful.\n\nValidated payload:\n${JSON.stringify(validatedData, null, 2)}`,
1181
- },
1182
- ],
1183
- };
1184
- } catch (e) {
1185
- if (e instanceof SyntaxError) {
1186
- return { content: [{ type: 'text', text: `Invalid JSON payload: ${e.message}` }] };
1187
- } else {
1188
- return { content: [{ type: 'text', text: `Payload validation failed: ${e.message}` }] };
1189
- }
1190
- }
1191
- }
1192
-
1193
- if (toolName === 'run_tribunal_audit') {
1194
- const text = runTribunalAudit();
1195
- return { content: [{ type: 'text', text }] };
1196
- }
1197
-
1198
- if (toolName === 'sync_ide_bridges') {
1199
- const fs = require('fs');
1200
- const cwd = process.cwd();
1201
- const agentDest = path.join(cwd, '.agent');
1202
- if (!fs.existsSync(agentDest)) {
1203
- return {
1204
- content: [
1205
- {
1206
- type: 'text',
1207
- text: 'Error: .agent/ directory not found. Run `tk init` first.',
1208
- },
1209
- ],
1210
- };
1211
- }
1212
- try {
1213
- const { generateIDEBridges } = require(
1214
- path.resolve(__dirname, '../dist/commands/init.js'),
1215
- );
1216
- // generateIDEBridges is async
1217
- await generateIDEBridges(cwd, agentDest, true);
1218
- return {
1219
- content: [
1220
- {
1221
- type: 'text',
1222
- text: 'Sync complete',
1223
- },
1224
- ],
1225
- };
1226
- } catch (e) {
1227
- return {
1228
- content: [
1229
- {
1230
- type: 'text',
1231
- text: `Sync failed: ${e.message}`,
1232
- },
1233
- ],
1234
- };
1235
- }
1236
- }
1237
-
1238
- if (toolName === 'search_case_law') {
1239
- const query = req.params && req.params.arguments && req.params.arguments.query;
1240
- if (!query || typeof query !== 'string') {
1241
- throw new RpcError(-32602, 'Missing or invalid required argument: query (string)');
1242
- }
1243
- const text = searchCaseLaw(query);
1244
- return { content: [{ type: 'text', text }] };
1245
- }
1246
-
1247
- if (toolName === 'list_tribunal_agents') {
1248
- const fs = require('fs');
1249
- const agentDir = path.join(getAgentDir(), 'agents');
1250
- if (!fs.existsSync(agentDir))
1251
- return {
1252
- content: [{ type: 'text', text: 'No agents found or .agent directory missing.' }],
1253
- };
1254
- const agents = fs
1255
- .readdirSync(agentDir)
1256
- .filter(f => f.endsWith('.md'))
1257
- .map(f => f.replace('.md', ''));
1258
- return { content: [{ type: 'text', text: 'Available Agents:\n- ' + agents.join('\n- ') }] };
1259
- }
1260
-
1261
- if (toolName === 'get_tribunal_agent') {
1262
- const fs = require('fs');
1263
- const name = req.params?.arguments?.name;
1264
- if (!name || typeof name !== 'string')
1265
- throw new RpcError(-32602, 'Missing or invalid argument: name (string)');
1266
- const sanitizedName = path.basename(name);
1267
- const agentsDir = path.resolve(getAgentDir(), 'agents');
1268
- const agentPath = path.resolve(agentsDir, `${sanitizedName}.md`);
1269
- // Path containment: ensure resolved path stays within agents directory
1270
- if (!agentPath.startsWith(agentsDir))
1271
- throw new RpcError(-32602, 'Invalid agent name: path traversal detected');
1272
- if (!fs.existsSync(agentPath))
1273
- return { content: [{ type: 'text', text: `Agent '${sanitizedName}' not found.` }] };
1274
- const text = fs.readFileSync(agentPath, 'utf8');
1275
- return { content: [{ type: 'text', text: stripBoilerplate(text) }] };
1276
- }
1277
-
1278
- if (toolName === 'list_tribunal_skills') {
1279
- const fs = require('fs');
1280
- const skillsDir = path.join(getAgentDir(), 'skills');
1281
- if (!fs.existsSync(skillsDir))
1282
- return {
1283
- content: [{ type: 'text', text: 'No skills found or .agent directory missing.' }],
1284
- };
1285
- const skills = fs
1286
- .readdirSync(skillsDir, { withFileTypes: true })
1287
- .filter(d => d.isDirectory())
1288
- .map(d => d.name);
1289
- return { content: [{ type: 'text', text: 'Available Skills:\n- ' + skills.join('\n- ') }] };
1290
- }
1291
-
1292
- if (toolName === 'get_tribunal_skill') {
1293
- const fs = require('fs');
1294
- const name = req.params?.arguments?.name;
1295
- if (!name || typeof name !== 'string')
1296
- throw new RpcError(-32602, 'Missing or invalid argument: name (string)');
1297
- const sanitizedName = path.basename(name);
1298
- const skillsDir = path.resolve(getAgentDir(), 'skills');
1299
- const skillPath = path.resolve(skillsDir, sanitizedName, 'SKILL.md');
1300
- // Path containment: ensure resolved path stays within skills directory
1301
- if (!skillPath.startsWith(skillsDir))
1302
- throw new RpcError(-32602, 'Invalid skill name: path traversal detected');
1303
- if (!fs.existsSync(skillPath))
1304
- return { content: [{ type: 'text', text: `Skill '${sanitizedName}' not found.` }] };
1305
- const text = fs.readFileSync(skillPath, 'utf8');
1306
- return { content: [{ type: 'text', text: stripBoilerplate(text) }] };
1307
- }
1308
-
1309
- if (toolName === 'get_sparse_context') {
1310
- const task = req.params?.arguments?.task;
1311
- const files = req.params?.arguments?.files || [];
1312
- const _model = req.params?.arguments?.model || 'large';
1313
-
1314
- if (!task) throw new RpcError(-32602, 'Missing required argument: task');
1315
-
1316
- const agentDest = getAgentDir();
1317
- const fs = require('fs');
1318
- if (!fs.existsSync(agentDest)) {
1319
- return {
1320
- content: [
1321
- { type: 'text', text: 'Error: .agent/ directory not found. Run `tk init` first.' },
1322
- ],
1323
- };
1324
- }
1325
-
1326
- try {
1327
- const workspaceRoot = process.cwd();
1328
- const { spawn } = require('child_process');
1329
- const args = [path.join(__dirname, 'wrapper.js'), 'context-broker', '--repo-path', workspaceRoot];
1330
- if (files && files.length > 0) {
1331
- args.push('--target-file');
1332
- args.push(files[0]);
1333
- }
1334
-
1335
- const result = await new Promise((resolve, reject) => {
1336
- const child = spawn(process.execPath, args, { cwd: workspaceRoot, encoding: 'utf8' });
1337
- let out = '';
1338
- child.stdout.on('data', d => out += d);
1339
- child.stderr.on('data', d => out += d);
1340
- child.on('close', _code => {
1341
- resolve(out);
1342
- });
1343
- child.on('error', reject);
1344
- });
1345
-
1346
- let finalOutput = '';
1347
- try {
1348
- const parsed = JSON.parse(result);
1349
- finalOutput = `# Tribunal Context Broker\n\n`;
1350
- if (task) {
1351
- finalOutput += `Task: ${task}\n\n`;
1352
- }
1353
- if (parsed.context_snapshot) {
1354
- finalOutput += parsed.context_snapshot;
1355
- }
1356
- } catch (_e) {
1357
- finalOutput = result;
1358
- }
1359
-
1360
- return { content: [{ type: 'text', text: stripBoilerplate(finalOutput) }] };
1361
- } catch (e) {
1362
- return {
1363
- content: [{ type: 'text', text: `Failed to retrieve sparse context: ${e.message}` }],
1364
- };
1365
- }
1366
- }
1367
-
1368
- if (toolName === 'recall_memory') {
1369
- const query = req.params?.arguments?.query;
1370
- if (!query || typeof query !== 'string') {
1371
- throw new RpcError(-32602, 'Missing or invalid required argument: query (string)');
1372
- }
1373
- const budget = req.params?.arguments?.budget || 2000;
1374
- const agentDest = getAgentDir();
1375
- const fs = require('fs');
1376
- if (!fs.existsSync(agentDest)) {
1377
- return {
1378
- content: [
1379
- { type: 'text', text: 'Error: .agent/ directory not found. Run `tk init` first.' },
1380
- ],
1381
- };
1382
- }
1383
- try {
1384
- const { _memoryRecall } = require('../dist/commands/memory.js');
1385
- const { results, tokens_used } = _memoryRecall(agentDest, query, budget);
1386
- if (results.length === 0) {
1387
- return { content: [{ type: 'text', text: `No memories match query: "${query}"` }] };
1388
- }
1389
- let text = `## Memory Recall (${results.length} results, ~${tokens_used}/${budget} tokens)\n\n`;
1390
- for (const entry of results) {
1391
- text += `- **[${entry.memory_type.toUpperCase()}]** #${entry.id}: ${entry.content}`;
1392
- if (entry.tags.length > 0) text += ` _(${entry.tags.join(', ')})_`;
1393
- text += `\n`;
1394
- }
1395
- return { content: [{ type: 'text', text }] };
1396
- } catch (e) {
1397
- return { content: [{ type: 'text', text: `Memory recall failed: ${e.message}` }] };
1398
- }
1399
- }
1400
-
1401
- if (toolName === 'store_memory') {
1402
- const memType = req.params?.arguments?.type;
1403
- const content = req.params?.arguments?.content;
1404
- const tags = req.params?.arguments?.tags || [];
1405
- if (!memType || !content) {
1406
- throw new RpcError(-32602, 'Missing required arguments: type (string), content (string)');
1407
- }
1408
- const validTypes = ['semantic', 'procedural', 'episodic', 'working'];
1409
- if (!validTypes.includes(memType)) {
1410
- throw new RpcError(
1411
- -32602,
1412
- `Invalid memory type: "${memType}". Must be one of: ${validTypes.join(', ')}`,
1413
- );
1414
- }
1415
- const agentDest = getAgentDir();
1416
- const fs = require('fs');
1417
- if (!fs.existsSync(agentDest)) {
1418
- return {
1419
- content: [
1420
- { type: 'text', text: 'Error: .agent/ directory not found. Run `tk init` first.' },
1421
- ],
1422
- };
1423
- }
1424
- try {
1425
- const { _memoryStore } = require('../dist/commands/memory.js');
1426
- const result = _memoryStore(agentDest, memType, content, tags, null);
1427
- return {
1428
- content: [
1429
- {
1430
- type: 'text',
1431
- text: `Memory stored: #${result.id} (${memType}, ~${result.token_estimate} tokens)`,
1432
- },
1433
- ],
1434
- };
1435
- } catch (e) {
1436
- return { content: [{ type: 'text', text: `Memory store failed: ${e.message}` }] };
1437
- }
1438
- }
1439
-
1440
- if (toolName === 'query_semantic_graph') {
1441
- const targetPath = req.params?.arguments?.targetPath || process.cwd();
1442
- try {
1443
- const result = spawnSync(
1444
- 'node',
1445
- [path.join(__dirname, '../scripts/build-graph.js'), targetPath],
1446
- {
1447
- encoding: 'utf8',
1448
- timeout: 10000,
1449
- },
1450
- );
1451
- if (result.error) throw result.error;
1452
- return { content: [{ type: 'text', text: result.stdout || result.stderr }] };
1453
- } catch (e) {
1454
- return { content: [{ type: 'text', text: `Failed to query graph: ${e.message}` }] };
1455
- }
1456
- }
1457
-
1458
- if (toolName === 'align_output') {
1459
- const text = req.params?.arguments?.text;
1460
- if (typeof text !== 'string') {
1461
- throw new RpcError(-32602, 'Missing or invalid required argument: text (string)');
1462
- }
1463
- try {
1464
- const { alignText, validateCodeContent } = require('../dist/commands/align.js');
1465
- const aligned = alignText(text);
1466
- const warnings = validateCodeContent(aligned);
1467
-
1468
- let outputText = aligned;
1469
- if (warnings.length > 0) {
1470
- outputText += '\n\n⚠️ OCAE Alignment Validator Warnings:\n';
1471
- for (const warnMsg of warnings) {
1472
- outputText += `● ${warnMsg}\n`;
1473
- }
1474
- }
1475
- return { content: [{ type: 'text', text: outputText }] };
1476
- } catch (e) {
1477
- return { content: [{ type: 'text', text: `Output alignment failed: ${e.message}` }] };
1478
- }
1479
- }
1480
-
1481
- if (toolName === 'verify_contracts') {
1482
- const file = req.params?.arguments?.file;
1483
- const content = req.params?.arguments?.content;
1484
-
1485
- if (!file || typeof file !== 'string' || typeof content !== 'string') {
1486
- throw new RpcError(
1487
- -32602,
1488
- 'Missing or invalid required arguments: file (string), content (string)',
1489
- );
1490
- }
1491
-
1492
- try {
1493
- const projectRoot = process.cwd();
1494
- const contractEnginePath = path.join(getAgentDir(), 'scripts', 'contract_engine.js');
1495
- if (!require('fs').existsSync(contractEnginePath)) {
1496
- return {
1497
- content: [
1498
- { type: 'text', text: 'Error: contract_engine.js not found. Run `tk init` first.' },
1499
- ],
1500
- };
1501
- }
1502
-
1503
- const contractEngine = require(contractEnginePath);
1504
- const contracts = contractEngine.loadContracts(projectRoot);
1505
-
1506
- if (contracts.length === 0) {
1507
- return {
1508
- content: [
1509
- {
1510
- type: 'text',
1511
- text: 'No active behavioral contracts found in .tribunal/contracts/.',
1512
- },
1513
- ],
1514
- };
1515
- }
1516
-
1517
- const relativePath = path.relative(projectRoot, file).replace(/\\/g, '/');
1518
- const allViolations = [];
1519
-
1520
- for (const contract of contracts) {
1521
- const vList = contractEngine.evaluateContract(contract, relativePath, content);
1522
- if (vList.length > 0) {
1523
- allViolations.push(...vList);
1524
- }
1525
- }
1526
-
1527
- if (allViolations.length === 0) {
1528
- return {
1529
- content: [
1530
- {
1531
- type: 'text',
1532
- text: '✅ Contract check passed. Zero behavioral violations detected.',
1533
- },
1534
- ],
1535
- };
1536
- }
1537
-
1538
- let report = `📜 Contract Verification Results (${allViolations.length} violations):\n`;
1539
- for (const v of allViolations) {
1540
- report += `● [${v.severity.toUpperCase()}] ${v.contract}: ${v.message}\n`;
1541
- if (v.line) report += ` Line ${v.line}: ${v.snippet || ''}\n`;
1542
- }
1543
-
1544
- return { content: [{ type: 'text', text: report }] };
1545
- } catch (e) {
1546
- return {
1547
- content: [{ type: 'text', text: `Contract verification failed: ${e.message}` }],
1548
- };
1549
- }
1550
- }
1551
-
1552
- throw new RpcError(-32601, `Unknown tool: ${toolName}`);
1553
- };
1554
-
1555
- try {
1556
- const result = await withToolTimeout(executeTool, GENERAL_TOOL_TIMEOUT_MS);
1557
- if (reminder) {
1558
- result.content.push({ type: 'text', text: '\n\n' + reminder });
1559
- }
1560
- return result;
1561
- } catch (e) {
1562
- if (e.message === 'TOOL_TIMEOUT') {
1563
- const errorMsg = `Error: Tool execution timed out after ${GENERAL_TOOL_TIMEOUT_MS}ms`;
1564
- const result = { content: [{ type: 'text', text: errorMsg }] };
1565
- if (reminder) result.content.push({ type: 'text', text: '\n\n' + reminder });
1566
- return result;
1567
- }
1568
- throw e;
1569
- }
1570
- }
1571
-
1572
- throw new RpcError(-32601, `Unknown method: ${req.method}`);
1573
- }
1574
-
1575
- async function processSingleRequest(req) {
1576
- try {
1577
- const result = await handleRequest(req);
1578
- // If it's a notification, do not send a response
1579
- if (req.id === undefined || req.id === null) {
1580
- return null;
1581
- }
1582
- return { jsonrpc: '2.0', id: req.id, result };
1583
- } catch (e) {
1584
- const code = e && typeof e.code === 'number' ? e.code : -32603;
1585
- const message = e && e.message ? e.message : 'Internal server error';
1586
- if (req.id === undefined || req.id === null) {
1587
- return {
1588
- jsonrpc: '2.0',
1589
- id: null,
1590
- error: { code, message },
1591
- };
1592
- }
1593
- return {
1594
- jsonrpc: '2.0',
1595
- id: req.id,
1596
- error: { code, message },
1597
- };
1598
- }
1599
- }
1600
-
1601
- rl.on('line', async line => {
1602
- if (line.length > 1048576) {
1603
- // 1MB limit
1604
- const errorRes = {
1605
- jsonrpc: '2.0',
1606
- id: null,
1607
- error: { code: -32700, message: 'Parse error: input line too long (exceeds 1MB limit)' },
1608
- };
1609
- console.log(JSON.stringify(errorRes));
1610
- return;
1611
- }
1612
- if (!line.trim()) return;
1613
-
1614
- let req;
1615
- try {
1616
- req = JSON.parse(line);
1617
- } catch (parseErr) {
1618
- // Invalid JSON — send a parse error
1619
- const errorRes = {
1620
- jsonrpc: '2.0',
1621
- id: null,
1622
- error: { code: -32700, message: 'Parse error: ' + parseErr.message },
1623
- };
1624
- console.log(JSON.stringify(errorRes));
1625
- return;
1626
- }
1627
-
1628
- if (Array.isArray(req)) {
1629
- const responses = [];
1630
- for (const singleReq of req) {
1631
- const response = await processSingleRequest(singleReq);
1632
- if (response) {
1633
- responses.push(response);
1634
- }
1635
- }
1636
- if (responses.length > 0) {
1637
- console.log(JSON.stringify(responses));
1638
- }
1639
- } else {
1640
- const response = await processSingleRequest(req);
1641
- if (response) {
1642
- console.log(JSON.stringify(response));
1643
- }
1644
- }
1645
- });
1646
-
1647
- if (process.env.NODE_ENV === 'test') {
1648
- module.exports = {
1649
- handleRequest,
1650
- stripBoilerplate,
1651
- runTribunalAudit,
1652
- };
1653
- }
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Tribunal-Kit MCP Server (Performance-Optimized)
5
+ *
6
+ * This file exposes tribunal-kit tools via the Model Context Protocol (MCP)
7
+ * over standard I/O, allowing AI clients (Cursor, Windsurf, Claude) to natively
8
+ * invoke tribunal checks.
9
+ *
10
+ * In-process tools load reusable modules directly. Commands that depend on a
11
+ * standalone CLI process remain isolated deliberately.
12
+ *
13
+ * Protocol: MCP 2024-11-05 over JSON-RPC 2.0 / stdio
14
+ */
15
+
16
+ const path = require('path');
17
+ const { spawnSync } = require('child_process');
18
+
19
+ const PKG = require(path.resolve(__dirname, '../package.json'));
20
+
21
+ // Timeout for intentionally isolated child processes (30 seconds).
22
+ const SPAWN_TIMEOUT_MS = 30000;
23
+ const GENERAL_TOOL_TIMEOUT_MS = 60000;
24
+
25
+ // --- DSH Guard: Cooperative Timeout ---
26
+ async function withToolTimeout(fn, timeoutMs) {
27
+ let timeoutId;
28
+ const timeoutPromise = new Promise((_, reject) => {
29
+ timeoutId = setTimeout(() => {
30
+ reject(new Error('TOOL_TIMEOUT'));
31
+ }, timeoutMs);
32
+ });
33
+
34
+ try {
35
+ const result = await Promise.race([Promise.resolve().then(fn), timeoutPromise]);
36
+ return result;
37
+ } finally {
38
+ clearTimeout(timeoutId);
39
+ }
40
+ }
41
+
42
+ // --- DSH Guard: Loop Detection ---
43
+ class ToolRepeatGuard {
44
+ constructor() {
45
+ this.history = new Map();
46
+ }
47
+
48
+ observe(toolName, argsObj) {
49
+ const canonicalize = obj => {
50
+ if (Array.isArray(obj)) return obj.map(canonicalize);
51
+ if (obj !== null && typeof obj === 'object') {
52
+ const sorted = {};
53
+ for (const key of Object.keys(obj).sort()) {
54
+ sorted[key] = canonicalize(obj[key]);
55
+ }
56
+ return sorted;
57
+ }
58
+ if (typeof obj === 'string') {
59
+ return obj.trim().toLowerCase().replace(/\s+/g, ' ');
60
+ }
61
+ return obj;
62
+ };
63
+
64
+ const canonicalArgs = JSON.stringify(canonicalize(argsObj) || {});
65
+ const key = `${toolName}::${canonicalArgs}`;
66
+
67
+ const currentCount = (this.history.get(key) || 0) + 1;
68
+ this.history.clear();
69
+ this.history.set(key, currentCount);
70
+
71
+ if (currentCount === 3) {
72
+ return 'SYSTEM NOTIFICATION: You are repeating the exact same tool call with identical arguments. Carefully analyze the previous result before calling again: if the task is not complete, try a different approach or different arguments instead of repeating the call.';
73
+ }
74
+ if (currentCount >= 5) {
75
+ return `SYSTEM NOTIFICATION: Repeated tool call detected:\n- tool: ${toolName}\n- consecutive_calls: ${currentCount}\n- arguments: ${canonicalArgs}\nThe repeated calls are not making progress. Do not call this tool with these exact arguments again. Inspect the latest result and choose a different action, different arguments, or finish the task.`;
76
+ }
77
+ return null;
78
+ }
79
+ }
80
+ const repeatGuard = new ToolRepeatGuard();
81
+
82
+ class RpcError extends Error {
83
+ constructor(code, message) {
84
+ super(message);
85
+ this.code = code;
86
+ this.name = 'RpcError';
87
+ }
88
+ }
89
+
90
+ // Minimal JSON-RPC 2.0 over stdio
91
+ const readline = require('readline');
92
+
93
+ const rl = readline.createInterface({
94
+ input: process.stdin,
95
+ output: process.stdout,
96
+ terminal: false,
97
+ });
98
+
99
+ /**
100
+ * Run the workspace integrity audit without invoking the CLI schema validator.
101
+ * The MCP audit is about Tribunal assets, while `tk validate` validates one
102
+ * explicitly supplied payload and schema.
103
+ */
104
+ function runTribunalAudit() {
105
+ const fs = require('fs');
106
+ const projectRoot = process.cwd();
107
+ const manifestScript = path.join(projectRoot, '.agent', 'scripts', 'integrity_manifest.js');
108
+
109
+ if (!fs.existsSync(manifestScript)) {
110
+ return 'Error: .agent/scripts/integrity_manifest.js was not found. Run `tk init` first.';
111
+ }
112
+
113
+ try {
114
+ const { generateManifest } = require(manifestScript);
115
+ const manifest = generateManifest(projectRoot);
116
+ if (manifest.error) return `Error: ${manifest.error}`;
117
+
118
+ const { integrity } = manifest;
119
+ const lines = [
120
+ 'Tribunal audit complete.',
121
+ `Agents: ${manifest.agents.total} (${manifest.agents.reviewer_count} reviewers)`,
122
+ `Skills: ${manifest.skills.total}`,
123
+ `Scripts: ${manifest.scripts.total}`,
124
+ `Workflows: ${manifest.workflows.total}`,
125
+ `References: ${integrity.total_references}; phantom references: ${integrity.phantom_references}`,
126
+ `Count claims: ${integrity.total_claims}; invalid claims: ${integrity.invalid_claims}`,
127
+ ];
128
+
129
+ if (integrity.phantom_references > 0 || integrity.invalid_claims > 0) {
130
+ lines.push(
131
+ 'Audit found integrity issues; run `tk guardrail --scan` for remediation details.',
132
+ );
133
+ } else {
134
+ lines.push('All discovered references and global asset-count claims are valid.');
135
+ }
136
+ return lines.join('\n');
137
+ } catch (error) {
138
+ return `Audit failed: ${error.message}`;
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Search case law in an isolated process because its CLI owns persistent state.
144
+ */
145
+ function searchCaseLaw(query) {
146
+ const caseLawScript = path.resolve(__dirname, '../.agent/scripts/case_law_manager.js');
147
+ // case_law_manager is a standalone stateful CLI, so retain its process boundary.
148
+ const result = spawnSync(process.execPath, [caseLawScript, 'search-cases', '--query', query], {
149
+ encoding: 'utf8',
150
+ timeout: SPAWN_TIMEOUT_MS,
151
+ });
152
+ if (result.error) {
153
+ if (result.error.code === 'ETIMEDOUT')
154
+ return 'Error: Case law search timed out (exceeded 30s limit)';
155
+ return `Error executing case law search: ${result.error.message}`;
156
+ }
157
+ return result.stdout || result.stderr || 'No results';
158
+ }
159
+
160
+ function stripBoilerplate(text) {
161
+ if (!text) return text;
162
+ let minified = text.replace(
163
+ /AI coding assistants often fall into specific bad habits[\s\S]*$/g,
164
+ '',
165
+ );
166
+ minified = minified.replace(/## 🤖 LLM-Specific Traps[\s\S]*$/g, '');
167
+ minified = minified.replace(/## 🏛️ Tribunal Integration[\s\S]*$/g, '');
168
+ minified = minified.replace(/## Pre-Flight Checklist[\s\S]*$/g, '');
169
+ return minified.trim();
170
+ }
171
+
172
+ function getAgentDir() {
173
+ const fs = require('fs');
174
+ const local = path.join(process.cwd(), '.agent');
175
+ if (fs.existsSync(local)) return local;
176
+ return path.resolve(__dirname, '../.agent');
177
+ }
178
+
179
+ async function handleRequest(req) {
180
+ const fs = require('fs');
181
+ if (req.method === 'notifications/initialized' || req.method === 'notifications/cancelled') {
182
+ return null;
183
+ }
184
+ if (req.method === 'ping') {
185
+ return {};
186
+ }
187
+
188
+ // MCP spec: method names follow path-style convention
189
+ if (req.method === 'initialize') {
190
+ return {
191
+ protocolVersion: '2025-03-26',
192
+ capabilities: {
193
+ tools: {},
194
+ resources: { subscribe: false, listChanged: false },
195
+ prompts: { listChanged: false },
196
+ },
197
+ serverInfo: {
198
+ name: 'tribunal-kit-mcp',
199
+ version: PKG.version,
200
+ },
201
+ };
202
+ }
203
+
204
+ if (req.method === 'resources/list') {
205
+ const agentDir = getAgentDir();
206
+ const resources = [];
207
+
208
+ // Agents
209
+ const agentsDir = path.join(agentDir, 'agents');
210
+ if (fs.existsSync(agentsDir)) {
211
+ const files = fs.readdirSync(agentsDir).filter(f => f.endsWith('.md'));
212
+ for (const f of files) {
213
+ const name = path.basename(f, '.md');
214
+ resources.push({
215
+ uri: `tribunal://agent/${name}`,
216
+ name: `Agent: ${name}`,
217
+ description: `Tribunal Specialist Agent rule file for ${name}`,
218
+ mimeType: 'text/markdown',
219
+ });
220
+ }
221
+ }
222
+
223
+ // Skills
224
+ const skillsDir = path.join(agentDir, 'skills');
225
+ if (fs.existsSync(skillsDir)) {
226
+ const dirs = fs.readdirSync(skillsDir, { withFileTypes: true });
227
+ for (const d of dirs) {
228
+ if (d.isDirectory()) {
229
+ const skillFile = path.join(skillsDir, d.name, 'SKILL.md');
230
+ if (fs.existsSync(skillFile)) {
231
+ resources.push({
232
+ uri: `tribunal://skill/${d.name}`,
233
+ name: `Skill: ${d.name}`,
234
+ description: `Tribunal Skill instruction file for ${d.name}`,
235
+ mimeType: 'text/markdown',
236
+ });
237
+ }
238
+ }
239
+ }
240
+ }
241
+
242
+ // Workflows
243
+ const workflowsDir = path.join(agentDir, 'workflows');
244
+ if (fs.existsSync(workflowsDir)) {
245
+ const files = fs.readdirSync(workflowsDir).filter(f => f.endsWith('.md'));
246
+ for (const f of files) {
247
+ const name = path.basename(f, '.md');
248
+ resources.push({
249
+ uri: `tribunal://workflow/${name}`,
250
+ name: `Workflow: ${name}`,
251
+ description: `Tribunal Workflow guide for ${name}`,
252
+ mimeType: 'text/markdown',
253
+ });
254
+ }
255
+ }
256
+
257
+ return { resources };
258
+ }
259
+
260
+ if (req.method === 'resources/read') {
261
+ const uri = req.params && req.params.uri;
262
+ if (!uri) throw new Error('Missing uri parameter');
263
+ const agentDir = getAgentDir();
264
+ let filePath = null;
265
+
266
+ if (uri.startsWith('tribunal://agent/')) {
267
+ const name = uri.replace('tribunal://agent/', '');
268
+ filePath = path.join(agentDir, 'agents', `${name}.md`);
269
+ } else if (uri.startsWith('tribunal://skill/')) {
270
+ const name = uri.replace('tribunal://skill/', '');
271
+ filePath = path.join(agentDir, 'skills', name, 'SKILL.md');
272
+ } else if (uri.startsWith('tribunal://workflow/')) {
273
+ const name = uri.replace('tribunal://workflow/', '');
274
+ filePath = path.join(agentDir, 'workflows', `${name}.md`);
275
+ }
276
+
277
+ if (!filePath || !fs.existsSync(filePath)) {
278
+ throw new Error(`Resource not found: ${uri}`);
279
+ }
280
+
281
+ const text = fs.readFileSync(filePath, 'utf8');
282
+ return {
283
+ contents: [
284
+ {
285
+ uri,
286
+ mimeType: 'text/markdown',
287
+ text,
288
+ },
289
+ ],
290
+ };
291
+ }
292
+
293
+ if (req.method === 'prompts/list') {
294
+ const agentDir = getAgentDir();
295
+ const prompts = [];
296
+ const workflowsDir = path.join(agentDir, 'workflows');
297
+
298
+ if (fs.existsSync(workflowsDir)) {
299
+ const files = fs.readdirSync(workflowsDir).filter(f => f.endsWith('.md'));
300
+ for (const f of files) {
301
+ const name = path.basename(f, '.md');
302
+ prompts.push({
303
+ name,
304
+ description: `Execute tribunal workflow /${name}`,
305
+ arguments: [
306
+ {
307
+ name: 'task',
308
+ description: 'The task or target file to execute the workflow against',
309
+ required: false,
310
+ },
311
+ ],
312
+ });
313
+ }
314
+ }
315
+
316
+ return { prompts };
317
+ }
318
+
319
+ if (req.method === 'prompts/get') {
320
+ const name = req.params && req.params.name;
321
+ const task = (req.params && req.params.arguments && req.params.arguments.task) || '';
322
+ if (!name) throw new Error('Missing prompt name parameter');
323
+
324
+ const agentDir = getAgentDir();
325
+ const workflowPath = path.join(agentDir, 'workflows', `${name}.md`);
326
+ if (!fs.existsSync(workflowPath)) {
327
+ throw new Error(`Prompt workflow not found: ${name}`);
328
+ }
329
+
330
+ const content = fs.readFileSync(workflowPath, 'utf8');
331
+ const promptText = task ? `${content}\n\nTarget Task/File: ${task}` : content;
332
+
333
+ return {
334
+ messages: [
335
+ {
336
+ role: 'user',
337
+ content: {
338
+ type: 'text',
339
+ text: promptText,
340
+ },
341
+ },
342
+ ],
343
+ };
344
+ }
345
+
346
+ if (req.method === 'tools/list') {
347
+ return {
348
+ tools: [
349
+ {
350
+ name: 'run_tribunal_audit',
351
+ description: 'Runs a full anti-hallucination audit across the workspace.',
352
+ inputSchema: {
353
+ type: 'object',
354
+ properties: {},
355
+ additionalProperties: false,
356
+ },
357
+ },
358
+ {
359
+ name: 'sync_ide_bridges',
360
+ description: 'Synchronize IDE bridge files with the current GEMINI.md rules.',
361
+ inputSchema: {
362
+ type: 'object',
363
+ properties: {},
364
+ additionalProperties: false,
365
+ },
366
+ },
367
+ {
368
+ name: 'search_case_law',
369
+ description:
370
+ 'Search historical code rejections and legal precedent. Use this before writing code to avoid past mistakes.',
371
+ inputSchema: {
372
+ type: 'object',
373
+ properties: {
374
+ query: {
375
+ type: 'string',
376
+ description: "Search query (e.g. 'useEffect state')",
377
+ },
378
+ },
379
+ required: ['query'],
380
+ additionalProperties: false,
381
+ },
382
+ },
383
+ {
384
+ name: 'list_tribunal_agents',
385
+ description: 'List all available Tribunal Kit agents.',
386
+ inputSchema: {
387
+ type: 'object',
388
+ properties: {},
389
+ additionalProperties: false,
390
+ },
391
+ },
392
+ {
393
+ name: 'get_tribunal_agent',
394
+ description: 'Get the full markdown rules for a specific Tribunal agent.',
395
+ inputSchema: {
396
+ type: 'object',
397
+ properties: {
398
+ name: { type: 'string', description: "The agent name (e.g. 'frontend-specialist')" },
399
+ },
400
+ required: ['name'],
401
+ additionalProperties: false,
402
+ },
403
+ },
404
+ {
405
+ name: 'list_tribunal_skills',
406
+ description: 'List all available Tribunal Kit skills.',
407
+ inputSchema: {
408
+ type: 'object',
409
+ properties: {},
410
+ additionalProperties: false,
411
+ },
412
+ },
413
+ {
414
+ name: 'get_tribunal_skill',
415
+ description: 'Get the full markdown instructions for a specific Tribunal skill.',
416
+ inputSchema: {
417
+ type: 'object',
418
+ properties: {
419
+ name: { type: 'string', description: "The skill name (e.g. 'react-specialist')" },
420
+ },
421
+ required: ['name'],
422
+ additionalProperties: false,
423
+ },
424
+ },
425
+ {
426
+ name: 'recall_memory',
427
+ description:
428
+ 'Budget-constrained memory recall from the 4-Type Taxonomy Persistent Memory Engine. Returns the most relevant memories that fit within the token budget, ranked by relevance × recency × priority. Use this BEFORE writing code to recall project guidelines without bloating context.',
429
+ inputSchema: {
430
+ type: 'object',
431
+ properties: {
432
+ query: {
433
+ type: 'string',
434
+ description: "Search query (e.g. 'database', 'auth', 'deploy')",
435
+ },
436
+ budget: {
437
+ type: 'number',
438
+ description:
439
+ 'Maximum token budget for recall (default: 2000). Only the top-ranked memories that fit within this budget are returned.',
440
+ },
441
+ },
442
+ required: ['query'],
443
+ additionalProperties: false,
444
+ },
445
+ },
446
+ {
447
+ name: 'store_memory',
448
+ description:
449
+ 'Store a new memory entry in the 4-Type Taxonomy Persistent Memory Engine. Memories are schema-validated and persisted across sessions. Types: semantic (permanent facts), procedural (how-to recipes), episodic (30-day TTL events), working (session scratch).',
450
+ inputSchema: {
451
+ type: 'object',
452
+ properties: {
453
+ type: {
454
+ type: 'string',
455
+ enum: ['semantic', 'procedural', 'episodic', 'working'],
456
+ description:
457
+ 'Memory type: semantic (facts), procedural (recipes), episodic (events), working (scratch)',
458
+ },
459
+ content: {
460
+ type: 'string',
461
+ description: 'The memory content to store',
462
+ },
463
+ tags: {
464
+ type: 'array',
465
+ items: { type: 'string' },
466
+ description: 'Searchable tags for this memory',
467
+ },
468
+ },
469
+ required: ['type', 'content'],
470
+ additionalProperties: false,
471
+ },
472
+ },
473
+ {
474
+ name: 'get_sparse_context',
475
+ description:
476
+ 'Get a JIT, token-optimized context prompt tailored to the active task and files. Uses the Context Density Broker to score and select relevant skills, stripping duplicate boilerplate and saving up to 85% in prompt tokens.',
477
+ inputSchema: {
478
+ type: 'object',
479
+ properties: {
480
+ task: {
481
+ type: 'string',
482
+ description: "The user task description (e.g. 'JWT auth API')",
483
+ },
484
+ files: {
485
+ type: 'array',
486
+ items: { type: 'string' },
487
+ description: "List of files being touched (e.g. ['src/auth.js'])",
488
+ },
489
+ model: {
490
+ type: 'string',
491
+ enum: ['large', 'small'],
492
+ description:
493
+ 'Model tier: large (default, includes key rules of supplementary skills) or small (essential skills only)',
494
+ },
495
+ },
496
+ required: ['task'],
497
+ additionalProperties: false,
498
+ },
499
+ },
500
+ {
501
+ name: 'align_output',
502
+ description:
503
+ 'Align model outputs to Fabel-5 constraints: strips conversational introductions and conclusions, collapses single/double bullet items to prose, and checks for code traps (unawaited dynamic functions in Next.js 15, deprecated hooks in React 19, or non-existent models).',
504
+ inputSchema: {
505
+ type: 'object',
506
+ properties: {
507
+ text: {
508
+ type: 'string',
509
+ description: 'The raw output text generated by the model to be aligned.',
510
+ },
511
+ },
512
+ required: ['text'],
513
+ additionalProperties: false,
514
+ },
515
+ },
516
+ {
517
+ name: 'verify_contracts',
518
+ description:
519
+ 'Verify proposed code changes against project behavioral contracts. Use BEFORE writing code to ensure compliance with team conventions.',
520
+ inputSchema: {
521
+ type: 'object',
522
+ properties: {
523
+ file: {
524
+ type: 'string',
525
+ description: "Relative or absolute file path to verify (e.g. 'src/api/user.ts')",
526
+ },
527
+ content: {
528
+ type: 'string',
529
+ description: 'Proposed file content to verify against loaded contracts',
530
+ },
531
+ },
532
+ required: ['file', 'content'],
533
+ additionalProperties: false,
534
+ },
535
+ },
536
+ {
537
+ name: 'query_semantic_graph',
538
+ description:
539
+ 'Query the Ahead-of-Time (AOT) Semantic Context Graph to quickly resolve function signatures, dependencies, and file structures without inflating context windows.',
540
+ inputSchema: {
541
+ type: 'object',
542
+ properties: {
543
+ targetPath: {
544
+ type: 'string',
545
+ description: 'The directory to query (defaults to current workspace).',
546
+ },
547
+ },
548
+ additionalProperties: false,
549
+ },
550
+ },
551
+ {
552
+ name: 'exit_plan_mode',
553
+ description:
554
+ 'Present your finished plan for human reviewed designing your approach. Execution will suspend until the user approves or requests changes.',
555
+ inputSchema: {
556
+ type: 'object',
557
+ properties: {
558
+ plan_content: {
559
+ type: 'string',
560
+ description: 'The markdown content of your proposed plan.',
561
+ },
562
+ },
563
+ required: ['plan_content'],
564
+ additionalProperties: false,
565
+ },
566
+ },
567
+ {
568
+ name: 'tk_browser_navigate',
569
+ description:
570
+ 'Token-efficient browser navigation. Navigates headlessly to a URL, prunes HTML using htmltrim (< 4,000 bytes / ~1,000 tokens), enforces IDPI prompt injection defense, and returns compact semantic markdown with an interactive elements tree.',
571
+ inputSchema: {
572
+ type: 'object',
573
+ properties: {
574
+ url: {
575
+ type: 'string',
576
+ description:
577
+ 'The target URL to inspect (e.g. http://localhost:3000 or https://example.com)',
578
+ },
579
+ },
580
+ required: ['url'],
581
+ additionalProperties: false,
582
+ },
583
+ },
584
+ {
585
+ name: 'tk_browser_audit',
586
+ description:
587
+ 'Live web quality, accessibility, console error, and Core Web Vitals auditor. Navigates headlessly to a URL, checks WCAG 2.2 contrast/aria, network failures, uncaught exceptions, and security headers. Returns structured audit report.',
588
+ inputSchema: {
589
+ type: 'object',
590
+ properties: {
591
+ url: {
592
+ type: 'string',
593
+ description: 'The target URL to audit (e.g. http://localhost:3000)',
594
+ },
595
+ },
596
+ required: ['url'],
597
+ additionalProperties: false,
598
+ },
599
+ },
600
+ {
601
+ name: 'tk_browser_compare',
602
+ description:
603
+ 'Visual regression differ. Captures synchronized screenshots of two URLs (e.g. localhost dev server vs production) and computes pixel mismatch percentage to verify layout integrity before release.',
604
+ inputSchema: {
605
+ type: 'object',
606
+ properties: {
607
+ url1: {
608
+ type: 'string',
609
+ description: 'Baseline or staging URL (e.g. http://localhost:3000)',
610
+ },
611
+ url2: {
612
+ type: 'string',
613
+ description: 'Production or target URL to compare against',
614
+ },
615
+ maxDiffPercent: {
616
+ type: 'number',
617
+ description:
618
+ 'Maximum allowable difference percentage before failing (default: 1.0)',
619
+ },
620
+ },
621
+ required: ['url1', 'url2'],
622
+ additionalProperties: false,
623
+ },
624
+ },
625
+ {
626
+ name: 'tk_browser_screenshot',
627
+ description: 'Captures a viewport screenshot of a target URL as base64 PNG data.',
628
+ inputSchema: {
629
+ type: 'object',
630
+ properties: {
631
+ url: {
632
+ type: 'string',
633
+ description: 'The URL to screenshot',
634
+ },
635
+ },
636
+ required: ['url'],
637
+ additionalProperties: false,
638
+ },
639
+ },
640
+ {
641
+ name: 'tk_deconstruct_component',
642
+ description:
643
+ 'Reverse-engineers a live web element into a production React TSX component with Tailwind CSS classes by inspecting computed CSSOM (geometry, typography, elevation, transitions).',
644
+ inputSchema: {
645
+ type: 'object',
646
+ properties: {
647
+ url: {
648
+ type: 'string',
649
+ description: 'The URL hosting the target element',
650
+ },
651
+ selector: {
652
+ type: 'string',
653
+ description:
654
+ 'CSS selector matching the element (e.g. button.primary or #pricing-card)',
655
+ },
656
+ name: {
657
+ type: 'string',
658
+ description: 'Optional PascalCase component name (e.g. PricingCard)',
659
+ },
660
+ },
661
+ required: ['url', 'selector'],
662
+ additionalProperties: false,
663
+ },
664
+ },
665
+ {
666
+ name: 'tk_heal_runtime_errors',
667
+ description:
668
+ 'Runtime Sentinel error hunter. Scans a live web page or dev server for uncaught exceptions, React boundary errors, and framework overlays, localizing them to workspace source files.',
669
+ inputSchema: {
670
+ type: 'object',
671
+ properties: {
672
+ url: {
673
+ type: 'string',
674
+ description: 'The dev server or web page URL (e.g. http://localhost:3000)',
675
+ },
676
+ verify: {
677
+ type: 'boolean',
678
+ description:
679
+ 'If true, verifies whether previously reported runtime errors have cleared',
680
+ },
681
+ },
682
+ required: ['url'],
683
+ additionalProperties: false,
684
+ },
685
+ },
686
+ {
687
+ name: 'tk_codify_browser_audit',
688
+ description:
689
+ 'Audits a target URL and automatically codifies detected WCAG accessibility failures, missing security headers, and console errors into binding Case Law precedents.',
690
+ inputSchema: {
691
+ type: 'object',
692
+ properties: {
693
+ url: {
694
+ type: 'string',
695
+ description: 'The URL to audit and codify',
696
+ },
697
+ },
698
+ required: ['url'],
699
+ additionalProperties: false,
700
+ },
701
+ },
702
+ {
703
+ name: 'tribunal_get_context',
704
+ description:
705
+ "Generate or retrieve an elite Flight Data HUD context dossier for any file, multi-file pair, or directory. Automatically extracts public API contracts, callers, Chesterton's Fences, invariants, and test recipes. Supports drift checking and living vault sync.",
706
+ inputSchema: {
707
+ type: 'object',
708
+ properties: {
709
+ target: {
710
+ type: 'string',
711
+ description: 'File path, folder path, or primary file to analyze.',
712
+ },
713
+ compareWith: {
714
+ type: 'string',
715
+ description: 'Optional secondary file for multi-file interface bridge analysis.',
716
+ },
717
+ write: {
718
+ type: 'boolean',
719
+ description:
720
+ 'Whether to write the generated dossier to docs/context/ and update INDEX.md (default: true).',
721
+ },
722
+ check: {
723
+ type: 'boolean',
724
+ description: 'Run vault-wide semantic drift check instead of analyzing a target.',
725
+ },
726
+ },
727
+ additionalProperties: false,
728
+ },
729
+ },
730
+ ],
731
+ };
732
+ }
733
+
734
+ if (req.method === 'tools/call') {
735
+ const toolName = req.params && req.params.name;
736
+ const argsObj = req.params && req.params.arguments;
737
+ if (!toolName) {
738
+ throw new RpcError(-32602, 'Missing required parameter: params.name');
739
+ }
740
+
741
+ const reminder = repeatGuard.observe(toolName, argsObj);
742
+
743
+ const executeTool = async () => {
744
+ if (toolName === 'tribunal_get_context') {
745
+ const target = req.params?.arguments?.target;
746
+ const compareWith = req.params?.arguments?.compareWith;
747
+ const write = req.params?.arguments?.write !== false;
748
+ const check = req.params?.arguments?.check;
749
+
750
+ try {
751
+ const workspaceRoot = process.cwd();
752
+
753
+ if (check) {
754
+ const { spawn } = require('child_process');
755
+ const result = await new Promise((resolve, reject) => {
756
+ const child = spawn(
757
+ process.execPath,
758
+ [path.join(__dirname, '../scripts/context_compiler.js'), '--check', '--json'],
759
+ { cwd: workspaceRoot, encoding: 'utf8' },
760
+ );
761
+ let out = '';
762
+ child.stdout.on('data', d => (out += d));
763
+ child.stderr.on('data', d => (out += d));
764
+ child.on('close', _code => resolve(out));
765
+ child.on('error', reject);
766
+ });
767
+ return {
768
+ content: [
769
+ {
770
+ type: 'text',
771
+ text: result,
772
+ },
773
+ ],
774
+ };
775
+ }
776
+
777
+ if (!target) {
778
+ throw new RpcError(
779
+ -32602,
780
+ 'Missing required argument: target (file or directory path)',
781
+ );
782
+ }
783
+
784
+ // We use scripts/context_compiler.js to parse AST without blocking the event loop
785
+ const { spawn } = require('child_process');
786
+ const args = [path.join(__dirname, '../scripts/context_compiler.js')];
787
+
788
+ if (compareWith) {
789
+ args.push('--multi', target, compareWith);
790
+ } else {
791
+ args.push(target);
792
+ }
793
+
794
+ if (write) {
795
+ args.push('--write');
796
+ }
797
+
798
+ const result = await new Promise((resolve, reject) => {
799
+ const child = spawn(process.execPath, args, { cwd: workspaceRoot, encoding: 'utf8' });
800
+ let out = '';
801
+ child.stdout.on('data', d => (out += d));
802
+ child.stderr.on('data', d => (out += d));
803
+ child.on('close', _code => {
804
+ resolve(out);
805
+ });
806
+ child.on('error', reject);
807
+ });
808
+
809
+ return {
810
+ content: [{ type: 'text', text: result }],
811
+ };
812
+ } catch (e) {
813
+ return {
814
+ content: [{ type: 'text', text: `Context Compiler Error: ${e.message}` }],
815
+ isError: true,
816
+ };
817
+ }
818
+ }
819
+
820
+ if (toolName === 'exit_plan_mode') {
821
+ const planContent = req.params?.arguments?.plan_content;
822
+ if (typeof planContent !== 'string') {
823
+ throw new RpcError(-32602, 'Missing or invalid required argument: plan_content (string)');
824
+ }
825
+ // The wrapper CLI can intercept this, but for the LLM context, we explicitly tell it to wait.
826
+ return {
827
+ content: [
828
+ {
829
+ type: 'text',
830
+ text: 'PLAN_SUBMITTED_FOR_REVIEW: The plan has been presented to the human. Please suspend execution and wait for the human to approve or provide feedback in the next turn. Do not call any further tools until you receive a response.',
831
+ },
832
+ ],
833
+ };
834
+ }
835
+
836
+ if (toolName === 'tk_browser_navigate') {
837
+ const url = req.params?.arguments?.url;
838
+ if (!url || typeof url !== 'string') {
839
+ throw new RpcError(-32602, 'Missing required argument: url (string)');
840
+ }
841
+ try {
842
+ const { browse } = require('../src/browser');
843
+ const result = await browse(url);
844
+ return {
845
+ content: [
846
+ {
847
+ type: 'text',
848
+ text: result.sandboxed,
849
+ },
850
+ ],
851
+ };
852
+ } catch (e) {
853
+ return {
854
+ content: [{ type: 'text', text: `Browser navigation error: ${e.message}` }],
855
+ isError: true,
856
+ };
857
+ }
858
+ }
859
+
860
+ if (toolName === 'tk_browser_audit') {
861
+ const url = req.params?.arguments?.url;
862
+ if (!url || typeof url !== 'string') {
863
+ throw new RpcError(-32602, 'Missing required argument: url (string)');
864
+ }
865
+ try {
866
+ const { auditURL } = require('../src/browser');
867
+ const report = await auditURL(url);
868
+ return {
869
+ content: [
870
+ {
871
+ type: 'text',
872
+ text: JSON.stringify(report, null, 2),
873
+ },
874
+ ],
875
+ };
876
+ } catch (e) {
877
+ return {
878
+ content: [{ type: 'text', text: `Browser audit error: ${e.message}` }],
879
+ isError: true,
880
+ };
881
+ }
882
+ }
883
+
884
+ if (toolName === 'tk_browser_compare') {
885
+ const url1 = req.params?.arguments?.url1;
886
+ const url2 = req.params?.arguments?.url2;
887
+ const maxDiffPercent = req.params?.arguments?.maxDiffPercent;
888
+ if (!url1 || !url2) {
889
+ throw new RpcError(-32602, 'Missing required arguments: url1 and url2 (strings)');
890
+ }
891
+ try {
892
+ const { compareURLs } = require('../src/browser');
893
+ const result = await compareURLs(url1, url2, { maxDiffPercent });
894
+ return {
895
+ content: [
896
+ {
897
+ type: 'text',
898
+ text: JSON.stringify(result, null, 2),
899
+ },
900
+ ],
901
+ };
902
+ } catch (e) {
903
+ return {
904
+ content: [{ type: 'text', text: `Browser compare error: ${e.message}` }],
905
+ isError: true,
906
+ };
907
+ }
908
+ }
909
+
910
+ if (toolName === 'tk_browser_screenshot') {
911
+ const url = req.params?.arguments?.url;
912
+ if (!url || typeof url !== 'string') {
913
+ throw new RpcError(-32602, 'Missing required argument: url (string)');
914
+ }
915
+ try {
916
+ const { launchBrowser, CdpClient, createNewTab, closeTab } = require('../src/browser');
917
+ const browser = await launchBrowser();
918
+ let client = null;
919
+ let tab = null;
920
+ try {
921
+ tab = await createNewTab(browser.port);
922
+ client = new CdpClient();
923
+ await client.connect(tab.webSocketDebuggerUrl);
924
+ await client.initDomains();
925
+ await client.navigate(url);
926
+ const shot = await client.captureScreenshot('png');
927
+ return {
928
+ content: [
929
+ {
930
+ type: 'text',
931
+ text: `Screenshot captured successfully for ${url} (${Buffer.byteLength(shot, 'base64')} bytes base64 PNG).`,
932
+ },
933
+ ],
934
+ };
935
+ } finally {
936
+ if (client) client.close();
937
+ if (tab && browser) await closeTab(tab.id, browser.port);
938
+ await browser.close();
939
+ }
940
+ } catch (e) {
941
+ return {
942
+ content: [{ type: 'text', text: `Screenshot error: ${e.message}` }],
943
+ isError: true,
944
+ };
945
+ }
946
+ }
947
+
948
+ if (toolName === 'tk_deconstruct_component') {
949
+ const url = req.params?.arguments?.url;
950
+ const selector = req.params?.arguments?.selector;
951
+ const name = req.params?.arguments?.name;
952
+ if (!url || !selector) {
953
+ throw new RpcError(-32602, 'Missing required arguments: url and selector (strings)');
954
+ }
955
+ try {
956
+ const { deconstructElement } = require('../src/browser');
957
+ const result = await deconstructElement(url, selector, { name });
958
+ return {
959
+ content: [
960
+ {
961
+ type: 'text',
962
+ text: result.code,
963
+ },
964
+ ],
965
+ };
966
+ } catch (e) {
967
+ return {
968
+ content: [{ type: 'text', text: `Component deconstruction error: ${e.message}` }],
969
+ isError: true,
970
+ };
971
+ }
972
+ }
973
+
974
+ if (toolName === 'tk_heal_runtime_errors') {
975
+ const url = req.params?.arguments?.url;
976
+ const verify = req.params?.arguments?.verify;
977
+ if (!url) {
978
+ throw new RpcError(-32602, 'Missing required argument: url (string)');
979
+ }
980
+ try {
981
+ const { captureRuntimeErrors, verifyRuntimeFix } = require('../src/browser');
982
+ const result = verify ? await verifyRuntimeFix(url) : await captureRuntimeErrors(url);
983
+ return {
984
+ content: [
985
+ {
986
+ type: 'text',
987
+ text: JSON.stringify(result, null, 2),
988
+ },
989
+ ],
990
+ };
991
+ } catch (e) {
992
+ return {
993
+ content: [{ type: 'text', text: `Runtime Sentinel error: ${e.message}` }],
994
+ isError: true,
995
+ };
996
+ }
997
+ }
998
+
999
+ if (toolName === 'tk_codify_browser_audit') {
1000
+ const url = req.params?.arguments?.url;
1001
+ if (!url) {
1002
+ throw new RpcError(-32602, 'Missing required argument: url (string)');
1003
+ }
1004
+ try {
1005
+ const { auditURL, codifyAuditViolations } = require('../src/browser');
1006
+ const report = await auditURL(url);
1007
+ const codified = codifyAuditViolations(report);
1008
+ return {
1009
+ content: [
1010
+ {
1011
+ type: 'text',
1012
+ text: JSON.stringify({ report, codified }, null, 2),
1013
+ },
1014
+ ],
1015
+ };
1016
+ } catch (e) {
1017
+ return {
1018
+ content: [{ type: 'text', text: `Audit & codify error: ${e.message}` }],
1019
+ isError: true,
1020
+ };
1021
+ }
1022
+ }
1023
+
1024
+ if (toolName === 'dispatch_swarm') {
1025
+ const payload = req.params?.arguments?.payload;
1026
+ const file = req.params?.arguments?.file;
1027
+ const workspace = req.params?.arguments?.workspace || '.';
1028
+ const mode = req.params?.arguments?.mode || 'legacy';
1029
+ const useTui = req.params?.arguments?.use_tui || false;
1030
+
1031
+ if (!payload && !file) {
1032
+ throw new RpcError(
1033
+ -32602,
1034
+ 'Missing required argument: either payload or file must be provided',
1035
+ );
1036
+ }
1037
+
1038
+ if (payload && file) {
1039
+ throw new RpcError(-32602, 'Invalid arguments: provide either payload or file, not both');
1040
+ }
1041
+
1042
+ const agentDir = getAgentDir();
1043
+ const fs = require('fs');
1044
+ if (!fs.existsSync(agentDir)) {
1045
+ return {
1046
+ content: [
1047
+ { type: 'text', text: 'Error: .agent/ directory not found. Run `tk init` first.' },
1048
+ ],
1049
+ };
1050
+ }
1051
+
1052
+ try {
1053
+ let _payloadData;
1054
+ if (file) {
1055
+ const filePath = path.resolve(workspace, file);
1056
+ if (!fs.existsSync(filePath)) {
1057
+ throw new Error(`File not found: ${filePath}`);
1058
+ }
1059
+ _payloadData = JSON.parse(fs.readFileSync(filePath, 'utf8'));
1060
+ } else {
1061
+ _payloadData = JSON.parse(payload);
1062
+ }
1063
+
1064
+ // Import swarm dispatcher functions
1065
+ const _swarmDispatcher = require(path.join(agentDir, 'scripts', 'swarm_dispatcher.js'));
1066
+
1067
+ // Execute the swarm dispatcher
1068
+ const originalArgv = process.argv;
1069
+ process.argv = ['node', 'swarm_dispatcher.js', '--mode', mode, '--workspace', workspace];
1070
+
1071
+ if (useTui) {
1072
+ process.argv.push('--tui');
1073
+ }
1074
+
1075
+ if (file) {
1076
+ process.argv.push('--file');
1077
+ process.argv.push(file);
1078
+ } else if (payload) {
1079
+ process.argv.push('--payload');
1080
+ process.argv.push(payload);
1081
+ }
1082
+
1083
+ // Capture output
1084
+ const { spawnSync } = require('child_process');
1085
+ const result = spawnSync(
1086
+ process.execPath,
1087
+ [path.join(agentDir, 'scripts', 'swarm_dispatcher.js'), ...process.argv.slice(2)],
1088
+ {
1089
+ encoding: 'utf8',
1090
+ timeout: 30000,
1091
+ },
1092
+ );
1093
+
1094
+ // Restore argv
1095
+ process.argv = originalArgv;
1096
+
1097
+ if (result.error) {
1098
+ throw result.error;
1099
+ }
1100
+
1101
+ return {
1102
+ content: [
1103
+ { type: 'text', text: result.stdout || result.stderr || 'Swarm dispatch completed' },
1104
+ ],
1105
+ };
1106
+ } catch (e) {
1107
+ return {
1108
+ content: [{ type: 'text', text: `Swarm dispatch failed: ${e.message}` }],
1109
+ };
1110
+ }
1111
+ }
1112
+
1113
+ if (toolName === 'get_ast_context') {
1114
+ const targetPath = req.params?.arguments?.targetPath || process.cwd();
1115
+ try {
1116
+ const result = spawnSync(
1117
+ 'node',
1118
+ [path.join(__dirname, '../scripts/build-graph.js'), targetPath],
1119
+ {
1120
+ encoding: 'utf8',
1121
+ timeout: 10000,
1122
+ },
1123
+ );
1124
+ if (result.error) throw result.error;
1125
+ return { content: [{ type: 'text', text: result.stdout || result.stderr }] };
1126
+ } catch (e) {
1127
+ return { content: [{ type: 'text', text: `Failed to query graph: ${e.message}` }] };
1128
+ }
1129
+ }
1130
+
1131
+ if (toolName === 'validate_payload') {
1132
+ const payloadStr = req.params?.arguments?.payload;
1133
+ const schemaType = req.params?.arguments?.schemaType;
1134
+
1135
+ if (!payloadStr || typeof payloadStr !== 'string') {
1136
+ throw new RpcError(-32602, 'Missing or invalid required argument: payload (string)');
1137
+ }
1138
+ if (!schemaType || typeof schemaType !== 'string') {
1139
+ throw new RpcError(-32602, 'Missing or invalid required argument: schemaType (string)');
1140
+ }
1141
+
1142
+ const agentDir = getAgentDir();
1143
+ const fs = require('fs');
1144
+ if (!fs.existsSync(agentDir)) {
1145
+ return {
1146
+ content: [
1147
+ { type: 'text', text: 'Error: .agent/ directory not found. Run `tk init` first.' },
1148
+ ],
1149
+ };
1150
+ }
1151
+
1152
+ try {
1153
+ const payloadData = JSON.parse(payloadStr);
1154
+ const {
1155
+ WorkerRequestSchema,
1156
+ WorkerResultSchema,
1157
+ SwarmPayloadSchema,
1158
+ validatePayloadOrThrow,
1159
+ } = require(path.join(agentDir, 'scripts', 'payload_schemas.js'));
1160
+
1161
+ let schema;
1162
+ switch (schemaType) {
1163
+ case 'worker-request':
1164
+ schema = WorkerRequestSchema;
1165
+ break;
1166
+ case 'worker-result':
1167
+ schema = WorkerResultSchema;
1168
+ break;
1169
+ case 'swarm-payload':
1170
+ schema = SwarmPayloadSchema;
1171
+ break;
1172
+ default:
1173
+ throw new RpcError(
1174
+ -32602,
1175
+ `Invalid schemaType: ${schemaType}. Must be one of: worker-request, worker-result, swarm-payload`,
1176
+ );
1177
+ }
1178
+
1179
+ const validatedData = validatePayloadOrThrow(payloadData, schema);
1180
+ return {
1181
+ content: [
1182
+ {
1183
+ type: 'text',
1184
+ text: `Payload validation successful.\n\nValidated payload:\n${JSON.stringify(validatedData, null, 2)}`,
1185
+ },
1186
+ ],
1187
+ };
1188
+ } catch (e) {
1189
+ if (e instanceof SyntaxError) {
1190
+ return { content: [{ type: 'text', text: `Invalid JSON payload: ${e.message}` }] };
1191
+ } else {
1192
+ return { content: [{ type: 'text', text: `Payload validation failed: ${e.message}` }] };
1193
+ }
1194
+ }
1195
+ }
1196
+
1197
+ if (toolName === 'run_tribunal_audit') {
1198
+ const text = runTribunalAudit();
1199
+ return { content: [{ type: 'text', text }] };
1200
+ }
1201
+
1202
+ if (toolName === 'sync_ide_bridges') {
1203
+ const fs = require('fs');
1204
+ const cwd = process.cwd();
1205
+ const agentDest = path.join(cwd, '.agent');
1206
+ if (!fs.existsSync(agentDest)) {
1207
+ return {
1208
+ content: [
1209
+ {
1210
+ type: 'text',
1211
+ text: 'Error: .agent/ directory not found. Run `tk init` first.',
1212
+ },
1213
+ ],
1214
+ };
1215
+ }
1216
+ try {
1217
+ const { generateIDEBridges } = require(
1218
+ path.resolve(__dirname, '../src/commands/init.js'),
1219
+ );
1220
+ // generateIDEBridges is async
1221
+ await generateIDEBridges(cwd, agentDest, true);
1222
+ return {
1223
+ content: [
1224
+ {
1225
+ type: 'text',
1226
+ text: 'Sync complete',
1227
+ },
1228
+ ],
1229
+ };
1230
+ } catch (e) {
1231
+ return {
1232
+ content: [
1233
+ {
1234
+ type: 'text',
1235
+ text: `Sync failed: ${e.message}`,
1236
+ },
1237
+ ],
1238
+ };
1239
+ }
1240
+ }
1241
+
1242
+ if (toolName === 'search_case_law') {
1243
+ const query = req.params && req.params.arguments && req.params.arguments.query;
1244
+ if (!query || typeof query !== 'string') {
1245
+ throw new RpcError(-32602, 'Missing or invalid required argument: query (string)');
1246
+ }
1247
+ const text = searchCaseLaw(query);
1248
+ return { content: [{ type: 'text', text }] };
1249
+ }
1250
+
1251
+ if (toolName === 'list_tribunal_agents') {
1252
+ const fs = require('fs');
1253
+ const agentDir = path.join(getAgentDir(), 'agents');
1254
+ if (!fs.existsSync(agentDir))
1255
+ return {
1256
+ content: [{ type: 'text', text: 'No agents found or .agent directory missing.' }],
1257
+ };
1258
+ const agents = fs
1259
+ .readdirSync(agentDir)
1260
+ .filter(f => f.endsWith('.md'))
1261
+ .map(f => f.replace('.md', ''));
1262
+ return { content: [{ type: 'text', text: 'Available Agents:\n- ' + agents.join('\n- ') }] };
1263
+ }
1264
+
1265
+ if (toolName === 'get_tribunal_agent') {
1266
+ const fs = require('fs');
1267
+ const name = req.params?.arguments?.name;
1268
+ if (!name || typeof name !== 'string')
1269
+ throw new RpcError(-32602, 'Missing or invalid argument: name (string)');
1270
+ const sanitizedName = path.basename(name);
1271
+ const agentsDir = path.resolve(getAgentDir(), 'agents');
1272
+ const agentPath = path.resolve(agentsDir, `${sanitizedName}.md`);
1273
+ // Path containment: ensure resolved path stays within agents directory
1274
+ if (!agentPath.startsWith(agentsDir))
1275
+ throw new RpcError(-32602, 'Invalid agent name: path traversal detected');
1276
+ if (!fs.existsSync(agentPath))
1277
+ return { content: [{ type: 'text', text: `Agent '${sanitizedName}' not found.` }] };
1278
+ const text = fs.readFileSync(agentPath, 'utf8');
1279
+ return { content: [{ type: 'text', text: stripBoilerplate(text) }] };
1280
+ }
1281
+
1282
+ if (toolName === 'list_tribunal_skills') {
1283
+ const fs = require('fs');
1284
+ const skillsDir = path.join(getAgentDir(), 'skills');
1285
+ if (!fs.existsSync(skillsDir))
1286
+ return {
1287
+ content: [{ type: 'text', text: 'No skills found or .agent directory missing.' }],
1288
+ };
1289
+ const skills = fs
1290
+ .readdirSync(skillsDir, { withFileTypes: true })
1291
+ .filter(d => d.isDirectory())
1292
+ .map(d => d.name);
1293
+ return { content: [{ type: 'text', text: 'Available Skills:\n- ' + skills.join('\n- ') }] };
1294
+ }
1295
+
1296
+ if (toolName === 'get_tribunal_skill') {
1297
+ const fs = require('fs');
1298
+ const name = req.params?.arguments?.name;
1299
+ if (!name || typeof name !== 'string')
1300
+ throw new RpcError(-32602, 'Missing or invalid argument: name (string)');
1301
+ const sanitizedName = path.basename(name);
1302
+ const skillsDir = path.resolve(getAgentDir(), 'skills');
1303
+ const skillPath = path.resolve(skillsDir, sanitizedName, 'SKILL.md');
1304
+ // Path containment: ensure resolved path stays within skills directory
1305
+ if (!skillPath.startsWith(skillsDir))
1306
+ throw new RpcError(-32602, 'Invalid skill name: path traversal detected');
1307
+ if (!fs.existsSync(skillPath))
1308
+ return { content: [{ type: 'text', text: `Skill '${sanitizedName}' not found.` }] };
1309
+ const text = fs.readFileSync(skillPath, 'utf8');
1310
+ return { content: [{ type: 'text', text: stripBoilerplate(text) }] };
1311
+ }
1312
+
1313
+ if (toolName === 'get_sparse_context') {
1314
+ const task = req.params?.arguments?.task;
1315
+ const files = req.params?.arguments?.files || [];
1316
+ const _model = req.params?.arguments?.model || 'large';
1317
+
1318
+ if (!task) throw new RpcError(-32602, 'Missing required argument: task');
1319
+
1320
+ const agentDest = getAgentDir();
1321
+ const fs = require('fs');
1322
+ if (!fs.existsSync(agentDest)) {
1323
+ return {
1324
+ content: [
1325
+ { type: 'text', text: 'Error: .agent/ directory not found. Run `tk init` first.' },
1326
+ ],
1327
+ };
1328
+ }
1329
+
1330
+ try {
1331
+ const workspaceRoot = process.cwd();
1332
+ const { spawn } = require('child_process');
1333
+ const args = [
1334
+ path.join(__dirname, 'wrapper.js'),
1335
+ 'context-broker',
1336
+ '--repo-path',
1337
+ workspaceRoot,
1338
+ ];
1339
+ if (files && files.length > 0) {
1340
+ args.push('--target-file');
1341
+ args.push(files[0]);
1342
+ }
1343
+
1344
+ const result = await new Promise((resolve, reject) => {
1345
+ const child = spawn(process.execPath, args, { cwd: workspaceRoot, encoding: 'utf8' });
1346
+ let out = '';
1347
+ child.stdout.on('data', d => (out += d));
1348
+ child.stderr.on('data', d => (out += d));
1349
+ child.on('close', _code => {
1350
+ resolve(out);
1351
+ });
1352
+ child.on('error', reject);
1353
+ });
1354
+
1355
+ let finalOutput = '';
1356
+ try {
1357
+ const parsed = JSON.parse(result);
1358
+ finalOutput = `# Tribunal Context Broker\n\n`;
1359
+ if (task) {
1360
+ finalOutput += `Task: ${task}\n\n`;
1361
+ }
1362
+ if (parsed.context_snapshot) {
1363
+ finalOutput += parsed.context_snapshot;
1364
+ }
1365
+ } catch (_e) {
1366
+ finalOutput = result;
1367
+ }
1368
+
1369
+ return { content: [{ type: 'text', text: stripBoilerplate(finalOutput) }] };
1370
+ } catch (e) {
1371
+ return {
1372
+ content: [{ type: 'text', text: `Failed to retrieve sparse context: ${e.message}` }],
1373
+ };
1374
+ }
1375
+ }
1376
+
1377
+ if (toolName === 'recall_memory') {
1378
+ const query = req.params?.arguments?.query;
1379
+ if (!query || typeof query !== 'string') {
1380
+ throw new RpcError(-32602, 'Missing or invalid required argument: query (string)');
1381
+ }
1382
+ const budget = req.params?.arguments?.budget || 2000;
1383
+ const agentDest = getAgentDir();
1384
+ const fs = require('fs');
1385
+ if (!fs.existsSync(agentDest)) {
1386
+ return {
1387
+ content: [
1388
+ { type: 'text', text: 'Error: .agent/ directory not found. Run `tk init` first.' },
1389
+ ],
1390
+ };
1391
+ }
1392
+ try {
1393
+ const { _memoryRecall } = require('../src/commands/memory.js');
1394
+ const { results, tokens_used } = _memoryRecall(agentDest, query, budget);
1395
+ if (results.length === 0) {
1396
+ return { content: [{ type: 'text', text: `No memories match query: "${query}"` }] };
1397
+ }
1398
+ let text = `## Memory Recall (${results.length} results, ~${tokens_used}/${budget} tokens)\n\n`;
1399
+ for (const entry of results) {
1400
+ text += `- **[${entry.memory_type.toUpperCase()}]** #${entry.id}: ${entry.content}`;
1401
+ if (entry.tags.length > 0) text += ` _(${entry.tags.join(', ')})_`;
1402
+ text += `\n`;
1403
+ }
1404
+ return { content: [{ type: 'text', text }] };
1405
+ } catch (e) {
1406
+ return { content: [{ type: 'text', text: `Memory recall failed: ${e.message}` }] };
1407
+ }
1408
+ }
1409
+
1410
+ if (toolName === 'store_memory') {
1411
+ const memType = req.params?.arguments?.type;
1412
+ const content = req.params?.arguments?.content;
1413
+ const tags = req.params?.arguments?.tags || [];
1414
+ if (!memType || !content) {
1415
+ throw new RpcError(-32602, 'Missing required arguments: type (string), content (string)');
1416
+ }
1417
+ const validTypes = ['semantic', 'procedural', 'episodic', 'working'];
1418
+ if (!validTypes.includes(memType)) {
1419
+ throw new RpcError(
1420
+ -32602,
1421
+ `Invalid memory type: "${memType}". Must be one of: ${validTypes.join(', ')}`,
1422
+ );
1423
+ }
1424
+ const agentDest = getAgentDir();
1425
+ const fs = require('fs');
1426
+ if (!fs.existsSync(agentDest)) {
1427
+ return {
1428
+ content: [
1429
+ { type: 'text', text: 'Error: .agent/ directory not found. Run `tk init` first.' },
1430
+ ],
1431
+ };
1432
+ }
1433
+ try {
1434
+ const { _memoryStore } = require('../src/commands/memory.js');
1435
+ const result = _memoryStore(agentDest, memType, content, tags, null);
1436
+ return {
1437
+ content: [
1438
+ {
1439
+ type: 'text',
1440
+ text: `Memory stored: #${result.id} (${memType}, ~${result.token_estimate} tokens)`,
1441
+ },
1442
+ ],
1443
+ };
1444
+ } catch (e) {
1445
+ return { content: [{ type: 'text', text: `Memory store failed: ${e.message}` }] };
1446
+ }
1447
+ }
1448
+
1449
+ if (toolName === 'query_semantic_graph') {
1450
+ const targetPath = req.params?.arguments?.targetPath || process.cwd();
1451
+ try {
1452
+ const result = spawnSync(
1453
+ 'node',
1454
+ [path.join(__dirname, '../scripts/build-graph.js'), targetPath],
1455
+ {
1456
+ encoding: 'utf8',
1457
+ timeout: 10000,
1458
+ },
1459
+ );
1460
+ if (result.error) throw result.error;
1461
+ return { content: [{ type: 'text', text: result.stdout || result.stderr }] };
1462
+ } catch (e) {
1463
+ return { content: [{ type: 'text', text: `Failed to query graph: ${e.message}` }] };
1464
+ }
1465
+ }
1466
+
1467
+ if (toolName === 'align_output') {
1468
+ const text = req.params?.arguments?.text;
1469
+ if (typeof text !== 'string') {
1470
+ throw new RpcError(-32602, 'Missing or invalid required argument: text (string)');
1471
+ }
1472
+ try {
1473
+ const { alignText, validateCodeContent } = require('../src/commands/align.js');
1474
+ const aligned = alignText(text);
1475
+ const warnings = validateCodeContent(aligned);
1476
+
1477
+ let outputText = aligned;
1478
+ if (warnings.length > 0) {
1479
+ outputText += '\n\n⚠️ OCAE Alignment Validator Warnings:\n';
1480
+ for (const warnMsg of warnings) {
1481
+ outputText += `● ${warnMsg}\n`;
1482
+ }
1483
+ }
1484
+ return { content: [{ type: 'text', text: outputText }] };
1485
+ } catch (e) {
1486
+ return { content: [{ type: 'text', text: `Output alignment failed: ${e.message}` }] };
1487
+ }
1488
+ }
1489
+
1490
+ if (toolName === 'verify_contracts') {
1491
+ const file = req.params?.arguments?.file;
1492
+ const content = req.params?.arguments?.content;
1493
+
1494
+ if (!file || typeof file !== 'string' || typeof content !== 'string') {
1495
+ throw new RpcError(
1496
+ -32602,
1497
+ 'Missing or invalid required arguments: file (string), content (string)',
1498
+ );
1499
+ }
1500
+
1501
+ try {
1502
+ const projectRoot = process.cwd();
1503
+ const contractEnginePath = path.join(getAgentDir(), 'scripts', 'contract_engine.js');
1504
+ if (!require('fs').existsSync(contractEnginePath)) {
1505
+ return {
1506
+ content: [
1507
+ { type: 'text', text: 'Error: contract_engine.js not found. Run `tk init` first.' },
1508
+ ],
1509
+ };
1510
+ }
1511
+
1512
+ const contractEngine = require(contractEnginePath);
1513
+ const contracts = contractEngine.loadContracts(projectRoot);
1514
+
1515
+ if (contracts.length === 0) {
1516
+ return {
1517
+ content: [
1518
+ {
1519
+ type: 'text',
1520
+ text: 'No active behavioral contracts found in .tribunal/contracts/.',
1521
+ },
1522
+ ],
1523
+ };
1524
+ }
1525
+
1526
+ const relativePath = path.relative(projectRoot, file).replace(/\\/g, '/');
1527
+ const allViolations = [];
1528
+
1529
+ for (const contract of contracts) {
1530
+ const vList = contractEngine.evaluateContract(contract, relativePath, content);
1531
+ if (vList.length > 0) {
1532
+ allViolations.push(...vList);
1533
+ }
1534
+ }
1535
+
1536
+ if (allViolations.length === 0) {
1537
+ return {
1538
+ content: [
1539
+ {
1540
+ type: 'text',
1541
+ text: '✅ Contract check passed. Zero behavioral violations detected.',
1542
+ },
1543
+ ],
1544
+ };
1545
+ }
1546
+
1547
+ let report = `📜 Contract Verification Results (${allViolations.length} violations):\n`;
1548
+ for (const v of allViolations) {
1549
+ report += `● [${v.severity.toUpperCase()}] ${v.contract}: ${v.message}\n`;
1550
+ if (v.line) report += ` Line ${v.line}: ${v.snippet || ''}\n`;
1551
+ }
1552
+
1553
+ return { content: [{ type: 'text', text: report }] };
1554
+ } catch (e) {
1555
+ return {
1556
+ content: [{ type: 'text', text: `Contract verification failed: ${e.message}` }],
1557
+ };
1558
+ }
1559
+ }
1560
+
1561
+ throw new RpcError(-32601, `Unknown tool: ${toolName}`);
1562
+ };
1563
+
1564
+ try {
1565
+ const result = await withToolTimeout(executeTool, GENERAL_TOOL_TIMEOUT_MS);
1566
+ if (reminder) {
1567
+ result.content.push({ type: 'text', text: '\n\n' + reminder });
1568
+ }
1569
+ return result;
1570
+ } catch (e) {
1571
+ if (e.message === 'TOOL_TIMEOUT') {
1572
+ const errorMsg = `Error: Tool execution timed out after ${GENERAL_TOOL_TIMEOUT_MS}ms`;
1573
+ const result = { content: [{ type: 'text', text: errorMsg }] };
1574
+ if (reminder) result.content.push({ type: 'text', text: '\n\n' + reminder });
1575
+ return result;
1576
+ }
1577
+ throw e;
1578
+ }
1579
+ }
1580
+
1581
+ throw new RpcError(-32601, `Unknown method: ${req.method}`);
1582
+ }
1583
+
1584
+ async function processSingleRequest(req) {
1585
+ try {
1586
+ const result = await handleRequest(req);
1587
+ // If it's a notification, do not send a response
1588
+ if (req.id === undefined || req.id === null) {
1589
+ return null;
1590
+ }
1591
+ return { jsonrpc: '2.0', id: req.id, result };
1592
+ } catch (e) {
1593
+ const code = e && typeof e.code === 'number' ? e.code : -32603;
1594
+ const message = e && e.message ? e.message : 'Internal server error';
1595
+ if (req.id === undefined || req.id === null) {
1596
+ return {
1597
+ jsonrpc: '2.0',
1598
+ id: null,
1599
+ error: { code, message },
1600
+ };
1601
+ }
1602
+ return {
1603
+ jsonrpc: '2.0',
1604
+ id: req.id,
1605
+ error: { code, message },
1606
+ };
1607
+ }
1608
+ }
1609
+
1610
+ rl.on('line', async line => {
1611
+ if (line.length > 1048576) {
1612
+ // 1MB limit
1613
+ const errorRes = {
1614
+ jsonrpc: '2.0',
1615
+ id: null,
1616
+ error: { code: -32700, message: 'Parse error: input line too long (exceeds 1MB limit)' },
1617
+ };
1618
+ console.log(JSON.stringify(errorRes));
1619
+ return;
1620
+ }
1621
+ if (!line.trim()) return;
1622
+
1623
+ let req;
1624
+ try {
1625
+ req = JSON.parse(line);
1626
+ } catch (parseErr) {
1627
+ // Invalid JSON — send a parse error
1628
+ const errorRes = {
1629
+ jsonrpc: '2.0',
1630
+ id: null,
1631
+ error: { code: -32700, message: 'Parse error: ' + parseErr.message },
1632
+ };
1633
+ console.log(JSON.stringify(errorRes));
1634
+ return;
1635
+ }
1636
+
1637
+ if (Array.isArray(req)) {
1638
+ const responses = [];
1639
+ for (const singleReq of req) {
1640
+ const response = await processSingleRequest(singleReq);
1641
+ if (response) {
1642
+ responses.push(response);
1643
+ }
1644
+ }
1645
+ if (responses.length > 0) {
1646
+ console.log(JSON.stringify(responses));
1647
+ }
1648
+ } else {
1649
+ const response = await processSingleRequest(req);
1650
+ if (response) {
1651
+ console.log(JSON.stringify(response));
1652
+ }
1653
+ }
1654
+ });
1655
+
1656
+ if (process.env.NODE_ENV === 'test') {
1657
+ module.exports = {
1658
+ handleRequest,
1659
+ stripBoilerplate,
1660
+ runTribunalAudit,
1661
+ };
1662
+ }