@jigyasudham/veto 0.8.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 (198) hide show
  1. package/.claude/settings.local.json +9 -0
  2. package/README.md +190 -0
  3. package/dist/adapters/claude.js +57 -0
  4. package/dist/adapters/codex.js +58 -0
  5. package/dist/adapters/gemini.js +58 -0
  6. package/dist/adapters/index.js +156 -0
  7. package/dist/agents/development/api.js +116 -0
  8. package/dist/agents/development/backend.js +82 -0
  9. package/dist/agents/development/coder.js +207 -0
  10. package/dist/agents/development/database.js +81 -0
  11. package/dist/agents/development/debugger.js +234 -0
  12. package/dist/agents/development/devops.js +84 -0
  13. package/dist/agents/development/frontend.js +83 -0
  14. package/dist/agents/development/migration.js +141 -0
  15. package/dist/agents/development/performance.js +142 -0
  16. package/dist/agents/development/refactor.js +85 -0
  17. package/dist/agents/development/reviewer.js +260 -0
  18. package/dist/agents/development/tester.js +143 -0
  19. package/dist/agents/executor.js +144 -0
  20. package/dist/agents/memory/context-manager.js +167 -0
  21. package/dist/agents/memory/decision-logger.js +157 -0
  22. package/dist/agents/memory/knowledge-base.js +120 -0
  23. package/dist/agents/memory/pattern-learner.js +140 -0
  24. package/dist/agents/memory/project-mapper.js +114 -0
  25. package/dist/agents/quality/accessibility.js +89 -0
  26. package/dist/agents/quality/code-quality.js +109 -0
  27. package/dist/agents/quality/compatibility.js +55 -0
  28. package/dist/agents/quality/documentation.js +95 -0
  29. package/dist/agents/quality/error-handling.js +87 -0
  30. package/dist/agents/research/competitor-analyzer.js +44 -0
  31. package/dist/agents/research/cost-analyzer.js +51 -0
  32. package/dist/agents/research/estimator.js +57 -0
  33. package/dist/agents/research/ethics-bias.js +111 -0
  34. package/dist/agents/research/researcher.js +112 -0
  35. package/dist/agents/research/risk-assessor.js +61 -0
  36. package/dist/agents/research/tech-advisor.js +52 -0
  37. package/dist/agents/security/auth.js +269 -0
  38. package/dist/agents/security/dependency-audit.js +273 -0
  39. package/dist/agents/security/penetration.js +245 -0
  40. package/dist/agents/security/privacy.js +259 -0
  41. package/dist/agents/security/scanner.js +288 -0
  42. package/dist/agents/security/secrets.js +212 -0
  43. package/dist/agents/types.js +2 -0
  44. package/dist/agents/workflow/automation.js +56 -0
  45. package/dist/agents/workflow/file-manager.js +49 -0
  46. package/dist/agents/workflow/git-agent.js +52 -0
  47. package/dist/agents/workflow/reporter.js +48 -0
  48. package/dist/agents/workflow/search-agent.js +39 -0
  49. package/dist/agents/workflow/task-coordinator.js +40 -0
  50. package/dist/agents/workflow/task-planner.js +46 -0
  51. package/dist/cli.js +132 -0
  52. package/dist/council/decision-engine.js +136 -0
  53. package/dist/council/devil-advocate.js +106 -0
  54. package/dist/council/index.js +37 -0
  55. package/dist/council/lead-developer.js +108 -0
  56. package/dist/council/legal-compliance.js +142 -0
  57. package/dist/council/product-manager.js +92 -0
  58. package/dist/council/security.js +162 -0
  59. package/dist/council/system-architect.js +122 -0
  60. package/dist/council/types.js +2 -0
  61. package/dist/council/ux-designer.js +109 -0
  62. package/dist/memory/local.js +182 -0
  63. package/dist/memory/schema.js +116 -0
  64. package/dist/memory/sync.js +199 -0
  65. package/dist/router/complexity-scorer.js +78 -0
  66. package/dist/router/context-compressor.js +58 -0
  67. package/dist/router/index.js +29 -0
  68. package/dist/router/learning-updater.js +186 -0
  69. package/dist/router/model-selector.js +51 -0
  70. package/dist/router/rate-monitor.js +73 -0
  71. package/dist/server.js +949 -0
  72. package/dist/skills/development/skill-api-design.js +313 -0
  73. package/dist/skills/development/skill-auth.js +255 -0
  74. package/dist/skills/development/skill-ci-cd.js +2 -0
  75. package/dist/skills/development/skill-crud.js +193 -0
  76. package/dist/skills/development/skill-db-schema.js +2 -0
  77. package/dist/skills/development/skill-docker.js +2 -0
  78. package/dist/skills/development/skill-env-setup.js +2 -0
  79. package/dist/skills/development/skill-scaffold.js +299 -0
  80. package/dist/skills/intelligence/skill-complexity-score.js +66 -0
  81. package/dist/skills/intelligence/skill-cost-track.js +36 -0
  82. package/dist/skills/intelligence/skill-learning-loop.js +66 -0
  83. package/dist/skills/intelligence/skill-pattern-detect.js +35 -0
  84. package/dist/skills/intelligence/skill-rate-watch.js +58 -0
  85. package/dist/skills/memory/skill-context-compress.js +82 -0
  86. package/dist/skills/memory/skill-cross-sync.js +88 -0
  87. package/dist/skills/memory/skill-decision-log.js +103 -0
  88. package/dist/skills/memory/skill-session-restore.js +44 -0
  89. package/dist/skills/memory/skill-session-save.js +78 -0
  90. package/dist/skills/quality/skill-accessibility.js +2 -0
  91. package/dist/skills/quality/skill-code-review.js +60 -0
  92. package/dist/skills/quality/skill-docs-gen.js +2 -0
  93. package/dist/skills/quality/skill-perf-audit.js +2 -0
  94. package/dist/skills/quality/skill-security-scan.js +67 -0
  95. package/dist/skills/quality/skill-test-suite.js +274 -0
  96. package/dist/skills/workflow/skill-deploy.js +2 -0
  97. package/dist/skills/workflow/skill-git-workflow.js +2 -0
  98. package/dist/skills/workflow/skill-rollback.js +2 -0
  99. package/dist/skills/workflow/skill-task-breakdown.js +2 -0
  100. package/package.json +30 -0
  101. package/src/adapters/claude.ts +70 -0
  102. package/src/adapters/codex.ts +71 -0
  103. package/src/adapters/gemini.ts +71 -0
  104. package/src/adapters/index.ts +217 -0
  105. package/src/agents/development/api.ts +120 -0
  106. package/src/agents/development/backend.ts +85 -0
  107. package/src/agents/development/coder.ts +213 -0
  108. package/src/agents/development/database.ts +83 -0
  109. package/src/agents/development/debugger.ts +238 -0
  110. package/src/agents/development/devops.ts +86 -0
  111. package/src/agents/development/frontend.ts +85 -0
  112. package/src/agents/development/migration.ts +144 -0
  113. package/src/agents/development/performance.ts +144 -0
  114. package/src/agents/development/refactor.ts +86 -0
  115. package/src/agents/development/reviewer.ts +268 -0
  116. package/src/agents/development/tester.ts +151 -0
  117. package/src/agents/executor.ts +158 -0
  118. package/src/agents/memory/context-manager.ts +171 -0
  119. package/src/agents/memory/decision-logger.ts +160 -0
  120. package/src/agents/memory/knowledge-base.ts +124 -0
  121. package/src/agents/memory/pattern-learner.ts +143 -0
  122. package/src/agents/memory/project-mapper.ts +118 -0
  123. package/src/agents/quality/accessibility.ts +99 -0
  124. package/src/agents/quality/code-quality.ts +115 -0
  125. package/src/agents/quality/compatibility.ts +58 -0
  126. package/src/agents/quality/documentation.ts +105 -0
  127. package/src/agents/quality/error-handling.ts +96 -0
  128. package/src/agents/research/competitor-analyzer.ts +45 -0
  129. package/src/agents/research/cost-analyzer.ts +54 -0
  130. package/src/agents/research/estimator.ts +60 -0
  131. package/src/agents/research/ethics-bias.ts +113 -0
  132. package/src/agents/research/researcher.ts +114 -0
  133. package/src/agents/research/risk-assessor.ts +63 -0
  134. package/src/agents/research/tech-advisor.ts +55 -0
  135. package/src/agents/security/auth.ts +287 -0
  136. package/src/agents/security/dependency-audit.ts +337 -0
  137. package/src/agents/security/penetration.ts +262 -0
  138. package/src/agents/security/privacy.ts +285 -0
  139. package/src/agents/security/scanner.ts +322 -0
  140. package/src/agents/security/secrets.ts +249 -0
  141. package/src/agents/types.ts +66 -0
  142. package/src/agents/workflow/automation.ts +59 -0
  143. package/src/agents/workflow/file-manager.ts +52 -0
  144. package/src/agents/workflow/git-agent.ts +55 -0
  145. package/src/agents/workflow/reporter.ts +51 -0
  146. package/src/agents/workflow/search-agent.ts +40 -0
  147. package/src/agents/workflow/task-coordinator.ts +41 -0
  148. package/src/agents/workflow/task-planner.ts +47 -0
  149. package/src/cli.ts +143 -0
  150. package/src/council/decision-engine.ts +171 -0
  151. package/src/council/devil-advocate.ts +116 -0
  152. package/src/council/index.ts +44 -0
  153. package/src/council/lead-developer.ts +118 -0
  154. package/src/council/legal-compliance.ts +152 -0
  155. package/src/council/product-manager.ts +102 -0
  156. package/src/council/security.ts +172 -0
  157. package/src/council/system-architect.ts +132 -0
  158. package/src/council/types.ts +33 -0
  159. package/src/council/ux-designer.ts +121 -0
  160. package/src/memory/local.ts +305 -0
  161. package/src/memory/schema.ts +174 -0
  162. package/src/memory/sync.ts +274 -0
  163. package/src/router/complexity-scorer.ts +96 -0
  164. package/src/router/context-compressor.ts +74 -0
  165. package/src/router/index.ts +60 -0
  166. package/src/router/learning-updater.ts +271 -0
  167. package/src/router/model-selector.ts +83 -0
  168. package/src/router/rate-monitor.ts +103 -0
  169. package/src/server.ts +1038 -0
  170. package/src/skills/development/skill-api-design.ts +329 -0
  171. package/src/skills/development/skill-auth.ts +271 -0
  172. package/src/skills/development/skill-ci-cd.ts +0 -0
  173. package/src/skills/development/skill-crud.ts +209 -0
  174. package/src/skills/development/skill-db-schema.ts +0 -0
  175. package/src/skills/development/skill-docker.ts +0 -0
  176. package/src/skills/development/skill-env-setup.ts +0 -0
  177. package/src/skills/development/skill-scaffold.ts +323 -0
  178. package/src/skills/intelligence/skill-complexity-score.ts +69 -0
  179. package/src/skills/intelligence/skill-cost-track.ts +39 -0
  180. package/src/skills/intelligence/skill-learning-loop.ts +69 -0
  181. package/src/skills/intelligence/skill-pattern-detect.ts +38 -0
  182. package/src/skills/intelligence/skill-rate-watch.ts +61 -0
  183. package/src/skills/memory/skill-context-compress.ts +98 -0
  184. package/src/skills/memory/skill-cross-sync.ts +104 -0
  185. package/src/skills/memory/skill-decision-log.ts +119 -0
  186. package/src/skills/memory/skill-session-restore.ts +59 -0
  187. package/src/skills/memory/skill-session-save.ts +94 -0
  188. package/src/skills/quality/skill-accessibility.ts +0 -0
  189. package/src/skills/quality/skill-code-review.ts +84 -0
  190. package/src/skills/quality/skill-docs-gen.ts +0 -0
  191. package/src/skills/quality/skill-perf-audit.ts +0 -0
  192. package/src/skills/quality/skill-security-scan.ts +91 -0
  193. package/src/skills/quality/skill-test-suite.ts +290 -0
  194. package/src/skills/workflow/skill-deploy.ts +0 -0
  195. package/src/skills/workflow/skill-git-workflow.ts +0 -0
  196. package/src/skills/workflow/skill-rollback.ts +0 -0
  197. package/src/skills/workflow/skill-task-breakdown.ts +0 -0
  198. package/tsconfig.json +20 -0
