@weavelogic/knowledge-graph-agent 0.1.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 (74) hide show
  1. package/README.md +264 -0
  2. package/dist/cli/bin.d.ts +8 -0
  3. package/dist/cli/bin.d.ts.map +1 -0
  4. package/dist/cli/bin.js +20 -0
  5. package/dist/cli/bin.js.map +1 -0
  6. package/dist/cli/commands/claude.d.ts +11 -0
  7. package/dist/cli/commands/claude.d.ts.map +1 -0
  8. package/dist/cli/commands/claude.js +102 -0
  9. package/dist/cli/commands/claude.js.map +1 -0
  10. package/dist/cli/commands/docs.d.ts +11 -0
  11. package/dist/cli/commands/docs.d.ts.map +1 -0
  12. package/dist/cli/commands/docs.js +108 -0
  13. package/dist/cli/commands/docs.js.map +1 -0
  14. package/dist/cli/commands/graph.d.ts +11 -0
  15. package/dist/cli/commands/graph.d.ts.map +1 -0
  16. package/dist/cli/commands/graph.js +122 -0
  17. package/dist/cli/commands/graph.js.map +1 -0
  18. package/dist/cli/commands/init.d.ts +11 -0
  19. package/dist/cli/commands/init.d.ts.map +1 -0
  20. package/dist/cli/commands/init.js +80 -0
  21. package/dist/cli/commands/init.js.map +1 -0
  22. package/dist/cli/commands/search.d.ts +11 -0
  23. package/dist/cli/commands/search.d.ts.map +1 -0
  24. package/dist/cli/commands/search.js +80 -0
  25. package/dist/cli/commands/search.js.map +1 -0
  26. package/dist/cli/commands/stats.d.ts +11 -0
  27. package/dist/cli/commands/stats.d.ts.map +1 -0
  28. package/dist/cli/commands/stats.js +84 -0
  29. package/dist/cli/commands/stats.js.map +1 -0
  30. package/dist/cli/commands/sync.d.ts +11 -0
  31. package/dist/cli/commands/sync.d.ts.map +1 -0
  32. package/dist/cli/commands/sync.js +76 -0
  33. package/dist/cli/commands/sync.js.map +1 -0
  34. package/dist/cli/index.d.ts +11 -0
  35. package/dist/cli/index.d.ts.map +1 -0
  36. package/dist/cli/index.js +45 -0
  37. package/dist/cli/index.js.map +1 -0
  38. package/dist/core/database.d.ts +121 -0
  39. package/dist/core/database.d.ts.map +1 -0
  40. package/dist/core/database.js +470 -0
  41. package/dist/core/database.js.map +1 -0
  42. package/dist/core/graph.d.ts +109 -0
  43. package/dist/core/graph.d.ts.map +1 -0
  44. package/dist/core/graph.js +343 -0
  45. package/dist/core/graph.js.map +1 -0
  46. package/dist/core/security.d.ts +62 -0
  47. package/dist/core/security.d.ts.map +1 -0
  48. package/dist/core/security.js +31 -0
  49. package/dist/core/security.js.map +1 -0
  50. package/dist/core/types.d.ts +232 -0
  51. package/dist/core/types.d.ts.map +1 -0
  52. package/dist/core/types.js +37 -0
  53. package/dist/core/types.js.map +1 -0
  54. package/dist/generators/claude-md.d.ts +33 -0
  55. package/dist/generators/claude-md.d.ts.map +1 -0
  56. package/dist/generators/claude-md.js +410 -0
  57. package/dist/generators/claude-md.js.map +1 -0
  58. package/dist/generators/docs-init.d.ts +20 -0
  59. package/dist/generators/docs-init.d.ts.map +1 -0
  60. package/dist/generators/docs-init.js +625 -0
  61. package/dist/generators/docs-init.js.map +1 -0
  62. package/dist/generators/graph-generator.d.ts +41 -0
  63. package/dist/generators/graph-generator.d.ts.map +1 -0
  64. package/dist/generators/graph-generator.js +266 -0
  65. package/dist/generators/graph-generator.js.map +1 -0
  66. package/dist/index.d.ts +41 -0
  67. package/dist/index.d.ts.map +1 -0
  68. package/dist/index.js +99 -0
  69. package/dist/index.js.map +1 -0
  70. package/dist/integrations/claude-flow.d.ts +62 -0
  71. package/dist/integrations/claude-flow.d.ts.map +1 -0
  72. package/dist/integrations/claude-flow.js +243 -0
  73. package/dist/integrations/claude-flow.js.map +1 -0
  74. package/package.json +77 -0
