tribunal-kit 9.0.2 → 9.2.3

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 (691) hide show
  1. package/.agent/agents/backend-specialist.md +1 -1
  2. package/.agent/agents/code-archaeologist.md +1 -1
  3. package/.agent/agents/database-architect.md +1 -1
  4. package/.agent/agents/debugger.md +1 -1
  5. package/.agent/agents/devops-engineer.md +1 -1
  6. package/.agent/agents/documentation-writer.md +1 -1
  7. package/.agent/agents/explorer-agent.md +1 -1
  8. package/.agent/agents/game-developer.md +1 -1
  9. package/.agent/agents/minimalist-reviewer.md +1 -1
  10. package/.agent/agents/mobile-developer.md +1 -1
  11. package/.agent/agents/orchestrator.md +44 -2
  12. package/.agent/agents/penetration-tester.md +1 -1
  13. package/.agent/agents/performance-optimizer.md +1 -1
  14. package/.agent/agents/product-manager.md +1 -1
  15. package/.agent/agents/product-owner.md +1 -1
  16. package/.agent/agents/project-planner.md +1 -1
  17. package/.agent/agents/qa-automation-engineer.md +1 -1
  18. package/.agent/agents/seo-specialist.md +1 -1
  19. package/.agent/agents/test-engineer.md +1 -1
  20. package/.agent/config/claude.json +1 -1
  21. package/.agent/config/plugin.json +1 -1
  22. package/.agent/history/architecture-explorer.html +352 -0
  23. package/.agent/history/architecture-graph.yaml +181 -1
  24. package/.agent/history/graph-cache.json +323 -13
  25. package/.agent/history/integrity_manifest.json +3937 -299
  26. package/.agent/history/memory/.memory.idx +50 -50
  27. package/.agent/history/snapshots/.opencode__plugins__tribunal.js.json +12 -0
  28. package/.agent/history/snapshots/.pi__extensions__tribunal.ts.json +12 -0
  29. package/.agent/history/snapshots/bin__adapter-install.js.json +1 -1
  30. package/.agent/history/snapshots/bin__mcp-server.js.json +4 -2
  31. package/.agent/history/snapshots/bin__proxy-server.js.json +1 -1
  32. package/.agent/history/snapshots/bin__spawn-agent.js.json +1 -1
  33. package/.agent/history/snapshots/bin__wrapper.js.json +1 -1
  34. package/.agent/history/snapshots/eslint.config.js.json +1 -1
  35. package/.agent/history/snapshots/hooks__session-start.js.json +11 -0
  36. package/.agent/history/snapshots/scripts__apply-version.js.json +11 -0
  37. package/.agent/history/snapshots/scripts__audit_skill_sdo.js.json +11 -0
  38. package/.agent/history/snapshots/scripts__clean-pycache.js.json +11 -0
  39. package/.agent/history/snapshots/scripts__context_compiler.js.json +17 -0
  40. package/.agent/history/snapshots/scripts__modernize_skills.js.json +11 -0
  41. package/.agent/history/snapshots/scripts__package-cores.js.json +12 -0
  42. package/.agent/history/snapshots/scripts__skill_enhancement_engine.js.json +11 -0
  43. package/.agent/history/snapshots/scripts__sync-skills.js.json +11 -0
  44. package/.agent/history/snapshots/scripts__telemetry_gc.js.json +11 -0
  45. package/.agent/history/snapshots/scripts__validate-payload.js.json +1 -1
  46. package/.agent/history/snapshots/test__integration__browser_cli.test.js.json +12 -0
  47. package/.agent/history/snapshots/test__integration__sync_status.test.js.json +1 -1
  48. package/.agent/history/snapshots/test__unit__ast_context_loader.test.js.json +12 -0
  49. package/.agent/history/snapshots/test__unit__browser_case_bridge.test.js.json +11 -0
  50. package/.agent/history/snapshots/test__unit__browser_discovery.test.js.json +10 -0
  51. package/.agent/history/snapshots/test__unit__browser_idpi.test.js.json +10 -0
  52. package/.agent/history/snapshots/test__unit__browser_sentinel.test.js.json +11 -0
  53. package/.agent/history/snapshots/test__unit__browser_synapse.test.js.json +10 -0
  54. package/.agent/history/snapshots/test__unit__browser_trimmer.test.js.json +10 -0
  55. package/.agent/history/snapshots/test__unit__context_compiler.test.js.json +26 -0
  56. package/.agent/history/snapshots/test__unit__init.test.js.json +1 -1
  57. package/.agent/history/snapshots/test__unit__learn.test.js.json +1 -1
  58. package/.agent/history/snapshots/test__unit__mcp_server.test.js.json +1 -1
  59. package/.agent/history/snapshots/test__unit__platform_download_audit.test.js.json +11 -0
  60. package/.agent/history/snapshots/test__unit__prompt_compiler.test.js.json +10 -0
  61. package/.agent/history/snapshots/test__unit__sdd_integration.test.js.json +12 -0
  62. package/.agent/history/snapshots/test__unit__stress.test.js.json +1 -1
  63. package/.agent/history/snapshots/test__unit__token_budget_broker.test.js.json +10 -0
  64. package/.agent/history/snapshots/test__unit__tui.test.js.json +10 -0
  65. package/.agent/routing_index.json +266 -1531
  66. package/.agent/rules/kernel.md +86 -0
  67. package/.agent/scripts/_utils.js +78 -0
  68. package/.agent/scripts/browser_audit.js +13 -5
  69. package/.agent/scripts/bundle_analyzer.js +7 -3
  70. package/.agent/scripts/context_broker.js +0 -8
  71. package/.agent/scripts/context_compiler.js +1106 -3
  72. package/.agent/scripts/dependency_analyzer.js +16 -16
  73. package/.agent/scripts/guardrail_engine.js +48 -11
  74. package/.agent/scripts/inner_loop_validator.js +1 -1
  75. package/.agent/scripts/memory_engine.js +490 -329
  76. package/.agent/scripts/payload_schemas.js +18 -0
  77. package/.agent/scripts/pipeline_engine.js +29 -105
  78. package/.agent/scripts/schema_validator.js +2 -1
  79. package/.agent/scripts/swarm_dispatcher.js +148 -46
  80. package/.agent/scripts/test_runner.js +1 -2
  81. package/.agent/skill_topic_map.json +71 -22
  82. package/.agent/skills/12-principles-of-animation/SKILL.md +1 -76
  83. package/.agent/skills/60fps-animation/SKILL.md +4 -77
  84. package/.agent/skills/accessible-animation/SKILL.md +9 -86
  85. package/.agent/skills/adapt/SKILL.md +1 -76
  86. package/.agent/skills/advanced-rag-pipelines/SKILL.md +1 -76
  87. package/.agent/skills/agent-organizer/SKILL.md +1 -76
  88. package/.agent/skills/agentic-patterns/SKILL.md +1 -76
  89. package/.agent/skills/agentic-workflows-2026/SKILL.md +1 -75
  90. package/.agent/skills/ai-app-hardening/SKILL.md +1 -75
  91. package/.agent/skills/ai-prompt-injection-defense/SKILL.md +1 -76
  92. package/.agent/skills/animation-on-scroll/SKILL.md +16 -87
  93. package/.agent/skills/animation-systems/SKILL.md +15 -90
  94. package/.agent/skills/antfu-conventions/SKILL.md +0 -75
  95. package/.agent/skills/api-patterns/SKILL.md +1 -76
  96. package/.agent/skills/api-security-auditor/SKILL.md +1 -76
  97. package/.agent/skills/app-builder/SKILL.md +1 -76
  98. package/.agent/skills/appflow-wireframe/SKILL.md +1 -78
  99. package/.agent/skills/apple-design/SKILL.md +1 -76
  100. package/.agent/skills/architecture/SKILL.md +1 -76
  101. package/.agent/skills/audit-and-fix/SKILL.md +41 -77
  102. package/.agent/skills/authentication-best-practices/SKILL.md +1 -76
  103. package/.agent/skills/backend-security-expert/SKILL.md +1 -76
  104. package/.agent/skills/baseline-ui/SKILL.md +1 -76
  105. package/.agent/skills/bash-linux/SKILL.md +1 -76
  106. package/.agent/skills/behavioral-modes/SKILL.md +1 -76
  107. package/.agent/skills/better-colors/SKILL.md +1 -76
  108. package/.agent/skills/better-typography/SKILL.md +1 -75
  109. package/.agent/skills/better-ui/SKILL.md +18 -81
  110. package/.agent/skills/bolder/SKILL.md +1 -76
  111. package/.agent/skills/brainstorming/SKILL.md +1 -75
  112. package/.agent/skills/browser-audit/SKILL.md +15 -83
  113. package/.agent/skills/browser-native-ai/SKILL.md +1 -76
  114. package/.agent/skills/build-primitive/SKILL.md +1 -76
  115. package/.agent/skills/building-native-ui/SKILL.md +1 -76
  116. package/.agent/skills/cicd-pro/SKILL.md +1 -76
  117. package/.agent/skills/clarify/SKILL.md +1 -76
  118. package/.agent/skills/clean-code/SKILL.md +1 -76
  119. package/.agent/skills/cloud-architect/SKILL.md +1 -76
  120. package/.agent/skills/cobejs/SKILL.md +1 -76
  121. package/.agent/skills/code-review-checklist/SKILL.md +1 -76
  122. package/.agent/skills/codebase-design/SKILL.md +1 -76
  123. package/.agent/skills/colorize/SKILL.md +1 -76
  124. package/.agent/skills/compact-landing/SKILL.md +1 -76
  125. package/.agent/skills/company-logos/SKILL.md +1 -76
  126. package/.agent/skills/config-validator/SKILL.md +1 -76
  127. package/.agent/skills/containerization-pro/SKILL.md +1 -76
  128. package/.agent/skills/context-engineering-pro/SKILL.md +1 -75
  129. package/.agent/skills/create-design-md/SKILL.md +1 -76
  130. package/.agent/skills/critique/SKILL.md +1 -76
  131. package/.agent/skills/csharp-developer/SKILL.md +1 -76
  132. package/.agent/skills/data-validation-schemas/SKILL.md +1 -76
  133. package/.agent/skills/database-design/SKILL.md +1 -76
  134. package/.agent/skills/delight/SKILL.md +1 -76
  135. package/.agent/skills/deployment-procedures/SKILL.md +1 -76
  136. package/.agent/skills/design-lab/SKILL.md +0 -75
  137. package/.agent/skills/devops-engineer/SKILL.md +1 -76
  138. package/.agent/skills/devops-incident-responder/SKILL.md +1 -76
  139. package/.agent/skills/diagnosing-bugs/SKILL.md +0 -75
  140. package/.agent/skills/distill/SKILL.md +1 -76
  141. package/.agent/skills/documentation-templates/SKILL.md +1 -76
  142. package/.agent/skills/domain-modeling/SKILL.md +1 -76
  143. package/.agent/skills/duckdb-analytical-sql/SKILL.md +1 -75
  144. package/.agent/skills/edge-ai-mobile/SKILL.md +1 -75
  145. package/.agent/skills/edge-computing/SKILL.md +1 -76
  146. package/.agent/skills/emil-design-eng/SKILL.md +1 -76
  147. package/.agent/skills/error-resilience/SKILL.md +1 -76
  148. package/.agent/skills/expo-router-v4/SKILL.md +1 -75
  149. package/.agent/skills/extract-design-system/SKILL.md +1 -76
  150. package/.agent/skills/fabel-protocol/SKILL.md +1 -76
  151. package/.agent/skills/fixing-accessibility/SKILL.md +1 -76
  152. package/.agent/skills/fixing-metadata/SKILL.md +1 -76
  153. package/.agent/skills/fixing-motion-performance/SKILL.md +1 -76
  154. package/.agent/skills/framer-motion-expert/SKILL.md +1 -76
  155. package/.agent/skills/frontend-design/SKILL.md +1 -76
  156. package/.agent/skills/frontend-security-expert/SKILL.md +1 -76
  157. package/.agent/skills/game-design-expert/SKILL.md +1 -76
  158. package/.agent/skills/game-engineering-expert/SKILL.md +1 -76
  159. package/.agent/skills/generative-ui-expert/SKILL.md +1 -76
  160. package/.agent/skills/geo-fundamentals/SKILL.md +1 -76
  161. package/.agent/skills/git-pro/SKILL.md +1 -76
  162. package/.agent/skills/github-operations/SKILL.md +1 -76
  163. package/.agent/skills/gpt-taste/SKILL.md +1 -76
  164. package/.agent/skills/gsap-core/SKILL.md +1 -76
  165. package/.agent/skills/gsap-frameworks/SKILL.md +1 -76
  166. package/.agent/skills/gsap-performance/SKILL.md +1 -76
  167. package/.agent/skills/gsap-plugins/SKILL.md +1 -76
  168. package/.agent/skills/gsap-react/SKILL.md +1 -76
  169. package/.agent/skills/gsap-scrolltrigger/SKILL.md +1 -76
  170. package/.agent/skills/gsap-timeline/SKILL.md +1 -76
  171. package/.agent/skills/gsap-utils/SKILL.md +1 -76
  172. package/.agent/skills/harden/SKILL.md +1 -76
  173. package/.agent/skills/harness-protocol/SKILL.md +1 -76
  174. package/.agent/skills/i18n-localization/SKILL.md +1 -76
  175. package/.agent/skills/impeccable/SKILL.md +1 -76
  176. package/.agent/skills/improve-codebase-architecture/SKILL.md +1 -76
  177. package/.agent/skills/improve-ui/SKILL.md +1 -76
  178. package/.agent/skills/intelligent-routing/SKILL.md +2 -87
  179. package/.agent/skills/knowledge-graph/SKILL.md +1 -76
  180. package/.agent/skills/landing-page/SKILL.md +1 -76
  181. package/.agent/skills/lint-and-validate/SKILL.md +1 -76
  182. package/.agent/skills/llm-engineering/SKILL.md +1 -76
  183. package/.agent/skills/local-first/SKILL.md +1 -76
  184. package/.agent/skills/local-first-architecture/SKILL.md +1 -76
  185. package/.agent/skills/lottie-animation/SKILL.md +1 -76
  186. package/.agent/skills/marquee-loop/SKILL.md +1 -76
  187. package/.agent/skills/masked-reveal/SKILL.md +1 -76
  188. package/.agent/skills/mcp-builder/SKILL.md +1 -76
  189. package/.agent/skills/micro-interaction/SKILL.md +19 -87
  190. package/.agent/skills/mobile-design/SKILL.md +1 -76
  191. package/.agent/skills/monorepo-management/SKILL.md +1 -76
  192. package/.agent/skills/morphing-icons/SKILL.md +1 -76
  193. package/.agent/skills/motion-engineering/SKILL.md +1 -76
  194. package/.agent/skills/nextjs-react-expert/SKILL.md +1 -76
  195. package/.agent/skills/nodejs-best-practices/SKILL.md +1 -76
  196. package/.agent/skills/observability/SKILL.md +1 -76
  197. package/.agent/skills/opentelemetry-observability/SKILL.md +1 -75
  198. package/.agent/skills/page-transition-animation/SKILL.md +1 -76
  199. package/.agent/skills/parallel-agents/SKILL.md +1 -76
  200. package/.agent/skills/performance-profiling/SKILL.md +1 -76
  201. package/.agent/skills/plan-writing/SKILL.md +1 -76
  202. package/.agent/skills/platform-engineer/SKILL.md +1 -76
  203. package/.agent/skills/platform-engineering-opentofu/SKILL.md +1 -75
  204. package/.agent/skills/playwright-ai-e2e/SKILL.md +1 -75
  205. package/.agent/skills/playwright-best-practices/SKILL.md +1 -76
  206. package/.agent/skills/polish/SKILL.md +1 -76
  207. package/.agent/skills/powershell-windows/SKILL.md +1 -76
  208. package/.agent/skills/pricing-page/SKILL.md +1 -76
  209. package/.agent/skills/product-aware-heuristics/SKILL.md +1 -76
  210. package/.agent/skills/progressive-blur/SKILL.md +1 -76
  211. package/.agent/skills/project-idioms/SKILL.md +1 -76
  212. package/.agent/skills/property-based-testing/SKILL.md +1 -75
  213. package/.agent/skills/python-patterns/SKILL.md +1 -76
  214. package/.agent/skills/python-pro/SKILL.md +1 -76
  215. package/.agent/skills/quieter/SKILL.md +1 -76
  216. package/.agent/skills/react-doctor/SKILL.md +1 -76
  217. package/.agent/skills/react-specialist/SKILL.md +1 -76
  218. package/.agent/skills/readme-builder/SKILL.md +1 -76
  219. package/.agent/skills/realtime-patterns/SKILL.md +1 -76
  220. package/.agent/skills/red-team-tactics/SKILL.md +1 -76
  221. package/.agent/skills/redesign-skill/SKILL.md +1 -76
  222. package/.agent/skills/review-animations/SKILL.md +1 -76
  223. package/.agent/skills/rust-pro/SKILL.md +1 -76
  224. package/.agent/skills/seo-fundamentals/SKILL.md +1 -76
  225. package/.agent/skills/server-management/SKILL.md +1 -76
  226. package/.agent/skills/shadcn-ui-expert/SKILL.md +1 -76
  227. package/.agent/skills/shape/SKILL.md +1 -76
  228. package/.agent/skills/skill-creator/SKILL.md +127 -86
  229. package/.agent/skills/soft-skill/SKILL.md +1 -76
  230. package/.agent/skills/sounds-on-the-web/SKILL.md +1 -76
  231. package/.agent/skills/sql-pro/SKILL.md +1 -76
  232. package/.agent/skills/supabase-postgres-best-practices/SKILL.md +1 -76
  233. package/.agent/skills/svg-animation/SKILL.md +1 -76
  234. package/.agent/skills/swiftui-expert/SKILL.md +1 -76
  235. package/.agent/skills/swiss-design/SKILL.md +1 -76
  236. package/.agent/skills/system-design-pro/SKILL.md +1 -76
  237. package/.agent/skills/systematic-debugging/SKILL.md +2 -76
  238. package/.agent/skills/systematic-debugging/condition-based-waiting.md +14 -9
  239. package/.agent/skills/systematic-debugging/defense-in-depth.md +9 -3
  240. package/.agent/skills/systematic-debugging/root-cause-tracing.md +14 -0
  241. package/.agent/skills/tailwind-patterns/SKILL.md +1 -76
  242. package/.agent/skills/taste-skill/SKILL.md +1 -76
  243. package/.agent/skills/tdd-workflow/SKILL.md +8 -82
  244. package/.agent/skills/test-result-analyzer/SKILL.md +1 -76
  245. package/.agent/skills/testing-patterns/SKILL.md +1 -76
  246. package/.agent/skills/thermo-nuclear-code-quality-review/SKILL.md +1 -76
  247. package/.agent/skills/thinking-protocol/SKILL.md +1 -77
  248. package/.agent/skills/to-spring-or-not-to-spring/SKILL.md +1 -76
  249. package/.agent/skills/transitions-dev/SKILL.md +1 -76
  250. package/.agent/skills/trend-researcher/SKILL.md +1 -76
  251. package/.agent/skills/typescript-advanced/SKILL.md +1 -76
  252. package/.agent/skills/typeset/SKILL.md +1 -76
  253. package/.agent/skills/ui-reasoning-engine/SKILL.md +1 -76
  254. package/.agent/skills/ui-skill-packs/SKILL.md +1 -76
  255. package/.agent/skills/ui-skills-root/SKILL.md +1 -76
  256. package/.agent/skills/ui-ux-pro-max/SKILL.md +1 -76
  257. package/.agent/skills/ui-ux-researcher/SKILL.md +1 -76
  258. package/.agent/skills/vector-search-pgvector/SKILL.md +1 -75
  259. package/.agent/skills/verification-before-completion/SKILL.md +20 -91
  260. package/.agent/skills/vue-expert/SKILL.md +1 -76
  261. package/.agent/skills/vulnerability-scanner/SKILL.md +1 -76
  262. package/.agent/skills/web-accessibility-auditor/SKILL.md +1 -76
  263. package/.agent/skills/web-design-guidelines/SKILL.md +1 -76
  264. package/.agent/skills/web-quality-audit/SKILL.md +1 -76
  265. package/.agent/skills/webapp-testing/SKILL.md +1 -76
  266. package/.agent/skills/webgpu-performance/SKILL.md +1 -76
  267. package/.agent/skills/whimsy-injector/SKILL.md +1 -76
  268. package/.agent/skills/workflow-optimizer/SKILL.md +1 -76
  269. package/.agent/skills/zero-trust-passkeys/SKILL.md +1 -75
  270. package/.agent/templates/DESIGN.md +312 -290
  271. package/.agent/templates/sdd/task-reviewer-prompt.md +2 -2
  272. package/.agent/workflows/audit-live.md +4 -3
  273. package/.agent/workflows/brainstorm.md +1 -0
  274. package/.agent/workflows/context.md +9 -7
  275. package/.agent/workflows/generate.md +1 -1
  276. package/.agent/workflows/minimal.md +3 -2
  277. package/.agent/workflows/orchestrate.md +1 -1
  278. package/.agent/workflows/plan.md +1 -1
  279. package/.agent/workflows/review-ai.md +1 -1
  280. package/.agent/workflows/sdd.md +15 -0
  281. package/.agent/workflows/skill-enhancement-engine.md +17 -21
  282. package/.agent/workflows/super-prompt.md +25 -24
  283. package/.agent/workflows/swarm.md +1 -1
  284. package/.agent/workflows/tribunal-backend.md +1 -1
  285. package/.agent/workflows/tribunal-cicd.md +1 -1
  286. package/.agent/workflows/tribunal-database.md +1 -1
  287. package/.agent/workflows/tribunal-frontend.md +1 -1
  288. package/.agent/workflows/tribunal-full.md +9 -9
  289. package/.agent/workflows/tribunal-mobile.md +1 -1
  290. package/.agent/workflows/tribunal-speed.md +1 -1
  291. package/.agent/workflows/tribunal-ui.md +1 -1
  292. package/.agents/skills/12-principles-of-animation/SKILL.md +1 -76
  293. package/.agents/skills/60fps-animation/SKILL.md +4 -77
  294. package/.agents/skills/accessible-animation/SKILL.md +9 -86
  295. package/.agents/skills/adapt/SKILL.md +1 -76
  296. package/.agents/skills/advanced-rag-pipelines/SKILL.md +1 -76
  297. package/.agents/skills/agent-organizer/SKILL.md +1 -76
  298. package/.agents/skills/agentic-patterns/SKILL.md +1 -76
  299. package/.agents/skills/agentic-workflows-2026/SKILL.md +1 -75
  300. package/.agents/skills/ai-app-hardening/SKILL.md +1 -75
  301. package/.agents/skills/ai-prompt-injection-defense/SKILL.md +1 -76
  302. package/.agents/skills/animation-on-scroll/SKILL.md +16 -87
  303. package/.agents/skills/animation-systems/SKILL.md +15 -90
  304. package/.agents/skills/antfu-conventions/SKILL.md +0 -75
  305. package/.agents/skills/api-patterns/SKILL.md +1 -76
  306. package/.agents/skills/api-security-auditor/SKILL.md +1 -76
  307. package/.agents/skills/app-builder/SKILL.md +1 -76
  308. package/.agents/skills/appflow-wireframe/SKILL.md +1 -78
  309. package/.agents/skills/apple-design/SKILL.md +1 -76
  310. package/.agents/skills/architecture/SKILL.md +1 -76
  311. package/.agents/skills/audit-and-fix/SKILL.md +41 -77
  312. package/.agents/skills/authentication-best-practices/SKILL.md +1 -76
  313. package/.agents/skills/backend-security-expert/SKILL.md +1 -76
  314. package/.agents/skills/baseline-ui/SKILL.md +1 -76
  315. package/.agents/skills/bash-linux/SKILL.md +1 -76
  316. package/.agents/skills/behavioral-modes/SKILL.md +1 -76
  317. package/.agents/skills/better-colors/SKILL.md +1 -76
  318. package/.agents/skills/better-typography/SKILL.md +1 -75
  319. package/.agents/skills/better-ui/SKILL.md +18 -81
  320. package/.agents/skills/bolder/SKILL.md +1 -76
  321. package/.agents/skills/brainstorming/SKILL.md +1 -75
  322. package/.agents/skills/browser-audit/SKILL.md +15 -83
  323. package/.agents/skills/browser-native-ai/SKILL.md +1 -76
  324. package/.agents/skills/build-primitive/SKILL.md +1 -76
  325. package/.agents/skills/building-native-ui/SKILL.md +1 -76
  326. package/.agents/skills/cicd-pro/SKILL.md +1 -76
  327. package/.agents/skills/clarify/SKILL.md +1 -76
  328. package/.agents/skills/clean-code/SKILL.md +1 -76
  329. package/.agents/skills/cloud-architect/SKILL.md +1 -76
  330. package/.agents/skills/cobejs/SKILL.md +1 -76
  331. package/.agents/skills/code-review-checklist/SKILL.md +1 -76
  332. package/.agents/skills/codebase-design/SKILL.md +1 -76
  333. package/.agents/skills/colorize/SKILL.md +1 -76
  334. package/.agents/skills/compact-landing/SKILL.md +1 -76
  335. package/.agents/skills/company-logos/SKILL.md +1 -76
  336. package/.agents/skills/config-validator/SKILL.md +1 -76
  337. package/.agents/skills/containerization-pro/SKILL.md +1 -76
  338. package/.agents/skills/context-engineering-pro/SKILL.md +1 -75
  339. package/.agents/skills/create-design-md/SKILL.md +1 -76
  340. package/.agents/skills/critique/SKILL.md +1 -76
  341. package/.agents/skills/csharp-developer/SKILL.md +1 -76
  342. package/.agents/skills/data-validation-schemas/SKILL.md +1 -76
  343. package/.agents/skills/database-design/SKILL.md +1 -76
  344. package/.agents/skills/delight/SKILL.md +1 -76
  345. package/.agents/skills/deployment-procedures/SKILL.md +1 -76
  346. package/.agents/skills/design-lab/SKILL.md +0 -75
  347. package/.agents/skills/devops-engineer/SKILL.md +1 -76
  348. package/.agents/skills/devops-incident-responder/SKILL.md +1 -76
  349. package/.agents/skills/diagnosing-bugs/SKILL.md +0 -75
  350. package/.agents/skills/distill/SKILL.md +1 -76
  351. package/.agents/skills/documentation-templates/SKILL.md +1 -76
  352. package/.agents/skills/domain-modeling/SKILL.md +1 -76
  353. package/.agents/skills/duckdb-analytical-sql/SKILL.md +1 -75
  354. package/.agents/skills/edge-ai-mobile/SKILL.md +1 -75
  355. package/.agents/skills/edge-computing/SKILL.md +1 -76
  356. package/.agents/skills/emil-design-eng/SKILL.md +1 -76
  357. package/.agents/skills/error-resilience/SKILL.md +1 -76
  358. package/.agents/skills/expo-router-v4/SKILL.md +1 -75
  359. package/.agents/skills/extract-design-system/SKILL.md +1 -76
  360. package/.agents/skills/fabel-protocol/SKILL.md +1 -76
  361. package/.agents/skills/fixing-accessibility/SKILL.md +1 -76
  362. package/.agents/skills/fixing-metadata/SKILL.md +1 -76
  363. package/.agents/skills/fixing-motion-performance/SKILL.md +1 -76
  364. package/.agents/skills/framer-motion-expert/SKILL.md +1 -76
  365. package/.agents/skills/frontend-design/SKILL.md +1 -76
  366. package/.agents/skills/frontend-security-expert/SKILL.md +1 -76
  367. package/.agents/skills/game-design-expert/SKILL.md +1 -76
  368. package/.agents/skills/game-engineering-expert/SKILL.md +1 -76
  369. package/.agents/skills/generative-ui-expert/SKILL.md +1 -76
  370. package/.agents/skills/geo-fundamentals/SKILL.md +1 -76
  371. package/.agents/skills/git-pro/SKILL.md +1 -76
  372. package/.agents/skills/github-operations/SKILL.md +1 -76
  373. package/.agents/skills/gpt-taste/SKILL.md +1 -76
  374. package/.agents/skills/gsap-core/SKILL.md +1 -76
  375. package/.agents/skills/gsap-frameworks/SKILL.md +1 -76
  376. package/.agents/skills/gsap-performance/SKILL.md +1 -76
  377. package/.agents/skills/gsap-plugins/SKILL.md +1 -76
  378. package/.agents/skills/gsap-react/SKILL.md +1 -76
  379. package/.agents/skills/gsap-scrolltrigger/SKILL.md +1 -76
  380. package/.agents/skills/gsap-timeline/SKILL.md +1 -76
  381. package/.agents/skills/gsap-utils/SKILL.md +1 -76
  382. package/.agents/skills/harden/SKILL.md +1 -76
  383. package/.agents/skills/harness-protocol/SKILL.md +1 -76
  384. package/.agents/skills/i18n-localization/SKILL.md +1 -76
  385. package/.agents/skills/impeccable/SKILL.md +1 -76
  386. package/.agents/skills/improve-codebase-architecture/SKILL.md +1 -76
  387. package/.agents/skills/improve-ui/SKILL.md +1 -76
  388. package/.agents/skills/intelligent-routing/SKILL.md +2 -87
  389. package/.agents/skills/knowledge-graph/SKILL.md +1 -76
  390. package/.agents/skills/landing-page/SKILL.md +1 -76
  391. package/.agents/skills/lint-and-validate/SKILL.md +1 -76
  392. package/.agents/skills/llm-engineering/SKILL.md +1 -76
  393. package/.agents/skills/local-first/SKILL.md +1 -76
  394. package/.agents/skills/local-first-architecture/SKILL.md +1 -76
  395. package/.agents/skills/lottie-animation/SKILL.md +1 -76
  396. package/.agents/skills/marquee-loop/SKILL.md +1 -76
  397. package/.agents/skills/masked-reveal/SKILL.md +1 -76
  398. package/.agents/skills/mcp-builder/SKILL.md +1 -76
  399. package/.agents/skills/micro-interaction/SKILL.md +19 -87
  400. package/.agents/skills/mobile-design/SKILL.md +1 -76
  401. package/.agents/skills/monorepo-management/SKILL.md +1 -76
  402. package/.agents/skills/morphing-icons/SKILL.md +1 -76
  403. package/.agents/skills/motion-engineering/SKILL.md +1 -76
  404. package/.agents/skills/nextjs-react-expert/SKILL.md +1 -76
  405. package/.agents/skills/nodejs-best-practices/SKILL.md +1 -76
  406. package/.agents/skills/observability/SKILL.md +1 -76
  407. package/.agents/skills/opentelemetry-observability/SKILL.md +1 -75
  408. package/.agents/skills/page-transition-animation/SKILL.md +1 -76
  409. package/.agents/skills/parallel-agents/SKILL.md +1 -76
  410. package/.agents/skills/performance-profiling/SKILL.md +1 -76
  411. package/.agents/skills/plan-writing/SKILL.md +1 -76
  412. package/.agents/skills/platform-engineer/SKILL.md +1 -76
  413. package/.agents/skills/platform-engineering-opentofu/SKILL.md +1 -75
  414. package/.agents/skills/playwright-ai-e2e/SKILL.md +1 -75
  415. package/.agents/skills/playwright-best-practices/SKILL.md +1 -76
  416. package/.agents/skills/polish/SKILL.md +1 -76
  417. package/.agents/skills/powershell-windows/SKILL.md +1 -76
  418. package/.agents/skills/pricing-page/SKILL.md +1 -76
  419. package/.agents/skills/product-aware-heuristics/SKILL.md +1 -76
  420. package/.agents/skills/progressive-blur/SKILL.md +1 -76
  421. package/.agents/skills/project-idioms/SKILL.md +1 -76
  422. package/.agents/skills/property-based-testing/SKILL.md +1 -75
  423. package/.agents/skills/python-patterns/SKILL.md +1 -76
  424. package/.agents/skills/python-pro/SKILL.md +1 -76
  425. package/.agents/skills/quieter/SKILL.md +1 -76
  426. package/.agents/skills/react-doctor/SKILL.md +1 -76
  427. package/.agents/skills/react-specialist/SKILL.md +1 -76
  428. package/.agents/skills/readme-builder/SKILL.md +1 -76
  429. package/.agents/skills/realtime-patterns/SKILL.md +1 -76
  430. package/.agents/skills/red-team-tactics/SKILL.md +1 -76
  431. package/.agents/skills/redesign-skill/SKILL.md +1 -76
  432. package/.agents/skills/review-animations/SKILL.md +1 -76
  433. package/.agents/skills/rust-pro/SKILL.md +1 -76
  434. package/.agents/skills/seo-fundamentals/SKILL.md +1 -76
  435. package/.agents/skills/server-management/SKILL.md +1 -76
  436. package/.agents/skills/shadcn-ui-expert/SKILL.md +1 -76
  437. package/.agents/skills/shape/SKILL.md +1 -76
  438. package/.agents/skills/skill-creator/SKILL.md +127 -86
  439. package/.agents/skills/soft-skill/SKILL.md +1 -76
  440. package/.agents/skills/sounds-on-the-web/SKILL.md +1 -76
  441. package/.agents/skills/sql-pro/SKILL.md +1 -76
  442. package/.agents/skills/supabase-postgres-best-practices/SKILL.md +1 -76
  443. package/.agents/skills/svg-animation/SKILL.md +1 -76
  444. package/.agents/skills/swiftui-expert/SKILL.md +1 -76
  445. package/.agents/skills/swiss-design/SKILL.md +1 -76
  446. package/.agents/skills/system-design-pro/SKILL.md +1 -76
  447. package/.agents/skills/systematic-debugging/SKILL.md +2 -76
  448. package/.agents/skills/systematic-debugging/condition-based-waiting.md +14 -9
  449. package/.agents/skills/systematic-debugging/defense-in-depth.md +9 -3
  450. package/.agents/skills/systematic-debugging/root-cause-tracing.md +14 -0
  451. package/.agents/skills/tailwind-patterns/SKILL.md +1 -76
  452. package/.agents/skills/taste-skill/SKILL.md +1 -76
  453. package/.agents/skills/tdd-workflow/SKILL.md +8 -82
  454. package/.agents/skills/test-result-analyzer/SKILL.md +1 -76
  455. package/.agents/skills/testing-patterns/SKILL.md +1 -76
  456. package/.agents/skills/thermo-nuclear-code-quality-review/SKILL.md +1 -76
  457. package/.agents/skills/thinking-protocol/SKILL.md +1 -77
  458. package/.agents/skills/to-spring-or-not-to-spring/SKILL.md +1 -76
  459. package/.agents/skills/transitions-dev/SKILL.md +1 -76
  460. package/.agents/skills/trend-researcher/SKILL.md +1 -76
  461. package/.agents/skills/typescript-advanced/SKILL.md +1 -76
  462. package/.agents/skills/typeset/SKILL.md +1 -76
  463. package/.agents/skills/ui-reasoning-engine/SKILL.md +1 -76
  464. package/.agents/skills/ui-skill-packs/SKILL.md +1 -76
  465. package/.agents/skills/ui-skills-root/SKILL.md +1 -76
  466. package/.agents/skills/ui-ux-pro-max/SKILL.md +1 -76
  467. package/.agents/skills/ui-ux-researcher/SKILL.md +1 -76
  468. package/.agents/skills/vector-search-pgvector/SKILL.md +1 -75
  469. package/.agents/skills/verification-before-completion/SKILL.md +20 -91
  470. package/.agents/skills/vue-expert/SKILL.md +1 -76
  471. package/.agents/skills/vulnerability-scanner/SKILL.md +1 -76
  472. package/.agents/skills/web-accessibility-auditor/SKILL.md +1 -76
  473. package/.agents/skills/web-design-guidelines/SKILL.md +1 -76
  474. package/.agents/skills/web-quality-audit/SKILL.md +1 -76
  475. package/.agents/skills/webapp-testing/SKILL.md +1 -76
  476. package/.agents/skills/webgpu-performance/SKILL.md +1 -76
  477. package/.agents/skills/whimsy-injector/SKILL.md +1 -76
  478. package/.agents/skills/workflow-optimizer/SKILL.md +1 -76
  479. package/.agents/skills/zero-trust-passkeys/SKILL.md +1 -75
  480. package/.codex-plugin/plugin.json +1 -5
  481. package/.kimi-plugin/plugin.json +1 -5
  482. package/.opencode/INSTALL.md +1 -0
  483. package/.opencode/plugins/tribunal.js +15 -6
  484. package/.pi/extensions/tribunal.ts +26 -29
  485. package/AGENTS.md +15 -13
  486. package/CLAUDE.md +3 -1
  487. package/README.md +23 -16
  488. package/bin/adapter-install.js +1 -1
  489. package/bin/mcp-server.js +88 -58
  490. package/bin/wrapper.js +22 -2
  491. package/dist/commands/init.js +25 -11
  492. package/dist/tui/banner.js +77 -77
  493. package/gemini-extension.json +1 -1
  494. package/package.json +13 -10
  495. package/plugin.json +1 -1
  496. package/scripts/apply-version.js +2 -2
  497. package/scripts/audit_skill_sdo.js +6 -4
  498. package/scripts/context_compiler.js +256 -83
  499. package/scripts/modernize_skills.js +25 -11
  500. package/scripts/package-cores.js +4 -1
  501. package/scripts/skill_enhancement_engine.js +212 -77
  502. package/scripts/telemetry_gc.js +156 -0
  503. package/scripts/validate-payload.js +1 -6
  504. package/skills/12-principles-of-animation/SKILL.md +1 -76
  505. package/skills/60fps-animation/SKILL.md +4 -77
  506. package/skills/accessible-animation/SKILL.md +9 -86
  507. package/skills/adapt/SKILL.md +1 -76
  508. package/skills/advanced-rag-pipelines/SKILL.md +1 -76
  509. package/skills/agent-organizer/SKILL.md +1 -76
  510. package/skills/agentic-patterns/SKILL.md +1 -76
  511. package/skills/agentic-workflows-2026/SKILL.md +1 -75
  512. package/skills/ai-app-hardening/SKILL.md +1 -75
  513. package/skills/ai-prompt-injection-defense/SKILL.md +1 -76
  514. package/skills/animation-on-scroll/SKILL.md +16 -87
  515. package/skills/animation-systems/SKILL.md +15 -90
  516. package/skills/antfu-conventions/SKILL.md +0 -75
  517. package/skills/api-patterns/SKILL.md +1 -76
  518. package/skills/api-security-auditor/SKILL.md +1 -76
  519. package/skills/app-builder/SKILL.md +1 -76
  520. package/skills/appflow-wireframe/SKILL.md +1 -78
  521. package/skills/apple-design/SKILL.md +1 -76
  522. package/skills/architecture/SKILL.md +1 -76
  523. package/skills/audit-and-fix/SKILL.md +41 -77
  524. package/skills/authentication-best-practices/SKILL.md +1 -76
  525. package/skills/backend-security-expert/SKILL.md +1 -76
  526. package/skills/baseline-ui/SKILL.md +1 -76
  527. package/skills/bash-linux/SKILL.md +1 -76
  528. package/skills/behavioral-modes/SKILL.md +1 -76
  529. package/skills/better-colors/SKILL.md +1 -76
  530. package/skills/better-typography/SKILL.md +1 -75
  531. package/skills/better-ui/SKILL.md +18 -81
  532. package/skills/bolder/SKILL.md +1 -76
  533. package/skills/brainstorming/SKILL.md +1 -75
  534. package/skills/browser-audit/SKILL.md +15 -83
  535. package/skills/browser-native-ai/SKILL.md +1 -76
  536. package/skills/build-primitive/SKILL.md +1 -76
  537. package/skills/building-native-ui/SKILL.md +1 -76
  538. package/skills/cicd-pro/SKILL.md +1 -76
  539. package/skills/clarify/SKILL.md +1 -76
  540. package/skills/clean-code/SKILL.md +1 -76
  541. package/skills/cloud-architect/SKILL.md +1 -76
  542. package/skills/cobejs/SKILL.md +1 -76
  543. package/skills/code-review-checklist/SKILL.md +1 -76
  544. package/skills/codebase-design/SKILL.md +1 -76
  545. package/skills/colorize/SKILL.md +1 -76
  546. package/skills/compact-landing/SKILL.md +1 -76
  547. package/skills/company-logos/SKILL.md +1 -76
  548. package/skills/config-validator/SKILL.md +1 -76
  549. package/skills/containerization-pro/SKILL.md +1 -76
  550. package/skills/context-engineering-pro/SKILL.md +1 -75
  551. package/skills/create-design-md/SKILL.md +1 -76
  552. package/skills/critique/SKILL.md +1 -76
  553. package/skills/csharp-developer/SKILL.md +1 -76
  554. package/skills/data-validation-schemas/SKILL.md +1 -76
  555. package/skills/database-design/SKILL.md +1 -76
  556. package/skills/delight/SKILL.md +1 -76
  557. package/skills/deployment-procedures/SKILL.md +1 -76
  558. package/skills/design-lab/SKILL.md +0 -75
  559. package/skills/devops-engineer/SKILL.md +1 -76
  560. package/skills/devops-incident-responder/SKILL.md +1 -76
  561. package/skills/diagnosing-bugs/SKILL.md +0 -75
  562. package/skills/distill/SKILL.md +1 -76
  563. package/skills/documentation-templates/SKILL.md +1 -76
  564. package/skills/domain-modeling/SKILL.md +1 -76
  565. package/skills/duckdb-analytical-sql/SKILL.md +1 -75
  566. package/skills/edge-ai-mobile/SKILL.md +1 -75
  567. package/skills/edge-computing/SKILL.md +1 -76
  568. package/skills/emil-design-eng/SKILL.md +1 -76
  569. package/skills/error-resilience/SKILL.md +1 -76
  570. package/skills/expo-router-v4/SKILL.md +1 -75
  571. package/skills/extract-design-system/SKILL.md +1 -76
  572. package/skills/fabel-protocol/SKILL.md +1 -76
  573. package/skills/fixing-accessibility/SKILL.md +1 -76
  574. package/skills/fixing-metadata/SKILL.md +1 -76
  575. package/skills/fixing-motion-performance/SKILL.md +1 -76
  576. package/skills/framer-motion-expert/SKILL.md +1 -76
  577. package/skills/frontend-design/SKILL.md +1 -76
  578. package/skills/frontend-security-expert/SKILL.md +1 -76
  579. package/skills/game-design-expert/SKILL.md +1 -76
  580. package/skills/game-engineering-expert/SKILL.md +1 -76
  581. package/skills/generative-ui-expert/SKILL.md +1 -76
  582. package/skills/geo-fundamentals/SKILL.md +1 -76
  583. package/skills/git-pro/SKILL.md +1 -76
  584. package/skills/github-operations/SKILL.md +1 -76
  585. package/skills/gpt-taste/SKILL.md +1 -76
  586. package/skills/gsap-core/SKILL.md +1 -76
  587. package/skills/gsap-frameworks/SKILL.md +1 -76
  588. package/skills/gsap-performance/SKILL.md +1 -76
  589. package/skills/gsap-plugins/SKILL.md +1 -76
  590. package/skills/gsap-react/SKILL.md +1 -76
  591. package/skills/gsap-scrolltrigger/SKILL.md +1 -76
  592. package/skills/gsap-timeline/SKILL.md +1 -76
  593. package/skills/gsap-utils/SKILL.md +1 -76
  594. package/skills/harden/SKILL.md +1 -76
  595. package/skills/harness-protocol/SKILL.md +1 -76
  596. package/skills/i18n-localization/SKILL.md +1 -76
  597. package/skills/impeccable/SKILL.md +1 -76
  598. package/skills/improve-codebase-architecture/SKILL.md +1 -76
  599. package/skills/improve-ui/SKILL.md +1 -76
  600. package/skills/intelligent-routing/SKILL.md +2 -87
  601. package/skills/knowledge-graph/SKILL.md +1 -76
  602. package/skills/landing-page/SKILL.md +1 -76
  603. package/skills/lint-and-validate/SKILL.md +1 -76
  604. package/skills/llm-engineering/SKILL.md +1 -76
  605. package/skills/local-first/SKILL.md +1 -76
  606. package/skills/local-first-architecture/SKILL.md +1 -76
  607. package/skills/lottie-animation/SKILL.md +1 -76
  608. package/skills/marquee-loop/SKILL.md +1 -76
  609. package/skills/masked-reveal/SKILL.md +1 -76
  610. package/skills/mcp-builder/SKILL.md +1 -76
  611. package/skills/micro-interaction/SKILL.md +19 -87
  612. package/skills/mobile-design/SKILL.md +1 -76
  613. package/skills/monorepo-management/SKILL.md +1 -76
  614. package/skills/morphing-icons/SKILL.md +1 -76
  615. package/skills/motion-engineering/SKILL.md +1 -76
  616. package/skills/nextjs-react-expert/SKILL.md +1 -76
  617. package/skills/nodejs-best-practices/SKILL.md +1 -76
  618. package/skills/observability/SKILL.md +1 -76
  619. package/skills/opentelemetry-observability/SKILL.md +1 -75
  620. package/skills/page-transition-animation/SKILL.md +1 -76
  621. package/skills/parallel-agents/SKILL.md +1 -76
  622. package/skills/performance-profiling/SKILL.md +1 -76
  623. package/skills/plan-writing/SKILL.md +1 -76
  624. package/skills/platform-engineer/SKILL.md +1 -76
  625. package/skills/platform-engineering-opentofu/SKILL.md +1 -75
  626. package/skills/playwright-ai-e2e/SKILL.md +1 -75
  627. package/skills/playwright-best-practices/SKILL.md +1 -76
  628. package/skills/polish/SKILL.md +1 -76
  629. package/skills/powershell-windows/SKILL.md +1 -76
  630. package/skills/pricing-page/SKILL.md +1 -76
  631. package/skills/product-aware-heuristics/SKILL.md +1 -76
  632. package/skills/progressive-blur/SKILL.md +1 -76
  633. package/skills/project-idioms/SKILL.md +1 -76
  634. package/skills/property-based-testing/SKILL.md +1 -75
  635. package/skills/python-patterns/SKILL.md +1 -76
  636. package/skills/python-pro/SKILL.md +1 -76
  637. package/skills/quieter/SKILL.md +1 -76
  638. package/skills/react-doctor/SKILL.md +1 -76
  639. package/skills/react-specialist/SKILL.md +1 -76
  640. package/skills/readme-builder/SKILL.md +1 -76
  641. package/skills/realtime-patterns/SKILL.md +1 -76
  642. package/skills/red-team-tactics/SKILL.md +1 -76
  643. package/skills/redesign-skill/SKILL.md +1 -76
  644. package/skills/review-animations/SKILL.md +1 -76
  645. package/skills/rust-pro/SKILL.md +1 -76
  646. package/skills/seo-fundamentals/SKILL.md +1 -76
  647. package/skills/server-management/SKILL.md +1 -76
  648. package/skills/shadcn-ui-expert/SKILL.md +1 -76
  649. package/skills/shape/SKILL.md +1 -76
  650. package/skills/skill-creator/SKILL.md +127 -86
  651. package/skills/soft-skill/SKILL.md +1 -76
  652. package/skills/sounds-on-the-web/SKILL.md +1 -76
  653. package/skills/sql-pro/SKILL.md +1 -76
  654. package/skills/supabase-postgres-best-practices/SKILL.md +1 -76
  655. package/skills/svg-animation/SKILL.md +1 -76
  656. package/skills/swiftui-expert/SKILL.md +1 -76
  657. package/skills/swiss-design/SKILL.md +1 -76
  658. package/skills/system-design-pro/SKILL.md +1 -76
  659. package/skills/systematic-debugging/SKILL.md +2 -76
  660. package/skills/systematic-debugging/condition-based-waiting.md +14 -9
  661. package/skills/systematic-debugging/defense-in-depth.md +9 -3
  662. package/skills/systematic-debugging/root-cause-tracing.md +14 -0
  663. package/skills/tailwind-patterns/SKILL.md +1 -76
  664. package/skills/taste-skill/SKILL.md +1 -76
  665. package/skills/tdd-workflow/SKILL.md +8 -82
  666. package/skills/test-result-analyzer/SKILL.md +1 -76
  667. package/skills/testing-patterns/SKILL.md +1 -76
  668. package/skills/thermo-nuclear-code-quality-review/SKILL.md +1 -76
  669. package/skills/thinking-protocol/SKILL.md +1 -77
  670. package/skills/to-spring-or-not-to-spring/SKILL.md +1 -76
  671. package/skills/transitions-dev/SKILL.md +1 -76
  672. package/skills/trend-researcher/SKILL.md +1 -76
  673. package/skills/typescript-advanced/SKILL.md +1 -76
  674. package/skills/typeset/SKILL.md +1 -76
  675. package/skills/ui-reasoning-engine/SKILL.md +1 -76
  676. package/skills/ui-skill-packs/SKILL.md +1 -76
  677. package/skills/ui-skills-root/SKILL.md +1 -76
  678. package/skills/ui-ux-pro-max/SKILL.md +1 -76
  679. package/skills/ui-ux-researcher/SKILL.md +1 -76
  680. package/skills/vector-search-pgvector/SKILL.md +1 -75
  681. package/skills/verification-before-completion/SKILL.md +20 -91
  682. package/skills/vue-expert/SKILL.md +1 -76
  683. package/skills/vulnerability-scanner/SKILL.md +1 -76
  684. package/skills/web-accessibility-auditor/SKILL.md +1 -76
  685. package/skills/web-design-guidelines/SKILL.md +1 -76
  686. package/skills/web-quality-audit/SKILL.md +1 -76
  687. package/skills/webapp-testing/SKILL.md +1 -76
  688. package/skills/webgpu-performance/SKILL.md +1 -76
  689. package/skills/whimsy-injector/SKILL.md +1 -76
  690. package/skills/workflow-optimizer/SKILL.md +1 -76
  691. package/skills/zero-trust-passkeys/SKILL.md +1 -75
