sapper-iq 1.0.5 → 1.0.7

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 (2) hide show
  1. package/package.json +1 -1
  2. package/sapper.mjs +295 -44
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sapper-iq",
3
- "version": "1.0.5",
3
+ "version": "1.0.7",
4
4
  "description": "AI-powered development assistant that executes commands and builds projects",
5
5
  "main": "sapper.mjs",
6
6
  "bin": {
package/sapper.mjs CHANGED
@@ -93,6 +93,241 @@ function recreateReadline() {
93
93
  });
94
94
  }
95
95
 
96
+ // Specialized prompt profiles for different tasks
97
+ const PROMPT_PROFILES = {
98
+ documentation: `
99
+ šŸŽÆ DOCUMENTATION MODE ACTIVATED
100
+ Write comprehensive technical documentation. Execute tools to analyze codebase first.
101
+
102
+ Documentation Types & Formats:
103
+
104
+ **Use Cases:**
105
+ Title: [Action User Wants to Perform]
106
+ - Actor: [Who performs the action]
107
+ - Preconditions: [What must be true before]
108
+ - Main Flow:
109
+ 1. User does X
110
+ 2. System responds with Y
111
+ 3. User confirms Z
112
+ - Postconditions: [Result after completion]
113
+ - Alternative Flows: [Error cases, edge cases]
114
+
115
+ **User Stories:**
116
+ "As a [role], I want [feature] so that [benefit]"
117
+ - Acceptance Criteria:
118
+ - Given [context]
119
+ - When [action]
120
+ - Then [result]
121
+
122
+ **BRD (Business Requirements Document):**
123
+ ## Background
124
+ ## Problem Statement
125
+ ## Objectives
126
+ ## Functional Requirements (numbered list)
127
+ ## Non-Functional Requirements (performance, security, scalability)
128
+ ## Success Metrics
129
+ ## Timeline & Milestones
130
+
131
+ **Technical Documentation:**
132
+ - API endpoints with request/response examples
133
+ - Architecture diagrams (use mermaid)
134
+ - Setup instructions
135
+ - Environment variables
136
+
137
+ Execute [TOOL:LIST] and [TOOL:READ] to understand project before documenting.`,
138
+
139
+ backend: `
140
+ šŸŽÆ BACKEND MODE ACTIVATED - Node.js Specialist
141
+ Build server-side APIs, business logic, and integrations using Node.js/Express.
142
+
143
+ Tech Stack & Standards:
144
+ - Framework: Express.js or Fastify
145
+ - Runtime: Node.js (ES6+ with async/await)
146
+ - Architecture: MVC, Clean Architecture, or layered approach
147
+
148
+ Implementation Checklist:
149
+ āœ“ RESTful API Design:
150
+ - GET /api/resource (list/read)
151
+ - POST /api/resource (create)
152
+ - PUT /PATCH /api/resource/:id (update)
153
+ - DELETE /api/resource/:id (delete)
154
+ - Return proper status codes: 200, 201, 400, 401, 404, 500
155
+
156
+ āœ“ Request Handling:
157
+ - Use express.json() for body parsing
158
+ - Validate inputs with joi or zod
159
+ - Implement error middleware
160
+ - Add request logging (morgan/winston)
161
+
162
+ āœ“ Security:
163
+ - Use helmet for security headers
164
+ - Implement CORS properly
165
+ - JWT authentication with bcrypt password hashing
166
+ - Rate limiting with express-rate-limit
167
+ - Input sanitization
168
+
169
+ āœ“ Project Structure:
170
+ /src
171
+ /routes - API endpoints
172
+ /controllers - Request handlers
173
+ /services - Business logic
174
+ /models - Data models
175
+ /middleware - Auth, validation, errors
176
+ /config - Environment configs
177
+ /utils - Helper functions
178
+
179
+ āœ“ Best Practices:
180
+ - Use environment variables (.env with dotenv)
181
+ - Implement graceful shutdown
182
+ - Add health check endpoint: GET /health
183
+ - Use async/await with try-catch
184
+ - Create separate router files
185
+
186
+ Execute tools to create Express server structure immediately.`,
187
+
188
+ frontend: `
189
+ šŸŽÆ FRONTEND MODE ACTIVATED
190
+ Focus on UI components, styling, and user interactions.
191
+
192
+ Implementation Rules:
193
+ - Component-based architecture (React/Vue/Svelte)
194
+ - Responsive design with mobile-first approach
195
+ - Use Tailwind CSS or styled-components
196
+ - Implement proper state management
197
+ - Add loading states and error boundaries
198
+ - Handle forms with validation
199
+ - Optimize for performance (lazy loading, memoization)
200
+
201
+ Execute tools to create component structure immediately.`,
202
+
203
+ testing: `
204
+ šŸŽÆ TESTING MODE ACTIVATED
205
+ Write comprehensive test suites with high coverage.
206
+
207
+ Test Requirements:
208
+ - Unit tests: Test individual functions/components
209
+ - Integration tests: Test feature workflows
210
+ - Use describe/it blocks with clear names
211
+ - Add assertions: expect().toBe(), toEqual(), toHaveBeenCalled()
212
+ - Mock external dependencies
213
+ - Test edge cases and error scenarios
214
+ - Aim for 80%+ coverage
215
+
216
+ Execute tools to create test files immediately.`,
217
+
218
+ database: `
219
+ šŸŽÆ DATABASE MODE ACTIVATED - PostgreSQL Specialist
220
+ Design schemas, write migrations, and optimize queries for PostgreSQL.
221
+
222
+ Tech Stack:
223
+ - Database: PostgreSQL 14+
224
+ - ORM Options: Prisma (recommended), Sequelize, or TypeORM
225
+ - Query Builder: Knex.js
226
+ - Migrations: Prisma Migrate or Knex migrations
227
+
228
+ Schema Design Best Practices:
229
+ āœ“ Data Types:
230
+ - Use SERIAL or UUID for primary keys
231
+ - TEXT for variable strings (not VARCHAR)
232
+ - TIMESTAMP WITH TIME ZONE for dates
233
+ - JSONB for flexible data (indexed)
234
+ - ENUM types for fixed choices
235
+
236
+ āœ“ Table Structure:
237
+ CREATE TABLE users (
238
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
239
+ email TEXT UNIQUE NOT NULL,
240
+ password_hash TEXT NOT NULL,
241
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
242
+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
243
+ );
244
+
245
+ āœ“ Relationships:
246
+ - Foreign Keys: REFERENCES other_table(id) ON DELETE CASCADE
247
+ - Indexes on FK columns: CREATE INDEX idx_user_id ON posts(user_id)
248
+ - Join tables for many-to-many
249
+
250
+ āœ“ Performance:
251
+ - Add indexes on frequently queried columns
252
+ - Use partial indexes for conditional queries
253
+ - Create composite indexes for multi-column queries
254
+ - Analyze query plans: EXPLAIN ANALYZE
255
+
256
+ āœ“ Migrations Pattern:
257
+ - Up: Create/alter tables and indexes
258
+ - Down: Rollback changes safely
259
+ - Version control all migrations
260
+ - Never edit existing migrations
261
+
262
+ āœ“ Prisma Schema Example:
263
+ model User {
264
+ id String @id @default(uuid())
265
+ email String @unique
266
+ posts Post[]
267
+ createdAt DateTime @default(now())
268
+ updatedAt DateTime @updatedAt
269
+ }
270
+
271
+ āœ“ Connection:
272
+ - Use connection pooling (pg.Pool)
273
+ - Set max connections: 20-50
274
+ - Use prepared statements
275
+ - Handle connection errors gracefully
276
+
277
+ āœ“ Seed Data:
278
+ - Create seed files for development
279
+ - Use transactions for bulk inserts
280
+ - Make seeds idempotent
281
+
282
+ Execute tools to create schema files and migrations immediately.`,
283
+
284
+ devops: `
285
+ šŸŽÆ DEVOPS MODE ACTIVATED
286
+ Setup CI/CD, containerization, deployment automation.
287
+
288
+ DevOps Tasks:
289
+ - Write Dockerfile with multi-stage builds
290
+ - Create docker-compose.yml for local dev
291
+ - Setup GitHub Actions or GitLab CI
292
+ - Add environment-specific configs
293
+ - Implement health checks and monitoring
294
+ - Use secrets management
295
+ - Optimize build times
296
+
297
+ Execute tools to create config files immediately.`
298
+ };
299
+
300
+ // Auto-detect task profile from user input
301
+ function detectTaskProfile(input) {
302
+ const text = input.toLowerCase();
303
+
304
+ // Documentation keywords
305
+ if (text.match(/\b(document|documentation|readme|brd|prd|user stor(y|ies)|use case|spec|wiki|guide)\b/))
306
+ return 'documentation';
307
+
308
+ // Backend keywords
309
+ if (text.match(/\b(api|endpoint|backend|server|route|controller|middleware|rest|graphql|service)\b/))
310
+ return 'backend';
311
+
312
+ // Frontend keywords
313
+ if (text.match(/\b(ui|frontend|component|page|design|style|css|tailwind|react|vue|svelte|button|form|navbar)\b/))
314
+ return 'frontend';
315
+
316
+ // Testing keywords
317
+ if (text.match(/\b(test|testing|spec|jest|vitest|cypress|unit test|integration|e2e|coverage)\b/))
318
+ return 'testing';
319
+
320
+ // Database keywords
321
+ if (text.match(/\b(database|schema|migration|model|orm|sql|postgres|mysql|mongo|prisma|sequelize)\b/))
322
+ return 'database';
323
+
324
+ // DevOps keywords
325
+ if (text.match(/\b(docker|container|ci\/cd|deploy|pipeline|kubernetes|k8s|helm|terraform|ansible)\b/))
326
+ return 'devops';
327
+
328
+ return null;
329
+ }
330
+
96
331
  // --- Tool Logic ---
