opencastle 1.4.2 → 1.5.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 (128) hide show
  1. package/dist/cli/bootstrap-on-init.test.js +5 -5
  2. package/dist/cli/bootstrap-on-init.test.js.map +1 -1
  3. package/dist/cli/bootstrap.d.ts +17 -0
  4. package/dist/cli/bootstrap.d.ts.map +1 -1
  5. package/dist/cli/bootstrap.js +284 -312
  6. package/dist/cli/bootstrap.js.map +1 -1
  7. package/dist/cli/bootstrap.test.js +22 -16
  8. package/dist/cli/bootstrap.test.js.map +1 -1
  9. package/dist/cli/convoy/engine.d.ts.map +1 -1
  10. package/dist/cli/convoy/engine.js +8 -2
  11. package/dist/cli/convoy/engine.js.map +1 -1
  12. package/dist/cli/convoy/spec-types.d.ts +15 -0
  13. package/dist/cli/convoy/spec-types.d.ts.map +1 -1
  14. package/dist/cli/detect.d.ts +4 -0
  15. package/dist/cli/detect.d.ts.map +1 -1
  16. package/dist/cli/detect.js +1 -1
  17. package/dist/cli/detect.js.map +1 -1
  18. package/dist/cli/doctor.js +4 -4
  19. package/dist/cli/doctor.js.map +1 -1
  20. package/dist/cli/init.test.js +4 -5
  21. package/dist/cli/init.test.js.map +1 -1
  22. package/dist/cli/log.d.ts +2 -2
  23. package/dist/cli/log.d.ts.map +1 -1
  24. package/dist/cli/log.js +1 -1
  25. package/dist/cli/log.js.map +1 -1
  26. package/dist/cli/log.test.js +1 -1
  27. package/dist/cli/log.test.js.map +1 -1
  28. package/dist/cli/managed-paths.d.ts +1 -1
  29. package/dist/cli/managed-paths.d.ts.map +1 -1
  30. package/dist/cli/managed-paths.js +0 -1
  31. package/dist/cli/managed-paths.js.map +1 -1
  32. package/dist/cli/pipeline.d.ts.map +1 -1
  33. package/dist/cli/pipeline.flow.test.js +134 -27
  34. package/dist/cli/pipeline.flow.test.js.map +1 -1
  35. package/dist/cli/pipeline.js +113 -34
  36. package/dist/cli/pipeline.js.map +1 -1
  37. package/dist/cli/plan.d.ts +22 -0
  38. package/dist/cli/plan.d.ts.map +1 -1
  39. package/dist/cli/plan.js +43 -6
  40. package/dist/cli/plan.js.map +1 -1
  41. package/dist/cli/project-facts.d.ts +103 -0
  42. package/dist/cli/project-facts.d.ts.map +1 -0
  43. package/dist/cli/project-facts.js +577 -0
  44. package/dist/cli/project-facts.js.map +1 -0
  45. package/dist/cli/project-facts.test.d.ts +2 -0
  46. package/dist/cli/project-facts.test.d.ts.map +1 -0
  47. package/dist/cli/project-facts.test.js +209 -0
  48. package/dist/cli/project-facts.test.js.map +1 -0
  49. package/dist/cli/run/adapters/claude.d.ts +13 -0
  50. package/dist/cli/run/adapters/claude.d.ts.map +1 -1
  51. package/dist/cli/run/adapters/claude.js +30 -1
  52. package/dist/cli/run/adapters/claude.js.map +1 -1
  53. package/dist/cli/run/adapters/claude.test.js +34 -1
  54. package/dist/cli/run/adapters/claude.test.js.map +1 -1
  55. package/dist/cli/run/adapters/codex.d.ts.map +1 -1
  56. package/dist/cli/run/adapters/codex.js +4 -0
  57. package/dist/cli/run/adapters/codex.js.map +1 -1
  58. package/dist/cli/run/adapters/codex.test.js +8 -0
  59. package/dist/cli/run/adapters/codex.test.js.map +1 -1
  60. package/dist/cli/run/adapters/copilot.d.ts.map +1 -1
  61. package/dist/cli/run/adapters/copilot.js +4 -1
  62. package/dist/cli/run/adapters/copilot.js.map +1 -1
  63. package/dist/cli/run/adapters/copilot.test.js +9 -0
  64. package/dist/cli/run/adapters/copilot.test.js.map +1 -1
  65. package/dist/cli/run/adapters/stub-cli.test-helper.d.ts +2 -0
  66. package/dist/cli/run/adapters/stub-cli.test-helper.d.ts.map +1 -1
  67. package/dist/cli/run/adapters/stub-cli.test-helper.js +16 -1
  68. package/dist/cli/run/adapters/stub-cli.test-helper.js.map +1 -1
  69. package/dist/cli/run/platform.d.ts +12 -0
  70. package/dist/cli/run/platform.d.ts.map +1 -1
  71. package/dist/cli/run/platform.js +49 -0
  72. package/dist/cli/run/platform.js.map +1 -1
  73. package/dist/cli/run/platform.test.js +21 -1
  74. package/dist/cli/run/platform.test.js.map +1 -1
  75. package/dist/cli/stack-config.js +1 -1
  76. package/dist/cli/stack-config.js.map +1 -1
  77. package/package.json +1 -1
  78. package/src/cli/bootstrap-on-init.test.ts +5 -5
  79. package/src/cli/bootstrap.test.ts +22 -16
  80. package/src/cli/bootstrap.ts +361 -373
  81. package/src/cli/convoy/engine.ts +9 -2
  82. package/src/cli/convoy/spec-types.ts +15 -0
  83. package/src/cli/detect.ts +1 -1
  84. package/src/cli/doctor.ts +4 -4
  85. package/src/cli/init.test.ts +4 -5
  86. package/src/cli/log.test.ts +1 -1
  87. package/src/cli/log.ts +2 -2
  88. package/src/cli/managed-paths.ts +0 -1
  89. package/src/cli/pipeline.flow.test.ts +143 -28
  90. package/src/cli/pipeline.ts +141 -34
  91. package/src/cli/plan.ts +51 -6
  92. package/src/cli/project-facts.test.ts +228 -0
  93. package/src/cli/project-facts.ts +647 -0
  94. package/src/cli/run/adapters/claude.test.ts +39 -1
  95. package/src/cli/run/adapters/claude.ts +27 -1
  96. package/src/cli/run/adapters/codex.test.ts +9 -0
  97. package/src/cli/run/adapters/codex.ts +3 -0
  98. package/src/cli/run/adapters/copilot.test.ts +11 -0
  99. package/src/cli/run/adapters/copilot.ts +3 -1
  100. package/src/cli/run/adapters/stub-cli.test-helper.ts +16 -1
  101. package/src/cli/run/platform.test.ts +23 -1
  102. package/src/cli/run/platform.ts +50 -0
  103. package/src/cli/stack-config.ts +1 -1
  104. package/src/orchestrator/agent-workflows/data-pipeline.md +2 -2
  105. package/src/orchestrator/agent-workflows/feature-implementation.md +1 -1
  106. package/src/orchestrator/agent-workflows/schema-changes.md +1 -1
  107. package/src/orchestrator/agents/team-lead.agent.md +1 -1
  108. package/src/orchestrator/customizations/README.md +27 -84
  109. package/src/orchestrator/prompts/bootstrap-customizations.prompt.md +38 -238
  110. package/src/orchestrator/prompts/brainstorm.prompt.md +1 -1
  111. package/src/orchestrator/prompts/implement-feature.prompt.md +6 -6
  112. package/src/orchestrator/skills/agent-memory/KNOWLEDGE-GRAPH.md +1 -1
  113. package/src/orchestrator/skills/agent-memory/SKILL.md +7 -16
  114. package/src/orchestrator/skills/documentation-standards/SKILL.md +1 -1
  115. package/src/orchestrator/skills/observability-logging/SKILL.md +1 -1
  116. package/src/orchestrator/skills/panel-majority-vote/REFERENCE.md +1 -1
  117. package/src/orchestrator/skills/team-lead-reference/SKILL.md +2 -2
  118. package/src/orchestrator/customizations/AGENT-EXPERTISE.md +0 -325
  119. package/src/orchestrator/customizations/AGENT-FAILURES.md +0 -69
  120. package/src/orchestrator/customizations/AGENT-PERFORMANCE.md +0 -55
  121. package/src/orchestrator/customizations/DISPUTES.md +0 -162
  122. package/src/orchestrator/customizations/KNOWLEDGE-GRAPH.md +0 -10
  123. package/src/orchestrator/customizations/agents/skill-matrix.md +0 -111
  124. package/src/orchestrator/customizations/logs/events.ndjson +0 -0
  125. package/src/orchestrator/customizations/project/decisions.md +0 -31
  126. package/src/orchestrator/customizations/project/docs-structure.md +0 -34
  127. package/src/orchestrator/customizations/project/roadmap.md +0 -24
  128. /package/src/orchestrator/{customizations/logs/README.md → skills/observability-logging/LOG-SCHEMA.md} +0 -0