@@ -1,19 +1,21 @@
1
1
  {
2
2
  "file": "bin/mcp-server.js",
3
3
  "riskScore": "Medium",
4
- "blastRadius": 3,
4
+ "blastRadius": 4,
5
5
  "imports": {
6
6
  "path": [],
7
7
  "child_process": [],
8
8
  "readline": [],
9
9
  "fs": [],
10
+ "../dist/browser": [],
10
11
  "../dist/commands/memory.js": [],
11
12
  "../dist/commands/align.js": []
12
13
  },
13
14
  "dependents": [
14
15
  "test/unit/audit_release.test.js",
16
+ "test/unit/context_compiler.test.js",
15
17
  "test/unit/mcp_server.test.js",
16
18
  "test/unit/production_readiness_evidence.test.js"
17
19
  ],
18
- "content": "#!/usr/bin/env node\n\n/**\n * Tribunal-Kit MCP Server (Performance-Optimized)\n *\n * This file exposes tribunal-kit tools via the Model Context Protocol (MCP)\n * over standard I/O, allowing AI clients (Cursor, Windsurf, Claude) to natively\n * invoke tribunal checks.\n *\n * In-process tools load reusable modules directly. Commands that depend on a\n * standalone CLI process remain isolated deliberately.\n *\n * Protocol: MCP 2024-11-05 over JSON-RPC 2.0 / stdio\n */\n\nconst path = require('path');\nconst { spawnSync } = require('child_process');\n\nconst PKG = require(path.resolve(__dirname, '../package.json'));\n\n// Timeout for intentionally isolated child processes (30 seconds).\nconst SPAWN_TIMEOUT_MS = 30000;\nconst GENERAL_TOOL_TIMEOUT_MS = 60000;\n\n// --- DSH Guard: Cooperative Timeout ---\nasync function withToolTimeout(fn, timeoutMs) {\n let timeoutId;\n const timeoutPromise = new Promise((_, reject) => {\n timeoutId = setTimeout(() => {\n reject(new Error('TOOL_TIMEOUT'));\n }, timeoutMs);\n });\n\n try {\n const result = await Promise.race([Promise.resolve().then(fn), timeoutPromise]);\n return result;\n } finally {\n clearTimeout(timeoutId);\n }\n}\n\n// --- DSH Guard: Loop Detection ---\nclass ToolRepeatGuard {\n constructor() {\n this.history = new Map();\n }\n\n observe(toolName, argsObj) {\n const canonicalize = obj => {\n if (Array.isArray(obj)) return obj.map(canonicalize);\n if (obj !== null && typeof obj === 'object') {\n const sorted = {};\n for (const key of Object.keys(obj).sort()) {\n sorted[key] = canonicalize(obj[key]);\n }\n return sorted;\n }\n return obj;\n };\n\n const canonicalArgs = JSON.stringify(canonicalize(argsObj) || {});\n const key = `${toolName}::${canonicalArgs}`;\n\n const currentCount = (this.history.get(key) || 0) + 1;\n this.history.clear();\n this.history.set(key, currentCount);\n\n if (currentCount === 3) {\n 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.';\n }\n if (currentCount >= 5) {\n 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.`;\n }\n return null;\n }\n}\nconst repeatGuard = new ToolRepeatGuard();\n\nclass RpcError extends Error {\n constructor(code, message) {\n super(message);\n this.code = code;\n this.name = 'RpcError';\n }\n}\n\n// Minimal JSON-RPC 2.0 over stdio\nconst readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false,\n});\n\n/**\n * Run the workspace integrity audit without invoking the CLI schema validator.\n * The MCP audit is about Tribunal assets, while `tk validate` validates one\n * explicitly supplied payload and schema.\n */\nfunction runTribunalAudit() {\n const fs = require('fs');\n const projectRoot = process.cwd();\n const manifestScript = path.join(projectRoot, '.agent', 'scripts', 'integrity_manifest.js');\n\n if (!fs.existsSync(manifestScript)) {\n return 'Error: .agent/scripts/integrity_manifest.js was not found. Run `tk init` first.';\n }\n\n try {\n const { generateManifest } = require(manifestScript);\n const manifest = generateManifest(projectRoot);\n if (manifest.error) return `Error: ${manifest.error}`;\n\n const { integrity } = manifest;\n const lines = [\n 'Tribunal audit complete.',\n `Agents: ${manifest.agents.total} (${manifest.agents.reviewer_count} reviewers)`,\n `Skills: ${manifest.skills.total}`,\n `Scripts: ${manifest.scripts.total}`,\n `Workflows: ${manifest.workflows.total}`,\n `References: ${integrity.total_references}; phantom references: ${integrity.phantom_references}`,\n `Count claims: ${integrity.total_claims}; invalid claims: ${integrity.invalid_claims}`,\n ];\n\n if (integrity.phantom_references > 0 || integrity.invalid_claims > 0) {\n lines.push(\n 'Audit found integrity issues; run `tk guardrail --scan` for remediation details.',\n );\n } else {\n lines.push('All discovered references and global asset-count claims are valid.');\n }\n return lines.join('\\n');\n } catch (error) {\n return `Audit failed: ${error.message}`;\n }\n}\n\n/**\n * Search case law in an isolated process because its CLI owns persistent state.\n */\nfunction searchCaseLaw(query) {\n const caseLawScript = path.resolve(__dirname, '../.agent/scripts/case_law_manager.js');\n // case_law_manager is a standalone stateful CLI, so retain its process boundary.\n const result = spawnSync(process.execPath, [caseLawScript, 'search-cases', '--query', query], {\n encoding: 'utf8',\n timeout: SPAWN_TIMEOUT_MS,\n });\n if (result.error) {\n if (result.error.code === 'ETIMEDOUT')\n return 'Error: Case law search timed out (exceeded 30s limit)';\n return `Error executing case law search: ${result.error.message}`;\n }\n return result.stdout || result.stderr || 'No results';\n}\n\nfunction stripBoilerplate(text) {\n if (!text) return text;\n let minified = text.replace(\n /AI coding assistants often fall into specific bad habits[\\s\\S]*$/g,\n '',\n );\n minified = minified.replace(/## 🤖 LLM-Specific Traps[\\s\\S]*$/g, '');\n minified = minified.replace(/## 🏛️ Tribunal Integration[\\s\\S]*$/g, '');\n minified = minified.replace(/## Pre-Flight Checklist[\\s\\S]*$/g, '');\n return minified.trim();\n}\n\nfunction getAgentDir() {\n const fs = require('fs');\n const local = path.join(process.cwd(), '.agent');\n if (fs.existsSync(local)) return local;\n return path.resolve(__dirname, '../.agent');\n}\n\nasync function handleRequest(req) {\n const fs = require('fs');\n if (req.method === 'notifications/initialized' || req.method === 'notifications/cancelled') {\n return null;\n }\n if (req.method === 'ping') {\n return {};\n }\n\n // MCP spec: method names follow path-style convention\n if (req.method === 'initialize') {\n return {\n protocolVersion: '2025-03-26',\n capabilities: {\n tools: {},\n resources: { subscribe: false, listChanged: false },\n prompts: { listChanged: false },\n },\n serverInfo: {\n name: 'tribunal-kit-mcp',\n version: PKG.version,\n },\n };\n }\n\n if (req.method === 'resources/list') {\n const agentDir = getAgentDir();\n const resources = [];\n\n // Agents\n const agentsDir = path.join(agentDir, 'agents');\n if (fs.existsSync(agentsDir)) {\n const files = fs.readdirSync(agentsDir).filter(f => f.endsWith('.md'));\n for (const f of files) {\n const name = path.basename(f, '.md');\n resources.push({\n uri: `tribunal://agent/${name}`,\n name: `Agent: ${name}`,\n description: `Tribunal Specialist Agent rule file for ${name}`,\n mimeType: 'text/markdown',\n });\n }\n }\n\n // Skills\n const skillsDir = path.join(agentDir, 'skills');\n if (fs.existsSync(skillsDir)) {\n const dirs = fs.readdirSync(skillsDir, { withFileTypes: true });\n for (const d of dirs) {\n if (d.isDirectory()) {\n const skillFile = path.join(skillsDir, d.name, 'SKILL.md');\n if (fs.existsSync(skillFile)) {\n resources.push({\n uri: `tribunal://skill/${d.name}`,\n name: `Skill: ${d.name}`,\n description: `Tribunal Skill instruction file for ${d.name}`,\n mimeType: 'text/markdown',\n });\n }\n }\n }\n }\n\n // Workflows\n const workflowsDir = path.join(agentDir, 'workflows');\n if (fs.existsSync(workflowsDir)) {\n const files = fs.readdirSync(workflowsDir).filter(f => f.endsWith('.md'));\n for (const f of files) {\n const name = path.basename(f, '.md');\n resources.push({\n uri: `tribunal://workflow/${name}`,\n name: `Workflow: ${name}`,\n description: `Tribunal Workflow guide for ${name}`,\n mimeType: 'text/markdown',\n });\n }\n }\n\n return { resources };\n }\n\n if (req.method === 'resources/read') {\n const uri = req.params && req.params.uri;\n if (!uri) throw new Error('Missing uri parameter');\n const agentDir = getAgentDir();\n let filePath = null;\n\n if (uri.startsWith('tribunal://agent/')) {\n const name = uri.replace('tribunal://agent/', '');\n filePath = path.join(agentDir, 'agents', `${name}.md`);\n } else if (uri.startsWith('tribunal://skill/')) {\n const name = uri.replace('tribunal://skill/', '');\n filePath = path.join(agentDir, 'skills', name, 'SKILL.md');\n } else if (uri.startsWith('tribunal://workflow/')) {\n const name = uri.replace('tribunal://workflow/', '');\n filePath = path.join(agentDir, 'workflows', `${name}.md`);\n }\n\n if (!filePath || !fs.existsSync(filePath)) {\n throw new Error(`Resource not found: ${uri}`);\n }\n\n const text = fs.readFileSync(filePath, 'utf8');\n return {\n contents: [\n {\n uri,\n mimeType: 'text/markdown',\n text,\n },\n ],\n };\n }\n\n if (req.method === 'prompts/list') {\n const agentDir = getAgentDir();\n const prompts = [];\n const workflowsDir = path.join(agentDir, 'workflows');\n\n if (fs.existsSync(workflowsDir)) {\n const files = fs.readdirSync(workflowsDir).filter(f => f.endsWith('.md'));\n for (const f of files) {\n const name = path.basename(f, '.md');\n prompts.push({\n name,\n description: `Execute tribunal workflow /${name}`,\n arguments: [\n {\n name: 'task',\n description: 'The task or target file to execute the workflow against',\n required: false,\n },\n ],\n });\n }\n }\n\n return { prompts };\n }\n\n if (req.method === 'prompts/get') {\n const name = req.params && req.params.name;\n const task = (req.params && req.params.arguments && req.params.arguments.task) || '';\n if (!name) throw new Error('Missing prompt name parameter');\n\n const agentDir = getAgentDir();\n const workflowPath = path.join(agentDir, 'workflows', `${name}.md`);\n if (!fs.existsSync(workflowPath)) {\n throw new Error(`Prompt workflow not found: ${name}`);\n }\n\n const content = fs.readFileSync(workflowPath, 'utf8');\n const promptText = task ? `${content}\\n\\nTarget Task/File: ${task}` : content;\n\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: promptText,\n },\n },\n ],\n };\n }\n\n if (req.method === 'tools/list') {\n return {\n tools: [\n {\n name: 'run_tribunal_audit',\n description: 'Runs a full anti-hallucination audit across the workspace.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: 'sync_ide_bridges',\n description: 'Synchronize IDE bridge files with the current GEMINI.md rules.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: 'search_case_law',\n description:\n 'Search historical code rejections and legal precedent. Use this before writing code to avoid past mistakes.',\n inputSchema: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: \"Search query (e.g. 'useEffect state')\",\n },\n },\n required: ['query'],\n additionalProperties: false,\n },\n },\n {\n name: 'list_tribunal_agents',\n description: 'List all available Tribunal Kit agents.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: 'get_tribunal_agent',\n description: 'Get the full markdown rules for a specific Tribunal agent.',\n inputSchema: {\n type: 'object',\n properties: {\n name: { type: 'string', description: \"The agent name (e.g. 'frontend-specialist')\" },\n },\n required: ['name'],\n additionalProperties: false,\n },\n },\n {\n name: 'list_tribunal_skills',\n description: 'List all available Tribunal Kit skills.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: 'get_tribunal_skill',\n description: 'Get the full markdown instructions for a specific Tribunal skill.',\n inputSchema: {\n type: 'object',\n properties: {\n name: { type: 'string', description: \"The skill name (e.g. 'react-specialist')\" },\n },\n required: ['name'],\n additionalProperties: false,\n },\n },\n {\n name: 'recall_memory',\n description:\n '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.',\n inputSchema: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: \"Search query (e.g. 'database', 'auth', 'deploy')\",\n },\n budget: {\n type: 'number',\n description:\n 'Maximum token budget for recall (default: 2000). Only the top-ranked memories that fit within this budget are returned.',\n },\n },\n required: ['query'],\n additionalProperties: false,\n },\n },\n {\n name: 'store_memory',\n description:\n '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).',\n inputSchema: {\n type: 'object',\n properties: {\n type: {\n type: 'string',\n enum: ['semantic', 'procedural', 'episodic', 'working'],\n description:\n 'Memory type: semantic (facts), procedural (recipes), episodic (events), working (scratch)',\n },\n content: {\n type: 'string',\n description: 'The memory content to store',\n },\n tags: {\n type: 'array',\n items: { type: 'string' },\n description: 'Searchable tags for this memory',\n },\n },\n required: ['type', 'content'],\n additionalProperties: false,\n },\n },\n {\n name: 'get_sparse_context',\n description:\n '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.',\n inputSchema: {\n type: 'object',\n properties: {\n task: {\n type: 'string',\n description: \"The user task description (e.g. 'JWT auth API')\",\n },\n files: {\n type: 'array',\n items: { type: 'string' },\n description: \"List of files being touched (e.g. ['src/auth.js'])\",\n },\n model: {\n type: 'string',\n enum: ['large', 'small'],\n description:\n 'Model tier: large (default, includes key rules of supplementary skills) or small (essential skills only)',\n },\n },\n required: ['task'],\n additionalProperties: false,\n },\n },\n {\n name: 'align_output',\n description:\n '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).',\n inputSchema: {\n type: 'object',\n properties: {\n text: {\n type: 'string',\n description: 'The raw output text generated by the model to be aligned.',\n },\n },\n required: ['text'],\n additionalProperties: false,\n },\n },\n {\n name: 'verify_contracts',\n description:\n 'Verify proposed code changes against project behavioral contracts. Use BEFORE writing code to ensure compliance with team conventions.',\n inputSchema: {\n type: 'object',\n properties: {\n file: {\n type: 'string',\n description: \"Relative or absolute file path to verify (e.g. 'src/api/user.ts')\",\n },\n content: {\n type: 'string',\n description: 'Proposed file content to verify against loaded contracts',\n },\n },\n required: ['file', 'content'],\n additionalProperties: false,\n },\n },\n {\n name: 'query_semantic_graph',\n description:\n 'Query the Ahead-of-Time (AOT) Semantic Context Graph to quickly resolve function signatures, dependencies, and file structures without inflating context windows.',\n inputSchema: {\n type: 'object',\n properties: {\n targetPath: {\n type: 'string',\n description: 'The directory to query (defaults to current workspace).',\n },\n },\n additionalProperties: false,\n },\n },\n {\n name: 'exit_plan_mode',\n description:\n 'Present your finished plan for human reviewed designing your approach. Execution will suspend until the user approves or requests changes.',\n inputSchema: {\n type: 'object',\n properties: {\n plan_content: {\n type: 'string',\n description: 'The markdown content of your proposed plan.',\n },\n },\n required: ['plan_content'],\n additionalProperties: false,\n },\n },\n ],\n };\n }\n\n if (req.method === 'tools/call') {\n const toolName = req.params && req.params.name;\n const argsObj = req.params && req.params.arguments;\n if (!toolName) {\n throw new RpcError(-32602, 'Missing required parameter: params.name');\n }\n\n const reminder = repeatGuard.observe(toolName, argsObj);\n\n const executeTool = async () => {\n if (toolName === 'exit_plan_mode') {\n const planContent = req.params?.arguments?.plan_content;\n if (typeof planContent !== 'string') {\n throw new RpcError(-32602, 'Missing or invalid required argument: plan_content (string)');\n }\n // The wrapper CLI can intercept this, but for the LLM context, we explicitly tell it to wait.\n return {\n content: [\n {\n type: 'text',\n 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.',\n },\n ],\n };\n }\n\n if (toolName === 'run_tribunal_audit') {\n const text = runTribunalAudit();\n return { content: [{ type: 'text', text }] };\n }\n\n if (toolName === 'sync_ide_bridges') {\n const fs = require('fs');\n const cwd = process.cwd();\n const agentDest = path.join(cwd, '.agent');\n if (!fs.existsSync(agentDest)) {\n return {\n content: [\n {\n type: 'text',\n text: 'Error: .agent/ directory not found. Run `tk init` first.',\n },\n ],\n };\n }\n try {\n const { generateIDEBridges } = require(\n path.resolve(__dirname, '../dist/commands/init.js'),\n );\n // generateIDEBridges is async\n await generateIDEBridges(cwd, agentDest, true);\n return {\n content: [\n {\n type: 'text',\n text: 'Sync complete',\n },\n ],\n };\n } catch (e) {\n return {\n content: [\n {\n type: 'text',\n text: `Sync failed: ${e.message}`,\n },\n ],\n };\n }\n }\n\n if (toolName === 'search_case_law') {\n const query = req.params && req.params.arguments && req.params.arguments.query;\n if (!query || typeof query !== 'string') {\n throw new RpcError(-32602, 'Missing or invalid required argument: query (string)');\n }\n const text = searchCaseLaw(query);\n return { content: [{ type: 'text', text }] };\n }\n\n if (toolName === 'list_tribunal_agents') {\n const fs = require('fs');\n const agentDir = path.join(getAgentDir(), 'agents');\n if (!fs.existsSync(agentDir))\n return {\n content: [{ type: 'text', text: 'No agents found or .agent directory missing.' }],\n };\n const agents = fs\n .readdirSync(agentDir)\n .filter(f => f.endsWith('.md'))\n .map(f => f.replace('.md', ''));\n return { content: [{ type: 'text', text: 'Available Agents:\\n- ' + agents.join('\\n- ') }] };\n }\n\n if (toolName === 'get_tribunal_agent') {\n const fs = require('fs');\n const name = req.params?.arguments?.name;\n if (!name || typeof name !== 'string')\n throw new RpcError(-32602, 'Missing or invalid argument: name (string)');\n const sanitizedName = path.basename(name);\n const agentsDir = path.resolve(getAgentDir(), 'agents');\n const agentPath = path.resolve(agentsDir, `${sanitizedName}.md`);\n // Path containment: ensure resolved path stays within agents directory\n if (!agentPath.startsWith(agentsDir))\n throw new RpcError(-32602, 'Invalid agent name: path traversal detected');\n if (!fs.existsSync(agentPath))\n return { content: [{ type: 'text', text: `Agent '${sanitizedName}' not found.` }] };\n const text = fs.readFileSync(agentPath, 'utf8');\n return { content: [{ type: 'text', text: stripBoilerplate(text) }] };\n }\n\n if (toolName === 'list_tribunal_skills') {\n const fs = require('fs');\n const skillsDir = path.join(getAgentDir(), 'skills');\n if (!fs.existsSync(skillsDir))\n return {\n content: [{ type: 'text', text: 'No skills found or .agent directory missing.' }],\n };\n const skills = fs\n .readdirSync(skillsDir, { withFileTypes: true })\n .filter(d => d.isDirectory())\n .map(d => d.name);\n return { content: [{ type: 'text', text: 'Available Skills:\\n- ' + skills.join('\\n- ') }] };\n }\n\n if (toolName === 'get_tribunal_skill') {\n const fs = require('fs');\n const name = req.params?.arguments?.name;\n if (!name || typeof name !== 'string')\n throw new RpcError(-32602, 'Missing or invalid argument: name (string)');\n const sanitizedName = path.basename(name);\n const skillsDir = path.resolve(getAgentDir(), 'skills');\n const skillPath = path.resolve(skillsDir, sanitizedName, 'SKILL.md');\n // Path containment: ensure resolved path stays within skills directory\n if (!skillPath.startsWith(skillsDir))\n throw new RpcError(-32602, 'Invalid skill name: path traversal detected');\n if (!fs.existsSync(skillPath))\n return { content: [{ type: 'text', text: `Skill '${sanitizedName}' not found.` }] };\n const text = fs.readFileSync(skillPath, 'utf8');\n return { content: [{ type: 'text', text: stripBoilerplate(text) }] };\n }\n\n if (toolName === 'get_sparse_context') {\n const task = req.params?.arguments?.task;\n const files = req.params?.arguments?.files || [];\n const model = req.params?.arguments?.model || 'large';\n\n if (!task) throw new RpcError(-32602, 'Missing required argument: task');\n\n const agentDest = getAgentDir();\n const fs = require('fs');\n if (!fs.existsSync(agentDest)) {\n return {\n content: [\n { type: 'text', text: 'Error: .agent/ directory not found. Run `tk init` first.' },\n ],\n };\n }\n\n try {\n const brokerScript = path.join(agentDest, 'scripts', 'context_broker.js');\n const { broker } = require(brokerScript);\n const brokerResult = broker(task, files, model, agentDest);\n return { content: [{ type: 'text', text: stripBoilerplate(brokerResult.promptText) }] };\n } catch (e) {\n return {\n content: [{ type: 'text', text: `Failed to retrieve sparse context: ${e.message}` }],\n };\n }\n }\n\n if (toolName === 'recall_memory') {\n const query = req.params?.arguments?.query;\n if (!query || typeof query !== 'string') {\n throw new RpcError(-32602, 'Missing or invalid required argument: query (string)');\n }\n const budget = req.params?.arguments?.budget || 2000;\n const agentDest = getAgentDir();\n const fs = require('fs');\n if (!fs.existsSync(agentDest)) {\n return {\n content: [\n { type: 'text', text: 'Error: .agent/ directory not found. Run `tk init` first.' },\n ],\n };\n }\n try {\n const { _memoryRecall } = require('../dist/commands/memory.js');\n const { results, tokens_used } = _memoryRecall(agentDest, query, budget);\n if (results.length === 0) {\n return { content: [{ type: 'text', text: `No memories match query: \"${query}\"` }] };\n }\n let text = `## Memory Recall (${results.length} results, ~${tokens_used}/${budget} tokens)\\n\\n`;\n for (const entry of results) {\n text += `- **[${entry.memory_type.toUpperCase()}]** #${entry.id}: ${entry.content}`;\n if (entry.tags.length > 0) text += ` _(${entry.tags.join(', ')})_`;\n text += `\\n`;\n }\n return { content: [{ type: 'text', text }] };\n } catch (e) {\n return { content: [{ type: 'text', text: `Memory recall failed: ${e.message}` }] };\n }\n }\n\n if (toolName === 'store_memory') {\n const memType = req.params?.arguments?.type;\n const content = req.params?.arguments?.content;\n const tags = req.params?.arguments?.tags || [];\n if (!memType || !content) {\n throw new RpcError(-32602, 'Missing required arguments: type (string), content (string)');\n }\n const validTypes = ['semantic', 'procedural', 'episodic', 'working'];\n if (!validTypes.includes(memType)) {\n throw new RpcError(\n -32602,\n `Invalid memory type: \"${memType}\". Must be one of: ${validTypes.join(', ')}`,\n );\n }\n const agentDest = getAgentDir();\n const fs = require('fs');\n if (!fs.existsSync(agentDest)) {\n return {\n content: [\n { type: 'text', text: 'Error: .agent/ directory not found. Run `tk init` first.' },\n ],\n };\n }\n try {\n const { _memoryStore } = require('../dist/commands/memory.js');\n const result = _memoryStore(agentDest, memType, content, tags, null);\n return {\n content: [\n {\n type: 'text',\n text: `Memory stored: #${result.id} (${memType}, ~${result.token_estimate} tokens)`,\n },\n ],\n };\n } catch (e) {\n return { content: [{ type: 'text', text: `Memory store failed: ${e.message}` }] };\n }\n }\n\n if (toolName === 'query_semantic_graph') {\n const targetPath = req.params?.arguments?.targetPath || process.cwd();\n try {\n const result = spawnSync(\n 'node',\n [path.join(__dirname, '../scripts/build-graph.js'), targetPath],\n {\n encoding: 'utf8',\n timeout: 10000,\n },\n );\n if (result.error) throw result.error;\n return { content: [{ type: 'text', text: result.stdout || result.stderr }] };\n } catch (e) {\n return { content: [{ type: 'text', text: `Failed to query graph: ${e.message}` }] };\n }\n }\n\n if (toolName === 'align_output') {\n const text = req.params?.arguments?.text;\n if (typeof text !== 'string') {\n throw new RpcError(-32602, 'Missing or invalid required argument: text (string)');\n }\n try {\n const { alignText, validateCodeContent } = require('../dist/commands/align.js');\n const aligned = alignText(text);\n const warnings = validateCodeContent(aligned);\n\n let outputText = aligned;\n if (warnings.length > 0) {\n outputText += '\\n\\n⚠️ OCAE Alignment Validator Warnings:\\n';\n for (const warnMsg of warnings) {\n outputText += `● ${warnMsg}\\n`;\n }\n }\n return { content: [{ type: 'text', text: outputText }] };\n } catch (e) {\n return { content: [{ type: 'text', text: `Output alignment failed: ${e.message}` }] };\n }\n }\n\n if (toolName === 'verify_contracts') {\n const file = req.params?.arguments?.file;\n const content = req.params?.arguments?.content;\n\n if (!file || typeof file !== 'string' || typeof content !== 'string') {\n throw new RpcError(\n -32602,\n 'Missing or invalid required arguments: file (string), content (string)',\n );\n }\n\n try {\n const projectRoot = process.cwd();\n const contractEnginePath = path.join(getAgentDir(), 'scripts', 'contract_engine.js');\n if (!require('fs').existsSync(contractEnginePath)) {\n return {\n content: [\n { type: 'text', text: 'Error: contract_engine.js not found. Run `tk init` first.' },\n ],\n };\n }\n\n const contractEngine = require(contractEnginePath);\n const contracts = contractEngine.loadContracts(projectRoot);\n\n if (contracts.length === 0) {\n return {\n content: [\n {\n type: 'text',\n text: 'No active behavioral contracts found in .tribunal/contracts/.',\n },\n ],\n };\n }\n\n const relativePath = path.relative(projectRoot, file).replace(/\\\\/g, '/');\n const allViolations = [];\n\n for (const contract of contracts) {\n const vList = contractEngine.evaluateContract(contract, relativePath, content);\n if (vList.length > 0) {\n allViolations.push(...vList);\n }\n }\n\n if (allViolations.length === 0) {\n return {\n content: [\n {\n type: 'text',\n text: '✅ Contract check passed. Zero behavioral violations detected.',\n },\n ],\n };\n }\n\n let report = `📜 Contract Verification Results (${allViolations.length} violations):\\n`;\n for (const v of allViolations) {\n report += `● [${v.severity.toUpperCase()}] ${v.contract}: ${v.message}\\n`;\n if (v.line) report += ` Line ${v.line}: ${v.snippet || ''}\\n`;\n }\n\n return { content: [{ type: 'text', text: report }] };\n } catch (e) {\n return {\n content: [{ type: 'text', text: `Contract verification failed: ${e.message}` }],\n };\n }\n }\n\n throw new RpcError(-32601, `Unknown tool: ${toolName}`);\n };\n\n try {\n const result = await withToolTimeout(executeTool, GENERAL_TOOL_TIMEOUT_MS);\n if (reminder) {\n result.content.push({ type: 'text', text: '\\n\\n' + reminder });\n }\n return result;\n } catch (e) {\n if (e.message === 'TOOL_TIMEOUT') {\n const errorMsg = `Error: Tool execution timed out after ${GENERAL_TOOL_TIMEOUT_MS}ms`;\n const result = { content: [{ type: 'text', text: errorMsg }] };\n if (reminder) result.content.push({ type: 'text', text: '\\n\\n' + reminder });\n return result;\n }\n throw e;\n }\n }\n\n throw new RpcError(-32601, `Unknown method: ${req.method}`);\n}\n\nasync function processSingleRequest(req) {\n try {\n const result = await handleRequest(req);\n // If it's a notification, do not send a response\n if (req.id === undefined || req.id === null) {\n return null;\n }\n return { jsonrpc: '2.0', id: req.id, result };\n } catch (e) {\n const code = e && typeof e.code === 'number' ? e.code : -32603;\n const message = e && e.message ? e.message : 'Internal server error';\n if (req.id === undefined || req.id === null) {\n return {\n jsonrpc: '2.0',\n id: null,\n error: { code, message },\n };\n }\n return {\n jsonrpc: '2.0',\n id: req.id,\n error: { code, message },\n };\n }\n}\n\nrl.on('line', async line => {\n if (line.length > 1048576) {\n // 1MB limit\n const errorRes = {\n jsonrpc: '2.0',\n id: null,\n error: { code: -32700, message: 'Parse error: input line too long (exceeds 1MB limit)' },\n };\n console.log(JSON.stringify(errorRes));\n return;\n }\n if (!line.trim()) return;\n\n let req;\n try {\n req = JSON.parse(line);\n } catch (parseErr) {\n // Invalid JSON — send a parse error\n const errorRes = {\n jsonrpc: '2.0',\n id: null,\n error: { code: -32700, message: 'Parse error: ' + parseErr.message },\n };\n console.log(JSON.stringify(errorRes));\n return;\n }\n\n if (Array.isArray(req)) {\n const responses = [];\n for (const singleReq of req) {\n const response = await processSingleRequest(singleReq);\n if (response) {\n responses.push(response);\n }\n }\n if (responses.length > 0) {\n console.log(JSON.stringify(responses));\n }\n } else {\n const response = await processSingleRequest(req);\n if (response) {\n console.log(JSON.stringify(response));\n }\n }\n});\n\nif (process.env.NODE_ENV === 'test') {\n module.exports = {\n handleRequest,\n stripBoilerplate,\n runTribunalAudit,\n };\n}\n"
20
+ "content": "#!/usr/bin/env node\n\n/**\n * Tribunal-Kit MCP Server (Performance-Optimized)\n *\n * This file exposes tribunal-kit tools via the Model Context Protocol (MCP)\n * over standard I/O, allowing AI clients (Cursor, Windsurf, Claude) to natively\n * invoke tribunal checks.\n *\n * In-process tools load reusable modules directly. Commands that depend on a\n * standalone CLI process remain isolated deliberately.\n *\n * Protocol: MCP 2024-11-05 over JSON-RPC 2.0 / stdio\n */\n\nconst path = require('path');\nconst { spawnSync } = require('child_process');\n\nconst PKG = require(path.resolve(__dirname, '../package.json'));\n\n// Timeout for intentionally isolated child processes (30 seconds).\nconst SPAWN_TIMEOUT_MS = 30000;\nconst GENERAL_TOOL_TIMEOUT_MS = 60000;\n\n// --- DSH Guard: Cooperative Timeout ---\nasync function withToolTimeout(fn, timeoutMs) {\n let timeoutId;\n const timeoutPromise = new Promise((_, reject) => {\n timeoutId = setTimeout(() => {\n reject(new Error('TOOL_TIMEOUT'));\n }, timeoutMs);\n });\n\n try {\n const result = await Promise.race([Promise.resolve().then(fn), timeoutPromise]);\n return result;\n } finally {\n clearTimeout(timeoutId);\n }\n}\n\n// --- DSH Guard: Loop Detection ---\nclass ToolRepeatGuard {\n constructor() {\n this.history = new Map();\n }\n\n observe(toolName, argsObj) {\n const canonicalize = obj => {\n if (Array.isArray(obj)) return obj.map(canonicalize);\n if (obj !== null && typeof obj === 'object') {\n const sorted = {};\n for (const key of Object.keys(obj).sort()) {\n sorted[key] = canonicalize(obj[key]);\n }\n return sorted;\n }\n if (typeof obj === 'string') {\n return obj.trim().toLowerCase().replace(/\\s+/g, ' ');\n }\n return obj;\n };\n\n const canonicalArgs = JSON.stringify(canonicalize(argsObj) || {});\n const key = `${toolName}::${canonicalArgs}`;\n\n const currentCount = (this.history.get(key) || 0) + 1;\n this.history.clear();\n this.history.set(key, currentCount);\n\n if (currentCount === 3) {\n 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.';\n }\n if (currentCount >= 5) {\n 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.`;\n }\n return null;\n }\n}\nconst repeatGuard = new ToolRepeatGuard();\n\nclass RpcError extends Error {\n constructor(code, message) {\n super(message);\n this.code = code;\n this.name = 'RpcError';\n }\n}\n\n// Minimal JSON-RPC 2.0 over stdio\nconst readline = require('readline');\n\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false,\n});\n\n/**\n * Run the workspace integrity audit without invoking the CLI schema validator.\n * The MCP audit is about Tribunal assets, while `tk validate` validates one\n * explicitly supplied payload and schema.\n */\nfunction runTribunalAudit() {\n const fs = require('fs');\n const projectRoot = process.cwd();\n const manifestScript = path.join(projectRoot, '.agent', 'scripts', 'integrity_manifest.js');\n\n if (!fs.existsSync(manifestScript)) {\n return 'Error: .agent/scripts/integrity_manifest.js was not found. Run `tk init` first.';\n }\n\n try {\n const { generateManifest } = require(manifestScript);\n const manifest = generateManifest(projectRoot);\n if (manifest.error) return `Error: ${manifest.error}`;\n\n const { integrity } = manifest;\n const lines = [\n 'Tribunal audit complete.',\n `Agents: ${manifest.agents.total} (${manifest.agents.reviewer_count} reviewers)`,\n `Skills: ${manifest.skills.total}`,\n `Scripts: ${manifest.scripts.total}`,\n `Workflows: ${manifest.workflows.total}`,\n `References: ${integrity.total_references}; phantom references: ${integrity.phantom_references}`,\n `Count claims: ${integrity.total_claims}; invalid claims: ${integrity.invalid_claims}`,\n ];\n\n if (integrity.phantom_references > 0 || integrity.invalid_claims > 0) {\n lines.push(\n 'Audit found integrity issues; run `tk guardrail --scan` for remediation details.',\n );\n } else {\n lines.push('All discovered references and global asset-count claims are valid.');\n }\n return lines.join('\\n');\n } catch (error) {\n return `Audit failed: ${error.message}`;\n }\n}\n\n/**\n * Search case law in an isolated process because its CLI owns persistent state.\n */\nfunction searchCaseLaw(query) {\n const caseLawScript = path.resolve(__dirname, '../.agent/scripts/case_law_manager.js');\n // case_law_manager is a standalone stateful CLI, so retain its process boundary.\n const result = spawnSync(process.execPath, [caseLawScript, 'search-cases', '--query', query], {\n encoding: 'utf8',\n timeout: SPAWN_TIMEOUT_MS,\n });\n if (result.error) {\n if (result.error.code === 'ETIMEDOUT')\n return 'Error: Case law search timed out (exceeded 30s limit)';\n return `Error executing case law search: ${result.error.message}`;\n }\n return result.stdout || result.stderr || 'No results';\n}\n\nfunction stripBoilerplate(text) {\n if (!text) return text;\n let minified = text.replace(\n /AI coding assistants often fall into specific bad habits[\\s\\S]*$/g,\n '',\n );\n minified = minified.replace(/## 🤖 LLM-Specific Traps[\\s\\S]*$/g, '');\n minified = minified.replace(/## 🏛️ Tribunal Integration[\\s\\S]*$/g, '');\n minified = minified.replace(/## Pre-Flight Checklist[\\s\\S]*$/g, '');\n return minified.trim();\n}\n\nfunction getAgentDir() {\n const fs = require('fs');\n const local = path.join(process.cwd(), '.agent');\n if (fs.existsSync(local)) return local;\n return path.resolve(__dirname, '../.agent');\n}\n\nasync function handleRequest(req) {\n const fs = require('fs');\n if (req.method === 'notifications/initialized' || req.method === 'notifications/cancelled') {\n return null;\n }\n if (req.method === 'ping') {\n return {};\n }\n\n // MCP spec: method names follow path-style convention\n if (req.method === 'initialize') {\n return {\n protocolVersion: '2025-03-26',\n capabilities: {\n tools: {},\n resources: { subscribe: false, listChanged: false },\n prompts: { listChanged: false },\n },\n serverInfo: {\n name: 'tribunal-kit-mcp',\n version: PKG.version,\n },\n };\n }\n\n if (req.method === 'resources/list') {\n const agentDir = getAgentDir();\n const resources = [];\n\n // Agents\n const agentsDir = path.join(agentDir, 'agents');\n if (fs.existsSync(agentsDir)) {\n const files = fs.readdirSync(agentsDir).filter(f => f.endsWith('.md'));\n for (const f of files) {\n const name = path.basename(f, '.md');\n resources.push({\n uri: `tribunal://agent/${name}`,\n name: `Agent: ${name}`,\n description: `Tribunal Specialist Agent rule file for ${name}`,\n mimeType: 'text/markdown',\n });\n }\n }\n\n // Skills\n const skillsDir = path.join(agentDir, 'skills');\n if (fs.existsSync(skillsDir)) {\n const dirs = fs.readdirSync(skillsDir, { withFileTypes: true });\n for (const d of dirs) {\n if (d.isDirectory()) {\n const skillFile = path.join(skillsDir, d.name, 'SKILL.md');\n if (fs.existsSync(skillFile)) {\n resources.push({\n uri: `tribunal://skill/${d.name}`,\n name: `Skill: ${d.name}`,\n description: `Tribunal Skill instruction file for ${d.name}`,\n mimeType: 'text/markdown',\n });\n }\n }\n }\n }\n\n // Workflows\n const workflowsDir = path.join(agentDir, 'workflows');\n if (fs.existsSync(workflowsDir)) {\n const files = fs.readdirSync(workflowsDir).filter(f => f.endsWith('.md'));\n for (const f of files) {\n const name = path.basename(f, '.md');\n resources.push({\n uri: `tribunal://workflow/${name}`,\n name: `Workflow: ${name}`,\n description: `Tribunal Workflow guide for ${name}`,\n mimeType: 'text/markdown',\n });\n }\n }\n\n return { resources };\n }\n\n if (req.method === 'resources/read') {\n const uri = req.params && req.params.uri;\n if (!uri) throw new Error('Missing uri parameter');\n const agentDir = getAgentDir();\n let filePath = null;\n\n if (uri.startsWith('tribunal://agent/')) {\n const name = uri.replace('tribunal://agent/', '');\n filePath = path.join(agentDir, 'agents', `${name}.md`);\n } else if (uri.startsWith('tribunal://skill/')) {\n const name = uri.replace('tribunal://skill/', '');\n filePath = path.join(agentDir, 'skills', name, 'SKILL.md');\n } else if (uri.startsWith('tribunal://workflow/')) {\n const name = uri.replace('tribunal://workflow/', '');\n filePath = path.join(agentDir, 'workflows', `${name}.md`);\n }\n\n if (!filePath || !fs.existsSync(filePath)) {\n throw new Error(`Resource not found: ${uri}`);\n }\n\n const text = fs.readFileSync(filePath, 'utf8');\n return {\n contents: [\n {\n uri,\n mimeType: 'text/markdown',\n text,\n },\n ],\n };\n }\n\n if (req.method === 'prompts/list') {\n const agentDir = getAgentDir();\n const prompts = [];\n const workflowsDir = path.join(agentDir, 'workflows');\n\n if (fs.existsSync(workflowsDir)) {\n const files = fs.readdirSync(workflowsDir).filter(f => f.endsWith('.md'));\n for (const f of files) {\n const name = path.basename(f, '.md');\n prompts.push({\n name,\n description: `Execute tribunal workflow /${name}`,\n arguments: [\n {\n name: 'task',\n description: 'The task or target file to execute the workflow against',\n required: false,\n },\n ],\n });\n }\n }\n\n return { prompts };\n }\n\n if (req.method === 'prompts/get') {\n const name = req.params && req.params.name;\n const task = (req.params && req.params.arguments && req.params.arguments.task) || '';\n if (!name) throw new Error('Missing prompt name parameter');\n\n const agentDir = getAgentDir();\n const workflowPath = path.join(agentDir, 'workflows', `${name}.md`);\n if (!fs.existsSync(workflowPath)) {\n throw new Error(`Prompt workflow not found: ${name}`);\n }\n\n const content = fs.readFileSync(workflowPath, 'utf8');\n const promptText = task ? `${content}\\n\\nTarget Task/File: ${task}` : content;\n\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: promptText,\n },\n },\n ],\n };\n }\n\n if (req.method === 'tools/list') {\n return {\n tools: [\n {\n name: 'run_tribunal_audit',\n description: 'Runs a full anti-hallucination audit across the workspace.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: 'sync_ide_bridges',\n description: 'Synchronize IDE bridge files with the current GEMINI.md rules.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: 'search_case_law',\n description:\n 'Search historical code rejections and legal precedent. Use this before writing code to avoid past mistakes.',\n inputSchema: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: \"Search query (e.g. 'useEffect state')\",\n },\n },\n required: ['query'],\n additionalProperties: false,\n },\n },\n {\n name: 'list_tribunal_agents',\n description: 'List all available Tribunal Kit agents.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: 'get_tribunal_agent',\n description: 'Get the full markdown rules for a specific Tribunal agent.',\n inputSchema: {\n type: 'object',\n properties: {\n name: { type: 'string', description: \"The agent name (e.g. 'frontend-specialist')\" },\n },\n required: ['name'],\n additionalProperties: false,\n },\n },\n {\n name: 'list_tribunal_skills',\n description: 'List all available Tribunal Kit skills.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: 'get_tribunal_skill',\n description: 'Get the full markdown instructions for a specific Tribunal skill.',\n inputSchema: {\n type: 'object',\n properties: {\n name: { type: 'string', description: \"The skill name (e.g. 'react-specialist')\" },\n },\n required: ['name'],\n additionalProperties: false,\n },\n },\n {\n name: 'recall_memory',\n description:\n '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.',\n inputSchema: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: \"Search query (e.g. 'database', 'auth', 'deploy')\",\n },\n budget: {\n type: 'number',\n description:\n 'Maximum token budget for recall (default: 2000). Only the top-ranked memories that fit within this budget are returned.',\n },\n },\n required: ['query'],\n additionalProperties: false,\n },\n },\n {\n name: 'store_memory',\n description:\n '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).',\n inputSchema: {\n type: 'object',\n properties: {\n type: {\n type: 'string',\n enum: ['semantic', 'procedural', 'episodic', 'working'],\n description:\n 'Memory type: semantic (facts), procedural (recipes), episodic (events), working (scratch)',\n },\n content: {\n type: 'string',\n description: 'The memory content to store',\n },\n tags: {\n type: 'array',\n items: { type: 'string' },\n description: 'Searchable tags for this memory',\n },\n },\n required: ['type', 'content'],\n additionalProperties: false,\n },\n },\n {\n name: 'get_sparse_context',\n description:\n '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.',\n inputSchema: {\n type: 'object',\n properties: {\n task: {\n type: 'string',\n description: \"The user task description (e.g. 'JWT auth API')\",\n },\n files: {\n type: 'array',\n items: { type: 'string' },\n description: \"List of files being touched (e.g. ['src/auth.js'])\",\n },\n model: {\n type: 'string',\n enum: ['large', 'small'],\n description:\n 'Model tier: large (default, includes key rules of supplementary skills) or small (essential skills only)',\n },\n },\n required: ['task'],\n additionalProperties: false,\n },\n },\n {\n name: 'align_output',\n description:\n '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).',\n inputSchema: {\n type: 'object',\n properties: {\n text: {\n type: 'string',\n description: 'The raw output text generated by the model to be aligned.',\n },\n },\n required: ['text'],\n additionalProperties: false,\n },\n },\n {\n name: 'verify_contracts',\n description:\n 'Verify proposed code changes against project behavioral contracts. Use BEFORE writing code to ensure compliance with team conventions.',\n inputSchema: {\n type: 'object',\n properties: {\n file: {\n type: 'string',\n description: \"Relative or absolute file path to verify (e.g. 'src/api/user.ts')\",\n },\n content: {\n type: 'string',\n description: 'Proposed file content to verify against loaded contracts',\n },\n },\n required: ['file', 'content'],\n additionalProperties: false,\n },\n },\n {\n name: 'query_semantic_graph',\n description:\n 'Query the Ahead-of-Time (AOT) Semantic Context Graph to quickly resolve function signatures, dependencies, and file structures without inflating context windows.',\n inputSchema: {\n type: 'object',\n properties: {\n targetPath: {\n type: 'string',\n description: 'The directory to query (defaults to current workspace).',\n },\n },\n additionalProperties: false,\n },\n },\n {\n name: 'exit_plan_mode',\n description:\n 'Present your finished plan for human reviewed designing your approach. Execution will suspend until the user approves or requests changes.',\n inputSchema: {\n type: 'object',\n properties: {\n plan_content: {\n type: 'string',\n description: 'The markdown content of your proposed plan.',\n },\n },\n required: ['plan_content'],\n additionalProperties: false,\n },\n },\n {\n name: 'tk_browser_navigate',\n description:\n '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.',\n inputSchema: {\n type: 'object',\n properties: {\n url: {\n type: 'string',\n description:\n 'The target URL to inspect (e.g. http://localhost:3000 or https://example.com)',\n },\n },\n required: ['url'],\n additionalProperties: false,\n },\n },\n {\n name: 'tk_browser_audit',\n description:\n '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.',\n inputSchema: {\n type: 'object',\n properties: {\n url: {\n type: 'string',\n description: 'The target URL to audit (e.g. http://localhost:3000)',\n },\n },\n required: ['url'],\n additionalProperties: false,\n },\n },\n {\n name: 'tk_browser_compare',\n description:\n '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.',\n inputSchema: {\n type: 'object',\n properties: {\n url1: {\n type: 'string',\n description: 'Baseline or staging URL (e.g. http://localhost:3000)',\n },\n url2: {\n type: 'string',\n description: 'Production or target URL to compare against',\n },\n maxDiffPercent: {\n type: 'number',\n description:\n 'Maximum allowable difference percentage before failing (default: 1.0)',\n },\n },\n required: ['url1', 'url2'],\n additionalProperties: false,\n },\n },\n {\n name: 'tk_browser_screenshot',\n description: 'Captures a viewport screenshot of a target URL as base64 PNG data.',\n inputSchema: {\n type: 'object',\n properties: {\n url: {\n type: 'string',\n description: 'The URL to screenshot',\n },\n },\n required: ['url'],\n additionalProperties: false,\n },\n },\n {\n name: 'tk_deconstruct_component',\n description:\n 'Reverse-engineers a live web element into a production React TSX component with Tailwind CSS classes by inspecting computed CSSOM (geometry, typography, elevation, transitions).',\n inputSchema: {\n type: 'object',\n properties: {\n url: {\n type: 'string',\n description: 'The URL hosting the target element',\n },\n selector: {\n type: 'string',\n description:\n 'CSS selector matching the element (e.g. button.primary or #pricing-card)',\n },\n name: {\n type: 'string',\n description: 'Optional PascalCase component name (e.g. PricingCard)',\n },\n },\n required: ['url', 'selector'],\n additionalProperties: false,\n },\n },\n {\n name: 'tk_heal_runtime_errors',\n description:\n '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.',\n inputSchema: {\n type: 'object',\n properties: {\n url: {\n type: 'string',\n description: 'The dev server or web page URL (e.g. http://localhost:3000)',\n },\n verify: {\n type: 'boolean',\n description:\n 'If true, verifies whether previously reported runtime errors have cleared',\n },\n },\n required: ['url'],\n additionalProperties: false,\n },\n },\n {\n name: 'tk_codify_browser_audit',\n description:\n 'Audits a target URL and automatically codifies detected WCAG accessibility failures, missing security headers, and console errors into binding Case Law precedents.',\n inputSchema: {\n type: 'object',\n properties: {\n url: {\n type: 'string',\n description: 'The URL to audit and codify',\n },\n },\n required: ['url'],\n additionalProperties: false,\n },\n },\n {\n name: 'tribunal_get_context',\n description:\n \"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.\",\n inputSchema: {\n type: 'object',\n properties: {\n target: {\n type: 'string',\n description: 'File path, folder path, or primary file to analyze.',\n },\n compareWith: {\n type: 'string',\n description: 'Optional secondary file for multi-file interface bridge analysis.',\n },\n write: {\n type: 'boolean',\n description:\n 'Whether to write the generated dossier to docs/context/ and update INDEX.md (default: true).',\n },\n check: {\n type: 'boolean',\n description: 'Run vault-wide semantic drift check instead of analyzing a target.',\n },\n },\n additionalProperties: false,\n },\n },\n ],\n };\n }\n\n if (req.method === 'tools/call') {\n const toolName = req.params && req.params.name;\n const argsObj = req.params && req.params.arguments;\n if (!toolName) {\n throw new RpcError(-32602, 'Missing required parameter: params.name');\n }\n\n const reminder = repeatGuard.observe(toolName, argsObj);\n\n const executeTool = async () => {\n if (toolName === 'tribunal_get_context') {\n const target = req.params?.arguments?.target;\n const compareWith = req.params?.arguments?.compareWith;\n const write = req.params?.arguments?.write !== false;\n const check = req.params?.arguments?.check;\n\n try {\n const workspaceRoot = process.cwd();\n \n if (check) {\n const { spawn } = require('child_process');\n const result = await new Promise((resolve, reject) => {\n const child = spawn(process.execPath, [path.join(__dirname, 'wrapper.js'), 'guardrail', '--scan'], { cwd: workspaceRoot, encoding: 'utf8' });\n let out = '';\n child.stdout.on('data', d => out += d);\n child.stderr.on('data', d => out += d);\n child.on('close', code => resolve(out));\n child.on('error', reject);\n });\n return {\n content: [\n {\n type: 'text',\n text: result,\n },\n ],\n };\n }\n\n if (!target) {\n throw new RpcError(\n -32602,\n 'Missing required argument: target (file or directory path)',\n );\n }\n\n // We use wrapper.js context to route it to the Rust AST binary via the child process\n // This prevents blocking the MCP server event loop.\n const { spawn } = require('child_process');\n const args = [path.join(__dirname, 'wrapper.js'), 'context', target];\n if (compareWith) {\n args.push('--compareWith');\n args.push(compareWith);\n }\n if (write) {\n args.push('--write');\n }\n\n const result = await new Promise((resolve, reject) => {\n const child = spawn(process.execPath, args, { cwd: workspaceRoot, encoding: 'utf8' });\n let out = '';\n child.stdout.on('data', d => out += d);\n child.stderr.on('data', d => out += d);\n child.on('close', code => {\n resolve(out);\n });\n child.on('error', reject);\n });\n \n return {\n content: [{ type: 'text', text: result }],\n };\n } catch (e) {\n return {\n content: [{ type: 'text', text: `Context Compiler Error: ${e.message}` }],\n isError: true,\n };\n }\n }\n\n if (toolName === 'exit_plan_mode') {\n const planContent = req.params?.arguments?.plan_content;\n if (typeof planContent !== 'string') {\n throw new RpcError(-32602, 'Missing or invalid required argument: plan_content (string)');\n }\n // The wrapper CLI can intercept this, but for the LLM context, we explicitly tell it to wait.\n return {\n content: [\n {\n type: 'text',\n 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.',\n },\n ],\n };\n }\n\n if (toolName === 'tk_browser_navigate') {\n const url = req.params?.arguments?.url;\n if (!url || typeof url !== 'string') {\n throw new RpcError(-32602, 'Missing required argument: url (string)');\n }\n try {\n const { browse } = require('../dist/browser');\n const result = await browse(url);\n return {\n content: [\n {\n type: 'text',\n text: result.sandboxed,\n },\n ],\n };\n } catch (e) {\n return {\n content: [{ type: 'text', text: `Browser navigation error: ${e.message}` }],\n isError: true,\n };\n }\n }\n\n if (toolName === 'tk_browser_audit') {\n const url = req.params?.arguments?.url;\n if (!url || typeof url !== 'string') {\n throw new RpcError(-32602, 'Missing required argument: url (string)');\n }\n try {\n const { auditURL } = require('../dist/browser');\n const report = await auditURL(url);\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(report, null, 2),\n },\n ],\n };\n } catch (e) {\n return {\n content: [{ type: 'text', text: `Browser audit error: ${e.message}` }],\n isError: true,\n };\n }\n }\n\n if (toolName === 'tk_browser_compare') {\n const url1 = req.params?.arguments?.url1;\n const url2 = req.params?.arguments?.url2;\n const maxDiffPercent = req.params?.arguments?.maxDiffPercent;\n if (!url1 || !url2) {\n throw new RpcError(-32602, 'Missing required arguments: url1 and url2 (strings)');\n }\n try {\n const { compareURLs } = require('../dist/browser');\n const result = await compareURLs(url1, url2, { maxDiffPercent });\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n } catch (e) {\n return {\n content: [{ type: 'text', text: `Browser compare error: ${e.message}` }],\n isError: true,\n };\n }\n }\n\n if (toolName === 'tk_browser_screenshot') {\n const url = req.params?.arguments?.url;\n if (!url || typeof url !== 'string') {\n throw new RpcError(-32602, 'Missing required argument: url (string)');\n }\n try {\n const { launchBrowser, CdpClient, createNewTab, closeTab } = require('../dist/browser');\n const browser = await launchBrowser();\n let client = null;\n let tab = null;\n try {\n tab = await createNewTab(browser.port);\n client = new CdpClient();\n await client.connect(tab.webSocketDebuggerUrl);\n await client.initDomains();\n await client.navigate(url);\n const shot = await client.captureScreenshot('png');\n return {\n content: [\n {\n type: 'text',\n text: `Screenshot captured successfully for ${url} (${Buffer.byteLength(shot, 'base64')} bytes base64 PNG).`,\n },\n ],\n };\n } finally {\n if (client) client.close();\n if (tab && browser) await closeTab(tab.id, browser.port);\n await browser.close();\n }\n } catch (e) {\n return {\n content: [{ type: 'text', text: `Screenshot error: ${e.message}` }],\n isError: true,\n };\n }\n }\n\n if (toolName === 'tk_deconstruct_component') {\n const url = req.params?.arguments?.url;\n const selector = req.params?.arguments?.selector;\n const name = req.params?.arguments?.name;\n if (!url || !selector) {\n throw new RpcError(-32602, 'Missing required arguments: url and selector (strings)');\n }\n try {\n const { deconstructElement } = require('../dist/browser');\n const result = await deconstructElement(url, selector, { name });\n return {\n content: [\n {\n type: 'text',\n text: result.code,\n },\n ],\n };\n } catch (e) {\n return {\n content: [{ type: 'text', text: `Component deconstruction error: ${e.message}` }],\n isError: true,\n };\n }\n }\n\n if (toolName === 'tk_heal_runtime_errors') {\n const url = req.params?.arguments?.url;\n const verify = req.params?.arguments?.verify;\n if (!url) {\n throw new RpcError(-32602, 'Missing required argument: url (string)');\n }\n try {\n const { captureRuntimeErrors, verifyRuntimeFix } = require('../dist/browser');\n const result = verify ? await verifyRuntimeFix(url) : await captureRuntimeErrors(url);\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n } catch (e) {\n return {\n content: [{ type: 'text', text: `Runtime Sentinel error: ${e.message}` }],\n isError: true,\n };\n }\n }\n\n if (toolName === 'tk_codify_browser_audit') {\n const url = req.params?.arguments?.url;\n if (!url) {\n throw new RpcError(-32602, 'Missing required argument: url (string)');\n }\n try {\n const { auditURL, codifyAuditViolations } = require('../dist/browser');\n const report = await auditURL(url);\n const codified = codifyAuditViolations(report);\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({ report, codified }, null, 2),\n },\n ],\n };\n } catch (e) {\n return {\n content: [{ type: 'text', text: `Audit & codify error: ${e.message}` }],\n isError: true,\n };\n }\n }\n\n if (toolName === 'dispatch_swarm') {\n const payload = req.params?.arguments?.payload;\n const file = req.params?.arguments?.file;\n const workspace = req.params?.arguments?.workspace || '.';\n const mode = req.params?.arguments?.mode || 'legacy';\n const useTui = req.params?.arguments?.use_tui || false;\n\n if (!payload && !file) {\n throw new RpcError(\n -32602,\n 'Missing required argument: either payload or file must be provided',\n );\n }\n\n if (payload && file) {\n throw new RpcError(-32602, 'Invalid arguments: provide either payload or file, not both');\n }\n\n const agentDir = getAgentDir();\n const fs = require('fs');\n if (!fs.existsSync(agentDir)) {\n return {\n content: [\n { type: 'text', text: 'Error: .agent/ directory not found. Run `tk init` first.' },\n ],\n };\n }\n\n try {\n let _payloadData;\n if (file) {\n const filePath = path.resolve(workspace, file);\n if (!fs.existsSync(filePath)) {\n throw new Error(`File not found: ${filePath}`);\n }\n _payloadData = JSON.parse(fs.readFileSync(filePath, 'utf8'));\n } else {\n _payloadData = JSON.parse(payload);\n }\n\n // Import swarm dispatcher functions\n const _swarmDispatcher = require(path.join(agentDir, 'scripts', 'swarm_dispatcher.js'));\n\n // Execute the swarm dispatcher\n const originalArgv = process.argv;\n process.argv = ['node', 'swarm_dispatcher.js', '--mode', mode, '--workspace', workspace];\n\n if (useTui) {\n process.argv.push('--tui');\n }\n\n if (file) {\n process.argv.push('--file');\n process.argv.push(file);\n } else if (payload) {\n process.argv.push('--payload');\n process.argv.push(payload);\n }\n\n // Capture output\n const { spawnSync } = require('child_process');\n const result = spawnSync(\n process.execPath,\n [path.join(agentDir, 'scripts', 'swarm_dispatcher.js'), ...process.argv.slice(2)],\n {\n encoding: 'utf8',\n timeout: 30000,\n },\n );\n\n // Restore argv\n process.argv = originalArgv;\n\n if (result.error) {\n throw result.error;\n }\n\n return {\n content: [\n { type: 'text', text: result.stdout || result.stderr || 'Swarm dispatch completed' },\n ],\n };\n } catch (e) {\n return {\n content: [{ type: 'text', text: `Swarm dispatch failed: ${e.message}` }],\n };\n }\n }\n\n if (toolName === 'get_ast_context') {\n const targetPath = req.params?.arguments?.targetPath || process.cwd();\n try {\n const result = spawnSync(\n 'node',\n [path.join(__dirname, '../scripts/build-graph.js'), targetPath],\n {\n encoding: 'utf8',\n timeout: 10000,\n },\n );\n if (result.error) throw result.error;\n return { content: [{ type: 'text', text: result.stdout || result.stderr }] };\n } catch (e) {\n return { content: [{ type: 'text', text: `Failed to query graph: ${e.message}` }] };\n }\n }\n\n if (toolName === 'validate_payload') {\n const payloadStr = req.params?.arguments?.payload;\n const schemaType = req.params?.arguments?.schemaType;\n\n if (!payloadStr || typeof payloadStr !== 'string') {\n throw new RpcError(-32602, 'Missing or invalid required argument: payload (string)');\n }\n if (!schemaType || typeof schemaType !== 'string') {\n throw new RpcError(-32602, 'Missing or invalid required argument: schemaType (string)');\n }\n\n const agentDir = getAgentDir();\n const fs = require('fs');\n if (!fs.existsSync(agentDir)) {\n return {\n content: [\n { type: 'text', text: 'Error: .agent/ directory not found. Run `tk init` first.' },\n ],\n };\n }\n\n try {\n const payloadData = JSON.parse(payloadStr);\n const {\n WorkerRequestSchema,\n WorkerResultSchema,\n SwarmPayloadSchema,\n validatePayloadOrThrow,\n } = require(path.join(agentDir, 'scripts', 'payload_schemas.js'));\n\n let schema;\n switch (schemaType) {\n case 'worker-request':\n schema = WorkerRequestSchema;\n break;\n case 'worker-result':\n schema = WorkerResultSchema;\n break;\n case 'swarm-payload':\n schema = SwarmPayloadSchema;\n break;\n default:\n throw new RpcError(\n -32602,\n `Invalid schemaType: ${schemaType}. Must be one of: worker-request, worker-result, swarm-payload`,\n );\n }\n\n const validatedData = validatePayloadOrThrow(payloadData, schema);\n return {\n content: [\n {\n type: 'text',\n text: `Payload validation successful.\\n\\nValidated payload:\\n${JSON.stringify(validatedData, null, 2)}`,\n },\n ],\n };\n } catch (e) {\n if (e instanceof SyntaxError) {\n return { content: [{ type: 'text', text: `Invalid JSON payload: ${e.message}` }] };\n } else {\n return { content: [{ type: 'text', text: `Payload validation failed: ${e.message}` }] };\n }\n }\n }\n\n if (toolName === 'run_tribunal_audit') {\n const text = runTribunalAudit();\n return { content: [{ type: 'text', text }] };\n }\n\n if (toolName === 'sync_ide_bridges') {\n const fs = require('fs');\n const cwd = process.cwd();\n const agentDest = path.join(cwd, '.agent');\n if (!fs.existsSync(agentDest)) {\n return {\n content: [\n {\n type: 'text',\n text: 'Error: .agent/ directory not found. Run `tk init` first.',\n },\n ],\n };\n }\n try {\n const { generateIDEBridges } = require(\n path.resolve(__dirname, '../dist/commands/init.js'),\n );\n // generateIDEBridges is async\n await generateIDEBridges(cwd, agentDest, true);\n return {\n content: [\n {\n type: 'text',\n text: 'Sync complete',\n },\n ],\n };\n } catch (e) {\n return {\n content: [\n {\n type: 'text',\n text: `Sync failed: ${e.message}`,\n },\n ],\n };\n }\n }\n\n if (toolName === 'search_case_law') {\n const query = req.params && req.params.arguments && req.params.arguments.query;\n if (!query || typeof query !== 'string') {\n throw new RpcError(-32602, 'Missing or invalid required argument: query (string)');\n }\n const text = searchCaseLaw(query);\n return { content: [{ type: 'text', text }] };\n }\n\n if (toolName === 'list_tribunal_agents') {\n const fs = require('fs');\n const agentDir = path.join(getAgentDir(), 'agents');\n if (!fs.existsSync(agentDir))\n return {\n content: [{ type: 'text', text: 'No agents found or .agent directory missing.' }],\n };\n const agents = fs\n .readdirSync(agentDir)\n .filter(f => f.endsWith('.md'))\n .map(f => f.replace('.md', ''));\n return { content: [{ type: 'text', text: 'Available Agents:\\n- ' + agents.join('\\n- ') }] };\n }\n\n if (toolName === 'get_tribunal_agent') {\n const fs = require('fs');\n const name = req.params?.arguments?.name;\n if (!name || typeof name !== 'string')\n throw new RpcError(-32602, 'Missing or invalid argument: name (string)');\n const sanitizedName = path.basename(name);\n const agentsDir = path.resolve(getAgentDir(), 'agents');\n const agentPath = path.resolve(agentsDir, `${sanitizedName}.md`);\n // Path containment: ensure resolved path stays within agents directory\n if (!agentPath.startsWith(agentsDir))\n throw new RpcError(-32602, 'Invalid agent name: path traversal detected');\n if (!fs.existsSync(agentPath))\n return { content: [{ type: 'text', text: `Agent '${sanitizedName}' not found.` }] };\n const text = fs.readFileSync(agentPath, 'utf8');\n return { content: [{ type: 'text', text: stripBoilerplate(text) }] };\n }\n\n if (toolName === 'list_tribunal_skills') {\n const fs = require('fs');\n const skillsDir = path.join(getAgentDir(), 'skills');\n if (!fs.existsSync(skillsDir))\n return {\n content: [{ type: 'text', text: 'No skills found or .agent directory missing.' }],\n };\n const skills = fs\n .readdirSync(skillsDir, { withFileTypes: true })\n .filter(d => d.isDirectory())\n .map(d => d.name);\n return { content: [{ type: 'text', text: 'Available Skills:\\n- ' + skills.join('\\n- ') }] };\n }\n\n if (toolName === 'get_tribunal_skill') {\n const fs = require('fs');\n const name = req.params?.arguments?.name;\n if (!name || typeof name !== 'string')\n throw new RpcError(-32602, 'Missing or invalid argument: name (string)');\n const sanitizedName = path.basename(name);\n const skillsDir = path.resolve(getAgentDir(), 'skills');\n const skillPath = path.resolve(skillsDir, sanitizedName, 'SKILL.md');\n // Path containment: ensure resolved path stays within skills directory\n if (!skillPath.startsWith(skillsDir))\n throw new RpcError(-32602, 'Invalid skill name: path traversal detected');\n if (!fs.existsSync(skillPath))\n return { content: [{ type: 'text', text: `Skill '${sanitizedName}' not found.` }] };\n const text = fs.readFileSync(skillPath, 'utf8');\n return { content: [{ type: 'text', text: stripBoilerplate(text) }] };\n }\n\n if (toolName === 'get_sparse_context') {\n const task = req.params?.arguments?.task;\n const files = req.params?.arguments?.files || [];\n const model = req.params?.arguments?.model || 'large';\n\n if (!task) throw new RpcError(-32602, 'Missing required argument: task');\n\n const agentDest = getAgentDir();\n const fs = require('fs');\n if (!fs.existsSync(agentDest)) {\n return {\n content: [\n { type: 'text', text: 'Error: .agent/ directory not found. Run `tk init` first.' },\n ],\n };\n }\n\n try {\n const workspaceRoot = process.cwd();\n const { spawn } = require('child_process');\n const args = [path.join(__dirname, 'wrapper.js'), 'context-broker', '--repo-path', workspaceRoot];\n if (task) {\n args.push('--task');\n args.push(task);\n }\n if (files && files.length > 0) {\n args.push('--files');\n args.push(files.join(','));\n }\n\n const result = await new Promise((resolve, reject) => {\n const child = spawn(process.execPath, args, { cwd: workspaceRoot, encoding: 'utf8' });\n let out = '';\n child.stdout.on('data', d => out += d);\n child.stderr.on('data', d => out += d);\n child.on('close', code => {\n resolve(out);\n });\n child.on('error', reject);\n });\n \n return { content: [{ type: 'text', text: stripBoilerplate(result) }] };\n } catch (e) {\n return {\n content: [{ type: 'text', text: `Failed to retrieve sparse context: ${e.message}` }],\n };\n }\n }\n\n if (toolName === 'recall_memory') {\n const query = req.params?.arguments?.query;\n if (!query || typeof query !== 'string') {\n throw new RpcError(-32602, 'Missing or invalid required argument: query (string)');\n }\n const budget = req.params?.arguments?.budget || 2000;\n const agentDest = getAgentDir();\n const fs = require('fs');\n if (!fs.existsSync(agentDest)) {\n return {\n content: [\n { type: 'text', text: 'Error: .agent/ directory not found. Run `tk init` first.' },\n ],\n };\n }\n try {\n const { _memoryRecall } = require('../dist/commands/memory.js');\n const { results, tokens_used } = _memoryRecall(agentDest, query, budget);\n if (results.length === 0) {\n return { content: [{ type: 'text', text: `No memories match query: \"${query}\"` }] };\n }\n let text = `## Memory Recall (${results.length} results, ~${tokens_used}/${budget} tokens)\\n\\n`;\n for (const entry of results) {\n text += `- **[${entry.memory_type.toUpperCase()}]** #${entry.id}: ${entry.content}`;\n if (entry.tags.length > 0) text += ` _(${entry.tags.join(', ')})_`;\n text += `\\n`;\n }\n return { content: [{ type: 'text', text }] };\n } catch (e) {\n return { content: [{ type: 'text', text: `Memory recall failed: ${e.message}` }] };\n }\n }\n\n if (toolName === 'store_memory') {\n const memType = req.params?.arguments?.type;\n const content = req.params?.arguments?.content;\n const tags = req.params?.arguments?.tags || [];\n if (!memType || !content) {\n throw new RpcError(-32602, 'Missing required arguments: type (string), content (string)');\n }\n const validTypes = ['semantic', 'procedural', 'episodic', 'working'];\n if (!validTypes.includes(memType)) {\n throw new RpcError(\n -32602,\n `Invalid memory type: \"${memType}\". Must be one of: ${validTypes.join(', ')}`,\n );\n }\n const agentDest = getAgentDir();\n const fs = require('fs');\n if (!fs.existsSync(agentDest)) {\n return {\n content: [\n { type: 'text', text: 'Error: .agent/ directory not found. Run `tk init` first.' },\n ],\n };\n }\n try {\n const { _memoryStore } = require('../dist/commands/memory.js');\n const result = _memoryStore(agentDest, memType, content, tags, null);\n return {\n content: [\n {\n type: 'text',\n text: `Memory stored: #${result.id} (${memType}, ~${result.token_estimate} tokens)`,\n },\n ],\n };\n } catch (e) {\n return { content: [{ type: 'text', text: `Memory store failed: ${e.message}` }] };\n }\n }\n\n if (toolName === 'query_semantic_graph') {\n const targetPath = req.params?.arguments?.targetPath || process.cwd();\n try {\n const result = spawnSync(\n 'node',\n [path.join(__dirname, '../scripts/build-graph.js'), targetPath],\n {\n encoding: 'utf8',\n timeout: 10000,\n },\n );\n if (result.error) throw result.error;\n return { content: [{ type: 'text', text: result.stdout || result.stderr }] };\n } catch (e) {\n return { content: [{ type: 'text', text: `Failed to query graph: ${e.message}` }] };\n }\n }\n\n if (toolName === 'align_output') {\n const text = req.params?.arguments?.text;\n if (typeof text !== 'string') {\n throw new RpcError(-32602, 'Missing or invalid required argument: text (string)');\n }\n try {\n const { alignText, validateCodeContent } = require('../dist/commands/align.js');\n const aligned = alignText(text);\n const warnings = validateCodeContent(aligned);\n\n let outputText = aligned;\n if (warnings.length > 0) {\n outputText += '\\n\\n⚠️ OCAE Alignment Validator Warnings:\\n';\n for (const warnMsg of warnings) {\n outputText += `● ${warnMsg}\\n`;\n }\n }\n return { content: [{ type: 'text', text: outputText }] };\n } catch (e) {\n return { content: [{ type: 'text', text: `Output alignment failed: ${e.message}` }] };\n }\n }\n\n if (toolName === 'verify_contracts') {\n const file = req.params?.arguments?.file;\n const content = req.params?.arguments?.content;\n\n if (!file || typeof file !== 'string' || typeof content !== 'string') {\n throw new RpcError(\n -32602,\n 'Missing or invalid required arguments: file (string), content (string)',\n );\n }\n\n try {\n const projectRoot = process.cwd();\n const contractEnginePath = path.join(getAgentDir(), 'scripts', 'contract_engine.js');\n if (!require('fs').existsSync(contractEnginePath)) {\n return {\n content: [\n { type: 'text', text: 'Error: contract_engine.js not found. Run `tk init` first.' },\n ],\n };\n }\n\n const contractEngine = require(contractEnginePath);\n const contracts = contractEngine.loadContracts(projectRoot);\n\n if (contracts.length === 0) {\n return {\n content: [\n {\n type: 'text',\n text: 'No active behavioral contracts found in .tribunal/contracts/.',\n },\n ],\n };\n }\n\n const relativePath = path.relative(projectRoot, file).replace(/\\\\/g, '/');\n const allViolations = [];\n\n for (const contract of contracts) {\n const vList = contractEngine.evaluateContract(contract, relativePath, content);\n if (vList.length > 0) {\n allViolations.push(...vList);\n }\n }\n\n if (allViolations.length === 0) {\n return {\n content: [\n {\n type: 'text',\n text: '✅ Contract check passed. Zero behavioral violations detected.',\n },\n ],\n };\n }\n\n let report = `📜 Contract Verification Results (${allViolations.length} violations):\\n`;\n for (const v of allViolations) {\n report += `● [${v.severity.toUpperCase()}] ${v.contract}: ${v.message}\\n`;\n if (v.line) report += ` Line ${v.line}: ${v.snippet || ''}\\n`;\n }\n\n return { content: [{ type: 'text', text: report }] };\n } catch (e) {\n return {\n content: [{ type: 'text', text: `Contract verification failed: ${e.message}` }],\n };\n }\n }\n\n throw new RpcError(-32601, `Unknown tool: ${toolName}`);\n };\n\n try {\n const result = await withToolTimeout(executeTool, GENERAL_TOOL_TIMEOUT_MS);\n if (reminder) {\n result.content.push({ type: 'text', text: '\\n\\n' + reminder });\n }\n return result;\n } catch (e) {\n if (e.message === 'TOOL_TIMEOUT') {\n const errorMsg = `Error: Tool execution timed out after ${GENERAL_TOOL_TIMEOUT_MS}ms`;\n const result = { content: [{ type: 'text', text: errorMsg }] };\n if (reminder) result.content.push({ type: 'text', text: '\\n\\n' + reminder });\n return result;\n }\n throw e;\n }\n }\n\n throw new RpcError(-32601, `Unknown method: ${req.method}`);\n}\n\nasync function processSingleRequest(req) {\n try {\n const result = await handleRequest(req);\n // If it's a notification, do not send a response\n if (req.id === undefined || req.id === null) {\n return null;\n }\n return { jsonrpc: '2.0', id: req.id, result };\n } catch (e) {\n const code = e && typeof e.code === 'number' ? e.code : -32603;\n const message = e && e.message ? e.message : 'Internal server error';\n if (req.id === undefined || req.id === null) {\n return {\n jsonrpc: '2.0',\n id: null,\n error: { code, message },\n };\n }\n return {\n jsonrpc: '2.0',\n id: req.id,\n error: { code, message },\n };\n }\n}\n\nrl.on('line', async line => {\n if (line.length > 1048576) {\n // 1MB limit\n const errorRes = {\n jsonrpc: '2.0',\n id: null,\n error: { code: -32700, message: 'Parse error: input line too long (exceeds 1MB limit)' },\n };\n console.log(JSON.stringify(errorRes));\n return;\n }\n if (!line.trim()) return;\n\n let req;\n try {\n req = JSON.parse(line);\n } catch (parseErr) {\n // Invalid JSON — send a parse error\n const errorRes = {\n jsonrpc: '2.0',\n id: null,\n error: { code: -32700, message: 'Parse error: ' + parseErr.message },\n };\n console.log(JSON.stringify(errorRes));\n return;\n }\n\n if (Array.isArray(req)) {\n const responses = [];\n for (const singleReq of req) {\n const response = await processSingleRequest(singleReq);\n if (response) {\n responses.push(response);\n }\n }\n if (responses.length > 0) {\n console.log(JSON.stringify(responses));\n }\n } else {\n const response = await processSingleRequest(req);\n if (response) {\n console.log(JSON.stringify(response));\n }\n }\n});\n\nif (process.env.NODE_ENV === 'test') {\n module.exports = {\n handleRequest,\n stripBoilerplate,\n runTribunalAudit,\n };\n}\n"
19
21
  }
