dsh-project-flow 0.9.0 → 0.9.2

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 (46) hide show
  1. package/CHANGELOG.md +0 -0
  2. package/README.md +58 -11
  3. package/cordis.patch.yml +30 -11
  4. package/docs/DETAIL.md +6 -6
  5. package/docs/FEATURES.md +12 -5
  6. package/docs/LAUNCH.md +3 -3
  7. package/docs/MOMENTS.md +4 -4
  8. package/docs/USAGE.md +2 -2
  9. package/domains.mjs +1 -1
  10. package/evidence.mjs +19 -3
  11. package/flow.schema.mjs +192 -35
  12. package/gate.mjs +49 -23
  13. package/index.js +639 -120
  14. package/locale/en.json +15 -4
  15. package/locale/zh.json +17 -6
  16. package/package.json +5 -3
  17. package/tests/_heartbeat-regression.test.mjs +124 -0
  18. package/tests/aesthetic.test.mjs +534 -0
  19. package/tests/assertions-e2e.mjs +234 -0
  20. package/tests/bench-check.mjs +32 -0
  21. package/tests/client-bundle.test.mjs +707 -0
  22. package/tests/contract.test.mjs +137 -0
  23. package/tests/desktop.test.mjs +130 -0
  24. package/tests/domains.test.mjs +220 -0
  25. package/tests/e2e.mjs +300 -0
  26. package/tests/evidence.test.mjs +408 -0
  27. package/tests/extra-phase.test.mjs +133 -0
  28. package/tests/feedback.test.mjs +187 -0
  29. package/tests/flow-create.test.mjs +168 -0
  30. package/tests/flow-gate.test.mjs +232 -0
  31. package/tests/flow-schema.test.mjs +213 -0
  32. package/tests/gate.test.mjs +246 -0
  33. package/tests/issue-loop.test.mjs +254 -0
  34. package/tests/issues-e2e.mjs +246 -0
  35. package/tests/panel-independence.test.mjs +78 -0
  36. package/tests/panel-report.test.mjs +129 -0
  37. package/tests/patch-ledger.test.mjs +280 -0
  38. package/tests/paths.mjs +100 -0
  39. package/tests/preview-path.test.mjs +69 -0
  40. package/tests/qa-assertions.test.mjs +352 -0
  41. package/tests/run-all.mjs +90 -0
  42. package/tests/stage-model.test.mjs +120 -0
  43. package/tests/stop-resume.test.mjs +260 -0
  44. package/tests/watch-root.test.mjs +167 -0
  45. package/tests/watchdog-tokens.test.mjs +53 -0
  46. package/tests/watchdog.test.mjs +305 -0
