gatelight 0.19.2 → 0.39.1

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 (62) hide show
  1. package/.antigravity-plugin/plugin.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.codex-plugin/plugin.json +1 -1
  4. package/README.md +2 -2
  5. package/package.json +1 -1
  6. package/skills/merge/SKILL.md +1 -1
  7. package/skills/modular/SKILL.md +6 -6
  8. package/skills/setup/SKILL.md +2 -2
  9. package/skills/setup-codekeep/SKILL.md +61 -17
  10. package/skills/setup-codekeep/frontend.eslint.mjs +285 -0
  11. package/skills/setup-modwall/SKILL.md +10 -11
  12. package/skills/setup-testcraft/SKILL.md +9 -3
  13. package/skills/setup-testcraft/checklist/dev-login.md +3 -3
  14. package/skills/setup-testcraft/checklist/same-number.md +26 -0
  15. package/skills/write-tests/SKILL.md +13 -12
  16. package/src/base/baseline.ts +2 -2
  17. package/src/base/commands.ts +2 -40
  18. package/src/base/execute.ts +1 -11
  19. package/src/base/exit.ts +1 -1
  20. package/src/base/full.ts +15 -11
  21. package/src/base/git.ts +34 -3
  22. package/src/base/hook.ts +71 -17
  23. package/src/base/hookformat.ts +16 -6
  24. package/src/base/module.ts +9 -7
  25. package/src/base/repo.ts +8 -34
  26. package/src/base/sessions.ts +45 -13
  27. package/src/base/shell.ts +18 -10
  28. package/src/base/stop.ts +20 -6
  29. package/src/base/store.ts +15 -30
  30. package/src/cli.ts +3 -16
  31. package/src/craft/commands.ts +7 -1
  32. package/src/craft/defaults.ts +59 -0
  33. package/src/craft/session.ts +8 -4
  34. package/src/keep/check.ts +78 -39
  35. package/src/keep/config.ts +56 -26
  36. package/src/keep/eslint.ts +130 -5
  37. package/src/keep/loosen.ts +11 -61
  38. package/src/keep/session.ts +19 -5
  39. package/src/keep/styles.ts +72 -0
  40. package/src/pace/commands.ts +9 -3
  41. package/src/pace/full.ts +16 -6
  42. package/src/pace/index.ts +3 -0
  43. package/src/pace/record.ts +12 -6
  44. package/src/pace/results.ts +43 -2
  45. package/src/pace/run/playwright-reporter.mjs +5 -4
  46. package/src/pace/run/runner.ts +13 -7
  47. package/src/pace/run/targets.ts +3 -2
  48. package/src/pace/session.ts +3 -3
  49. package/src/pace/unfinished.ts +87 -0
  50. package/src/pace/unmerged.ts +87 -0
  51. package/src/pace/verify.ts +2 -2
  52. package/src/wall/commands.ts +94 -26
  53. package/src/wall/database.ts +12 -1
  54. package/src/wall/dbcheck.ts +2 -2
  55. package/src/wall/dbrules.ts +60 -19
  56. package/src/wall/full.ts +6 -1
  57. package/src/wall/literals.ts +162 -0
  58. package/src/wall/migrate.ts +248 -0
  59. package/src/wall/project.ts +29 -9
  60. package/src/wall/receipt.ts +74 -0
  61. package/src/wall/session.ts +5 -5
  62. package/src/wall/store.ts +3 -1
package/src/base/hook.ts CHANGED
@@ -10,14 +10,14 @@ import { fileURLToPath } from 'node:url'
10
10
  import { AGENTS, type AgentKind } from './agent.ts'
11
11
  import { CONFIRM_TOOL } from './confirm.ts'
12
12
  import { CONTRACT_FILE, joined, loadContract } from './contract.ts'
13
- import { entriesNotPlaced, entryDir, refreshEntries } from './entry.ts'
13
+ import { ENTRY_COMMANDS, type EntryCommand, entriesNotPlaced, entryDir, refreshEntries } from './entry.ts'
14
14
  import { ensureGate, gateProblem } from './gate.ts'
15
15
  import { git } from './git.ts'
16
16
  import type { HookEvent, HookVerdict } from './hookformat.ts'
17
17
  import { modules } from './module.ts'
18
18
  import { defaultTips, openRepo, type Repo } from './repo.ts'
19
- import { noteSessionRepos, sessionRepos } from './sessions.ts'
20
- import { invocations } from './shell.ts'
19
+ import { noteSessionRepos, sessionHome, sessionRepos } from './sessions.ts'
20
+ import { type Invocation, invocations } from './shell.ts'
21
21
  import { PLUGIN_NAME } from './version.ts'
22
22
  import { stopCheck } from './stop.ts'
23
23
  import type { SessionState } from './store.ts'
@@ -55,6 +55,49 @@ function noteWorking(repo: Repo, sessionId: string, now: number): void {
55
55
  repo.store.saveSession(sessionId, { ...state, worked: [...(state.worked ?? []), repo.root] })
56
56
  }
57
57
 
