opencastle 1.6.4 → 1.7.1

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 (76) hide show
  1. package/dist/cli/baseline.d.ts.map +1 -1
  2. package/dist/cli/baseline.js +8 -0
  3. package/dist/cli/baseline.js.map +1 -1
  4. package/dist/cli/bootstrap.d.ts.map +1 -1
  5. package/dist/cli/bootstrap.js +31 -9
  6. package/dist/cli/bootstrap.js.map +1 -1
  7. package/dist/cli/bootstrap.test.js +10 -0
  8. package/dist/cli/bootstrap.test.js.map +1 -1
  9. package/dist/cli/detect.d.ts.map +1 -1
  10. package/dist/cli/detect.js +32 -0
  11. package/dist/cli/detect.js.map +1 -1
  12. package/dist/cli/detect.test.js +23 -0
  13. package/dist/cli/detect.test.js.map +1 -1
  14. package/dist/cli/init.d.ts.map +1 -1
  15. package/dist/cli/init.js +10 -5
  16. package/dist/cli/init.js.map +1 -1
  17. package/dist/cli/layers.d.ts.map +1 -1
  18. package/dist/cli/layers.js +21 -1
  19. package/dist/cli/layers.js.map +1 -1
  20. package/dist/cli/layers.test.js +17 -0
  21. package/dist/cli/layers.test.js.map +1 -1
  22. package/dist/cli/manifest.d.ts +9 -0
  23. package/dist/cli/manifest.d.ts.map +1 -1
  24. package/dist/cli/manifest.js +12 -0
  25. package/dist/cli/manifest.js.map +1 -1
  26. package/dist/cli/project-facts-lang.d.ts +36 -0
  27. package/dist/cli/project-facts-lang.d.ts.map +1 -0
  28. package/dist/cli/project-facts-lang.js +323 -0
  29. package/dist/cli/project-facts-lang.js.map +1 -0
  30. package/dist/cli/project-facts.d.ts +5 -0
  31. package/dist/cli/project-facts.d.ts.map +1 -1
  32. package/dist/cli/project-facts.js +28 -11
  33. package/dist/cli/project-facts.js.map +1 -1
  34. package/dist/cli/project-facts.test.js +70 -0
  35. package/dist/cli/project-facts.test.js.map +1 -1
  36. package/dist/cli/promote-command.test.js +7 -0
  37. package/dist/cli/promote-command.test.js.map +1 -1
  38. package/dist/cli/promote.d.ts +7 -1
  39. package/dist/cli/promote.d.ts.map +1 -1
  40. package/dist/cli/promote.js +16 -2
  41. package/dist/cli/promote.js.map +1 -1
  42. package/dist/cli/stack-config-update.test.js +21 -1
  43. package/dist/cli/stack-config-update.test.js.map +1 -1
  44. package/dist/cli/stack-config.d.ts +20 -0
  45. package/dist/cli/stack-config.d.ts.map +1 -1
  46. package/dist/cli/stack-config.js +36 -0
  47. package/dist/cli/stack-config.js.map +1 -1
  48. package/dist/cli/team-commands.test.js +25 -0
  49. package/dist/cli/team-commands.test.js.map +1 -1
  50. package/dist/cli/team-config.d.ts +7 -2
  51. package/dist/cli/team-config.d.ts.map +1 -1
  52. package/dist/cli/team-config.js +8 -3
  53. package/dist/cli/team-config.js.map +1 -1
  54. package/dist/cli/update.d.ts.map +1 -1
  55. package/dist/cli/update.js +13 -16
  56. package/dist/cli/update.js.map +1 -1
  57. package/package.json +1 -1
  58. package/src/cli/baseline.ts +10 -0
  59. package/src/cli/bootstrap.test.ts +11 -0
  60. package/src/cli/bootstrap.ts +31 -9
  61. package/src/cli/detect.test.ts +27 -0
  62. package/src/cli/detect.ts +29 -0
  63. package/src/cli/init.ts +10 -5
  64. package/src/cli/layers.test.ts +20 -0
  65. package/src/cli/layers.ts +20 -1
  66. package/src/cli/manifest.ts +13 -0
  67. package/src/cli/project-facts-lang.ts +338 -0
  68. package/src/cli/project-facts.test.ts +75 -0
  69. package/src/cli/project-facts.ts +31 -11
  70. package/src/cli/promote-command.test.ts +8 -0
  71. package/src/cli/promote.ts +16 -2
  72. package/src/cli/stack-config-update.test.ts +25 -1
  73. package/src/cli/stack-config.ts +36 -0
  74. package/src/cli/team-commands.test.ts +28 -0
  75. package/src/cli/team-config.ts +10 -3
  76. package/src/cli/update.ts +15 -18
