mcp-cognition-engine 1.0.0-alpha.1

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 (158) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +281 -0
  3. package/dist/cli.d.ts +18 -0
  4. package/dist/cli.d.ts.map +1 -0
  5. package/dist/cli.js +66 -0
  6. package/dist/cli.js.map +1 -0
  7. package/dist/cognition-engine/ast-constraint-solver.d.ts +67 -0
  8. package/dist/cognition-engine/ast-constraint-solver.d.ts.map +1 -0
  9. package/dist/cognition-engine/ast-constraint-solver.js +294 -0
  10. package/dist/cognition-engine/ast-constraint-solver.js.map +1 -0
  11. package/dist/cognition-engine/constraint-validator.d.ts +35 -0
  12. package/dist/cognition-engine/constraint-validator.d.ts.map +1 -0
  13. package/dist/cognition-engine/constraint-validator.js +55 -0
  14. package/dist/cognition-engine/constraint-validator.js.map +1 -0
  15. package/dist/cognition-engine/graph-traverser.d.ts +43 -0
  16. package/dist/cognition-engine/graph-traverser.d.ts.map +1 -0
  17. package/dist/cognition-engine/graph-traverser.js +205 -0
  18. package/dist/cognition-engine/graph-traverser.js.map +1 -0
  19. package/dist/cognition-engine/index.d.ts +51 -0
  20. package/dist/cognition-engine/index.d.ts.map +1 -0
  21. package/dist/cognition-engine/index.js +60 -0
  22. package/dist/cognition-engine/index.js.map +1 -0
  23. package/dist/cognition-engine/intent-recognizer.d.ts +25 -0
  24. package/dist/cognition-engine/intent-recognizer.d.ts.map +1 -0
  25. package/dist/cognition-engine/intent-recognizer.js +226 -0
  26. package/dist/cognition-engine/intent-recognizer.js.map +1 -0
  27. package/dist/cognition-engine/types.d.ts +96 -0
  28. package/dist/cognition-engine/types.d.ts.map +1 -0
  29. package/dist/cognition-engine/types.js +17 -0
  30. package/dist/cognition-engine/types.js.map +1 -0
  31. package/dist/conflict/arbitrator.d.ts +24 -0
  32. package/dist/conflict/arbitrator.d.ts.map +1 -0
  33. package/dist/conflict/arbitrator.js +43 -0
  34. package/dist/conflict/arbitrator.js.map +1 -0
  35. package/dist/index.d.ts +17 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +90 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/legacy-engine/ast-diff.d.ts +23 -0
  40. package/dist/legacy-engine/ast-diff.d.ts.map +1 -0
  41. package/dist/legacy-engine/ast-diff.js +146 -0
  42. package/dist/legacy-engine/ast-diff.js.map +1 -0
  43. package/dist/legacy-engine/ast-node.d.ts +24 -0
  44. package/dist/legacy-engine/ast-node.d.ts.map +1 -0
  45. package/dist/legacy-engine/ast-node.js +52 -0
  46. package/dist/legacy-engine/ast-node.js.map +1 -0
  47. package/dist/legacy-engine/parsers.d.ts +34 -0
  48. package/dist/legacy-engine/parsers.d.ts.map +1 -0
  49. package/dist/legacy-engine/parsers.js +134 -0
  50. package/dist/legacy-engine/parsers.js.map +1 -0
  51. package/dist/legacy-engine/regex-fallback.d.ts +23 -0
  52. package/dist/legacy-engine/regex-fallback.d.ts.map +1 -0
  53. package/dist/legacy-engine/regex-fallback.js +40 -0
  54. package/dist/legacy-engine/regex-fallback.js.map +1 -0
  55. package/dist/legacy-engine/rule-generator.d.ts +31 -0
  56. package/dist/legacy-engine/rule-generator.d.ts.map +1 -0
  57. package/dist/legacy-engine/rule-generator.js +54 -0
  58. package/dist/legacy-engine/rule-generator.js.map +1 -0
  59. package/dist/legacy-engine/rule-matcher.d.ts +28 -0
  60. package/dist/legacy-engine/rule-matcher.d.ts.map +1 -0
  61. package/dist/legacy-engine/rule-matcher.js +79 -0
  62. package/dist/legacy-engine/rule-matcher.js.map +1 -0
  63. package/dist/legacy-engine/token-controller.d.ts +31 -0
  64. package/dist/legacy-engine/token-controller.d.ts.map +1 -0
  65. package/dist/legacy-engine/token-controller.js +66 -0
  66. package/dist/legacy-engine/token-controller.js.map +1 -0
  67. package/dist/middleware/response-validation.d.ts +27 -0
  68. package/dist/middleware/response-validation.d.ts.map +1 -0
  69. package/dist/middleware/response-validation.js +50 -0
  70. package/dist/middleware/response-validation.js.map +1 -0
  71. package/dist/modes/confirm.d.ts +29 -0
  72. package/dist/modes/confirm.d.ts.map +1 -0
  73. package/dist/modes/confirm.js +27 -0
  74. package/dist/modes/confirm.js.map +1 -0
  75. package/dist/modes/silent.d.ts +24 -0
  76. package/dist/modes/silent.d.ts.map +1 -0
  77. package/dist/modes/silent.js +24 -0
  78. package/dist/modes/silent.js.map +1 -0
  79. package/dist/resources/cognition-resources.d.ts +28 -0
  80. package/dist/resources/cognition-resources.d.ts.map +1 -0
  81. package/dist/resources/cognition-resources.js +124 -0
  82. package/dist/resources/cognition-resources.js.map +1 -0
  83. package/dist/storage/client.d.ts +26 -0
  84. package/dist/storage/client.d.ts.map +1 -0
  85. package/dist/storage/client.js +45 -0
  86. package/dist/storage/client.js.map +1 -0
  87. package/dist/storage/cognition-repository.d.ts +55 -0
  88. package/dist/storage/cognition-repository.d.ts.map +1 -0
  89. package/dist/storage/cognition-repository.js +287 -0
  90. package/dist/storage/cognition-repository.js.map +1 -0
  91. package/dist/storage/cognition-types.d.ts +96 -0
  92. package/dist/storage/cognition-types.d.ts.map +1 -0
  93. package/dist/storage/cognition-types.js +41 -0
  94. package/dist/storage/cognition-types.js.map +1 -0
  95. package/dist/storage/conflict-repo.d.ts +41 -0
  96. package/dist/storage/conflict-repo.d.ts.map +1 -0
  97. package/dist/storage/conflict-repo.js +67 -0
  98. package/dist/storage/conflict-repo.js.map +1 -0
  99. package/dist/storage/diff-log-repo.d.ts +48 -0
  100. package/dist/storage/diff-log-repo.d.ts.map +1 -0
  101. package/dist/storage/diff-log-repo.js +51 -0
  102. package/dist/storage/diff-log-repo.js.map +1 -0
  103. package/dist/storage/metric-repo.d.ts +20 -0
  104. package/dist/storage/metric-repo.d.ts.map +1 -0
  105. package/dist/storage/metric-repo.js +36 -0
  106. package/dist/storage/metric-repo.js.map +1 -0
  107. package/dist/storage/rule-repo.d.ts +66 -0
  108. package/dist/storage/rule-repo.d.ts.map +1 -0
  109. package/dist/storage/rule-repo.js +188 -0
  110. package/dist/storage/rule-repo.js.map +1 -0
  111. package/dist/tools/analyze-workspace.d.ts +26 -0
  112. package/dist/tools/analyze-workspace.d.ts.map +1 -0
  113. package/dist/tools/analyze-workspace.js +147 -0
  114. package/dist/tools/analyze-workspace.js.map +1 -0
  115. package/dist/tools/capture-diff.d.ts +26 -0
  116. package/dist/tools/capture-diff.d.ts.map +1 -0
  117. package/dist/tools/capture-diff.js +58 -0
  118. package/dist/tools/capture-diff.js.map +1 -0
  119. package/dist/tools/cognition-tools.d.ts +60 -0
  120. package/dist/tools/cognition-tools.d.ts.map +1 -0
  121. package/dist/tools/cognition-tools.js +170 -0
  122. package/dist/tools/cognition-tools.js.map +1 -0
  123. package/dist/tools/config-tools.d.ts +29 -0
  124. package/dist/tools/config-tools.d.ts.map +1 -0
  125. package/dist/tools/config-tools.js +58 -0
  126. package/dist/tools/config-tools.js.map +1 -0
  127. package/dist/tools/confirm-rule.d.ts +32 -0
  128. package/dist/tools/confirm-rule.d.ts.map +1 -0
  129. package/dist/tools/confirm-rule.js +64 -0
  130. package/dist/tools/confirm-rule.js.map +1 -0
  131. package/dist/tools/injection-approval.d.ts +43 -0
  132. package/dist/tools/injection-approval.d.ts.map +1 -0
  133. package/dist/tools/injection-approval.js +102 -0
  134. package/dist/tools/injection-approval.js.map +1 -0
  135. package/dist/tools/list-rules.d.ts +24 -0
  136. package/dist/tools/list-rules.d.ts.map +1 -0
  137. package/dist/tools/list-rules.js +20 -0
  138. package/dist/tools/list-rules.js.map +1 -0
  139. package/dist/tools/query-rules.d.ts +25 -0
  140. package/dist/tools/query-rules.d.ts.map +1 -0
  141. package/dist/tools/query-rules.js +65 -0
  142. package/dist/tools/query-rules.js.map +1 -0
  143. package/dist/tools/resolve-conflict.d.ts +33 -0
  144. package/dist/tools/resolve-conflict.d.ts.map +1 -0
  145. package/dist/tools/resolve-conflict.js +35 -0
  146. package/dist/tools/resolve-conflict.js.map +1 -0
  147. package/dist/types.d.ts +190 -0
  148. package/dist/types.d.ts.map +1 -0
  149. package/dist/types.js +50 -0
  150. package/dist/types.js.map +1 -0
  151. package/docs/api-reference.md +1229 -0
  152. package/docs/community/feedback-playbook.md +94 -0
  153. package/docs/integration-snippets.md +100 -0
  154. package/docs/mcp-integration-guide.md +151 -0
  155. package/docs/phase4-mcp-feedback.md +155 -0
  156. package/docs/trust-governance-protocol.md +72 -0
  157. package/package.json +74 -0
  158. package/prisma/schema.prisma +145 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 熊高锐
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,281 @@
1
+ # MCP Rule Engine — Cognition Engine & Trust Governance Layer
2
+
3
+ ![build](https://img.shields.io/badge/build-passing-brightgreen)
4
+ ![coverage](https://img.shields.io/badge/coverage-95%25-brightgreen)
5
+ ![MCP](https://img.shields.io/badge/MCP_v1.29.0-compliant-blue)
6
+ [![License](https://img.shields.io/badge/license-Apache_2.0-blue)](LICENSE)
7
+ [![Trademark Policy](https://img.shields.io/badge/trademark-policy-orange)](TRADEMARK.md)
8
+
9
+ > A production-grade MCP server that combines a cognition graph engine with a trusted governance layer. Provides intelligent code pattern matching, AST-level constraint validation, and auditable injection approval for AI agents.
10
+
11
+ <!-- TEMP_BANNER_REMOVE_AFTER_2W -->
12
+ > **📢 Protocol Update:** We have adopted Apache 2.0 licensing with a formal trademark policy. [Read the announcement →](DISCUSSION_ANNOUNCEMENT.md)
13
+ <!-- /TEMP_BANNER -->
14
+
15
+ ---
16
+
17
+
18
+
19
+ ## The Problem It Solves
20
+
21
+ AI Agents are powerful but chaotic. They generate code confidently, yet they lack a persistent *cognition layer* to remember project-specific patterns across sessions, and they lack a *governance layer* to enforce security boundaries on their own output. Without these, every agent session starts from zero — repeating the same mistakes, ignoring your team's conventions, and producing code that looks plausible but violates project invariants.
22
+
23
+ This engine fixes that. It gives agents a **long-term graph memory** of project patterns (what works, what's forbidden, what's idiomatic in *this* codebase) and a **trusted approval workflow** so every injection is reviewed, audited, and accountable.
24
+
25
+ ---
26
+
27
+ ## Core Features
28
+
29
+ - **Cognition Graph Engine** — Intent recognition, weighted graph traversal, and AST constraint solving for intelligent code analysis
30
+ - **Trust Governance** — Three-tier knowledge base with injection approval workflow, TTL-based proposals, and audit logging
31
+ - **Universal Connectivity** — Stdio (local) and Streamable HTTP (remote) transports with full MCP lifecycle support
32
+ - **Agent Hard Constraints** — Output schema enforcement with \`validationRequired\` auto-validation; non-compliant agent responses intercepted
33
+ - **Hot Config Updates** — Dynamic threshold tuning with expert mode authorization and version chain tracking
34
+
35
+ ---
36
+
37
+ ## Architecture
38
+
39
+ \`\`\`mermaid
40
+ flowchart LR
41
+ Agent["AI Agent (Cursor / Claude / Cline)"]
42
+ MCP["MCP Server (stdio / HTTP)"]
43
+ CV["Constraint Validator"]
44
+ GT["Graph Traverser"]
45
+ IA["Injection Approval"]
46
+ FL["Feedback Loop"]
47
+ DB[("SQLite / Prisma")]
48
+
49
+ Agent -->|tools/list → tools/call| MCP
50
+ MCP -->|cognition_validate| CV
51
+ MCP -->|cognition_query| GT
52
+ MCP -->|cognition_approve_injection| IA
53
+ MCP -->|cognition_feedback| FL
54
+ CV -->|parse + validate| GT
55
+ GT -->|weighted BFS| DB
56
+ IA -->|TTL proposal| DB
57
+ FL -->|update weights| DB
58
+ DB -->|graph data| GT
59
+ \`\`\`
60
+
61
+ ---
62
+
63
+ ## Quick Start
64
+
65
+ ### Prerequisites
66
+
67
+ - Node.js >= 18
68
+ - npm >= 9
69
+
70
+ ### Setup
71
+
72
+ \`\`\`bash
73
+ git clone <repo-url> && cd mcp-rule-engine
74
+ npm install
75
+ npx prisma db push
76
+ npm run build
77
+ \`\`\`
78
+
79
+ ### Start Server
80
+
81
+ \`\`\`bash
82
+ # Stdio mode (default)
83
+ node dist/index.js
84
+
85
+ # HTTP mode
86
+ TRANSPORT=http PORT=3000 node dist/index.js
87
+ \`\`\`
88
+
89
+ ---
90
+
91
+ ## MCP Integration
92
+
93
+ ### Cursor
94
+
95
+ Add to \`.cursor/mcp.json\`:
96
+
97
+ \`\`\`json
98
+ {
99
+ "mcpServers": {
100
+ "cognition-engine": {
101
+ "command": "node",
102
+ "args": ["dist/index.js"],
103
+ "env": { "DATABASE_URL": "file:./dev.db" }
104
+ }
105
+ }
106
+ }
107
+ \`\`\`
108
+
109
+ ### Claude Desktop
110
+
111
+ Add to \`claude_desktop_config.json\`:
112
+
113
+ \`\`\`json
114
+ {
115
+ "mcpServers": {
116
+ "cognition-engine": {
117
+ "command": "node",
118
+ "args": ["path/to/mcp-rule-engine/dist/index.js"],
119
+ "env": { "DATABASE_URL": "file:./dev.db" }
120
+ }
121
+ }
122
+ }
123
+ \`\`\`
124
+
125
+ ### VS Code (GitHub Copilot Chat / VS Code MCP Extension)
126
+
127
+ Add to your VS Code settings (User \`settings.json\` or workspace \`.vscode/mcp.json\`):
128
+
129
+ \`\`\`json
130
+ {
131
+ "mcp": {
132
+ "servers": {
133
+ "cognition-engine": {
134
+ "type": "stdio",
135
+ "command": "node",
136
+ "args": ["dist/index.js"],
137
+ "env": { "DATABASE_URL": "file:./dev.db" }
138
+ }
139
+ }
140
+ }
141
+ }
142
+ \`\`\`
143
+
144
+ ### Cline / Roo Code (HTTP)
145
+
146
+ \`\`\`json
147
+ {
148
+ "mcpServers": {
149
+ "cognition-engine": {
150
+ "url": "http://localhost:3000",
151
+ "transport": "streamable-http"
152
+ }
153
+ }
154
+ }
155
+ \`\`\`
156
+
157
+ ---
158
+
159
+ ## Trust Governance Protocol
160
+
161
+ ### Three-Tier Knowledge
162
+
163
+ | Tier | Scope | Node Type | Validation |
164
+ |------|-------|-----------|------------|
165
+ | Global | Universal patterns | NegativeConstraint = REJECT | Hard block |
166
+ | Project | Project conventions | PositiveConstraint = WARN | Soft warning |
167
+ | Reuse | Cross-project patterns | Intent + Heuristic | Weight-based |
168
+
169
+ ### Injection Proposal State Machine
170
+
171
+ \`\`\`mermaid
172
+ stateDiagram-v2
173
+ [*] --> PENDING: cognition_query triggers implicit proposal
174
+ PENDING --> APPROVED: cognition_approve_injection(proposalId, APPROVE)
175
+ PENDING --> REJECTED: cognition_approve_injection(proposalId, REJECT)
176
+ PENDING --> OVERRIDDEN: cognition_approve_injection(proposalId, OVERRIDE)
177
+ PENDING --> EXPIRED: TTL = 5 min elapsed
178
+ APPROVED --> [*]: Rules injected into graph
179
+ REJECTED --> [*]: Proposal discarded
180
+ OVERRIDDEN --> [*]: Force-injected (audit logged)
181
+ EXPIRED --> [*]: -32602 Proposal Expired + retryable:true
182
+ \`\`\`
183
+
184
+ Proposals are in-memory with a 5-minute TTL. Concurrent proposals for the same context hash return the existing proposal to prevent conflicts. Expired proposals return \`-32602 Proposal Expired\` with \`retryable: true\`.
185
+
186
+ ### Constraint Validation Dual-Mode
187
+
188
+ - **REJECT (Hard Block)** — Returned as \`-32602\` + \`ruleId\`. Agent must stop.
189
+ - **WARN (Soft Warning)** — Returned as violation. Agent may continue with user confirmation.
190
+
191
+ ### Config Hot Update
192
+
193
+ Dynamic thresholds (similarity 0.7 / 0.9) are stored as \`CognitionNode(type=HEURISTIC)\`. Each update creates a new version node with the old node marked \`supersededBy\`. Requires \`expertMode: true\`.
194
+
195
+ ### Audit & Compliance
196
+
197
+ All injection decisions, config changes, and validation events are recorded via \`MetricEvent\` with async non-blocking writes. On database write failure, events fall back to \`logs/fallback.log\`.
198
+
199
+ ---
200
+
201
+ ## MCP Resources
202
+
203
+ | URI | Type | Content |
204
+ |-----|------|---------|
205
+ | \`cognition://schema\` | application/json | Cognition graph data model |
206
+ | \`cognition://stats\` | application/json | Node/edge counts + approvalRate7d |
207
+ | \`cognition://docs\` | text/markdown | Full tool documentation |
208
+ | \`cognition://rules-changelog\` | application/json | Versioned rule change log |
209
+
210
+ ---
211
+
212
+ ## MCP Tools
213
+
214
+ | Tool | Description | readOnlyHint |
215
+ |------|-------------|:---:|
216
+ | \`cognition_query\` | Query graph by context hash | ✅ |
217
+ | \`cognition_validate\` | Validate code against AST templates | ✅ |
218
+ | \`cognition_feedback\` | Provide feedback to refine traversal | ❌ |
219
+ | \`cognition_approve_injection\` | Approve/reject proposals with TTL | ❌ |
220
+ | \`cognition_update_config\` | Hot-update thresholds (expert mode) | ❌ |
221
+
222
+ ---
223
+
224
+ ## Testing
225
+
226
+ \`\`\`bash
227
+ # Run all tests (118/118 passing)
228
+ npm test
229
+
230
+ # Run specific suite
231
+ npx vitest run tests/protocol/
232
+ \`\`\`
233
+
234
+ ---
235
+
236
+ ## Protocol Compliance
237
+
238
+ This server conforms to **MCP Specification v1.29.0** and supports:
239
+
240
+ - [x] initialize / initialized / ping / shutdown lifecycle
241
+ - [x] tools/list + tools/call with JSON Schema input/output
242
+ - [x] resources/list + resources/read with \`cognition://\` URI scheme
243
+ - [x] StdioServerTransport and StreamableHTTPServerTransport
244
+ - [x] Error codes: -32602 (invalid params), -32603 (internal), -32001 (timeout)
245
+ - [x] Annotations: readOnlyHint, destructiveHint, openWorldHint
246
+
247
+ ---
248
+
249
+ ## Contributing
250
+
251
+ We welcome contributions from the community! Here's how you can get involved:
252
+
253
+ - **Report a bug**: Open an [issue](../../issues/new?labels=bug) with reproduction steps.
254
+ - **Suggest a feature**: Start a [discussion](../../discussions) to gather feedback before implementation.
255
+ - **Submit a PR**: Follow the guidelines in [CONTRIBUTING.md](CONTRIBUTING.md).
256
+
257
+ For major changes, please open an issue first to discuss what you would like to change.
258
+
259
+ ### 🟢 New to the project?
260
+
261
+ Looking for a place to start? Check out our [Good First Issues](../../issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) — they're specifically scoped for first-time contributors and include detailed context, acceptance criteria, and file references.
262
+
263
+ ---
264
+
265
+ ## License
266
+
267
+ Copyright (c) 2026 熊高锐
268
+
269
+ Licensed under the Apache License, Version 2.0 (the "License");
270
+ you may not use this file except in compliance with the License.
271
+ You may obtain a copy of the License at
272
+
273
+ http://www.apache.org/licenses/LICENSE-2.0
274
+
275
+ Unless required by applicable law or agreed to in writing, software
276
+ distributed under the License is distributed on an "AS IS" BASIS,
277
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
278
+ See the License for the specific language governing permissions and
279
+ limitations under the License.
280
+
281
+ Full license text: [LICENSE](LICENSE).
package/dist/cli.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Copyright 2026 熊高锐
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ export {};
18
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;GAcG"}
package/dist/cli.js ADDED
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Copyright 2026 熊高锐
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { execSync } from "child_process";
18
+ import { existsSync, mkdirSync } from "fs";
19
+ import { homedir } from "os";
20
+ import { join } from "path";
21
+ // ── Resolve database path ────────────────────────────────
22
+ const DB_PATH = process.env.COGNITION_DB_PATH ?? join(homedir(), ".cognition", "dev.db");
23
+ function resolveDbPath() {
24
+ const dir = DB_PATH.replace(/[/\\][^/\\]+$/, "");
25
+ if (!existsSync(dir)) {
26
+ try {
27
+ mkdirSync(dir, { recursive: true });
28
+ }
29
+ catch { /* ok */ }
30
+ }
31
+ return DB_PATH;
32
+ }
33
+ function ensureDatabase() {
34
+ const dbFile = resolveDbPath();
35
+ if (existsSync(dbFile))
36
+ return;
37
+ console.error("\ud83d\udd27 Initializing cognition database...");
38
+ const prismaSchema = join(import.meta.dirname, "..", "prisma", "schema.prisma");
39
+ if (!existsSync(prismaSchema)) {
40
+ console.error("Warning: prisma/schema.prisma not found — skipping auto-init");
41
+ return;
42
+ }
43
+ process.env.DATABASE_URL = `file:${dbFile}`;
44
+ try {
45
+ execSync("npx prisma db push --skip-generate", {
46
+ env: { ...process.env, DATABASE_URL: process.env.DATABASE_URL },
47
+ stdio: "inherit",
48
+ });
49
+ console.error("\u2705 Database initialized at", dbFile);
50
+ }
51
+ catch (err) {
52
+ console.error("\u2757 Database auto-init failed:", String(err));
53
+ console.error("You can run manually: npx prisma db push --skip-generate");
54
+ }
55
+ }
56
+ // ── Run server ────────────────────────────────────────────
57
+ ensureDatabase();
58
+ // Set env for the Prisma client used by the server
59
+ process.env.DATABASE_URL = `file:${resolveDbPath()}`;
60
+ // Now import and run the full server (same as src/index.ts but with
61
+ // DATABASE_URL already set)
62
+ import("./index.js").catch((err) => {
63
+ console.error("Fatal error:", err);
64
+ process.exit(1);
65
+ });
66
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAC3C,OAAO,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAC7B,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAE5B,4DAA4D;AAE5D,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,iBAAiB,IAAI,IAAI,CAAC,OAAO,EAAE,EAAE,YAAY,EAAE,QAAQ,CAAC,CAAC;AAEzF,SAAS,aAAa;IACpB,MAAM,GAAG,GAAG,OAAO,CAAC,OAAO,CAAC,eAAe,EAAE,EAAE,CAAC,CAAC;IACjD,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;QACrB,IAAI,CAAC;YAAC,SAAS,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QAAC,CAAC;QAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,CAAC;IACjE,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,SAAS,cAAc;IACrB,MAAM,MAAM,GAAG,aAAa,EAAE,CAAC;IAC/B,IAAI,UAAU,CAAC,MAAM,CAAC;QAAE,OAAO;IAE/B,OAAO,CAAC,KAAK,CAAC,iDAAiD,CAAC,CAAC;IAEjE,MAAM,YAAY,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,eAAe,CAAC,CAAC;IAChF,IAAI,CAAC,UAAU,CAAC,YAAY,CAAC,EAAE,CAAC;QAC9B,OAAO,CAAC,KAAK,CAAC,8DAA8D,CAAC,CAAC;QAC9E,OAAO;IACT,CAAC;IAED,OAAO,CAAC,GAAG,CAAC,YAAY,GAAG,QAAQ,MAAM,EAAE,CAAC;IAC5C,IAAI,CAAC;QACH,QAAQ,CAAC,oCAAoC,EAAE;YAC7C,GAAG,EAAE,EAAE,GAAG,OAAO,CAAC,GAAG,EAAE,YAAY,EAAE,OAAO,CAAC,GAAG,CAAC,YAAY,EAAE;YAC/D,KAAK,EAAE,SAAS;SACjB,CAAC,CAAC;QACH,OAAO,CAAC,KAAK,CAAC,gCAAgC,EAAE,MAAM,CAAC,CAAC;IAC1D,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,OAAO,CAAC,KAAK,CAAC,mCAAmC,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;QAChE,OAAO,CAAC,KAAK,CAAC,0DAA0D,CAAC,CAAC;IAC5E,CAAC;AACH,CAAC;AAED,6DAA6D;AAE7D,cAAc,EAAE,CAAC;AAEjB,mDAAmD;AACnD,OAAO,CAAC,GAAG,CAAC,YAAY,GAAG,QAAQ,aAAa,EAAE,EAAE,CAAC;AAErD,oEAAoE;AACpE,4BAA4B;AAC5B,MAAM,CAAC,YAAY,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;IACjC,OAAO,CAAC,KAAK,CAAC,cAAc,EAAE,GAAG,CAAC,CAAC;IACnC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC"}
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Copyright 2026 熊高锐
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import type { ASTNode } from "../types.js";
17
+ import type { CognitionNodeData } from "../storage/cognition-types.js";
18
+ import type { AstConstraint, ValidationResult, ValidationFailure, TransformPatch } from "./types.js";
19
+ /**
20
+ * Parse templateDsl JSON string into AstConstraint array.
21
+ */
22
+ export declare function parseConstraintDsl(dsl: string): AstConstraint[];
23
+ export interface BindingResult {
24
+ bound: AstConstraint[];
25
+ /** Map of placeholder → bound value */
26
+ bindings: Record<string, string>;
27
+ }
28
+ /**
29
+ * Bind {{placeholder}} values in a constraint to actual AST node text.
30
+ * Walks the AST to find nodes matching each constraint's nodeType,
31
+ * then extracts text values for placeholders.
32
+ */
33
+ export declare function bindConstraints(constraints: AstConstraint[], ast: ASTNode): BindingResult;
34
+ /**
35
+ * Validate an AST against a set of bound constraints.
36
+ *
37
+ * @param constraints Parsed + bound AstConstraint array
38
+ * @param nodeId Source cognition node ID (for traceability)
39
+ * @param templateDsl Original template DSL string
40
+ * @param ast Target AST to validate
41
+ * @returns Structured validation result
42
+ */
43
+ export declare function validateConstraints(constraints: AstConstraint[], nodeId: string, templateDsl: string, ast: ASTNode): ValidationResult;
44
+ /**
45
+ * Generate a transform patch from validation failures.
46
+ * Creates operations that would fix the validation failures.
47
+ */
48
+ export declare function generatePatchFromFailures(failures: ValidationFailure[], ast: ASTNode): TransformPatch[];
49
+ /**
50
+ * Run the full constraint-solving pipeline:
51
+ * 1. Parse templateDSL from cognition nodes
52
+ * 2. Parse file content to AST
53
+ * 3. Bind {{placeholder}} values
54
+ * 4. Validate constraints
55
+ * 5. Generate transform patches
56
+ *
57
+ * @param cognitionNodes Nodes with astTemplate to check
58
+ * @param fileContent Source code to validate against
59
+ * @param language Language for AST parsing
60
+ * @returns Validation + patch results
61
+ */
62
+ export declare function solveConstraints(cognitionNodes: CognitionNodeData[], fileContent: string, language: string): Promise<{
63
+ validations: ValidationResult[];
64
+ patches: TransformPatch[];
65
+ boundValues: Record<string, string>;
66
+ }>;
67
+ //# sourceMappingURL=ast-constraint-solver.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ast-constraint-solver.d.ts","sourceRoot":"","sources":["../../src/cognition-engine/ast-constraint-solver.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAaH,OAAO,KAAK,EAAE,OAAO,EAAiB,MAAM,aAAa,CAAC;AAC1D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AACvE,OAAO,KAAK,EACV,aAAa,EAEb,gBAAgB,EAChB,iBAAiB,EACjB,cAAc,EAEf,MAAM,YAAY,CAAC;AAIpB;;GAEG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,GAAG,aAAa,EAAE,CAe/D;AAkCD,MAAM,WAAW,aAAa;IAC5B,KAAK,EAAE,aAAa,EAAE,CAAC;IACvB,uCAAuC;IACvC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAClC;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAC7B,WAAW,EAAE,aAAa,EAAE,EAC5B,GAAG,EAAE,OAAO,GACX,aAAa,CAwBf;AAgCD;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CACjC,WAAW,EAAE,aAAa,EAAE,EAC5B,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,MAAM,EACnB,GAAG,EAAE,OAAO,GACX,gBAAgB,CA+BlB;AAmED;;;GAGG;AACH,wBAAgB,yBAAyB,CACvC,QAAQ,EAAE,iBAAiB,EAAE,EAC7B,GAAG,EAAE,OAAO,GACX,cAAc,EAAE,CAoClB;AAID;;;;;;;;;;;;GAYG;AACH,wBAAsB,gBAAgB,CACpC,cAAc,EAAE,iBAAiB,EAAE,EACnC,WAAW,EAAE,MAAM,EACnB,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC;IACT,WAAW,EAAE,gBAAgB,EAAE,CAAC;IAChC,OAAO,EAAE,cAAc,EAAE,CAAC;IAC1B,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACrC,CAAC,CA8BD"}