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,90 @@
1
+ // 固定命令入口:~/.local/bin 下的 testpace、modwall、testcraft。Codex 不把插件的 bin/ 放进命令的 PATH,合并门的 git 钩子也靠 PATH 找 testpace。
2
+ // 入口文件只有一份(entry/command),每条命令放一份一样的;它不带版本,运行时按被叫的名字找这台机器上装着的最高版本的插件里同名的命令,插件升级不用重放。
3
+ // 这是全局安装:只在 testpace install 时放,不在会话开始时自动放(放过别的命令的机器上,新加的命令也一样)。
4
+ // 放过的入口是旧版本放的(入口文件本身变了,比如插件改了名、旧入口按旧名字找不到装着的那份):会话开始时换成这一版的。
5
+ // 放上去的入口第二行记着是哪一版放的,只升不降:几个 agent 里装的版本不同时(比如 Claude Code 里更新了、Codex 里还是旧的),
6
+ // 各自会话开始时不来回覆盖,更新的版本放的留着(和合并门的钩子命令一样,gate.ts)。
7
+
8
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
9
+ import { homedir } from 'node:os'
10
+ import { join } from 'node:path'
11
+ import { compareVersions, VERSION } from './version.ts'
12
+
13
+ /** 放固定入口的命令:插件 bin/ 里给 agent 直接叫的那几条。加命令只改这里。 */
14
+ export const ENTRY_COMMANDS = ['testpace', 'modwall', 'testcraft'] as const
15
+ export type EntryCommand = (typeof ENTRY_COMMANDS)[number]
16
+
17
+ const SOURCE = new URL('../../entry/command', import.meta.url)
18
+ /** 入口文件里认得出是 testpace install 放的那一行。 */
19
+ const MARK = '# testpace 固定入口'
20
+ /** 放上去时插在第一行(#!)后面、记着是哪一版放的那一行;没有这一行的是加这一行之前的版本放的。 */
21
+ const VERSION_LINE = /^# gatelight (\S+) 放的$/m
22
+
23
+ /** 这一版放上去的入口:源文件第一行后面插上记版本的那一行。 */
24
+ function entryText(): string {
25
+ const source = readFileSync(SOURCE, 'utf8')
26
+ const end = source.indexOf('\n') + 1
27
+ return `${source.slice(0, end)}# gatelight ${VERSION} 放的\n${source.slice(end)}`
28
+ }
29
+
30
+ export function entryDir(): string {
31
+ return join(homedir(), '.local', 'bin')
32
+ }
33
+
34
+ export function entryPath(command: EntryCommand): string {
35
+ return join(entryDir(), command)
36
+ }
37
+
38
+ export type EntryState = 'installed' | 'newer' | 'missing' | 'outdated' | 'foreign'
39
+
40
+ /**
41
+ * 一条命令的固定入口的状态:没放、放的是这一版、更新的版本放的(照常用,不动它)、旧的(包括同一版但内容不同的)、
42
+ * 还是同名的别的文件(不动它)。
43
+ */
44
+ export function entryState(command: EntryCommand): EntryState {
45
+ const path = entryPath(command)
46
+ if (!existsSync(path)) return 'missing'
47
+ const text = readFileSync(path, 'utf8')
48
+ if (text === entryText()) return 'installed'
49
+ if (!text.includes(MARK)) return 'foreign'
50
+ const placed = VERSION_LINE.exec(text)?.[1]
51
+ return placed && compareVersions(placed, VERSION) > 0 ? 'newer' : 'outdated'
52
+ }
53
+
54
+ /** 固定入口没放好的那几条命令(没放、旧的、同名的别的文件):靠入口找命令的地方找不到它们。更新的版本放的算放好了。 */
55
+ export function entriesNotPlaced(): EntryCommand[] {
56
+ return ENTRY_COMMANDS.filter(command => !['installed', 'newer'].includes(entryState(command)))
57
+ }
58
+
59
+ function place(command: EntryCommand): void {
60
+ mkdirSync(entryDir(), { recursive: true })
61
+ const path = entryPath(command)
62
+ writeFileSync(path, entryText())
63
+ chmodSync(path, 0o755)
64
+ }
65
+
66
+ /**
67
+ * 会话开始时:放过、但是旧版本放的入口,换成这一版的,不问(放的时候用户同意过;合并门的钩子也是这样更新的)。
68
+ * 没放过的不放,同名的别的文件不动。写不进去(目录只读、在沙箱里)时不挡会话:入口还是旧的,会话说明和 testpace status 照旧会说。
69
+ */
70
+ export function refreshEntries(): void {
71
+ for (const command of ENTRY_COMMANDS) {
72
+ if (entryState(command) !== 'outdated') continue
73
+ try {
74
+ place(command)
75
+ } catch {
76
+ // 见上:不挡会话
77
+ }
78
+ }
79
+ }
80
+
81
+ /** 放上或更新每条命令的固定入口;同名的别的文件不覆盖、更新的版本放的不换成旧的,返回是哪几条因为是别的文件没放上。 */
82
+ export function installEntries(): { refused: EntryCommand[] } {
83
+ const refused: EntryCommand[] = []
84
+ for (const command of ENTRY_COMMANDS) {
85
+ const state = entryState(command)
86
+ if (state === 'foreign') refused.push(command)
87
+ else if (state !== 'installed' && state !== 'newer') place(command)
88
+ }
89
+ return { refused }
90
+ }
@@ -0,0 +1,46 @@
1
+ // 精简输出:失败时只给失败相关的行和结尾,完整内容在日志文件里。
2
+
3
+ const ANSI = /\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g
4
+ const FAILURE = /\b(FAIL|FAILED|Failed|failed|ERROR|Error|error|panic|AssertionError|not ok)\b|[✗✘×❌]/
5
+
6
+ const MAX_LINE = 300
7
+
8
+ export interface ExcerptOptions {
9
+ /** 最多取多少行失败相关的行(从前往后,最先出错的地方最有用)。 */
10
+ matches: number
11
+ /** 结尾取多少行(测试工具的汇总一般在最后)。 */
12
+ tail: number
13
+ }
14
+
15
+ export const DEFAULT_EXCERPT: ExcerptOptions = { matches: 20, tail: 30 }
16
+
17
+ export function cleanLines(text: string): string[] {
18
+ return text
19
+ .replace(ANSI, '')
20
+ .split('\n')
21
+ .map(line => {
22
+ // 进度条用 \r 覆盖同一行,只留最后一次的内容
23
+ const last = line.slice(line.lastIndexOf('\r') + 1)
24
+ return last.length > MAX_LINE ? `${last.slice(0, MAX_LINE)}…` : last
25
+ })
26
+ }
27
+
28
+ /** 按原顺序取失败相关的行和结尾几行,中间跳过的部分用 "…" 表示。 */
29
+ export function failureExcerpt(text: string, options: ExcerptOptions = DEFAULT_EXCERPT): string[] {
30
+ const lines = cleanLines(text)
31
+ while (lines.length > 0 && lines.at(-1)!.trim() === '') lines.pop()
32
+ const keep = new Set<number>()
33
+ for (let i = 0; i < lines.length && keep.size < options.matches; i++) {
34
+ if (FAILURE.test(lines[i]!)) keep.add(i)
35
+ }
36
+ for (let i = Math.max(0, lines.length - options.tail); i < lines.length; i++) keep.add(i)
37
+
38
+ const out: string[] = []
39
+ let previous = -1
40
+ for (const i of [...keep].sort((a, b) => a - b)) {
41
+ if (i > previous + 1) out.push('…')
42
+ out.push(lines[i]!)
43
+ previous = i
44
+ }
45
+ return out
46
+ }
@@ -0,0 +1,70 @@
1
+ // 执行项目的命令:从仓库根目录用 sh 跑,输出全部写进日志文件,计时。
2
+ // testpace 自己被中断时,把整个子进程组一起停掉;不肯退出的,过一会儿强杀(见 process-group.ts)。
3
+
4
+ import { closeSync, openSync } from 'node:fs'
5
+ import { delimiter } from 'node:path'
6
+ import { fileURLToPath } from 'node:url'
7
+ import { COMMAND_KILL_AFTER_MS, spawnGroup } from './process-group.ts'
8
+
9
+ /**
10
+ * 整组起要借用工作区的检查(模块交的段里标了 borrows 的,比如 testcraft check 要建副本)时,在这个环境变量里给这一轮的运行 id
11
+ * (登记的 RunMarker.id),只给这样的段。借用工作区时见到它和这个工作区的登记一样就不另占:这些检查在测试之前跑,
12
+ * 那时工作区里还没有测试在跑,工作区已经是这一轮的。
13
+ * 别的项目命令(fast、files、full 和整组跑测试的那一段)跑的就是测试,在里面借用工作区要被挡,不给。
14
+ */
15
+ export const RUN_ENV = 'TESTPACE_RUN'
16
+
17
+ /**
18
+ * 跑项目命令的环境:testpace 自己的命令目录放在 PATH 最前面。项目命令和脚本里调的 testpace(比如 files 里的
19
+ * testpace run)就是正在跑的这一版,Claude Code、Codex、合并门的钩子里都一样,不靠 PATH 上碰巧有哪一版。
20
+ * 从外面继承来的 RUN_ENV 去掉(比如整组里的检查又调了 testpace files):它只认起它的那一轮,要给的段由 execute 的 env 按这一轮重新给。
21
+ */
22
+ const { [RUN_ENV]: _inheritedRun, ...inherited } = process.env
23
+ export const PROJECT_ENV: NodeJS.ProcessEnv = {
24
+ ...inherited,
25
+ PATH: [fileURLToPath(new URL('../../bin', import.meta.url)), process.env.PATH].filter(Boolean).join(delimiter),
26
+ }
27
+
28
+ /** 把一段文字(比如带空格的完整路径)写进命令字符串:加单引号,sh 照原样当成一个词。 */
29
+ export const quoted = (text: string): string => `'${text.replace(/'/g, `'\\''`)}'`
30
+
31
+ export interface Execution {
32
+ /** 正常退出时的退出码;被信号终止或没能启动时为 null。 */
33
+ exitCode: number | null
34
+ /** 子进程被信号终止时的信号名(不是 testpace 自己被中断)。 */
35
+ signal: NodeJS.Signals | null
36
+ /** testpace 自己被中断。 */
37
+ interrupted: boolean
38
+ durationMs: number
39
+ }
40
+
41
+ /**
42
+ * onStart 在子进程起来、中断处理挂好之后调用,拿到子进程组的 id:登记在跑的是哪个进程组。
43
+ * env 是另加给项目命令的环境变量(比如交每个测试结果的位置,见 results.ts)。
44
+ */
45
+ export async function execute(
46
+ command: string,
47
+ args: string[],
48
+ cwd: string,
49
+ logPath: string,
50
+ onStart?: (group: number) => void,
51
+ env: Record<string, string> = {},
52
+ ): Promise<Execution> {
53
+ const started = Date.now()
54
+ const log = openSync(logPath, 'a')
55
+ // 额外参数(测试文件路径)用 "$@" 传,不拼进命令字符串,避免路径里的特殊字符被 shell 解释。
56
+ const script = args.length > 0 ? `${command} "$@"` : command
57
+ try {
58
+ const { exitCode, signal, interrupted } = await spawnGroup('/bin/sh', ['-c', script, 'sh', ...args], {
59
+ cwd,
60
+ env: { ...PROJECT_ENV, ...env },
61
+ stdio: ['ignore', log, log],
62
+ stopSignal: 'SIGTERM',
63
+ killAfterMs: COMMAND_KILL_AFTER_MS,
64
+ onStart,
65
+ })
66
+ return { exitCode, signal, interrupted, durationMs: Date.now() - started }
67
+ } finally {
68
+ closeSync(log)
69
+ }
70
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * 命令的退出码:0 通过;1 失败或没得到通过记录;2 用法或配置问题;
3
+ * 3 这个工作区已有测试在跑或被借用着(hold:占不上),或别处在跑同一份代码的整组;4 在默认分支上,跑了的都通过,但选测靠不住,应当跑整组;130 被中断。
4
+ * gate 拒绝时是 GATE_REJECT,说这次没有检查时是 GATE_UNCHECKED(见 gate.ts)。
5
+ */
6
+ export const EXIT = { ok: 0, fail: 1, usage: 2, busy: 3, fullNeeded: 4, interrupted: 130 } as const
@@ -0,0 +1,27 @@
1
+ // 时间和时长的显示。
2
+
3
+ export function duration(ms: number): string {
4
+ const seconds = Math.round(ms / 1000)
5
+ if (seconds < 60) return `${seconds}秒`
6
+ const minutes = Math.floor(seconds / 60)
7
+ if (minutes < 60) return `${minutes}分${String(seconds % 60).padStart(2, '0')}秒`
8
+ return `${Math.floor(minutes / 60)}小时${String(minutes % 60).padStart(2, '0')}分`
9
+ }
10
+
11
+ function pad(n: number): string {
12
+ return String(n).padStart(2, '0')
13
+ }
14
+
15
+ export function when(ms: number): string {
16
+ const d = new Date(ms)
17
+ return `${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
18
+ }
19
+
20
+ export function day(ms: number): string {
21
+ const d = new Date(ms)
22
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
23
+ }
24
+
25
+ export function short(tree: string): string {
26
+ return tree.slice(0, 10)
27
+ }
@@ -0,0 +1,160 @@
1
+ // 整组(testpace full)的编排:底座跑、底座记录,跑什么由各模块交的各段决定(module.ts 的 fullPart)。
2
+ // 检查随插件一起装,没有在本机另外登记检查的入口:模块的顺序就是各段的顺序(src/modules.ts)。
3
+
4
+ import { appendFileSync, existsSync, statSync } from 'node:fs'
5
+ import { countedIgnore, loadContract } from './contract.ts'
6
+ import { type Execution, execute, RUN_ENV } from './execute.ts'
7
+ import { EXIT } from './exit.ts'
8
+ import { duration, short } from './format.ts'
9
+ import { changedPaths, currentBranch, headCommit, workTreeId } from './git.ts'
10
+ import { type FullPart, type FullStep, modules } from './module.ts'
11
+ import { busyText, coverageOf, describeCoverage, failureText, type Repo, runner, started } from './repo.ts'
12
+ import { isHold, newRunId, type RunMarker, type RunRecord, type RunStep } from './store.ts'
13
+
14
+ /**
15
+ * testpace full:依次跑各模块交的各段,便宜的在前,一段没过就停;都过了、跑的过程中内容没变,
16
+ * 才留下这份内容的整组通过记录。sessionId 是起这次整组的 agent 会话(停止门只拦起它的会话和等着用它结果的会话)。
17
+ */
18
+ export async function full(ctx: Repo, sessionId: string | undefined): Promise<number> {
19
+ // 约定有问题,或哪个模块现在跑不了(没接入、没有要跑的):说明原因,不跑
20
+ const contract = loadContract(ctx.root)
21
+ const parts: FullPart[] = []
22
+ const dispose = (): void => parts.forEach(part => part.dispose?.())
23
+ let problem = contract?.problems.length ? contract.problems.join(';') : undefined
24
+ for (const module of modules()) {
25
+ if (problem !== undefined) break
26
+ const part = module.fullPart?.(ctx)
27
+ if (!part) continue
28
+ if ('problem' in part) problem = part.problem
29
+ else parts.push(part)
30
+ }
31
+ if (problem === undefined && parts.length === 0) problem = '没有哪个模块有要跑的'
32
+ if (problem !== undefined) {
33
+ dispose()
34
+ console.error(`没法跑整组:${problem}`)
35
+ return EXIT.usage
36
+ }
37
+ try {
38
+ return await run(ctx, sessionId, countedIgnore(ctx.root, contract).rules, parts)
39
+ } finally {
40
+ dispose()
41
+ }
42
+ }
43
+
44
+ async function run(ctx: Repo, sessionId: string | undefined, ignore: string[], parts: FullPart[]): Promise<number> {
45
+ const tree = workTreeId(ctx.root)
46
+ const coverage = coverageOf(ctx, ignore, tree)
47
+ if (coverage.kind !== 'none') {
48
+ console.log(`这份代码${describeCoverage(coverage)},不重跑。`)
49
+ return EXIT.ok
50
+ }
51
+
52
+ const elsewhere = ctx.store.running().find((marker): marker is RunMarker => !isHold(marker) && marker.kind === 'full' && marker.tree === tree && marker.worktree !== ctx.root)
53
+ if (elsewhere) {
54
+ console.log(`工作区 ${elsewhere.worktree} 正在跑同一份代码的整组(${started(elsewhere)})。等它结束后用 testpace status 看结果。`)
55
+ return EXIT.busy
56
+ }
57
+
58
+ const startedAt = Date.now()
59
+ const id = newRunId(startedAt)
60
+ const log = ctx.store.logPath(id)
61
+ const session = sessionId ? { session: sessionId } : {}
62
+ const busy = ctx.store.claim({ id, kind: 'full', pid: process.pid, worktree: ctx.root, tree, startedAt, ...session, log })
63
+ if (busy && !isHold(busy) && busy.kind === 'full') {
64
+ if (sessionId) ctx.store.waitOn(busy, sessionId)
65
+ console.log(`这个工作区已有整组在跑(${started(busy)})。等它结束后用 testpace status 看结果。`)
66
+ return EXIT.busy
67
+ }
68
+ if (busy) {
69
+ console.log(busyText(busy, tree))
70
+ return EXIT.busy
71
+ }
72
+
73
+ // 依次跑各模块交的各段,便宜的在前,一段没过就停。都过了才算整组通过。
74
+ // 要借用工作区的段(建副本)拿到这一轮的运行 id(见 RUN_ENV):它们在测试之前跑,在里面借用工作区不另占
75
+ const steps: Array<FullStep & { env?: Record<string, string> }> = parts.flatMap(part =>
76
+ part.steps.map(step => (step.borrows ? { ...step, env: { [RUN_ENV]: id } } : step)),
77
+ )
78
+ // 各模块给命令的环境变量(比如交每个测试结果的位置),每一段都带着
79
+ const partsEnv: Record<string, string> = Object.assign({}, ...parts.map(part => part.env ?? {}))
80
+ // 每段各用了多久:report 据此说整组的时间花在哪一段
81
+ const timings: RunStep[] = []
82
+ const onStart = (group: number) => ctx.store.update(ctx.root, id, { group })
83
+ const sizeOf = (path: string) => (existsSync(path) ? statSync(path).size : 0)
84
+ let failed: (typeof steps)[number] | undefined
85
+ // 失败节选从没通过的那一段的输出开始
86
+ let excerptFrom = 0
87
+ let execution: Execution | undefined
88
+ let waiting: string[]
89
+ try {
90
+ for (const step of steps) {
91
+ excerptFrom = sizeOf(log)
92
+ appendFileSync(log, `===== testpace ${step.header}\n`)
93
+ const part = await execute(step.command, step.args, ctx.root, log, onStart, { ...partsEnv, ...step.env })
94
+ execution = execution ? { ...part, durationMs: execution.durationMs + part.durationMs } : part
95
+ if (!part.interrupted) timings.push({ kind: step.kind, name: step.name, durationMs: part.durationMs })
96
+ if (part.interrupted || part.exitCode !== 0) {
97
+ failed = step
98
+ break
99
+ }
100
+ }
101
+ } finally {
102
+ waiting = ctx.store.release(ctx.root, id)
103
+ }
104
+ if (!execution) throw new Error('整组没有运行')
105
+
106
+ if (execution.interrupted) {
107
+ console.log(`整组被中断,没有记录结果。日志:${log}`)
108
+ return EXIT.interrupted
109
+ }
110
+
111
+ // 各模块往记录里加自己的字段,记录写下之后再说它们要说的话
112
+ const finished = parts.map(part => part.finish?.() ?? {})
113
+ const treeAtEnd = workTreeId(ctx.root)
114
+ const result = execution.exitCode === 0 ? 'pass' : 'fail'
115
+ const before = ctx.store.readRuns()
116
+ const record: RunRecord = {
117
+ id,
118
+ kind: 'full',
119
+ worktree: ctx.root,
120
+ branch: currentBranch(ctx.root),
121
+ head: headCommit(ctx.root),
122
+ tree,
123
+ treeAtEnd,
124
+ startedAt,
125
+ durationMs: execution.durationMs,
126
+ exitCode: execution.exitCode,
127
+ result,
128
+ ...session,
129
+ ...(waiting.length ? { waiting } : {}),
130
+ steps: timings,
131
+ ...Object.assign({}, ...finished.map(done => done.fields ?? {})),
132
+ ...runner(),
133
+ log,
134
+ }
135
+ ctx.store.appendRun(record)
136
+ const notes = finished.flatMap(done => done.notes?.(record, before) ?? [])
137
+ const say = (text: string): void => console.log([text, ...notes].join('\n'))
138
+
139
+ const took = duration(execution.durationMs)
140
+ if (result === 'pass' && tree === treeAtEnd) {
141
+ say(`${['整组通过', ...parts.flatMap(part => part.summary ?? []), `用时 ${took}`, `代码 ${short(tree)}`].join(' · ')}\n日志:${log}`)
142
+ return EXIT.ok
143
+ }
144
+ if (result === 'pass') {
145
+ const changed = changedPaths(ctx.root, tree, treeAtEnd)
146
+ const more = changed.length > 5 ? ` 等 ${changed.length} 个` : ''
147
+ say(
148
+ [
149
+ `整组通过,但跑的过程中代码改过,这次不算通过记录。变了的文件:${changed.slice(0, 5).join('、')}${more}`,
150
+ '是整组自己生成的文件,就加进 .gitignore 或让它写到仓库外;是别处改的,代码不再改动时重跑 testpace full。',
151
+ `用时 ${took} · 日志:${log}`,
152
+ ].join('\n'),
153
+ )
154
+ return EXIT.fail
155
+ }
156
+ const what = failed?.title ?? '整组'
157
+ const gap = /[A-Za-z0-9]$/.test(what) ? ' ' : ''
158
+ say(failureText(`整组失败:${what}${gap}没通过${failed === steps.at(-1) ? '' : ',后面的没有跑'}`, log, execution, excerptFrom))
159
+ return EXIT.fail
160
+ }
@@ -0,0 +1,251 @@
1
+ // 合并门:agent 的 git 命令要移动默认分支时,git 的 reference-transaction 钩子把分支要指向的提交交给
2
+ // testpace gate;那份代码没有 testpace full 的通过记录,就取消这次更新,默认分支不动。
3
+ // 判断发生在 git 更新分支的那一刻,按实际要落地的提交算,不管命令是怎么写的:
4
+ // commit、merge、cherry-pick、rebase、reset、脚本里调的 git 都一样。
5
+ // 只管 agent 的命令(钩子脚本看已接入的 agent 的标记变量,见 agent.ts 的 AGENTS),用户自己在终端里的操作不管。
6
+ // 不经过本地默认分支的落地(git push 别的分支:main、gh pr merge)不在这里拦,由停止门事后提示。
7
+ // 管不管、按哪些 ignore 判断,都看提交里的 testpace.json,不看工作区里的文件:
8
+ // 默认分支现在的代码或要落地的代码里有它就管,ignore 取要落地的那份。
9
+
10
+ import { AGENT_MARKERS } from './agent.ts'
11
+ import { contractAt, CONTRACT_FILE, effectiveIgnore } from './contract.ts'
12
+ import { short } from './format.ts'
13
+ import { commitOf, configuredHooks, configValue, FALLBACK_BRANCHES, findDefaultBranch, git, hasFile, hasRemote, isAncestor, onRemoteBranch, treeOf, workTreeId } from './git.ts'
14
+ import { coverageOf, openRepo, type Repo } from './repo.ts'
15
+ import { compareVersions, VERSION } from './version.ts'
16
+
17
+ /** 合并门在 git 配置里的钩子:hook.testpace.event、hook.testpace.command。 */
18
+ const HOOK = 'testpace'
19
+ const EVENT = 'reference-transaction'
20
+
21
+ /**
22
+ * testpace gate 拒绝这次更新时的退出码。钩子只认它和 0:别的退出码都不是检查结论,放行。
23
+ * 不和 node、sh 自己出错时的退出码(1、2、9、13、126、127、128 以上等)重合:
24
+ * testpace 没能运行(找不到命令、插件没装全、找不到 node、崩了)时不会碰巧拿到它。
25
+ */
26
+ export const GATE_REJECT = 20
27
+
28
+ /**
29
+ * testpace gate 说"这次没有检查"时的退出码:认不出默认分支,这次更新却建出了 main、master(见 uncheckedNote)。
30
+ * 钩子放行,原样转达它的话。和 GATE_REJECT 一样不和 node、sh 自己出错时的退出码重合。
31
+ */
32
+ export const GATE_UNCHECKED = 21
33
+
34
+ const NOT_CHECKED = 'testpace 合并门:testpace 没有给出检查结论(退出码 %s),这次没有检查。可能是找不到 testpace 命令、插件没装全、找不到能运行它的 node,或会话里的 testpace 是旧版本(插件更新后,开着的会话要重开才换成新版本)。'
35
+
36
+ /**
37
+ * 钩子命令,写在全局 git 配置里,所有仓库都跑它。git 用 sh 运行,把钩子参数接在命令后面,
38
+ * 所以写成一个函数,最后一个词是函数名,参数交给它。
39
+ * 判断都在 testpace gate 里,这里不放规则。
40
+ * - 开头一句记下是哪一版 testpace 配的:不同 agent 里装的版本不同、命令正文也不同时,会话开始的自动更新只升不降,
41
+ * 不来回覆盖。正文没变时不看这一句,发版不用重配。
42
+ * - 只管 agent 的命令(命令环境里有已接入的 agent 的标记变量,见 agent.ts 的 AGENTS),用户自己在终端里的操作不管。
43
+ * - 没有分支要动(只是远程跟踪分支、HEAD)的不调用 testpace:agent 每次更新引用都会经过这里,不用每次启动 node。
44
+ * - 只有 testpace gate 明确拒绝(退出码 GATE_REJECT)才拦。它自己说这次没有检查的(退出码 GATE_UNCHECKED)放行,原样转达。
45
+ * 别的都是没检查:放行,仓库里有 testpace.json(钩子在工作区根目录运行)才说一句、附上 testpace 的输出,别的仓库不打扰。
46
+ */
47
+ const HOOK_BODY = [
48
+ 'testpace_gate() {',
49
+ `[ "$1" = prepared ] && [ -n "${AGENT_MARKERS.map(name => `$${name}`).join('')}" ] || return 0;`,
50
+ `testpace_refs=$(cat); case $testpace_refs in *' refs/heads/'*) ;; *) return 0 ;; esac;`,
51
+ // printf 自己的报错不外露:testpace 起不来(找不到命令)时没人接这些内容,git 起钩子时又忽略 SIGPIPE,
52
+ // printf 交不出去就会报一行 write error: Broken pipe,排在下面那句说明的前面
53
+ `testpace_msg=$(printf '%s\\n' "$testpace_refs" 2>/dev/null | testpace gate 2>&1); testpace_code=$?;`,
54
+ `[ "$testpace_code" != 0 ] || return 0;`,
55
+ `if [ "$testpace_code" = ${GATE_REJECT} ]; then printf '%s\\n' "$testpace_msg" >&2; return 1; fi;`,
56
+ `if [ "$testpace_code" = ${GATE_UNCHECKED} ]; then printf '%s\\n' "$testpace_msg" >&2; return 0; fi;`,
57
+ `[ -f testpace.json ] || return 0;`,
58
+ `printf '${NOT_CHECKED}\\n' "$testpace_code" >&2;`,
59
+ `[ -z "$testpace_msg" ] || printf '%s\\n' "$testpace_msg" >&2;`,
60
+ 'return 0;',
61
+ '}; testpace_gate',
62
+ ].join(' ')
63
+
64
+ /** 钩子命令开头记版本的那一句。 */
65
+ const VERSION_TAG = /^: testpace (\S+); /
66
+
67
+ export const HOOK_COMMAND = `: testpace ${VERSION}; ${HOOK_BODY}`
68
+
69
+ type HookState =
70
+ | { kind: 'installed' }
71
+ /** 配了,但命令正文和这一版的不同,是更旧的版本配的。 */
72
+ | { kind: 'outdated' }
73
+ /** 配了,是更新的版本配的(比如另一个 agent 里装的 testpace 更新):照常把关,不改回去。 */
74
+ | { kind: 'newer'; version: string }
75
+ | { kind: 'missing' }
76
+ /** 配了,但这个仓库的 git 配置把它关了(hook.testpace.enabled = false)。 */
77
+ | { kind: 'disabled' }
78
+ /** git 太旧,不认配置里声明的钩子。 */
79
+ | { kind: 'oldGit'; version: string }
80
+
81
+ /** 合并门的钩子在这个仓库里生没生效:git 认不认配置里的钩子,配没配,命令是不是这一版的。 */
82
+ function hookState(root: string): HookState {
83
+ const hooks = configuredHooks(root, EVENT)
84
+ if (!hooks) return { kind: 'oldGit', version: git(root, ['--version']).replace(/^git version /, '') }
85
+ if (hooks.includes(`disabled\t${HOOK}`)) return { kind: 'disabled' }
86
+ if (!hooks.includes(HOOK)) return { kind: 'missing' }
87
+ const command = configValue(root, `hook.${HOOK}.command`) ?? ''
88
+ // 只比命令正文:正文没变(只是发了新版)时不用重配
89
+ if (command.replace(VERSION_TAG, '') === HOOK_BODY) return { kind: 'installed' }
90
+ const version = VERSION_TAG.exec(command)?.[1]
91
+ return version && compareVersions(version, VERSION) > 0 ? { kind: 'newer', version } : { kind: 'outdated' }
92
+ }
93
+
94
+ /** 合并门没在把关时的说明;在把关返回 undefined。status、会话说明和 install 共用。 */
95
+ function hookProblem(state: HookState): string | undefined {
96
+ switch (state.kind) {
97
+ case 'installed':
98
+ case 'newer':
99
+ return undefined
100
+ case 'oldGit':
101
+ return `这台机器的 git(${state.version})不认配置里声明的钩子,合并门没有生效。要 git 2.54 以上:告诉用户升级 git(比如 brew upgrade git),不要自己装。`
102
+ case 'missing':
103
+ return `合并门没配(用户自己删掉了,或还没配过),提交、合并到默认分支时不会检查。用户要的话,跑 testpace install 在全局 git 配置里配上。`
104
+ case 'disabled':
105
+ return `git 配置把合并门的钩子关掉了(hook.${HOOK}.enabled = false),合并门没有生效。`
106
+ case 'outdated':
107
+ return `git 配置里合并门的钩子命令(hook.${HOOK}.command)不是这一版的,跑 testpace install 更新。`
108
+ }
109
+ }
110
+
111
+ /** 合并门没在把关时给 agent 的说明;在把关返回 undefined。 */
112
+ export function gateProblem(root: string): string | undefined {
113
+ const found = findDefaultBranch(root)
114
+ if ('problem' in found) return `找不到默认分支(${found.problem}),合并门没有生效。设好 origin/HEAD(git remote set-head origin --auto)后才会检查。`
115
+ return hookProblem(hookState(root))
116
+ }
117
+
118
+ /** origin/HEAD 指着不存在的分支时给用户的说明:合并门照常把关,守的是按 main、master 认出的那个。没有这回事返回 undefined。 */
119
+ export function danglingNote(root: string): string | undefined {
120
+ const found = findDefaultBranch(root)
121
+ if ('problem' in found || !found.dangling) return undefined
122
+ return `origin/HEAD 指着不存在的分支 ${found.dangling}(远程可能改了默认分支的名字),默认分支按 ${found.branch} 算。用 git remote set-head origin --auto 更新。`
123
+ }
124
+
125
+ /**
126
+ * 在全局 git 配置里配上合并门的钩子(这台机器配一次,所有仓库生效)。git 太旧时不配,返回原因;
127
+ * 配好了还没生效(比如仓库自己的配置把它关了)也返回原因。
128
+ */
129
+ export function installGate(root: string): { ok: boolean; problem?: string } {
130
+ const before = hookState(root)
131
+ if (before.kind === 'oldGit') return { ok: false, problem: hookProblem(before) }
132
+ git(root, ['config', '--global', '--replace-all', `hook.${HOOK}.event`, EVENT])
133
+ git(root, ['config', '--global', '--replace-all', `hook.${HOOK}.command`, HOOK_COMMAND])
134
+ const problem = hookProblem(hookState(root))
135
+ return problem ? { ok: false, problem: `全局 git 配置里配好了,但在这个仓库里没有生效:${problem}` } : { ok: true }
136
+ }
137
+
138
+ /** 自动配过合并门的记号(全局 git 配置):之后钩子没了,是用户自己删的,不再自动配回去。 */
139
+ const AUTO_KEY = 'testpace.autoInstalled'
140
+
141
+ /**
142
+ * 会话开始时自动配合并门:装了插件就当同意,不问,只告诉用户一声。
143
+ * 没配过的配上;配过但命令是旧版本的更新;更新的版本配的、用户自己删掉的、git 太旧的、仓库把它关掉的不动。
144
+ * 返回给用户看的说明,没动返回 undefined。
145
+ */
146
+ export function ensureGate(root: string): string | undefined {
147
+ const state = hookState(root)
148
+ if (state.kind === 'outdated') {
149
+ installGate(root)
150
+ return undefined
151
+ }
152
+ if (state.kind !== 'missing' || configValue(root, AUTO_KEY) === 'true') return undefined
153
+ const result = installGate(root)
154
+ if (!result.ok) return undefined
155
+ git(root, ['config', '--global', AUTO_KEY, 'true'])
156
+ return [
157
+ 'testpace:在全局 git 配置里配上了合并门(这台机器上所有仓库生效)。',
158
+ '它只在 agent 要把代码落到默认分支时检查有没有跑过全部测试,没接入 testpace 的仓库不受影响,你自己在终端里的操作也不管。',
159
+ `不想要的话:git config --global --remove-section hook.${HOOK},之后不会再自动配上。`,
160
+ ].join('')
161
+ }
162
+
163
+ interface RefUpdate {
164
+ next: string
165
+ ref: string
166
+ }
167
+
168
+ /** 删除分支(新值全是 0)、符号引用:没有代码落地。 */
169
+ function landsNothing(next: string): boolean {
170
+ return /^0+$/.test(next) || next.startsWith('ref:')
171
+ }
172
+
173
+ /**
174
+ * 认不出默认分支时合并门没法把关。多数时候不用说(status 和会话说明里有),只有一种要当场说:这次更新建出了 main 或
175
+ * master,建好以后它就是默认分支(比如没有远程的仓库把 main 删了再建),而那份代码接入了约定、又没有整组通过记录。
176
+ * 不拦:建之前确实不知道该守哪个分支。
177
+ */
178
+ function uncheckedNote(repo: Repo, updates: RefUpdate[], problem: string): string | undefined {
179
+ for (const { next, ref } of updates) {
180
+ const name = FALLBACK_BRANCHES.find(branch => ref === `refs/heads/${branch}`)
181
+ if (!name || landsNothing(next)) continue
182
+ const incoming = contractAt(repo.root, next)
183
+ const tree = incoming && treeOf(repo.root, next)
184
+ if (!tree || coverageOf(repo, effectiveIgnore(incoming, undefined), tree).kind !== 'none') continue
185
+ return `testpace 合并门:这次建出了 ${name},建之前认不出默认分支(${problem}),这次没有检查。它指向的代码(${short(tree)})没有整组通过记录:在这份代码上跑 testpace full。`
186
+ }
187
+ return undefined
188
+ }
189
+
190
+ /** 合并门对一次引用更新的结论:reject 是拒绝的原因;unchecked 是这次没有检查、要当场说的话(放行)。 */
191
+ export type GateAnswer = { reject: string } | { unchecked: string }
192
+
193
+ /**
194
+ * git 钩子交来的引用更新(每行 "<旧值> <新值> <引用>"):要移动默认分支、而且落地的代码没有整组通过记录时,
195
+ * 返回拒绝的原因。没有要说的返回 undefined。
196
+ */
197
+ export function checkRefUpdates(cwd: string, input: string): GateAnswer | undefined {
198
+ const repo = openRepo(cwd)
199
+ if (!repo) return undefined
200
+ const updates: RefUpdate[] = input.split('\n').map(line => {
201
+ const [, next = '', ref = ''] = line.split(' ')
202
+ return { next, ref }
203
+ })
204
+ const found = findDefaultBranch(repo.root)
205
+ if ('problem' in found) {
206
+ const unchecked = uncheckedNote(repo, updates, found.problem)
207
+ return unchecked ? { unchecked } : undefined
208
+ }
209
+ const { branch } = found
210
+ const root = repo.root
211
+ // 同一次更新里远程默认分支(refs/remotes/<远程>/<分支>)的新位置:git fetch <远程> main:main 这类,
212
+ // 本地分支和远程跟踪分支一起动,这时远程跟踪分支还没更新到位
213
+ const fetched = updates.filter(({ ref }) => /^refs\/remotes\/[^/]+\/(.+)$/.exec(ref)?.[1] === branch).map(({ next }) => next)
214
+ for (const { next, ref } of updates) {
215
+ if (ref !== `refs/heads/${branch}` || landsNothing(next)) continue
216
+ // 接入了约定的仓库才管:默认分支现在的代码或要落地的代码里有 testpace.json
217
+ const incoming = contractAt(root, next)
218
+ if (!incoming && !hasFile(root, `refs/heads/${branch}`, CONTRACT_FILE)) continue
219
+ // ignore 按默认分支上原来那份认:这次要落地的代码里新加的规则,落地以后才生效
220
+ const ignore = effectiveIgnore(incoming, contractAt(root, `refs/heads/${branch}`))
221
+ const current = commitOf(root, `refs/heads/${branch}`)
222
+ // 退回默认分支以前的提交,或同步远程默认分支已有的提交:没有新内容落地
223
+ if (current && isAncestor(root, next, current)) continue
224
+ if (onRemoteBranch(root, branch, next) || fetched.some(tip => isAncestor(root, next, tip))) continue
225
+ const tree = treeOf(root, next)
226
+ if (!tree) throw new Error(`读不到提交 ${next} 的内容`)
227
+ if (coverageOf(repo, ignore, tree).kind !== 'none') continue
228
+ const worktree = workTreeId(root)
229
+ const notes = !incoming
230
+ ? // 要落地的提交接在默认分支现在的提交后面:是这些提交删掉了它;不然是接入之前分出去的分支,本来就没有
231
+ current && isAncestor(root, current, next)
232
+ ? [`要落地的提交删掉了 ${CONTRACT_FILE},拿不到整组通过记录。要退出接入,由用户自己在终端里提交;不是要退出,就把它恢复回来。`]
233
+ : [`要落地的代码里没有 ${CONTRACT_FILE}(${branch} 上有),拿不到整组通过记录:这个分支是接入之前分出去的。把 ${branch} 合进这个分支再测。`]
234
+ : incoming.problems.length > 0
235
+ ? [`要落地的代码里的 ${CONTRACT_FILE} 有问题:${incoming.problems.join(';')}。testpace full 跑不了,拿不到整组通过记录:先修好它,在改好的代码上跑整组。`]
236
+ : worktree !== tree && coverageOf(repo, ignore, worktree).kind !== 'none'
237
+ ? ['工作区的整组通过了,但要落地的内容和工作区不一样:还有没提交的改动或未跟踪的文件。把它们一起提交,或者删掉、加进 .gitignore 后重跑整组。']
238
+ : [
239
+ '先在要落地的这份代码上跑 testpace full,通过后再落地;合并分支照 gatelight:merge 技能做,在合并分支上测过再快进。',
240
+ ...(hasRemote(root) ? [`只是同步远程的 ${branch} 的话:先 git fetch <远程>,再把 ${branch} 快进到 <远程>/${branch}。`] : []),
241
+ ]
242
+ return {
243
+ reject: [
244
+ `testpace 合并门:这次要把 ${branch} 更新到 ${short(next)},那份代码(${short(tree)})没有整组通过记录,${branch} 没有更新。`,
245
+ ...notes,
246
+ '工作区和暂存区里可能留着这次操作带来的改动,用 git status 看;cherry-pick、rebase、revert 这类停在半路的操作先 --abort。',
247
+ ].join('\n'),
248
+ }
249
+ }
250
+ return undefined
251
+ }