cmp-standards 3.5.0 → 3.7.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 (129) hide show
  1. package/README.md +399 -633
  2. package/dist/analytics/CrossProjectAnalytics.js +65 -65
  3. package/dist/cli/index.js +255 -12
  4. package/dist/cli/index.js.map +1 -1
  5. package/dist/dashboard/tokens.js +173 -173
  6. package/dist/db/client.d.ts.map +1 -1
  7. package/dist/db/client.js +2 -0
  8. package/dist/db/client.js.map +1 -1
  9. package/dist/db/cloud.d.ts +1 -0
  10. package/dist/db/cloud.d.ts.map +1 -1
  11. package/dist/db/drizzle-client.d.ts +2 -2
  12. package/dist/db/drizzle-client.d.ts.map +1 -1
  13. package/dist/db/drizzle-client.js +0 -1
  14. package/dist/db/drizzle-client.js.map +1 -1
  15. package/dist/db/migrations.js +256 -256
  16. package/dist/db/turso-client.js +2 -2
  17. package/dist/db/upstash-client.d.ts +9 -0
  18. package/dist/db/upstash-client.d.ts.map +1 -1
  19. package/dist/db/upstash-client.js +11 -0
  20. package/dist/db/upstash-client.js.map +1 -1
  21. package/dist/eslint/rules/no-async-useeffect.js +6 -6
  22. package/dist/experts/ExpertVotePersistence.js +9 -9
  23. package/dist/feedback/collector.d.ts.map +1 -1
  24. package/dist/feedback/collector.js +6 -2
  25. package/dist/feedback/collector.js.map +1 -1
  26. package/dist/hooks/cloud-post-tool-use.d.ts.map +1 -1
  27. package/dist/hooks/cloud-post-tool-use.js +72 -10
  28. package/dist/hooks/cloud-post-tool-use.js.map +1 -1
  29. package/dist/hooks/cloud-pre-tool-use.d.ts +12 -9
  30. package/dist/hooks/cloud-pre-tool-use.d.ts.map +1 -1
  31. package/dist/hooks/cloud-pre-tool-use.js +227 -99
  32. package/dist/hooks/cloud-pre-tool-use.js.map +1 -1
  33. package/dist/hooks/cloud-session-start.d.ts.map +1 -1
  34. package/dist/hooks/cloud-session-start.js +19 -16
  35. package/dist/hooks/cloud-session-start.js.map +1 -1
  36. package/dist/hooks/resilient-hook-runner.d.ts +78 -0
  37. package/dist/hooks/resilient-hook-runner.d.ts.map +1 -0
  38. package/dist/hooks/resilient-hook-runner.js +201 -0
  39. package/dist/hooks/resilient-hook-runner.js.map +1 -0
  40. package/dist/hooks/session-end.js +14 -14
  41. package/dist/patterns/registry.js +90 -90
  42. package/dist/registry/generator.d.ts.map +1 -1
  43. package/dist/registry/generator.js +31 -21
  44. package/dist/registry/generator.js.map +1 -1
  45. package/dist/schema/codewiki-types.d.ts +10 -10
  46. package/dist/schema/docs-types.d.ts +8 -8
  47. package/dist/schema/ecosystem-types.d.ts +12 -12
  48. package/dist/schema/expert-types.d.ts +2 -2
  49. package/dist/schema/opportunity-types.d.ts +6 -6
  50. package/dist/schema/tracking.d.ts +2 -2
  51. package/dist/services/BootstrapService.d.ts +123 -0
  52. package/dist/services/BootstrapService.d.ts.map +1 -0
  53. package/dist/services/BootstrapService.js +309 -0
  54. package/dist/services/BootstrapService.js.map +1 -0
  55. package/dist/services/CodeWikiIndexer.js +3 -3
  56. package/dist/services/ContextGenerator.js +7 -7
  57. package/dist/services/FeedbackCollector.js +11 -11
  58. package/dist/services/GitIntegration.d.ts.map +1 -1
  59. package/dist/services/GitIntegration.js +27 -23
  60. package/dist/services/GitIntegration.js.map +1 -1
  61. package/dist/services/HookVerifier.js +70 -70
  62. package/dist/services/KnowledgeGapDetector.d.ts +122 -0
  63. package/dist/services/KnowledgeGapDetector.d.ts.map +1 -0
  64. package/dist/services/KnowledgeGapDetector.js +530 -0
  65. package/dist/services/KnowledgeGapDetector.js.map +1 -0
  66. package/dist/services/ProjectScaffold.d.ts.map +1 -1
  67. package/dist/services/ProjectScaffold.js +79 -78
  68. package/dist/services/ProjectScaffold.js.map +1 -1
  69. package/dist/services/index.d.ts +4 -0
  70. package/dist/services/index.d.ts.map +1 -1
  71. package/dist/services/index.js +6 -0
  72. package/dist/services/index.js.map +1 -1
  73. package/dist/services/knowledge-graph.d.ts +121 -0
  74. package/dist/services/knowledge-graph.d.ts.map +1 -0
  75. package/dist/services/knowledge-graph.js +446 -0
  76. package/dist/services/knowledge-graph.js.map +1 -0
  77. package/dist/services/memory-router.d.ts +25 -0
  78. package/dist/services/memory-router.d.ts.map +1 -1
  79. package/dist/services/memory-router.js +236 -98
  80. package/dist/services/memory-router.js.map +1 -1
  81. package/dist/services/pattern-learning.d.ts +79 -0
  82. package/dist/services/pattern-learning.d.ts.map +1 -0
  83. package/dist/services/pattern-learning.js +312 -0
  84. package/dist/services/pattern-learning.js.map +1 -0
  85. package/dist/services/pattern-tracker.js +95 -95
  86. package/dist/services/semantic-search.d.ts.map +1 -1
  87. package/dist/services/semantic-search.js +12 -8
  88. package/dist/services/semantic-search.js.map +1 -1
  89. package/package.json +124 -116
  90. package/standards/README.md +94 -50
  91. package/standards/experts/expert-routing.md +215 -215
  92. package/standards/general/code-quality.md +86 -86
  93. package/standards/general/ecosystem.md +243 -0
  94. package/standards/general/learning-loop.md +192 -0
  95. package/standards/general/memory-usage.md +205 -205
  96. package/standards/general/project-onboarding.md +339 -0
  97. package/standards/general/sync-workflow.md +235 -235
  98. package/standards/general/workflow.md +82 -82
  99. package/standards/hooks/mandatory-tracking.md +446 -446
  100. package/standards/infrastructure/cloud-database.md +287 -287
  101. package/standards/mcp/server-design.md +243 -243
  102. package/standards/mcp/tool-patterns.md +354 -354
  103. package/standards/skills/skill-structure.md +286 -286
  104. package/standards/skills/workflow-design.md +323 -323
  105. package/standards/tools/tool-design.md +297 -297
  106. package/templates/agents/architecture-expert.md +61 -61
  107. package/templates/agents/database-expert.md +62 -62
  108. package/templates/agents/documentation-expert.md +57 -57
  109. package/templates/agents/ecosystem-expert.md +104 -0
  110. package/templates/agents/memory-expert.md +88 -88
  111. package/templates/agents/performance-expert.md +61 -61
  112. package/templates/agents/security-expert.md +59 -59
  113. package/templates/agents/ux-expert.md +63 -63
  114. package/templates/agents/worker.md +75 -75
  115. package/templates/ai-skills/SKILL_TEMPLATE.md +55 -55
  116. package/templates/claude-settings.json +72 -72
  117. package/templates/commands/experts.md +138 -138
  118. package/templates/hooks/README.md +158 -158
  119. package/templates/hooks/project.config.json.template +77 -77
  120. package/templates/hooks/settings.local.json.template +57 -57
  121. package/templates/hooks.config.json +21 -0
  122. package/templates/memory-config.json +56 -56
  123. package/templates/memory-config.schema.json +212 -212
  124. package/templates/settings.json +58 -58
  125. package/templates/skills/continue.md +205 -205
  126. package/templates/workflows/business-improvement.md +264 -264
  127. package/templates/workflows/expert-review.md +153 -153
  128. package/templates/workflows/internal-app.md +245 -245
  129. package/templates/workflows/sync-docs.md +187 -187