@@ -0,0 +1,84 @@
1
+ function detectTarget(task, context) {
2
+ const combined = (task + ' ' + (context ?? '')).toLowerCase();
3
+ if (combined.includes('kubernetes') || combined.includes('k8s') || combined.includes('helm') || combined.includes('pod'))
4
+ return 'kubernetes';
5
+ if (combined.includes('lambda') || combined.includes('serverless') || combined.includes('cloud function') || combined.includes('faas'))
6
+ return 'serverless';
7
+ if (combined.includes('heroku') || combined.includes('render') || combined.includes('railway') || combined.includes('fly.io') || combined.includes('paas'))
8
+ return 'paas';
9
+ if (combined.includes('docker') || combined.includes('container') || combined.includes('compose'))
10
+ return 'docker';
11
+ return 'general';
12
+ }
13
+ const targetApproach = {
14
+ docker: 'Multi-stage Dockerfile to minimise image size, docker-compose for local development with dependent services, GitHub Actions for build-push-deploy pipeline.',
15
+ kubernetes: 'Helm chart per service, resource requests/limits, liveness/readiness probes, HorizontalPodAutoscaler, ConfigMap and Secret management, Ingress with TLS.',
16
+ serverless: 'Serverless Framework or AWS SAM for IaC, per-function IAM roles with least privilege, environment-specific stages, DLQ for failed invocations.',
17
+ paas: 'Environment variables in the platform console (never committed), Procfile or start command, health check route, deployment hooks for migrations.',
18
+ general: 'Containerise with Docker for environment parity. Use a CI/CD pipeline for automated testing and deployment. Manage secrets with a vault, not environment files.',
19
+ };
20
+ export function plan(task, context) {
21
+ const target = detectTarget(task, context);
22
+ return {
23
+ agent: 'devops',
24
+ task,
25
+ tier: 3,
26
+ approach: targetApproach[target],
27
+ steps: [
28
+ 'Write a multi-stage Dockerfile: stage 1 (builder) installs deps and compiles, stage 2 (runtime) copies only the built artefact',
29
+ 'Set a non-root USER in the Dockerfile runtime stage',
30
+ 'Pin the base image to a specific digest, not :latest',
31
+ 'Add .dockerignore to exclude node_modules, .git, and secrets',
32
+ 'Write docker-compose.yml for local development with all dependent services (DB, Redis, etc.)',
33
+ 'Add health checks to compose services so the app only starts when dependencies are ready',
34
+ 'Write the CI pipeline: lint → test → build image → push to registry → deploy',
35
+ 'Use separate environment stages: development, staging, production',
36
+ 'Store secrets in a vault (AWS Secrets Manager, HashiCorp Vault, GitHub Actions secrets) — never in the repo',
37
+ 'Configure rolling deployment or blue/green to achieve zero-downtime deploys',
38
+ 'Add liveness probe (is the process alive?) and readiness probe (can it serve traffic?) to the container',
39
+ 'Set CPU and memory resource requests and limits',
40
+ 'Configure structured logging to stdout — let the orchestrator collect it',
41
+ 'Add a /health endpoint that checks DB connectivity and returns 200 or 503',
42
+ 'Set up alerting on error rate, latency p95, and pod restart count',
43
+ ],
44
+ checklist: [
45
+ '[ ] Dockerfile is multi-stage — runtime image contains no build tools or source code',
46
+ '[ ] Base image pinned to a specific SHA or version tag, not :latest',
47
+ '[ ] Container runs as a non-root user',
48
+ '[ ] .dockerignore excludes node_modules, .git, .env, and secrets',
49
+ '[ ] All secrets loaded from environment variables or a vault — never baked into the image',
50
+ '[ ] CI pipeline runs lint and tests before building the image',
51
+ '[ ] CI pipeline fails the deploy if tests fail',
52
+ '[ ] Docker image scanned for vulnerabilities (trivy or snyk) in CI',
53
+ '[ ] Deployment uses rolling update or blue/green — no downtime on deploy',
54
+ '[ ] Liveness and readiness probes configured',
55
+ '[ ] Resource requests and limits set on all containers',
56
+ '[ ] Structured JSON logging to stdout',
57
+ '[ ] Log retention policy set (no unlimited growth)',
58
+ '[ ] Health check endpoint returns 503 when dependencies are unhealthy',
59
+ '[ ] Alerts configured for error rate > 1% and p95 latency > SLO',
60
+ '[ ] Runbook written for on-call responders',
61
+ ],
62
+ pitfalls: [
63
+ 'Using :latest as the base image tag — breaks reproducibility when the upstream image changes',
64
+ 'Running the container as root — a container escape becomes a root host compromise',
65
+ 'Baking secrets into the image via ENV or COPY — secrets are visible in docker history',
66
+ 'Not adding health checks to compose — the app starts before the database is ready, crashes on first query',
67
+ 'Building the full Docker image in CI without layer caching — 10-minute builds for a one-line change',
68
+ 'Deploying directly to production without a staging environment test — no safety net',
69
+ 'Not setting resource limits — a memory leak can starve all other pods on the node',
70
+ 'Using docker-compose in production — lacks self-healing, scheduling, and scaling capabilities',
71
+ ],
72
+ patterns: [
73
+ 'Multi-stage Docker build (minimise image size)',
74
+ 'Blue/Green deployment (zero-downtime swap)',
75
+ 'Canary release (route small percentage to new version)',
76
+ 'GitOps (declarative infra state tracked in git, applied by Flux/ArgoCD)',
77
+ 'Infrastructure as Code (Terraform, Pulumi, CDK)',
78
+ 'Immutable infrastructure (replace, never patch in place)',
79
+ 'Twelve-Factor App methodology',
80
+ ],
81
+ duration_estimate: '1-2 days',
82
+ };
83
+ }
84
+ //# sourceMappingURL=devops.js.map
@@ -0,0 +1,83 @@
1
+ function detectFrontendType(task, context) {
2
+ const combined = (task + ' ' + (context ?? '')).toLowerCase();
3
+ if (combined.includes('form') || combined.includes('input') || combined.includes('submit') || combined.includes('validation'))
4
+ return 'form';
5
+ if (combined.includes('table') || combined.includes('list') || combined.includes('chart') || combined.includes('dashboard') || combined.includes('grid'))
6
+ return 'data-display';
7
+ if (combined.includes('page') || combined.includes('route') || combined.includes('view') || combined.includes('screen'))
8
+ return 'page';
9
+ if (combined.includes('component') || combined.includes('button') || combined.includes('modal') || combined.includes('dialog') || combined.includes('dropdown'))
10
+ return 'component';
11
+ return 'general';
12
+ }
13
+ const typeApproach = {
14
+ component: 'Define the Props interface first. Implement the static presentational render before adding state. Extract sub-components when the render method exceeds 50 JSX lines. Test each state independently.',
15
+ page: 'Design the page data requirements (what APIs to call), implement data fetching with loading/error/empty states, compose from smaller components. Handle navigation state and deep linking.',
16
+ form: 'Use a form library (react-hook-form or Formik). Define the schema with Zod or Yup. Show inline validation errors. Handle submission loading state and server errors. Ensure keyboard-accessible.',
17
+ 'data-display': 'Fetch data with pagination or virtual scrolling for large datasets. Show skeleton loaders. Handle empty state with a clear call-to-action. Make columns resizable and sortable if applicable.',
18
+ general: 'Design the component tree top-down. Define props interfaces before writing JSX. Add loading, error, and empty states to every data-dependent component.',
19
+ };
20
+ export function plan(task, context) {
21
+ const frontendType = detectFrontendType(task, context);
22
+ return {
23
+ agent: 'frontend',
24
+ task,
25
+ tier: 2,
26
+ approach: typeApproach[frontendType],
27
+ steps: [
28
+ 'Define the Props interface with JSDoc on every prop, including optional vs required',
29
+ 'Identify and define any local state the component manages',
30
+ 'Sketch the component tree — identify which parts should be extracted as sub-components',
31
+ 'Implement the static happy-path render with hardcoded sample data',
32
+ 'Replace sample data with props and verify TypeScript types',
33
+ 'Add loading state — use a skeleton loader, not a spinner for layout-heavy content',
34
+ 'Add error state — show a user-friendly message with a retry action',
35
+ 'Add empty state — show a meaningful prompt when there is no data',
36
+ 'Add useEffect for data fetching or subscriptions, with proper dependency array',
37
+ 'Implement event handlers and form submission logic',
38
+ 'Add ARIA roles, labels, and keyboard navigation for interactive elements',
39
+ 'Test with keyboard only — tab order must be logical',
40
+ 'Apply responsive CSS: mobile-first, then tablet (768px), then desktop (1280px) breakpoints',
41
+ 'Write render tests covering loading, error, empty, and data states',
42
+ 'Profile with React DevTools and memo/useMemo only where profiling shows a real regression',
43
+ ],
44
+ checklist: [
45
+ '[ ] Props interface fully typed and exported',
46
+ '[ ] Default props specified for optional props with sensible defaults',
47
+ '[ ] Loading state uses skeleton loader matching the content layout',
48
+ '[ ] Error state shows user-friendly message with retry button',
49
+ '[ ] Empty state shows message and call-to-action',
50
+ '[ ] No useEffect with stale closure (dependency array complete)',
51
+ '[ ] No state for derived data — compute it from props/state on render',
52
+ '[ ] Interactive elements are keyboard operable',
53
+ '[ ] All images have alt text',
54
+ '[ ] Form inputs have associated <label> elements',
55
+ '[ ] Color is not the only means of conveying information',
56
+ '[ ] Focus is managed correctly when modals open/close',
57
+ '[ ] Component works at 320px mobile width',
58
+ '[ ] Component works at 1440px desktop width',
59
+ '[ ] No inline styles — use CSS modules or styled-components',
60
+ '[ ] Render tests written for all significant states',
61
+ ],
62
+ pitfalls: [
63
+ 'Calling setState inside useEffect with the setState function in the dependency array — infinite re-render loop',
64
+ 'Forgetting the key prop on list items — React silently mismatches DOM elements during reconciliation',
65
+ 'Storing derived data (e.g., filtered list) in state instead of computing it on each render',
66
+ 'Using array index as key when the list can be reordered — causes incorrect component reuse',
67
+ 'Making components too generic too early — premature abstraction adds props nobody uses',
68
+ 'Not handling the loading state — a blank flash before data arrives breaks perceived performance',
69
+ 'useCallback / useMemo without profiling first — adds overhead for no measurable gain',
70
+ 'Forgetting to clean up event listeners, timers, and subscriptions in useEffect return function',
71
+ ],
72
+ patterns: [
73
+ 'Compound component pattern (parent shares state with slotted children)',
74
+ 'Controlled component pattern (props drive state, events propagate up)',
75
+ 'Render props pattern (for cross-cutting component logic)',
76
+ 'Custom hook extraction (move complex effect logic out of the component)',
77
+ 'Container / Presenter split (data fetching vs rendering separation)',
78
+ 'Skeleton loader pattern (avoid layout shift on load)',
79
+ ],
80
+ duration_estimate: frontendType === 'page' ? '4-8 hours' : '2-4 hours',
81
+ };
82
+ }
83
+ //# sourceMappingURL=frontend.js.map
@@ -0,0 +1,141 @@
1
+ function detectMigrationType(task, context) {
2
+ const combined = (task + ' ' + (context ?? '')).toLowerCase();
3
+ if (combined.includes('zero downtime') || combined.includes('blue-green') || combined.includes('rolling') || combined.includes('live migration'))
4
+ return 'zero-downtime';
5
+ if (combined.includes('data migration') || combined.includes('backfill') || combined.includes('etl') || combined.includes('transform data'))
6
+ return 'data';
7
+ if (combined.includes('platform') || combined.includes('cloud') || combined.includes('aws') || combined.includes('gcp') || combined.includes('azure') || combined.includes('move'))
8
+ return 'platform';
9
+ if (combined.includes('schema') || combined.includes('column') || combined.includes('table') || combined.includes('database') || combined.includes('alter'))
10
+ return 'schema';
11
+ return 'general';
12
+ }
13
+ const typeApproach = {
14
+ schema: 'Expand-Migrate-Contract pattern: first add new columns as nullable (backward compatible), then backfill, then add constraints, then remove old columns. Each phase is a separate deployment.',
15
+ data: 'Write idempotent backfill scripts that can be re-run safely. Process in batches of 1000-10000 rows to avoid locking. Verify row counts before and after. Keep the original data until verified.',
16
+ platform: 'Run old and new platforms in parallel. Migrate traffic gradually (10% → 50% → 100%). Maintain rollback capability at each step. Verify data consistency between platforms before cutover.',
17
+ 'zero-downtime': 'Decouple schema changes from code changes. Make schema additive first. Deploy code that supports both old and new schema. Then migrate schema. Then deploy code that requires new schema only.',
18
+ general: 'Always take a backup before migrating. Test the migration on a staging environment with production-volume data. Plan and rehearse the rollback procedure before starting.',
19
+ };
20
+ const typeSteps = {
21
+ schema: [
22
+ 'Take a full database backup and verify it is restorable',
23
+ 'Analyse the table size — migrations on large tables require extra care',
24
+ 'Write the expansion migration: add new nullable columns or tables (no data changes)',
25
+ 'Deploy the expansion migration to staging and verify with EXPLAIN on common queries',
26
+ 'Deploy the expansion migration to production — additive changes are safe and fast',
27
+ 'Write the application code that writes to both old and new columns simultaneously',
28
+ 'Deploy the dual-write code to production',
29
+ 'Write the backfill script: UPDATE new_column = derive(old_column) WHERE new_column IS NULL LIMIT 10000',
30
+ 'Run the backfill in batches during low-traffic hours, monitoring DB load',
31
+ 'Verify: SELECT COUNT(*) WHERE new_column IS NULL — should return 0',
32
+ 'Deploy code that reads from new columns only',
33
+ 'Write the contract migration: add NOT NULL constraint, create indexes, drop old columns',
34
+ 'Deploy the contract migration to production during a maintenance window',
35
+ 'Verify application health and run smoke tests',
36
+ ],
37
+ data: [
38
+ 'Define the transformation logic and document the expected output for a sample of rows',
39
+ 'Write the backfill script as an idempotent operation (re-running it produces the same result)',
40
+ 'Test the script on 100 rows in staging and manually verify the output',
41
+ 'Measure the script execution time on staging at full data volume',
42
+ 'Schedule the production backfill during the lowest-traffic window',
43
+ 'Process in batches: use LIMIT + WHERE id > last_processed_id to paginate',
44
+ 'Add a progress counter — log every N rows processed',
45
+ 'Monitor DB CPU, lock waits, and replication lag during the backfill',
46
+ 'Pause the script automatically if replication lag exceeds a threshold',
47
+ 'Verify row counts: SELECT COUNT(*) before and after should balance',
48
+ 'Spot-check 10-20 randomly selected rows — manual verification of the transformation',
49
+ 'Keep the original data in the source columns or a backup table until fully verified',
50
+ 'Archive or drop the source data only after a defined hold period (e.g., 30 days)',
51
+ ],
52
+ platform: [
53
+ 'Document all dependencies of the current platform (databases, queues, external services)',
54
+ 'Set up the new platform environment with identical configuration',
55
+ 'Migrate all secrets and configuration to the new platform\'s secrets manager',
56
+ 'Deploy the application to the new platform and run full integration tests',
57
+ 'Set up a data sync from old to new platform (replication or CDC with Debezium)',
58
+ 'Route 5% of production traffic to the new platform and monitor error rates',
59
+ 'Compare metrics between old and new platform over 24 hours',
60
+ 'Increase traffic to 25%, 50%, 75%, 100% with monitoring gates at each step',
61
+ 'When at 100%, stop new writes to the old platform and verify replication caught up',
62
+ 'Run a final data consistency check between old and new platform',
63
+ 'Update DNS/load balancer to point exclusively to new platform',
64
+ 'Keep the old platform running for 7 days as a rollback option',
65
+ 'Decommission the old platform after the hold period',
66
+ ],
67
+ 'zero-downtime': [
68
+ 'Identify all schema changes needed and classify each as additive (safe) or destructive (requires care)',
69
+ 'Phase 1 — Expansion: add new tables and nullable columns without removing anything',
70
+ 'Deploy Phase 1 migration — no code change needed, old code still works',
71
+ 'Phase 2 — Compatibility code: deploy app code that writes to old and new columns, reads from new if available',
72
+ 'Verify Phase 2 is working correctly in staging for 24+ hours',
73
+ 'Phase 3 — Backfill: run idempotent backfill to populate new columns from old data',
74
+ 'Verify backfill completeness: zero rows with NULL in new columns',
75
+ 'Phase 4 — New code: deploy app code that reads exclusively from new columns',
76
+ 'Monitor for 24 hours — check error rates and data correctness',
77
+ 'Phase 5 — Contract: add NOT NULL constraints, create indexes, drop old columns',
78
+ 'Verify final state with integration tests and manual spot-checks',
79
+ 'Document the completed migration and update the schema documentation',
80
+ ],
81
+ general: [
82
+ 'Take a full backup of all data involved in the migration',
83
+ 'Verify the backup is restorable by doing a test restore on a separate instance',
84
+ 'Write the migration script and test it thoroughly on staging',
85
+ 'Test the rollback procedure on staging — confirm you can undo the migration',
86
+ 'Calculate the expected execution time at production data volume',
87
+ 'Plan the maintenance window if downtime is required',
88
+ 'Communicate the migration plan and timeline to stakeholders',
89
+ 'Execute the migration and monitor closely',
90
+ 'Run smoke tests immediately after migration',
91
+ 'Monitor for 24-48 hours before declaring success',
92
+ 'Document lessons learned',
93
+ ],
94
+ };
95
+ export function plan(task, context) {
96
+ const migrationType = detectMigrationType(task, context);
97
+ return {
98
+ agent: 'migration',
99
+ task,
100
+ tier: 3,
101
+ approach: typeApproach[migrationType],
102
+ steps: typeSteps[migrationType],
103
+ checklist: [
104
+ '[ ] Full backup taken and restore tested before starting',
105
+ '[ ] Migration tested on staging with production data volume',
106
+ '[ ] Rollback procedure written, tested, and rehearsed',
107
+ '[ ] Execution time estimated at production scale',
108
+ '[ ] Stakeholders notified of migration plan and timeline',
109
+ '[ ] Backfill script is idempotent — safe to re-run on failure',
110
+ '[ ] Backfill processes in batches — no single query that locks the whole table',
111
+ '[ ] Replication lag monitored during migration',
112
+ '[ ] Row counts verified before and after migration',
113
+ '[ ] Smoke tests pass immediately after migration',
114
+ '[ ] Application metrics (error rate, latency) normal after migration',
115
+ '[ ] Old data retained for a defined hold period before deletion',
116
+ '[ ] Schema documentation updated',
117
+ '[ ] Post-migration review scheduled for 48 hours after cutover',
118
+ ],
119
+ pitfalls: [
120
+ 'Running ALTER TABLE on a large table without ALGORITHM=INPLACE or pg_rewrite — locks the table for minutes and causes downtime',
121
+ 'Not testing the rollback — every migration plan needs a verified rollback procedure',
122
+ 'Backfilling without batching — a single UPDATE affecting millions of rows holds a table lock for minutes',
123
+ 'Migrating production without staging validation — staging exists for this purpose',
124
+ 'Not monitoring replication lag during the migration — a lagging replica causes stale reads',
125
+ 'Removing the old columns before the application is fully migrated to the new columns',
126
+ 'Skipping the data verification step — corrupted data may not surface for days',
127
+ 'Under-estimating the time at production data volume — test with realistic row counts',
128
+ ],
129
+ patterns: [
130
+ 'Expand-Migrate-Contract pattern (safe schema evolution)',
131
+ 'Dual-write pattern (write to old and new during transition)',
132
+ 'Strangler Fig pattern (gradually replace old system with new)',
133
+ 'Blue/Green deployment (parallel environments for zero-downtime cutover)',
134
+ 'Change Data Capture (CDC) for live platform migrations',
135
+ 'Idempotent migration scripts (safe to re-run)',
136
+ 'Feature flag gating (roll out new schema reading gradually)',
137
+ ],
138
+ duration_estimate: '2-5 days',
139
+ };
140
+ }
141
+ //# sourceMappingURL=migration.js.map
@@ -0,0 +1,142 @@
1
+ function detectDomain(task, context) {
2
+ const combined = (task + ' ' + (context ?? '')).toLowerCase();
3
+ if (combined.includes('database') || combined.includes('query') || combined.includes('sql') || combined.includes('slow query') || combined.includes('n+1'))
4
+ return 'database';
5
+ if (combined.includes('network') || combined.includes('latency') || combined.includes('bandwidth') || combined.includes('api') || combined.includes('http'))
6
+ return 'network';
7
+ if (combined.includes('cpu') || combined.includes('algorithm') || combined.includes('computation') || combined.includes('big-o') || combined.includes('loop'))
8
+ return 'cpu';
9
+ if (combined.includes('memory') || combined.includes('ram') || combined.includes('heap') || combined.includes('leak') || combined.includes('gc'))
10
+ return 'memory';
11
+ if (combined.includes('frontend') || combined.includes('render') || combined.includes('fcp') || combined.includes('lcp') || combined.includes('cls') || combined.includes('bundle'))
12
+ return 'frontend';
13
+ return 'general';
14
+ }
15
+ const domainApproach = {
16
+ database: 'Profile slow queries with EXPLAIN ANALYZE. Eliminate N+1 patterns. Add missing indexes. Implement query result caching. Consider read replicas for read-heavy workloads.',
17
+ network: 'Measure with real network traces (HAR file, curl --trace). Enable HTTP/2. Add connection pooling. Implement response compression. Use CDN for static assets. Cache at the edge.',
18
+ cpu: 'Profile with clinic.js or perf_hooks to find the hotspot. Check algorithm complexity — O(n²) over thousands of items is always the first target. Move heavy computation off the event loop (worker threads).',
19
+ memory: 'Take heap snapshots to identify retained objects. Implement LRU eviction on all caches. Remove event listeners on cleanup. Bound queue and buffer sizes. Configure GC flags for the workload.',
20
+ frontend: 'Measure Core Web Vitals (LCP, FID, CLS) with Lighthouse. Code-split by route. Lazy-load off-screen images. Tree-shake dependencies. Remove render-blocking scripts. Implement service worker caching.',
21
+ general: 'Establish a baseline measurement before optimising. Use a profiler to identify the actual bottleneck — never optimise by intuition. Fix one thing at a time and re-measure after each change.',
22
+ };
23
+ export function plan(task, context) {
24
+ const domain = detectDomain(task, context);
25
+ const domainSteps = {
26
+ database: [
27
+ 'Enable query logging and collect the 10 slowest queries over a representative time window',
28
+ 'Run EXPLAIN ANALYZE on each slow query — read the execution plan top to bottom',
29
+ 'Identify sequential scans on large tables — these are the highest-priority index candidates',
30
+ 'Add indexes for missing JOIN columns, frequent WHERE filters, and ORDER BY columns',
31
+ 'Detect N+1 queries by counting DB calls per HTTP request (use a query counter middleware)',
32
+ 'Fix N+1 by using JOIN, eager loading (include in ORM), or DataLoader batching',
33
+ 'Implement query result caching for expensive read-only queries (Redis, in-memory LRU)',
34
+ 'Review ORM-generated SQL — ORMs frequently produce inefficient queries',
35
+ 'Set statement_timeout to prevent runaway queries from blocking the connection pool',
36
+ 'Consider read replicas for analytics queries that do not need fresh data',
37
+ 'Benchmark before and after with a realistic data volume (not an empty dev database)',
38
+ ],
39
+ network: [
40
+ 'Capture a HAR file from the browser or use curl --trace for API calls',
41
+ 'Measure Time to First Byte (TTFB) — high TTFB means server-side is slow',
42
+ 'Enable HTTP/2 — multiplexes requests over a single connection',
43
+ 'Enable Brotli or gzip compression on all text responses',
44
+ 'Implement cache-control headers for static assets (immutable for hashed files)',
45
+ 'Move static assets to a CDN geographically close to users',
46
+ 'Reduce payload size — paginate, select only needed fields, avoid sending unused data',
47
+ 'Implement connection pooling for HTTP clients making outbound requests',
48
+ 'Add keep-alive headers to reuse TCP connections',
49
+ 'Measure DNS lookup time — use DNS prefetching for known third-party domains',
50
+ 'Benchmark with Apache Benchmark or k6 at realistic concurrency levels',
51
+ ],
52
+ cpu: [
53
+ 'Run clinic.js flame or Node.js --prof to identify the CPU hotspot',
54
+ 'Analyse the flame graph — find the widest block (most self-time)',
55
+ 'Check the algorithm complexity of the hotspot — is it O(n²) over a large input?',
56
+ 'Replace O(n²) nested loops with O(n) approaches using hash maps or sorting',
57
+ 'Move CPU-heavy synchronous work to a worker thread pool (piscina)',
58
+ 'Cache the results of deterministic expensive computations (memoisation)',
59
+ 'Avoid creating large temporary arrays in hot paths — reuse buffers',
60
+ 'Use Buffer.allocUnsafe() instead of Buffer.alloc() where the content is immediately overwritten',
61
+ 'Profile again after the fix — confirm the hotspot is gone, not just moved',
62
+ 'Add a performance regression test that benchmarks the fixed function',
63
+ ],
64
+ memory: [
65
+ 'Take a heap snapshot with Chrome DevTools or --heapsnapshot-signal before the test',
66
+ 'Run the operation that causes the memory growth',
67
+ 'Take a second heap snapshot and use the Comparison view to find new retained objects',
68
+ 'Identify the shortest GC root path to the retained objects',
69
+ 'Find all unbounded caches and add LRU eviction (lru-cache npm package)',
70
+ 'Audit all EventEmitter.on() calls — ensure off() is called in cleanup',
71
+ 'Find all setInterval and setTimeout and ensure clearInterval/clearTimeout in cleanup',
72
+ 'Check for closures that capture large objects unnecessarily',
73
+ 'Set --max-old-space-size appropriately for the container memory limit',
74
+ 'Monitor heap usage in production with process.memoryUsage() sent to metrics',
75
+ 'Take a third heap snapshot after the fix to verify retention is resolved',
76
+ ],
77
+ frontend: [
78
+ 'Run Lighthouse on the production URL and record the Core Web Vitals baseline',
79
+ 'Fix Largest Contentful Paint (LCP) — preload the hero image, avoid render-blocking CSS/JS',
80
+ 'Fix Cumulative Layout Shift (CLS) — reserve space for images and ads with width/height attributes',
81
+ 'Fix First Input Delay / Interaction to Next Paint — break up long tasks (> 50ms) on the main thread',
82
+ 'Implement route-based code splitting with dynamic import()',
83
+ 'Lazy-load images below the fold with loading="lazy" or IntersectionObserver',
84
+ 'Audit the JavaScript bundle with webpack-bundle-analyzer or vite-bundle-visualizer',
85
+ 'Remove unused dependencies — check import cost of each third-party library',
86
+ 'Tree-shake lodash — import { debounce } from \'lodash\' not import _ from \'lodash\'',
87
+ 'Implement service worker caching for repeat visits (Workbox)',
88
+ 'Serve next-gen image formats (WebP, AVIF) with <picture> fallback',
89
+ 'Measure again with Lighthouse after each change — confirm improvement',
90
+ ],
91
+ general: [
92
+ 'Establish a baseline — measure latency (p50, p95, p99), throughput (rps), CPU, and memory',
93
+ 'Use a profiler appropriate to the stack — clinic.js, Pyspy, JProfiler, pprof',
94
+ 'Identify the single largest bottleneck — fix that first before anything else',
95
+ 'Check for database query issues (N+1, missing indexes, full table scans)',
96
+ 'Check for algorithmic complexity issues (O(n²) loops)',
97
+ 'Check for I/O blocking the event loop (synchronous file/network reads)',
98
+ 'Check for memory pressure causing GC pauses',
99
+ 'Fix one bottleneck at a time and re-measure after each change',
100
+ 'Add performance regression tests to CI (k6, autocannon, benchmark.js)',
101
+ 'Document the improvement with before/after numbers',
102
+ ],
103
+ };
104
+ return {
105
+ agent: 'performance',
106
+ task,
107
+ tier: 3,
108
+ approach: domainApproach[domain],
109
+ steps: domainSteps[domain],
110
+ checklist: [
111
+ '[ ] Baseline measurements recorded (p50/p95/p99 latency, throughput, CPU, memory)',
112
+ '[ ] Profiler run — bottleneck identified, not assumed',
113
+ '[ ] Highest-impact bottleneck fixed first',
114
+ '[ ] No N+1 query patterns in the hot path',
115
+ '[ ] All caches have a maximum size and eviction policy',
116
+ '[ ] No synchronous blocking I/O in async code paths',
117
+ '[ ] Algorithm complexity reviewed — no O(n²) over large inputs',
118
+ '[ ] Post-fix measurement confirms improvement',
119
+ '[ ] Performance regression test added to CI',
120
+ '[ ] Improvement documented with before/after numbers',
121
+ ],
122
+ pitfalls: [
123
+ 'Optimising before profiling — wastes hours on non-bottlenecks',
124
+ 'Caching without an eviction strategy — trades a performance problem for a memory leak',
125
+ 'Fixing the wrong layer — optimising the API handler when the bottleneck is the database',
126
+ 'Measuring on a development machine with a tiny dataset — results do not reflect production',
127
+ 'Parallelising I/O without a concurrency limit — overwhelms the downstream service and causes cascading failure',
128
+ 'Trusting microbenchmarks for macro performance — benchmark the real workload, not a toy example',
129
+ ],
130
+ patterns: [
131
+ 'Memoisation (cache pure function results)',
132
+ 'Lazy evaluation (compute on demand, not upfront)',
133
+ 'Connection pooling (reuse expensive connections)',
134
+ 'Read-through cache (populate cache on miss, serve from cache on hit)',
135
+ 'Worker thread pool (offload CPU work from the event loop)',
136
+ 'Pagination and cursor-based pagination (bound response size)',
137
+ 'Index-only queries (cover all needed columns in the index)',
138
+ ],
139
+ duration_estimate: '4-8 hours',
140
+ };
141
+ }
142
+ //# sourceMappingURL=performance.js.map
@@ -0,0 +1,85 @@
1
+ function detectFocus(task, context) {
2
+ const combined = (task + ' ' + (context ?? '')).toLowerCase();
3
+ if (combined.includes('complex') || combined.includes('nesting') || combined.includes('long function') || combined.includes('spaghetti'))
4
+ return 'complexity';
5
+ if (combined.includes('duplicat') || combined.includes('copy') || combined.includes('repeat') || combined.includes('dry'))
6
+ return 'duplication';
7
+ if (combined.includes('naming') || combined.includes('rename') || combined.includes('readab'))
8
+ return 'naming';
9
+ if (combined.includes('architect') || combined.includes('layer') || combined.includes('module') || combined.includes('structure'))
10
+ return 'architecture';
11
+ if (combined.includes('type') || combined.includes('any') || combined.includes('typescript') || combined.includes('interface'))
12
+ return 'types';
13
+ return 'general';
14
+ }
15
+ const focusApproach = {
16
+ complexity: 'Identify the most complex functions first using cyclomatic complexity metrics. Extract sub-functions, apply guard clauses, replace conditionals with polymorphism, reduce nesting step by step.',
17
+ duplication: 'Find all duplicated logic using diff tools or manual inspection. Extract to a shared utility/hook/module. Parameterise differences. Verify all callers still work after consolidation.',
18
+ naming: 'Rename systematically using IDE refactoring tools, not text-replace. Start with the most confusing names. Add JSDoc where a name alone is insufficient. Update all references atomically.',
19
+ architecture: 'Diagram the current structure, identify coupling hotspots, define the target architecture, then migrate incrementally with an anti-corruption layer during transition.',
20
+ types: 'Eliminate all implicit any types by enabling TypeScript strict mode. Define precise interfaces for all data shapes. Replace type assertions with proper narrowing. Add runtime validation at boundaries.',
21
+ general: 'Apply the Boy Scout Rule: leave the code cleaner than you found it. Identify the highest-impact improvement (complexity, duplication, naming, or architecture) and address it first.',
22
+ };
23
+ export function plan(task, context) {
24
+ const focus = detectFocus(task, context);
25
+ return {
26
+ agent: 'refactor',
27
+ task,
28
+ tier: 2,
29
+ approach: focusApproach[focus],
30
+ steps: [
31
+ 'Run the full test suite and record the baseline — all tests must pass before and after',
32
+ 'Identify code smells: long functions, deep nesting, duplicated logic, primitive obsession, feature envy',
33
+ 'Prioritise by impact — fix the highest-complexity or most-duplicated code first',
34
+ 'Add missing tests for code that lacks coverage before refactoring it',
35
+ 'Apply extract function refactoring to any function longer than 30 lines',
36
+ 'Apply guard clauses (early returns) to reduce nesting depth',
37
+ 'Extract magic numbers and strings to named constants',
38
+ 'Rename variables and functions to be self-documenting — eliminate abbreviations',
39
+ 'Consolidate duplicated logic into shared utilities or base classes',
40
+ 'Remove dead code — if it is not tested and not called, delete it',
41
+ 'Apply TypeScript strict improvements — eliminate any, add precise types',
42
+ 'Run the linter and formatter after each logical change',
43
+ 'Run the full test suite again — compare with baseline, all tests must pass',
44
+ 'Review the diff — if a single commit is too large, split into atomic changes',
45
+ ],
46
+ checklist: [
47
+ '[ ] All tests pass before starting refactoring',
48
+ '[ ] All tests still pass after each refactoring step',
49
+ '[ ] No function exceeds 30 lines of executable code after refactoring',
50
+ '[ ] Nesting depth reduced to maximum 3 levels',
51
+ '[ ] All magic numbers replaced with named constants',
52
+ '[ ] No duplicated code blocks (copy-paste > 5 lines)',
53
+ '[ ] All variables and functions have descriptive names',
54
+ '[ ] No implicit any types remain',
55
+ '[ ] Dead code removed (unused functions, imports, variables)',
56
+ '[ ] Linter passes with zero warnings',
57
+ '[ ] Code coverage not reduced by the refactoring',
58
+ '[ ] Each commit is a single atomic refactoring step',
59
+ '[ ] Public API is unchanged (or version-bumped if breaking)',
60
+ '[ ] Complexity metrics improved — measure before and after',
61
+ ],
62
+ pitfalls: [
63
+ 'Refactoring without tests — you will not know if you broke something',
64
+ 'Big-bang refactoring in one commit — impossible to review, high merge conflict risk',
65
+ 'Renaming without IDE refactoring tools — misses call sites, creates runtime bugs',
66
+ 'Extracting a function that is only called once without a clear abstraction reason',
67
+ 'Changing behaviour while refactoring — refactoring must be semantics-preserving',
68
+ 'Removing code that looks unused but is called via dynamic reflection or eval',
69
+ 'Over-abstracting — a third function extracted for two call sites adds indirection without clarity',
70
+ ],
71
+ patterns: [
72
+ 'Extract Function (Fowler refactoring catalogue)',
73
+ 'Replace Conditional with Polymorphism',
74
+ 'Guard Clause (replace nested conditionals with early returns)',
75
+ 'Introduce Parameter Object (replace long parameter lists)',
76
+ 'Replace Magic Number with Symbolic Constant',
77
+ 'Move Function (reduce feature envy)',
78
+ 'Inline Variable (remove unnecessary variable aliases)',
79
+ 'Decompose Conditional',
80
+ 'Consolidate Duplicate Conditional Fragments',
81
+ ],
82
+ duration_estimate: focus === 'architecture' ? '1-3 days' : '2-6 hours',
83
+ };
84
+ }
85
+ //# sourceMappingURL=refactor.js.map