@yuaone/core 0.3.3 → 0.4.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 (126) hide show
  1. package/dist/agent-loop.d.ts +62 -0
  2. package/dist/agent-loop.d.ts.map +1 -1
  3. package/dist/agent-loop.js +705 -18
  4. package/dist/agent-loop.js.map +1 -1
  5. package/dist/background-agent.d.ts +110 -0
  6. package/dist/background-agent.d.ts.map +1 -0
  7. package/dist/background-agent.js +255 -0
  8. package/dist/background-agent.js.map +1 -0
  9. package/dist/coding-standards.d.ts +45 -0
  10. package/dist/coding-standards.d.ts.map +1 -0
  11. package/dist/coding-standards.js +1152 -0
  12. package/dist/coding-standards.js.map +1 -0
  13. package/dist/constants.d.ts.map +1 -1
  14. package/dist/constants.js +2 -6
  15. package/dist/constants.js.map +1 -1
  16. package/dist/context-manager.d.ts +6 -0
  17. package/dist/context-manager.d.ts.map +1 -1
  18. package/dist/context-manager.js +23 -4
  19. package/dist/context-manager.js.map +1 -1
  20. package/dist/index.d.ts +28 -4
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +26 -2
  23. package/dist/index.js.map +1 -1
  24. package/dist/llm-client.d.ts +8 -3
  25. package/dist/llm-client.d.ts.map +1 -1
  26. package/dist/llm-client.js +64 -13
  27. package/dist/llm-client.js.map +1 -1
  28. package/dist/plugin-auto-loader.d.ts +108 -0
  29. package/dist/plugin-auto-loader.d.ts.map +1 -0
  30. package/dist/plugin-auto-loader.js +743 -0
  31. package/dist/plugin-auto-loader.js.map +1 -0
  32. package/dist/plugin-registry.d.ts +112 -0
  33. package/dist/plugin-registry.d.ts.map +1 -0
  34. package/dist/plugin-registry.js +319 -0
  35. package/dist/plugin-registry.js.map +1 -0
  36. package/dist/plugin-types.d.ts +388 -0
  37. package/dist/plugin-types.d.ts.map +1 -0
  38. package/dist/plugin-types.js +8 -0
  39. package/dist/plugin-types.js.map +1 -0
  40. package/dist/plugin-validator.d.ts +54 -0
  41. package/dist/plugin-validator.d.ts.map +1 -0
  42. package/dist/plugin-validator.js +129 -0
  43. package/dist/plugin-validator.js.map +1 -0
  44. package/dist/repo-knowledge-graph.d.ts +112 -0
  45. package/dist/repo-knowledge-graph.d.ts.map +1 -0
  46. package/dist/repo-knowledge-graph.js +561 -0
  47. package/dist/repo-knowledge-graph.js.map +1 -0
  48. package/dist/role-registry.js +1 -1
  49. package/dist/role-registry.js.map +1 -1
  50. package/dist/self-debug-loop.d.ts +257 -0
  51. package/dist/self-debug-loop.d.ts.map +1 -0
  52. package/dist/self-debug-loop.js +870 -0
  53. package/dist/self-debug-loop.js.map +1 -0
  54. package/dist/skill-learner.d.ts +136 -0
  55. package/dist/skill-learner.d.ts.map +1 -0
  56. package/dist/skill-learner.js +382 -0
  57. package/dist/skill-learner.js.map +1 -0
  58. package/dist/skill-loader.d.ts +90 -0
  59. package/dist/skill-loader.d.ts.map +1 -0
  60. package/dist/skill-loader.js +309 -0
  61. package/dist/skill-loader.js.map +1 -0
  62. package/dist/specialist-registry.d.ts +132 -0
  63. package/dist/specialist-registry.d.ts.map +1 -0
  64. package/dist/specialist-registry.js +413 -0
  65. package/dist/specialist-registry.js.map +1 -0
  66. package/dist/sub-agent-prompts.d.ts +45 -0
  67. package/dist/sub-agent-prompts.d.ts.map +1 -0
  68. package/dist/sub-agent-prompts.js +177 -0
  69. package/dist/sub-agent-prompts.js.map +1 -0
  70. package/dist/sub-agent-router.d.ts +75 -0
  71. package/dist/sub-agent-router.d.ts.map +1 -0
  72. package/dist/sub-agent-router.js +174 -0
  73. package/dist/sub-agent-router.js.map +1 -0
  74. package/dist/sub-agent.d.ts +48 -0
  75. package/dist/sub-agent.d.ts.map +1 -1
  76. package/dist/sub-agent.js +108 -5
  77. package/dist/sub-agent.js.map +1 -1
  78. package/dist/system-prompt.d.ts +26 -0
  79. package/dist/system-prompt.d.ts.map +1 -1
  80. package/dist/system-prompt.js +177 -7
  81. package/dist/system-prompt.js.map +1 -1
  82. package/dist/task-classifier.d.ts +25 -1
  83. package/dist/task-classifier.d.ts.map +1 -1
  84. package/dist/task-classifier.js +171 -1
  85. package/dist/task-classifier.js.map +1 -1
  86. package/dist/tool-planner.d.ts +160 -0
  87. package/dist/tool-planner.d.ts.map +1 -0
  88. package/dist/tool-planner.js +501 -0
  89. package/dist/tool-planner.js.map +1 -0
  90. package/dist/types.d.ts +1 -1
  91. package/dist/types.d.ts.map +1 -1
  92. package/package.json +2 -1
  93. package/plugins/git/patterns/branch-patterns.json +101 -0
  94. package/plugins/git/patterns/commit-patterns.json +186 -0
  95. package/plugins/git/plugin.yaml +128 -0
  96. package/plugins/git/skills/branch-strategy.md +172 -0
  97. package/plugins/git/skills/commit-conv.md +178 -0
  98. package/plugins/git/skills/conflict-resolve.md +159 -0
  99. package/plugins/git/skills/history-clean.md +199 -0
  100. package/plugins/git/skills/pr-review.md +196 -0
  101. package/plugins/git/strategies/conflict-resolve.json +244 -0
  102. package/plugins/git/strategies/release-flow.json +292 -0
  103. package/plugins/git/validators/rules.json +348 -0
  104. package/plugins/react/patterns/anti-patterns.json +88 -0
  105. package/plugins/react/patterns/components.json +80 -0
  106. package/plugins/react/patterns/hooks.json +72 -0
  107. package/plugins/react/plugin.yaml +229 -0
  108. package/plugins/react/skills/bugfix.md +208 -0
  109. package/plugins/react/skills/component-gen.md +206 -0
  110. package/plugins/react/skills/hook-extract.md +208 -0
  111. package/plugins/react/skills/ssr.md +256 -0
  112. package/plugins/react/skills/test.md +273 -0
  113. package/plugins/react/strategies/build-fix.json +43 -0
  114. package/plugins/react/strategies/hook-loop-fix.json +36 -0
  115. package/plugins/react/strategies/hydration-fix.json +42 -0
  116. package/plugins/react/validators/rules.json +92 -0
  117. package/plugins/typescript/patterns/best-practices.json +25 -0
  118. package/plugins/typescript/patterns/common-errors.json +32 -0
  119. package/plugins/typescript/plugin.yaml +74 -0
  120. package/plugins/typescript/skills/debug.md +23 -0
  121. package/plugins/typescript/skills/migration.md +24 -0
  122. package/plugins/typescript/skills/refactor.md +22 -0
  123. package/plugins/typescript/skills/strict-mode.md +23 -0
  124. package/plugins/typescript/strategies/strict-migration.json +37 -0
  125. package/plugins/typescript/strategies/type-error-fix.json +37 -0
  126. package/plugins/typescript/validators/rules.json +28 -0
