@cstack-protocol/pingala 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (328) hide show
  1. package/.agent/CSD.md +39 -0
  2. package/.agent/MANIFEST.md +4 -0
  3. package/.agent/MANIFEST.md.template +4 -0
  4. package/.agent/agent-contractor.md +45 -0
  5. package/.agent/architecture/consent-model-fsm.md +77 -0
  6. package/.agent/architecture/governor-maturity-fsm.md +101 -0
  7. package/.agent/architecture/governor-validation-fsm.md +106 -0
  8. package/.agent/architecture/humanized-audit-fsm.md +76 -0
  9. package/.agent/architecture/pingala-csi-fsm.md +81 -0
  10. package/.agent/architecture.md +34 -0
  11. package/.agent/behavior.md +29 -0
  12. package/.agent/compute.md +32 -0
  13. package/.agent/consent-prompts.md +41 -0
  14. package/.agent/governance.yaml +5 -0
  15. package/.agent/identity.md +29 -0
  16. package/.agent/knowledge-lattice.json +96 -0
  17. package/.agent/knowledge-lattice.md +53 -0
  18. package/.agent/lattice-viz.html +157 -0
  19. package/.agent/mission.md +37 -0
  20. package/.agent/pairing-protocol.md +89 -0
  21. package/.agent/pairing.csp +108 -0
  22. package/.agent/personas/reflective-operator.md +67 -0
  23. package/.agent/personas/research.md +62 -0
  24. package/.agent/pingala.md +47 -0
  25. package/.agent/roadmap.md +56 -0
  26. package/.agent/scripts/lattice-extract.py +100 -0
  27. package/.agent/scripts/sync-agents.sh +82 -0
  28. package/.agent/scripts/vault-ingest.py +80 -0
  29. package/.agent/seo-strategy.md +71 -0
  30. package/.agent/skills/agent-orchestrator/SKILL.md +22 -0
  31. package/.agent/skills/agent-orchestrator/scripts/sync-agents.sh +61 -0
  32. package/.agent/skills/knowledge-lattice/SKILL.md +23 -0
  33. package/.agent/skills/knowledge-lattice/scripts/lattice-extract.py +107 -0
  34. package/.agent/skills/resource-vault/SKILL.md +30 -0
  35. package/.agent/skills/resource-vault/scripts/vault-ingest.py +80 -0
  36. package/.agent/skills/sites-integrity/SKILL.md +28 -0
  37. package/.agent/skills/stack-auditor/SKILL.md +25 -0
  38. package/.agent/sources.md +20 -0
  39. package/.agent/stack-auditor.md +47 -0
  40. package/.agent/standards.md +36 -0
  41. package/.agent/strategy.md +65 -0
  42. package/.agent/vault-schema.md +53 -0
  43. package/.agent/voice.md +27 -0
  44. package/.agent/workflows/sync-agents.md +14 -0
  45. package/.env.example +5 -0
  46. package/.env.production +3 -0
  47. package/DISTRIBUTION-PLAN.md +33 -0
  48. package/HOSTED_SETUP.md +54 -0
  49. package/LANDING_PAGE_DESIGN.md +46 -0
  50. package/MANUAL_VERCEL_STEPS.md +39 -0
  51. package/PRODUCT-ROADMAP.md +241 -0
  52. package/PROVISIONING_GUIDE.md +39 -0
  53. package/README.md +38 -0
  54. package/ROADMAP.md +21 -0
  55. package/SYNC-ENGINE-SPEC.md +257 -0
  56. package/build/core/531-protocol.d.ts +26 -0
  57. package/build/core/531-protocol.js +87 -0
  58. package/build/core/531-protocol.js.map +1 -0
  59. package/build/core/531-rule.d.ts +26 -0
  60. package/build/core/531-rule.js +106 -0
  61. package/build/core/531-rule.js.map +1 -0
  62. package/build/core/auth.d.ts +1 -0
  63. package/build/core/auth.js +24 -0
  64. package/build/core/auth.js.map +1 -0
  65. package/build/core/consent-manager.d.ts +17 -0
  66. package/build/core/consent-manager.js +104 -0
  67. package/build/core/consent-manager.js.map +1 -0
  68. package/build/core/csp.d.ts +12 -0
  69. package/build/core/csp.js +20 -0
  70. package/build/core/csp.js.map +1 -0
  71. package/build/core/engagement-analyzer.d.ts +42 -0
  72. package/build/core/engagement-analyzer.js +71 -0
  73. package/build/core/engagement-analyzer.js.map +1 -0
  74. package/build/core/governor.d.ts +106 -0
  75. package/build/core/governor.js +405 -0
  76. package/build/core/governor.js.map +1 -0
  77. package/build/core/life-area-mapper.d.ts +39 -0
  78. package/build/core/life-area-mapper.js +73 -0
  79. package/build/core/life-area-mapper.js.map +1 -0
  80. package/build/core/methodology.d.ts +39 -0
  81. package/build/core/methodology.js +164 -0
  82. package/build/core/methodology.js.map +1 -0
  83. package/build/core/pingala.d.ts +31 -0
  84. package/build/core/pingala.js +56 -0
  85. package/build/core/pingala.js.map +1 -0
  86. package/build/core/sdk-adapter.d.ts +6 -0
  87. package/build/core/sdk-adapter.js +33 -0
  88. package/build/core/sdk-adapter.js.map +1 -0
  89. package/build/cs-agent-core/sdk/index.d.ts +6 -0
  90. package/build/cs-agent-core/sdk/index.js +18 -0
  91. package/build/cs-agent-core/sdk/index.js.map +1 -0
  92. package/build/cs-agent-core/sdk/patterns/index.d.ts +3 -0
  93. package/build/cs-agent-core/sdk/patterns/index.js +37 -0
  94. package/build/cs-agent-core/sdk/patterns/index.js.map +1 -0
  95. package/build/cs-agent-core/sdk/patterns/registry.d.ts +4 -0
  96. package/build/cs-agent-core/sdk/patterns/registry.js +80 -0
  97. package/build/cs-agent-core/sdk/patterns/registry.js.map +1 -0
  98. package/build/cs-agent-core/sdk/telemetry/buffer.d.ts +9 -0
  99. package/build/cs-agent-core/sdk/telemetry/buffer.js +47 -0
  100. package/build/cs-agent-core/sdk/telemetry/buffer.js.map +1 -0
  101. package/build/cs-agent-core/sdk/telemetry/scrubber.d.ts +3 -0
  102. package/build/cs-agent-core/sdk/telemetry/scrubber.js +13 -0
  103. package/build/cs-agent-core/sdk/telemetry/scrubber.js.map +1 -0
  104. package/build/cs-agent-core/sdk/telemetry/types.d.ts +50 -0
  105. package/build/cs-agent-core/sdk/telemetry/types.js +2 -0
  106. package/build/cs-agent-core/sdk/telemetry/types.js.map +1 -0
  107. package/build/cs-agent-core/sdk/types/decision.d.ts +18 -0
  108. package/build/cs-agent-core/sdk/types/decision.js +2 -0
  109. package/build/cs-agent-core/sdk/types/decision.js.map +1 -0
  110. package/build/cs-agent-core/sdk/types/index.d.ts +4 -0
  111. package/build/cs-agent-core/sdk/types/index.js +5 -0
  112. package/build/cs-agent-core/sdk/types/index.js.map +1 -0
  113. package/build/cs-agent-core/sdk/types/pattern.d.ts +17 -0
  114. package/build/cs-agent-core/sdk/types/pattern.js +2 -0
  115. package/build/cs-agent-core/sdk/types/pattern.js.map +1 -0
  116. package/build/cs-agent-core/sdk/types/stack.d.ts +8 -0
  117. package/build/cs-agent-core/sdk/types/stack.js +2 -0
  118. package/build/cs-agent-core/sdk/types/stack.js.map +1 -0
  119. package/build/cs-agent-core/sdk/types/tool.d.ts +9 -0
  120. package/build/cs-agent-core/sdk/types/tool.js +2 -0
  121. package/build/cs-agent-core/sdk/types/tool.js.map +1 -0
  122. package/build/cs-agent-core/sdk/validator/csi.d.ts +2 -0
  123. package/build/cs-agent-core/sdk/validator/csi.js +24 -0
  124. package/build/cs-agent-core/sdk/validator/csi.js.map +1 -0
  125. package/build/cs-agent-core/sdk/validator/index.d.ts +2 -0
  126. package/build/cs-agent-core/sdk/validator/index.js +3 -0
  127. package/build/cs-agent-core/sdk/validator/index.js.map +1 -0
  128. package/build/cs-agent-core/sdk/validator/rules/geometry.d.ts +11 -0
  129. package/build/cs-agent-core/sdk/validator/rules/geometry.js +22 -0
  130. package/build/cs-agent-core/sdk/validator/rules/geometry.js.map +1 -0
  131. package/build/cs-agent-core/sdk/validator/validate.d.ts +2 -0
  132. package/build/cs-agent-core/sdk/validator/validate.js +46 -0
  133. package/build/cs-agent-core/sdk/validator/validate.js.map +1 -0
  134. package/build/index.d.ts +2 -0
  135. package/build/index.js +444 -0
  136. package/build/index.js.map +1 -0
  137. package/build/pingala-mcp/src/core/531-rule.d.ts +26 -0
  138. package/build/pingala-mcp/src/core/531-rule.js +96 -0
  139. package/build/pingala-mcp/src/core/531-rule.js.map +1 -0
  140. package/build/pingala-mcp/src/core/auth.d.ts +1 -0
  141. package/build/pingala-mcp/src/core/auth.js +15 -0
  142. package/build/pingala-mcp/src/core/auth.js.map +1 -0
  143. package/build/pingala-mcp/src/core/consent-manager.d.ts +17 -0
  144. package/build/pingala-mcp/src/core/consent-manager.js +104 -0
  145. package/build/pingala-mcp/src/core/consent-manager.js.map +1 -0
  146. package/build/pingala-mcp/src/core/csp.d.ts +12 -0
  147. package/build/pingala-mcp/src/core/csp.js +20 -0
  148. package/build/pingala-mcp/src/core/csp.js.map +1 -0
  149. package/build/pingala-mcp/src/core/engagement-analyzer.d.ts +42 -0
  150. package/build/pingala-mcp/src/core/engagement-analyzer.js +71 -0
  151. package/build/pingala-mcp/src/core/engagement-analyzer.js.map +1 -0
  152. package/build/pingala-mcp/src/core/governor.d.ts +104 -0
  153. package/build/pingala-mcp/src/core/governor.js +359 -0
  154. package/build/pingala-mcp/src/core/governor.js.map +1 -0
  155. package/build/pingala-mcp/src/core/life-area-mapper.d.ts +39 -0
  156. package/build/pingala-mcp/src/core/life-area-mapper.js +73 -0
  157. package/build/pingala-mcp/src/core/life-area-mapper.js.map +1 -0
  158. package/build/pingala-mcp/src/core/methodology.d.ts +39 -0
  159. package/build/pingala-mcp/src/core/methodology.js +164 -0
  160. package/build/pingala-mcp/src/core/methodology.js.map +1 -0
  161. package/build/pingala-mcp/src/core/pingala.d.ts +25 -0
  162. package/build/pingala-mcp/src/core/pingala.js +56 -0
  163. package/build/pingala-mcp/src/core/pingala.js.map +1 -0
  164. package/build/pingala-mcp/src/core/sdk-adapter.d.ts +6 -0
  165. package/build/pingala-mcp/src/core/sdk-adapter.js +33 -0
  166. package/build/pingala-mcp/src/core/sdk-adapter.js.map +1 -0
  167. package/build/pingala-mcp/src/index.d.ts +1 -0
  168. package/build/pingala-mcp/src/index.js +221 -0
  169. package/build/pingala-mcp/src/index.js.map +1 -0
  170. package/build/pingala-mcp/src/test-l3.d.ts +1 -0
  171. package/build/pingala-mcp/src/test-l3.js +35 -0
  172. package/build/pingala-mcp/src/test-l3.js.map +1 -0
  173. package/build/pingala-mcp/src/tools/audit-workspace.d.ts +16 -0
  174. package/build/pingala-mcp/src/tools/audit-workspace.js +39 -0
  175. package/build/pingala-mcp/src/tools/audit-workspace.js.map +1 -0
  176. package/build/pingala-mcp/src/tools/calculate-csi.d.ts +24 -0
  177. package/build/pingala-mcp/src/tools/calculate-csi.js +29 -0
  178. package/build/pingala-mcp/src/tools/calculate-csi.js.map +1 -0
  179. package/build/pingala-mcp/src/tools/cs-audit.d.ts +54 -0
  180. package/build/pingala-mcp/src/tools/cs-audit.js +310 -0
  181. package/build/pingala-mcp/src/tools/cs-audit.js.map +1 -0
  182. package/build/pingala-mcp/src/tools/get-governance-context.d.ts +11 -0
  183. package/build/pingala-mcp/src/tools/get-governance-context.js +16 -0
  184. package/build/pingala-mcp/src/tools/get-governance-context.js.map +1 -0
  185. package/build/pingala-mcp/src/tools/validate-stack-change.d.ts +41 -0
  186. package/build/pingala-mcp/src/tools/validate-stack-change.js +35 -0
  187. package/build/pingala-mcp/src/tools/validate-stack-change.js.map +1 -0
  188. package/build/sdk/index.d.ts +6 -0
  189. package/build/sdk/index.js +18 -0
  190. package/build/sdk/index.js.map +1 -0
  191. package/build/sdk/patterns/index.d.ts +3 -0
  192. package/build/sdk/patterns/index.js +37 -0
  193. package/build/sdk/patterns/index.js.map +1 -0
  194. package/build/sdk/patterns/registry.d.ts +4 -0
  195. package/build/sdk/patterns/registry.js +80 -0
  196. package/build/sdk/patterns/registry.js.map +1 -0
  197. package/build/sdk/telemetry/buffer.d.ts +9 -0
  198. package/build/sdk/telemetry/buffer.js +47 -0
  199. package/build/sdk/telemetry/buffer.js.map +1 -0
  200. package/build/sdk/telemetry/scrubber.d.ts +3 -0
  201. package/build/sdk/telemetry/scrubber.js +13 -0
  202. package/build/sdk/telemetry/scrubber.js.map +1 -0
  203. package/build/sdk/telemetry/types.d.ts +50 -0
  204. package/build/sdk/telemetry/types.js +2 -0
  205. package/build/sdk/telemetry/types.js.map +1 -0
  206. package/build/sdk/types/decision.d.ts +18 -0
  207. package/build/sdk/types/decision.js +2 -0
  208. package/build/sdk/types/decision.js.map +1 -0
  209. package/build/sdk/types/index.d.ts +4 -0
  210. package/build/sdk/types/index.js +5 -0
  211. package/build/sdk/types/index.js.map +1 -0
  212. package/build/sdk/types/pattern.d.ts +17 -0
  213. package/build/sdk/types/pattern.js +2 -0
  214. package/build/sdk/types/pattern.js.map +1 -0
  215. package/build/sdk/types/stack.d.ts +8 -0
  216. package/build/sdk/types/stack.js +2 -0
  217. package/build/sdk/types/stack.js.map +1 -0
  218. package/build/sdk/types/tool.d.ts +9 -0
  219. package/build/sdk/types/tool.js +2 -0
  220. package/build/sdk/types/tool.js.map +1 -0
  221. package/build/sdk/validator/csi.d.ts +2 -0
  222. package/build/sdk/validator/csi.js +24 -0
  223. package/build/sdk/validator/csi.js.map +1 -0
  224. package/build/sdk/validator/index.d.ts +2 -0
  225. package/build/sdk/validator/index.js +3 -0
  226. package/build/sdk/validator/index.js.map +1 -0
  227. package/build/sdk/validator/rules/geometry.d.ts +11 -0
  228. package/build/sdk/validator/rules/geometry.js +22 -0
  229. package/build/sdk/validator/rules/geometry.js.map +1 -0
  230. package/build/sdk/validator/validate.d.ts +2 -0
  231. package/build/sdk/validator/validate.js +46 -0
  232. package/build/sdk/validator/validate.js.map +1 -0
  233. package/build/src/core/531-rule.d.ts +26 -0
  234. package/build/src/core/531-rule.js +96 -0
  235. package/build/src/core/531-rule.js.map +1 -0
  236. package/build/src/core/auth.d.ts +1 -0
  237. package/build/src/core/auth.js +15 -0
  238. package/build/src/core/auth.js.map +1 -0
  239. package/build/src/core/consent-manager.d.ts +17 -0
  240. package/build/src/core/consent-manager.js +104 -0
  241. package/build/src/core/consent-manager.js.map +1 -0
  242. package/build/src/core/csp.d.ts +12 -0
  243. package/build/src/core/csp.js +20 -0
  244. package/build/src/core/csp.js.map +1 -0
  245. package/build/src/core/engagement-analyzer.d.ts +42 -0
  246. package/build/src/core/engagement-analyzer.js +71 -0
  247. package/build/src/core/engagement-analyzer.js.map +1 -0
  248. package/build/src/core/governor.d.ts +104 -0
  249. package/build/src/core/governor.js +371 -0
  250. package/build/src/core/governor.js.map +1 -0
  251. package/build/src/core/life-area-mapper.d.ts +39 -0
  252. package/build/src/core/life-area-mapper.js +73 -0
  253. package/build/src/core/life-area-mapper.js.map +1 -0
  254. package/build/src/core/methodology.d.ts +39 -0
  255. package/build/src/core/methodology.js +164 -0
  256. package/build/src/core/methodology.js.map +1 -0
  257. package/build/src/core/pingala.d.ts +25 -0
  258. package/build/src/core/pingala.js +56 -0
  259. package/build/src/core/pingala.js.map +1 -0
  260. package/build/src/core/sdk-adapter.d.ts +8 -0
  261. package/build/src/core/sdk-adapter.js +34 -0
  262. package/build/src/core/sdk-adapter.js.map +1 -0
  263. package/build/src/index.d.ts +2 -0
  264. package/build/src/index.js +333 -0
  265. package/build/src/index.js.map +1 -0
  266. package/build/src/test-l3.d.ts +1 -0
  267. package/build/src/test-l3.js +35 -0
  268. package/build/src/test-l3.js.map +1 -0
  269. package/build/src/tools/audit-workspace.d.ts +16 -0
  270. package/build/src/tools/audit-workspace.js +39 -0
  271. package/build/src/tools/audit-workspace.js.map +1 -0
  272. package/build/src/tools/calculate-csi.d.ts +24 -0
  273. package/build/src/tools/calculate-csi.js +29 -0
  274. package/build/src/tools/calculate-csi.js.map +1 -0
  275. package/build/src/tools/cs-audit.d.ts +54 -0
  276. package/build/src/tools/cs-audit.js +310 -0
  277. package/build/src/tools/cs-audit.js.map +1 -0
  278. package/build/src/tools/get-governance-context.d.ts +11 -0
  279. package/build/src/tools/get-governance-context.js +16 -0
  280. package/build/src/tools/get-governance-context.js.map +1 -0
  281. package/build/src/tools/validate-stack-change.d.ts +41 -0
  282. package/build/src/tools/validate-stack-change.js +35 -0
  283. package/build/src/tools/validate-stack-change.js.map +1 -0
  284. package/build/test-l3.d.ts +1 -0
  285. package/build/test-l3.js +35 -0
  286. package/build/test-l3.js.map +1 -0
  287. package/build/tools/analyze-stack.d.ts +40 -0
  288. package/build/tools/analyze-stack.js +121 -0
  289. package/build/tools/analyze-stack.js.map +1 -0
  290. package/build/tools/audit-workspace.d.ts +16 -0
  291. package/build/tools/audit-workspace.js +39 -0
  292. package/build/tools/audit-workspace.js.map +1 -0
  293. package/build/tools/calculate-csi.d.ts +26 -0
  294. package/build/tools/calculate-csi.js +30 -0
  295. package/build/tools/calculate-csi.js.map +1 -0
  296. package/build/tools/cs-audit.d.ts +43 -0
  297. package/build/tools/cs-audit.js +330 -0
  298. package/build/tools/cs-audit.js.map +1 -0
  299. package/build/tools/get-governance-context.d.ts +11 -0
  300. package/build/tools/get-governance-context.js +61 -0
  301. package/build/tools/get-governance-context.js.map +1 -0
  302. package/build/tools/validate-stack-change.d.ts +41 -0
  303. package/build/tools/validate-stack-change.js +54 -0
  304. package/build/tools/validate-stack-change.js.map +1 -0
  305. package/package.json +34 -0
  306. package/scripts/cloud-bridge.js +62 -0
  307. package/scripts/generate-token.js +13 -0
  308. package/src/core/531-rule.ts +148 -0
  309. package/src/core/auth.ts +42 -0
  310. package/src/core/consent-manager.ts +134 -0
  311. package/src/core/csp.ts +40 -0
  312. package/src/core/engagement-analyzer.ts +122 -0
  313. package/src/core/governor.ts +522 -0
  314. package/src/core/life-area-mapper.ts +138 -0
  315. package/src/core/methodology.ts +256 -0
  316. package/src/core/pingala.ts +77 -0
  317. package/src/core/sdk-adapter.ts +52 -0
  318. package/src/index.ts +562 -0
  319. package/src/test-l3.ts +45 -0
  320. package/src/tools/analyze-stack.ts +153 -0
  321. package/src/tools/audit-workspace.ts +50 -0
  322. package/src/tools/calculate-csi.ts +38 -0
  323. package/src/tools/cs-audit.ts +384 -0
  324. package/src/tools/get-governance-context.ts +69 -0
  325. package/src/tools/validate-stack-change.ts +71 -0
  326. package/src/types.d.ts +2 -0
  327. package/tsconfig.json +40 -0
  328. package/vercel.json +15 -0
