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