dsh-project-flow 0.9.2 → 0.10.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 (72) hide show
  1. package/CHANGELOG.md +0 -0
  2. package/README.md +25 -0
  3. package/checks/assertion.mjs +104 -0
  4. package/checks/command.mjs +416 -0
  5. package/checks/requirement.mjs +91 -0
  6. package/commands/slash.mjs +754 -0
  7. package/commands/steer.mjs +43 -0
  8. package/config/settings.mjs +217 -0
  9. package/docs/DETAIL.md +2 -0
  10. package/docs/FEATURES.md +9 -6
  11. package/docs/anchors/file-whitelist.md +1 -1
  12. package/http/routes.mjs +252 -0
  13. package/index.js +173 -8538
  14. package/issues/issue.mjs +322 -0
  15. package/package.json +16 -1
  16. package/persistence/lock.mjs +67 -0
  17. package/persistence/log.mjs +43 -0
  18. package/persistence/recovery.mjs +118 -0
  19. package/persistence/state.mjs +202 -0
  20. package/pricing/estimate.mjs +72 -0
  21. package/prompts/rules.mjs +192 -0
  22. package/rollback/ledger.mjs +237 -0
  23. package/runner/pipeline.mjs +1190 -0
  24. package/runner/stage.mjs +370 -0
  25. package/runner/tools/context.mjs +64 -0
  26. package/runner/tools/decorate-cost.mjs +49 -0
  27. package/runner/tools/doctor.mjs +59 -0
  28. package/runner/tools/estimate.mjs +63 -0
  29. package/runner/tools/execute-run.mjs +255 -0
  30. package/runner/tools/models.mjs +55 -0
  31. package/runner/tools/resume.mjs +136 -0
  32. package/runner/tools/rollback.mjs +291 -0
  33. package/runner/tools/run.mjs +262 -0
  34. package/runner/tools/set.mjs +65 -0
  35. package/runner/tools/snapshots.mjs +83 -0
  36. package/runner/tools/status.mjs +70 -0
  37. package/runner/tools.mjs +94 -0
  38. package/shared/constants.mjs +273 -0
  39. package/shared/tool.mjs +32 -0
  40. package/shared/util.mjs +231 -0
  41. package/snapshot/repo.mjs +452 -0
  42. package/state/registry.mjs +40 -0
  43. package/tests/aesthetic.test.mjs +20 -12
  44. package/tests/apply-wiring.test.mjs +172 -0
  45. package/tests/assertions-e2e.mjs +2 -1
  46. package/tests/atomic-write.test.mjs +129 -0
  47. package/tests/client-bundle.test.mjs +3 -3
  48. package/tests/command-whitelist.test.mjs +135 -0
  49. package/tests/contract.test.mjs +2 -2
  50. package/tests/desktop.test.mjs +2 -2
  51. package/tests/domains.test.mjs +10 -7
  52. package/tests/e2e.mjs +2 -1
  53. package/tests/extra-phase.test.mjs +2 -2
  54. package/tests/feedback.test.mjs +2 -1
  55. package/tests/flow-gate.test.mjs +16 -56
  56. package/tests/issues-e2e.mjs +2 -1
  57. package/tests/panel-independence.test.mjs +2 -2
  58. package/tests/panel-report.test.mjs +2 -2
  59. package/tests/paths.mjs +70 -1
  60. package/tests/preview-path.test.mjs +2 -1
  61. package/tests/qa-assertions.test.mjs +10 -3
  62. package/tests/run-all.mjs +6 -0
  63. package/tests/snapshot-core.test.mjs +234 -0
  64. package/tests/stage-model.test.mjs +2 -2
  65. package/tests/steer-command.test.mjs +151 -0
  66. package/tests/stop-resume.test.mjs +7 -2
  67. package/tests/watch-root.test.mjs +2 -1
  68. package/ui/prompt.mjs +101 -0
  69. package/workspace/models.mjs +111 -0
  70. package/workspace/panel.mjs +359 -0
  71. package/workspace/paths.mjs +393 -0
  72. package/workspace/resume.mjs +107 -0
