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,40 @@
1
+ // 三条命令(testpace、modwall、testcraft)的入口共用的一层:在 agent 的沙箱里跑不了的子命令事先拒绝,写入被拒时说清楚。
2
+ // 各命令只说哪些子命令在沙箱里跑不了、要做什么(outside);怎么认沙箱、怎么说、退出码是什么都在这里,三个入口都经过它。
3
+
4
+ import { AGENTS, currentAgent } from './agent.ts'
5
+ import { EXIT } from './exit.ts'
6
+
7
+ /** 跑这条命令的 agent:会话号、在不在沙箱里。用户在终端里跑的没有。 */
8
+ export const AGENT = currentAgent()
9
+
10
+ export interface CommandLine {
11
+ /** 命令名:提示里用。 */
12
+ name: string
13
+ /**
14
+ * 这次调用在 agent 的沙箱里跑不了时,说它要做什么(接在"它要"后面);跑得了的返回 undefined,没有这样的子命令的不填。
15
+ * 算跑不了的:要写项目目录以外的地方(.git/testpace/ 的记录、LayerMap 存在项目外面的地图),或者要跑项目的命令(常要端口、网络)。
16
+ * 沙箱里这些会被拒,得出的是假结论(测试假失败、检查假的没通过),所以不跑,不等它失败。
17
+ * 仓库在沙箱放行的位置(比如 /tmp)时记录目录也写得进去,所以不能只靠写不写得进去判断。
18
+ * git 钩子调用的子命令不算在里面:在这里拒绝不是检查结论,钩子会当成没检查而放行。
19
+ */
20
+ outside?(argv: string[]): string | undefined
21
+ run(argv: string[]): number | Promise<number>
22
+ }
23
+
24
+ /** 跑一条命令,返回退出码。 */
25
+ export async function runCommandLine(line: CommandLine, argv: string[]): Promise<number> {
26
+ const needs = AGENT?.sandboxed ? line.outside?.(argv) : undefined
27
+ if (AGENT && needs) {
28
+ console.error(`${line.name} 要在 ${AGENTS[AGENT.kind].name} 的沙箱外跑:它要${needs},在沙箱里会被拒、结果不准。申请提权(在沙箱外)重新运行这条命令。`)
29
+ return EXIT.usage
30
+ }
31
+ try {
32
+ return await line.run(argv)
33
+ } catch (error) {
34
+ // 写入被拒(记录目录 .git/testpace、项目里的文件):多半是在 agent 的沙箱里,说清楚,不只抛一句写入被拒
35
+ const code = (error as NodeJS.ErrnoException).code
36
+ if (code !== 'EPERM' && code !== 'EACCES' && code !== 'EROFS') throw error
37
+ console.error(`${line.name} 写不了 ${(error as NodeJS.ErrnoException).path ?? '记录目录'}(${code})。在 agent 的沙箱里时,申请提权(在沙箱外)重新运行这条命令。`)
38
+ return EXIT.usage
39
+ }
40
+ }
@@ -0,0 +1,94 @@
1
+ // 底座的命令:借用工作区(hold、release)、这台机器配一次(install)、git 钩子调的 gate。
2
+ // 命令行入口(src/cli.ts)分发到这里;各模块的命令在各自的目录里。
3
+
4
+ import { readFileSync } from 'node:fs'
5
+ import { ENTRY_COMMANDS, entryDir, entryPath, installEntries } from './entry.ts'
6
+ import { EXIT } from './exit.ts'
7
+ import { checkRefUpdates, GATE_REJECT, GATE_UNCHECKED, gateProblem, installGate } from './gate.ts'
8
+ import { borrow, giveBack, openRepo, type Repo, runningText } from './repo.ts'
9
+ import { processAlive } from './store.ts'
10
+
11
+ /** 命令所在的仓库;不在 git 仓库里时说一句。 */
12
+ export function context(): Repo | undefined {
13
+ const repo = openRepo(process.cwd())
14
+ if (!repo) console.error('testpace 要在 git 仓库里运行。')
15
+ return repo
16
+ }
17
+
18
+ /** testpace hold:别的工具借用这个工作区(见 repo.ts 的 borrow)。占上了输出借用的 id,放开时用。 */
19
+ export function hold(args: string[], usage: string): number {
20
+ const [pid, ...what] = args
21
+ const by = what.join(' ').trim()
22
+ if (!pid || !/^[1-9]\d*$/.test(pid) || !by) {
23
+ console.error(usage)
24
+ return EXIT.usage
25
+ }
26
+ // 进程不在了的登记马上作废,调用方会以为占上了
27
+ if (!processAlive(Number(pid))) {
28
+ console.error(`进程 ${pid} 不在,借用要登记正在用工作区的那个进程。`)
29
+ return EXIT.usage
30
+ }
31
+ const ctx = context()
32
+ if (!ctx) return EXIT.usage
33
+ const held = borrow(ctx, Number(pid), by)
34
+ if ('busy' in held) {
35
+ console.log(`${runningText(held.busy)}。`)
36
+ return EXIT.busy
37
+ }
38
+ if (held.id) console.log(held.id)
39
+ return EXIT.ok
40
+ }
41
+
42
+ /** testpace release:放开 hold 占的工作区。 */
43
+ export function release(args: string[], usage: string): number {
44
+ const [id] = args
45
+ if (!id || args.length !== 1) {
46
+ console.error(usage)
47
+ return EXIT.usage
48
+ }
49
+ const ctx = context()
50
+ if (!ctx) return EXIT.usage
51
+ giveBack(ctx, id)
52
+ return EXIT.ok
53
+ }
54
+
55
+ export function install(): number {
56
+ const ctx = context()
57
+ if (!ctx) return EXIT.usage
58
+ const { ok, problem } = installGate(ctx.root)
59
+ if (!ok) {
60
+ console.error(`没有配好:${problem}`)
61
+ return EXIT.usage
62
+ }
63
+ console.log('合并门已配好:全局 git 配置里的 hook.testpace,这台机器上 agent 在所有仓库里移动默认分支时都检查(只管接入了 testpace 的仓库)。')
64
+ const rest = gateProblem(ctx.root)
65
+ if (rest) console.log(rest)
66
+ const { refused } = installEntries()
67
+ const placed = ENTRY_COMMANDS.filter(command => !refused.includes(command))
68
+ if (placed.length) console.log(`固定命令入口已放好:${entryDir()} 下的 ${placed.join('、')},运行时转给这台机器上装着的最高版本的插件里同名的命令。`)
69
+ if (refused.length) {
70
+ console.error(`固定命令入口没放上:${refused.map(entryPath).join('、')} 已经有别的文件,没有覆盖。确认不要它后删掉,再跑 testpace install。`)
71
+ return EXIT.usage
72
+ }
73
+ return EXIT.ok
74
+ }
75
+
76
+ /**
77
+ * git 的 reference-transaction 钩子调用:标准输入是要更新的引用。放行退出码 0;拒绝退出码 GATE_REJECT,
78
+ * git 就取消这次更新;这次没有检查、要当场说一句的退出码 GATE_UNCHECKED,钩子放行并转达。
79
+ * 检查时出错也拒绝:已经在检查了,确认不了要落地的代码测过就不放。
80
+ */
81
+ export function gate(): number {
82
+ try {
83
+ const answer = checkRefUpdates(process.cwd(), readFileSync(0, 'utf8'))
84
+ if (!answer) return EXIT.ok
85
+ if ('unchecked' in answer) {
86
+ console.error(answer.unchecked)
87
+ return GATE_UNCHECKED
88
+ }
89
+ console.error(answer.reject)
90
+ } catch (error) {
91
+ console.error(`testpace 合并门:没能确认要落地的代码测过(${(error as Error).message.split('\n')[0]}),这次不更新。`)
92
+ }
93
+ return GATE_REJECT
94
+ }
@@ -0,0 +1,161 @@
1
+ // 用户确认:检查里有要用户同意的改动(放松了测试、放宽了规则)时,模块把条目交到这里,不自己弹窗、不自己存同意记录。
2
+ // 同意只能来自确认工具(src/mcp.ts 的 confirm_with_user):每次调用都要用户在弹窗里同意(Claude Code 靠工具上的标记,
3
+ // Antigravity 靠 hook 的 force_ask),agent 自己说"用户同意了"不算。
4
+ //
5
+ // 同意按项记:一项是"哪个模块的、改之前是什么、改成什么、用户当时看到的文字",四样都一样才是同一项。
6
+ // 几个分支合到一起,没再动过的那一项不用重新确认;文字相同但改之前的内容不同,是另一项,要重新确认。
7
+ //
8
+ // 两步:检查(askUser)把还没同意的条目按编号存好,输出编号和弹窗文字让 agent 去调工具;
9
+ // 工具(confirm)只按编号取存下的内容,核对传来的文字一字不差,记下同意。工具进程跟着会话开着、插件更新后还是旧代码,
10
+ // 所以它不打开改动、不做任何判断。
11
+ //
12
+ // 记录在 .git/testpace/confirm/ 下(所有 worktree 共用):pending.json 等用户过目的,confirmed.json 用户同意过的。
13
+
14
+ import { existsSync } from 'node:fs'
15
+ import { commonDir, repoRoot } from './git.ts'
16
+ import { hash, ModuleRecords } from './records.ts'
17
+ import { type Repo } from './repo.ts'
18
+ import { Store } from './store.ts'
19
+ import { PLUGIN_NAME } from './version.ts'
20
+
21
+ /** 确认工具的名字(src/mcp.ts)。 */
22
+ export const CONFIRM_TOOL = 'confirm_with_user'
23
+
24
+ /** 要用户同意的一项改动。 */
25
+ export interface ConfirmItem {
26
+ /** 这一项改之前是什么。写法由模块定(内容本身或它的摘要都行),同一项改动每次要写得一样。 */
27
+ before: string
28
+ /** 改成了什么。 */
29
+ after: string
30
+ /** 给用户看的文字:白话,用户不看代码也能判断。 */
31
+ text: string
32
+ }
33
+
34
+ export interface Asked {
35
+ /** 用户同意过的。 */
36
+ confirmed: ConfirmItem[]
37
+ /** 还没同意的。 */
38
+ pending: ConfirmItem[]
39
+ /** 有没同意的条目时:存好的编号和弹窗文字,以及说给 agent 的话(怎么调工具)。 */
40
+ ask?: { id: string; text: string; lines: string[] }
41
+ }
42
+
43
+ interface PendingRecord {
44
+ module: string
45
+ /** 弹窗里给用户看的文字:工具只核对传来的和它一字不差。 */
46
+ text: string
47
+ /** 这次弹窗里的各项:同意后按 key 各记一条。 */
48
+ items: Array<{ key: string; text: string }>
49
+ at: number
50
+ }
51
+
52
+ interface ConfirmRecord {
53
+ module: string
54
+ /** 用户同意时看到的这一项的文字。 */
55
+ text: string
56
+ at: number
57
+ }
58
+
59
+ /** 文字比对用:每行去掉首尾空白,去掉空行,一样才算同一份。 */
60
+ function plain(text: string): string {
61
+ return text
62
+ .split('\n')
63
+ .map(line => line.trim())
64
+ .filter(Boolean)
65
+ .join('\n')
66
+ }
67
+
68
+ /** 一项的记号:模块、改之前、改成什么、给用户看的文字。 */
69
+ function itemKey(module: string, item: ConfirmItem): string {
70
+ return hash('item', module, item.before, item.after, plain(item.text))
71
+ }
72
+
73
+ /** 两份记录都用底座的模块记录存取(records.ts):90 天前的不再算,文件坏了当成没有。 */
74
+ const pendingOf = (store: Store): ModuleRecords<PendingRecord> => new ModuleRecords(store, 'confirm', 'pending')
75
+ const confirmedOf = (store: Store): ModuleRecords<ConfirmRecord> => new ModuleRecords(store, 'confirm', 'confirmed')
76
+
77
+ /** 弹窗里给用户看的文字:一项一段,带编号。 */
78
+ function popupText(heading: string, items: ConfirmItem[]): string {
79
+ const lines = [`${heading},要你确认的有 ${items.length} 项:`]
80
+ items.forEach((item, index) => {
81
+ const [first = '', ...rest] = item.text.split('\n').map(line => line.trim()).filter(Boolean)
82
+ lines.push('', `${index + 1}. ${first}`, ...rest.map(line => ` ${line}`))
83
+ })
84
+ lines.push('', '同意:按这样改。不同意:告诉 agent 改回去或换个做法。')
85
+ return lines.join('\n')
86
+ }
87
+
88
+ /**
89
+ * 检查时调:这些条目里用户同意过哪些。有没同意的,把它们按编号存好,返回编号、弹窗文字和说给 agent 的话。
90
+ * module 是模块的名字,heading 是弹窗开头说这是什么的半句(比如"这次改动里放松测试的地方")。
91
+ * 有没同意的条目时,模块的检查不能算通过。
92
+ */
93
+ export function askUser(repo: Repo, module: string, heading: string, items: ConfirmItem[]): Asked {
94
+ const records = confirmedOf(repo.store)
95
+ const seen = new Set<string>()
96
+ const confirmed: ConfirmItem[] = []
97
+ const pending: Array<{ key: string; item: ConfirmItem }> = []
98
+ for (const item of items) {
99
+ const key = itemKey(module, item)
100
+ if (seen.has(key)) continue
101
+ seen.add(key)
102
+ if (records.get(key)) confirmed.push(item)
103
+ else pending.push({ key, item })
104
+ }
105
+ if (pending.length === 0) return { confirmed, pending: [] }
106
+ const text = popupText(heading, pending.map(({ item }) => item))
107
+ // 编号按这一批没同意的条目算:条目变了就是另一个编号,旧编号的同意对它不算
108
+ const id = hash('ask', module, text, ...pending.map(({ key }) => key))
109
+ pendingOf(repo.store).put(id, { module, text, items: pending.map(({ key, item }) => ({ key, text: item.text })), at: Date.now() })
110
+ return {
111
+ confirmed,
112
+ pending: pending.map(({ item }) => item),
113
+ ask: {
114
+ id,
115
+ text,
116
+ lines: [
117
+ `这 ${pending.length} 项还没经用户确认。用户不会看命令输出,要调用 ${PLUGIN_NAME} 的 ${CONFIRM_TOOL} 工具,弹窗给用户看,用户同意了才算。`,
118
+ '调用之前,先在对话里用白话告诉用户每一项原来是什么样、现在改成什么样、为什么;用户不同意的,改回去或者换个做法。',
119
+ `repo:${repo.root}`,
120
+ `id:${id}`,
121
+ 'text(下面两行分隔线之间的原样填,一字不改):',
122
+ '-----',
123
+ text,
124
+ '-----',
125
+ ],
126
+ },
127
+ }
128
+ }
129
+
130
+ export interface Confirmed {
131
+ ok: boolean
132
+ text: string
133
+ }
134
+
135
+ /** 编号是 32 位十六进制。 */
136
+ const ID = /^[0-9a-f]{32}$/
137
+
138
+ /** 确认工具调:核对传来的文字就是检查给这个编号存下的弹窗内容,记下用户同意了里面的每一项。 */
139
+ export function confirm(repoPath: string, id: string, text: string): Confirmed {
140
+ const root = existsSync(repoPath) ? repoRoot(repoPath) : undefined
141
+ if (!root) return { ok: false, text: `${repoPath} 不在 git 仓库里` }
142
+ const missing = { ok: false, text: '没有这个编号要确认的内容:重跑要求确认的那条检查,照它输出的编号和文字填。' }
143
+ if (!ID.test(id)) return missing
144
+ const store = new Store(commonDir(root))
145
+ // 编号是外面传来的:模块记录只取文件里这个键自己的
146
+ const pending = pendingOf(store).get(id)
147
+ if (!pending) return missing
148
+ const whole =
149
+ typeof pending.text === 'string' &&
150
+ typeof pending.module === 'string' &&
151
+ Array.isArray(pending.items) &&
152
+ pending.items.every(item => typeof item?.key === 'string' && typeof item.text === 'string')
153
+ if (!whole) return { ok: false, text: '这个编号存下的内容坏了:重跑要求确认的那条检查,照它输出的编号和文字填。' }
154
+ if (plain(text) !== plain(pending.text)) {
155
+ return { ok: false, text: '传来的文字和检查给这个编号的不一致:照它输出的原样填,不要改写、增删。' }
156
+ }
157
+ const records = confirmedOf(store)
158
+ const at = Date.now()
159
+ for (const item of pending.items) records.put(item.key, { module: pending.module, text: item.text, at })
160
+ return { ok: true, text: `已记下:用户确认并同意了这 ${pending.items.length} 项。再跑一次要求确认的那条检查。` }
161
+ }
@@ -0,0 +1,94 @@
1
+ // 项目的约定文件 testpace.json,底座看到的部分:接没接入、哪些路径不影响结果(ignore)、整个文件有没有问题。
2
+ // 别的字段归各模块(见 module.ts 的 fields、contractProblems),底座只把它们的问题合到一起。
3
+
4
+ import { existsSync, readFileSync } from 'node:fs'
5
+ import { join } from 'node:path'
6
+ import { defaultBranch, fileAt, refTip } from './git.ts'
7
+ import { modules } from './module.ts'
8
+
9
+ export const CONTRACT_FILE = 'testpace.json'
10
+
11
+ export interface Contract {
12
+ /** 这份约定里写的、不影响结果的路径规则。文件写坏了读不出来时为空(按没有 ignore 算:要内容完全一致的通过记录)。判断时认哪些见 effectiveIgnore。 */
13
+ ignore: string[]
14
+ /** 文件的内容;不是合法的 JSON 对象时没有。 */
15
+ raw?: Record<string, unknown>
16
+ /** 约定的问题:格式不对、未知字段、ignore 写错,和各模块对自己字段的检查。有问题时整组跑不了。 */
17
+ problems: string[]
18
+ }
19
+
20
+ /** 工作区接入了:根目录有 testpace.json。写坏了也算接入,问题由命令和会话说明讲出来。 */
21
+ export function joined(root: string): boolean {
22
+ return existsSync(join(root, CONTRACT_FILE))
23
+ }
24
+
25
+ /** 工作区里的约定;没接入返回 undefined。 */
26
+ export function loadContract(root: string): Contract | undefined {
27
+ return joined(root) ? readContract(readFileSync(join(root, CONTRACT_FILE), 'utf8')) : undefined
28
+ }
29
+
30
+ /**
31
+ * 一个提交自己带的约定(提交里的 testpace.json);提交里没有这个文件返回 undefined。
32
+ * 合并门、停止门判断落到默认分支的代码时用它,不看工作区里的文件:工作区里没提交的改动、
33
+ * 别的分支检出的旧文件都不该影响判断。
34
+ */
35
+ export function contractAt(root: string, rev: string): Contract | undefined {
36
+ const text = fileAt(root, rev, CONTRACT_FILE)
37
+ return text === undefined ? undefined : readContract(text)
38
+ }
39
+
40
+ /** 默认分支上现在那份约定(本地的默认分支,没有就看 origin 上的);认不出默认分支、那里没有 testpace.json 时没有。 */
41
+ export function landedContract(root: string): Contract | undefined {
42
+ const branch = defaultBranch(root)
43
+ const tip = branch ? (refTip(root, `refs/heads/${branch}`) ?? refTip(root, `refs/remotes/origin/${branch}`)) : undefined
44
+ return tip ? contractAt(root, tip.commit) : undefined
45
+ }
46
+
47
+ /**
48
+ * 判断"只改了不影响结果的路径"时认哪些 ignore 规则。ignore 是评判用的配置,走"合并后才生效"(见 judging.ts):
49
+ * 这份约定里有、默认分支上原来那份(landed)里也有的才认。分支上新加的规则这次不算,合并以后才生效;删掉的马上生效。
50
+ * 默认分支上还没有约定(首次接入)时一条也不认。
51
+ */
52
+ export function effectiveIgnore(contract: Contract | undefined, landed: Contract | undefined): string[] {
53
+ if (!contract || !landed) return []
54
+ return contract.ignore.filter(rule => landed.ignore.includes(rule))
55
+ }
56
+
57
+ /** 工作区里这份约定现在认的 ignore 规则(rules),和写了但要合并后才生效的(deferred)。 */
58
+ export function countedIgnore(root: string, contract: Contract | undefined): { rules: string[]; deferred: string[] } {
59
+ const rules = effectiveIgnore(contract, landedContract(root))
60
+ return { rules, deferred: (contract?.ignore ?? []).filter(rule => !rules.includes(rule)) }
61
+ }
62
+
63
+ /** 从 testpace.json 的内容读约定(工作区里的文件,或某个提交里的那份)。 */
64
+ export function readContract(text: string): Contract {
65
+ let raw: unknown
66
+ try {
67
+ raw = JSON.parse(text)
68
+ } catch (error) {
69
+ return { ignore: [], problems: [`${CONTRACT_FILE} 不是合法的 JSON:${(error as Error).message}`] }
70
+ }
71
+ return parseContract(raw)
72
+ }
73
+
74
+ export function parseContract(raw: unknown): Contract {
75
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
76
+ return { ignore: [], problems: [`${CONTRACT_FILE} 应该是一个对象`] }
77
+ }
78
+ const record = raw as Record<string, unknown>
79
+ const problems: string[] = []
80
+ const known = new Set(['ignore', ...modules().flatMap(module => module.fields ?? [])])
81
+ for (const key of Object.keys(record)) {
82
+ if (!known.has(key)) problems.push(`未知字段 "${key}"`)
83
+ }
84
+ for (const module of modules()) problems.push(...(module.contractProblems?.(record) ?? []))
85
+ let ignore: string[] = []
86
+ if (record.ignore !== undefined) {
87
+ if (!Array.isArray(record.ignore) || record.ignore.some(item => typeof item !== 'string' || item === '')) {
88
+ problems.push('"ignore" 应该是路径规则的字符串数组')
89
+ } else {
90
+ ignore = record.ignore as string[]
91
+ }
92
+ }
93
+ return { ignore, raw: record, problems }
94
+ }
@@ -0,0 +1,46 @@
1
+ // 某份代码内容有没有整组通过的记录。
2
+
3
+ import type { RunRecord } from './store.ts'
4
+
5
+ export type Coverage =
6
+ | { kind: 'exact'; run: RunRecord }
7
+ | { kind: 'ignored'; run: RunRecord; changed: string[] }
8
+ | { kind: 'none' }
9
+
10
+ /** 能当通过记录的整组:通过,而且跑的过程中代码没改过。 */
11
+ export function isValidPass(run: RunRecord): boolean {
12
+ return run.kind === 'full' && run.result === 'pass' && run.tree === run.treeAtEnd
13
+ }
14
+
15
+ /** 只和最近这么多份通过的代码比较忽略路径,避免历史很长时逐个 diff。 */
16
+ const IGNORE_CANDIDATES = 20
17
+
18
+ /**
19
+ * 先找内容完全一致的通过记录;没有的话,找相对它只改了 ignore 路径的最近一次。
20
+ * diff 由调用方给(git diff-tree),这里不碰 git,方便单测。
21
+ */
22
+ export function findCoverage(
23
+ tree: string,
24
+ runs: RunRecord[],
25
+ isIgnored: (path: string) => boolean,
26
+ diff: (from: string, to: string) => string[],
27
+ ): Coverage {
28
+ const passes = runs.filter(isValidPass).sort((a, b) => b.startedAt - a.startedAt)
29
+ const exact = passes.find(run => run.tree === tree)
30
+ if (exact) return { kind: 'exact', run: exact }
31
+
32
+ const seen = new Set<string>()
33
+ for (const run of passes) {
34
+ if (seen.has(run.tree)) continue
35
+ seen.add(run.tree)
36
+ if (seen.size > IGNORE_CANDIDATES) break
37
+ let changed: string[]
38
+ try {
39
+ changed = diff(run.tree, tree)
40
+ } catch {
41
+ continue // 树对象已被清理
42
+ }
43
+ if (changed.length > 0 && changed.every(isIgnored)) return { kind: 'ignored', run, changed }
44
+ }
45
+ return { kind: 'none' }
46
+ }
@@ -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