@@ -0,0 +1,410 @@
1
+ import { existsSync, writeFileSync, readFileSync } from "fs";
2
+ import { join, basename, resolve, normalize } from "path";
3
+ import Handlebars from "handlebars";
4
+ function validateTemplatePath(projectRoot, templatePath) {
5
+ const resolvedRoot = resolve(projectRoot);
6
+ const resolvedTemplate = resolve(projectRoot, templatePath);
7
+ const normalizedTemplate = normalize(resolvedTemplate);
8
+ if (!normalizedTemplate.startsWith(resolvedRoot + "/") && normalizedTemplate !== resolvedRoot) {
9
+ return null;
10
+ }
11
+ if (!normalizedTemplate.endsWith(".md")) {
12
+ return null;
13
+ }
14
+ return normalizedTemplate;
15
+ }
16
+ const DEFAULT_TEMPLATE = `# Claude Code Configuration - {{projectName}}
17
+
18
+ ## Project Overview
19
+
20
+ {{description}}
21
+
22
+ ## Knowledge Graph Integration
23
+
24
+ This project uses @weavelogic/knowledge-graph-agent for documentation and planning.
25
+
26
+ ### Quick Commands
27
+
28
+ \`\`\`bash
29
+ # Initialize knowledge graph
30
+ npx kg init
31
+
32
+ # Generate/update graph from docs
33
+ npx kg graph
34
+
35
+ # Sync with claude-flow memory
36
+ npx kg sync
37
+
38
+ # Initialize docs directory
39
+ npx kg docs init
40
+
41
+ # Update CLAUDE.md
42
+ npx kg claude update
43
+ \`\`\`
44
+
45
+ ### Vault Location
46
+
47
+ Documentation is stored in: \`{{docsPath}}\`
48
+
49
+ ## File Organization
50
+
51
+ {{#if customDirectories}}
52
+ {{#each customDirectories}}
53
+ - \`{{this.path}}\` - {{this.description}}
54
+ {{/each}}
55
+ {{else}}
56
+ - \`/src\` - Source code files
57
+ - \`/docs\` - Documentation and knowledge base
58
+ - \`/tests\` - Test files
59
+ - \`/config\` - Configuration files
60
+ {{/if}}
61
+
62
+ ## Build Commands
63
+
64
+ {{#each buildCommands}}
65
+ - \`{{this.command}}\` - {{this.description}}
66
+ {{/each}}
67
+
68
+ ## Code Style & Best Practices
69
+
70
+ {{#each codeStyleRules}}
71
+ - **{{this.name}}**: {{this.description}}
72
+ {{/each}}
73
+
74
+ {{#if includeClaudeFlow}}
75
+ ## Claude-Flow Integration
76
+
77
+ This project uses claude-flow for AI coordination:
78
+
79
+ ### MCP Configuration
80
+
81
+ \`\`\`bash
82
+ claude mcp add claude-flow npx claude-flow@alpha mcp start
83
+ \`\`\`
84
+
85
+ ### Memory Namespace
86
+
87
+ - **Namespace**: \`{{namespace}}\`
88
+ - **Sync on change**: {{syncOnChange}}
89
+
90
+ ### Available Tools
91
+
92
+ - \`mcp__claude-flow__memory_usage\` - Store/retrieve knowledge
93
+ - \`mcp__claude-flow__swarm_init\` - Initialize agent swarms
94
+ - \`mcp__claude-flow__task_orchestrate\` - Coordinate tasks
95
+
96
+ {{/if}}
97
+ {{#if includeKnowledgeGraph}}
98
+ ## Knowledge Graph Commands
99
+
100
+ The knowledge graph provides semantic navigation of the codebase:
101
+
102
+ ### CLI Commands
103
+
104
+ | Command | Description |
105
+ |---------|-------------|
106
+ | \`kg init\` | Initialize knowledge graph in project |
107
+ | \`kg graph\` | Generate/update knowledge graph |
108
+ | \`kg docs init\` | Initialize docs directory |
109
+ | \`kg docs generate\` | Generate docs from codebase |
110
+ | \`kg claude update\` | Update CLAUDE.md |
111
+ | \`kg sync\` | Sync with claude-flow memory |
112
+ | \`kg stats\` | Show graph statistics |
113
+ | \`kg search <query>\` | Search the knowledge graph |
114
+
115
+ ### Graph Structure
116
+
117
+ \`\`\`
118
+ {{docsPath}}/
119
+ ├── concepts/ # Abstract concepts
120
+ ├── components/ # Reusable components
121
+ ├── services/ # Backend services
122
+ ├── features/ # Product features
123
+ ├── integrations/ # External integrations
124
+ ├── standards/ # Coding standards
125
+ ├── guides/ # How-to guides
126
+ └── references/ # API references
127
+ \`\`\`
128
+
129
+ {{/if}}
130
+ {{#if customSections}}
131
+ {{#each customSections}}
132
+ ## {{this.title}}
133
+
134
+ {{this.content}}
135
+
136
+ {{/each}}
137
+ {{/if}}
138
+ ## Important Instructions
139
+
140
+ - NEVER create files unless absolutely necessary
141
+ - ALWAYS prefer editing existing files
142
+ - Use the knowledge graph for documentation
143
+ - Follow the file organization above
144
+ - Run tests before committing
145
+
146
+ ---
147
+ *Generated by @weavelogic/knowledge-graph-agent*
148
+ `;
149
+ const SECTION_TEMPLATES = {
150
+ sparc: {
151
+ title: "SPARC Methodology",
152
+ order: 10,
153
+ content: `This project follows the SPARC development methodology:
154
+
155
+ 1. **Specification** - Requirements analysis
156
+ 2. **Pseudocode** - Algorithm design
157
+ 3. **Architecture** - System design
158
+ 4. **Refinement** - TDD implementation
159
+ 5. **Completion** - Integration
160
+
161
+ ### SPARC Commands
162
+
163
+ \`\`\`bash
164
+ npx claude-flow sparc modes # List available modes
165
+ npx claude-flow sparc tdd "<task>" # Run TDD workflow
166
+ npx claude-flow sparc run <mode> # Execute specific mode
167
+ \`\`\``
168
+ },
169
+ testing: {
170
+ title: "Testing Requirements",
171
+ order: 20,
172
+ content: `All code changes must include appropriate tests:
173
+
174
+ - **Unit tests**: For individual functions and components
175
+ - **Integration tests**: For API endpoints and services
176
+ - **E2E tests**: For critical user flows
177
+
178
+ ### Running Tests
179
+
180
+ \`\`\`bash
181
+ npm run test # Run all tests
182
+ npm run test:watch # Watch mode
183
+ npm run test:cov # With coverage
184
+ \`\`\``
185
+ },
186
+ security: {
187
+ title: "Security Guidelines",
188
+ order: 30,
189
+ content: `Security is a priority. Follow these guidelines:
190
+
191
+ - Never hardcode secrets or API keys
192
+ - Use environment variables for sensitive data
193
+ - Validate all user inputs
194
+ - Sanitize outputs to prevent XSS
195
+ - Follow OWASP guidelines`
196
+ },
197
+ agents: {
198
+ title: "Available Agents",
199
+ order: 40,
200
+ content: `Use Claude Code's Task tool to spawn specialized agents:
201
+
202
+ ### Core Agents
203
+ \`coder\`, \`reviewer\`, \`tester\`, \`planner\`, \`researcher\`
204
+
205
+ ### SPARC Agents
206
+ \`sparc-coord\`, \`sparc-coder\`, \`specification\`, \`architecture\`
207
+
208
+ ### Specialized Agents
209
+ \`backend-dev\`, \`system-architect\`, \`code-analyzer\`, \`api-docs\`
210
+
211
+ ### Usage
212
+
213
+ \`\`\`javascript
214
+ Task("Implement feature", "Description...", "coder")
215
+ Task("Review code", "Description...", "reviewer")
216
+ \`\`\``
217
+ }
218
+ };
219
+ function generateClaudeMd(options) {
220
+ const {
221
+ projectRoot,
222
+ template,
223
+ includeKnowledgeGraph = true,
224
+ includeClaudeFlow = true,
225
+ customSections = []
226
+ } = options;
227
+ const projectInfo = detectProjectInfo(projectRoot);
228
+ const context = {
229
+ projectName: projectInfo.name,
230
+ description: projectInfo.description || `${projectInfo.name} project`,
231
+ docsPath: getDocsPath(projectRoot),
232
+ includeKnowledgeGraph,
233
+ includeClaudeFlow,
234
+ namespace: "knowledge-graph",
235
+ syncOnChange: true,
236
+ buildCommands: projectInfo.scripts,
237
+ codeStyleRules: getDefaultCodeStyleRules(),
238
+ customSections: [...customSections],
239
+ customDirectories: null
240
+ };
241
+ const templateContent = template ? getTemplateContent(template, projectRoot) : DEFAULT_TEMPLATE;
242
+ const compiled = Handlebars.compile(templateContent);
243
+ return compiled(context);
244
+ }
245
+ async function updateClaudeMd(options) {
246
+ const { projectRoot, outputPath } = options;
247
+ const filePath = outputPath || join(projectRoot, "CLAUDE.md");
248
+ const exists = existsSync(filePath);
249
+ const content = generateClaudeMd(options);
250
+ writeFileSync(filePath, content, "utf-8");
251
+ return {
252
+ created: !exists,
253
+ updated: exists,
254
+ path: filePath,
255
+ content
256
+ };
257
+ }
258
+ function addSection(projectRoot, section) {
259
+ const filePath = join(projectRoot, "CLAUDE.md");
260
+ if (!existsSync(filePath)) {
261
+ return false;
262
+ }
263
+ const content = readFileSync(filePath, "utf-8");
264
+ const sectionRegex = new RegExp(`^## ${section.title}`, "m");
265
+ if (sectionRegex.test(content)) {
266
+ return false;
267
+ }
268
+ const importantMatch = content.match(/^## Important Instructions/m);
269
+ let newContent;
270
+ const sectionContent = `
271
+ ## ${section.title}
272
+
273
+ ${section.content}
274
+ `;
275
+ if (importantMatch && importantMatch.index !== void 0) {
276
+ newContent = content.slice(0, importantMatch.index) + sectionContent + "\n" + content.slice(importantMatch.index);
277
+ } else {
278
+ newContent = content + sectionContent;
279
+ }
280
+ writeFileSync(filePath, newContent, "utf-8");
281
+ return true;
282
+ }
283
+ function getSectionTemplate(name) {
284
+ return SECTION_TEMPLATES[name] || null;
285
+ }
286
+ function listSectionTemplates() {
287
+ return Object.keys(SECTION_TEMPLATES);
288
+ }
289
+ function sanitizeForTemplate(str, maxLength = 200) {
290
+ if (!str || typeof str !== "string") return "";
291
+ return str.replace(/[<>&"'`{}\\]/g, "").replace(/\{\{/g, "").replace(/\}\}/g, "").slice(0, maxLength).trim();
292
+ }
293
+ function detectProjectInfo(projectRoot) {
294
+ const info = {
295
+ name: sanitizeForTemplate(basename(projectRoot), 100) || "project",
296
+ scripts: []
297
+ };
298
+ try {
299
+ const pkgPath = join(projectRoot, "package.json");
300
+ if (existsSync(pkgPath)) {
301
+ let pkg;
302
+ try {
303
+ pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
304
+ } catch {
305
+ return info;
306
+ }
307
+ const rawName = (pkg.name || basename(projectRoot)).replace(/^@[^/]+\//, "");
308
+ info.name = sanitizeForTemplate(rawName, 100) || "project";
309
+ info.description = sanitizeForTemplate(pkg.description, 500);
310
+ if (pkg.scripts && typeof pkg.scripts === "object") {
311
+ const commonScripts = ["build", "test", "dev", "start", "lint", "typecheck"];
312
+ for (const script of commonScripts) {
313
+ if (pkg.scripts[script] && typeof pkg.scripts[script] === "string") {
314
+ info.scripts.push({
315
+ command: `npm run ${script}`,
316
+ description: sanitizeForTemplate(
317
+ getScriptDescription(script, pkg.scripts[script]),
318
+ 200
319
+ )
320
+ });
321
+ }
322
+ }
323
+ }
324
+ }
325
+ } catch {
326
+ }
327
+ if (info.scripts.length === 0) {
328
+ info.scripts = [
329
+ { command: "npm run build", description: "Build the project" },
330
+ { command: "npm run test", description: "Run tests" },
331
+ { command: "npm run dev", description: "Development mode" }
332
+ ];
333
+ }
334
+ return info;
335
+ }
336
+ function getScriptDescription(name, script) {
337
+ const descriptions = {
338
+ build: "Build the project",
339
+ test: "Run tests",
340
+ dev: "Start development server",
341
+ start: "Start production server",
342
+ lint: "Run linter",
343
+ typecheck: "Type checking"
344
+ };
345
+ return descriptions[name] || `Run ${name}`;
346
+ }
347
+ function getDocsPath(projectRoot) {
348
+ const possiblePaths = ["docs", "documentation", "doc"];
349
+ for (const path of possiblePaths) {
350
+ if (existsSync(join(projectRoot, path))) {
351
+ return path;
352
+ }
353
+ }
354
+ return "docs";
355
+ }
356
+ function getDefaultCodeStyleRules() {
357
+ return [
358
+ { name: "Modular Design", description: "Files under 500 lines" },
359
+ { name: "Environment Safety", description: "Never hardcode secrets" },
360
+ { name: "Test-First", description: "Write tests before implementation" },
361
+ { name: "Clean Architecture", description: "Separate concerns" },
362
+ { name: "Documentation", description: "Keep docs updated" }
363
+ ];
364
+ }
365
+ function getTemplateContent(templateName, projectRoot) {
366
+ if (templateName === "minimal") {
367
+ return `# {{projectName}}
368
+
369
+ {{description}}
370
+
371
+ ## Commands
372
+
373
+ {{#each buildCommands}}
374
+ - \`{{this.command}}\` - {{this.description}}
375
+ {{/each}}
376
+
377
+ ---
378
+ *Generated by @weavelogic/knowledge-graph-agent*
379
+ `;
380
+ }
381
+ if (templateName === "full") {
382
+ let content = DEFAULT_TEMPLATE;
383
+ for (const section of Object.values(SECTION_TEMPLATES)) {
384
+ content = content.replace(
385
+ /^## Important Instructions/m,
386
+ `## ${section.title}
387
+
388
+ ${section.content}
389
+
390
+ ## Important Instructions`
391
+ );
392
+ }
393
+ return content;
394
+ }
395
+ if (projectRoot && (templateName.includes("/") || templateName.includes("."))) {
396
+ const validatedPath = validateTemplatePath(projectRoot, templateName);
397
+ if (validatedPath && existsSync(validatedPath)) {
398
+ return readFileSync(validatedPath, "utf-8");
399
+ }
400
+ }
401
+ return DEFAULT_TEMPLATE;
402
+ }
403
+ export {
404
+ addSection,
405
+ generateClaudeMd,
406
+ getSectionTemplate,
407
+ listSectionTemplates,
408
+ updateClaudeMd
409
+ };
410
+ //# sourceMappingURL=claude-md.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"claude-md.js","sources":["../../src/generators/claude-md.ts"],"sourcesContent":["/**\n * CLAUDE.md Generator\n *\n * Generates and manages CLAUDE.md configuration files for Claude Code\n * with knowledge graph integration.\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'fs';\nimport { join, basename, resolve, normalize } from 'path';\nimport Handlebars from 'handlebars';\nimport type {\n ClaudeMdGeneratorOptions,\n ClaudeMdSection,\n ClaudeMdTemplate,\n} from '../core/types.js';\n\n/**\n * Validate that a template path is within the project directory\n * and is a markdown file\n */\nfunction validateTemplatePath(projectRoot: string, templatePath: string): string | null {\n // Resolve both paths to absolute\n const resolvedRoot = resolve(projectRoot);\n const resolvedTemplate = resolve(projectRoot, templatePath);\n const normalizedTemplate = normalize(resolvedTemplate);\n\n // Ensure template is within project directory\n if (!normalizedTemplate.startsWith(resolvedRoot + '/') && normalizedTemplate !== resolvedRoot) {\n return null; // Path traversal attempt\n }\n\n // Must be a markdown file\n if (!normalizedTemplate.endsWith('.md')) {\n return null;\n }\n\n return normalizedTemplate;\n}\n\n/**\n * Default CLAUDE.md template with knowledge graph integration\n */\nconst DEFAULT_TEMPLATE = `# Claude Code Configuration - {{projectName}}\n\n## Project Overview\n\n{{description}}\n\n## Knowledge Graph Integration\n\nThis project uses @weavelogic/knowledge-graph-agent for documentation and planning.\n\n### Quick Commands\n\n\\`\\`\\`bash\n# Initialize knowledge graph\nnpx kg init\n\n# Generate/update graph from docs\nnpx kg graph\n\n# Sync with claude-flow memory\nnpx kg sync\n\n# Initialize docs directory\nnpx kg docs init\n\n# Update CLAUDE.md\nnpx kg claude update\n\\`\\`\\`\n\n### Vault Location\n\nDocumentation is stored in: \\`{{docsPath}}\\`\n\n## File Organization\n\n{{#if customDirectories}}\n{{#each customDirectories}}\n- \\`{{this.path}}\\` - {{this.description}}\n{{/each}}\n{{else}}\n- \\`/src\\` - Source code files\n- \\`/docs\\` - Documentation and knowledge base\n- \\`/tests\\` - Test files\n- \\`/config\\` - Configuration files\n{{/if}}\n\n## Build Commands\n\n{{#each buildCommands}}\n- \\`{{this.command}}\\` - {{this.description}}\n{{/each}}\n\n## Code Style & Best Practices\n\n{{#each codeStyleRules}}\n- **{{this.name}}**: {{this.description}}\n{{/each}}\n\n{{#if includeClaudeFlow}}\n## Claude-Flow Integration\n\nThis project uses claude-flow for AI coordination:\n\n### MCP Configuration\n\n\\`\\`\\`bash\nclaude mcp add claude-flow npx claude-flow@alpha mcp start\n\\`\\`\\`\n\n### Memory Namespace\n\n- **Namespace**: \\`{{namespace}}\\`\n- **Sync on change**: {{syncOnChange}}\n\n### Available Tools\n\n- \\`mcp__claude-flow__memory_usage\\` - Store/retrieve knowledge\n- \\`mcp__claude-flow__swarm_init\\` - Initialize agent swarms\n- \\`mcp__claude-flow__task_orchestrate\\` - Coordinate tasks\n\n{{/if}}\n{{#if includeKnowledgeGraph}}\n## Knowledge Graph Commands\n\nThe knowledge graph provides semantic navigation of the codebase:\n\n### CLI Commands\n\n| Command | Description |\n|---------|-------------|\n| \\`kg init\\` | Initialize knowledge graph in project |\n| \\`kg graph\\` | Generate/update knowledge graph |\n| \\`kg docs init\\` | Initialize docs directory |\n| \\`kg docs generate\\` | Generate docs from codebase |\n| \\`kg claude update\\` | Update CLAUDE.md |\n| \\`kg sync\\` | Sync with claude-flow memory |\n| \\`kg stats\\` | Show graph statistics |\n| \\`kg search <query>\\` | Search the knowledge graph |\n\n### Graph Structure\n\n\\`\\`\\`\n{{docsPath}}/\n├── concepts/ # Abstract concepts\n├── components/ # Reusable components\n├── services/ # Backend services\n├── features/ # Product features\n├── integrations/ # External integrations\n├── standards/ # Coding standards\n├── guides/ # How-to guides\n└── references/ # API references\n\\`\\`\\`\n\n{{/if}}\n{{#if customSections}}\n{{#each customSections}}\n## {{this.title}}\n\n{{this.content}}\n\n{{/each}}\n{{/if}}\n## Important Instructions\n\n- NEVER create files unless absolutely necessary\n- ALWAYS prefer editing existing files\n- Use the knowledge graph for documentation\n- Follow the file organization above\n- Run tests before committing\n\n---\n*Generated by @weavelogic/knowledge-graph-agent*\n`;\n\n/**\n * Section templates for common configurations\n */\nconst SECTION_TEMPLATES: Record<string, ClaudeMdSection> = {\n sparc: {\n title: 'SPARC Methodology',\n order: 10,\n content: `This project follows the SPARC development methodology:\n\n1. **Specification** - Requirements analysis\n2. **Pseudocode** - Algorithm design\n3. **Architecture** - System design\n4. **Refinement** - TDD implementation\n5. **Completion** - Integration\n\n### SPARC Commands\n\n\\`\\`\\`bash\nnpx claude-flow sparc modes # List available modes\nnpx claude-flow sparc tdd \"<task>\" # Run TDD workflow\nnpx claude-flow sparc run <mode> # Execute specific mode\n\\`\\`\\``,\n },\n\n testing: {\n title: 'Testing Requirements',\n order: 20,\n content: `All code changes must include appropriate tests:\n\n- **Unit tests**: For individual functions and components\n- **Integration tests**: For API endpoints and services\n- **E2E tests**: For critical user flows\n\n### Running Tests\n\n\\`\\`\\`bash\nnpm run test # Run all tests\nnpm run test:watch # Watch mode\nnpm run test:cov # With coverage\n\\`\\`\\``,\n },\n\n security: {\n title: 'Security Guidelines',\n order: 30,\n content: `Security is a priority. Follow these guidelines:\n\n- Never hardcode secrets or API keys\n- Use environment variables for sensitive data\n- Validate all user inputs\n- Sanitize outputs to prevent XSS\n- Follow OWASP guidelines`,\n },\n\n agents: {\n title: 'Available Agents',\n order: 40,\n content: `Use Claude Code's Task tool to spawn specialized agents:\n\n### Core Agents\n\\`coder\\`, \\`reviewer\\`, \\`tester\\`, \\`planner\\`, \\`researcher\\`\n\n### SPARC Agents\n\\`sparc-coord\\`, \\`sparc-coder\\`, \\`specification\\`, \\`architecture\\`\n\n### Specialized Agents\n\\`backend-dev\\`, \\`system-architect\\`, \\`code-analyzer\\`, \\`api-docs\\`\n\n### Usage\n\n\\`\\`\\`javascript\nTask(\"Implement feature\", \"Description...\", \"coder\")\nTask(\"Review code\", \"Description...\", \"reviewer\")\n\\`\\`\\``,\n },\n};\n\n/**\n * Generate CLAUDE.md content\n */\nexport function generateClaudeMd(options: ClaudeMdGeneratorOptions): string {\n const {\n projectRoot,\n template,\n includeKnowledgeGraph = true,\n includeClaudeFlow = true,\n customSections = [],\n } = options;\n\n // Detect project info\n const projectInfo = detectProjectInfo(projectRoot);\n\n // Prepare context\n const context = {\n projectName: projectInfo.name,\n description: projectInfo.description || `${projectInfo.name} project`,\n docsPath: getDocsPath(projectRoot),\n includeKnowledgeGraph,\n includeClaudeFlow,\n namespace: 'knowledge-graph',\n syncOnChange: true,\n buildCommands: projectInfo.scripts,\n codeStyleRules: getDefaultCodeStyleRules(),\n customSections: [...customSections],\n customDirectories: null,\n };\n\n // Get template content (pass projectRoot for path validation)\n const templateContent = template ? getTemplateContent(template, projectRoot) : DEFAULT_TEMPLATE;\n\n // Compile and render\n const compiled = Handlebars.compile(templateContent);\n return compiled(context);\n}\n\n/**\n * Create or update CLAUDE.md file\n */\nexport async function updateClaudeMd(options: ClaudeMdGeneratorOptions): Promise<{\n created: boolean;\n updated: boolean;\n path: string;\n content: string;\n}> {\n const { projectRoot, outputPath } = options;\n const filePath = outputPath || join(projectRoot, 'CLAUDE.md');\n\n const exists = existsSync(filePath);\n const content = generateClaudeMd(options);\n\n writeFileSync(filePath, content, 'utf-8');\n\n return {\n created: !exists,\n updated: exists,\n path: filePath,\n content,\n };\n}\n\n/**\n * Add section to existing CLAUDE.md\n */\nexport function addSection(\n projectRoot: string,\n section: ClaudeMdSection\n): boolean {\n const filePath = join(projectRoot, 'CLAUDE.md');\n\n if (!existsSync(filePath)) {\n return false;\n }\n\n const content = readFileSync(filePath, 'utf-8');\n\n // Check if section already exists\n const sectionRegex = new RegExp(`^## ${section.title}`, 'm');\n if (sectionRegex.test(content)) {\n return false; // Section already exists\n }\n\n // Find the best position to insert (before Important Instructions or at end)\n const importantMatch = content.match(/^## Important Instructions/m);\n let newContent: string;\n\n const sectionContent = `\\n## ${section.title}\\n\\n${section.content}\\n`;\n\n if (importantMatch && importantMatch.index !== undefined) {\n newContent =\n content.slice(0, importantMatch.index) +\n sectionContent +\n '\\n' +\n content.slice(importantMatch.index);\n } else {\n newContent = content + sectionContent;\n }\n\n writeFileSync(filePath, newContent, 'utf-8');\n return true;\n}\n\n/**\n * Get predefined section template\n */\nexport function getSectionTemplate(name: string): ClaudeMdSection | null {\n return SECTION_TEMPLATES[name] || null;\n}\n\n/**\n * List available section templates\n */\nexport function listSectionTemplates(): string[] {\n return Object.keys(SECTION_TEMPLATES);\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\ninterface ProjectInfo {\n name: string;\n description?: string;\n scripts: Array<{ command: string; description: string }>;\n}\n\n/**\n * Sanitize string for safe template use\n * Prevents template injection and removes dangerous characters\n */\nfunction sanitizeForTemplate(str: string | undefined, maxLength = 200): string {\n if (!str || typeof str !== 'string') return '';\n return str\n .replace(/[<>&\"'`{}\\\\]/g, '') // Remove template-sensitive chars\n .replace(/\\{\\{/g, '') // Remove Handlebars delimiters\n .replace(/\\}\\}/g, '')\n .slice(0, maxLength)\n .trim();\n}\n\nfunction detectProjectInfo(projectRoot: string): ProjectInfo {\n const info: ProjectInfo = {\n name: sanitizeForTemplate(basename(projectRoot), 100) || 'project',\n scripts: [],\n };\n\n try {\n const pkgPath = join(projectRoot, 'package.json');\n if (existsSync(pkgPath)) {\n let pkg;\n try {\n pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));\n } catch {\n return info; // Return default info on JSON parse error\n }\n\n // Sanitize project name\n const rawName = (pkg.name || basename(projectRoot)).replace(/^@[^/]+\\//, '');\n info.name = sanitizeForTemplate(rawName, 100) || 'project';\n\n // Sanitize description\n info.description = sanitizeForTemplate(pkg.description, 500);\n\n // Extract common scripts (sanitize script names)\n if (pkg.scripts && typeof pkg.scripts === 'object') {\n const commonScripts = ['build', 'test', 'dev', 'start', 'lint', 'typecheck'];\n for (const script of commonScripts) {\n if (pkg.scripts[script] && typeof pkg.scripts[script] === 'string') {\n info.scripts.push({\n command: `npm run ${script}`,\n description: sanitizeForTemplate(\n getScriptDescription(script, pkg.scripts[script]),\n 200\n ),\n });\n }\n }\n }\n }\n } catch {\n // Ignore errors - return default info\n }\n\n // Add default scripts if none found\n if (info.scripts.length === 0) {\n info.scripts = [\n { command: 'npm run build', description: 'Build the project' },\n { command: 'npm run test', description: 'Run tests' },\n { command: 'npm run dev', description: 'Development mode' },\n ];\n }\n\n return info;\n}\n\nfunction getScriptDescription(name: string, script: string): string {\n const descriptions: Record<string, string> = {\n build: 'Build the project',\n test: 'Run tests',\n dev: 'Start development server',\n start: 'Start production server',\n lint: 'Run linter',\n typecheck: 'Type checking',\n };\n\n return descriptions[name] || `Run ${name}`;\n}\n\nfunction getDocsPath(projectRoot: string): string {\n const possiblePaths = ['docs', 'documentation', 'doc'];\n\n for (const path of possiblePaths) {\n if (existsSync(join(projectRoot, path))) {\n return path;\n }\n }\n\n return 'docs';\n}\n\nfunction getDefaultCodeStyleRules(): Array<{ name: string; description: string }> {\n return [\n { name: 'Modular Design', description: 'Files under 500 lines' },\n { name: 'Environment Safety', description: 'Never hardcode secrets' },\n { name: 'Test-First', description: 'Write tests before implementation' },\n { name: 'Clean Architecture', description: 'Separate concerns' },\n { name: 'Documentation', description: 'Keep docs updated' },\n ];\n}\n\nfunction getTemplateContent(templateName: string, projectRoot?: string): string {\n // Check for built-in templates\n if (templateName === 'minimal') {\n return `# {{projectName}}\n\n{{description}}\n\n## Commands\n\n{{#each buildCommands}}\n- \\`{{this.command}}\\` - {{this.description}}\n{{/each}}\n\n---\n*Generated by @weavelogic/knowledge-graph-agent*\n`;\n }\n\n if (templateName === 'full') {\n // Add all sections\n let content = DEFAULT_TEMPLATE;\n for (const section of Object.values(SECTION_TEMPLATES)) {\n content = content.replace(\n /^## Important Instructions/m,\n `## ${section.title}\\n\\n${section.content}\\n\\n## Important Instructions`\n );\n }\n return content;\n }\n\n // Try to read as file path - only if within project directory\n if (projectRoot && (templateName.includes('/') || templateName.includes('.'))) {\n const validatedPath = validateTemplatePath(projectRoot, templateName);\n if (validatedPath && existsSync(validatedPath)) {\n return readFileSync(validatedPath, 'utf-8');\n }\n }\n\n return DEFAULT_TEMPLATE;\n}\n"],"names":[],"mappings":";;;A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A,SAAO;AACT;"}
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Docs Directory Initializer
3
+ *
4
+ * Creates the initial docs directory structure following the weave-nn
5
+ * methodology with proper PRIMITIVES.md taxonomy.
6
+ */
7
+ import type { DocsInitOptions, DocsInitResult } from '../core/types.js';
8
+ /**
9
+ * Initialize docs directory
10
+ */
11
+ export declare function initDocs(options: DocsInitOptions): Promise<DocsInitResult>;
12
+ /**
13
+ * Check if docs directory exists
14
+ */
15
+ export declare function docsExist(projectRoot: string, docsPath?: string): boolean;
16
+ /**
17
+ * Get docs path for a project
18
+ */
19
+ export declare function getDocsPath(projectRoot: string): string | null;
20
+ //# sourceMappingURL=docs-init.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"docs-init.d.ts","sourceRoot":"","sources":["../../src/generators/docs-init.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAMH,OAAO,KAAK,EACV,eAAe,EACf,cAAc,EAEf,MAAM,kBAAkB,CAAC;AA2X1B;;GAEG;AACH,wBAAsB,QAAQ,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,cAAc,CAAC,CA6FhF;AAmPD;;GAEG;AACH,wBAAgB,SAAS,CAAC,WAAW,EAAE,MAAM,EAAE,QAAQ,SAAS,GAAG,OAAO,CAEzE;AAED;;GAEG;AACH,wBAAgB,WAAW,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAW9D"}