@@ -16,5 +16,5 @@
16
16
  "dependents": [
17
17
  "bin/tk-proxy.js"
18
18
  ],
19
- "content": "const http = require('http');\nconst https = require('https');\nconst fs = require('fs');\nconst path = require('path');\nconst globalStore = require('./global-store');\n\nlet proxyServer = null;\n\nfunction getSystemPrompt() {\n const agentPath = globalStore.getGlobalAgentPath();\n const rulesPath = path.join(agentPath, 'rules', 'GEMINI.md');\n\n let rules = 'You are governed by Tribunal Kit rules.';\n if (fs.existsSync(rulesPath)) {\n rules = fs.readFileSync(rulesPath, 'utf8');\n }\n\n return `<tribunal_rules>\\n${rules}\\n</tribunal_rules>\\n`;\n}\n\nfunction injectRulesIntoAnthropicPayload(payloadString) {\n try {\n const payload = JSON.parse(payloadString);\n\n // Inject into Anthropic's system parameter\n const tribunalSystem = getSystemPrompt();\n\n if (payload.system) {\n if (Array.isArray(payload.system)) {\n payload.system.unshift({ type: 'text', text: tribunalSystem });\n } else if (typeof payload.system === 'string') {\n payload.system = tribunalSystem + '\\n' + payload.system;\n }\n } else {\n payload.system = tribunalSystem;\n }\n\n return JSON.stringify(payload);\n } catch (e) {\n console.error('[Tribunal Proxy] Failed to parse payload for injection:', e);\n return payloadString;\n }\n}\n\nfunction startProxyServer(port) {\n return new Promise((resolve, reject) => {\n proxyServer = http.createServer((clientReq, clientRes) => {\n let body = '';\n clientReq.on('data', chunk => {\n body += chunk.toString();\n // 5MB payload limit to prevent memory exhaustion (DoS)\n if (body.length > 5 * 1024 * 1024) {\n console.error('[Tribunal Proxy] Request too large, aborting.');\n clientReq.destroy();\n }\n });\n\n clientReq.on('end', () => {\n let modifiedBody = body;\n\n // Only intercept AI chat completion endpoints\n if (clientReq.url.includes('/v1/messages')) {\n console.log(`[Tribunal Proxy] Intercepting request to ${clientReq.url}`);\n modifiedBody = injectRulesIntoAnthropicPayload(body);\n }\n\n const options = {\n hostname: 'api.anthropic.com',\n port: 443,\n path: clientReq.url,\n method: clientReq.method,\n headers: {\n ...clientReq.headers,\n host: 'api.anthropic.com',\n 'content-length': Buffer.byteLength(modifiedBody),\n },\n };\n\n const proxyReq = https.request(options, proxyRes => {\n clientRes.writeHead(proxyRes.statusCode, proxyRes.headers);\n proxyRes.pipe(clientRes, { end: true });\n });\n\n proxyReq.on('error', err => {\n console.error('[Tribunal Proxy] Proxy request error:', err);\n clientRes.writeHead(500);\n clientRes.end();\n });\n\n proxyReq.write(modifiedBody);\n proxyReq.end();\n });\n });\n\n proxyServer.listen(port, () => {\n console.log(`[Tribunal Proxy] Listening on http://localhost:${port}`);\n resolve(port);\n });\n\n proxyServer.on('error', reject);\n });\n}\n\nfunction stopProxyServer() {\n if (proxyServer) {\n proxyServer.close();\n }\n}\n\nmodule.exports = {\n startProxyServer,\n stopProxyServer,\n};\n"
19
+ "content": "const http = require('http');\nconst https = require('https');\nconst fs = require('fs');\nconst path = require('path');\nconst globalStore = require('./global-store');\n\nlet proxyServer = null;\n\nfunction getSystemPrompt() {\n const agentPath = globalStore.getGlobalAgentPath();\n const rulesPath = path.join(agentPath, 'rules', 'GEMINI.md');\n\n let rules = 'You are governed by Tribunal Kit rules.';\n if (fs.existsSync(rulesPath)) {\n rules = fs.readFileSync(rulesPath, 'utf8');\n }\n\n return `<tribunal_rules>\\n${rules}\\n</tribunal_rules>\\n`;\n}\n\nfunction injectRulesIntoAnthropicPayload(payloadString) {\n try {\n const payload = JSON.parse(payloadString);\n\n // Inject into Anthropic's system parameter\n const tribunalSystem = getSystemPrompt();\n\n if (payload.system) {\n if (Array.isArray(payload.system)) {\n payload.system.unshift({ type: 'text', text: tribunalSystem });\n } else if (typeof payload.system === 'string') {\n payload.system = tribunalSystem + '\\n' + payload.system;\n }\n } else {\n payload.system = tribunalSystem;\n }\n\n return JSON.stringify(payload);\n } catch (e) {\n console.error('[Tribunal Proxy] Failed to parse payload for injection:', e);\n return payloadString;\n }\n}\n\nfunction startProxyServer(port) {\n return new Promise((resolve, reject) => {\n proxyServer = http.createServer((clientReq, clientRes) => {\n let body = '';\n clientReq.on('data', chunk => {\n body += chunk.toString();\n // 5MB payload limit to prevent memory exhaustion (DoS)\n if (body.length > 5 * 1024 * 1024) {\n console.error('[Tribunal Proxy] Request too large, aborting.');\n if (!clientRes.headersSent) {\n clientRes.writeHead(413, { 'Content-Type': 'text/plain' });\n clientRes.end('Payload Too Large');\n }\n clientReq.destroy();\n }\n });\n\n clientReq.on('end', () => {\n if (clientReq.destroyed) return;\n let modifiedBody = body;\n\n // Only intercept AI chat completion endpoints\n if (clientReq.url && clientReq.url.includes('/v1/messages')) {\n console.log(`[Tribunal Proxy] Intercepting request to ${clientReq.url}`);\n modifiedBody = injectRulesIntoAnthropicPayload(body);\n }\n\n const headers = { ...clientReq.headers, host: 'api.anthropic.com' };\n delete headers['transfer-encoding'];\n headers['content-length'] = Buffer.byteLength(modifiedBody);\n\n const options = {\n hostname: 'api.anthropic.com',\n port: 443,\n path: clientReq.url,\n method: clientReq.method,\n headers,\n };\n\n const proxyReq = https.request(options, proxyRes => {\n clientRes.writeHead(proxyRes.statusCode, proxyRes.headers);\n proxyRes.pipe(clientRes, { end: true });\n });\n\n proxyReq.on('error', err => {\n console.error('[Tribunal Proxy] Proxy request error:', err);\n if (!clientRes.headersSent) {\n clientRes.writeHead(502, { 'Content-Type': 'text/plain' });\n clientRes.end('Bad Gateway');\n }\n });\n\n if (modifiedBody && clientReq.method !== 'GET' && clientReq.method !== 'HEAD') {\n proxyReq.write(modifiedBody);\n }\n proxyReq.end();\n });\n });\n\n proxyServer.listen(port, () => {\n console.log(`[Tribunal Proxy] Listening on http://localhost:${port}`);\n resolve(port);\n });\n\n proxyServer.on('error', reject);\n });\n}\n\nfunction stopProxyServer() {\n if (proxyServer) {\n proxyServer.close();\n }\n}\n\nmodule.exports = {\n startProxyServer,\n stopProxyServer,\n};\n"
20
20
  }
