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,281 @@
1
+ // "跑测试"的命令:focused、files、report、verify、run。命令行入口(src/cli.ts)分发到这里。
2
+
3
+ import { existsSync, readFileSync, statSync } from 'node:fs'
4
+ import { relative, resolve } from 'node:path'
5
+ import { context } from '../base/commands.ts'
6
+ import { CONTRACT_FILE } from '../base/contract.ts'
7
+ import { EXIT } from '../base/exit.ts'
8
+ import { duration, short } from '../base/format.ts'
9
+ import { gateProblem } from '../base/gate.ts'
10
+ import { currentBranch, defaultBranch, forkPoint, landings, workTreeId } from '../base/git.ts'
11
+ import { busyText, failureText, ignoredBy } from '../base/repo.ts'
12
+ import { commandExists, COMMAND_KEYS, loadConfig } from './config.ts'
13
+ import { askLayermap, BRANCH_CAP, fullReasons, INDIRECT_RANK, LAYERMAP_HINT, NEARBY_RANK, outsideNote } from './focused.ts'
14
+ import { paceRuns, runRecorded } from './record.ts'
15
+ import { renderReport } from './report.ts'
16
+ import { PROVE_RUNS, provenFixed, type TestResult } from './results.ts'
17
+ import { nodeTest } from './run/node-test.ts'
18
+ import { playwright } from './run/playwright.ts'
19
+ import { type Framework, runFramework } from './run/runner.ts'
20
+ import { vitest } from './run/vitest.ts'
21
+ import { flakyTests, LOCATED, testKey } from './testlist.ts'
22
+ import { findTests, testMatcher } from './tests.ts'
23
+ import { verifyFiles } from './verify.ts'
24
+
25
+ export async function focused(args: string[], usage: string): Promise<number> {
26
+ const at = args.indexOf('--base')
27
+ if (at === -1 ? args.length > 0 : args.length !== 2 || at !== 0) {
28
+ console.error(usage)
29
+ return EXIT.usage
30
+ }
31
+ const ctx = context()
32
+ if (!ctx) return EXIT.usage
33
+ const { config, problems } = loadConfig(ctx.root)
34
+ // 相关测试只从整组的测试里选,tests 规则写坏了就没法选
35
+ if (!config?.fast || !config.files || config.tests.length === 0) {
36
+ console.error(`没法跑 focused:${problems.join(';')}`)
37
+ return EXIT.usage
38
+ }
39
+
40
+ const tree = workTreeId(ctx.root)
41
+ const lines: string[] = []
42
+ const fast = await runRecorded(ctx, 'fast', config.fast, [], tree)
43
+ if ('busy' in fast) {
44
+ console.log(busyText(fast.busy, tree))
45
+ return EXIT.busy
46
+ }
47
+ if (fast.execution.interrupted) return EXIT.interrupted
48
+ if (fast.record.result === 'fail') {
49
+ console.log([failureText('fast 失败', fast.record.log, fast.execution), ...fast.notes].join('\n'))
50
+ return EXIT.fail
51
+ }
52
+ lines.push(`fast 通过 · 用时 ${duration(fast.execution.durationMs)}`, ...fast.notes)
53
+
54
+ // 对比和默认分支的分叉点:分支上已经提交的改动也算这次的改动。算不出分叉点时只比没提交的改动。
55
+ const branch = defaultBranch(ctx.root)
56
+ // 不在默认分支上(包括分离的 HEAD):要落地还得合并,合并前的整组兜底,选测靠不住也不用现在跑整组
57
+ const onBranch = branch !== undefined && currentBranch(ctx.root) !== branch
58
+ const base = at !== -1 ? args[at + 1]! : (forkPoint(ctx.root).commit ?? 'HEAD')
59
+ const isIgnored = ignoredBy(config.ignore)
60
+ // 在分支上只跑这次改到的测试,加上最相关的几个;其余留给合并时的整组
61
+ const selection = askLayermap(ctx.root, base, isIgnored, new Set(findTests(ctx.root, config.tests)), testMatcher(config.tests), onBranch ? NEARBY_RANK : INDIRECT_RANK, onBranch ? BRANCH_CAP : Infinity)
62
+ const reasons = fullReasons(selection)
63
+
64
+ let code: number = EXIT.ok
65
+ if (selection.kind === 'selected' && selection.changed.length === 0) {
66
+ lines.push(`相对 ${short(base)} 没有改动,不用跑测试。`)
67
+ } else if (selection.kind === 'selected' && selection.nothingToTest) {
68
+ lines.push(selection.changed.every(isIgnored) ? '改动只涉及 ignore 里的路径,不用跑测试。' : '改动里没有整组要跑的东西(只有 ignore 里的路径、tests 规则外或删掉的测试),不用跑测试。')
69
+ } else if (selection.kind === 'selected' && selection.tests.length > 0) {
70
+ const shown = selection.tests.slice(0, 10).map(test => ` ${test}`)
71
+ if (selection.tests.length > 10) shown.push(` 等 ${selection.tests.length} 个`)
72
+ const indirect = selection.indirect ? (onBranch ? `;另有 ${selection.indirect} 个相关的留给合并时的整组` : `;另有 ${selection.indirect} 个只是间接导入改动,没选`) : ''
73
+ lines.push(`相关测试 ${selection.tests.length} 个(对比 ${short(base)}${indirect}):`, ...shown)
74
+ const related = await runRecorded(ctx, 'files', config.files, selection.tests, tree)
75
+ if ('busy' in related) {
76
+ console.log([...lines, busyText(related.busy, tree)].join('\n'))
77
+ return EXIT.busy
78
+ }
79
+ if (related.execution.interrupted) return EXIT.interrupted
80
+ if (related.record.result === 'fail') {
81
+ console.log([...lines, failureText('相关测试失败', related.record.log, related.execution), ...related.notes].join('\n'))
82
+ return EXIT.fail
83
+ }
84
+ lines.push(`相关测试通过 · 用时 ${duration(related.execution.durationMs)}`, ...related.notes)
85
+ }
86
+ const outside = outsideNote(selection)
87
+ if (outside) lines.push(outside)
88
+ if (reasons.length > 0 && onBranch) {
89
+ lines.push(`这次选测不完全可靠:${reasons.join(';')}。在分支上不用现在跑整组,合回 ${branch} 时的整组会覆盖。`)
90
+ } else if (reasons.length > 0) {
91
+ lines.push(`建议跑整组(testpace full):${reasons.join(';')}。`)
92
+ code = EXIT.fullNeeded
93
+ }
94
+ if (reasons.length > 0 && selection.kind === 'unavailable' && selection.missing) lines.push(LAYERMAP_HINT)
95
+ console.log(lines.join('\n'))
96
+ return code
97
+ }
98
+
99
+ export async function files(argv: string[], usage: string): Promise<number> {
100
+ // --repeat N:连跑 N 次,没过就停。造出时好时坏的测试的失败,或证明修好了(见 results.ts 的 PROVE_RUNS)
101
+ let times = 1
102
+ let paths = argv
103
+ const at = argv.indexOf('--repeat')
104
+ if (at >= 0) {
105
+ times = Number(argv[at + 1])
106
+ paths = [...argv.slice(0, at), ...argv.slice(at + 2)]
107
+ if (!Number.isInteger(times) || times < 1) {
108
+ console.error('--repeat 要跟一个正整数')
109
+ return EXIT.usage
110
+ }
111
+ }
112
+ if (paths.length === 0) {
113
+ console.error(usage)
114
+ return EXIT.usage
115
+ }
116
+ const ctx = context()
117
+ if (!ctx) return EXIT.usage
118
+ const { config, problems } = loadConfig(ctx.root)
119
+ if (!config?.files) {
120
+ console.error(`没法跑测试文件:${problems.join(';')}`)
121
+ return EXIT.usage
122
+ }
123
+ const tree = workTreeId(ctx.root)
124
+ // 路径按当前目录算,交给项目命令时换成相对仓库根目录(项目命令在根目录跑);文件:行号 的行号原样带上
125
+ const targets = paths.map(path => {
126
+ const location = LOCATED.exec(path)?.[0] ?? ''
127
+ return relative(ctx.root, resolve(path.slice(0, path.length - location.length))) + location
128
+ })
129
+ // 文件:行号 只跑那一行的测试
130
+ const what = targets.some(target => LOCATED.test(target)) ? `${targets.length} 处测试` : `${targets.length} 个测试文件`
131
+ const notes: string[] = []
132
+ const passes: TestResult[][] = []
133
+ // 连跑时前面通过的测试和那次的日志:后面没过就是时好时坏。只认同一份代码上的,代码一变就清掉
134
+ const passedEarlier = new Map<string, string>()
135
+ // 每次从上一次跑完时的代码开始;中途代码变过,这次连跑就不算证明修好了
136
+ let current = tree
137
+ let changed = false
138
+ let took = 0
139
+ for (let index = 1; index <= times; index += 1) {
140
+ const repeat = times > 1 ? { repeat: { index, of: times }, passedEarlier } : {}
141
+ const run = await runRecorded(ctx, 'files', config.files, targets, current, repeat)
142
+ if ('busy' in run) {
143
+ console.log([busyText(run.busy, current), ...notes].join('\n'))
144
+ return EXIT.busy
145
+ }
146
+ if (run.execution.interrupted) {
147
+ if (notes.length > 0) console.log(notes.join('\n'))
148
+ return EXIT.interrupted
149
+ }
150
+ notes.push(...run.notes)
151
+ const stayed = run.record.treeAtEnd === current
152
+ if (!stayed) {
153
+ changed = true
154
+ current = run.record.treeAtEnd
155
+ passedEarlier.clear()
156
+ }
157
+ took += run.execution.durationMs
158
+ if (run.record.result === 'fail') {
159
+ const which = times > 1 ? `连跑第 ${index} 次(共 ${times} 次)` : ''
160
+ console.log([failureText(`${what}${which}失败`, run.record.log, run.execution), ...notes].join('\n'))
161
+ return EXIT.fail
162
+ }
163
+ passes.push(run.results)
164
+ if (stayed) {
165
+ for (const test of run.results) if (test.status === 'passed' && !passedEarlier.has(testKey(test))) passedEarlier.set(testKey(test), run.record.log)
166
+ }
167
+ }
168
+ // 证明修好了要代码一直没改
169
+ if (!changed) notes.push(...provenFixed(ctx, passes))
170
+ else if (times >= PROVE_RUNS && flakyTests(ctx.store).length > 0) {
171
+ notes.push('连跑的过程中代码或工作区变了(比如测试生成了没被 .gitignore 忽略的文件),这次不算证明时好时坏的测试修好了,名单没动。')
172
+ }
173
+ const how = times > 1 ? `连跑 ${times} 次都通过 · 共用时 ${duration(took)}` : `通过 · 用时 ${duration(took)}`
174
+ console.log([`${what}${how}`, ...notes].join('\n'))
175
+ return EXIT.ok
176
+ }
177
+
178
+ export function report(args: string[]): number {
179
+ let days = 28
180
+ const at = args.indexOf('--days')
181
+ if (at !== -1) {
182
+ days = Number(args[at + 1])
183
+ if (!Number.isInteger(days) || days <= 0) {
184
+ console.error('--days 要跟一个正整数')
185
+ return EXIT.usage
186
+ }
187
+ }
188
+ const ctx = context()
189
+ if (!ctx) return EXIT.usage
190
+ const now = Date.now()
191
+ const branch = defaultBranch(ctx.root)
192
+ console.log(
193
+ renderReport({
194
+ repo: ctx.root,
195
+ days,
196
+ now,
197
+ runs: paceRuns(ctx.store),
198
+ defaultBranch: branch,
199
+ landings: branch ? landings(ctx.root, branch, now - days * 24 * 3600 * 1000) : [],
200
+ }),
201
+ )
202
+ return EXIT.ok
203
+ }
204
+
205
+ /** 由程序核对这个项目的接入守不守约定(见 verify.ts)。整组太长,不在这里跑。 */
206
+ export async function verify(args: string[]): Promise<number> {
207
+ const ctx = context()
208
+ if (!ctx) return EXIT.usage
209
+ const { config, problems } = loadConfig(ctx.root)
210
+ if (!config) {
211
+ console.error(`${CONTRACT_FILE} 读不出来,先修好:${problems.join(';')}`)
212
+ return EXIT.usage
213
+ }
214
+ const tests: { path: string; text: string }[] = []
215
+ for (const arg of args) {
216
+ const absolute = resolve(arg)
217
+ const path = relative(ctx.root, absolute)
218
+ if (!existsSync(absolute) || !statSync(absolute).isFile() || path.startsWith('..')) {
219
+ console.error(`找不到测试文件 ${arg}(要是这个仓库里的文件)`)
220
+ return EXIT.usage
221
+ }
222
+ if (!tests.some(test => test.path === path)) tests.push({ path, text: readFileSync(absolute, 'utf8') })
223
+ }
224
+
225
+ const say = (line: string): void => console.log(line)
226
+ let failed = problems.length > 0 ? 1 : 0
227
+ say(problems.length > 0 ? `没通过 ${CONTRACT_FILE} 写得对:${problems.join(';')}` : `通过 ${CONTRACT_FILE} 写得对`)
228
+ for (const key of COMMAND_KEYS) {
229
+ // 没写的命令上一行已经算过
230
+ const command = config[key]
231
+ if (command === undefined) continue
232
+ const found = commandExists(ctx.root, command)
233
+ if (!found) failed += 1
234
+ say(found ? `通过 找得到 ${key} 的命令(${command})` : `没通过 找得到 ${key} 的命令:找不到 ${command}`)
235
+ }
236
+ const gate = gateProblem(ctx.root)
237
+ if (gate) failed += 1
238
+ say(gate ? `没通过 合并门在把关:${gate}` : '通过 合并门在把关')
239
+ // 整组跑的测试是 tests 规则找到的文件:给的测试文件不在里面,整组就跑不到它这一类
240
+ if (config.tests.length) {
241
+ const found = findTests(ctx.root, config.tests)
242
+ if (found.length === 0) failed += 1
243
+ say(found.length ? `通过 tests 规则找到测试文件(${found.length} 个)` : `没通过 tests 规则找到测试文件:按 ${config.tests.join('、')} 一个都没找到`)
244
+ const selected = testMatcher(config.tests)
245
+ for (const test of tests) {
246
+ const covered = selected(test.path)
247
+ if (!covered) failed += 1
248
+ say(covered ? `通过 整组会跑到 ${test.path}` : `没通过 整组会跑到 ${test.path}:它不在 tests 规则里,整组跑不到这一类测试`)
249
+ }
250
+ }
251
+
252
+ if (!config.files) {
253
+ say(`接入核对:${failed} 项没通过;${CONTRACT_FILE} 里没有 files,其余没法查。`)
254
+ return EXIT.fail
255
+ }
256
+ const tree = workTreeId(ctx.root)
257
+ const result = await verifyFiles(ctx, config.files, tree, tests, say)
258
+ if (result.kind === 'busy') {
259
+ console.log(busyText(result.marker, tree))
260
+ return EXIT.busy
261
+ }
262
+ if (result.kind === 'interrupted') return EXIT.interrupted
263
+ failed += result.failed
264
+ say(`没查 整组(${config.full ?? `${CONTRACT_FILE} 里没有 full`},再加上 tests 找到的全部测试):太长不在这里跑;能不能通过用 testpace full 看。`)
265
+
266
+ const notChecked = result.skipped + 1
267
+ say(failed > 0 ? `接入核对:${failed} 项没通过,${notChecked} 项没查。` : `接入核对:查了的都通过,${notChecked} 项没查。`)
268
+ return failed > 0 ? EXIT.fail : EXIT.ok
269
+ }
270
+
271
+ /** testpace run 认的框架。 */
272
+ export const FRAMEWORKS = new Map<string, Framework>([['node-test', nodeTest], ['vitest', vitest], ['playwright', playwright]])
273
+
274
+ /** testpace run <框架>:按框架跑测试文件、守 files 的约定。 */
275
+ export function run(rest: string[]): Promise<number> | number {
276
+ const [name, ...args] = rest
277
+ const framework = name === undefined ? undefined : FRAMEWORKS.get(name)
278
+ if (framework) return runFramework(framework, args)
279
+ console.error(`${name === undefined ? '没有给框架' : `不认识的框架 "${name}"`}\n用法:\n${[...FRAMEWORKS.values()].map(f => ` ${f.usage}`).join('\n')}`)
280
+ return EXIT.usage
281
+ }
@@ -0,0 +1,103 @@
1
+ // testpace.json 里归"跑测试"的部分:三条命令(fast、files、full)和找测试文件的规则(tests)。
2
+ // 文件本身、ignore 和未知字段由底座读(base/contract.ts);这里校验自己的字段,交给底座合到一起。
3
+
4
+ import { execFileSync } from 'node:child_process'
5
+ import { fileURLToPath } from 'node:url'
6
+ import { type Contract, CONTRACT_FILE, countedIgnore, loadContract, parseContract } from '../base/contract.ts'
7
+ import { PROJECT_ENV } from '../base/execute.ts'
8
+
9
+ export const COMMAND_KEYS = ['fast', 'files', 'full'] as const
10
+ export type CommandKey = (typeof COMMAND_KEYS)[number]
11
+ /** testpace.json 里归这个模块的字段。 */
12
+ export const FIELDS = [...COMMAND_KEYS, 'tests'] as const
13
+
14
+ /** 接入说明(插件里的 setup 技能)。没有 testpace.json 时指给 agent 看,Codex 这类没有技能的环境也能直接读。 */
15
+ export const SETUP_GUIDE = fileURLToPath(new URL('../../skills/setup/SKILL.md', import.meta.url))
16
+
17
+ export interface Config {
18
+ fast?: string
19
+ files?: string
20
+ /** 整组里测试以外的检查(类型检查、构建这些)。测试由 testpace 按 tests 找出来交给 files 跑。 */
21
+ full?: string
22
+ /** 找测试文件的路径规则;以 ! 开头的是排除。整组跑的就是它们找到的全部文件。 */
23
+ tests: string[]
24
+ /** 现在认的 ignore 规则(见 base/contract.ts 的 effectiveIgnore)。 */
25
+ ignore: string[]
26
+ /** 写了但要合并后才生效的 ignore 规则(分支上新加的)。 */
27
+ deferredIgnore?: string[]
28
+ }
29
+
30
+ export interface LoadedConfig {
31
+ config?: Config
32
+ /** 配置本身的问题:文件缺失、格式不对、字段缺失或拼错。 */
33
+ problems: string[]
34
+ }
35
+
36
+ /** 读这个模块的字段:写对的读出来,写得不对的说明问题。 */
37
+ function readFields(record: Record<string, unknown>): { fields: Omit<Config, 'ignore'>; problems: string[] } {
38
+ const problems: string[] = []
39
+ const fields: Omit<Config, 'ignore'> = { tests: [] }
40
+ for (const key of COMMAND_KEYS) {
41
+ const value = record[key]
42
+ if (value === undefined) problems.push(`缺少 "${key}" 命令`)
43
+ else if (typeof value !== 'string' || value.trim() === '') problems.push(`"${key}" 应该是非空字符串`)
44
+ else fields[key] = value
45
+ }
46
+ const tests = record.tests
47
+ if (tests === undefined) problems.push('缺少 "tests":找测试文件的路径规则,比如 ["**/*.test.ts"]')
48
+ else if (!Array.isArray(tests) || tests.length === 0 || tests.some(item => typeof item !== 'string' || item === '' || item === '!')) {
49
+ problems.push('"tests" 应该是路径规则的非空字符串数组,以 ! 开头的是排除')
50
+ } else if (tests.every(item => (item as string).startsWith('!'))) {
51
+ problems.push('"tests" 里至少要有一条不以 ! 开头的规则')
52
+ } else {
53
+ fields.tests = tests as string[]
54
+ }
55
+ return { fields, problems }
56
+ }
57
+
58
+ /** 交给底座的校验(Module.contractProblems)。 */
59
+ export function contractProblems(raw: Record<string, unknown>): string[] {
60
+ return readFields(raw).problems
61
+ }
62
+
63
+ /** 从底座读出的约定里取这个模块的配置。问题是整个文件的(底座的字段、各模块的字段合在一起)。 */
64
+ export function configOf(contract: Contract): LoadedConfig {
65
+ if (!contract.raw) return { problems: contract.problems }
66
+ return { config: { ...readFields(contract.raw).fields, ignore: contract.ignore }, problems: contract.problems }
67
+ }
68
+
69
+ /** 工作区里的约定。 */
70
+ export function loadConfig(root: string): LoadedConfig {
71
+ const contract = loadContract(root)
72
+ if (!contract) return { problems: [`仓库根目录没有 ${CONTRACT_FILE},接入说明见 ${SETUP_GUIDE}`] }
73
+ const loaded = configOf(contract)
74
+ if (!loaded.config) return loaded
75
+ // ignore 按默认分支上原来那份认:分支上新加的规则合并后才生效
76
+ const { rules, deferred } = countedIgnore(root, contract)
77
+ return { ...loaded, config: { ...loaded.config, ignore: rules, ...(deferred.length ? { deferredIgnore: deferred } : {}) } }
78
+ }
79
+
80
+ export function parseConfig(raw: unknown): LoadedConfig {
81
+ return configOf(parseContract(raw))
82
+ }
83
+
84
+ /** 命令的第一个词(跳过开头的 `FOO=bar` 环境变量赋值)。 */
85
+ export function commandWord(command: string): string | undefined {
86
+ for (const word of command.trim().split(/\s+/)) {
87
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(word)) continue
88
+ return word.replace(/^['"]|['"]$/g, '')
89
+ }
90
+ return undefined
91
+ }
92
+
93
+ /** 在仓库根目录用 sh 的 `command -v` 找命令,内建命令、PATH 和相对路径都认。PATH 和跑项目命令时一样,testpace 自己也找得到。 */
94
+ export function commandExists(root: string, command: string): boolean {
95
+ const word = commandWord(command)
96
+ if (!word) return false
97
+ try {
98
+ execFileSync('/bin/sh', ['-c', 'command -v -- "$1"', 'sh', word], { cwd: root, env: PROJECT_ENV, stdio: 'ignore' })
99
+ return true
100
+ } catch {
101
+ return false
102
+ }
103
+ }
@@ -0,0 +1,81 @@
1
+ // 落地前怎么测(testpace.json 的三条命令和 tests 规则)是评判用的配置,走"用户同意后生效"(见 base/judging.ts):
2
+ // 和分叉点那一版比,改了命令、缩小了找测试的范围,要用户在确认工具的弹窗里同意过,整组才跑。
3
+ // 加严的不用问:tests 规则多加一条找测试的规则、去掉一条排除。首次接入(分叉点上还没有 testpace.json)也不用问。
4
+ // 命令往哪个方向改程序判断不了(换个脚本名和换成 true 看起来一样),所以改了就问。
5
+
6
+ import { askUser, type ConfirmItem } from '../base/confirm.ts'
7
+ import { CONTRACT_FILE } from '../base/contract.ts'
8
+ import { forkPoint } from '../base/git.ts'
9
+ import { type Judging, judgingFile } from '../base/judging.ts'
10
+ import type { Repo } from '../base/repo.ts'
11
+ import { COMMAND_KEYS, type CommandKey } from './config.ts'
12
+
13
+ const COMMAND_USE: Record<CommandKey, string> = {
14
+ fast: '改完代码先跑的快检查',
15
+ files: '跑测试文件用的命令',
16
+ full: '落地前跑的全部检查',
17
+ }
18
+
19
+ function fieldsOf(text: string | undefined): Record<string, unknown> | undefined {
20
+ if (text === undefined) return undefined
21
+ try {
22
+ const raw = JSON.parse(text) as unknown
23
+ return typeof raw === 'object' && raw !== null && !Array.isArray(raw) ? (raw as Record<string, unknown>) : undefined
24
+ } catch {
25
+ return undefined
26
+ }
27
+ }
28
+
29
+ const rules = (value: unknown): string[] => (Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [])
30
+
31
+ /** 这次改动放松了落地前怎么测的地方,一个字段一项。分叉点上没有约定(首次接入)、或那一版读不出来时没有可比的,不算放松。 */
32
+ export function loosenedItems(contract: Judging): ConfirmItem[] {
33
+ const before = fieldsOf(contract.before)
34
+ const now = fieldsOf(contract.now)
35
+ if (!before || !now) return []
36
+ const items: ConfirmItem[] = []
37
+ for (const key of COMMAND_KEYS) {
38
+ const was = before[key]
39
+ const is = now[key]
40
+ if (typeof was !== 'string' || was === is) continue
41
+ items.push({
42
+ before: JSON.stringify([key, was]),
43
+ after: JSON.stringify([key, is]),
44
+ text: [`${CONTRACT_FILE} 的 ${key} 命令(${COMMAND_USE[key]})改了`, `原来:${was}`, `现在:${typeof is === 'string' ? is : '(没有了)'}`].join('\n'),
45
+ })
46
+ }
47
+ const was = rules(before.tests)
48
+ const is = rules(now.tests)
49
+ const excluded = (rule: string): boolean => rule.startsWith('!')
50
+ // 少了一条找测试的规则,或多了一条排除:整组跑的测试可能变少
51
+ const dropped = was.filter(rule => !excluded(rule) && !is.includes(rule))
52
+ const added = is.filter(rule => excluded(rule) && !was.includes(rule))
53
+ if (dropped.length || added.length) {
54
+ items.push({
55
+ before: JSON.stringify(['tests', was]),
56
+ after: JSON.stringify(['tests', is]),
57
+ text: [
58
+ `${CONTRACT_FILE} 里找测试文件的规则(tests)缩小了,落地前跑的测试可能变少`,
59
+ ...(dropped.length ? [`去掉了:${dropped.join('、')}`] : []),
60
+ ...(added.length ? [`新加了排除:${added.map(rule => rule.slice(1)).join('、')}`] : []),
61
+ `原来:${was.join('、')}`,
62
+ `现在:${is.join('、')}`,
63
+ ].join('\n'),
64
+ })
65
+ }
66
+ return items
67
+ }
68
+
69
+ /**
70
+ * 整组之前:这次改动放松了落地前怎么测的地方,用户都同意过没有。有没同意的,返回说给 agent 的话(怎么让用户确认)。
71
+ * 算不出分叉点的仓库(认不出默认分支)不问:那里合并门本来就没在把关。
72
+ */
73
+ export function unconfirmedChanges(repo: Repo): string | undefined {
74
+ const fork = forkPoint(repo.root)
75
+ if (!fork.commit) return undefined
76
+ const items = loosenedItems(judgingFile(repo.root, fork.commit, CONTRACT_FILE))
77
+ if (items.length === 0) return undefined
78
+ const asked = askUser(repo, 'pace', '这次改动改了落地前怎么测', items)
79
+ if (!asked.ask) return undefined
80
+ return [`${CONTRACT_FILE} 里落地前怎么测的改动要用户同意后才生效(和分叉点 ${fork.commit.slice(0, 10)} 上的比)。`, ...asked.ask.lines].join('\n')
81
+ }