@@ -1,7 +1,22 @@
1
- import { readFile, writeFile, unlink, readdir } from 'node:fs/promises'
1
+ import { readFile, writeFile, unlink, rmdir } from 'node:fs/promises'
2
2
  import { join } from 'node:path'
3
3
  import { existsSync } from 'node:fs'
4
4
  import type { RepoInfo, StackConfig } from './types.js'
5
+ import { readProjectFacts, displayName, type ProjectFacts } from './project-facts.js'
6
+ import { PLUGINS } from '../orchestrator/plugins/index.js'
7
+
8
+ /**
9
+ * Fill `.opencastle/` with what the repository says, on a first install.
10
+ *
11
+ * The files used to be copied as templates and filled at a few markers: a
12
+ * project name, a stack table with `<!-- TODO: verify -->` in every version
13
+ * cell, and a dozen empty tables. Until an agent ran
14
+ * `/oc:bootstrap-customizations`, every skill that sent an agent to them for
15
+ * the project's routes, models or commands sent it to an empty table. Each file
16
+ * is now written whole from the project's own files (`project-facts.ts`): what
17
+ * the code says is there, and what it cannot say is listed at the end, once,
18
+ * instead of left as empty rows.
19
+ */
5
20
 
6
21
  export interface BootstrapResult {
7
22
  populated: string[]
@@ -9,409 +24,355 @@ export interface BootstrapResult {
9
24
  renamed: string[]
10
25
  }
11
26
 
12
- // ── Internal types ─────────────────────────────────────────────
13
-
14
- interface PackageJson {
15
- name?: string
16
- description?: string
17
- scripts?: Record<string, string>
18
- }
27
+ // ── Markdown ───────────────────────────────────────────────────
19
28
 
20
- interface WorkspacePkg {
21
- path: string
22
- name: string
23
- description?: string
24
- }
29
+ /** Every written file starts with this: who wrote it and when, and that it is now the team's. */
30
+ const HEADER =
31
+ `<!-- Written by \`opencastle init\` from the repository on ${new Date().toISOString().slice(0, 10)}. It is yours: correct it and\n` +
32
+ ' add what the code cannot say. No OpenCastle command rewrites it. -->'
25
33
 
26
- // ── Utilities ──────────────────────────────────────────────────
34
+ const code = (s: string): string => '`' + s + '`'
27
35
 
28
- async function tryReadJson<T>(p: string): Promise<T | null> {
29
- try {
30
- return JSON.parse(await readFile(p, 'utf8')) as T
31
- } catch {
32
- return null
33
- }
36
+ function table(head: string[], rows: string[][]): string {
37
+ return [`| ${head.join(' | ')} |`, `|${head.map(() => '---').join('|')}|`, ...rows.map((r) => `| ${r.join(' | ')} |`)].join('\n')
34
38
  }
35
39
 
36
- /**
37
- * Replace the first empty table row within a named markdown section.
38
- * Scopes the search from `sectionMarker` to the next `## ` heading.
39
- */
40
- function fillTableSection(
41
- content: string,
42
- sectionMarker: string,
43
- emptyRow: string,
44
- rows: string[],
45
- ): string {
46
- if (rows.length === 0) return content
47
- const sIdx = content.indexOf(sectionMarker)
48
- if (sIdx === -1) return content
49
- const nextSectionIdx = content.indexOf('\n## ', sIdx + sectionMarker.length)
50
- const end = nextSectionIdx === -1 ? content.length : nextSectionIdx
51
- const slice = content.slice(sIdx, end)
52
- const needle = '\n' + emptyRow
53
- const needleIdx = slice.indexOf(needle)
54
- if (needleIdx === -1) return content
55
- const abs = sIdx + needleIdx + 1 // position of first char of emptyRow (skip \n)
56
- return content.slice(0, abs) + rows.join('\n') + content.slice(abs + emptyRow.length)
40
+ /** `a`, `b`, … — at most `max`, and how many there are when that is not all. */
41
+ function inline(items: string[], max = 12): string {
42
+ const shown = items.slice(0, max).map(code).join(', ')
43
+ return items.length > max ? `${shown}, … (${items.length} in all)` : shown
57
44
  }
58
45
 
59
- function replaceMarker(content: string, marker: string, replacement: string): string {
60
- if (!content.includes(marker)) return content
61
- return content.replace(marker, replacement)
46
+ /** What could not be read from the code, for a person or an agent to add. */
47
+ function stillToDescribe(items: string[]): string {
48
+ return [
49
+ '## Still to describe',
50
+ '',
51
+ '<!-- Add these by hand, or run /oc:bootstrap-customizations to have an agent read the code and fill them in. -->',
52
+ '',
53
+ ...items.map((i) => `- ${i}`),
54
+ ].join('\n')
62
55
  }
63
56
 
64
- function filterConfigFiles(configFiles: string[] | undefined, patterns: string[]): string[] {
65
- if (!configFiles?.length) return []
66
- return configFiles.filter(f => patterns.some(p => f === p || f.endsWith('/' + p) || f.includes(p)))
57
+ function file(...sections: Array<string | null | undefined | false>): string {
58
+ return sections.filter(Boolean).join('\n\n') + '\n'
67
59
  }
68
60
 
69
- // ── Workspace scanning ─────────────────────────────────────────
70
-
71
- async function scanWorkspace(projectRoot: string): Promise<WorkspacePkg[]> {
72
- const packages: WorkspacePkg[] = []
73
- for (const dir of ['apps', 'packages', 'libs']) {
74
- const dirPath = join(projectRoot, dir)
75
- if (!existsSync(dirPath)) continue
76
- let entries: Array<{ name: string; isDirectory(): boolean }> = []
77
- try {
78
- entries = await readdir(dirPath, { withFileTypes: true })
79
- } catch {
80
- continue
81
- }
82
- for (const e of entries) {
83
- if (!e.isDirectory()) continue
84
- const pkg = await tryReadJson<PackageJson>(join(dirPath, e.name, 'package.json'))
85
- packages.push({
86
- path: `${dir}/${e.name}`,
87
- name: pkg?.name ?? `${dir}/${e.name}`,
88
- description: pkg?.description,
89
- })
90
- }
91
- }
92
- return packages
61
+ /** The skill an integration ships, for the line that says which skill reads a file. */
62
+ function skillOf(id: string): string | null {
63
+ return PLUGINS[id]?.skillName ?? null
93
64
  }
94
65
 
95
- // ── Builders ───────────────────────────────────────────────────
96
-
97
- function buildStackRows(info: RepoInfo): string[] {
98
- const rows: string[] = []
99
- const addList = (layer: string, values: string[] | undefined) => {
100
- if (!values?.length) return
101
- for (const v of values) rows.push(`| ${layer} | ${v} | <!-- TODO: verify --> | |`)
102
- }
103
- if (info.language) rows.push(`| Language | ${info.language} | | |`)
104
- if (info.packageManager) rows.push(`| Package Manager | ${info.packageManager} | | |`)
105
- addList('Framework', info.frameworks)
106
- addList('Database', info.databases)
107
- addList('CMS', info.cms)
108
- addList('Deployment', info.deployment)
109
- addList('Testing', info.testing)
110
- addList('CI/CD', info.cicd)
111
- addList('Styling', info.styling)
112
- addList('Auth', info.auth)
113
- return rows
66
+ const READ_BY = (skills: Array<string | null>): string | null => {
67
+ const named = skills.filter((s): s is string => Boolean(s))
68
+ return named.length ? `Read by the ${named.map(code).join(' and ')} skill${named.length > 1 ? 's' : ''}.` : null
114
69
  }
115
70
 
116
- function buildKeyCommandsBlock(pm: string, scripts: Record<string, string>): string {
117
- const commands = (['dev', 'build', 'test', 'lint', 'start'] as const)
118
- .filter(k => scripts[k])
119
- .map(k => `${pm} run ${k}`)
120
- if (commands.length === 0) return ''
121
- return `**Package manager:** \`${pm}\`\n\n\`\`\`bash\n${commands.join('\n')}\n\`\`\``
71
+ function devLine(facts: ProjectFacts): string | null {
72
+ if (!facts.scripts.dev && !facts.scripts.start) return null
73
+ const cmd = `${facts.packageManager} ${facts.scripts.dev ? 'dev' : 'start'}`
74
+ return `Dev server: ${code(cmd)}${facts.devPort ? ` → http://localhost:${facts.devPort}` : ''}`
122
75
  }
123
76
 
124
- // ── Populators ─────────────────────────────────────────────────
125
-
126
- async function populateProjectInstructions(
127
- opencastleDir: string,
128
- projectRoot: string,
129
- info: RepoInfo,
130
- pkg: PackageJson,
131
- result: BootstrapResult,
132
- ): Promise<void> {
133
- const filePath = join(opencastleDir, 'project.instructions.md')
134
- if (!existsSync(filePath)) return
135
- let content = await readFile(filePath, 'utf8')
136
- const orig = content
137
-
138
- // Overview: project name + description
139
- if (pkg.name || pkg.description) {
140
- const parts: string[] = []
141
- if (pkg.name) parts.push(`**Project:** ${pkg.name}`)
142
- if (pkg.description) parts.push(`**Description:** ${pkg.description}`)
143
- content = replaceMarker(
144
- content,
145
- '<!-- Project name, description, and current status -->',
146
- parts.join('\n\n'),
147
- )
148
- }
149
-
150
- // Tech stack table
151
- content = fillTableSection(content, '## Tech Stack', '| | | | |', buildStackRows(info))
152
-
153
- // Key commands
154
- if (pkg.scripts) {
155
- const pm = info.packageManager ?? 'npm'
156
- const cmdBlock = buildKeyCommandsBlock(pm, pkg.scripts)
157
- if (cmdBlock) {
158
- content = replaceMarker(
159
- content,
160
- '<!-- Package manager and common development commands -->',
161
- '<!-- Package manager and common development commands -->\n\n' + cmdBlock,
162
- )
163
- }
164
- }
165
-
166
- // Monorepo workspace packages
167
- if (info.monorepo) {
168
- const workspaces = await scanWorkspace(projectRoot)
169
- if (workspaces.length > 0) {
170
- const pkgRows = workspaces.map(w => {
171
- const cell =
172
- w.name !== w.path ? `\`${w.path}\` (\`${w.name}\`)` : `\`${w.path}\``
173
- return `| ${cell} | ${w.description ?? '<!-- TODO: verify -->'} |`
174
- })
175
- content = fillTableSection(content, '## Project Structure', '| | |', pkgRows)
176
- }
177
- }
178
-
179
- if (content !== orig) {
180
- await writeFile(filePath, content, 'utf8')
181
- result.populated.push('project.instructions.md')
182
- }
77
+ // ── project.instructions.md ────────────────────────────────────
78
+
79
+ const SCRIPT_ORDER = ['dev', 'build', 'start', 'test', 'lint', 'typecheck', 'type-check', 'format']
80
+
81
+ function keyCommands(facts: ProjectFacts): string | null {
82
+ const names = Object.keys(facts.scripts).filter((s) => !/^(pre|post)/.test(s))
83
+ if (names.length === 0) return null
84
+ names.sort((a, b) => {
85
+ const ia = SCRIPT_ORDER.indexOf(a)
86
+ const ib = SCRIPT_ORDER.indexOf(b)
87
+ return (ia === -1 ? 99 : ia) - (ib === -1 ? 99 : ib) || a.localeCompare(b)
88
+ })
89
+ // npm runs `test` and `start` directly and everything else through `run`; pnpm, yarn and bun run any script by name.
90
+ const run = (s: string) => (facts.packageManager !== 'npm' || s === 'test' || s === 'start' ? `${facts.packageManager} ${s}` : `npm run ${s}`)
91
+ const width = Math.max(...names.slice(0, 14).map((s) => run(s).length))
92
+ const lines = names.slice(0, 14).map((s) => `${run(s).padEnd(width)} # ${facts.scripts[s].slice(0, 70)}`)
93
+ const ci = facts.ciCommands.length
94
+ ? ['', `CI (${inline(facts.ciWorkflows, 3)}) runs: ${inline(facts.ciCommands, 8)} — a change passes these before it merges.`]
95
+ : []
96
+ return ['## Key Commands', '', devLine(facts) ?? '', '', '```bash', ...lines, '```', ...ci].filter((l, i, a) => l !== '' || a[i - 1] !== '').join('\n')
183
97
  }
184
98
 
185
- async function populateTestingConfig(
186
- opencastleDir: string,
187
- info: RepoInfo,
188
- result: BootstrapResult,
189
- ): Promise<void> {
190
- const filePath = join(opencastleDir, 'stack', 'testing-config.md')
191
- if (!existsSync(filePath)) return
192
-
193
- if (!info.testing?.length) {
194
- await unlink(filePath)
195
- result.removed.push('stack/testing-config.md')
196
- return
197
- }
198
-
199
- let content = await readFile(filePath, 'utf8')
200
- const orig = content
201
-
202
- const introLine = 'Project-specific testing details referenced by the `browser-testing` skill.'
203
- if (content.includes(introLine)) {
204
- // Strip any previously-added content to make this idempotent
205
- const existingAdditionRegex = /\n\n\*\*Test frameworks:\*\*[^\n]*(\n\n\*\*Config files:\*\*[^\n]*)?/;
206
- content = content.replace(existingAdditionRegex, '');
207
-
208
- const cfg = filterConfigFiles(info.configFiles, [
209
- 'vitest.config.ts',
210
- 'vitest.config.js',
211
- 'jest.config.ts',
212
- 'jest.config.js',
213
- 'playwright.config.ts',
214
- 'playwright.config.js',
215
- ])
216
- let addition = `\n\n**Test frameworks:** ${info.testing.join(', ')}`
217
- if (cfg.length > 0) {
218
- addition += `\n\n**Config files:** ${cfg.map(f => `\`${f}\``).join(', ')}`
219
- }
220
- content = content.replace(introLine, introLine + addition)
221
- }
222
-
223
- if (content !== orig) {
224
- await writeFile(filePath, content, 'utf8')
225
- result.populated.push('stack/testing-config.md')
226
- }
99
+ /** Which page roots belong to which framework integration. */
100
+ const PAGE_ROOT: Record<string, RegExp> = {
101
+ nextjs: /(^|\/)(src\/)?(app|pages)\/$/, astro: /(^|\/)src\/pages\/$/, sveltekit: /(^|\/)src\/routes\/$/, remix: /(^|\/)app\/routes\/$/,
227
102
  }
228
103
 
229
- async function populateDeploymentConfig(
230
- opencastleDir: string,
231
- info: RepoInfo,
232
- result: BootstrapResult,
233
- ): Promise<void> {
234
- const filePath = join(opencastleDir, 'stack', 'deployment-config.md')
235
- if (!existsSync(filePath)) return
236
-
237
- if (!info.deployment?.length) {
238
- await unlink(filePath)
239
- result.removed.push('stack/deployment-config.md')
240
- return
241
- }
104
+ const DOMAIN: Record<string, string> = {
105
+ framework: 'Framework', database: 'Database', cms: 'CMS', deployment: 'Deployment', 'codebase-tool': 'Build tooling',
106
+ testing: 'Testing', 'e2e-testing': 'Browser testing', design: 'Design', email: 'Email', payments: 'Payments',
107
+ observability: 'Observability', notifications: 'Notifications', 'task-management': 'Tasks', 'knowledge-management': 'Docs',
108
+ }
242
109
 
243
- let content = await readFile(filePath, 'utf8')
244
- const orig = content
245
-
246
- const archMarker =
247
- '<!-- Describe the deployment platform, CI/CD pipeline, and trigger mechanism. -->'
248
- if (content.includes(archMarker)) {
249
- const cfg = filterConfigFiles(info.configFiles, [
250
- 'vercel.json',
251
- 'netlify.toml',
252
- 'Dockerfile',
253
- 'docker-compose.yml',
254
- 'docker-compose.yaml',
255
- 'fly.toml',
256
- 'render.yaml',
257
- ])
258
- let addition = `**Platform:** ${info.deployment.join(', ')}`
259
- if (cfg.length > 0) {
260
- addition += `\n\n**Config files:** ${cfg.map(f => `\`${f}\``).join(', ')}`
110
+ function domainRows(facts: ProjectFacts, stack: StackConfig): string[][] {
111
+ const configs = facts.configPaths
112
+ // Shallowest first: the root `turbo.json` before each app's.
113
+ const named = (prefix: string) =>
114
+ configs.filter((f) => f.split('/').pop()!.startsWith(prefix)).sort((a, b) => a.split('/').length - b.split('/').length)
115
+ const rows: string[][] = []
116
+ for (const id of stack.techTools) {
117
+ const plugin = PLUGINS[id]
118
+ if (!plugin?.skillName) continue
119
+ const label = id === 'nextjs' ? 'next' : id
120
+ let paths: string[] = []
121
+ switch (plugin.subCategory) {
122
+ case 'framework':
123
+ paths = [
124
+ ...facts.pages.map((p) => p.root).filter((r) => PAGE_ROOT[id]?.test(r)),
125
+ ...named(`${label}.config`),
126
+ ...(id === 'expo' ? [...named('app.json'), ...named('app.config')] : []),
127
+ ]
128
+ break
129
+ case 'database':
130
+ paths = [facts.models?.source ?? '', facts.migrations?.dir ?? '', ...(facts.importers[label] ?? []).slice(0, 1)]
131
+ break
132
+ case 'testing':
133
+ case 'e2e-testing':
134
+ paths = named(`${label}.config`)
135
+ break
136
+ case 'deployment':
137
+ case 'codebase-tool':
138
+ paths = id === 'turborepo' ? named('turbo.json') : id === 'nx' ? named('nx.json') : configs.filter((f) => f.includes(label))
139
+ break
140
+ default:
141
+ paths = facts.importers[label] ?? named(`${label}.config`)
261
142
  }
262
- content = content.replace(archMarker, addition + '\n\n' + archMarker)
263
- }
264
-
265
- if (content !== orig) {
266
- await writeFile(filePath, content, 'utf8')
267
- result.populated.push('stack/deployment-config.md')
143
+ const unique = [...new Set(paths.filter(Boolean))]
144
+ const where = unique.length
145
+ ? inline(unique, 3)
146
+ : plugin.subCategory === 'e2e-testing' && facts.devPort ? `http://localhost:${facts.devPort}` : '—'
147
+ rows.push([DOMAIN[plugin.subCategory] ?? plugin.subCategory, code(plugin.skillName), where])
268
148
  }
149
+ const ui = facts.dirs.find((d) => /^(src\/)?components\/$/.test(d.path))
150
+ if (ui) rows.push(['UI', code('frontend-design'), code(ui.path)])
151
+ return rows
269
152
  }
270
153
 
271
- async function handleDatabaseConfig(
272
- opencastleDir: string,
273
- info: RepoInfo,
274
- result: BootstrapResult,
275
- ): Promise<void> {
276
- const filePath = join(opencastleDir, 'stack', 'database-config.md')
277
- if (!existsSync(filePath)) return
154
+ function renderProjectInstructions(facts: ProjectFacts, info: RepoInfo, stack: StackConfig): string {
155
+ const about = [
156
+ facts.name ? `**${facts.name}**` : null,
157
+ facts.description ? `— ${facts.description}` : null,
158
+ ].filter(Boolean).join(' ')
159
+ const language = { typescript: 'TypeScript', javascript: 'JavaScript' }[facts.language ?? ''] ?? facts.language
160
+ const basics = [language, facts.nodeVersion ? `Node ${facts.nodeVersion}` : null, `package manager ${code(facts.packageManager)}`, facts.workspaces.length ? `${info.monorepo ?? 'workspaces'} monorepo` : null]
161
+ .filter(Boolean).join(' · ')
162
+
163
+ const stackRows = facts.stack.map((s) => [s.layer, s.name, s.version ?? '—'])
164
+ for (const d of info.deployment ?? []) stackRows.push(['Deployment', displayName(d), '—'])
165
+ for (const c of info.cicd ?? []) stackRows.push(['CI', displayName(c), '—'])
166
+
167
+ const routes = facts.pages.map((p) => `${p.routes.length} page${p.routes.length === 1 ? '' : 's'} in ${code(p.root)}: ${inline(p.routes, 20)}`)
168
+ const apiParts = [
169
+ facts.api.length ? `${facts.api.length} API endpoint${facts.api.length === 1 ? '' : 's'}` : null,
170
+ facts.rpcRouters.length ? `${facts.rpcRouters.length} tRPC router file${facts.rpcRouters.length === 1 ? '' : 's'}` : null,
171
+ ].filter(Boolean)
172
+ const api = apiParts.length ? `${apiParts.join(' and ')}, listed in ${code('.opencastle/stack/api-config.md')}.` : null
173
+
174
+ const missing = [
175
+ 'Architecture — how the parts fit together, and what talks to what',
176
+ 'Production URLs and environments',
177
+ ...(facts.dirs.some((d) => !d.purpose) || facts.workspaces.some((w) => !w.purpose) ? ['What the folders without a purpose above hold'] : []),
178
+ ]
179
+
180
+ return file(
181
+ '# Project Context',
182
+ HEADER,
183
+ [about, basics].filter(Boolean).join('\n\n'),
184
+ stackRows.length ? ['## Tech Stack', '', table(['Layer', 'Technology', 'Version'], stackRows)].join('\n') : null,
185
+ facts.workspaces.length
186
+ ? ['## Workspaces', '', table(['Path', 'Package', 'Purpose'], facts.workspaces.map((w) => [code(w.path), code(w.name), w.purpose]))].join('\n')
187
+ : null,
188
+ facts.dirs.length ? ['## Project Structure', '', table(['Path', 'Purpose'], facts.dirs.map((d) => [code(d.path), d.purpose]))].join('\n') : null,
189
+ keyCommands(facts),
190
+ routes.length || api ? ['## Routes', ...routes, ...(api ? [api] : [])].join('\n\n') : null,
191
+ facts.envVars ? ['## Environment', '', `Names from ${code(facts.envVars.source)} — values never belong here: ${inline(facts.envVars.names, 30)}`].join('\n') : null,
192
+ facts.docs.length ? ['## Key Documentation', '', ...facts.docs.map((d) => `- ${code(d)}`)].join('\n') : null,
193
+ (() => {
194
+ const rows = domainRows(facts, stack)
195
+ return rows.length ? ['## Domain Quick Reference', '', table(['Domain', 'Skill', 'Key paths'], rows)].join('\n') : null
196
+ })(),
197
+ stillToDescribe(missing),
198
+ )
199
+ }
278
200
 
279
- if (!info.databases?.length) {
280
- await unlink(filePath)
281
- result.removed.push('stack/database-config.md')
282
- return
283
- }
201
+ // ── stack/*.md ─────────────────────────────────────────────────
202
+
203
+ /** The frameworks that serve an API, in the order one is named for it. */
204
+ const SERVES_API = ['Next.js', 'Astro', 'SvelteKit', 'Remix', 'Nuxt', 'Express', 'Fastify', 'Hono']
205
+
206
+ function renderApiConfig(facts: ProjectFacts, info: RepoInfo): string {
207
+ const frameworks = facts.stack.filter((s) => s.layer === 'Framework')
208
+ const fw = SERVES_API.map((n) => frameworks.find((s) => s.name === n)).find(Boolean) ?? frameworks[0]
209
+ const services = (info.services ?? []).filter((s) => facts.importers[s]?.length)
210
+ return file(
211
+ '# API Configuration',
212
+ HEADER,
213
+ [fw ? `Framework: ${fw.name}${fw.version ? ` ${fw.version}` : ''}.` : null, READ_BY(['api-patterns'])].filter(Boolean).join(' '),
214
+ ['## Endpoints', '', facts.api.length
215
+ ? table(['Endpoint', 'Methods', 'File'], facts.api.map((a) => [code(a.route), a.methods.join(', ') || '—', code(a.file)]))
216
+ : facts.rpcRouters.length ? 'No route files: the API is tRPC, below.' : 'None found in route files.'].join('\n'),
217
+ facts.rpcRouters.length ? ['## tRPC routers', '', ...facts.rpcRouters.map((f) => `- ${code(f)}`)].join('\n') : null,
218
+ facts.serverActions.length ? ['## Server Actions', '', ...facts.serverActions.map((f) => `- ${code(f)}`)].join('\n') : null,
219
+ facts.middleware ? ['## Middleware', '', `${code(facts.middleware)} runs before matching requests.`].join('\n') : null,
220
+ services.length
221
+ ? ['## External APIs', '', table(['Service', 'Used in'], services.map((s) => [displayName(s), inline(facts.importers[s], 3)]))].join('\n')
222
+ : null,
223
+ stillToDescribe(['Who may call each endpoint, and how it is authorized', 'Rate limits, caching and error format']),
224
+ )
225
+ }
284
226
 
285
- let content = await readFile(filePath, 'utf8')
286
- const provider = info.databases[0]
287
-
288
- const integrationMarker =
289
- '<!-- Auth library path, migration directory, session pattern, role system overview. -->'
290
- if (content.includes(integrationMarker)) {
291
- const cfg = filterConfigFiles(info.configFiles, [
292
- 'supabase/config.toml',
293
- 'prisma/schema.prisma',
294
- 'drizzle.config.ts',
295
- 'drizzle.config.js',
296
- ])
297
- let addition = `**Provider:** ${provider}`
298
- if (cfg.length > 0) {
299
- addition += `\n\n**Config files:** ${cfg.map(f => `\`${f}\``).join(', ')}`
300
- }
301
- addition += '\n\n<!-- TODO: verify -->'
302
- content = content.replace(integrationMarker, addition + '\n\n' + integrationMarker)
303
- }
227
+ function renderDatabaseConfig(facts: ProjectFacts, provider: string): string {
228
+ const version = facts.stack.find((s) => s.layer === 'Database' && s.name === displayName(provider))?.version
229
+ const client = facts.importers[provider]?.[0]
230
+ const env = facts.envVars?.names.filter((n) => /DATABASE|DB_|POSTGRES|MYSQL|MONGO|SUPABASE|CONVEX|TURSO|REDIS/.test(n)) ?? []
231
+ return file(
232
+ `# ${displayName(provider)} Configuration`,
233
+ HEADER,
234
+ READ_BY([skillOf(provider)]),
235
+ [
236
+ version ? `**Version:** ${version}` : null,
237
+ facts.models ? `**Schema:** ${code(facts.models.source)}` : null,
238
+ client ? `**Client:** ${code(client)}` : null,
239
+ ].filter(Boolean).join(' · ') || null,
240
+ facts.models?.names.length ? ['## Models', '', inline(facts.models.names, 60)].join('\n') : null,
241
+ facts.migrations
242
+ ? ['## Migrations', '', `${facts.migrations.count} in ${code(facts.migrations.dir)}; the latest: ${inline(facts.migrations.latest)}.`].join('\n')
243
+ : null,
244
+ env.length ? ['## Environment', '', inline(env)].join('\n') : null,
245
+ stillToDescribe([
246
+ 'What each model holds, and how they relate',
247
+ provider === 'supabase' ? 'Row-level security: which policies guard which tables' : 'Who may read and write what, and where that is enforced',
248
+ 'How a schema change is made and rolled out',
249
+ ]),
250
+ )
251
+ }
304
252
 
305
- if (info.databases.length === 1) {
306
- const newName = `${provider}-config.md`
307
- const newPath = join(opencastleDir, 'stack', newName)
308
- await writeFile(newPath, content, 'utf8')
309
- await unlink(filePath)
310
- result.renamed.push(`stack/database-config.md \u2192 stack/${newName}`)
311
- } else {
312
- await writeFile(filePath, content, 'utf8')
313
- result.populated.push('stack/database-config.md')
314
- }
253
+ function renderCmsConfig(facts: ProjectFacts, provider: string): string {
254
+ const configs = facts.configPaths.filter((f) => f.split('/').pop()!.startsWith(`${provider}.config`))
255
+ const used = facts.importers[provider] ?? []
256
+ return file(
257
+ `# ${displayName(provider)} Configuration`,
258
+ HEADER,
259
+ READ_BY([skillOf(provider)]),
260
+ configs.length ? `**Config:** ${inline(configs)}` : null,
261
+ used.length ? ['## Used in', '', inline(used)].join('\n') : null,
262
+ stillToDescribe(['Project and dataset IDs (never tokens)', 'Document types and their key fields', 'How content is queried, with an example']),
263
+ )
315
264
  }
316
265
 
317
- async function handleCmsConfig(
318
- opencastleDir: string,
319
- info: RepoInfo,
320
- result: BootstrapResult,
321
- ): Promise<void> {
322
- const filePath = join(opencastleDir, 'stack', 'cms-config.md')
323
- if (!existsSync(filePath)) return
266
+ function renderTestingConfig(facts: ProjectFacts, info: RepoInfo, browserChecks: boolean): string {
267
+ const dirs = [...new Set(facts.testFiles.map((f) => f.split('/').slice(0, -1).join('/') || '.'))].slice(0, 6)
268
+ const testScripts = Object.keys(facts.scripts).filter((s) => /^(test|e2e)/.test(s)).map((s) => `${facts.packageManager} run ${s}`)
269
+ const configs = facts.testConfigs
270
+ const frameworks = facts.testFrameworks.length ? facts.testFrameworks : (info.testing ?? []).map(displayName)
271
+ const bp = facts.breakpoints
272
+ return file(
273
+ '# Testing Configuration',
274
+ HEADER,
275
+ READ_BY(['testing-workflow', browserChecks ? 'browser-testing' : null]),
276
+ [
277
+ frameworks.length ? `**Frameworks:** ${frameworks.join(', ')}${configs.length ? ` (${inline(configs)})` : ''}` : '**Frameworks:** none in package.json.',
278
+ facts.testFiles.length ? `**Test files:** ${facts.testFiles.length}, in ${inline(dirs, 6)}` : '**Test files:** none found.',
279
+ testScripts.length ? `**Run:** ${inline(testScripts)}` : null,
280
+ facts.coverage.length ? `**Coverage required:** ${facts.coverage.join(', ')} (from the test config)` : null,
281
+ ].filter(Boolean).join('\n\n'),
282
+ browserChecks
283
+ ? [
284
+ '## Browser checks',
285
+ '',
286
+ devLine(facts) ?? 'Dev server: not found in package.json.',
287
+ bp ? `\nBreakpoints (${bp.source}): ${bp.values.map(([n, v]) => `${n} ${v}`).join(' · ')}` : '',
288
+ ].join('\n')
289
+ : null,
290
+ stillToDescribe([
291
+ 'Selector conventions (`data-testid` or roles) and test data',
292
+ ...(facts.testFiles.length ? [] : ['Where new tests go, and with which framework']),
293
+ ]),
294
+ )
295
+ }
324
296
 
325
- if (!info.cms?.length) {
326
- await unlink(filePath)
327
- result.removed.push('stack/cms-config.md')
328
- return
329
- }
297
+ function renderDeploymentConfig(facts: ProjectFacts, info: RepoInfo): string {
298
+ const platforms = (info.deployment ?? []).map(displayName)
299
+ const configs = facts.configPaths.filter((f) =>
300
+ /(^|\/)(vercel\.json|netlify\.toml|Dockerfile|(docker-)?compose\.ya?ml|fly\.toml|render\.yaml|wrangler\.(toml|jsonc?))$/.test(f),
301
+ )
302
+ return file(
303
+ '# Deployment Configuration',
304
+ HEADER,
305
+ READ_BY([...(info.deployment ?? []).map((d) => skillOf(d)), 'deployment-infrastructure']),
306
+ [
307
+ `**Platform:** ${platforms.join(', ')}`,
308
+ configs.length ? `**Config:** ${inline(configs)}` : null,
309
+ facts.scripts.build ? `**Build:** ${code(`${facts.packageManager} run build`)}` : null,
310
+ facts.ciWorkflows.length ? `**CI:** ${inline(facts.ciWorkflows)}` : null,
311
+ ].filter(Boolean).join('\n\n'),
312
+ facts.envVars ? ['## Environment', '', `Names from ${code(facts.envVars.source)}: ${inline(facts.envVars.names, 30)}`].join('\n') : null,
313
+ stillToDescribe(['Environments and their URLs', 'Scheduled jobs, security headers and caching', 'How a release is rolled back']),
314
+ )
315
+ }
330
316
 
331
- let content = await readFile(filePath, 'utf8')
332
- const provider = info.cms[0]
333
-
334
- const configMarker = '<!-- CMS project IDs, dataset, API version, studio location, etc. -->'
335
- if (content.includes(configMarker)) {
336
- const cfg = filterConfigFiles(info.configFiles, [
337
- 'sanity.config.ts',
338
- 'sanity.config.js',
339
- '.contentful.json',
340
- 'payload.config.ts',
341
- ])
342
- let addition = `**Provider:** ${provider}`
343
- if (cfg.length > 0) {
344
- addition += `\n\n**Config files:** ${cfg.map(f => `\`${f}\``).join(', ')}`
345
- }
346
- addition += '\n\n<!-- TODO: verify -->'
347
- content = content.replace(configMarker, addition + '\n\n' + configMarker)
317
+ /** The Deepen-Plan scopes in the agent registry, with this project's directories. */
318
+ async function fillAgentRegistry(opencastleDir: string, facts: ProjectFacts, result: BootstrapResult): Promise<void> {
319
+ const path = join(opencastleDir, 'agents', 'agent-registry.md')
320
+ if (!existsSync(path)) return
321
+ const text = await readFile(path, 'utf8')
322
+ const has = (p: string) => facts.dirs.find((d) => d.path === p || d.path === `src/${p}`)?.path
323
+ const backend = [facts.migrations?.dir, ...['prisma/', 'supabase/', 'drizzle/', 'db/', 'convex/', 'server/', 'lib/'].map(has)].filter(Boolean) as string[]
324
+ const frontend = [...facts.pages.map((p) => p.root), ...['components/', 'ui/', 'styles/'].map(has)].filter(Boolean) as string[]
325
+ for (const w of facts.workspaces) {
326
+ if (/^packages\/(db|database|api)\/$/.test(w.path)) backend.push(w.path)
327
+ if (/^packages\/(ui|components)\/$/.test(w.path)) frontend.push(w.path)
348
328
  }
349
-
350
- if (info.cms.length === 1) {
351
- const newName = `${provider}-config.md`
352
- const newPath = join(opencastleDir, 'stack', newName)
353
- await writeFile(newPath, content, 'utf8')
354
- await unlink(filePath)
355
- result.renamed.push(`stack/cms-config.md \u2192 stack/${newName}`)
356
- } else {
357
- await writeFile(filePath, content, 'utf8')
358
- result.populated.push('stack/cms-config.md')
329
+ const content = ['content/', 'studio/', 'sanity/', 'cms/'].map(has).filter(Boolean) as string[]
330
+ // A directory inside another one listed is already in scope.
331
+ const scope = (paths: string[]) => {
332
+ const unique = [...new Set(paths)]
333
+ return unique.filter((p) => !unique.some((q) => q !== p && p.startsWith(q))).join(', ')
359
334
  }
335
+ const lines: string[] = []
336
+ if (backend.length) lines.push('Researcher A: "Research database/backend aspects of [feature]"', ` Scope: ${scope(backend)}`, '')
337
+ if (frontend.length) lines.push('Researcher B: "Research frontend/UI aspects of [feature]"', ` Scope: ${scope(frontend)}`, '')
338
+ if (content.length) lines.push('Researcher C: "Research content aspects of [feature]"', ` Scope: ${scope(content)}`, '')
339
+ if (lines.length === 0) return
340
+ const next = text.replace(/```\nResearcher A:[\s\S]*?```/, '```\n' + lines.join('\n').trimEnd() + '\n```')
341
+ .replace(/<!-- Customize these paths[\s\S]*?-->\n\n/, '')
342
+ if (next === text) return
343
+ await writeFile(path, next, 'utf8')
344
+ result.populated.push('agents/agent-registry.md')
360
345
  }
361
346
 
362
- async function removeNotificationsIfUnused(
363
- opencastleDir: string,
364
- info: RepoInfo,
365
- result: BootstrapResult,
366
- ): Promise<void> {
367
- const filePath = join(opencastleDir, 'stack', 'notifications-config.md')
368
- if (!existsSync(filePath) || info.notifications?.length) return
369
- await unlink(filePath)
370
- result.removed.push('stack/notifications-config.md')
371
- }
347
+ // ── Writing ────────────────────────────────────────────────────
372
348
 
373
- async function handleApiConfig(
349
+ async function writeOrRemove(
374
350
  opencastleDir: string,
375
- info: RepoInfo,
351
+ rel: string,
352
+ content: string | null,
376
353
  result: BootstrapResult,
354
+ as?: string,
377
355
  ): Promise<void> {
378
- const filePath = join(opencastleDir, 'stack', 'api-config.md')
379
- if (!existsSync(filePath)) return
380
-
381
- if (!info.frameworks?.length) {
382
- await unlink(filePath)
383
- result.removed.push('stack/api-config.md')
356
+ const from = join(opencastleDir, rel)
357
+ if (!existsSync(from)) return
358
+ if (content === null) {
359
+ await unlink(from)
360
+ result.removed.push(rel)
384
361
  return
385
362
  }
386
-
387
- let content = await readFile(filePath, 'utf8')
388
- const orig = content
389
-
390
- const initMarker =
391
- '<!-- Populated by `opencastle init` based on detected API routes and Server Actions. -->'
392
- if (content.includes(initMarker)) {
393
- const frameworkList = info.frameworks.join(', ')
394
- content = content.replace(
395
- initMarker,
396
- `<!-- Populated by \`opencastle init\`. Framework: ${frameworkList} -->`,
397
- )
398
- }
399
-
400
- if (content !== orig) {
401
- await writeFile(filePath, content, 'utf8')
402
- result.populated.push('stack/api-config.md')
363
+ if (as && as !== rel) {
364
+ await writeFile(join(opencastleDir, as), content, 'utf8')
365
+ await unlink(from)
366
+ result.renamed.push(`${rel} → ${as}`)
367
+ return
403
368
  }
369
+ await writeFile(from, content, 'utf8')
370
+ result.populated.push(rel)
404
371
  }
405
372
 
406
- async function removeDataPipelineConfig(
407
- opencastleDir: string,
408
- result: BootstrapResult,
409
- ): Promise<void> {
410
- const filePath = join(opencastleDir, 'stack', 'data-pipeline-config.md')
411
- if (!existsSync(filePath)) return
412
- await unlink(filePath)
413
- result.removed.push('stack/data-pipeline-config.md')
414
- }
373
+ /** Test frameworks a project runs itself; an integration like Chrome DevTools is not one. */
374
+ const TEST_FRAMEWORKS = new Set(['jest', 'vitest', 'playwright', 'cypress', 'mocha'])
375
+ const BROWSER_CHECKS = new Set(['chrome-devtools', 'playwright', 'cypress'])
415
376
 
416
377
  export const TRACKER_TOOLS = new Set<string>(['linear', 'jira', 'trello'])
417
378
 
@@ -435,23 +396,27 @@ async function handleTrackerConfig(
435
396
  }
436
397
 
437
398
  let content = await readFile(filePath, 'utf8')
438
- const displayName = tracker.charAt(0).toUpperCase() + tracker.slice(1)
399
+ const displayed = tracker.charAt(0).toUpperCase() + tracker.slice(1)
439
400
 
440
- content = content.replace('# Task Tracker Configuration', `# ${displayName} Configuration`)
401
+ content = content.replace('# Task Tracker Configuration', `# ${displayed} Configuration`)
441
402
 
442
403
  const renameComment =
443
404
  '<!-- Populated by `opencastle init`.\n Rename this file to match your tracker: linear-config.md, jira-config.md, etc. -->'
444
405
  content = content.replace(renameComment + '\n', '')
445
406
 
446
407
  const newName = `${tracker}-config.md`
447
- const newPath = join(opencastleDir, 'project', newName)
448
- await writeFile(newPath, content, 'utf8')
408
+ await writeFile(join(opencastleDir, 'project', newName), content, 'utf8')
449
409
  await unlink(filePath)
450
- result.renamed.push(`project/tracker-config.md \u2192 project/${newName}`)
410
+ result.renamed.push(`project/tracker-config.md → project/${newName}`)
451
411
  }
452
412
 
453
413
  // ── Main export ────────────────────────────────────────────────
454
414
 
415
+ /**
416
+ * `repoInfo` is the detection merged with the selected integrations; the facts
417
+ * are read from the files, so a selected integration the project does not use
418
+ * — Chrome DevTools — is never listed as one of its test frameworks.
419
+ */
455
420
  export async function bootstrapCustomizations(
456
421
  projectRoot: string,
457
422
  repoInfo: RepoInfo,
@@ -460,18 +425,41 @@ export async function bootstrapCustomizations(
460
425
  const opencastleDir = join(projectRoot, '.opencastle')
461
426
  const result: BootstrapResult = { populated: [], removed: [], renamed: [] }
462
427
 
463
- const pkg = (await tryReadJson<PackageJson>(join(projectRoot, 'package.json'))) ?? {}
428
+ const testing = (repoInfo.testing ?? []).filter((t) => TEST_FRAMEWORKS.has(t))
429
+ const facts = await readProjectFacts(projectRoot, { ...repoInfo, testing })
430
+
431
+ if (existsSync(join(opencastleDir, 'project.instructions.md'))) {
432
+ await writeFile(join(opencastleDir, 'project.instructions.md'), renderProjectInstructions(facts, repoInfo, stack), 'utf8')
433
+ result.populated.push('project.instructions.md')
434
+ }
464
435
 
465
- await populateProjectInstructions(opencastleDir, projectRoot, repoInfo, pkg, result)
466
- await populateTestingConfig(opencastleDir, repoInfo, result)
467
- await populateDeploymentConfig(opencastleDir, repoInfo, result)
468
- await handleDatabaseConfig(opencastleDir, repoInfo, result)
469
- await handleCmsConfig(opencastleDir, repoInfo, result)
470
- await removeNotificationsIfUnused(opencastleDir, repoInfo, result)
471
- await handleApiConfig(opencastleDir, repoInfo, result)
472
- await removeDataPipelineConfig(opencastleDir, result)
436
+ const browserChecks = [...stack.techTools].some((t) => BROWSER_CHECKS.has(t))
437
+ await writeOrRemove(opencastleDir, 'stack/testing-config.md',
438
+ testing.length || facts.testFiles.length || browserChecks ? renderTestingConfig(facts, { ...repoInfo, testing }, browserChecks) : null, result)
439
+ await writeOrRemove(opencastleDir, 'stack/deployment-config.md',
440
+ repoInfo.deployment?.length ? renderDeploymentConfig(facts, repoInfo) : null, result)
441
+ await writeOrRemove(opencastleDir, 'stack/api-config.md',
442
+ repoInfo.frameworks?.length ? renderApiConfig(facts, repoInfo) : null, result)
443
+
444
+ // One provider gets a file named after it; several share the generic one.
445
+ const databases = repoInfo.databases ?? []
446
+ await writeOrRemove(opencastleDir, 'stack/database-config.md',
447
+ databases.length ? renderDatabaseConfig(facts, databases[0]) : null, result,
448
+ databases.length === 1 ? `stack/${databases[0]}-config.md` : undefined)
449
+ const cms = repoInfo.cms ?? []
450
+ await writeOrRemove(opencastleDir, 'stack/cms-config.md',
451
+ cms.length ? renderCmsConfig(facts, cms[0]) : null, result,
452
+ cms.length === 1 ? `stack/${cms[0]}-config.md` : undefined)
453
+
454
+ if (!repoInfo.notifications?.length) await writeOrRemove(opencastleDir, 'stack/notifications-config.md', null, result)
455
+ await writeOrRemove(opencastleDir, 'stack/data-pipeline-config.md', null, result)
473
456
  await handleTrackerConfig(opencastleDir, repoInfo, stack, result)
474
457
  await removeUnusedProviderTemplates(opencastleDir, repoInfo, result)
458
+ await fillAgentRegistry(opencastleDir, facts, result)
459
+
460
+ // A folder whose every template was left out is not left behind empty: with
461
+ // no tracker, `project/` held nothing else.
462
+ for (const dir of ['project', 'stack']) await rmdir(join(opencastleDir, dir)).catch(() => {})
475
463
 
476
464
  return result
477
465
  }
@@ -489,10 +477,10 @@ async function removeUnusedProviderTemplates(
489
477
  ): Promise<void> {
490
478
  const inUse = new Set<string>([...(info.databases ?? []), ...(info.cms ?? [])])
491
479
  for (const provider of ['supabase', 'sanity']) {
492
- if (inUse.has(provider)) continue
493
480
  const rel = `stack/${provider}-config.md`
494
481
  const abs = join(opencastleDir, rel)
495
482
  if (!existsSync(abs)) continue
483
+ if (inUse.has(provider)) continue
496
484
  await unlink(abs)
497
485
  result.removed.push(rel)
498
486
  }