myaidev-method 0.2.1 → 0.2.2

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.
@@ -0,0 +1,1868 @@
1
+ # MyAIDev Method - Technical Architecture Guide
2
+
3
+ **Version**: 0.2.1
4
+ **Target Audience**: Developers, System Architects, Contributors
5
+ **Last Updated**: 2025-10-16
6
+
7
+ ## Table of Contents
8
+
9
+ 1. [System Overview](#system-overview)
10
+ 2. [Architecture Patterns](#architecture-patterns)
11
+ 3. [Core Components](#core-components)
12
+ 4. [Publishing System](#publishing-system)
13
+ 5. [Deployment System](#deployment-system)
14
+ 6. [Agent System](#agent-system)
15
+ 7. [Integration Patterns](#integration-patterns)
16
+ 8. [Data Flow](#data-flow)
17
+ 9. [Extension Guide](#extension-guide)
18
+ 10. [Testing Strategy](#testing-strategy)
19
+
20
+ ---
21
+
22
+ ## System Overview
23
+
24
+ ### Purpose
25
+
26
+ MyAIDev Method is an AI-powered CLI toolkit that provides:
27
+ - **Multi-platform content publishing** (WordPress, PayloadCMS, Docusaurus, Mintlify, Astro)
28
+ - **Application deployment** (Coolify)
29
+ - **AI agents** for automated workflows
30
+ - **Claude Code 2.0 integration** via slash commands and agents
31
+
32
+ ### Technology Stack
33
+
34
+ ```yaml
35
+ Runtime:
36
+ - Node.js: >=18.0.0
37
+ - Module System: ES Modules (type: "module")
38
+
39
+ Core Dependencies:
40
+ - @modelcontextprotocol/sdk: ^1.18.0 # MCP protocol integration
41
+ - marked: ^11.0.0 # Markdown parsing
42
+ - gray-matter: ^4.0.3 # Frontmatter parsing
43
+ - simple-git: ^3.22.0 # Git operations
44
+ - node-fetch: ^3.3.2 # HTTP requests
45
+ - chalk: ^5.3.0 # Terminal styling
46
+ - commander: ^12.0.0 # CLI framework
47
+ - inquirer: ^9.2.15 # Interactive prompts
48
+ - ora: ^8.0.1 # Terminal spinners
49
+ - dotenv: ^16.4.1 # Environment config
50
+ - fs-extra: ^11.2.0 # File operations
51
+ - ssh2: ^1.15.0 # SSH integration
52
+ - zod: ^3.23.8 # Schema validation
53
+
54
+ Development:
55
+ - Test Framework: Custom node-based test runner
56
+ - Build System: npm scripts + file copying
57
+ - Distribution: npm registry
58
+ ```
59
+
60
+ ### Project Structure
61
+
62
+ ```
63
+ myaidev-method/
64
+ ├── bin/
65
+ │ └── cli.js # Main CLI entry point
66
+ ├── src/
67
+ │ ├── lib/ # Core utility libraries
68
+ │ │ ├── payloadcms-utils.js # PayloadCMS API wrapper
69
+ │ │ ├── static-site-utils.js # Unified static site publishing
70
+ │ │ ├── coolify-utils.js # Coolify deployment wrapper
71
+ │ │ ├── wordpress-admin-utils.js # WordPress administration
72
+ │ │ └── report-synthesizer.js # Report generation
73
+ │ ├── scripts/ # Executable scripts
74
+ │ │ ├── payloadcms-publish.js # PayloadCMS CLI
75
+ │ │ ├── docusaurus-publish.js # Docusaurus CLI
76
+ │ │ ├── mintlify-publish.js # Mintlify CLI
77
+ │ │ ├── astro-publish.js # Astro CLI
78
+ │ │ ├── coolify-deploy-app.js # Coolify deployment CLI
79
+ │ │ ├── coolify-status.js # Coolify status check
80
+ │ │ ├── coolify-list-resources.js # Coolify resource listing
81
+ │ │ └── init-project.js # Project initialization
82
+ │ ├── templates/
83
+ │ │ └── claude/ # Claude Code templates
84
+ │ │ ├── agents/ # Agent definitions (.md)
85
+ │ │ └── commands/ # Slash commands (.md)
86
+ │ └── mcp/ # MCP server implementations
87
+ │ ├── wordpress-server.js # WordPress MCP server
88
+ │ └── mcp-launcher.js # MCP lifecycle manager
89
+ ├── .claude/ # Package Claude Code config
90
+ │ ├── CLAUDE.md # Configuration metadata
91
+ │ ├── commands/ # Packaged commands
92
+ │ ├── agents/ # Packaged agents
93
+ │ └── mcp/ # MCP server files
94
+ ├── test/ # Test suite
95
+ │ ├── run-tests.js # Test orchestrator
96
+ │ ├── test-gutenberg-converter.js # Gutenberg tests
97
+ │ └── test-installation.js # Installation tests
98
+ ├── .env.example # Environment template
99
+ ├── package.json # Package metadata
100
+ └── Documentation/
101
+ ├── README.md # User-facing readme
102
+ ├── USER_GUIDE.md # Getting started guide
103
+ ├── PUBLISHING_GUIDE.md # Multi-platform publishing
104
+ ├── COOLIFY_DEPLOYMENT.md # Deployment guide
105
+ ├── WORDPRESS_ADMIN_SCRIPTS.md # WordPress utilities
106
+ └── TECHNICAL_ARCHITECTURE.md # This document
107
+ ```
108
+
109
+ ---
110
+
111
+ ## Architecture Patterns
112
+
113
+ ### 1. Platform Adapter Pattern
114
+
115
+ **Problem**: Need to support multiple publishing platforms with different APIs and workflows.
116
+
117
+ **Solution**: Create platform-specific utility classes with unified interfaces.
118
+
119
+ ```javascript
120
+ // Unified interface
121
+ class PublishingAdapter {
122
+ constructor(config) { }
123
+ async authenticate() { }
124
+ async publishContent(file, options) { }
125
+ async updateContent(id, file, options) { }
126
+ async healthCheck() { }
127
+ }
128
+
129
+ // Implementations
130
+ - PayloadCMSUtils: API-based CMS with Lexical conversion
131
+ - StaticSiteUtils: Git-based publishing with platform detection
132
+ - CoolifyUtils: Deployment platform with resource management
133
+ ```
134
+
135
+ **Benefits**:
136
+ - Easy to add new platforms
137
+ - Consistent error handling
138
+ - Reusable across agents and scripts
139
+
140
+ ### 2. Two-Tier Publishing Architecture
141
+
142
+ Publishing platforms are divided into two categories:
143
+
144
+ #### API-Based Publishers (WordPress, PayloadCMS)
145
+ ```
146
+ Flow: Markdown → API Transform → HTTP POST → Platform API → Published Content
147
+
148
+ Characteristics:
149
+ - Real-time publishing
150
+ - JWT/API key authentication
151
+ - Rich text format conversion (Gutenberg blocks, Lexical nodes)
152
+ - Immediate feedback
153
+ - No git operations required
154
+ ```
155
+
156
+ #### Git-Based Publishers (Docusaurus, Mintlify, Astro)
157
+ ```
158
+ Flow: Markdown → Frontmatter Transform → File Write → Git Commit → Git Push → CI/CD → Deployed Site
159
+
160
+ Characteristics:
161
+ - File system operations
162
+ - Frontmatter transformation
163
+ - Platform-specific conventions
164
+ - Automatic git workflow
165
+ - Deployment via platform's CI/CD
166
+ ```
167
+
168
+ ### 3. Agent-Script Duality Pattern
169
+
170
+ **Problem**: Need both interactive AI agents and standalone CLI scripts.
171
+
172
+ **Solution**: Implement core logic in reusable utility libraries, with two entry points:
173
+
174
+ ```
175
+ ┌─────────────────┐
176
+ │ Core Utility │ (src/lib/payloadcms-utils.js)
177
+ │ PayloadCMSUtils│
178
+ └────────┬────────┘
179
+
180
+ ├─────────────┐
181
+ │ │
182
+ ┌────▼──────┐ ┌───▼────────────┐
183
+ │ Script │ │ AI Agent │
184
+ │ Entry │ │ Entry │
185
+ └───────────┘ └────────────────┘
186
+ CLI execution Claude Code agent
187
+ npm scripts Slash commands
188
+ Direct use Conversational
189
+ ```
190
+
191
+ **Example**:
192
+ ```javascript
193
+ // src/lib/payloadcms-utils.js - Core implementation
194
+ export class PayloadCMSUtils {
195
+ async publishContent(file, collection, options) { }
196
+ }
197
+
198
+ // src/scripts/payloadcms-publish.js - CLI script
199
+ import { PayloadCMSUtils } from '../lib/payloadcms-utils.js';
200
+ const payload = new PayloadCMSUtils();
201
+ await payload.publishContent(options.file, options.collection, options);
202
+
203
+ // src/templates/claude/agents/payloadcms-publish.md - AI agent
204
+ // Uses PayloadCMSUtils via Claude Code tool invocation
205
+ // Provides conversational interface, error guidance, workflow orchestration
206
+ ```
207
+
208
+ ### 4. Claude Code 2.0 Integration Pattern
209
+
210
+ Following official Claude Code 2.0 best practices:
211
+
212
+ #### Lightweight Agents (<3k tokens)
213
+ ```markdown
214
+ ---
215
+ name: payloadcms-publish
216
+ description: PayloadCMS publishing agent
217
+ version: 2.0.0
218
+ token_target: 2800
219
+ ---
220
+
221
+ # Concise agent definition
222
+ - Clear responsibilities
223
+ - Step-by-step workflow
224
+ - Tool usage examples
225
+ - Error handling patterns
226
+ ```
227
+
228
+ #### Extended Thinking Support
229
+ ```
230
+ Trigger keywords: "think", "think hard", "ultrathink"
231
+ Behavior: Deep analysis before execution
232
+ Use cases: Complex decisions, troubleshooting, optimization
233
+ ```
234
+
235
+ #### Subagent Delegation
236
+ ```
237
+ Main Agent
238
+ ├─> Subagent 1 (Deploy App A)
239
+ ├─> Subagent 2 (Deploy App B)
240
+ └─> Subagent 3 (Configure DB)
241
+
242
+ Pattern: Parallel execution of independent tasks
243
+ ```
244
+
245
+ ---
246
+
247
+ ## Core Components
248
+
249
+ ### 1. CLI System (bin/cli.js)
250
+
251
+ **Purpose**: Initialize project configuration for different AI CLIs.
252
+
253
+ **Architecture**:
254
+ ```javascript
255
+ program
256
+ .command('init')
257
+ .option('--claude') // Claude Code
258
+ .option('--gemini') // Gemini CLI
259
+ .option('--codex') // Codex CLI
260
+ .action(async (options) => {
261
+ // 1. Determine CLI type (interactive or flag-based)
262
+ // 2. Call platform-specific setup function
263
+ // 3. Copy templates (agents, commands, MCP config)
264
+ // 4. Copy documentation to project root
265
+ // 5. Create CLAUDE.md configuration
266
+ // 6. Copy comprehensive .env.example
267
+ // 7. Display usage instructions
268
+ });
269
+ ```
270
+
271
+ **Setup Workflow**:
272
+ ```
273
+ 1. Create directory structure
274
+ .claude/
275
+ ├── commands/ (slash commands)
276
+ ├── agents/ (AI agent definitions)
277
+ └── mcp/ (MCP server files)
278
+
279
+ 2. Copy templates from package
280
+ src/templates/claude/agents/*.md → .claude/agents/
281
+ src/templates/claude/commands/*.md → .claude/commands/
282
+ .claude/mcp/*.js → .claude/mcp/
283
+
284
+ 3. Generate configuration
285
+ CLAUDE.md with available commands and agents
286
+ .env.example with all platform credentials
287
+
288
+ 4. Copy documentation
289
+ USER_GUIDE.md
290
+ PUBLISHING_GUIDE.md
291
+ COOLIFY_DEPLOYMENT.md
292
+ WORDPRESS_ADMIN_SCRIPTS.md
293
+ ```
294
+
295
+ ### 2. PayloadCMS Utility (src/lib/payloadcms-utils.js)
296
+
297
+ **Purpose**: Complete API wrapper for PayloadCMS headless CMS.
298
+
299
+ **Key Features**:
300
+ - JWT authentication with token caching
301
+ - Markdown to Lexical rich text conversion
302
+ - CRUD operations on collections
303
+ - Media upload support
304
+ - Health checking
305
+
306
+ **Architecture**:
307
+ ```javascript
308
+ class PayloadCMSUtils {
309
+ constructor(config = {}) {
310
+ // Auto-load from .env or accept direct config
311
+ this.url = config.url || process.env.PAYLOADCMS_URL;
312
+ this.email = config.email;
313
+ this.password = config.password;
314
+ this.apiKey = config.apiKey;
315
+ this.token = null; // JWT token cached after auth
316
+ }
317
+
318
+ async authenticate() {
319
+ // POST /api/users/login
320
+ // Store JWT token for subsequent requests
321
+ }
322
+
323
+ async request(endpoint, options) {
324
+ // Unified request handler
325
+ // Auto-authenticate if token missing
326
+ // Add Authorization header
327
+ // Parse JSON response
328
+ // Handle errors with context
329
+ }
330
+
331
+ convertMarkdownToLexical(markdown) {
332
+ // Parse markdown with marked.lexer()
333
+ // Transform tokens to Lexical nodes
334
+ // Return Lexical JSON structure
335
+ }
336
+
337
+ async publishContent(file, collection, options) {
338
+ // Read file, parse frontmatter
339
+ // Convert markdown to Lexical
340
+ // POST to /api/{collection} (create)
341
+ // Or PATCH to /api/{collection}/{id} (update)
342
+ }
343
+ }
344
+ ```
345
+
346
+ **Lexical Conversion**:
347
+ ```javascript
348
+ Markdown Token → Lexical Node Mapping:
349
+ heading → { type: 'heading', tag: 'h1-h6', children: [...] }
350
+ paragraph → { type: 'paragraph', children: [...] }
351
+ list (ordered) → { type: 'number', listType: 'number', children: [...] }
352
+ list (unordered) → { type: 'bullet', listType: 'bullet', children: [...] }
353
+ code → { type: 'code', language: 'lang', children: [...] }
354
+ blockquote → { type: 'quote', children: [...] }
355
+ hr → { type: 'horizontalrule', version: 1 }
356
+ text → { type: 'text', text: '...', format: 0 }
357
+ ```
358
+
359
+ ### 3. Static Site Utility (src/lib/static-site-utils.js)
360
+
361
+ **Purpose**: Unified publishing for git-based static site generators.
362
+
363
+ **Supported Platforms**:
364
+ - Docusaurus (docs + blog)
365
+ - Mintlify (API documentation)
366
+ - Astro (content collections + pages)
367
+
368
+ **Architecture**:
369
+ ```javascript
370
+ // Platform configuration object
371
+ const platformConfigs = {
372
+ docusaurus: {
373
+ contentDirs: { docs: 'docs', blog: 'blog', pages: 'src/pages' },
374
+ frontmatterFields: ['id', 'title', 'sidebar_label', 'sidebar_position', ...],
375
+ configFile: 'docusaurus.config.js',
376
+ sidebarFile: 'sidebars.js',
377
+ requiresNavUpdate: false
378
+ },
379
+ mintlify: {
380
+ contentDirs: { default: '.' },
381
+ frontmatterFields: ['title', 'description', 'icon', 'iconType'],
382
+ configFile: 'mint.json',
383
+ requiresNavUpdate: true, // Update mint.json navigation
384
+ fileExtensions: ['.mdx']
385
+ },
386
+ astro: {
387
+ contentDirs: { content: 'src/content', pages: 'src/pages' },
388
+ frontmatterFields: ['title', 'description', 'pubDate', 'author', ...],
389
+ configFile: 'astro.config.mjs',
390
+ collectionSchema: true, // Type-safe content collections
391
+ requiresNavUpdate: false
392
+ }
393
+ };
394
+
395
+ class StaticSiteUtils {
396
+ constructor({ platform, projectPath, gitUserName, gitUserEmail }) {
397
+ this.platform = platform;
398
+ this.platformConfig = platformConfigs[platform];
399
+ this.projectPath = projectPath || detectFromEnv();
400
+ this.git = simpleGit(this.projectPath);
401
+ }
402
+
403
+ validateProject() {
404
+ // Check if config file exists
405
+ // Verify git repository
406
+ }
407
+
408
+ transformFrontmatter(frontmatter) {
409
+ // Platform-specific transformations
410
+ // Docusaurus: Generate id from title
411
+ // Astro: date → pubDate (ISO 8601)
412
+ // Mintlify: Require title field
413
+ }
414
+
415
+ async publishContent(file, options) {
416
+ // 1. Validate project structure
417
+ // 2. Read and parse markdown
418
+ // 3. Transform frontmatter
419
+ // 4. Determine target directory
420
+ // 5. Write file
421
+ // 6. Update navigation (if required)
422
+ // 7. Git commit and push
423
+ }
424
+
425
+ async updateNavigation(filename, frontmatter, options) {
426
+ // Mintlify only
427
+ // Read mint.json
428
+ // Add file to specified navigation section
429
+ // Write updated mint.json
430
+ }
431
+
432
+ async gitCommitAndPush(filePath, options) {
433
+ // Configure git user
434
+ // Stage file
435
+ // Commit with message
436
+ // Push to remote (unless --no-push)
437
+ }
438
+ }
439
+ ```
440
+
441
+ **Frontmatter Transformations**:
442
+ ```yaml
443
+ # Universal → Platform-Specific
444
+
445
+ # Docusaurus
446
+ title: "Guide" → title: "Guide", id: "guide"
447
+ sidebar_position: 1 → sidebar_position: 1
448
+
449
+ # Astro
450
+ date: "2025-10-16" → pubDate: "2025-10-16T00:00:00Z"
451
+ status: "published" → draft: false
452
+
453
+ # Mintlify
454
+ title: "API Reference" → title: "API Reference"
455
+ # If nav-section specified → Update mint.json navigation
456
+ ```
457
+
458
+ ### 4. Coolify Utility (src/lib/coolify-utils.js)
459
+
460
+ **Purpose**: Complete API wrapper for Coolify self-hosted PaaS.
461
+
462
+ **Key Features**:
463
+ - Server management
464
+ - Project and application CRUD
465
+ - Deployment operations
466
+ - Environment variable management
467
+ - Database provisioning
468
+ - Health monitoring
469
+
470
+ **Architecture**:
471
+ ```javascript
472
+ class CoolifyUtils {
473
+ constructor({ url, apiKey }) {
474
+ this.url = url || process.env.COOLIFY_URL;
475
+ this.apiKey = apiKey || process.env.COOLIFY_API_KEY;
476
+ this.headers = {
477
+ 'Authorization': `Bearer ${this.apiKey}`,
478
+ 'Content-Type': 'application/json'
479
+ };
480
+ }
481
+
482
+ // Resource Management
483
+ async listServers() { }
484
+ async listProjects() { }
485
+ async listApplications() { }
486
+ async listDatabases() { }
487
+
488
+ // Application Lifecycle
489
+ async createApplication(config) { }
490
+ async deployApplication(uuid, options) { }
491
+ async restartApplication(uuid) { }
492
+ async stopApplication(uuid) { }
493
+ async deleteApplication(uuid) { }
494
+
495
+ // Environment Management
496
+ async getEnvironmentVariables(uuid) { }
497
+ async updateEnvironmentVariables(uuid, envVars) { }
498
+
499
+ // Monitoring
500
+ async getDeploymentLogs(uuid) { }
501
+ async waitForDeployment(uuid, { maxAttempts, interval }) { }
502
+ async healthCheck() { }
503
+
504
+ // Helpers
505
+ buildApplicationConfig(options) { }
506
+ buildDatabaseConfig(options) { }
507
+ formatServerList(servers) { }
508
+ generateDeploymentReport(deployment, application) { }
509
+ }
510
+ ```
511
+
512
+ **Deployment Configuration**:
513
+ ```javascript
514
+ {
515
+ name: "app-name",
516
+ source: {
517
+ type: "git",
518
+ repository: "https://github.com/user/repo",
519
+ branch: "main"
520
+ },
521
+ build_pack: "nixpacks|dockerfile|static",
522
+ ports_exposes: "3000",
523
+ domains: ["app.example.com"],
524
+ environment_variables: { NODE_ENV: "production" },
525
+ settings: {
526
+ auto_deploy: true,
527
+ instant_deploy: false
528
+ }
529
+ }
530
+ ```
531
+
532
+ ---
533
+
534
+ ## Publishing System
535
+
536
+ ### API-Based Publishing Flow
537
+
538
+ ```
539
+ ┌──────────────────────────────────────────────────────────────┐
540
+ │ 1. User Request │
541
+ │ /myai-payloadcms-publish "article.md" --status published │
542
+ └───────────────────────┬──────────────────────────────────────┘
543
+
544
+ ┌───────────────────────▼──────────────────────────────────────┐
545
+ │ 2. Agent/Script Entry Point │
546
+ │ - Parse command arguments │
547
+ │ - Load .env configuration │
548
+ │ - Instantiate PayloadCMSUtils │
549
+ └───────────────────────┬──────────────────────────────────────┘
550
+
551
+ ┌───────────────────────▼──────────────────────────────────────┐
552
+ │ 3. Authentication │
553
+ │ POST /api/users/login │
554
+ │ {email, password} → JWT token │
555
+ └───────────────────────┬──────────────────────────────────────┘
556
+
557
+ ┌───────────────────────▼──────────────────────────────────────┐
558
+ │ 4. Content Processing │
559
+ │ - Read markdown file │
560
+ │ - Parse frontmatter (title, description, etc.) │
561
+ │ - Parse markdown body with marked.lexer() │
562
+ │ - Convert to Lexical JSON format │
563
+ └───────────────────────┬──────────────────────────────────────┘
564
+
565
+ ┌───────────────────────▼──────────────────────────────────────┐
566
+ │ 5. API Request │
567
+ │ POST /api/{collection} │
568
+ │ Authorization: JWT {token} │
569
+ │ Body: { │
570
+ │ title: "...", │
571
+ │ content: { root: { ... } }, // Lexical JSON │
572
+ │ status: "published" │
573
+ │ } │
574
+ └───────────────────────┬──────────────────────────────────────┘
575
+
576
+ ┌───────────────────────▼──────────────────────────────────────┐
577
+ │ 6. Response Handling │
578
+ │ - Extract document ID │
579
+ │ - Construct admin URL │
580
+ │ - Report success to user │
581
+ └──────────────────────────────────────────────────────────────┘
582
+ ```
583
+
584
+ ### Git-Based Publishing Flow
585
+
586
+ ```
587
+ ┌──────────────────────────────────────────────────────────────┐
588
+ │ 1. User Request │
589
+ │ /myai-docusaurus-publish "guide.md" --type docs │
590
+ └───────────────────────┬──────────────────────────────────────┘
591
+
592
+ ┌───────────────────────▼──────────────────────────────────────┐
593
+ │ 2. Agent/Script Entry Point │
594
+ │ - Parse command arguments │
595
+ │ - Detect or specify platform (docusaurus, mintlify, astro)│
596
+ │ - Instantiate StaticSiteUtils │
597
+ └───────────────────────┬──────────────────────────────────────┘
598
+
599
+ ┌───────────────────────▼──────────────────────────────────────┐
600
+ │ 3. Project Validation │
601
+ │ - Check for platform config file (docusaurus.config.js) │
602
+ │ - Verify git repository │
603
+ │ - Confirm project path │
604
+ └───────────────────────┬──────────────────────────────────────┘
605
+
606
+ ┌───────────────────────▼──────────────────────────────────────┐
607
+ │ 4. Content Processing │
608
+ │ - Read markdown file │
609
+ │ - Parse frontmatter │
610
+ │ - Transform frontmatter (platform-specific) │
611
+ │ - Determine target directory (docs/, blog/, src/content/) │
612
+ │ - Generate filename │
613
+ └───────────────────────┬──────────────────────────────────────┘
614
+
615
+ ┌───────────────────────▼──────────────────────────────────────┐
616
+ │ 5. File Operations │
617
+ │ - Write transformed content to target directory │
618
+ │ - Update navigation config (Mintlify only) │
619
+ └───────────────────────┬──────────────────────────────────────┘
620
+
621
+ ┌───────────────────────▼──────────────────────────────────────┐
622
+ │ 6. Git Workflow │
623
+ │ - git add {file} │
624
+ │ - git commit -m "Add/Update {file}" │
625
+ │ - git push origin {branch} │
626
+ └───────────────────────┬──────────────────────────────────────┘
627
+
628
+ ┌───────────────────────▼──────────────────────────────────────┐
629
+ │ 7. Platform CI/CD (Automatic) │
630
+ │ - Platform detects git push │
631
+ │ - Runs build process │
632
+ │ - Deploys to hosting │
633
+ │ - Content goes live │
634
+ └──────────────────────────────────────────────────────────────┘
635
+ ```
636
+
637
+ ---
638
+
639
+ ## Deployment System
640
+
641
+ ### Coolify Deployment Architecture
642
+
643
+ ```
644
+ ┌──────────────────────────────────────────────────────────────┐
645
+ │ User Request │
646
+ │ /myai-coolify-deploy --name myapp --repo https://... │
647
+ └───────────────────────┬──────────────────────────────────────┘
648
+
649
+ ┌───────────────────────▼──────────────────────────────────────┐
650
+ │ Agent/Script: coolify-deploy-app.js │
651
+ │ - Parse arguments │
652
+ │ - Load Coolify credentials │
653
+ │ - Instantiate CoolifyUtils │
654
+ └───────────────────────┬──────────────────────────────────────┘
655
+
656
+ ┌───────────────────────▼──────────────────────────────────────┐
657
+ │ Resource Discovery │
658
+ │ - List servers (GET /api/v1/servers) │
659
+ │ - Select optimal server (user-specified or auto) │
660
+ │ - List projects (GET /api/v1/projects) │
661
+ │ - Select/create project │
662
+ └───────────────────────┬──────────────────────────────────────┘
663
+
664
+ ┌───────────────────────▼──────────────────────────────────────┐
665
+ │ Application Configuration │
666
+ │ buildApplicationConfig({ │
667
+ │ name, repository, branch, buildPack, ports, domains, │
668
+ │ serverUuid, projectUuid, envVars, settings │
669
+ │ }) │
670
+ └───────────────────────┬──────────────────────────────────────┘
671
+
672
+ ┌───────────────────────▼──────────────────────────────────────┐
673
+ │ Create Application │
674
+ │ POST /api/v1/applications/public │
675
+ │ Body: applicationConfig │
676
+ │ Response: { uuid, ...applicationData } │
677
+ └───────────────────────┬──────────────────────────────────────┘
678
+
679
+ ┌───────────────────────▼──────────────────────────────────────┐
680
+ │ Trigger Deployment │
681
+ │ POST /api/v1/deploy?uuid={uuid} │
682
+ │ Body: { force: false, instant_deploy: false } │
683
+ └───────────────────────┬──────────────────────────────────────┘
684
+
685
+ ┌───────────────────────▼──────────────────────────────────────┐
686
+ │ Monitor Deployment │
687
+ │ waitForDeployment(uuid, { maxAttempts: 60, interval: 5s }) │
688
+ │ - Poll GET /api/v1/applications/{uuid} │
689
+ │ - Check status: building → running | error | timeout │
690
+ └───────────────────────┬──────────────────────────────────────┘
691
+
692
+ ┌───────────────────────▼──────────────────────────────────────┐
693
+ │ Report Results │
694
+ │ - Success: Application URL, deployment time │
695
+ │ - Failure: Error logs, rollback options │
696
+ └──────────────────────────────────────────────────────────────┘
697
+ ```
698
+
699
+ ### Deployment Workflow Patterns
700
+
701
+ #### Pattern 1: Single Application Deployment
702
+ ```bash
703
+ # Step 1: Verify connectivity
704
+ node src/scripts/coolify-status.js
705
+
706
+ # Step 2: Deploy
707
+ node src/scripts/coolify-deploy-app.js \
708
+ --name "myapp" \
709
+ --repo "https://github.com/user/myapp" \
710
+ --branch "main" \
711
+ --build-pack "nixpacks" \
712
+ --port "3000"
713
+
714
+ # Step 3: Monitor
715
+ # (Automatic via waitForDeployment)
716
+ ```
717
+
718
+ #### Pattern 2: Multi-Component Application (Database + Backend + Frontend)
719
+ ```javascript
720
+ // Orchestration via agent delegation
721
+ Main Agent
722
+ ├─> Database Agent: Deploy PostgreSQL
723
+ │ └─> Returns: DATABASE_URL
724
+
725
+ ├─> Backend Agent: Deploy API with DATABASE_URL
726
+ │ └─> Returns: API_URL
727
+
728
+ └─> Frontend Agent: Deploy UI with API_URL
729
+ └─> Returns: APP_URL
730
+
731
+ // Parallel execution where possible (DB creation independent of app builds)
732
+ ```
733
+
734
+ #### Pattern 3: Environment-Specific Deployment
735
+ ```javascript
736
+ // Staging
737
+ deployApplication({
738
+ name: "myapp-staging",
739
+ branch: "develop",
740
+ domains: ["staging.myapp.com"],
741
+ envVars: loadEnv('.env.staging')
742
+ });
743
+
744
+ // Production (with approval gate)
745
+ if (await confirmProduction()) {
746
+ deployApplication({
747
+ name: "myapp-prod",
748
+ branch: "main",
749
+ domains: ["myapp.com", "www.myapp.com"],
750
+ envVars: loadEnv('.env.production')
751
+ });
752
+ }
753
+ ```
754
+
755
+ ---
756
+
757
+ ## Agent System
758
+
759
+ ### Agent Architecture
760
+
761
+ Agents are markdown files with YAML frontmatter following Claude Code 2.0 patterns.
762
+
763
+ **Agent Definition Structure**:
764
+ ```markdown
765
+ ---
766
+ name: agent-name
767
+ description: Brief description
768
+ version: 2.0.0
769
+ capabilities:
770
+ - Capability 1
771
+ - Capability 2
772
+ agent_type: publishing|deployment|administration
773
+ token_target: 2800 # Lightweight agent target
774
+ ---
775
+
776
+ # Agent Name
777
+
778
+ **Purpose**: Clear statement of agent's role
779
+
780
+ ## Core Responsibilities
781
+ 1. Responsibility 1
782
+ 2. Responsibility 2
783
+
784
+ ## Workflow
785
+
786
+ ### Step 1: Preparation
787
+ [Detailed step description]
788
+
789
+ ### Step 2: Execution
790
+ [Detailed step description]
791
+
792
+ ## Usage Examples
793
+
794
+ ### Example 1: Basic Usage
795
+ [Example with user request and agent response]
796
+
797
+ ### Example 2: Advanced Usage
798
+ [Example with complex scenario]
799
+
800
+ ## Tool Usage Pattern
801
+ [Which tools to use and when]
802
+
803
+ ## Error Handling
804
+ [Common issues and solutions]
805
+ ```
806
+
807
+ ### Available Agents
808
+
809
+ #### 1. Content Writer Agent
810
+ ```yaml
811
+ File: .claude/agents/content-writer.md
812
+ Purpose: Generate SEO-optimized content
813
+ Capabilities:
814
+ - Research topics
815
+ - Structure content
816
+ - Optimize for SEO
817
+ - Generate markdown files
818
+ Token Target: <3k
819
+ ```
820
+
821
+ #### 2. WordPress Admin Agent
822
+ ```yaml
823
+ File: .claude/agents/wordpress-admin.md
824
+ Purpose: WordPress administration and security
825
+ Capabilities:
826
+ - Health checks
827
+ - Security scanning
828
+ - Performance analysis
829
+ - Comprehensive reporting
830
+ Token Target: <3k
831
+ ```
832
+
833
+ #### 3. PayloadCMS Publishing Agent
834
+ ```yaml
835
+ File: .claude/agents/payloadcms-publish.md
836
+ Purpose: Publish content to PayloadCMS
837
+ Workflow:
838
+ 1. Authenticate with JWT
839
+ 2. Convert markdown to Lexical
840
+ 3. POST to collections API
841
+ 4. Verify publication
842
+ Token Target: 2800
843
+ ```
844
+
845
+ #### 4. Docusaurus Publishing Agent
846
+ ```yaml
847
+ File: .claude/agents/docusaurus-publish.md
848
+ Purpose: Publish to Docusaurus docs/blog
849
+ Workflow:
850
+ 1. Validate Docusaurus project
851
+ 2. Transform frontmatter
852
+ 3. Write to docs/ or blog/
853
+ 4. Git commit and push
854
+ Token Target: <3k
855
+ ```
856
+
857
+ #### 5. Mintlify Publishing Agent
858
+ ```yaml
859
+ File: .claude/agents/mintlify-publish.md
860
+ Purpose: Publish to Mintlify docs
861
+ Workflow:
862
+ 1. Validate Mintlify project
863
+ 2. Transform to MDX
864
+ 3. Update mint.json navigation
865
+ 4. Git commit and push
866
+ Token Target: <3k
867
+ ```
868
+
869
+ #### 6. Astro Publishing Agent
870
+ ```yaml
871
+ File: .claude/agents/astro-publish.md
872
+ Purpose: Publish to Astro content collections
873
+ Workflow:
874
+ 1. Validate Astro project
875
+ 2. Transform frontmatter (date → pubDate)
876
+ 3. Write to src/content/{collection}/
877
+ 4. Git commit and push
878
+ Token Target: <3k
879
+ ```
880
+
881
+ #### 7. Coolify Deploy Agent
882
+ ```yaml
883
+ File: .claude/agents/coolify-deploy.md
884
+ Purpose: Deploy applications to Coolify
885
+ Patterns:
886
+ - Lightweight: Direct script invocation
887
+ - Extended Thinking: Complex deployment decisions
888
+ - Subagent Delegation: Multi-app deployments
889
+ Token Target: Adaptive (2k-10k based on complexity)
890
+ Capabilities:
891
+ - Application deployment
892
+ - Database provisioning
893
+ - Environment management
894
+ - Monitoring and logging
895
+ ```
896
+
897
+ ### Slash Commands
898
+
899
+ Commands are lightweight wrappers that invoke agents or scripts.
900
+
901
+ **Command Structure**:
902
+ ```markdown
903
+ ---
904
+ name: myai-command-name
905
+ description: Brief command description
906
+ ---
907
+
908
+ Brief explanation of what this command does.
909
+
910
+ Invoke the {agent-name} agent to {action}.
911
+
912
+ ## Usage
913
+
914
+ ```bash
915
+ /myai-command-name "argument" --option value
916
+ ```
917
+
918
+ ## Options
919
+
920
+ - `--option1 <value>` - Description
921
+ - `--option2` - Boolean flag
922
+
923
+ ## Examples
924
+
925
+ Basic usage:
926
+ ```
927
+ /myai-command-name "example"
928
+ ```
929
+
930
+ With options:
931
+ ```
932
+ /myai-command-name "example" --option1 value
933
+ ```
934
+ ```
935
+
936
+ **Available Commands**:
937
+ 1. `/myai-content-writer` → Content creation
938
+ 2. `/myai-wordpress-publish` → WordPress publishing
939
+ 3. `/myai-wordpress-admin` → WordPress administration
940
+ 4. `/myai-payloadcms-publish` → PayloadCMS publishing
941
+ 5. `/myai-docusaurus-publish` → Docusaurus publishing
942
+ 6. `/myai-mintlify-publish` → Mintlify publishing
943
+ 7. `/myai-astro-publish` → Astro publishing
944
+ 8. `/myai-coolify-deploy` → Coolify deployment
945
+ 9. `/myai-configure` → Platform configuration
946
+
947
+ ---
948
+
949
+ ## Integration Patterns
950
+
951
+ ### Pattern 1: Claude Code → Agent → Script → Utility
952
+
953
+ ```
954
+ User: /myai-payloadcms-publish "article.md"
955
+
956
+
957
+ Claude Code: Interprets slash command
958
+
959
+
960
+ Agent: payloadcms-publish.md
961
+ │ (Provides context, workflow, error handling)
962
+
963
+ Script: src/scripts/payloadcms-publish.js
964
+ │ (CLI argument parsing, execution)
965
+
966
+ Utility: src/lib/payloadcms-utils.js
967
+ │ (Core API logic)
968
+
969
+ PayloadCMS API
970
+ ```
971
+
972
+ ### Pattern 2: Direct Script Invocation
973
+
974
+ ```
975
+ npm run payloadcms:publish -- --file article.md --status published
976
+
977
+
978
+ Script: src/scripts/payloadcms-publish.js
979
+
980
+
981
+ Utility: src/lib/payloadcms-utils.js
982
+
983
+
984
+ PayloadCMS API
985
+ ```
986
+
987
+ ### Pattern 3: Agent-to-Agent Delegation
988
+
989
+ ```
990
+ Main Agent: Complex Publishing Workflow
991
+
992
+ ├─> Content Writer Agent: Generate content
993
+ │ └─> Markdown file created
994
+
995
+ ├─> PayloadCMS Agent: Publish to CMS
996
+ │ └─> CMS entry created
997
+
998
+ └─> Docusaurus Agent: Publish to docs
999
+ └─> Documentation updated
1000
+ ```
1001
+
1002
+ ### Pattern 4: MCP Server Integration
1003
+
1004
+ ```
1005
+ Claude Code
1006
+
1007
+
1008
+ MCP Protocol
1009
+
1010
+
1011
+ WordPress MCP Server (.claude/mcp/wordpress-server.js)
1012
+ │ (Implements MCP SDK, exposes tools)
1013
+
1014
+ WordPress REST API
1015
+ ```
1016
+
1017
+ **MCP Tools Exposed**:
1018
+ - `wordpress_publish`: Publish content
1019
+ - `wordpress_health_check`: System health
1020
+ - `wordpress_security_scan`: Security analysis
1021
+ - `wordpress_performance_check`: Performance metrics
1022
+
1023
+ ---
1024
+
1025
+ ## Data Flow
1026
+
1027
+ ### Content Publishing Data Flow
1028
+
1029
+ ```
1030
+ ┌─────────────────┐
1031
+ │ User Input │ (Markdown file, frontmatter, images)
1032
+ │ article.md │
1033
+ └────────┬────────┘
1034
+
1035
+
1036
+ ┌─────────────────┐
1037
+ │ Parse & Load │ (gray-matter: frontmatter + content)
1038
+ │ Read file │
1039
+ └────────┬────────┘
1040
+
1041
+ ├─────────────────┬─────────────────┐
1042
+ │ │ │
1043
+ ▼ ▼ ▼
1044
+ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐
1045
+ │ API-Based │ │ Git-Based │ │ Deployment │
1046
+ │ Transform │ │ Transform │ │ Config │
1047
+ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘
1048
+ │ │ │
1049
+ ▼ ▼ ▼
1050
+ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐
1051
+ │ Lexical JSON │ │ Frontmatter │ │ App Config │
1052
+ │ Gutenberg │ │ Transform │ │ JSON │
1053
+ │ Blocks │ │ File Write │ │ │
1054
+ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘
1055
+ │ │ │
1056
+ ▼ ▼ ▼
1057
+ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐
1058
+ │ HTTP POST │ │ Git Commit │ │ API POST │
1059
+ │ to CMS API │ │ & Push │ │ to Coolify │
1060
+ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘
1061
+ │ │ │
1062
+ ▼ ▼ ▼
1063
+ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐
1064
+ │ Published │ │ Platform │ │ Deployed │
1065
+ │ Content │ │ CI/CD │ │ Application │
1066
+ │ (Live) │ │ Build/Deploy │ │ (Running) │
1067
+ └──────────────┘ └──────────────┘ └──────────────┘
1068
+ ```
1069
+
1070
+ ### Configuration Data Flow
1071
+
1072
+ ```
1073
+ ┌─────────────────┐
1074
+ │ .env File │
1075
+ │ PLATFORM_URL= │
1076
+ │ PLATFORM_KEY= │
1077
+ └────────┬────────┘
1078
+
1079
+
1080
+ ┌─────────────────┐
1081
+ │ dotenv.parse() │ (Load and parse environment variables)
1082
+ └────────┬────────┘
1083
+
1084
+
1085
+ ┌─────────────────┐
1086
+ │ Utility Class │
1087
+ │ Constructor │ (PayloadCMSUtils, CoolifyUtils, etc.)
1088
+ │ this.url = ... │
1089
+ │ this.apiKey = ..│
1090
+ └────────┬────────┘
1091
+
1092
+
1093
+ ┌─────────────────┐
1094
+ │ API Request │
1095
+ │ Headers: │
1096
+ │ Authorization │
1097
+ └────────┬────────┘
1098
+
1099
+
1100
+ ┌─────────────────┐
1101
+ │ Platform API │
1102
+ │ Authenticated │
1103
+ │ Response │
1104
+ └─────────────────┘
1105
+ ```
1106
+
1107
+ ---
1108
+
1109
+ ## Extension Guide
1110
+
1111
+ ### Adding a New Publishing Platform
1112
+
1113
+ Follow this step-by-step guide to add support for a new platform.
1114
+
1115
+ #### Step 1: Create Utility Class
1116
+
1117
+ ```javascript
1118
+ // src/lib/newplatform-utils.js
1119
+
1120
+ export class NewPlatformUtils {
1121
+ constructor(config = {}) {
1122
+ // Load from .env or config
1123
+ this.url = config.url || process.env.NEWPLATFORM_URL;
1124
+ this.apiKey = config.apiKey || process.env.NEWPLATFORM_API_KEY;
1125
+ }
1126
+
1127
+ loadEnvConfig() {
1128
+ // Parse .env file
1129
+ }
1130
+
1131
+ async authenticate() {
1132
+ // Handle authentication (JWT, API key, OAuth, etc.)
1133
+ }
1134
+
1135
+ async request(endpoint, options) {
1136
+ // Unified HTTP request wrapper
1137
+ }
1138
+
1139
+ async publishContent(file, options) {
1140
+ // Main publishing logic
1141
+ // 1. Read file
1142
+ // 2. Parse frontmatter
1143
+ // 3. Transform content (if needed)
1144
+ // 4. API request
1145
+ // 5. Return result
1146
+ }
1147
+
1148
+ async healthCheck() {
1149
+ // Verify API connectivity
1150
+ }
1151
+ }
1152
+
1153
+ export default NewPlatformUtils;
1154
+ ```
1155
+
1156
+ #### Step 2: Create CLI Script
1157
+
1158
+ ```javascript
1159
+ // src/scripts/newplatform-publish.js
1160
+
1161
+ import { Command } from 'commander';
1162
+ import chalk from 'chalk';
1163
+ import ora from 'ora';
1164
+ import { NewPlatformUtils } from '../lib/newplatform-utils.js';
1165
+
1166
+ const program = new Command();
1167
+
1168
+ program
1169
+ .requiredOption('--file <path>', 'Markdown file to publish')
1170
+ .option('--status <status>', 'Publication status', 'draft')
1171
+ .option('--dry-run', 'Validate without publishing')
1172
+ .parse(process.argv);
1173
+
1174
+ const options = program.opts();
1175
+
1176
+ async function publishContent() {
1177
+ const spinner = ora('Publishing to NewPlatform...').start();
1178
+
1179
+ try {
1180
+ const platform = new NewPlatformUtils();
1181
+
1182
+ // Verify connection
1183
+ const healthy = await platform.healthCheck();
1184
+ if (!healthy) throw new Error('NewPlatform not accessible');
1185
+
1186
+ // Publish
1187
+ const result = await platform.publishContent(options.file, {
1188
+ status: options.status,
1189
+ dryRun: options.dryRun
1190
+ });
1191
+
1192
+ spinner.succeed(chalk.green('Published successfully!'));
1193
+ console.log(chalk.cyan(`URL: ${result.url}`));
1194
+ } catch (error) {
1195
+ spinner.fail(chalk.red('Publishing failed'));
1196
+ console.error(error.message);
1197
+ process.exit(1);
1198
+ }
1199
+ }
1200
+
1201
+ publishContent();
1202
+ ```
1203
+
1204
+ #### Step 3: Add npm Script
1205
+
1206
+ ```json
1207
+ // package.json
1208
+ {
1209
+ "scripts": {
1210
+ "newplatform:publish": "node src/scripts/newplatform-publish.js"
1211
+ }
1212
+ }
1213
+ ```
1214
+
1215
+ #### Step 4: Create Agent Definition
1216
+
1217
+ ```markdown
1218
+ <!-- src/templates/claude/agents/newplatform-publish.md -->
1219
+ ---
1220
+ name: newplatform-publish
1221
+ description: Publish content to NewPlatform
1222
+ version: 2.0.0
1223
+ capabilities:
1224
+ - Authenticate with NewPlatform
1225
+ - Convert markdown
1226
+ - Publish content
1227
+ agent_type: publishing
1228
+ token_target: 2800
1229
+ ---
1230
+
1231
+ # NewPlatform Publishing Agent
1232
+
1233
+ **Purpose**: Publish markdown content to NewPlatform.
1234
+
1235
+ ## Workflow
1236
+
1237
+ ### Step 1: Configuration Validation
1238
+ 1. Check NEWPLATFORM_URL and NEWPLATFORM_API_KEY
1239
+ 2. If missing → prompt `/myai-configure newplatform`
1240
+
1241
+ ### Step 2: Authentication
1242
+ 1. Authenticate with API
1243
+ 2. Handle auth errors
1244
+
1245
+ ### Step 3: Content Processing
1246
+ 1. Read markdown file
1247
+ 2. Parse frontmatter
1248
+ 3. Transform content (if needed)
1249
+
1250
+ ### Step 4: Publishing
1251
+ 1. POST to NewPlatform API
1252
+ 2. Verify success
1253
+ 3. Return URL
1254
+
1255
+ ## Usage Examples
1256
+
1257
+ ### Basic Publishing
1258
+ ```
1259
+ User: "Publish article.md to NewPlatform"
1260
+ Agent: Executes workflow → Reports success with URL
1261
+ ```
1262
+
1263
+ ## Tool Usage Pattern
1264
+ ```
1265
+ 1. Read(markdown_file)
1266
+ 2. authenticateNewPlatform()
1267
+ 3. publishToNewPlatform()
1268
+ 4. Report success
1269
+ ```
1270
+ ```
1271
+
1272
+ #### Step 5: Create Slash Command
1273
+
1274
+ ```markdown
1275
+ <!-- src/templates/claude/commands/myai-newplatform-publish.md -->
1276
+ ---
1277
+ name: myai-newplatform-publish
1278
+ description: Publish content to NewPlatform
1279
+ ---
1280
+
1281
+ Publish markdown content to NewPlatform.
1282
+
1283
+ Invoke the NewPlatform publishing agent.
1284
+
1285
+ ## Usage
1286
+
1287
+ ```bash
1288
+ /myai-newplatform-publish "article.md"
1289
+ /myai-newplatform-publish "article.md" --status published
1290
+ ```
1291
+
1292
+ ## Options
1293
+
1294
+ - `--status <draft|published>` - Publication status
1295
+ - `--dry-run` - Validate without publishing
1296
+
1297
+ ## Examples
1298
+
1299
+ Publish as draft:
1300
+ ```
1301
+ /myai-newplatform-publish "article.md"
1302
+ ```
1303
+
1304
+ Publish live:
1305
+ ```
1306
+ /myai-newplatform-publish "article.md" --status published
1307
+ ```
1308
+ ```
1309
+
1310
+ #### Step 6: Update .env.example
1311
+
1312
+ ```bash
1313
+ # .env.example
1314
+
1315
+ # NewPlatform Configuration
1316
+ NEWPLATFORM_URL=https://api.newplatform.com
1317
+ NEWPLATFORM_API_KEY=your-api-key-here
1318
+ ```
1319
+
1320
+ #### Step 7: Update CLI Init
1321
+
1322
+ ```javascript
1323
+ // bin/cli.js - setupClaude() function
1324
+
1325
+ const claudeMd = `
1326
+ ## Available Commands
1327
+
1328
+ ### Publishing Platforms
1329
+ - \`/myai-wordpress-publish\` - Publish to WordPress
1330
+ - \`/myai-payloadcms-publish\` - Publish to PayloadCMS
1331
+ - \`/myai-newplatform-publish\` - Publish to NewPlatform // ADD THIS
1332
+ ...
1333
+ `;
1334
+ ```
1335
+
1336
+ #### Step 8: Update Documentation
1337
+
1338
+ 1. Add section to PUBLISHING_GUIDE.md
1339
+ 2. Update README.md features list
1340
+ 3. Add platform-specific guide if needed
1341
+
1342
+ #### Step 9: Add Tests
1343
+
1344
+ ```javascript
1345
+ // test/test-newplatform-publish.js
1346
+
1347
+ import { NewPlatformUtils } from '../src/lib/newplatform-utils.js';
1348
+
1349
+ export async function runNewPlatformTests() {
1350
+ console.log('🧪 Running NewPlatform Publishing Tests...\n');
1351
+
1352
+ const tests = [
1353
+ {
1354
+ name: 'Should authenticate successfully',
1355
+ fn: async () => {
1356
+ const platform = new NewPlatformUtils({
1357
+ url: 'https://test.newplatform.com',
1358
+ apiKey: 'test-key'
1359
+ });
1360
+ // Test authentication
1361
+ }
1362
+ },
1363
+ {
1364
+ name: 'Should publish content',
1365
+ fn: async () => {
1366
+ // Test publishing
1367
+ }
1368
+ }
1369
+ ];
1370
+
1371
+ // Run tests...
1372
+ }
1373
+ ```
1374
+
1375
+ #### Step 10: Version and Publish
1376
+
1377
+ ```bash
1378
+ # Update version
1379
+ npm version minor
1380
+
1381
+ # Run tests
1382
+ npm test
1383
+
1384
+ # Publish
1385
+ npm publish
1386
+
1387
+ # Push to git
1388
+ git push --tags
1389
+ ```
1390
+
1391
+ ### Adding a New Agent
1392
+
1393
+ For agents that don't require new platforms (e.g., workflow orchestration, reporting):
1394
+
1395
+ 1. **Create Agent Definition**: `.claude/agents/new-agent.md`
1396
+ 2. **Create Slash Command**: `.claude/commands/myai-new-agent.md`
1397
+ 3. **Create Script** (if needed): `src/scripts/new-agent.js`
1398
+ 4. **Update CLAUDE.md**: Add to agents list
1399
+ 5. **Update CLI Init**: Include in welcome message
1400
+ 6. **Test**: Verify agent loads and executes correctly
1401
+
1402
+ ---
1403
+
1404
+ ## Testing Strategy
1405
+
1406
+ ### Test Structure
1407
+
1408
+ ```
1409
+ test/
1410
+ ├── run-tests.js # Test orchestrator
1411
+ ├── test-gutenberg-converter.js # Gutenberg block tests
1412
+ ├── test-installation.js # Package installation tests
1413
+ ├── test-payloadcms-publish.js # PayloadCMS tests (future)
1414
+ ├── test-static-site-publish.js # Static site tests (future)
1415
+ └── test-coolify-deploy.js # Coolify tests (future)
1416
+ ```
1417
+
1418
+ ### Test Runner (run-tests.js)
1419
+
1420
+ ```javascript
1421
+ import { runGutenbergTests } from './test-gutenberg-converter.js';
1422
+ import { runInstallationTests } from './test-installation.js';
1423
+
1424
+ async function runAllTests() {
1425
+ console.log('🚀 MyAIDev Method - Test Suite');
1426
+ console.log('═══════════════════════════════\n');
1427
+
1428
+ let allPassed = true;
1429
+
1430
+ // Run test suites
1431
+ const gutenbergPassed = await runGutenbergTests();
1432
+ const installationPassed = await runInstallationTests();
1433
+
1434
+ allPassed = gutenbergPassed && installationPassed;
1435
+
1436
+ // Overall results
1437
+ console.log('\n═══════════════════════════════');
1438
+ console.log('📊 OVERALL TEST RESULTS');
1439
+ console.log('═══════════════════════════════\n');
1440
+
1441
+ if (allPassed) {
1442
+ console.log('🎉 ALL TESTS PASSED! 🎉');
1443
+ process.exit(0);
1444
+ } else {
1445
+ console.log('❌ SOME TESTS FAILED');
1446
+ process.exit(1);
1447
+ }
1448
+ }
1449
+
1450
+ runAllTests();
1451
+ ```
1452
+
1453
+ ### Test Categories
1454
+
1455
+ #### 1. Unit Tests
1456
+ Test individual functions in isolation.
1457
+
1458
+ ```javascript
1459
+ // Example: Test markdown to Lexical conversion
1460
+ testCase('Should convert H2 heading to Lexical block', () => {
1461
+ const markdown = '## Test Heading';
1462
+ const result = convertMarkdownToLexical(markdown);
1463
+ assert(result.root.children[0].type === 'heading');
1464
+ assert(result.root.children[0].tag === 'h2');
1465
+ });
1466
+ ```
1467
+
1468
+ #### 2. Integration Tests
1469
+ Test complete workflows.
1470
+
1471
+ ```javascript
1472
+ // Example: Test PayloadCMS publishing workflow
1473
+ testCase('Should publish markdown to PayloadCMS', async () => {
1474
+ const payload = new PayloadCMSUtils({ ...testConfig });
1475
+ await payload.authenticate();
1476
+ const result = await payload.publishContent('test.md', 'posts', {
1477
+ status: 'draft'
1478
+ });
1479
+ assert(result.doc.id !== null);
1480
+ });
1481
+ ```
1482
+
1483
+ #### 3. Installation Tests
1484
+ Verify package installation creates correct structure.
1485
+
1486
+ ```javascript
1487
+ testCase('Installation should create .claude directory', async () => {
1488
+ const testDir = await createTestProject();
1489
+ await runInit(testDir);
1490
+ const claudeDir = path.join(testDir, '.claude');
1491
+ assert(fs.existsSync(claudeDir));
1492
+ });
1493
+ ```
1494
+
1495
+ ### Running Tests
1496
+
1497
+ ```bash
1498
+ # Run all tests
1499
+ npm test
1500
+
1501
+ # Run specific test suite
1502
+ npm run test:gutenberg
1503
+ npm run test:install
1504
+
1505
+ # Future test commands
1506
+ npm run test:payloadcms
1507
+ npm run test:static-sites
1508
+ npm run test:coolify
1509
+ ```
1510
+
1511
+ ### Test Guidelines
1512
+
1513
+ 1. **Isolation**: Tests should not depend on external services (use mocks)
1514
+ 2. **Cleanup**: Always clean up test directories and resources
1515
+ 3. **Assertions**: Use clear, descriptive assertions
1516
+ 4. **Error Handling**: Test both success and failure paths
1517
+ 5. **Documentation**: Comment complex test logic
1518
+
1519
+ ---
1520
+
1521
+ ## Performance Considerations
1522
+
1523
+ ### 1. Token Optimization (Claude Code 2.0)
1524
+
1525
+ - **Lightweight Agents**: Keep agents under 3k tokens
1526
+ - **Lazy Loading**: Load utility libraries only when needed
1527
+ - **Caching**: Cache authentication tokens, git state
1528
+ - **Parallel Execution**: Use subagent delegation for independent tasks
1529
+
1530
+ ### 2. API Request Optimization
1531
+
1532
+ ```javascript
1533
+ // Batch requests where possible
1534
+ const [servers, projects, apps] = await Promise.all([
1535
+ coolify.listServers(),
1536
+ coolify.listProjects(),
1537
+ coolify.listApplications()
1538
+ ]);
1539
+
1540
+ // Cache authentication tokens
1541
+ if (!this.token) {
1542
+ await this.authenticate();
1543
+ }
1544
+ // Reuse token for subsequent requests
1545
+ ```
1546
+
1547
+ ### 3. File Operations
1548
+
1549
+ ```javascript
1550
+ // Use streams for large files
1551
+ import { createReadStream, createWriteStream } from 'fs';
1552
+
1553
+ // Use fs-extra for recursive operations
1554
+ import fs from 'fs-extra';
1555
+ await fs.copy(source, destination);
1556
+ ```
1557
+
1558
+ ### 4. Git Operations
1559
+
1560
+ ```javascript
1561
+ // Batch git operations
1562
+ await git.add(file).commit(message).push();
1563
+
1564
+ // Use shallow clones when appropriate
1565
+ await git.clone(repo, { depth: 1 });
1566
+ ```
1567
+
1568
+ ---
1569
+
1570
+ ## Security Best Practices
1571
+
1572
+ ### 1. Credential Management
1573
+
1574
+ ```javascript
1575
+ // ✅ GOOD: Load from .env
1576
+ const apiKey = process.env.PLATFORM_API_KEY;
1577
+
1578
+ // ❌ BAD: Hardcoded credentials
1579
+ const apiKey = 'sk-1234567890abcdef';
1580
+
1581
+ // ✅ GOOD: Validate before use
1582
+ if (!apiKey) {
1583
+ throw new Error('API key required. Run /myai-configure');
1584
+ }
1585
+ ```
1586
+
1587
+ ### 2. API Key Redaction
1588
+
1589
+ ```javascript
1590
+ // Utility function to redact sensitive data in logs
1591
+ function redactApiKey(key) {
1592
+ if (!key || key.length < 8) return '***';
1593
+ return `${key.slice(0, 4)}...${key.slice(-4)}`;
1594
+ }
1595
+
1596
+ console.log(`Using API key: ${redactApiKey(apiKey)}`);
1597
+ // Output: Using API key: sk-1...f3d2
1598
+ ```
1599
+
1600
+ ### 3. Input Validation
1601
+
1602
+ ```javascript
1603
+ // Validate user inputs
1604
+ function validateUrl(url) {
1605
+ try {
1606
+ new URL(url);
1607
+ return true;
1608
+ } catch {
1609
+ throw new Error('Invalid URL format');
1610
+ }
1611
+ }
1612
+
1613
+ // Sanitize file paths
1614
+ function sanitizePath(filePath) {
1615
+ // Prevent directory traversal
1616
+ if (filePath.includes('..')) {
1617
+ throw new Error('Invalid file path');
1618
+ }
1619
+ return path.resolve(filePath);
1620
+ }
1621
+ ```
1622
+
1623
+ ### 4. Error Handling
1624
+
1625
+ ```javascript
1626
+ // Don't expose sensitive info in errors
1627
+ try {
1628
+ await api.request('/sensitive-endpoint');
1629
+ } catch (error) {
1630
+ // ❌ BAD: Exposes API details
1631
+ throw error;
1632
+
1633
+ // ✅ GOOD: Generic error message
1634
+ throw new Error('API request failed. Check credentials.');
1635
+ }
1636
+ ```
1637
+
1638
+ ---
1639
+
1640
+ ## Debugging and Troubleshooting
1641
+
1642
+ ### Debug Mode
1643
+
1644
+ ```javascript
1645
+ // Enable debug mode via environment variable
1646
+ if (process.env.DEBUG) {
1647
+ console.log('Debug: Request payload', payload);
1648
+ console.log('Debug: API response', response);
1649
+ }
1650
+ ```
1651
+
1652
+ ### Logging Utilities
1653
+
1654
+ ```javascript
1655
+ import chalk from 'chalk';
1656
+
1657
+ function logInfo(message) {
1658
+ console.log(chalk.blue('ℹ'), message);
1659
+ }
1660
+
1661
+ function logSuccess(message) {
1662
+ console.log(chalk.green('✓'), message);
1663
+ }
1664
+
1665
+ function logWarning(message) {
1666
+ console.log(chalk.yellow('⚠'), message);
1667
+ }
1668
+
1669
+ function logError(message) {
1670
+ console.error(chalk.red('✗'), message);
1671
+ }
1672
+ ```
1673
+
1674
+ ### Common Issues
1675
+
1676
+ #### Issue: "Authentication failed"
1677
+ ```bash
1678
+ # Verify credentials
1679
+ cat .env | grep PLATFORM
1680
+
1681
+ # Test connectivity
1682
+ curl -H "Authorization: Bearer $API_KEY" $PLATFORM_URL/api/health
1683
+
1684
+ # Re-configure
1685
+ /myai-configure
1686
+ ```
1687
+
1688
+ #### Issue: "Git operation failed"
1689
+ ```bash
1690
+ # Check git status
1691
+ cd project-path && git status
1692
+
1693
+ # Verify remote
1694
+ git remote -v
1695
+
1696
+ # Configure git user
1697
+ git config user.name "Your Name"
1698
+ git config user.email "your-email@example.com"
1699
+ ```
1700
+
1701
+ #### Issue: "Module not found"
1702
+ ```bash
1703
+ # Reinstall dependencies
1704
+ npm install
1705
+
1706
+ # Clear cache
1707
+ npm cache clean --force
1708
+ rm -rf node_modules
1709
+ npm install
1710
+ ```
1711
+
1712
+ ---
1713
+
1714
+ ## Appendix
1715
+
1716
+ ### A. Environment Variables Reference
1717
+
1718
+ ```bash
1719
+ # WordPress (API-based)
1720
+ WORDPRESS_URL=https://your-site.com
1721
+ WORDPRESS_USERNAME=your-username
1722
+ WORDPRESS_APP_PASSWORD=xxxx-xxxx-xxxx-xxxx
1723
+
1724
+ # PayloadCMS (API-based)
1725
+ PAYLOADCMS_URL=https://cms.your-site.com
1726
+ PAYLOADCMS_EMAIL=your-email@example.com
1727
+ PAYLOADCMS_PASSWORD=your-password
1728
+ PAYLOADCMS_API_KEY=your-api-key # Alternative to email/password
1729
+
1730
+ # Git Configuration (for static sites)
1731
+ GIT_USER_NAME=Your Name
1732
+ GIT_USER_EMAIL=your-email@example.com
1733
+ GIT_REMOTE_URL=origin # Default
1734
+
1735
+ # Static Site Project Paths (optional)
1736
+ DOCUSAURUS_PROJECT_PATH=./docs
1737
+ MINTLIFY_PROJECT_PATH=./docs
1738
+ ASTRO_PROJECT_PATH=./blog
1739
+
1740
+ # Coolify Deployment
1741
+ COOLIFY_URL=https://coolify.your-server.com
1742
+ COOLIFY_API_KEY=your-coolify-api-key
1743
+
1744
+ # Debug Mode
1745
+ DEBUG=true # Enable verbose logging
1746
+ ```
1747
+
1748
+ ### B. API Endpoints Reference
1749
+
1750
+ #### PayloadCMS API
1751
+ ```
1752
+ POST /api/users/login # Authenticate
1753
+ GET /api # List collections
1754
+ GET /api/{collection} # Get documents
1755
+ GET /api/{collection}/{id} # Get document by ID
1756
+ POST /api/{collection} # Create document
1757
+ PATCH /api/{collection}/{id} # Update document
1758
+ DELETE /api/{collection}/{id} # Delete document
1759
+ POST /api/media # Upload media
1760
+ ```
1761
+
1762
+ #### Coolify API
1763
+ ```
1764
+ GET /api/v1/servers # List servers
1765
+ GET /api/v1/projects # List projects
1766
+ GET /api/v1/applications # List applications
1767
+ POST /api/v1/applications/public # Create application
1768
+ POST /api/v1/deploy?uuid={uuid} # Deploy application
1769
+ GET /api/v1/applications/{uuid} # Get application
1770
+ POST /api/v1/applications/{uuid}/restart # Restart app
1771
+ POST /api/v1/applications/{uuid}/stop # Stop app
1772
+ GET /api/v1/databases # List databases
1773
+ POST /api/v1/databases # Create database
1774
+ ```
1775
+
1776
+ ### C. File Format Specifications
1777
+
1778
+ #### Frontmatter Schema (Universal)
1779
+ ```yaml
1780
+ ---
1781
+ title: "Article Title" # Required for all platforms
1782
+ description: "Brief description" # SEO description
1783
+ date: "2025-10-16" # Publication date (ISO 8601 for Astro)
1784
+ author: "Author Name" # Content author
1785
+ tags: ["tag1", "tag2"] # Content tags
1786
+ status: "draft|published" # Publication status
1787
+ ---
1788
+ ```
1789
+
1790
+ #### Platform-Specific Frontmatter
1791
+
1792
+ **Docusaurus**:
1793
+ ```yaml
1794
+ ---
1795
+ id: "unique-slug" # Document ID
1796
+ sidebar_position: 1 # Sidebar order
1797
+ sidebar_label: "Label" # Sidebar display name
1798
+ ---
1799
+ ```
1800
+
1801
+ **Astro**:
1802
+ ```yaml
1803
+ ---
1804
+ pubDate: "2025-10-16T00:00:00Z" # ISO 8601 format (required)
1805
+ draft: false # Boolean draft status
1806
+ heroImage: "/images/hero.jpg" # Featured image
1807
+ ---
1808
+ ```
1809
+
1810
+ **Mintlify**:
1811
+ ```yaml
1812
+ ---
1813
+ icon: "rocket" # Icon name from library
1814
+ iconType: "solid" # Icon style
1815
+ ---
1816
+ ```
1817
+
1818
+ ### D. Glossary
1819
+
1820
+ - **Agent**: AI-powered assistant defined in markdown with YAML frontmatter
1821
+ - **API-Based Publishing**: Content publishing via HTTP APIs (WordPress, PayloadCMS)
1822
+ - **CLI**: Command Line Interface
1823
+ - **Coolify**: Self-hosted Platform-as-a-Service (PaaS) for application deployment
1824
+ - **Frontmatter**: YAML metadata at the top of markdown files
1825
+ - **Git-Based Publishing**: Content publishing via file operations and git workflow
1826
+ - **Gutenberg**: WordPress block editor format
1827
+ - **JWT**: JSON Web Token for authentication
1828
+ - **Lexical**: Rich text editor format used by PayloadCMS
1829
+ - **MCP**: Model Context Protocol for AI tool integration
1830
+ - **Nixpacks**: Automatic build system used by Coolify
1831
+ - **Slash Command**: Claude Code command starting with `/`
1832
+ - **Static Site Generator**: Tool that generates static HTML from markdown (Docusaurus, Astro)
1833
+ - **Subagent**: Delegated agent for parallel task execution
1834
+ - **Token**: Authentication credential or AI context unit
1835
+ - **Utility Class**: Reusable JavaScript class with core platform logic
1836
+
1837
+ ---
1838
+
1839
+ ## Contributing
1840
+
1841
+ To contribute to MyAIDev Method:
1842
+
1843
+ 1. **Fork Repository**: https://github.com/myaione/myaidev-method
1844
+ 2. **Create Feature Branch**: `git checkout -b feature/new-platform`
1845
+ 3. **Follow Patterns**: Use existing utilities as templates
1846
+ 4. **Write Tests**: Add tests for new functionality
1847
+ 5. **Update Docs**: Document new features comprehensively
1848
+ 6. **Submit PR**: Provide clear description of changes
1849
+
1850
+ ---
1851
+
1852
+ ## License
1853
+
1854
+ MIT License - See LICENSE file for details.
1855
+
1856
+ ---
1857
+
1858
+ ## Support
1859
+
1860
+ - **GitHub Issues**: https://github.com/myaione/myaidev-method/issues
1861
+ - **NPM Package**: https://www.npmjs.com/package/myaidev-method
1862
+ - **Documentation**: See USER_GUIDE.md, PUBLISHING_GUIDE.md
1863
+
1864
+ ---
1865
+
1866
+ **Document Version**: 1.0.0
1867
+ **Package Version**: 0.2.1
1868
+ **Last Updated**: 2025-10-16