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