gatelight 0.0.0-stage → 0.17.9

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 (108) 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/bin/modwall +8 -0
  6. package/bin/node.sh +14 -0
  7. package/bin/testcraft +8 -0
  8. package/bin/testpace +8 -0
  9. package/entry/command +44 -0
  10. package/hooks/antigravity.sh +24 -0
  11. package/hooks/codex.json +50 -0
  12. package/hooks/codex.sh +7 -0
  13. package/hooks/hooks.json +43 -0
  14. package/hooks/testpace.ts +25 -0
  15. package/hooks.json +16 -0
  16. package/mcp_config.json +8 -0
  17. package/package.json +21 -4
  18. package/setup.mjs +99 -0
  19. package/skills/merge/SKILL.md +42 -0
  20. package/skills/modular/SKILL.md +75 -0
  21. package/skills/setup/SKILL.md +101 -0
  22. package/skills/setup-modwall/SKILL.md +112 -0
  23. package/skills/setup-testcraft/SKILL.md +23 -0
  24. package/skills/setup-testcraft/checklist/dev-login.md +20 -0
  25. package/skills/write-tests/SKILL.md +153 -0
  26. package/src/base/agent.ts +100 -0
  27. package/src/base/baseline.ts +54 -0
  28. package/src/base/commandline.ts +40 -0
  29. package/src/base/commands.ts +94 -0
  30. package/src/base/confirm.ts +161 -0
  31. package/src/base/contract.ts +94 -0
  32. package/src/base/coverage.ts +46 -0
  33. package/src/base/entry.ts +90 -0
  34. package/src/base/excerpt.ts +46 -0
  35. package/src/base/execute.ts +70 -0
  36. package/src/base/exit.ts +6 -0
  37. package/src/base/format.ts +27 -0
  38. package/src/base/full.ts +160 -0
  39. package/src/base/gate.ts +251 -0
  40. package/src/base/git.ts +361 -0
  41. package/src/base/glob.ts +38 -0
  42. package/src/base/hook.ts +297 -0
  43. package/src/base/hookformat.ts +257 -0
  44. package/src/base/judging.ts +27 -0
  45. package/src/base/layermap.ts +69 -0
  46. package/src/base/module.ts +88 -0
  47. package/src/base/process-group.ts +101 -0
  48. package/src/base/records.ts +66 -0
  49. package/src/base/repo.ts +155 -0
  50. package/src/base/sessions.ts +55 -0
  51. package/src/base/shell.ts +176 -0
  52. package/src/base/stop.ts +100 -0
  53. package/src/base/store.ts +348 -0
  54. package/src/base/version.ts +24 -0
  55. package/src/cli.ts +186 -0
  56. package/src/craft/change.ts +24 -0
  57. package/src/craft/checklist.ts +157 -0
  58. package/src/craft/commands.ts +111 -0
  59. package/src/craft/config.ts +15 -0
  60. package/src/craft/full.ts +30 -0
  61. package/src/craft/index.ts +12 -0
  62. package/src/craft/session.ts +21 -0
  63. package/src/mcp.ts +79 -0
  64. package/src/modules.ts +10 -0
  65. package/src/modwall.ts +8 -0
  66. package/src/pace/commands.ts +281 -0
  67. package/src/pace/config.ts +103 -0
  68. package/src/pace/consent.ts +81 -0
  69. package/src/pace/focused.ts +208 -0
  70. package/src/pace/full.ts +38 -0
  71. package/src/pace/index.ts +16 -0
  72. package/src/pace/record.ts +84 -0
  73. package/src/pace/report.ts +335 -0
  74. package/src/pace/results.ts +243 -0
  75. package/src/pace/run/node-test-reporter.mjs +34 -0
  76. package/src/pace/run/node-test.ts +26 -0
  77. package/src/pace/run/playwright-reporter.mjs +48 -0
  78. package/src/pace/run/playwright.ts +34 -0
  79. package/src/pace/run/runner.ts +157 -0
  80. package/src/pace/run/targets.ts +130 -0
  81. package/src/pace/run/vitest-launcher.mjs +101 -0
  82. package/src/pace/run/vitest.ts +22 -0
  83. package/src/pace/session.ts +35 -0
  84. package/src/pace/testlist.ts +91 -0
  85. package/src/pace/tests.ts +22 -0
  86. package/src/pace/verify.ts +95 -0
  87. package/src/testcraft.ts +9 -0
  88. package/src/wall/check.ts +258 -0
  89. package/src/wall/commands.ts +279 -0
  90. package/src/wall/config.ts +394 -0
  91. package/src/wall/database.ts +136 -0
  92. package/src/wall/dbcheck.ts +389 -0
  93. package/src/wall/dbrules.ts +213 -0
  94. package/src/wall/edit.ts +64 -0
  95. package/src/wall/files.ts +35 -0
  96. package/src/wall/full.ts +30 -0
  97. package/src/wall/index.ts +15 -0
  98. package/src/wall/init.ts +149 -0
  99. package/src/wall/layermap.ts +124 -0
  100. package/src/wall/layout.ts +231 -0
  101. package/src/wall/loosen.ts +157 -0
  102. package/src/wall/miniprogram.ts +80 -0
  103. package/src/wall/project.ts +88 -0
  104. package/src/wall/rules.ts +400 -0
  105. package/src/wall/session.ts +198 -0
  106. package/src/wall/sql.ts +510 -0
  107. package/src/wall/store.ts +39 -0
  108. package/README.md +0 -3
@@ -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
+ }