@@ -0,0 +1,187 @@
1
+ /**
2
+ * 三件事各自真的发生了没有:
3
+ *
4
+ * 1. 第 4 阶拿得到 git diff,而且里面是真实改动
5
+ * 2. 停下来时给的是「为什么 / 能不能接着跑 / 不管它会怎样」,并且落到 Next_Step.md
6
+ * 3. 盲区确认过一次就记住,下次能沿用(project_context)
7
+ *
8
+ * 用真插件、真快照仓库、真磁盘,只有子会话是假的。
9
+ */
10
+ import { mkdtemp, mkdir, writeFile, readFile, rm } from 'node:fs/promises'
11
+ import { existsSync } from 'node:fs'
12
+ import { join, dirname } from 'node:path'
13
+ import { tmpdir } from 'node:os'
14
+ import { fileURLToPath, pathToFileURL } from 'node:url'
15
+
16
+ const here = dirname(fileURLToPath(import.meta.url))
17
+ const LIVE = 'C:/Users/ASUS/.dsh/profiles/desktop/node_modules/dsh-project-flow/index.js'
18
+ const mod = await import(pathToFileURL(LIVE).href + `?t=${Date.now()}`)
19
+
20
+ const results = []
21
+ const check = (label, fn) => {
22
+ let ok = false
23
+ let detail = ''
24
+ try {
25
+ const out = fn()
26
+ ok = out === true || (out && out.ok === true)
27
+ detail = out && out.detail ? String(out.detail) : ''
28
+ } catch (error) {
29
+ ok = false
30
+ detail = error.message
31
+ }
32
+ results.push({ label, ok, detail })
33
+ }
34
+
35
+ const BLINDSPOTS = {
36
+ permissions: '只动这个临时目录,不碰别处',
37
+ concurrency: '单人单次运行,不会撞车',
38
+ edge_cases: '任何一步失败就停下等人看',
39
+ stack: '纯文本改动,不加任何依赖',
40
+ data_flow: '读 src.txt 再写回去',
41
+ }
42
+
43
+ const base = join(tmpdir(), '工作流')
44
+ await mkdir(base, { recursive: true })
45
+
46
+ /** 造一个跑批环境;script 决定每一阶怎么回。 */
47
+ async function harness(script) {
48
+ const dir = await mkdtemp(join(base, 'pf-fb-'))
49
+ await writeFile(join(dir, 'src.txt'), 'hello\n', 'utf8')
50
+ const prompts = []
51
+ const tools = new Map()
52
+ const effects = []
53
+ const ctx = {
54
+ subagents: {
55
+ startActivation(options) {
56
+ prompts.push({ label: options.label, prompt: options.prompt?.[0]?.text ?? '' })
57
+ const reply = script(options, dir, prompts.length)
58
+ return {
59
+ result: (async () => {
60
+ if (reply === undefined) return { stopReason: 'error', diagnostic: '脚本没给这一段' }
61
+ const text = typeof reply === 'string' ? reply : reply.text
62
+ if (typeof reply === 'object') await reply.before?.()
63
+ return { stopReason: 'completed', output: [{ type: 'text', text }] }
64
+ })(),
65
+ dispose: async () => {},
66
+ }
67
+ },
68
+ },
69
+ tools: { register(tool) { tools.set(tool.name, tool); return () => tools.delete(tool.name) } },
70
+ systemPrompt: { section() { return () => {} }, getSectionOrder() { return 2800 } },
71
+ effect(fn) { effects.push(fn) },
72
+ inject() {},
73
+ get() { return undefined },
74
+ on() { return () => {} },
75
+ logger: { info() {}, warn() {}, error() {} },
76
+ root: {},
77
+ }
78
+ mod.apply(ctx, { testCommand: 'exit 0', testTimeoutMs: 60000, stageRetryDelayMs: 0 })
79
+ for (const fn of effects) fn()
80
+ const agent = { session: { header: { cwd: dir } } }
81
+ return { dir, tools, agent, prompts, stateDir: join(dir, '.project-flow', 'demo') }
82
+ }
83
+
84
+ const runArgs = project => ({
85
+ project,
86
+ intent: '把 src.txt 改一下',
87
+ requirements: ['改成 hello world'],
88
+ intentConfidence: 96,
89
+ questionsAsked: 2,
90
+ blindspots: BLINDSPOTS,
91
+ assumptions: ['按 UTF-8 读'],
92
+ })
93
+
94
+ // ── 场景 A:正常跑完,看 diff 和记忆 ────────────────────
95
+
96
+ const A = await harness(() => undefined)
97
+ // 用具体回复覆盖默认脚本
98
+ A.tools // 保持引用
99
+ const happy = await (async () => {
100
+ const { dir, tools, agent, prompts, stateDir } = await harness((options, workdir) => {
101
+ if (options.label.includes('规划')) {
102
+ return '```json\n{"plan":"把 src.txt 改成 hello world","buildTicket":"在 src.txt 末尾加一行 world"}\n```'
103
+ }
104
+ if (options.label.includes('实施')) {
105
+ return {
106
+ text: '```json\n{"summary":"在 src.txt 加了 world","files":["src.txt"]}\n```',
107
+ before: async () => { await writeFile(join(workdir, 'src.txt'), 'hello\nworld\n', 'utf8') },
108
+ }
109
+ }
110
+ if (options.label.includes('质检')) {
111
+ return '```json\n{"verdict":"PASS","reasons":["要求 1 做到了"],"acceptable_risks":["没测并发"]}\n```'
112
+ }
113
+ return undefined
114
+ })
115
+ const value = await tools.get('project_run').execute(runArgs('demo'), { agent, signal: undefined })
116
+ return { value, prompts, stateDir, dir, tools, agent }
117
+ })()
118
+
119
+ const qaPrompt = happy.prompts.find(item => item.label.includes('质检'))?.prompt ?? ''
120
+ check('第 4 阶的提示词里有 diff 一节', () => ({
121
+ ok: qaPrompt.includes('## 改动(从快照仓库两端算出来的 git diff)'),
122
+ detail: qaPrompt.slice(-300),
123
+ }))
124
+ check('diff 里是真实改动,不是自述', () => ({
125
+ ok: qaPrompt.includes('+world') && qaPrompt.includes('src.txt'),
126
+ detail: qaPrompt.slice(-400),
127
+ }))
128
+ check('质检规则里写明 diff 高于自述', () => (
129
+ qaPrompt.includes('diff 是事实,自述是说法')
130
+ ))
131
+
132
+ const contextPath = join(happy.stateDir, '..', 'context.json')
133
+ check('盲区确认后被记住', () => existsSync(contextPath))
134
+ const remembered = existsSync(contextPath) ? JSON.parse(await readFile(contextPath, 'utf8')) : undefined
135
+ check('记住的内容是那五格', () => ({
136
+ ok: remembered?.blindspots?.permissions === BLINDSPOTS.permissions,
137
+ detail: JSON.stringify(remembered?.blindspots ?? null).slice(0, 200),
138
+ }))
139
+ check('假设也记住了', () => Array.isArray(remembered?.assumptions) && remembered.assumptions[0] === '按 UTF-8 读')
140
+
141
+ const contextTool = happy.tools.get('project_context')
142
+ check('project_context 工具注册上了', () => typeof contextTool?.execute === 'function')
143
+ const ctxOut = await contextTool.execute({}, { agent: happy.agent })
144
+ check('project_context 报告找到了,并带出五格', () => ({
145
+ ok: ctxOut.found === true
146
+ && ctxOut.line.includes(BLINDSPOTS.permissions)
147
+ && ctxOut.line.includes('权限')
148
+ && ctxOut.line.includes('数据流向'),
149
+ detail: ctxOut.line.slice(0, 300),
150
+ }))
151
+ check('project_context 明确说「能沿用就沿用」', () => ctxOut.line.includes('能沿用的照原样交上去'))
152
+
153
+ // ── 场景 B:规划连挂,看停机说明 ────────────────────────
154
+
155
+ const B = await harness(options => {
156
+ if (options.label.includes('规划')) return undefined // 每试都失败
157
+ return '```json\n{"verdict":"PASS","reasons":[],"acceptable_risks":[]}\n```'
158
+ })
159
+ const failed = await B.tools.get('project_run').execute(runArgs('broken'), { agent: B.agent, signal: undefined })
160
+ check('规划连挂时返回 blocked', () => ({ ok: failed.outcome === 'blocked', detail: failed.outcome }))
161
+ check('说明里有「为什么停」', () => failed.note.includes('为什么停'))
162
+ check('说明里有「能不能接着跑」', () => failed.note.includes('能不能接着跑'))
163
+ check('说明里有「不管它会怎样」', () => failed.note.includes('不管它会怎样'))
164
+ check('说明里点明是规划这一阶', () => failed.note.includes('第 2 阶'))
165
+
166
+ // 这一轮的项目叫 broken,不是 harness 里那个默认的 demo
167
+ const nextStepPath = join(B.dir, '.project-flow', 'broken', 'Next_Step.md')
168
+ check('Next_Step.md 落盘了', () => existsSync(nextStepPath))
169
+ const nextStep = existsSync(nextStepPath) ? await readFile(nextStepPath, 'utf8') : ''
170
+ check('Next_Step.md 内容是那份说明', () => ({
171
+ ok: nextStep.includes('为什么停') && nextStep.includes('不管它会怎样'),
172
+ detail: nextStep.slice(0, 200),
173
+ }))
174
+
175
+ // ── 汇总 ────────────────────────────────────────────────
176
+
177
+ let failedCount = 0
178
+ for (const r of results) {
179
+ console.log(`${r.ok ? '✔' : '✖'} ${r.label}${r.ok || r.detail === '' ? '' : `\n → ${r.detail}`}`)
180
+ if (!r.ok) failedCount += 1
181
+ }
182
+ console.log(`\n${results.length - failedCount}/${results.length} 通过`)
183
+
184
+ for (const dir of [A.dir, happy.dir, B.dir]) {
185
+ await rm(dir, { recursive: true, force: true }).catch(() => {})
186
+ }
187
+ process.exit(failedCount === 0 ? 0 : 1)
@@ -0,0 +1,168 @@
1
+ /**
2
+ * 工作流目录的自动创建。
3
+ *
4
+ * 用户报的两件事都在这里钉住:
5
+ * 1. 「装上之后没法自动建工作流」——建不出来时以前静默退回,什么都不说;
6
+ * 2. 「默认不要在此盘」——默认工作区在 C 盘,工作流不该建在系统盘上。
7
+ *
8
+ * 凡是会真建目录的用例,都用显式 flowRoot 指到临时目录,绝不按平台规则
9
+ * 往真实磁盘上写东西。
10
+ */
11
+ import { test } from 'node:test'
12
+ import assert from 'node:assert/strict'
13
+ import { join } from 'node:path'
14
+ import { mkdtemp, rm, mkdir, writeFile } from 'node:fs/promises'
15
+ import { existsSync } from 'node:fs'
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 + `?t=${Date.now()}`)
21
+ const { ensureFlowRoot, flowRootOf, insideFlow, flowModeOf, onSystemDrive, pickDataDrive } = mod
22
+
23
+ const settingsOf = over => ({
24
+ flowRoot: '',
25
+ // 和插件默认值对齐:不写 flowGate 就是 off。
26
+ flowGate: 'off',
27
+ autoCreateFlowDir: true,
28
+ ...over,
29
+ })
30
+
31
+ /** 指到临时目录里,避免测试按平台规则往真实盘上写。strict 下才有「建了再进」。 */
32
+ const sandbox = dir => settingsOf({ flowRoot: join(dir, '工作流'), flowGate: 'strict' })
33
+
34
+ const withTemp = async fn => {
35
+ const dir = await mkdtemp(join(tmpdir(), 'pf-flow-'))
36
+ try {
37
+ return await fn(dir)
38
+ } finally {
39
+ await rm(dir, { recursive: true, force: true })
40
+ }
41
+ }
42
+
43
+ test('默认是 off 门控 + 自动建目录', () => {
44
+ assert.equal(flowModeOf({}), 'off', 'flowGate 不写就是 off,装上即可用')
45
+ assert.equal(flowModeOf({ flowGate: 'off' }), 'off')
46
+ assert.equal(flowModeOf({ flowGate: 'auto' }), 'auto', 'auto 是合法值,不该被归一掉')
47
+ assert.equal(flowModeOf({ flowGate: 'strict' }), 'strict')
48
+ assert.equal(flowModeOf({ flowGate: '瞎写' }), 'off', '认不出来的一律按 off,别悄悄把门关上')
49
+ })
50
+
51
+ test('默认 off:普通目录也能开,且不凭空建目录', () => withTemp(async dir => {
52
+ assert.equal(insideFlow(dir, settingsOf()), true, '默认不设目录边界')
53
+ const ensured = await ensureFlowRoot(dir, settingsOf())
54
+ assert.equal(ensured.created, false, '默认模式不该凭空造目录')
55
+ assert.equal(ensured.root, dir, '工作目录就是当前目录')
56
+ }))
57
+
58
+ test('strict 下普通目录不在工作流里', () => withTemp(async dir => {
59
+ assert.equal(insideFlow(dir, settingsOf({ flowGate: 'strict' })), false)
60
+ }))
61
+
62
+ test('strict 下名字叫「工作流」的目录算在里面', () => withTemp(async dir => {
63
+ const flow = join(dir, '工作流')
64
+ await mkdir(flow, { recursive: true })
65
+ assert.equal(insideFlow(flow, settingsOf({ flowGate: 'strict' })), true)
66
+ }))
67
+
68
+ test('strict 下工作流下面的子目录也算在里面', () => withTemp(async dir => {
69
+ const sub = join(dir, '工作流', '某个项目')
70
+ await mkdir(sub, { recursive: true })
71
+ assert.equal(insideFlow(sub, settingsOf({ flowGate: 'strict' })), true)
72
+ }))
73
+
74
+ test('门控 off 时哪儿都能开,也不建目录', () => withTemp(async dir => {
75
+ const off = settingsOf({ flowGate: 'off' })
76
+ assert.equal(insideFlow(dir, off), true, 'off 模式不设边界')
77
+ const ensured = await ensureFlowRoot(dir, off)
78
+ assert.equal(ensured.created, false, 'off 模式不该凭空造目录')
79
+ }))
80
+
81
+ test('普通的目录里开工,会把「工作流」建出来', () => withTemp(async dir => {
82
+ assert.equal(existsSync(join(dir, '工作流')), false)
83
+ const ensured = await ensureFlowRoot(dir, sandbox(dir))
84
+ assert.equal(ensured.created, true, '应该建了')
85
+ assert.equal(ensured.root, join(dir, '工作流'))
86
+ assert.equal(ensured.moved, true)
87
+ assert.equal(existsSync(join(dir, '工作流')), true, '目录真的在磁盘上')
88
+ }))
89
+
90
+ test('建完之后 insideFlow 认这个新目录', () => withTemp(async dir => {
91
+ // 只在 strict 下才有「建出来再进门」这回事:off 不设边界,建不建都放行。
92
+ const ensured = await ensureFlowRoot(dir, { ...sandbox(dir), flowGate: 'strict' })
93
+ assert.equal(insideFlow(ensured.root, { flowGate: 'strict' }),
94
+ true, '建完还认不出来的话,接下来的门控会立刻把刚建的目录拒掉')
95
+ }))
96
+
97
+ test('已经在工作流里就不再建,也不挪', () => withTemp(async dir => {
98
+ const flow = join(dir, '工作流')
99
+ await mkdir(flow, { recursive: true })
100
+ const ensured = await ensureFlowRoot(flow, { ...sandbox(dir), flowGate: 'strict' })
101
+ assert.equal(ensured.created, false)
102
+ assert.equal(ensured.moved, false)
103
+ assert.equal(ensured.root, flow)
104
+ }))
105
+
106
+ test('重复调用不会建出第二层', () => withTemp(async dir => {
107
+ await ensureFlowRoot(dir, sandbox(dir))
108
+ const again = await ensureFlowRoot(dir, sandbox(dir))
109
+ assert.equal(again.created, false, '第二次不该再报「新建了」')
110
+ assert.equal(existsSync(join(dir, '工作流', '工作流')), false, '不该套娃')
111
+ }))
112
+
113
+ test('建不出来要说清,不能静默退回', () => withTemp(async dir => {
114
+ // 拿一个已经存在的「文件」当目录用,mkdir 必失败。
115
+ const blocker = join(dir, '被占住的名字')
116
+ await writeFile(blocker, 'x', 'utf8')
117
+
118
+ // 必须 strict 才会走到「建」这一步:off 压根不建目录,也就无从失败。
119
+ const ensured = await ensureFlowRoot(dir, {
120
+ flowRoot: join(blocker, '工作流'),
121
+ flowGate: 'strict',
122
+ autoCreateFlowDir: true,
123
+ })
124
+
125
+ assert.equal(ensured.created, false)
126
+ assert.equal(ensured.root, dir, '失败时退回原目录')
127
+ assert.ok(typeof ensured.error === 'string' && ensured.error !== '',
128
+ '必须带上错误原因——以前这里什么都不说,用户只看到「不在工作流目录里」')
129
+ assert.equal(ensured.attempted, join(blocker, '工作流'), '还要说清试的是哪个路径')
130
+ }))
131
+
132
+ // ── 默认不往系统盘上建 ──────────────────────────────────
133
+
134
+ test('系统盘判定:C 盘算,D 盘不算', () => {
135
+ if (process.platform !== 'win32') return
136
+ assert.equal(onSystemDrive('C:\\Users\\x'), true)
137
+ assert.equal(onSystemDrive('c:/users/x'), true, '大小写和斜杠都要归一')
138
+ assert.equal(onSystemDrive('D:\\work'), false)
139
+ })
140
+
141
+ test('cwd 在系统盘上时,根挪到别的盘', () => {
142
+ if (process.platform !== 'win32') return
143
+ const data = pickDataDrive()
144
+ if (data === undefined) return // 单盘机器,没得挪,跳过
145
+ const root = flowRootOf('C:\\Users\\ASUS\\default-workspace', settingsOf())
146
+ assert.equal(onSystemDrive(root), false, `根不该落在系统盘上,实际 ${root}`)
147
+ assert.ok(root.startsWith(data), `应该挪到 ${data},实际 ${root}`)
148
+ })
149
+
150
+ test('cwd 本来就在别的盘上,就在它下面建', () => {
151
+ if (process.platform !== 'win32') return
152
+ const data = pickDataDrive()
153
+ if (data === undefined) return
154
+ const root = flowRootOf(`${data}\\myproj`, settingsOf())
155
+ assert.equal(root, join(`${data}\\myproj`, '工作流'))
156
+ })
157
+
158
+ test('配了 flowRoot 就听配置的,不管在哪个盘', () => {
159
+ const root = flowRootOf('C:\\whatever', settingsOf({ flowRoot: 'C:\\我就要这里' }))
160
+ assert.equal(root, join('C:\\我就要这里'))
161
+ })
162
+
163
+ test('flowRootOf 不配且不是系统盘,就是 cwd 下的「工作流」', () => {
164
+ if (process.platform !== 'win32') return
165
+ const data = pickDataDrive()
166
+ if (data === undefined) return
167
+ assert.equal(flowRootOf(`${data}\\demo`, settingsOf()), join(`${data}\\demo`, '工作流'))
168
+ })
@@ -0,0 +1,232 @@
1
+ /**
2
+ * 工作流目录这道门:判据对不对。
3
+ *
4
+ * 这不是权限,是给用户的一道分界线——重要的活丢进「工作流」,普通的照常做。
5
+ * 所以判错的两种后果都要防:
6
+ * 1. 该放的放不进去(工作流里开不了工)→ 这道门变成墙
7
+ * 2. 不该放的地方放进去(普通目录也能跑)→ 这道门形同虚设
8
+ *
9
+ * 从落盘的 index.js 里切出流式函数跑,不验复刻版。
10
+ */
11
+ import { readFile, writeFile, unlink, mkdtemp, stat, mkdir } from 'node:fs/promises'
12
+ import { join, resolve } from 'node:path'
13
+ import { tmpdir } from 'node:os'
14
+ import { pathToFileURL } from 'node:url'
15
+ import { TRIAL, requireTarget } from './paths.mjs'
16
+
17
+ const src = await readFile(requireTarget(), 'utf8')
18
+ const lines = src.split(/\r?\n/u)
19
+
20
+ function sliceTopLevel(startLine) {
21
+ const out = []
22
+ for (let i = startLine; i < lines.length; i += 1) {
23
+ out.push(lines[i])
24
+ if (i > startLine && /^\}/u.test(lines[i])) break
25
+ }
26
+ return out.join('\n')
27
+ }
28
+
29
+ function findLine(re) {
30
+ const i = lines.findIndex(line => re.test(line))
31
+ if (i === -1) throw new Error(`找不到 ${re}`)
32
+ return i
33
+ }
34
+
35
+ const mod = [
36
+ "import { join, isAbsolute, resolve, relative, sep } from 'node:path'",
37
+ "import { mkdir } from 'node:fs/promises'",
38
+ "import { existsSync } from 'node:fs'",
39
+ lines[findLine(/^const FLOW_DIR_NAME = /u)],
40
+ lines[findLine(/^const FLOW_GATE_MODES = /u)],
41
+ // flowRootOf 现在依赖这两个:一个判「是不是系统盘」,一个挑「该挪到哪个盘」。
42
+ // 不切进来就是 ReferenceError。
43
+ sliceTopLevel(findLine(/^(?:export )?function onSystemDrive\(/u)),
44
+ sliceTopLevel(findLine(/^(?:export )?function pickDataDrive\(/u)),
45
+ sliceTopLevel(findLine(/^(?:export )?function flowModeOf\(/u)),
46
+ sliceTopLevel(findLine(/^(?:export )?function flowRootOf\(/u)),
47
+ // flowGateMessage 现在依赖这两个:一个判断「配置里写死了没」,
48
+ // 一个算出「真正该去的那一层」。不切进来就是 ReferenceError。
49
+ sliceTopLevel(findLine(/^(?:export )?function flowRootConfigured\(/u)),
50
+ sliceTopLevel(findLine(/^(?:export )?function flowRootTargetOf\(/u)),
51
+ sliceTopLevel(findLine(/^(?:export )?function insideFlow\(/u)),
52
+ sliceTopLevel(findLine(/^(?:export )?function flowGateMessage\(/u)),
53
+ sliceTopLevel(findLine(/^(?:export )?async function ensureFlowRoot\(/u)),
54
+ 'export { FLOW_DIR_NAME, FLOW_GATE_MODES, flowModeOf, flowRootOf, flowRootConfigured, flowRootTargetOf, insideFlow, flowGateMessage, ensureFlowRoot }',
55
+ ].join('\n\n')
56
+ // 切出来的函数有些带 `export` 前缀(它们要导出给别的测试用),再统一导出
57
+ // 一次就会撞成 Duplicate export。先剥掉函数上的那种,`export {` 那行留着当地唯一出口。
58
+ .replace(/^export (?!\{)/gmu, '')
59
+
60
+ const tmp = join(TRIAL, '_gate_extracted.mjs')
61
+ // 这个目录在一次干净的包里还不存在(开发工作区里是跑别的套件时建出来的)。
62
+ // 依赖「上一个测试顺手建了它」是最容易在别人机器上崩的一类写法。
63
+ await mkdir(TRIAL, { recursive: true })
64
+ await writeFile(tmp, mod, 'utf8')
65
+ const { insideFlow, flowRootOf, flowGateMessage, flowModeOf, ensureFlowRoot, FLOW_DIR_NAME } = await import(pathToFileURL(tmp).href)
66
+
67
+ const results = []
68
+ const pending = []
69
+ const check = (label, fn) => { pending.push({ label, fn }) }
70
+
71
+ const runChecks = async () => {
72
+ for (const item of pending) {
73
+ let ok = false
74
+ let detail = ''
75
+ try {
76
+ const out = await item.fn()
77
+ ok = out === true || (out && out.ok === true)
78
+ detail = out && out.detail ? String(out.detail) : ''
79
+ } catch (error) {
80
+ ok = false
81
+ detail = error.message
82
+ }
83
+ results.push({ label: item.label, ok, detail })
84
+ }
85
+ }
86
+
87
+ const NONE = {}
88
+ /** 默认就是 off:装上即用,不在目录上设门槛。 */
89
+ const OFF = { flowGate: 'off' }
90
+ /** strict:主动要那道边界时才有。 */
91
+ const STRICT = { flowGate: 'strict' }
92
+
93
+ // ── 默认(off):不设目录门槛 ───────────────────────────
94
+
95
+ check('默认就是 off:普通目录也放行', () => (
96
+ flowModeOf({}) === 'off' && insideFlow('C:\\work', NONE) === true
97
+ ))
98
+ check('默认 off 下,任何别的地方都能开', () => (
99
+ insideFlow('C:\\随便一个地方', NONE) === true
100
+ ))
101
+ check('auto 是合法值,同样不拦', () => (
102
+ flowModeOf({ flowGate: 'auto' }) === 'auto' && insideFlow('C:\\work', { flowGate: 'auto' }) === true
103
+ ))
104
+
105
+ // ── strict:只认工作流目录 ──────────────────────────────
106
+
107
+ check('strict:普通目录不放行', () => (
108
+ insideFlow('C:\\work', STRICT) === false
109
+ ))
110
+ check('strict:工作流目录本身可以开', () => (
111
+ insideFlow(`C:\\work\\${FLOW_DIR_NAME}`, STRICT) === true
112
+ ))
113
+ check('strict:工作流下面的子目录也可以', () => (
114
+ insideFlow(`C:\\work\\${FLOW_DIR_NAME}\\api`, STRICT) === true
115
+ ))
116
+ check('strict:名字只是前缀的一部分不算(工作流备份 不是 工作流)', () => (
117
+ insideFlow(`C:\\work\\${FLOW_DIR_NAME}备份`, STRICT) === false
118
+ ))
119
+ check('strict:路径里任何一层叫工作流都算', () => (
120
+ insideFlow(`C:/work/${FLOW_DIR_NAME}/很深的/子目录`, STRICT) === true
121
+ ))
122
+ check('strict:正斜杠反斜杠都认', () => (
123
+ insideFlow(`C:/work/${FLOW_DIR_NAME}`, STRICT) === true
124
+ && insideFlow(`C:\\work\\${FLOW_DIR_NAME}`, STRICT) === true
125
+ ))
126
+
127
+ // ── off:明确表示不要这道门 ─────────────────────────────
128
+
129
+ check('off 模式任何目录都能开', () => (
130
+ insideFlow('C:\\随便一个地方', OFF) === true
131
+ ))
132
+ check('写错的模式值退到 off,不会意外把门关上', () => (
133
+ flowModeOf({ flowGate: '瞎写' }) === 'off' && insideFlow('C:\\work', { flowGate: '瞎写' }) === true
134
+ ))
135
+
136
+ // ── 自动建目录:这一版新增的那一步 ──────────────────────
137
+
138
+ check('已在工作流目录里时不建、也不改目录', async () => {
139
+ const ensured = await ensureFlowRoot(`C:\\work\\${FLOW_DIR_NAME}`, NONE)
140
+ return { ok: ensured.created === false && ensured.moved === false, detail: JSON.stringify(ensured) }
141
+ })
142
+
143
+ check('普通目录里会自动把工作流建出来,并把工作目录指过去', async () => {
144
+ const base = await mkdtemp(join(tmpdir(), 'pf-ensure-'))
145
+ // 显式把 flowRoot 指到临时目录里:不配的话,cwd 落在系统盘时根会被挪到
146
+ // 别的盘(那是有意的),这条断言就跟平台无关了。
147
+ const ensured = await ensureFlowRoot(base, { flowRoot: join(base, FLOW_DIR_NAME), flowGate: 'strict' })
148
+ const exists = await stat(ensured.root).then(info => info.isDirectory()).catch(() => false)
149
+ return {
150
+ ok: ensured.created === true
151
+ && ensured.moved === true
152
+ && ensured.root === join(base, FLOW_DIR_NAME)
153
+ && exists,
154
+ detail: `${ensured.root} created=${ensured.created}`,
155
+ }
156
+ })
157
+
158
+ check('建过一次之后不会重复报「新建」', async () => {
159
+ const base = await mkdtemp(join(tmpdir(), 'pf-ensure2-'))
160
+ const settings = { flowRoot: join(base, FLOW_DIR_NAME), flowGate: 'strict' }
161
+ await ensureFlowRoot(base, settings)
162
+ // 第二次从同一个 base 出发:目录已存在,但 base 本身仍不在工作流里,
163
+ // 所以还是会把它指过去——只是这一步不该再算「新建」
164
+ const again = await ensureFlowRoot(base, settings)
165
+ return {
166
+ ok: again.root === join(base, FLOW_DIR_NAME) && again.created === false,
167
+ detail: JSON.stringify(again),
168
+ }
169
+ })
170
+
171
+ check('配了绝对 flowRoot 时按配置建,不看名字', async () => {
172
+ const base = await mkdtemp(join(tmpdir(), 'pf-ensure3-'))
173
+ const target = join(base, '我的活')
174
+ const ensured = await ensureFlowRoot(base, { flowRoot: target, flowGate: 'strict' })
175
+ return { ok: ensured.root === target && ensured.created === true, detail: ensured.root }
176
+ })
177
+
178
+ // ── 配了绝对路径:只在 strict 下认子树 ──────────────────
179
+
180
+ const ROOT = 'C:\\Users\\ASUS\\流向'
181
+ check('strict + flowRoot 绝对路径:根可以开', () =>
182
+ insideFlow(ROOT, { flowRoot: ROOT, flowGate: 'strict' }) === true)
183
+ check('strict + flowRoot 绝对路径:子目录可以开', () =>
184
+ insideFlow(`${ROOT}\\proj`, { flowRoot: ROOT, flowGate: 'strict' }) === true)
185
+ check('strict + flowRoot 绝对路径:外面不行', () =>
186
+ insideFlow('C:\\Users\\ASUS\\别处', { flowRoot: ROOT, flowGate: 'strict' }) === false)
187
+ check('strict + flowRoot 绝对路径:不再看名字(叫工作流也不认)', () =>
188
+ insideFlow(`C:\\work\\${FLOW_DIR_NAME}`, { flowRoot: ROOT, flowGate: 'strict' }) === false)
189
+ check('flowRoot 尾随反斜杠不影响', () =>
190
+ insideFlow(`${ROOT}\\proj`, { flowRoot: `${ROOT}\\`, flowGate: 'strict' }) === true)
191
+ // 配了绝对路径不再顺带把门关死:默认 off 时,别处也能先试试。
192
+ check('默认 off 时配了 flowRoot 也不拦别处', () =>
193
+ insideFlow('C:\\别的目录', { flowRoot: ROOT }) === true)
194
+
195
+ // ── 配了个名字:还是认名字 ──────────────────────────────
196
+
197
+ check('flowRoot 填名字:strict 下按名字认', () => (
198
+ insideFlow('C:\\work\\我的活\\a', { flowRoot: '我的活', flowGate: 'strict' }) === true
199
+ && insideFlow(`C:\\work\\${FLOW_DIR_NAME}`, { flowRoot: '我的活', flowGate: 'strict' }) === false
200
+ ))
201
+
202
+ // ── 提示语要给对的地方 ──────────────────────────────────
203
+
204
+ check('被拦住时给出该去的目录,并说明目录会自动建', () => {
205
+ const text = flowGateMessage('C:\\work', STRICT)
206
+ // 目标目录不再固定是 `<cwd>\工作流`:cwd 落在系统盘时会被挪到别的盘。
207
+ // 所以拿 flowRootOf 算出来的那个来比,别写死。
208
+ const target = flowRootOf('C:\\work', STRICT)
209
+ return {
210
+ ok: text.includes(target)
211
+ && /不用你自己建/u.test(text)
212
+ && /自动建|会把这个目录建出来/u.test(text)
213
+ && /flow-set 门控 off/u.test(text),
214
+ detail: text.slice(0, 260),
215
+ }
216
+ })
217
+
218
+ check('配了 flowRoot 时提示语指向配置的位置', () => {
219
+ const text = flowGateMessage('C:\\work', { flowRoot: ROOT, flowGate: 'strict' })
220
+ return { ok: text.includes(ROOT), detail: text.slice(0, 160) }
221
+ })
222
+
223
+ await runChecks()
224
+
225
+ let failed = 0
226
+ for (const r of results) {
227
+ console.log(`${r.ok ? '✔' : '✖'} ${r.label}${r.ok || r.detail === '' ? '' : `\n → ${r.detail}`}`)
228
+ if (!r.ok) failed += 1
229
+ }
230
+ console.log(`\n${results.length - failed}/${results.length} 通过`)
231
+ await unlink(tmp).catch(() => {})
232
+ process.exit(failed === 0 ? 0 : 1)