@claudetools/tools 0.9.0 → 0.9.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.
Files changed (85) hide show
  1. package/dist/cli.js +9 -1
  2. package/dist/codedna/__tests__/examples/mongoose-example.d.ts +6 -0
  3. package/dist/codedna/__tests__/examples/mongoose-example.js +163 -0
  4. package/dist/codedna/__tests__/fixtures/typeorm-production-test.d.ts +1 -0
  5. package/dist/codedna/__tests__/fixtures/typeorm-production-test.js +231 -0
  6. package/dist/codedna/__tests__/fixtures/typeorm-test.d.ts +1 -0
  7. package/dist/codedna/__tests__/fixtures/typeorm-test.js +124 -0
  8. package/dist/codedna/__tests__/laravel-output-review.d.ts +1 -0
  9. package/dist/codedna/__tests__/laravel-output-review.js +249 -0
  10. package/dist/codedna/__tests__/mongoose-output-test.d.ts +1 -0
  11. package/dist/codedna/__tests__/mongoose-output-test.js +178 -0
  12. package/dist/codedna/examples/radix-example.d.ts +2 -0
  13. package/dist/codedna/examples/radix-example.js +259 -0
  14. package/dist/codedna/index.d.ts +5 -3
  15. package/dist/codedna/index.js +6 -3
  16. package/dist/codedna/kappa-ast.d.ts +143 -5
  17. package/dist/codedna/kappa-drizzle-generator.js +8 -5
  18. package/dist/codedna/kappa-gofiber-generator.d.ts +65 -0
  19. package/dist/codedna/kappa-gofiber-generator.js +587 -0
  20. package/dist/codedna/kappa-laravel-generator.d.ts +68 -0
  21. package/dist/codedna/kappa-laravel-generator.js +741 -0
  22. package/dist/codedna/kappa-lexer.d.ts +44 -0
  23. package/dist/codedna/kappa-lexer.js +124 -0
  24. package/dist/codedna/kappa-mantine-generator.d.ts +65 -0
  25. package/dist/codedna/kappa-mantine-generator.js +518 -0
  26. package/dist/codedna/kappa-mongoose-generator.d.ts +44 -0
  27. package/dist/codedna/kappa-mongoose-generator.js +442 -0
  28. package/dist/codedna/kappa-parser.d.ts +43 -1
  29. package/dist/codedna/kappa-parser.js +601 -0
  30. package/dist/codedna/kappa-radix-generator.d.ts +61 -0
  31. package/dist/codedna/kappa-radix-generator.js +566 -0
  32. package/dist/codedna/kappa-typeorm-generator.d.ts +59 -0
  33. package/dist/codedna/kappa-typeorm-generator.js +723 -0
  34. package/dist/codedna/kappa-vitest-generator.d.ts +85 -0
  35. package/dist/codedna/kappa-vitest-generator.js +739 -0
  36. package/dist/codedna/parser.js +26 -1
  37. package/dist/codegen/cloud-client.d.ts +160 -0
  38. package/dist/codegen/cloud-client.js +195 -0
  39. package/dist/codegen/codegen-tool.d.ts +35 -0
  40. package/dist/codegen/codegen-tool.js +312 -0
  41. package/dist/codegen/field-inference.d.ts +24 -0
  42. package/dist/codegen/field-inference.js +101 -0
  43. package/dist/codegen/form-parser.d.ts +13 -0
  44. package/dist/codegen/form-parser.js +186 -0
  45. package/dist/codegen/index.d.ts +2 -0
  46. package/dist/codegen/index.js +4 -0
  47. package/dist/codegen/natural-parser.d.ts +50 -0
  48. package/dist/codegen/natural-parser.js +769 -0
  49. package/dist/handlers/codedna-handlers.d.ts +1 -1
  50. package/dist/handlers/codegen-handlers.d.ts +20 -0
  51. package/dist/handlers/codegen-handlers.js +60 -0
  52. package/dist/handlers/kappa-handlers.d.ts +97 -0
  53. package/dist/handlers/kappa-handlers.js +408 -0
  54. package/dist/handlers/tool-handlers.js +124 -221
  55. package/dist/helpers/api-client.js +48 -3
  56. package/dist/helpers/compact-formatter.d.ts +9 -2
  57. package/dist/helpers/compact-formatter.js +26 -2
  58. package/dist/helpers/config.d.ts +7 -2
  59. package/dist/helpers/config.js +25 -10
  60. package/dist/helpers/session-validation.d.ts +1 -1
  61. package/dist/helpers/session-validation.js +2 -4
  62. package/dist/helpers/tasks.d.ts +21 -0
  63. package/dist/helpers/tasks.js +52 -0
  64. package/dist/helpers/workers.d.ts +1 -1
  65. package/dist/helpers/workers.js +19 -19
  66. package/dist/setup.d.ts +1 -0
  67. package/dist/setup.js +228 -3
  68. package/dist/templates/claude-md.d.ts +1 -1
  69. package/dist/templates/claude-md.js +37 -152
  70. package/dist/templates/orchestrator-prompt.d.ts +2 -2
  71. package/dist/templates/orchestrator-prompt.js +31 -38
  72. package/dist/templates/self-critique.d.ts +50 -0
  73. package/dist/templates/self-critique.js +209 -0
  74. package/dist/templates/worker-prompt.d.ts +3 -3
  75. package/dist/templates/worker-prompt.js +18 -18
  76. package/dist/tools.js +77 -413
  77. package/docs/codedna/generator-testing-summary.md +205 -0
  78. package/docs/codedna/radix-ui-generator.md +478 -0
  79. package/docs/kappa-gofiber-generator.md +274 -0
  80. package/docs/kappa-laravel-fixes.md +172 -0
  81. package/docs/kappa-mongoose-generator.md +322 -0
  82. package/docs/kappa-vitest-generator.md +337 -0
  83. package/package.json +1 -1
  84. package/dist/context/deduplication.test.d.ts +0 -6
  85. package/dist/context/deduplication.test.js +0 -84
