berget 2.2.4 → 2.2.6

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 (44) hide show
  1. package/.github/workflows/publish.yml +2 -2
  2. package/.github/workflows/test.yml +1 -1
  3. package/dist/package.json +3 -1
  4. package/dist/src/commands/code/__tests__/fake-command-runner.js +52 -0
  5. package/dist/src/commands/code/__tests__/fake-file-store.js +46 -0
  6. package/dist/src/commands/code/__tests__/fake-prompter.js +91 -0
  7. package/dist/src/commands/code/__tests__/setup-flow.test.js +238 -0
  8. package/dist/src/commands/code/adapters/clack-prompter.js +71 -0
  9. package/dist/src/commands/code/adapters/fs-file-store.js +75 -0
  10. package/dist/src/commands/code/adapters/spawn-command-runner.js +49 -0
  11. package/dist/src/commands/code/errors.js +27 -0
  12. package/dist/src/commands/code/ports/command-runner.js +2 -0
  13. package/dist/src/commands/code/ports/file-store.js +2 -0
  14. package/dist/src/commands/code/ports/prompter.js +2 -0
  15. package/dist/src/commands/code/setup.js +392 -0
  16. package/dist/src/commands/code.js +189 -633
  17. package/dist/src/constants/command-structure.js +2 -0
  18. package/dist/tests/commands/code.test.js +31 -0
  19. package/dist/tests/utils/opencode-validator.test.js +15 -14
  20. package/package.json +3 -1
  21. package/src/commands/code/__tests__/fake-command-runner.ts +47 -0
  22. package/src/commands/code/__tests__/fake-file-store.ts +35 -0
  23. package/src/commands/code/__tests__/fake-prompter.ts +83 -0
  24. package/src/commands/code/__tests__/setup-flow.test.ts +274 -0
  25. package/src/commands/code/adapters/clack-prompter.ts +43 -0
  26. package/src/commands/code/adapters/fs-file-store.ts +33 -0
  27. package/src/commands/code/adapters/spawn-command-runner.ts +36 -0
  28. package/src/commands/code/errors.ts +23 -0
  29. package/src/commands/code/ports/command-runner.ts +6 -0
  30. package/src/commands/code/ports/file-store.ts +6 -0
  31. package/src/commands/code/ports/prompter.ts +23 -0
  32. package/src/commands/code/setup.ts +402 -0
  33. package/src/commands/code.ts +211 -748
  34. package/src/constants/command-structure.ts +3 -0
  35. package/templates/agents/app.md +22 -0
  36. package/templates/agents/backend.md +22 -0
  37. package/templates/agents/devops.md +28 -0
  38. package/templates/agents/frontend.md +24 -0
  39. package/templates/agents/fullstack.md +22 -0
  40. package/templates/agents/quality.md +64 -0
  41. package/templates/agents/security.md +20 -0
  42. package/tests/commands/code.test.ts +47 -0
  43. package/tests/utils/opencode-validator.test.ts +16 -15
  44. package/opencode.json +0 -146
@@ -3,11 +3,11 @@ import chalk from 'chalk'
3
3
  import readline from 'readline'
4
4
  import { COMMAND_GROUPS, SUBCOMMANDS } from '../constants/command-structure'
5
5
  import { handleError } from '../utils/error-handler'
6
+ import { runSetupCommand } from './code/setup'
6
7
  import * as fs from 'fs'
7
8
  import { readFile, writeFile } from 'fs/promises'
8
9
  import path from 'path'
9
10
  import { spawn } from 'child_process'
10
- import { createAuthenticatedClient } from '../client'
11
11
 
12
12
  /**
13
13
  * Check if current directory has git
@@ -20,138 +20,6 @@ function hasGit(): boolean {
20
20
  }
21
21
  }
22
22
 
23
- /**
24
- * Merge opencode configurations using chat completions API
25
- */
26
- async function mergeConfigurations(
27
- currentConfig: any,
28
- latestConfig: any
29
- ): Promise<any> {
30
- try {
31
- const client = createAuthenticatedClient()
32
-
33
- console.log(chalk.blue('šŸ¤– Using AI to merge configurations...'))
34
-
35
- const mergePrompt = `You are a configuration merge specialist. Merge these two OpenCode configurations:
36
-
37
- CURRENT CONFIG (user's customizations):
38
- ${JSON.stringify(currentConfig, null, 2)}
39
-
40
- LATEST CONFIG (new updates):
41
- ${JSON.stringify(latestConfig, null, 2)}
42
-
43
- Merge rules:
44
- 1. Preserve ALL user customizations from current config
45
- 2. Add ALL new features and improvements from latest config
46
- 3. For conflicts, prefer user's customizations but add new latest features
47
- 4. Maintain valid JSON structure
48
- 5. Keep the merged configuration complete and functional
49
-
50
- Return ONLY the merged JSON configuration, no explanations.`
51
-
52
- const response = await client.POST('/v1/chat/completions', {
53
- body: {
54
- model: 'glm-4.7',
55
- messages: [
56
- {
57
- role: 'user',
58
- content: mergePrompt,
59
- },
60
- ],
61
- temperature: 0.1,
62
- max_tokens: 8000,
63
- },
64
- })
65
-
66
- if (response.error) {
67
- console.warn(chalk.yellow('āš ļø AI merge failed, using fallback merge'))
68
- return fallbackMerge(currentConfig, latestConfig)
69
- }
70
-
71
- const content = response.data?.choices?.[0]?.message?.content
72
- if (!content) {
73
- console.warn(chalk.yellow('āš ļø No AI response, using fallback merge'))
74
- return fallbackMerge(currentConfig, latestConfig)
75
- }
76
-
77
- try {
78
- const mergedConfig = JSON.parse(content.trim())
79
- console.log(chalk.green('āœ“ AI merge completed successfully'))
80
- return mergedConfig
81
- } catch (parseError) {
82
- console.warn(
83
- chalk.yellow('āš ļø AI response invalid, using fallback merge')
84
- )
85
- return fallbackMerge(currentConfig, latestConfig)
86
- }
87
- } catch (error) {
88
- console.warn(chalk.yellow('āš ļø AI merge unavailable, using fallback merge'))
89
- return fallbackMerge(currentConfig, latestConfig)
90
- }
91
- }
92
-
93
- /**
94
- * Fallback merge logic when AI merge is unavailable
95
- */
96
- function fallbackMerge(currentConfig: any, latestConfig: any): any {
97
- console.log(chalk.blue('šŸ”€ Using fallback merge logic...'))
98
-
99
- const merged = { ...latestConfig }
100
-
101
- // Preserve user customizations
102
- if (currentConfig.theme && currentConfig.theme !== latestConfig.theme) {
103
- merged.theme = currentConfig.theme
104
- }
105
-
106
- if (currentConfig.share && currentConfig.share !== latestConfig.share) {
107
- merged.share = currentConfig.share
108
- }
109
-
110
- // Merge custom agents while preserving new ones
111
- if (currentConfig.agent) {
112
- merged.agent = { ...latestConfig.agent }
113
-
114
- // Add any custom agents from current config
115
- Object.keys(currentConfig.agent).forEach((agentName) => {
116
- if (!latestConfig.agent[agentName]) {
117
- merged.agent[agentName] = currentConfig.agent[agentName]
118
- console.log(chalk.cyan(` • Preserved custom agent: ${agentName}`))
119
- }
120
- })
121
- }
122
-
123
- // Merge custom commands while preserving new ones
124
- if (currentConfig.commands) {
125
- merged.commands = { ...latestConfig.commands }
126
-
127
- Object.keys(currentConfig.commands).forEach((commandName) => {
128
- if (!latestConfig.commands[commandName]) {
129
- merged.commands[commandName] = currentConfig.commands[commandName]
130
- console.log(chalk.cyan(` • Preserved custom command: ${commandName}`))
131
- }
132
- })
133
- }
134
-
135
- // Preserve custom provider settings if user has modified them
136
- if (currentConfig.provider) {
137
- merged.provider = { ...latestConfig.provider }
138
-
139
- // Deep merge provider settings
140
- Object.keys(currentConfig.provider).forEach((providerName) => {
141
- if (merged.provider[providerName]) {
142
- merged.provider[providerName] = {
143
- ...merged.provider[providerName],
144
- ...currentConfig.provider[providerName],
145
- }
146
- } else {
147
- merged.provider[providerName] = currentConfig.provider[providerName]
148
- }
149
- })
150
- }
151
-
152
- return merged
153
- }
154
-
155
23
  /**
156
24
  * Helper function to get user confirmation
157
25
  */
@@ -177,47 +45,6 @@ async function confirm(question: string, autoYes = false): Promise<boolean> {
177
45
  })