58
+ /** 这个会话在这个工作区动了一次手(停止门靠它分清内容的变化是不是这个会话的,见 stop.ts)。 */
59
+ function noteActing(repo: Repo, sessionId: string, now: number): void {
60
+ const state = repo.store.session(sessionId, now, () => defaultTips(repo))
61
+ const acted = state.acted ?? {}
62
+ repo.store.saveSession(sessionId, { ...state, acted: { ...acted, [repo.root]: (acted[repo.root] ?? 0) + 1 } })
63
+ }
64
+
65
+ /** 只看、不改内容的程序(往文件里写的重定向另算)。 */
66
+ const READERS = new Set([
67
+ ...['ls', 'cat', 'head', 'tail', 'wc', 'grep', 'egrep', 'fgrep', 'rg', 'tree', 'stat', 'file', 'du', 'pwd', 'echo', 'printf'],
68
+ ...['diff', 'cmp', 'less', 'more', 'jq', 'which', 'type', 'basename', 'dirname', 'realpath', 'readlink', 'date', 'true', 'cut', 'tr'],
69
+ ])
70
+ /** 只看的 git 子命令。 */
71
+ const GIT_READS = new Set(['status', 'log', 'diff', 'show', 'blame', 'rev-parse', 'ls-files', 'ls-tree', 'grep', 'merge-base', 'rev-list', 'describe', 'cat-file', 'shortlog'])
72
+ /** gatelight 只做检查的子命令(会写配置的 modwall init、testpace install 这类不在里面)。 */
73
+ const CHECKS: Record<EntryCommand, readonly string[]> = {
74
+ testpace: ['focused', 'files', 'full', 'status', 'report', 'verify'],
75
+ modwall: ['check', 'status', 'db check'],
76
+ codekeep: ['check'],
77
+ testcraft: ['checklist', 'status'],
78
+ }
79
+
80
+ /** 去掉 git 自己的选项(-C 目录、-c 配置、--no-pager 这类),剩下的从子命令开始。 */
81
+ function gitArgs(args: string[]): string[] {
82
+ let at = 0
83
+ while (at < args.length && args[at]!.startsWith('-')) at += ['-C', '-c'].includes(args[at]!) ? 2 : 1
84
+ return args.slice(at)
85
+ }
86
+
87
+ /** 这次调用只看、不改内容。 */
88
+ function readsOnly({ argv, writes }: Invocation): boolean {
89
+ if (writes) return false
90
+ const program = basename(argv[0] ?? '')
91
+ const args = argv.slice(1)
92
+ if (READERS.has(program)) return true
93
+ if (program === 'sed') return !args.some(arg => /^-[^-]*[iI]/.test(arg) || arg.startsWith('--in-place'))
94
+ if (program === 'sort') return !args.some(arg => /^-[^-]*o/.test(arg) || arg.startsWith('--output'))
95
+ if (program === 'find') return !args.some(arg => /^-(?:exec|execdir|ok|okdir|delete|fprint|fprint0|fprintf|fls)$/.test(arg))
96
+ if (program === 'git') return GIT_READS.has(gitArgs(args)[0] ?? '')
97
+ const checks = (ENTRY_COMMANDS as readonly string[]).includes(program) ? CHECKS[program as EntryCommand] : undefined
98
+ return checks?.some(check => args.slice(0, check.split(' ').length).join(' ') === check) ?? false
99
+ }
100
+
58
101
  /** 新仓库最多这么多个提交:还没接入时,会话开始就提出接入。老仓库要先改造,不在这里提。 */
59
102
  export const NEW_REPO_COMMITS = 20
60
103
 
@@ -124,19 +167,27 @@ function contractRepos(dirs: Iterable<string>): Repo[] {
124
167
  }
125
168
 
126
169
  /**
127
- * 这条命令碰到的接入仓库(会话所在目录和命令里 cd 进去的目录;同一条命令里多数调用在同一个目录,按目录去重)。
170
+ * 这条命令碰到的接入仓库(这次 hook 给的目录和命令里 cd 进去的目录;同一条命令里多数调用在同一个目录,按目录去重)。
128
171
  * 每个仓库都记下会话,插件数据目录里记下会话碰过它;每个工作区都让各模块记下会话在那里的起点(节奏按仓库说一次,起点按工作区各记一份:
129
172
  * 同一个仓库的另一个工作区不会再说节奏,起点照样要记)。会话所在目录的工作区记成它干活的地方;cd 进去的不算(noteWorking)。
130
- * 返回还没给这个会话说过节奏的。
173
+ * 不只是看的调用,在它所在的工作区记一次动手(noteActing)。返回还没给这个会话说过节奏的。
131
174
  * 已知的缺口:会话没进某个工作区、从外面按路径往里写了文件(cp、重定向这类),这里看不到,那个工作区的起点要到会话进去时才记,
132
- * 已经带着它写的东西;停止门不提醒这一部分,合并前的整组照样查(整体设计方案 9.4)。
175
+ * 已经带着它写的东西;停止门不提醒这一部分,合并前的整组照样查。
176
+ * 还有一处:cd 进别的工作区、只用命令(sed -i、git cherry-pick 这类)改的,那里不算干活的地方,停止门不为它问;
177
+ * 用改文件的工具改的照样算。不只是看的命令里也有不改代码的(装依赖、构建、跑别的测试),按它认干活的地方,
178
+ * 去别人的工作区帮着跑一下就会被那里的改动拦,所以不补。
179
+ * 试过按字面认命令里别的工作区的路径来补:相对路径、软链认不出,只提到路径也会提前记起点成误报;每条命令前后各比一次各工作区又拖慢每条命令,所以不补。
133
180
  */