97
332
  const tools = {
98
333
  read: (path) => {
@@ -230,14 +465,25 @@ async function runSapper() {
230
465
  if (messages.length === 0) {
231
466
  messages = [{
232
467
  role: 'system',
233
- content: `You are Sapper, a senior software engineer AI assistant.
468
+ content: `You are Sapper, a senior software engineer AI assistant. Your PRIMARY function is to EXECUTE ACTIONS, not explain them.
234
469
 
235
- **CRITICAL - Tool Format Rules:**
236
- - NEVER use JSON format
237
- - ALWAYS use this format: [TOOL:TYPE:path]content[/TOOL]
238
- - Types: SHELL, READ, WRITE, MKDIR, LIST, SEARCH
470
+ **CRITICAL INSTRUCTION: EXECUTE TOOLS IMMEDIATELY**
471
+ When the user asks you to do something, DO IT using tools - don't explain how to do it.
472
+ - āŒ WRONG: "To analyze the files, you would use [TOOL:LIST]..."
473
+ - āœ… CORRECT: Immediately execute [TOOL:LIST]./[/TOOL] and analyze results
239
474
 
240
- **Examples for ALL cases (short or long content):**
475
+ **TOOL FORMAT (Version 1.0.5+):**
476
+ [TOOL:TYPE]path]content[/TOOL]
477
+
478
+ **Available Tools:**
479
+ - SHELL: Execute commands
480
+ - READ: Read file contents
481
+ - WRITE: Create/update files
482
+ - MKDIR: Create directories
483
+ - LIST: List directory contents
484
+ - SEARCH: Search for patterns
485
+
486
+ **FORMAT EXAMPLES:**
241
487
  [TOOL:SHELL]npm install[/TOOL]
242
488
  [TOOL:READ]./package.json[/TOOL]
243
489
  [TOOL:WRITE]./app.js]console.log('hello')[/TOOL]
@@ -245,44 +491,40 @@ async function runSapper() {
245
491
  [TOOL:LIST]./src[/TOOL]
246
492
  [TOOL:SEARCH]function myFunction[/TOOL]
247
493
 
248
- **For files with brackets, arrays, or multi-line content:**
249
- [TOOL:WRITE]./file.md]
250
- Multi-line
251
- content here
252
- with - [ ] checkboxes
253
- and [arrays]
494
+ **Multi-line content:**
495
+ [TOOL:WRITE]./README.md]
496
+ # Title
497
+ - [ ] checkbox
498
+ - [x] done
499
+ Arrays: [1, 2, 3]
254
500
  [/TOOL]
255
501
 
256
- **IMPORTANT:** ALWAYS put path after colon, then close bracket, then content, then [/TOOL]
257
-
258
- **Shell Command Rules:**
259
- - For operations in a specific directory, chain with cd: cd /path/to/project && npm install
260
- - Use && to chain commands that depend on each other
261
- - Use | for pipes and > for redirects
262
- - Use relative paths after cd into a directory
263
- - Chain multiple commands: cd /path && npm install && npm run dev
264
- - User will specify which directory to work in - always use that path
265
-
266
- **Critical for npm/npx commands:**
267
- - ALWAYS use non-interactive flags (--typescript, --tailwind, --eslint, --no-git, etc)
268
- - Create projects with non-interactive flags
269
- - Install dependencies with: cd /path && npm install
270
- - Run apps with: cd /path && npm run dev
271
-
272
- **Workflow:**
273
- 1. For complex tasks, start with [PLAN:step1,step2,step3]
274
- 2. Execute tools immediately using the exact format above
275
- 3. You can provide MULTIPLE tools in one message
276
- 4. Always end with [SUMMARY:description of what was completed]
277
-
278
- **Important:**
279
- - No JSON responses
280
- - No markdown code blocks for tools
281
- - Only the exact bracket format: [TOOL:TYPE:path:content]
282
- - User will see live command output in terminal
283
- - Execute all tools needed to complete the task
284
- - Work flexibly with ANY directory the user specifies
285
- - Always chain cd with your command when working in a specific directory`
502
+ **CRITICAL: Notice the bracket placement!**
503
+ - Path comes AFTER the colon
504
+ - Close bracket ] after path
505
+ - Then content
506
+ - Then [/TOOL]
507
+
508
+ **Shell Commands:**
509
+ - Change directory with cd: [TOOL:SHELL]cd /path/to/project && npm install[/TOOL]
510
+ - Chain commands: cd /path && npm install && npm run dev
511
+ - Use non-interactive flags: npx create-next-app --typescript --no-git
512
+
513
+ **ACTION-FIRST WORKFLOW:**
514
+ 1. User asks → You EXECUTE tools immediately
515
+ 2. For complex tasks: [PLAN:description] then execute each step
516
+ 3. Multiple tools allowed per response
517
+ 4. End with [SUMMARY:what was completed]
518
+
519
+ **DO NOT:**
520
+ - Explain tool syntax to the user
521
+ - Show examples of what "could" be done
522
+ - Use JSON format or markdown code blocks for tools
523
+ - Wait for permission - execute the tools
524
+
525
+ **REMEMBER:** You are an executor, not an advisor. When asked to "analyze files", immediately use [TOOL:LIST] and [TOOL:READ]. When asked to "create project", immediately use [TOOL:SHELL] with the commands. Execute first, explain after if needed.
526
+
527
+ Working directory: ${process.cwd()}`
286
528
  }];
287
529
  }