@@ -8,5 +8,5 @@
8
8
  "dependents": [
9
9
  "bin/tk-proxy.js"
10
10
  ],
11
- "content": "const { spawn } = require('child_process');\n\nfunction spawnAgent(agentCommand, proxyPort) {\n const proxyUrl = `http://localhost:${proxyPort}`;\n console.log(`[Tribunal Proxy] Launching ${agentCommand} with proxy ${proxyUrl}`);\n\n // Split command and arguments. e.g. \"claude-code\" or \"npx claude-code\"\n const args = agentCommand.split(' ');\n const command = args.shift();\n\n // Inject proxy environment variables\n // ANTHROPIC_BASE_URL is commonly respected by Anthropic-based CLI tools\n const env = {\n ...process.env,\n ANTHROPIC_BASE_URL: proxyUrl,\n // Note: If using HTTPS_PROXY, it would look like this:\n // HTTPS_PROXY: proxyUrl,\n // NODE_TLS_REJECT_UNAUTHORIZED: \"0\"\n };\n\n const child = spawn(command, args, {\n stdio: 'inherit', // Pass stdin, stdout, stderr directly to the TTY\n env,\n });\n\n child.on('close', code => {\n console.log(`[Tribunal Proxy] ${command} exited with code ${code}`);\n process.exit(code);\n });\n\n child.on('error', err => {\n console.error(`[Tribunal Proxy] Failed to start ${command}:`, err);\n process.exit(1);\n });\n}\n\nmodule.exports = {\n spawnAgent,\n};\n"
11
+ "content": "const { spawn } = require('child_process');\n\nfunction spawnAgent(agentCommand, proxyPort) {\n const proxyUrl = `http://localhost:${proxyPort}`;\n console.log(`[Tribunal Proxy] Launching ${agentCommand} with proxy ${proxyUrl}`);\n\n // Split command and arguments. e.g. \"claude-code\" or \"npx claude-code\"\n const args = agentCommand.split(' ');\n const command = args.shift();\n\n // Inject proxy environment variables\n // ANTHROPIC_BASE_URL is commonly respected by Anthropic-based CLI tools\n const env = {\n ...process.env,\n ANTHROPIC_BASE_URL: proxyUrl,\n // Note: If using HTTPS_PROXY, it would look like this:\n // HTTPS_PROXY: proxyUrl,\n // NODE_TLS_REJECT_UNAUTHORIZED: \"0\"\n };\n\n const isWin = process.platform === 'win32';\n const child = spawn(command, args, {\n stdio: 'inherit', // Pass stdin, stdout, stderr directly to the TTY\n env,\n shell: isWin,\n });\n\n child.on('close', (code, signal) => {\n console.log(`[Tribunal Proxy] ${command} exited with code ${code !== null ? code : signal}`);\n if (code !== null) {\n process.exit(code);\n } else {\n process.exit(signal ? 128 : 1);\n }\n });\n\n child.on('error', err => {\n console.error(`[Tribunal Proxy] Failed to start ${command}:`, err);\n process.exit(1);\n });\n}\n\nmodule.exports = {\n spawnAgent,\n};\n"
12
12
  }
