gatelight 0.0.0-stage → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/.antigravity-plugin/plugin.json +9 -0
  2. package/.claude-plugin/plugin.json +11 -0
  3. package/.codex-plugin/plugin.json +18 -0
  4. package/.mcp.json +8 -0
  5. package/LICENSE +21 -0
  6. package/README.md +29 -2
  7. package/bin/modwall +8 -0
  8. package/bin/node.sh +14 -0
  9. package/bin/testcraft +8 -0
  10. package/bin/testpace +8 -0
  11. package/entry/command +44 -0
  12. package/hooks/antigravity.sh +24 -0
  13. package/hooks/codex.json +50 -0
  14. package/hooks/codex.sh +7 -0
  15. package/hooks/hooks.json +43 -0
  16. package/hooks/testpace.ts +25 -0
  17. package/hooks.json +16 -0
  18. package/mcp_config.json +8 -0
  19. package/package.json +23 -4
  20. package/setup.mjs +99 -0
  21. package/skills/merge/SKILL.md +42 -0
  22. package/skills/modular/SKILL.md +75 -0
  23. package/skills/setup/SKILL.md +101 -0
  24. package/skills/setup-modwall/SKILL.md +112 -0
  25. package/skills/setup-testcraft/SKILL.md +23 -0
  26. package/skills/setup-testcraft/checklist/dev-login.md +20 -0
  27. package/skills/write-tests/SKILL.md +153 -0
  28. package/src/base/agent.ts +100 -0
  29. package/src/base/baseline.ts +54 -0
  30. package/src/base/commandline.ts +40 -0
  31. package/src/base/commands.ts +94 -0
  32. package/src/base/confirm.ts +161 -0
  33. package/src/base/contract.ts +94 -0
  34. package/src/base/coverage.ts +46 -0
  35. package/src/base/entry.ts +90 -0
  36. package/src/base/excerpt.ts +46 -0
  37. package/src/base/execute.ts +70 -0
  38. package/src/base/exit.ts +6 -0
  39. package/src/base/format.ts +27 -0
  40. package/src/base/full.ts +160 -0
  41. package/src/base/gate.ts +251 -0
  42. package/src/base/git.ts +361 -0
  43. package/src/base/glob.ts +38 -0
  44. package/src/base/hook.ts +297 -0
  45. package/src/base/hookformat.ts +257 -0
  46. package/src/base/judging.ts +27 -0
  47. package/src/base/layermap.ts +69 -0
  48. package/src/base/module.ts +88 -0
  49. package/src/base/process-group.ts +101 -0
  50. package/src/base/records.ts +66 -0
  51. package/src/base/repo.ts +155 -0
  52. package/src/base/sessions.ts +55 -0
  53. package/src/base/shell.ts +176 -0
  54. package/src/base/stop.ts +100 -0
  55. package/src/base/store.ts +348 -0
  56. package/src/base/version.ts +24 -0
  57. package/src/cli.ts +186 -0
  58. package/src/craft/change.ts +24 -0
  59. package/src/craft/checklist.ts +157 -0
  60. package/src/craft/commands.ts +111 -0
  61. package/src/craft/config.ts +15 -0
  62. package/src/craft/full.ts +30 -0
  63. package/src/craft/index.ts +12 -0
  64. package/src/craft/session.ts +21 -0
  65. package/src/mcp.ts +79 -0
  66. package/src/modules.ts +10 -0
  67. package/src/modwall.ts +8 -0
  68. package/src/pace/commands.ts +281 -0
  69. package/src/pace/config.ts +103 -0
  70. package/src/pace/consent.ts +81 -0
  71. package/src/pace/focused.ts +208 -0
  72. package/src/pace/full.ts +38 -0
  73. package/src/pace/index.ts +16 -0
  74. package/src/pace/record.ts +84 -0
  75. package/src/pace/report.ts +335 -0
  76. package/src/pace/results.ts +243 -0
  77. package/src/pace/run/node-test-reporter.mjs +34 -0
  78. package/src/pace/run/node-test.ts +26 -0
  79. package/src/pace/run/playwright-reporter.mjs +48 -0
  80. package/src/pace/run/playwright.ts +34 -0
  81. package/src/pace/run/runner.ts +157 -0
  82. package/src/pace/run/targets.ts +130 -0
  83. package/src/pace/run/vitest-launcher.mjs +101 -0
  84. package/src/pace/run/vitest.ts +22 -0
  85. package/src/pace/session.ts +35 -0
  86. package/src/pace/testlist.ts +91 -0
  87. package/src/pace/tests.ts +22 -0
  88. package/src/pace/verify.ts +95 -0
  89. package/src/testcraft.ts +9 -0
  90. package/src/wall/check.ts +258 -0
  91. package/src/wall/commands.ts +279 -0
  92. package/src/wall/config.ts +394 -0
  93. package/src/wall/database.ts +136 -0
  94. package/src/wall/dbcheck.ts +389 -0
  95. package/src/wall/dbrules.ts +213 -0
  96. package/src/wall/edit.ts +64 -0
  97. package/src/wall/files.ts +35 -0
  98. package/src/wall/full.ts +30 -0
  99. package/src/wall/index.ts +15 -0
  100. package/src/wall/init.ts +149 -0
  101. package/src/wall/layermap.ts +124 -0
  102. package/src/wall/layout.ts +231 -0
  103. package/src/wall/loosen.ts +157 -0
  104. package/src/wall/miniprogram.ts +80 -0
  105. package/src/wall/project.ts +88 -0
  106. package/src/wall/rules.ts +400 -0
  107. package/src/wall/session.ts +198 -0
  108. package/src/wall/sql.ts +510 -0
  109. package/src/wall/store.ts +39 -0
