gatelight 0.18.1 → 0.19.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.
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "gatelight",
3
3
  "displayName": "gatelight",
4
- "version": "0.18.1",
5
- "description": "Gates for coding agents: tests actually ran before code lands, code stays inside its module boundaries, plus test-writing conventions and a change-triggered checklist",
4
+ "version": "0.19.1",
5
+ "description": "Gates for coding agents: tests actually ran before code lands, code stays inside its module boundaries, standards (types, lint, format, secrets) are not quietly loosened, plus test-writing conventions and a change-triggered checklist",
6
6
  "author": {
7
7
  "name": "coffeecoproject"
8
8
  }
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "gatelight",
3
3
  "displayName": "gatelight",
4
- "version": "0.18.1",
5
- "description": "Gates for coding agents: tests actually ran before code lands, code stays inside its module boundaries, plus test-writing conventions and a change-triggered checklist",
4
+ "version": "0.19.1",
5
+ "description": "Gates for coding agents: tests actually ran before code lands, code stays inside its module boundaries, standards (types, lint, format, secrets) are not quietly loosened, plus test-writing conventions and a change-triggered checklist",
6
6
  "author": {
7
7
  "name": "coffeecoproject"
8
8
  },
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "gatelight",
3
- "version": "0.18.1",
4
- "description": "Gates for coding agents: tests actually ran before code lands, code stays inside its module boundaries, plus test-writing conventions and a change-triggered checklist",
3
+ "version": "0.19.1",
4
+ "description": "Gates for coding agents: tests actually ran before code lands, code stays inside its module boundaries, standards (types, lint, format, secrets) are not quietly loosened, plus test-writing conventions and a change-triggered checklist",
5
5
  "author": {
6
6
  "name": "coffeecoproject"
7
7
  },
@@ -12,7 +12,7 @@
12
12
  "skills": "./skills/",
13
13
  "interface": {
14
14
  "displayName": "gatelight",
15
- "shortDescription": "Gates for coding agents: tests ran, code stays in bounds, test-writing conventions",
15
+ "shortDescription": "Gates for coding agents: tests ran, code stays in bounds, standards hold, test-writing conventions",
16
16
  "developerName": "coffeecoproject",
17
17
  "category": "Developer Tools"
18
18
  }
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # gatelight
2
2
 
3
- 给 agent 写代码把关的插件(Claude Code、Codex、Antigravity):测试跑了没有、测试怎么写、代码有没有越界。
3
+ 给 agent 写代码把关的插件(Claude Code、Codex、Antigravity):测试跑了没有、测试怎么写、代码有没有越界、代码守不守规范。
4
4
 