@@ -142,6 +142,27 @@ export declare const LOCK_DURATION_BY_EFFORT: {
142
142
  readonly xl: 240;
143
143
  };
144
144
  export declare const DEFAULT_CAPACITY_BUDGET = 20;
145
+ /**
146
+ * Workflow violation types for enforcement
147
+ */
148
+ export interface WorkflowViolation {
149
+ type: 'no_active_task' | 'no_task_plan' | 'task_not_started';
150
+ message: string;
151
+ severity: 'warning' | 'error';
152
+ }
153
+ /**
154
+ * Get the active task for a specific agent (if any)
155
+ * Returns the task that is currently claimed by this agent
156
+ */
157
+ export declare function getActiveTaskForAgent(userId: string, projectId: string, agentId: string): Promise<Task | null>;
158
+ /**
159
+ * Check workflow compliance and return any violations
160
+ * Call this before completing significant work to ensure proper workflow was followed
161
+ */
162
+ export declare function checkWorkflowCompliance(userId: string, projectId: string, agentId: string, context?: {
163
+ isCompletingTask?: boolean;
164
+ taskId?: string;
165
+ }): Promise<WorkflowViolation[]>;
145
166
  /**
146
167
  * Get effort-weighted load of currently active tasks
147
168
  * Returns both in_progress and claimed (locked) task counts, plus effort-weighted load
@@ -112,6 +112,58 @@ export const LOCK_DURATION_BY_EFFORT = {
112
112
  // Configuration: Default capacity budget in effort units
113
113
  // 20 units allows: 20 xs tasks OR 1 xl + 1 m task OR 5 m tasks, etc.
114
114
  export const DEFAULT_CAPACITY_BUDGET = 20;
115
+ /**
116
+ * Get the active task for a specific agent (if any)
117
+ * Returns the task that is currently claimed by this agent
118
+ */
119
+ export async function getActiveTaskForAgent(userId, projectId, agentId) {
120
+ const result = await listTasks(userId, projectId, {
121
+ status: 'in_progress',
122
+ assigned_to: agentId,
123
+ limit: 1,
124
+ });
125
+ if (!result.success || result.data.length === 0) {
126
+ return null;
127
+ }
128
+ // Check if the lock is still valid
129
+ const task = result.data[0];
130
+ if (task.lock_expires_at) {
131
+ const lockExpires = new Date(task.lock_expires_at);
132
+ if (lockExpires > new Date()) {
133
+ return task;
134
+ }
135
+ }
136
+ return null;
137
+ }
138
+ /**
139
+ * Check workflow compliance and return any violations
140
+ * Call this before completing significant work to ensure proper workflow was followed
141
+ */
142
+ export async function checkWorkflowCompliance(userId, projectId, agentId, context = {}) {
143
+ const violations = [];
144
+ // Check 1: Is there an active task for this agent?
145
+ const activeTask = await getActiveTaskForAgent(userId, projectId, agentId);
146
+ if (!activeTask && !context.isCompletingTask) {
147
+ violations.push({
148
+ type: 'no_active_task',
149
+ message: '⚠️ No active task. Use task_start before beginning work.',
150
+ severity: 'warning',
151
+ });
152
+ }
153
+ // Check 2: If completing a task, was it properly started?
154
+ if (context.isCompletingTask && context.taskId) {
155
+ // We'll just note if the task wasn't claimed - the handler already handles this
156
+ // by auto-claiming, but we can still warn about the pattern
157
+ if (!activeTask || activeTask.id !== context.taskId) {
158
+ violations.push({
159
+ type: 'task_not_started',
160
+ message: '⚠️ Task was not started with task_start. Consider using proper workflow.',
161
+ severity: 'warning',
162
+ });
163
+ }
164
+ }
165
+ return violations;
166
+ }
115
167
  /**
116
168
  * Get effort-weighted load of currently active tasks
117
169
  * Returns both in_progress and claimed (locked) task counts, plus effort-weighted load
@@ -14,7 +14,7 @@ export declare const EXPERT_WORKERS: Record<string, ExpertWorker>;
14
14
  *
15
15
  * This function uses the new template system that includes:
16
16
  * - XML semantic boundaries for machine-parseable structure
17
- * - CodeDNA integration instructions (95-99% token savings for CRUD)
17
+ * - Codegen integration instructions (95-99% token savings for CRUD)
18
18
  * - Tool usage priorities (memory_search, codebase_find before writing)
19
19
  * - Tier-based complexity (minimal/standard/professional)
20
20
  *
@@ -2,10 +2,10 @@
2
2
  // Expert Worker Definitions (Orchestration System)
3
3
  // =============================================================================
4
4
  //
5
- // Updated with 10/10 AI System Prompt Architecture and CodeDNA integration.
6
- // Workers now know to use CodeDNA generators before writing boilerplate code.
5
+ // Updated with 10/10 AI System Prompt Architecture.
6
+ // Workers know to use codegen before writing boilerplate code.
7
7
  //
8
- import { buildWorkerPromptWithCodeDNA, } from '../templates/worker-prompt.js';
8
+ import { buildWorkerPrompt as templateBuildWorkerPrompt, } from '../templates/worker-prompt.js';
9
9
  export const EXPERT_WORKERS = {
10
10
  'schema-expert': {
11
11
  id: 'schema-expert',
@@ -19,7 +19,7 @@ export const EXPERT_WORKERS = {
19
19
  - Index optimisation
20
20
  - Data modelling decisions
21
21
 
22
- CODEDNA: If task includes Entity DSL (e.g., "User(email:string:unique)"),
22
+ CODEGEN: If task includes Entity DSL (e.g., "User(email:string:unique)"),
23
23
  the API layer will be generated automatically. Focus only on SQL schema.
24
24
 
25
25
  Focus only on schema-related changes. Do not modify application code.
@@ -38,15 +38,15 @@ When complete, provide a concise summary of changes made.`,
38
38
  - Error handling for endpoints
39
39
 
40
40
  PATTERN DETECTION (for existing projects):
41
- 1. Call codedna_detect_patterns(package_json) to find existing patterns
41
+ 1. Check package.json for existing patterns
42
42
  2. MATCH detected patterns - don't introduce conflicting libraries
43
43
  3. Check for: zod vs yup validation, tanstack-query vs swr, etc.
44
44
 
45
- CODEDNA PRIORITY: Before writing CRUD code manually:
46
- 1. Call codedna_list_generators() to discover available generators
45
+ CODEGEN PRIORITY: Before writing CRUD code manually:
46
+ 1. Call codegen_list() to discover available generators
47
47
  2. Look for Entity DSL in task (e.g., "User(email:string:unique, password:string:hashed)")
48
48
  3. Detect framework from project (check package.json, existing patterns)
49
- 4. Call codedna_generate_api(spec, framework="<detected>", options={...})
49
+ 4. Call codegen({ describe: "...", generate: [...], stack: {...} })
50
50
  5. Only write manually for complex business logic that can't be generated
51
51
 
52
52
  Focus only on API-related changes. Do not modify schema or extraction code.
@@ -119,20 +119,20 @@ When complete, provide a concise summary of integrations configured.`,
119
119
  - Client-side state management
120
120
 
121
121
  PATTERN DETECTION (CRITICAL for existing projects):
122
- 1. Call codedna_detect_patterns(package_json) to detect existing patterns
122
+ 1. Check package.json to detect existing patterns
123
123
  2. RESPECT detected patterns - consistency > "better":
124
124
  - Compound components? Use compound pattern
125
125
  - React Hook Form? Don't introduce Formik
126
126
  - Zustand? Don't add Redux
127
127
  - Tailwind? Match styling approach
128
- 3. Check codedna_list_patterns(category="anti-patterns") for code smells to avoid
128
+ 3. Check for common anti-patterns
129
129
 
130
- CODEDNA PRIORITY: Before writing UI components manually:
131
- 1. Call codedna_list_generators() to discover available generators
130
+ CODEGEN PRIORITY: Before writing UI components manually:
131
+ 1. Call codegen_list() to discover available generators
132
132
  2. Detect UI framework from project (check package.json for react, vue, etc.)
133
133
  3. Check for UI library (package.json: @shadcn/ui, @mui/material, @chakra-ui, etc.)
134
- 4. Call codedna_generate_frontend or codedna_generate_component with detected settings
135
- 5. DO NOT assume any specific framework/library - discover via list_generators, detect from project
134
+ 4. Call codegen({ describe: "...", generate: ["components"], stack: {...} })
135
+ 5. DO NOT assume any specific framework/library - discover via codegen_list, detect from project
136
136
 
137
137
  TOOLS: Use codebase_find to discover existing component patterns.
138
138
  TOOLS: Use memory_search for past UI decisions.
@@ -148,8 +148,8 @@ When complete, provide a concise summary of components created.`,
148
148
  capabilities: ['general-development', 'refactoring', 'documentation', 'testing'],
149
149
  promptTemplate: `You are a general purpose development expert.
150
150
 
151
- CODEDNA - DISCOVER THEN DETECT:
152
- 1. Call codedna_list_generators() to see what's available
151
+ CODEGEN - DISCOVER THEN DETECT:
152
+ 1. Call codegen_list() to see what's available
153
153
  2. Detect project framework from package.json/pyproject.toml
154
154
  3. Match detected framework to generator capabilities
155
155
  4. If no match, ASK the user which framework to use
@@ -170,7 +170,7 @@ When complete, provide a concise summary of work done.`,
170
170
  *
171
171
  * This function uses the new template system that includes:
172
172
  * - XML semantic boundaries for machine-parseable structure
173
- * - CodeDNA integration instructions (95-99% token savings for CRUD)
173
+ * - Codegen integration instructions (95-99% token savings for CRUD)
174
174
  * - Tool usage priorities (memory_search, codebase_find before writing)
175
175
  * - Tier-based complexity (minimal/standard/professional)
176
176
  *
@@ -189,8 +189,8 @@ export function buildWorkerPrompt(params, tier = 'standard') {
189
189
  content: ctx.content,
190
190
  source: ctx.source,
191
191
  }));
192
- // Use the new 10/10 template system
193
- return buildWorkerPromptWithCodeDNA({
192
+ // Use the 10/10 template system
193
+ return templateBuildWorkerPrompt({
194
194
  task: {
195
195
  id: task.id,
196
196
  title: task.title,
package/dist/setup.d.ts CHANGED
@@ -2,3 +2,4 @@ export declare function runSetup(): Promise<void>;
2
2
  export declare function runUninstall(): Promise<void>;
3
3
  export declare function runInit(): Promise<void>;
4
4
  export declare function runCleanup(): Promise<void>;
5
+ export declare function runOnboard(): Promise<void>;
package/dist/setup.js CHANGED
@@ -21,6 +21,7 @@ const MCP_CONFIG_PATH = join(CLAUDE_DIR, 'mcp.json');
21
21
  const CLAUDE_DESKTOP_CONFIG_PATH = join(CLAUDE_DIR, 'claude_desktop_config.json');
22
22
  const SETTINGS_PATH = join(CLAUDE_DIR, 'settings.json');
23
23
  const HOOKS_DIR = join(CLAUDE_DIR, 'hooks');
24
+ const COMMANDS_DIR = join(CLAUDE_DIR, 'commands');
24
25
  const CLAUDE_MD_PATH = join(CLAUDE_DIR, 'CLAUDE.md');
25
26
  const SYSTEM_FILE = join(CLAUDETOOLS_DIR, 'system.json');
26
27
  const PROJECTS_FILE = join(CLAUDETOOLS_DIR, 'projects.json');
@@ -920,6 +921,197 @@ exit 0
920
921
  writeFileSync(preCompactPath, preCompactHook, { mode: 0o755 });
921
922
  success('Installed pre-compact.sh hook');
922
923
  }
924
+ // -----------------------------------------------------------------------------
925
+ // Slash Commands Installation
926
+ // -----------------------------------------------------------------------------
927
+ const PROJECT_INIT_COMMAND = `---
928
+ description: Initialize a new project with AI-driven onboarding
929
+ model: claude-sonnet-4-5
930
+ ---
931
+
932
+ # Project Onboarding
933
+
934
+ Starting interactive onboarding for this project...
935
+
936
+ ## Instructions for Claude
937
+
938
+ You are beginning an onboarding session for a new or existing project. Your goal is to:
939
+ 1. Gather project context through conversational questioning
940
+ 2. **Store ALL learned facts in the memory system immediately** (don't batch - store as you learn)
941
+ 3. **Cache documentation for libraries/frameworks mentioned** (using \`docs_cache\`)
942
+ 4. **Verify ClaudeTools integration is working correctly**
943
+
944
+ ### Phase 1: ClaudeTools Verification
945
+
946
+ Before starting onboarding, verify the tooling is correctly set up:
947
+
948
+ \`\`\`bash
949
+ # Check session facts cache exists
950
+ ls -la ~/.claudetools/session-facts.json
951
+
952
+ # Check hooks are in place
953
+ ls -la ~/.claude/hooks/
954
+
955
+ # Verify MCP connection
956
+ # (If memory_search works, MCP is connected)
957
+ \`\`\`
958
+
959
+ If any issues found, help the user fix their ClaudeTools setup before proceeding.
960
+
961
+ ### Phase 2: Onboarding Workflow
962
+
963
+ **1. Check if project exists**
964
+ - Use \`memory_search\` to check for existing project context
965
+ - If exists, offer to update/extend vs start fresh
966
+
967
+ **2. Start onboarding conversation**
968
+ Ask about (store facts AS you learn them, not at the end):
969
+
970
+ - **Project Type**: What kind of project? (web app, API, library, CLI, etc.)
971
+ → Store: \`[ProjectName] IS_TYPE [ProjectType]\`
972
+
973
+ - **Tech Stack**: What technologies/frameworks?
974
+ → Store: \`[ProjectName] USES [Technology]\` for EACH technology
975
+ → **IMPORTANT**: Call \`docs_cache({ library: "technology-name" })\` for each library mentioned
976
+
977
+ - **Architecture**: Key patterns, structure, decisions?
978
+ → Store: \`[ProjectName] USES_PATTERN [Pattern]\`
979
+ → Store: \`[Component] IMPLEMENTS [Pattern]\`
980
+
981
+ - **Constraints**: Performance requirements, limitations, must-haves?
982
+ → Store: \`[ProjectName] HAS_CONSTRAINT [Constraint]\`
983
+
984
+ - **External Integrations**: APIs, services, databases?
985
+ → Store: \`[ProjectName] INTEGRATES_WITH [Service]\`
986
+ → Call \`docs_cache\` if documentation available
987
+
988
+ - **Development Practices**: Testing, CI/CD, code style?
989
+ → Store: \`[ProjectName] FOLLOWS [Practice]\`
990
+
991
+ **3. Research when needed**
992
+ If user mentions:
993
+ - Existing specs/docs → Read and extract facts
994
+ - External libraries → Cache docs with \`docs_cache({ library: "name" })\`
995
+ - Existing code → Analyse patterns and store architectural decisions
996
+
997
+ **4. Complete onboarding**
998
+ - Summarise what was learned
999
+ - Confirm with user before finalising
1000
+ - List all cached documentation
1001
+
1002
+ ### Memory Storage (CRITICAL)
1003
+
1004
+ **Store facts IMMEDIATELY as you learn them, not at the end.**
1005
+
1006
+ \`\`\`typescript
1007
+ // After learning tech stack
1008
+ memory_store_fact({
1009
+ entity1: "MyProject",
1010
+ relationship: "USES",
1011
+ entity2: "React",
1012
+ context: "Frontend framework chosen for component-based architecture"
1013
+ })
1014
+
1015
+ // Immediately cache React docs
1016
+ docs_cache({ library: "react" })
1017
+ \`\`\`
1018
+
1019
+ **Fact relationship types:**
1020
+ - \`IS_TYPE\` - Project classification
1021
+ - \`USES\` - Technologies, libraries, frameworks
1022
+ - \`USES_PATTERN\` - Architectural patterns
1023
+ - \`HAS_CONSTRAINT\` - Requirements, limitations
1024
+ - \`INTEGRATES_WITH\` - External services
1025
+ - \`FOLLOWS\` - Development practices
1026
+ - \`DEPENDS_ON\` - Critical dependencies
1027
+ - \`OWNED_BY\` - Team/ownership info
1028
+
1029
+ ### Documentation Caching
1030
+
1031
+ For ANY library/framework mentioned, cache its docs:
1032
+
1033
+ \`\`\`typescript
1034
+ // Cache documentation for mentioned technologies
1035
+ docs_cache({ library: "next.js" })
1036
+ docs_cache({ library: "prisma" })
1037
+ docs_cache({ library: "zod" })
1038
+ docs_cache({ library: "tanstack-query" })
1039
+ \`\`\`
1040
+
1041
+ This enables future sessions to reference up-to-date documentation.
1042
+
1043
+ ### Code Generation
1044
+
1045
+ **IMPORTANT**: When the project involves APIs or data models, use the \`codegen\` tool to save 95%+ tokens:
1046
+
1047
+ \`\`\`typescript
1048
+ codegen({ describe: "User with email, password, role (admin/user)" })
1049
+ \`\`\`
1050
+
1051
+ **What it generates:**
1052
+ - Drizzle schema (database tables)
1053
+ - TypeScript types
1054
+ - Zod validators
1055
+ - API routes (Hono/Express)
1056
+
1057
+ **Smart field inference:**
1058
+ - \`email\` → email type, \`password\` → hashed, \`createdAt\` → timestamp
1059
+ - \`price\` → decimal, \`isActive\` → boolean, \`(admin/user)\` → enum
1060
+
1061
+ Stack is auto-detected from package.json (Drizzle, Hono, Express, etc.)
1062
+
1063
+ Store code generation preferences:
1064
+ \`\`\`typescript
1065
+ memory_store_fact({
1066
+ entity1: "ProjectName",
1067
+ relationship: "USES",
1068
+ entity2: "codegen",
1069
+ context: "Project uses codegen for schema/types/validators generation"
1070
+ })
1071
+ \`\`\`
1072
+
1073
+ ### Conversation Style
1074
+
1075
+ - Be conversational, not interrogative
1076
+ - Explain WHY you're asking each question
1077
+ - Store facts immediately after each answer (don't wait)
1078
+ - Confirm what you've stored: "I've noted that you're using React for..."
1079
+ - Offer to skip questions if not relevant
1080
+ - Summarise understanding periodically
1081
+
1082
+ ### Troubleshooting ClaudeTools
1083
+
1084
+ If MCP tools aren't available:
1085
+ 1. Check \`~/.claudetools/config.json\` exists
1086
+ 2. Verify Claude Code has MCP server configured
1087
+ 3. Run \`/doctor\` command if available
1088
+
1089
+ If hooks aren't triggering:
1090
+ 1. Check \`~/.claude/hooks/\` directory
1091
+ 2. Verify hook files are executable
1092
+ 3. Check hook logs in \`/tmp/claude-*.log\`
1093
+
1094
+ ### User Request (if provided):
1095
+
1096
+ $ARGUMENTS
1097
+ `;
1098
+ async function installSlashCommands() {
1099
+ header('Slash Commands');
1100
+ // Create commands/project directory
1101
+ const projectCommandsDir = join(COMMANDS_DIR, 'project');
1102
+ if (!existsSync(projectCommandsDir)) {
1103
+ mkdirSync(projectCommandsDir, { recursive: true });
1104
+ }
1105
+ // Install project:init command
1106
+ const initPath = join(projectCommandsDir, 'init.md');
1107
+ if (existsSync(initPath)) {
1108
+ const backup = backupFile(initPath);
1109
+ if (backup)
1110
+ info(`Backed up existing command to ${basename(backup)}`);
1111
+ }
1112
+ writeFileSync(initPath, PROJECT_INIT_COMMAND);
1113
+ success('Installed /project:init slash command');
1114
+ }
923
1115
  async function configureSettings() {
924
1116
  header('Claude Code Settings');
925
1117
  // Read existing settings
@@ -1244,11 +1436,13 @@ export async function runSetup() {
1244
1436
  await configureMcpSettings(services);
1245
1437
  // Step 8: Install Hooks
1246
1438
  await installHooks();
1247
- // Step 9: Configure Settings
1439
+ // Step 9: Install Slash Commands
1440
+ await installSlashCommands();
1441
+ // Step 10: Configure Settings
1248
1442
  await configureSettings();
1249
- // Step 10: Configure CLAUDE.md
1443
+ // Step 11: Configure CLAUDE.md
1250
1444
  await configureCLAUDEMD();
1251
- // Step 11: Verify
1445
+ // Step 12: Verify
1252
1446
  await verifySetup(extendedConfig);
1253
1447
  // Done
1254
1448
  header('Setup Complete');
@@ -1841,3 +2035,34 @@ export async function runCleanup() {
1841
2035
  console.log('\n' + chalk.green(' Cleanup complete!'));
1842
2036
  console.log(chalk.dim(' Restart Claude Code for changes to take effect.\n'));
1843
2037
  }
2038
+ // -----------------------------------------------------------------------------
2039
+ // Onboard Command (standalone)
2040
+ // -----------------------------------------------------------------------------
2041
+ export async function runOnboard() {
2042
+ const cwd = process.cwd();
2043
+ const projectName = basename(cwd);
2044
+ // Load config
2045
+ const config = await loadConfigFromFile();
2046
+ if (!config?.apiKey) {
2047
+ error('Not configured. Run: claudetools --setup');
2048
+ process.exit(1);
2049
+ }
2050
+ const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;
2051
+ const apiKey = config.apiKey;
2052
+ // Find project for current directory
2053
+ if (!existsSync(PROJECTS_FILE)) {
2054
+ error('No projects registered. Run: claudetools init');
2055
+ process.exit(1);
2056
+ }
2057
+ const projectsData = JSON.parse(readFileSync(PROJECTS_FILE, 'utf-8'));
2058
+ const binding = projectsData.bindings?.find((b) => b.local_path === cwd);
2059
+ if (!binding) {
2060
+ error('Current directory is not a registered project.');
2061
+ info('Run: claudetools init');
2062
+ process.exit(1);
2063
+ }
2064
+ const projectId = binding.project_id;
2065
+ const displayName = binding.project_name || projectName;
2066
+ // Run the onboarding flow
2067
+ await runOnboarding(apiUrl, apiKey, projectId, displayName);
2068
+ }
@@ -5,7 +5,7 @@ export declare const PROJECT_SECTION_END = "<!-- CLAUDETOOLS:PROJECT:END -->";
5
5
  /**
6
6
  * Global CLAUDE.md content - added to ~/.claude/CLAUDE.md
7
7
  */