178
46
  }
179
47
 
180
- /**
181
- * Helper function to get user choice from options
182
- */
183
- async function askChoice(
184
- question: string,
185
- options: string[],
186
- defaultChoice?: string
187
- ): Promise<string> {
188
- return new Promise((resolve) => {
189
- const rl = readline.createInterface({
190
- input: process.stdin,
191
- output: process.stdout,
192
- })
193
-
194
- rl.question(question, (answer) => {
195
- rl.close()
196
-
197
- const trimmed = answer.trim().toLowerCase()
198
-
199
- // Handle numeric input (1, 2, etc.)
200
- const numericIndex = parseInt(trimmed) - 1
201
- if (numericIndex >= 0 && numericIndex < options.length) {
202
- resolve(options[numericIndex])
203
- return
204
- }
205
-
206
- // Handle text input
207
- const matchingOption = options.find((option) =>
208
- option.toLowerCase().startsWith(trimmed)
209
- )
210
-
211
- if (matchingOption) {
212
- resolve(matchingOption)
213
- } else if (defaultChoice) {
214
- resolve(defaultChoice)
215
- } else {
216
- resolve(options[0]) // Default to first option
217
- }
218
- })
219
- })
220
- }
221
48
 
222
49
  /**
223
50
  * Helper function to get user input
@@ -262,84 +89,95 @@ function getProjectName(): string {
262
89
  }
263
90
 
264
91
  /**
265
- * Load the latest agent configuration from embedded config
92
+ * Get the path to the bundled agent templates directory
93
+ */
94
+ function getAgentTemplatesDir(): string {
95
+ return path.resolve(__dirname, '../../templates/agents')
96
+ }
97
+
98
+ /**
99
+ * Parse a markdown agent file with YAML frontmatter into an agent config object
100
+ */
101
+ function parseAgentMarkdown(content: string): Record<string, any> {
102
+ const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/)
103
+ if (!frontmatterMatch) {
104
+ throw new Error('Invalid agent markdown: missing frontmatter')
105
+ }
106
+
107
+ const yamlStr = frontmatterMatch[1]
108
+ const promptBody = frontmatterMatch[2].trim()
109
+
110
+ const config: Record<string, any> = { prompt: promptBody }
111
+
112
+ for (const line of yamlStr.split('\n')) {
113
+ const trimmed = line.trim()
114
+ if (!trimmed || trimmed.startsWith('#')) continue
115
+
116
+ const colonIdx = trimmed.indexOf(':')
117
+ if (colonIdx === -1) continue
118
+
119
+ const key = trimmed.substring(0, colonIdx).trim()
120
+ const value = trimmed.substring(colonIdx + 1).trim()
121
+
122
+ if (key === 'permission') continue
123
+
124
+ if (value === 'true') {
125
+ config[key] = true
126
+ } else if (value === 'false') {
127
+ config[key] = false
128
+ } else if (!isNaN(Number(value)) && value !== '') {
129
+ config[key] = Number(value)
130
+ } else {
131
+ config[key] = value
132
+ }
133
+ }
134
+
135
+ const permission: Record<string, string> = {}
136
+ const permMatch = yamlStr.match(/permission:\s*\n((?:\s+\w+:.*\n?)*)/)
137
+ if (permMatch) {
138
+ for (const permLine of permMatch[1].split('\n')) {
139
+ const permTrimmed = permLine.trim()
140
+ if (!permTrimmed) continue
141
+ const permColonIdx = permTrimmed.indexOf(':')
142
+ if (permColonIdx === -1) continue
143
+ const permKey = permTrimmed.substring(0, permColonIdx).trim()
144
+ const permValue = permTrimmed.substring(permColonIdx + 1).trim()
145
+ if (permKey && permValue) {
146
+ permission[permKey] = permValue
147
+ }
148
+ }
149
+ }
150
+ if (Object.keys(permission).length > 0) {
151
+ config.permission = permission
152
+ }
153
+
154
+ return config
155
+ }
156
+
157
+ /**
158
+ * Load the latest agent configuration from bundled markdown templates
266
159
  */