@@ -10,5 +10,5 @@
10
10
  "../dist/cli.js": []
11
11
  },
12
12
  "dependents": [],
13
- "content": "#!/usr/bin/env node\n/**\n * Tribunal-Kit Core Wrapper\n *\n * This script routes commands to the ultra-fast Rust binary if available and supported.\n * For legacy commands (or if the binary isn't available/compiled yet), it gracefully\n * falls back to the original JavaScript implementation.\n */\n\nconst fs = require('fs');\nconst path = require('path');\nconst { spawnSync } = require('child_process');\nconst os = require('os');\n\n// Commands that have been fully ported to Rust so far\nconst RUST_COMMANDS = new Set([\n 'init',\n 'validate',\n 'status',\n 'sync',\n 'hook',\n 'uninstall',\n 'memory',\n 'min-context',\n 'dag-schedule',\n 'context-compress',\n 'context-broker',\n 'optimize-step',\n 'impact-tier',\n]);\n\n// Determine the path to the compiled Rust binary\n// In a full production release, this checks optionalDependencies in node_modules\n// For development, it checks the local target/release folder\nfunction getBinaryPath() {\n if (process.env.TRIBUNAL_FORCE_JS === '1') {\n return null;\n }\n\n if (process.env.TRIBUNAL_CORE_PATH && fs.existsSync(process.env.TRIBUNAL_CORE_PATH)) {\n return process.env.TRIBUNAL_CORE_PATH;\n }\n\n const isWindows = os.platform() === 'win32';\n const ext = isWindows ? '.exe' : '';\n const platform = os.platform();\n const arch = os.arch();\n\n // First, try production resolution (from optionalDependencies)\n const pkgName = `@tribunal-kit/core-${platform}-${arch}`;\n try {\n const pkgPath = require.resolve(`${pkgName}/package.json`);\n const pkgDir = path.dirname(pkgPath);\n const binPath = path.resolve(pkgDir, `bin/tribunal-core${ext}`);\n if (fs.existsSync(binPath)) {\n return binPath;\n }\n const rootBinPath = path.resolve(pkgDir, `tribunal-core${ext}`);\n if (fs.existsSync(rootBinPath)) {\n return rootBinPath;\n }\n } catch {\n // Package not found, ignore and fall back to local dev targets\n }\n\n // Second, try to find the binary in local dev target directories\n const candidatePaths = [\n path.resolve(__dirname, '..', 'target', 'release', `tribunal-core${ext}`),\n path.resolve(__dirname, '..', 'target', 'debug', `tribunal-core${ext}`),\n path.resolve(__dirname, '..', '..', 'target', 'release', `tribunal-core${ext}`),\n path.resolve(__dirname, '..', '..', 'target', 'debug', `tribunal-core${ext}`),\n path.resolve(process.cwd(), 'target', 'release', `tribunal-core${ext}`),\n path.resolve(process.cwd(), 'target', 'debug', `tribunal-core${ext}`),\n path.resolve(process.cwd(), 'tribunal-kit', 'target', 'release', `tribunal-core${ext}`),\n path.resolve(process.cwd(), 'tribunal-kit', 'target', 'debug', `tribunal-core${ext}`),\n ];\n\n for (const candidate of candidatePaths) {\n if (fs.existsSync(candidate)) {\n return candidate;\n }\n }\n\n // Third, attempt on-demand compilation if Cargo.toml exists locally and cargo is installed\n const cargoTomlPath = path.resolve(__dirname, '..', 'Cargo.toml');\n if (fs.existsSync(cargoTomlPath)) {\n try {\n const buildResult = spawnSync('cargo', ['build', '--release'], {\n cwd: path.resolve(__dirname, '..'),\n stdio: 'ignore',\n timeout: 60000,\n });\n if (buildResult.status === 0) {\n const releasePath = candidatePaths[0];\n if (fs.existsSync(releasePath)) {\n return releasePath;\n }\n }\n } catch {\n // cargo not available or build failed, fallback gracefully\n }\n }\n\n return null;\n}\n\nfunction runRustBinary(binPath, args) {\n const stdio = ['inherit', 'inherit', 'inherit'];\n const result = spawnSync(binPath, args, {\n stdio: stdio,\n env: process.env,\n });\n\n if (result.error) {\n // Graceful degradation: fall back to JS engine instead of hard-crashing.\n // Spawn errors include missing binaries, permission denied, corrupted\n // executables, missing shared libraries, and OS-level exec failures.\n console.warn(\n `\\x1b[93m⚠ Rust engine failed (${result.error.code || result.error.message}). Falling back to JS engine.\\x1b[0m`,\n );\n return false; // Signal caller to fall back\n }\n\n process.exit(result.status || 0);\n}\n\nfunction runLegacyFallback() {\n // Use the modular dist/ CLI with lazy-loaded commands for faster cold-start.\n // Each command module is require()'d only when invoked (~70% fewer files loaded).\n const { main } = require('../dist/cli.js');\n main().catch(err => {\n console.error(`\\x1b[91m✖ Fatal Error:\\x1b[0m ${err.message || err}`);\n process.exit(1);\n });\n}\n\nfunction main() {\n // Skip 'node' and 'wrapper.js'\n const args = process.argv.slice(2);\n\n // Extract the command (the first non-flag argument)\n const command = args.find(a => !a.startsWith('-'));\n\n if (command && RUST_COMMANDS.has(command)) {\n const binPath = getBinaryPath();\n\n if (binPath) {\n // For the init command, Rust needs to know where the .agent template folder is.\n if (command === 'init') {\n const sourceDir = path.resolve(__dirname, '..', '.agent');\n args.push('--source-dir', sourceDir);\n }\n\n // Route to Rust engine\n // console.log('\\x1b[90m⚡ Executing via Rust Core Engine\\x1b[0m');\n const rustResult = runRustBinary(binPath, args);\n if (rustResult !== false) {\n return; // Rust engine handled it (process.exit was called)\n }\n // rustResult === false means spawn error; fall through to JS fallback\n } else {\n // Warn if Rust command was requested but binary is missing (in verbose mode)\n if (process.env.TK_VERBOSE || process.env.VERBOSE) {\n console.warn(\n '\\x1b[93m⚠ Rust binary not found in target/. Falling back to JS engine.\\x1b[0m',\n );\n }\n }\n }\n\n // Fall back to JS logic for un-ported commands (e.g. `learn`, `case`, `marathon`)\n runLegacyFallback();\n}\n\nmain();\n"
13
+ "content": "#!/usr/bin/env node\n/**\n * Tribunal-Kit Core Wrapper\n *\n * This script routes commands to the ultra-fast Rust binary if available and supported.\n * For legacy commands (or if the binary isn't available/compiled yet), it gracefully\n * falls back to the original JavaScript implementation.\n */\n\nconst fs = require('fs');\nconst path = require('path');\nconst { spawnSync } = require('child_process');\nconst os = require('os');\n\n// Commands that have been fully ported to Rust so far\nconst RUST_COMMANDS = new Set([\n 'init',\n 'validate',\n 'status',\n 'sync',\n 'hook',\n 'uninstall',\n 'memory',\n 'min-context',\n 'dag-schedule',\n 'context-compress',\n 'context-broker',\n 'optimize-step',\n 'impact-tier',\n 'sdd',\n 'fitness',\n 'telemetry-record',\n 'telemetry-summary',\n 'resolve-skills',\n 'heatmap',\n 'pollinate',\n 'leaderboard',\n 'benchmark',\n 'genome',\n 'compile',\n 'purge',\n]);\n\n// Determine the path to the compiled Rust binary\n// In a full production release, this checks optionalDependencies in node_modules\n// For development, it checks the local target/release folder\nfunction getBinaryPath() {\n if (process.env.TRIBUNAL_FORCE_JS === '1' || process.env.TRIBUNAL_FORCE_JS === 'true') {\n return null;\n }\n\n if (process.env.TRIBUNAL_CORE_PATH && fs.existsSync(process.env.TRIBUNAL_CORE_PATH)) {\n return process.env.TRIBUNAL_CORE_PATH;\n }\n\n const isWindows = os.platform() === 'win32';\n const ext = isWindows ? '.exe' : '';\n const platform = os.platform();\n const arch = os.arch();\n\n // First, try production resolution (from optionalDependencies)\n const pkgName = `@tribunal-kit/core-${platform}-${arch}`;\n try {\n const pkgPath = require.resolve(`${pkgName}/package.json`);\n const pkgDir = path.dirname(pkgPath);\n const binPath = path.resolve(pkgDir, `bin/tribunal-core${ext}`);\n if (fs.existsSync(binPath)) {\n return binPath;\n }\n const rootBinPath = path.resolve(pkgDir, `tribunal-core${ext}`);\n if (fs.existsSync(rootBinPath)) {\n return rootBinPath;\n }\n } catch {\n // Package not found, ignore and fall back to local dev targets\n }\n\n // Second, try to find the binary in local dev target directories\n const candidatePaths = [\n path.resolve(__dirname, '..', 'target', 'release', `tribunal-core${ext}`),\n path.resolve(__dirname, '..', 'target', 'debug', `tribunal-core${ext}`),\n path.resolve(__dirname, '..', '..', 'target', 'release', `tribunal-core${ext}`),\n path.resolve(__dirname, '..', '..', 'target', 'debug', `tribunal-core${ext}`),\n path.resolve(process.cwd(), 'target', 'release', `tribunal-core${ext}`),\n path.resolve(process.cwd(), 'target', 'debug', `tribunal-core${ext}`),\n path.resolve(process.cwd(), 'tribunal-kit', 'target', 'release', `tribunal-core${ext}`),\n path.resolve(process.cwd(), 'tribunal-kit', 'target', 'debug', `tribunal-core${ext}`),\n ];\n\n for (const candidate of candidatePaths) {\n if (fs.existsSync(candidate)) {\n return candidate;\n }\n }\n\n // Third, attempt on-demand compilation if Cargo.toml exists locally and explicitly requested\n const cargoTomlPath = path.resolve(__dirname, '..', 'Cargo.toml');\n if (process.env.TK_AUTO_BUILD === '1' && fs.existsSync(cargoTomlPath)) {\n try {\n console.log('\\x1b[90m⚡ Building Rust core engine (TK_AUTO_BUILD=1)...\\x1b[0m');\n const buildResult = spawnSync('cargo', ['build', '--release'], {\n cwd: path.resolve(__dirname, '..'),\n stdio: 'inherit',\n timeout: 60000,\n });\n if (buildResult.status === 0) {\n const releasePath = candidatePaths[0];\n if (fs.existsSync(releasePath)) {\n return releasePath;\n }\n }\n } catch {\n // cargo not available or build failed, fallback gracefully\n }\n }\n\n return null;\n}\n\nfunction runRustBinary(binPath, args) {\n // On Unix-like platforms, ensure the binary has execute permissions\n if (os.platform() !== 'win32') {\n try {\n fs.chmodSync(binPath, 0o755);\n } catch {\n // Best-effort permission check\n }\n }\n\n const stdio = ['inherit', 'inherit', 'inherit'];\n const result = spawnSync(binPath, args, {\n stdio: stdio,\n env: process.env,\n });\n\n if (result.error) {\n // Graceful degradation: fall back to JS engine instead of hard-crashing.\n // Spawn errors include missing binaries, permission denied, corrupted\n // executables, missing shared libraries, and OS-level exec failures.\n console.warn(\n `\\x1b[93m⚠ Rust engine failed (${result.error.code || result.error.message}). Falling back to JS engine.\\x1b[0m`,\n );\n return false; // Signal caller to fall back\n }\n\n if (result.signal) {\n const signalCode = os.constants?.signals?.[result.signal] || 1;\n process.exit(128 + signalCode);\n }\n\n process.exit(result.status !== null && result.status !== undefined ? result.status : 1);\n}\n\nfunction runLegacyFallback() {\n // Use the modular dist/ CLI with lazy-loaded commands for faster cold-start.\n // Each command module is require()'d only when invoked (~70% fewer files loaded).\n const { main } = require('../dist/cli.js');\n main().catch(err => {\n console.error(`\\x1b[91m✖ Fatal Error:\\x1b[0m ${err.message || err}`);\n process.exit(1);\n });\n}\n\nfunction main() {\n // Skip 'node' and 'wrapper.js'\n const args = process.argv.slice(2);\n\n // Extract the command (the first non-flag argument)\n const command = args.find(a => !a.startsWith('-'));\n\n if (command && RUST_COMMANDS.has(command)) {\n const binPath = getBinaryPath();\n\n if (binPath) {\n // For the init command, Rust needs to know where the .agent template folder is.\n if (command === 'init') {\n const sourceDir = path.resolve(__dirname, '..', '.agent');\n args.push('--source-dir', sourceDir);\n }\n\n // Route to Rust engine\n // console.log('\\x1b[90m⚡ Executing via Rust Core Engine\\x1b[0m');\n const rustResult = runRustBinary(binPath, args);\n if (rustResult !== false) {\n return; // Rust engine handled it (process.exit was called)\n }\n // rustResult === false means spawn error; fall through to JS fallback\n } else {\n // Warn if Rust command was requested but binary is missing (in verbose mode)\n if (process.env.TK_VERBOSE || process.env.VERBOSE) {\n console.warn(\n '\\x1b[93m⚠ Rust binary not found in target/. Falling back to JS engine.\\x1b[0m',\n );\n }\n }\n }\n\n // Fall back to JS logic for un-ported commands (e.g. `learn`, `case`, `marathon`)\n runLegacyFallback();\n}\n\nmain();\n"
14
14
  }