5
5
  这个 npm 包就是插件本身。说明、规则和开发都在 [gatelight 仓库](https://github.com/coffeecoproject/gatelight)。
6
6
 
package/bin/codekeep ADDED
@@ -0,0 +1,8 @@
1
+ #!/bin/sh
2
+ # codekeep 命令入口("代码规范"模块的命令)。Claude Code 插件启用时这个目录在 Bash 工具的 PATH 里;
3
+ # 别处(Codex 的命令)由固定入口 ~/.local/bin/codekeep(entry/command)转过来。
4
+ dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
5
+ . "$dir/node.sh"
6
+ # 找不到 node 时退出码 2(配置问题)
7
+ node=$(testpace_node) || { echo 'codekeep:找不到 22.18 以上的 node(要能直接运行 TypeScript)。装一个,或用 TESTPACE_NODE 指给它。' >&2; exit 2; }
8
+ exec "$node" --disable-warning=ExperimentalWarning "$dir/../src/codekeep.ts" "$@"
package/entry/command CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/bin/sh
2
- # testpace 固定入口:testpace install 把这个文件放到 ~/.local/bin 下,gatelight 的每条命令放一份(testpace、modwall、testcraft),内容一样,
2
+ # testpace 固定入口:testpace install 把这个文件放到 ~/.local/bin 下,gatelight 的每条命令放一份(testpace、modwall、testcraft、codekeep),内容一样,
3
3
  # 运行时按被叫的名字转给插件里同名的命令(Codex 的命令和终端的 PATH 里都有这个目录)。放哪几条由 src/base/entry.ts 定,这里不列。
4
4
  # 放上去时第一行后面插一行记着是哪一版放的(entry.ts),会话开始的自动更新只升不降。
5
5
  # 插件(gatelight)的安装目录随版本变,不能写死,这里每次运行时找这台机器上装着的最高版本,Claude Code、Codex、Antigravity 装的都算,不分先后。
package/hooks/hooks.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "description": "gatelight:会话开始时说明测试节奏和写测试的约定(接入了 testcraft 的仓库),直接跑 full 的命令时提醒改用 testpace full;接入了 modwall 的仓库再说明模块列表和写法约定,改文件之前拦下没有归属的代码文件,和新文字里绕过入口引用别的模块内部文件的写法(只看路径和要写的文字);整组没跑完或结果没看、改了代码却没有 modwall check 的通过记录,拦一次结束。合并门是 git 钩子(testpace install)。",
2
+ "description": "gatelight:会话开始时说明测试节奏和写测试的约定(接入了 testcraft 的仓库)、代码规范的约定(接入了 codekeep 的仓库),直接跑 full 的命令时提醒改用 testpace full;接入了 modwall 的仓库再说明模块列表和写法约定,改文件之前拦下没有归属的代码文件,和新文字里绕过入口引用别的模块内部文件的写法(只看路径和要写的文字);整组没跑完或结果没看、改了代码却没有 modwall check 的通过记录,拦一次结束。合并门是 git 钩子(testpace install)。",
3
3
  "hooks": {
4
4
  "SessionStart": [
5
5
  {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "gatelight",
3
- "version": "0.18.1",
4
- "description": "Gates for coding agents: tests actually ran before code lands, code stays inside its module boundaries, plus test-writing conventions and a change-triggered checklist",
3
+ "version": "0.19.1",
4
+ "description": "Gates for coding agents: tests actually ran before code lands, code stays inside its module boundaries, standards (types, lint, format, secrets) are not quietly loosened, plus test-writing conventions and a change-triggered checklist",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/coffeecoproject/gatelight#readme",
7
7
  "repository": { "type": "git", "url": "git+https://github.com/coffeecoproject/gatelight.git", "directory": "plugin" },
package/setup.mjs CHANGED
@@ -86,7 +86,7 @@ function remove() {
86
86
  rmSync(target, { recursive: true, force: true })
87
87
  console.log(`已从 Antigravity 卸掉 ${name} ${now.version}(删了 ${target})。新开的对话里就没有了。`)
88
88
  if (existsSync(join(process.env.HOME || homedir(), '.local', 'bin', 'testpace'))) {
89
- console.log('~/.local/bin 下的 testpace、modwall、testcraft 入口留着:别的 agent 装着的 gatelight 还用它们,一个都没装时它们会说没装。')
89
+ console.log('~/.local/bin 下的 testpace、modwall、testcraft、codekeep 入口留着:别的 agent 装着的 gatelight 还用它们,一个都没装时它们会说没装。')
90
90
  }
91
91
  return 0
92
92
  }
@@ -0,0 +1,80 @@
1
+ ---
2
+ name: setup-codekeep
3
+ description: 给项目接入 codekeep:确认已接入 testpace、testpace 的 ignore 没盖住规范配置;按项目现有的工具配好严格类型、lint(长度和复杂度上限、"这里不查"的注释要写理由)、格式检查,旧代码超标的记进 eslint 的批量豁免文件;写 .codekeep/config.json,把规范检查从 full 挪过来;没装 gitleaks 的问用户要不要装;跑一次 codekeep check 和整组。用户要给项目接入 codekeep 时使用。
4
+ ---
5
+
6
+ # 接入 codekeep
7
+
8
+ codekeep 管代码本身的规范:类型查得严不严、lint 和格式检查有没有、规范有没有被悄悄改松、提交里有没有密钥。它不让 AI 判断代码写得好不好,只做程序判断得了的事。它和 testpace 在同一个插件里:仓库里有 `.codekeep/` 目录,`testpace full` 就会在测试之前跑一次 `codekeep check`,不用另外登记。
9
+
10
+ `codekeep check` 依次做:
11
+
12
+ 1. 配置写得对不对(`.codekeep/config.json`)。
13
+ 2. 和分叉点比,规范改松了哪些:关规则、error 降成 warn、调高上限、文件不再被 lint、关严格类型选项、开 `skipLibCheck`、`include` 少了或 `exclude` 多了、批量豁免变多、`.gitleaksignore` 多了条目、改了 gitleaks 或 biome 的配置、改了或删了检查命令。改松的要用户在弹窗里同意;分叉点上还没有 `.codekeep/`(首次接入)的不问。
14
+ 3. 依次跑 `checks` 里的命令,一条没过就停。
15
+ 4. `secrets` 开着时用 gitleaks 扫分叉点之后的提交和没提交的改动。
16
+
17
+ 第一期只做 TypeScript、JavaScript,lint 只比 eslint。
18
+
19
+ ## 先确认
20
+
21
+ 1. **接入了 testpace**:仓库根目录有 `testpace.json`,`testpace verify` 能过。没有就先用 `gatelight:setup` 接入:会话说明、整组、合并前的把关都只管接入了 testpace 的仓库。
22
+ 2. **`testpace.json` 的 `ignore` 没盖住规范配置**:`.codekeep/`、eslint 的配置文件、`tsconfig*.json`、`eslint-suppressions.json`、`.prettierignore`、`.gitleaksignore`、`.gitleaks.toml` 都不能在 `ignore` 里(比如 `.*/**`、`*.json`)。盖住的话,改这些不会重跑整组,改松规范就绕过了合并门:从 `ignore` 里去掉它们。
23
+
24
+ ## 步骤(在接入分支上做)
25
+
26
+ 1. **看项目现有的工具**:类型检查(TypeScript)、lint(eslint 还是 biome)、格式(prettier 还是 biome)各有没有,各子包用的是不是同一套。缺的要新装依赖,**先问用户**,说清装什么、为什么。
27
+ - 用 biome 的项目:eslint 那一项先不写(codekeep 不比 biome 生效的规则),biome 的配置(仓库根目录的 `biome.json`、`biome.jsonc`)改了,整组按"程序看不出改松还是改紧"问用户。
28
+ 2. **配严格类型**:每个 tsconfig 开 `strict`。开了以后旧代码报错的,少的直接改;多的、或者要动业务逻辑才改得掉的,停下来问用户。
29
+ 3. **配 lint**(eslint 的 flat config;批量豁免用 eslint 自带的,实测 eslint 10 有):
30
+ - 用工具的推荐集:`@eslint/js` 的 `recommended`,TypeScript 项目加 `typescript-eslint` 的 `recommended`(里面有不许 `any`、不许没用的变量和导入),React 项目加 `eslint-plugin-react-hooks` 的推荐集(代码里已经有 `react-hooks/...` 的注释的,不加它 lint 会报找不到规则)。
31
+ - 长度和复杂度上限:`max-lines` 500(`{ max: 500, skipBlankLines: true, skipComments: true }`)、`max-lines-per-function` 80(同样不算空行和注释)、`complexity` 20、`max-depth` 5,都是 `error`。先放宽一点,试接后再调。
32
+ - 只查 git 收的文件:eslint 不读 `.git/info/exclude` 和全局的排除规则,本机工具放在仓库里的目录(napbox 的 `.napbox/`、agent 开在仓库里的 `.claude/worktrees/`)只写在那里,在主目录跑会查到它们(嵌着的工作区还会按它自己的配置查、对不上主目录的批量豁免)。配置文件开头用 git 列出它不收的,放进 `ignores`:
33
+
34
+ ```js
35
+ import { execFileSync } from 'node:child_process'
36
+ const gitIgnored = execFileSync('git', ['ls-files', '-z', '--others', '--ignored', '--exclude-standard', '--directory'], { cwd: import.meta.dirname, encoding: 'utf8' })
37
+ .split('\0')
38
+ .filter(Boolean)
39
+ .map(path => path.replace(/[*?[\]{}()!\\]/g, '\\$&'))
40
+ // export default [{ ignores: gitIgnored }, ...]
41
+ ```
42
+
43
+ - "这里不查"的注释要写理由、没用了的要删:`linterOptions: { reportUnusedDisableDirectives: 'error' }`;`@eslint-community/eslint-plugin-eslint-comments` 的 `require-description`(`eslint-disable` 一类的注释要带 `-- 理由`);TypeScript 项目用 `@typescript-eslint/ban-ts-comment` 的默认设置(`@ts-ignore`、`@ts-nocheck` 不许用,`@ts-expect-error` 要写理由)。没装这几个插件的,装之前先问用户。
44
+ 4. **格式检查**:项目有 prettier 的用它;没有的问用户要不要加。检查命令把 git 收的文件交给 prettier(`git ls-files -z --cached --others --exclude-standard | xargs -0 pnpm -s exec prettier --check --ignore-unknown --no-error-on-unmatched-pattern`),不用 `prettier --check .`:prettier 只读仓库根目录的 `.gitignore` 和 `.prettierignore`,会查到上面说的本机工具目录。新加的照项目现有的写法配(分号、引号、行宽),让改动尽量小,再 `prettier --write .` 把全部代码排一遍(改动大,先和用户说清;有别的分支正在做的,排完它们合进来会冲突,先问)。`.prettierignore` 里写上 `eslint-suppressions.json`(eslint 生成、改写它,不按 prettier 排)和锁文件。
45
+ 5. **旧代码超标的记进批量豁免**:`eslint --suppress-all`,生成仓库根目录的 `eslint-suppressions.json`,提交进仓库。以后豁免只许变少:代码改好了用 `eslint --prune-suppressions` 清掉用不上的;豁免变多算改松,要用户同意。lint 不在仓库根目录跑的,用 `--suppressions-location` 指到同一个文件,并在配置里写上 `eslint.suppressions`。
46
+ 6. **写 `.codekeep/config.json`**:
47
+
48
+ ```json
49
+ {
50
+ "checks": [
51
+ { "name": "类型检查", "command": "pnpm -s exec tsc -p apps/server --noEmit" },
52
+ { "name": "lint", "command": "pnpm -s exec eslint ." },
53
+ { "name": "格式", "command": "git ls-files -z --cached --others --exclude-standard | xargs -0 pnpm -s exec prettier --check --ignore-unknown --no-error-on-unmatched-pattern" }
54
+ ],
55
+ "eslint": { "config": "eslint.config.mjs" },
56
+ "tsconfig": ["apps/server/tsconfig.json", "apps/web/tsconfig.app.json"],
57
+ "prettier": true,
58
+ "secrets": true
59
+ }
60
+ ```
61
+
62
+ - `checks`:规范检查直接写工具命令,从仓库根目录用 sh 跑,不经过项目的脚本(脚本里删掉一行,codekeep 看不到)。每个要类型检查的 tsconfig 各写一条。
63
+ - `eslint.config`:eslint 的配置文件,codekeep 按它对每个代码文件算"生效的规则"来比;`eslint.suppressions`:批量豁免文件,不在仓库根目录的 `eslint-suppressions.json` 时才写。不用 eslint 的项目不写 `eslint`。
64
+ - `prettier`:用 prettier 做格式检查的写 `true`,codekeep 比每个文件查不查(往 `.prettierignore` 里加路径算改松)。
65
+ - `tsconfig`:`checks` 里类型检查用到的 tsconfig,codekeep 比它们的严格选项。只写引用别的 tsconfig 的(`tsc -b` 用的那种总的)不用写它,写它引用的那几份。
66
+ - `secrets`:开着时扫密钥(下一步)。
67
+ - 路径都从仓库根目录写起。
68
+ - 把这几条检查从项目的 `full`(`testpace.json` 的 `full`,或它调用的脚本)里挪出来,不要两边都跑。先用白话告诉用户挪了什么:`full` 直接写在 `testpace.json` 里的,改了整组会照 testpace 原有的流程弹窗;`full` 调的是脚本的,testpace 看不到脚本里删了哪行,不会弹窗,只靠这一句告诉用户。`fast` 里的 lint 和类型检查照旧留着;`fast` 没有 lint 的加上(整个仓库 lint 一遍一般几秒)。
69
+ - 接入了 modwall 的仓库:新加的 `eslint.config.mjs` 这类配置文件没有归属,`modwall check` 会报,把它加进 `.modwall/config.json` 的 `outside`(放宽规则,整组会弹窗要用户同意一次)。
70
+ 7. **密钥扫描**:`gitleaks version` 看装没装。没装的问用户要不要装(`brew install gitleaks`,别的系统见 https://github.com/gitleaks/gitleaks#installing),这是装在这台机器上的工具,用户同意了再装;用户不要的,`secrets` 写 `false`。gitleaks 用仓库根目录的 `.gitleaks.toml`、`.gitleaksignore`(有的话),旧提交里的不管,只扫这次改动。代码里的 `gitleaks:allow` 注释不认:确实不是密钥的,把那一条的 Fingerprint 加进 `.gitleaksignore`(算放松,要用户同意)。
71
+ 8. **跑一次**:`codekeep check` 通过(首次接入不问用户),再跑 `testpace full`。
72
+ 9. 提交前先问用户;合回默认分支照 testpace 的节奏(`gatelight:merge`)。
73
+
74
+ ## 完成时用白话告诉用户
75
+
76
+ 比如:
77
+
78
+ > 项目的类型检查开了严格模式,lint 加上了文件和函数长度、复杂度的上限,旧代码里超标的先记下来、以后只许减少。从现在起,谁把这些规范改松(关规则、调高上限、加豁免),合并前都会弹窗问你;提交里带了密钥也会被拦下。
79
+
80
+ 有没接上的(没装 gitleaks、项目用 biome 所以 lint 规则没在比),也在这里说清楚。
@@ -1,5 +1,5 @@
1
- // 三条命令(testpace、modwall、testcraft)的入口共用的一层:在 agent 的沙箱里跑不了的子命令事先拒绝,写入被拒时说清楚。
2
- // 各命令只说哪些子命令在沙箱里跑不了、要做什么(outside);怎么认沙箱、怎么说、退出码是什么都在这里,三个入口都经过它。
1
+ // 几条命令(testpace、modwall、testcraft、codekeep)的入口共用的一层:在 agent 的沙箱里跑不了的子命令事先拒绝,写入被拒时说清楚。
2
+ // 各命令只说哪些子命令在沙箱里跑不了、要做什么(outside);怎么认沙箱、怎么说、退出码是什么都在这里,各个入口都经过它。
3
3
 
4
4
  import { AGENTS, currentAgent } from './agent.ts'
5
5
  import { EXIT } from './exit.ts'
package/src/base/entry.ts CHANGED
@@ -1,4 +1,4 @@
1
- // 固定命令入口:~/.local/bin 下的 testpace、modwall、testcraft。Codex 不把插件的 bin/ 放进命令的 PATH,合并门的 git 钩子也靠 PATH 找 testpace。
1
+ // 固定命令入口:~/.local/bin 下的 testpace、modwall、testcraft、codekeep。Codex 不把插件的 bin/ 放进命令的 PATH,合并门的 git 钩子也靠 PATH 找 testpace。
2
2
  // 入口文件只有一份(entry/command),每条命令放一份一样的;它不带版本,运行时按被叫的名字找这台机器上装着的最高版本的插件里同名的命令,插件升级不用重放。
3
3
  // 这是全局安装:只在 testpace install 时放,不在会话开始时自动放(放过别的命令的机器上,新加的命令也一样)。
4
4
  // 放过的入口是旧版本放的(入口文件本身变了,比如插件改了名、旧入口按旧名字找不到装着的那份):会话开始时换成这一版的。
@@ -11,7 +11,7 @@ import { join } from 'node:path'
11
11
  import { compareVersions, VERSION } from './version.ts'
12
12
 
13
13
  /** 放固定入口的命令:插件 bin/ 里给 agent 直接叫的那几条。加命令只改这里。 */
14
- export const ENTRY_COMMANDS = ['testpace', 'modwall', 'testcraft'] as const
14
+ export const ENTRY_COMMANDS = ['testpace', 'modwall', 'testcraft', 'codekeep'] as const
15
15
  export type EntryCommand = (typeof ENTRY_COMMANDS)[number]
16
16
 
17
17
  const SOURCE = new URL('../../entry/command', import.meta.url)
@@ -8,7 +8,7 @@ export const VERSION: string = manifest.version
8
8
 
9
9
  /**
10
10
  * 插件的名字。说给 agent 的话里提到插件时用它;确认工具的全名里也有它(.mcp.json 里服务的名字,测试核对和它一样)。
11
- * 三条命令(testpace、testcraft、modwall)不跟它走。
11
+ * 几条命令(testpace、testcraft、modwall、codekeep)不跟它走。
12
12
  */
13
13
  export const PLUGIN_NAME: string = manifest.name
14
14
 
package/src/cli.ts CHANGED
@@ -29,7 +29,7 @@ const USAGE = `用法:
29
29
  testpace files [--repeat N] PATH[:行号]...
30
30
  只跑给定的测试文件(testpace.json 的 files);文件:行号 只跑那一行的测试,比如重跑失败的测试。
31
31
  --repeat N 连跑 N 次、没过就停:造出时好时坏的测试的失败,或修好后连跑 3 次证明
32
- testpace full 跑整组:接入了的检查(modwall check、testcraft checklist)、full(测试以外的检查),再把 tests 规则找到的全部测试交给 files,
32
+ testpace full 跑整组:接入了的检查(modwall check、testcraft checklist、codekeep check)、full(测试以外的检查),再把 tests 规则找到的全部测试交给 files,
33
33
  一段没过就停,按当前工作区完整内容记录结果。要跑几分钟,能放到后台的就放后台
34
34
  testpace status 当前代码有没有整组通过记录、有没有正在跑的整组、最近一次结果、配置检查
35
35
  testpace hold PID 说明 借用这个工作区(比如要复制一份工作区的工具):占着时别的 testpace 命令不跑,说明是谁占着。
@@ -39,7 +39,7 @@ const USAGE = `用法:
39
39
  testpace report [--days N] 计时诊断,默认最近 28 天
40
40
  testpace verify [测试文件...] 核对接入守不守约定:三条命令找得到、合并门在把关、files 对不存在的文件报失败、认 文件:行号;每种测试各给一个文件
41
41
  testpace install 这台机器配一次:在全局 git 配置里配上合并门(agent 移动默认分支时,要求落地的代码有整组通过记录),
42
- 并在 ~/.local/bin 放上 testpace、modwall、testcraft 的固定命令入口(Codex 的命令和合并门的钩子靠它们找到这几条命令)
42
+ 并在 ~/.local/bin 放上 testpace、modwall、testcraft、codekeep 的固定命令入口(Codex 的命令和合并门的钩子靠它们找到这几条命令)
43
43
  ${nodeTest.usage}
44
44
  ${vitest.usage}
45
45
  ${playwright.usage}
@@ -117,7 +117,7 @@ const ENTRY_STATES = {
117
117
  foreign: '那里是别的文件,没有放',
118
118
  } as const
119
119
 
120
- /** 各条命令的固定入口放得怎样,状态一样的并在一起说:testpace 已放好;modwall、testcraft 没放:…… */
120
+ /** 各条命令的固定入口放得怎样,状态一样的并在一起说:testpace 已放好;modwall、testcraft、codekeep 没放:…… */
121
121
  function entryLine(): string {
122
122
  const states = Object.keys(ENTRY_STATES) as EntryState[]
123
123
  return states
@@ -0,0 +1,8 @@
1
+ // codekeep 命令行入口:check(实现在 keep/commands.ts)。
2
+ // 这个文件的路径不能变:bin/codekeep 和整组里"代码规范"的那一段按它找。
3
+
4
+ import './modules.ts'
5
+ import { runCommandLine } from './base/commandline.ts'
6
+ import { main, outside } from './keep/commands.ts'
7
+
8
+ process.exitCode = await runCommandLine({ name: 'codekeep', outside, run: main }, process.argv.slice(2))
@@ -0,0 +1,296 @@
1
+ // codekeep check:整组里"代码规范"的那一段(见 full.ts),也可以单独跑。依次做四件事,一件没过就停:
2
+ // 1. 配置写得对不对(.codekeep/config.json),写到的文件在不在;现在这一版 eslint、prettier、tsconfig 生效的配置算不算得出来。
3
+ // 2. 和分叉点比,规范改松了哪些(loosen.ts、eslint.ts、prettier.ts、tsconfig.ts;biome 只看配置文件改没改)。放松的条目交给底座的用户确认(askUser),
4
+ // 还没同意的这一段不过,照底座给的话让 agent 调确认工具。分叉点上还没有配置(首次接入)的不比、不问。
5
+ // 分叉点那一版算不出来的(工具在那一版上跑不起来),不当成没放松,列成"程序看不出"的一项,问。
6
+ // 3. 依次跑 checks 里的命令(从仓库根目录用 sh 跑),一条没过就停。
7
+ // 4. secrets 开着时用 gitleaks 扫这次改动(secrets.ts)。
8
+ // 退出码用底座的:0 通过;1 没通过;2 配置、环境问题(配置写错、工具没装、算不出分叉点)。
9
+
10
+ import { spawnSync } from 'node:child_process'
11
+ import { existsSync } from 'node:fs'
12
+ import { join } from 'node:path'
13
+ import { askUser, type ConfirmItem } from '../base/confirm.ts'
14
+ import { EXIT } from '../base/exit.ts'
15
+ import { PROJECT_ENV } from '../base/execute.ts'
16
+ import { filesNow, forkPoint } from '../base/git.ts'
17
+ import { judgingFile } from '../base/judging.ts'
18
+ import { hash } from '../base/records.ts'
19
+ import type { Repo } from '../base/repo.ts'
20
+ import { type Config, CONFIG_PATH, joined, KEEP_DIR, missingFiles, parseConfig } from './config.ts'
21
+ import { eslintItems, type FileRules, fileRules, isCode, loadEslint, stable } from './eslint.ts'
22
+ import { withForkTree } from './forktree.ts'
23
+ import { BIOME_CONFIGS, biomeItem, configItems, GITLEAKS_CONFIG, GITLEAKS_IGNORE, gitleaksItems, removedItem, suppressionsItem } from './loosen.ts'
24
+ import { checkedFiles, loadPrettier, prettierItem } from './prettier.ts'
25
+ import { scanSecrets } from './secrets.ts'
26
+ import { findTsc, type TsSettings, tsconfigItem, tsSettings } from './tsconfig.ts'
27
+
28
+ /** 弹窗开头说这是什么的半句。 */
29
+ const HEADING = '这次改动里放松代码规范的地方'
30
+
31
+ const firstLine = (error: unknown): string => (error instanceof Error ? error.message : String(error)).split('\n')[0] ?? ''
32
+
33
+ /** 现在这一版 eslint、prettier、tsconfig 生效的配置。files 是工作区里现有的文件。 */
34
+ interface NowSide {
35
+ files: string[]
36
+ eslint?: FileRules
37
+ prettier?: Set<string>
38
+ tsconfig: Map<string, TsSettings>
39
+ }
40
+
41
+ /** 现在这一版算出来;算不出来的、eslint 一个文件都不查的说清楚(配置、环境问题)。 */
42
+ async function nowSide(root: string, config: Config): Promise<NowSide | { problems: string[] }> {
43
+ const problems: string[] = []
44
+ const side: NowSide = { files: filesNow(root), tsconfig: new Map() }
45
+ if (config.eslint) {
46
+ try {
47
+ const eslint = await loadEslint(root, config.eslint.config)
48
+ side.eslint = await fileRules(eslint, root, config.eslint.config, side.files.filter(isCode))
49
+ if (![...side.eslint.values()].some(Boolean)) problems.push(`${config.eslint.config} 一个代码文件都没 lint 到(都被忽略了,或配置没覆盖它们)`)
50
+ } catch (error) {
51
+ problems.push(`eslint 生效的规则算不出来(${config.eslint.config}):${firstLine(error)}`)
52
+ }
53
+ }
54
+ if (config.prettier) {
55
+ try {
56
+ side.prettier = await checkedFiles(await loadPrettier(root), root, side.files)
57
+ } catch (error) {
58
+ problems.push(`格式检查查哪些文件算不出来(prettier):${firstLine(error)}`)
59
+ }
60
+ }
61
+ for (const path of config.tsconfig) {
62
+ try {
63
+ side.tsconfig.set(path, tsSettings(findTsc(root, path), root, path))
64
+ } catch (error) {
65
+ problems.push(`${path} 生效的选项算不出来:${firstLine(error)}`)
66
+ }
67
+ }
68
+ return problems.length ? { problems } : side
69
+ }
70
+
71
+ /** 放松的条目,和分叉点那一版算不出来的原因(只给 agent 看,不进弹窗)。 */
72
+ interface Loosened {
73
+ items: ConfirmItem[]
74
+ reasons: string[]
75
+ }
76
+
77
+ /** 分叉点那一版算不出来:列成"程序看不出"的一项。同意过一次后,现在这一版算出来的不变就不再问。 */
78
+ function unknownItem(kind: string, before: unknown, now: unknown, text: string): ConfirmItem {
79
+ return { before: stable([kind, before]), after: hash(stable([kind, now])), text: `${text}:分叉点那一版算不出来,程序看不出这次是改松还是改紧` }
80
+ }
81
+
82
+ /** 要跑工具才比得出来的:eslint 生效的规则、格式检查查哪些文件、tsconfig 的严格选项。分叉点那一版在临时 worktree 里算。 */
83
+ async function toolItems(root: string, fork: string, before: Config, now: Config, side: NowSide): Promise<Loosened> {
84
+ const result: Loosened = { items: [], reasons: [] }
85
+ const lint = Boolean(before.eslint && side.eslint)
86
+ const format = Boolean(before.prettier && side.prettier)
87
+ const tsconfigs = before.tsconfig.filter(path => now.tsconfig.includes(path))
88
+ if (!lint && !format && tsconfigs.length === 0) return result
89
+ const unknown = {
90
+ lint: (reason: string): void => {
91
+ result.reasons.push(`eslint 生效的规则(分叉点那一版):${reason}`)
92
+ result.items.push(unknownItem('eslint-unknown', before.eslint, [...side.eslint!], 'lint 规则'))
93
+ },
94
+ format: (reason: string): void => {
95
+ result.reasons.push(`格式检查查哪些文件(分叉点那一版):${reason}`)
96
+ result.items.push(unknownItem('prettier-unknown', true, [...side.prettier!].sort(), '格式检查查哪些文件'))
97
+ },
98
+ tsconfig: (path: string, reason: string): void => {
99
+ result.reasons.push(`${path}(分叉点那一版):${reason}`)
100
+ result.items.push(unknownItem('tsconfig-unknown', path, side.tsconfig.get(path), `类型检查的配置 ${path}`))
101
+ },
102
+ }
103
+ try {
104
+ await withForkTree(root, fork, async tree => {
105
+ // 两边都有的文件:这次新加的没有"原来"
106
+ const shared = side.files.filter(file => existsSync(join(tree.root, file)))
107
+ if (lint) {
108
+ try {
109
+ const eslint = await loadEslint(root, now.eslint!.config)
110
+ const old = await fileRules(eslint, tree.root, before.eslint!.config, shared.filter(isCode))
111
+ result.items.push(...eslintItems(old, side.eslint!))
112
+ } catch (error) {
113
+ unknown.lint(firstLine(error))
114
+ }
115
+ }
116
+ if (format) {
117
+ try {
118
+ const old = await checkedFiles(await loadPrettier(root), tree.root, shared)
119
+ const item = prettierItem(old, side.prettier!, shared)
120
+ if (item) result.items.push(item)
121
+ } catch (error) {
122
+ unknown.format(firstLine(error))
123
+ }
124
+ }
125
+ for (const path of tsconfigs) {
126
+ try {
127
+ const item = tsconfigItem(path, tsSettings(findTsc(root, path), tree.root, path), side.tsconfig.get(path)!)
128
+ if (item) result.items.push(item)
129
+ } catch (error) {
130
+ unknown.tsconfig(path, firstLine(error))
131
+ }
132
+ }
133
+ })
134
+ } catch (error) {
135
+ // 临时 worktree 建不起来:都算不出来
136
+ const reason = `分叉点的临时 worktree 建不起来:${firstLine(error)}`
137
+ result.items = []
138
+ result.reasons = []
139
+ if (lint) unknown.lint(reason)
140
+ if (format) unknown.format(reason)
141
+ for (const path of tsconfigs) unknown.tsconfig(path, reason)
142
+ }
143
+ return result
144
+ }
145
+
146
+ /** 和分叉点那一版比,放松了哪些。beforeText 是分叉点上的配置文件(没有就是首次接入,不比)。 */
147
+ async function loosened(root: string, fork: string, beforeText: string | undefined, now: Config, side: NowSide): Promise<Loosened> {
148
+ if (beforeText === undefined) return { items: [], reasons: [] }
149
+ const before = parseConfig(beforeText).config
150
+ if (!before) {
151
+ return {
152
+ items: [{ before: stable(['config-unknown', beforeText]), after: stable(['config-unknown', now]), text: `分叉点上的 ${CONFIG_PATH} 写得不对、读不出来,程序看不出这次规范是改松还是改紧` }],
153
+ reasons: [`分叉点上的 ${CONFIG_PATH} 读不出来:${parseConfig(beforeText).problems.join(';')}`],
154
+ }
155
+ }
156
+ const tools = await toolItems(root, fork, before, now, side)
157
+ const items = [...configItems(before, now), ...tools.items]
158
+ if (before.eslint && now.eslint) {
159
+ const item = suppressionsItem(now.eslint.suppressions, judgingFile(root, fork, now.eslint.suppressions))
160
+ if (item) items.push(item)
161
+ }
162
+ if (before.secrets) items.push(...gitleaksItems(judgingFile(root, fork, GITLEAKS_IGNORE), judgingFile(root, fork, GITLEAKS_CONFIG)))
163
+ for (const path of BIOME_CONFIGS) {
164
+ const item = biomeItem(path, judgingFile(root, fork, path))
165
+ if (item) items.push(item)
166
+ }
167
+ return { items, reasons: tools.reasons }
168
+ }
169
+
170
+ /** 一项的头一句:第一行以冒号结尾的(下面逐行列的),带上第二行。 */
171
+ function headline(text: string): string {
172
+ const [first = '', second] = text.split('\n')
173
+ return first.endsWith(':') && second ? `${first}${second}` : first
174
+ }
175
+
176
+ /** 没同意的放松:说给 agent 的话。 */
177
+ function askLines(items: ConfirmItem[], ask: string[], reasons: string[]): string[] {
178
+ return [
179
+ `规范改松了 ${items.length} 项(和分叉点上的比),要用户同意:`,
180
+ ...items.map(item => ` · ${headline(item.text)}`),
181
+ ...(reasons.length ? ['分叉点那一版算不出来的原因(不用给用户看):', ...reasons.map(reason => ` · ${reason}`)] : []),
182
+ '用户不同意的,改回去,按规范改代码。',
183
+ ...ask,
184
+ ]
185
+ }
186
+
187
+ /** 跑 checks 里的命令,一条没过就停。返回没过的那条和原因。 */
188
+ function runChecks(root: string, config: Config): { name: string; cause: string } | undefined {
189
+ for (const check of config.checks) {
190
+ console.log(`== 规范检查:${check.name}(${check.command})`)
191
+ const r = spawnSync('/bin/sh', ['-c', check.command], { cwd: root, env: PROJECT_ENV, stdio: ['ignore', 'inherit', 'inherit'] })
192
+ if (r.status === 0) continue
193
+ const cause = r.status !== null ? `退出码 ${r.status}` : r.signal ? `被信号 ${r.signal} 终止` : `没能启动:${r.error?.message ?? ''}`
194
+ return { name: check.name, cause }
195
+ }
196
+ return undefined
197
+ }
198
+
199
+ export async function check(repo: Repo): Promise<number> {
200
+ const { root } = repo
201
+ const fork = forkPoint(root)
202
+ if (!joined(root, fork.commit)) {
203
+ console.log(`这个仓库没有接入 codekeep(没有 ${KEEP_DIR}/ 目录),不检查。`)
204
+ return EXIT.ok
205
+ }
206
+ if ('problem' in fork) {
207
+ console.error(`没法检查:${fork.problem}(规范改没改松要和分叉点上的配置比)`)
208
+ return EXIT.usage
209
+ }
210
+ const judging = judgingFile(root, fork.commit, CONFIG_PATH)
211
+
212
+ // 配置删掉了:分叉点上有能用的配置的,删掉算放松,用户同意过就退出 codekeep
213
+ if (judging.now === undefined) {
214
+ const before = judging.before === undefined ? undefined : parseConfig(judging.before).config
215
+ if (!before) {
216
+ const hasDir = existsSync(join(root, KEEP_DIR))
217
+ console.error(
218
+ hasDir
219
+ ? `codekeep check:有 ${KEEP_DIR}/ 目录但没有 ${CONFIG_PATH},照 gatelight:setup-codekeep 技能写好配置。`
220
+ : `codekeep check:工作区里删掉了 ${KEEP_DIR}/,分叉点上的 ${CONFIG_PATH} 又不在或写得不对:没有能用的配置,没法判断这次改松了什么。要继续用 codekeep 就恢复配置;要退出,先在默认分支上把配置改好,再删掉 ${KEEP_DIR}/。`,
221
+ )
222
+ return EXIT.usage
223
+ }
224
+ const item = removedItem(before, existsSync(join(root, KEEP_DIR)))
225
+ const asked = askUser(repo, 'keep', HEADING, [item])
226
+ if (!asked.ask) {
227
+ console.log('codekeep check:通过。配置删掉了,用户同意过:这份改动退出 codekeep,不再检查。')
228
+ return EXIT.ok
229
+ }
230
+ console.log(['codekeep check:没通过。', '', ...askLines([item], asked.ask.lines, [])].join('\n'))
231
+ return EXIT.fail
232
+ }
233
+
234
+ // 1. 配置
235
+ const parsed = parseConfig(judging.now)
236
+ const problems = parsed.config ? missingFiles(root, parsed.config) : parsed.problems
237
+ if (!parsed.config || problems.length) {
238
+ console.error([`codekeep check:配置有问题(${CONFIG_PATH}),先改好再检查:`, ...problems.map(text => ` ✗ ${text}`)].join('\n'))
239
+ return EXIT.usage
240
+ }
241
+ const config = parsed.config
242
+ const side = await nowSide(root, config)
243
+ if ('problems' in side) {
244
+ console.error([`codekeep check:现在这一版的规范配置算不出来,先修好(依赖没装的先装好):`, ...side.problems.map(text => ` ✗ ${text}`)].join('\n'))
245
+ return EXIT.usage
246
+ }
247
+
248
+ // 2. 放松
249
+ const found = await loosened(root, fork.commit, judging.before, config, side)
250
+ const asked = askUser(repo, 'keep', HEADING, found.items)
251
+ if (asked.ask) {
252
+ console.log(['codekeep check:没通过。', '', ...askLines(asked.pending, asked.ask.lines, found.reasons)].join('\n'))
253
+ return EXIT.fail
254
+ }
255
+ const loosenedLine = found.items.length ? `规范改松 ${found.items.length} 项,用户都同意过` : '规范配置没有改松(和分叉点上的比)'
256
+
257
+ // 3. 规范检查
258
+ const failed = runChecks(root, config)
259
+ if (failed) {
260
+ console.log(
261
+ `\ncodekeep check:没通过,规范检查"${failed.name}"没过(${failed.cause})。按上面的输出改代码;不要为了过关改松规范(关规则、降级、调高上限、加忽略、加豁免),确实要改的先用白话跟用户讲清。`,
262
+ )
263
+ return EXIT.fail
264
+ }
265
+
266
+ // 4. 密钥
267
+ if (config.secrets) {
268
+ const secrets = scanSecrets(root, fork.commit)
269
+ if ('missing' in secrets) {
270
+ console.error(
271
+ `\ncodekeep check:没通过,找不到 gitleaks(${CONFIG_PATH} 开着 secrets,要用它扫密钥)。这是装在这台机器上的工具,先问用户;同意后装:brew install gitleaks(没有 Homebrew 的见 https://github.com/gitleaks/gitleaks#installing)。`,
272
+ )
273
+ return EXIT.usage
274
+ }
275
+ if ('problem' in secrets) {
276
+ console.error(`\ncodekeep check:没通过,密钥没扫成:${secrets.problem}`)
277
+ return EXIT.usage
278
+ }
279
+ if ('leaks' in secrets) {
280
+ console.log(
281
+ [
282
+ '',
283
+ 'codekeep check:没通过,gitleaks 在这次改动里扫出了疑似密钥(上面列出,已打码)。改法:',
284
+ ' · 真的密钥、密码:从代码里拿掉,改成从环境变量或不进版本库的本地配置读,并告诉用户这个密钥可能已经泄露、要换掉。已经提交了的,要改写这个分支上的那几个提交才去得掉,先问用户。',
285
+ ' · 测试用的假值:改成一眼看得出是假的写法(比如 test-password-not-real)。',
286
+ ` · 确实不是密钥的:把那一条的 Fingerprint 加进 ${GITLEAKS_IGNORE}(算放松,整组会要用户确认)。`,
287
+ ].join('\n'),
288
+ )
289
+ return EXIT.fail
290
+ }
291
+ }
292
+
293
+ const names = config.checks.map(item => item.name).join('、')
294
+ console.log(`\ncodekeep check:通过。${loosenedLine};规范检查都过了(${names})${config.secrets ? ';这次改动里没扫出密钥' : ''}。`)
295
+ return EXIT.ok
296
+ }
@@ -0,0 +1,48 @@
1
+ // codekeep 的命令:check。命令入口(src/codekeep.ts)分发到这里。
2
+ // check 也是整组里的一段(见 full.ts):接入了的仓库,testpace full 在测试之前跑它,不用另外登记。
3
+
4
+ import { EXIT } from '../base/exit.ts'
5
+ import { openRepo } from '../base/repo.ts'
6
+ import { check } from './check.ts'
7
+ import { CONFIG_PATH } from './config.ts'
8
+
9
+ const USAGE = `用法:
10
+ codekeep check 规范检查:${CONFIG_PATH} 写得对不对;和分叉点比规范改松了哪些(改松的要用户确认);
11
+ 依次跑 checks 里的命令;secrets 开着时用 gitleaks 扫这次改动里的密钥。
12
+ 接入了的仓库,testpace full 里自动跑它`
13
+
14
+ /** 退出码用底座的:0 通过;1 没通过;2 用法、配置或环境问题。 */
15
+
16
+ /**
17
+ * 在 agent 的沙箱里跑不了的子命令和它要做的事(见 base/commandline.ts)。
18
+ * check 要跑项目的检查命令、在系统临时目录建分叉点的临时 worktree、写 .git/testpace/ 的确认记录,沙箱里会被拒。
19
+ */
20
+ export function outside(argv: string[]): string | undefined {
21
+ return argv[0] === 'check' ? `跑 ${CONFIG_PATH} 里的检查命令和 gitleaks、在系统临时目录建分叉点的临时 worktree、写 .git/testpace/ 的记录` : undefined
22
+ }
23
+
24
+ export async function main(argv: string[]): Promise<number> {
25
+ switch (argv[0]) {
26
+ case 'check': {
27
+ if (argv.length > 1) {
28
+ console.error(`不认识的参数:${argv.slice(1).join(' ')}\n${USAGE}`)
29
+ return EXIT.usage
30
+ }
31
+ const repo = openRepo(process.cwd())
32
+ if (!repo) {
33
+ console.error('codekeep 要在 git 仓库里运行。')
34
+ return EXIT.usage
35
+ }
36
+ return check(repo)
37
+ }
38
+ case undefined:
39
+ case '-h':
40
+ case '--help':
41
+ case 'help':
42
+ console.log(USAGE)
43
+ return argv[0] === undefined ? EXIT.usage : EXIT.ok
44
+ default:
45
+ console.error(`不认识的命令:${argv[0]}\n${USAGE}`)
46
+ return EXIT.usage
47
+ }
48
+ }