134
- function untoldRepos(command: string, cwd: string, sessionId: string, now: number): Array<{ repo: Repo; state: SessionState }> {
135
- const repos = contractRepos([cwd, ...invocations(command, cwd).map(call => call.cwd)])
181
+ function untoldRepos(command: string, cwd: string, home: string, sessionId: string, now: number): Array<{ repo: Repo; state: SessionState }> {
182
+ const calls = invocations(command, cwd)
183
+ const repos = contractRepos([cwd, ...calls.map(call => call.cwd)])
136
184
  noteSessionRepos(sessionId, repos.map(repo => repo.root), now)
137
- const here = openRepo(cwd)?.root
138
- const home = repos.find(repo => repo.root === here)
139
- if (home) noteWorking(home, sessionId, now)
185
+ // 只看的命令不算动手:算的话,同一个工作区里别人一改内容,停止门就又为会话看过的东西拦它(被拦后照话跑检查也一样,拦成循环)。
186
+ const acting = calls.filter(call => !readsOnly(call))
187
+ for (const repo of contractRepos(acting.map(call => call.cwd))) noteActing(repo, sessionId, now)
188
+ const here = openRepo(home)?.root
189
+ const homeRepo = repos.find(repo => repo.root === here)
190
+ if (homeRepo) noteWorking(homeRepo, sessionId, now)
140
191
  const untold: Array<{ repo: Repo; state: SessionState }> = []
141
192
  for (const repo of repos) {
142
193
  const state = repo.store.session(sessionId, now, () => defaultTips(repo))
@@ -154,6 +205,7 @@ function noteEditing(repo: Repo, sessionId: string, now: number): void {
154
205
  noteSession(repo, sessionId)
155
206
  noteSessionRepos(sessionId, [repo.root], now)
156
207
  noteWorking(repo, sessionId, now)
208
+ noteActing(repo, sessionId, now)
157
209
  }
158
210
 
159
211
  /**
@@ -192,6 +244,8 @@ function editRefusal({ repo, path }: { repo: Repo; path: string }, text: string
192
244
  */
193
245
  export function judge(event: HookEvent, now: number, agent: AgentKind): HookVerdict | undefined {
194
246
  const { cwd, sessionId } = event
247
+ // 会话所在目录按第一次见到时的认(sessions.ts 的 sessionHome);cwd 是这次 hook 给的目录,解析命令、相对路径用它
248
+ const home = event.kind === 'confirm' ? cwd : sessionHome(sessionId, cwd, now)
195
249
 
196
250
  // 确认工具:用户当场在弹窗里看到原文、点了同意才执行。没填原文的不弹空窗,拒掉让 agent 照检查输出填
197
251
  if (event.kind === 'confirm') {
@@ -202,9 +256,9 @@ export function judge(event: HookEvent, now: number, agent: AgentKind): HookVerd
202
256
  // 旧版本放的固定入口先换成这一版的:下面的会话说明、之后的命令和合并门的钩子都靠它们找到命令
203
257
  refreshEntries()
204
258
  // 会话所在目录的仓库,加上会话之前碰过的仓库(压缩、恢复后重新开始时上下文里的节奏说明可能没了)。
205
- const hereRepo = openRepo(cwd)
259
+ const hereRepo = openRepo(home)
206
260
  const here = hereRepo?.root
207
- const repos = contractRepos([cwd, ...sessionRepos(sessionId)])
261
+ const repos = contractRepos([home, cwd, ...sessionRepos(sessionId)])
208
262
  const fresh = hereRepo && !joined(hereRepo.root) && isNewRepo(hereRepo.root) ? hereRepo : undefined
209
263
  if (repos.length === 0 && !fresh) return undefined
210
264
  // 用得上合并门的会话里自动配上它,只告诉用户一声
@@ -243,7 +297,7 @@ export function judge(event: HookEvent, now: number, agent: AgentKind): HookVerd
243
297
  if (event.kind === 'command') {
244
298
  // 记下会话第一次出现的时间:停止门只管这之后起的整组。会话不在仓库里开始(会话开始时没说节奏)时,
245
299
  // 第一次碰到接入的仓库就补说一次。
246
- const untold = untoldRepos(event.command, cwd, sessionId, now)
300
+ const untold = untoldRepos(event.command, cwd, home, sessionId, now)
247
301
  for (const { repo, state } of untold) repo.store.saveSession(sessionId, { ...state, rhythm: true })
248
302
  const briefs = untold.map(({ repo }) => told(repo, agent, `${repo.root} 这个仓库`))
249
303
  let hints = modules().flatMap(module => module.beforeCommand?.(event.command, cwd) ?? [])
@@ -273,11 +327,11 @@ export function judge(event: HookEvent, now: number, agent: AgentKind): HookVerd
273
327
  }
274
328
 
275
329
  // 要结束这一轮:会话所在目录的仓库和会话碰过的仓库都查;不是所在目录的,话里写上是哪个仓库。
276
- const here = openRepo(cwd)?.root
330
+ const here = openRepo(home)?.root
277
331
  const blocks: string[] = []
278
332
  const warns: string[] = []
279
- for (const repo of contractRepos([cwd, ...sessionRepos(sessionId)])) {
280
- const result = stopCheck({ sessionId, cwd: repo.root, now, named: repo.root !== here })
333
+ for (const repo of contractRepos([home, cwd, ...sessionRepos(sessionId)])) {
334
+ const result = stopCheck({ sessionId, cwd: repo.root, now, named: repo.root !== here, ...(event.busy ? { busy: true } : {}) })
281
335
  if (result.block) blocks.push(result.block)
282
336
  if (result.warn) warns.push(result.warn)
283
337
  }
@@ -8,7 +8,7 @@ import { PLUGIN_NAME } from './version.ts'
8
8
 
9
9
  interface Session {
10
10
  sessionId: string
11
- /** 会话所在目录。 */
11
+ /** 这次 hook 给的目录:agent 现在所在的目录(cd 会留住,会话所在目录按第一次见到的认,见 sessions.ts 的 sessionHome)。 */
12
12
  cwd: string
13
13
  }
14
14
 
@@ -16,7 +16,7 @@ interface Session {
16
16
  export type HookEvent = Session &
17
17
  (
18
18
  | { kind: 'start' }
19
- /** 要用改文件的工具改一个文件:路径(相对会话所在目录,或绝对路径),和这次要写进去的新文字(拿得到时)。可以拒绝。 */
19
+ /** 要用改文件的工具改一个文件:路径(相对 cwd,或绝对路径),和这次要写进去的新文字(拿得到时)。可以拒绝。 */
20
20
  | { kind: 'edit'; file: string; text?: string }
21
21
  /** 要用一段补丁改这几个文件(Codex 的 apply_patch):只记下改到的工作区,不检查(一段补丁里有几个文件,修改的部分只有差异)。 */
22
22
  | { kind: 'patch'; files: string[] }
@@ -24,7 +24,8 @@ export type HookEvent = Session &
24
24
  | { kind: 'command'; command: string }
25
25
  /** 一条命令执行完了。放到后台的,agent 这时还没看到它的输出。 */
26
26
  | { kind: 'ran'; command: string; background: boolean }
27
- | { kind: 'stop' }
27
+ /** 要结束这一轮。busy:会话放到后台的 agent(子代理、workflow、队友)还在干活,这一轮结束不是活干完了,它们干完会再叫醒会话。 */
28
+ | { kind: 'stop'; busy?: boolean }
28
29
  /**
29
30
  * 要调 gatelight 自己的 MCP 服务(src/mcp.ts,只有确认工具 confirm_with_user):text 是要给用户看的原文(调用里填的,没填是 undefined)。
30
31
  * 只有工具自己不能保证每次弹窗的 agent 才读出这种事件(Antigravity);Claude Code 靠工具自己的标记弹窗,不经过 hook。
@@ -67,8 +68,13 @@ interface ClaudeInput {
67
68
  tool_name?: string
68
69
  tool_input?: { command?: unknown; run_in_background?: unknown; file_path?: unknown; content?: unknown; new_string?: unknown; edits?: unknown }
69
70
  tool_response?: unknown
71
+ /** Stop 时还在跑的后台任务(Claude Code 给;老版本没有这个字段)。type 是 subagent、workflow、teammate、shell、monitor 这类。 */
72
+ background_tasks?: Array<{ type?: unknown }>
70
73
  }
71
74
 
75
+ /** 会在本机替会话改文件、跑命令的后台任务。shell、monitor 不算:开着的开发服务、监视器会一直在,算上它们停止门就再也不问了。 */
76
+ const WORKING_TASKS = new Set(['subagent', 'workflow', 'teammate'])
77
+
72
78
  /** 改文件的工具(Claude Code 的,和 hooks.json 里的 matcher 一样)。Codex 的 apply_patch 另算(patchFiles)。 */
73
79
  const EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit'])
74
80
 
@@ -88,7 +94,7 @@ function writtenText(input: ClaudeInput['tool_input']): string | undefined {
88
94
 
89
95
  /**
90
96
  * Codex 的 apply_patch 补丁(tool_input.command 是补丁正文)要改的文件:新建、修改、删除的,和改名后的新路径。
91
- * 路径相对会话所在目录,也可以是绝对路径。
97
+ * 路径相对 cwd,也可以是绝对路径。
92
98
  */
93
99
  function patchFiles(patch: string): string[] {
94
100
  return patch.split('\n').flatMap(line => /^\*\*\* (?:(?:Add|Update|Delete) File|Move to): (.+?)\s*$/.exec(line)?.[1] ?? [])
@@ -112,7 +118,10 @@ export const CLAUDE_HOOKS: HookFormat = {
112
118
  const session: Session = { sessionId: input.session_id ?? 'unknown', cwd: input.cwd ?? process.cwd() }
113
119
  const event = input.hook_event_name
114
120
  if (event === 'SessionStart') return { ...session, kind: 'start' }
115
- if (event === 'Stop') return { ...session, kind: 'stop' }
121
+ if (event === 'Stop') {
122
+ const busy = Array.isArray(input.background_tasks) && input.background_tasks.some(task => WORKING_TASKS.has(task?.type as string))
123
+ return { ...session, kind: 'stop', ...(busy ? { busy } : {}) }
124
+ }
116
125
  const tool = input.tool_name ?? ''
117
126
  if (event === 'PreToolUse' && EDIT_TOOLS.has(tool)) {
118
127
  const file = input.tool_input?.file_path
@@ -199,7 +208,7 @@ function oneParagraph(text: string): string {
199
208
  }
200
209
 
201
210
  /**
202
- * Antigravity(桌面 App)的 hook 格式,按 2026-11-24 的实测(Antigravity适配方案.md 1.1):
211
+ * Antigravity(桌面 App)的 hook 格式,按 2026-11-24 的实测:
203
212
  * - 跑命令是 run_command(args.CommandLine);改文件的专门工具只有 write_file(args.Path 是绝对路径、args.Content)和
204
213
  * edit_file(args.Path、args.Replacement 是换进去的文字;它的输入没实际见过,照工具定义)。删文件、移动文件只能走 run_command,和 Claude Code 下走 Bash 一样不在改文件的检查里。
205
214
  * - 不干预时什么都不能输出:PreToolUse 输出 {}、空的 decision、退出码非 0 都会把这次工具调用拦掉。所以这里没有要说的就返回 undefined,
@@ -244,6 +253,7 @@ export const ANTIGRAVITY_HOOKS: HookFormat = {
244
253
  ]
245
254
  return steps.length > 0 ? { injectSteps: steps } : undefined
246
255
  }
256
+ // Stop 的输出里没有只给用户看、不拦的写法:提醒类的话只能不说,并进 reason 就成了拦 agent
247
257
  if (event.kind === 'stop') return verdict.block ? { decision: 'continue', reason: verdict.block } : undefined
248
258
  // force_ask:每次都弹窗问用户,"总是允许"在弹窗里选不了(实测);用户拒绝时工具不执行
249
259
  if (verdict.ask) return { decision: 'force_ask', reason: oneParagraph(verdict.ask) }
@@ -1,6 +1,5 @@
1
1
  // 检查模块交给底座的入口。底座(这个目录)不认识任何模块:合并门、停止门、会话说明、整组都按这里的入口去问,
2
2
  // 模块(比如 ../pace 跑测试)把自己的实现登记进来。登记由装配的文件做(src/modules.ts),底座的代码不引用模块。
3
- // 设计见仓库根目录的 整体设计方案.md。
4
3
 
5
4
  import type { Repo } from './repo.ts'
6
5
  import type { RunRecord } from './store.ts'
@@ -16,8 +15,6 @@ export interface FullStep {
16
15
  header: string
17
16
  command: string
18
17
  args: string[]
19
- /** 这一段要借用工作区(比如建副本):底座把这一轮的运行 id 给它(见 execute.ts 的 RUN_ENV),它借用时不另占。只给测试之前跑的检查。 */
20
- borrows?: boolean
21
18
  }
22
19
 
23
20
  /** 一个模块在这一轮整组里的部分。 */
@@ -30,8 +27,11 @@ export interface FullPart {
30
27
  /**
31
28
  * 各段跑完(没被中断)以后:模块往这次的运行记录里加自己的字段(fields),在记录写下之后说给 agent 的话(notes,
32
29
  * 拿得到写好的记录和这之前的全部记录)。
30
+ * failedStep 是没过的那一段的 name(各段都过了时没有):模块自己的段跑了、没过的,照样可以核对它跑到了什么,写进 notes。
31
+ * problems:按跑完交回来的东西核对出的问题(比如该跑到的没跑到),一条一句、写明怎么改。各段都过了、却有问题的,整组算没过;
32
+ * 有哪一段没过时不看(已经算没过了)。
33
33
  */
34
- finish?(): { fields?: Record<string, unknown>; notes?(record: RunRecord, before: RunRecord[]): string[] }
34
+ finish?(failedStep?: string): { fields?: Record<string, unknown>; problems?: string[]; notes?(record: RunRecord, before: RunRecord[]): string[] }
35
35
  /** 这一轮结束(不管怎么结束)时收拾模块自己的临时文件。 */
36
36
  dispose?(): void
37
37
  }
@@ -67,10 +67,12 @@ export interface Module {
67
67
  beforeEdit?(repo: Repo, path: string, text?: string): string | undefined
68
68
 
69
69
  /**
70
- * 停止门:这个会话在这个仓库里还有没处理完的事。keys 是这几件事各自的记号,底座记下拦过的,每件只拦一次
71
- * (seen 是已经拦过的);named 为真时话里要写明是哪个仓库(会话不是在这个仓库里开始的)。
70
+ * 停止门:这个会话在这个仓库里还有没处理完的事。keys 是这几件事各自的记号,写成"模块:项:内容的样子"(比如 wall:check:<摘要>),
71
+ * 底座记下拦过的,每件只拦一次;seen 说一个记号该不该当作拦过(拦过的,和这个会话上次为同一项被拦之后没再动过手的,见 stop.ts);
72
+ * named 为真时话里要写明是哪个仓库(会话不是在这个仓库里开始的)。
73
+ * notice 是同时直接给用户看的一行(agent 转述可能被一句带过的事),不给就只说给 agent。
72
74
  */
73
- unfinished?(repo: Repo, sessionId: string, seen: readonly string[], named: boolean): { keys: string[]; text: string } | undefined
75
+ unfinished?(repo: Repo, sessionId: string, seen: (key: string) => boolean, named: boolean): { keys: string[]; text: string; notice?: string } | undefined
74
76
 
75
77
  /** 整组里这个模块的部分;现在跑不了(配置不对、没有要跑的)时给出原因。 */
76
78
  fullPart?(repo: Repo): FullPart | { problem: string }
package/src/base/repo.ts CHANGED
@@ -5,11 +5,11 @@ import { currentAgent } from './agent.ts'
5
5
  import { CONTRACT_FILE } from './contract.ts'
6
6
  import { type Coverage, findCoverage } from './coverage.ts'
7
7
  import { failureExcerpt } from './excerpt.ts'
8
- import { type Execution, execute, RUN_ENV } from './execute.ts'
8
+ import { type Execution, execute } from './execute.ts'
9
9
  import { duration, when } from './format.ts'
10
10
  import { changedPaths, commonDir, defaultBranch, refTip, repoRoot } from './git.ts'
11
11
  import { matcher } from './glob.ts'
12
- import { isHold, newRunId, processAlive, type RunningMarker, type RunRecord, Store } from './store.ts'
12
+ import { newRunId, processAlive, type RunMarker, type RunRecord, Store } from './store.ts'
13
13
  import { VERSION } from './version.ts'
14
14
 
15
15
  export interface Repo {
@@ -65,25 +65,22 @@ export function defaultTips(repo: Repo): Record<string, string> {
65
65
 
66
66
  /**
67
67
  * 在跑的那次是什么时候、哪个进程起的。testpace 被强杀后测试可能还在跑,说清楚怎么停。
68
- * 借用工作区的登记只认那一个进程,列得出来就是它还在。
69
68
  */
70
- export function started(marker: RunningMarker): string {
71
- const owner = isHold(marker) || processAlive(marker.pid)
69
+ export function started(marker: RunMarker): string {
70
+ const owner = processAlive(marker.pid)
72
71
  ? `进程 ${marker.pid}`
73
72
  : `起它的 testpace 已经退出,测试进程组 ${marker.group} 还在跑,不要了用 kill -- -${marker.group} 停掉`
74
73
  return `开始于 ${when(marker.startedAt)},${owner}`
75
74
  }
76
75
 
77
- /** 这个工作区在跑的是哪种命令(或被谁借用着)、什么时候哪个进程起的。 */
78
- export function runningText(marker: RunningMarker): string {
79
- if (isHold(marker)) return `这个工作区正被 ${marker.by} 占着(${started(marker)})`
76
+ /** 这个工作区在跑的是哪种命令、什么时候哪个进程起的。 */
77
+ function runningText(marker: RunMarker): string {
80
78
  const what = marker.kind === 'full' ? '整组' : ` ${marker.kind} `
81
79
  return `这个工作区正在跑${what}(${started(marker)})`
82
80
  }
83
81
 
84
82
  /** 因为这个工作区已经在跑测试而不跑时的说明。 */
85
- export function busyText(marker: RunningMarker, tree: string): string {
86
- if (isHold(marker)) return `${runningText(marker)},占着时不跑测试,等它放开再跑。`
83
+ export function busyText(marker: RunMarker, tree: string): string {
87
84
  const stale = marker.kind === 'full' && marker.tree !== tree ? '那次整组开始后代码改过,它跑完的结果不算当前代码的记录。' : ''
88
85
  return `${runningText(marker)},同一个工作区一次只跑一轮测试,等它结束再跑。${stale}`
89
86
  }
@@ -99,7 +96,7 @@ export async function runClaimed(
99
96
  args: string[],
100
97
  tree: string,
101
98
  env: Record<string, string> = {},
102
- ): Promise<{ id: string; startedAt: number; log: string; execution: Execution } | { busy: RunningMarker }> {
99
+ ): Promise<{ id: string; startedAt: number; log: string; execution: Execution } | { busy: RunMarker }> {
103
100
  const startedAt = Date.now()
104
101
  const id = newRunId(startedAt)
105
102
  const log = repo.store.logPath(id)
@@ -113,29 +110,6 @@ export async function runClaimed(
113
110
  }
114
111
  }
115
112
 
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
113
  /** 命令为什么算失败:退出码、信号,或没能启动。 */
140
114
  export function failureCause(execution: Execution): string {
141
115
  if (execution.exitCode !== null) return `退出码 ${execution.exitCode}`
@@ -9,8 +9,12 @@ import { SESSION_KEEP_MS, writeWhole } from './store.ts'
9
9
  interface SessionRepos {
10
10
  updatedAt: number
11
11
  repos: string[]
12
+ /** 会话所在的目录:第一次见到这个会话时 hook 给的目录。 */
13
+ home?: string
12
14
  }
13
15
 
16
+ const DAY_MS = 24 * 60 * 60 * 1000
17
+
14
18
  function sessionsDir(): string | undefined {
15
19
  const data = process.env.CLAUDE_PLUGIN_DATA || process.env.PLUGIN_DATA
16
20
  return data ? join(data, 'sessions') : undefined
@@ -35,21 +39,49 @@ export function sessionRepos(id: string): string[] {
35
39
  return read(fileOf(dir, id))?.repos ?? []
36
40
  }
37
41
 
38
- /** 记下这个会话碰到的仓库;第一次记这个会话时顺手清掉过期的会话。 */
39
- export function noteSessionRepos(id: string, roots: string[], now: number): void {
42
+ /** 清掉过期的会话。 */
43
+ function prune(dir: string, now: number): void {
44
+ for (const name of readdirSync(dir).filter(name => name.endsWith('.json'))) {
45
+ const file = join(dir, name)
46
+ const state = read(file)
47
+ if (!state || now - state.updatedAt > SESSION_KEEP_MS) rmSync(file, { force: true })
48
+ }
49
+ }
50
+
51
+ /**
52
+ * 改这个会话的记录:change 拿到现在记着的(没有时是空的),返回要记的;返回 undefined 不用改。
53
+ * 第一次记这个会话时顺手清掉过期的会话。
54
+ */
55
+ function update(id: string, now: number, change: (known: SessionRepos | undefined) => Omit<SessionRepos, 'updatedAt'> | undefined): void {
40
56
  const dir = sessionsDir()
41
- if (!dir || roots.length === 0) return
57
+ if (!dir) return
42
58
  const path = fileOf(dir, id)
43
59
  const known = existsSync(path) ? read(path) : undefined
44
- if (known && roots.every(root => known.repos.includes(root))) return
60
+ const next = change(known)
61
+ if (!next) return
45
62
  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))
63
+ if (!known) prune(dir, now)
64
+ writeWhole(path, JSON.stringify({ ...next, updatedAt: now } satisfies SessionRepos))
65
+ }
66
+
67
+ /** 记下这个会话碰到的仓库。 */
68
+ export function noteSessionRepos(id: string, roots: string[], now: number): void {
69
+ if (roots.length === 0) return
70
+ update(id, now, known => (known && roots.every(root => known.repos.includes(root)) ? undefined : { ...known, repos: [...new Set([...(known?.repos ?? []), ...roots])] }))
71
+ }
72
+
73
+ /**
74
+ * 会话所在的目录:记下第一次见到这个会话时的目录,以后都按它认,不跟着 hook 给的目录变。
75
+ * Claude Code 主会话里 cd 会留到下一条命令,之后 hook 给的就是 cd 进去的目录:按它认,只进去看过的别人的工作区会被当成会话干活的地方。
76
+ * 隔一天刷新一次记录的时间:会话还在用,不能当过期清掉、再按那时 cd 进去的目录重记。
77
+ * 没有插件数据目录(不在 hook 里)时记不下,用这次给的目录。
78
+ */
79
+ export function sessionHome(id: string, cwd: string, now: number): string {
80
+ let home = cwd
81
+ update(id, now, known => {
82
+ home = known?.home ?? cwd
83
+ if (known?.home && now - known.updatedAt < DAY_MS) return undefined
84
+ return { repos: known?.repos ?? [], home }
85
+ })
86
+ return home
55
87
  }
package/src/base/shell.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  // 大致读懂 agent 要跑的 Bash 命令:拆成一条条命令,跟着 cd 算出每条在哪个目录跑。
2
- // 只用于提示(节奏说明、直接跑整组命令时的提醒、前台跑完整组算看过结果),不用来把关:
3
- // 引号、转义、&& || ; | & 换行、cd、环境变量前缀、sh -c。
2
+ // 用于提示(节奏说明、直接跑整组命令时的提醒、前台跑完整组算看过结果)和停止门认会话动没动手(hook.ts),不用来拦命令:
3
+ // 认错了最多是停止门多问或少问一次。认得出:引号、转义、&& || ; | & 换行、cd、环境变量前缀、sh -c、往文件里写的重定向。
4
4
 
5
5
  import { homedir } from 'node:os'
6
6
  import { basename, resolve } from 'node:path'
@@ -8,12 +8,14 @@ import { basename, resolve } from 'node:path'
8
8
  export interface Invocation {
9
9
  cwd: string
10
10
  argv: string[]
11
+ /** 输出重定向到了文件(> file、>> file、&> file;/dev/null 和 2>&1 这类不算)。 */
12
+ writes: boolean
11
13
  }
12
14
 
13
15
  const OPERATORS = ['&&', '||', ';;', ';', '|&', '|', '&', '\n', '(', ')']
14
16
 
15
17
  /** 重定向:`>`、`2>&1`、`&>file`、`<<EOF` 这类。不带目标时目标是下一个词。 */
16
- const REDIRECT = /^(?:\d+|&)?(?:>>|>&|>\||>|<<<|<<-?|<&|<>|<)(.*)$/s
18
+ const REDIRECT = /^(?:\d+|&)?(>>|>&|>\||>|<<<|<<-?|<&|<>|<)(.*)$/s
17
19
  const HEREDOC = /^\d*<<(?!<)(-?)(.*)$/s
18
20
 
19
21
  /**
@@ -105,15 +107,20 @@ export function tokenize(command: string): string[] {
105
107
  return tokens
106
108
  }
107
109
 
108
- /** 去掉重定向和它的目标。 */
109
- function withoutRedirects(argv: string[]): string[] {
110
+ /** 去掉重定向和它的目标;有没有往文件里写。 */
111
+ function withoutRedirects(argv: string[]): { argv: string[]; writes: boolean } {
110
112
  const out: string[] = []
113
+ let writes = false
111
114
  for (let i = 0; i < argv.length; i++) {
112
115
  const redirect = REDIRECT.exec(argv[i]!)
113
- if (!redirect) out.push(argv[i]!)
114
- else if (redirect[1] === '') i++
116
+ if (!redirect) {
117
+ out.push(argv[i]!)
118
+ continue
119
+ }
120
+ const target = redirect[2] === '' ? argv[++i] : redirect[2]
121
+ if (redirect[1]!.includes('>') && !/^(?:\/dev\/null|&?\d+|-)$/.test(target ?? '')) writes = true
115
122
  }
116
- return out
123
+ return { argv: out, writes }
117
124
  }
118
125
 
119
126
  const WRAPPERS = new Set(['command', 'exec', 'nohup', 'time', 'builtin'])
@@ -128,7 +135,8 @@ export function invocations(command: string, cwd: string): Invocation[] {
128
135
  let here = cwd
129
136
  let segment: string[] = []
130
137
  const flush = (): void => {
131
- let argv = withoutRedirects(segment)
138
+ const redirected = withoutRedirects(segment)
139
+ let argv = redirected.argv
132
140
  segment = []
133
141
  // 跳过环境变量前缀和 env、command 这类包装
134
142
  for (;;) {
@@ -154,7 +162,7 @@ export function invocations(command: string, cwd: string): Invocation[] {
154
162
  return
155
163
  }
156
164
  }
157
- result.push({ cwd: here, argv })
165
+ result.push({ cwd: here, argv, writes: redirected.writes })
158
166
  }
159
167
  for (const token of tokenize(command)) {
160
168
  if (OPERATORS.includes(token)) flush()
package/src/base/stop.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  // 停止门:agent 要结束这一轮时,这个会话起的整组还在跑、或跑完还没看结果,就拦一次。
2
- // 各模块在这个会话里还没处理完的事(module.ts 的 unfinished,比如改了代码还没有 modwall check 的通过记录),每件也拦一次;
3
- // 只问会话干活的工作区(所在目录的、用改文件的工具改过的),只在命令里 cd 进去看过的别人的工作区不问。
2
+ // 各模块在这个会话里还没处理完的事(module.ts 的 unfinished,比如改了代码还没跑过 testpace focused、提交了却还有没合进默认分支的提交、
3
+ // 还没有 modwall check 的通过记录),每件也拦一次,要紧的同时直接给用户看一行;
4
+ // 只问会话干活的工作区(所在目录的、用改文件的工具改过的),只在命令里 cd 进去看过的别人的工作区不问;
5
+ // 会话在那里没动过手的不问,拦过一项之后没再动手的同一项不再拦(SessionState.acted);放到后台的 agent 还在干活时不问。
4
6
  // 每次整组只拦一次(还在跑时一次、跑完没看结果时一次),拦过的记在会话状态里,不靠 agent 给的 stop_hook_active:
5
7
  // 有的 agent 不给或总是 false,靠它会反复拦。
6
8
  // 谁起的整组看记录里的会话号(testpace full 从命令环境里 agent 的会话号记下,见 agent.ts);
@@ -20,6 +22,8 @@ export interface StopInput {
20
22
  cwd: string
21
23
  /** 仓库不是会话所在目录的(会话从仓库外开始),话里写上是哪个仓库。 */
22
24
  named?: boolean
25
+ /** 会话放到后台的 agent 还在干活。 */
26
+ busy?: boolean
23
27
  now: number
24
28
  }
25
29
 
@@ -59,13 +63,21 @@ export function stopCheck(input: StopInput): StopResult {
59
63
 
60
64
  // 各模块在这个会话里还没处理完的事(比如改了代码还没有 modwall check 的通过记录):每件拦一次,免得一句带过。
61
65
  // 只问这个会话干活的工作区(会话所在目录的、用改文件的工具改过的,见 SessionState.worked):只 cd 进去看过的,那里后来的改动是别的会话的
62
- const works = input.named !== true || session.worked?.includes(repo.root) === true
66
+ // 放到后台的 agent 还在干活时不问:内容还会变,每轮结束都拦一次只会空跑;它们干完会叫醒会话,那时再问
67
+ const works = input.busy !== true && (input.named !== true || session.worked?.includes(repo.root) === true)
68
+ // 起点只说"这之后变了",不说是谁变的:同一个工作区里别的会话、用户自己改的也算进去。会话在这里没动过手,变化就不是它的;
69
+ // 拦过一项、之后没再动手(只跑了检查),后来的变化也不是它的,同一项不再拦
70
+ const acts = session.acted?.[repo.root] ?? 0
71
+ const blockedActs = { ...session.blockedActs }
72
+ const item = (key: string): string => `${repo.root}\0${key.split(':').slice(0, 2).join(':')}`
73
+ const seen = (key: string): boolean => acts === 0 || blocked.includes(key) || blockedActs[item(key)] === acts
63
74
  const moduleProblems: string[] = []
75
+ const moduleNotices: string[] = []
64
76
  for (const module of works ? modules() : []) {
65
77
  if (result.block) break
66
78
  let left: ReturnType<NonNullable<typeof module.unfinished>>
67
79
  try {
68
- left = module.unfinished?.(repo, input.sessionId, blocked, input.named === true)
80
+ left = module.unfinished?.(repo, input.sessionId, seen, input.named === true)
69
81
  } catch (error) {
70
82
  // 一个模块出错不挡别的检查,但要让人看得到
71
83
  moduleProblems.push(`testpace:停止门里"${module.name}"这一项检查出错,这次没查它(${(error as Error).message.split('\n')[0]})。`)
@@ -73,12 +85,14 @@ export function stopCheck(input: StopInput): StopResult {
73
85
  }
74
86
  if (!left) continue
75
87
  blocked.push(...left.keys)
88
+ for (const key of left.keys) blockedActs[item(key)] = acts
76
89
  result.block = left.text
90
+ if (left.notice) moduleNotices.push(left.notice)
77
91
  }
78
92
 
79
93
  // 没经过合并门的落地:默认分支在这个会话里有了新提交,却没有整组通过记录
80
94
  const warned = [...session.warned]
81
- const warns: string[] = [...moduleProblems]
95
+ const warns: string[] = [...moduleNotices, ...moduleProblems]
82
96
  for (const [ref, commit] of Object.entries(defaultTips(repo))) {
83
97
  if (commit === session.tipsAtStart[ref] || warned.includes(commit)) continue
84
98
  const tip = refTip(repo.root, ref)
@@ -95,6 +109,6 @@ export function stopCheck(input: StopInput): StopResult {
95
109
  warns.push(`testpace:${input.named ? `${repo.root} 的 ` : ''}${name} 的最新提交 ${short(commit)} 没有整组通过记录(${how})。`)
96
110
  }
97
111
  if (warns.length > 0) result.warn = warns.join('\n')
98
- if (warns.length > 0 || result.block) repo.store.saveSession(input.sessionId, { ...session, warned, blocked })
112
+ if (warns.length > 0 || result.block) repo.store.saveSession(input.sessionId, { ...session, warned, blocked, blockedActs })
99
113
  return result
100
114
  }