dsh-extra-plan 0.0.0-stage → 1.7.0

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 (56) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +179 -2
  3. package/assets/presets/extra-plan/agent.cordis.yml +580 -0
  4. package/assets/presets/extra-plan/preset-definition-extra-plan-executor.generated.yml +115 -0
  5. package/assets/presets/extra-plan/preset-definition-extra-plan-planner.generated.yml +113 -0
  6. package/assets/presets/extra-plan/preset-definition-extra-plan-prober.generated.yml +107 -0
  7. package/assets/presets/extra-plan/preset-definition-extra-plan-reviewer.generated.yml +115 -0
  8. package/assets/presets/extra-plan/preset-definition.generated.yml +335 -0
  9. package/assets/presets/extra-plan/preset.yml +2 -0
  10. package/cordis.patch.yml +7 -0
  11. package/index.js +1671 -0
  12. package/lib/agent-runtime.js +172 -0
  13. package/lib/agent-session.js +65 -0
  14. package/lib/assembly-presentation.js +267 -0
  15. package/lib/client-carrier.js +7 -0
  16. package/lib/client.js +314 -0
  17. package/lib/extra-plan-gate-tool.js +387 -0
  18. package/lib/gate-decisions.js +744 -0
  19. package/lib/gate-words.js +108 -0
  20. package/lib/live-config.js +293 -0
  21. package/lib/log-retention.js +132 -0
  22. package/lib/model-routing.js +648 -0
  23. package/lib/path-policy.js +464 -0
  24. package/lib/plan-draft-tool.js +294 -0
  25. package/lib/planner-budget.js +136 -0
  26. package/lib/preset-defaults.generated.js +17 -0
  27. package/lib/preset-settings.js +3 -0
  28. package/lib/preset-sync.js +809 -0
  29. package/lib/preset-yaml.js +438 -0
  30. package/lib/role-contract.js +11 -0
  31. package/lib/run-code-scanner.js +360 -0
  32. package/lib/run-code-static.js +621 -0
  33. package/lib/runtime-diagnostics.js +89 -0
  34. package/lib/runtime-lifecycle.js +162 -0
  35. package/lib/runtime-static.js +23 -0
  36. package/lib/save-contract.js +263 -0
  37. package/lib/save-persistence.js +223 -0
  38. package/lib/save-plan-markdown-parser.js +369 -0
  39. package/lib/save-plan-validation-diagnostics.js +49 -0
  40. package/lib/save-plan-validation.js +812 -0
  41. package/lib/save-probe-validation.js +173 -0
  42. package/lib/save-source-verification.js +195 -0
  43. package/lib/save-tool-factories.js +270 -0
  44. package/lib/sdk-text-cache.js +161 -0
  45. package/lib/settings-contract.js +191 -0
  46. package/lib/settings.js +369 -0
  47. package/lib/shell-mutation.js +484 -0
  48. package/lib/usage-ledger-background.js +214 -0
  49. package/lib/usage-ledger-worker.js +116 -0
  50. package/lib/usage-ledger.js +1393 -0
  51. package/locale/en.json +6 -0
  52. package/locale/settings/en.json +6 -0
  53. package/locale/settings/zh.json +6 -0
  54. package/locale/zh.json +6 -0
  55. package/package.json +56 -4
  56. package/scripts/generate-runtime-defaults.mjs +796 -0