267
160
  async function loadLatestAgentConfig(): Promise<any> {
268
- // Return the latest agent configuration directly - no file reading needed
269
- return {
270
- fullstack: {
271
- temperature: 0.3,
272
- top_p: 0.9,
273
- mode: 'primary',
274
- permission: { edit: 'allow', bash: 'allow', webfetch: 'allow' },
275
- description:
276
- 'Router/coordinator agent for full-stack development with schema-driven architecture',
277
- prompt:
278
- "Voice: Scandinavian calm—precise, concise, confident; no fluff. You are Berget Code Fullstack agent. Act as a router and coordinator in a monorepo. Bottom-up schema: database → OpenAPI → generated types. Top-down types: API → UI → components. Use openapi-fetch and Zod at every boundary; compile-time errors are desired when contracts change. Routing rules: if task/paths match /apps/frontend or React (.tsx) → use frontend; if /apps/app or Expo/React Native → app; if /infra, /k8s, flux-system, kustomization.yaml, Helm values → devops; if /services, Koa routers, services/adapters/domain → backend. If ambiguous, remain fullstack and outline the end-to-end plan, then delegate subtasks to the right persona. Security: validate inputs; secrets via FluxCD SOPS/Sealed Secrets. Documentation is generated from code—never duplicated.\n\nGIT WORKFLOW RULES (CRITICAL):\n- NEVER push directly to main branch - ALWAYS use pull requests\n- NEVER use 'git add .' - ALWAYS add specific files with 'git add path/to/file'\n- ALWAYS clean up test files, documentation files, and temporary artifacts before committing\n- ALWAYS ensure git history maintains production quality - no test commits, no debugging code\n- ALWAYS create descriptive commit messages following project conventions\n- ALWAYS run tests and build before creating PR\n\nCRITICAL: When all implementation tasks are complete and ready for merge, ALWAYS invoke @quality subagent to handle testing, building, and complete PR management including URL provision.",
279
- },
280
- frontend: {
281
- temperature: 0.4,
282
- top_p: 0.9,
283
- mode: 'primary',
284
- permission: { edit: 'allow', bash: 'deny', webfetch: 'allow' },
285
- note: 'Bash access is denied for frontend persona to prevent shell command execution in UI environments. This restriction enforces security and architectural boundaries.',
286
- description:
287
- 'Builds Scandinavian, type-safe UIs with React, Tailwind, Shadcn.',
288
- prompt:
289
- 'You are Berget Code Frontend agent. Voice: Scandinavian calm—precise, concise, confident. React 18 + TypeScript. Tailwind + Shadcn UI only via the design system (index.css, tailwind.config.ts). Use semantic tokens for color/spacing/typography/motion; never ad-hoc classes or inline colors. Components are pure and responsive; props-first data; minimal global state (Zustand/Jotai). Accessibility and keyboard navigation mandatory. Mock data only at init under /data via typed hooks (e.g., useProducts() reading /data/products.json). Design: minimal, balanced, quiet motion.\n\nIMPORTANT: You have NO bash access and cannot run git commands. When your frontend implementation tasks are complete, inform the user that changes are ready and suggest using /pr command to create a pull request with proper testing and quality checks.\n\nCODE QUALITY RULES:\n- Write clean, production-ready code\n- Follow React and TypeScript best practices\n- Ensure accessibility and responsive design\n- Use semantic tokens from design system\n- Test your components manually when possible\n- Document any complex logic with comments\n\nCRITICAL: When frontend implementation is complete, ALWAYS inform the user to use "/pr" command to handle testing, building, and pull request creation.',
290
- },
291
- backend: {
292
- temperature: 0.3,
293
- top_p: 0.9,
294
- mode: 'primary',
295
- permission: { edit: 'allow', bash: 'allow', webfetch: 'allow' },
296
- description:
297
- 'Functional, modular Koa + TypeScript services; schema-first with code quality focus.',
298
- prompt:
299
- "You are Berget Code Backend agent. Voice: Scandinavian calm—precise, concise, confident. TypeScript + Koa. Prefer many small pure functions; avoid big try/catch blocks. Routes thin; logic in services/adapters/domain. Validate with Zod; auto-generate OpenAPI. Adapters isolate external systems; domain never depends on framework. Test with supertest; idempotent and stateless by default. Each microservice emits an OpenAPI contract; changes propagate upward to types. Code Quality & Refactoring Principles: Apply Single Responsibility Principle, fail fast with explicit errors, eliminate code duplication, remove nested complexity, use descriptive error codes, keep functions under 30 lines. Always leave code cleaner and more readable than you found it.\n\nGIT WORKFLOW RULES (CRITICAL):\n- NEVER push directly to main branch - ALWAYS use pull requests\n- NEVER use 'git add .' - ALWAYS add specific files with 'git add path/to/file'\n- ALWAYS clean up test files, documentation files, and temporary artifacts before committing\n- ALWAYS ensure git history maintains production quality - no test commits, no debugging code\n- ALWAYS create descriptive commit messages following project conventions\n- ALWAYS run tests and build before creating PR\n\nCRITICAL: When all backend implementation tasks are complete and ready for merge, ALWAYS invoke @quality subagent to handle testing, building, and complete PR management including URL provision.",
300
- },
301
- devops: {
302
- temperature: 0.3,
303
- top_p: 0.8,
304
- mode: 'primary',
305
- permission: { edit: 'allow', bash: 'allow', webfetch: 'allow' },
306
- description:
307
- 'Declarative GitOps infra with FluxCD, Kustomize, Helm, operators.',
308
- prompt:
309
- "You are Berget Code DevOps agent. Voice: Scandinavian calm—precise, concise, confident. Start simple: k8s/{deployment,service,ingress}. Add FluxCD sync to repo and image automation. Use Kustomize bases/overlays (staging, production). Add dependencies via Helm from upstream sources; prefer native operators when available (CloudNativePG, cert-manager, external-dns). SemVer with -rc tags keeps CI environments current. Observability with Prometheus/Grafana. No manual kubectl in production—Git is the source of truth.\n\nGIT WORKFLOW RULES (CRITICAL):\n- NEVER push directly to main branch - ALWAYS use pull requests\n- NEVER use 'git add .' - ALWAYS add specific files with 'git add path/to/file'\n- ALWAYS clean up test files, documentation files, and temporary artifacts before committing\n- ALWAYS ensure git history maintains production quality - no test commits, no debugging code\n- ALWAYS create descriptive commit messages following project conventions\n- ALWAYS run tests and build before creating PR\n\nHelm Values Configuration Process:\n1. Documentation First Approach: Always fetch official documentation from Artifact Hub/GitHub for the specific chart version before writing values. Search Artifact Hub for exact chart version documentation, check the chart's GitHub repository for official docs and examples, verify the exact version being used in the deployment.\n2. Validation Requirements: Check for available validation schemas before committing YAML files. Use Helm's built-in validation tools (helm lint, helm template). Validate against JSON schema if available for the chart. Ensure YAML syntax correctness with linters.\n3. Standard Workflow: Identify chart name and exact version. Fetch official documentation from Artifact Hub/GitHub. Check for available schemas and validation tools. Write values according to official documentation. Validate against schema (if available). Test with helm template or helm lint. Commit validated YAML files.\n4. Quality Assurance: Never commit unvalidated Helm values. Use helm dependency update when adding new charts. Test rendering with helm template --dry-run before deployment. Document any custom values with comments referencing official docs.",
310
- },
311
- app: {
312
- temperature: 0.4,
313
- top_p: 0.9,
314
- mode: 'primary',
315
- permission: { edit: 'allow', bash: 'deny', webfetch: 'allow' },
316
- note: 'Bash access is denied for app persona to prevent shell command execution in mobile/Expo environments. This restriction enforces security and architectural boundaries.',
317
- description:
318
- 'Expo + React Native apps; props-first, offline-aware, shared tokens.',
319
- prompt:
320
- "You are Berget Code App agent. Voice: Scandinavian calm—precise, concise, confident. Expo + React Native + TypeScript. Structure by components/hooks/services/navigation. Components are pure; data via props; refactor shared logic into hooks/stores. Share tokens with frontend. Mock data in /data via typed hooks; later replace with live APIs. Offline via SQLite/MMKV; notifications via Expo. Request permissions only when needed. Subtle, meaningful motion; light/dark parity.\n\nGIT WORKFLOW RULES (CRITICAL):\n- NEVER push directly to main branch - ALWAYS use pull requests\n- NEVER use 'git add .' - ALWAYS add specific files with 'git add path/to/file'\n- ALWAYS clean up test files, documentation files, and temporary artifacts before committing\n- ALWAYS ensure git history maintains production quality - no test commits, no debugging code\n- ALWAYS create descriptive commit messages following project conventions\n- ALWAYS run tests and build before creating PR\n\nCRITICAL: When all app implementation tasks are complete and ready for merge, ALWAYS invoke @quality subagent to handle testing, building, and complete PR management including URL provision.",
321
- },
322
- security: {
323
- temperature: 0.2,
324
- top_p: 0.8,
325
- mode: 'subagent',
326
- permission: { edit: 'deny', bash: 'allow', webfetch: 'allow' },
327
- description:
328
- 'Security specialist for pentesting, OWASP compliance, and vulnerability assessments.',
329
- prompt:
330
- "Voice: Scandinavian calm—precise, concise, confident. You are Berget Code Security agent. Expert in application security, penetration testing, and OWASP standards. Core responsibilities: Conduct security assessments and penetration tests, Validate OWASP Top 10 compliance, Review code for security vulnerabilities, Implement security headers and Content Security Policy (CSP), Audit API security, Check for sensitive data exposure, Validate input sanitization and output encoding, Assess dependency security and supply chain risks. Tools and techniques: OWASP ZAP, Burp Suite, security linters, dependency scanners, manual code review. Always provide specific, actionable security recommendations with priority levels.\n\nGIT WORKFLOW RULES (CRITICAL):\n- NEVER push directly to main branch - ALWAYS use pull requests\n- NEVER use 'git add .' - ALWAYS add specific files with 'git add path/to/file'\n- ALWAYS clean up test files, documentation files, and temporary artifacts before committing\n- ALWAYS ensure git history maintains production quality - no test commits, no debugging code\n- ALWAYS create descriptive commit messages following project conventions\n- ALWAYS run tests and build before creating PR",
331
- },
332
- quality: {
333
- temperature: 0.1,
334
- top_p: 0.9,
335
- mode: 'subagent',
336
- permission: { edit: 'allow', bash: 'allow', webfetch: 'allow' },
337
- description:
338
- 'Quality assurance specialist for testing, building, and PR management.',
339
- prompt:
340
- "Voice: Scandinavian calm—precise, concise, confident. You are Berget Code Quality agent. Specialist in code quality assurance, testing, building, and pull request management.\\n\\nCore responsibilities:\\n - Run comprehensive test suites (npm test, npm run test, jest, vitest)\\n - Execute build processes (npm run build, webpack, vite, tsc)\\n - Create and manage pull requests with proper descriptions\\n - Monitor GitHub for Copilot/reviewer comments\\n - Ensure code quality standards are met\\n - Validate linting and formatting (npm run lint, prettier)\\n - Check test coverage and performance benchmarks\\n - Handle CI/CD pipeline validation\\n\\nGIT WORKFLOW RULES (CRITICAL - ENFORCE STRICTLY):\\n - NEVER push directly to main branch - ALWAYS use pull requests\\n - NEVER use 'git add .' - ALWAYS add specific files with 'git add path/to/file'\\n - ALWAYS clean up test files, documentation files, and temporary artifacts before committing\\n - ALWAYS ensure git history maintains production quality - no test commits, no debugging code\\n - ALWAYS create descriptive commit messages following project conventions\\n - ALWAYS run tests and build before creating PR\\n\\nCommon CLI commands:\\n - npm test or npm run test (run test suite)\\n - npm run build (build project)\\n - npm run lint (run linting)\\n - npm run format (format code)\\n - npm run test:coverage (check coverage)\\n - gh pr create (create pull request)\\n - gh pr view --comments (check PR comments)\\n - git add specific/files && git commit -m \\\"message\\\" && git push (NEVER use git add .)\\n\\nPR Workflow:\\n 1. Ensure all tests pass: npm test\\n 2. Build successfully: npm run build\\n 3. Create/update PR with clear description\\n 4. Monitor for reviewer comments\\n 5. Address feedback promptly\\n 6. Update PR with fixes\\n 7. Ensure CI checks pass\\n\\nAlways provide specific command examples and wait for processes to complete before proceeding.",
341
- },
161
+ const templatesDir = getAgentTemplatesDir()
162
+ const agents: Record<string, any> = {}
163
+
164
+ const files = fs.readdirSync(templatesDir).filter((f) => f.endsWith('.md'))
165
+
166
+ for (const file of files) {
167
+ const agentName = path.basename(file, '.md')
168
+ const filePath = path.join(templatesDir, file)
169
+ const content = fs.readFileSync(filePath, 'utf8')
170
+
171
+ try {
172
+ agents[agentName] = parseAgentMarkdown(content)
173
+ } catch (error) {
174
+ console.warn(
175
+ chalk.yellow(`Warning: Failed to parse agent template ${file}: ${error}`)
176
+ )
177
+ }
342
178
  }
179
+
180
+ return agents
343
181
  }
344
182
 
345
183
  /**
@@ -454,6 +292,19 @@ export function registerCodeCommands(program: Command): void {
454
292
  .command(COMMAND_GROUPS.CODE)
455
293
  .description('AI-powered coding assistant with OpenCode')
456
294
 
295
+ if (process.env.BERGET_EXPERIMENTAL) {
296
+ code
297
+ .command('setup')
298
+ .description('Interactive setup for Berget AI coding tools')
299
+ .action(async () => {
300
+ try {
301
+ await runSetupCommand()
302
+ } catch (error) {
303
+ handleError('Setup failed', error)
304
+ }
305
+ })
306
+ }
307
+
457
308
  code
458
309
  .command(SUBCOMMANDS.CODE.INIT)
459
310
  .description('Initialize project for AI coding assistant')
@@ -495,142 +346,18 @@ export function registerCodeCommands(program: Command): void {
495
346
  chalk.cyan(`Initializing OpenCode for project: ${projectName}`)
496
347
  )
497
348
 
498
- // Load latest agent configuration from our own codebase
499
- const latestAgentConfig = await loadLatestAgentConfig()
500
-
501
- // Use hardcoded defaults for init - never try to load from project
502
- // Create opencode.json config — plugin handles auth, models, and provider
503
349
  const config = {
504
350
  $schema: 'https://opencode.ai/config.json',
505
- plugin: ['@bergetai/opencode-auth@1.0.15'],
506
- username: 'berget-code',
507
- theme: 'berget-dark',
508
- share: 'manual',
509
- autoupdate: true,
510
- agent: {
511
- fullstack: {
512
- temperature: 0.3,
513
- top_p: 0.9,
514
- mode: 'primary',
515
- permission: { edit: 'allow', bash: 'allow', webfetch: 'allow' },
516
- description:
517
- 'Router/coordinator agent for full-stack development with schema-driven architecture',
518
- prompt:
519
- 'Voice: Scandinavian calm—precise, concise, confident; no fluff. You are Berget Code Fullstack agent. Act as a router and coordinator in a monorepo. Bottom-up schema: database → OpenAPI → generated types. Top-down types: API → UI → components. Use openapi-fetch and Zod at every boundary; compile-time errors are desired when contracts change. Routing rules: if task/paths match /apps/frontend or React (.tsx) → use frontend; if /apps/app or Expo/React Native → app; if /infra, /k8s, flux-system, kustomization.yaml, Helm values → devops; if /services, Koa routers, services/adapters/domain → backend. If ambiguous, remain fullstack and outline the end-to-end plan, then delegate subtasks to the right persona. Security: validate inputs; secrets via FluxCD SOPS/Sealed Secrets. Documentation is generated from code—never duplicated. CRITICAL: When all implementation tasks are complete and ready for merge, ALWAYS invoke @quality subagent to handle testing, building, and complete PR management including URL provision.',
520
- },
521
- frontend: {
522
- temperature: 0.4,
523
- top_p: 0.9,
524
- mode: 'primary',
525
- permission: { edit: 'allow', bash: 'deny', webfetch: 'allow' },
526
- note: 'Bash access is denied for frontend persona to prevent shell command execution in UI environments. This restriction enforces security and architectural boundaries.',
527
- description:
528
- 'Builds Scandinavian, type-safe UIs with React, Tailwind, Shadcn.',
529
- prompt:
530
- 'You are Berget Code Frontend agent. Voice: Scandinavian calm—precise, concise, confident. React 18 + TypeScript. Tailwind + Shadcn UI only via the design system (index.css, tailwind.config.ts). Use semantic tokens for color/spacing/typography/motion; never ad-hoc classes or inline colors. Components are pure and responsive; props-first data; minimal global state (Zustand/Jotai). Accessibility and keyboard navigation mandatory. Mock data only at init under /data via typed hooks (e.g., useProducts() reading /data/products.json). Design: minimal, balanced, quiet motion. CRITICAL: When all frontend implementation tasks are complete and ready for merge, ALWAYS invoke @quality subagent to handle testing, building, and complete PR management including URL provision.',
531
- },
532
- backend: {
533
- temperature: 0.3,
534
- top_p: 0.9,
535
- mode: 'primary',
536
- permission: { edit: 'allow', bash: 'allow', webfetch: 'allow' },
537
- description:
538
- 'Functional, modular Koa + TypeScript services; schema-first with code quality focus.',
539
- prompt:
540
- 'You are Berget Code Backend agent. Voice: Scandinavian calm—precise, concise, confident. TypeScript + Koa. Prefer many small pure functions; avoid big try/catch blocks. Routes thin; logic in services/adapters/domain. Validate with Zod; auto-generate OpenAPI. Adapters isolate external systems; domain never depends on framework. Test with supertest; idempotent and stateless by default. Each microservice emits an OpenAPI contract; changes propagate upward to types. Code Quality & Refactoring Principles: Apply Single Responsibility Principle, fail fast with explicit errors, eliminate code duplication, remove nested complexity, use descriptive error codes, keep functions under 30 lines. Always leave code cleaner and more readable than you found it. CRITICAL: When all backend implementation tasks are complete and ready for merge, ALWAYS invoke @quality subagent to handle testing, building, and complete PR management including URL provision.',
541
- },
542
- // Use centralized devops configuration with Helm guidelines
543
- devops: latestAgentConfig.devops || {
544
- temperature: 0.3,
545
- top_p: 0.8,
546
- mode: 'primary',
547
- permission: { edit: 'allow', bash: 'allow', webfetch: 'allow' },
548
- description:
549
- 'Declarative GitOps infra with FluxCD, Kustomize, Helm, operators.',
550
- prompt:
551
- 'You are Berget Code DevOps agent. Voice: Scandinavian calm—precise, concise, confident. Start simple: k8s/{deployment,service,ingress}. Add FluxCD sync to repo and image automation. Use Kustomize bases/overlays (staging, production). Add dependencies via Helm from upstream sources; prefer native operators when available (CloudNativePG, cert-manager, external-dns). SemVer with -rc tags keeps CI environments current. Observability with Prometheus/Grafana. No manual kubectl in production—Git is the source of truth.',
552
- },
553
- app: {
554
- temperature: 0.4,
555
- top_p: 0.9,
556
- mode: 'primary',
557
- permission: { edit: 'allow', bash: 'deny', webfetch: 'allow' },
558
- note: 'Bash access is denied for app persona to prevent shell command execution in mobile/Expo environments. This restriction enforces security and architectural boundaries.',
559
- description:
560
- 'Expo + React Native apps; props-first, offline-aware, shared tokens.',
561
- prompt:
562
- 'You are Berget Code App agent. Voice: Scandinavian calm—precise, concise, confident. Expo + React Native + TypeScript. Structure by components/hooks/services/navigation. Components are pure; data via props; refactor shared logic into hooks/stores. Share tokens with frontend. Mock data in /data via typed hooks; later replace with live APIs. Offline via SQLite/MMKV; notifications via Expo. Request permissions only when needed. Subtle, meaningful motion; light/dark parity.',
563
- },
564
- security: {
565
- temperature: 0.2,
566
- top_p: 0.8,
567
- mode: 'subagent',
568
- permission: { edit: 'deny', bash: 'allow', webfetch: 'allow' },
569
- description:
570
- 'Security specialist for pentesting, OWASP compliance, and vulnerability assessments.',
571
- prompt:
572
- 'Voice: Scandinavian calm—precise, concise, confident. You are Berget Code Security agent. Expert in application security, penetration testing, and OWASP standards. Core responsibilities: Conduct security assessments and penetration tests, Validate OWASP Top 10 compliance, Review code for security vulnerabilities, Implement security headers and Content Security Policy (CSP), Audit API security, Check for sensitive data exposure, Validate input sanitization and output encoding, Assess dependency security and supply chain risks. Tools and techniques: OWASP ZAP, Burp Suite, security linters, dependency scanners, manual code review. Always provide specific, actionable security recommendations with priority levels.',
573
- },
574
- quality: {
575
- temperature: 0.1,
576
- top_p: 0.9,
577
- mode: 'subagent',
578
- permission: { edit: 'allow', bash: 'allow', webfetch: 'allow' },
579
- description:
580
- 'Quality assurance specialist for testing, building, and PR management.',
581
- prompt:
582
- 'Voice: Scandinavian calm—precise, concise, confident. You are Berget Code Quality agent. Specialist in code quality assurance, testing, building, and pull request management.\n\nCore responsibilities:\n - Run comprehensive test suites (npm test, npm run test, jest, vitest)\n - Execute build processes (npm run build, webpack, vite, tsc)\n - Create and manage pull requests with proper descriptions\n - Monitor GitHub for Copilot/reviewer comments\n - Ensure code quality standards are met\n - Validate linting and formatting (npm run lint, prettier)\n - Check test coverage and performance benchmarks\n - Handle CI/CD pipeline validation\n\nCommon CLI commands:\n - npm test or npm run test (run test suite)\n - npm run build (build project)\n - npm run lint (run linting)\n - npm run format (format code)\n - npm run test:coverage (check coverage)\n - gh pr create (create pull request)\n - gh pr view --comments (check PR comments)\n - git add . && git commit -m "message" && git push (commit and push)\n\nPR Workflow:\n 1. Ensure all tests pass: npm test\n 2. Build successfully: npm run build\n 3. Create/update PR with clear description\n 4. Monitor for reviewer comments\n 5. Address feedback promptly\n 6. Update PR with fixes\n 7. Ensure CI checks pass\n\nAlways provide specific command examples and wait for processes to complete before proceeding.',
583
- },
584
- },
585
- command: {
586
- fullstack: {
587
- description: 'Switch to Fullstack (router)',
588
- template: '{{input}}',
589
- agent: 'fullstack',
590
- },
591
- route: {
592
- description:
593
- 'Let Fullstack auto-route to the right persona based on files/intent',
594
- template: 'ROUTE {{input}}',
595
- agent: 'fullstack',
596
- subtask: true,
597
- },
598
- frontend: {
599
- description: 'Switch to Frontend persona',
600
- template: '{{input}}',
601
- agent: 'frontend',
602
- },
603
- backend: {
604
- description: 'Switch to Backend persona',
605
- template: '{{input}}',
606
- agent: 'backend',
607
- },
608
- devops: {
609
- description: 'Switch to DevOps persona',
610
- template: '{{input}}',
611
- agent: 'devops',
612
- },
613
- app: {
614
- description: 'Switch to App persona',
615
- template: '{{input}}',
616
- agent: 'app',
617
- },
618
- quality: {
619
- description:
620
- 'Switch to Quality agent for testing, building, and PR management',
621
- template: '{{input}}',
622
- agent: 'quality',
623
- },
624
- },
625
- watcher: {
626
- ignore: ['node_modules', 'dist', '.git', 'coverage'],
627
- },
351
+ plugin: ['@bergetai/opencode-auth@1.0.16'],
628
352
  }
629
353
 
630
- // Ask for permission to create config files
354
+ const agentsDir = path.join(process.cwd(), '.opencode', 'agents')
355
+ const templatesDir = getAgentTemplatesDir()
356
+
631
357
  if (!options.yes) {
632
358
  console.log(chalk.blue('\nAbout to create configuration files:'))
633
359
  console.log(chalk.dim(`Config: ${configPath}`))
360
+ console.log(chalk.dim(`Agents: ${agentsDir}/`))
634
361
  console.log(
635
362
  chalk.dim('This will configure OpenCode with the Berget auth plugin.')
636
363
  )
@@ -640,11 +367,24 @@ export function registerCodeCommands(program: Command): void {
640
367
  await confirm('\nCreate configuration files? (Y/n): ', options.yes)
641
368
  ) {
642
369
  try {
643
- // Create opencode.json
644
370
  await writeFile(configPath, JSON.stringify(config, null, 2))
645
- console.log(chalk.green(`āœ“ Created opencode.json`))
646
- console.log(chalk.dim(` Plugin: @bergetai/opencode-auth`))
647
- console.log(chalk.dim(` Theme: ${config.theme}`))
371
+ console.log(chalk.green('āœ“ Created opencode.json'))
372
+ console.log(chalk.dim(' Plugin: @bergetai/opencode-auth'))
373
+
374
+ fs.mkdirSync(agentsDir, { recursive: true })
375
+ const templateFiles = fs
376
+ .readdirSync(templatesDir)
377
+ .filter((f) => f.endsWith('.md'))
378
+ for (const file of templateFiles) {
379
+ const src = path.join(templatesDir, file)
380
+ const dest = path.join(agentsDir, file)
381
+ fs.copyFileSync(src, dest)
382
+ }
383
+ console.log(
384
+ chalk.green(
385
+ `āœ“ Created ${templateFiles.length} agent definitions in .opencode/agents/`
386
+ )
387
+ )
648
388
  } catch (error) {
649
389
  console.error(chalk.red('Failed to create config files:'))
650
390
  handleError('Config file creation failed', error)
@@ -869,198 +609,62 @@ export function registerCodeCommands(program: Command): void {
869
609
  }
870
610
 
871
611
  console.log(chalk.blue('šŸ“‹ Current configuration:'))
872
- console.log(chalk.dim(` Model: ${currentConfig.model}`))
873
- console.log(chalk.dim(` Theme: ${currentConfig.theme}`))
874
- console.log(
875
- chalk.dim(
876
- ` Agents: ${
877
- Object.keys(currentConfig.agent || {}).length
878
- } configured`
879
- )
880
- )
612
+ if (currentConfig.model) {
613
+ console.log(chalk.dim(` Model: ${currentConfig.model}`))
614
+ }
881
615
 
882
- // Load latest agent configuration to ensure consistency
883
- const latestAgentConfig = await loadLatestAgentConfig()
616
+ const agentsDir = path.join(process.cwd(), '.opencode', 'agents')
617
+ const templatesDir = getAgentTemplatesDir()
618
+ const templateFiles = fs
619
+ .readdirSync(templatesDir)
620
+ .filter((f) => f.endsWith('.md'))
884
621
 
885
- // Create latest configuration — plugin handles auth, models, and provider
886
622
  const latestConfig = {
887
623
  $schema: 'https://opencode.ai/config.json',
888
- plugin: ['@bergetai/opencode-auth@1.0.15'],
889
- username: 'berget-code',
890
- theme: 'berget-dark',
891
- share: 'manual',
892
- autoupdate: true,
893
- agent: {
894
- fullstack: {
895
- temperature: 0.3,
896
- top_p: 0.9,
897
- mode: 'primary',
898
- permission: { edit: 'allow', bash: 'allow', webfetch: 'allow' },
899
- description:
900
- 'Router/coordinator agent for full-stack development with schema-driven architecture',
901
- prompt:
902
- 'Voice: Scandinavian calm—precise, concise, confident; no fluff. You are Berget Code Fullstack agent. Act as a router and coordinator in a monorepo. Bottom-up schema: database → OpenAPI → generated types. Top-down types: API → UI → components. Use openapi-fetch and Zod at every boundary; compile-time errors are desired when contracts change. Routing rules: if task/paths match /apps/frontend or React (.tsx) → use frontend; if /apps/app or Expo/React Native → app; if /infra, /k8s, flux-system, kustomization.yaml, Helm values → devops; if /services, Koa routers, services/adapters/domain → backend. If ambiguous, remain fullstack and outline the end-to-end plan, then delegate subtasks to the right persona. Security: validate inputs; secrets via FluxCD SOPS/Sealed Secrets. Documentation is generated from code—never duplicated. CRITICAL: When all implementation tasks are complete and ready for merge, ALWAYS invoke @quality subagent to handle testing, building, and complete PR management including URL provision.',
903
- },
904
- frontend: {
905
- temperature: 0.4,
906
- top_p: 0.9,
907
- mode: 'primary',
908
- permission: { edit: 'allow', bash: 'deny', webfetch: 'allow' },
909
- note: 'Bash access is denied for frontend persona to prevent shell command execution in UI environments. This restriction enforces security and architectural boundaries.',
910
- description:
911
- 'Builds Scandinavian, type-safe UIs with React, Tailwind, Shadcn.',
912
- prompt:
913
- 'You are Berget Code Frontend agent. Voice: Scandinavian calm—precise, concise, confident. React 18 + TypeScript. Tailwind + Shadcn UI only via the design system (index.css, tailwind.config.ts). Use semantic tokens for color/spacing/typography/motion; never ad-hoc classes or inline colors. Components are pure and responsive; props-first data; minimal global state (Zustand/Jotai). Accessibility and keyboard navigation mandatory. Mock data only at init under /data via typed hooks (e.g., useProducts() reading /data/products.json). Design: minimal, balanced, quiet motion. CRITICAL: When all frontend implementation tasks are complete and ready for merge, ALWAYS invoke @quality subagent to handle testing, building, and complete PR management including URL provision.',
914
- },
915
- backend: {
916
- temperature: 0.3,
917
- top_p: 0.9,
918
- mode: 'primary',
919
- permission: { edit: 'allow', bash: 'allow', webfetch: 'allow' },
920
- description:
921
- 'Functional, modular Koa + TypeScript services; schema-first with code quality focus.',
922
- prompt:
923
- 'You are Berget Code Backend agent. Voice: Scandinavian calm—precise, concise, confident. TypeScript + Koa. Prefer many small pure functions; avoid big try/catch blocks. Routes thin; logic in services/adapters/domain. Validate with Zod; auto-generate OpenAPI. Adapters isolate external systems; domain never depends on framework. Test with supertest; idempotent and stateless by default. Each microservice emits an OpenAPI contract; changes propagate upward to types. Code Quality & Refactoring Principles: Apply Single Responsibility Principle, fail fast with explicit errors, eliminate code duplication, remove nested complexity, use descriptive error codes, keep functions under 30 lines. Always leave code cleaner and more readable than you found it. CRITICAL: When all backend implementation tasks are complete and ready for merge, ALWAYS invoke @quality subagent to handle testing, building, and complete PR management including URL provision.',
924
- },
925
- // Use centralized devops configuration with Helm guidelines
926
- devops: latestAgentConfig.devops || {
927
- temperature: 0.3,
928
- top_p: 0.8,
929
- mode: 'primary',
930
- permission: { edit: 'allow', bash: 'allow', webfetch: 'allow' },
931
- description:
932
- 'Declarative GitOps infra with FluxCD, Kustomize, Helm, operators.',
933
- prompt:
934
- 'You are Berget Code DevOps agent. Voice: Scandinavian calm—precise, concise, confident. Start simple: k8s/{deployment,service,ingress}. Add FluxCD sync to repo and image automation. Use Kustomize bases/overlays (staging, production). Add dependencies via Helm from upstream sources; prefer native operators when available (CloudNativePG, cert-manager, external-dns). SemVer with -rc tags keeps CI environments current. Observability with Prometheus/Grafana. No manual kubectl in production—Git is the source of truth. For testing, building, and PR management, use @quality subagent.',
935
- },
936
- app: {
937
- temperature: 0.4,
938
- top_p: 0.9,
939
- mode: 'primary',
940
- permission: { edit: 'allow', bash: 'deny', webfetch: 'allow' },
941
- note: 'Bash access is denied for app persona to prevent shell command execution in mobile/Expo environments. This restriction enforces security and architectural boundaries.',
942
- description:
943
- 'Expo + React Native apps; props-first, offline-aware, shared tokens.',
944
- prompt:
945
- 'You are Berget Code App agent. Voice: Scandinavian calm—precise, concise, confident. Expo + React Native + TypeScript. Structure by components/hooks/services/navigation. Components are pure; data via props; refactor shared logic into hooks/stores. Share tokens with frontend. Mock data in /data via typed hooks; later replace with live APIs. Offline via SQLite/MMKV; notifications via Expo. Request permissions only when needed. Subtle, meaningful motion; light/dark parity. For testing, building, and PR management, use @quality subagent.',
946
- },
947
- security: {
948
- temperature: 0.2,
949
- top_p: 0.8,
950
- mode: 'subagent',
951
- permission: { edit: 'deny', bash: 'allow', webfetch: 'allow' },
952
- description:
953
- 'Security specialist for pentesting, OWASP compliance, and vulnerability assessments.',
954
- prompt:
955
- 'Voice: Scandinavian calm—precise, concise, confident. You are Berget Code Security agent. Expert in application security, penetration testing, and OWASP standards. Core responsibilities: Conduct security assessments and penetration tests, Validate OWASP Top 10 compliance, Review code for security vulnerabilities, Implement security headers and Content Security Policy (CSP), Audit API security, Check for sensitive data exposure, Validate input sanitization and output encoding, Assess dependency security and supply chain risks. Tools and techniques: OWASP ZAP, Burp Suite, security linters, dependency scanners, manual code review. Always provide specific, actionable security recommendations with priority levels. Workflow: Always follow branch_strategy and commit_convention from workflow section. Never work directly in main. Agent awareness: Review code from all personas (frontend, backend, app, devops). If implementation changes are needed, suggest <tab> to switch to appropriate persona after security assessment.',
956
- },
957
- quality: {
958
- temperature: 0.1,
959
- top_p: 0.9,
960
- mode: 'subagent',
961
- permission: { edit: 'allow', bash: 'allow', webfetch: 'allow' },
962
- description:
963
- 'Quality assurance specialist for testing, building, and complete PR management.',
964
- prompt:
965
- 'Voice: Scandinavian calm—precise, concise, confident. You are Berget Code Quality agent. Specialist in code quality assurance, testing, building, and complete pull request lifecycle management.\n\nCore responsibilities:\n - Run comprehensive test suites (npm test, npm run test, jest, vitest)\n - Execute build processes (npm run build, webpack, vite, tsc)\n - Create and manage pull requests with proper descriptions\n - Handle merge conflicts and keep main updated\n - Monitor GitHub for reviewer comments and address them\n - Ensure code quality standards are met\n - Validate linting and formatting (npm run lint, prettier)\n - Check test coverage and performance benchmarks\n - Handle CI/CD pipeline validation\n\nComplete PR Workflow:\n 1. Ensure all tests pass: npm test\n 2. Build successfully: npm run build\n 3. Commit all changes with proper message\n 4. Push to feature branch\n 5. Update main branch and handle merge conflicts\n 6. Create or update PR with comprehensive description\n 7. Monitor for reviewer comments\n 8. Address feedback and push updates\n 9. Always provide PR URL for user review\n\nEssential CLI commands:\n - npm test or npm run test (run test suite)\n - npm run build (build project)\n - npm run lint (run linting)\n - npm run format (format code)\n - npm run test:coverage (check coverage)\n - git add . && git commit -m "message" && git push (commit and push)\n - git checkout main && git pull origin main (update main)\n - git checkout feature-branch && git merge main (handle conflicts)\n - gh pr create --title "title" --body "body" (create PR)\n - gh pr view --comments (check PR comments)\n - gh pr edit --title "title" --body "body" (update PR)\n\nPR Creation Process:\n - Always include clear summary of changes\n - List technical details and improvements\n - Include testing and validation results\n - Add any breaking changes or migration notes\n - Provide PR URL immediately after creation\n\nMerge Conflict Resolution:\n - Always update main before creating/updating PR\n - Handle conflicts automatically when possible\n - If conflicts require human input, clearly explain what\'s needed\n - Re-run tests after conflict resolution\n - Ensure CI checks pass before finalizing\n\nReviewer Comment Handling:\n - Monitor PR for new comments regularly\n - Address each comment specifically\n - Push fixes and update PR accordingly\n - Always provide updated PR URL after changes\n - Continue monitoring until all feedback is addressed\n\nCRITICAL: When invoked by other agents (@quality), you MUST:\n - Complete all testing and building tasks\n - Handle entire PR creation/update process\n - Provide PR URL at the end\n - Ensure main branch is properly merged\n - Handle any merge conflicts automatically\n\nAlways provide specific command examples and wait for processes to complete before proceeding.\nWorkflow: Always follow branch_strategy and commit_convention from workflow section. Never work directly in main.\nAgent awareness: Can be invoked by any primary agent (@quality) for complete testing, building, and PR management. You are the final step before user review - ensure everything is perfect.',
966
- },
967
- },
968
- command: {
969
- fullstack: {
970
- description: 'Switch to Fullstack (router)',
971
- template: '{{input}}',
972
- agent: 'fullstack',
973
- },
974
- route: {
975
- description:
976
- 'Let Fullstack auto-route to the right persona based on files/intent',
977
- template: 'ROUTE {{input}}',
978
- agent: 'fullstack',
979
- subtask: true,
980
- },
981
- frontend: {
982
- description: 'Switch to Frontend persona',
983
- template: '{{input}}',
984
- agent: 'frontend',
985
- },
986
- backend: {
987
- description: 'Switch to Backend persona',
988
- template: '{{input}}',
989
- agent: 'backend',
990
- },
991
- devops: {
992
- description: 'Switch to DevOps persona',
993
- template: '{{input}}',
994
- agent: 'devops',
995
- },
996
- app: {
997
- description: 'Switch to App persona',
998
- template: '{{input}}',
999
- agent: 'app',
1000
- },
1001
- security: {
1002
- description:
1003
- 'Switch to Security persona for pentesting and OWASP compliance',
1004
- template: '{{input}}',
1005
- agent: 'security',
1006
- },
1007
- quality: {
1008
- description:
1009
- 'Switch to Quality agent for testing, building, and PR management',
1010
- template: '{{input}}',
1011
- agent: 'quality',
1012
- },
1013
- },
1014
- watcher: {
1015
- ignore: ['node_modules', 'dist', '.git', 'coverage'],
1016
- },
624
+ plugin: ['@bergetai/opencode-auth@1.0.16'],
1017
625
  }
1018
626
 
1019
- // Check if update is needed
1020
- const needsUpdate =
1021
- JSON.stringify(currentConfig) !== JSON.stringify(latestConfig)
627
+ // Check if agent definitions need updating
628
+ let agentsNeedUpdate = false
629
+ const existingAgentFiles = fs.existsSync(agentsDir)
630
+ ? fs.readdirSync(agentsDir).filter((f) => f.endsWith('.md'))
631
+ : []
632
+
633
+ for (const file of templateFiles) {
634
+ const src = path.join(templatesDir, file)
635
+ const dest = path.join(agentsDir, file)
636
+ if (!fs.existsSync(dest)) {
637
+ agentsNeedUpdate = true
638
+ break
639
+ }
640
+ const srcContent = fs.readFileSync(src, 'utf8')
641
+ const destContent = fs.readFileSync(dest, 'utf8')
642
+ if (srcContent !== destContent) {
643
+ agentsNeedUpdate = true
644
+ break
645
+ }
646
+ }
647
+
648
+ // Check if opencode.json still has inline agent config (needs migration)
649
+ const needsMigration = !!currentConfig.agent
1022
650
 
1023
- if (!needsUpdate && !options.force) {
651
+ if (!agentsNeedUpdate && !needsMigration && !options.force) {
1024
652
  console.log(chalk.green('āœ… Already using the latest configuration!'))
1025
653
  return
1026
654
  }
1027
655
 
1028
- if (needsUpdate) {
656
+ if (agentsNeedUpdate || needsMigration) {
1029
657
  console.log(chalk.blue('\nšŸ”„ Updates available:'))
1030
658
 
1031
- // Compare agents
1032
- const currentAgents = Object.keys(currentConfig.agent || {})
1033
- const latestAgents = Object.keys(latestConfig.agent)
1034
- const newAgents = latestAgents.filter(
1035
- (agent) => !currentAgents.includes(agent)
1036
- )
1037
-
1038
- if (newAgents.length > 0) {
1039
- console.log(chalk.cyan(` • New agents: ${newAgents.join(', ')}`))
1040
- }
1041
-
1042
- // Check for quality agent specifically
1043
- if (!currentConfig.agent?.quality && latestConfig.agent.quality) {
659
+ if (needsMigration) {
1044
660
  console.log(
1045
- chalk.cyan(' • Quality subagent for testing and PR management')
661
+ chalk.cyan(' • Migrate agents from opencode.json to .opencode/agents/')
1046
662
  )
1047
663
  }
1048
664
 
1049
- // Check for security subagent mode
1050
- if (currentConfig.agent?.security?.mode !== 'subagent') {
1051
- console.log(
1052
- chalk.cyan(' • Security agent converted to subagent (read-only)')
1053
- )
665
+ if (agentsNeedUpdate) {
666
+ console.log(chalk.cyan(' • Latest agent prompts and improvements'))
1054
667
  }
1055
-
1056
- // Check for plugin migration
1057
- if (!currentConfig.plugin) {
1058
- console.log(
1059
- chalk.cyan(' • Plugin-first auth (automatic token refresh + model discovery)')
1060
- )
1061
- }
1062
-
1063
- console.log(chalk.cyan(' • Latest agent prompts and improvements'))
1064
668
  }
1065
669
 
1066
670
  if (options.force) {
@@ -1070,11 +674,10 @@ export function registerCodeCommands(program: Command): void {
1070
674
  if (!options.yes) {
1071
675
  console.log(
1072
676
  chalk.blue(
1073
- '\nThis will update your OpenCode configuration with the latest improvements.'
677
+ '\nThis will update your agent definitions and OpenCode configuration.'
1074
678
  )
1075
679
  )
1076
680
 
1077
- // Check if user has git for backup
1078
681
  const hasGitRepo = hasGit()
1079
682
  if (!hasGitRepo) {
1080
683
  console.log(
@@ -1089,38 +692,12 @@ export function registerCodeCommands(program: Command): void {
1089
692
  }
1090
693
  }
1091
694
 
1092
- // Ask user what they want to do
1093
- console.log(chalk.blue('\nChoose update strategy:'))
1094
- console.log(
1095
- chalk.cyan(
1096
- '1) Replace - Use latest configuration (your customizations will be lost)'
1097
- )
1098
- )
1099
- console.log(
1100
- chalk.cyan(
1101
- '2) Merge - Combine latest updates with your customizations (recommended)'
1102
- )
1103
- )
1104
-
1105
- let mergeChoice: 'replace' | 'merge' = 'merge'
1106
-
1107
- if (!options.yes) {
1108
- const choice = await askChoice(
1109
- '\nYour choice (1-2, default: 2): ',
1110
- ['replace', 'merge'],
1111
- 'merge'
1112
- )
1113
- mergeChoice = choice as 'replace' | 'merge'
1114
- }
1115
-
1116
695
  if (
1117
- await confirm(`\nProceed with ${mergeChoice}? (Y/n): `, options.yes)
696
+ await confirm('\nProceed with update? (Y/n): ', options.yes)
1118
697
  ) {
1119
698
  try {
1120
- let finalConfig: any
1121
699
  let backupPath: string | null = null
1122
700
 
1123
- // Create backup if no git
1124
701
  if (!hasGit()) {
1125
702
  backupPath = `${configPath}.backup.${Date.now()}`
1126
703
  await writeFile(
@@ -1134,28 +711,38 @@ export function registerCodeCommands(program: Command): void {
1134
711
  )
1135
712
  }
1136
713
 
1137
- if (mergeChoice === 'merge') {
1138
- // Merge configurations
1139
- finalConfig = await mergeConfigurations(
1140
- currentConfig,
1141
- latestConfig
1142
- )
714
+ // Remove inline agent section from opencode.json if present
715
+ if (currentConfig.agent) {
716
+ delete currentConfig.agent
717
+ await writeFile(configPath, JSON.stringify(currentConfig, null, 2))
1143
718
  console.log(
1144
- chalk.green('āœ“ Merged configurations with latest updates')
719
+ chalk.green('āœ“ Removed inline agent config from opencode.json')
1145
720
  )
1146
- } else {
1147
- // Replace with latest
1148
- finalConfig = latestConfig
1149
- console.log(chalk.green('āœ“ Replaced with latest configuration'))
1150
721
  }
1151
722
 
1152
- // Write final configuration
1153
- await writeFile(configPath, JSON.stringify(finalConfig, null, 2))
1154
- console.log(
1155
- chalk.green(
1156
- `āœ“ Updated opencode.json with ${mergeChoice} strategy`
723
+ // Sync agent markdown files from templates
724
+ fs.mkdirSync(agentsDir, { recursive: true })
725
+ let updatedCount = 0
726
+ for (const file of templateFiles) {
727
+ const src = path.join(templatesDir, file)
728
+ const dest = path.join(agentsDir, file)
729
+ const agentName = path.basename(file, '.md')
730
+
731
+ if (
732
+ !fs.existsSync(dest) ||
733
+ fs.readFileSync(src, 'utf8') !== fs.readFileSync(dest, 'utf8')
734
+ ) {
735
+ fs.copyFileSync(src, dest)
736
+ updatedCount++
737
+ console.log(chalk.cyan(` • Updated agent: ${agentName}`))
738
+ }
739
+ }
740
+
741
+ if (updatedCount > 0) {
742
+ console.log(
743
+ chalk.green(`āœ“ Updated ${updatedCount} agent definition(s)`)
1157
744
  )
1158
- )
745
+ }
1159
746
 
1160
747
  // Update AGENTS.md if it doesn't exist
1161
748
  const agentsMdPath = path.join(process.cwd(), 'AGENTS.md')
@@ -1164,158 +751,46 @@ export function registerCodeCommands(program: Command): void {
1164
751
 
1165
752
  This document describes the specialized agents available in this project for use with OpenCode.
1166
753
 
754
+ Agents are defined as markdown files in \`.opencode/agents/\` with YAML frontmatter.
755
+
1167
756
  ## Available Agents
1168
757
 
1169
758
  ### Primary Agents
1170
759
 
1171
- #### fullstack
1172
- Router/coordinator agent for full-stack development with schema-driven architecture. Handles routing between different personas based on file paths and task requirements.
1173
-
1174
- **Use when:**
1175
- - Working across multiple parts of a monorepo
1176
- - Need to coordinate between frontend, backend, devops, and app
1177
- - Starting new projects and need to determine tech stack
1178
-
1179
- **Key features:**
1180
- - Schema-driven development (database → OpenAPI → types)
1181
- - Automatic routing to appropriate persona
1182
- - Tech stack discovery and recommendations
1183
-
1184
- #### frontend
1185
- Builds Scandinavian, type-safe UIs with React, Tailwind, and Shadcn.
1186
-
1187
- **Use when:**
1188
- - Working with React components (.tsx files)
1189
- - Frontend development in /apps/frontend
1190
- - UI/UX implementation
1191
-
1192
- **Key features:**
1193
- - Design system integration
1194
- - Semantic tokens and accessibility
1195
- - Props-first component architecture
1196
-
1197
- #### backend
1198
- Functional, modular Koa + TypeScript services with schema-first approach and code quality focus.
1199
-
1200
- **Use when:**
1201
- - Working with Koa routers and services
1202
- - Backend development in /services
1203
- - API development and database work
1204
-
1205
- **Key features:**
1206
- - Zod validation and OpenAPI generation
1207
- - Code quality and refactoring principles
1208
- - PR workflow integration
1209
-
1210
- #### devops
1211
- Declarative GitOps infrastructure with FluxCD, Kustomize, Helm, and operators.
1212
-
1213
- **Use when:**
1214
- - Working with Kubernetes manifests
1215
- - Infrastructure in /infra or /k8s
1216
- - CI/CD and deployment configurations
1217
-
1218
- **Key features:**
1219
- - GitOps workflows
1220
- - Operator-first approach
1221
- - SemVer with release candidates
1222
-
1223
- **Helm Values Configuration Process:**
1224
- 1. Documentation First Approach: Always fetch official documentation from Artifact Hub/GitHub for the specific chart version before writing values. Search Artifact Hub for exact chart version documentation, check the chart's GitHub repository for official docs and examples, verify the exact version being used in the deployment.
1225
- 2. Validation Requirements: Check for available validation schemas before committing YAML files. Use Helm's built-in validation tools (helm lint, helm template). Validate against JSON schema if available for the chart. Ensure YAML syntax correctness with linters.
1226
- 3. Standard Workflow: Identify chart name and exact version. Fetch official documentation from Artifact Hub/GitHub. Check for available schemas and validation tools. Write values according to official documentation. Validate against schema (if available). Test with helm template or helm lint. Commit validated YAML files.
1227
- 4. Quality Assurance: Never commit unvalidated Helm values. Use helm dependency update when adding new charts. Test rendering with helm template --dry-run before deployment. Document any custom values with comments referencing official docs.
1228
-
1229
- #### app
1230
- Expo + React Native applications with props-first architecture and offline awareness.
1231
-
1232
- **Use when:**
1233
- - Mobile app development with Expo
1234
- - React Native projects in /apps/app
1235
- - Cross-platform mobile development
1236
-
1237
- **Key features:**
1238
- - Shared design tokens with frontend
1239
- - Offline-first architecture
1240
- - Expo integration
760
+ | Agent | Description | Temperature |
761
+ |-------|-------------|-------------|
762
+ | fullstack | Router/coordinator for full-stack development | 0.3 |
763
+ | frontend | Scandinavian, type-safe UIs with React, Tailwind, Shadcn | 0.4 |
764
+ | backend | Functional, modular Koa + TypeScript services | 0.3 |
765
+ | devops | Declarative GitOps infra with FluxCD, Kustomize, Helm | 0.3 |
766
+ | app | Expo + React Native apps; props-first, offline-aware | 0.4 |
1241
767
 
1242
768
  ### Subagents
1243
769
 
1244
- #### security
1245
- Security specialist for penetration testing, OWASP compliance, and vulnerability assessments.
1246
-
1247
- **Use when:**
1248
- - Need security review of code changes
1249
- - OWASP Top 10 compliance checks
1250
- - Vulnerability assessments
1251
-
1252
- **Key features:**
1253
- - OWASP standards compliance
1254
- - Security best practices
1255
- - Actionable remediation strategies
1256
-
1257
- #### quality
1258
- Quality assurance specialist for testing, building, and PR management.
1259
-
1260
- **Use when:**
1261
- - Need to run test suites and build processes
1262
- - Creating or updating pull requests
1263
- - Monitoring GitHub for reviewer comments
1264
- - Ensuring code quality standards
1265
-
1266
- **Key features:**
1267
- - Comprehensive testing and building workflows
1268
- - PR creation and management
1269
- - GitHub integration for reviewer feedback
1270
- - CLI command expertise for quality assurance
770
+ | Agent | Description | Temperature |
771
+ |-------|-------------|-------------|
772
+ | security | Security specialist for pentesting and OWASP compliance | 0.2 |
773
+ | quality | QA specialist for testing, building, and PR management | 0.1 |
1271
774
 
1272
775
  ## Usage
1273
776
 
1274
- ### Switching Agents
1275
- Use the \`<tab>\` key to cycle through primary agents during a session.
1276
-
1277
- ### Manual Agent Selection
1278
- Use commands to switch to specific agents:
1279
- - \`/fullstack\` - Switch to Fullstack agent
1280
- - \`/frontend\` - Switch to Frontend agent
1281
- - \`/backend\` - Switch to Backend agent
1282
- - \`/devops\` - Switch to DevOps agent
1283
- - \`/app\` - Switch to App agent
1284
- - \`/quality\` - Switch to Quality agent for testing and PR management
1285
-
1286
- ### Using Subagents
1287
- Mention subagents with \`@\` symbol:
1288
- - \`@security review this authentication implementation\`
1289
- - \`@quality run tests and create PR for these changes\`
777
+ - **Tab** key to cycle between primary agents
778
+ - **@mention** to invoke subagents (e.g. \`@security review this code\`)
779
+ - \`/fullstack\`, \`/frontend\`, \`/backend\`, \`/devops\`, \`/app\` to switch agents
1290
780
 
1291
781
  ## Routing Rules
1292
782
 
1293
783
  The fullstack agent automatically routes tasks based on file patterns:
1294
784
 
1295
785
  - \`/apps/frontend\` or \`.tsx\` files → frontend
1296
- - \`/apps/app\` or Expo/React Native → app
786
+ - \`/apps/app\` or Expo/React Native → app
1297
787
  - \`/infra\`, \`/k8s\`, FluxCD, Helm → devops
1298
788
  - \`/services\`, Koa routers → backend
1299
789
 
1300
- ## Configuration
1301
-
1302
- All agents are configured in \`opencode.json\` with:
1303
- - Specialized prompts and temperature settings
1304
- - Appropriate tool permissions
1305
- - Model optimizations for their specific tasks
1306
-
1307
- ## Environment Setup
1308
-
1309
- Authentication is handled by the Berget plugin. Run \`/connect\` in OpenCode to authenticate.
1310
-
1311
- ## Workflow
790
+ ## Customization
1312
791
 
1313
- All agents follow these principles:
1314
- - Never work directly in main branch
1315
- - Follow branch strategy and commit conventions
1316
- - Create PRs for new functionality
1317
- - Run tests before committing
1318
- - Address reviewer feedback promptly
792
+ Edit the markdown files in \`.opencode/agents/\` to customize agent behavior.
793
+ See https://opencode.ai/docs/agents/ for available options.
1319
794
 
1320
795
  ---
1321
796
 
@@ -1323,27 +798,14 @@ All agents follow these principles:
1323
798
  `
1324
799
 
1325
800
  await writeFile(agentsMdPath, agentsMdContent)
1326
- console.log(chalk.green('āœ“ Updated AGENTS.md documentation'))
801
+ console.log(chalk.green('āœ“ Created AGENTS.md documentation'))
1327
802
  }
1328
803
 
1329
804
  console.log(chalk.green('\nāœ… Update completed successfully!'))
1330
- console.log(chalk.blue('New features available:'))
1331
- console.log(
1332
- chalk.cyan(' • @quality subagent for testing and PR management')
1333
- )
1334
- console.log(
1335
- chalk.cyan(' • @security subagent for security reviews')
1336
- )
1337
- console.log(chalk.cyan(' • Improved agent prompts and routing'))
1338
- console.log(chalk.cyan(' • GLM-4.7 token optimizations'))
1339
- console.log(chalk.blue('\nTry these new commands:'))
1340
- console.log(chalk.cyan(' @quality run tests and create PR'))
1341
- console.log(chalk.cyan(' @security review this code'))
1342
805
  } catch (error) {
1343
806
  console.error(chalk.red('Failed to update configuration:'))
1344
807
  handleError('Update failed', error)
1345
808
 
1346
- // Restore from backup if update failed
1347
809
  try {
1348
810
  await writeFile(
1349
811
  configPath,
@@ -1364,3 +826,4 @@ All agents follow these principles:
1364
826
  }
1365
827
  })
1366
828
  }
829
+