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
@@ -0,0 +1,248 @@
1
+ // modwall migrate、modwall db bootstrap:生成交给 psql 的脚本。不连数据库、不装客户端库,和 db check 一样由项目给执行 SQL 的命令;
2
+ // 线上没有 gatelight 也没有仓库,打包时用 --print 生成脚本带上去,只用 psql 跑。脚本可以重复执行,要跑哪些由脚本在库里判断。
3
+ // 要 Postgres 16 以上:成员关系按条设 INHERIT FALSE、SET TRUE,建角色的账号只能管自己建的角色(别人建的同名角色会被拒,不会被借用)。
4
+
5
+ import { createHash } from 'node:crypto'
6
+ import { spawnSync } from 'node:child_process'
7
+ import { readFileSync } from 'node:fs'
8
+ import { join } from 'node:path'
9
+ import { apiOf, type Database, groupOf, internalOf, runtimeOf, SHARED_SCHEMA } from './database.ts'
10
+ import type { Module } from './layout.ts'
11
+
12
+ export const LEDGER = `${SHARED_SCHEMA}.modwall_migrations`
13
+ const MIN_VERSION = 160000
14
+
15
+ const ident = (name: string): string => `"${name.replace(/"/g, '""')}"`
16
+ const literal = (text: string): string => `'${text.replace(/'/g, "''")}'`
17
+
18
+ /** 不出现在 text 里的 dollar 引号。 */
19
+ function dollarTag(text: string, seed: string): string {
20
+ for (let i = 0; ; i++) {
21
+ const tag = `$modwall_${seed}${i || ''}$`
22
+ if (!text.includes(tag)) return tag
23
+ }
24
+ }
25
+ const dollar = (text: string, seed: string): string => {
26
+ const tag = dollarTag(text, seed)
27
+ return `${tag}${text}${tag}`
28
+ }
29
+
30
+ /** 一段 DO:正文里有错就 RAISE,psql 带 ON_ERROR_STOP 停下、退出码非零。 */
31
+ const doBlock = (body: string): string => `DO ${dollar(body, 'do')};`
32
+
33
+ const HEADER = String.raw`\set ON_ERROR_STOP on
34
+ \set QUIET on
35
+ \pset pager off
36
+ \encoding UTF8
37
+ SET client_min_messages = warning;`
38
+
39
+ const versionCheck = (command: string): string =>
40
+ `IF current_setting('server_version_num')::int < ${MIN_VERSION} THEN
41
+ RAISE EXCEPTION '${command} 要 Postgres 16 以上,这个库是 %', current_setting('server_version');
42
+ END IF;`
43
+
44
+ const modulesOf = (database: Database): Module[] => [...database.schemas.values()].flatMap(owner => (owner.kind === 'internal' ? [owner.module] : []))
45
+
46
+ interface Planned {
47
+ path: string
48
+ name: string
49
+ checksum: string
50
+ owner: string
51
+ script: string
52
+ }
53
+
54
+ /** 迁移按文件名统一排序(文件名以时间戳开头);记录按文件名认,文件跟着目录挪了不会再跑。 */
55
+ function planned(database: Database, read: (path: string) => string): Planned[] {
56
+ return database.migrations
57
+ .map(({ path, module }) => {
58
+ const script = read(path)
59
+ return {
60
+ path,
61
+ name: path.slice(path.lastIndexOf('/') + 1),
62
+ checksum: createHash('sha256').update(script).digest('hex'),
63
+ owner: module ? internalOf(module) : SHARED_SCHEMA,
64
+ script,
65
+ }
66
+ })
67
+ .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
68
+ }
69
+
70
+ /** modwall migrate 的脚本:用跑迁移的账号执行。 */
71
+ export function migrateScript(database: Database, read: (path: string) => string): string {
72
+ const config = database.app.database
73
+ if (!config) throw new Error('这个应用没有写 database')
74
+ const modules = modulesOf(database)
75
+ const group = groupOf(config.login)
76
+ const runtimes = config.runtime === undefined ? [] : modules.map(module => runtimeOf(module, config.runtime as string))
77
+ const owners = [SHARED_SCHEMA, ...modules.map(internalOf)]
78
+ const roles = [...owners, group, ...runtimes]
79
+ const migrations = planned(database, read)
80
+ const migrator = config.migrator
81
+ const out: string[] = [`-- modwall migrate 生成${database.app.name === undefined ? '' : `(${database.app.name} 应用)`}:用跑迁移的账号 ${migrator} 执行,可以重复执行。`, HEADER]
82
+
83
+ out.push(
84
+ doBlock(`
85
+ BEGIN
86
+ ${versionCheck('modwall migrate')}
87
+ IF current_user <> ${literal(migrator)} THEN
88
+ RAISE EXCEPTION 'modwall migrate 要用跑迁移的账号 ${migrator} 连库(.modwall/config.json 的 database.migrator),现在连的是 %', current_user;
89
+ END IF;
90
+ IF NOT (SELECT rolcreaterole FROM pg_roles WHERE rolname = current_user) OR NOT has_database_privilege(current_database(), 'CREATE') THEN
91
+ RAISE EXCEPTION '跑迁移的账号 ${migrator} 要能建角色、能在库里建 schema:先用超级用户跑 modwall db bootstrap';
92
+ END IF;
93
+ END`),
94
+ )
95
+ // 同一个库同时跑两次时排队;锁到 psql 退出为止
96
+ out.push(`SELECT pg_advisory_lock(hashtext('modwall migrate')) AS modwall_locked \\gset`)
97
+
98
+ out.push('BEGIN;')
99
+ out.push(
100
+ doBlock(`
101
+ DECLARE
102
+ r text;
103
+ BEGIN
104
+ FOREACH r IN ARRAY ARRAY[${roles.map(literal).join(', ')}] LOOP
105
+ IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = r) THEN
106
+ EXECUTE format('CREATE ROLE %I NOLOGIN', r);
107
+ ELSIF NOT EXISTS (
108
+ SELECT FROM pg_auth_members m JOIN pg_roles g ON g.oid = m.roleid JOIN pg_roles u ON u.oid = m.member
109
+ WHERE g.rolname = r AND u.rolname = current_user AND m.admin_option
110
+ ) THEN
111
+ RAISE EXCEPTION '角色 % 已经有了,但不是跑迁移的账号 % 建的:角色整个实例共用,同一个实例上别的项目或别人建了同名的角色。换个模块名,或者用单独的实例', r, current_user;
112
+ END IF;
113
+ END LOOP;
114
+ END`),
115
+ )
116
+ for (const owner of owners) out.push(`GRANT ${ident(owner)} TO ${ident(migrator)} WITH INHERIT FALSE, SET TRUE;`)
117
+ const loginRoles = config.runtime === undefined ? owners.filter(owner => owner !== SHARED_SCHEMA) : runtimes
118
+ for (const role of loginRoles) out.push(`GRANT ${ident(role)} TO ${ident(config.login)} WITH INHERIT FALSE, SET TRUE;`)
119
+ // 后来才写 runtime 的,登录账号原来是模块角色的成员:收回,程序只能切成运行角色
120
+ if (config.runtime !== undefined && modules.length) {
121
+ out.push(
122
+ doBlock(`
123
+ DECLARE
124
+ r text;
125
+ BEGIN
126
+ FOREACH r IN ARRAY ARRAY[${modules.map(module => literal(internalOf(module))).join(', ')}] LOOP
127
+ IF EXISTS (
128
+ SELECT FROM pg_auth_members m JOIN pg_roles g ON g.oid = m.roleid JOIN pg_roles u ON u.oid = m.member
129
+ WHERE g.rolname = r AND u.rolname = ${literal(config.login)}
130
+ ) THEN
131
+ EXECUTE format('REVOKE %I FROM %I', r, ${literal(config.login)});
132
+ END IF;
133
+ END LOOP;
134
+ END`),
135
+ )
136
+ }
137
+ for (const role of [...owners.filter(owner => owner !== SHARED_SCHEMA), ...runtimes]) out.push(`GRANT ${ident(group)} TO ${ident(role)} WITH INHERIT TRUE, SET FALSE;`)
138
+
139
+ out.push(`CREATE SCHEMA IF NOT EXISTS ${ident(SHARED_SCHEMA)} AUTHORIZATION ${ident(SHARED_SCHEMA)};`)
140
+ for (const module of modules) {
141
+ out.push(`CREATE SCHEMA IF NOT EXISTS ${ident(internalOf(module))} AUTHORIZATION ${ident(internalOf(module))};`)
142
+ out.push(`CREATE SCHEMA IF NOT EXISTS ${ident(apiOf(module))} AUTHORIZATION ${ident(internalOf(module))};`)
143
+ }
144
+ // 迁移全文交给各自的 run_migration 执行:SECURITY DEFINER 的函数里切不了身份,迁移里写了切身份由库拒绝
145
+ for (const owner of owners) {
146
+ out.push(
147
+ `SET LOCAL ROLE ${ident(owner)};`,
148
+ `CREATE OR REPLACE FUNCTION ${ident(owner)}.run_migration(script text) RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path = ${ident(owner)}, pg_temp AS ${dollar('BEGIN EXECUTE script; END', 'fn')};`,
149
+ `REVOKE ALL ON FUNCTION ${ident(owner)}.run_migration(text) FROM PUBLIC;`,
150
+ )
151
+ if (owner === SHARED_SCHEMA) {
152
+ out.push(
153
+ `GRANT USAGE ON SCHEMA ${ident(SHARED_SCHEMA)} TO ${ident(group)};`,
154
+ `CREATE TABLE IF NOT EXISTS ${LEDGER} (name text PRIMARY KEY, checksum text NOT NULL, applied_at timestamptz NOT NULL DEFAULT now());`,
155
+ )
156
+ } else {
157
+ const api = ident(`${owner}_api`)
158
+ out.push(`GRANT USAGE ON SCHEMA ${api} TO ${ident(group)};`, `ALTER DEFAULT PRIVILEGES IN SCHEMA ${api} GRANT SELECT ON TABLES TO ${ident(group)};`)
159
+ }
160
+ out.push('RESET ROLE;')
161
+ }
162
+ out.push('COMMIT;')
163
+
164
+ // 跑过的迁移改了、删了,库和文件就对不上了:先查,有一个就一个都不跑
165
+ const files = migrations.length
166
+ ? `(VALUES ${migrations.map(m => `(${literal(m.name)}, ${literal(m.checksum)})`).join(', ')}) AS f(name, checksum)`
167
+ : '(SELECT NULL::text AS name, NULL::text AS checksum WHERE false) AS f'
168
+ out.push(
169
+ 'BEGIN;',
170
+ `SET LOCAL ROLE ${ident(SHARED_SCHEMA)};`,
171
+ doBlock(`
172
+ DECLARE
173
+ changed text;
174
+ missing text;
175
+ BEGIN
176
+ SELECT string_agg(l.name, '、' ORDER BY l.name) INTO changed FROM ${LEDGER} l JOIN ${files} USING (name) WHERE l.checksum <> f.checksum;
177
+ SELECT string_agg(l.name, '、' ORDER BY l.name) INTO missing FROM ${LEDGER} l WHERE NOT EXISTS (SELECT FROM ${files} WHERE f.name = l.name);
178
+ IF changed IS NOT NULL OR missing IS NOT NULL THEN
179
+ RAISE EXCEPTION '跑过的迁移%,一个都没跑。迁移只加不改:已合进默认分支的改回原样,要改的写成新的迁移;分支上自己新写的,把开发库重置了再跑',
180
+ concat_ws(';', '改了内容:' || changed, '文件不见了:' || missing);
181
+ END IF;
182
+ END`),
183
+ 'COMMIT;',
184
+ '\\set modwall_ran 0',
185
+ )
186
+
187
+ for (const m of migrations) {
188
+ out.push(
189
+ '',
190
+ `-- ${m.path}`,
191
+ 'BEGIN;',
192
+ `SET LOCAL ROLE ${ident(SHARED_SCHEMA)};`,
193
+ `SELECT NOT EXISTS (SELECT FROM ${LEDGER} WHERE name = ${literal(m.name)}) AS modwall_pending \\gset`,
194
+ 'COMMIT;',
195
+ '\\if :modwall_pending',
196
+ `\\echo modwall migrate:执行 ${m.path}`,
197
+ 'BEGIN;',
198
+ `SET LOCAL ROLE ${ident(m.owner)};`,
199
+ `SELECT ${ident(m.owner)}.run_migration(${dollar(m.script, m.checksum.slice(0, 8))}) AS modwall_done \\gset`,
200
+ `SET LOCAL ROLE ${ident(SHARED_SCHEMA)};`,
201
+ `INSERT INTO ${LEDGER} (name, checksum) VALUES (${literal(m.name)}, ${literal(m.checksum)});`,
202
+ 'COMMIT;',
203
+ '\\set modwall_ran 1',
204
+ '\\endif',
205
+ )
206
+ }
207
+ out.push('', '\\if :modwall_ran', '\\echo modwall migrate:完成', '\\else', '\\echo modwall migrate:没有要跑的迁移,库已是最新', '\\endif', '')
208
+ return out.join('\n')
209
+ }
210
+
211
+ /** modwall db bootstrap 的脚本:用超级用户(或能建角色、拥有这个库的账号)执行。不设密码。 */
212
+ export function bootstrapScript(database: Database): string {
213
+ const config = database.app.database
214
+ if (!config) throw new Error('这个应用没有写 database')
215
+ const { login, migrator } = config
216
+ return [
217
+ `-- modwall db bootstrap 生成${database.app.name === undefined ? '' : `(${database.app.name} 应用)`}:用超级用户在要用的库里执行,可以重复执行。不设密码。`,
218
+ HEADER,
219
+ doBlock(`
220
+ BEGIN
221
+ ${versionCheck('modwall db bootstrap')}
222
+ IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${literal(login)}) THEN
223
+ CREATE ROLE ${ident(login)} LOGIN NOINHERIT;
224
+ END IF;
225
+ IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${literal(migrator)}) THEN
226
+ CREATE ROLE ${ident(migrator)} LOGIN NOINHERIT CREATEROLE;
227
+ END IF;
228
+ EXECUTE format('REVOKE CONNECT ON DATABASE %I FROM PUBLIC', current_database());
229
+ EXECUTE format('GRANT CONNECT ON DATABASE %I TO %I, %I', current_database(), ${literal(login)}, ${literal(migrator)});
230
+ EXECUTE format('GRANT CREATE ON DATABASE %I TO %I', current_database(), ${literal(migrator)});
231
+ END`),
232
+ // 两个账号本身没有权限、不继承模块角色,只能切身份;迁移账号另外能建角色(它建的模块角色归它管)
233
+ `ALTER ROLE ${ident(login)} LOGIN NOINHERIT NOCREATEROLE NOCREATEDB;`,
234
+ `ALTER ROLE ${ident(migrator)} LOGIN NOINHERIT CREATEROLE NOCREATEDB;`,
235
+ 'REVOKE CREATE ON SCHEMA public FROM PUBLIC;',
236
+ `\\echo modwall db bootstrap:账号 ${login}、${migrator} 好了,库只让这两个连。密码按项目的方式设(ALTER ROLE … PASSWORD)`,
237
+ '',
238
+ ].join('\n')
239
+ }
240
+
241
+ /** 读迁移文件:路径相对仓库根目录。 */
242
+ export const fileReader = (root: string) => (path: string): string => readFileSync(join(root, path), 'utf8')
243
+
244
+ /** 把脚本从标准输入交给项目给的命令(在 sh 里跑),输出原样给用户。status:命令的退出码;没跑起来时有 error。 */
245
+ export function runScript(root: string, command: string, script: string): { status: number | null; error?: string } {
246
+ const r = spawnSync('/bin/sh', ['-c', command], { cwd: root, input: script, stdio: ['pipe', 'inherit', 'inherit'] })
247
+ return r.error ? { status: null, error: r.error.message } : { status: r.status }
248
+ }
@@ -8,9 +8,10 @@ import { currentBranch, fileNow, filesNow, forkPoint } from '../base/git.ts'
8
8
  import { judgingFile } from '../base/judging.ts'