@@ -0,0 +1,173 @@
1
+ import { isAbsolute, join, resolve } from 'node:path'
2
+ import { createPathContext, resolveWorkspacePath, resolveHostPath, validateReadTarget } from './path-policy.js'
3
+ import { PROBE_LIMITS, LINE_FORMAT_HINT, RANGE_FORMAT_HINT } from './save-contract.js'
4
+ import { errorCodeOf } from './runtime-static.js'
5
+
6
+ // save_probe 校验合同:先完成结构、条目、长度、总量与 range 校验,再按已授权根做路径读校验。
7
+
8
+ function contextOf(cwd, supplied) {
9
+ if (supplied !== undefined && supplied !== null) return supplied
10
+ if (typeof cwd !== 'string' || cwd === '') return null
11
+ return createPathContext({ workspaceRoot: cwd })
12
+ }
13
+
14
+ function resolveAbsoluteProbeTarget(context, value) {
15
+ let workspaceError
16
+ let hostError
17
+ try {
18
+ // 明确落在W内的绝对引用归W;即使HdataRoot是W子目录,也不把合法W引用误判为H/W冲突。
19
+ return resolveWorkspacePath(context, value, { purpose: 'probe-reference' })
20
+ } catch (error) {
21
+ workspaceError = error
22
+ }
23
+ try {
24
+ return resolveHostPath(context, value, { purpose: 'probe-reference' })
25
+ } catch (error) {
26
+ hostError = error
27
+ }
28
+ const capabilities = context.hostCapabilities !== null && typeof context.hostCapabilities === 'object' ? context.hostCapabilities : {}
29
+ for (const [name, descriptor] of Object.entries(capabilities)) {
30
+ if (descriptor === null || typeof descriptor !== 'object') continue
31
+ const purpose = typeof descriptor.purpose === 'string' && descriptor.purpose !== '' ? descriptor.purpose : 'probe-reference'
32
+ try {
33
+ return resolveHostPath(context, value, { capability: name, purpose })
34
+ } catch (error) {
35
+ // 仅按已注册能力继续词法匹配;不以exists/stat试探其它根。
36
+ }
37
+ }
38
+ throw workspaceError || hostError || new Error('探查路径不在授权W/H或已知Host capability内')
39
+ }
40
+
41
+ export function resolveProbeTarget(cwd, value, pathContext) {
42
+ const context = contextOf(cwd, pathContext)
43
+ if (context === null) throw new Error('探查路径缺少明确工作区根')
44
+ if (typeof value !== 'string') throw new Error('探查路径必须是字符串')
45
+ if (!isAbsolute(value)) return resolveWorkspacePath(context, value, { purpose: 'probe-reference' })
46
+ return resolveAbsoluteProbeTarget(context, value)
47
+ }
48
+
49
+ function pathViolation(cwd, value, pathContext) {
50
+ let target
51
+ try {
52
+ target = resolveProbeTarget(cwd, value, pathContext)
53
+ } catch (error) {
54
+ return '路径未授权:' + value + '(' + (error instanceof Error ? error.message : String(error)) + ')'
55
+ }
56
+ try {
57
+ validateReadTarget(pathContext || contextOf(cwd, undefined), target, { expectedType: 'file', purpose: 'probe-reference' })
58
+ return null
59
+ } catch (error) {
60
+ if (errorCodeOf(error) === 'TARGET_MISSING') return '路径不存在:' + value
61
+ return '路径不可读取:' + value + '(' + (error instanceof Error ? error.message : String(error)) + ')'
62
+ }
63
+ }
64
+
65
+ export function validateProbe(args, cwd, pathContext) {
66
+ if (args === null || typeof args !== 'object') return 'save_probe: 参数必须是对象(四字段 fileMap/focusAreas/exclusions/background 均为数组)'
67
+ const violations = []
68
+ const pathRefs = []
69
+ const fields = ['fileMap', 'focusAreas', 'exclusions', 'background']
70
+ for (const field of fields) {
71
+ if (!Array.isArray(args[field])) { violations.push('save_probe: ' + field + ' 必须是数组'); continue }
72
+ const limit = PROBE_LIMITS.maxEntries[field]
73
+ if (args[field].length > limit) violations.push('save_probe: ' + field + ' 条目数 ' + args[field].length + ' 超过上限 ' + limit)
74
+ }
75
+ if (Array.isArray(args.fileMap)) {
76
+ for (let i = 0; i < args.fileMap.length; i += 1) {
77
+ const item = args.fileMap[i]
78
+ if (item === null || typeof item !== 'object') { violations.push('save_probe: fileMap[' + i + '] 必须是对象'); continue }
79
+ if (typeof item.path !== 'string') violations.push('save_probe: fileMap[' + i + '].path 必须是字符串')
80
+ else if (item.path.length > PROBE_LIMITS.maxPathLen) violations.push('save_probe: fileMap[' + i + '].path 长度 ' + item.path.length + ' 超过上限 ' + PROBE_LIMITS.maxPathLen)
81
+ else pathRefs.push({ field: 'fileMap', index: i, value: item.path })
82
+ if (typeof item.relation !== 'string') violations.push('save_probe: fileMap[' + i + '].relation 必须是字符串')
83
+ else if (item.relation.length > PROBE_LIMITS.maxRelationLen) violations.push('save_probe: fileMap[' + i + '].relation 长度 ' + item.relation.length + ' 超过上限 ' + PROBE_LIMITS.maxRelationLen)
84
+ }
85
+ }
86
+ if (Array.isArray(args.focusAreas)) {
87
+ for (let i = 0; i < args.focusAreas.length; i += 1) {
88
+ const item = args.focusAreas[i]
89
+ if (item === null || typeof item !== 'object') { violations.push('save_probe: focusAreas[' + i + '] 必须是对象'); continue }
90
+ if (typeof item.path !== 'string') violations.push('save_probe: focusAreas[' + i + '].path 必须是字符串')
91
+ else if (item.path.length > PROBE_LIMITS.maxPathLen) violations.push('save_probe: focusAreas[' + i + '].path 长度 ' + item.path.length + ' 超过上限 ' + PROBE_LIMITS.maxPathLen)
92
+ else pathRefs.push({ field: 'focusAreas', index: i, value: item.path })
93
+ if (typeof item.note !== 'string') violations.push('save_probe: focusAreas[' + i + '].note 必须是字符串')
94
+ else if (item.note.length > PROBE_LIMITS.maxNoteLen) violations.push('save_probe: focusAreas[' + i + '].note 长度 ' + item.note.length + ' 超过上限 ' + PROBE_LIMITS.maxNoteLen)
95
+ if (item.range !== undefined && item.range !== null && item.range !== '') {
96
+ if (typeof item.range !== 'string') violations.push('save_probe: focusAreas[' + i + '].range 必须是字符串')
97
+ else if (item.range.length > PROBE_LIMITS.maxRangeLen) violations.push('save_probe: focusAreas[' + i + '].range 长度 ' + item.range.length + ' 超过上限 ' + PROBE_LIMITS.maxRangeLen)
98
+ else if (!new RegExp(PROBE_LIMITS.rangePattern, 'i').test(item.range)) violations.push('save_probe: focusAreas[' + i + '].range 非法:' + item.range + '(' + RANGE_FORMAT_HINT + ';正确格式如 12 或 L12-34)')
99
+ }
100
+ }
101
+ }
102
+ if (Array.isArray(args.exclusions)) {
103
+ for (let i = 0; i < args.exclusions.length; i += 1) {
104
+ const item = args.exclusions[i]
105
+ if (item === null || typeof item !== 'object') { violations.push('save_probe: exclusions[' + i + '] 必须是对象'); continue }
106
+ if (typeof item.note !== 'string') violations.push('save_probe: exclusions[' + i + '].note 必须是字符串')
107
+ else if (item.note.length > PROBE_LIMITS.maxNoteLen) violations.push('save_probe: exclusions[' + i + '].note 长度 ' + item.note.length + ' 超过上限 ' + PROBE_LIMITS.maxNoteLen)
108
+ }
109
+ }
110
+ if (Array.isArray(args.background)) {
111
+ for (let i = 0; i < args.background.length; i += 1) {
112
+ const item = args.background[i]
113
+ if (item === null || typeof item !== 'object') { violations.push('save_probe: background[' + i + '] 必须是对象'); continue }
114
+ if (typeof item.topic !== 'string') violations.push('save_probe: background[' + i + '].topic 必须是字符串')
115
+ else if (item.topic.length > PROBE_LIMITS.maxTopicLen) violations.push('save_probe: background[' + i + '].topic 长度 ' + item.topic.length + ' 超过上限 ' + PROBE_LIMITS.maxTopicLen)
116
+ if (typeof item.detail !== 'string') violations.push('save_probe: background[' + i + '].detail 必须是字符串')
117
+ else if (item.detail.length > PROBE_LIMITS.maxDetailLen) violations.push('save_probe: background[' + i + '].detail 长度 ' + item.detail.length + ' 超过上限 ' + PROBE_LIMITS.maxDetailLen)
118
+ }
119
+ }
120
+ if (args.evidence !== undefined && args.evidence !== null) {
121
+ if (!Array.isArray(args.evidence)) violations.push('save_probe: evidence 必须是数组')
122
+ else {
123
+ if (args.evidence.length > PROBE_LIMITS.maxEvidenceEntries) violations.push('save_probe: evidence 条目数 ' + args.evidence.length + ' 超过上限 ' + PROBE_LIMITS.maxEvidenceEntries)
124
+ for (let i = 0; i < args.evidence.length; i += 1) {
125
+ const item = args.evidence[i]
126
+ if (item === null || typeof item !== 'object') { violations.push('save_probe: evidence[' + i + '] 必须是对象'); continue }
127
+ if (typeof item.path !== 'string') violations.push('save_probe: evidence[' + i + '].path 类型错误(应为字符串)')
128
+ else if (item.path.length > PROBE_LIMITS.maxPathLen) violations.push('save_probe: evidence[' + i + '].path 长度 ' + item.path.length + ' 超过上限 ' + PROBE_LIMITS.maxPathLen)
129
+ else pathRefs.push({ field: 'evidence', index: i, value: item.path })
130
+ if (item.line !== undefined && item.line !== null && item.line !== '') {
131
+ if (typeof item.line !== 'string') violations.push('save_probe: evidence[' + i + '].line 类型错误(应为字符串)')
132
+ else if (item.line.length > PROBE_LIMITS.maxEvidenceLineLen) violations.push('save_probe: evidence[' + i + '].line 长度 ' + item.line.length + ' 超过上限 ' + PROBE_LIMITS.maxEvidenceLineLen + '(' + LINE_FORMAT_HINT + ')')
133
+ else if (!new RegExp(PROBE_LIMITS.evidenceLinePattern, 'i').test(item.line)) violations.push('save_probe: evidence[' + i + '].line 非法:' + item.line + '(' + LINE_FORMAT_HINT + ')')
134
+ }
135
+ if (item.value !== undefined && item.value !== null && item.value !== '') {
136
+ if (typeof item.value !== 'string') violations.push('save_probe: evidence[' + i + '].value 类型错误(应为字符串)')
137
+ else if (item.value.length > PROBE_LIMITS.maxEvidenceValueLen) violations.push('save_probe: evidence[' + i + '].value 长度 ' + item.value.length + ' 超过上限 ' + PROBE_LIMITS.maxEvidenceValueLen)
138
+ }
139
+ if (item.text !== undefined && item.text !== null && item.text !== '') {
140
+ if (typeof item.text !== 'string') violations.push('save_probe: evidence[' + i + '].text 类型错误(应为字符串)')
141
+ else if (item.text.length > PROBE_LIMITS.maxEvidenceTextLen) violations.push('save_probe: evidence[' + i + '].text 长度 ' + item.text.length + ' 超过上限 ' + PROBE_LIMITS.maxEvidenceTextLen)
142
+ }
143
+ if (item.note !== undefined && item.note !== null && item.note !== '') {
144
+ if (typeof item.note !== 'string') violations.push('save_probe: evidence[' + i + '].note 类型错误(应为字符串)')
145
+ else if (item.note.length > PROBE_LIMITS.maxEvidenceNoteLen) violations.push('save_probe: evidence[' + i + '].note 长度 ' + item.note.length + ' 超过上限 ' + PROBE_LIMITS.maxEvidenceNoteLen)
146
+ }
147
+ if ((item.line === undefined || item.line === null || item.line === '') && (item.value === undefined || item.value === null || item.value === '') && (item.text === undefined || item.text === null || item.text === '')) violations.push('save_probe: evidence[' + i + '] 须至少提供 line/value/text 之一')
148
+ }
149
+ const evTotal = JSON.stringify(args.evidence).length
150
+ if (evTotal > PROBE_LIMITS.maxEvidenceTotalChars) violations.push('save_probe: evidence 总量 ' + evTotal + ' 字符超过上限 ' + PROBE_LIMITS.maxEvidenceTotalChars)
151
+ }
152
+ }
153
+ const allFieldsArrays = fields.every((field) => Array.isArray(args[field]))
154
+ if (allFieldsArrays) {
155
+ const total = JSON.stringify({ fileMap: args.fileMap, focusAreas: args.focusAreas, exclusions: args.exclusions, background: args.background }).length
156
+ if (total > PROBE_LIMITS.maxTotalChars) violations.push('save_probe: 四字段总量 ' + total + ' 字符超过上限 ' + PROBE_LIMITS.maxTotalChars)
157
+ }
158
+ if (violations.length === 0 && pathRefs.length > 0 && typeof cwd === 'string' && cwd !== '') {
159
+ for (const ref of pathRefs) {
160
+ const problem = pathViolation(cwd, ref.value, pathContext)
161
+ if (problem !== null) violations.push('save_probe: ' + ref.field + '[' + ref.index + '].path ' + problem)
162
+ }
163
+ }
164
+ if (violations.length === 0) return null
165
+ return 'save_probe: 校验不通过,共发现 ' + violations.length + ' 处违规(超限一律拒绝、不静默截断,请逐条修正后重试):\n- ' + violations.join('\n- ')
166
+ }
167
+
168
+ // 兼容旧调用:无上下文时只做词法拼接;生产路径校验必须传入pathContext并使用resolveProbeTarget。
169
+ export function probePathOf(cwd, p, pathContext) {
170
+ if (pathContext !== undefined && pathContext !== null) return resolveProbeTarget(cwd, p, pathContext).path
171
+ if (isAbsolute(p)) return p
172
+ return resolve(join(cwd, p))
173
+ }
@@ -0,0 +1,195 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { basename, dirname, resolve } from 'node:path'
3
+ import { TextDecoder } from 'node:util'
4
+ import { resolveProbeTarget } from './save-probe-validation.js'
5
+ import { createPathContext, resolveWorkspacePath, validateReadTarget } from './path-policy.js'
6
+ import { errorCodeOf } from './runtime-static.js'
7
+
8
+ const sourceDecoder = new TextDecoder('utf-8', { fatal: true })
9
+
10
+ // 证据错误用 JSON.stringify 展示引用,必要时追加非权威的装饰提示。
11
+ // 提示只检查下方诊断字符集的首字符;成对清洗在 save-contract.js,
12
+ // 文件名中的单侧装饰保持不变,供存在性校验使用。
13
+ const PROBE_REF_DECOR_RE = /^[`*_"'<>[\]()()「」【】『』,。;:!?、|]/
14
+ function probeRefDecorationHint(ref) {
15
+ return PROBE_REF_DECOR_RE.test(ref) ? '(疑似含 Markdown 装饰;引用证据请使用裸路径,每条单独一行)' : ''
16
+ }
17
+
18
+ // 仅读取会话头部工作区,不计算目录、短名或工件 base。
19
+ export function cwdOf(exec) {
20
+ const session = exec !== undefined && exec !== null && exec.agent !== undefined && exec.agent !== null ? exec.agent.session : undefined
21
+ const header = session !== undefined && session !== null && session.header !== undefined && session.header !== null ? session.header : undefined
22
+ return header !== undefined && typeof header.cwd === 'string' ? header.cwd : ''
23
+ }
24
+
25
+ export function pathContextOf(cwd, getPathContext) {
26
+ if (typeof getPathContext === 'function') {
27
+ const supplied = getPathContext(cwd)
28
+ if (supplied !== undefined && supplied !== null) return supplied
29
+ }
30
+ return createPathContext({ workspaceRoot: cwd })
31
+ }
32
+
33
+ const SOURCE_RANGE_RE = /^L([1-9]\d*)(?:-([1-9]\d*))?$/
34
+
35
+ function sourceCacheKey(value) {
36
+ const normalized = String(value).replace(/\\/g, '/')
37
+ return process.platform === 'win32' ? normalized.toLowerCase() : normalized
38
+ }
39
+
40
+ function resolveMissingWorkspaceIdentity(pathContext, target) {
41
+ const missingSegments = []
42
+ let missingPath = target.path
43
+ for (;;) {
44
+ const parentPath = dirname(missingPath)
45
+ missingSegments.unshift(basename(missingPath))
46
+ const parentTarget = resolveWorkspacePath(pathContext, parentPath, { purpose: 'save-plan-source' })
47
+ try {
48
+ const parent = validateReadTarget(pathContext, parentTarget, { expectedType: 'directory', purpose: 'save-plan-source' })
49
+ return resolve(parent.realPath, ...missingSegments)
50
+ } catch (error) {
51
+ if (errorCodeOf(error) !== 'TARGET_MISSING') throw error
52
+ missingPath = parentPath
53
+ }
54
+ }
55
+ }
56
+
57
+ function resolveWorkspaceEntry(pathContext, relativePath, cache) {
58
+ const target = resolveWorkspacePath(pathContext, relativePath, { purpose: 'save-plan-source' })
59
+ const key = sourceCacheKey(target.path)
60
+ if (cache.has(key)) return cache.get(key)
61
+ let readTarget
62
+ try {
63
+ readTarget = validateReadTarget(pathContext, target, { expectedType: 'file', purpose: 'save-plan-source' })
64
+ } catch (error) {
65
+ if (errorCodeOf(error) !== 'TARGET_MISSING') throw new Error('无法读取目标路径:' + relativePath + '(' + String(error.message || error) + ')')
66
+ let identityPath
67
+ try {
68
+ identityPath = resolveMissingWorkspaceIdentity(pathContext, target)
69
+ } catch (identityError) {
70
+ throw new Error('无法读取目标路径:' + relativePath + '(' + String(identityError.message || identityError) + ')')
71
+ }
72
+ const entry = { exists: false, path: identityPath, buffer: null, text: undefined, lines: undefined }
73
+ cache.set(key, entry)
74
+ return entry
75
+ }
76
+ let buffer
77
+ try { buffer = readFileSync(readTarget.realPath) } catch (error) { throw new Error('无法读取目标文件:' + relativePath + '(' + String(error.message || error) + ')') }
78
+ const entry = { exists: true, path: readTarget.realPath, buffer, text: undefined, lines: undefined }
79
+ cache.set(key, entry)
80
+ return entry
81
+ }
82
+
83
+ function strictTextEntry(entry, relativePath) {
84
+ if (entry.text !== undefined) return entry
85
+ let text
86
+ try { text = sourceDecoder.decode(entry.buffer) } catch (error) { throw new Error('源文件不是合法 UTF-8:' + relativePath + '(' + String(error.message || error) + ')') }
87
+ if (text.includes('\u0000')) throw new Error('源文件包含 NUL:' + relativePath)
88
+ if (text.startsWith('\uFEFF')) text = text.slice(1)
89
+ text = text.replace(/\r\n?/g, '\n')
90
+ const lines = text === '' ? [] : text.split('\n')
91
+ if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop()
92
+ entry.text = text
93
+ entry.lines = lines
94
+ return entry
95
+ }
96
+
97
+ function literalCount(line, needle) {
98
+ let count = 0
99
+ let from = 0
100
+ for (;;) {
101
+ const index = line.indexOf(needle, from)
102
+ if (index < 0) return count
103
+ count += 1
104
+ from = index + Math.max(needle.length, 1)
105
+ }
106
+ }
107
+
108
+ function verifyModificationPoint(entry, relativePath, point) {
109
+ const location = String(point.modificationLocation || '').trim()
110
+ const anchor = String(point.anchor || '').trim()
111
+ if (location === '空文件' && anchor === '空文件') {
112
+ if (entry.lines.length !== 0) throw new Error('空文件例外要求源文件去 BOM 后为空:' + relativePath)
113
+ return
114
+ }
115
+ const match = location.match(SOURCE_RANGE_RE)
116
+ if (match === null) throw new Error('修改位置格式无效:' + relativePath + '#' + String(point.id || ''))
117
+ const start = Number(match[1])
118
+ const end = match[2] === undefined ? start : Number(match[2])
119
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 1 || end < start) throw new Error('修改位置不是安全正整数区间:' + relativePath + '#' + String(point.id || ''))
120
+ if (end > entry.lines.length) throw new Error('修改位置超出源文件实际行数:' + relativePath + '#' + String(point.id || '') + '(上界 ' + end + ',实际 ' + entry.lines.length + ')')
121
+ if (anchor === '' || anchor.includes('\n') || anchor.includes('\r')) throw new Error('定位锚点必须是非空单行原文:' + relativePath + '#' + String(point.id || ''))
122
+ let matches = 0
123
+ for (const line of entry.lines.slice(start - 1, end)) matches += literalCount(line, anchor)
124
+ if (matches !== 1) throw new Error('定位锚点在指定范围内必须恰好匹配一次:' + relativePath + '#' + String(point.id || '') + '(实际 ' + matches + ' 次)')
125
+ }
126
+
127
+ // 源核实与证据核实为 save_plan 与草稿工具共用实现,导出复用,禁止复制语义。
128
+ export function verifyPlanSources(summary, pathContext) {
129
+ const cache = new Map()
130
+ const targetOwners = new Map()
131
+ const verifyFile = (fileRecord) => {
132
+ const operation = String(fileRecord.operation || '')
133
+ const entry = resolveWorkspaceEntry(pathContext, fileRecord.path, cache)
134
+ const targetKey = sourceCacheKey(entry.path)
135
+ const firstPath = targetOwners.get(targetKey)
136
+ if (firstPath !== undefined) throw new Error('多个文件记录指向同一真实目标:' + firstPath + ' 与 ' + fileRecord.path)
137
+ targetOwners.set(targetKey, fileRecord.path)
138
+ if (operation === '新建') {
139
+ if (entry.exists) throw new Error('新建目标已存在:' + fileRecord.path)
140
+ return
141
+ }
142
+ if (operation === '删除' || operation === '修改') {
143
+ if (!entry.exists) throw new Error('目标文件不存在:' + fileRecord.path)
144
+ if (operation === '修改') {
145
+ const textEntry = strictTextEntry(entry, fileRecord.path)
146
+ for (const point of fileRecord.points || []) verifyModificationPoint(textEntry, fileRecord.path, point)
147
+ }
148
+ return
149
+ }
150
+ if (operation === '生成') {
151
+ for (const point of fileRecord.points || []) {
152
+ for (const source of point.generationSources || []) {
153
+ const sourceEntry = resolveWorkspaceEntry(pathContext, source, cache)
154
+ if (!sourceEntry.exists) throw new Error('生成来源文件不存在:' + source)
155
+ }
156
+ }
157
+ }
158
+ }
159
+ for (const task of summary.tasks || []) for (const fileRecord of task.fileRecords || []) verifyFile(fileRecord)
160
+ if (summary.closure !== null && summary.closure !== undefined) for (const fileRecord of summary.closure.fileRecords || []) verifyFile(fileRecord)
161
+ return { cache }
162
+ }
163
+
164
+ export function verifyProbeEvidenceRef(cwd, reference, sourceState, pathContext, toolLabel = 'save_plan') {
165
+ // 前缀由调用方指定:非空才拼「label: 」;空串表示外层调用方已带工具名,不得重复拼。
166
+ const labelPrefix = typeof toolLabel === 'string' && toolLabel !== '' ? toolLabel + ': ' : ''
167
+ const target = resolveProbeTarget(cwd, reference, pathContext)
168
+ let readTarget
169
+ try {
170
+ readTarget = validateReadTarget(pathContext, target, { expectedType: 'file', purpose: 'probe-evidence' })
171
+ } catch (error) {
172
+ if (errorCodeOf(error) === 'TARGET_MISSING') throw new Error(labelPrefix + '【探查者已核实】证据文件不存在:' + JSON.stringify(reference) + probeRefDecorationHint(reference))
173
+ throw new Error(labelPrefix + '【探查者已核实】证据文件无法读取:' + JSON.stringify(reference) + '(' + String(error.message || error) + ')')
174
+ }
175
+ const key = sourceCacheKey(readTarget.realPath)
176
+ let buffer
177
+ const cached = sourceState.cache.get(key)
178
+ if (cached !== undefined && cached.buffer !== null) buffer = cached.buffer
179
+ else {
180
+ try { buffer = readFileSync(readTarget.realPath) } catch (error) { throw new Error(labelPrefix + '【探查者已核实】证据文件无法读取:' + JSON.stringify(reference) + '(' + String(error.message || error) + ')') }
181
+ sourceState.cache.set(key, { exists: true, path: readTarget.realPath, buffer, text: undefined, lines: undefined })
182
+ }
183
+ const head = buffer.toString('utf8').slice(0, 200)
184
+ if (!head.includes('探查证据报告')) throw new Error(labelPrefix + '【探查者已核实】证据文件非探查者落盘(缺「探查证据报告」标题):' + JSON.stringify(reference))
185
+ }
186
+
187
+ // 方括号包裹的未探查/待确认标记:命中返回匹配文本,未命中返回 null。
188
+ // save_plan 与 edit_plan_draft 共用同一判定与同一时机(合同校验之前),否则草稿工具会
189
+ // 旁路 save_plan 的未探查拒绝,把带标记的方案转正。
190
+ const UNEXPLORED_MARKER_RE = /【[^】]*(?:未探查|待确认)[^】]*】/
191
+ export function unexploredMarkerOf(plan) {
192
+ if (typeof plan !== 'string') return null
193
+ const matched = UNEXPLORED_MARKER_RE.exec(plan)
194
+ return matched === null ? null : matched[0]
195
+ }
@@ -0,0 +1,270 @@
1
+ import { join } from 'node:path'
2
+ import { PROBE_LIMITS, SAVE_PLAN_LIMITS, RANGE_FORMAT_HINT, LINE_FORMAT_HINT, sanitizeTaskName, sessionTagOf, saveArtifactBase, renderSavePlan, renderProbeMarkdown, renderSaveProbe, extractProbeEvidenceRefs } from './save-contract.js'
3
+ import { validateProbe } from './save-probe-validation.js'
4
+ import { resolveWorkspacePath, assertAllowedPath } from './path-policy.js'
5
+ import { validateSavePlanContract } from './save-plan-validation.js'
6
+ import { cwdOf, pathContextOf, unexploredMarkerOf, verifyPlanSources, verifyProbeEvidenceRef } from './save-source-verification.js'
7
+
8
+ export { cwdOf, pathContextOf, unexploredMarkerOf, verifyPlanSources, verifyProbeEvidenceRef }
9
+
10
+ // 两个工具共享会话/目录/base 构造,但各自保留参数校验与提交形状;失败只由本次调用处理。
11
+ function resolveSaveContext(args, exec, savePlanDir, knownCwd, getPathContext) {
12
+ const session = exec !== undefined && exec !== null && exec.agent !== undefined && exec.agent !== null ? exec.agent.session : undefined
13
+ const header = session !== undefined && session !== null && session.header !== undefined && session.header !== null ? session.header : undefined
14
+ const cwd = typeof knownCwd === 'string' ? knownCwd : cwdOf(exec)
15
+ const sessionId = header === undefined ? undefined : header.id
16
+ const sessionTag = sessionTagOf(sessionId)
17
+ const pathContext = cwd === '' ? null : pathContextOf(cwd, getPathContext)
18
+ const directoryTarget = pathContext === null ? null : assertAllowedPath(pathContext, resolveWorkspacePath(pathContext, savePlanDir, { purpose: 'save-artifacts' }))
19
+ const dir = directoryTarget === null ? '' : directoryTarget.path
20
+ const nameSeg = sanitizeTaskName(args !== undefined && args !== null && typeof args === 'object' ? args.taskName : undefined)
21
+ const base = saveArtifactBase(nameSeg, sessionId)
22
+ return { cwd, sessionTag, dir, base, pathContext }
23
+ }
24
+
25
+ // save_plan/save_probe 工具定义只捕获显式目录与持久化依赖,不持有宿主会话状态。
26
+ export function createSaveToolFactories({ savePlanDir, atomicCommit, atomicReplace, getPathContext }) {
27
+ // 草稿与正式工件同形落盘:优先 atomicReplace;未提供时回落 atomicCommit(同一套目录/文件授权)。
28
+ // 两者签名不同(atomicReplace(dir, files, …) / atomicCommit(dir, base, files, …)),回落时按各自形状调用。
29
+ function replaceFiles(dir, base, files, pathContext) {
30
+ if (typeof atomicReplace === 'function') return atomicReplace(dir, files, undefined, { pathContext })
31
+ return atomicCommit(dir, base, files, undefined, { pathContext })
32
+ }
33
+
34
+ // 失败草稿:仅当上下文可用(context 非 null 且 dir 非空串)时写 <dir>/draft 下的 .md_mid,
35
+ // 供 edit_plan_draft 就地修复后重跑校验;上下文不可用时只降级为一句提示,禁止拼接落盘路径。
36
+ // 草稿写失败只降级说明,绝不掩盖调用方原本要抛出的报错。
37
+ function dumpDrafts(context, plan, checklist) {
38
+ if (context === null || context === undefined || typeof context.dir !== 'string' || context.dir === '') {
39
+ return { wrote: false, suffix: '(草稿未写成:未解析到可写的草稿目录,请先修复上述失败原因后重试)' }
40
+ }
41
+ const draftDir = join(context.dir, 'draft')
42
+ const planName = `方案-${context.base}.md_mid`
43
+ const checkName = `验收-${context.base}.md_mid`
44
+ try {
45
+ replaceFiles(draftDir, context.base, [{ name: planName, content: plan }, { name: checkName, content: checklist }], context.pathContext)
46
+ } catch (error) {
47
+ return { wrote: false, suffix: '(草稿未写成:' + (error instanceof Error ? error.message : String(error)) + ')' }
48
+ }
49
+ const relativeOf = (name) => join(savePlanDir, 'draft', name).replace(/\\/g, '/')
50
+ return {
51
+ wrote: true,
52
+ suffix: '\n可用 edit_plan_draft 修改这两份草稿后重试:校验通过会自动转正为正式 .md\n草稿:' + relativeOf(planName) + '、' + relativeOf(checkName),
53
+ }
54
+ }
55
+
56
+ function defineSavePlan() {
57
+ return {
58
+ name: 'save_plan',
59
+ description: '严格写入方案和验收清单,生成供执行者与验收者使用的自包含、受限工件;只校验并双写工件,不启动代理、不执行检查命令或其他任务,成功 structured output 仅含 paths',
60
+ parameters: {
61
+ type: 'object',
62
+ properties: {
63
+ plan: { type: 'string', description: "严格方案全文(至少 200 字符)。结构字段必须列首书写;下列示例路径、旧位置、锚点和动作必须替换为已读取的真实内容。\n卷首:\n- 派遣说明:各组领取范围、依赖交付和自检约定\n任务最小格式:\n[任务1] 标题\n- 主文件:src/example.js\n- 文件操作:修改\n- 修改点:M1\n- 修改位置:L12-34\n- 定位锚点:function example()\n- 修改:具体删改动作\n- 执行组:G1\n- 依赖:无\n- 依赖理由:无\n- 分组理由:无\n- 自检:有限检查动作\n同一文件可重复修改点,但M编号唯一;每点都要位置、锚点和动作。关联文件另起 - 关联文件:src/helper.js,紧接该文件的操作/M点/定位/动作,不能借用主文件的点。位置只接受L12或L12-34,锚点是范围内恰好出现一次的单行原文。路径是裸工作区相对文件路径,不拼行号。\n任务数 1 至 " + SAVE_PLAN_LIMITS.maxTasks + " 个。任务ID从1连续递增。依赖可写无或[任务1]、[任务2];无依赖的依赖理由写无,有依赖须解释真实先后关系。任务及执行组依赖不得成环。不同任务不得重复修改同一文件;关联文件须说明不可安全拆分的分组理由;同组多任务理由相同且非无。可选 - 独占资源:稳定标识,同资源任务必须同组。\n操作例外:新建、删除、生成每文件恰一M点,不填旧位置/锚点,仍须 - 修改:具体动作。新建要求目标不存在并说明内容结构;删除须写整文件删除、理由、引用清理。生成须逐项 - 生成来源:现有工作区文件、恰一 - 生成命令:命令声明,并在修改中说明产物,可另列 - 生成产物:说明;工具不执行命令。真正空文件仍用修改操作,唯一M点的 - 修改位置:空文件 与 - 定位锚点:空文件。\n可选收尾位于全部任务后:[收尾];带文件时先写 - 收尾文件:docs/summary.md,再写该文件的操作/M点/必要定位字段,用 - 收尾动作:具体动作 代替修改。随后必须 - 收尾依赖:[任务1]、[任务2](恰好列全所有数字任务)、- 自检:有限检查;无文件收尾只写收尾依赖、收尾动作、自检。收尾文件不得与数字任务文件重叠。\n若引用探查报告,使用【探查者已核实】并写已核实结论及证据来源裸路径;报告只是事实来源,不能代替本方案内完整步骤和验收规则,不得保留待定设计。" },
64
+ checklist: { type: 'string', description: "严格验收全文(至少 200 字符)。结构字段列首书写;任务ID、文件角色/路径、文件操作及M点集合与方案精确对应。卷首:\n- 验收说明:指定检查分工、取证和判定规则\n任务最小格式:\n[任务1] 标题\n- 主文件:src/example.js\n- 文件操作:修改\n- 对应修改点:M1\n- 验收定位:example修改后的符号、结构或行为条件\n- 期望:该点客观可验证的结果\n- 禁止:明确边界\n- 正式验收:[检查1]\n每个关联文件另起 - 关联文件:路径,随后独立声明操作、对应修改点、验收定位、期望。每个M点恰一验收定位、至少一期望。验收定位不写旧行号或同方案/同上/纯M编号;未来符号保存时不必已经存在。新建/生成可验文件存在及内容结构,删除验文件不存在与引用清理。每个任务恰一条正式验收字段,允许同条引用[检查1]、[检查2]。\n全部数字任务后可写[收尾]:带文件时先 - 收尾文件:路径,再按任务格式写文件操作、对应修改点、验收定位、期望;随后 - 禁止:边界、- 正式验收:[检查1]。无文件收尾仅写期望、禁止、正式验收。\n任务与可选收尾后定义检查,至少一个,ID从1连续递增:\n[检查1] 标题\n- 验收组:R1\n- 取证方式:只读复核\n- 工作目录:.\n- 检查:具体核对动作\n- 验收证据:原始结果及客观通过/失败标准\n取证方式也可写执行取证;工作目录为.或裸工作区相对目录。可选 - 独占资源:稳定标识,同资源检查必须同验收组。所有检查必须被任务/收尾/全局引用;相同取证方式、工作目录、检查动作不得用不同ID重复定义,应复用同一检查。\n最后可写:\n[全局验收]\n- 期望:全局客观结果\n- 禁止:全局边界\n- 正式验收:[检查1]、[检查2]\n两份正文任务集合一致;路径裸写且不拼行号。所有步骤、期望和判定规则必须在本正文中完整,不要求下游从父会话、摘要或其它方案补全。" },
65
+ taskName: { type: 'string', description: `可选任务短名(最多 ${PROBE_LIMITS.maxTaskNameLen} 字;不要传路径)` },
66
+ },
67
+ required: ['plan', 'checklist'],
68
+ additionalProperties: false,
69
+ },
70
+ output: {
71
+ schema: {
72
+ type: 'object',
73
+ properties: { paths: { type: 'array', items: { type: 'string' } } },
74
+ required: ['paths'],
75
+ additionalProperties: false,
76
+ },
77
+ render(_args, value) {
78
+ return renderSavePlan(value)
79
+ },
80
+ },
81
+ timeoutMs: 30000,
82
+ async execute(args, exec) {
83
+ if (args === null || typeof args !== 'object' || typeof args.plan !== 'string' || args.plan.length < 200 || typeof args.checklist !== 'string' || args.checklist.length < 200) {
84
+ throw new Error('save_plan: plan/checklist 参数缺失或内容过短(未收到合法参数;调用参数须为合法 JSON,请检查后重试)')
85
+ }
86
+ const plan = args.plan
87
+ const checklist = args.checklist
88
+ // 执行顺序固定:参数校验 → 取一次 cwd → 容错解析上下文(目录/base/会话标识)→ 未探查标记
89
+ // → 合同校验 → 源核实 → 证据核实 → 用 context 落盘。上下文解析失败只记原错误继续走,
90
+ // 绝不用路径错误替换合同诊断;判空只认 sessionTag(缺 sessionId 时 base 仍非空)。
91
+ const cwd = cwdOf(exec)
92
+ let contextError = null
93
+ let context = null
94
+ if (cwd === '') contextError = new Error('save_plan: 会话缺少工作区路径,无法落盘')
95
+ else {
96
+ try {
97
+ const resolved = resolveSaveContext(args, exec, savePlanDir, cwd, getPathContext)
98
+ if (resolved.sessionTag === '') contextError = new Error('save_plan: 会话缺少有效标识,无法隔离落盘事务')
99
+ else if (resolved.pathContext === null || resolved.pathContext === undefined || resolved.dir === '') contextError = new Error('save_plan: 无法解析允许写入的落盘目录,无法落盘')
100
+ else context = resolved
101
+ } catch (error) {
102
+ contextError = error
103
+ context = null
104
+ }
105
+ }
106
+ // 四处失败出口统一先落草稿再抛错:草稿提示追加在原报错末尾,绝不替换原报错。
107
+ const failWithDraft = (message) => {
108
+ throw new Error(message + dumpDrafts(context, plan, checklist).suffix)
109
+ }
110
+ if (unexploredMarkerOf(plan) !== null) {
111
+ failWithDraft('save_plan: 方案中包含方括号包裹的未探查/待确认标记。请先申请追加预算继续探查,确认所有项均已探查核实后再调用 save_plan')
112
+ }
113
+ const contract = validateSavePlanContract(plan, checklist)
114
+ if (!contract.ok) {
115
+ // 派遣摘要超限只能改写更短的方案,草稿助不了修复:不落草稿、不追加提示。
116
+ if (contract.limitExceeded === true) throw new Error(contract.error)
117
+ failWithDraft(contract.error)
118
+ }
119
+ // 上下文不可用(缺 cwd/会话标识,或目录授权失败)时无法核实真实源与证据:跳过核实,
120
+ // 全部校验通过后一律以已记下的原错误拒绝落盘,不落草稿、不拼接任何落盘路径。
121
+ if (context !== null) {
122
+ const pathContext = context.pathContext
123
+ let sourceState
124
+ try {
125
+ sourceState = verifyPlanSources(contract.summary, pathContext)
126
+ } catch (error) {
127
+ failWithDraft('save_plan: 源核实失败:' + (error instanceof Error ? error.message : String(error)))
128
+ }
129
+ // 【探查者已核实】证据校验:方案中标注引用的证据文件必须真实存在、且为探查者
130
+ // save_probe 落盘的证据报告(标题含「探查证据报告」),杜绝编造证据引用。
131
+ try {
132
+ for (const ref of extractProbeEvidenceRefs(plan)) verifyProbeEvidenceRef(cwd, ref, sourceState, pathContext)
133
+ } catch (error) {
134
+ failWithDraft(error instanceof Error ? error.message : String(error))
135
+ }
136
+ }
137
+ // T3:base 内嵌调用方会话标识段(主会话与规划子代理同秒落盘不再撞名)。
138
+ if (context === null) throw contextError !== null && contextError !== undefined ? contextError : new Error('save_plan: 会话缺少有效标识,无法隔离落盘事务')
139
+ const { dir, base } = context
140
+ const planFile = join(dir, `方案-${base}.md`)
141
+ const checkFile = join(dir, `验收-${base}.md`)
142
+ try {
143
+ atomicCommit(dir, base, [
144
+ { name: `方案-${base}.md`, content: plan },
145
+ { name: `验收-${base}.md`, content: checklist },
146
+ ], undefined, { pathContext: context.pathContext })
147
+ } catch (error) {
148
+ throw new Error(`save_plan: 落盘失败:${error instanceof Error ? error.message : String(error)}`)
149
+ }
150
+ return { paths: [planFile, checkFile] }
151
+ },
152
+ }
153
+ }
154
+
155
+ function defineSaveProbe() {
156
+ return {
157
+ name: 'save_probe',
158
+ description: '写入只读探查结果。fileMap、focusAreas、exclusions、background 四个数组必填,按 JSON 序列化计总量最多 20000 字;evidence 可选,非空时正文按证据报告形态渲染(标题『探查证据报告』+证据节),否则渲染线索形态;落盘文件名统一为『线索-』前缀。字段格式和单项上限见参数说明;返回文件路径。',
159
+ parameters: {
160
+ type: 'object',
161
+ properties: {
162
+ fileMap: {
163
+ type: 'array',
164
+ description: `相关文件列表(最多 ${PROBE_LIMITS.maxEntries.fileMap} 项)`,
165
+ items: {
166
+ type: 'object',
167
+ properties: {
168
+ path: { type: 'string', description: `现有文件路径(相对路径按工作区解析,最多 ${PROBE_LIMITS.maxPathLen} 字)` },
169
+ relation: { type: 'string', description: `文件与任务的关系(最多 ${PROBE_LIMITS.maxRelationLen} 字)` },
170
+ },
171
+ required: ['path', 'relation'],
172
+ additionalProperties: false,
173
+ },
174
+ },
175
+ focusAreas: {
176
+ type: 'array',
177
+ description: `重点区域列表(最多 ${PROBE_LIMITS.maxEntries.focusAreas} 项)`,
178
+ items: {
179
+ type: 'object',
180
+ properties: {
181
+ path: { type: 'string', description: `现有文件路径(相对路径按工作区解析,最多 ${PROBE_LIMITS.maxPathLen} 字)` },
182
+ range: { type: 'string', description: `可选行号范围(最多 ${PROBE_LIMITS.maxRangeLen} 字)${RANGE_FORMAT_HINT}` },
183
+ note: { type: 'string', description: `重点和补查方向(最多 ${PROBE_LIMITS.maxNoteLen} 字)` },
184
+ },
185
+ required: ['path', 'note'],
186
+ additionalProperties: false,
187
+ },
188
+ },
189
+ exclusions: {
190
+ type: 'array',
191
+ description: `排除项列表(最多 ${PROBE_LIMITS.maxEntries.exclusions} 项;scope 可为概念边界,无须对应现有路径)`,
192
+ items: {
193
+ type: 'object',
194
+ properties: {
195
+ scope: { type: 'string', description: '可选排除范围' },
196
+ note: { type: 'string', description: `排除原因(最多 ${PROBE_LIMITS.maxNoteLen} 字)` },
197
+ },
198
+ required: ['note'],
199
+ additionalProperties: false,
200
+ },
201
+ },
202
+ background: {
203
+ type: 'array',
204
+ description: `背景与意图列表(最多 ${PROBE_LIMITS.maxEntries.background} 项)`,
205
+ items: {
206
+ type: 'object',
207
+ properties: {
208
+ topic: { type: 'string', description: `背景主题(最多 ${PROBE_LIMITS.maxTopicLen} 字)` },
209
+ detail: { type: 'string', description: `背景或用户意图(最多 ${PROBE_LIMITS.maxDetailLen} 字)` },
210
+ },
211
+ required: ['topic', 'detail'],
212
+ additionalProperties: false,
213
+ },
214
+ },
215
+ evidence: {
216
+ type: 'array',
217
+ description: `可选证据列表(最多 ${PROBE_LIMITS.maxEvidenceEntries} 项,按 JSON 序列化计总量最多 ${PROBE_LIMITS.maxEvidenceTotalChars} 字);非空时正文按证据报告形态渲染;落盘文件名仍为『线索-』前缀。每项 path 必须存在,并至少填写 line、value、text 之一。`,
218
+ items: {
219
+ type: 'object',
220
+ properties: {
221
+ path: { type: 'string', description: `现有被核实文件路径(相对路径按工作区解析,最多 ${PROBE_LIMITS.maxPathLen} 字)` },
222
+ line: { type: 'string', description: `可选行号(最多 ${PROBE_LIMITS.maxEvidenceLineLen} 字);${LINE_FORMAT_HINT}` },
223
+ value: { type: 'string', description: `可选核实值(最多 ${PROBE_LIMITS.maxEvidenceValueLen} 字)` },
224
+ text: { type: 'string', description: `可选原文摘录(最多 ${PROBE_LIMITS.maxEvidenceTextLen} 字)` },
225
+ note: { type: 'string', description: `可选备注(最多 ${PROBE_LIMITS.maxEvidenceNoteLen} 字)` },
226
+ },
227
+ required: ['path'],
228
+ additionalProperties: false,
229
+ },
230
+ },
231
+ taskName: { type: 'string', description: `可选任务短名(最多 ${PROBE_LIMITS.maxTaskNameLen} 字;不要传路径)` },
232
+ },
233
+ required: ['fileMap', 'focusAreas', 'exclusions', 'background'],
234
+ additionalProperties: false,
235
+ },
236
+ output: {
237
+ schema: {
238
+ type: 'object',
239
+ properties: { path: { type: 'string' } },
240
+ required: ['path'],
241
+ additionalProperties: false,
242
+ },
243
+ render(args, value) {
244
+ return renderSaveProbe(value, Array.isArray(args.evidence) && args.evidence.length > 0)
245
+ },
246
+ },
247
+ timeoutMs: 30000,
248
+ async execute(args, exec) {
249
+ // 先仅读取 cwd 并完成全部参数/路径校验,避免非法调用消耗工件 base 序号。
250
+ const probeCwd = cwdOf(exec)
251
+ const probePathContext = probeCwd === '' ? undefined : pathContextOf(probeCwd, getPathContext)
252
+ const invalid = validateProbe(args, probeCwd, probePathContext)
253
+ if (invalid !== null) throw new Error(invalid)
254
+ const context = resolveSaveContext(args, exec, savePlanDir, probeCwd, getPathContext)
255
+ const { cwd, sessionTag, dir, base } = context
256
+ if (cwd === '') throw new Error('save_probe: 会话缺少工作区路径,无法落盘')
257
+ if (sessionTag === '') throw new Error('save_probe: 会话缺少有效标识,无法隔离落盘事务')
258
+ const fileName = `线索-${base}.md`
259
+ try {
260
+ atomicCommit(dir, base, [{ name: fileName, content: renderProbeMarkdown(args) }], undefined, { pathContext: context.pathContext })
261
+ } catch (error) {
262
+ throw new Error(`save_probe: 落盘失败:${error instanceof Error ? error.message : String(error)}`)
263
+ }
264
+ return { path: join(dir, fileName) }
265
+ },
266
+ }
267
+ }
268
+
269
+ return { defineSavePlan, defineSaveProbe }
270
+ }