@@ -0,0 +1,153 @@
1
+ import { z } from "zod";
2
+ import { PingalaEngine } from "../core/pingala.js";
3
+ import { MethodologyLoader } from "../core/methodology.js";
4
+ import { Governor } from "../core/governor.js";
5
+ import { Rule531, type ToolInstance } from "../core/531-rule.js";
6
+ import { EngagementAnalyzer, type ToolWithEngagement } from "../core/engagement-analyzer.js";
7
+ import { DiamondMapper } from "../core/life-area-mapper.js";
8
+ import { ConvexHttpClient } from "convex/browser";
9
+
10
+ // Hardcoded for now to unblock, but should be env var
11
+ const CONVEX_URL = process.env.CONVEX_URL || "https://impressive-hamster-318.convex.cloud";
12
+ const client = new ConvexHttpClient(CONVEX_URL);
13
+
14
+ // Minimal Protocol Schema: Only what is needed for 5:3:1 Validation
15
+ const ToolSchema = z.object({
16
+ name: z.string(),
17
+ role: z.enum(["Anchor", "Active", "Supporting"]),
18
+ // Optional enrichment data (passed through, not inferred)
19
+ category: z.string().optional(),
20
+ description: z.string().optional(),
21
+ context: z.string().optional(), // e.g. "mobile", "work-laptop"
22
+ functionId: z.string().optional(), // e.g. "browser", "email" - for clustering
23
+ // Hierarchical Metadata
24
+ is_parent: z.boolean().optional(),
25
+ is_substack: z.boolean().optional(),
26
+ parent_name: z.string().optional()
27
+ });
28
+
29
+ export const analyzeStackTool = {
30
+ name: "analyze_stack",
31
+ description: "Validates a tool stack against the 5:3:1 Clean Architecture Protocol. Requires a structured list of tools with assigned roles.",
32
+ schema: {
33
+ tools: z.array(ToolSchema).describe("List of tools to analyze. MINIMUM REQUIREMENT: { name, role } per tool."),
34
+ context: z.object({
35
+ user_intent: z.string().optional(),
36
+ attention_depth: z.number().min(0).max(100).optional(),
37
+ dependency_exposure: z.number().min(0).max(100).optional()
38
+ }).optional()
39
+ },
40
+ handler: async (args: {
41
+ tools: any[];
42
+ context?: {
43
+ user_intent?: string;
44
+ attention_depth?: number;
45
+ dependency_exposure?: number;
46
+ };
47
+ }) => {
48
+ // Direct Mapping: No inference, no aliases.
49
+ // We trust the LLM/User to provide the correct structure.
50
+ const toolList: any[] = args.tools.map(t => ({
51
+ name: t.name,
52
+ role: t.role,
53
+ category: t.category,
54
+ context: t.context,
55
+ functionId: t.functionId,
56
+ is_parent: t.is_parent,
57
+ is_substack: t.is_substack,
58
+ parent_name: t.parent_name
59
+ }));
60
+
61
+ // 1. Structural Audit (Stability Norms via API/Convex)
62
+ let validation;
63
+ let diffSource = "Local (Fallback)";
64
+
65
+ try {
66
+ // "stacks:validateAndStore"
67
+ const apiKey = process.env.CSTACK_API_KEY || "anonymous";
68
+
69
+ validation = await client.mutation("stacks:validateAndStore" as any, {
70
+ operatorHash: apiKey, // Using API Key as identity proxy for now
71
+ tools: toolList,
72
+ agentId: "Pingala-MCP-v1"
73
+ });
74
+ diffSource = "CSTACK API (Convex)";
75
+ } catch (e) {
76
+ console.error("API Validation Failed, falling back to local:", e);
77
+ validation = Rule531.validate({ tools: toolList });
78
+ }
79
+
80
+ // @ts-ignore - geometry is dynamically added
81
+ const { geometry } = validation;
82
+ const strain_signals = validation.violations;
83
+
84
+ // 2. Engagement & Fragmentation Analysis
85
+ const engagement = EngagementAnalyzer.classifyByEngagement(toolList as ToolWithEngagement[]);
86
+ const fragmentation = EngagementAnalyzer.detectFragmentation(toolList as ToolWithEngagement[]);
87
+
88
+ // 3. CSI Computation (Stateless)
89
+ const diagnosis = await PingalaEngine.diagnose({
90
+ tools: toolList,
91
+ scores: {
92
+ attention_depth: args.context?.attention_depth || 50,
93
+ dependency_exposure: args.context?.dependency_exposure || 50
94
+ }
95
+ });
96
+
97
+ // 4. Maturity Assessment
98
+ const context = Governor.getGovernanceContext();
99
+ const maturity = {
100
+ level: context.maturity_level,
101
+ name: context.maturity_name,
102
+ guidance: `Validated via ${diffSource}. Monitor your Strain Signals to maintain Crystalline Norms.`
103
+ };
104
+
105
+ // 5. Construct Consolidated Report
106
+ const report = {
107
+ type: "governance_report",
108
+ version: "0.5.0 (Stability Norms)",
109
+ timestamp: new Date().toISOString(),
110
+ csi_score: diagnosis.csi_score,
111
+ functional_geometry: {
112
+ // @ts-ignore
113
+ core: geometry.core,
114
+ // @ts-ignore
115
+ contexts: geometry.contexts,
116
+ slots: toolList.reduce((acc: any, tool) => {
117
+ const fid = tool.functionId || "Unclassified";
118
+ if (!acc[fid]) acc[fid] = { id: fid, primary_role: tool.role, nodes: [] };
119
+ acc[fid].nodes.push({
120
+ name: tool.name,
121
+ role: tool.role,
122
+ context: tool.context,
123
+ is_parent: tool.is_parent,
124
+ is_substack: tool.is_substack,
125
+ parent_name: tool.parent_name
126
+ });
127
+ return acc;
128
+ }, {})
129
+ },
130
+ audit_result: {
131
+ isValid: validation.isValid && fragmentation.length === 0,
132
+ strain_signals,
133
+ recommendations: [
134
+ strain_signals.length > 0 ? "Strain detected. Adjust stack to align with Crystalline Norms." : "Structure is coherent.",
135
+ fragmentation.length > 0 ? "Consolidate your functional nodes to reduce context switching." : "No fragmentation detected."
136
+ ]
137
+ },
138
+ engagement_reality: {
139
+ high_engagement_hubs: engagement.high_engagement.map(t => t.name),
140
+ fragmentation_clusters: fragmentation.map(f => f.functionId)
141
+ },
142
+ maturity_assessment: maturity,
143
+ inner_diamond: new DiamondMapper().mapToDiamond(toolList, false)
144
+ };
145
+
146
+ return {
147
+ content: [{
148
+ type: "text" as const,
149
+ text: JSON.stringify(report, null, 2)
150
+ }]
151
+ };
152
+ }
153
+ };
@@ -0,0 +1,50 @@
1
+ import { z } from "zod";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { PingalaEngine } from "../core/pingala.js";
5
+ import type { ToolInstance } from "../core/531-rule.js";
6
+
7
+ /**
8
+ * Tool definition for auditing a workspace.
9
+ */
10
+ export const auditWorkspaceTool = {
11
+ name: "audit_workspace",
12
+ description: "Scans a workspace for .agent configuration and evaluates 5:3:1 protocol alignment (CSI/SAS).",
13
+ schema: {
14
+ path: z.string().describe("The absolute path to the workspace directory to audit.")
15
+ },
16
+ handler: async (args: { path: string }) => {
17
+ const workspacePath = args.path;
18
+ const agentPath = path.join(workspacePath, ".agent");
19
+
20
+ const report: any = {
21
+ workspace: workspacePath,
22
+ agent_found: fs.existsSync(agentPath),
23
+ timestamp: new Date().toISOString()
24
+ };
25
+
26
+ if (!report.agent_found) {
27
+ return {
28
+ content: [{
29
+ type: "text" as const,
30
+ text: `Pingala Analysis: Workspace '${workspacePath}' is unmapped. No '.agent' directory found. High risk of cognitive erosion.`
31
+ }]
32
+ };
33
+ }
34
+
35
+ // Simplified tool detection for MVP
36
+ // In a real scenario, this would parse vault.yaml or scan files
37
+ const mockTools: ToolInstance[] = [
38
+ { name: "Claude/Antigravity", category: "Intelligence", role: "Anchor" }
39
+ ];
40
+
41
+ const diagnosis = PingalaEngine.diagnose({ tools: mockTools });
42
+
43
+ return {
44
+ content: [{
45
+ type: "text" as const,
46
+ text: JSON.stringify({ ...report, diagnosis }, null, 2)
47
+ }]
48
+ };
49
+ }
50
+ };
@@ -0,0 +1,38 @@
1
+ import { z } from "zod";
2
+ import { Governor } from "../core/governor.js";
3
+ import { PingalaEngine } from "../core/pingala.js";
4
+
5
+ export const calculateCsiTool = {
6
+ name: "calculate_csi",
7
+ description: "Computes current Cognitive Sovereignty Index (0-100) from telemetry scores. Allows recording of Attention Depth and Dependency Exposure.",
8
+ schema: {
9
+ attention_depth: z.number().min(0).max(100).optional().describe("0-100 score for attention quality/deep work"),
10
+ dependency_exposure: z.number().min(0).max(100).optional().describe("0-100 score for workflow independence from AI"),
11
+ time_window: z.enum(["7d", "30d", "90d"]).optional().describe("Lookback period (default 7d)"),
12
+ tools: z.array(z.any()).optional().describe("Optional list of tools to calculate CSI for (Stateless Mode)")
13
+ },
14
+ handler: async (args: {
15
+ attention_depth?: number;
16
+ dependency_exposure?: number;
17
+ time_window?: string;
18
+ tools?: any[];
19
+ }) => {
20
+ // Record telemetry if provided (only if not in stateless mode or if we specifically want to save)
21
+ if (args.attention_depth !== undefined || args.dependency_exposure !== undefined) {
22
+ Governor.recordTelemetry({
23
+ attention_depth: args.attention_depth,
24
+ dependency_exposure: args.dependency_exposure
25
+ });
26
+ }
27
+
28
+ const stack = args.tools || Governor.getStack();
29
+ const diagnosis = await PingalaEngine.diagnose({ tools: stack });
30
+
31
+ return {
32
+ content: [{
33
+ type: "text" as const,
34
+ text: JSON.stringify(diagnosis, null, 2)
35
+ }]
36
+ };
37
+ }
38
+ };
@@ -0,0 +1,384 @@
1
+ import { z } from "zod";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { PingalaEngine } from "../core/pingala.js";
5
+ import { MethodologyLoader } from "../core/methodology.js";
6
+ import { Governor } from "../core/governor.js";
7
+ import type { ToolInstance } from "../core/531-rule.js";
8
+ import { EngagementAnalyzer, type ToolWithEngagement } from "../core/engagement-analyzer.js";
9
+ import { ConsentManager } from "../core/consent-manager.js";
10
+ import { BaguaMapper, DiamondMapper } from "../core/life-area-mapper.js";
11
+
12
+ /**
13
+ * cs_audit Tool: The Governor's Primary Interface
14
+ *
15
+ * Accepts tool lists (raw, from vault, or from image) and runs the
16
+ * 6-step Intervention Logic to audit stack alignment with 5:3:1.
17
+ * Supports three levels of depth (L1, L2, L3) gated by consent.
18
+ */
19
+
20
+ // Minimal Protocol Schema: Matches analyze_stack
21
+ const ToolSchema = z.object({
22
+ name: z.string(),
23
+ role: z.enum(["Anchor", "Active", "Supporting"]),
24
+ category: z.string().optional(),
25
+ description: z.string().optional(),
26
+ context: z.string().optional(),
27
+ functionId: z.string().optional()
28
+ });
29
+
30
+ export const csAuditTool = {
31
+ name: "cs_audit",
32
+ description: "Audits a stack as a Cognitive Mirror, not just a rule checker. Analyzes ENGAGEMENT REALITY—distinguishing high-engagement hubs from passive utilities—and flags fragmentation (multiple tools per function).",
33
+ schema: {
34
+ tools: z.array(ToolSchema).optional().describe("List of tools to audit"),
35
+ path: z.string().optional().describe("Path to a vault.yaml or .agent directory"),
36
+ image_uri: z.string().optional().describe("URI to a screenshot of a stack (parsed via LLM vision if available)"),
37
+ proposed_tool: z.string().optional().describe("A new tool being considered for addition"),
38
+ current_phase: z.string().optional().describe("Current work phase (e.g., 'pre-launch', 'scale', 'maintenance')"),
39
+ depth_level: z.enum(["L1", "L2", "L3"]).default("L1").describe("The requested depth level of auditing"),
40
+ practitioner_mode: z.boolean().optional().describe("If true, overrides consent gates and exposes internal jargon")
41
+ },
42
+ handler: async (args: {
43
+ tools?: Array<any>;
44
+ path?: string;
45
+ image_uri?: string;
46
+ proposed_tool?: string;
47
+ current_phase?: string;
48
+ depth_level?: 'L1' | 'L2' | 'L3';
49
+ practitioner_mode?: boolean;
50
+ }) => {
51
+ const depth = args.depth_level || "L1";
52
+ const practitionerMode = args.practitioner_mode || false;
53
+
54
+ // Set workspace context for consent persistence
55
+ if (args.path) {
56
+ ConsentManager.setWorkspace(args.path);
57
+ }
58
+
59
+ // CHECK CONSENT
60
+ if (!ConsentManager.isAuthorized(depth, practitionerMode)) {
61
+ const prompts = MethodologyLoader.loadConsentPrompts();
62
+ return {
63
+ content: [{
64
+ type: "text" as const,
65
+ text: JSON.stringify({
66
+ type: "consent_request",
67
+ level: depth,
68
+ message: depth === "L2" ? prompts.l2 : prompts.l3,
69
+ hint: "Consent will be saved for this workspace."
70
+ }, null, 2)
71
+ }]
72
+ };
73
+ }
74
+ // STEP 0: Input Resolution
75
+ let toolList: ToolInstance[] = [];
76
+
77
+ // Priority: explicit tools > path > image
78
+ if (args.tools && args.tools.length > 0) {
79
+ const rawList: ToolInstance[] = args.tools.map(t => ({
80
+ name: t.name,
81
+ category: t.category || "Uncategorized",
82
+ role: (t.role as "Anchor" | "Active" | "Supporting") || "Supporting",
83
+ avgDailyMinutes: t.avgDailyMinutes,
84
+ usagePattern: t.usagePattern,
85
+ functionId: t.functionId,
86
+ contexts: t.contexts || (t.device ? [t.device] : undefined),
87
+ isAdapter: t.isAdapter ?? t.contextual_adapter,
88
+ substack: t.substack ?? t.substacks
89
+ }));
90
+ toolList = rawList as ToolWithEngagement[];
91
+ } else if (args.path) {
92
+ // Attempt to read from vault
93
+ const vaultPath = path.join(args.path, "vault.yaml");
94
+ if (fs.existsSync(vaultPath)) {
95
+ // For MVP: just indicate vault found, parsing TODO
96
+ return {
97
+ content: [{
98
+ type: "text" as const,
99
+ text: JSON.stringify({
100
+ type: "clarification",
101
+ message: "Vault detected. Please provide tools as a list for now (vault parsing coming soon).",
102
+ vault_path: vaultPath
103
+ }, null, 2)
104
+ }]
105
+ };
106
+ } else {
107
+ return {
108
+ content: [{
109
+ type: "text" as const,
110
+ text: JSON.stringify({
111
+ type: "clarification",
112
+ message: `No vault.yaml found at ${args.path}. Please provide tools as a list.`
113
+ }, null, 2)
114
+ }]
115
+ };
116
+ }
117
+ } else if (args.image_uri) {
118
+ // Image parsing requires LLM vision - return clarification
119
+ return {
120
+ content: [{
121
+ type: "text" as const,
122
+ text: JSON.stringify({
123
+ type: "clarification",
124
+ message: "Image received. LLM vision parsing not yet implemented. Please provide tools as a list.",
125
+ image_uri: args.image_uri
126
+ }, null, 2)
127
+ }]
128
+ };
129
+ } else {
130
+ // No input provided - ask for stack
131
+ return {
132
+ content: [{
133
+ type: "text" as const,
134
+ text: JSON.stringify({
135
+ type: "clarification",
136
+ step: 2,
137
+ question: "What tools are currently in your stack?",
138
+ hint: "List each tool with its name. Optionally include role (Anchor/Active/Supporting) and category."
139
+ }, null, 2)
140
+ }]
141
+ };
142
+ }
143
+
144
+ // STEP 1: Engagement Analysis (The Cognitive Mirror)
145
+ const engagement = EngagementAnalyzer.classifyByEngagement(toolList as ToolWithEngagement[]);
146
+ const fragmentation = EngagementAnalyzer.detectFragmentation(toolList as ToolWithEngagement[]);
147
+ const anomalies = EngagementAnalyzer.flagAnomalies(toolList as ToolWithEngagement[]);
148
+ const anchorCheck = EngagementAnalyzer.identifyAnchorEnvironment(toolList as ToolWithEngagement[]);
149
+
150
+ // Cognitive Load calculation: High-engagement tools + frag clusters
151
+ const cognitivelyActiveTools = engagement.high_engagement.length + fragmentation.length;
152
+
153
+ if (cognitivelyActiveTools > 9) {
154
+ return {
155
+ content: [{
156
+ type: "text" as const,
157
+ text: JSON.stringify({
158
+ type: "intervention",
159
+ step: 1,
160
+ status: "HARD_STOP",
161
+ message: `Your high-engagement stack has ${cognitivelyActiveTools} Active Hubs. The 5:3:1 Protocol limits you to 9. You are in a state of cognitive debt.`,
162
+ active_hubs: cognitivelyActiveTools,
163
+ max_allowed: 9,
164
+ fragmentation_clusters: fragmentation.map(f => f.functionId)
165
+ }, null, 2)
166
+ }]
167
+ };
168
+ }
169
+
170
+ // STEP 2: Current State Audit
171
+ const anchors = toolList.filter(t => t.role === "Anchor");
172
+ const active = toolList.filter(t => t.role === "Active");
173
+ const supporting = toolList.filter(t => t.role === "Supporting");
174
+ const unassigned = toolList.filter(t => !t.role);
175
+
176
+ // Check for role assignment issues
177
+ if (unassigned.length > 0) {
178
+ return {
179
+ content: [{
180
+ type: "text" as const,
181
+ text: JSON.stringify({
182
+ type: "clarification",
183
+ step: 2,
184
+ question: "Some tools don't have roles assigned. Please classify these:",
185
+ unassigned_tools: unassigned.map(t => t.name),
186
+ valid_roles: ["Anchor", "Active", "Supporting"],
187
+ rule: "You need exactly 1 Anchor, up to 3 Active, and up to 5 Supporting."
188
+ }, null, 2)
189
+ }]
190
+ };
191
+ }
192
+
193
+ // Validate structure
194
+ const structureIssues: string[] = [];
195
+ if (anchors.length !== 1) {
196
+ structureIssues.push(`Expected 1 Anchor, found ${anchors.length}.`);
197
+ }
198
+ if (active.length > 3) {
199
+ structureIssues.push(`Expected max 3 Active, found ${active.length}.`);
200
+ }
201
+ if (supporting.length > 5) {
202
+ structureIssues.push(`Expected max 5 Supporting, found ${supporting.length}.`);
203
+ }
204
+ if (!anchorCheck.hasAnchor) {
205
+ structureIssues.push(anchorCheck.observation || "No clear Anchor environment detected.");
206
+ }
207
+
208
+ if (structureIssues.length > 0) {
209
+ return {
210
+ content: [{
211
+ type: "text" as const,
212
+ text: JSON.stringify({
213
+ type: "intervention",
214
+ step: 2,
215
+ status: "STRUCTURE_VIOLATION",
216
+ issues: structureIssues,
217
+ hint: anchorCheck.hint,
218
+ current_structure: {
219
+ anchors: anchors.map(t => t.name),
220
+ active: active.map(t => t.name),
221
+ supporting: supporting.map(t => t.name)
222
+ }
223
+ }, null, 2)
224
+ }]
225
+ };
226
+ }
227
+
228
+ // STEP 3: Fragmentation Intervention
229
+ if (fragmentation.length > 0) {
230
+ return {
231
+ content: [{
232
+ type: "text" as const,
233
+ text: JSON.stringify({
234
+ type: "intervention",
235
+ step: 3,
236
+ status: "FRAGMENTATION_DETECTED",
237
+ message: "You have multiple tools serving the same function. This creates obligation anxiety and check-in loops.",
238
+ clusters: fragmentation,
239
+ recommendation: "Consolidate to a single tool per function, or explicitly acknowledge the split as intentional."
240
+ }, null, 2)
241
+ }]
242
+ };
243
+ }
244
+
245
+ // STEP 3-6: Only if proposed_tool is given
246
+ if (args.proposed_tool) {
247
+ // Step 3: Value vs Redundancy Test
248
+ const overlap = toolList.find(t =>
249
+ t.name.toLowerCase().includes(args.proposed_tool!.toLowerCase()) ||
250
+ args.proposed_tool!.toLowerCase().includes(t.name.toLowerCase())
251
+ );
252
+
253
+ if (overlap) {
254
+ return {
255
+ content: [{
256
+ type: "text" as const,
257
+ text: JSON.stringify({
258
+ type: "intervention",
259
+ step: 3,
260
+ status: "REDUNDANCY_CHECK",
261
+ question: `You already have '${overlap.name}'. How is '${args.proposed_tool}' different?`,
262
+ existing_tool: overlap.name,
263
+ proposed_tool: args.proposed_tool,
264
+ hint: "If they serve the same function, this addition violates Stack Substitution rules."
265
+ }, null, 2)
266
+ }]
267
+ };
268
+ }
269
+
270
+ // Step 4: Phase Alignment Check
271
+ if (!args.current_phase) {
272
+ return {
273
+ content: [{
274
+ type: "text" as const,
275
+ text: JSON.stringify({
276
+ type: "clarification",
277
+ step: 4,
278
+ question: "What is your current work phase?",
279
+ hint: "e.g., 'pre-launch', 'growth', 'scale', 'maintenance'",
280
+ context: `You're considering adding '${args.proposed_tool}'. Is it needed for your current phase, or a future one?`
281
+ }, null, 2)
282
+ }]
283
+ };
284
+ }
285
+
286
+ // Step 5: Substitution Requirement
287
+ if (toolList.length >= 9) {
288
+ return {
289
+ content: [{
290
+ type: "text" as const,
291
+ text: JSON.stringify({
292
+ type: "intervention",
293
+ step: 5,
294
+ status: "SUBSTITUTION_REQUIRED",
295
+ question: `Your stack is at capacity (${toolList.length}/9). If '${args.proposed_tool}' joins, what gets removed?`,
296
+ current_stack: toolList.map(t => t.name),
297
+ proposed_tool: args.proposed_tool,
298
+ rule: "No addition without subtraction."
299
+ }, null, 2)
300
+ }]
301
+ };
302
+ }
303
+
304
+ // Step 6: Inner Stack Reflection
305
+ return {
306
+ content: [{
307
+ type: "text" as const,
308
+ text: JSON.stringify({
309
+ type: "intervention",
310
+ step: 6,
311
+ status: "REFLECTION",
312
+ question: "Before adding this tool, pause: What internal pattern is driving this consideration?",
313
+ prompts: [
314
+ "Is this FOMO?",
315
+ "Are you in 'expansion-through-addition' mode?",
316
+ "What are you avoiding by considering this right now?"
317
+ ],
318
+ proposed_tool: args.proposed_tool,
319
+ current_phase: args.current_phase,
320
+ message: "The intervention isn't 'No, don't do that.' It's: Here's your own protocol and how it applies to what you're doing in real-time."
321
+ }, null, 2)
322
+ }]
323
+ };
324
+ }
325
+
326
+ // Full diagnosis (no proposed tool)
327
+ const diagnosis = await PingalaEngine.diagnose({
328
+ tools: toolList
329
+ });
330
+ const rules = MethodologyLoader.load531Rules();
331
+
332
+ return {
333
+ content: [{
334
+ type: "text" as const,
335
+ text: JSON.stringify({
336
+ type: "diagnosis",
337
+ version: "0.4.5 (Horizon 1.5)",
338
+ protocol_metadata: {
339
+ name: "5:3:1 Protocol",
340
+ mapping: rules.rawDescription || "1 Anchor, 3 Active, 5 Supporting",
341
+ total_limit: rules.maxTools
342
+ },
343
+ functional_geometry: {
344
+ clusters: toolList.reduce((acc: any, tool) => {
345
+ const fid = tool.functionId || "Unclassified";
346
+ if (!acc[fid]) acc[fid] = { id: fid, primary: tool.name, nodes: [] };
347
+ acc[fid].nodes.push({
348
+ name: tool.name,
349
+ context: tool.context,
350
+ is_adapter: tool.isAdapter
351
+ });
352
+ return acc;
353
+ }, {})
354
+ },
355
+ engagement_reality: {
356
+ high_engagement_hubs: engagement.high_engagement.map(t => t.name),
357
+ contextual_utilities: engagement.contextual_utility.map(t => t.name),
358
+ passive_background: engagement.passive_background.map(t => t.name),
359
+ fragmentation_clusters: fragmentation.map(f => f.functionId),
360
+ anomalies: anomalies
361
+ },
362
+ stack_structure: {
363
+ anchor: anchors.map(t => t.name),
364
+ active: active.map(t => t.name),
365
+ supporting: supporting.map(t => t.name)
366
+ },
367
+ total_tools: toolList.length,
368
+ active_hubs: cognitivelyActiveTools,
369
+ diagnosis,
370
+ life_area_mapping: depth !== "L1" ? new BaguaMapper().mapToolsToAreas(toolList, practitionerMode) : undefined,
371
+ inner_diamond: depth === "L3" ? new DiamondMapper().mapToDiamond(toolList, practitionerMode) : undefined,
372
+ progression_offer: (depth === "L1" && !ConsentManager.isAuthorized("L2") && Governor.getGovernanceContext().progression.is_l2_eligible) ? {
373
+ level: "L2",
374
+ message: MethodologyLoader.loadConsentPrompts().l2,
375
+ reason: "You have improved your CSI by 10+ points. You've earned a deeper look."
376
+ } : undefined,
377
+ the_real_question: depth === "L3" ?
378
+ "What are you choosing not to see by maintaining this specific friction?" :
379
+ "Which 3 apps actually create value in your life, and which are just installed because 'I might need it someday'?"
380
+ }, null, 2)
381
+ }]
382
+ };
383
+ }
384
+ };