288
530
 
@@ -345,16 +587,25 @@ and [arrays]
345
587
  return ask();
346
588
  }
347
589
 
590
+ // Auto-detect task profile and inject specialized instructions
591
+ const profile = detectTaskProfile(input);
592
+ let contextMsg = input;
593
+
594
+ // Inject profile if detected
595
+ if (profile) {
596
+ console.log(chalk.magenta(`\nšŸŽÆ ${profile.toUpperCase()} MODE DETECTED\n`));
597
+ contextMsg = `${input}\n\n${PROMPT_PROFILES[profile]}`;
598
+ }
599
+
348
600
  // Check if user mentioned a directory and provide context
349
601
  const dirMatch = input.match(/\/Users\/[^\s]+|\/[a-zA-Z0-9_\/-]+/g);
350
- let contextMsg = input;
351
602
 
352
603
  if (dirMatch && dirMatch[0]) {
353
604
  const mentionedDir = dirMatch[0];
354
605
  try {
355
606
  if (fs.existsSync(mentionedDir) && fs.statSync(mentionedDir).isDirectory()) {
356
607
  const files = fs.readdirSync(mentionedDir).slice(0, 10).join(', ');
357
- contextMsg = `${input}\n\n[CONTEXT: Directory "${mentionedDir}" contains: ${files}${fs.readdirSync(mentionedDir).length > 10 ? '...' : ''}]`;
608
+ contextMsg += `\n\n[CONTEXT: Directory "${mentionedDir}" contains: ${files}${fs.readdirSync(mentionedDir).length > 10 ? '...' : ''}]`;
358
609
  }
359
610
  } catch (e) {
360
611
  // Silently ignore if directory doesn't exist