@@ -0,0 +1,64 @@
1
+ // 写文件那一刻的"只走入口":agent 要写进文件的新文字里,有没有直接引用别的模块的内部文件。
2
+ // 这是 R1(绕过入口)提前到改文件之前的那一部分:越界在写的那一刻就拦下,不等到跑 modwall check。
3
+ // 只做看文字就能判断的事(钩子进程里不建 LayerMap 的图):
4
+ // 只管 TypeScript / JavaScript 文件里用相对路径写的引用(./、../);别名、包名这类要解析才知道指向哪的不管。
5
+ // 引用的是样式、图片、数据这类不是代码的文件不管。配置里给这个文件写了 R1 例外的不管。
6
+ // 这里放过的不等于没越界:完整的判断照旧由 modwall check 做(rules.ts 的 importViolations)。
7
+
8
+ import { posix } from 'node:path'
9
+ import { moduleId, type Scheme } from './config.ts'
10
+ import { label, type Owner, ownerIn, placeInRoots } from './layout.ts'
11
+
12
+ const SCRIPT = /\.[cm]?[jt]sx?$/u
13
+ /** import … from '…'、export … from '…'、import '…'、import('…')、require('…') 里用相对路径写的那一段。 */
14
+ const RELATIVE_IMPORT = /(?:\bfrom\s*|\bimport\s*\(\s*|\brequire\s*\(\s*|\bimport\s+)(['"])(\.{1,2}\/[^'"\n]*)\1/gu
15
+
16
+ const withoutExtension = (name: string): string => name.replace(/\.[^./]+$/u, '')
17
+
18
+ /** 新文字里用相对路径引用的文件(相对仓库根目录,照写的样子,可能没有扩展名)。整行注释里的不算。 */
19
+ export function relativeImports(path: string, text: string): Array<{ spec: string; target: string }> {
20
+ const found: Array<{ spec: string; target: string }> = []
21
+ for (const line of text.split('\n')) {
22
+ const trimmed = line.trimStart()
23
+ if (trimmed.startsWith('//') || trimmed.startsWith('*') || trimmed.startsWith('/*')) continue
24
+ for (const match of line.matchAll(RELATIVE_IMPORT)) {
25
+ const spec = match[2] as string
26
+ const target = posix.normalize(posix.join(posix.dirname(path), spec)).replace(/\/$/u, '')
27
+ if (!target.startsWith('../')) found.push({ spec, target })
28
+ }
29
+ }
30
+ return found
31
+ }
32
+
33
+ /**
34
+ * path 这个文件要写进 text:里面有没有绕过入口引用了别的模块的内部文件。有就返回拒绝的原因(带改法),没有返回 undefined。
35
+ * owner 是 path 的归属。
36
+ */
37
+ export function entryBypass(scheme: Scheme, path: string, owner: Owner, text: string): string | undefined {
38
+ if (!SCRIPT.test(path)) return undefined
39
+ if (owner.kind !== 'module' && owner.kind !== 'app') return undefined
40
+ if (scheme.allow.some(entry => entry.rule === 'R1' && entry.from === path)) return undefined
41
+ const from = owner.kind === 'module' ? moduleId(owner.app, owner.name) : undefined
42
+ for (const { spec, target } of relativeImports(path, text)) {
43
+ const extension = posix.extname(target)
44
+ if (extension !== '' && !SCRIPT.test(target)) continue
45
+ // 目标可能是模块目录本身(引目录就是引它的入口):补一段再认归属
46
+ const to = ownerIn(scheme, `${target}/_`)
47
+ if (to.kind !== 'module' || to.mapped) continue
48
+ const id = moduleId(to.app, to.name)
49
+ if (id === from) continue
50
+ const app = scheme.apps.find(item => item.name === to.app)
51
+ const place = app && placeInRoots(app, `${target}/_`)
52
+ if (!app || !place?.name) continue
53
+ const dir = `${place.root}/${place.name}`
54
+ const rest = target === dir ? '' : target.slice(dir.length + 1)
55
+ const entries = app.entry.map(withoutExtension)
56
+ if (rest === '' || (!rest.includes('/') && entries.includes(withoutExtension(rest)))) continue
57
+ const names = app.entry.filter(name => SCRIPT.test(name)).join('、')
58
+ return (
59
+ `modwall(R1 绕过入口):${path}(${label(owner)})要 import ${id} 模块的内部文件(${spec})。` +
60
+ `改成从 ${id} 的入口引用(${dir}/ 下的 ${names});入口里没有,就先在对方入口新增导出(作为单独的一小步),再从入口引用。`
61
+ )
62
+ }
63
+ return undefined
64
+ }
@@ -0,0 +1,35 @@
1
+ // 文件的认法,和 LayerMap 一致:哪些是代码文件(它支持的四种语言)、哪些是测试文件、哪些目录它不读。
2
+ // 测试文件不归 modwall 管;LayerMap 给的 import 里也没有来源是测试文件的。
3
+ // LayerMap 不读的目录里的代码,modwall 照样列进文件清单:它引用了谁查不到,只有写进 outside 才算有归属(layout.ts)。
4
+
5
+ /** LayerMap 认作测试的路径(它的 mapTestPath)。 */
6
+ const TEST_PATH =
7
+ /(?:^|\/)(?:__tests__|tests?|fixtures?|testFixtures|e2e|testdata)(?:\/|$)|\.(?:spec|test)\.|_test\.(?:go|py)$|(?:^|\/)(?:test_[^/]*\.py|conftest\.py)$/iu
8
+
9
+ /** LayerMap 四种语言的源文件:TS/JS、Python、Go、Java。 */
10
+ const CODE = /\.(?:[cm]?[jt]sx?|pyi?|go|java)$/u
11
+
12
+ /** R1(必须走入口)第一版只管的语言:TS/JS 和 Python。 */
13
+ const ENTRY_LANGUAGE = /\.(?:[cm]?[jt]sx?|pyi?)$/u
14
+
15
+ /** LayerMap 不读的目录名(它的 excludedSegments):依赖、缓存、coding agent 自己的目录。 */
16
+ export const UNREAD_DIRECTORIES = ['node_modules', 'vendor', '.venv', '__pycache__', 'site-packages', '.claude', '.codex', '.cursor', '.pi']
17
+ const UNREAD = new Set(UNREAD_DIRECTORIES)
18
+
19
+ /** 样式文件:不能经模块入口导出(R1 的改法不同)。 */
20
+ const STYLESHEET = /\.(?:css|scss|sass|less|styl|stylus|pcss|wxss|acss)$/iu
21
+
22
+ export const isTest = (path: string): boolean => TEST_PATH.test(path)
23
+ export const isStylesheet = (path: string): boolean => STYLESHEET.test(path)
24
+ export const isCode = (path: string): boolean => CODE.test(path)
25
+ export const inEntryLanguage = (path: string): boolean => ENTRY_LANGUAGE.test(path)
26
+
27
+ /**
28
+ * 这个文件在 LayerMap 不读的目录里时,给出那个目录(从仓库根目录写到最外层那一段,大小写照原样)。
29
+ * 认法和 LayerMap 的 inExcludedDirectory 一样:转小写、按 / 切开、去掉最后的文件名,看有没有哪一段在清单里。
30
+ */
31
+ export function unreadDirectory(path: string): string | undefined {
32
+ const segments = path.split('/').slice(0, -1)
33
+ const index = segments.findIndex(segment => UNREAD.has(segment.toLowerCase()))
34
+ return index === -1 ? undefined : segments.slice(0, index + 1).join('/')
35
+ }
@@ -0,0 +1,30 @@
1
+ // 整组里"模块边界"的部分(base/module.ts 的 fullPart):接入了的仓库在测试之前跑一次 modwall check。
2
+ // 它随插件一起装,不用在本机另外登记;没接入的仓库没有这一段。
3
+ // 库里的现状(modwall db check)不在这一段:要迁移跑完才能查,由项目写在自己的 full 命令里。
4
+
5
+ import { fileURLToPath } from 'node:url'
6
+ import { quoted } from '../base/execute.ts'
7
+ import { forkPoint } from '../base/git.ts'
8
+ import type { FullPart } from '../base/module.ts'
9
+ import type { Repo } from '../base/repo.ts'
10
+ import { joined } from './config.ts'
11
+
12
+ /** 这个插件里的 modwall 命令:用完整路径,不靠 PATH 上碰巧有哪一版。 */
13
+ const BIN = fileURLToPath(new URL('../../bin/modwall', import.meta.url))
14
+
15
+ export function fullPart(repo: Repo): FullPart {
16
+ // 按分叉点也算接入:删掉 .modwall/ 躲不过检查
17
+ if (!joined(repo.root, forkPoint(repo.root).commit)) return { steps: [] }
18
+ return {
19
+ steps: [
20
+ {
21
+ kind: 'wall',
22
+ name: '模块边界的检查(modwall check)',
23
+ title: '模块边界的检查(modwall check)',
24
+ header: '模块边界的检查:modwall check',
25
+ command: `${quoted(BIN)} check`,
26
+ args: [],
27
+ },
28
+ ],
29
+ }
30
+ }
@@ -0,0 +1,15 @@
1
+ // "模块边界"这个检查模块交给底座的入口(见 base/module.ts):底座只通过这里知道它。
2
+ // 它在项目里的配置是 .modwall/ 目录,没有这个目录的仓库里它不出声、不加检查。
3
+
4
+ import type { Module } from '../base/module.ts'
5
+ import { fullPart } from './full.ts'
6
+ import { beforeEdit, brief, onSession, unfinished } from './session.ts'
7
+
8
+ export const wall: Module = {
9
+ name: 'wall',
10
+ brief,
11
+ onSession,
12
+ beforeEdit,
13
+ unfinished,
14
+ fullPart,
15
+ }
@@ -0,0 +1,149 @@
1
+ // modwall init:按现有目录生成配置草稿。只认常见的目录名,认不出的留空,由 agent 照 setup 技能补好、再用 modwall check 核对。
2
+ // 模块根目录分属几个应用目录时,按应用分组起草,应用名取应用目录的名字。应用目录从这几处找:
3
+ // 工作区包:pnpm-workspace.yaml 的 packages、package.json 的 workspaces(有 package.json、路径对上的目录;仓库根目录本身不算);
4
+ // 常见的 apps/*、services/*、packages/*(下面有代码的子目录,不要求是工作区包:Go、Python 的服务没有 package.json)。
5
+ // 认不出来的应用目录(比如不是工作区包、又不在这几个目录下的小程序)不起草,它下面的代码列为没有归属,由接入的 agent 手动补一组应用配置。
6
+ // 在每个应用目录里按同样的常见目录名找模块根目录、共享层、装配层;找到模块根目录的应用目录有两个以上才按应用分组。
7
+
8
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
9
+ import { basename, join } from 'node:path'
10
+ import type { AppConfig, Config } from './config.ts'
11
+ import { isCode, isTest, unreadDirectory } from './files.ts'
12
+ import { globToRegExp } from '../base/glob.ts'
13
+ import { ownerOf, placeInRoots } from './layout.ts'
14
+
15
+ /** 常见的模块根目录:下面有子目录才算。 */
16
+ const ROOTS = ['src/modules', 'modules', 'src/features', 'features', 'app/modules']
17
+ /** 常见的共享层目录。 */
18
+ const SHARED = ['src/shared', 'shared', 'src/common', 'common', 'src/lib', 'lib']
19
+ /** 常见的程序入口文件和装配目录。 */
20
+ const APP_FILES = ['src/main.ts', 'src/main.tsx', 'src/main.js', 'src/index.ts', 'src/index.tsx', 'src/index.js', 'src/app.ts', 'src/app.js', 'main.py', 'app.py', 'main.go']
21
+ const APP_DIRS = ['src/app']
22
+ /** 常见的不归 modwall 管的目录:脚本、迁移。 */
23
+ const OUTSIDE_DIRS = ['scripts', 'migrations', 'tools']
24
+ /** 常见的放应用的目录:下面每个有代码的子目录是一个应用目录。 */
25
+ const APP_PARENTS = ['apps', 'services', 'packages']
26
+
27
+ const DEFAULT_ENTRY = ['index.ts', 'index.tsx', 'index.js', '__init__.py']
28
+
29
+ const isDir = (root: string, path: string): boolean => statSync(join(root, path), { throwIfNoEntry: false })?.isDirectory() === true
30
+ const hasSubdirs = (root: string, path: string): boolean =>
31
+ isDir(root, path) && readdirSync(join(root, path), { withFileTypes: true }).some(entry => entry.isDirectory() && !entry.name.startsWith('.'))
32
+
33
+ /** 一个应用目录(dir 为空是仓库根目录)里起草的划分,和这个目录里不归 modwall 管的路径。 */
34
+ function draftApp(root: string, files: readonly string[], dir: string): { app: AppConfig; outside: string[] } {
35
+ const at = (path: string): string => (dir ? `${dir}/${path}` : path)
36
+ const present = new Set(files)
37
+ const hasCode = (path: string): boolean => files.some(file => file.startsWith(`${path}/`) && isCode(file) && !isTest(file))
38
+ const roots = ROOTS.map(at).filter(path => hasSubdirs(root, path))
39
+ const inRoot = (path: string): boolean => roots.some(rootDir => path === rootDir || path.startsWith(`${rootDir}/`))
40
+ const shared = SHARED.map(at)
41
+ .filter(path => !inRoot(path) && hasCode(path))
42
+ .map(path => `${path}/**`)
43
+ // 直接放在模块根目录下、名字是入口文件名的(Python 包的 __init__.py、汇总各模块的 index.ts):点名归装配层
44
+ const rootFiles = files.filter(path => {
45
+ const place = placeInRoots({ roots }, path)
46
+ return place !== undefined && place.name === undefined && DEFAULT_ENTRY.some(name => path === `${place.root}/${name}`)
47
+ })
48
+ const app = [
49
+ ...APP_FILES.map(at).filter(path => present.has(path)),
50
+ ...APP_DIRS.map(at)
51
+ .filter(path => !inRoot(path) && hasCode(path))
52
+ .map(path => `${path}/**`),
53
+ ...rootFiles,
54
+ ]
55
+ // 这一层的构建配置(vite.config.ts 这类)和脚本、迁移目录
56
+ const top = (path: string): boolean => (dir ? path.startsWith(`${dir}/`) && !path.slice(dir.length + 1).includes('/') : !path.includes('/'))
57
+ const configs = files.filter(path => top(path) && isCode(path) && /\.config\.[^.]+$/.test(path))
58
+ const outside = [
59
+ ...configs,
60
+ ...OUTSIDE_DIRS.map(at)
61
+ .filter(path => hasCode(path))
62
+ .map(path => `${path}/**`),
63
+ ]
64
+ return { app: { roots, shared, app, entry: DEFAULT_ENTRY, map: {} }, outside }
65
+ }
66
+
67
+ /** pnpm-workspace.yaml 的 packages:只读这一个列表(每行 "- 路径规则"),不是完整的 YAML 解析。 */
68
+ function pnpmPackages(root: string): string[] {
69
+ const file = join(root, 'pnpm-workspace.yaml')
70
+ if (!existsSync(file)) return []
71
+ const patterns: string[] = []
72
+ let inPackages = false
73
+ for (const line of readFileSync(file, 'utf8').split('\n')) {
74
+ if (/^packages\s*:/.test(line)) {
75
+ inPackages = true
76
+ continue
77
+ }
78
+ if (!inPackages || line.trim() === '' || line.trim().startsWith('#')) continue
79
+ const item = /^\s+-\s*(['"]?)(.+?)\1\s*(?:#.*)?$/.exec(line)
80
+ if (!item) {
81
+ if (!/^\s/.test(line)) inPackages = false
82
+ continue
83
+ }
84
+ patterns.push(item[2] as string)
85
+ }
86
+ return patterns
87
+ }
88
+
89
+ /** package.json 的 workspaces:数组,或 { packages: [...] }。 */
90
+ function npmWorkspaces(root: string): string[] {
91
+ try {
92
+ const raw = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { workspaces?: unknown }
93
+ const list = Array.isArray(raw.workspaces) ? raw.workspaces : (raw.workspaces as { packages?: unknown } | undefined)?.packages
94
+ return Array.isArray(list) ? list.filter((item): item is string => typeof item === 'string') : []
95
+ } catch {
96
+ return []
97
+ }
98
+ }
99
+
100
+ /** 仓库里的应用目录:工作区包、常见的 apps/*、services/*、packages/*;互相嵌套的只留外面那个。 */
101
+ export function appDirs(root: string, files: readonly string[]): string[] {
102
+ const found = new Set<string>()
103
+ const workspaces = [...pnpmPackages(root), ...npmWorkspaces(root)].map(item => item.replace(/^(?:\.\/)+/, '').replace(/\/+$/, ''))
104
+ const include = workspaces.filter(item => item !== '' && item !== '.' && !item.startsWith('!')).map(item => globToRegExp(item))
105
+ const exclude = workspaces.filter(item => item.startsWith('!')).map(item => globToRegExp(item.slice(1).replace(/^(?:\.\/)+/, '')))
106
+ for (const path of files) {
107
+ if (!path.endsWith('/package.json') || unreadDirectory(path) !== undefined) continue
108
+ const dir = path.slice(0, -'/package.json'.length)
109
+ if (include.some(reg => reg.test(dir)) && !exclude.some(reg => reg.test(dir))) found.add(dir)
110
+ }
111
+ for (const path of files) {
112
+ if (!isCode(path) || isTest(path) || unreadDirectory(path) !== undefined) continue
113
+ const [parent, child, ...rest] = path.split('/')
114
+ if (parent !== undefined && APP_PARENTS.includes(parent) && child !== undefined && rest.length > 0) found.add(`${parent}/${child}`)
115
+ }
116
+ const dirs = [...found].sort()
117
+ return dirs.filter(dir => !dirs.some(other => other !== dir && dir.startsWith(`${other}/`)))
118
+ }
119
+
120
+ /** files:工作区里现有的文件。 */
121
+ export function draftConfig(root: string, files: readonly string[]): Config {
122
+ const base = draftApp(root, files, '')
123
+ const apps = appDirs(root, files)
124
+ .map(dir => ({ dir, ...draftApp(root, files, dir) }))
125
+ .filter(item => item.app.roots.length > 0)
126
+ let draft: Config
127
+ if (apps.length >= 2) {
128
+ // 应用名取应用目录的名字;两个应用目录同名(apps/web、services/web)时用整个路径,/ 换成 -
129
+ const names = apps.map(item => basename(item.dir))
130
+ const grouped: Record<string, AppConfig> = {}
131
+ apps.forEach((item, index) => {
132
+ const name = names.filter(other => other === names[index]).length > 1 ? item.dir.split('/').join('-') : (names[index] as string)
133
+ grouped[name] = item.app
134
+ })
135
+ draft = { apps: grouped, shared: [], outside: [...base.outside, ...apps.flatMap(item => item.outside)], allow: [] }
136
+ } else {
137
+ draft = { ...base.app, outside: base.outside, allow: [] }
138
+ }
139
+ // LayerMap 不读的目录(提交进仓库的 vendor/、agent 目录里的脚本)里没被忽略的代码:不在模块、共享层、装配层里的,起草进 outside。
140
+ // 在那些范围里的不起草(会和它们重叠),留给 R5 报出来,换个目录名
141
+ for (const path of files) {
142
+ if (!isCode(path)) continue
143
+ const owner = ownerOf(draft, path)
144
+ if (owner.kind !== 'none' || !owner.unread || owner.within) continue
145
+ const rule = `${owner.unread}/**`
146
+ if (!draft.outside.includes(rule)) draft.outside.push(rule)
147
+ }
148
+ return draft
149
+ }
@@ -0,0 +1,124 @@
1
+ // 读 LayerMap 输出里 modwall 要的事实:规则代码只用这里给出的事实。命令经底座跑(base/layermap.ts):
2
+ // 找命令、版本下限、出了问题怎么说都在那一处;这里读不到要的字段,就按版本太旧说。
3
+ // LayerMap 用不了时检查算没做完,不算通过(check.ts)。
4
+
5
+ import { layermap, LAYERMAP_COMMAND, LAYERMAP_MINIMUM, tooOld } from '../base/layermap.ts'
6
+
7
+ const TOO_OLD = tooOld().problem
8
+ const MISSING = `没找到 layermap 命令:modwall 用 LayerMap 读代码里的 import,要装 LayerMap 插件(${LAYERMAP_MINIMUM} 以上),开新会话后在 Bash 里再跑;${LAYERMAP_COMMAND}`
9
+
10
+ /** 一条对上了项目文件的 import。 */
11
+ export interface ImportFact {
12
+ from: string
13
+ line: number
14
+ to: string
15
+ specifier: string
16
+ }
17
+
18
+ /** 一条没对上项目文件的 import。possiblyOwn:可能是项目自己的(路径或别名没对上、地图里没有、只做了语法解析),要列为"没检查到"。 */
19
+ export interface UnresolvedFact {
20
+ from: string
21
+ line: number
22
+ specifier: string
23
+ reason: string
24
+ possiblyOwn: boolean
25
+ }
26
+
27
+ export interface ProjectImports {
28
+ imports: ImportFact[]
29
+ unresolved: UnresolvedFact[]
30
+ }
31
+
32
+ /** 这次改动(和分叉点比)增删的关系。 */
33
+ export interface ChangeFacts {
34
+ /** 新增和删除的 import(含转导出、require)。 */
35
+ imports: Array<{ from: string; to: string; line: number; change: 'ADDED' | 'REMOVED' }>
36
+ /** 新增的调用:调用指向声明所在的文件。exported:那个声明是不是文件顶层的导出。 */
37
+ calls: Array<{ from: string; line: number; to: string; declaration: string; exported: boolean }>
38
+ /** 被改动的已有声明。exported:是不是文件顶层的导出。 */
39
+ declarations: Array<{ path: string; declaration: string; line: number; exported: boolean }>
40
+ /** 改动的声明太多,有的没列出来(R4 的提示可能不全)。 */
41
+ edgesTruncated: boolean
42
+ /** LayerMap 标明没看全的地方:检查的结果被截断、检查本身没做完的、它不跟的改动文件。 */
43
+ truncated: boolean
44
+ incomplete: string[]
45
+ unmapped: Array<{ path: string; kind: string }>
46
+ }
47
+
48
+ export type Result<T> = { ok: true; value: T } | { ok: false; problem: string }
49
+
50
+ /** 外部包和语言自带的库:忽略。其余原因(含以后新加的)都当成可能是项目自己的。 */
51
+ const EXTERNAL = new Set(['OUTSIDE_SOURCE_CONTEXT', 'DECLARATION_NOT_AVAILABLE', 'COMPILER_LIBRARY'])
52
+
53
+ function run(root: string, args: string[]): Result<unknown> {
54
+ const answer = layermap(root, args)
55
+ if (answer.ok) return answer
56
+ if (answer.kind === 'missing') return { ok: false, problem: MISSING }
57
+ return { ok: false, problem: answer.kind === 'failed' ? `layermap ${args.join(' ')}:${answer.problem}` : answer.problem }
58
+ }
59
+
60
+ const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)
61
+ const str = (value: unknown): value is string => typeof value === 'string'
62
+ const num = (value: unknown): value is number => typeof value === 'number'
63
+ const strings = (value: unknown): value is string[] => Array.isArray(value) && value.every(str)
64
+
65
+ /** 数组里每一项都合格才算;有一项缺字段就当版本不对。 */
66
+ function list<T>(value: unknown, item: (row: Record<string, unknown>) => T | undefined): T[] | undefined {
67
+ if (!Array.isArray(value)) return undefined
68
+ const rows: T[] = []
69
+ for (const row of value) {
70
+ const parsed = isRecord(row) ? item(row) : undefined
71
+ if (parsed === undefined) return undefined
72
+ rows.push(parsed)
73
+ }
74
+ return rows
75
+ }
76
+
77
+ /** 项目现有的全部 import(含未提交的改动;来源是测试文件的不在其中)。 */
78
+ export function readImports(root: string): Result<ProjectImports> {
79
+ const out = run(root, ['imports', '--json'])
80
+ if (!out.ok) return out
81
+ const value = out.value
82
+ if (!isRecord(value)) return { ok: false, problem: TOO_OLD }
83
+ const imports = list(value.imports, row =>
84
+ str(row.from) && num(row.line) && str(row.to) && str(row.specifier) ? { from: row.from, line: row.line, to: row.to, specifier: row.specifier } : undefined,
85
+ )
86
+ const unresolved = list(value.unresolved, row =>
87
+ str(row.from) && num(row.line) && str(row.specifier) && str(row.reason)
88
+ ? { from: row.from, line: row.line, specifier: row.specifier, reason: row.reason, possiblyOwn: !EXTERNAL.has(row.reason) }
89
+ : undefined,
90
+ )
91
+ if (!imports || !unresolved) return { ok: false, problem: TOO_OLD }
92
+ return { ok: true, value: { imports, unresolved } }
93
+ }
94
+
95
+ /** 这次改动(和 base 比,含未提交的)增删的关系。 */
96
+ export function readChanges(root: string, base: string): Result<ChangeFacts> {
97
+ const out = run(root, ['check', '--json', '--base', base])
98
+ if (!out.ok) return out
99
+ const value = out.value
100
+ if (!isRecord(value) || !isRecord(value.edges)) return { ok: false, problem: TOO_OLD }
101
+ const edges = value.edges
102
+ const imports = list(edges.imports, row =>
103
+ str(row.from) && str(row.to) && num(row.line) && (row.change === 'ADDED' || row.change === 'REMOVED')
104
+ ? { from: row.from, to: row.to, line: row.line, change: row.change as 'ADDED' | 'REMOVED' }
105
+ : undefined,
106
+ )
107
+ const calls = list(edges.calls, row =>
108
+ str(row.from) && num(row.line) && str(row.to) && str(row.declaration) && typeof row.exported === 'boolean'
109
+ ? { from: row.from, line: row.line, to: row.to, declaration: row.declaration, exported: row.exported }
110
+ : undefined,
111
+ )
112
+ const declarations = list(edges.declarations, row =>
113
+ str(row.path) && str(row.declaration) && num(row.line) && typeof row.exported === 'boolean'
114
+ ? { path: row.path, declaration: row.declaration, line: row.line, exported: row.exported }
115
+ : undefined,
116
+ )
117
+ const unmapped = list(value.unmapped ?? [], row => (str(row.path) && str(row.kind) ? { path: row.path, kind: row.kind } : undefined))
118
+ const incomplete = value.incomplete ?? []
119
+ if (!imports || !calls || !declarations || typeof edges.truncated !== 'boolean' || !unmapped || !strings(incomplete)) return { ok: false, problem: TOO_OLD }
120
+ return {
121
+ ok: true,
122
+ value: { imports, calls, declarations, edgesTruncated: edges.truncated, truncated: value.truncated === true, incomplete, unmapped },
123
+ }
124
+ }
@@ -0,0 +1,231 @@
1
+ // 项目的划分:每个文件归谁(哪个应用的模块、共享层、装配层,外面一层的共享层、outside、测试),有哪些模块、各自的入口;
2
+ // 各项路径重叠、数据库的 schema 名撞了、迁移时间戳重复算配置错误。只看路径,不调用 LayerMap:改文件之前的钩子也用它。
3
+ // 单应用 = 一个没有名字的应用:归属里不带 app,模块名不加前缀。按应用分组时模块写成 应用名/模块名。
4
+ // LayerMap 不读的目录(vendor、node_modules、.claude 等)里的代码,它引用了谁查不到:只有写进 outside 才算有归属。
5
+
6
+ import { type App, type AppConfig, type Config, field, GLOB_CHARS, moduleId, type Scheme, schemeOf } from './config.ts'
7
+ import { type Database, databasesOf } from './database.ts'
8
+ import { isCode, isTest, unreadDirectory } from './files.ts'
9
+ import { globToRegExp } from '../base/glob.ts'
10
+
11
+ /** app:所在的应用(按应用分组时才有)。 */
12
+ export type Owner =
13
+ | { kind: 'module'; name: string; mapped: boolean; app?: string }
14
+ | { kind: 'shared'; app?: string }
15
+ /** root:直接放在这个模块根目录下、在 app 里点名的文件。 */
16
+ | { kind: 'app'; root?: string; app?: string }
17
+ /** 外面一层的共享层:几个应用共用的(只有按应用分组时才有)。 */
18
+ | { kind: 'common' }
19
+ | { kind: 'outside' }
20
+ | { kind: 'test' }
21
+ /**
22
+ * 没有归属。root:直接放在这个模块根目录下的文件(app:那个根目录所在的应用)。
23
+ * unread:在这个 LayerMap 不读的目录里,又没写进 outside;within:按路径它本来归谁(模块、共享层、装配层、映射),别处的没有。
24
+ */
25
+ | { kind: 'none'; root?: string; app?: string; unread?: string; within?: string }
26
+
27
+ const matcher = (patterns: readonly string[]): ((path: string) => boolean) => {
28
+ const regs = patterns.map(pattern => globToRegExp(pattern))
29
+ return path => regs.some(reg => reg.test(path))
30
+ }
31
+
32
+ /** 归属里的应用名:单应用不写。 */
33
+ const inApp = (app: App): { app?: string } => (app.name === undefined ? {} : { app: app.name })
34
+
35
+ /** 归属的说法,比如 booking 模块、admin/booking 模块、admin 应用的共享层。 */
36
+ export function label(owner: Owner): string {
37
+ switch (owner.kind) {
38
+ case 'module':
39
+ return `${moduleId(owner.app, owner.name)} 模块${owner.mapped ? '(映射)' : ''}`
40
+ case 'shared':
41
+ return owner.app === undefined ? '共享层' : `${owner.app} 应用的共享层`
42
+ case 'app':
43
+ return owner.app === undefined ? '装配层' : `${owner.app} 应用的装配层`
44
+ case 'common':
45
+ return '外面一层的共享层'
46
+ case 'outside':
47
+ return 'outside'
48
+ case 'test':
49
+ return '测试文件'
50
+ case 'none':
51
+ return '没有归属的文件'
52
+ }
53
+ }
54
+
55
+ /**
56
+ * 路径在哪个模块根目录下:name 是它所在的模块(根目录下第一层的目录名);
57
+ * 没有 name 就是直接放在根目录下的文件,不在任何模块目录里。
58
+ */
59
+ export function placeInRoots(config: Pick<AppConfig, 'roots'>, path: string): { root: string; name?: string } | undefined {
60
+ const root = config.roots.find(dir => path.startsWith(`${dir}/`))
61
+ if (root === undefined) return undefined
62
+ const rest = path.slice(root.length + 1)
63
+ const slash = rest.indexOf('/')
64
+ return slash === -1 ? { root } : { root, name: rest.slice(0, slash) }
65
+ }
66
+
67
+ /** 路径在哪个应用的哪个模块根目录下。 */
68
+ function placeIn(scheme: Scheme, path: string): { app: App; root: string; name?: string } | undefined {
69
+ for (const app of scheme.apps) {
70
+ const place = placeInRoots(app, path)
71
+ if (place) return { app, ...place }
72
+ }
73
+ return undefined
74
+ }
75
+
76
+ /** app 里点名写了这个文件:写到具体的文件、不用通配。直接放在模块根目录下的文件只有这样才能归装配层。 */
77
+ function namedInApp(app: App, path: string): boolean {
78
+ return app.app.some(rule => rule === path && !GLOB_CHARS.test(rule))
79
+ }
80
+
81
+ /**
82
+ * 这个路径归谁。测试文件不归 modwall 管;LayerMap 不读的目录里的,只有 outside 认领了才有归属。
83
+ * 路径重叠时的先后只在配置有错时起作用。
84
+ */
85
+ export function ownerOf(config: Config, path: string): Owner {
86
+ return ownerIn(schemeOf(config), path)
87
+ }
88
+
89
+ export function ownerIn(scheme: Scheme, path: string): Owner {
90
+ if (isTest(path)) return { kind: 'test' }
91
+ const owner = ownerByPath(scheme, path)
92
+ const unread = unreadDirectory(path)
93
+ if (unread === undefined || owner.kind === 'outside') return owner
94
+ const within = owner.kind === 'module' || owner.kind === 'shared' || owner.kind === 'app' || owner.kind === 'common' ? label(owner) : undefined
95
+ return { kind: 'none', unread, ...(within ? { within } : {}) }
96
+ }
97
+
98
+ /** 只按配置里的路径看归谁,不管 LayerMap 读不读。 */
99
+ function ownerByPath(scheme: Scheme, path: string): Owner {
100
+ if (matcher(scheme.outside)(path)) return { kind: 'outside' }
101
+ for (const app of scheme.apps) {
102
+ for (const [pattern, name] of Object.entries(app.map)) {
103
+ if (globToRegExp(pattern).test(path)) return { kind: 'module', name, mapped: true, ...inApp(app) }
104
+ }
105
+ }
106
+ const place = placeIn(scheme, path)
107
+ if (place?.name !== undefined) return { kind: 'module', name: place.name, mapped: false, ...inApp(place.app) }
108
+ if (place) return namedInApp(place.app, path) ? { kind: 'app', root: place.root, ...inApp(place.app) } : { kind: 'none', root: place.root, ...inApp(place.app) }
109
+ for (const app of scheme.apps) if (matcher(app.shared)(path)) return { kind: 'shared', ...inApp(app) }
110
+ for (const app of scheme.apps) if (matcher(app.app)(path)) return { kind: 'app', ...inApp(app) }
111
+ if (matcher(scheme.shared)(path)) return { kind: 'common' }
112
+ return { kind: 'none' }
113
+ }
114
+
115
+ export interface Module {
116
+ /** 所在的应用(按应用分组时才有)。 */
117
+ app?: string
118
+ name: string
119
+ /** 模块的名字:单应用就是 name,按应用分组是 应用名/模块名。 */
120
+ id: string
121
+ /** 模块目录。 */
122
+ dir: string
123
+ /** 现有的入口文件(模块目录下第一层、名字在这个应用的 entry 里的代码文件)。 */
124
+ entries: string[]
125
+ }
126
+
127
+ export class Layout {
128
+ readonly config: Config
129
+ readonly scheme: Scheme
130
+ readonly modules: Module[] = []
131
+ /** 写了 database 的应用各一个库:schema、迁移文件各归谁。 */
132
+ readonly databases: Database[]
133
+ readonly problems: string[] = []
134
+ /** problems 里有路径重叠。 */
135
+ overlapping = false
136
+ private readonly byId = new Map<string, Module>()
137
+
138
+ /**
139
+ * files:工作区里现有的文件(相对仓库根目录)。模块从文件推出来:模块根目录下有文件按路径归到某个模块,它就是一个模块,
140
+ * 和"文件归谁"同一个算法。只有 MODULE.md、还没有代码的模块目录也算;git 不跟踪空目录,空目录不算。根目录不存在不算错。
141
+ * 模块名只在应用内唯一:几个应用都有同名的模块是正常的。
142
+ */
143
+ constructor(config: Config, files: readonly string[]) {
144
+ this.config = config
145
+ this.scheme = schemeOf(config)
146
+ const present = new Set(files)
147
+ const dirs = new Map<string, { app: App; name: string }>()
148
+ for (const path of files) {
149
+ const owner = ownerIn(this.scheme, path)
150
+ const place = placeIn(this.scheme, path)
151
+ if (owner.kind === 'module' && !owner.mapped && place?.name !== undefined) dirs.set(`${place.root}/${place.name}`, { app: place.app, name: place.name })
152
+ }
153
+ for (const [dir, { app, name }] of [...dirs].sort(([a], [b]) => a.localeCompare(b))) {
154
+ const entries = app.entry.map(file => `${dir}/${file}`).filter(path => present.has(path) && isCode(path))
155
+ const id = moduleId(app.name, name)
156
+ const module: Module = { ...inApp(app), name, id, dir, entries }
157
+ const other = this.byId.get(id)
158
+ if (other) this.problems.push(`模块名重复:${other.dir} 和 ${dir} 都叫 ${id}(模块按目录名认,要改个名字)`)
159
+ else this.byId.set(id, module)
160
+ this.modules.push(module)
161
+ }
162
+ for (const app of this.scheme.apps) {
163
+ for (const [pattern, name] of Object.entries(app.map)) {
164
+ const id = moduleId(app.name, name)
165
+ if (!this.byId.has(id)) this.problems.push(`${field(app, 'map')} 里 "${pattern}" 指向的模块 ${id} 不存在(模块是模块根目录下的子目录)`)
166
+ }
167
+ }
168
+ this.checkOverlaps(files)
169
+ this.databases = databasesOf(this.scheme.apps, this.modules, files)
170
+ for (const database of this.databases) this.problems.push(...database.problems)
171
+ }
172
+
173
+ /**
174
+ * 各项的路径不能重叠:看现有的代码文件(测试文件除外)各被哪几项认领。重叠要报,是因为文件归谁有歧义:
175
+ * 同一项(同一个应用的 shared、app,外面一层的 shared、outside)里几条规则认领同一个文件不算;
176
+ * map 里指向同一个模块的不算,指向不同模块的算;每个模块根目录各算一项(互相嵌套时文件归哪个模块有歧义)。
177
+ * 不同应用的各项、应用和外面一层的 shared 都是不同的项。
178
+ * 唯一的例外:直接放在模块根目录下、在那个应用的 app 里点名的文件,不算 roots 认领了它。
179
+ */
180
+ private checkOverlaps(files: readonly string[]): void {
181
+ /** name:报错里的写法;item:属于哪一项,同一项里的认领不算重叠。 */
182
+ type Claim = { name: string; item: string; claims: (path: string) => boolean; root?: true }
183
+ const claims: Claim[] = [
184
+ ...this.scheme.apps.flatMap(app =>
185
+ app.roots.map((root): Claim => ({ name: `${field(app, 'roots')} 的 "${root}"`, item: `roots ${root}`, claims: path => path.startsWith(`${root}/`), root: true })),
186
+ ),
187
+ ...this.scheme.apps.flatMap(app => app.shared.map((rule): Claim => ({ name: `${field(app, 'shared')} 的 "${rule}"`, item: field(app, 'shared'), claims: matcher([rule]) }))),
188
+ ...this.scheme.apps.flatMap(app => app.app.map((rule): Claim => ({ name: `${field(app, 'app')} 的 "${rule}"`, item: field(app, 'app'), claims: matcher([rule]) }))),
189
+ ...this.scheme.apps.flatMap(app =>
190
+ Object.entries(app.map).map(([rule, module]): Claim => ({ name: `${field(app, 'map')} 的 "${rule}"`, item: `${field(app, 'map')} ${module}`, claims: matcher([rule]) })),
191
+ ),
192
+ // 外面一层的 shared:项名 common,和单应用写法里应用自己的 shared 分开
193
+ ...this.scheme.shared.map((rule): Claim => ({ name: `shared 的 "${rule}"`, item: 'common', claims: matcher([rule]) })),
194
+ ...this.scheme.outside.map((rule): Claim => ({ name: `outside 的 "${rule}"`, item: 'outside', claims: matcher([rule]) })),
195
+ ]
196
+ const overlaps = new Map<string, string[]>()
197
+ for (const path of files) {
198
+ if (!isCode(path) || isTest(path)) continue
199
+ const place = placeIn(this.scheme, path)
200
+ const named = place !== undefined && place.name === undefined && namedInApp(place.app, path)
201
+ const by = claims.filter(claim => claim.claims(path) && !(named && claim.root))
202
+ if (new Set(by.map(claim => claim.item)).size < 2) continue
203
+ const key = by.map(claim => claim.name).join(' 和 ')
204
+ overlaps.set(key, [...(overlaps.get(key) ?? []), path])
205
+ }
206
+ this.overlapping = overlaps.size > 0
207
+ for (const [by, paths] of overlaps) {
208
+ const shown = paths.slice(0, 3).join('、')
209
+ this.problems.push(`路径重叠:${by} 都包含 ${shown}${paths.length > 3 ? ` 等 ${paths.length} 个文件` : ''}`)
210
+ }
211
+ }
212
+
213
+ owner(path: string): Owner {
214
+ return ownerIn(this.scheme, path)
215
+ }
216
+
217
+ /** id:模块的名字(按应用分组时是 应用名/模块名)。 */
218
+ module(id: string): Module | undefined {
219
+ return this.byId.get(id)
220
+ }
221
+
222
+ /** 这个文件是这个模块(id)的入口。 */
223
+ isEntry(path: string, id: string): boolean {
224
+ return this.byId.get(id)?.entries.includes(path) ?? false
225
+ }
226
+
227
+ /** 应用(单应用时是那个没有名字的应用)。 */
228
+ app(name: string | undefined): App | undefined {
229
+ return this.scheme.apps.find(app => app.name === name)
230
+ }
231
+ }