9
9
  import { hash } from '../base/records.ts'
10
10
  import { type Config, CONFIG_PATH, joined, MODWALL_DIR, parseConfig, readConfig } from './config.ts'
11
- import { isCode } from './files.ts'
11
+ import { isCode, isTest } from './files.ts'
12
12
  import { Layout } from './layout.ts'
13
- import { type ConfigSide, configText } from './loosen.ts'
13
+ import { type ConfigSide, looseningItems } from './loosen.ts'
14
+ import type { PassRecord, Store } from './store.ts'
14
15
 
15
16
  export interface Project {
16
17
  root: string
@@ -57,19 +58,23 @@ export function layoutOf(project: Project, config: Config): Layout {
57
58
  return new Layout(config, project.files)
58
59
  }
59
60
 
60
- /** 影响检查结果的文件:代码文件(含测试),JSON(配置、路径别名、包清单、小程序页面配置),Python 和 Go 的项目文件,SQL(迁移),小程序的模板和样式。 */
61
- const MATTERS = (path: string): boolean => isCode(path) || /\.(?:json|toml|sql|wxml|wxss)$/.test(path) || /(?:^|\/)go\.(?:mod|work)$/.test(path)
61
+ /**
62
+ * 影响检查结果的文件:代码文件,JSON(配置、路径别名、包清单、小程序页面配置),Python 和 Go 的项目文件,SQL(迁移),小程序的模板和样式。
63
+ * 测试文件不算:检查不看测试发起的引用,算进来的话只改测试也要重跑。正式代码引用测试文件那种越界,整组里的 modwall check 照查(整组不看通过记录)。
64
+ */
65
+ const MATTERS = (path: string): boolean =>
66
+ !isTest(path) && (isCode(path) || /\.(?:json|toml|sql|wxml|wxss)$/.test(path) || /(?:^|\/)go\.(?:mod|work)$/.test(path))
62
67
 
63
68
  /** contentKey 的算法的名字:算法变了要改它,会话起点里以前记的样子就不算了(见 base/baseline.ts)。 */
64
- export const CONTENT_FORMAT = 'content-1'
69
+ export const CONTENT_FORMAT = 'content-2'
65
70
 
66
71
  /**
67
- * 当前内容的摘要:分叉点上的配置加上影响检查结果的文件。通过记录、会话起点都按它记。
68
- * 检查能不能过,和分叉点有关的只有那里的配置(放宽项和它比;R4、入口清单只是提示),所以不记分叉点的提交号:
69
- * 在默认分支上提交、默认分支往前走,都不让通过记录失效;分叉点上的配置变了才失效。
72
+ * 当前内容的摘要:影响检查结果的文件。通过记录、会话起点都按它记。
73
+ * 不含分叉点上的配置:检查过不过和分叉点有关的只有放宽项,记在通过记录里(checkPassed)。含了的话,
74
+ * 分支改过配置、快进到默认分支后分叉点变成自己,合并前刚通过的记录就对不上了。
70
75
  */
71
76
  export function contentKey(project: Project): string {
72
- const parts: string[] = [project.base ? (project.before.config ? configText(project.before.config) : 'no-config') : 'no-base']
77
+ const parts: string[] = [project.base ? 'base' : 'no-base']
73
78
  for (const path of project.files.filter(MATTERS).sort()) {
74
79
  parts.push(path)
75
80
  try {
@@ -81,6 +86,21 @@ export function contentKey(project: Project): string {
81
86
  return hash(...parts)
82
87
  }
83
88
 
89
+ /** 检查通过时要记的:通过时和分叉点比出来的放宽项(都经用户同意过,不然过不了)。 */
90
+ export function passRecord(project: Project): PassRecord {
91
+ return { at: Date.now(), loosening: looseningItems(project.before.config, project.now).map(item => item.text) }
92
+ }
93
+
94
+ /**
95
+ * 当前内容 modwall check 通过过:有这份内容的通过记录,现在和分叉点比出来的放宽项都在通过时那一组里。
96
+ * 分叉点挪了(快进、合进默认分支)放宽项只会少;多出来的没经用户同意,要重跑。
97
+ */
98
+ export function checkPassed(project: Project, store: Store): boolean {
99
+ const record = store.passes.get(contentKey(project))
100
+ if (!record) return false
101
+ return looseningItems(project.before.config, project.now).every(item => record.loosening.includes(item.text))
102
+ }
103
+
84
104
  /** 这个仓库现在的内容摘要(重新打开一遍);没接入时为 undefined。写通过记录前用它核对内容没变。 */
85
105
  export function currentKey(root: string): string | undefined {
86
106
  const opened = openProject(root)
@@ -0,0 +1,74 @@
1
+ // modwall db check 在整组里交回的凭据。它由项目写进自己的 full 命令(迁移跑完才能查),脚本里删掉那一行,库的模块边界就不查了。
2
+ // 所以不读脚本,按凭据核对:整组给各段命令一个环境变量(DB_RECEIPTS_ENV),db check 查完往那个文件追加一行(查的是哪个应用、过没过);
3
+ // 整组跑完,配置里每个写了 database 的应用都要有凭据、而且都过了。只防看错:凭据是 agent 写得到的文件,故意伪造拦不住。
4
+
5
+ import { appendFileSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
6
+ import { tmpdir } from 'node:os'
7
+ import { join } from 'node:path'
8
+ import { fileNow } from '../base/git.ts'
9
+ import { CONFIG_PATH, readConfig, schemeOf } from './config.ts'
10
+
11
+ export const DB_RECEIPTS_ENV = 'MODWALL_DB_RECEIPTS'
12
+
13
+ /** 一次 db check 的凭据。app:查的是哪个应用的库(单应用的写法没有名字,为 null)。 */
14
+ export interface DbReceipt {
15
+ app: string | null
16
+ passed: boolean
17
+ }
18
+
19
+ /** 给一次整组准备收凭据的文件。用完调 dispose。 */
20
+ export function receiptsFile(): { path: string; dispose: () => void } {
21
+ const dir = mkdtempSync(join(tmpdir(), 'modwall-db-receipts-'))
22
+ return { path: join(dir, 'receipts.jsonl'), dispose: () => rmSync(dir, { recursive: true, force: true }) }
23
+ }
24
+
25
+ /** db check 查完时调:在整组里跑的(有那个环境变量),交一条凭据。 */
26
+ export function leaveReceipt(app: string | undefined, passed: boolean): void {
27
+ const path = process.env[DB_RECEIPTS_ENV]
28
+ if (path) appendFileSync(path, `${JSON.stringify({ app: app ?? null, passed } satisfies DbReceipt)}\n`)
29
+ }
30
+
31
+ function readReceipts(path: string): DbReceipt[] {
32
+ let text: string
33
+ try {
34
+ text = readFileSync(path, 'utf8')
35
+ } catch {
36
+ return []
37
+ }
38
+ return text.split('\n').flatMap(line => {
39
+ try {
40
+ const value = JSON.parse(line) as Partial<DbReceipt>
41
+ return typeof value.passed === 'boolean' && (value.app === null || typeof value.app === 'string') ? [{ app: value.app, passed: value.passed }] : []
42
+ } catch {
43
+ return [] // 空行、写到一半的
44
+ }
45
+ })
46
+ }
47
+
48
+ /** 工作区的配置里写了 database 的应用(单应用的写法为 null)。配置有问题的不算:整组里的 modwall check 已经报了。
49
+ * 不按分叉点要凭据:删掉 database 本来就算放宽、要用户同意,同意了还按分叉点要,modwall db check 交不出凭据,整组永远过不了。 */
50
+ function databaseApps(root: string): Array<string | null> {
51
+ const { config } = readConfig(fileNow(root, CONFIG_PATH))
52
+ if (!config) return []
53
+ return schemeOf(config).apps.filter(app => app.database).map(app => app.name ?? null)
54
+ }
55
+
56
+ /** 整组跑完:写了 database 的应用,哪个没交凭据、哪个没过却没让整组失败。一条一句、写明怎么改。 */
57
+ export function receiptProblems(root: string, path: string): string[] {
58
+ const receipts = readReceipts(path)
59
+ const problems: string[] = []
60
+ const apps = databaseApps(root)
61
+ for (const app of apps) {
62
+ // 只有一个应用写了 database 时,db check 不用 --app 也查它
63
+ const which = app === null ? '' : apps.length > 1 ? `(${app} 应用的库,用 --app ${app})` : `(${app} 应用的库)`
64
+ const mine = receipts.filter(receipt => receipt.app === app)
65
+ if (mine.length === 0) {
66
+ problems.push(
67
+ `整组里没跑 modwall db check${which}:${CONFIG_PATH} 写了 database,项目的 full 命令要在迁移跑完后跑它,查库里的模块边界(写法见 gatelight:setup-modwall 技能)。`,
68
+ )
69
+ } else if (mine.some(receipt => !receipt.passed)) {
70
+ problems.push(`modwall db check${which}没通过,整组却接着跑完了:项目的 full 命令里不要忽略它的退出码(比如 || true),没通过要让整组失败。`)
71
+ }
72
+ }
73
+ return problems
74
+ }
@@ -17,7 +17,7 @@ import { type App, CONFIG_PATH, joined, readConfig, type Scheme, schemeOf } from
17
17
  import { entryBypass } from './edit.ts'
18
18
  import { isCode, unreadDirectory } from './files.ts'
19
19
  import { type Layout, type Module, ownerIn } from './layout.ts'
20
- import { CONTENT_FORMAT, contentKey, layoutOf, openProject } from './project.ts'
20
+ import { checkPassed, CONTENT_FORMAT, contentKey, layoutOf, openProject } from './project.ts'
21
21
  import { unownedText } from './rules.ts'
22
22
  import { MODULE, openStore } from './store.ts'
23
23
 
@@ -47,13 +47,13 @@ export function onSession(repo: Repo, sessionId: string): void {
47
47
  }
48
48
 
49
49
  /** 停止门:这个会话在这个仓库里改了代码或配置(和起点比;没有起点的不算这个会话改的),当前内容还没有 modwall check 的通过记录。 */
50
- export function unfinished(repo: Repo, sessionId: string, seen: readonly string[], named: boolean): { keys: string[]; text: string } | undefined {
50
+ export function unfinished(repo: Repo, sessionId: string, seen: (key: string) => boolean, named: boolean): { keys: string[]; text: string } | undefined {
51
51
  const opened = openProject(repo.root)
52
52
  if ('notJoined' in opened) return undefined
53
53
  const now = contentKey(opened.project)
54
- if (baselines(repo).since(sessionId, now) === now || openStore(repo).passes.get(now)) return undefined
54
+ if (baselines(repo).since(sessionId, now) === now || checkPassed(opened.project, openStore(repo))) return undefined
55
55
  const key = `wall:check:${now}`
56
- if (seen.includes(key)) return undefined
56
+ if (seen(key)) return undefined
57
57
  return {
58
58
  keys: [key],
59
59
  text:
@@ -111,7 +111,7 @@ function databaseLines(scheme: Scheme): string[] {
111
111
  ? '每个模块一个同名的数据库角色,程序每个事务开头切成模块的角色'
112
112
  : `每个模块一个同名的数据库角色(拥有对象,迁移切成它跑)和一个运行角色(${db.runtime},只有本模块的读写授权,不拥有对象、不建对象),程序每个事务开头切成模块的运行角色`
113
113
  return [
114
- `- ${at}数据库(Postgres)也按模块分:模块的表、视图、函数建在它的内部 schema(模块目录名转成小写加下划线,adminAccess → admin_access),给别的模块用的视图和函数放进入口 schema(<内部 schema>_api,不放表);别的模块只引用对方入口 schema 里的对象,不在对方入口上建视图(跨模块读取写在函数正文或代码里),写入走对方入口里的函数,入口只加不改(入口里的类型别的模块可以用),模块之间不建外键(只存 id);只在自己的两个 schema 里建、改、删对象;共享层用 shared,public 里不放对象。迁移放在模块目录下的 ${db.migrations}/(共享层的在 ${db.shared}/),文件名以 14 位时间戳开头,只写正向(一个时间戳一个文件);迁移里不建 schema(跑迁移的工具建);函数一律带 SET search_path = <本模块的内部 schema>, pg_temp、一律 SECURITY DEFINER,迁移和函数里不改 search_path,引用别的模块、shared 写带 schema 的全名;别名、变量不和模块的 schema 同名,引用的表名和别的模块的 schema 同名时起别名。${roles}:迁移和模块的代码里不自己切身份(SET ROLE、set_config('role', …)),切身份只在装配层或共享层的那个小函数里。`,
114
+ `- ${at}数据库(Postgres)也按模块分:模块的表、视图、函数建在它的内部 schema(模块目录名转成小写加下划线,adminAccess → admin_access),给别的模块用的视图和函数放进入口 schema(<内部 schema>_api,不放表);别的模块只引用对方入口 schema 里的对象,不在对方入口上建视图(跨模块读取写在函数正文或代码里),写入走对方入口里的函数,入口只加不改(入口里的类型别的模块可以用),模块之间不建外键(只存 id);只在自己的两个 schema 里建、改、删对象;共享层用 shared,public 里不放对象。迁移放在模块目录下的 ${db.migrations}/(共享层的在 ${db.shared}/),文件名以 14 位时间戳开头,只写正向(一个时间戳一个文件);迁移里不建 schema(modwall migrate 建),写了迁移就用 modwall migrate 跑,跑过的迁移不改不删;函数一律带 SET search_path = <本模块的内部 schema>, pg_temp、一律 SECURITY DEFINER,迁移和函数里不改 search_path,引用别的模块、shared 写带 schema 的全名;别名、变量不和模块的 schema 同名,引用的表名和别的模块的 schema 同名时起别名。${roles}:迁移和模块的代码里不自己切身份(SET ROLE、set_config('role', …)),切身份只在装配层或共享层的那个小函数里。`,
115
115
  ]
116
116
  })
117
117
  }
package/src/wall/store.ts CHANGED
@@ -8,6 +8,8 @@ import { newRunId } from '../base/store.ts'
8
8
 
9
9
  export interface PassRecord {
10
10
  at: number
11
+ /** 通过时和分叉点比出来的放宽项(给用户看的文字)。 */
12
+ loosening: string[]
11
13
  }
12
14
 
13
15
  /** 一个分支上一次查全了的检查:下一次据此算改正了哪些越界。 */
@@ -17,7 +19,7 @@ export interface LastCheck {
17
19
  }
18
20
 
19
21
  export interface Store {
20
- /** modwall check 的通过记录,按当时的内容记,内容变了就对不上。 */
22
+ /** modwall check 的通过记录,按当时的内容记,内容变了就对不上(还算不算数见 project.ts 的 checkPassed)。 */
21
23
  passes: ModuleRecords<PassRecord>
22
24
  /** 按分支记。 */
23
25
  last: ModuleRecords<LastCheck>