package/README.md CHANGED
@@ -1,633 +1,399 @@
1
- # CMP - Collective Memory Protocol
2
-
3
- > **The Development Intelligence Layer** - Persistent memory, cross-project learning, and multi-agent collaboration for AI-assisted development.
4
-
5
- [![npm version](https://img.shields.io/npm/v/cmp-standards.svg)](https://www.npmjs.com/package/cmp-standards)
6
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
-
8
- ---
9
-
10
- ## Philosophy
11
-
12
- | Principle | Meaning |
13
- |-----------|---------|
14
- | **Evidence > Assumptions** | Never assume. Always verify. Read before writing. |
15
- | **Cloud > Local** | Memory lives in the cloud. Sessions are ephemeral, knowledge is permanent. |
16
- | **Collective > Individual** | One project's learnings benefit all projects. |
17
- | **Continuity > Restarts** | Work survives IDE restarts, machine changes, and agent switches. |
18
-
19
- ---
20
-
21
- ## Features
22
-
23
- ### Core
24
- - **Plans with Checkpoints** - Persistent objectives with semantic matching and multi-agent handoffs
25
- - **ESLint Plugin** - 11+ custom rules for code quality
26
- - **Task Tracking** - Automatic task registration in database
27
- - **Idea Capture** - Collect ideas and improvements during work
28
- - **Memory System** - Session context and memory management
29
- - **Auto-Improvement** - Pattern detection and ESLint rule generation
30
- - **Dashboard** - Web UI for visualization
31
- - **MCP Server** - Model Context Protocol integration
32
- - **Analytics** - Usage tracking and insights
33
-
34
- ### Cloud Infrastructure
35
- - **Turso** (SQLite Edge) - Plans, tasks, improvements, memories
36
- - **Upstash Redis** - Session cache, rate limiting, real-time sync
37
- - **Upstash Vector** - Semantic search with embeddings
38
- - **Cloud Hooks** - Session continuity across IDE restarts
39
-
40
- ### Multi-Agent Continuity (v2.5.0+)
41
- - **Plan Detection** - Semantic matching finds related plans at session start
42
- - **Checkpoints** - Save points that record progress, decisions, and next steps
43
- - **Agent Handoffs** - One agent can resume where another left off
44
- - **Cross-Session** - Plans persist across IDE restarts and machine changes
45
-
46
- ## Cloud Quick Start
47
-
48
- ```typescript
49
- import { cloud } from 'cmp-standards'
50
-
51
- // Initialize cloud services
52
- await cloud.init()
53
-
54
- // Start work session
55
- const session = await cloud.startWorkSession('MYPROJECT')
56
- console.log(`Active tasks: ${session.activeTasks.length}`)
57
-
58
- // Start task
59
- const taskId = await cloud.startTask('MYPROJECT', session.sessionId, {
60
- title: 'Implement feature X',
61
- plan: ['Step 1', 'Step 2'],
62
- domain: 'features'
63
- })
64
-
65
- // Complete task (requires at least 1 improvement)
66
- await cloud.completeTask(taskId, {
67
- result: 'success',
68
- improvements: [{
69
- area: 'features',
70
- title: 'Add caching',
71
- description: 'Could cache API responses',
72
- priority: 'medium'
73
- }],
74
- lessons: ['Pattern X works better']
75
- })
76
- ```
77
-
78
- ## Environment Variables
79
-
80
- ```env
81
- # Turso (SQLite Edge)
82
- TURSO_DATABASE_URL=libsql://your-db.turso.io
83
- TURSO_AUTH_TOKEN=your-token
84
-
85
- # Upstash Redis
86
- UPSTASH_REDIS_REST_URL=https://your-redis.upstash.io
87
- UPSTASH_REDIS_REST_TOKEN=your-token
88
-
89
- # Upstash Vector
90
- UPSTASH_VECTOR_REST_URL=https://your-vector.upstash.io
91
- UPSTASH_VECTOR_REST_TOKEN=your-token
92
- ```
93
-
94
- ## Installation
95
-
96
- ```bash
97
- npm install cmp-standards
98
- ```
99
-
100
- ## Quick Start
101
-
102
- ```bash
103
- # Initialize in project
104
- cmp-standards init --system MYPROJECT --name "My Project"
105
-
106
- # Check status
107
- cmp-standards status
108
-
109
- # Start dashboard
110
- cmp-standards dashboard
111
- ```
112
-
113
- ## CLI Commands
114
-
115
- ### `cmp-standards init`
116
-
117
- Initialize the system in current project.
118
-
119
- ```bash
120
- cmp-standards init [options]
121
-
122
- Options:
123
- -s, --system <system> System identifier (SWARMSCALE, PANEL)
124
- -n, --name <name> Project name
125
- -f, --force Overwrite existing configuration
126
- ```
127
-
128
- ### `cmp-standards generate`
129
-
130
- Generate embedding registry from documentation.
131
-
132
- ```bash
133
- cmp-standards generate [options]
134
-
135
- Options:
136
- -i, --incremental Only update changed files
137
- --files <files> Specific files (comma-separated)
138
- ```
139
-
140
- ### `cmp-standards scan`
141
-
142
- Scan codebase for patterns.
143
-
144
- ```bash
145
- cmp-standards scan [options]
146
-
147
- Options:
148
- -d, --dir <directory> Directory to scan (default: src)
149
- -t, --threshold <n> Pattern threshold (default: 3)
150
- ```
151
-
152
- ### `cmp-standards improve`
153
-
154
- Run auto-improvement for triggered patterns.
155
-
156
- ```bash
157
- cmp-standards improve [options]
158
-
159
- Options:
160
- --dry-run Show without making changes
161
- -p, --pattern <id> Specific pattern to improve
162
- ```
163
-
164
- ### `cmp-standards status`
165
-
166
- Show memory system status.
167
-
168
- ### `cmp-standards dashboard`
169
-
170
- Start the memory dashboard web UI.
171
-
172
- ```bash
173
- cmp-standards dashboard [options]
174
-
175
- Options:
176
- -p, --port <port> Port to run on (default: 3847)
177
- --no-open Don't open browser automatically
178
- ```
179
-
180
- ### `cmp-standards analytics`
181
-
182
- Show analytics and system health.
183
-
184
- ```bash
185
- cmp-standards analytics [options]
186
-
187
- Options:
188
- -p, --period <period> Time period (day, week, month)
189
- --json Output as JSON
190
- ```
191
-
192
- ### `cmp-standards feedback`
193
-
194
- View feedback statistics.
195
-
196
- ### `cmp-standards mcp`
197
-
198
- Start the MCP server for Claude integration.
199
-
200
- ---
201
-
202
- ## Workflow Commands
203
-
204
- ### `cmp-standards tasks`
205
-
206
- View and manage tasks.
207
-
208
- ```bash
209
- cmp-standards tasks [options]
210
-
211
- Options:
212
- -a, --all Show all tasks including completed
213
- -l, --limit <number> Limit number of tasks (default: 10)
214
- ```
215
-
216
- ### `cmp-standards ideas`
217
-
218
- View captured ideas.
219
-
220
- ```bash
221
- cmp-standards ideas [options]
222
-
223
- Options:
224
- -c, --category <cat> Filter by category (feature, refactor, bug, optimization, documentation)
225
- -p, --priority <pri> Filter by priority (high, medium, low)
226
- -l, --limit <number> Limit number of ideas (default: 20)
227
- ```
228
-
229
- ### `cmp-standards improvements`
230
-
231
- View suggested improvements.
232
-
233
- ```bash
234
- cmp-standards improvements [options]
235
-
236
- Options:
237
- -t, --type <type> Filter by type (code_quality, performance, security, ux, architecture)
238
- -e, --effort <effort> Filter by effort (small, medium, large)
239
- -l, --limit <number> Limit number (default: 20)
240
- ```
241
-
242
- ### `cmp-standards plan`
243
-
244
- Manage work plans.
245
-
246
- ```bash
247
- cmp-standards plan [options]
248
-
249
- Options:
250
- -s, --status Show current plan status
251
- -c, --complete Complete current task
252
- -n, --next Move to next task
253
- -h, --history Show plan history
254
- ```
255
-
256
- ### `cmp-standards capture <text>`
257
-
258
- Quick capture an idea or improvement. Auto-categorizes based on content.
259
-
260
- ```bash
261
- cmp-standards capture "Consider adding caching to API calls"
262
- ```
263
-
264
- ### `cmp-standards export`
265
-
266
- Export ideas and improvements as markdown.
267
-
268
- ```bash
269
- cmp-standards export [options]
270
-
271
- Options:
272
- -o, --output <file> Output file (default: IDEAS_AND_IMPROVEMENTS.md)
273
- ```
274
-
275
- ---
276
-
277
- ## Architecture
278
-
279
- ```
280
- cmp-standards
281
- ├── src/
282
- │ ├── hooks/
283
- │ │ ├── session-start.ts # Context loader on session start
284
- │ │ ├── pre-tool-use.ts # Guards + embedding injection
285
- │ │ ├── post-tool-use.ts # Record changes after Edit/Write
286
- │ │ └── memory-checkpoint.ts # Record learnings after changes
287
- │ ├── eslint/
288
- │ │ ├── index.ts # ESLint plugin entry
289
- │ │ ├── rules/ # Custom ESLint rules
290
- │ │ └── config-builder.ts # Dynamic config generation
291
- │ ├── services/
292
- │ │ ├── TaskTracker.ts # Task tracking
293
- │ │ ├── IdeaCollector.ts # Idea/improvement capture
294
- │ │ ├── WorkPlanManager.ts # Work plan management
295
- │ │ └── ... # Other services
296
- │ ├── registry/
297
- │ │ ├── generator.ts # Parse docs → embeddings
298
- │ │ └── embeddings.ts # OpenAI/Gemini embedding service
299
- │ ├── auto-improve/
300
- │ │ ├── pattern-detector.ts # Detect repeated violations
301
- │ │ └── eslint-generator.ts # Generate ESLint rules
302
- │ ├── db/
303
- │ │ ├── client.ts # DEV_Items database client (mock)
304
- │ │ └── drizzle-client.ts # Real Drizzle ORM client
305
- │ ├── mcp/
306
- │ │ └── server.ts # MCP server for Claude tools
307
- │ ├── dashboard/
308
- │ │ ├── server.ts # Express dashboard server
309
- │ │ └── ui.ts # React UI generator
310
- │ ├── utils/
311
- │ │ ├── config.ts # Configuration management
312
- │ │ ├── paths.ts # Path utilities with traversal protection
313
- │ │ └── git.ts # Safe git operations (simple-git)
314
- │ ├── types/
315
- │ │ └── index.ts # Type definitions
316
- │ ├── cli/
317
- │ │ └── index.ts # CLI commands
318
- │ └── index.ts # Main exports
319
- ```
320
-
321
- ## Configuration
322
-
323
- ### `.claude/memory-config.json`
324
-
325
- ```json
326
- {
327
- "system": "SWARMSCALE",
328
- "projectName": "SwarmScale",
329
- "domains": ["video-studio", "avatars", "campaigns"],
330
- "guards": {
331
- "enabled": true,
332
- "rules": [
333
- {
334
- "id": "schema-protection",
335
- "type": "block",
336
- "filePattern": "src/server/schema/auth.ts",
337
- "message": "PANEL_* tables are READ-ONLY"
338
- }
339
- ]
340
- },
341
- "embedding": {
342
- "enabled": true,
343
- "threshold": 0.60,
344
- "maxSections": 3
345
- },
346
- "autoImprovement": {
347
- "enabled": true,
348
- "violationThreshold": 3,
349
- "generateEslintRules": true
350
- }
351
- }
352
- ```
353
-
354
- ### `.claude/settings.json`
355
-
356
- ```json
357
- {
358
- "hooks": {
359
- "PreToolUse": [
360
- {
361
- "matcher": "Task",
362
- "hooks": [{
363
- "type": "command",
364
- "command": "npx tsx node_modules/cmp-standards/dist/hooks/pre-tool-use.js"
365
- }]
366
- }
367
- ],
368
- "SessionStart": [
369
- {
370
- "matcher": "",
371
- "hooks": [{
372
- "type": "command",
373
- "command": "npx tsx node_modules/cmp-standards/dist/hooks/session-start.js"
374
- }]
375
- }
376
- ]
377
- },
378
- "plugins": {
379
- "cmp-standards": {
380
- "version": "2.0.0",
381
- "enabled": true
382
- }
383
- }
384
- }
385
- ```
386
-
387
- ## Hooks
388
-
389
- ### SessionStart Hook
390
-
391
- Executes on session start:
392
- 1. Detects module from `git diff` (last 24h)
393
- 2. Queries DEV_Items for relevant memories
394
- 3. Returns formatted context
395
-
396
- ```typescript
397
- import { SessionStartHook } from 'cmp-standards/hooks'
398
-
399
- const hook = new SessionStartHook()
400
- const result = await hook.execute()
401
- // result.context contains session context
402
- ```
403
-
404
- ### PreToolUse Hook
405
-
406
- Executes before Edit/Write/Task tools:
407
- 1. **Edit/Write**: Validates against guard rules
408
- 2. **Task**: Injects relevant knowledge via embeddings
409
-
410
- ```typescript
411
- import { PreToolUseHook } from 'cmp-standards/hooks'
412
-
413
- const hook = new PreToolUseHook()
414
- const result = await hook.execute({
415
- tool_name: 'Edit',
416
- parameters: { file_path: 'src/file.ts', new_string: '...' }
417
- })
418
-
419
- if (result.mode === 'block') {
420
- // Guard violation - block operation
421
- }
422
- ```
423
-
424
- ## ESLint Plugin
425
-
426
- The package includes a custom ESLint plugin with 11+ rules.
427
-
428
- ### Using the ESLint Plugin
429
-
430
- ```javascript
431
- // eslint.config.mjs
432
- import cmpStandards from 'cmp-standards/eslint'
433
-
434
- export default [
435
- ...cmpStandards.configs.recommended,
436
- ]
437
- ```
438
-
439
- ### Dynamic Configuration
440
-
441
- ```typescript
442
- import { generateConfig } from 'cmp-standards/eslint'
443
-
444
- // Generate config based on project structure
445
- const config = await generateConfig(process.cwd())
446
- ```
447
-
448
- ## Auto-Improvement
449
-
450
- ### Pattern Detection
451
-
452
- Built-in patterns detected:
453
- - `any-type` - Using `any` type
454
- - `console-log` - Console.log in production
455
- - `eslint-disable` - ESLint disable comments
456
- - `hardcoded-string` - UI strings not using i18n
457
- - `direct-db-query` - Database queries in components
458
- - `inline-style` - Inline styles instead of Tailwind
459
-
460
- ### ESLint Rule Generation
461
-
462
- When a pattern is detected 3+ times:
463
-
464
- ```bash
465
- # Scan for patterns
466
- cmp-standards scan
467
-
468
- # Output:
469
- # any-type [high]
470
- # Count: 5, Files: 3
471
- # Patterns ready for auto-improvement
472
-
473
- # Generate ESLint rule
474
- cmp-standards improve
475
-
476
- # Creates: eslint-plugin-charter/rules/no-any-type.js
477
- ```
478
-
479
- ## Programmatic Usage
480
-
481
- ```typescript
482
- import {
483
- loadConfig,
484
- PatternDetector,
485
- ESLintGenerator,
486
- RegistryGenerator
487
- } from 'cmp-standards'
488
-
489
- // Load config
490
- const config = await loadConfig(process.cwd())
491
-
492
- // Detect patterns
493
- const detector = new PatternDetector(config)
494
- const patterns = detector.scan(fileContent, filePath)
495
- const results = detector.getResults()
496
-
497
- // Generate ESLint rules
498
- const generator = new ESLintGenerator()
499
- await generator.generateAllRules(results.triggered)
500
-
501
- // Generate registry
502
- const registry = new RegistryGenerator()
503
- await registry.generate()
504
- ```
505
-
506
- ## System Isolation
507
-
508
- Data is isolated by `system` field in DEV_Items:
509
-
510
- | System | Project |
511
- |--------|---------|
512
- | `SWARMSCALE` | SwarmScale |
513
- | `PANEL` | TheCharterPanel |
514
- | `ECOSYSTEM` | Cross-project |
515
-
516
- Always filter by system:
517
-
518
- ```typescript
519
- // Correct
520
- db.select().from(devItems).where(eq(devItems.system, 'SWARMSCALE'))
521
-
522
- // Wrong - returns ALL projects' data
523
- db.select().from(devItems)
524
- ```
525
-
526
- ## Security Features
527
-
528
- ### Path Traversal Protection
529
-
530
- All path operations are validated to prevent directory traversal attacks:
531
-
532
- ```typescript
533
- import { validateSafePath, safeJoin } from 'cmp-standards'
534
-
535
- // Throws PathTraversalError if path escapes base
536
- validateSafePath(projectRoot, userPath)
537
-
538
- // Safe path joining with validation
539
- const safePath = safeJoin(projectRoot, 'subdir', filename)
540
- ```
541
-
542
- ### Safe Git Operations
543
-
544
- Git operations use `simple-git` instead of shell commands to prevent command injection:
545
-
546
- ```typescript
547
- import { getCurrentBranch, getRecentChanges } from 'cmp-standards'
548
-
549
- // Safe - uses simple-git internally
550
- const branch = await getCurrentBranch(projectRoot)
551
- const changes = await getRecentChanges(projectRoot, { commits: 10 })
552
- ```
553
-
554
- ## Environment Variables
555
-
556
- ```bash
557
- # Required for embedding generation
558
- OPENAI_API_KEY=sk-... # Preferred
559
- GEMINI_API_KEY=... # Fallback
560
-
561
- # Optional
562
- MEMORY_DEBUG=true # Enable debug logging
563
- ```
564
-
565
- ## Development
566
-
567
- ```bash
568
- # Install dependencies
569
- npm install
570
-
571
- # Build
572
- npm run build
573
-
574
- # Watch mode
575
- npm run dev
576
-
577
- # Run tests
578
- npm test
579
-
580
- # Link for local development
581
- npm link
582
- ```
583
-
584
- ## MCP Server
585
-
586
- The MCP (Model Context Protocol) server exposes memory tools that Claude can use directly:
587
-
588
- ```bash
589
- # Start MCP server
590
- cmp-standards mcp
591
- ```
592
-
593
- **Available Tools:**
594
- - `memory_search` - Search memories by query
595
- - `memory_write` - Write new memory/learning
596
- - `memory_list` - List recent memories
597
- - `pattern_check` - Check for detected patterns
598
- - `pattern_report` - Report a new pattern occurrence
599
- - `session_context` - Get current session context
600
- - `feedback_submit` - Submit feedback on a memory
601
-
602
- ## Dashboard
603
-
604
- Start the standalone web dashboard:
605
-
606
- ```bash
607
- cmp-standards dashboard
608
- # Opens http://localhost:3847
609
- ```
610
-
611
- **Features:**
612
- - View all memories with search and filtering
613
- - Browse detected patterns
614
- - See session history
615
- - Submit feedback on memories
616
- - Create new memories
617
- - View analytics and system health
618
-
619
- ## Database Configuration
620
-
621
- Set environment variables for database connection:
622
-
623
- ```bash
624
- DATABASE_HOST=localhost
625
- DATABASE_PORT=3306
626
- DATABASE_USER=root
627
- DATABASE_PASSWORD=your-password
628
- DATABASE_NAME=metanautical
629
- ```
630
-
631
- ## License
632
-
633
- MIT - Carlos Martin Pavon
1
+ # CMP - Collective Memory Protocol
2
+
3
+ > **For AI Agents, By AI Agents** - The Development Intelligence Layer
4
+
5
+ [![npm version](https://img.shields.io/npm/v/cmp-standards.svg)](https://www.npmjs.com/package/cmp-standards)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
+
8
+ ---
9
+
10
+ ## What is CMP?
11
+
12
+ CMP is an **agent-first protocol** that gives AI coding assistants (Claude, Gemini, GPT, etc.) persistent memory across sessions, cross-project learning, and multi-agent collaboration capabilities.
13
+
14
+ **The Problem**: AI assistants forget everything when a session ends. They can't learn from past mistakes. They can't share knowledge between projects.
15
+
16
+ **The Solution**: CMP creates a shared intelligence layer where:
17
+ - Errors become learning opportunities (Learning Loop)
18
+ - One project's lessons benefit all your projects (Cross-Project Sync)
19
+ - Work survives session restarts (Persistent Plans)
20
+ - Multiple agents can collaborate on the same project (Multi-Agent Handoffs)
21
+
22
+ **Created by Carlos Martin Pavón** as a personal methodology for working with AI agents across projects. Open source and adaptable to anyone's workflow.
23
+
24
+ ---
25
+
26
+ ## For AI Agents: Self-Installation Guide
27
+
28
+ > **AI Agent**: Follow these instructions to install CMP in any project.
29
+
30
+ ### Step 1: Install Package
31
+
32
+ ```bash
33
+ npm install cmp-standards
34
+ ```
35
+
36
+ ### Step 2: Initialize Project
37
+
38
+ ```bash
39
+ npx cmp-standards init --system PROJECT_CODE --name "Project Name"
40
+ ```
41
+
42
+ Replace `PROJECT_CODE` with a unique identifier for this project (e.g., `MYAPP`, `WEBAPP`, `API`).
43
+
44
+ ### Step 3: Create CLAUDE.md
45
+
46
+ Create or update the project's `CLAUDE.md` with this template:
47
+
48
+ ```markdown
49
+ # CLAUDE.md - [Project Name]
50
+
51
+ > **System**: [PROJECT_CODE]
52
+ > **CMP Version**: 3.7.0
53
+
54
+ ## CMP Integration
55
+
56
+ This project uses **Collective Memory Protocol** for persistent memory.
57
+
58
+ ### Session Start
59
+ On session start, check for:
60
+ - Active work plans: Query DEV_Items where system='PROJECT_CODE' AND status='in_progress'
61
+ - Learning Loop status: Check pending errors for knowledge extraction
62
+ - Cross-project knowledge: Query DEV_Items where system='SHARED'
63
+
64
+ ### Memory Commands
65
+ - `npm run ai:health` - Check system health
66
+ - `npm run ai:distill` - Extract knowledge from pending items
67
+
68
+ ### Core Rules
69
+ - Filter database queries by `system='PROJECT_CODE'`
70
+ - Use shared knowledge with `system='SHARED'`
71
+ - Record significant decisions in DEV_Items
72
+ ```
73
+
74
+ ### Step 4: Set Up Database
75
+
76
+ CMP uses a `DEV_Items` table to store all knowledge, tasks, and learnings:
77
+
78
+ ```sql
79
+ CREATE TABLE DEV_Items (
80
+ id VARCHAR(255) PRIMARY KEY,
81
+ system VARCHAR(50) NOT NULL, -- Project identifier
82
+ type ENUM('task', 'memory', 'knowledge', 'pattern', 'error') NOT NULL,
83
+ status ENUM('pending', 'in_progress', 'done', 'archived') DEFAULT 'pending',
84
+ priority ENUM('critical', 'high', 'medium', 'low') DEFAULT 'medium',
85
+ content JSON NOT NULL, -- Flexible content storage
86
+ tags JSON, -- Searchable tags
87
+ created_at TIMESTAMP DEFAULT NOW(),
88
+ updated_at TIMESTAMP DEFAULT NOW()
89
+ );
90
+ ```
91
+
92
+ ### Step 5: Configure Hooks (Optional - Claude Code)
93
+
94
+ For Claude Code, add to `.claude/settings.json`:
95
+
96
+ ```json
97
+ {
98
+ "hooks": {
99
+ "SessionStart": [{
100
+ "matcher": "",
101
+ "hooks": [{
102
+ "type": "command",
103
+ "command": "npx tsx node_modules/cmp-standards/dist/hooks/cloud-session-start.js"
104
+ }]
105
+ }]
106
+ }
107
+ }
108
+ ```
109
+
110
+ ---
111
+
112
+ ## Philosophy
113
+
114
+ | Principle | Meaning |
115
+ |-----------|---------|
116
+ | **Evidence > Assumptions** | Never assume. Always verify. Read before writing. |
117
+ | **Cloud > Local** | Memory lives in the database. Sessions are ephemeral, knowledge is permanent. |
118
+ | **Collective > Individual** | One project's learnings benefit all your projects. |
119
+ | **Continuity > Restarts** | Work survives IDE restarts, machine changes, and agent switches. |
120
+
121
+ ---
122
+
123
+ ## How It Works
124
+
125
+ ### The DEV_Items Table
126
+
127
+ All knowledge is stored in a single, flexible table:
128
+
129
+ ```
130
+ ┌─────────────────────────────────────────────────────────────────┐
131
+ │ DEV_Items │
132
+ ├─────────────────────────────────────────────────────────────────┤
133
+ │ │
134
+ │ Project A (system='WEBAPP') │
135
+ │ ├── task: "Implement auth" │
136
+ ├── knowledge: "JWT works better than sessions" │
137
+ └── pattern: "Always validate inputs with Zod" │
138
+ │ │
139
+ │ Project B (system='API') │
140
+ │ ├── task: "Add rate limiting" │
141
+ │ └── error: "Redis connection timeout" │
142
+ │ │
143
+ │ Shared (system='SHARED') │
144
+ │ ├── knowledge: "Use semantic tokens for colors" │
145
+ │ └── pattern: "Never use any type" │
146
+ │ │
147
+ └─────────────────────────────────────────────────────────────────┘
148
+ ```
149
+
150
+ ### Learning Loop
151
+
152
+ CMP automatically converts errors into knowledge:
153
+
154
+ ```
155
+ CAPTURE → ANALYZE → DISTILL → PREVENT
156
+ ↓ ↓ ↓ ↓
157
+ Errors Patterns Knowledge Rules
158
+ ```
159
+
160
+ 1. **Errors** are logged with context
161
+ 2. **Patterns** emerge when errors repeat (≥3 times)
162
+ 3. **Knowledge** is extracted (Rules, Patterns, Gotchas)
163
+ 4. **Rules** are generated (ESLint, guidelines) to prevent recurrence
164
+
165
+ ---
166
+
167
+ ## Adapt to Your Workflow
168
+
169
+ CMP is designed to be **flexible**. You can:
170
+
171
+ ### Use Your Own Database
172
+
173
+ ```typescript
174
+ // MySQL, PostgreSQL, SQLite - any database works
175
+ import { initCMP } from 'cmp-standards'
176
+
177
+ await initCMP({
178
+ database: {
179
+ type: 'mysql',
180
+ connectionString: process.env.DATABASE_URL
181
+ }
182
+ })
183
+ ```
184
+
185
+ ### Define Your Own Systems
186
+
187
+ ```typescript
188
+ // Your projects, your naming
189
+ const systems = {
190
+ FRONTEND: 'React web app',
191
+ BACKEND: 'Node.js API',
192
+ MOBILE: 'React Native app',
193
+ SHARED: 'Cross-project knowledge'
194
+ }
195
+ ```
196
+
197
+ ### Customize Knowledge Types
198
+
199
+ ```typescript
200
+ // Extend the content schema for your needs
201
+ const customTypes = ['task', 'bug', 'feature', 'learning', 'decision']
202
+ ```
203
+
204
+ ---
205
+
206
+ ## Agent Compatibility
207
+
208
+ CMP works with any AI coding assistant:
209
+
210
+ | Agent | Integration |
211
+ |-------|-------------|
212
+ | **Claude Code** | Full integration via hooks, commands, MCP |
213
+ | **Cursor** | Read CLAUDE.md, use CLI commands |
214
+ | **GitHub Copilot** | Read CLAUDE.md, use CLI commands |
215
+ | **Gemini** | Read CLAUDE.md, use CLI commands |
216
+ | **Custom Agents** | Use programmatic API |
217
+
218
+ ### Universal Agent Instructions
219
+
220
+ For any AI agent to use CMP:
221
+
222
+ 1. **Read** `CLAUDE.md` for project context
223
+ 2. **Query** `DEV_Items` for relevant knowledge
224
+ 3. **Filter** by `system='PROJECT_CODE'` for project-specific data
225
+ 4. **Record** learnings back to `DEV_Items`
226
+ 5. **Check** `system='SHARED'` for cross-project patterns
227
+
228
+ ---
229
+
230
+ ## CLI Commands
231
+
232
+ ```bash
233
+ # Initialize project
234
+ cmp-standards init --system CODE --name "Name"
235
+
236
+ # Check system status
237
+ cmp-standards status
238
+
239
+ # Generate embeddings for semantic search
240
+ cmp-standards generate
241
+
242
+ # Scan codebase for patterns
243
+ cmp-standards scan
244
+
245
+ # Run auto-improvement
246
+ cmp-standards improve
247
+
248
+ # Start visual dashboard
249
+ cmp-standards dashboard
250
+
251
+ # Start MCP server (for Claude tools)
252
+ cmp-standards mcp
253
+ ```
254
+
255
+ ---
256
+
257
+ ## Multi-Agent Collaboration
258
+
259
+ ### Plans with Checkpoints
260
+
261
+ When an agent can't finish in one session:
262
+
263
+ ```typescript
264
+ import { PlanManager } from 'cmp-standards'
265
+
266
+ // Agent 1: Start work
267
+ await PlanManager.createPlan({
268
+ objective: 'Implement user authentication',
269
+ tasks: ['Design schema', 'Create API', 'Build UI']
270
+ })
271
+
272
+ // Agent 1: Save progress before session ends
273
+ await PlanManager.saveCheckpoint({
274
+ progress: 'Completed schema design',
275
+ decisions: ['Using JWT tokens'],
276
+ nextSteps: ['Implement login endpoint']
277
+ })
278
+
279
+ // Agent 2 (new session): Resume work
280
+ const plans = await PlanManager.findActivePlans()
281
+ await PlanManager.resumePlan(plans[0].id)
282
+ // Agent 2 knows exactly where Agent 1 left off
283
+ ```
284
+
285
+ ### Expert Code Review
286
+
287
+ Built-in multi-expert review system:
288
+
289
+ ```bash
290
+ /experts src/path/to/file.ts
291
+ ```
292
+
293
+ Experts include: Security, Performance, Architecture, UX, Database, Memory
294
+
295
+ ---
296
+
297
+ ## Programmatic API
298
+
299
+ ```typescript
300
+ import { cloud, PatternDetector, PlanManager } from 'cmp-standards'
301
+
302
+ // Initialize
303
+ await cloud.init()
304
+
305
+ // Start work session
306
+ const session = await cloud.startWorkSession('MYPROJECT')
307
+
308
+ // Create task
309
+ const taskId = await cloud.startTask('MYPROJECT', session.sessionId, {
310
+ title: 'Implement feature X',
311
+ domain: 'features'
312
+ })
313
+
314
+ // Complete with learnings
315
+ await cloud.completeTask(taskId, {
316
+ result: 'success',
317
+ improvements: [{ title: 'Add caching', priority: 'medium' }],
318
+ lessons: ['Pattern X works well for this use case']
319
+ })
320
+ ```
321
+
322
+ ---
323
+
324
+ ## Quick Start Checklist
325
+
326
+ For AI Agents setting up CMP in a new project:
327
+
328
+ ```
329
+ 1. npm install cmp-standards
330
+ □ 2. npx cmp-standards init --system CODE --name "Name"
331
+ 3. Create/update CLAUDE.md with CMP section
332
+ 4. Set up DEV_Items table in your database
333
+ □ 5. Run: cmp-standards status
334
+ 6. Start recording knowledge!
335
+ ```
336
+
337
+ ---
338
+
339
+ ## Standards Documentation
340
+
341
+ CMP includes documentation standards for AI agents:
342
+
343
+ ```
344
+ standards/
345
+ ├── general/
346
+ │ ├── workflow.md # Working with AI agents
347
+ │ ├── code-quality.md # Code standards
348
+ │ ├── memory-usage.md # Memory system usage
349
+ │ ├── learning-loop.md # Error→Knowledge cycle
350
+ │ └── project-onboarding.md # New project setup
351
+ ├── mcp/
352
+ │ └── server-design.md # MCP server patterns
353
+ └── skills/
354
+ └── skill-structure.md # Skill file format
355
+ ```
356
+
357
+ ---
358
+
359
+ ## Why CMP?
360
+
361
+ **Before CMP:**
362
+ - Agent forgets everything each session
363
+ - Same mistakes repeated across projects
364
+ - No way to share learnings
365
+ - Work lost on session restart
366
+
367
+ **After CMP:**
368
+ - Persistent memory in database
369
+ - Errors become documented knowledge
370
+ - Cross-project learning
371
+ - Seamless multi-agent handoffs
372
+
373
+ ---
374
+
375
+ ## Contributing
376
+
377
+ This is an open protocol. Contributions welcome:
378
+
379
+ 1. Fork the repository
380
+ 2. Create feature branch
381
+ 3. Submit pull request
382
+
383
+ ---
384
+
385
+ ## Links
386
+
387
+ - **npm**: [npmjs.com/package/cmp-standards](https://www.npmjs.com/package/cmp-standards)
388
+ - **GitHub**: [github.com/carlosmartinpavon/carlosmartinpavon](https://github.com/carlosmartinpavon/carlosmartinpavon)
389
+ - **Author**: [Carlos Martin Pavón](https://carlosmartinpavon.com)
390
+
391
+ ---
392
+
393
+ ## License
394
+
395
+ MIT - Carlos Martin Pavón
396
+
397
+ ---
398
+
399
+ *Built by agents, for agents. Adapt it to your workflow.*