@@ -4,5 +4,5 @@
4
4
  "blastRadius": 0,
5
5
  "imports": {},
6
6
  "dependents": [],
7
- "content": "module.exports = [\n {\n ignores: ['dist/**', 'node_modules/**', 'target/**', 'coverage/**', 'scratch/**'],\n },\n {\n files: ['**/*.js'],\n languageOptions: {\n ecmaVersion: 'latest',\n sourceType: 'commonjs',\n globals: {\n require: 'readonly',\n module: 'readonly',\n process: 'readonly',\n __dirname: 'readonly',\n console: 'readonly',\n exports: 'readonly',\n setTimeout: 'readonly',\n clearTimeout: 'readonly',\n setInterval: 'readonly',\n clearInterval: 'readonly',\n setImmediate: 'readonly',\n performance: 'readonly',\n Buffer: 'readonly',\n describe: 'readonly',\n test: 'readonly',\n it: 'readonly',\n expect: 'readonly',\n beforeEach: 'readonly',\n afterEach: 'readonly',\n beforeAll: 'readonly',\n afterAll: 'readonly',\n jest: 'readonly',\n fail: 'readonly',\n },\n },\n rules: {\n 'no-unused-vars': [\n 'warn',\n {\n argsIgnorePattern: '^_',\n varsIgnorePattern: '^_',\n caughtErrorsIgnorePattern: '^_',\n },\n ],\n 'no-undef': 'error',\n 'no-eval': 'error',\n 'no-implied-eval': 'error',\n 'no-new-func': 'error',\n eqeqeq: ['error', 'always', { null: 'ignore' }],\n 'prefer-const': 'warn',\n 'no-var': 'warn',\n 'no-throw-literal': 'error',\n 'no-return-await': 'warn',\n 'no-template-curly-in-string': 'warn',\n },\n },\n];\n"
7
+ "content": "module.exports = [\n {\n ignores: ['dist/**', '**/dist/**', 'node_modules/**', 'target/**', 'coverage/**', 'scratch/**'],\n },\n {\n files: ['**/*.js'],\n languageOptions: {\n ecmaVersion: 'latest',\n sourceType: 'commonjs',\n globals: {\n require: 'readonly',\n module: 'readonly',\n process: 'readonly',\n __dirname: 'readonly',\n __filename: 'readonly',\n console: 'readonly',\n exports: 'readonly',\n setTimeout: 'readonly',\n clearTimeout: 'readonly',\n setInterval: 'readonly',\n clearInterval: 'readonly',\n setImmediate: 'readonly',\n performance: 'readonly',\n Buffer: 'readonly',\n describe: 'readonly',\n test: 'readonly',\n it: 'readonly',\n expect: 'readonly',\n beforeEach: 'readonly',\n afterEach: 'readonly',\n beforeAll: 'readonly',\n afterAll: 'readonly',\n jest: 'readonly',\n fail: 'readonly',\n },\n },\n rules: {\n 'no-unused-vars': [\n 'warn',\n {\n argsIgnorePattern: '^_',\n varsIgnorePattern: '^_',\n caughtErrorsIgnorePattern: '^_',\n },\n ],\n 'no-undef': 'error',\n 'no-eval': 'error',\n 'no-implied-eval': 'error',\n 'no-new-func': 'error',\n eqeqeq: ['error', 'always', { null: 'ignore' }],\n 'prefer-const': 'warn',\n 'no-var': 'warn',\n 'no-throw-literal': 'error',\n 'no-return-await': 'warn',\n 'no-template-curly-in-string': 'warn',\n },\n },\n {\n files: ['.opencode/**/*.js', '**/*.mjs'],\n languageOptions: {\n ecmaVersion: 'latest',\n sourceType: 'module',\n },\n },\n];\n"
8
8
  }
