@skilldeck/craft 0.0.0-stage → 1.0.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.
@@ -0,0 +1,792 @@
1
+ #!/usr/bin/env node
2
+ // craft / arch-scan.mjs
3
+ //
4
+ // Find shallow-module candidates and back each one with numbers. Walks JS/TS
5
+ // (plus Python and Go when present) and computes, per module: lines of code,
6
+ // exported symbols, LOC per export (depth), import fan-in and fan-out, cyclic
7
+ // import groups (Tarjan SCC), pass-through functions, and git churn. Ranks
8
+ // candidates with a documented score and writes an offline Markdown report with
9
+ // a Mermaid dependency graph (rendered by your Markdown viewer; nothing is
10
+ // fetched, no browser is opened).
11
+ //
12
+ // node arch-scan.mjs [root] [--out .craft/arch-report.md] [--json] [--since "6 months ago"]
13
+ // [--top 15] [--lang auto|js,py,go] [--include-tests] [--cartograph <graph.json>]
14
+ //
15
+ // Exit 0 on success, 1 when the root can't be read, 2 on bad usage.
16
+ // Zero dependencies. Node 20+.
17
+
18
+ import { realpathSync } from 'node:fs'
19
+ import { fileURLToPath } from 'node:url'
20
+ import fs from 'node:fs'
21
+ import path from 'node:path'
22
+ import { spawnSync } from 'node:child_process'
23
+
24
+ const HELP = `arch-scan: rank shallow-module candidates with metrics
25
+
26
+ node arch-scan.mjs [root] [options] root defaults to the current directory
27
+
28
+ --out <file> report path (default .craft/arch-report.md, relative to cwd)
29
+ --json print the full analysis as JSON to stdout (no report unless --out)
30
+ --since <window> git churn window (default "6 months ago"); skipped outside a git repo
31
+ --top N candidates in the report (default 15)
32
+ --lang <list> auto (default), or any of js,py,go
33
+ --include-tests count test files as modules (default: skipped)
34
+ --cartograph <file> cartograph graph.json to cross-reference (auto: cartograph-out/graph.json)
35
+
36
+ Score (higher = more worth deepening):
37
+ thin = clamp((30 - LOC/exports) / 30, 0, 1) thin implementation behind each export
38
+ breadth = min(1, log2(1+exports) / log2(5)) 1 export 0.43, 2 0.68, 4+ 1
39
+ shallow = thin * breadth * (0.5 if data-only, else 1) data-only = exports but no functions
40
+ pass = pass-through functions / functions (1 for a re-export-only module)
41
+ cycle = 1 when the module sits in an import cycle
42
+ base = 5*shallow + 4*pass + 2*cycle
43
+ score = base * (1 + 0.5*log2(1+fanIn) + 0.5*log2(1+churn))
44
+ `
45
+
46
+ export const DEEP_LOC_PER_EXPORT = 30
47
+
48
+ const IGNORE_DIRS = new Set([
49
+ 'node_modules', '.git', 'dist', 'build', 'out', 'coverage', '.next', '.nuxt', '.svelte-kit', '.turbo', '.cache',
50
+ 'vendor', '__pycache__', '.venv', 'venv', '.tox', '.mypy_cache', '.pytest_cache', 'target', 'cartograph-out', '.craft',
51
+ ])
52
+ const JS_EXT = ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs']
53
+ const LANG_OF = Object.fromEntries([...JS_EXT.map((e) => [e, 'js']), ['.py', 'py'], ['.go', 'go']])
54
+ const TEST_RE = /(^|\/)(__tests__|tests?|spec)\/|\.(test|spec)\.[cm]?[jt]sx?$|(^|\/)test_[^/]+\.py$|_test\.(py|go)$/
55
+ const KEYWORDS = new Set(['if', 'for', 'while', 'switch', 'catch', 'function', 'return', 'with', 'constructor', 'super'])
56
+
57
+ // ---------------------------------------------------------------------------
58
+ // Source text helpers
59
+ // ---------------------------------------------------------------------------
60
+
61
+ /**
62
+ * Remove // and /* *\/ comments while keeping strings and every newline, so line
63
+ * numbers still match. Single- and double-quoted strings end at a newline, which
64
+ * bounds the damage when a regex literal contains a quote.
65
+ */
66
+ export function stripComments(src) {
67
+ let out = ''
68
+ let i = 0
69
+ const n = src.length
70
+ while (i < n) {
71
+ const c = src[i]
72
+ const d = src[i + 1]
73
+ if (c === '/' && d === '/') {
74
+ while (i < n && src[i] !== '\n') i++
75
+ } else if (c === '/' && d === '*') {
76
+ i += 2
77
+ while (i < n && !(src[i] === '*' && src[i + 1] === '/')) {
78
+ if (src[i] === '\n') out += '\n'
79
+ i++
80
+ }
81
+ i += 2
82
+ } else if (c === '"' || c === "'" || c === '`') {
83
+ const q = c
84
+ out += c
85
+ i++
86
+ while (i < n && src[i] !== q) {
87
+ if (src[i] === '\\') {
88
+ out += src[i] + (src[i + 1] ?? '')
89
+ i += 2
90
+ continue
91
+ }
92
+ if (src[i] === '\n' && q !== '`') break
93
+ out += src[i++]
94
+ }
95
+ if (src[i] === q) out += src[i++]
96
+ } else out += src[i++]
97
+ }
98
+ return out
99
+ }
100
+
101
+ function stripHashComments(src) {
102
+ return src.replace(/^[ \t]*#.*$/gm, '')
103
+ }
104
+
105
+ const countLoc = (text) => text.split('\n').filter((l) => l.trim()).length
106
+ const lineAt = (text, idx) => text.slice(0, idx).split('\n').length
107
+
108
+ function paramNames(list, lang) {
109
+ const raw = list.trim()
110
+ if (!raw) return []
111
+ if (/[{[]/.test(raw)) return null // destructuring: not a plain pass-through
112
+ const names = raw.split(',').map((p) => {
113
+ let s = p.trim()
114
+ if (lang === 'go') s = s.split(/\s+/)[0]
115
+ s = s.replace(/[=:].*$/, '').replace(/\?$/, '').trim()
116
+ if (lang === 'py') s = s.replace(/^\*\*?/, '*')
117
+ return s
118
+ })
119
+ return names.filter(Boolean)
120
+ }
121
+
122
+ function argNames(list, lang) {
123
+ const raw = list.trim()
124
+ if (!raw) return []
125
+ return raw.split(',').map((a) => {
126
+ let s = a.trim()
127
+ if (lang === 'go') s = s.replace(/\.\.\.$/, '')
128
+ if (lang === 'py') s = s.replace(/^\*\*?/, '*')
129
+ return s
130
+ })
131
+ }
132
+
133
+ const normParam = (p) => p.replace(/^\.\.\./, '...').replace(/^\*+/, '*')
134
+ function sameArgs(params, args, lang) {
135
+ if (!params) return false
136
+ let ps = params.map(normParam)
137
+ if (lang === 'py') ps = ps.filter((p) => p !== 'self' && p !== 'cls')
138
+ if (lang === 'go') ps = ps.map((p) => p.replace(/^\.\.\./, ''))
139
+ const as = args.map((a) => (lang === 'py' ? a.replace(/^\*+/, '*') : a))
140
+ const clean = (x) => x.replace(/^\*/, '').replace(/^\.\.\./, '')
141
+ return ps.length === as.length && ps.every((p, i) => clean(p) === clean(as[i]))
142
+ }
143
+
144
+ /**
145
+ * Functions whose whole body is `return other(sameArgs...)`. Returns
146
+ * [{ name, target, line }]. Works on comment-stripped text.
147
+ */
148
+ export function findPassThroughs(text, lang = 'js') {
149
+ const found = []
150
+ const push = (m, name, params, target, args) => {
151
+ if (!name || KEYWORDS.has(name)) return
152
+ if (sameArgs(paramNames(params, lang), argNames(args, lang), lang) && target !== name) found.push({ name, target, line: lineAt(text, m.index) })
153
+ }
154
+ const CALL = String.raw`(?:await\s+)?((?:this\.|self\.)?[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*\(([^()]*)\)`
155
+ if (lang === 'js') {
156
+ const rules = [
157
+ // function name(a, b) { return other(a, b) }
158
+ new RegExp(String.raw`^(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*\(([^()]*)\)\s*(?::\s*[^{;]+)?\{\s*return\s+${CALL}\s*;?\s*\}`, 'gm'),
159
+ // const name = (a, b) => other(a, b)
160
+ new RegExp(String.raw`^(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]+)?=\s*(?:async\s*)?\(([^()]*)\)\s*(?::\s*[^=]+)?=>\s*${CALL}[ \t]*;?[ \t]*$`, 'gm'),
161
+ // const name = (a, b) => { return other(a, b) }
162
+ new RegExp(String.raw`^(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]+)?=\s*(?:async\s*)?\(([^()]*)\)\s*(?::\s*[^=]+)?=>\s*\{\s*return\s+${CALL}\s*;?\s*\}`, 'gm'),
163
+ // const name = a => other(a)
164
+ new RegExp(String.raw`^(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s+)?([A-Za-z_$][\w$]*)\s*=>\s*${CALL}[ \t]*;?[ \t]*$`, 'gm'),
165
+ // class method: name(a) { return this.x.name(a) }
166
+ new RegExp(String.raw`^[ \t]*(?:public\s+|private\s+|protected\s+|static\s+|async\s+)*([A-Za-z_$][\w$]*)\s*\(([^()]*)\)\s*(?::\s*[^{;]+)?\{\s*return\s+${CALL}\s*;?\s*\}`, 'gm'),
167
+ ]
168
+ const seen = new Set()
169
+ for (const re of rules) {
170
+ for (const m of text.matchAll(re)) {
171
+ const key = `${m[1]}@${lineAt(text, m.index)}`
172
+ if (seen.has(key)) continue
173
+ seen.add(key)
174
+ push(m, m[1], m[2], m[3], m[4])
175
+ }
176
+ }
177
+ } else if (lang === 'py') {
178
+ const re = new RegExp(String.raw`^([ \t]*)(?:async\s+)?def\s+(\w+)\s*\(([^()]*)\)\s*(?:->\s*[^:]+)?:[ \t]*\n(?:[ \t]*(?:"""[\s\S]*?"""|'''[\s\S]*?''')[ \t]*\n)?([ \t]+)return\s+${CALL}[ \t]*$`, 'gm')
179
+ for (const m of text.matchAll(re)) {
180
+ // body must be exactly this statement: next non-blank line dedents to the def or less
181
+ const after = text.slice(m.index + m[0].length).split('\n').slice(1).find((l) => l.trim() && !l.trim().startsWith('#'))
182
+ if (after !== undefined && after.match(/^[ \t]*/)[0].length > m[1].length) continue
183
+ push(m, m[2], m[3], m[5], m[6])
184
+ }
185
+ } else if (lang === 'go') {
186
+ const re = new RegExp(String.raw`func\s+(?:\([^)]*\)\s*)?([A-Za-z_]\w*)\s*\(([^()]*)\)\s*[^{\n]*\{\s*return\s+${CALL}\s*\}`, 'g')
187
+ for (const m of text.matchAll(re)) push(m, m[1], m[2], m[3], m[4])
188
+ }
189
+ return found
190
+ }
191
+
192
+ function countFunctions(text, lang) {
193
+ if (lang === 'py') return (text.match(/^[ \t]*(?:async\s+)?def\s+\w+/gm) ?? []).length
194
+ if (lang === 'go') return (text.match(/^func\s/gm) ?? []).length
195
+ const decl = (text.match(/\bfunction\b\s*\*?\s*[A-Za-z_$]/g) ?? []).length
196
+ const arrows = (text.match(/(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*(?::[^=]+)?=\s*(?:async\s*)?(?:\([^()]*\)|[A-Za-z_$][\w$]*)\s*(?::\s*[^=]+)?=>/g) ?? []).length
197
+ const methods = (text.match(/^[ \t]+(?:public\s+|private\s+|protected\s+|static\s+|async\s+)*(?!if\b|for\b|while\b|switch\b|catch\b|return\b)[A-Za-z_$][\w$]*\s*\([^()]*\)\s*(?::\s*[^{;]+)?\{/gm) ?? []).length
198
+ return decl + arrows + methods
199
+ }
200
+
201
+ /** Exported symbols and re-export facts for one JS/TS file (comment-stripped). */
202
+ export function jsExports(text) {
203
+ const names = new Set()
204
+ let reexports = 0
205
+ let reexportAll = 0
206
+ for (const m of text.matchAll(/\bexport\s+(?:declare\s+)?(?:default\s+)?(?:async\s+)?(?:abstract\s+)?(?:function\s*\*?|class|const|let|var|interface|type|enum|namespace)\s+([A-Za-z_$][\w$]*)/g)) names.add(m[1])
207
+ if (/\bexport\s+default\s+(?!(?:async\s+)?(?:function|class)\s+[A-Za-z_$])/.test(text)) names.add('default')
208
+ for (const m of text.matchAll(/\bexport\s+(?:type\s+)?\{([^}]*)\}\s*(from\s*['"][^'"]+['"])?/g)) {
209
+ for (const part of m[1].split(',')) {
210
+ const nm = part.trim().split(/\s+as\s+/).pop()?.trim()
211
+ if (nm) {
212
+ names.add(nm)
213
+ if (m[2]) reexports++
214
+ }
215
+ }
216
+ }
217
+ for (const m of text.matchAll(/\bexport\s*\*\s*(?:as\s+([A-Za-z_$][\w$]*)\s*)?from\s*['"][^'"]+['"]/g)) {
218
+ reexportAll++
219
+ names.add(m[1] ?? `* from #${reexportAll}`)
220
+ }
221
+ const cjs = /\bmodule\.exports\s*=\s*\{([^}]*)\}/.exec(text)
222
+ if (cjs) for (const part of cjs[1].split(',')) {
223
+ const nm = part.trim().split(/[:\s(]/)[0]
224
+ if (nm && /^[A-Za-z_$]/.test(nm)) names.add(nm)
225
+ }
226
+ else if (/\bmodule\.exports\s*=/.test(text)) names.add('module.exports')
227
+ for (const m of text.matchAll(/\b(?:module\.)?exports\.([A-Za-z_$][\w$]*)\s*=/g)) names.add(m[1])
228
+ return { names: [...names], reexports, reexportAll }
229
+ }
230
+
231
+ function pyExports(text) {
232
+ const all = /^__all__\s*=\s*[[(]([^\])]*)[\])]/m.exec(text)
233
+ if (all) return { names: [...all[1].matchAll(/['"]([^'"]+)['"]/g)].map((m) => m[1]), reexports: 0, reexportAll: 0 }
234
+ const names = [...text.matchAll(/^(?:async\s+)?(?:def|class)\s+([A-Za-z]\w*)/gm)].map((m) => m[1])
235
+ return { names, reexports: 0, reexportAll: 0 }
236
+ }
237
+
238
+ function goExports(text) {
239
+ const names = new Set()
240
+ for (const m of text.matchAll(/^func\s+(?:\([^)]*\)\s*)?([A-Z]\w*)/gm)) names.add(m[1])
241
+ for (const m of text.matchAll(/^(?:type|var|const)\s+([A-Z]\w*)/gm)) names.add(m[1])
242
+ for (const m of text.matchAll(/^(?:type|var|const)\s*\(([\s\S]*?)^\)/gm)) for (const n of m[1].matchAll(/^\s+([A-Z]\w*)/gm)) names.add(n[1])
243
+ return { names: [...names], reexports: 0, reexportAll: 0 }
244
+ }
245
+
246
+ function jsImports(text) {
247
+ const specs = new Set()
248
+ for (const m of text.matchAll(/\b(?:import|export)\s+(?:type\s+)?(?:[\w$*{}\s,]+?\s+from\s*)?['"]([^'"\n]+)['"]/g)) specs.add(m[1])
249
+ for (const m of text.matchAll(/\b(?:require|import)\s*\(\s*['"]([^'"\n]+)['"]\s*\)/g)) specs.add(m[1])
250
+ return [...specs]
251
+ }
252
+
253
+ function pyImports(text) {
254
+ const specs = []
255
+ for (const m of text.matchAll(/^[ \t]*import\s+([\w.]+(?:\s+as\s+\w+)?(?:\s*,\s*[\w.]+(?:\s+as\s+\w+)?)*)/gm))
256
+ for (const part of m[1].split(',')) specs.push({ mod: part.trim().split(/\s+/)[0], names: [] })
257
+ for (const m of text.matchAll(/^[ \t]*from\s+(\.*[\w.]*)\s+import\s+\(?([\w\s,*]+)\)?/gm))
258
+ specs.push({ mod: m[1], names: m[2].split(',').map((s) => s.trim().split(/\s+/)[0]).filter(Boolean) })
259
+ return specs
260
+ }
261
+
262
+ function goImports(text) {
263
+ const specs = []
264
+ for (const m of text.matchAll(/^import\s+(?:\w+\s+)?"([^"]+)"/gm)) specs.push(m[1])
265
+ for (const m of text.matchAll(/^import\s*\(([\s\S]*?)\)/gm)) for (const s of m[1].matchAll(/"([^"]+)"/g)) specs.push(s[1])
266
+ return specs
267
+ }
268
+
269
+ // ---------------------------------------------------------------------------
270
+ // Graph algorithms
271
+ // ---------------------------------------------------------------------------
272
+
273
+ /** Tarjan's strongly connected components. graph: Map<node, Iterable<node>>. Returns groups of size > 1 (or self-loops). */
274
+ export function tarjan(graph) {
275
+ let index = 0
276
+ const idx = new Map()
277
+ const low = new Map()
278
+ const onStack = new Set()
279
+ const stack = []
280
+ const groups = []
281
+ const nodes = [...graph.keys()].sort()
282
+ for (const root of nodes) {
283
+ if (idx.has(root)) continue
284
+ // iterative DFS to survive deep graphs
285
+ const work = [{ v: root, it: null }]
286
+ while (work.length) {
287
+ const frame = work[work.length - 1]
288
+ const { v } = frame
289
+ if (frame.it === null) {
290
+ idx.set(v, index)
291
+ low.set(v, index)
292
+ index++
293
+ stack.push(v)
294
+ onStack.add(v)
295
+ frame.it = [...(graph.get(v) ?? [])].sort()[Symbol.iterator]()
296
+ }
297
+ let pushed = false
298
+ for (let step = frame.it.next(); !step.done; step = frame.it.next()) {
299
+ const w = step.value
300
+ if (!graph.has(w)) continue
301
+ if (!idx.has(w)) {
302
+ work.push({ v: w, it: null, parent: v })
303
+ pushed = true
304
+ break
305
+ } else if (onStack.has(w)) low.set(v, Math.min(low.get(v), idx.get(w)))
306
+ }
307
+ if (pushed) continue
308
+ if (low.get(v) === idx.get(v)) {
309
+ const group = []
310
+ let w
311
+ do {
312
+ w = stack.pop()
313
+ onStack.delete(w)
314
+ group.push(w)
315
+ } while (w !== v)
316
+ const selfLoop = group.length === 1 && [...(graph.get(v) ?? [])].includes(v)
317
+ if (group.length > 1 || selfLoop) groups.push(group.sort())
318
+ }
319
+ work.pop()
320
+ if (frame.parent !== undefined) low.set(frame.parent, Math.min(low.get(frame.parent), low.get(v)))
321
+ }
322
+ }
323
+ return groups
324
+ }
325
+
326
+ // ---------------------------------------------------------------------------
327
+ // Walk + resolve
328
+ // ---------------------------------------------------------------------------
329
+
330
+ function walk(root, { langs, includeTests }) {
331
+ const files = []
332
+ const packages = []
333
+ const visit = (dir) => {
334
+ let entries
335
+ try {
336
+ entries = fs.readdirSync(dir, { withFileTypes: true })
337
+ } catch {
338
+ return
339
+ }
340
+ for (const e of entries) {
341
+ if (e.isSymbolicLink()) continue
342
+ const abs = path.join(dir, e.name)
343
+ if (e.isDirectory()) {
344
+ if (!IGNORE_DIRS.has(e.name) && !e.name.startsWith('.')) visit(abs)
345
+ continue
346
+ }
347
+ if (e.name === 'package.json') packages.push(abs)
348
+ const ext = path.extname(e.name)
349
+ const lang = LANG_OF[ext]
350
+ if (!lang || !langs.has(lang)) continue
351
+ if (e.name.endsWith('.d.ts') || /\.min\.[cm]?js$/.test(e.name)) continue
352
+ const rel = path.relative(root, abs).split(path.sep).join('/')
353
+ if (!includeTests && TEST_RE.test(rel)) continue
354
+ let size = 0
355
+ try {
356
+ size = fs.statSync(abs).size
357
+ } catch {
358
+ continue
359
+ }
360
+ if (size > 1_000_000) continue
361
+ files.push({ abs, rel, lang })
362
+ }
363
+ }
364
+ visit(root)
365
+ return { files: files.sort((a, b) => a.rel.localeCompare(b.rel)), packages }
366
+ }
367
+
368
+ /** Workspace packages inside the root: name -> { dir, exports, main }, so bare imports of sibling packages resolve. */
369
+ function workspacePackages(root, pkgFiles) {
370
+ const map = new Map()
371
+ for (const abs of pkgFiles) {
372
+ try {
373
+ const pj = JSON.parse(fs.readFileSync(abs, 'utf8'))
374
+ if (!pj.name) continue
375
+ const dir = path.relative(root, path.dirname(abs)).split(path.sep).join('/')
376
+ map.set(pj.name, { dir, exports: pj.exports, main: pj.main })
377
+ } catch {}
378
+ }
379
+ return map
380
+ }
381
+
382
+ function exportTarget(entry) {
383
+ if (typeof entry === 'string') return entry
384
+ if (entry && typeof entry === 'object') return exportTarget(entry.import ?? entry.default ?? entry.node ?? entry.require)
385
+ return null
386
+ }
387
+
388
+ function resolveWorkspace(spec, pkgs, known) {
389
+ for (const [name, pkg] of pkgs) {
390
+ if (spec !== name && !spec.startsWith(name + '/')) continue
391
+ const sub = spec === name ? '.' : '.' + spec.slice(name.length)
392
+ let target = null
393
+ if (pkg.exports && typeof pkg.exports === 'object' && !Array.isArray(pkg.exports) && Object.keys(pkg.exports).some((k) => k.startsWith('.'))) target = exportTarget(pkg.exports[sub])
394
+ else if (sub === '.') target = exportTarget(pkg.exports) ?? pkg.main ?? './index'
395
+ target ??= sub
396
+ const from = pkg.dir ? `${pkg.dir}/package.json` : 'package.json'
397
+ return resolveJs(from, target.startsWith('.') ? target : `./${target}`, known)
398
+ }
399
+ return null
400
+ }
401
+
402
+ function detectLangs(root) {
403
+ const found = new Set(['js'])
404
+ const peek = (dir, depth) => {
405
+ if (depth > 4 || found.size === 3) return
406
+ let entries
407
+ try {
408
+ entries = fs.readdirSync(dir, { withFileTypes: true })
409
+ } catch {
410
+ return
411
+ }
412
+ for (const e of entries) {
413
+ if (e.isDirectory() && !IGNORE_DIRS.has(e.name) && !e.name.startsWith('.')) peek(path.join(dir, e.name), depth + 1)
414
+ else if (e.name.endsWith('.py')) found.add('py')
415
+ else if (e.name.endsWith('.go')) found.add('go')
416
+ }
417
+ }
418
+ peek(root, 0)
419
+ return found
420
+ }
421
+
422
+ function resolveJs(fromRel, spec, known) {
423
+ if (!spec.startsWith('.') && !spec.startsWith('/')) return null
424
+ const base = path.posix.normalize(path.posix.join(path.posix.dirname(fromRel), spec))
425
+ const cands = [base]
426
+ const stem = base.replace(/\.(m|c)?jsx?$/, '')
427
+ for (const e of JS_EXT) cands.push(base + e, stem + e, `${base}/index${e}`)
428
+ return cands.find((c) => known.has(c)) ?? null
429
+ }
430
+
431
+ function moduleKey(file) {
432
+ return file.lang === 'go' ? path.posix.dirname(file.rel) + '/' : file.rel
433
+ }
434
+
435
+ // ---------------------------------------------------------------------------
436
+ // Churn
437
+ // ---------------------------------------------------------------------------
438
+
439
+ /** Commits touching each file since <since>. Returns { available, window, byAbs: Map<abs, n> }. */
440
+ export function gitChurn(root, since = '6 months ago') {
441
+ const top = spawnSync('git', ['-C', root, 'rev-parse', '--show-toplevel'], { encoding: 'utf8' })
442
+ if (top.status !== 0) return { available: false, window: since, reason: 'not a git repository', byAbs: new Map() }
443
+ const topDir = fs.realpathSync(top.stdout.trim())
444
+ const log = spawnSync('git', ['-C', root, 'log', `--since=${since}`, '--name-only', '--no-renames', '--pretty=format:@@commit', '--', '.'], {
445
+ encoding: 'utf8',
446
+ maxBuffer: 256 * 1024 * 1024,
447
+ })
448
+ if (log.status !== 0) return { available: false, window: since, reason: (log.stderr || 'git log failed').trim(), byAbs: new Map() }
449
+ const byAbs = new Map()
450
+ let commits = 0
451
+ for (const line of log.stdout.split('\n')) {
452
+ const l = line.trim()
453
+ if (!l) continue
454
+ if (l === '@@commit') {
455
+ commits++
456
+ continue
457
+ }
458
+ const abs = path.join(topDir, l)
459
+ byAbs.set(abs, (byAbs.get(abs) ?? 0) + 1)
460
+ }
461
+ return { available: true, window: since, commits, byAbs }
462
+ }
463
+
464
+ // ---------------------------------------------------------------------------
465
+ // Analysis
466
+ // ---------------------------------------------------------------------------
467
+
468
+ const round = (x, d = 1) => Math.round(x * 10 ** d) / 10 ** d
469
+
470
+ /** Score from the module metrics. Documented in HELP and references/deep-modules.md. */
471
+ export function scoreModule(m) {
472
+ const depth = m.exports > 0 ? m.loc / m.exports : Infinity
473
+ const thin = m.exports > 0 ? Math.min(1, Math.max(0, (DEEP_LOC_PER_EXPORT - depth) / DEEP_LOC_PER_EXPORT)) : 0
474
+ // breadth: one tiny export is a small smell, a wide thin interface a big one (1 export 0.43, 2 0.68, 4+ 1)
475
+ const breadth = Math.min(1, Math.log2(1 + m.exports) / Math.log2(5))
476
+ // data-only modules (constants, tables, no functions) hide no logic; count them half
477
+ const dataOnly = m.functions === 0 && !m.reexportOnly ? 0.5 : 1
478
+ const shallow = thin * breadth * dataOnly
479
+ const pass = m.reexportOnly ? 1 : m.functions > 0 ? Math.min(1, m.passThroughs.length / m.functions) : 0
480
+ const cycle = m.cycle !== null ? 1 : 0
481
+ const base = 5 * shallow + 4 * pass + 2 * cycle
482
+ const weight = 1 + 0.5 * Math.log2(1 + m.fanIn) + 0.5 * Math.log2(1 + (m.churn ?? 0))
483
+ return { depth: Number.isFinite(depth) ? round(depth) : null, shallow: round(shallow, 2), pass: round(pass, 2), cycle, base: round(base, 2), score: round(base * weight) }
484
+ }
485
+
486
+ function reasonsFor(m) {
487
+ const r = []
488
+ if (m.reexportOnly) r.push('re-export only (barrel)')
489
+ if (m.exports > 0 && m.depth !== null && m.depth < DEEP_LOC_PER_EXPORT) r.push(`${m.depth} LOC per export`)
490
+ if (m.passThroughs.length) r.push(`${m.passThroughs.length}/${Math.max(m.functions, m.passThroughs.length)} fns pass-through`)
491
+ if (m.cycle !== null) r.push(`in cycle #${m.cycle + 1}`)
492
+ if (m.fanIn >= 5) r.push(`fan-in ${m.fanIn}`)
493
+ if ((m.churn ?? 0) >= 5) r.push(`churn ${m.churn}`)
494
+ return r
495
+ }
496
+
497
+ /** Scan a source tree. Pure apart from reading files and running git. */
498
+ export function scanRepo(rootArg, opts = {}) {
499
+ const root = fs.realpathSync(path.resolve(rootArg))
500
+ if (!fs.statSync(root).isDirectory()) throw new Error(`${rootArg} is not a directory`)
501
+ const langs = !opts.lang || opts.lang === 'auto' ? detectLangs(root) : new Set(String(opts.lang).split(',').map((s) => s.trim()).map((s) => (s === 'ts' ? 'js' : s)))
502
+ const { files, packages } = walk(root, { langs, includeTests: !!opts.includeTests })
503
+ const known = new Set(files.map((f) => f.rel))
504
+ const pkgs = workspacePackages(root, packages)
505
+
506
+ // Python: dotted module name -> rel path
507
+ const pyMods = new Map()
508
+ for (const f of files.filter((f) => f.lang === 'py')) {
509
+ let dotted = f.rel.replace(/\.py$/, '').replace(/\/__init__$/, '').split('/').join('.')
510
+ pyMods.set(dotted, f.rel)
511
+ if (dotted.startsWith('src.')) pyMods.set(dotted.slice(4), f.rel)
512
+ }
513
+ // Go: module path from go.mod
514
+ let goModule = null
515
+ try {
516
+ goModule = /^module\s+(\S+)/m.exec(fs.readFileSync(path.join(root, 'go.mod'), 'utf8'))?.[1] ?? null
517
+ } catch {}
518
+
519
+ const modules = new Map()
520
+ const edges = new Map() // key -> Set(key)
521
+ const external = new Map()
522
+ for (const f of files) {
523
+ const rawText = fs.readFileSync(f.abs, 'utf8')
524
+ const text = f.lang === 'py' ? stripHashComments(rawText) : stripComments(rawText)
525
+ const key = moduleKey(f)
526
+ const exp = f.lang === 'js' ? jsExports(text) : f.lang === 'py' ? pyExports(text) : goExports(text)
527
+ const pts = findPassThroughs(text, f.lang).map((p) => ({ ...p, file: f.rel }))
528
+ const m = modules.get(key) ?? { key, lang: f.lang, files: [], loc: 0, exportNames: [], reexports: 0, reexportAll: 0, functions: 0, passThroughs: [], churn: 0 }
529
+ m.files.push(f.rel)
530
+ m.loc += countLoc(text)
531
+ m.exportNames.push(...exp.names)
532
+ m.reexports += exp.reexports
533
+ m.reexportAll += exp.reexportAll
534
+ m.functions += countFunctions(text, f.lang)
535
+ m.passThroughs.push(...pts)
536
+ modules.set(key, m)
537
+ if (!edges.has(key)) edges.set(key, new Set())
538
+
539
+ const targets = []
540
+ if (f.lang === 'js') {
541
+ for (const spec of jsImports(text)) {
542
+ const t = resolveJs(f.rel, spec, known) ?? (spec.startsWith('.') ? null : resolveWorkspace(spec, pkgs, known))
543
+ if (t) targets.push(t)
544
+ else if (!spec.startsWith('.')) external.set(spec, (external.get(spec) ?? 0) + 1)
545
+ }
546
+ } else if (f.lang === 'py') {
547
+ const pkgParts = f.rel.replace(/\.py$/, '').split('/')
548
+ pkgParts.pop() // module file or __init__ -> its package
549
+ for (const { mod, names } of pyImports(text)) {
550
+ let dotted = mod
551
+ const dots = /^\.*/.exec(mod)[0].length
552
+ if (dots) {
553
+ const base = pkgParts.slice(0, pkgParts.length - (dots - 1))
554
+ const rest = mod.slice(dots)
555
+ dotted = [...base, ...(rest ? rest.split('.') : [])].join('.')
556
+ }
557
+ const hits = [pyMods.get(dotted), ...names.map((n) => pyMods.get(`${dotted}.${n}`))].filter(Boolean)
558
+ if (hits.length) targets.push(...hits)
559
+ else if (!dots) external.set(mod.split('.')[0], (external.get(mod.split('.')[0]) ?? 0) + 1)
560
+ }
561
+ } else if (f.lang === 'go') {
562
+ for (const spec of goImports(text)) {
563
+ if (goModule && (spec === goModule || spec.startsWith(goModule + '/'))) {
564
+ const dir = spec === goModule ? '.' : spec.slice(goModule.length + 1)
565
+ targets.push({ goDir: dir + '/' })
566
+ } else external.set(spec, (external.get(spec) ?? 0) + 1)
567
+ }
568
+ }
569
+ for (const t of targets) {
570
+ const tk = typeof t === 'object' ? t.goDir : moduleKey(files.find((x) => x.rel === t) ?? { rel: t, lang: 'js' })
571
+ if (tk !== key) edges.get(key).add(tk)
572
+ }
573
+ }
574
+ // drop edges to modules we never scanned (e.g. go dirs that only hold tests)
575
+ for (const [k, set] of edges) for (const t of set) if (!modules.has(t)) set.delete(t)
576
+
577
+ const churn = opts.churn === false ? { available: false, window: opts.since ?? '6 months ago', reason: 'disabled', byAbs: new Map() } : gitChurn(root, opts.since ?? '6 months ago')
578
+ const cycles = tarjan(edges)
579
+ const cycleOf = new Map()
580
+ cycles.forEach((g, i) => g.forEach((k) => cycleOf.set(k, i)))
581
+
582
+ const fanIn = new Map()
583
+ for (const [, set] of edges) for (const t of set) fanIn.set(t, (fanIn.get(t) ?? 0) + 1)
584
+
585
+ const list = []
586
+ for (const m of modules.values()) {
587
+ const exportsCount = new Set(m.exportNames).size
588
+ const reexportOnly = exportsCount > 0 && (m.reexports + m.reexportAll) >= exportsCount && m.functions === 0
589
+ const rec = {
590
+ module: m.key,
591
+ lang: m.lang,
592
+ files: m.files,
593
+ loc: m.loc,
594
+ exports: exportsCount,
595
+ exportNames: [...new Set(m.exportNames)].slice(0, 40),
596
+ functions: m.functions,
597
+ passThroughs: m.passThroughs,
598
+ reexportOnly,
599
+ fanIn: fanIn.get(m.key) ?? 0,
600
+ fanOut: edges.get(m.key)?.size ?? 0,
601
+ churn: churn.available ? m.files.reduce((s, rel) => s + (churn.byAbs.get(path.join(root, rel)) ?? 0), 0) : null,
602
+ cycle: cycleOf.has(m.key) ? cycleOf.get(m.key) : null,
603
+ }
604
+ const s = scoreModule(rec)
605
+ rec.depth = s.depth
606
+ rec.interfaceRatio = rec.loc > 0 ? round((rec.exports / rec.loc) * 100, 1) : null // exports per 100 LOC
607
+ rec.scoreParts = { shallow: s.shallow, pass: s.pass, cycle: s.cycle, base: s.base }
608
+ rec.score = s.score
609
+ rec.reasons = reasonsFor(rec)
610
+ list.push(rec)
611
+ }
612
+ list.sort((a, b) => b.score - a.score || b.fanIn - a.fanIn || a.module.localeCompare(b.module))
613
+ const candidates = list.filter((m) => m.scoreParts.base > 0 && (m.exports > 0 || m.passThroughs.length > 0))
614
+
615
+ let cartograph = null
616
+ const cgPath = opts.cartograph ? path.resolve(opts.cartograph) : [path.join(root, 'cartograph-out', 'graph.json'), path.resolve('cartograph-out', 'graph.json')].find((p) => fs.existsSync(p))
617
+ if (cgPath && fs.existsSync(cgPath)) {
618
+ try {
619
+ const g = JSON.parse(fs.readFileSync(cgPath, 'utf8'))
620
+ cartograph = { path: cgPath, nodes: g.nodes?.length ?? null, edges: (g.edges ?? g.links)?.length ?? null }
621
+ } catch {
622
+ cartograph = { path: cgPath, error: 'unreadable graph.json' }
623
+ }
624
+ }
625
+
626
+ return {
627
+ root,
628
+ generatedAt: new Date().toISOString(),
629
+ languages: [...langs].sort(),
630
+ churn: { available: churn.available, window: churn.window, commits: churn.commits ?? null, reason: churn.reason ?? null },
631
+ totals: { modules: list.length, files: files.length, loc: list.reduce((s, m) => s + m.loc, 0), edges: [...edges.values()].reduce((s, e) => s + e.size, 0), cycles: cycles.length, passThroughs: list.reduce((s, m) => s + m.passThroughs.length, 0) },
632
+ candidates,
633
+ modules: list,
634
+ cycles,
635
+ edges: Object.fromEntries([...edges].map(([k, v]) => [k, [...v].sort()])),
636
+ external: [...external].sort((a, b) => b[1] - a[1]).slice(0, 25).map(([name, count]) => ({ name, count })),
637
+ cartograph,
638
+ }
639
+ }
640
+
641
+ // ---------------------------------------------------------------------------
642
+ // Report
643
+ // ---------------------------------------------------------------------------
644
+
645
+ const esc = (s) => String(s).replace(/\|/g, '\\|')
646
+
647
+ /** Mermaid flowchart of the top candidates and their direct neighbours. */
648
+ export function mermaidGraph(a, top) {
649
+ const focus = a.candidates.slice(0, Math.min(top, 12)).map((c) => c.module)
650
+ const nodes = new Set(focus)
651
+ for (const k of focus) {
652
+ for (const t of a.edges[k] ?? []) if (nodes.size < 40) nodes.add(t)
653
+ for (const [src, ts] of Object.entries(a.edges)) if (ts.includes(k) && nodes.size < 40) nodes.add(src)
654
+ }
655
+ const ids = new Map([...nodes].sort().map((n, i) => [n, `m${i}`]))
656
+ const L = ['```mermaid', 'flowchart LR']
657
+ for (const [n, id] of ids) L.push(` ${id}["${n.replace(/"/g, "'")}"]`)
658
+ const inCycle = new Set(a.cycles.flat())
659
+ for (const [src, ts] of Object.entries(a.edges)) {
660
+ if (!ids.has(src)) continue
661
+ for (const t of ts) if (ids.has(t)) L.push(` ${ids.get(src)} ${inCycle.has(src) && inCycle.has(t) ? '-.->' : '-->'} ${ids.get(t)}`)
662
+ }
663
+ L.push(' classDef shallow fill:#fde2e1,stroke:#c0392b,color:#222')
664
+ if (focus.length) L.push(` class ${focus.map((f) => ids.get(f)).join(',')} shallow`)
665
+ L.push('```')
666
+ return L.join('\n')
667
+ }
668
+
669
+ export function renderMarkdown(a, { top = 15 } = {}) {
670
+ const L = []
671
+ const c = a.candidates.slice(0, top)
672
+ L.push('# Architecture scan: shallow-module candidates', '')
673
+ L.push(`- **Root:** \`${a.root}\``)
674
+ L.push(`- **Generated:** ${a.generatedAt}`)
675
+ L.push(`- **Languages:** ${a.languages.join(', ')}`)
676
+ L.push(`- **Scanned:** ${a.totals.modules} modules, ${a.totals.loc} LOC, ${a.totals.edges} internal imports`)
677
+ L.push(`- **Churn:** ${a.churn.available ? `${a.churn.commits} commits since "${a.churn.window}"` : `unavailable (${a.churn.reason})`}`)
678
+ if (a.cartograph) L.push(`- **Cartograph graph:** \`${a.cartograph.path}\`${a.cartograph.nodes != null ? ` (${a.cartograph.nodes} nodes)` : ''}; cross-check candidates with \`query.mjs explain <module>\``)
679
+ L.push('')
680
+ L.push('## How to read this', '')
681
+ L.push(`Depth = LOC per exported symbol: a deep module hides a lot of implementation behind a small interface. Below ${DEEP_LOC_PER_EXPORT} LOC per export the module starts to count as shallow.`, '')
682
+ L.push('```')
683
+ L.push(`thin = clamp((${DEEP_LOC_PER_EXPORT} - LOC/exports) / ${DEEP_LOC_PER_EXPORT}, 0, 1)`)
684
+ L.push('breadth = min(1, log2(1+exports) / log2(5)) 1 export 0.43, 4+ exports 1')
685
+ L.push('shallow = thin * breadth * (0.5 if data-only) data-only: exports, no functions')
686
+ L.push('pass = pass-through fns / fns (1 for a re-export-only module)')
687
+ L.push('cycle = 1 if the module is in an import cycle')
688
+ L.push('score = (5*shallow + 4*pass + 2*cycle) * (1 + 0.5*log2(1+fanIn) + 0.5*log2(1+churn))')
689
+ L.push('```', '')
690
+ L.push('The score ranks where to look, not what to change. Run the deletion test on each candidate before redesigning.', '')
691
+
692
+ L.push(`## Top ${c.length} candidates`, '')
693
+ if (!c.length) L.push('_No shallow candidates found._')
694
+ else {
695
+ L.push('| # | Module | Score | LOC | Exports | LOC/export | Fan-in | Fan-out | Churn | Why |')
696
+ L.push('|---:|---|---:|---:|---:|---:|---:|---:|---:|---|')
697
+ c.forEach((m, i) =>
698
+ L.push(`| ${i + 1} | \`${esc(m.module)}\` | ${m.score} | ${m.loc} | ${m.exports} | ${m.depth ?? '-'} | ${m.fanIn} | ${m.fanOut} | ${m.churn ?? '-'} | ${esc(m.reasons.join('; '))} |`),
699
+ )
700
+ }
701
+
702
+ if (c.length) L.push('', '## Dependency graph (top candidates)', '', 'Shaded nodes are candidates; dotted edges sit inside an import cycle.', '', mermaidGraph(a, top))
703
+
704
+ const pts = a.modules.flatMap((m) => m.passThroughs)
705
+ L.push('', `## Pass-through functions (${pts.length})`, '')
706
+ if (!pts.length) L.push('_None found._')
707
+ for (const p of pts.slice(0, 40)) L.push(`- \`${p.file}:${p.line}\` \`${p.name}\` -> \`${p.target}(...)\` with the same arguments`)
708
+ if (pts.length > 40) L.push(`- ...and ${pts.length - 40} more (see --json)`)
709
+
710
+ L.push('', `## Import cycles (${a.cycles.length})`, '')
711
+ if (!a.cycles.length) L.push('_None found._')
712
+ a.cycles.slice(0, 20).forEach((g, i) => L.push(`${i + 1}. ${g.map((k) => `\`${k}\``).join(' <-> ')}`))
713
+
714
+ if (a.churn.available) {
715
+ const hot = a.modules.filter((m) => m.churn > 0).sort((x, y) => y.churn * Math.log2(1 + y.loc) - x.churn * Math.log2(1 + x.loc)).slice(0, 10)
716
+ L.push('', '## Churn hotspots', '', 'Commits touching the module in the window, weighted by size. High churn on a shallow module means its interface keeps leaking change to callers.', '')
717
+ if (!hot.length) L.push('_No commits in the window._')
718
+ else {
719
+ L.push('| Module | Churn | LOC | Fan-in |', '|---|---:|---:|---:|')
720
+ for (const m of hot) L.push(`| \`${esc(m.module)}\` | ${m.churn} | ${m.loc} | ${m.fanIn} |`)
721
+ }
722
+ }
723
+
724
+ const fan = [...a.modules].sort((x, y) => y.fanIn - x.fanIn).filter((m) => m.fanIn > 0).slice(0, 10)
725
+ L.push('', '## Most depended-on modules', '', 'High fan-in plus a wide interface makes every change expensive; high fan-in plus a narrow interface is a deep module doing its job.', '')
726
+ if (!fan.length) L.push('_No internal imports found._')
727
+ else {
728
+ L.push('| Module | Fan-in | Exports | LOC/export |', '|---|---:|---:|---:|')
729
+ for (const m of fan) L.push(`| \`${esc(m.module)}\` | ${m.fanIn} | ${m.exports} | ${m.depth ?? '-'} |`)
730
+ }
731
+ L.push('', '---', 'Generated by craft/deepen-modules arch-scan.mjs. Offline: render the Mermaid block in any Markdown viewer that supports it.')
732
+ return L.join('\n') + '\n'
733
+ }
734
+
735
+ // ---------------------------------------------------------------------------
736
+ // CLI
737
+ // ---------------------------------------------------------------------------
738
+
739
+ export function main(argv) {
740
+ if (argv.includes('--help') || argv.includes('-h')) {
741
+ process.stdout.write(HELP)
742
+ return 0
743
+ }
744
+ const valued = new Set(['--out', '--since', '--top', '--lang', '--cartograph'])
745
+ const opts = {}
746
+ const pos = []
747
+ for (let i = 0; i < argv.length; i++) {
748
+ if (valued.has(argv[i])) {
749
+ if (argv[i + 1] === undefined) {
750
+ process.stderr.write(`arch-scan: ${argv[i]} needs a value\n`)
751
+ return 2
752
+ }
753
+ opts[argv[i].slice(2)] = argv[++i]
754
+ } else if (argv[i].startsWith('--')) opts[argv[i].slice(2)] = true
755
+ else pos.push(argv[i])
756
+ }
757
+ const top = Number(opts.top ?? 15)
758
+ if (!Number.isInteger(top) || top < 1) {
759
+ process.stderr.write('arch-scan: --top must be a positive integer\n')
760
+ return 2
761
+ }
762
+ const root = pos[0] ?? '.'
763
+ let a
764
+ try {
765
+ a = scanRepo(root, { since: opts.since, lang: opts.lang, includeTests: !!opts['include-tests'], cartograph: opts.cartograph })
766
+ } catch (err) {
767
+ process.stderr.write(`arch-scan: ${err.message}\n`)
768
+ return 1
769
+ }
770
+ if (opts.json) {
771
+ console.log(JSON.stringify(a, null, 2))
772
+ if (!opts.out) return 0
773
+ }
774
+ const out = path.resolve(opts.out ?? path.join('.craft', 'arch-report.md'))
775
+ fs.mkdirSync(path.dirname(out), { recursive: true })
776
+ fs.writeFileSync(out, renderMarkdown(a, { top }))
777
+ if (!opts.json) {
778
+ console.log(`arch-scan: ${a.totals.modules} modules, ${a.totals.edges} imports, ${a.totals.cycles} cycles, ${a.totals.passThroughs} pass-throughs; churn ${a.churn.available ? 'on' : 'off'}`)
779
+ for (const [i, m] of a.candidates.slice(0, 5).entries()) console.log(` ${i + 1}. ${m.module} score ${m.score} (${m.reasons.join('; ')})`)
780
+ console.log(`report: ${out}`)
781
+ }
782
+ return 0
783
+ }
784
+
785
+ // Run only when this file is the entry point. Real paths are compared because
786
+ // the path Node was given can be a symlink (macOS /tmp and /var, a linked
787
+ // skills folder), and then it never equals the module's own URL.
788
+ function isEntryPoint(url) {
789
+ try { return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(url)) } catch { return false }
790
+ }
791
+
792
+ if (isEntryPoint(import.meta.url)) process.exitCode = main(process.argv.slice(2))