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,464 @@
1
+ import * as fs from 'node:fs'
2
+ import * as path from 'node:path'
3
+
4
+ const nativePath = process.platform === 'win32' ? path.win32 : path.posix
5
+ const isWindows = process.platform === 'win32'
6
+ const OTHER = 'other'
7
+ const KINDS = new Set(['workspace', 'host'])
8
+ const CAPABILITY_TYPES = new Set(['file', 'directory'])
9
+ const realpathSync = typeof fs.realpathSync.native === 'function' ? fs.realpathSync.native : fs.realpathSync
10
+ const INTERNAL_PURPOSE = Symbol('path-policy-purpose')
11
+ const targetMetadata = new WeakMap()
12
+
13
+ function policyError(code, message, details = {}) {
14
+ const error = new TypeError('[path-policy:' + code + '] ' + message)
15
+ error.code = code
16
+ error.details = Object.freeze({ ...details })
17
+ return error
18
+ }
19
+
20
+ function isObject(value) {
21
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
22
+ }
23
+
24
+ function isOther(value) {
25
+ return typeof value === 'string' && value.toLowerCase() === OTHER
26
+ }
27
+
28
+ function rejectOther(value, label) {
29
+ if (!isObject(value)) return
30
+ for (const key of ['kind', 'scope', 'source', 'category', 'purpose']) {
31
+ if (isOther(value[key])) throw policyError('OTHER_REJECTED', label + '.' + key + ' 使用保留类别 Other')
32
+ }
33
+ }
34
+
35
+ function rejectOtherOptions(options, label) {
36
+ rejectOther(options, label)
37
+ if (isObject(options) && isOther(options.capability)) {
38
+ throw policyError('OTHER_REJECTED', label + '.capability 使用保留类别 Other')
39
+ }
40
+ }
41
+
42
+ function isFullyQualifiedAbsolute(value) {
43
+ if (isWindows) return /^[A-Za-z]:[\\/]/.test(value) || /^\\\\/.test(value)
44
+ return value.startsWith('/')
45
+ }
46
+
47
+ function rejectVariable(value, label) {
48
+ if (/(?:%[A-Za-z_][A-Za-z0-9_]*%)/.test(value)) {
49
+ throw policyError('VARIABLE_PATH', label + ' 拒绝环境变量字面量')
50
+ }
51
+ if (/(?:^|[\\/])\$(?:\{[A-Za-z_][A-Za-z0-9_]*\}|[A-Za-z_][A-Za-z0-9_]*)/.test(value)) {
52
+ throw policyError('VARIABLE_PATH', label + ' 拒绝环境变量字面量')
53
+ }
54
+ if (/(?:^|[\\/])~(?:[\\/]|$)/.test(value) || value.startsWith('~')) {
55
+ throw policyError('VARIABLE_PATH', label + ' 拒绝家目录缩写')
56
+ }
57
+ }
58
+
59
+ function lexicalPath(value, label) {
60
+ if (typeof value !== 'string') throw policyError('PATH_TYPE', label + ' 必须是字符串')
61
+ if (value.length === 0 || value.trim() === '') throw policyError('EMPTY_PATH', label + ' 不能为空')
62
+ if (value.includes(String.fromCharCode(0))) throw policyError('NUL_PATH', label + ' 含 NUL')
63
+ rejectVariable(value, label)
64
+ const driveRelative = /^[A-Za-z]:[^\\/]/.test(value)
65
+ if (driveRelative) throw policyError('DRIVE_RELATIVE', label + ' 拒绝 drive-relative 路径')
66
+ const protocol = /^[A-Za-z][A-Za-z0-9+.-]*:/.test(value)
67
+ const driveAbsolute = /^[A-Za-z]:[\\/]/.test(value)
68
+ if (protocol && !driveAbsolute) throw policyError('INVALID_URI', label + ' 拒绝URI/协议路径')
69
+ if (nativePath.isAbsolute(value) && !isFullyQualifiedAbsolute(value)) {
70
+ throw policyError('AMBIGUOUS_ABSOLUTE', label + ' 不是明确的绝对路径')
71
+ }
72
+ return value
73
+ }
74
+
75
+ function rootPath(value, label) {
76
+ if (value === undefined || value === null) throw policyError('ROOT_REQUIRED', label + ' 必须明确提供')
77
+ const lexical = lexicalPath(value, label)
78
+ if (!isFullyQualifiedAbsolute(lexical) || !nativePath.isAbsolute(lexical)) {
79
+ throw policyError('ROOT_REQUIRED', label + ' 必须是明确的绝对根')
80
+ }
81
+ return nativePath.normalize(lexical)
82
+ }
83
+
84
+ function keyOf(value) {
85
+ const normalized = nativePath.normalize(value)
86
+ return isWindows ? normalized.toLowerCase() : normalized
87
+ }
88
+
89
+ function samePath(left, right) {
90
+ return keyOf(left) === keyOf(right)
91
+ }
92
+
93
+ function isWithin(root, candidate) {
94
+ const rootKey = keyOf(root)
95
+ const candidateKey = keyOf(candidate)
96
+ if (rootKey === candidateKey) return true
97
+ const relative = nativePath.relative(rootKey, candidateKey)
98
+ return relative !== '' && relative !== '..' && !relative.startsWith('..' + nativePath.sep) && !nativePath.isAbsolute(relative)
99
+ }
100
+
101
+ function assertLexicalWithin(root, candidate, label) {
102
+ if (!isWithin(root, candidate)) {
103
+ throw policyError('ROOT_ESCAPE', label + ' 超出授权根', { root, candidate })
104
+ }
105
+ }
106
+
107
+ function readOnlyCapabilityForLogicalPath(context, candidate) {
108
+ for (const descriptor of Object.values(context.hostCapabilities)) {
109
+ if (descriptor.access !== 'read') continue
110
+ const protectedPath = descriptor.path
111
+ if (descriptor.type === 'file' ? samePath(protectedPath, candidate) : isWithin(protectedPath, candidate)) return descriptor
112
+ }
113
+ return null
114
+ }
115
+
116
+ function readOnlyCapabilityForRealPath(context, candidate) {
117
+ if (candidate === null || candidate === undefined) return null
118
+ for (const descriptor of Object.values(context.hostCapabilities)) {
119
+ if (descriptor.access !== 'read') continue
120
+ let protectedRealPath
121
+ try { protectedRealPath = realpathSync(descriptor.path) } catch { continue }
122
+ if (descriptor.type === 'file' ? samePath(protectedRealPath, candidate) : isWithin(protectedRealPath, candidate)) return descriptor
123
+ }
124
+ return null
125
+ }
126
+
127
+ function rejectReadOnlyCapability(descriptor) {
128
+ if (descriptor !== null) throw policyError('HOST_RESOURCE_READONLY', 'Host代码/资源能力只读', { capability: descriptor.name })
129
+ }
130
+
131
+ function purposeOf(options, fallback) {
132
+ const purpose = options === undefined || options.purpose === undefined ? fallback : options.purpose
133
+ if (typeof purpose !== 'string' || purpose.trim() === '') throw policyError('PURPOSE_REQUIRED', '用途必须是非空字符串')
134
+ if (isOther(purpose)) throw policyError('OTHER_REJECTED', '用途使用保留类别 Other')
135
+ if (purpose.includes(String.fromCharCode(0))) throw policyError('PURPOSE_INVALID', '用途含 NUL')
136
+ return purpose
137
+ }
138
+
139
+ function capabilityName(value) {
140
+ if (value === undefined || value === null) return null
141
+ if (typeof value !== 'string' || value.trim() === '') throw policyError('CAPABILITY_INVALID', 'Host capability 必须是非空名称')
142
+ if (isOther(value)) throw policyError('OTHER_REJECTED', 'Host capability 使用保留类别 Other')
143
+ if (value.includes(String.fromCharCode(0))) throw policyError('CAPABILITY_INVALID', 'Host capability 含 NUL')
144
+ return value
145
+ }
146
+
147
+ function normalizeCapabilities(value) {
148
+ if (value === undefined || value === null) return Object.freeze(Object.create(null))
149
+ const entries = Array.isArray(value)
150
+ ? value.map((item) => {
151
+ if (!isObject(item) || typeof item.name !== 'string') throw policyError('CAPABILITY_INVALID', 'Host capability 列表项必须含 name')
152
+ return [item.name, item]
153
+ })
154
+ : Object.entries(value)
155
+ const out = Object.create(null)
156
+ for (const [name, raw] of entries) {
157
+ capabilityName(name)
158
+ if (Object.prototype.hasOwnProperty.call(out, name)) throw policyError('CAPABILITY_DUPLICATE', 'Host capability 重复: ' + name)
159
+ const descriptor = typeof raw === 'string' ? { path: raw, type: 'file' } : raw
160
+ if (!isObject(descriptor)) throw policyError('CAPABILITY_INVALID', 'Host capability ' + name + ' 必须是描述对象')
161
+ const type = descriptor.type === undefined ? 'file' : descriptor.type
162
+ if (!CAPABILITY_TYPES.has(type)) throw policyError('CAPABILITY_INVALID', 'Host capability ' + name + ' type 无效')
163
+ const access = descriptor.access === undefined ? 'read' : descriptor.access
164
+ if (access !== 'read' && access !== 'write') throw policyError('CAPABILITY_INVALID', 'Host capability ' + name + ' access 无效')
165
+ const capabilityPath = rootPath(descriptor.path, 'hostCapabilities.' + name + '.path')
166
+ const purpose = descriptor.purpose === undefined ? null : purposeOf(descriptor, name)
167
+ out[name] = Object.freeze({ name, path: capabilityPath, type, purpose, access })
168
+ }
169
+ return Object.freeze(out)
170
+ }
171
+
172
+ export function createPathContext(options = {}) {
173
+ if (!isObject(options)) throw policyError('CONTEXT_TYPE', 'createPathContext 参数必须是对象')
174
+ rejectOtherOptions(options, 'context')
175
+ const workspaceRoot = options.workspaceRoot === undefined || options.workspaceRoot === null
176
+ ? null
177
+ : rootPath(options.workspaceRoot, 'workspaceRoot')
178
+ const hostDataRoot = options.hostDataRoot === undefined || options.hostDataRoot === null
179
+ ? null
180
+ : rootPath(options.hostDataRoot, 'hostDataRoot')
181
+ const hostCapabilities = normalizeCapabilities(options.hostCapabilities)
182
+ if (workspaceRoot === null && hostDataRoot === null && Object.keys(hostCapabilities).length === 0) {
183
+ throw policyError('ROOT_REQUIRED', '至少需要明确的 workspaceRoot、hostDataRoot 或 Host capability')
184
+ }
185
+ return Object.freeze({
186
+ workspaceRoot,
187
+ hostDataRoot,
188
+ hostCapabilities,
189
+ })
190
+ }
191
+
192
+ function ensureContext(context) {
193
+ if (!isObject(context)) throw policyError('CONTEXT_TYPE', '路径上下文必须是 createPathContext 返回的对象')
194
+ if (context.workspaceRoot !== null && context.workspaceRoot !== undefined) rootPath(context.workspaceRoot, 'context.workspaceRoot')
195
+ if (context.hostDataRoot !== null && context.hostDataRoot !== undefined) rootPath(context.hostDataRoot, 'context.hostDataRoot')
196
+ if (!isObject(context.hostCapabilities)) throw policyError('CAPABILITY_INVALID', '上下文 hostCapabilities 无效')
197
+ if (context.workspaceRoot === null && context.hostDataRoot === null && Object.keys(context.hostCapabilities).length === 0) {
198
+ throw policyError('ROOT_REQUIRED', '至少需要明确的 workspaceRoot、hostDataRoot 或 Host capability')
199
+ }
200
+ return context
201
+ }
202
+
203
+ function capabilityOf(context, name) {
204
+ const capability = capabilityName(name)
205
+ if (capability === null) return null
206
+ const descriptor = context.hostCapabilities[capability]
207
+ if (descriptor === undefined) throw policyError('CAPABILITY_UNKNOWN', '未注册的 Host capability: ' + capability)
208
+ return descriptor
209
+ }
210
+
211
+ function relativeInput(base, value, label) {
212
+ const lexical = lexicalPath(value, label)
213
+ const absolute = isFullyQualifiedAbsolute(lexical)
214
+ if (absolute) return nativePath.normalize(lexical)
215
+ if (nativePath.isAbsolute(lexical)) throw policyError('AMBIGUOUS_ABSOLUTE', label + ' 不是明确的绝对路径')
216
+ return nativePath.normalize(nativePath.resolve(base, lexical))
217
+ }
218
+
219
+ function makeTarget(context, kind, input, options = {}) {
220
+ rejectOtherOptions(options, 'path options')
221
+ if (!KINDS.has(kind)) throw policyError('KIND_INVALID', '路径类别必须是 workspace 或 host')
222
+ const capability = kind === 'host' ? capabilityOf(context, options.capability) : null
223
+ if (kind === 'workspace' && options.capability !== undefined && options.capability !== null) {
224
+ throw policyError('CAPABILITY_INVALID', 'workspace 路径不能使用 Host capability')
225
+ }
226
+ let root
227
+ let exactPath = null
228
+ if (capability !== null) {
229
+ root = capability.type === 'file' ? nativePath.dirname(capability.path) : capability.path
230
+ exactPath = capability.type === 'file' ? capability.path : null
231
+ if (input === undefined || input === null || input === '') {
232
+ input = capability.path
233
+ }
234
+ } else {
235
+ root = kind === 'workspace' ? context.workspaceRoot : context.hostDataRoot
236
+ if (root === null || root === undefined) {
237
+ throw policyError('ROOT_REQUIRED', kind === 'workspace' ? '缺少明确的 workspaceRoot' : '缺少明确的 hostDataRoot')
238
+ }
239
+ if (input === undefined || input === null) throw policyError('PATH_REQUIRED', '路径值不能为空')
240
+ }
241
+ const purposeExplicit = options[INTERNAL_PURPOSE] === undefined
242
+ ? options.purpose !== undefined && typeof options.purpose === 'string' && options.purpose.trim() !== ''
243
+ : options[INTERNAL_PURPOSE] === true
244
+ const purpose = purposeOf(options, capability === null || capability.purpose === null ? kind : capability.purpose)
245
+ if (capability !== null && capability.purpose !== null && purpose !== capability.purpose) {
246
+ throw policyError('PURPOSE_MISMATCH', '用途与 Host capability 不匹配', { expected: capability.purpose, actual: purpose })
247
+ }
248
+ const candidate = relativeInput(root, input, kind + ' path')
249
+ assertLexicalWithin(root, candidate, kind + ' path')
250
+ if (exactPath !== null && !samePath(candidate, exactPath)) {
251
+ throw policyError('CAPABILITY_ESCAPE', '精确 Host 文件 capability 不允许扩展为目录')
252
+ }
253
+ const target = {
254
+ kind,
255
+ scope: kind,
256
+ path: candidate,
257
+ root,
258
+ relativePath: nativePath.relative(root, candidate),
259
+ purpose,
260
+ purposeExplicit,
261
+ access: capability === null ? (kind === 'host' ? 'data' : 'write') : capability.access,
262
+ capability: capability === null ? null : capability.name,
263
+ exactPath,
264
+ }
265
+ targetMetadata.set(target, { purposeExplicit })
266
+ return Object.freeze(target)
267
+ }
268
+
269
+ export function resolveWorkspacePath(context, value, options = {}) {
270
+ ensureContext(context)
271
+ rejectOtherOptions(options, 'workspace options')
272
+ return makeTarget(context, 'workspace', value, options)
273
+ }
274
+
275
+ export function resolveHostPath(context, value, options = {}) {
276
+ ensureContext(context)
277
+ rejectOtherOptions(options, 'host options')
278
+ return makeTarget(context, 'host', value, options)
279
+ }
280
+
281
+ function targetInput(context, candidate, options = {}) {
282
+ rejectOther(candidate, 'target')
283
+ rejectOtherOptions(options, 'target options')
284
+ let kind = options.kind
285
+ let value = candidate
286
+ let capability = options.capability
287
+ let purpose = options.purpose
288
+ let purposeExplicit = typeof purpose === 'string' && purpose.trim() !== ''
289
+ let candidateMetadata = null
290
+ if (isObject(candidate)) {
291
+ candidateMetadata = targetMetadata.get(candidate) || null
292
+ kind = candidate.kind === undefined ? kind : candidate.kind
293
+ value = candidate.path
294
+ capability = candidate.capability === undefined ? capability : candidate.capability
295
+ purpose = candidate.purpose === undefined ? purpose : candidate.purpose
296
+ if (candidateMetadata !== null) purposeExplicit = candidateMetadata.purposeExplicit === true
297
+ else purposeExplicit = typeof purpose === 'string' && purpose.trim() !== ''
298
+ }
299
+ if (typeof kind !== 'string' || !KINDS.has(kind)) throw policyError('KIND_REQUIRED', '必须显式指定 workspace 或 host 类别')
300
+ const pathOptions = { ...options, capability, purpose, [INTERNAL_PURPOSE]: purposeExplicit, kind: undefined }
301
+ delete pathOptions.kind
302
+ return kind === 'workspace'
303
+ ? resolveWorkspacePath(context, value, pathOptions)
304
+ : resolveHostPath(context, value, pathOptions)
305
+ }
306
+
307
+ export function assertAllowedPath(context, candidate, options = {}) {
308
+ ensureContext(context)
309
+ const target = targetInput(context, candidate, options)
310
+ const allowed = Object.freeze({ ...target, allowed: true })
311
+ const metadata = targetMetadata.get(target)
312
+ if (metadata !== undefined) targetMetadata.set(allowed, metadata)
313
+ return allowed
314
+ }
315
+
316
+ function isMissing(error) {
317
+ return error !== null && typeof error === 'object' && (error.code === 'ENOENT' || error.code === 'ENOTDIR')
318
+ }
319
+
320
+ function sameOrChildReal(root, candidate, label) {
321
+ if (!isWithin(root, candidate)) throw policyError('REALPATH_ESCAPE', label + ' 的真实路径越界', { rootRealPath: root, realPath: candidate })
322
+ }
323
+
324
+ function physicalRoot(target, operation) {
325
+ let rootRealPath
326
+ try {
327
+ rootRealPath = realpathSync(target.root)
328
+ } catch (error) {
329
+ throw policyError('ROOT_UNAVAILABLE', operation + ' 授权根不可解析', { root: target.root, cause: error.code || String(error) })
330
+ }
331
+ let rootStat
332
+ try {
333
+ rootStat = fs.statSync(rootRealPath)
334
+ } catch (error) {
335
+ throw policyError('ROOT_UNAVAILABLE', operation + ' 授权根不可读取', { root: target.root, cause: error.code || String(error) })
336
+ }
337
+ if (!rootStat.isDirectory()) throw policyError('ROOT_NOT_DIRECTORY', operation + ' 授权根不是目录', { root: target.root })
338
+ return rootRealPath
339
+ }
340
+
341
+ function inspectChain(target, rootRealPath, operation, rejectLinks) {
342
+ const rootPath = nativePath.normalize(target.root)
343
+ const targetPath = nativePath.normalize(target.path)
344
+ const targetParentPath = nativePath.dirname(targetPath)
345
+ let cursor = targetPath
346
+ let candidateStat = null
347
+ let candidateRealPath = null
348
+ let parentRealPath = null
349
+ while (true) {
350
+ let stat
351
+ try {
352
+ stat = fs.lstatSync(cursor)
353
+ } catch (error) {
354
+ if (!isMissing(error)) throw policyError('PATH_PROBE_FAILED', operation + ' 路径探查失败', { path: cursor, cause: error.code || String(error) })
355
+ if (error.code === 'ENOTDIR') throw policyError('PARENT_NOT_DIRECTORY', operation + ' 父路径不是目录', { path: cursor })
356
+ const parent = nativePath.dirname(cursor)
357
+ if (samePath(parent, cursor)) throw policyError('ROOT_CHAIN_MISSING', operation + ' 找不到授权根父链')
358
+ cursor = parent
359
+ continue
360
+ }
361
+ let realPath
362
+ try {
363
+ realPath = realpathSync(cursor)
364
+ } catch (error) {
365
+ throw policyError('REALPATH_FAILED', operation + ' 无法验证真实路径', { path: cursor, cause: error.code || String(error) })
366
+ }
367
+ sameOrChildReal(rootRealPath, realPath, operation)
368
+ const isLink = typeof stat.isSymbolicLink === 'function' && stat.isSymbolicLink()
369
+ if (rejectLinks && isLink && !samePath(cursor, rootPath)) {
370
+ throw policyError('LINK_WRITE_REJECTED', operation + ' 不跟随链接写入', { path: cursor })
371
+ }
372
+ if (samePath(cursor, targetPath)) {
373
+ candidateStat = stat
374
+ candidateRealPath = realPath
375
+ }
376
+ if (samePath(cursor, targetParentPath) || (samePath(cursor, targetPath) && samePath(cursor, rootPath))) {
377
+ parentRealPath = realPath
378
+ }
379
+ if (parentRealPath === null && !samePath(cursor, targetPath)) parentRealPath = realPath
380
+ if (samePath(cursor, rootPath)) break
381
+ const parent = nativePath.dirname(cursor)
382
+ if (samePath(parent, cursor)) throw policyError('ROOT_CHAIN_MISSING', operation + ' 未到达授权根')
383
+ cursor = parent
384
+ }
385
+ return { candidateStat, candidateRealPath, parentRealPath }
386
+ }
387
+
388
+ function expectedType(options, fallback) {
389
+ const value = options.expectedType === undefined ? fallback : options.expectedType
390
+ if (!['file', 'directory', 'any'].includes(value)) throw policyError('TYPE_INVALID', 'expectedType 必须是 file、directory 或 any')
391
+ return value
392
+ }
393
+
394
+ function checkType(stat, expected, operation, targetPath) {
395
+ if (expected === 'any') return
396
+ if (expected === 'file' && !stat.isFile()) throw policyError('TARGET_TYPE', operation + ' 目标不是文件', { path: targetPath })
397
+ if (expected === 'directory' && !stat.isDirectory()) throw policyError('TARGET_TYPE', operation + ' 目标不是目录', { path: targetPath })
398
+ }
399
+
400
+ export function validateReadTarget(context, candidate, options = {}) {
401
+ ensureContext(context)
402
+ rejectOther(candidate, 'read target')
403
+ rejectOtherOptions(options, 'read options')
404
+ const target = assertAllowedPath(context, candidate, options)
405
+ const expected = expectedType(options, 'file')
406
+ const rootRealPath = physicalRoot(target, 'read')
407
+ const chain = inspectChain(target, rootRealPath, 'read', false)
408
+ if (chain.candidateStat === null) throw policyError('TARGET_MISSING', 'read 目标不存在', { path: target.path })
409
+ let actualStat
410
+ try {
411
+ actualStat = fs.statSync(target.path)
412
+ } catch (error) {
413
+ throw policyError('TARGET_UNREADABLE', 'read 目标不可读取', { path: target.path, cause: error.code || String(error) })
414
+ }
415
+ checkType(actualStat, expected, 'read', target.path)
416
+ const readTarget = Object.freeze({
417
+ ...target,
418
+ operation: 'read',
419
+ rootRealPath,
420
+ realPath: chain.candidateRealPath,
421
+ parentRealPath: chain.parentRealPath,
422
+ exists: true,
423
+ isFile: actualStat.isFile(),
424
+ isDirectory: actualStat.isDirectory(),
425
+ })
426
+ const metadata = targetMetadata.get(target)
427
+ if (metadata !== undefined) targetMetadata.set(readTarget, metadata)
428
+ return readTarget
429
+ }
430
+
431
+ export function prepareWriteTarget(context, candidate, options = {}) {
432
+ ensureContext(context)
433
+ rejectOther(candidate, 'write target')
434
+ rejectOtherOptions(options, 'write options')
435
+ const target = assertAllowedPath(context, candidate, options)
436
+ rejectReadOnlyCapability(readOnlyCapabilityForLogicalPath(context, target.path))
437
+ const expected = expectedType(options, 'file')
438
+ if (target.kind === 'host') {
439
+ if (!target.purposeExplicit) throw policyError('PURPOSE_REQUIRED', 'Host写入必须显式提供用途')
440
+ if (target.capability !== null && target.access !== 'write') throw policyError('HOST_RESOURCE_READONLY', 'Host代码/资源能力只读')
441
+ }
442
+ const rootRealPath = physicalRoot(target, 'write')
443
+ const chain = inspectChain(target, rootRealPath, 'write', true)
444
+ rejectReadOnlyCapability(readOnlyCapabilityForRealPath(context, chain.candidateRealPath))
445
+ rejectReadOnlyCapability(readOnlyCapabilityForRealPath(context, chain.parentRealPath))
446
+ const exists = chain.candidateStat !== null
447
+ if (exists) {
448
+ if (chain.candidateStat.isSymbolicLink()) throw policyError('LINK_WRITE_REJECTED', 'write 目标不能是链接', { path: target.path })
449
+ checkType(chain.candidateStat, expected, 'write', target.path)
450
+ } else if (expected === 'directory') {
451
+ throw policyError('TARGET_MISSING', 'write 目录目标不存在,解析函数不会隐式建目录', { path: target.path })
452
+ }
453
+ return Object.freeze({
454
+ ...target,
455
+ operation: 'write',
456
+ rootRealPath,
457
+ realPath: chain.candidateRealPath,
458
+ parentRealPath: chain.parentRealPath,
459
+ parentPath: nativePath.dirname(target.path),
460
+ exists,
461
+ isFile: exists && chain.candidateStat.isFile(),
462
+ isDirectory: exists && chain.candidateStat.isDirectory(),
463
+ })
464
+ }