@@ -0,0 +1,40 @@
1
+ /**
2
+ * 跨模块共享的可变状态。三样东西必须住在这里:
3
+ *
4
+ * 1. 活对象(running / panelStops / ...)——复制一份出去就各写各的:
5
+ * 面板看不见运行、停止按钮停不掉。
6
+ * 2. ctx.inject 异步挂上的服务句柄(llm / agents / clientModules)——
7
+ * 值在 apply 之后才有。
8
+ * 3. 本机探测到的模型 id——估价和模型列表都读它。
9
+ *
10
+ * 为什么统一放在一个对象的属性上,而不是各导各的:ES 模块的导入绑定
11
+ * 是单向快照,`export let x` 在被导入方赋值,导入方读到的还是旧值。
12
+ * 放在对象属性上就只有一处可写,读写天然一致。
13
+ *
14
+ * 为什么叫 pfState:原文里大量函数参数就叫 state(`function statusLine(state)`),
15
+ * 同名会被参数遮蔽,读到的永远是局部那份——那种 bug 不报错,
16
+ * 只表现为「按钮点了没反应」。
17
+ */
18
+ export const pfState = {
19
+ /** 正在跑的项目:project → task。并发的门就这一道。 */
20
+ running: new Map(),
21
+ /** 面板发出的停止请求:project → { at, by }。和真实故障分开,不当错误报。 */
22
+ panelStops: new Map(),
23
+ /** 每个工作区根最近一次的面板数据。 */
24
+ lastPanelByRoot: new Map(),
25
+ /** 最近一次全量面板快照。 */
26
+ lastPanelReport: null,
27
+ /** 全量快照(面板内部用)。 */
28
+ lastPanelFull: null,
29
+ /** 本机探测到的模型 id。 */
30
+ detectedModelIds: [],
31
+ /** 意图门控读的就绪度,按 agent 分开。WeakMap 不拖住 agent。 */
32
+ readinessByAgent: new WeakMap(),
33
+ /** 浏览器那半边回连的记录,最多留 80 条。 */
34
+ clientHits: [],
35
+ /** ctx.inject 之后才有值的服务句柄。 */
36
+ llm: undefined,
37
+ agents: undefined,
38
+ clientModules: undefined,
39
+ }
40
+
@@ -11,7 +11,7 @@ import { sibling } from './paths.mjs'
11
11
  import { join } from 'node:path'
12
12
  import { tmpdir } from 'node:os'
13
13
  import { pathToFileURL } from 'node:url'
14
- import { LIVE_DIR } from './paths.mjs'
14
+ import { LIVE_DIR, sourceText, sourceFiles, orderHolds } from './paths.mjs'
15
15
  const {
16
16
  CARRIERS,
17
17
  UNIVERSAL_RULES,
@@ -384,11 +384,13 @@ checkAsync('存库时不会把没战绩的内置条目写盘', async () => {
384
384
  }
385
385
  })
386
386
 
387
- const host = await readFile(join(LIVE_DIR, 'index.js'), 'utf8').catch(() => '')
387
+ const host = sourceText()
388
+ const files = sourceFiles()
388
389
  const pkg = JSON.parse(await readFile(join(LIVE_DIR, 'package.json'), 'utf8').catch(() => '{}'))
389
390
 
390
391
  check('宿主真的 import 了这个模块', () => ({
391
- ok: host.includes("from './aesthetic.mjs'"),
392
+ // 拆分之后 import 分散在各模块里,扫全树即可——要验的是「有人用了它」
393
+ ok: host.includes("from './aesthetic.mjs'") || host.includes("from '../aesthetic.mjs'"),
392
394
  }))
393
395
 