8
- export declare const GLOBAL_TEMPLATE = "\n<!-- CLAUDETOOLS:START -->\n# ClaudeTools Memory System\n\nYou have access to a persistent memory system. **Context is AUTO-INJECTED via hooks** - you rarely need to call memory tools explicitly.\n\n## \u26A0\uFE0F IMPORTANT: Hooks vs MCP Tools\n\n**AUTOMATIC (via hooks - zero context cost):**\n- Context injection \u2192 `user-prompt-submit` hook runs on every message\n- Fact extraction \u2192 `post-tool-use` hook extracts from your work\n- Session context \u2192 `session-start` hook provides initial context\n\n**EXPLICIT (MCP tools - costs context):**\n- `memory_store_fact` \u2192 Store a specific fact you learned\n- `task_plan` / `task_start` / `task_complete` \u2192 Task management\n\n**DO NOT CALL these tools routinely (context already injected):**\n- `memory_search` - only if you need DIFFERENT search params\n- `memory_inject` - only if you need to refresh for a different query\n- `memory_get_context` - only for debugging\n- `memory_index` - only for debugging\n\n## Storing Facts (DO use this)\n```\nmemory_store_fact(\n entity1: \"UserService\",\n relationship: \"USES\",\n entity2: \"bcrypt\",\n context: \"Password hashing uses bcrypt with 12 rounds\"\n)\n```\nStore important facts when you learn something concrete. The `post-tool-use` hook also extracts facts automatically.\n\n## Task Management\n\n### Creating Work Plans with Auto-Dispatch\n```\ntask_plan(\n goal: \"Add user authentication\",\n epic_title: \"User Auth System\",\n tasks: [...]\n)\n```\nBreak down complex work into tracked tasks. **Tasks are automatically set to `ready` status.**\n\nAfter `task_plan` completes, you will receive Task tool invocations to spawn parallel agents.\n**Execute ALL Task tool calls in a SINGLE message** to enable parallel execution.\n\n### Parallel Agent Workflow\n1. User describes work needed\n2. Call `task_plan_draft` to present the plan\n3. User says \"go\" to approve\n4. Call `task_plan` - tasks created in `ready` status\n5. Execute the provided Task tool calls in ONE message\n6. Agents work in parallel, each calling `task_complete` when done\n\n### Manual Task Start (Sequential)\n```\ntask_start(task_id: \"task_xxx\")\n```\nClaim a task before working on it. Use for sequential execution.\n\n### Completing Tasks\n```\ntask_complete(task_id: \"task_xxx\", summary: \"Implemented JWT auth with refresh tokens\")\n```\nMark tasks done with a summary of work completed. **Always call this when a task is finished.**\n\n## Codebase Intelligence\n\n### Start with codebase_map() - ALWAYS\n```\ncodebase_map() # FIRST TOOL when exploring unfamiliar code\n```\n**When to use:** Starting a new task, exploring unfamiliar code, understanding project structure, finding entry points.\n\nThe map shows:\n- Project structure and key directories\n- Entry points and their exports\n- Framework detection (React, Express, etc.)\n- Key symbols and their locations\n\n**Use codebase_map BEFORE using Grep/Glob** - it gives you the lay of the land so you know where to look.\n\n### Then use targeted tools\n```\ncodebase_find(\"UserService\") # Find specific symbols/files\ncodebase_context(\"src/auth.ts\") # Get file dependencies\nanalyze_impact(\"validateToken\") # See what changing a function affects\n```\n\n## CodeDNA: Generate Code, Save 99% Tokens\n\n**BEFORE writing ANY code, check if CodeDNA can generate it.** Call `codedna_list_generators()` to see available generators.\n\n### Available Generators (20+)\n\n| Category | Frameworks | Tool |\n|----------|------------|------|\n| **API** | Express, FastAPI, NestJS, Hono, Elysia, tRPC | `codedna_generate_api` |\n| **Frontend** | React, Vue, SvelteKit, Astro, React Router v7, TanStack Start | `codedna_generate_frontend` |\n| **ORM** | Prisma, Drizzle | `codedna_generate_api` with database option |\n| **Auth** | Better Auth, Auth.js, Lucia | `codedna_generate_api` with auth option |\n| **Components** | Forms, Tables, Cards, Modals (React/Vue/Svelte) | `codedna_generate_component` |\n\n### Usage Examples\n\n```typescript\n// API with auth and validation\ncodedna_generate_api({\n spec: \"User(email:string:unique, password:string:hashed)\",\n framework: \"express\", // or: fastapi, nestjs, hono, elysia, trpc\n options: { auth: true, validation: true, tests: true }\n})\n\n// Frontend with forms and data fetching\ncodedna_generate_frontend({\n spec: \"User(email:string, name:string, role:enum(admin,user))\",\n framework: \"react\", // or: vue, nextjs, sveltekit, astro\n options: { forms: true, tables: true, ui: \"shadcn\" }\n})\n\n// Single component\ncodedna_generate_component({\n spec: \"Product(name:string, price:decimal, inStock:boolean)\",\n type: \"form\", // or: table, card, modal\n framework: \"react\",\n options: { validation: true, ui: \"shadcn\" }\n})\n```\n\n### Entity DSL Quick Reference\n\n```\nEntityName(field:type:modifier, field2:type:modifier)\n\nTypes: string, integer, decimal, boolean, datetime, text, json\nModifiers: unique, required, optional, hashed, email, min(n), max(n), default(v)\nRelations: userId:User (reference), posts:Post[] (array)\nEnums: role:enum(admin,user,guest)\n```\n\n**Token savings:** 30,000 tokens \u2192 200 tokens (99% reduction per generation)\n\n## Kappa v2.5: Declarative Full-Stack Generation\n\n**For even higher-level generation**, use Kappa DSL - a declarative specification language that generates complete applications from compact specs.\n\n### When to Use Kappa vs CodeDNA\n\n| Use Case | Tool |\n|----------|------|\n| Single entity/component | CodeDNA (`codedna_generate_*`) |\n| Full application with multiple entities | Kappa (`kappa_generate_all`) |\n| Pages, forms, routing together | Kappa |\n| Design system + components | Kappa |\n\n### Kappa Tools\n\n| Tool | Purpose |\n|------|---------|\n| `kappa_parse` | Parse and validate Kappa spec |\n| `kappa_generate_schema` | Generate Drizzle schema + Zod + types |\n| `kappa_generate_api` | Generate API routes (Hono/Express/tRPC) |\n| `kappa_generate_pages` | Generate pages (TanStack Start/Next.js) |\n| `kappa_generate_forms` | Generate forms (React Hook Form + Zod + shadcn) |\n| `kappa_generate_components` | Generate React components (compound, forwardRef) |\n| `kappa_generate_design` | Generate CSS variables + Tailwind config |\n| `kappa_generate_all` | Generate complete full-stack application |\n\n### Kappa DSL Example\n\n```\n// Complete app specification in ~50 lines\nproject TaskManager {\n database postgres\n framework tanstack-start\n}\n\nentity Task {\n title string required max(100)\n description text\n status enum(todo, in_progress, done) default(todo)\n dueDate datetime\n assignee User\n}\n\nentity User {\n email string unique email\n name string required\n tasks Task[]\n}\n\napi /tasks {\n GET / -> list Task[]\n POST / -> create Task\n GET /:id -> get Task\n PUT /:id -> update Task\n DELETE /:id -> delete Task\n}\n\npage /tasks {\n layout dashboard\n load tasks from /api/tasks\n components [TaskList, TaskForm]\n}\n\nform TaskForm for Task {\n fields [title, description, status, dueDate]\n submit POST /api/tasks\n}\n\ndesign {\n colors {\n primary #3B82F6\n secondary #6B7280\n }\n typography {\n fontFamily \"Inter\"\n scale { sm: \"0.875rem\", base: \"1rem\", lg: \"1.125rem\" }\n }\n}\n```\n\n### Usage\n\n```typescript\n// Generate everything from spec\nkappa_generate_all({\n spec: `project MyApp { ... }`,\n options: {\n framework: \"tanstack-start\",\n ui: \"shadcn\",\n dbDialect: \"postgres\"\n }\n})\n\n// Or generate incrementally\nkappa_parse({ spec: \"...\" }) // Validate first\nkappa_generate_schema({ spec: \"...\", outputs: [\"drizzle\", \"zod\", \"types\"] })\nkappa_generate_api({ spec: \"...\", framework: \"hono\" })\nkappa_generate_pages({ spec: \"...\", framework: \"tanstack-start\" })\n```\n\n**Token savings:** ~50 lines of Kappa \u2192 thousands of lines of production code (95%+ reduction)\n\n## Best Practices\n\n1. **Trust auto-injection** - Context is injected automatically, don't call memory_search\n2. **Store decisions** - Use `memory_store_fact` for architectural choices\n3. **Use task tracking** - Break complex work into tasks\n4. **Use Kappa for full apps** - For multi-entity apps with pages/forms, use `kappa_generate_all`\n5. **Use CodeDNA for single components** - For individual entities or components, use `codedna_generate_*`\n6. **Minimize tool calls** - Every MCP call costs context tokens\n<!-- CLAUDETOOLS:END -->\n";
8
+ export declare const GLOBAL_TEMPLATE = "\n<!-- CLAUDETOOLS:START -->\n# ClaudeTools Memory System\n\nYou have access to a persistent memory system. **Context is AUTO-INJECTED via hooks** - you rarely need to call memory tools explicitly.\n\n## \u26A0\uFE0F IMPORTANT: Hooks vs MCP Tools\n\n**AUTOMATIC (via hooks - zero context cost):**\n- Context injection \u2192 `user-prompt-submit` hook runs on every message\n- Fact extraction \u2192 `post-tool-use` hook extracts from your work\n- Session context \u2192 `session-start` hook provides initial context\n\n**EXPLICIT (MCP tools - costs context):**\n- `memory_store_fact` \u2192 Store a specific fact you learned\n- `task_plan` / `task_start` / `task_complete` \u2192 Task management\n\n**DO NOT CALL these tools routinely (context already injected):**\n- `memory_search` - only if you need DIFFERENT search params\n- `memory_inject` - only if you need to refresh for a different query\n- `memory_get_context` - only for debugging\n- `memory_index` - only for debugging\n\n## Storing Facts (DO use this)\n```\nmemory_store_fact(\n entity1: \"UserService\",\n relationship: \"USES\",\n entity2: \"bcrypt\",\n context: \"Password hashing uses bcrypt with 12 rounds\"\n)\n```\nStore important facts when you learn something concrete. The `post-tool-use` hook also extracts facts automatically.\n\n## Task Management\n\n### Creating Work Plans with Auto-Dispatch\n```\ntask_plan(\n goal: \"Add user authentication\",\n epic_title: \"User Auth System\",\n tasks: [...]\n)\n```\nBreak down complex work into tracked tasks. **Tasks are automatically set to `ready` status.**\n\nAfter `task_plan` completes, you will receive Task tool invocations to spawn parallel agents.\n**Execute ALL Task tool calls in a SINGLE message** to enable parallel execution.\n\n### Parallel Agent Workflow\n1. User describes work needed\n2. Call `task_plan_draft` to present the plan\n3. User says \"go\" to approve\n4. Call `task_plan` - tasks created in `ready` status\n5. Execute the provided Task tool calls in ONE message\n6. Agents work in parallel, each calling `task_complete` when done\n\n### Manual Task Start (Sequential)\n```\ntask_start(task_id: \"task_xxx\")\n```\nClaim a task before working on it. Use for sequential execution.\n\n### Completing Tasks\n```\ntask_complete(task_id: \"task_xxx\", summary: \"Implemented JWT auth with refresh tokens\")\n```\nMark tasks done with a summary of work completed. **Always call this when a task is finished.**\n\n## Codebase Intelligence\n\n### Start with codebase_map() - ALWAYS\n```\ncodebase_map() # FIRST TOOL when exploring unfamiliar code\n```\n**When to use:** Starting a new task, exploring unfamiliar code, understanding project structure, finding entry points.\n\nThe map shows:\n- Project structure and key directories\n- Entry points and their exports\n- Framework detection (React, Express, etc.)\n- Key symbols and their locations\n\n**Use codebase_map BEFORE using Grep/Glob** - it gives you the lay of the land so you know where to look.\n\n### Then use targeted tools\n```\ncodebase_find(\"UserService\") # Find specific symbols/files\ncodebase_context(\"src/auth.ts\") # Get file dependencies\nanalyze_impact(\"validateToken\") # See what changing a function affects\n```\n\n## Code Generation (saves 95-99% tokens)\n\n**ALWAYS use `codegen` instead of writing boilerplate.** One line of natural language \u2192 10+ production files.\n\n### Quick Reference\n\n```typescript\n// Entities \u2192 schema + types + validators + API + tests\ncodegen({ describe: \"User with email, password, role (admin/user)\" })\ncodegen({ describe: \"Post with title, content, belongs to User as author\" })\n\n// Forms \u2192 React Hook Form + Zod + shadcn inputs\ncodegen({ describe: \"Login form with email, password, submit to /auth/login\" })\n\n// Components \u2192 Radix/shadcn with variants\ncodegen({ describe: \"Button with label, onClick, variant (primary/secondary)\" })\n\n// Pages \u2192 TanStack Start or Next.js routes\ncodegen({ describe: \"Dashboard page at /dashboard, requires auth, loads User\" })\n\n// Generate specific outputs\ncodegen({ describe: \"User with email\", generate: ['schema', 'types'] })\ncodegen({ describe: \"User with email\", generate: ['tests'] })\ncodegen({ describe: \"User with email\", generate: ['all'] }) // everything\n```\n\n### What It Generates\n| Type | Output Files |\n|------|-------------|\n| Entity | schema.ts, types.ts, validators.ts, routes.ts |\n| Tests | *.test.ts, *.factory.ts, *.mock.ts |\n| Form | *-form.tsx (RHF + Zod + shadcn) |\n| Component | *.tsx (Radix primitives + Tailwind) |\n| Page | route.tsx (loaders, guards, layouts) |\n\n### Smart Inference\n- Field names \u2192 types: `email` \u2192 email, `password` \u2192 hashed, `price` \u2192 decimal\n- Enums: `role (admin/user)` \u2192 enum type\n- Relationships: `belongs to User as author` \u2192 foreign key + relation\n- Forms: `email` \u2192 email input, `message` \u2192 textarea\n- Pages: `requires auth` \u2192 guard, `loads User` \u2192 data loader\n\n## Best Practices\n\n1. **Trust auto-injection** - Context is injected automatically, don't call memory_search\n2. **Store decisions** - Use `memory_store_fact` for architectural choices\n3. **Use task tracking** - Break complex work into tasks\n4. **Use codegen for boilerplate** - Generate schemas, types, validators, routes\n5. **Minimize tool calls** - Every MCP call costs context tokens\n<!-- CLAUDETOOLS:END -->\n";
9
9
  /**
10
10
  * Project-level CLAUDE.md content - added to .claude/CLAUDE.md
11
11
  */