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
@@ -0,0 +1,647 @@
1
+ import { existsSync } from 'node:fs'
2
+ import { readdir, readFile } from 'node:fs/promises'
3
+ import { join } from 'node:path'
4
+ import { PACKAGE_DETECTIONS } from './detect.js'
5
+
6
+ /**
7
+ * What a project is, read from its files: the facts `init` writes into
8
+ * `.opencastle/` on a first install.
9
+ *
10
+ * The customization files used to be templates with empty tables and
11
+ * `TODO: verify` in every version cell, waiting for an agent to fill them in —
12
+ * and until one did, every skill that sent an agent to them sent it to nothing.
13
+ * Most of what they ask for is in the repository already: the routes are
14
+ * files, the API is files, the models are in the schema, the commands are in
15
+ * package.json. Everything here is deterministic and bounded; anything that
16
+ * needs judgement — architecture, production URLs — is left for a person or
17
+ * `/oc:bootstrap-customizations`.
18
+ */
19
+
20
+ export interface ProjectFacts {
21
+ name?: string
22
+ description?: string
23
+ packageManager: string
24
+ language?: string
25
+ scripts: Record<string, string>
26
+ /** Detected technologies with the version a package.json declares. */
27
+ stack: Array<{ layer: string; name: string; version?: string }>
28
+ /** Top-level directories, and `src/`'s, with what they hold when the name says. */
29
+ dirs: Array<{ path: string; purpose: string }>
30
+ /** Workspace packages of a monorepo, with what each is when it can be told. */
31
+ workspaces: Array<{ path: string; name: string; purpose: string }>
32
+ devPort?: number
33
+ /** Each place pages live, e.g. `app/` or `apps/web/src/app/`, with their URLs. */
34
+ pages: Array<{ root: string; routes: string[] }>
35
+ api: Array<{ route: string; methods: string[]; file: string }>
36
+ /** tRPC routers, for a project whose API has no route files. */
37
+ rpcRouters: string[]
38
+ serverActions: string[]
39
+ middleware?: string
40
+ models: { source: string; names: string[] } | null
41
+ migrations: { dir: string; count: number; latest: string[] } | null
42
+ testFrameworks: string[]
43
+ testConfigs: string[]
44
+ testFiles: string[]
45
+ breakpoints: { source: string; values: Array<[string, string]> } | null
46
+ docs: string[]
47
+ envVars: { source: string; names: string[] } | null
48
+ ciWorkflows: string[]
49
+ /** The project commands the CI workflows run — the checks a change has to pass. */
50
+ ciCommands: string[]
51
+ /** From `engines.node`, `.nvmrc` or `.node-version`. */
52
+ nodeVersion?: string
53
+ /** Coverage thresholds the test config enforces, e.g. `lines 80`. */
54
+ coverage: string[]
55
+ /** Config files of frameworks and tools, wherever in the tree they are. */
56
+ configPaths: string[]
57
+ /** Files that import a package, by the detection label of the package. */
58
+ importers: Record<string, string[]>
59
+ }
60
+
61
+ // ── Reading the tree ────────────────────────────────────────────────────────
62
+
63
+ /** Never walked into: dependencies, build output, caches, VCS, native projects. */
64
+ const SKIP = new Set([
65
+ 'node_modules', '.git', 'dist', 'build', 'out', '.next', '.nuxt', '.output', '.svelte-kit', '.astro',
66
+ '.turbo', '.vercel', '.netlify', '.cache', 'coverage', '.opencastle', 'vendor', 'target', '.expo',
67
+ 'android', 'ios', 'Pods', '.venv', 'venv', '__pycache__', 'storybook-static', '.docusaurus',
68
+ ])
69
+
70
+ const MAX_FILES = 10_000
71
+ const MAX_DEPTH = 10
72
+ const MAX_READ_BYTES = 200_000
73
+
74
+ /** Project files, relative and with `/`, in a stable order. Dot-directories are skipped. */
75
+ async function listFiles(root: string): Promise<string[]> {
76
+ const out: string[] = []
77
+ async function walk(dir: string, rel: string, depth: number): Promise<void> {
78
+ if (out.length >= MAX_FILES || depth > MAX_DEPTH) return
79
+ let entries: Array<{ name: string; isDirectory(): boolean; isFile(): boolean }>
80
+ try {
81
+ entries = await readdir(dir, { withFileTypes: true })
82
+ } catch {
83
+ return
84
+ }
85
+ entries.sort((a, b) => a.name.localeCompare(b.name))
86
+ for (const e of entries) {
87
+ if (out.length >= MAX_FILES) return
88
+ const path = rel ? `${rel}/${e.name}` : e.name
89
+ if (e.isDirectory()) {
90
+ if (SKIP.has(e.name) || e.name.startsWith('.')) continue
91
+ await walk(join(dir, e.name), path, depth + 1)
92
+ } else if (e.isFile()) {
93
+ out.push(path)
94
+ }
95
+ }
96
+ }
97
+ await walk(root, '', 0)
98
+ return out
99
+ }
100
+
101
+ async function read(root: string, rel: string): Promise<string> {
102
+ try {
103
+ const text = await readFile(join(root, rel), 'utf8')
104
+ return text.length > MAX_READ_BYTES ? text.slice(0, MAX_READ_BYTES) : text
105
+ } catch {
106
+ return ''
107
+ }
108
+ }
109
+
110
+ interface PackageJson {
111
+ name?: string
112
+ description?: string
113
+ engines?: Record<string, string>
114
+ jest?: { coverageThreshold?: { global?: Record<string, number> } }
115
+ scripts?: Record<string, string>
116
+ dependencies?: Record<string, string>
117
+ devDependencies?: Record<string, string>
118
+ }
119
+
120
+ async function readPackage(root: string, rel: string): Promise<PackageJson | null> {
121
+ try {
122
+ return JSON.parse(await read(root, rel)) as PackageJson
123
+ } catch {
124
+ return null
125
+ }
126
+ }
127
+
128
+ // ── Directory purposes ──────────────────────────────────────────────────────
129
+
130
+ const PURPOSE: Record<string, string> = {
131
+ apps: 'Applications', packages: 'Shared packages', libs: 'Libraries', tooling: 'Shared tooling config',
132
+ turbo: 'Turborepo generators', components: 'UI components', ui: 'UI components', lib: 'Shared code and clients',
133
+ utils: 'Utilities', helpers: 'Utilities', hooks: 'React hooks', styles: 'Styles', public: 'Static assets',
134
+ static: 'Static assets', assets: 'Assets', prisma: 'Prisma schema and migrations',
135
+ supabase: 'Supabase config and migrations', drizzle: 'Drizzle schema and migrations', db: 'Database code',
136
+ database: 'Database code', migrations: 'Database migrations', convex: 'Convex functions and schema',
137
+ config: 'Configuration', content: 'Content files', types: 'Shared types', test: 'Tests', tests: 'Tests',
138
+ __tests__: 'Tests', e2e: 'End-to-end tests', cypress: 'Cypress tests', scripts: 'Scripts', docs: 'Documentation',
139
+ server: 'Server code', api: 'API', auth: 'Authentication', validators: 'Validation schemas', services: 'Services',
140
+ features: 'Feature modules', modules: 'Modules', layouts: 'Layouts', emails: 'Email templates',
141
+ email: 'Email templates', locales: 'Translations', i18n: 'Translations', messages: 'Translations', store: 'State',
142
+ stores: 'State', state: 'State', middleware: 'Middleware', routes: 'Routes', pages: 'Pages', app: 'Application',
143
+ studio: 'CMS studio', sanity: 'Sanity Studio', actions: 'Server actions', models: 'Data models',
144
+ schemas: 'Schemas', schema: 'Schema', infra: 'Infrastructure', terraform: 'Infrastructure (Terraform)',
145
+ deploy: 'Deployment', bin: 'Executables', src: 'Source', fixtures: 'Test fixtures', mocks: 'Mocks',
146
+ examples: 'Examples', data: 'Data',
147
+ }
148
+
149
+ function purposeOf(path: string, frameworks: string[]): string {
150
+ const name = path.split('/').pop()!
151
+ if (name === 'app' && frameworks.includes('next')) return 'Routes (App Router)'
152
+ if (name === 'pages' && frameworks.includes('next')) return 'Routes (Pages Router)'
153
+ if (name === 'pages' && frameworks.includes('astro')) return 'Pages and endpoints'
154
+ if (name === 'routes' && frameworks.includes('sveltekit')) return 'Routes'
155
+ return PURPOSE[name] ?? ''
156
+ }
157
+
158
+ /** What a workspace is, from its description, the framework it depends on, or its folder name. */
159
+ const APP_KIND: Array<[string, string]> = [
160
+ ['next', 'Next.js app'], ['expo', 'Expo app'], ['astro', 'Astro site'], ['@sveltejs/kit', 'SvelteKit app'],
161
+ ['nuxt', 'Nuxt app'], ['@remix-run/react', 'Remix app'], ['@tanstack/react-start', 'TanStack Start app'],
162
+ ['@nestjs/core', 'NestJS service'], ['express', 'Express server'], ['fastify', 'Fastify server'], ['hono', 'Hono server'],
163
+ ['vite', 'Vite app'], ['electron', 'Electron app'],
164
+ ]
165
+
166
+ function workspacePurpose(path: string, pkg: PackageJson): string {
167
+ if (pkg.description) return pkg.description
168
+ const deps = { ...pkg.devDependencies, ...pkg.dependencies }
169
+ for (const [dep, kind] of APP_KIND) if (deps[dep]) return kind
170
+ return PURPOSE[path.replace(/\/$/, '').split('/').pop()!] ?? ''
171
+ }
172
+
173
+ // ── Routes ──────────────────────────────────────────────────────────────────
174
+
175
+ const HTTP = /export\s+(?:async\s+)?(?:function|const|let)\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS|ALL)\b/g
176
+
177
+ function methodsIn(source: string): string[] {
178
+ return [...new Set([...source.matchAll(HTTP)].map((m) => m[1]))]
179
+ }
180
+
181
+ /** `app/(marketing)/blog/[slug]` → `/blog/[slug]`: groups and slots are not in the URL. */
182
+ function appRoute(dir: string): string {
183
+ const parts = dir.split('/').filter((s) => s && !/^\(.*\)$/.test(s) && !s.startsWith('@'))
184
+ return '/' + parts.join('/')
185
+ }
186
+
187
+ /** A route file's path, without its extension: `blog/index` → `/blog`. */
188
+ function fileRoute(path: string): string {
189
+ return '/' + path.replace(/(^|\/)index$/, '').replace(/^\/+/, '')
190
+ }
191
+
192
+ /** A folder or file whose name starts with `_` is not routed (Next.js, Astro). */
193
+ const PRIVATE = (path: string): boolean => path.split('/').some((s) => s.startsWith('_'))
194
+
195
+ async function findRoutes(
196
+ root: string,
197
+ files: string[],
198
+ frameworks: string[],
199
+ ): Promise<{ pages: ProjectFacts['pages']; api: ProjectFacts['api'] }> {
200
+ const api: ProjectFacts['api'] = []
201
+ const pages = new Map<string, Set<string>>()
202
+ const page = (at: string, route: string) => {
203
+ if (!pages.has(at)) pages.set(at, new Set())
204
+ pages.get(at)!.add(route)
205
+ }
206
+
207
+ for (const path of files) {
208
+ // In a monorepo the routes are in each app: the same rules, under its folder.
209
+ const ws = /^((?:apps|packages|services)\/[^/]+\/)/.exec(path)?.[1] ?? ''
210
+ const f = path.slice(ws.length)
211
+ // Next.js App Router
212
+ let m = /^(src\/)?app\/(?:(.*)\/)?page\.(tsx|ts|jsx|js|mdx|md)$/.exec(f)
213
+ if (m && frameworks.includes('next')) {
214
+ if (!PRIVATE(m[2] ?? '')) page(`${ws}${m[1] ?? ''}app/`, appRoute(m[2] ?? ''))
215
+ continue
216
+ }
217
+ m = /^(src\/)?app\/(?:(.*)\/)?route\.(ts|js)$/.exec(f)
218
+ if (m && frameworks.includes('next')) {
219
+ if (!PRIVATE(m[2] ?? '')) api.push({ route: appRoute(m[2] ?? ''), methods: methodsIn(await read(root, path)), file: path })
220
+ continue
221
+ }
222
+ // Next.js Pages Router
223
+ m = /^(src\/)?pages\/(.+)\.(tsx|ts|jsx|js|mdx|md)$/.exec(f)
224
+ if (m && frameworks.includes('next')) {
225
+ if (/(^|\/)_(app|document|error)$/.test(m[2])) continue
226
+ if (m[2].startsWith('api/')) api.push({ route: fileRoute(m[2]), methods: [], file: path })
227
+ else page(`${ws}${m[1] ?? ''}pages/`, fileRoute(m[2]))
228
+ continue
229
+ }
230
+ // Astro
231
+ m = /^src\/pages\/(.+)\.(astro|md|mdx|html|ts|js)$/.exec(f)
232
+ if (m && frameworks.includes('astro')) {
233
+ if (PRIVATE(m[1])) continue
234
+ if (m[2] === 'ts' || m[2] === 'js') api.push({ route: fileRoute(m[1]), methods: methodsIn(await read(root, path)), file: path })
235
+ else page(`${ws}src/pages/`, fileRoute(m[1]))
236
+ continue
237
+ }
238
+ // SvelteKit
239
+ m = /^src\/routes\/(?:(.*)\/)?\+(page\.svelte|server\.(ts|js))$/.exec(f)
240
+ if (m && frameworks.includes('sveltekit')) {
241
+ const route = appRoute(m[1] ?? '')
242
+ if (m[2].startsWith('server')) api.push({ route, methods: methodsIn(await read(root, path)), file: path })
243
+ else page(`${ws}src/routes/`, route)
244
+ continue
245
+ }
246
+ // Remix flat routes
247
+ m = /^app\/routes\/([^/]+)\.(tsx|ts|jsx|js)$/.exec(f)
248
+ if (m && frameworks.includes('remix')) {
249
+ page(`${ws}app/routes/`, '/' + m[1].replace(/^_index$/, '').replace(/\._index$/, '').replace(/\./g, '/').replace(/\$/g, ':'))
250
+ }
251
+ }
252
+
253
+ // Express, Fastify, Hono and their like: `app.get('/path', …)`.
254
+ if (api.length === 0 && frameworks.some((f) => ['express', 'fastify', 'hono'].includes(f))) {
255
+ const call = /\b(?:app|router|server|api|fastify)\.(get|post|put|patch|delete)\(\s*['"`](\/[^'"`]*)['"`]/g
256
+ for (const f of files.filter((p) => /\.(ts|js|mjs|cjs)$/.test(p) && !/\.(test|spec)\./.test(p)).slice(0, 400)) {
257
+ for (const hit of (await read(root, f)).matchAll(call)) {
258
+ const existing = api.find((a) => a.route === hit[2] && a.file === f)
259
+ if (existing) existing.methods.push(hit[1].toUpperCase())
260
+ else api.push({ route: hit[2], methods: [hit[1].toUpperCase()], file: f })
261
+ }
262
+ }
263
+ }
264
+
265
+ api.sort((a, b) => a.route.localeCompare(b.route))
266
+ return {
267
+ pages: [...pages].map(([at, routes]) => ({ root: at, routes: [...routes].sort() })).sort((a, b) => a.root.localeCompare(b.root)),
268
+ api,
269
+ }
270
+ }
271
+
272
+ // ── Data ────────────────────────────────────────────────────────────────────
273
+
274
+ async function findModels(root: string, files: string[]): Promise<ProjectFacts['models']> {
275
+ const prisma = files.filter((f) => f.endsWith('.prisma'))
276
+ if (prisma.length) {
277
+ const names = (await Promise.all(prisma.map((f) => read(root, f))))
278
+ .flatMap((s) => [...s.matchAll(/^model\s+(\w+)\s*\{/gm)].map((m) => m[1]))
279
+ return { source: prisma.length === 1 ? prisma[0] : `${prisma.length} .prisma files`, names }
280
+ }
281
+ const convex = files.find((f) => /(^|\/)convex\/schema\.ts$/.test(f))
282
+ if (convex) {
283
+ const names = [...(await read(root, convex)).matchAll(/(\w+)\s*:\s*defineTable\(/g)].map((m) => m[1])
284
+ return { source: convex, names }
285
+ }
286
+ const drizzle: string[] = []
287
+ let drizzleSource = ''
288
+ const candidates = files.filter((p) => /\.(ts|js)$/.test(p) && (/schema/i.test(p.split('/').pop()!) || /(^|\/)(db|drizzle|schema)\//.test(p)))
289
+ for (const f of candidates.slice(0, 80)) {
290
+ const names = [...(await read(root, f)).matchAll(/(?:pgTable|mysqlTable|sqliteTable)\(\s*['"]([\w-]+)['"]/g)].map((m) => m[1])
291
+ if (names.length) {
292
+ drizzle.push(...names)
293
+ drizzleSource ||= f
294
+ }
295
+ }
296
+ if (drizzle.length) return { source: drizzleSource, names: [...new Set(drizzle)] }
297
+ const sql = files.filter((f) => /(^|\/)supabase\/migrations\/.+\.sql$/.test(f))
298
+ if (sql.length) {
299
+ const names = (await Promise.all(sql.map((f) => read(root, f))))
300
+ .flatMap((s) => [...s.matchAll(/create\s+table\s+(?:if\s+not\s+exists\s+)?(?:"?public"?\.)?"?(\w+)"?/gi)].map((m) => m[1]))
301
+ return { source: 'supabase/migrations/', names: [...new Set(names)] }
302
+ }
303
+ return null
304
+ }
305
+
306
+ function findMigrations(files: string[]): ProjectFacts['migrations'] {
307
+ for (const dir of ['prisma/migrations', 'supabase/migrations', 'drizzle', 'migrations', 'db/migrations']) {
308
+ const within = files.filter((f) => new RegExp(`(^|/)${dir}/`).test(f) && f.endsWith('.sql'))
309
+ if (within.length === 0) continue
310
+ const base = within[0].slice(0, within[0].indexOf(`${dir}/`) + dir.length + 1)
311
+ const entries = [...new Set(within.map((f) => f.slice(base.length).split('/')[0]))].sort()
312
+ return { dir: base, count: entries.length, latest: entries.slice(-3) }
313
+ }
314
+ return null
315
+ }
316
+
317
+ // ── Everything else ─────────────────────────────────────────────────────────
318
+
319
+ const TEST_PACKAGES: Record<string, string> = {
320
+ vitest: 'Vitest', jest: 'Jest', '@playwright/test': 'Playwright', cypress: 'Cypress', mocha: 'Mocha', ava: 'AVA',
321
+ }
322
+
323
+ const DEFAULT_PORT: Array<[string, number]> = [
324
+ ['next', 3000], ['nuxt', 3000], ['astro', 4321], ['sveltekit', 5173], ['remix', 5173], ['expo', 8081],
325
+ ]
326
+
327
+ function devPortOf(scripts: Record<string, string>, frameworks: string[], deps: Record<string, string>): number | undefined {
328
+ const dev = scripts.dev ?? scripts.start ?? ''
329
+ const explicit = /(?:-p|--port)[ =](\d{2,5})\b|\bPORT=(\d{2,5})\b/.exec(dev)
330
+ if (explicit) return Number(explicit[1] ?? explicit[2])
331
+ for (const [fw, port] of DEFAULT_PORT) if (frameworks.includes(fw)) return port
332
+ if (deps.vite && /\bvite\b/.test(dev)) return 5173
333
+ return undefined
334
+ }
335
+
336
+ const TAILWIND_DEFAULTS: Array<[string, string]> = [['sm', '640px'], ['md', '768px'], ['lg', '1024px'], ['xl', '1280px'], ['2xl', '1536px']]
337
+
338
+ async function findBreakpoints(root: string, files: string[], usesTailwind: boolean): Promise<ProjectFacts['breakpoints']> {
339
+ if (!usesTailwind) return null
340
+ const config = files.find((f) => /(^|\/)tailwind\.config\.(js|ts|mjs|cjs)$/.test(f))
341
+ const values = new Map(TAILWIND_DEFAULTS)
342
+ let source = config ?? 'Tailwind defaults'
343
+ if (config) {
344
+ const text = await read(root, config)
345
+ for (const m of text.matchAll(/screens\s*:\s*\{([^}]*)\}/g)) {
346
+ // `container: { screens: … }` sizes the container, not the breakpoints.
347
+ if (/container\s*:\s*\{[^}]*$/.test(text.slice(Math.max(0, m.index - 300), m.index))) continue
348
+ for (const [, name, value] of m[1].matchAll(/['"]?([\w-]+)['"]?\s*:\s*['"](\d+(?:\.\d+)?(?:px|rem|em))['"]/g)) values.set(name, value)
349
+ }
350
+ }
351
+ // Tailwind 4 declares them in CSS.
352
+ for (const css of files.filter((f) => f.endsWith('.css')).slice(0, 40)) {
353
+ const text = await read(root, css)
354
+ if (!text.includes('@theme')) continue
355
+ const declared = [...text.matchAll(/--breakpoint-([\w-]+)\s*:\s*([\d.]+(?:px|rem|em))/g)]
356
+ for (const [, name, value] of declared) values.set(name, value)
357
+ if (declared.length) source = css
358
+ }
359
+ return { source, values: [...values] }
360
+ }
361
+
362
+ async function findEnvVars(root: string, files: string[]): Promise<ProjectFacts['envVars']> {
363
+ // Example files and validated env schemas only. A real `.env` holds secrets
364
+ // and is never read.
365
+ const example = ['.env.example', '.env.sample', '.env.template', '.env.local.example'].find((f) => existsSync(join(root, f)))
366
+ if (example) {
367
+ const names = [...(await read(root, example)).matchAll(/^\s*(?:export\s+)?([A-Z][A-Z0-9_]*)\s*=/gm)].map((m) => m[1])
368
+ if (names.length) return { source: example, names: [...new Set(names)] }
369
+ }
370
+ const schema = files.find((f) => /(^|\/)(src\/)?env\.(mjs|js|ts)$/.test(f))
371
+ if (schema) {
372
+ const names = [...(await read(root, schema)).matchAll(/^\s*([A-Z][A-Z0-9_]*)\s*:/gm)].map((m) => m[1])
373
+ if (names.length) return { source: schema, names: [...new Set(names)] }
374
+ }
375
+ return null
376
+ }
377
+
378
+ /**
379
+ * The files that import each detected package, best first, at most three: the
380
+ * one that sets the client up — `lib/db.ts`, `lib/stripe.ts` — before the
381
+ * pages that use it.
382
+ */
383
+ async function findImporters(root: string, files: string[], packages: Map<string, string>): Promise<Record<string, string[]>> {
384
+ const found: Record<string, string[]> = {}
385
+ if (packages.size === 0) return found
386
+ const code = files.filter((f) => /\.(ts|tsx|js|jsx|mjs|cjs|astro|svelte|vue)$/.test(f) && !/\.(test|spec|d)\./.test(f)).slice(0, 1500)
387
+ const patterns = [...packages].map(([pkg, label]) => {
388
+ const quoted = pkg.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')
389
+ return { label, re: new RegExp(`(?:from|require\\(|import\\()\\s*['"]${quoted}(?:/[^'"]*)?['"]`) }
390
+ })
391
+ for (const f of code) {
392
+ const text = await read(root, f)
393
+ for (const { label, re } of patterns) if (re.test(text)) (found[label] ??= []).push(f)
394
+ }
395
+ const score = (f: string, label: string): number => {
396
+ const base = f.split('/').pop()!.replace(/\.[^.]+$/, '').toLowerCase()
397
+ return (base.includes(label.split('-')[0]) || ['db', 'client', 'prisma', 'auth'].includes(base) ? 0 : 10) +
398
+ (/(^|\/)(lib|server|db|utils|services)\//.test(f) ? 0 : 5) +
399
+ f.split('/').length
400
+ }
401
+ const out: Record<string, string[]> = {}
402
+ for (const [label, list] of Object.entries(found)) {
403
+ out[label] = [...list].sort((a, b) => score(a, label) - score(b, label) || a.localeCompare(b)).slice(0, 3)
404
+ }
405
+ return out
406
+ }
407
+
408
+ /** The packages behind a detection label. Frameworks are left out: every file imports them. */
409
+ function packagesFor(labels: string[]): Map<string, string> {
410
+ const wanted = new Set(labels)
411
+ const map = new Map<string, string>()
412
+ for (const [pkg, { category, label }] of Object.entries(PACKAGE_DETECTIONS)) {
413
+ if (category === 'frameworks' || category === 'styling' || category === 'testing') continue
414
+ if (wanted.has(label)) map.set(pkg, label)
415
+ }
416
+ return map
417
+ }
418
+
419
+ const CONFIG_FILE =
420
+ /(^|\/)((next|astro|nuxt|svelte|vite|remix|tailwind|drizzle|sanity|playwright|vitest|jest|cypress|metro)\.config\.[cm]?[jt]s|app\.json|app\.config\.[jt]s|vercel\.json|netlify\.toml|turbo\.json|nx\.json|wrangler\.(toml|jsonc?)|Dockerfile|(docker-)?compose\.ya?ml|fly\.toml|render\.yaml)$/
421
+
422
+ const LAYERS: Array<[string, string]> = [
423
+ ['frameworks', 'Framework'], ['databases', 'Database'], ['cms', 'CMS'], ['auth', 'Auth'],
424
+ ['styling', 'Styling'], ['testing', 'Testing'], ['services', 'Service'],
425
+ ]
426
+
427
+ const DISPLAY: Record<string, string> = {
428
+ next: 'Next.js', nuxt: 'Nuxt', astro: 'Astro', remix: 'Remix', sveltekit: 'SvelteKit', express: 'Express',
429
+ fastify: 'Fastify', hono: 'Hono', expo: 'Expo', vite: 'Vite', prisma: 'Prisma', drizzle: 'Drizzle',
430
+ supabase: 'Supabase', convex: 'Convex', mongoose: 'Mongoose', typeorm: 'TypeORM', sanity: 'Sanity',
431
+ contentful: 'Contentful', strapi: 'Strapi', payload: 'Payload', 'next-auth': 'NextAuth.js', clerk: 'Clerk',
432
+ auth0: 'Auth0', lucia: 'Lucia', passport: 'Passport', tailwind: 'Tailwind CSS', sass: 'Sass',
433
+ 'styled-components': 'styled-components', emotion: 'Emotion', 'css-modules': 'CSS Modules', jest: 'Jest',
434
+ vitest: 'Vitest', playwright: 'Playwright', cypress: 'Cypress', stripe: 'Stripe', resend: 'Resend',
435
+ sentry: 'Sentry', notion: 'Notion', vercel: 'Vercel', netlify: 'Netlify', cloudflare: 'Cloudflare',
436
+ docker: 'Docker', railway: 'Railway', fly: 'Fly.io', render: 'Render', 'github-actions': 'GitHub Actions',
437
+ 'gitlab-ci': 'GitLab CI', circleci: 'CircleCI', jenkins: 'Jenkins', turborepo: 'Turborepo', nx: 'Nx',
438
+ }
439
+
440
+ export function displayName(label: string): string {
441
+ return DISPLAY[label] ?? label
442
+ }
443
+
444
+ /** `^13.4.0` → `13.4.0`; a range or tag that is not a version is kept as written. */
445
+ function cleanVersion(range: string | undefined): string | undefined {
446
+ if (!range || /^(workspace|catalog|link|file):/.test(range)) return undefined
447
+ const m = /^[\^~>=<\s]*(\d[\w.+-]*)/.exec(range)
448
+ return m ? m[1] : range
449
+ }
450
+
451
+ /** pnpm's `catalog:` versions, from pnpm-workspace.yaml: the default catalog and named ones. */
452
+ async function readCatalog(root: string): Promise<Map<string, string>> {
453
+ const text = await read(root, 'pnpm-workspace.yaml')
454
+ const catalog = new Map<string, string>()
455
+ let inCatalog = false
456
+ for (const line of text.split('\n')) {
457
+ if (/^catalogs?:\s*$/.test(line)) {
458
+ inCatalog = true
459
+ continue
460
+ }
461
+ if (/^\S/.test(line)) inCatalog = false
462
+ if (!inCatalog) continue
463
+ const m = /^\s+['"]?(@?[\w./-]+)['"]?\s*:\s*['"]?([^'"#\s]+)/.exec(line)
464
+ if (m && /\d/.test(m[2]) && !catalog.has(m[1])) catalog.set(m[1], m[2])
465
+ }
466
+ return catalog
467
+ }
468
+
469
+ export interface DetectedStack {
470
+ packageManager?: string
471
+ language?: string
472
+ frameworks?: string[]
473
+ databases?: string[]
474
+ cms?: string[]
475
+ auth?: string[]
476
+ styling?: string[]
477
+ testing?: string[]
478
+ services?: string[]
479
+ }
480
+
481
+ /**
482
+ * The commands CI runs that a developer could run too: lines of a workflow's
483
+ * `run:` that call the package manager or a project script.
484
+ */
485
+ async function findCiCommands(root: string, workflows: string[], pm: string): Promise<string[]> {
486
+ const out: string[] = []
487
+ const runner = new RegExp(`^(?:${pm}|npm|pnpm|yarn|bun|npx|node)\\b`)
488
+ for (const wf of workflows) {
489
+ const lines = (await read(root, wf)).split('\n')
490
+ for (let i = 0; i < lines.length; i++) {
491
+ const m = /^(\s*)-?\s*run:\s*(.*)$/.exec(lines[i])
492
+ if (!m) continue
493
+ const cmds: string[] = []
494
+ if (/^[|>]-?\s*$/.test(m[2])) {
495
+ const indent = m[1].length
496
+ for (let j = i + 1; j < lines.length && (lines[j].trim() === '' || lines[j].search(/\S/) > indent); j++) cmds.push(lines[j].trim())
497
+ } else cmds.push(m[2].trim())
498
+ for (const c of cmds) if (runner.test(c) && !/\binstall\b|\bci$|\bci\s/.test(c) && !out.includes(c)) out.push(c)
499
+ }
500
+ }
501
+ return out.slice(0, 8)
502
+ }
503
+
504
+ async function findCoverage(root: string, configs: string[], pkg: PackageJson): Promise<string[]> {
505
+ const fromJest = pkg.jest?.coverageThreshold?.global
506
+ if (fromJest) return Object.entries(fromJest).map(([k, v]) => `${k} ${v}`)
507
+ for (const f of configs.filter((c) => /(vitest|jest)\.config/.test(c))) {
508
+ const text = await read(root, f)
509
+ const block = /(?:thresholds|coverageThreshold)\s*:\s*\{([\s\S]*?)\}/.exec(text)?.[1]
510
+ if (!block) continue
511
+ const values = [...block.matchAll(/\b(lines|branches|functions|statements)\s*:\s*(\d+)/g)].map((m) => `${m[1]} ${m[2]}`)
512
+ if (values.length) return values
513
+ }
514
+ return []
515
+ }
516
+
517
+ /** The README's opening paragraph, when it is a sentence or two that says what the project is. */
518
+ async function readmeSummary(root: string, files: string[]): Promise<string | undefined> {
519
+ const readme = files.find((f) => /^readme\.mdx?$/i.test(f))
520
+ if (!readme) return undefined
521
+ const text = (await read(root, readme)).replace(/<!--[\s\S]*?-->/g, '')
522
+ // Only what comes before the first section: an introduction, not instructions.
523
+ const intro = text.split(/\n#{2,}\s/)[0]
524
+ const first = intro
525
+ .split(/\n\s*\n/)
526
+ .map((p) => p.trim())
527
+ .find((p) => p && !/^(#|!\[|\[!\[|<|>|```|\||-|\*|\d+\.)/.test(p))
528
+ if (!first || /:\s*$/.test(first)) return undefined
529
+ const sentence = first.replace(/\s+/g, ' ').replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
530
+ return sentence.length <= 300 ? sentence : undefined
531
+ }
532
+
533
+ /**
534
+ * Read the facts. `detected` is what `detectRepoInfo` found in the files —
535
+ * not the integrations someone selected, which name tools like Chrome DevTools
536
+ * that the project itself does not use.
537
+ */
538
+ export async function readProjectFacts(root: string, detected: DetectedStack): Promise<ProjectFacts> {
539
+ const pkg = (await readPackage(root, 'package.json')) ?? {}
540
+ const files = await listFiles(root)
541
+ const frameworks = detected.frameworks ?? []
542
+
543
+ // Every package.json of a monorepo declares versions; the root often none.
544
+ const workspaceManifests = files.filter((f) => /^(apps|packages|libs|services|tooling)\/[^/]+\/package\.json$/.test(f))
545
+ const workspacePkgs = await Promise.all(workspaceManifests.map(async (f) => ({ f, pkg: (await readPackage(root, f)) ?? {} })))
546
+ const catalog = await readCatalog(root)
547
+ const deps: Record<string, string> = {}
548
+ for (const p of [pkg, ...workspacePkgs.map((w) => w.pkg)]) {
549
+ for (const [name, range] of Object.entries({ ...p.devDependencies, ...p.dependencies })) {
550
+ const resolved = /^catalog:/.test(range) ? catalog.get(name) ?? range : range
551
+ if (!deps[name] || (cleanVersion(resolved) && !cleanVersion(deps[name]))) deps[name] = resolved
552
+ }
553
+ }
554
+
555
+ const versionOf = (label: string): string | undefined => {
556
+ for (const [name, rule] of Object.entries(PACKAGE_DETECTIONS)) {
557
+ if (rule.label === label && deps[name]) return cleanVersion(deps[name])
558
+ }
559
+ return cleanVersion(deps[label])
560
+ }
561
+ const stack: ProjectFacts['stack'] = []
562
+ for (const [key, layer] of LAYERS) {
563
+ for (const label of (detected as Record<string, string[] | undefined>)[key] ?? []) {
564
+ stack.push({ layer, name: displayName(label), version: versionOf(label) })
565
+ }
566
+ }
567
+
568
+ const top = await readdir(root, { withFileTypes: true }).catch(() => [])
569
+ const dirs: ProjectFacts['dirs'] = []
570
+ for (const e of top.filter((d) => d.isDirectory() && !d.name.startsWith('.') && !SKIP.has(d.name)).sort((a, b) => a.name.localeCompare(b.name))) {
571
+ dirs.push({ path: `${e.name}/`, purpose: purposeOf(e.name, frameworks) })
572
+ if (e.name === 'src') {
573
+ const inner = await readdir(join(root, 'src'), { withFileTypes: true }).catch(() => [])
574
+ for (const s of inner.filter((d) => d.isDirectory() && !d.name.startsWith('.')).sort((a, b) => a.name.localeCompare(b.name))) {
575
+ dirs.push({ path: `src/${s.name}/`, purpose: purposeOf(s.name, frameworks) })
576
+ }
577
+ }
578
+ }
579
+
580
+ const { pages, api } = await findRoutes(root, files, frameworks)
581
+
582
+ const rpcRouters: string[] = []
583
+ if (deps['@trpc/server']) {
584
+ for (const f of files.filter((p) => /\.(ts|tsx)$/.test(p) && !/\.(test|spec|d)\./.test(p)).slice(0, 1500)) {
585
+ if (/createTRPCRouter\(|\bt\.router\(|\brouter\(\s*\{/.test(await read(root, f))) rpcRouters.push(f)
586
+ if (rpcRouters.length >= 20) break
587
+ }
588
+ }
589
+
590
+ const actionCandidates = files.filter((f) => /\.(ts|tsx|js|jsx)$/.test(f) && /(^|\/)(src\/)?(app|lib|actions|server)\//.test(f)).slice(0, 800)
591
+ const serverActions: string[] = []
592
+ for (const f of actionCandidates) {
593
+ if (/^\s*['"]use server['"]/m.test((await read(root, f)).slice(0, 400))) serverActions.push(f)
594
+ }
595
+
596
+ const testFrameworks = Object.entries(TEST_PACKAGES).filter(([p]) => deps[p]).map(([, name]) => name)
597
+ const testFiles = files.filter((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f) || /(^|\/)(__tests__|e2e|cypress\/e2e)\//.test(f))
598
+ const testConfigs = files.filter((f) => /(^|\/)(vitest|jest|playwright|cypress)\.config\.[cm]?[jt]s$/.test(f))
599
+
600
+ const ciWorkflows = (await readdir(join(root, '.github', 'workflows')).catch(() => []))
601
+ .filter((f) => /\.ya?ml$/.test(f))
602
+ .map((f) => `.github/workflows/${f}`)
603
+ const nodeFile = ((await read(root, '.nvmrc')) || (await read(root, '.node-version'))).trim()
604
+ const nodeVersion = pkg.engines?.node ?? (nodeFile || undefined)
605
+
606
+ const docs = files.filter((f) =>
607
+ /^(README|CONTRIBUTING|ARCHITECTURE|CHANGELOG|DEVELOPMENT|SECURITY)\.mdx?$/i.test(f) || /^docs\/[^/]+\.mdx?$/.test(f),
608
+ ).slice(0, 15)
609
+
610
+ return {
611
+ name: pkg.name,
612
+ description: pkg.description ?? (await readmeSummary(root, files)),
613
+ packageManager: detected.packageManager ?? 'npm',
614
+ language: detected.language,
615
+ scripts: pkg.scripts ?? {},
616
+ stack,
617
+ dirs,
618
+ workspaces: workspacePkgs
619
+ .filter(({ f }) => /^(apps|packages|libs|services)\//.test(f))
620
+ .map(({ f, pkg: w }) => {
621
+ const path = f.replace(/package\.json$/, '')
622
+ return { path, name: w.name ?? path, purpose: workspacePurpose(path, w) }
623
+ }),
624
+ devPort: devPortOf(pkg.scripts ?? {}, frameworks, deps),
625
+ pages,
626
+ api,
627
+ rpcRouters,
628
+ serverActions,
629
+ middleware: files.find((f) => /^((apps|packages)\/[^/]+\/)?(src\/)?middleware\.(ts|js)$/.test(f)),
630
+ models: await findModels(root, files),
631
+ migrations: findMigrations(files),
632
+ testFrameworks,
633
+ testConfigs,
634
+ testFiles,
635
+ breakpoints: await findBreakpoints(root, files, (detected.styling ?? []).includes('tailwind')),
636
+ docs,
637
+ envVars: await findEnvVars(root, files),
638
+ ciWorkflows,
639
+ ciCommands: await findCiCommands(root, ciWorkflows, detected.packageManager ?? 'npm'),
640
+ nodeVersion,
641
+ coverage: await findCoverage(root, testConfigs, pkg),
642
+ configPaths: files.filter((f) => CONFIG_FILE.test(f)),
643
+ importers: await findImporters(root, files, packagesFor([
644
+ ...(detected.databases ?? []), ...(detected.cms ?? []), ...(detected.auth ?? []), ...(detected.services ?? []),
645
+ ])),
646
+ }
647
+ }
@@ -393,7 +393,7 @@ export function updateSkillMatrixContent(content: string, stack: StackConfig): s
393
393
  .filter((e): e is SkillMatrixEntry => e !== null);
394
394
 
395
395
  if (data.bindings[slotName]) {
396
- // Merge, not replace. `skill-matrix.md` tells users "to switch tech, update
396
+ // Merge, not replace. `skill-matrix.md` told users "to switch tech, update
397
397
  // only the binding entries", and this ran on every sync, so the edit the
398
398
  // documentation asks for was erased by the next recompile — in the
399
399
  // directory the drift checker calls theirs.