@@ -0,0 +1,11 @@
1
+ {
2
+ "file": "hooks/session-start.js",
3
+ "riskScore": "Low",
4
+ "blastRadius": 0,
5
+ "imports": {
6
+ "fs": [],
7
+ "path": []
8
+ },
9
+ "dependents": [],
10
+ "content": "#!/usr/bin/env node\n/**\n * Cross-Platform SessionStart Hook for Tribunal Kit\n *\n * Injects Tribunal Kit master governance instructions into the host agent session\n * on startup, clear, and context compaction.\n *\n * Supports:\n * - Cursor Agent (emits additional_context)\n * - Claude Code (emits hookSpecificOutput.additionalContext)\n * - GitHub Copilot CLI / Standard Agent SDK (emits additionalContext)\n */\n\nconst fs = require('fs');\nconst path = require('path');\n\nfunction getPluginRoot() {\n if (process.env.CURSOR_PLUGIN_ROOT) return process.env.CURSOR_PLUGIN_ROOT;\n if (process.env.CLAUDE_PLUGIN_ROOT) return process.env.CLAUDE_PLUGIN_ROOT;\n return path.resolve(__dirname, '..');\n}\n\nfunction loadMasterRules(pluginRoot) {\n const candidates = [\n path.join(pluginRoot, '.agent', 'rules', 'GEMINI.md'),\n path.join(pluginRoot, '.agent', 'config', 'system-prompt.md'),\n path.join(pluginRoot, '.cursorrules'),\n ];\n\n for (const candidate of candidates) {\n if (fs.existsSync(candidate)) {\n try {\n return fs.readFileSync(candidate, 'utf8');\n } catch (_err) {\n // Continue to next candidate\n }\n }\n }\n\n return '# Tribunal Kit Master Governance Active\\nEnforce strict TDD, out-of-band context isolation, and parallel reviewer waves.';\n}\n\nfunction main() {\n const pluginRoot = getPluginRoot();\n const rules = loadMasterRules(pluginRoot);\n\n const sessionContext = [\n '<EXTREMELY_IMPORTANT>',\n 'Tribunal Kit Master Governance is active.',\n 'You are operating under the Tribunal Anti-Hallucination & Subagent-Driven Development (SDD) protocol.',\n 'Enforce: Iron Law of TDD (Red-Green-Refactor), 28-Specialist Review Waves, Out-of-Band Context Isolation, and Zero Placeholders.',\n '',\n rules,\n '</EXTREMELY_IMPORTANT>',\n ].join('\\n');\n\n let outputObj;\n if (process.env.CURSOR_PLUGIN_ROOT) {\n // Cursor expects snake_case additional_context\n outputObj = { additional_context: sessionContext };\n } else if (process.env.CLAUDE_PLUGIN_ROOT && !process.env.COPILOT_CLI) {\n // Claude Code expects nested hookSpecificOutput\n outputObj = {\n hookSpecificOutput: {\n hookEventName: 'SessionStart',\n additionalContext: sessionContext,\n },\n };\n } else {\n // Standard SDK / Copilot CLI\n outputObj = { additionalContext: sessionContext };\n }\n\n process.stdout.write(JSON.stringify(outputObj, null, 2) + '\\n');\n}\n\nmain();\n"
11
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "file": "scripts/apply-version.js",
3
+ "riskScore": "Low",
4
+ "blastRadius": 0,
5
+ "imports": {
6
+ "fs": [],
7
+ "path": []
8
+ },
9
+ "dependents": [],
10
+ "content": "const fs = require('fs');\nconst path = require('path');\n\nconst ROOT = path.resolve(__dirname, '..');\nconst PKG_PATH = path.join(ROOT, 'package.json');\nconst PKG = JSON.parse(fs.readFileSync(PKG_PATH, 'utf8'));\nconst VERSION = PKG.version;\n\nfunction updateFiles() {\n const filesToUpdate = [\n 'plugin.json',\n 'gemini-extension.json',\n 'npm/core-template/package.json',\n 'README.md',\n 'crates/core/Cargo.toml',\n 'bin/adapter-install.js',\n 'dist/tui/banner.js',\n ];\n\n for (const relPath of filesToUpdate) {\n const fullPath = path.join(ROOT, relPath);\n if (fs.existsSync(fullPath)) {\n let content = fs.readFileSync(fullPath, 'utf8');\n\n if (relPath.endsWith('.json')) {\n const json = JSON.parse(content);\n if (json.version) {\n json.version = VERSION;\n }\n fs.writeFileSync(fullPath, JSON.stringify(json, null, 2) + '\\n');\n } else if (relPath === 'crates/core/Cargo.toml') {\n content = content.replace(/^version\\s*=\\s*\"[^\"]+\"/m, `version = \"${VERSION}\"`);\n fs.writeFileSync(fullPath, content);\n } else if (relPath === 'README.md') {\n content = content.replace(/Release-v([0-9]+\\.[0-9]+\\.[0-9]+)/g, `Release-v${VERSION}`);\n fs.writeFileSync(fullPath, content);\n } else if (relPath === 'bin/adapter-install.js' || relPath === 'dist/tui/banner.js') {\n content = content.replace(/v\\d+\\.\\d+\\.\\d+/g, `v${VERSION}`);\n content = content.replace(/version = '\\d+\\.\\d+\\.\\d+'/g, `version = '${VERSION}'`);\n fs.writeFileSync(fullPath, content);\n }\n console.log(`Updated ${relPath} to ${VERSION}`);\n }\n }\n\n // Update optionalDependencies in package.json\n if (PKG.optionalDependencies) {\n for (const key of Object.keys(PKG.optionalDependencies)) {\n PKG.optionalDependencies[key] = `^${VERSION}`;\n }\n fs.writeFileSync(PKG_PATH, JSON.stringify(PKG, null, 2) + '\\n');\n console.log(`Updated package.json optionalDependencies to ^${VERSION}`);\n }\n}\n\nupdateFiles();\nconsole.log('Applied version update across repository successfully.');\n"
11
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "file": "scripts/audit_skill_sdo.js",
3
+ "riskScore": "Low",
4
+ "blastRadius": 0,
5
+ "imports": {
6
+ "fs": [],
7
+ "path": []
8
+ },
9
+ "dependents": [],
10
+ "content": "#!/usr/bin/env node\n/**\n * Skill Discovery Optimization (SDO) Linter for Tribunal-Kit\n *\n * Scans all skills in .agent/skills/ to ensure their frontmatter descriptions\n * follow the SDO invariant:\n * - Must describe *when to trigger* (symptoms, contexts, conditions)\n * - Must NOT summarize the internal workflow or process (which causes LLMs to skim/hallucinate)\n */\n\nconst fs = require('fs');\nconst path = require('path');\n\nconst SKILLS_DIR = path.resolve(__dirname, '..', '.agent', 'skills');\n\nfunction parseFrontmatter(content) {\n const match = content.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---/);\n if (!match) return null;\n\n const yamlBlock = match[1];\n const nameMatch = yamlBlock.match(/^name:\\s*(.+)$/m);\n const descMatch = yamlBlock.match(/^description:\\s*(.+)$/m);\n\n return {\n name: nameMatch ? nameMatch[1].trim().replace(/^[\"']|[\"']$/g, '') : null,\n description: descMatch ? descMatch[1].trim().replace(/^[\"']|[\"']$/g, '') : null,\n };\n}\n\nfunction auditSkills() {\n if (!fs.existsSync(SKILLS_DIR)) {\n console.error(`✖ Skills directory not found: ${SKILLS_DIR}`);\n process.exit(1);\n }\n\n const entries = fs.readdirSync(SKILLS_DIR, { withFileTypes: true });\n const skillDirs = entries.filter(e => e.isDirectory()).map(e => e.name);\n\n let totalSkills = 0;\n let validSkills = 0;\n const warnings = [];\n\n for (const dir of skillDirs) {\n const skillMdPath = path.join(SKILLS_DIR, dir, 'SKILL.md');\n if (!fs.existsSync(skillMdPath)) continue;\n\n totalSkills++;\n const content = fs.readFileSync(skillMdPath, 'utf8');\n const fm = parseFrontmatter(content);\n\n if (!fm || !fm.description) {\n warnings.push({ skill: dir, issue: 'Missing frontmatter description' });\n continue;\n }\n\n const desc = fm.description;\n const isTriggerFocused =\n desc.toLowerCase().includes('use when') ||\n desc.toLowerCase().includes('activate when') ||\n desc.toLowerCase().includes('when ');\n\n if (!isTriggerFocused) {\n warnings.push({\n skill: dir,\n issue:\n 'Description does not explicitly specify trigger condition (should start with \"Use when...\")',\n description: desc.slice(0, 80) + '...',\n });\n } else {\n validSkills++;\n }\n }\n\n console.log(`\\n🔍 Skill Discovery Optimization (SDO) Audit Results:`);\n console.log(` Total Skills Analyzed: ${totalSkills}`);\n console.log(` SDO Trigger-Compliant: ${validSkills}`);\n console.log(` Advisory Warnings: ${warnings.length}\\n`);\n\n if (warnings.length > 0) {\n console.log(`⚠️ Advisory Sample (first 5):`);\n for (const w of warnings.slice(0, 5)) {\n console.log(` - [${w.skill}]: ${w.issue}`);\n }\n }\n\n console.log(`\\n✔ SDO audit complete. System has ${totalSkills} searchable skills.\\n`);\n}\n\nauditSkills();\n"
11
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "file": "scripts/clean-pycache.js",
3
+ "riskScore": "Low",
4
+ "blastRadius": 0,
5
+ "imports": {
6
+ "fs": [],
7
+ "path": []
8
+ },
9
+ "dependents": [],
10
+ "content": "#!/usr/bin/env node\n/**\n * clean-pycache.js — Removes Python bytecode and __pycache__ directories.\n * Ensures clean npm tarballs without platform-specific Python artifacts.\n */\n\n'use strict';\n\nconst fs = require('fs');\nconst path = require('path');\n\nconst ROOT = path.resolve(__dirname, '..');\nconst TARGET_DIR = path.join(ROOT, '.agent');\n\nlet removedCount = 0;\n\nfunction cleanRecursively(dir) {\n if (!fs.existsSync(dir)) return;\n\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n if (entry.name === '__pycache__') {\n fs.rmSync(fullPath, { recursive: true, force: true });\n removedCount++;\n // console.log(` Removed: ${path.relative(ROOT, fullPath)}`);\n } else {\n cleanRecursively(fullPath);\n }\n } else if (/\\.(?:pyc|pyo|pyd)$/i.test(entry.name)) {\n fs.unlinkSync(fullPath);\n removedCount++;\n // console.log(` Removed: ${path.relative(ROOT, fullPath)}`);\n }\n }\n}\n\ncleanRecursively(TARGET_DIR);\nif (removedCount > 0) {\n console.log(`✓ Cleaned ${removedCount} Python cache files/directories from .agent/`);\n}\n"
11
+ }
@@ -0,0 +1,17 @@
1
+ {
2
+ "file": "scripts/context_compiler.js",
3
+ "riskScore": "Low",
4
+ "blastRadius": 1,
5
+ "imports": {
6
+ "fs": [],
7
+ "path": [],
8
+ "crypto": [],
9
+ "child_process": [],
10
+ "./_colors": [],
11
+ "../.agent/scripts/_colors": []
12
+ },
13
+ "dependents": [
14
+ "test/unit/context_compiler.test.js"
15
+ ],
16
+ "content": "#!/usr/bin/env node\n/**\n * context_compiler.js — Tribunal Kit SOTA Context Compiler Engine\n * ════════════════════════════════════════════════════════════════════\n * Deterministic, high-speed context extraction engine for:\n * 1. Single Files (Flight Data HUD Dossier)\n * 2. Multi-File Pairs (Interface Bridge Dossier)\n * 3. Project Folders (Subsystem Macro Dossier)\n * 4. Batch Vault Crawling (--crawl)\n * 5. Semantic Drift Sentinel (--check)\n *\n * Designed for both CLI execution and in-process MCP server integration.\n */\n\n'use strict';\n\nconst fs = require('fs');\nconst path = require('path');\nconst crypto = require('crypto');\nconst { execSync } = require('child_process');\n\n// Optional ANSI colors\nlet C = {\n GREEN: '\\x1b[92m',\n YELLOW: '\\x1b[93m',\n CYAN: '\\x1b[96m',\n RED: '\\x1b[91m',\n BLUE: '\\x1b[94m',\n BOLD: '\\x1b[1m',\n DIM: '\\x1b[2m',\n RESET: '\\x1b[0m',\n};\n\ntry {\n const colorsMod = require('./_colors');\n if (colorsMod) C = Object.assign({}, C, colorsMod);\n} catch {\n try {\n const colorsMod = require('../.agent/scripts/_colors');\n if (colorsMod) C = Object.assign({}, C, colorsMod);\n } catch {\n // Fallback C used\n }\n}\n\n// ── Hashing Helpers ─────────────────────────────────────────────────────────\n\nfunction computeSha256(content) {\n const normalized = content.replace(/\\r\\n/g, '\\n').trim();\n return crypto.createHash('sha256').update(normalized, 'utf8').digest('hex').substring(0, 16);\n}\n\nfunction computeInterfaceHash(signatures) {\n const text = signatures\n .map(s => `${s.kind}:${s.name}:${s.signature}`)\n .sort()\n .join('\\n');\n return crypto.createHash('sha256').update(text, 'utf8').digest('hex').substring(0, 16);\n}\n\n// ── Multi-Language AST / Regex Skeleton Extractor ───────────────────────────\n\nfunction extractFileSkeleton(filePath, rawContent) {\n const ext = path.extname(filePath).toLowerCase();\n const lines = rawContent.split(/\\r?\\n/);\n const imports = [];\n const exports = [];\n const types = [];\n const landmines = [];\n\n // 1. Comments and Landmines (Chesterton's Fences)\n lines.forEach((line, idx) => {\n const trimmed = line.trim();\n if (\n trimmed.includes('// VERIFY') ||\n trimmed.includes('// NOTE') ||\n trimmed.includes('// FIX') ||\n trimmed.includes('// HACK') ||\n trimmed.includes('// CAUTION') ||\n trimmed.includes('// INVARIANT') ||\n trimmed.includes('// DO NOT') ||\n trimmed.includes('# VERIFY') ||\n trimmed.includes('# NOTE')\n ) {\n landmines.push({\n line: idx + 1,\n content: trimmed,\n });\n }\n });\n\n // 2. Language-Specific Parsers\n if (ext === '.ts' || ext === '.tsx' || ext === '.js' || ext === '.jsx' || ext === '.mjs') {\n // Phase 1: Try Rust AST Extraction\n try {\n const absPath = path.resolve(process.cwd(), filePath);\n const binName = process.platform === 'win32' ? 'tribunal-core.exe' : 'tribunal-core';\n // Use release build if available, otherwise debug\n let corePath = path.join(__dirname, '..', 'crates', 'core', 'target', 'release', binName);\n if (!fs.existsSync(corePath)) {\n corePath = path.join(__dirname, '..', 'crates', 'core', 'target', 'debug', binName);\n }\n \n if (fs.existsSync(corePath)) {\n const result = require('child_process').execSync(`\"${corePath}\" ast-extract --file \"${absPath}\"`, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });\n const data = JSON.parse(result);\n if (data && data.success) {\n // We map the Rust JSON into the exact format expected by the rest of the JS code\n const mappedImports = data.imports.map(i => ({ source: i.source, specifiers: i.specifiers, line: 0 }));\n const mappedExports = data.exports.map(e => ({ kind: e.kind, name: e.name, signature: e.signature, line: 0 }));\n const mappedTypes = data.types.map(t => ({ kind: t.kind, name: t.name, signature: t.signature, line: 0 }));\n \n return {\n imports: mappedImports,\n exports: mappedExports,\n types: mappedTypes,\n landmines: data.landmines,\n interfaceHash: computeInterfaceHash(mappedExports.concat(mappedTypes))\n };\n }\n }\n } catch(e) {\n // Silent fallback to Regex parsing\n }\n\n lines.forEach((line, idx) => {\n const trimmed = line.trim();\n\n // Imports\n const importMatch = trimmed.match(\n /^import\\s+(?:type\\s+)?(?:(.+?)\\s+from\\s+)?['\"]([^'\"]+)['\"]/,\n );\n if (importMatch) {\n imports.push({\n source: importMatch[2],\n specifiers: importMatch[1] ? importMatch[1].trim() : '*',\n line: idx + 1,\n });\n }\n const requireMatch = trimmed.match(\n /(?:const|let|var)\\s+(.+?)\\s*=\\s*require\\(['\"]([^'\"]+)['\"]\\)/,\n );\n if (requireMatch) {\n imports.push({\n source: requireMatch[2],\n specifiers: requireMatch[1].trim(),\n line: idx + 1,\n });\n }\n\n // Exports\n const exportFunc = trimmed.match(\n /^export\\s+(?:default\\s+)?(?:async\\s+)?function\\s+(\\w+)\\s*(\\(.*?\\))/,\n );\n if (exportFunc) {\n exports.push({\n kind: 'function',\n name: exportFunc[1],\n signature: `function ${exportFunc[1]}${exportFunc[2]}`,\n line: idx + 1,\n });\n }\n\n const exportConst = trimmed.match(\n /^export\\s+const\\s+(\\w+)(?:\\s*:\\s*([^=]+))?\\s*=\\s*(?:async\\s+)?(?:\\((.*?)\\)|(\\w+))\\s*=>/,\n );\n if (exportConst) {\n exports.push({\n kind: 'arrow_function',\n name: exportConst[1],\n signature: `const ${exportConst[1]}: (${exportConst[3] || exportConst[4] || ''}) => ...`,\n line: idx + 1,\n });\n }\n\n const exportClass = trimmed.match(\n /^export\\s+(?:default\\s+)?class\\s+(\\w+)(?:\\s+extends\\s+(\\w+))?/,\n );\n if (exportClass) {\n exports.push({\n kind: 'class',\n name: exportClass[1],\n signature: `class ${exportClass[1]}${exportClass[2] ? ' extends ' + exportClass[2] : ''}`,\n line: idx + 1,\n });\n }\n\n // Types & Interfaces\n const exportType = trimmed.match(/^export\\s+type\\s+(\\w+)(?:<.*?>)?\\s*=/);\n if (exportType) {\n types.push({\n kind: 'type',\n name: exportType[1],\n signature: trimmed.replace(/;?$/, ''),\n line: idx + 1,\n });\n }\n\n const exportInterface = trimmed.match(\n /^export\\s+interface\\s+(\\w+)(?:<.*?>)?(?:\\s+extends\\s+.*?)?\\s*\\{?/,\n );\n if (exportInterface) {\n types.push({\n kind: 'interface',\n name: exportInterface[1],\n signature: trimmed.replace(/\\{?$/, '').trim(),\n line: idx + 1,\n });\n }\n });\n } else if (ext === '.rs') {\n lines.forEach((line, idx) => {\n const trimmed = line.trim();\n\n // Use statements\n const useMatch = trimmed.match(/^(?:pub\\s+)?use\\s+([^;]+);/);\n if (useMatch) {\n imports.push({\n source: useMatch[1].trim(),\n specifiers: useMatch[1].trim(),\n line: idx + 1,\n });\n }\n\n // Public Functions\n const pubFn = trimmed.match(\n /^pub(?:\\(.*?\\))?\\s+(?:async\\s+)?fn\\s+(\\w+)(?:<.*?>)?\\s*(\\(.*?\\))(?:\\s*->\\s*([^{;]+))?/,\n );\n if (pubFn) {\n exports.push({\n kind: 'function',\n name: pubFn[1],\n signature: `pub fn ${pubFn[1]}${pubFn[2]}${pubFn[3] ? ' -> ' + pubFn[3].trim() : ''}`,\n line: idx + 1,\n });\n }\n\n // Structs & Enums\n const pubStruct = trimmed.match(/^pub(?:\\(.*?\\))?\\s+struct\\s+(\\w+)/);\n if (pubStruct) {\n types.push({\n kind: 'struct',\n name: pubStruct[1],\n signature: `pub struct ${pubStruct[1]}`,\n line: idx + 1,\n });\n }\n\n const pubEnum = trimmed.match(/^pub(?:\\(.*?\\))?\\s+enum\\s+(\\w+)/);\n if (pubEnum) {\n types.push({\n kind: 'enum',\n name: pubEnum[1],\n signature: `pub enum ${pubEnum[1]}`,\n line: idx + 1,\n });\n }\n\n const pubTrait = trimmed.match(/^pub(?:\\(.*?\\))?\\s+trait\\s+(\\w+)/);\n if (pubTrait) {\n types.push({\n kind: 'trait',\n name: pubTrait[1],\n signature: `pub trait ${pubTrait[1]}`,\n line: idx + 1,\n });\n }\n });\n } else if (ext === '.py') {\n lines.forEach((line, idx) => {\n const trimmed = line.trim();\n\n const importMatch = trimmed.match(/^(?:from\\s+([\\w.]+)\\s+)?import\\s+(.+)$/);\n if (importMatch) {\n imports.push({\n source: importMatch[1] || importMatch[2],\n specifiers: importMatch[2],\n line: idx + 1,\n });\n }\n\n const defMatch = trimmed.match(\n /^(?:async\\s+)?def\\s+([a-zA-Z_]\\w*)\\s*(\\(.*?\\))(?:\\s*->\\s*([^:]+))?:/,\n );\n if (defMatch && !defMatch[1].startsWith('_')) {\n exports.push({\n kind: 'function',\n name: defMatch[1],\n signature: `def ${defMatch[1]}${defMatch[2]}${defMatch[3] ? ' -> ' + defMatch[3].trim() : ''}`,\n line: idx + 1,\n });\n }\n\n const classMatch = trimmed.match(/^class\\s+([a-zA-Z_]\\w*)(?:\\((.*?)\\))?:/);\n if (classMatch && !classMatch[1].startsWith('_')) {\n types.push({\n kind: 'class',\n name: classMatch[1],\n signature: `class ${classMatch[1]}${classMatch[2] ? '(' + classMatch[2] + ')' : ''}`,\n line: idx + 1,\n });\n }\n });\n }\n\n const allSignatures = exports.concat(types);\n const interfaceHash = computeInterfaceHash(allSignatures);\n\n return {\n imports,\n exports,\n types,\n landmines,\n interfaceHash,\n };\n}\n\n// ── Inbound Callers Discovery ───────────────────────────────────────────────\n\nfunction findInboundCallers(targetFilePath, exportNames, workspaceRoot = process.cwd()) {\n const callers = [];\n const baseName = path.basename(targetFilePath);\n const stem = baseName.replace(/\\.[^.]+$/, '');\n const relativeTarget = path.relative(workspaceRoot, targetFilePath).replace(/\\\\/g, '/');\n\n // Search tokens: module stem and exported symbol names\n const searchTokens = new Set([stem]);\n exportNames.slice(0, 8).forEach(n => searchTokens.add(n));\n\n // Try using git grep or ripgrep if available\n const grepOutputs = [];\n try {\n for (const token of searchTokens) {\n if (!token || token.length < 3) continue;\n try {\n const cmd = `git grep -n -I \"${token}\" -- \":!docs/\" \":!node_modules/\" \":!dist/\" \":!target/\" \":!*.lock\"`;\n const res = execSync(cmd, {\n cwd: workspaceRoot,\n stdio: ['ignore', 'pipe', 'ignore'],\n encoding: 'utf8',\n });\n if (res) grepOutputs.push(...res.split('\\n').filter(Boolean));\n } catch {\n // Ripgrep fallback\n try {\n const cmd = `rg -n --no-heading --color=never \"${token}\" -g \"!docs/**\" -g \"!node_modules/**\" -g \"!target/**\" -g \"!dist/**\"`;\n const res = execSync(cmd, {\n cwd: workspaceRoot,\n stdio: ['ignore', 'pipe', 'ignore'],\n encoding: 'utf8',\n });\n if (res) grepOutputs.push(...res.split('\\n').filter(Boolean));\n } catch {\n // Silent catch\n }\n }\n }\n } catch {\n // Grep unavailable\n }\n\n const seenSites = new Set();\n\n for (const line of grepOutputs) {\n const parts = line.split(':');\n if (parts.length < 3) continue;\n const callerFile = parts[0].replace(/\\\\/g, '/');\n const lineNum = parseInt(parts[1], 10);\n const lineContent = parts.slice(2).join(':').trim();\n\n // Ignore self-references and context docs\n if (\n callerFile === relativeTarget ||\n callerFile.includes('.context.md') ||\n callerFile.includes('INDEX.md')\n ) {\n continue;\n }\n\n const key = `${callerFile}:${lineNum}`;\n if (seenSites.has(key)) continue;\n seenSites.add(key);\n\n callers.push({\n file: callerFile,\n line: lineNum,\n snippet: lineContent.substring(0, 100),\n isDirectImport:\n lineContent.includes('import') ||\n lineContent.includes('require') ||\n lineContent.includes('use '),\n });\n\n if (callers.length >= 12) break; // Cap callers for token efficiency\n }\n\n return callers;\n}\n\n// ── Test & Skill Discovery ──────────────────────────────────────────────────\n\nfunction discoverTests(targetFilePath, workspaceRoot = process.cwd()) {\n const tests = [];\n const baseName = path.basename(targetFilePath);\n const stem = baseName.replace(/\\.[^.]+$/, '');\n\n const testPatterns = [`${stem}.test.`, `${stem}.spec.`, `${stem}_test.`, `test_${stem}.`];\n\n function walk(dir) {\n if (!fs.existsSync(dir)) return;\n try {\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n if (\n entry.name === 'node_modules' ||\n entry.name === 'target' ||\n entry.name === '.git' ||\n entry.name === 'dist'\n ) {\n continue;\n }\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n // Only walk tests dirs or immediate directories\n if (\n entry.name === 'tests' ||\n entry.name === '__tests__' ||\n entry.name === 'test' ||\n entry.name === 'crates'\n ) {\n walk(full);\n }\n } else if (entry.isFile()) {\n for (const pat of testPatterns) {\n if (entry.name.includes(pat)) {\n tests.push(path.relative(workspaceRoot, full).replace(/\\\\/g, '/'));\n break;\n }\n }\n }\n }\n } catch {\n // Ignore read errors\n }\n }\n\n walk(workspaceRoot);\n return Array.from(new Set(tests)).slice(0, 5);\n}\n\nfunction resolveSkills(targetFilePath, content) {\n const skills = [];\n const ext = path.extname(targetFilePath).toLowerCase();\n const lowerContent = content.toLowerCase();\n\n if (ext === '.rs') skills.push('rust-pro');\n if (ext === '.py') skills.push('python-pro');\n if (ext === '.ts' || ext === '.tsx' || ext === '.js') {\n if (lowerContent.includes('react') || ext.endsWith('x')) skills.push('react-specialist');\n else skills.push('clean-code');\n }\n\n if (\n lowerContent.includes('auth') ||\n lowerContent.includes('jwt') ||\n lowerContent.includes('token') ||\n lowerContent.includes('crypto')\n ) {\n skills.push('backend-security-expert');\n }\n if (\n lowerContent.includes('query') ||\n lowerContent.includes('prisma') ||\n lowerContent.includes('sql') ||\n lowerContent.includes('database')\n ) {\n skills.push('database-architect');\n }\n if (\n lowerContent.includes('compress') ||\n lowerContent.includes('tokens') ||\n lowerContent.includes('prompt')\n ) {\n skills.push('context-engineering-pro');\n }\n\n skills.push('fabel-protocol');\n return Array.from(new Set(skills));\n}\n\nfunction resolvePath(targetPath, workspaceRoot = process.cwd()) {\n const clean = targetPath.replace(/^['\"]|['\"]$/g, '');\n if (path.isAbsolute(clean) && fs.existsSync(clean)) return clean;\n\n const direct = path.resolve(workspaceRoot, clean);\n if (fs.existsSync(direct)) return direct;\n\n if (clean.startsWith('tribunal-kit/') || clean.startsWith('tribunal-kit\\\\')) {\n const stripped = clean.replace(/^tribunal-kit[/\\\\]/, '');\n const strippedPath = path.resolve(workspaceRoot, stripped);\n if (fs.existsSync(strippedPath)) return strippedPath;\n }\n\n const parentPath = path.resolve(workspaceRoot, '..', clean);\n if (fs.existsSync(parentPath)) return parentPath;\n\n return direct;\n}\n\nfunction getDocsDir(workspaceRoot = process.cwd()) {\n const local = path.join(workspaceRoot, 'docs', 'context');\n if (fs.existsSync(local)) {\n try {\n const files = fs\n .readdirSync(local)\n .filter(f => f.endsWith('.context.md') || f.endsWith('.bridge.md'));\n if (files.length > 0) return local;\n } catch {\n // fallback\n }\n }\n const parent = path.join(workspaceRoot, '..', 'docs', 'context');\n if (fs.existsSync(parent)) {\n try {\n const files = fs\n .readdirSync(parent)\n .filter(f => f.endsWith('.context.md') || f.endsWith('.bridge.md'));\n if (files.length > 0) return parent;\n } catch {\n // fallback\n }\n }\n return local;\n}\n\n// ── Single-File Context Analysis ────────────────────────────────────────────\n\nfunction analyzeSingleFile(targetPath, workspaceRoot = process.cwd()) {\n const absPath = resolvePath(targetPath, workspaceRoot);\n if (!fs.existsSync(absPath)) {\n throw new Error(`File not found: ${absPath}`);\n }\n\n const rawContent = fs.readFileSync(absPath, 'utf8');\n const relativePath = path.relative(workspaceRoot, absPath).replace(/\\\\/g, '/');\n const sourceHash = computeSha256(rawContent);\n const skeleton = extractFileSkeleton(relativePath, rawContent);\n const exportNames = skeleton.exports.map(e => e.name).concat(skeleton.types.map(t => t.name));\n const callers = findInboundCallers(absPath, exportNames, workspaceRoot);\n const tests = discoverTests(absPath, workspaceRoot);\n const skills = resolveSkills(relativePath, rawContent);\n\n // Determine domain layer\n let domainLayer = 'Core Logic / Utility';\n if (relativePath.includes('api') || relativePath.includes('route'))\n domainLayer = 'API / Gateway Layer';\n else if (relativePath.includes('service')) domainLayer = 'Service / Business Logic';\n else if (\n relativePath.includes('model') ||\n relativePath.includes('schema') ||\n relativePath.includes('db')\n )\n domainLayer = 'Data / Persistence Layer';\n else if (relativePath.includes('components') || relativePath.includes('ui'))\n domainLayer = 'UI / Presentation Layer';\n else if (relativePath.includes('commands')) domainLayer = 'Command / Dispatch Layer';\n\n return {\n mode: 'single_file',\n filePath: relativePath,\n sourceHash,\n interfaceHash: skeleton.interfaceHash,\n domainLayer,\n imports: skeleton.imports,\n exports: skeleton.exports,\n types: skeleton.types,\n landmines: skeleton.landmines,\n callers,\n tests,\n skills,\n lineCount: rawContent.split('\\n').length,\n byteSize: Buffer.byteLength(rawContent, 'utf8'),\n };\n}\n\n// ── Multi-File Interface Bridge Analysis ────────────────────────────────────\n\nfunction analyzeMultiFileBridge(pathA, pathB, workspaceRoot = process.cwd()) {\n const metaA = analyzeSingleFile(pathA, workspaceRoot);\n const metaB = analyzeSingleFile(pathB, workspaceRoot);\n\n const aImportsB = metaA.imports.some(imp =>\n imp.source.includes(path.basename(metaB.filePath).replace(/\\.[^.]+$/, '')),\n );\n const bImportsA = metaB.imports.some(imp =>\n imp.source.includes(path.basename(metaA.filePath).replace(/\\.[^.]+$/, '')),\n );\n\n const sharedTypes = [];\n const typeNamesA = new Set(metaA.types.map(t => t.name));\n for (const t of metaB.types) {\n if (typeNamesA.has(t.name)) sharedTypes.push(t.name);\n }\n\n return {\n mode: 'multi_file_bridge',\n fileA: metaA,\n fileB: metaB,\n coupling: {\n aImportsB,\n bImportsA,\n sharedTypes,\n relationship:\n aImportsB && bImportsA\n ? 'Bidirectional Coupling'\n : aImportsB\n ? 'A depends on B'\n : bImportsA\n ? 'B depends on A'\n : 'Sibling / Peer Modules',\n },\n };\n}\n\n// ── Directory / Project Subsystem Analysis ──────────────────────────────────\n\nfunction analyzeDirectory(dirPath, workspaceRoot = process.cwd()) {\n const absDir = path.isAbsolute(dirPath) ? dirPath : path.resolve(workspaceRoot, dirPath);\n if (!fs.existsSync(absDir) || !fs.statSync(absDir).isDirectory()) {\n throw new Error(`Directory not found: ${absDir}`);\n }\n\n const relativeDir = path.relative(workspaceRoot, absDir).replace(/\\\\/g, '/') || '.';\n const manifests = [];\n const subsystems = [];\n let totalFiles = 0;\n const langCounts = {};\n\n const ignoreSet = new Set([\n 'node_modules',\n 'target',\n '.git',\n 'dist',\n 'coverage',\n '.gemini',\n 'build',\n ]);\n\n // Check top-level manifests\n if (fs.existsSync(path.join(absDir, 'package.json'))) manifests.push('package.json');\n if (fs.existsSync(path.join(absDir, 'Cargo.toml'))) manifests.push('Cargo.toml');\n if (fs.existsSync(path.join(absDir, 'pyproject.toml'))) manifests.push('pyproject.toml');\n\n const entries = fs.readdirSync(absDir, { withFileTypes: true });\n\n for (const entry of entries) {\n if (ignoreSet.has(entry.name) || entry.name.startsWith('.')) continue;\n const subFull = path.join(absDir, entry.name);\n if (entry.isDirectory()) {\n try {\n const subFiles = fs.readdirSync(subFull);\n subsystems.push({\n name: entry.name,\n fileCount: subFiles.length,\n keySample: subFiles.slice(0, 3).join(', '),\n });\n } catch {\n // Ignore unreadable\n }\n } else if (entry.isFile()) {\n totalFiles++;\n const ext = path.extname(entry.name).toLowerCase() || 'other';\n langCounts[ext] = (langCounts[ext] || 0) + 1;\n }\n }\n\n return {\n mode: 'directory_subsystem',\n dirPath: relativeDir,\n manifests,\n subsystems,\n directFiles: totalFiles,\n langCounts,\n };\n}\n\n// ── Markdown Dossier Generators ─────────────────────────────────────────────\n\nfunction renderSingleFileDossier(data) {\n const callersTable =\n data.callers.length > 0\n ? data.callers\n .map(\n c =>\n `| \\`${c.file}:${c.line}\\` | \\`${c.snippet}\\` | ${c.isDirectImport ? 'Direct Import' : 'Symbol Reference'} |`,\n )\n .join('\\n')\n : '| *None detected (potential root entrypoint or test)* | - | - |';\n\n const typesTable =\n data.exports.concat(data.types).length > 0\n ? data.exports\n .concat(data.types)\n .slice(0, 10)\n .map(s => `| \\`${s.name}\\` | \\`${s.kind}\\` | \\`${s.signature}\\` | Line ${s.line} |`)\n .join('\\n')\n : '| *No explicit exported symbols detected* | - | - | - |';\n\n const landminesContent =\n data.landmines.length > 0\n ? data.landmines.map(l => `> [!CAUTION]\\n> **Line ${l.line}:** \\`${l.content}\\``).join('\\n\\n')\n : '> [!NOTE]\\n> No explicit defensive comments (`// VERIFY`, `// NOTE`, `// HACK`) found in source code.';\n\n const testCommand = data.tests.length > 0 ? `npm test -- ${data.tests[0]}` : `npm test`;\n\n return `---\nversion: 2.0.0\nsource_file: \"${data.filePath}\"\nsource_hash: \"${data.sourceHash}\"\ninterface_hash: \"${data.interfaceHash}\"\nlast_synced: \"${new Date().toISOString().split('T')[0]}\"\ndomain_layer: \"${data.domainLayer}\"\nassociated_skills:\n${data.skills.map(s => ` - ${s}`).join('\\n')}\nassociated_tests:\n${data.tests.length > 0 ? data.tests.map(t => ` - ${t}`).join('\\n') : ' - none'}\n---\n\n<!-- AI_QUICK_INJECT_START -->\n> [!TIP]\n> **AI Prompt Injection Card (Copy into future prompts touching this file):**\n> \\`\\`\\`yaml\n> Target: ${data.filePath} (${data.domainLayer})\n> Role: Core logic for ${path.basename(data.filePath)}.\n> Exports: [${data.exports\n .map(e => e.name)\n .slice(0, 6)\n .join(', ')}]\n> Inbound Callers: ${data.callers.length} active consumer sites.\n> Invariant Check: Verify test passing before merge: ${testCommand}\n> \\`\\`\\`\n<!-- AI_QUICK_INJECT_END -->\n\n# 🧭 FILE DOSSIER: \\`${path.basename(data.filePath)}\\`\n\\`${data.filePath}\\` • **${data.domainLayer}** • **Hash:** \\`${data.sourceHash}\\`\n\n| Freshness | Blast Radius | Exports Count | Test Coverage | Primary Callers |\n| :--- | :--- | :--- | :--- | :--- |\n| 🟢 **Fresh** (\\`${data.sourceHash}\\`) | **${data.callers.length} Callers** | **${data.exports.length} Symbols** | ${data.tests.length > 0 ? '✅ Linked (' + data.tests.length + ' files)' : '⚠️ Unlinked'} | \\`${data.callers[0] ? data.callers[0].file : 'Entrypoint'}\\` |\n\n---\n\n## ⚡ 30-Second Mental Model\n> **Mission:** Implements ${data.domainLayer.toLowerCase()} responsibilities for \\`${data.filePath}\\`, exposing verified interfaces to callers while adhering to Tribunal safety standards.\n\n---\n\n## 📋 Public API & Type Contract Matrix\n\n| Symbol | Kind | Signature | Location |\n| :--- | :--- | :--- | :--- |\n${typesTable}\n\n---\n\n## 🔗 Blast Radius & Call Topology\n\n\\`\\`\\`mermaid\ngraph LR\n classDef target fill:#1e293b,stroke:#3b82f6,stroke-width:2px,color:#fff;\n classDef ext fill:#0f172a,stroke:#64748b,stroke-width:1px,color:#94a3b8;\n\n subgraph Inbound Callers\n${\n data.callers\n .slice(0, 4)\n .map((c, i) => ` C${i}[\"${c.file}\"]:::ext`)\n .join('\\n') || ' C0[\"Entrypoint / CLI\"]:::ext'\n}\n end\n\n T[\"${path.basename(data.filePath)}\"]:::target\n\n subgraph Dependencies\n${\n data.imports\n .slice(0, 4)\n .map((imp, i) => ` D${i}[\"${imp.source}\"]:::ext`)\n .join('\\n') || ' D0[\"Stdlib\"]:::ext'\n}\n end\n\n${\n data.callers\n .slice(0, 4)\n .map((_, i) => ` C${i} --> T`)\n .join('\\n') || ' C0 --> T'\n}\n${\n data.imports\n .slice(0, 4)\n .map((_, i) => ` T --> D${i}`)\n .join('\\n') || ' T --> D0'\n}\n\\`\\`\\`\n\n### Inbound Consumer Sites\n| Caller File | Line Snippet | Vector |\n| :--- | :--- | :--- |\n${callersTable}\n\n---\n\n## ⚠️ Chesterton's Fences & Non-Obvious Quirks\n\n${landminesContent}\n\n---\n\n## 🧪 Verification & Test Harness\n\n\\`\\`\\`bash\n# Run isolated tests for this module:\n${testCommand}\n\\`\\`\\`\n`;\n}\n\nfunction renderBridgeDossier(data) {\n return `---\nversion: 2.0.0\nbridge: \"${data.fileA.filePath} <--> ${data.fileB.filePath}\"\nrelationship: \"${data.coupling.relationship}\"\nlast_synced: \"${new Date().toISOString().split('T')[0]}\"\n---\n\n# 🌉 INTERFACE BRIDGE DOSSIER\n**Module A:** \\`${data.fileA.filePath}\\` \n**Module B:** \\`${data.fileB.filePath}\\` \n**Coupling Relationship:** \\`${data.coupling.relationship}\\`\n\n---\n\n## 🗺️ Cross-Boundary Topology\n\n\\`\\`\\`mermaid\ngraph LR\n A[\"${path.basename(data.fileA.filePath)}\"]\n B[\"${path.basename(data.fileB.filePath)}\"]\n\n ${data.coupling.aImportsB ? 'A -->|\"Imports & Calls\"| B' : ''}\n ${data.coupling.bImportsA ? 'B -->|\"Imports & Calls\"| A' : ''}\n ${!data.coupling.aImportsB && !data.coupling.bImportsA ? 'A -.->|\"Sibling / Parallel\"| B' : ''}\n\\`\\`\\`\n\n## 📦 Shared Types & Interfaces\n${\n data.coupling.sharedTypes.length > 0\n ? data.coupling.sharedTypes.map(t => `- \\`${t}\\``).join('\\n')\n : '- *No identical type names detected between modules.*'\n}\n\n## 📋 Interface Alignment Summary\n- **${path.basename(data.fileA.filePath)} Exports:** ${data.fileA.exports.length} symbols.\n- **${path.basename(data.fileB.filePath)} Exports:** ${data.fileB.exports.length} symbols.\n`;\n}\n\nfunction renderDirectoryDossier(data) {\n return `---\nversion: 2.0.0\ntarget_dir: \"${data.dirPath}\"\nmanifests: [${data.manifests.join(', ')}]\nlast_synced: \"${new Date().toISOString().split('T')[0]}\"\n---\n\n<!-- PROJECT_AI_ONBOARDING_CARD -->\nProject Subsystem: ${data.dirPath}\nManifests: ${data.manifests.join(', ') || 'None'}\nSubsystems: ${data.subsystems.map(s => s.name).join(', ')}\n<!-- /PROJECT_AI_ONBOARDING_CARD -->\n\n# 🏛️ SUBSYSTEM DOSSIER: \\`${data.dirPath}\\`\n\n## 🗺️ Subsystem Architecture Clusters\n\\`\\`\\`mermaid\ngraph TD\n${data.subsystems.map(s => ` S_${s.name}[\"${s.name} (${s.fileCount} files)\"]`).join('\\n')}\n\\`\\`\\`\n\n## 📂 Subsystem Breakdown\n| Subsystem Folder | File Count | Samples |\n| :--- | :--- | :--- |\n${data.subsystems.map(s => `| \\`${s.name}/\\` | ${s.fileCount} | \\`${s.keySample}\\` |`).join('\\n')}\n`;\n}\n\n// ── Living Vault Manager ───────────────────────────────────────────────────\n\nfunction syncVaultIndex(workspaceRoot = process.cwd()) {\n const docsDir = getDocsDir(workspaceRoot);\n const indexFile = path.join(docsDir, 'INDEX.md');\n\n if (!fs.existsSync(docsDir)) {\n fs.mkdirSync(docsDir, { recursive: true });\n }\n\n const files = fs\n .readdirSync(docsDir)\n .filter(f => f.endsWith('.context.md') || f.endsWith('.bridge.md'));\n\n const rows = [];\n for (const f of files) {\n const content = fs.readFileSync(path.join(docsDir, f), 'utf8');\n const sourceMatch = content.match(/source_file:\\s*[\"']?([^\"'\\n]+)/);\n const bridgeMatch = content.match(/bridge:\\s*[\"']?([^\"'\\n]+)/);\n const dirMatch = content.match(/target_dir:\\s*[\"']?([^\"'\\n]+)/);\n const hashMatch = content.match(/source_hash:\\s*[\"']?([^\"'\\n]+)/);\n const domainMatch = content.match(/domain_layer:\\s*[\"']?([^\"'\\n]+)/);\n\n let source = f;\n let domain = 'General';\n const hash = hashMatch ? hashMatch[1] : 'n/a';\n let status = '🟢 Fresh';\n\n if (sourceMatch) {\n source = sourceMatch[1].replace(/[\"']/g, '');\n domain = domainMatch ? domainMatch[1].replace(/[\"']/g, '') : 'Single Module';\n const absSource = resolvePath(source, workspaceRoot);\n if (fs.existsSync(absSource)) {\n const curHash = computeSha256(fs.readFileSync(absSource, 'utf8'));\n if (curHash !== hash) {\n status = '🔴 Stale';\n }\n } else {\n status = '⚪ Missing';\n }\n } else if (bridgeMatch) {\n source = bridgeMatch[1].replace(/[\"']/g, '');\n domain = 'Interface Bridge';\n status = '🟢 Linked';\n } else if (dirMatch) {\n source = dirMatch[1].replace(/[\"']/g, '');\n domain = 'Subsystem Cluster';\n const absDir = resolvePath(source, workspaceRoot);\n status = fs.existsSync(absDir) ? '🟢 Active' : '⚪ Missing';\n }\n\n rows.push(`| [\\`${source}\\`](${f}) | ${domain} | \\`${hash}\\` | ${status} |`);\n }\n\n const indexContent = `# 📚 Codebase Context Vault Registry\n> Living architectural catalog generated and verified by \\`/context\\`.\n\n| Source Target | Domain Layer | Hash Snapshot | Status |\n| :--- | :--- | :--- | :--- |\n${rows.join('\\n') || '| *No context dossiers generated yet. Run `/context <file>` to begin.* | - | - | - |'}\n\n---\n*Run \\`node scripts/context_compiler.js --check\\` to audit context freshness across all files.*\n`;\n\n fs.writeFileSync(indexFile, indexContent, 'utf8');\n return { indexedCount: files.length, indexFile };\n}\n\nfunction checkDrift(workspaceRoot = process.cwd()) {\n const syncRes = syncVaultIndex(workspaceRoot);\n const content = fs.readFileSync(syncRes.indexFile, 'utf8');\n const staleCount = (content.match(/🔴 Stale/g) || []).length;\n const freshCount = (content.match(/🟢 Fresh/g) || []).length;\n\n return {\n total: syncRes.indexedCount,\n fresh: freshCount,\n stale: staleCount,\n isHealthy: staleCount === 0,\n };\n}\n\n// ── CLI Dispatcher ─────────────────────────────────────────────────────────\n\nfunction main() {\n const args = process.argv.slice(2);\n const workspaceRoot = process.cwd();\n\n if (args.includes('--check')) {\n const drift = checkDrift(workspaceRoot);\n console.log(`\\n${C.BOLD}═══ Context Vault Drift Audit ═══${C.RESET}`);\n console.log(`Total Dossiers: ${drift.total}`);\n console.log(`🟢 Fresh: ${drift.fresh}`);\n console.log(`🔴 Stale: ${drift.stale}`);\n console.log(\n `Status: ${drift.isHealthy ? C.GREEN + 'HEALTHY' : C.RED + 'DRIFT DETECTED'}${C.RESET}\\n`,\n );\n process.exit(drift.isHealthy ? 0 : 1);\n }\n\n let fileArg = null;\n let dirArg = null;\n let multiArgs = [];\n const writeFlag = args.includes('--write');\n const jsonFlag = args.includes('--json');\n\n for (let i = 0; i < args.length; i++) {\n if (args[i] === '--file' && args[i + 1]) {\n fileArg = args[++i];\n } else if (args[i] === '--dir' && args[i + 1]) {\n dirArg = args[++i];\n } else if (args[i] === '--multi' && args[i + 1] && args[i + 2]) {\n multiArgs = [args[++i], args[++i]];\n } else if (!args[i].startsWith('--')) {\n if (!fileArg && !dirArg) {\n // Autodetect positional arg\n const candidate = args[i].replace(/^['\"]|['\"]$/g, '');\n if (fs.existsSync(candidate)) {\n if (fs.statSync(candidate).isDirectory()) {\n dirArg = candidate;\n } else {\n fileArg = candidate;\n }\n }\n }\n }\n }\n\n if (multiArgs.length === 2) {\n const result = analyzeMultiFileBridge(multiArgs[0], multiArgs[1], workspaceRoot);\n if (jsonFlag) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n const md = renderBridgeDossier(result);\n if (writeFlag) {\n const outName = `${path.basename(multiArgs[0]).replace(/\\.[^.]+$/, '')}__${path.basename(multiArgs[1]).replace(/\\.[^.]+$/, '')}.bridge.md`;\n const dest = path.join(workspaceRoot, 'docs', 'context', outName);\n fs.mkdirSync(path.dirname(dest), { recursive: true });\n fs.writeFileSync(dest, md, 'utf8');\n syncVaultIndex(workspaceRoot);\n console.log(`${C.GREEN}✔ Bridge Dossier written to ${dest}${C.RESET}`);\n } else {\n console.log(md);\n }\n }\n } else if (dirArg) {\n const result = analyzeDirectory(dirArg, workspaceRoot);\n if (jsonFlag) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n const md = renderDirectoryDossier(result);\n if (writeFlag) {\n const outName = `${path.basename(dirArg)}.context.md`;\n const dest = path.join(workspaceRoot, 'docs', 'context', outName);\n fs.mkdirSync(path.dirname(dest), { recursive: true });\n fs.writeFileSync(dest, md, 'utf8');\n syncVaultIndex(workspaceRoot);\n console.log(`${C.GREEN}✔ Directory Dossier written to ${dest}${C.RESET}`);\n } else {\n console.log(md);\n }\n }\n } else if (fileArg) {\n const result = analyzeSingleFile(fileArg, workspaceRoot);\n if (jsonFlag) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n const md = renderSingleFileDossier(result);\n if (writeFlag) {\n const outName = `${path.basename(fileArg).replace(/\\.[^.]+$/, '')}.context.md`;\n const dest = path.join(workspaceRoot, 'docs', 'context', outName);\n fs.mkdirSync(path.dirname(dest), { recursive: true });\n fs.writeFileSync(dest, md, 'utf8');\n syncVaultIndex(workspaceRoot);\n console.log(`${C.GREEN}✔ Single-File Dossier written to ${dest}${C.RESET}`);\n } else {\n console.log(md);\n }\n }\n } else {\n console.error(\n `${C.RED}Error: Provide --file <path>, --dir <path>, --multi <fileA> <fileB>, or --check${C.RESET}`,\n );\n process.exit(1);\n }\n}\n\n// Export functions for in-process MCP server use\nmodule.exports = {\n analyzeSingleFile,\n analyzeMultiFileBridge,\n analyzeDirectory,\n renderSingleFileDossier,\n renderBridgeDossier,\n renderDirectoryDossier,\n syncVaultIndex,\n checkDrift,\n};\n\nif (require.main === module) {\n main();\n}\n"
17
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "file": "scripts/modernize_skills.js",
3
+ "riskScore": "Low",
4
+ "blastRadius": 0,
5
+ "imports": {
6
+ "fs": [],
7
+ "path": []
8
+ },
9
+ "dependents": [],
10
+ "content": "#!/usr/bin/env node\n/**\n * modernize_skills.js — Tribunal Kit Skill Modernizer & Schema Validator (v4.0.0)\n *\n * Scans, deduplicates, standardizes, and validates all SKILL.md files across:\n * - tribunal-kit/.agent/skills/\n * - .agent/skills/ (when --sync-to-root is passed)\n *\n * Usage:\n * node scripts/modernize_skills.js --validate\n * node scripts/modernize_skills.js --dry-run\n * node scripts/modernize_skills.js --fix\n * node scripts/modernize_skills.js --fix --sync-to-root\n */\n\nconst fs = require('fs');\nconst path = require('path');\n\nconst ROOT = path.resolve(__dirname, '..');\nconst SKILLS_DIR = path.join(ROOT, '.agent', 'skills');\nconst WORKSPACE_ROOT = path.resolve(ROOT, '..');\nconst ROOT_SKILLS_DIR = path.join(WORKSPACE_ROOT, '.agent', 'skills');\n\nconst ARGS = process.argv.slice(2);\nconst DRY_RUN = ARGS.includes('--dry-run');\nconst FIX = ARGS.includes('--fix');\nconst _VALIDATE = ARGS.includes('--validate') || (!DRY_RUN && !FIX);\nconst SYNC_TO_ROOT = ARGS.includes('--sync-to-root');\n\nconst CANONICAL_FOOTER = `---\n\n## 🏛️ Tribunal Verification & Guardrails\n\n**Slash command: \\`/review\\` or \\`/tribunal-full\\`**\n**Active reviewers: \\`logic-reviewer\\` · \\`security-auditor\\`**\n\n### ❌ Forbidden AI Tropes\n1. **Blind Assumptions:** Never make an assumption without documenting it clearly with \\`// VERIFY: [reason]\\`.\n2. **Silent Degradation:** Catching and suppressing errors without logging or handling.\n3. **Context Amnesia:** Forgetting the user's constraints and offering generic advice instead of tailored solutions.\n\n### ✅ Pre-Flight Self-Audit\n\\`\\`\\`\n✅ Did I rely ONLY on real, verified tools and methods?\n✅ Is this solution appropriately scoped to the user's constraints?\n✅ Did I handle potential failure modes and edge cases?\n✅ Have I avoided generic boilerplate that doesn't add value?\n\\`\\`\\`\n\n### 🛑 Verification-Before-Completion (VBC) Protocol\n**CRITICAL:** You must follow a strict \"evidence-based closeout\" state machine.\n- ❌ **Forbidden:** Declaring a task complete because the output \"looks correct.\"\n- ✅ **Required:** You are explicitly forbidden from finalizing any task without providing **concrete evidence** (terminal output, passing tests, compile success, or equivalent proof) that your output works as intended.\n`;\n\nfunction parseFrontmatter(content) {\n if (!content.startsWith('---')) return { frontmatter: null, body: content };\n const endIdx = content.indexOf('\\n---', 3);\n if (endIdx === -1) return { frontmatter: null, body: content };\n\n const rawYaml = content.slice(4, endIdx).trim();\n const body = content.slice(endIdx + 4).trim();\n const meta = {};\n\n const lines = rawYaml.split('\\n');\n let currentKey = null;\n let isList = false;\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) continue;\n\n const match = line.match(/^([a-zA-Z0-9_-]+):\\s*(.*)$/);\n if (match) {\n currentKey = match[1];\n const val = match[2].trim();\n if (!val) {\n meta[currentKey] = [];\n isList = true;\n } else {\n meta[currentKey] = val;\n isList = false;\n }\n } else if (isList && trimmed.startsWith('-')) {\n const item = trimmed\n .slice(1)\n .trim()\n .replace(/^['\"]|['\"]$/g, '');\n if (Array.isArray(meta[currentKey])) {\n meta[currentKey].push(item);\n }\n }\n }\n\n return { frontmatter: rawYaml, meta, body };\n}\n\nfunction deduplicateAndCleanBody(body, skillName, description) {\n let cleaned = body;\n\n // 1. Remove duplicate top-level headers if repeated identical lines\n const titleMatch = cleaned.match(/^#\\s+(.+)$/m);\n if (titleMatch) {\n const title = titleMatch[1].trim();\n const titleRegex = new RegExp(`(^|\\\\n)#\\\\s+${escapeRegex(title)}(\\\\r?\\\\n)+`, 'g');\n let first = true;\n cleaned = cleaned.replace(titleRegex, (match, prefix) => {\n if (first) {\n first = false;\n return match;\n }\n return prefix;\n });\n }\n\n // 2. Strip existing canonical footer if present to ensure idempotency\n const existingFooterIdx = cleaned.indexOf('## 🏛️ Tribunal Verification & Guardrails');\n if (existingFooterIdx !== -1) {\n cleaned = cleaned.slice(0, existingFooterIdx).trim();\n }\n\n // Cut off legacy trailing guardrail stacks\n const footerMarkerRegex =\n /\\n---\\s*\\n+(\\*\\*Slash command: `\\/review`|## 🤖 LLM-Specific Traps|## 🏛️ Tribunal Integration|### ❌ Forbidden AI Tropes|## Pre-Flight Checklist|## VBC Protocol)[\\s\\S]*$/;\n cleaned = cleaned.replace(footerMarkerRegex, '').trim();\n\n // Remove any remaining isolated duplicate VBC blocks (H2 or H3)\n const isolatedVbcRegex =\n /(##|###)\\s+🛑?\\s*Verification-Before-Completion \\(VBC\\) Protocol[\\s\\S]*?(?=\\n## |\\n---|\\n# |$)/g;\n cleaned = cleaned.replace(isolatedVbcRegex, '');\n\n // Remove trailing horizontal rules or whitespace\n cleaned = cleaned.replace(/(\\n---\\s*)+$/, '').trim();\n\n // 3. Ensure Activation Boundaries section exists near the top\n if (!cleaned.includes('Activation Boundaries') && !cleaned.includes('Activate when:')) {\n const activationBlock = `\\n\\n## Activation Boundaries\\n\\n- **Activate when:** Operating in tasks requiring ${description || skillName}.\\n- **DO NOT activate when:** The task falls strictly outside ${skillName} domain or belongs to a different dedicated specialist.\\n`;\n\n if (cleaned.includes('## Mandatory Pre-Flight Context Inspection')) {\n cleaned = cleaned.replace(\n /(## Mandatory Pre-Flight Context Inspection[\\s\\S]*?(?=\\n## |\\n# |\\n---|$))/,\n `$1${activationBlock}`,\n );\n } else {\n cleaned = cleaned.replace(/^(#[^\\n]+\\n+)/, `$1${activationBlock}\\n`);\n }\n }\n\n // 4. Append single Canonical Footer\n cleaned = `${cleaned}\\n\\n${CANONICAL_FOOTER}`;\n\n return cleaned.trim();\n}\n\nfunction escapeRegex(string) {\n return string.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction processSkill(skillDirName) {\n const skillFile = path.join(SKILLS_DIR, skillDirName, 'SKILL.md');\n if (!fs.existsSync(skillFile)) return null;\n\n const originalContent = fs.readFileSync(skillFile, 'utf8');\n const { frontmatter, meta, body } = parseFrontmatter(originalContent);\n\n if (!frontmatter) {\n return { name: skillDirName, error: 'Missing frontmatter' };\n }\n\n const desc = meta ? meta.description || '' : '';\n const newBody = deduplicateAndCleanBody(body, skillDirName, desc);\n\n // Rebuild frontmatter with version: 4.0.0 and canonical scripts-binding\n let updatedFrontmatter = frontmatter\n .replace(/^version:\\s*.*$/m, 'version: 4.0.0')\n .replace(/^last-updated:\\s*.*$/m, 'last-updated: 2026-09-07');\n\n if (!updatedFrontmatter.includes('version:')) {\n updatedFrontmatter += '\\nversion: 4.0.0';\n }\n if (!updatedFrontmatter.includes('scripts-binding:')) {\n updatedFrontmatter +=\n '\\nscripts-binding:\\n - .agent/scripts/lint_runner.js\\n - .agent/scripts/verify_all.js';\n }\n\n const newContent = `---\\n${updatedFrontmatter.trim()}\\n---\\n\\n${newBody}\\n`;\n\n const vbcMatches = (newContent.match(/Verification-Before-Completion \\(VBC\\) Protocol/g) || [])\n .length;\n const trapsMatches = (newContent.match(/LLM-Specific Traps/g) || []).length;\n const isDuplicated = vbcMatches > 1 || trapsMatches > 1;\n\n const modified = newContent !== originalContent;\n\n if (modified && FIX) {\n fs.writeFileSync(skillFile, newContent, 'utf8');\n if (SYNC_TO_ROOT && fs.existsSync(ROOT_SKILLS_DIR)) {\n const rootSkillDir = path.join(ROOT_SKILLS_DIR, skillDirName);\n if (!fs.existsSync(rootSkillDir)) fs.mkdirSync(rootSkillDir, { recursive: true });\n fs.writeFileSync(path.join(rootSkillDir, 'SKILL.md'), newContent, 'utf8');\n }\n }\n\n return {\n name: skillDirName,\n isDuplicated,\n modified,\n vbcMatches,\n trapsMatches,\n };\n}\n\nfunction main() {\n console.log(`━━━ Tribunal Kit Skill Modernizer ━━━━━━━━━━━━━━━━━━━━━`);\n console.log(`Target: ${SKILLS_DIR}`);\n console.log(\n `Mode: ${FIX ? 'FIX (Overwriting files)' : DRY_RUN ? 'DRY-RUN (Simulated)' : 'VALIDATE (Read-only)'}`,\n );\n if (SYNC_TO_ROOT) console.log(`Sync: Enabled -> ${ROOT_SKILLS_DIR}`);\n console.log();\n\n const skillDirs = fs.readdirSync(SKILLS_DIR).filter(d => {\n return fs.statSync(path.join(SKILLS_DIR, d)).isDirectory();\n });\n\n let totalSkills = 0;\n let totalDuplicated = 0;\n let totalModified = 0;\n const errors = [];\n\n for (const dir of skillDirs) {\n totalSkills++;\n const res = processSkill(dir);\n if (!res) continue;\n if (res.error) {\n errors.push(`${dir}: ${res.error}`);\n continue;\n }\n if (res.isDuplicated) {\n totalDuplicated++;\n }\n if (res.modified) {\n totalModified++;\n }\n }\n\n console.log(`📊 Summary:`);\n console.log(` Total Skills Analyzed: ${totalSkills}`);\n console.log(` Skills with Remaining Duplications: ${totalDuplicated}`);\n console.log(` Skills Needing Modification: ${totalModified}`);\n console.log(` Errors: ${errors.length}`);\n\n if (errors.length > 0) {\n console.log(`\\n❌ Errors encountered:`);\n errors.forEach(e => console.log(` - ${e}`));\n }\n\n console.log();\n if (!FIX && totalModified > 0) {\n console.log(\n `💡 Run with --fix to apply cleanups and V4 schema across all ${totalModified} skills.`,\n );\n } else if (FIX) {\n console.log(`✅ Successfully modernized and deduplicated skills to V4 schema!`);\n }\n}\n\nmain();\n"
11
+ }