@@ -0,0 +1,413 @@
1
+ /**
2
+ * @module specialist-registry
3
+ * @description Specialist Agent Registry — Domain-specific agent configurations.
4
+ *
5
+ * Each specialist has pre-loaded expertise, preferred tools, and quality thresholds.
6
+ * Routing: TaskClassifier -> SpecialistRegistry -> specialist config -> SubAgent
7
+ */
8
+ // ─── SpecialistRegistry Class ───
9
+ /**
10
+ * Registry for domain-specific specialist agent configurations.
11
+ *
12
+ * Manages built-in and custom specialists that can be matched to tasks
13
+ * based on type, language, framework, and error context.
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * const registry = new SpecialistRegistry();
18
+ *
19
+ * // Find best specialist for a TypeScript security task
20
+ * const match = registry.findSpecialist("security", {
21
+ * language: "typescript",
22
+ * });
23
+ * if (match) {
24
+ * console.log(match.specialist.name); // "Security Specialist"
25
+ * console.log(match.confidence); // 0.9
26
+ * }
27
+ *
28
+ * // Register a custom specialist
29
+ * registry.register({
30
+ * id: "rust-specialist",
31
+ * name: "Rust Specialist",
32
+ * domain: "Rust systems programming",
33
+ * systemPrompt: "You are a Rust expert...",
34
+ * preferredTools: ["file_read", "file_edit", "shell_exec"],
35
+ * preferredSkills: ["cargo-check", "clippy-lint"],
36
+ * qualityThreshold: 0.85,
37
+ * languages: ["rust"],
38
+ * });
39
+ * ```
40
+ */
41
+ export class SpecialistRegistry {
42
+ specialists = new Map();
43
+ constructor() {
44
+ this.registerBuiltins();
45
+ }
46
+ /**
47
+ * Register a specialist configuration.
48
+ * If a specialist with the same ID exists, it is replaced.
49
+ *
50
+ * @param config - Specialist configuration to register
51
+ */
52
+ register(config) {
53
+ this.specialists.set(config.id, config);
54
+ }
55
+ /**
56
+ * Find the best specialist for a given task type and context.
57
+ *
58
+ * Matching priority:
59
+ * 1. Exact task type match
60
+ * 2. Language/framework affinity bonus
61
+ * 3. Error message pattern match
62
+ *
63
+ * @param taskType - Task type string (from TaskClassifier)
64
+ * @param context - Optional context for better matching
65
+ * @returns Best matching specialist or null if none found
66
+ */
67
+ findSpecialist(taskType, context) {
68
+ const candidates = [];
69
+ for (const specialist of this.specialists.values()) {
70
+ let confidence = 0;
71
+ let reason = "";
72
+ // 1. Domain match via specialist ID or domain keywords
73
+ if (this.matchesDomain(specialist, taskType)) {
74
+ confidence = 0.7;
75
+ reason = `Domain match: ${specialist.domain}`;
76
+ }
77
+ // 2. Language affinity bonus
78
+ if (context?.language &&
79
+ specialist.languages?.some((lang) => lang.toLowerCase() === context.language.toLowerCase())) {
80
+ confidence += 0.15;
81
+ reason += reason ? "; language match" : `Language match: ${context.language}`;
82
+ }
83
+ // 3. Framework affinity bonus
84
+ if (context?.framework &&
85
+ specialist.frameworks?.some((fw) => fw.toLowerCase() === context.framework.toLowerCase())) {
86
+ confidence += 0.1;
87
+ reason += reason ? "; framework match" : `Framework match: ${context.framework}`;
88
+ }
89
+ // 4. Error message pattern match (for debugger/security specialists)
90
+ if (context?.errorMessage && specialist.id === "security-specialist") {
91
+ const securityPatterns = /xss|csrf|injection|auth|token|secret|vuln/i;
92
+ if (securityPatterns.test(context.errorMessage)) {
93
+ confidence += 0.15;
94
+ reason += "; security error pattern detected";
95
+ }
96
+ }
97
+ if (confidence > 0) {
98
+ candidates.push({
99
+ specialist,
100
+ confidence: Math.min(1.0, confidence),
101
+ reason,
102
+ });
103
+ }
104
+ }
105
+ if (candidates.length === 0)
106
+ return null;
107
+ // Return highest confidence match (lexicographic tie-break for determinism)
108
+ candidates.sort((a, b) => {
109
+ if (b.confidence !== a.confidence)
110
+ return b.confidence - a.confidence;
111
+ return a.specialist.id.localeCompare(b.specialist.id);
112
+ });
113
+ return candidates[0];
114
+ }
115
+ /**
116
+ * Get a specialist by its unique ID.
117
+ *
118
+ * @param id - Specialist ID
119
+ * @returns Specialist config or undefined if not found
120
+ */
121
+ get(id) {
122
+ return this.specialists.get(id);
123
+ }
124
+ /**
125
+ * List all registered specialists.
126
+ *
127
+ * @returns Array of all specialist configurations
128
+ */
129
+ list() {
130
+ return Array.from(this.specialists.values());
131
+ }
132
+ /**
133
+ * Remove a specialist by ID.
134
+ *
135
+ * @param id - Specialist ID to remove
136
+ * @returns true if removed, false if not found
137
+ */
138
+ remove(id) {
139
+ return this.specialists.delete(id);
140
+ }
141
+ /**
142
+ * Get the total number of registered specialists.
143
+ */
144
+ get size() {
145
+ return this.specialists.size;
146
+ }
147
+ // ─── Private Helpers ───
148
+ /**
149
+ * Check if a specialist's domain matches the given task type.
150
+ */
151
+ matchesDomain(specialist, taskType) {
152
+ const normalizedType = taskType.toLowerCase();
153
+ // Direct ID match patterns
154
+ const domainMap = {
155
+ "typescript-specialist": ["feature", "refactor", "config"],
156
+ "react-specialist": ["feature", "design", "refactor"],
157
+ "infra-specialist": ["infra", "deploy"],
158
+ "testing-specialist": ["test"],
159
+ "security-specialist": ["security"],
160
+ "python-specialist": ["feature", "refactor"],
161
+ "database-specialist": ["migration", "feature", "performance"],
162
+ "performance-specialist": ["performance"],
163
+ };
164
+ const matchTypes = domainMap[specialist.id];
165
+ if (matchTypes && matchTypes.includes(normalizedType)) {
166
+ return true;
167
+ }
168
+ // Fallback: check domain description keywords
169
+ return specialist.domain.toLowerCase().includes(normalizedType);
170
+ }
171
+ /**
172
+ * Register all built-in specialist configurations.
173
+ */
174
+ registerBuiltins() {
175
+ // 1. TypeScript Specialist
176
+ this.register({
177
+ id: "typescript-specialist",
178
+ name: "TypeScript Specialist",
179
+ domain: "TypeScript type system, generics, and advanced patterns",
180
+ systemPrompt: `You are a TypeScript expert. Your strength is leveraging the type system for maximum safety and developer experience.
181
+
182
+ Expertise:
183
+ - Strict mode, noUncheckedIndexedAccess, exactOptionalPropertyTypes
184
+ - Generic constraints, conditional types, mapped types, template literals
185
+ - Type inference optimization — let TS infer when possible, annotate when ambiguous
186
+ - Declaration files (.d.ts) for untyped dependencies
187
+ - tsconfig optimization for monorepos (composite, references, paths)
188
+ - Discriminated unions over type assertions; exhaustive switches with never
189
+
190
+ Rules:
191
+ - Never use \`any\` — use \`unknown\` with type guards instead
192
+ - Prefer \`interface\` for objects, \`type\` for unions/intersections/utility types
193
+ - Use \`satisfies\` for type-safe object literals with inference
194
+ - Export types explicitly; avoid re-exporting \`*\` from barrel files
195
+ - Use \`as const\` for literal type inference on constant arrays/objects`,
196
+ preferredTools: ["file_read", "file_edit", "grep", "shell_exec"],
197
+ preferredSkills: ["type-check", "tsconfig-lint"],
198
+ qualityThreshold: 0.85,
199
+ languages: ["typescript", "javascript"],
200
+ frameworks: ["node", "deno", "bun"],
201
+ canDelegateTo: ["react-specialist", "testing-specialist"],
202
+ });
203
+ // 2. React Specialist
204
+ this.register({
205
+ id: "react-specialist",
206
+ name: "React Specialist",
207
+ domain: "React, hooks, SSR/hydration, state management, and Next.js",
208
+ systemPrompt: `You are a React expert. Your goal: build performant, accessible UI with clean component architecture.
209
+
210
+ Expertise:
211
+ - Hooks: useState, useEffect, useCallback, useMemo, useRef, custom hooks
212
+ - SSR/hydration pitfalls: useEffect vs useLayoutEffect, window checks, dynamic imports
213
+ - State management: Zustand, React Query/TanStack Query, context (sparingly)
214
+ - Performance: React.memo, useMemo, useCallback — only when measured as needed
215
+ - Next.js: App Router, Server Components, route handlers, middleware, ISR/SSG
216
+ - Suspense boundaries, error boundaries, streaming SSR
217
+
218
+ Rules:
219
+ - Prefer Server Components by default; use 'use client' only when needed
220
+ - Never store derived state — compute it during render
221
+ - Keep components small (<100 lines); extract hooks for reusable logic
222
+ - Use \`key\` prop correctly to avoid stale state bugs
223
+ - Always handle loading, error, and empty states
224
+ - Accessibility: semantic HTML, ARIA labels, keyboard navigation`,
225
+ preferredTools: ["file_read", "file_edit", "file_write", "glob", "shell_exec"],
226
+ preferredSkills: ["component-lint", "accessibility-check", "bundle-analyzer"],
227
+ qualityThreshold: 0.80,
228
+ languages: ["typescript", "javascript"],
229
+ frameworks: ["react", "next.js", "remix", "gatsby"],
230
+ canDelegateTo: ["typescript-specialist", "performance-specialist"],
231
+ });
232
+ // 3. Infrastructure Specialist
233
+ this.register({
234
+ id: "infra-specialist",
235
+ name: "Infrastructure Specialist",
236
+ domain: "DevOps, Docker, CI/CD, Terraform, Kubernetes, cloud services",
237
+ systemPrompt: `You are an infrastructure and DevOps expert. Your goal: reliable, reproducible, secure deployments.
238
+
239
+ Expertise:
240
+ - Docker: multi-stage builds, layer caching, minimal images (distroless/alpine)
241
+ - CI/CD: GitHub Actions, GitLab CI, Jenkins — caching, matrix builds, artifact management
242
+ - Terraform/IaC: state management, modules, workspaces, drift detection
243
+ - Kubernetes: deployments, services, ingress, HPA, resource limits, health checks
244
+ - Cloud: AWS (ECS, Lambda, RDS, S3), GCP (Cloud Run, GKE), Azure basics
245
+ - Monitoring: Prometheus, Grafana, CloudWatch, structured logging, alerting rules
246
+
247
+ Rules:
248
+ - Always pin versions (Docker tags, Terraform providers, CI action versions)
249
+ - Secrets via env vars or secret managers — never hardcode
250
+ - Health checks on every service; graceful shutdown handlers
251
+ - Least-privilege IAM roles and network policies
252
+ - Idempotent deployments; rollback strategy for every change
253
+ - Cost awareness: right-size resources, use spot/preemptible when safe`,
254
+ preferredTools: ["file_read", "file_edit", "shell_exec", "file_write"],
255
+ preferredSkills: ["docker-lint", "terraform-validate", "cloud-cost-estimate"],
256
+ qualityThreshold: 0.85,
257
+ languages: ["yaml", "hcl", "bash", "typescript"],
258
+ frameworks: ["docker", "kubernetes", "terraform", "github-actions"],
259
+ canDelegateTo: ["security-specialist"],
260
+ });
261
+ // 4. Testing Specialist
262
+ this.register({
263
+ id: "testing-specialist",
264
+ name: "Testing Specialist",
265
+ domain: "Unit, integration, e2e testing, TDD, mocking, coverage",
266
+ systemPrompt: `You are a testing expert. Your goal: comprehensive, maintainable tests that catch real bugs.
267
+
268
+ Expertise:
269
+ - Unit tests: isolated, fast, one assertion per concept, AAA pattern (Arrange/Act/Assert)
270
+ - Integration tests: test module boundaries, real dependencies where practical
271
+ - E2E tests: critical user flows, stable selectors, retry logic, visual regression
272
+ - Mocking: minimal mocks — prefer fakes/stubs; mock at boundaries, not internals
273
+ - Coverage: line coverage is necessary but not sufficient; branch and path coverage matter
274
+ - TDD: red-green-refactor cycle when building new features
275
+
276
+ Rules:
277
+ - Test behavior, not implementation details
278
+ - Name tests: "should [expected behavior] when [condition]"
279
+ - No test interdependence — each test sets up its own state
280
+ - Prefer \`describe/it\` grouping for readability
281
+ - Mock external APIs, databases, file system — not your own code
282
+ - Flaky tests are bugs: fix or quarantine immediately
283
+ - Aim for fast feedback: unit > integration > e2e (testing pyramid)`,
284
+ preferredTools: ["file_read", "file_write", "file_edit", "shell_exec", "grep"],
285
+ preferredSkills: ["test-generator", "coverage-analysis", "mock-generator"],
286
+ qualityThreshold: 0.80,
287
+ languages: ["typescript", "javascript", "python"],
288
+ frameworks: ["vitest", "jest", "playwright", "pytest", "mocha"],
289
+ canDelegateTo: ["typescript-specialist"],
290
+ });
291
+ // 5. Security Specialist
292
+ this.register({
293
+ id: "security-specialist",
294
+ name: "Security Specialist",
295
+ domain: "OWASP top 10, auth, injection prevention, secrets management, dependency auditing",
296
+ systemPrompt: `You are a security expert. Your goal: identify and remediate vulnerabilities before they reach production.
297
+
298
+ Expertise:
299
+ - OWASP Top 10: injection (SQL, NoSQL, OS cmd), XSS (reflected/stored/DOM), CSRF, SSRF
300
+ - Authentication: bcrypt/argon2 hashing, JWT best practices, session management, MFA
301
+ - Authorization: RBAC, ABAC, least privilege, broken access control patterns
302
+ - Secrets: never in code/logs; use vault/env vars; rotate regularly; detect with scanners
303
+ - Dependencies: npm audit, Snyk, Dependabot; pin versions; monitor CVEs
304
+ - Headers: CSP, HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy
305
+ - Input validation: allowlist over denylist; parameterized queries; output encoding
306
+
307
+ Rules:
308
+ - Defense in depth: never rely on a single control
309
+ - Fail secure: errors should deny access, not grant it
310
+ - Log security events but never log sensitive data (passwords, tokens, PII)
311
+ - Rate limiting on auth endpoints; account lockout with notification
312
+ - HTTPS everywhere; secure cookie flags (HttpOnly, Secure, SameSite)
313
+ - Regular dependency audits; automated vulnerability scanning in CI`,
314
+ preferredTools: ["grep", "file_read", "shell_exec", "file_edit"],
315
+ preferredSkills: ["vulnerability-scan", "secret-detection", "dependency-audit"],
316
+ qualityThreshold: 0.90,
317
+ languages: ["typescript", "javascript", "python", "go"],
318
+ frameworks: ["express", "next.js", "fastapi", "django"],
319
+ canDelegateTo: ["infra-specialist"],
320
+ });
321
+ // 6. Python Specialist
322
+ this.register({
323
+ id: "python-specialist",
324
+ name: "Python Specialist",
325
+ domain: "Python async, type hints, FastAPI/Django, data processing, packaging",
326
+ systemPrompt: `You are a Python expert. Your goal: idiomatic, well-typed, performant Python code.
327
+
328
+ Expertise:
329
+ - Async: asyncio, aiohttp, async generators; understand event loop mechanics
330
+ - Type hints: typing module, Protocol, TypeVar, ParamSpec, overload, TypeGuard
331
+ - Frameworks: FastAPI (Pydantic models, dependency injection), Django (ORM, middleware)
332
+ - Data: pandas, polars, numpy patterns; efficient chunked processing for large datasets
333
+ - Packaging: pyproject.toml, poetry/uv, virtual environments, wheel building
334
+ - Testing: pytest fixtures, parametrize, monkeypatch, hypothesis for property-based tests
335
+
336
+ Rules:
337
+ - Use type hints on all public functions and class methods
338
+ - Prefer dataclasses/Pydantic models over plain dicts for structured data
339
+ - Use pathlib.Path over os.path; f-strings over format/concatenation
340
+ - Context managers for resource cleanup (files, connections, locks)
341
+ - List comprehensions for simple transforms; generators for large data
342
+ - Follow PEP 8; use ruff for linting and formatting`,
343
+ preferredTools: ["file_read", "file_edit", "shell_exec", "file_write", "grep"],
344
+ preferredSkills: ["type-check", "ruff-lint", "pytest-runner"],
345
+ qualityThreshold: 0.80,
346
+ languages: ["python"],
347
+ frameworks: ["fastapi", "django", "flask", "pytorch", "pandas"],
348
+ canDelegateTo: ["testing-specialist", "database-specialist"],
349
+ });
350
+ // 7. Database Specialist
351
+ this.register({
352
+ id: "database-specialist",
353
+ name: "Database Specialist",
354
+ domain: "SQL optimization, indexing, migration, ORM patterns, connection pooling",
355
+ systemPrompt: `You are a database expert. Your goal: correct, performant, and safe data operations.
356
+
357
+ Expertise:
358
+ - SQL: query optimization, EXPLAIN ANALYZE, index design (B-tree, GIN, GiST, partial)
359
+ - Migrations: zero-downtime schema changes, backward-compatible migrations, rollback plans
360
+ - ORMs: Prisma, Drizzle, TypeORM, SQLAlchemy — when to use raw SQL vs ORM
361
+ - Connection pooling: PgBouncer, connection limits, idle timeout, pool sizing
362
+ - Patterns: soft delete, audit trails, optimistic locking, event sourcing basics
363
+ - NoSQL: when to use (document, KV, graph); MongoDB, Redis, DynamoDB patterns
364
+
365
+ Rules:
366
+ - Always add indexes for columns used in WHERE, JOIN, ORDER BY
367
+ - Never SELECT *; specify columns explicitly
368
+ - Use transactions for multi-statement writes; understand isolation levels
369
+ - Parameterized queries always — never string interpolation for SQL
370
+ - Migration scripts must be idempotent and reversible
371
+ - Test migrations on a copy of production data before deploying
372
+ - Monitor slow queries; set up query logging and alerting`,
373
+ preferredTools: ["file_read", "file_edit", "shell_exec", "grep"],
374
+ preferredSkills: ["query-analyzer", "migration-validator", "schema-lint"],
375
+ qualityThreshold: 0.85,
376
+ languages: ["sql", "typescript", "python"],
377
+ frameworks: ["prisma", "drizzle", "typeorm", "sqlalchemy", "knex"],
378
+ canDelegateTo: ["infra-specialist", "performance-specialist"],
379
+ });
380
+ // 8. Performance Specialist
381
+ this.register({
382
+ id: "performance-specialist",
383
+ name: "Performance Specialist",
384
+ domain: "Profiling, bundle optimization, lazy loading, caching, algorithmic complexity",
385
+ systemPrompt: `You are a performance expert. Your goal: measurable, impactful optimizations based on data, not guesswork.
386
+
387
+ Expertise:
388
+ - Profiling: Chrome DevTools, Node.js --inspect, flame graphs, heap snapshots
389
+ - Bundle: tree shaking, code splitting, dynamic imports, bundle analysis (webpack-bundle-analyzer)
390
+ - Rendering: virtual scrolling, windowing (react-window/virtuoso), layout thrashing prevention
391
+ - Caching: HTTP cache headers, service workers, in-memory caches (LRU), CDN edge caching
392
+ - Algorithms: Big-O analysis, data structure selection, avoiding N+1 queries
393
+ - Network: request waterfall optimization, prefetch/preload, compression (gzip/brotli)
394
+ - Core Web Vitals: LCP, FID/INP, CLS — measurement and improvement strategies
395
+
396
+ Rules:
397
+ - Measure before optimizing — use benchmarks and profiler data
398
+ - Optimize the bottleneck, not the whole system
399
+ - Prefer algorithmic improvements (O(n) vs O(n^2)) over micro-optimizations
400
+ - Lazy load non-critical resources; prioritize above-the-fold content
401
+ - Cache invalidation strategy is as important as caching itself
402
+ - Document performance budgets and set up CI checks for regressions
403
+ - Test on real devices and slow networks, not just developer machines`,
404
+ preferredTools: ["grep", "file_read", "shell_exec", "file_edit"],
405
+ preferredSkills: ["profiler", "bundle-analyzer", "cache-advisor", "lighthouse-audit"],
406
+ qualityThreshold: 0.80,
407
+ languages: ["typescript", "javascript", "python", "go"],
408
+ frameworks: ["react", "next.js", "node", "webpack", "vite"],
409
+ canDelegateTo: ["react-specialist", "database-specialist"],
410
+ });
411
+ }
412
+ }
413
+ //# sourceMappingURL=specialist-registry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"specialist-registry.js","sourceRoot":"","sources":["../src/specialist-registry.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAsCH,mCAAmC;AAEnC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,MAAM,OAAO,kBAAkB;IACrB,WAAW,GAAkC,IAAI,GAAG,EAAE,CAAC;IAE/D;QACE,IAAI,CAAC,gBAAgB,EAAE,CAAC;IAC1B,CAAC;IAED;;;;;OAKG;IACH,QAAQ,CAAC,MAAwB;QAC/B,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC;IAC1C,CAAC;IAED;;;;;;;;;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ChE,cAAc,EAAE,CAAC,MAAM,EAAE,WAAW,EAAE,YAAY,EAAE,WAAW,CAAC;YAChE,eAAe,EAAE,CAAC,UAAU,EAAE,iBAAiB,EAAE,eAAe,EAAE,kBAAkB,CAAC;YACrF,gBAAgB,EAAE,IAAI;YACtB,SAAS,EAAE,CAAC,YAAY,EAAE,YAAY,EAAE,QAAQ,EAAE,IAAI,CAAC;YACvD,UAAU,EAAE,CAAC,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,CAAC;YAC3D,aAAa,EAAE,CAAC,kBAAkB,EAAE,qBAAqB,CAAC;SAC3D,CAAC,CAAC;IACL,CAAC;CACF"}
@@ -0,0 +1,45 @@
1
+ /**
2
+ * @module sub-agent-prompts
3
+ * @description Role-specific, token-optimized prompts for sub-agents.
4
+ *
5
+ * Design principles:
6
+ * 1. Shorter prompts → fewer input tokens → lower cost
7
+ * 2. Clearer constraints → better first-attempt quality → fewer iterations
8
+ * 3. Output format → structured responses → easier parsing
9
+ * 4. Domain expertise → fewer mistakes → less back-and-forth
10
+ */
11
+ export type SubAgentRole = "coder" | "reviewer" | "tester" | "debugger" | "refactorer" | "planner";
12
+ export interface SubAgentPromptConfig {
13
+ /** Sub-agent role determines the system prompt template */
14
+ role: SubAgentRole;
15
+ /** Primary language (e.g. "typescript", "python") */
16
+ language?: string;
17
+ /** Framework in use (e.g. "react", "next.js") */
18
+ framework?: string;
19
+ /** Brief project description for context */
20
+ projectContext?: string;
21
+ /** Additional constraints injected verbatim */
22
+ constraints?: string[];
23
+ }
24
+ /**
25
+ * Build an optimized system prompt for a sub-agent.
26
+ *
27
+ * Assembles role-specific instructions, optional language standards,
28
+ * framework context, and custom constraints into a single prompt.
29
+ *
30
+ * Target: <800 tokens for simple roles, <1200 for complex roles.
31
+ *
32
+ * @param config - Prompt configuration specifying role and context
33
+ * @returns Fully constructed system prompt string
34
+ */
35
+ export declare function buildSubAgentPrompt(config: SubAgentPromptConfig): string;
36
+ /**
37
+ * Get the role-specific prompt template without additional context.
38
+ * Useful for inspecting or testing individual role prompts.
39
+ */
40
+ export declare function getRolePrompt(role: SubAgentRole): string;
41
+ /**
42
+ * Get all available sub-agent roles.
43
+ */
44
+ export declare function getAvailableRoles(): SubAgentRole[];
45
+ //# sourceMappingURL=sub-agent-prompts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sub-agent-prompts.d.ts","sourceRoot":"","sources":["../src/sub-agent-prompts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAMH,MAAM,MAAM,YAAY,GACpB,OAAO,GACP,UAAU,GACV,QAAQ,GACR,UAAU,GACV,YAAY,GACZ,SAAS,CAAC;AAEd,MAAM,WAAW,oBAAoB;IACnC,2DAA2D;IAC3D,IAAI,EAAE,YAAY,CAAC;IACnB,qDAAqD;IACrD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,iDAAiD;IACjD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,4CAA4C;IAC5C,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,+CAA+C;IAC/C,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;CACxB;AAoGD;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,oBAAoB,GAAG,MAAM,CAyCxE;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,YAAY,GAAG,MAAM,CAExD;AAED;;GAEG;AACH,wBAAgB,iBAAiB,IAAI,YAAY,EAAE,CAElD"}
@@ -0,0 +1,177 @@
1
+ /**
2
+ * @module sub-agent-prompts
3
+ * @description Role-specific, token-optimized prompts for sub-agents.
4
+ *
5
+ * Design principles:
6
+ * 1. Shorter prompts → fewer input tokens → lower cost
7
+ * 2. Clearer constraints → better first-attempt quality → fewer iterations
8
+ * 3. Output format → structured responses → easier parsing
9
+ * 4. Domain expertise → fewer mistakes → less back-and-forth
10
+ */
11
+ import { getCodingStandards } from "./coding-standards.js";
12
+ // ─── Role Prompt Templates ───
13
+ // Each template is kept concise: ~400-600 tokens to minimize input cost.
14
+ const ROLE_PROMPTS = {
15
+ coder: `You are a precise coding agent. Your goal: write minimal, correct code on the first attempt.
16
+
17
+ Rules:
18
+ - Read existing code before writing. Match the project's style, patterns, and conventions exactly.
19
+ - Make the smallest change that achieves the goal. No unnecessary abstractions, comments, or over-engineering.
20
+ - Prefer editing existing files (file_edit) over full rewrites (file_write).
21
+ - After changes, verify with build/lint/typecheck. Fix any errors before reporting done.
22
+ - Never modify files outside your assigned scope.
23
+
24
+ Output format:
25
+ 1. Brief plan (1-3 lines)
26
+ 2. Code changes (use tools)
27
+ 3. Verification result (build/lint output)
28
+ 4. Summary: files changed + what was done`,
29
+ reviewer: `You are a code review agent. Focus on correctness, security, and performance — in that order.
30
+
31
+ Rules:
32
+ - Read all changed files thoroughly before judging.
33
+ - Flag only real issues: bugs, security holes, perf problems, broken contracts.
34
+ - No style nits unless they cause bugs. No suggestions for "nice to have" improvements.
35
+ - Be specific: cite file, line, and the exact problem.
36
+
37
+ Output format (JSON):
38
+ {
39
+ "verdict": "approve" | "request_changes" | "comment",
40
+ "issues": [{ "severity": "critical|high|medium", "file": "...", "line": N, "description": "..." }],
41
+ "confidence": 0.0-1.0,
42
+ "summary": "one line"
43
+ }`,
44
+ tester: `You are a test-writing agent. Write tests that catch real bugs, not ceremonial coverage.
45
+
46
+ Rules:
47
+ - Test behavior and contracts, not implementation details.
48
+ - Cover: happy path, edge cases, error paths, boundary values.
49
+ - Keep tests independent — no shared mutable state between tests.
50
+ - Use the project's existing test framework and patterns.
51
+ - Run tests after writing. Fix failures before reporting done.
52
+
53
+ Output format:
54
+ 1. Test strategy (2-3 lines: what to test and why)
55
+ 2. Test files created/modified
56
+ 3. Test run results (pass/fail counts)
57
+ 4. Coverage gaps noted (if any)`,
58
+ debugger: `You are a debugging agent. Reproduce first, then diagnose, then fix minimally.
59
+
60
+ Rules:
61
+ - Reproduce the bug with a concrete test case or command before anything else.
62
+ - Build a causal chain: symptom → hypothesis → evidence → root cause.
63
+ - Make the minimal fix that addresses the root cause. Do NOT refactor during debugging.
64
+ - Verify the fix resolves the symptom and doesn't break other tests.
65
+ - If you can't reproduce, report what you tried and hypotheses.
66
+
67
+ Output format:
68
+ 1. Reproduction steps + result
69
+ 2. Root cause analysis (causal chain)
70
+ 3. Fix applied (minimal diff)
71
+ 4. Verification (tests pass, symptom gone)`,
72
+ refactorer: `You are a refactoring agent. Improve code structure while preserving behavior exactly.
73
+
74
+ Rules:
75
+ - Run tests BEFORE refactoring to establish a green baseline.
76
+ - Apply one refactoring pattern at a time (extract, inline, rename, move, simplify).
77
+ - After each refactoring, run tests again to confirm no regressions.
78
+ - Measure improvement: lines of code, cyclomatic complexity, duplication removed.
79
+ - Never change behavior. If tests fail after refactoring, revert and try a different approach.
80
+
81
+ Output format:
82
+ 1. Baseline test results
83
+ 2. Refactoring applied (pattern + files)
84
+ 3. Post-refactoring test results
85
+ 4. Metrics: before/after (LOC, complexity)`,
86
+ planner: `You are a planning agent. Break complex goals into concrete, actionable tasks.
87
+
88
+ Rules:
89
+ - Analyze the codebase structure before planning. Read key files to understand architecture.
90
+ - Each task must be independently executable with clear inputs/outputs.
91
+ - Identify dependencies between tasks (what blocks what).
92
+ - Estimate effort per task (simple/moderate/complex) and assign to appropriate agent roles.
93
+ - Flag risks and unknowns explicitly.
94
+
95
+ Output format:
96
+ 1. Goal analysis (what's needed, key challenges)
97
+ 2. Task list with dependencies, roles, and estimates
98
+ 3. Execution order (respecting dependencies)
99
+ 4. Risks and mitigations`,
100
+ };
101
+ // ─── Prompt Builder ───
102
+ /**
103
+ * Build an optimized system prompt for a sub-agent.
104
+ *
105
+ * Assembles role-specific instructions, optional language standards,
106
+ * framework context, and custom constraints into a single prompt.
107
+ *
108
+ * Target: <800 tokens for simple roles, <1200 for complex roles.
109
+ *
110
+ * @param config - Prompt configuration specifying role and context
111
+ * @returns Fully constructed system prompt string
112
+ */
113
+ export function buildSubAgentPrompt(config) {
114
+ const sections = [];
115
+ // 1. Role-specific prompt (core instructions)
116
+ const rolePrompt = ROLE_PROMPTS[config.role];
117
+ if (!rolePrompt) {
118
+ // Fallback to coder if unknown role
119
+ sections.push(ROLE_PROMPTS.coder);
120
+ }
121
+ else {
122
+ sections.push(rolePrompt);
123
+ }
124
+ // 2. Language-specific coding standards (if detected)
125
+ if (config.language) {
126
+ const standards = getCodingStandards(config.language);
127
+ if (standards) {
128
+ sections.push(`## ${config.language} Standards\n${standards}`);
129
+ }
130
+ }
131
+ // 3. Framework context (brief)
132
+ if (config.framework) {
133
+ const frameworkNote = getFrameworkNote(config.framework);
134
+ if (frameworkNote) {
135
+ sections.push(`## Framework: ${config.framework}\n${frameworkNote}`);
136
+ }
137
+ }
138
+ // 4. Project context (if provided)
139
+ if (config.projectContext) {
140
+ sections.push(`## Project Context\n${config.projectContext}`);
141
+ }
142
+ // 5. Additional constraints
143
+ if (config.constraints && config.constraints.length > 0) {
144
+ sections.push(`## Additional Constraints\n${config.constraints.map((c) => `- ${c}`).join("\n")}`);
145
+ }
146
+ return sections.join("\n\n").trim();
147
+ }
148
+ /**
149
+ * Get the role-specific prompt template without additional context.
150
+ * Useful for inspecting or testing individual role prompts.
151
+ */
152
+ export function getRolePrompt(role) {
153
+ return ROLE_PROMPTS[role] ?? ROLE_PROMPTS.coder;
154
+ }
155
+ /**
156
+ * Get all available sub-agent roles.
157
+ */
158
+ export function getAvailableRoles() {
159
+ return Object.keys(ROLE_PROMPTS);
160
+ }
161
+ // ─── Framework Notes ───
162
+ // Short notes (<100 tokens each) to orient the agent in a specific framework.
163
+ function getFrameworkNote(framework) {
164
+ const normalized = framework.toLowerCase().replace(/[.\s]/g, "");
165
+ const notes = {
166
+ react: "Use functional components + hooks. Follow Rules of Hooks. Use key props in lists. Memoize expensive computations. Clean up effects.",
167
+ nextjs: "App Router: use server components by default, 'use client' only when needed. Use next/image, next/link. API routes in app/api/. Metadata exports for SEO.",
168
+ vue: "Composition API preferred. Use ref/reactive for state. defineProps/defineEmits for component contracts. v-model for two-way binding.",
169
+ svelte: "Use $: for reactive declarations. Bind with bind:value. Use #each with key. Dispatch custom events. Use stores for shared state.",
170
+ express: "Use middleware composition. Validate inputs with schema. Handle errors in centralized error middleware. Use async handlers with try-catch.",
171
+ fastify: "Use schema validation for routes. Register plugins properly. Use decorators for shared state. Async handlers are native.",
172
+ django: "Use class-based views for complex logic, function views for simple. Follow model-view-template. Use ORM querysets efficiently.",
173
+ flask: "Use blueprints for modularity. Application factory pattern. Use decorators for routes. Register error handlers.",
174
+ };
175
+ return notes[normalized] ?? null;
176
+ }
177
+ //# sourceMappingURL=sub-agent-prompts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sub-agent-prompts.js","sourceRoot":"","sources":["../src/sub-agent-prompts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAyB3D,gCAAgC;AAChC,yEAAyE;AAEzE,MAAM,YAAY,GAAiC;IACjD,KAAK,EAAE;;;;;;;;;;;;;0CAaiC;IAExC,QAAQ,EAAE;;;;;;;;;;;;;;EAcV;IAEA,MAAM,EAAE;;;;;;;;;;;;;gCAasB;IAE9B,QAAQ,EAAE;;;;;;;;;;;;;2CAa+B;IAEzC,UAAU,EAAE;;;;;;;;;;;;;2CAa6B;IAEzC,OAAO,EAAE;;;;;;;;;;;;;yBAac;CACxB,CAAC;AAEF,yBAAyB;AAEzB;;;;;;;;;;GAUG;AACH,MAAM,UAAU,mBAAmB,CAAC,MAA4B;IAC9D,MAAM,QAAQ,GAAa,EAAE,CAAC;IAE9B,8CAA8C;IAC9C,MAAM,UAAU,GAAG,YAAY,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAC7C,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,oCAAoC;QACpC,QAAQ,CAAC,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;SAAM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