394
396
  check('三阶 prompt 都接上了', () => ({
@@ -398,10 +400,14 @@ check('三阶 prompt 都接上了', () => ({
398
400
  }))
399
401
 
400
402
  check('审美判定在函数级,三阶都够得着', () => {
401
- // 之前写进 `if (fromStage <= 2)` 里面,实施和质检引用会抛 ReferenceError
402
- const at = host.indexOf('const aesthetic = resolveAesthetic(')
403
- const guard = host.indexOf('if (fromStage <= 2)')
404
- return { ok: at !== -1 && guard !== -1 && at < guard, detail: `声明 ${at} / 分支 ${guard}` }
403
+ // 之前写进 `if (fromStage <= 2)` 里面,实施和质检引用会抛 ReferenceError。
404
+ //
405
+ // 拆分之后这段住在 runner/pipeline.mjs 里,但「声明在分支之前」这个关系
406
+ // 仍然要在**同一个文件**里成立:拼起来扫的话,测到的是拼接顺序,不是代码。
407
+ return {
408
+ ok: orderHolds(files, 'const aesthetic = resolveAesthetic(', 'if (fromStage <= 2)'),
409
+ detail: '要知道有没有写进分支里',
410
+ }
405
411
  })
406
412
 
407
413
  check('载体判断用意图加要求,不是只看标题', () => ({
@@ -485,11 +491,13 @@ check('质检结论会反馈给库,库才会越来越准', () => ({
485
491
  }))
486
492
 
487
493
  check('骨架与库位置在函数级,三阶都够得着', () => {
488
- // 这个坑踩过两次:写进 if (fromStage <= 2) 里,实施和质检引用会抛 ReferenceError
489
- const declared = host.indexOf('let patterns = []')
490
- const branch = host.indexOf('if (fromStage <= 2) {')
491
- const used = host.indexOf('describePatterns(patterns)')
492
- return { ok: declared !== -1 && branch !== -1 && declared < branch && used > declared, detail: `${declared} / ${branch} / ${used}` }
494
+ // 这个坑踩过两次:写进 if (fromStage <= 2) 里,实施和质检引用会抛 ReferenceError。
495
+ // 同上:顺序关系只在同一个文件里有意义。
496
+ return {
497
+ ok: orderHolds(files, 'let patterns = []', 'if (fromStage <= 2) {')
498
+ && orderHolds(files, 'let patterns = []', 'describePatterns(patterns)'),
499
+ detail: '声明要早于分支与使用',
500
+ }
493
501
  })
494
502
 
495
503
  check('库文件不放在项目里,审美是跨项目的手艺', async () => {
@@ -0,0 +1,172 @@
1
+ /**
2
+ * 装配冒烟测试:用一个假的 ctx 把 apply 跑起来,看它到底注册了什么。
3
+ *
4
+ * 为什么需要这一条:29 套单元测试验的是各模块的函数,没有一条真正
5
+ * 从 apply 进、看十个工具/四个路由/十一条命令有没有挂上去。拆模块之后
6
+ * 「每个模块都对,但组装起来漏了一半」是最可能的失败形态,而它不报错。
7
+ *
8
+ * 假的 ctx 按 cordis 的真实契约写:
9
+ * · ctx.effect(fn) 立刻调用 fn,fn 的返回值(一个函数)就是清理函数
10
+ * · ctx.inject(deps, fn) 在服务出现时调 fn,同样收清理函数
11
+ * · ctx.tools.register(tool) 返回卸载函数
12
+ * · ctx.systemPrompt.section(s) 返回卸载函数
13
+ */
14
+ import { test } from 'node:test'
15
+ import assert from 'node:assert/strict'
16
+ import { pathToFileURL } from 'node:url'
17
+ import { join } from 'node:path'
18
+ import { mkdtemp, rm } from 'node:fs/promises'
19
+ import { tmpdir } from 'node:os'
20
+ import { LIVE_DIR } from './paths.mjs'
21
+
22
+ const mod = await import(pathToFileURL(join(LIVE_DIR, 'index.js')).href)
23
+
24
+ /** 造一个够用的假宿主。记录每一类注册。 */
25
+ function fakeHost({ withWebServer = false, withCommands = false } = {}) {
26
+ const record = {
27
+ tools: [],
28
+ sections: [],
29
+ routes: [],
30
+ commands: [],
31
+ cleanups: [],
32
+ effects: 0,
33
+ injections: [],
34
+ }
35
+
36
+ const take = value => {
37
+ if (typeof value === 'function') record.cleanups.push(value)
38
+ return () => {}
39
+ }
40
+
41
+ const ctx = {
42
+ root: { cwd: process.cwd() },
43
+ tools: {
44
+ register(tool) {
45
+ record.tools.push(tool.name)
46
+ return () => {}
47
+ },
48
+ guard() {
49
+ return () => {}
50
+ },
51
+ },
52
+ systemPrompt: {
53
+ section(spec) {
54
+ record.sections.push(spec.name)
55
+ return () => {}
56
+ },
57
+ getSectionOrder() {
58
+ return 2800
59
+ },
60
+ },
61
+ effect(fn) {
62
+ record.effects += 1
63
+ take(fn())
64
+ return () => {}
65
+ },
66
+ inject(deps, fn) {
67
+ record.injections.push(deps.join('+'))
68
+ const services = {}
69
+ if (withWebServer && deps.includes('webServer')) {
70
+ services.webServer = {
71
+ register(route) {
72
+ record.routes.push(route.path)
73
+ return () => {}
74
+ },
75
+ }
76
+ }
77
+ if (withCommands && deps.includes('commands')) {
78
+ services.commands = {
79
+ register(command) {
80
+ record.commands.push(command.name)
81
+ return () => {}
82
+ },
83
+ }
84
+ }
85
+ // cordis 的实际语义:声明的服务**都存在**时才调这个回调。
86
+ // 少一个就不跑——这正是插件在没 commands 的宿主上仍能加载的原因。
87
+ const allPresent = deps.every(name => services[name] !== undefined)
88
+ if (!allPresent) return () => {}
89
+
90
+ // 注入上下文和父 ctx 同形:也有 effect / get / inject。
91
+ const inner = {
92
+ get: name => services[name],
93
+ effect(fn2) {
94
+ record.effects += 1
95
+ take(fn2())
96
+ return () => {}
97
+ },
98
+ inject: () => () => {},
99
+ on: () => () => {},
100
+ }
101
+ take(fn(inner))
102
+ return () => {}
103
+ }, on() {
104
+ return () => {}
105
+ },
106
+ get(name) {
107
+ return name === 'commands' ? undefined : undefined
108
+ },
109
+ }
110
+
111
+ return { ctx, record }
112
+ }
113
+
114
+ test('apply 把十个工具全挂上', () => {
115
+ const { ctx, record } = fakeHost()
116
+ mod.apply(ctx, {})
117
+ const expected = [
118
+ 'project_run', 'project_resume', 'project_doctor', 'project_snapshots', 'project_rollback',
119
+ 'project_status', 'project_context', 'project_estimate', 'project_models', 'project_set_model',
120
+ ]
121
+ assert.deepEqual([...record.tools].sort(), [...expected].sort())
122
+ })
123
+
124
+ test('apply 注入系统提示段', () => {
125
+ const { ctx, record } = fakeHost()
126
+ mod.apply(ctx, {})
127
+ assert.deepEqual(record.sections, ['project-flow:policy'])
128
+ })
129
+
130
+ test('宿主有 webServer 时四条只读路由都挂上', () => {
131
+ const { ctx, record } = fakeHost({ withWebServer: true })
132
+ mod.apply(ctx, {})
133
+ assert.equal(record.routes.length, 4, `实际挂了 ${record.routes.length} 条:${record.routes.join(', ')}`)
134
+ // 每条都要出现在自己的插件前缀下,别撞别人的路由
135
+ for (const path of record.routes) assert.match(path, /^\/plugins\/dsh-project-flow\//u)
136
+ })
137
+
138
+ test('宿主有 commands 时十二条斜杠命令都挂上', () => {
139
+ const { ctx, record } = fakeHost({ withCommands: true })
140
+ mod.apply(ctx, {})
141
+ assert.ok(record.commands.length >= 10, `只挂了 ${record.commands.length} 条:${record.commands.join(', ')}`)
142
+ })
143
+
144
+ test('apply 的清理函数能调,调完不炸', () => {
145
+ const { ctx, record } = fakeHost({ withWebServer: true, withCommands: true })
146
+ mod.apply(ctx, {})
147
+ // 只收 ctx.effect 给的卸载函数;ctx.inject 的生命周期由宿主管,
148
+ // 它返回 undefined,不该出现在这里。
149
+ const effectCleanups = record.cleanups.filter(fn => typeof fn === 'function')
150
+ assert.ok(effectCleanups.length > 0, 'ctx.effect 至少该收到一个清理函数')
151
+ for (const fn of effectCleanups) fn()
152
+ })
153
+
154
+ test('配置写进去之后 settingsOf 读得到', async () => {
155
+ // settingsOf 会把 %DSH_HOME%/project-flow.json 压在本进程的 patch 值上面。
156
+ // 那台机器上真有一份 maxRework=4 的覆盖文件,不隔离的话这里读到的永远是
157
+ // 4 而不是 apply 传进去的 5——测的就不是接线,而是本机配置。
158
+ const home = await mkdtemp(join(tmpdir(), 'pf-apply-'))
159
+ const previous = process.env.DSH_HOME
160
+ process.env.DSH_HOME = home
161
+ try {
162
+ const { ctx } = fakeHost({ withWebServer: true, withCommands: true })
163
+ mod.apply(ctx, { maxRework: 5, budgetUsd: 3 })
164
+ const settings = mod.settingsOf()
165
+ assert.equal(settings.maxRework, 5)
166
+ assert.equal(settings.budgetUsd, 3)
167
+ } finally {
168
+ if (previous === undefined) delete process.env.DSH_HOME
169
+ else process.env.DSH_HOME = previous
170
+ await rm(home, { recursive: true, force: true })
171
+ }
172
+ })
@@ -13,9 +13,10 @@ import { existsSync } from 'node:fs'
13
13
  import { join, dirname } from 'node:path'
14
14
  import { tmpdir } from 'node:os'
15
15
  import { fileURLToPath, pathToFileURL } from 'node:url'
16
+ import { LIVE_DIR } from './paths.mjs'
16
17
 
17
18
  const here = dirname(fileURLToPath(import.meta.url))
18
- const LIVE = 'C:/Users/ASUS/.dsh/profiles/desktop/node_modules/dsh-project-flow/index.js'
19
+ const LIVE = join(LIVE_DIR, 'index.js')
19
20
  // 不吃用户自己的 project-flow.json:他界面里设了哪个模型是另一回事。
20
21
  process.env.DSH_HOME = await mkdtemp(join(tmpdir(), 'pf-assert-home-'))
21
22
  const mod = await import(pathToFileURL(LIVE).href + `?t=${Date.now()}`)
@@ -0,0 +1,129 @@
1
+ /**
2
+ * 原子写与配置落盘。
3
+ *
4
+ * 这一套盯三件事:
5
+ * 1. 目标文件里是半截 JSON 时,写入能把它整个覆盖成合法内容
6
+ * 2. rename 失败、退化成直接写并且写成功了,不该再把 rename 的错误抛出来
7
+ * 3. 写完必须回读并 JSON.parse 校验——落盘的不是手里的那份就要报
8
+ *
9
+ * 全程在临时目录里跑,DSH_HOME 指到那儿;绝不碰用户真实的 ~/.dsh。
10
+ */
11
+ import { test, after } from 'node:test'
12
+ import assert from 'node:assert/strict'
13
+ import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'
14
+ import { join } from 'node:path'
15
+ import { tmpdir } from 'node:os'
16
+ import { pathToFileURL } from 'node:url'
17
+ import { LIVE_DIR } from './paths.mjs'
18
+
19
+ const home = await mkdtemp(join(tmpdir(), 'pf-atomic-'))
20
+ const previousHome = process.env.DSH_HOME
21
+ process.env.DSH_HOME = home
22
+ after(async () => {
23
+ if (previousHome === undefined) delete process.env.DSH_HOME
24
+ else process.env.DSH_HOME = previousHome
25
+ await rm(home, { recursive: true, force: true })
26
+ })
27
+
28
+ const mod = await import(pathToFileURL(join(LIVE_DIR, 'index.js')).href)
29
+ const { writeFileAtomic, writeOverride, overrideFile } = mod
30
+
31
+ test('半截 JSON:目标文件是坏的也能整体覆盖成合法内容', async () => {
32
+ await writeOverride({ maxRework: 3 })
33
+ const target = overrideFile()
34
+ assert.ok(target.startsWith(home), `配置没写进临时 home:${target}`)
35
+ // 造一个写了一半的现场:左花括号 + 没闭合的键
36
+ await writeFile(target, '{\n "maxRework": ', 'utf8')
37
+ await writeOverride({ maxRework: 3 })
38
+ const parsed = JSON.parse(await readFile(target, 'utf8'))
39
+ assert.deepEqual(parsed, { maxRework: 3 })
40
+ })
41
+
42
+ test('rename 失败但不误报:退化写成功就不再抛错,也不留 tmp', async () => {
43
+ const dir = await mkdtemp(join(home, 'rename-'))
44
+ const target = join(dir, 'x.json')
45
+ const deny = async () => {
46
+ const error = new Error('EPERM: operation not permitted, rename')
47
+ error.code = 'EPERM'
48
+ throw error
49
+ }
50
+ await writeFileAtomic(target, 'abc', { rename: deny })
51
+ assert.equal(await readFile(target, 'utf8'), 'abc')
52
+ const left = (await readdir(dir)).filter(name => name.includes('.tmp-'))
53
+ assert.deepEqual(left, [], `留下了临时文件:${left.join(', ')}`)
54
+ })
55
+
56
+ test('rename 与退化写都失败时,抛的是退化的那个错', async () => {
57
+ const dir = await mkdtemp(join(home, 'both-'))
58
+ const target = join(dir, 'y.json')
59
+ const renameBoom = async () => { throw new Error('RENAME_BOOM') }
60
+ // tmp 那一步必须真的写成:失败的是「改名」和「直接覆盖目标」这两步
61
+ const writeBoom = async (path, text, encoding) => {
62
+ if (String(path).includes('.tmp-')) return writeFile(path, text, encoding)
63
+ throw new Error('WRITE_BOOM')
64
+ }
65
+ await assert.rejects(
66
+ () => writeFileAtomic(target, 'abc', { rename: renameBoom, writeFile: writeBoom }),
67
+ /WRITE_BOOM/u,
68
+ )
69
+ const left = (await readdir(dir)).filter(name => name.includes('.tmp-'))
70
+ assert.deepEqual(left, [], `留下了临时文件:${left.join(', ')}`)
71
+ })
72
+
73
+ test('写完回读:正常写入后读回来就是刚落盘的那份', async () => {
74
+ await writeOverride({ aestheticPatterns: 2 })
75
+ const parsed = JSON.parse(await readFile(overrideFile(), 'utf8'))
76
+ assert.equal(parsed.aestheticPatterns, 2)
77
+ })
78
+
79
+ test('写完回读:落盘内容是截断的就必须报,不许假装成功', async () => {
80
+ const target = overrideFile()
81
+ // 注入一个只写前 5 个字符的 writeFile:rename 会成功,但落盘的是半截 JSON
82
+ const truncating = async (path, text) => writeFile(path, String(text).slice(0, 5), 'utf8')
83
+ await assert.rejects(
84
+ () => writeOverride({ maxRework: 7 }, { writeFile: truncating }),
85
+ /回读校验/u,
86
+ )
87
+ // 落盘的确实是被截断的那份,报错不是空穴来风
88
+ assert.equal((await readFile(target, 'utf8')).length, 5)
89
+ })
90
+
91
+ test('读不动就拒绝覆盖:既有配置不能因为读失败被清空', async () => {
92
+ // 先落一份有内容的配置
93
+ await writeOverride({ maxRework: 4, stageTimeoutMs: 3600000 })
94
+ const target = overrideFile()
95
+ const before = await readFile(target, 'utf8')
96
+
97
+ // 真去锁文件在 Windows 上不稳,直接注入一个 EACCES 的读:语义一样——
98
+ // 「文件在,但这一刻读不到」。
99
+ const denyRead = async () => {
100
+ const error = new Error('EACCES: permission denied, open')
101
+ error.code = 'EACCES'
102
+ throw error
103
+ }
104
+ await assert.rejects(
105
+ () => writeOverride({ maxRework: 9 }, { readFile: denyRead }),
106
+ /拒绝覆盖/u,
107
+ )
108
+ // 关键断言:一个字都没动。以前这里会变成 {"maxRework":9},别的键全没
109
+ assert.equal(await readFile(target, 'utf8'), before)
110
+ })
111
+
112
+ test('文件还没建出来(ENOENT)是正常情况,不该被当成读不动', async () => {
113
+ // 第一次写配置时文件本来就不存在。那条降级路径必须还留着,
114
+ // 否则装上插件后第一次 /flow-set 就会报「拒绝覆盖」。
115
+ // 这里只让第一次读抛 ENOENT,回读那一步走真的 readFile。
116
+ let calls = 0
117
+ const firstMissing = async (path, encoding) => {
118
+ calls += 1
119
+ if (calls === 1) {
120
+ const error = new Error('ENOENT: no such file or directory')
121
+ error.code = 'ENOENT'
122
+ throw error
123
+ }
124
+ return readFile(path, encoding)
125
+ }
126
+ const written = await writeOverride({ maxRework: 2 }, { readFile: firstMissing })
127
+ assert.deepEqual(written.value, { maxRework: 2 })
128
+ assert.deepEqual(JSON.parse(await readFile(overrideFile(), 'utf8')), { maxRework: 2 })
129
+ })
@@ -13,7 +13,7 @@ import { readFile } from 'node:fs/promises'
13
13
  import { readFileSync } from 'node:fs'
14
14
  import { join, dirname } from 'node:path'
15
15
  import { fileURLToPath } from 'node:url'
16
- import { LIVE_DIR } from './paths.mjs'
16
+ import { LIVE_DIR, sourceText } from './paths.mjs'
17
17
 
18
18
  const here = dirname(fileURLToPath(import.meta.url))
19
19
  const source = await readFile(join(LIVE_DIR, 'client.js'), 'utf8')
@@ -328,7 +328,7 @@ checkAsync('宿主那边 /flow-panel 命令已下线', async () => {
328
328
  const { readFile } = await import('node:fs/promises')
329
329
  const { join } = await import('node:path')
330
330
  const { LIVE_DIR } = await import('./paths.mjs')
331
- const hostSource = await readFile(join(LIVE_DIR, 'index.js'), 'utf8')
331
+ const hostSource = sourceText()
332
332
  const registered = hostSource.includes("name: 'flow-panel'")
333
333
  return { ok: registered === false, detail: `还注册着=${registered}` }
334
334
  })
@@ -483,7 +483,7 @@ check('路径里已经有「工作流」就算启用——不必等它跑过一
483
483
  })
484
484
 
485
485
  check('客户端的目录名常量和宿主一致', () => {
486
- const host = readFileSync(join(LIVE_DIR, 'index.js'), 'utf8')
486
+ const host = sourceText()
487
487
  const hostName = /const FLOW_DIR_NAME = '([^']+)'/u.exec(host)?.[1]
488
488
  const clientName = /const FLOW_DIR_NAME = '([^']+)'/u.exec(source)?.[1]
489
489
  return {
@@ -0,0 +1,135 @@
1
+ /**
2
+ * 命令白名单与 .bat 参数转义。
3
+ *
4
+ * 三件事,各自独立跑:
5
+ * 1. 带路径的命令不能只凭名字放行(PATH 外的同名二进制一律拒)
6
+ * 2. PATH 里真实存在的那份、以及 process.execPath,必须照旧放行
7
+ * 3. Windows 上真起一个 .cmd,四种难缠参数逐字回读——只断言 bat 文本里
8
+ * 有某个符号不算数,那验的是字符串拼接,不是程序真收到了什么
9
+ */
10
+ import { test } from 'node:test'
11
+ import assert from 'node:assert/strict'
12
+ import { mkdtemp, readFile, rm, writeFile, mkdir } from 'node:fs/promises'
13
+ import { existsSync } from 'node:fs'
14
+ import { execFile } from 'node:child_process'
15
+ import { join } from 'node:path'
16
+ import { tmpdir } from 'node:os'
17
+ import { pathToFileURL } from 'node:url'
18
+ import { LIVE_DIR } from './paths.mjs'
19
+
20
+ const mod = await import(pathToFileURL(join(LIVE_DIR, 'index.js')).href)
21
+ const { checkDenial, allowedCommandsOf, whichSync, resolveWindowsCommand } = mod
22
+
23
+ const allowed = allowedCommandsOf({})
24
+ const win32 = process.platform === 'win32'
25
+ const needWin = { skip: win32 ? false : '这条只在 Windows 上成立' }
26
+
27
+ // ── a 带路径的命令 ───────────────────────────────────────────
28
+
29
+ test('带路径的命令:PATH 外的写法一律拒,理由里说清是路径问题', () => {
30
+ for (const cmd of ['D:/evil/node.exe -v', '.\\node.exe -v', '..\\node.exe -v']) {
31
+ const denial = checkDenial(cmd, allowed)
32
+ assert.equal(denial.denied, true, `${cmd} 该被拒`)
33
+ assert.match(denial.reason, /路径/u, `${cmd} 的理由没说路径:${denial.reason}`)
34
+ }
35
+ })
36
+
37
+ test('带路径的命令:盘符相对写法 C:node.exe 也算路径,不按名字放行', () => {
38
+ // `C:node.exe` 一个分隔符都没有,跑起来是 C 盘当前目录下的同名二进制,
39
+ // 不是 PATH 里那份 node。按名字放行就等于在上面那条规则上又开了个口子。
40
+ const denial = checkDenial('C:node.exe -v', allowed)
41
+ assert.equal(denial.denied, true, '盘符相对写法该被拒')
42
+ assert.match(denial.reason, /路径/u, `理由没说路径:${denial.reason}`)
43
+ })
44
+
45
+ test('带路径的命令:理由区分「找不到」和「不在 PATH 里」,都不退化成按名字放行', () => {
46
+ const missing = checkDenial('D:\\nope\\node.exe -v', allowed)
47
+ assert.equal(missing.denied, true)
48
+ assert.match(missing.reason, /找不到/u)
49
+ // node 就在 PATH 外但属于 execPath 目录的情况见下一条;这里验的是
50
+ // 「解析不出来就拒」,而不是悄悄回退。
51
+ assert.notEqual(missing.denied, false)
52
+ })
53
+
54
+ // ── b PATH 内真实路径放行 ───────────────────────────────────
55
+
56
+ test('PATH 内真实路径:which 找到的那份放行,名字还是命令名', t => {
57
+ const abs = whichSync('git')
58
+ if (abs === undefined) {
59
+ t.skip('这台机器的 PATH 里没有 git')
60
+ return
61
+ }
62
+ const ok = checkDenial(`${JSON.stringify(abs)} --version`, allowed)
63
+ assert.equal(ok.denied, false, `PATH 里的 git 被拒了:${ok.reason}`)
64
+ assert.equal(ok.name, 'git')
65
+ })
66
+
67
+ test('PATH 内真实路径:process.execPath 放行,名字是 node', () => {
68
+ const ok = checkDenial(`${JSON.stringify(process.execPath)} -v`, allowed)
69
+ assert.equal(ok.denied, false, `execPath 被拒了:${ok.reason}`)
70
+ assert.equal(ok.name, 'node')
71
+ })
72
+
73
+ // ── c .bat 四类转义 ─────────────────────────────────────────
74
+
75
+ /**
76
+ * 真起一次 .cmd,把收到的第一个参数回读回来。
77
+ *
78
+ * 接收端是一个「转发型」批处理:自己不重解析命令行,直接 `%*` 交给 node。
79
+ * 为什么必须这么搭:cmd 的批处理参数解析里没有「转义双引号」这回事,
80
+ * `%~1` phase 拿到的是被 cmd 自己的规则处理过一遍的结果,`"` 在那一层
81
+ * 是不可表示的——用它当接收端,测到的是 cmd 的残缺,不是我们的转义。
82
+ * 真实目标(npm.cmd / pnpm.cmd)本来就是「批处理转发给 node」这个形状。
83
+ */
84
+ async function roundTrip(dir, target, arg) {
85
+ const out = join(dir, 'out.txt')
86
+ await rm(out, { force: true })
87
+ const resolved = resolveWindowsCommand(target, [arg])
88
+ assert.equal(resolved.viaCmd, true, '走的是临时 bat')
89
+ await new Promise((resolve, reject) => {
90
+ execFile(resolved.file, resolved.args, { cwd: dir, windowsHide: true }, error => {
91
+ if (typeof resolved.cleanup === 'function') resolved.cleanup()
92
+ if (error === null || error === undefined) resolve()
93
+ else reject(error)
94
+ })
95
+ })
96
+ assert.equal(existsSync(out), true, `目标命令没跑起来,out.txt 没生成(参数 ${JSON.stringify(arg)})`)
97
+ return JSON.parse(await readFile(out, 'utf8'))
98
+ }
99
+
100
+ test('bat 转义:% / ! / 双引号 / 中文路径 四类参数逐字回读一致', needWin, async () => {
101
+ const dir = await mkdtemp(join(tmpdir(), 'pf-cmd-'))
102
+ try {
103
+ const work = join(dir, '测试 目录')
104
+ await mkdir(work, { recursive: true })
105
+ // 收集端:把收到的参数列表写成 JSON
106
+ const sink = join(work, 'sink.mjs')
107
+ await writeFile(sink, 'import { writeFileSync } from "node:fs"\n'
108
+ + 'writeFileSync(process.argv[2], JSON.stringify(process.argv.slice(3)))\n', 'utf8')
109
+ // 接收端:转发给 node,命令行由 node 的 CRT 规则解析
110
+ const target = join(work, 'echo.cmd')
111
+ await writeFile(target, [
112
+ '@echo off',
113
+ 'setlocal DisableDelayedExpansion',
114
+ 'chcp 65001 >nul',
115
+ `"${process.execPath}" "${sink}" "%~dp0out.txt" %*`,
116
+ 'exit /b %ERRORLEVEL%',
117
+ '',
118
+ ].join('\r\n'), 'utf8')
119
+
120
+ const cases = [
121
+ '100%',
122
+ '%PATH%',
123
+ 'a!b!c',
124
+ 'a"b"c',
125
+ 'D:\\临时 目录\\x.txt',
126
+ 'plain',
127
+ ]
128
+ for (const arg of cases) {
129
+ const got = await roundTrip(work, target, arg)
130
+ assert.deepEqual(got, [arg], `参数 ${JSON.stringify(arg)} 回读成了 ${JSON.stringify(got)}`)
131
+ }
132
+ } finally {
133
+ await rm(dir, { recursive: true, force: true })
134
+ }
135
+ })
@@ -12,11 +12,11 @@ import assert from 'node:assert/strict'
12
12
  import { join } from 'node:path'
13
13
  import { readFile } from 'node:fs/promises'
14
14
  import { pathToFileURL } from 'node:url'
15
- import { LIVE_DIR } from './paths.mjs'
15
+ import { LIVE_DIR, sourceText } from './paths.mjs'
16
16
 
17
17
  const mod = await import(pathToFileURL(join(LIVE_DIR, 'index.js')).href + `?t=${Date.now()}`)
18
18
  const { contractSha, contractBlock, hitsForbidden } = mod
19
- const source = await readFile(join(LIVE_DIR, 'index.js'), 'utf8')
19
+ const source = sourceText()
20
20
 
21
21
  const BASE = {
22
22
  requirements: ['把 CSV 转成 Markdown 表格', '首行当表头'],
@@ -8,7 +8,7 @@ import { readFile } from 'node:fs/promises'
8
8
  import { pathToFileURL } from 'node:url'
9
9
  import { sibling } from './paths.mjs'
10
10
  import { join } from 'node:path'
11
- import { LIVE_DIR } from './paths.mjs'
11
+ import { LIVE_DIR, sourceText } from './paths.mjs'
12
12
  const {
13
13
  DESKTOP_TOOL_HINTS,
14
14
  shouldUseDesktop,
@@ -93,7 +93,7 @@ check('明确禁止用桌面工具碰产物以外的东西', () => ({
93
93
 
94
94
  // ── 接进流水了没有 ──────────────────────────────────────
95
95
 
96
- const host = await readFile(join(LIVE_DIR, 'index.js'), 'utf8').catch(() => '')
96
+ const host = sourceText()
97
97
  const pkg = JSON.parse(await readFile(join(LIVE_DIR, 'package.json'), 'utf8').catch(() => '{}'))
98
98
 
99
99
  check('两阶 prompt 都按 useDesktop 开关注入', () => ({
@@ -13,7 +13,7 @@ import { pathToFileURL } from 'node:url'
13
13
  import { sibling } from './paths.mjs'
14
14
  import { join } from 'node:path'
15
15
  import { tmpdir } from 'node:os'
16
- import { LIVE_DIR } from './paths.mjs'
16
+ import { LIVE_DIR, sourceText, sourceFiles, orderHolds } from './paths.mjs'
17
17
  const {
18
18
  BUILTIN_DOMAINS,
19
19
  DOMAIN_IDS,
@@ -167,7 +167,8 @@ check('没配目录时安静返回空,不报错', async () => {
167
167
 
168
168
  // ── 接进插件了没有 ──────────────────────────────────────
169
169
 
170
- const host = await readFile(join(LIVE_DIR, 'index.js'), 'utf8').catch(() => '')
170
+ const host = sourceText()
171
+ const files = sourceFiles()
171
172
  const pkg = JSON.parse(await readFile(join(LIVE_DIR, 'package.json'), 'utf8').catch(() => '{}'))
172
173
 
173
174
  check('三阶 prompt 都接上了领域', () => ({
@@ -176,11 +177,13 @@ check('三阶 prompt 都接上了领域', () => ({
176
177
  }))
177
178
 
178
179
  check('领域在函数级,三阶都够得着', () => {
179
- // 这个坑在 aesthetic 那轮踩过:写进 if (fromStage <= 2) 里就抛 ReferenceError
180
- const declared = host.indexOf('const domain = picked.domain')
181
- const branch = host.indexOf(' if (fromStage <= 2) {')
182
- const used = host.indexOf('domainQaChecks(domain)')
183
- return { ok: declared !== -1 && branch !== -1 && declared < branch && used > declared, detail: `${declared}/${branch}/${used}` }
180
+ // 这个坑在 aesthetic 那轮踩过:写进 if (fromStage <= 2) 里就抛 ReferenceError。
181
+ // 拆分后这段在 runner/pipeline.mjs,顺序关系仍要在同一个文件里成立。
182
+ return {
183
+ ok: orderHolds(files, 'const domain = picked.domain', 'if (fromStage <= 2) {')
184
+ && orderHolds(files, 'const domain = picked.domain', 'domainQaChecks(domain)'),
185
+ detail: '声明要早于分支与使用',
186
+ }
184
187
  })
185
188
 
186
189
  check('行当记进了 state 与日志', () => ({
package/tests/e2e.mjs CHANGED
@@ -11,9 +11,10 @@ import { existsSync } from 'node:fs'
11
11
  import { join, dirname } from 'node:path'
12
12
  import { tmpdir } from 'node:os'
13
13
  import { fileURLToPath, pathToFileURL } from 'node:url'
14
+ import { LIVE_DIR } from './paths.mjs'
14
15
 
15
16
  const here = dirname(fileURLToPath(import.meta.url))
16
- const LIVE = 'C:/Users/ASUS/.dsh/profiles/desktop/node_modules/dsh-project-flow/index.js'
17
+ const LIVE = join(LIVE_DIR, 'index.js')
17
18
  // 测试不读用户自己的运行时配置(C:\Users\ASUS\.dsh\project-flow.json):
18
19
  // 他在界面上设了哪三个模型是他的事,不该让这里的断言红得莫名其妙。
19
20
  process.env.DSH_HOME = await mkdtemp(join(tmpdir(), 'pf-e2e-home-'))