@@ -0,0 +1,338 @@
1
+ /**
2
+ * What can be read from a Python or Go project, and the commands any project
3
+ * declares outside package.json.
4
+ *
5
+ * The facts were read from package.json alone, so a FastAPI service got
6
+ * "package manager npm", no commands, no routes and "no test files" for its
7
+ * thirteen. Everything here is read from files, never run, and left out when
8
+ * it is not found.
9
+ */
10
+ import type { ProjectFacts } from './project-facts.js'
11
+
12
+ type Read = (rel: string) => Promise<string>
13
+
14
+ export interface LanguageFacts {
15
+ language: 'python' | 'go'
16
+ /** What installs and runs the project: poetry, uv, pdm, pipenv, pip — or go. */
17
+ tool: string
18
+ /** Rows for the Tech Stack table: the language, and the libraries that matter. */
19
+ stack: ProjectFacts['stack']
20
+ /** Version of each framework label `detect` records, e.g. `fastapi` → `0.110`. */
21
+ versions: Map<string, string>
22
+ api: ProjectFacts['api']
23
+ testFrameworks: string[]
24
+ testFiles: string[]
25
+ migrations: ProjectFacts['migrations']
26
+ models: ProjectFacts['models']
27
+ }
28
+
29
+ // ── Python ──────────────────────────────────────────────────────────────────
30
+
31
+ /** Python packages worth a row, by their name on PyPI. */
32
+ const PYTHON_PACKAGES: Record<string, { layer: string; name: string; label?: string }> = {
33
+ fastapi: { layer: 'Framework', name: 'FastAPI', label: 'fastapi' },
34
+ django: { layer: 'Framework', name: 'Django', label: 'django' },
35
+ flask: { layer: 'Framework', name: 'Flask', label: 'flask' },
36
+ starlette: { layer: 'Framework', name: 'Starlette' },
37
+ sqlalchemy: { layer: 'Database', name: 'SQLAlchemy' },
38
+ sqlmodel: { layer: 'Database', name: 'SQLModel' },
39
+ alembic: { layer: 'Database', name: 'Alembic' },
40
+ 'psycopg': { layer: 'Database', name: 'psycopg' },
41
+ 'psycopg2-binary': { layer: 'Database', name: 'psycopg2' },
42
+ asyncpg: { layer: 'Database', name: 'asyncpg' },
43
+ pydantic: { layer: 'Library', name: 'Pydantic' },
44
+ celery: { layer: 'Jobs', name: 'Celery' },
45
+ uvicorn: { layer: 'Server', name: 'Uvicorn' },
46
+ gunicorn: { layer: 'Server', name: 'Gunicorn' },
47
+ pytest: { layer: 'Testing', name: 'pytest' },
48
+ ruff: { layer: 'Tooling', name: 'Ruff' },
49
+ mypy: { layer: 'Tooling', name: 'mypy' },
50
+ }
51
+
52
+ /** `>=0.110,<1` → `0.110`; `^2.0` → `2.0`. */
53
+ function version(spec: string | undefined): string | undefined {
54
+ return spec?.match(/\d+(?:\.\d+){0,2}/)?.[0]
55
+ }
56
+
57
+ /** Dependencies a pyproject.toml, requirements file or Pipfile declares, by lower-cased name. */
58
+ function pythonDeps(pyproject: string, requirements: string): Map<string, string> {
59
+ const deps = new Map<string, string>()
60
+ const add = (name: string, spec: string): void => {
61
+ const key = name.toLowerCase().replace(/_/g, '-')
62
+ if (!deps.has(key) || (!deps.get(key) && spec)) deps.set(key, spec)
63
+ }
64
+ // PEP 621 and dependency groups: quoted requirement strings inside arrays.
65
+ for (const block of pyproject.matchAll(/^\s*[\w-]+\s*=\s*\[([\s\S]*?)\]/gm)) {
66
+ for (const m of block[1].matchAll(/["']([A-Za-z0-9][A-Za-z0-9._-]*)(?:\[[^\]]*\])?\s*([^"';]*)/g)) add(m[1], m[2])
67
+ }
68
+ // Poetry: `name = "^1.2"` or `name = { version = "^1.2", … }` under a dependencies table.
69
+ for (const table of pyproject.matchAll(/^\[tool\.poetry\.(?:[\w.-]*\.)?(?:dev-)?dependencies\]\n([\s\S]*?)(?=^\[|(?![\s\S]))/gm)) {
70
+ for (const m of table[1].matchAll(/^([A-Za-z0-9][A-Za-z0-9._-]*)\s*=\s*(?:"([^"]*)"|\{[^}]*?version\s*=\s*"([^"]*)")/gm)) add(m[1], m[2] ?? m[3] ?? '')
71
+ }
72
+ for (const m of requirements.matchAll(/^([A-Za-z0-9][A-Za-z0-9._-]*)(?:\[[^\]]*\])?\s*([<>=!~][^#\n;]*)?/gm)) add(m[1], m[2] ?? '')
73
+ return deps
74
+ }
75
+
76
+ function pythonTool(files: Set<string>, pyproject: string): string {
77
+ if (files.has('uv.lock')) return 'uv'
78
+ if (files.has('poetry.lock') || /^\[tool\.poetry\]/m.test(pyproject)) return 'poetry'
79
+ if (files.has('pdm.lock')) return 'pdm'
80
+ if (files.has('Pipfile') || files.has('Pipfile.lock')) return 'pipenv'
81
+ return 'pip'
82
+ }
83
+
84
+ /** The argument text of each `name(` call, to its matching parenthesis. */
85
+ function callArgs(text: string, name: string): string[] {
86
+ const out: string[] = []
87
+ for (let at = text.indexOf(`${name}(`); at !== -1; at = text.indexOf(`${name}(`, at + 1)) {
88
+ let depth = 0
89
+ for (let i = at + name.length; i < text.length; i++) {
90
+ if (text[i] === '(') depth++
91
+ else if (text[i] === ')' && --depth === 0) {
92
+ out.push(text.slice(at + name.length + 1, i))
93
+ break
94
+ }
95
+ }
96
+ }
97
+ return out
98
+ }
99
+
100
+ const prefixIn = (args: string): string => /prefix\s*=\s*["']([^"']*)["']/.exec(args)?.[1] ?? ''
101
+
102
+ /**
103
+ * `@router.get("/users/{id}")`, `@app.route("/", methods=["POST"])`, and
104
+ * Django's `path("users/", …)`.
105
+ *
106
+ * A FastAPI route is declared relative to its router, and the router mounted
107
+ * under a prefix somewhere else — `include_router(users.router, prefix="/users")`
108
+ * — so each file's prefix is followed up the includes; read alone, seven
109
+ * routes in a row were `/`.
110
+ */
111
+ async function pythonRoutes(read: Read, files: string[]): Promise<ProjectFacts['api']> {
112
+ const sources = files.filter((f) => f.endsWith('.py') && !/(^|\/)(tests?|migrations)\//.test(f) && !/(^|\/)test_[^/]*\.py$/.test(f))
113
+ type Seen = { routes: Array<{ path: string; methods: string[] }>; own: string; includes: Array<{ name: string; prefix: string }> }
114
+ const seen = new Map<string, Seen>()
115
+ for (const f of sources.slice(0, 1500)) {
116
+ const text = await read(f)
117
+ if (!/@\w+\.(get|post|put|patch|delete|head|options|route)\(|include_router\(|\bpath\(|\bre_path\(/.test(text)) continue
118
+ const routes: Seen['routes'] = []
119
+ for (const m of text.matchAll(/@\w+\.(get|post|put|patch|delete|head|options)\(\s*["']([^"']*)["']/g)) routes.push({ path: m[2], methods: [m[1].toUpperCase()] })
120
+ for (const m of text.matchAll(/@\w+\.route\(\s*["']([^"']+)["']([^)]*)\)/g)) {
121
+ const methods = [...(/methods\s*=\s*[[(]([^\])]*)/.exec(m[2])?.[1] ?? '"GET"').matchAll(/["'](\w+)["']/g)].map((x) => x[1].toUpperCase())
122
+ routes.push({ path: m[1], methods })
123
+ }
124
+ if (/(^|\/)urls\.py$/.test(f)) {
125
+ for (const m of text.matchAll(/\b(?:re_)?path\(\s*r?["']([^"']*)["']/g)) routes.push({ path: `/${m[1]}`, methods: ['ANY'] })
126
+ }
127
+ const own = callArgs(text, 'APIRouter').map(prefixIn).find(Boolean) ?? ''
128
+ const includes = callArgs(text, 'include_router').map((args) => ({
129
+ name: (/^\s*([\w.]+)/.exec(args)?.[1] ?? '').replace(/\.router$/, '').split('.').pop() ?? '',
130
+ prefix: prefixIn(args),
131
+ }))
132
+ seen.set(f, { routes, own, includes })
133
+ }
134
+ // The file an included name points at: `users` beside the including file, or
135
+ // a package of that name with its router in `api.py` or `__init__.py`.
136
+ const target = (from: string, name: string): string | undefined => {
137
+ const dir = from.includes('/') ? from.slice(0, from.lastIndexOf('/') + 1) : ''
138
+ return [`${dir}${name}.py`, `${dir}${name}/api.py`, `${dir}${name}/__init__.py`, `${dir}${name}/router.py`].find((c) => seen.has(c))
139
+ }
140
+ const mountedAt = new Map<string, string>()
141
+ const included = new Set<string>()
142
+ for (const [f, s] of seen) for (const inc of s.includes) {
143
+ const t = target(f, inc.name)
144
+ if (t) included.add(t)
145
+ }
146
+ const mount = (f: string, prefix: string, depth: number): void => {
147
+ if (depth > 8 || mountedAt.has(f)) return
148
+ const s = seen.get(f)!
149
+ mountedAt.set(f, prefix + s.own)
150
+ for (const inc of s.includes) {
151
+ const t = target(f, inc.name)
152
+ if (t) mount(t, prefix + s.own + inc.prefix, depth + 1)
153
+ }
154
+ }
155
+ for (const f of seen.keys()) if (!included.has(f)) mount(f, '', 0)
156
+ const api: ProjectFacts['api'] = []
157
+ for (const [f, s] of seen) {
158
+ for (const r of s.routes) api.push({ route: `${mountedAt.get(f) ?? s.own}${r.path}`.replace(/\/{2,}/g, '/') || '/', methods: r.methods, file: f })
159
+ if (api.length >= 80) break
160
+ }
161
+ return api
162
+ }
163
+
164
+ async function pythonModels(read: Read, files: string[]): Promise<ProjectFacts['models']> {
165
+ const names: string[] = []
166
+ let source = ''
167
+ for (const f of files.filter((p) => p.endsWith('.py') && /(^|\/)(models?|db|schemas?|tables?|entities)(\/|\.py$)/.test(p)).slice(0, 300)) {
168
+ const text = await read(f)
169
+ for (const m of text.matchAll(/^class\s+(\w+)\(\s*(models\.Model|Base|db\.Model|DeclarativeBase|SQLModel[^)]*table\s*=\s*True)/gm)) {
170
+ names.push(m[1])
171
+ source ||= m[2].startsWith('models.') ? 'Django models' : m[2].startsWith('SQLModel') ? 'SQLModel' : 'SQLAlchemy'
172
+ }
173
+ }
174
+ return names.length ? { source, names: [...new Set(names)] } : null
175
+ }
176
+
177
+ function pythonMigrations(files: string[]): ProjectFacts['migrations'] {
178
+ const alembic = files.filter((f) => /(^|\/)(alembic|migrations)\/versions\/[^/]+\.py$/.test(f))
179
+ const django = files.filter((f) => /(^|\/)migrations\/\d{4}_[^/]+\.py$/.test(f))
180
+ const within = alembic.length ? alembic : django
181
+ if (within.length === 0) return null
182
+ const dir = within[0].slice(0, within[0].lastIndexOf('/') + 1)
183
+ const names = within.map((f) => f.slice(f.lastIndexOf('/') + 1).replace(/\.py$/, '')).sort()
184
+ return { dir, count: within.length, latest: names.slice(-3) }
185
+ }
186
+
187
+ async function readPython(read: Read, files: string[], present: Set<string>): Promise<LanguageFacts> {
188
+ const pyproject = present.has('pyproject.toml') ? await read('pyproject.toml') : ''
189
+ const reqFiles = files.filter((f) => /^requirements[^/]*\.(txt|in)$/.test(f) || /^requirements\/[^/]+\.(txt|in)$/.test(f))
190
+ const requirements = (await Promise.all(reqFiles.map((f) => read(f)))).join('\n') + (present.has('Pipfile') ? `\n${await read('Pipfile')}` : '')
191
+ const deps = pythonDeps(pyproject, requirements)
192
+
193
+ const pythonVersion =
194
+ (await read('.python-version')).trim().split('\n')[0] ||
195
+ version(/requires-python\s*=\s*["']([^"']+)["']/.exec(pyproject)?.[1]) ||
196
+ version(/^python\s*=\s*["']([^"']+)["']/m.exec(pyproject)?.[1])
197
+ const stack: ProjectFacts['stack'] = [{ layer: 'Language', name: 'Python', version: version(pythonVersion) }]
198
+ const versions = new Map<string, string>()
199
+ for (const [pkg, row] of Object.entries(PYTHON_PACKAGES)) {
200
+ if (!deps.has(pkg)) continue
201
+ const v = version(deps.get(pkg))
202
+ // The frameworks `detect` records are listed from there; only their version comes from here.
203
+ if (row.label) {
204
+ if (v) versions.set(row.label, v)
205
+ continue
206
+ }
207
+ stack.push({ layer: row.layer, name: row.name, version: v })
208
+ }
209
+
210
+ const testFiles = files.filter((f) => /(^|\/)test_[^/]*\.py$|_test\.py$/.test(f))
211
+ const usesPytest = deps.has('pytest') || present.has('pytest.ini') || present.has('conftest.py') || /^\[tool\.pytest/m.test(pyproject)
212
+ return {
213
+ language: 'python',
214
+ tool: pythonTool(present, pyproject),
215
+ stack,
216
+ versions,
217
+ api: await pythonRoutes(read, files),
218
+ testFrameworks: usesPytest ? ['pytest'] : testFiles.length ? ['unittest'] : [],
219
+ testFiles,
220
+ migrations: pythonMigrations(files),
221
+ models: await pythonModels(read, files),
222
+ }
223
+ }
224
+
225
+ // ── Go ──────────────────────────────────────────────────────────────────────
226
+
227
+ const GO_MODULES: Record<string, { layer: string; name: string; label?: string }> = {
228
+ 'github.com/gin-gonic/gin': { layer: 'Framework', name: 'Gin', label: 'gin' },
229
+ 'github.com/labstack/echo': { layer: 'Framework', name: 'Echo', label: 'echo' },
230
+ 'github.com/go-chi/chi': { layer: 'Framework', name: 'chi', label: 'chi' },
231
+ 'github.com/gofiber/fiber': { layer: 'Framework', name: 'Fiber', label: 'fiber' },
232
+ 'gorm.io/gorm': { layer: 'Database', name: 'GORM' },
233
+ 'github.com/jmoiron/sqlx': { layer: 'Database', name: 'sqlx' },
234
+ 'github.com/jackc/pgx': { layer: 'Database', name: 'pgx' },
235
+ 'github.com/golang-migrate/migrate': { layer: 'Database', name: 'golang-migrate' },
236
+ 'github.com/stretchr/testify': { layer: 'Testing', name: 'testify' },
237
+ }
238
+
239
+ async function readGo(read: Read, files: string[]): Promise<LanguageFacts> {
240
+ const mod = await read('go.mod')
241
+ const stack: ProjectFacts['stack'] = [{ layer: 'Language', name: 'Go', version: /^go\s+(\d+\.\d+(?:\.\d+)?)/m.exec(mod)?.[1] }]
242
+ const versions = new Map<string, string>()
243
+ for (const [path, row] of Object.entries(GO_MODULES)) {
244
+ const m = new RegExp(`^\\s*(?:require\\s+)?${path.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?:/v\\d+)?\\s+v(\\d+\\.\\d+(?:\\.\\d+)?)`, 'm').exec(mod)
245
+ if (!m) continue
246
+ if (row.label) versions.set(row.label, m[1])
247
+ else stack.push({ layer: row.layer, name: row.name, version: m[1] })
248
+ }
249
+ const api: ProjectFacts['api'] = []
250
+ for (const f of files.filter((p) => p.endsWith('.go') && !p.endsWith('_test.go')).slice(0, 1500)) {
251
+ const text = await read(f)
252
+ for (const m of text.matchAll(/\.(GET|POST|PUT|PATCH|DELETE|Get|Post|Put|Patch|Delete)\(\s*"([^"]+)"/g)) {
253
+ api.push({ route: m[2], methods: [m[1].toUpperCase()], file: f })
254
+ }
255
+ // net/http, with Go 1.22's method patterns: `HandleFunc("GET /users/{id}", …)`.
256
+ for (const m of text.matchAll(/\bHandle(?:Func)?\(\s*"(?:(GET|POST|PUT|PATCH|DELETE)\s+)?(\/[^"]*)"/g)) {
257
+ api.push({ route: m[2], methods: [m[1] ?? 'ANY'], file: f })
258
+ }
259
+ if (api.length >= 80) break
260
+ }
261
+ const migrationFiles = files.filter((f) => /(^|\/)migrations\/[^/]+\.(up\.)?sql$/.test(f))
262
+ return {
263
+ language: 'go',
264
+ tool: 'go',
265
+ stack,
266
+ versions,
267
+ api,
268
+ testFrameworks: files.some((f) => f.endsWith('_test.go')) ? ['go test'] : [],
269
+ testFiles: files.filter((f) => f.endsWith('_test.go')),
270
+ migrations: migrationFiles.length
271
+ ? { dir: migrationFiles[0].slice(0, migrationFiles[0].lastIndexOf('/') + 1), count: migrationFiles.length, latest: migrationFiles.map((f) => f.slice(f.lastIndexOf('/') + 1)).sort().slice(-3) }
272
+ : null,
273
+ models: null,
274
+ }
275
+ }
276
+
277
+ /** A Python or Go project's facts, when its root says it is one; null otherwise. */
278
+ export async function readLanguageFacts(read: Read, files: string[]): Promise<LanguageFacts | null> {
279
+ const present = new Set(files.filter((f) => !f.includes('/')))
280
+ if (present.has('go.mod')) return readGo(read, files)
281
+ if (['pyproject.toml', 'requirements.txt', 'setup.py', 'Pipfile', 'setup.cfg'].some((f) => present.has(f))) {
282
+ return readPython(read, files, present)
283
+ }
284
+ return null
285
+ }
286
+
287
+ // ── Commands declared outside package.json ───────────────────────────────────
288
+
289
+ /**
290
+ * The commands a project declares for people to run: Makefile and justfile
291
+ * targets, executables in `scripts/`, and — for Python and Go — the tools it
292
+ * is set up for. `does` is the target's first recipe line, or what the tool is
293
+ * for.
294
+ */
295
+ export async function readCommands(read: Read, files: string[], lang: LanguageFacts | null): Promise<ProjectFacts['commands']> {
296
+ const out: ProjectFacts['commands'] = []
297
+ const seen = new Set<string>()
298
+ const add = (cmd: string, does: string): void => {
299
+ if (seen.has(cmd) || out.length >= 16) return
300
+ seen.add(cmd)
301
+ out.push({ cmd, does: does.replace(/\s+/g, ' ').trim() })
302
+ }
303
+ const makefile = files.find((f) => f === 'Makefile' || f === 'makefile' || f === 'GNUmakefile')
304
+ if (makefile) {
305
+ const text = await read(makefile)
306
+ for (const m of text.matchAll(/^([A-Za-z][\w.-]*)\s*:(?!=)[^\n]*\n((?:\t[^\n]*\n?)*)/gm)) {
307
+ add(`make ${m[1]}`, m[2].split('\n')[0]?.replace(/^\t@?/, '') ?? '')
308
+ }
309
+ }
310
+ const justfile = files.find((f) => /^\.?justfile$/i.test(f))
311
+ if (justfile) {
312
+ const text = await read(justfile)
313
+ for (const m of text.matchAll(/^@?([A-Za-z][\w-]*)(?:\s+[^:=\n]*)?:(?!=)[^\n]*\n((?:[ \t]+[^\n]*\n?)*)/gm)) {
314
+ add(`just ${m[1]}`, m[2].split('\n')[0]?.trim().replace(/^@/, '') ?? '')
315
+ }
316
+ }
317
+ for (const f of files.filter((p) => /^scripts\/[A-Za-z][\w-]*(\.sh)?$/.test(p)).slice(0, 10)) {
318
+ const first = (await read(f)).split('\n').find((l) => l.trim() && !l.startsWith('#!') && !/^set\s/.test(l.trim()) && !/^#\s*https?:\/\//.test(l.trim())) ?? ''
319
+ add(`./${f}`, first.replace(/^#\s*/, ''))
320
+ }
321
+ if (lang?.language === 'python') {
322
+ const run = { poetry: 'poetry run ', uv: 'uv run ', pdm: 'pdm run ', pipenv: 'pipenv run ' }[lang.tool] ?? ''
323
+ add({ poetry: 'poetry install', uv: 'uv sync', pdm: 'pdm install', pipenv: 'pipenv install --dev' }[lang.tool] ?? 'pip install -r requirements.txt', 'install the dependencies')
324
+ if (lang.testFrameworks.includes('pytest')) add(`${run}pytest`, 'run the tests')
325
+ if (lang.stack.some((s) => s.name === 'Ruff') || files.includes('ruff.toml') || files.includes('.ruff.toml')) {
326
+ add(`${run}ruff check .`, 'lint')
327
+ add(`${run}ruff format .`, 'format')
328
+ }
329
+ if (lang.stack.some((s) => s.name === 'mypy')) add(`${run}mypy .`, 'type-check')
330
+ }
331
+ if (lang?.language === 'go') {
332
+ add('go build ./...', 'build every package')
333
+ add('go test ./...', 'run the tests')
334
+ add('go vet ./...', 'report suspicious code')
335
+ if (files.some((f) => /^\.golangci\.ya?ml$/.test(f))) add('golangci-lint run', 'lint')
336
+ }
337
+ return out
338
+ }
@@ -226,3 +226,78 @@ describe('everything else', () => {
226
226
  expect(facts.testFiles.sort()).toEqual(['e2e/login.spec.ts', 'src/a.test.ts'])
227
227
  })
228
228
  })
229
+
230
+ describe('Python and Go projects', () => {
231
+ const FASTAPI = {
232
+ 'pyproject.toml': `[tool.poetry]\nname = "conduit"\n\n[tool.poetry.dependencies]\npython = "^3.9"\nfastapi = "^0.79.1"\nalembic = "^1.8"\n\n[tool.poetry.dev-dependencies]\npytest = "^7.1"\nmypy = "^0.971"\n`,
233
+ 'poetry.lock': '',
234
+ 'app/api/routes/api.py': 'from fastapi import APIRouter\nfrom app.api.routes import users, articles\nrouter = APIRouter()\nrouter.include_router(users.router, tags=["users"], prefix="/users")\nrouter.include_router(\n articles.router,\n dependencies=[Depends(auth)],\n)\n',
235
+ 'app/api/routes/users.py': 'router = APIRouter()\n\n@router.post("/login")\nasync def login(): ...\n\n@router.get("")\nasync def me(): ...\n',
236
+ 'app/api/routes/articles/api.py': 'router = APIRouter()\nrouter.include_router(resource.router, prefix="/articles")\n',
237
+ 'app/api/routes/articles/resource.py': 'router = APIRouter()\n\n@router.get("/{slug}")\nasync def one(): ...\n',
238
+ 'app/db/migrations/versions/fdf8821871d7_main_tables.py': '',
239
+ 'app/models/tables.py': 'class User(Base):\n pass\n',
240
+ 'tests/test_users.py': '',
241
+ 'scripts/test': '#!/usr/bin/env bash\nset -e\npytest --cov=app\n',
242
+ '.github/workflows/ci.yml': 'jobs:\n t:\n steps:\n - run: poetry install\n - run: poetry run pip --version >/dev/null 2>&1 || rm -rf .venv\n - run: poetry run uvicorn app.main:app &\n - run: poetry run ./scripts/test\n',
243
+ }
244
+
245
+ it('reads a FastAPI service: no npm, its versions, its commands, and routes with the prefixes they are mounted at', async () => {
246
+ const facts = await readProjectFacts(project(FASTAPI), { language: 'python', frameworks: ['fastapi'] })
247
+ expect(facts.packageManager).toBe('poetry')
248
+ expect(facts.language).toBe('python')
249
+ expect(facts.stack).toEqual(expect.arrayContaining([
250
+ { layer: 'Language', name: 'Python', version: '3.9' },
251
+ { layer: 'Framework', name: 'FastAPI', version: '0.79.1' },
252
+ { layer: 'Database', name: 'Alembic', version: '1.8' },
253
+ { layer: 'Testing', name: 'pytest', version: '7.1' },
254
+ ]))
255
+ expect(facts.api.map((a) => `${a.methods[0]} ${a.route}`).sort()).toEqual(['GET /articles/{slug}', 'GET /users', 'POST /users/login'])
256
+ expect(facts.commands.map((c) => c.cmd)).toEqual(['./scripts/test', 'poetry install', 'poetry run pytest', 'poetry run mypy .'])
257
+ expect(facts.commands[0].does).toBe('pytest --cov=app')
258
+ expect(facts.testFrameworks).toEqual(['pytest'])
259
+ expect(facts.testFiles).toEqual(['tests/test_users.py'])
260
+ expect(facts.migrations).toMatchObject({ count: 1, latest: ['fdf8821871d7_main_tables'] })
261
+ expect(facts.models).toEqual({ source: 'SQLAlchemy', names: ['User'] })
262
+ // The check a change has to pass, not the job's plumbing.
263
+ expect(facts.ciCommands).toEqual(['poetry run ./scripts/test'])
264
+ })
265
+
266
+ it('reads Flask and Django routes, and requirements files', async () => {
267
+ const facts = await readProjectFacts(project({
268
+ 'requirements.txt': 'Flask==3.0.2\nDjango>=5.0\n',
269
+ 'app/views.py': '@app.route("/health", methods=["GET", "POST"])\ndef health(): ...\n',
270
+ 'shop/urls.py': 'urlpatterns = [path("orders/", views.orders)]\n',
271
+ }), { language: 'python', frameworks: ['django', 'flask'] })
272
+ expect(facts.packageManager).toBe('pip')
273
+ expect(facts.api.map((a) => `${a.methods.join(',')} ${a.route}`).sort()).toEqual(['ANY /orders/', 'GET,POST /health'])
274
+ expect(facts.commands.map((c) => c.cmd)).toEqual(['pip install -r requirements.txt'])
275
+ })
276
+
277
+ it('reads a Go service: its version, its modules, its routes, and go test', async () => {
278
+ const facts = await readProjectFacts(project({
279
+ 'go.mod': 'module example.com/api\n\ngo 1.22\n\nrequire (\n\tgithub.com/gin-gonic/gin v1.10.0\n\tgorm.io/gorm v1.25.12\n)\n',
280
+ 'users/routers.go': 'func Register(r *gin.RouterGroup) {\n\tr.POST("/login", Login)\n\tr.GET("/:id", One)\n}\n',
281
+ 'main.go': 'http.HandleFunc("GET /healthz", health)\n',
282
+ 'users/users_test.go': '',
283
+ 'Makefile': '.PHONY: run\nrun:\n\tgo run .\n',
284
+ }), { language: 'go', frameworks: ['gin'] })
285
+ expect(facts.packageManager).toBe('go')
286
+ expect(facts.stack).toEqual(expect.arrayContaining([
287
+ { layer: 'Language', name: 'Go', version: '1.22' },
288
+ { layer: 'Framework', name: 'Gin', version: '1.10.0' },
289
+ { layer: 'Database', name: 'GORM', version: '1.25.12' },
290
+ ]))
291
+ expect(facts.api.map((a) => `${a.methods[0]} ${a.route}`).sort()).toEqual(['GET /:id', 'GET /healthz', 'POST /login'])
292
+ expect(facts.commands.map((c) => c.cmd)).toEqual(['make run', 'go build ./...', 'go test ./...', 'go vet ./...'])
293
+ expect(facts.testFrameworks).toEqual(['go test'])
294
+ })
295
+
296
+ it('leaves a JavaScript project as it was: npm only where there is a package.json', async () => {
297
+ const facts = await readProjectFacts(project({ 'README.md': '# x\n' }), {})
298
+ expect(facts.packageManager).toBe('')
299
+ expect(facts.commands).toEqual([])
300
+ const withPkg = await readProjectFacts(project({ 'package.json': pkg({ scripts: { test: 'vitest' } }) }), {})
301
+ expect(withPkg.packageManager).toBe('npm')
302
+ })
303
+ })
@@ -2,6 +2,7 @@ import { existsSync } from 'node:fs'
2
2
  import { readdir, readFile } from 'node:fs/promises'
3
3
  import { join } from 'node:path'
4
4
  import { PACKAGE_DETECTIONS } from './detect.js'
5
+ import { readCommands, readLanguageFacts } from './project-facts-lang.js'
5
6
 
6
7
  /**
7
8
  * What a project is, read from its files: the facts `init` writes into
@@ -17,6 +18,7 @@ import { PACKAGE_DETECTIONS } from './detect.js'
17
18
  * `/oc:bootstrap-customizations`.
18
19
  */
19
20
 
21
+
20
22
  export interface ProjectFacts {
21
23
  name?: string
22
24
  description?: string
@@ -56,6 +58,8 @@ export interface ProjectFacts {
56
58
  configPaths: string[]
57
59
  /** Files that import a package, by the detection label of the package. */
58
60
  importers: Record<string, string[]>
61
+ /** Commands declared outside package.json: Makefile, justfile, `scripts/`, and a Python or Go project's tools. */
62
+ commands: Array<{ cmd: string; does: string }>
59
63
  }
60
64
 
61
65
  // ── Reading the tree ────────────────────────────────────────────────────────
@@ -435,6 +439,7 @@ const DISPLAY: Record<string, string> = {
435
439
  sentry: 'Sentry', notion: 'Notion', vercel: 'Vercel', netlify: 'Netlify', cloudflare: 'Cloudflare',
436
440
  docker: 'Docker', railway: 'Railway', fly: 'Fly.io', render: 'Render', 'github-actions': 'GitHub Actions',
437
441
  'gitlab-ci': 'GitLab CI', circleci: 'CircleCI', jenkins: 'Jenkins', turborepo: 'Turborepo', nx: 'Nx',
442
+ fastapi: 'FastAPI', django: 'Django', flask: 'Flask', gin: 'Gin', echo: 'Echo', chi: 'chi', fiber: 'Fiber',
438
443
  }
439
444
 
440
445
  export function displayName(label: string): string {
@@ -484,7 +489,10 @@ export interface DetectedStack {
484
489
  */
485
490
  async function findCiCommands(root: string, workflows: string[], pm: string): Promise<string[]> {
486
491
  const out: string[] = []
487
- const runner = new RegExp(`^(?:${pm}|npm|pnpm|yarn|bun|npx|node)\\b`)
492
+ // The project's own tools, whatever its language. `pm` is empty for a project
493
+ // with no package manager, and an empty alternative would match every line.
494
+ const tools = [pm, 'npm', 'pnpm', 'yarn', 'bun', 'npx', 'node', 'pytest', 'python3? -m pytest', 'poetry run', 'uv run', 'pdm run', 'pipenv run', 'ruff', 'mypy', 'go (?:test|vet|build)', 'golangci-lint', 'make', '\\./scripts/']
495
+ const runner = new RegExp(`^(?:${tools.filter(Boolean).join('|')})(?:\\b|/)`)
488
496
  for (const wf of workflows) {
489
497
  const lines = (await read(root, wf)).split('\n')
490
498
  for (let i = 0; i < lines.length; i++) {
@@ -495,7 +503,11 @@ async function findCiCommands(root: string, workflows: string[], pm: string): Pr
495
503
  const indent = m[1].length
496
504
  for (let j = i + 1; j < lines.length && (lines[j].trim() === '' || lines[j].search(/\S/) > indent); j++) cmds.push(lines[j].trim())
497
505
  } 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)
506
+ // The checks a change must pass, not the job's plumbing: installs, shell
507
+ // control (`a || b`, a trailing `&`), a server started for the tests,
508
+ // migrations run to set a database up.
509
+ const plumbing = /\binstall\b|\bci$|\bci\s|\bsync$|\bmod download\b|\|\||&&|&\s*$|>\s*\/dev\/null|\bpip\b|\b(uvicorn|gunicorn|alembic)\b|\b(start|serve)$/
510
+ for (const c of cmds) if (runner.test(c) && !plumbing.test(c) && !out.includes(c)) out.push(c)
499
511
  }
500
512
  }
501
513
  return out.slice(0, 8)
@@ -536,9 +548,11 @@ async function readmeSummary(root: string, files: string[]): Promise<string | un
536
548
  * that the project itself does not use.
537
549
  */
538
550
  export async function readProjectFacts(root: string, detected: DetectedStack): Promise<ProjectFacts> {
551
+ const hasPackage = (await readPackage(root, 'package.json')) !== null
539
552
  const pkg = (await readPackage(root, 'package.json')) ?? {}
540
553
  const files = await listFiles(root)
541
554
  const frameworks = detected.frameworks ?? []
555
+ const lang = await readLanguageFacts((rel) => read(root, rel), files)
542
556
 
543
557
  // Every package.json of a monorepo declares versions; the root often none.
544
558
  const workspaceManifests = files.filter((f) => /^(apps|packages|libs|services|tooling)\/[^/]+\/package\.json$/.test(f))
@@ -556,14 +570,15 @@ export async function readProjectFacts(root: string, detected: DetectedStack): P
556
570
  for (const [name, rule] of Object.entries(PACKAGE_DETECTIONS)) {
557
571
  if (rule.label === label && deps[name]) return cleanVersion(deps[name])
558
572
  }
559
- return cleanVersion(deps[label])
573
+ return cleanVersion(deps[label]) ?? lang?.versions.get(label)
560
574
  }
561
- const stack: ProjectFacts['stack'] = []
575
+ const stack: ProjectFacts['stack'] = (lang?.stack ?? []).filter((s) => s.layer === 'Language')
562
576
  for (const [key, layer] of LAYERS) {
563
577
  for (const label of (detected as Record<string, string[] | undefined>)[key] ?? []) {
564
578
  stack.push({ layer, name: displayName(label), version: versionOf(label) })
565
579
  }
566
580
  }
581
+ stack.push(...(lang?.stack ?? []).filter((s) => s.layer !== 'Language'))
567
582
 
568
583
  const top = await readdir(root, { withFileTypes: true }).catch(() => [])
569
584
  const dirs: ProjectFacts['dirs'] = []
@@ -593,8 +608,11 @@ export async function readProjectFacts(root: string, detected: DetectedStack): P
593
608
  if (/^\s*['"]use server['"]/m.test((await read(root, f)).slice(0, 400))) serverActions.push(f)
594
609
  }
595
610
 
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))
611
+ const testFrameworks = [...Object.entries(TEST_PACKAGES).filter(([p]) => deps[p]).map(([, name]) => name), ...(lang?.testFrameworks ?? [])]
612
+ const testFiles = [
613
+ ...files.filter((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f) || /(^|\/)(__tests__|e2e|cypress\/e2e)\//.test(f)),
614
+ ...(lang?.testFiles ?? []),
615
+ ]
598
616
  const testConfigs = files.filter((f) => /(^|\/)(vitest|jest|playwright|cypress)\.config\.[cm]?[jt]s$/.test(f))
599
617
 
600
618
  const ciWorkflows = (await readdir(join(root, '.github', 'workflows')).catch(() => []))
@@ -610,8 +628,9 @@ export async function readProjectFacts(root: string, detected: DetectedStack): P
610
628
  return {
611
629
  name: pkg.name,
612
630
  description: pkg.description ?? (await readmeSummary(root, files)),
613
- packageManager: detected.packageManager ?? 'npm',
614
- language: detected.language,
631
+ // npm is the default only where there is a package.json for it to read.
632
+ packageManager: detected.packageManager ?? (hasPackage ? 'npm' : lang?.tool ?? ''),
633
+ language: detected.language ?? lang?.language,
615
634
  scripts: pkg.scripts ?? {},
616
635
  stack,
617
636
  dirs,
@@ -623,12 +642,12 @@ export async function readProjectFacts(root: string, detected: DetectedStack): P
623
642
  }),
624
643
  devPort: devPortOf(pkg.scripts ?? {}, frameworks, deps),
625
644
  pages,
626
- api,
645
+ api: [...api, ...(lang?.api ?? [])],
627
646
  rpcRouters,
628
647
  serverActions,
629
648
  middleware: files.find((f) => /^((apps|packages)\/[^/]+\/)?(src\/)?middleware\.(ts|js)$/.test(f)),
630
- models: await findModels(root, files),
631
- migrations: findMigrations(files),
649
+ models: (await findModels(root, files)) ?? lang?.models ?? null,
650
+ migrations: findMigrations(files) ?? lang?.migrations ?? null,
632
651
  testFrameworks,
633
652
  testConfigs,
634
653
  testFiles,
@@ -643,5 +662,6 @@ export async function readProjectFacts(root: string, detected: DetectedStack): P
643
662
  importers: await findImporters(root, files, packagesFor([
644
663
  ...(detected.databases ?? []), ...(detected.cms ?? []), ...(detected.auth ?? []), ...(detected.services ?? []),
645
664
  ])),
665
+ commands: await readCommands((rel) => read(root, rel), files, lang),
646
666
  }
647
667
  }
@@ -62,6 +62,14 @@ describe.skipIf(!built)('opencastle promote', () => {
62
62
  expect(existsSync(join(project, '.claude', 'skills', 'deploy-runbook', 'scripts', 'rollback.sh'))).toBe(true)
63
63
  })
64
64
 
65
+ it('looks in Claude Code’s config directory where CLAUDE_CONFIG_DIR moves it, as promote memory does', () => {
66
+ config = join(root, 'elsewhere')
67
+ write(config, { 'skills/sql-tips/SKILL.md': skill('sql-tips') })
68
+ const out = run(project, 'promote', 'skill', 'sql-tips', '--dry-run')
69
+ expect(out.status, out.stderr).toBe(0)
70
+ expect(out.stdout).toContain(join('elsewhere', 'skills', 'sql-tips'))
71
+ })
72
+
65
73
  it('finds one in the shared .agents/skills/ too', () => {
66
74
  write(home, { '.agents/skills/deploy-runbook/SKILL.md': skill('deploy-runbook') })
67
75
  expect(run(project, 'promote', 'skill', 'deploy-runbook').status).toBe(0)
@@ -103,10 +103,24 @@ function filesIn(dir: string): string[] {
103
103
 
104
104
  // ── skill ─────────────────────────────────────────────────────
105
105
 
106
- /** Where assistants keep a person's own skills. */
106
+ /**
107
+ * Where assistants keep a person's own skills.
108
+ *
109
+ * Claude Code's and Codex's under their config homes when those are moved:
110
+ * `promote memory` read `CLAUDE_CONFIG_DIR` and this did not, so one person's
111
+ * memories and skills were looked for in two different places.
112
+ */
107
113
  export function personalSkillDirs(): string[] {
108
114
  const h = home()
109
- return ['.claude/skills', '.agents/skills', '.codex/skills', '.cursor/skills', '.copilot/skills'].map((d) => join(h, d))
115
+ const claude = process.env.CLAUDE_CONFIG_DIR || join(h, '.claude')
116
+ const codex = process.env.CODEX_HOME || join(h, '.codex')
117
+ return [
118
+ join(claude, 'skills'),
119
+ join(h, '.agents', 'skills'),
120
+ join(codex, 'skills'),
121
+ join(h, '.cursor', 'skills'),
122
+ join(h, '.copilot', 'skills'),
123
+ ]
110
124
  }
111
125
 
112
126
  function findSkill(ref: string, cwd: string): string {
@@ -1,5 +1,5 @@
1
1
  import { describe, it, expect } from 'vitest';
2
- import { updateSkillMatrixContent, isEnvVarSatisfied } from './stack-config.js';
2
+ import { updateSkillMatrixContent, isEnvVarSatisfied, getExcludedCoreSkills, isPreselected } from './stack-config.js';
3
3
  import type { StackConfig } from './types.js';
4
4
  import type { SkillMatrixData } from './stack-config.js';
5
5
 
@@ -70,6 +70,30 @@ describe('isEnvVarSatisfied', () => {
70
70
  });
71
71
  });
72
72
 
73
+ describe('what a Python or Go project is given', () => {
74
+ const browser = { preselected: true, subCategory: 'e2e-testing' };
75
+
76
+ it('leaves TypeScript and web-interface rules, and the browser, out of an API service', () => {
77
+ const api = { language: 'python', frameworks: ['fastapi'] };
78
+ expect([...getExcludedCoreSkills(api)].sort()).toEqual(['accessibility-standards', 'frontend-design', 'seo-patterns', 'typescript-best-practices']);
79
+ expect(isPreselected(browser, api)).toBe(false);
80
+ expect(isPreselected(browser, { language: 'go', frameworks: ['gin'] })).toBe(false);
81
+ });
82
+
83
+ it('keeps the web rules and the browser for a framework that renders pages', () => {
84
+ const site = { language: 'python', frameworks: ['django'] };
85
+ expect([...getExcludedCoreSkills(site)]).toEqual(['typescript-best-practices']);
86
+ expect(isPreselected(browser, site)).toBe(true);
87
+ });
88
+
89
+ it('changes nothing for a JavaScript project, or a Python one with JavaScript in it', () => {
90
+ expect(getExcludedCoreSkills({ language: 'typescript' }).size).toBe(0);
91
+ expect(getExcludedCoreSkills({ language: 'python', packageManager: 'pnpm' }).size).toBe(0);
92
+ expect(isPreselected(browser, {})).toBe(true);
93
+ expect(isPreselected({ preselected: false }, {})).toBe(false);
94
+ });
95
+ });
96
+
73
97
  describe('updateSkillMatrixContent', () => {
74
98
  it('fills database slot when a database tool is selected', () => {
75
99
  const stack: StackConfig = { ides: ['vscode'], techTools: ['supabase'], teamTools: [] };