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,88 @@
1
+ // 检查模块交给底座的入口。底座(这个目录)不认识任何模块:合并门、停止门、会话说明、整组都按这里的入口去问,
2
+ // 模块(比如 ../pace 跑测试)把自己的实现登记进来。登记由装配的文件做(src/modules.ts),底座的代码不引用模块。
3
+ // 设计见仓库根目录的 整体设计方案.md。
4
+
5
+ import type { Repo } from './repo.ts'
6
+ import type { RunRecord } from './store.ts'
7
+
8
+ /** 整组里的一段:一条要跑的命令。kind 记进运行记录的分段用时(RunStep.kind),由模块自己定名字。 */
9
+ export interface FullStep {
10
+ kind: string
11
+ /** 耗时报告里这一段的名字:固定的,不带数量(比如"全部测试")。记进运行记录的分段用时(RunStep.name)。 */
12
+ name: string
13
+ /** 没通过时说的名字,比如"全部测试(12 个文件)"。 */
14
+ title: string
15
+ /** 写进日志的分隔行。 */
16
+ header: string
17
+ command: string
18
+ args: string[]
19
+ /** 这一段要借用工作区(比如建副本):底座把这一轮的运行 id 给它(见 execute.ts 的 RUN_ENV),它借用时不另占。只给测试之前跑的检查。 */
20
+ borrows?: boolean
21
+ }
22
+
23
+ /** 一个模块在这一轮整组里的部分。 */
24
+ export interface FullPart {
25
+ steps: FullStep[]
26
+ /** 整组通过时说的一小段,比如"12 个测试文件"。 */
27
+ summary?: string
28
+ /** 给这个模块各段命令的环境变量(比如交每个测试结果的位置)。 */
29
+ env?: Record<string, string>
30
+ /**
31
+ * 各段跑完(没被中断)以后:模块往这次的运行记录里加自己的字段(fields),在记录写下之后说给 agent 的话(notes,
32
+ * 拿得到写好的记录和这之前的全部记录)。
33
+ */
34
+ finish?(): { fields?: Record<string, unknown>; notes?(record: RunRecord, before: RunRecord[]): string[] }
35
+ /** 这一轮结束(不管怎么结束)时收拾模块自己的临时文件。 */
36
+ dispose?(): void
37
+ }
38
+
39
+ export interface Module {
40
+ name: string
41
+
42
+ /** testpace.json 里归这个模块的字段名:别的字段底座报"未知字段"。 */
43
+ fields?: readonly string[]
44
+ /** 这个模块的字段写得对不对(raw 是 testpace.json 的内容)。问题说给 agent,整组跑不了。 */
45
+ contractProblems?(raw: Record<string, unknown>): string[]
46
+
47
+ /**
48
+ * 会话说明:在这个仓库里干活要知道的规矩。会话开始、压缩后、会话第一次碰到这个仓库时说。label 是话里指这个仓库的写法;
49
+ * 给了 repo 就是在说那个仓库,模块没在那个仓库里启用的不用说。
50
+ */
51
+ brief?(label: string, repo?: Repo): string[]
52
+ /**
53
+ * 会话碰到这个工作区时(会话开始、每条命令之前、每次改文件之前都来):模块记下会话在这里的起点(比如这时测试的样子,
54
+ * 停止门只管这之后改的)。用底座的 SessionBaselines 记(baseline.ts):只记第一次,已经有了就不再算。
55
+ */
56
+ onSession?(repo: Repo, sessionId: string): void
57
+ /** 会话说明里跟在后面的提醒:这个仓库现在有什么要留意的(比如时好时坏的测试)。 */
58
+ alerts?(repo: Repo): string[]
59
+
60
+ /** 工具调用前:agent 要在 cwd 里跑这条命令时给它的提示。 */
61
+ beforeCommand?(command: string, cwd: string): string | undefined
62
+ /**
63
+ * 改文件之前:agent 要用改文件的工具新建或修改这个仓库里的 path(相对仓库根目录)。返回原因就拒绝这次改动,
64
+ * 话里要说清怎么改。每次改文件都会问,只做看路径、看要写的文字就能判断的事。text 是这次要写进文件的新文字
65
+ *(整份内容,或替换进去的那几段),拿不到时没有。
66
+ */
67
+ beforeEdit?(repo: Repo, path: string, text?: string): string | undefined
68
+
69
+ /**
70
+ * 停止门:这个会话在这个仓库里还有没处理完的事。keys 是这几件事各自的记号,底座记下拦过的,每件只拦一次
71
+ * (seen 是已经拦过的);named 为真时话里要写明是哪个仓库(会话不是在这个仓库里开始的)。
72
+ */
73
+ unfinished?(repo: Repo, sessionId: string, seen: readonly string[], named: boolean): { keys: string[]; text: string } | undefined
74
+
75
+ /** 整组里这个模块的部分;现在跑不了(配置不对、没有要跑的)时给出原因。 */
76
+ fullPart?(repo: Repo): FullPart | { problem: string }
77
+ }
78
+
79
+ let registered: Module[] = []
80
+
81
+ /** 登记这次运行里的模块(装配的文件调用,整份换掉)。 */
82
+ export function registerModules(modules: Module[]): void {
83
+ registered = modules
84
+ }
85
+
86
+ export function modules(): readonly Module[] {
87
+ return registered
88
+ }
@@ -0,0 +1,101 @@
1
+ // 在自己的进程组里起子进程,testpace 被中断时停掉整个组:它起的进程一起收到信号,不靠它转告;不肯退出的,过一会儿强杀整个组。
2
+ // 被中断时等整个组都退完才算结束,不只等直接起的那个进程:组里别的进程(测试框架跑测试的子进程、项目脚本起的服务)
3
+ // 可能晚一点才退,testpace 先退出的话,这个工作区看起来空了,其实它们还占着端口、测试库。
4
+ // 跑项目命令(execute.ts)和 testpace run 起框架(run/runner.ts)共用。
5
+
6
+ import { type StdioOptions, spawn } from 'node:child_process'
7
+
8
+ /** 跑项目命令时,中断后等子进程组自己退出的时间,过了就强杀。 */
9
+ export const COMMAND_KILL_AFTER_MS = 10_000
10
+ /**
11
+ * testpace run 起框架时的。要比跑项目命令的短:testpace run 写在项目命令里,是那个进程组里的一个进程,
12
+ * 框架却在自己的组里,强杀项目命令的组碰不到它。testpace run 先强杀框架,自己才不会被强杀时把框架留下。
13
+ */
14
+ export const FRAMEWORK_KILL_AFTER_MS = COMMAND_KILL_AFTER_MS - 2_000
15
+
16
+ export interface GroupOptions {
17
+ cwd: string
18
+ env: NodeJS.ProcessEnv
19
+ stdio: StdioOptions
20
+ /** testpace 被中断时(不管收到的是哪个信号)给整个组发的信号。 */
21
+ stopSignal: NodeJS.Signals
22
+ killAfterMs: number
23
+ /** 子进程起来、中断处理挂好之后调用,拿到进程组的 id。 */
24
+ onStart?: (group: number) => void
25
+ }
26
+
27
+ export interface GroupRun {
28
+ /** 正常退出时的退出码;被信号终止或没能启动时为 null。 */
29
+ exitCode: number | null
30
+ /** 子进程被信号终止时的信号名。 */
31
+ signal: NodeJS.Signals | null
32
+ /** testpace 自己被中断。 */
33
+ interrupted: boolean
34
+ /** 没能启动。 */
35
+ error?: NodeJS.ErrnoException
36
+ }
37
+
38
+ /** 强杀整个组以后,最多再等这么久:正常马上就没了,等不到(查不了这个组)也不卡住。 */
39
+ const AFTER_KILL_MS = 2_000
40
+ const POLL_MS = 20
41
+
42
+ /** 进程组里还有进程。查不了(没权限)也当还有。 */
43
+ function groupAlive(group: number): boolean {
44
+ try {
45
+ process.kill(-group, 0)
46
+ return true
47
+ } catch (error) {
48
+ return (error as NodeJS.ErrnoException).code === 'EPERM'
49
+ }
50
+ }
51
+
52
+ export function spawnGroup(program: string, args: string[], options: GroupOptions): Promise<GroupRun> {
53
+ const child = spawn(program, args, { cwd: options.cwd, env: options.env, stdio: options.stdio, detached: true })
54
+ let interrupted = false
55
+ /** 第一次被中断的时间:强杀的计时、等组退完的期限都从它算。 */
56
+ let interruptedAt = 0
57
+ const signalGroup = (signal: NodeJS.Signals): void => {
58
+ if (child.pid === undefined) return
59
+ try {
60
+ process.kill(-child.pid, signal)
61
+ } catch {
62
+ // 已经退出
63
+ }
64
+ }
65
+ // 每次收到都转给整个组(比如再按一次 Ctrl-C,框架会当成要它马上退);强杀的计时只从第一次算
66
+ const stop = (): void => {
67
+ if (!interrupted) {
68
+ interruptedAt = Date.now()
69
+ setTimeout(() => signalGroup('SIGKILL'), options.killAfterMs).unref()
70
+ }
71
+ interrupted = true
72
+ signalGroup(options.stopSignal)
73
+ }
74
+ const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'] as const
75
+ for (const signal of signals) process.on(signal, stop)
76
+ if (child.pid !== undefined) options.onStart?.(child.pid)
77
+
78
+ return new Promise(resolve => {
79
+ let done = false
80
+ const end = (run: Omit<GroupRun, 'interrupted'>): void => {
81
+ for (const signal of signals) process.off(signal, stop)
82
+ resolve({ ...run, interrupted })
83
+ }
84
+ const finish = (run: Omit<GroupRun, 'interrupted'>): void => {
85
+ if (done) return // 启动失败时 error 和 close 都会来
86
+ done = true
87
+ const group = child.pid
88
+ if (!interrupted || group === undefined) return end(run)
89
+ // 被中断:直接起的进程退了,等组里别的进程也退完。信号处理留着(再来一次照样转给组);
90
+ // 到强杀的时间还不退的由上面的计时强杀,强杀后再等一小会儿
91
+ const deadline = interruptedAt + options.killAfterMs + AFTER_KILL_MS
92
+ const wait = (): void => {
93
+ if (!groupAlive(group) || Date.now() >= deadline) return end(run)
94
+ setTimeout(wait, POLL_MS)
95
+ }
96
+ wait()
97
+ }
98
+ child.on('error', error => finish({ exitCode: null, signal: null, error }))
99
+ child.on('close', (exitCode, signal) => finish({ exitCode, signal }))
100
+ })
101
+ }
@@ -0,0 +1,66 @@
1
+ // 模块的记录:放在 .git/testpace/<模块>/<名字>.json,一个键一条,所有 worktree 共用。模块不自己写 .git 下的文件,都经这里。
2
+ // 按内容记的结论("这份内容检查过,通过")用 saveChecked:开始跑之前算出内容的标识当键,写之前再算一次,
3
+ // 变了就不写。跑的过程中内容改过的话,结论是按开始时的样子得出的,不是现在这份内容的。这条在这里统一做,模块不用各自核对。
4
+
5
+ import { createHash } from 'node:crypto'
6
+ import { existsSync, mkdirSync, readFileSync } from 'node:fs'
7
+ import { join } from 'node:path'
8
+ import { type Store, writeWhole } from './store.ts'
9
+
10
+ /** 几段内容合起来的摘要(32 位十六进制),当记录的键用。没有的那一段(undefined,比如文件不存在)和空内容不一样。 */
11
+ export function hash(...parts: Array<string | Buffer | undefined>): string {
12
+ const h = createHash('sha256')
13
+ for (const part of parts) {
14
+ h.update(part === undefined ? '\u0000missing' : part)
15
+ h.update('\u0000')
16
+ }
17
+ return h.digest('hex').slice(0, 32)
18
+ }
19
+
20
+ /** 记录留多久:太久以前的读不到,下次写回时清掉。 */
21
+ const KEEP_MS = 90 * 24 * 3600 * 1000
22
+
23
+ export class ModuleRecords<T extends { at: number }> {
24
+ private readonly file: string
25
+
26
+ /** module 是模块的名字,name 是这类记录的名字(比如 proofs)。 */
27
+ constructor(store: Store, module: string, name: string) {
28
+ this.file = join(store.dir, module, `${name}.json`)
29
+ }
30
+
31
+ private read(): Record<string, T> {
32
+ if (!existsSync(this.file)) return {}
33
+ let data: unknown
34
+ try {
35
+ data = JSON.parse(readFileSync(this.file, 'utf8'))
36
+ } catch {
37
+ return {}
38
+ }
39
+ if (typeof data !== 'object' || data === null || Array.isArray(data)) return {}
40
+ const since = Date.now() - KEEP_MS
41
+ return Object.fromEntries(Object.entries(data as Record<string, T>).filter(([, record]) => typeof record?.at === 'number' && record.at >= since))
42
+ }
43
+
44
+ /** 这个键的记录。键可能是外面传来的:只取文件里这个键自己的,不取对象原型上的东西。 */
45
+ get(key: string): T | undefined {
46
+ const all = this.read()
47
+ return Object.hasOwn(all, key) ? all[key] : undefined
48
+ }
49
+
50
+ /** 记下一条(不是按内容得出的结论,比如会话开始时的样子)。 */
51
+ put(key: string, record: T): void {
52
+ const all = this.read()
53
+ all[key] = record
54
+ mkdirSync(join(this.file, '..'), { recursive: true })
55
+ writeWhole(this.file, `${JSON.stringify(all, null, 1)}\n`)
56
+ }
57
+
58
+ /**
59
+ * 记下按内容得出的结论。key 是开始跑之前算的内容标识,current 现在再算一次:和 key 不一样(跑的过程中内容改过)就不记,返回 false。
60
+ */
61
+ saveChecked(key: string, current: () => string, record: T): boolean {
62
+ if (current() !== key) return false
63
+ this.put(key, record)
64
+ return true
65
+ }
66
+ }
@@ -0,0 +1,155 @@
1
+ // 命令行和 hook 共用的部分:找到仓库、判断通过记录、占住工作区跑命令。
2
+
3
+ import { readFileSync } from 'node:fs'
4
+ import { currentAgent } from './agent.ts'
5
+ import { CONTRACT_FILE } from './contract.ts'
6
+ import { type Coverage, findCoverage } from './coverage.ts'
7
+ import { failureExcerpt } from './excerpt.ts'
8
+ import { type Execution, execute, RUN_ENV } from './execute.ts'
9
+ import { duration, when } from './format.ts'
10
+ import { changedPaths, commonDir, defaultBranch, refTip, repoRoot } from './git.ts'
11
+ import { matcher } from './glob.ts'
12
+ import { isHold, newRunId, processAlive, type RunningMarker, type RunRecord, Store } from './store.ts'
13
+ import { VERSION } from './version.ts'
14
+
15
+ export interface Repo {
16
+ root: string
17
+ store: Store
18
+ }
19
+
20
+ export function openRepo(cwd: string): Repo | undefined {
21
+ const root = repoRoot(cwd)
22
+ return root ? { root, store: new Store(commonDir(root)) } : undefined
23
+ }
24
+
25
+ /**
26
+ * 约定里 ignore 的路径。testpace.json 自己不算:通过记录只在约定相同的代码之间沿用,
27
+ * 改了约定(包括改 ignore)要在改完的代码上重跑整组。
28
+ */
29
+ export function ignoredBy(ignore: string[]): (path: string) => boolean {
30
+ const ignored = matcher(ignore)
31
+ return path => path !== CONTRACT_FILE && ignored(path)
32
+ }
33
+
34
+ /** 这份内容有没有整组通过记录。ignore 是约定里不影响结果的路径(Contract.ignore)。 */
35
+ export function coverageOf(repo: Repo, ignore: string[], tree: string, runs: RunRecord[] = repo.store.readRuns()): Coverage {
36
+ return findCoverage(tree, runs, ignoredBy(ignore), (from, to) => changedPaths(repo.root, from, to))
37
+ }
38
+
39
+ export function describeCoverage(coverage: Coverage): string {
40
+ if (coverage.kind === 'none') return '没有整组通过记录'
41
+ const run = coverage.run
42
+ const base = `有整组通过记录(${when(run.startedAt)},用时 ${duration(run.durationMs)})`
43
+ if (coverage.kind === 'exact') return base
44
+ const sample = coverage.changed.slice(0, 3).join('、')
45
+ const more = coverage.changed.length > 3 ? ` 等 ${coverage.changed.length} 个` : ''
46
+ return `${base};相对那次只改了忽略路径:${sample}${more}`
47
+ }
48
+
49
+ /** 运行记录里谁跑的:哪个 agent(用户在终端里跑的没有)、哪一版 testpace。 */
50
+ export function runner(): Pick<RunRecord, 'agent' | 'version'> {
51
+ const agent = currentAgent()
52
+ return { ...(agent ? { agent: agent.kind } : {}), version: VERSION }
53
+ }
54
+
55
+ /** 本地和远程(origin)默认分支现在指向的提交,按引用名。找不到默认分支时为空。 */
56
+ export function defaultTips(repo: Repo): Record<string, string> {
57
+ const branch = defaultBranch(repo.root)
58
+ const tips: Record<string, string> = {}
59
+ for (const ref of branch ? [`refs/heads/${branch}`, `refs/remotes/origin/${branch}`] : []) {
60
+ const tip = refTip(repo.root, ref)
61
+ if (tip) tips[ref] = tip.commit
62
+ }
63
+ return tips
64
+ }
65
+
66
+ /**
67
+ * 在跑的那次是什么时候、哪个进程起的。testpace 被强杀后测试可能还在跑,说清楚怎么停。
68
+ * 借用工作区的登记只认那一个进程,列得出来就是它还在。
69
+ */
70
+ export function started(marker: RunningMarker): string {
71
+ const owner = isHold(marker) || processAlive(marker.pid)
72
+ ? `进程 ${marker.pid}`
73
+ : `起它的 testpace 已经退出,测试进程组 ${marker.group} 还在跑,不要了用 kill -- -${marker.group} 停掉`
74
+ return `开始于 ${when(marker.startedAt)},${owner}`
75
+ }
76
+
77
+ /** 这个工作区在跑的是哪种命令(或被谁借用着)、什么时候哪个进程起的。 */
78
+ export function runningText(marker: RunningMarker): string {
79
+ if (isHold(marker)) return `这个工作区正被 ${marker.by} 占着(${started(marker)})`
80
+ const what = marker.kind === 'full' ? '整组' : ` ${marker.kind} `
81
+ return `这个工作区正在跑${what}(${started(marker)})`
82
+ }
83
+
84
+ /** 因为这个工作区已经在跑测试而不跑时的说明。 */
85
+ export function busyText(marker: RunningMarker, tree: string): string {
86
+ if (isHold(marker)) return `${runningText(marker)},占着时不跑测试,等它放开再跑。`
87
+ const stale = marker.kind === 'full' && marker.tree !== tree ? '那次整组开始后代码改过,它跑完的结果不算当前代码的记录。' : ''
88
+ return `${runningText(marker)},同一个工作区一次只跑一轮测试,等它结束再跑。${stale}`
89
+ }
90
+
91
+ /**
92
+ * 占住这个工作区跑一次项目的命令,不记录。同一个工作区一次只跑一轮测试(两轮同时跑会抢端口、测试库这些资源,
93
+ * 失败了也分不清是谁的问题):已经有在跑的,不跑,返回它。
94
+ */
95
+ export async function runClaimed(
96
+ repo: Repo,
97
+ kind: string,
98
+ command: string,
99
+ args: string[],
100
+ tree: string,
101
+ env: Record<string, string> = {},
102
+ ): Promise<{ id: string; startedAt: number; log: string; execution: Execution } | { busy: RunningMarker }> {
103
+ const startedAt = Date.now()
104
+ const id = newRunId(startedAt)
105
+ const log = repo.store.logPath(id)
106
+ const busy = repo.store.claim({ id, kind, pid: process.pid, worktree: repo.root, tree, startedAt, log })
107
+ if (busy) return { busy }
108
+ try {
109
+ const execution = await execute(command, args, repo.root, log, group => repo.store.update(repo.root, id, { group }), env)
110
+ return { id, startedAt, log, execution }
111
+ } finally {
112
+ repo.store.release(repo.root, id)
113
+ }
114
+ }
115
+
116
+ /**
117
+ * 借用这个工作区(只占这个工作区,别的工作区不管):要复制或接着用工作区的时候用,比如建一次性副本。
118
+ * 借用期间别的 testpace 命令不跑,免得跑到一半的状态(锁文件、临时文件)被带进副本。
119
+ * 查有没有在跑的和占上是同一步(同 runClaimed 的登记),问完到用完之间不会有新起的插进来。
120
+ * 登记的是借用的那个进程(pid):它被杀了,占用跟着作废,不会把工作区永远锁住。
121
+ * 在跑的正是调用它的这一轮(环境变量 RUN_ENV 里的运行 id 和登记的一样)时不另占、没有 id:只有整组里测试之前的段拿得到它,
122
+ * 那时还没有测试在跑,工作区已经是这一轮的。已经有在跑的、被借用着的,返回它。
123
+ */
124
+ export function borrow(repo: Repo, pid: number, by: string): { id?: string } | { busy: RunningMarker } {
125
+ const current = repo.store.running().find(marker => marker.worktree === repo.root)
126
+ if (current && current.id === process.env[RUN_ENV]) return {}
127
+ const startedAt = Date.now()
128
+ const id = newRunId(startedAt)
129
+ const busy = repo.store.claim({ id, kind: 'hold', by, pid, worktree: repo.root, startedAt })
130
+ return busy ? { busy } : { id }
131
+ }
132
+
133
+ /** 放开 borrow 占的工作区。只放借用的登记:跑着的命令自己结束时放开。已经放开、借用的进程已经不在的,什么也不做。 */
134
+ export function giveBack(repo: Repo, id: string): void {
135
+ const current = repo.store.running().find(marker => marker.worktree === repo.root)
136
+ if (current && isHold(current) && current.id === id) repo.store.release(repo.root, id)
137
+ }
138
+
139
+ /** 命令为什么算失败:退出码、信号,或没能启动。 */
140
+ export function failureCause(execution: Execution): string {
141
+ if (execution.exitCode !== null) return `退出码 ${execution.exitCode}`
142
+ return execution.signal ? `被信号 ${execution.signal} 终止` : '命令没能启动'
143
+ }
144
+
145
+ /** 失败时的输出:结论、节选和日志路径。 */
146
+ /** from:从日志的这个位置(字节)起节选,比如只看没通过的那一段的输出。 */
147
+ export function failureText(title: string, log: string, execution: Execution, from = 0): string {
148
+ return [
149
+ `${title}(${failureCause(execution)})· 用时 ${duration(execution.durationMs)}`,
150
+ '--- 输出节选 ---',
151
+ ...failureExcerpt(readFileSync(log).subarray(from).toString('utf8')),
152
+ '---',
153
+ `完整日志:${log}`,
154
+ ].join('\n')
155
+ }
@@ -0,0 +1,55 @@
1
+ // 会话碰过哪些接入了 testpace 的仓库。记在插件数据目录(agent 给 hook 的 CLAUDE_PLUGIN_DATA,Claude Code 和 Codex 都给;
2
+ // Codex 实测是 ~/.codex/plugins/data/<插件>-<市场>。Antigravity 给的是 PLUGIN_DATA,文档说装好的插件才有)里,不在哪个仓库里:会话从仓库外(比如上一级目录)开始时,
3
+ // 压缩后补说节奏、停止门都靠它找到仓库。没有插件数据目录(不在 hook 里)时不记,只认会话所在目录的仓库。
4
+
5
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'node:fs'
6
+ import { join } from 'node:path'
7
+ import { SESSION_KEEP_MS, writeWhole } from './store.ts'
8
+
9
+ interface SessionRepos {
10
+ updatedAt: number
11
+ repos: string[]
12
+ }
13
+
14
+ function sessionsDir(): string | undefined {
15
+ const data = process.env.CLAUDE_PLUGIN_DATA || process.env.PLUGIN_DATA
16
+ return data ? join(data, 'sessions') : undefined
17
+ }
18
+
19
+ function fileOf(dir: string, id: string): string {
20
+ return join(dir, `${id.replace(/[^\w.-]/g, '_')}.json`)
21
+ }
22
+
23
+ function read(path: string): SessionRepos | undefined {
24
+ try {
25
+ return JSON.parse(readFileSync(path, 'utf8')) as SessionRepos
26
+ } catch {
27
+ return undefined
28
+ }
29
+ }
30
+
31
+ /** 这个会话碰过的仓库根目录。 */
32
+ export function sessionRepos(id: string): string[] {
33
+ const dir = sessionsDir()
34
+ if (!dir) return []
35
+ return read(fileOf(dir, id))?.repos ?? []
36
+ }
37
+
38
+ /** 记下这个会话碰到的仓库;第一次记这个会话时顺手清掉过期的会话。 */
39
+ export function noteSessionRepos(id: string, roots: string[], now: number): void {
40
+ const dir = sessionsDir()
41
+ if (!dir || roots.length === 0) return
42
+ const path = fileOf(dir, id)
43
+ const known = existsSync(path) ? read(path) : undefined
44
+ if (known && roots.every(root => known.repos.includes(root))) return
45
+ mkdirSync(dir, { recursive: true })
46
+ if (!known) {
47
+ for (const name of readdirSync(dir).filter(name => name.endsWith('.json'))) {
48
+ const file = join(dir, name)
49
+ const state = read(file)
50
+ if (!state || now - state.updatedAt > SESSION_KEEP_MS) rmSync(file, { force: true })
51
+ }
52
+ }
53
+ const repos = [...new Set([...(known?.repos ?? []), ...roots])]
54
+ writeWhole(path, JSON.stringify({ updatedAt: now, repos } satisfies SessionRepos))
55
+ }
@@ -0,0 +1,176 @@
1
+ // 大致读懂 agent 要跑的 Bash 命令:拆成一条条命令,跟着 cd 算出每条在哪个目录跑。
2
+ // 只用于提示(节奏说明、直接跑整组命令时的提醒、前台跑完整组算看过结果),不用来把关:
3
+ // 引号、转义、&& || ; | & 换行、cd、环境变量前缀、sh -c。
4
+
5
+ import { homedir } from 'node:os'
6
+ import { basename, resolve } from 'node:path'
7
+
8
+ export interface Invocation {
9
+ cwd: string
10
+ argv: string[]
11
+ }
12
+
13
+ const OPERATORS = ['&&', '||', ';;', ';', '|&', '|', '&', '\n', '(', ')']
14
+
15
+ /** 重定向:`>`、`2>&1`、`&>file`、`<<EOF` 这类。不带目标时目标是下一个词。 */
16
+ const REDIRECT = /^(?:\d+|&)?(?:>>|>&|>\||>|<<<|<<-?|<&|<>|<)(.*)$/s
17
+ const HEREDOC = /^\d*<<(?!<)(-?)(.*)$/s
18
+
19
+ /**
20
+ * 拆成词和操作符,不做展开:变量、反引号原样留在词里;$(...) 的括号按操作符拆开,里面的命令也当成命令。
21
+ * here-document 的正文跳过:它是给命令的输入,不是命令。
22
+ */
23
+ export function tokenize(command: string): string[] {
24
+ const tokens: string[] = []
25
+ let word = ''
26
+ let inWord = false
27
+ // 等下一个换行之后跳过正文的 here-document,以及 `<< EOF` 写法里还没读到的结束符
28
+ const heredocs: Array<{ delimiter: string; strip: boolean }> = []
29
+ let pendingStrip: boolean | undefined
30
+ const push = (): void => {
31
+ if (inWord) {
32
+ if (pendingStrip !== undefined) {
33
+ heredocs.push({ delimiter: word, strip: pendingStrip })
34
+ pendingStrip = undefined
35
+ } else {
36
+ const heredoc = HEREDOC.exec(word)
37
+ if (heredoc) {
38
+ if (heredoc[2]) heredocs.push({ delimiter: heredoc[2], strip: heredoc[1] === '-' })
39
+ else pendingStrip = heredoc[1] === '-'
40
+ }
41
+ }
42
+ tokens.push(word)
43
+ }
44
+ word = ''
45
+ inWord = false
46
+ }
47
+ const skipHeredocs = (from: number): number => {
48
+ let at = from
49
+ for (const { delimiter, strip } of heredocs.splice(0)) {
50
+ while (at < command.length) {
51
+ const end = command.indexOf('\n', at)
52
+ const line = command.slice(at, end === -1 ? command.length : end)
53
+ at = end === -1 ? command.length : end + 1
54
+ if ((strip ? line.replace(/^\t+/, '') : line) === delimiter) break
55
+ }
56
+ }
57
+ return at
58
+ }
59
+ for (let i = 0; i < command.length; i++) {
60
+ const c = command[i]!
61
+ if (c === "'") {
62
+ const end = command.indexOf("'", i + 1)
63
+ const stop = end === -1 ? command.length : end
64
+ word += command.slice(i + 1, stop)
65
+ inWord = true
66
+ i = stop
67
+ } else if (c === '"') {
68
+ inWord = true
69
+ for (i++; i < command.length && command[i] !== '"'; i++) {
70
+ if (command[i] === '\\' && i + 1 < command.length && '"\\$`\n'.includes(command[i + 1]!)) i++
71
+ word += command[i]
72
+ }
73
+ } else if (c === '\\') {
74
+ if (command[i + 1] === '\n') i++
75
+ else if (i + 1 < command.length) {
76
+ word += command[++i]
77
+ inWord = true
78
+ }
79
+ } else if (c === '#' && !inWord) {
80
+ const end = command.indexOf('\n', i)
81
+ i = (end === -1 ? command.length : end) - 1
82
+ } else if (c === ' ' || c === '\t') {
83
+ push()
84
+ } else if (c === '&' && ((inWord && /[<>]$/.test(word)) || command[i + 1] === '>')) {
85
+ // 2>&1、>&2、&>file 是重定向,不是后台运行
86
+ word += c
87
+ inWord = true
88
+ } else if (c === '\n') {
89
+ push()
90
+ tokens.push('\n')
91
+ if (heredocs.length > 0) i = skipHeredocs(i + 1) - 1
92
+ } else {
93
+ const op = OPERATORS.find(o => command.startsWith(o, i))
94
+ if (op) {
95
+ push()
96
+ tokens.push(op)
97
+ i += op.length - 1
98
+ } else {
99
+ word += c
100
+ inWord = true
101
+ }
102
+ }
103
+ }
104
+ push()
105
+ return tokens
106
+ }
107
+
108
+ /** 去掉重定向和它的目标。 */
109
+ function withoutRedirects(argv: string[]): string[] {
110
+ const out: string[] = []
111
+ for (let i = 0; i < argv.length; i++) {
112
+ const redirect = REDIRECT.exec(argv[i]!)
113
+ if (!redirect) out.push(argv[i]!)
114
+ else if (redirect[1] === '') i++
115
+ }
116
+ return out
117
+ }
118
+
119
+ const WRAPPERS = new Set(['command', 'exec', 'nohup', 'time', 'builtin'])
120
+
121
+ function expandHome(path: string): string {
122
+ return path === '~' ? homedir() : path.startsWith('~/') ? homedir() + path.slice(1) : path
123
+ }
124
+
125
+ /** 命令里的每条程序调用和它的工作目录。 */
126
+ export function invocations(command: string, cwd: string): Invocation[] {
127
+ const result: Invocation[] = []
128
+ let here = cwd
129
+ let segment: string[] = []
130
+ const flush = (): void => {
131
+ let argv = withoutRedirects(segment)
132
+ segment = []
133
+ // 跳过环境变量前缀和 env、command 这类包装
134
+ for (;;) {
135
+ if (argv.length > 0 && /^[A-Za-z_][A-Za-z0-9_]*=/.test(argv[0]!)) argv = argv.slice(1)
136
+ else if (argv[0] === 'env') {
137
+ argv = argv.slice(1)
138
+ while (argv.length > 0 && (argv[0]!.startsWith('-') || /^[A-Za-z_][A-Za-z0-9_]*=/.test(argv[0]!))) argv = argv.slice(1)
139
+ } else if (argv.length > 0 && WRAPPERS.has(argv[0]!)) argv = argv.slice(1)
140
+ else break
141
+ }
142
+ if (argv.length === 0) return
143
+ const program = basename(argv[0]!)
144
+ if (program === 'cd') {
145
+ // 目录要展开才知道(cd "$DIR"、cd $(git rev-parse --show-toplevel))的,算不出来,当作没动
146
+ const target = argv[1] ?? '~'
147
+ if (!/[$`]/.test(target)) here = resolve(here, expandHome(target))
148
+ return
149
+ }
150
+ if (['sh', 'bash', 'zsh', 'dash'].includes(program)) {
151
+ const c = argv.indexOf('-c')
152
+ if (c !== -1 && argv[c + 1] !== undefined) {
153
+ result.push(...invocations(argv[c + 1]!, here))
154
+ return
155
+ }
156
+ }
157
+ result.push({ cwd: here, argv })
158
+ }
159
+ for (const token of tokenize(command)) {
160
+ if (OPERATORS.includes(token)) flush()
161
+ else segment.push(token)
162
+ }
163
+ flush()
164
+ return result
165
+ }
166
+
167
+ /** command 里有没有按顺序、连着跑 target 的每条命令(参数完全一样)。 */
168
+ export function runsCommand(command: string, target: string, cwd: string): boolean {
169
+ const want = invocations(target, cwd).map(call => call.argv.join('\0'))
170
+ const have = invocations(command, cwd).map(call => call.argv.join('\0'))
171
+ if (want.length === 0) return false
172
+ for (let i = 0; i + want.length <= have.length; i++) {
173
+ if (want.every((argv, j) => have[i + j] === argv)) return true
174
+ }
175
+ return false
176
+ }