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,108 @@
1
+ // gateWords 元数据、整组严格校验与每次 apply 的运行时词表派生。
2
+ // YAML 的 config.gateWords 是唯一人工值源;本模块只保存字段规格与校验规则,不保存默认词值,
3
+ // 不读文件或环境变量;非法整组以 extra-plan: config.gateWords 前缀同步抛错。
4
+ // 有效结果冻结,并由显式参数传入各 helper;每次 apply 独立派生,避免模块全局状态串扰。
5
+ // 推荐后缀仅按文档白名单归一,匹配仍使用当前词的精确值。
6
+ const RECOMMENDED_SUFFIX = /\s*(?:\((?:recommended|推荐)\)|((?:recommended|推荐)))\s*$/i
7
+
8
+ /** 6 个闸门词字段与对应 prompt variable 名(仅元数据,不含任何词值)。 */
9
+ export const GATE_WORD_FIELDS = Object.freeze([
10
+ Object.freeze({ field: 'routeMain', variable: 'extra_plan_route_main' }),
11
+ Object.freeze({ field: 'routeExecutor', variable: 'extra_plan_route_executor' }),
12
+ Object.freeze({ field: 'routePlan', variable: 'extra_plan_route_plan' }),
13
+ Object.freeze({ field: 'routeDisagree', variable: 'extra_plan_route_disagree' }),
14
+ Object.freeze({ field: 'purposeRefine', variable: 'extra_plan_purpose_refine' }),
15
+ Object.freeze({ field: 'purposeRedo', variable: 'extra_plan_purpose_redo' }),
16
+ ])
17
+
18
+ /** 6 个字段名(顺序即 YAML 中的集中排列顺序)。 */
19
+ export const GATE_WORD_FIELD_NAMES = Object.freeze(GATE_WORD_FIELDS.map((item) => item.field))
20
+
21
+ /** 整组 locator:源模板(资产)内 id=extra-plan 行的 config.gateWords(供 resolveSetting 直接使用)。 */
22
+ export const GATE_WORDS_GROUP_DEFINITION = Object.freeze({
23
+ id: 'extra-plan',
24
+ rowId: 'extra-plan',
25
+ path: 'config.gateWords',
26
+ keys: GATE_WORD_FIELD_NAMES,
27
+ sourceLocator: Object.freeze({ rowId: 'extra-plan', path: 'config.gateWords' }),
28
+ })
29
+
30
+ function fail(detail) {
31
+ throw new Error('extra-plan: config.gateWords ' + detail)
32
+ }
33
+
34
+ /** 推荐后缀归一:把选项标签末尾的推荐标记剥掉,仅用于判定是否使用保留后缀,不做子串匹配。 */
35
+ export function normalizeGateLabel(label) {
36
+ return String(label).trim().replace(RECOMMENDED_SUFFIX, '').trim()
37
+ }
38
+
39
+ /**
40
+ * 整组严格校验:合法 → 返回冻结副本;任何一条不合法 → 抛 Error(消息以
41
+ * 'extra-plan: config.gateWords' 开头并指出字段与原因)。禁止部分接受。
42
+ * 本函数只判定单次入参(apply 的 definition 行、资产模板、资产 definition);
43
+ * 持久化 settings 值缺失/非法时由 preset-sync 回落当前资产默认并补齐,不在此放宽。
44
+ */
45
+ export function validateGateWords(raw) {
46
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
47
+ fail('必须是含恰好 6 个字段的普通对象(当前 ' + (raw === null ? 'null' : Array.isArray(raw) ? 'array' : typeof raw) + ')')
48
+ }
49
+ const keys = Object.keys(raw)
50
+ for (const field of GATE_WORD_FIELD_NAMES) {
51
+ if (!Object.prototype.hasOwnProperty.call(raw, field)) fail('缺少字段 ' + field)
52
+ }
53
+ for (const key of keys) {
54
+ if (!GATE_WORD_FIELD_NAMES.includes(key)) fail('存在未定义字段 ' + key)
55
+ }
56
+ const seenByValue = new Map()
57
+ const words = {}
58
+ for (const field of GATE_WORD_FIELD_NAMES) {
59
+ const value = raw[field]
60
+ if (typeof value !== 'string' || value === '') fail('.' + field + ' 必须是非空字符串')
61
+ if (value !== value.trim()) fail('.' + field + ' 首尾不得有空白')
62
+ if (value.includes('\n') || value.includes('\r')) fail('.' + field + ' 不得包含 CR/LF')
63
+ if (normalizeGateLabel(value) !== value) {
64
+ fail('.' + field + ' 不得以保留的推荐后缀结尾((Recommended)/(Recommended)/(推荐)/(推荐))')
65
+ }
66
+ const twin = seenByValue.get(value)
67
+ if (twin !== undefined) fail('.' + field + ' 与 .' + twin + ' 取值重复(6 个词必须两两不同)')
68
+ seenByValue.set(value, field)
69
+ words[field] = value
70
+ }
71
+ return Object.freeze(words)
72
+ }
73
+
74
+ function bracketed(words) {
75
+ return words.map((word) => '「' + word + '」').join('')
76
+ }
77
+
78
+ /**
79
+ * 运行时词表:只从入参派生(无参默认值不存在)。
80
+ * 返回 { words, route, purpose, options, confirm, variables }:
81
+ * - words:6 个字段 → 值(冻结)
82
+ * - route/purpose:冻结数组(route 为四值:routeMain、routeExecutor、routePlan、routeDisagree;purpose 为两值)
83
+ * - options/confirm:deny 教学文案插值片段(与历史静态文案逐字同构)
84
+ * - variables:prompt variable 名 → 本次 apply 的值(冻结映射)
85
+ */
86
+ export function createGateRuntime(raw) {
87
+ const words = validateGateWords(raw)
88
+ const route = Object.freeze([words.routeMain, words.routeExecutor, words.routePlan, words.routeDisagree])
89
+ const purpose = Object.freeze([words.purposeRefine, words.purposeRedo])
90
+ const options = Object.freeze({
91
+ route: bracketed(route),
92
+ purpose: bracketed(purpose),
93
+ })
94
+ const confirm = Object.freeze({
95
+ route: '须先调用 extra_plan_gate(gate=\'route\') 完成路线确认(选项固定为' + options.route + ')',
96
+ purpose: '须先调用 extra_plan_gate 并传入 gate = purpose 询问用户本次规划者的目的(选项固定为' + options.purpose + ')',
97
+ })
98
+ const variables = {}
99
+ for (const item of GATE_WORD_FIELDS) variables[item.variable] = words[item.field]
100
+ return Object.freeze({
101
+ words,
102
+ route,
103
+ purpose,
104
+ options,
105
+ confirm,
106
+ variables: Object.freeze(variables),
107
+ })
108
+ }
@@ -0,0 +1,293 @@
1
+ // 在消费点热读配置,不只信任 apply 快照。
2
+ // 路径优先级:options.configPath → DSH_EXTRA_PLAN_CONFIG_PATH → configEditor.documentPath;
3
+ // settings 行是权威值,旧预设目录不作回退。
4
+ // stamp 由路径和 stat 元数据组成;未变则跳过读盘和 YAML 解析。
5
+ // 构造期先读一次源文件建立初始基线,避免宿主 cfg 快照过期。
6
+ // 构造期同时做装载期严格校验:settings 行在(按行 id)时 10 个热读键出现 ambiguous /
7
+ // invalid → 直接抛错、插件不装载;missing(老版本升级缺新键)→ 告警一次并按 apply 快照/
8
+ // 内置默认回填;整行缺席(出厂形态)仍静默按 cfg 快照启动。
9
+ // 运行期(refresh 触发的读盘)保持 fail-safe:路径、文件、stat、YAML 或值失败时按键回退
10
+ // 并只告警一次,其中 ambiguous / invalid 显性告警、missing 静默。
11
+ // 回退顺序为 settings 行覆盖 → apply cfg → BUILTIN_DEFAULTS;每个 agent 的缓存键保持隔离。
12
+ // 11 项共享同一 row locator:10 项在此热读;余 1 项 toolPresentationMode 由宿主装载期快照消费,
13
+ // 改值需重启宿主。webFetch 属热读项:值由运行期 restrict 逐会话生效,不需重启。
14
+
15
+ import { statSync, readFileSync } from 'node:fs'
16
+ import { isAbsolute, resolve as pathResolve } from 'node:path'
17
+ import {
18
+ EXTRA_PLAN_SETTING_DEFINITIONS,
19
+ SETTINGS_ROW_ID,
20
+ SETTINGS_ROW_NAME,
21
+ SETTING_DEFINITIONS,
22
+ captureRowSettings,
23
+ getSettingDefinition,
24
+ normalizeSettingValue,
25
+ validateSettingValue,
26
+ } from './preset-settings.js'
27
+ import { resolveWorkspacePath, resolveHostPath, validateReadTarget } from './path-policy.js'
28
+ import { errorText } from './runtime-static.js'
29
+
30
+ const LIVE_KEYS = Object.freeze(EXTRA_PLAN_SETTING_DEFINITIONS.map((item) => item.key))
31
+ const READ_KEYS = LIVE_KEYS
32
+ const BUILTIN_DEFAULTS = Object.freeze(Object.fromEntries(
33
+ SETTING_DEFINITIONS.map((item) => [item.key, item.defaultValue]),
34
+ ))
35
+
36
+ function textOf(value) {
37
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : ''
38
+ }
39
+
40
+ function envConfigPath() {
41
+ return textOf(process.env.DSH_EXTRA_PLAN_CONFIG_PATH)
42
+ }
43
+
44
+ function sameAbsolutePath(left, right) {
45
+ const a = pathResolve(left)
46
+ const b = pathResolve(right)
47
+ return process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b
48
+ }
49
+
50
+ function exactHostCapabilities(context, value) {
51
+ const capabilities = context !== null && context !== undefined && context.hostCapabilities !== undefined && context.hostCapabilities !== null
52
+ ? Object.values(context.hostCapabilities)
53
+ : []
54
+ return capabilities
55
+ .filter((item) => item !== null && typeof item === 'object' && item.type === 'file' && item.purpose === 'config-editor' && typeof item.path === 'string' && sameAbsolutePath(item.path, value))
56
+ .sort((left, right) => {
57
+ const rank = (item) => item.name === 'profilePatch' ? 0 : item.name === 'editorDocument' ? 1 : 2
58
+ return rank(left) - rank(right) || String(left.name).localeCompare(String(right.name))
59
+ })
60
+ }
61
+
62
+ function exactHostTarget(context, value) {
63
+ const candidates = exactHostCapabilities(context, value)
64
+ if (candidates.length === 0) throw new Error('配置源不匹配可信精确Host能力')
65
+ return resolveHostPath(context, value, { capability: candidates[0].name, purpose: 'config-editor' })
66
+ }
67
+
68
+ function resolveAbsoluteTarget(context, value, options = {}) {
69
+ let workspaceError
70
+ let hostError
71
+ if (options.preferHost === true) {
72
+ return exactHostTarget(context, value)
73
+ }
74
+ try { return resolveWorkspacePath(context, value, { purpose: 'live-config' }) } catch (error) { workspaceError = error }
75
+ try { return exactHostTarget(context, value) } catch (error) { hostError = hostError || error }
76
+ throw workspaceError || hostError || new Error('配置路径不在授权H/W根内')
77
+ }
78
+
79
+ function contextFrom(options, agent) {
80
+ if (typeof options.getPathContext === 'function') {
81
+ const supplied = options.getPathContext(agent)
82
+ if (supplied !== undefined && supplied !== null) return supplied
83
+ }
84
+ if (options.pathContext !== undefined && options.pathContext !== null) return options.pathContext
85
+ return null
86
+ }
87
+
88
+ function targetFromValue(context, value, source = 'workspace') {
89
+ if (context === null) throw new Error('配置源缺少明确H/W根')
90
+ if (value !== null && typeof value === 'object' && !Array.isArray(value) && typeof value.path === 'string') {
91
+ if (value.kind === 'workspace') return resolveWorkspacePath(context, value.path, { purpose: 'live-config' })
92
+ if (value.kind === 'host' && typeof value.capability === 'string') return resolveHostPath(context, value.path, { capability: value.capability, purpose: 'config-editor' })
93
+ throw new Error('配置源目标未携带可信H/W分类与精确能力')
94
+ }
95
+ if (typeof value !== 'string' || value.trim() === '') throw new Error('配置源路径不可用')
96
+ if (source === 'document' && !isAbsolute(value)) throw new Error('宿主文档路径必须是绝对路径并匹配精确Host能力')
97
+ return isAbsolute(value)
98
+ ? resolveAbsoluteTarget(context, value, { preferHost: source === 'document' })
99
+ : resolveWorkspacePath(context, value, { purpose: 'live-config' })
100
+ }
101
+
102
+ function targetOf(options, resolver, targetResolver, agent) {
103
+ const context = contextFrom(options, agent)
104
+ const useTargetResolver = targetResolver !== null
105
+ const raw = useTargetResolver ? targetResolver(agent) : resolver === null ? '' : resolver()
106
+ return targetFromValue(context, raw, useTargetResolver || resolver !== null ? 'document' : 'workspace')
107
+ }
108
+
109
+ function statStamp(target, context) {
110
+ try {
111
+ const readable = validateReadTarget(context, target, { expectedType: 'file', purpose: 'live-config' })
112
+ const path = readable.realPath
113
+ try {
114
+ const info = statSync(path, { bigint: true })
115
+ const fields = ['dev', 'ino', 'size', 'mtimeNs', 'ctimeNs']
116
+ if (fields.every((key) => typeof info[key] === 'bigint')) return { ok: true, stamp: fields.map((key) => String(info[key])).join(':'), realPath: path }
117
+ } catch { /* fallback below keeps the same authorized real path */ }
118
+ const fallback = statSync(path)
119
+ return { ok: true, stamp: [fallback.ino, fallback.size, fallback.mtimeMs, fallback.ctimeMs].map((value) => String(value)).join(':'), realPath: path }
120
+ } catch (error) {
121
+ const code = error !== null && typeof error === 'object' && typeof error.code === 'string' ? error.code : ''
122
+ return { ok: false, reason: code !== '' ? code : errorText(error) }
123
+ }
124
+ }
125
+
126
+ function pick(key, raw, fallbackValue) {
127
+ const definition = getSettingDefinition(key)
128
+ if (!validateSettingValue(definition, raw)) return fallbackValue
129
+ return normalizeSettingValue(definition, raw)
130
+ }
131
+
132
+ function describeProblems(problems) {
133
+ return problems.map((item) => item.key + ' = ' + item.state).join(', ')
134
+ }
135
+
136
+ function normalizedFallback(fallbackDefaults) {
137
+ const source = fallbackDefaults !== null && typeof fallbackDefaults === 'object' ? fallbackDefaults : {}
138
+ const out = {}
139
+ for (const key of READ_KEYS) out[key] = key in source ? pick(key, source[key], BUILTIN_DEFAULTS[key]) : BUILTIN_DEFAULTS[key]
140
+ return out
141
+ }
142
+
143
+ /**
144
+ * @param options.resolveDocumentPath 返回 profile patch 绝对路径的函数(宿主侧
145
+ * = ctx.get('configEditor').documentPath);构造期与每次取值现场调用。
146
+ * @param options.resolveDocumentTarget 可选,返回已分类的可信H/W目标。
147
+ * @param options.getPathContext 返回包含workspaceRoot/hostDataRoot/capabilities的上下文。
148
+ * @param options.fallbackDefaults apply 期 cfg 快照(fallback 链第二段)。
149
+ * @param options.configPath 显式路径(最高优先级;必须落在已授权H/W根)。
150
+ */
151
+ export function createLiveConfig(options) {
152
+ const opts = options !== null && typeof options === 'object' ? options : {}
153
+ const fallbackValues = normalizedFallback(opts.fallbackDefaults)
154
+ const explicitPath = textOf(opts.configPath)
155
+ const resolver = typeof opts.resolveDocumentPath === 'function' ? opts.resolveDocumentPath : null
156
+ const targetResolver = typeof opts.resolveDocumentTarget === 'function' ? opts.resolveDocumentTarget : null
157
+
158
+ let path = ''
159
+ let target = null
160
+ let values = { ...fallbackValues }
161
+ let stamp = null
162
+ let warned = false
163
+
164
+ function warnOnce(reason) {
165
+ if (warned) return
166
+ warned = true
167
+ console.warn('[dsh-extra-plan] live-config: 配置热读不可用(' + reason + '),回退到 apply 期快照兜底:' + (path === '' ? '(路径不可得)' : path))
168
+ }
169
+
170
+ function currentResolved(agent) {
171
+ try {
172
+ const overridePath = explicitPath || envConfigPath()
173
+ if (overridePath !== '') {
174
+ const next = targetFromValue(contextFrom(opts, agent), overridePath)
175
+ return { path: next.path, target: next }
176
+ }
177
+ if (resolver === null && targetResolver === null) return { path: '', target: null }
178
+ const next = targetOf(opts, resolver, targetResolver, agent)
179
+ return { path: next.path, target: next }
180
+ } catch (error) {
181
+ return { path: '', target: null, reason: errorText(error) }
182
+ }
183
+ }
184
+
185
+ function currentContext(agent) {
186
+ return contextFrom(opts, agent)
187
+ }
188
+
189
+ function readDiskValues(readTarget, agent) {
190
+ let captured = null
191
+ try {
192
+ const context = currentContext(agent)
193
+ const readable = validateReadTarget(context, readTarget, { expectedType: 'file', purpose: 'live-config' })
194
+ captured = captureRowSettings(readFileSync(readable.realPath, 'utf8'), SETTING_DEFINITIONS)
195
+ } catch (error) {
196
+ return { ok: false, reason: '解析失败 ' + errorText(error) }
197
+ }
198
+ const rawValues = captured !== null && captured.values !== null && typeof captured.values === 'object' ? captured.values : {}
199
+ const states = captured !== null && captured.states !== null && typeof captured.states === 'object' ? captured.states : {}
200
+ const next = {}
201
+ const problems = []
202
+ for (const key of READ_KEYS) {
203
+ const state = typeof states[key] === 'string' ? states[key] : 'missing'
204
+ const hit = state === 'captured' && Object.prototype.hasOwnProperty.call(rawValues, key)
205
+ if (!hit) problems.push({ key, state })
206
+ next[key] = hit ? pick(key, rawValues[key], fallbackValues[key]) : fallbackValues[key]
207
+ }
208
+ if (captured === null || captured.rowPresent !== true) return { ok: false, reason: 'none', silent: true, values: next }
209
+ if (problems.length === 0) return { ok: true, values: next }
210
+ return { ok: false, reason: describeProblems(problems), problems, values: next }
211
+ }
212
+
213
+ const boot = currentResolved(undefined)
214
+ path = boot.path
215
+ target = boot.target
216
+ if (path === '') {
217
+ warnOnce(boot.reason || '路径不可得(configEditor 未就绪且无显式配置路径)')
218
+ } else {
219
+ const initial = statStamp(target, currentContext(undefined))
220
+ if (!initial.ok) warnOnce('stat 失败 ' + initial.reason)
221
+ else {
222
+ stamp = initial.stamp
223
+ const parsed = readDiskValues(target, undefined)
224
+ if (Array.isArray(parsed.problems)) {
225
+ const hard = parsed.problems.filter((item) => item.state === 'ambiguous' || item.state === 'invalid')
226
+ if (hard.length > 0) throw new Error('extra-plan: settings 行校验失败:' + describeProblems(hard) + '(期望在 ' + SETTINGS_ROW_ID + ' 行、name 为 ' + SETTINGS_ROW_NAME + ' 的 config 内取得合法值)')
227
+ warnOnce('settings 行缺键回填(' + parsed.reason + '),按 apply 快照/内置默认补齐')
228
+ values = { ...parsed.values }
229
+ } else if (parsed.ok) values = parsed.values
230
+ else if (parsed.silent !== true) warnOnce(parsed.reason)
231
+ }
232
+ }
233
+
234
+ function refresh(agent) {
235
+ const next = currentResolved(agent)
236
+ const pathChanged = next.path !== path
237
+ const targetChanged = target === null || next.target === null
238
+ ? target !== next.target
239
+ : ['kind', 'path', 'root', 'capability', 'exactPath', 'access', 'purpose'].some((key) => target[key] !== next.target[key])
240
+ path = next.path
241
+ target = next.target
242
+ if (pathChanged || targetChanged) {
243
+ stamp = null
244
+ if (path === '') {
245
+ values = { ...fallbackValues }
246
+ warnOnce(next.reason || '路径不可得(configEditor 未就绪且无显式配置路径)')
247
+ return
248
+ }
249
+ }
250
+ if (path === '' || target === null) return
251
+ const probe = statStamp(target, currentContext(agent))
252
+ if (!probe.ok) {
253
+ stamp = null
254
+ values = { ...fallbackValues }
255
+ warnOnce('stat 失败 ' + probe.reason)
256
+ return
257
+ }
258
+ if (probe.stamp === stamp) return
259
+ stamp = probe.stamp
260
+ const parsed = readDiskValues(target, agent)
261
+ if (parsed.ok) {
262
+ values = parsed.values
263
+ return
264
+ }
265
+ values = Array.isArray(parsed.problems) && parsed.values !== null && parsed.values !== undefined ? { ...parsed.values } : { ...fallbackValues }
266
+ if (Array.isArray(parsed.problems)) {
267
+ const hard = parsed.problems.filter((item) => item.state === 'ambiguous' || item.state === 'invalid')
268
+ if (hard.length > 0) warnOnce('settings 行键值不可用:' + describeProblems(hard))
269
+ return
270
+ }
271
+ if (parsed.silent !== true) warnOnce(parsed.reason)
272
+ }
273
+
274
+ function read(key, agent) {
275
+ refresh(agent)
276
+ return values[key]
277
+ }
278
+
279
+ const live = {
280
+ get(key, agent) { return read(key, agent) },
281
+ get anchoredBootstrap() { return read('anchoredBootstrap') },
282
+ get creativeMode() { return read('creativeMode') },
283
+ get webFetch() { return read('webFetch') },
284
+ get runcodeCatchGate() { return read('runcodeCatchGate') },
285
+ get crossProviderPlannerModel() { return read('crossProviderPlannerModel') },
286
+ get plannerModel() { return read('plannerModel') },
287
+ get plannerPromptSuffix() { return read('plannerPromptSuffix') },
288
+ get exploreBudget() { return read('exploreBudget') },
289
+ get otherAgentModel() { return read('otherAgentModel') },
290
+ get reviewerUsesPlannerModel() { return read('reviewerUsesPlannerModel') },
291
+ }
292
+ return Object.freeze(live)
293
+ }
@@ -0,0 +1,132 @@
1
+ import { createReadStream, createWriteStream, existsSync, readdirSync, renameSync, unlinkSync } from 'node:fs'
2
+ import { createInterface } from 'node:readline'
3
+ import { join } from 'node:path'
4
+ import { resolveHostPath, prepareWriteTarget, validateReadTarget } from './path-policy.js'
5
+
6
+ // 诊断日志保留期裁剪:只处理 <host 根>/logs/dsh-extra-plan 下的 .jsonl 诊断日志。
7
+ // 全部诊断 JSONL(usage ledger 除外)统一按固定 UTC+8 北京时间昨日零点裁剪,保留今天/昨天两个自然日。
8
+ // 不处理 usage-ledger:该文件由 lib/usage-ledger.js 的 startupArchive 归档链路自行管理。
9
+ // 清理算法为前缀边界裁剪:分界线=首个可解析且 cutoff<=ts<=now 的行;不可解析行(空行/坏JSON/无ts/非法ts)与未来时间行(ts>now,时钟过快写入)不作为分界,作为前缀候选随前缀删除。
10
+ // 分界线之后原样保留(含坏行与乱序过期行,随保留窗口自然收敛);零写条件=文件0行或分界为0;全部为前缀候选时清空为空文件。导出面调整见下,cutoff规则单一。
11
+ export const LOG_DIRECTORY = 'logs/dsh-extra-plan'
12
+ export const EXCLUDED_LOG_FILES = Object.freeze(['extra-plan-usage-ledger.jsonl'])
13
+ const DAY_MS = 86400000
14
+ const OFFSET_MS = 28800000
15
+ const PURPOSE = 'diagnostics'
16
+ const NEWLINE = String.fromCharCode(10)
17
+
18
+ function beijingYesterdayCutoffMs(now) {
19
+ return (Math.floor((now + OFFSET_MS) / DAY_MS) - 1) * DAY_MS - OFFSET_MS
20
+ }
21
+
22
+ function parsedTsOf(line) {
23
+ const text = typeof line === 'string' ? line.trim() : ''
24
+ if (text === '') return null
25
+ let row
26
+ try { row = JSON.parse(text) } catch { return null }
27
+ if (row === null || typeof row !== 'object') return null
28
+ const ts = row.ts
29
+ if (typeof ts !== 'string') return null
30
+ const value = Date.parse(ts)
31
+ return Number.isNaN(value) ? null : value
32
+ }
33
+
34
+ // Windows 上 rename 覆盖要求目标文件不再被任何句柄持有,故读流必须显式关闭并等待 close。
35
+ function closeInput(input) {
36
+ return new Promise((resolve) => {
37
+ if (input.closed === true) {
38
+ resolve()
39
+ return
40
+ }
41
+ input.once('close', () => resolve())
42
+ input.destroy()
43
+ })
44
+ }
45
+
46
+ function diagnosticReadTarget(pathContext, filePath, expectedType) {
47
+ const target = resolveHostPath(pathContext, filePath, { purpose: PURPOSE })
48
+ return validateReadTarget(pathContext, target, { expectedType, purpose: PURPOSE })
49
+ }
50
+
51
+ async function findPrefixBoundary(filePath, cutoffMs, now, pathContext) {
52
+ const input = createReadStream(diagnosticReadTarget(pathContext, filePath, 'file').realPath, { encoding: 'utf8' })
53
+ const reader = createInterface({ input, crlfDelay: Infinity })
54
+ let lines = 0
55
+ try {
56
+ for await (const line of reader) {
57
+ const ts = parsedTsOf(line)
58
+ if (ts !== null && ts >= cutoffMs && ts <= now) return { boundary: lines, lines: lines + 1 }
59
+ lines += 1
60
+ }
61
+ return { boundary: null, lines }
62
+ } finally {
63
+ reader.close()
64
+ await closeInput(input)
65
+ }
66
+ }
67
+
68
+ async function copyFromBoundary(filePath, tmpPath, skipCount, pathContext) {
69
+ const tmpTarget = resolveHostPath(pathContext, tmpPath, { purpose: PURPOSE })
70
+ prepareWriteTarget(pathContext, tmpTarget, { expectedType: 'file', purpose: PURPOSE })
71
+ const input = createReadStream(diagnosticReadTarget(pathContext, filePath, 'file').realPath, { encoding: 'utf8' })
72
+ const writer = createWriteStream(tmpTarget.path, { encoding: 'utf8' })
73
+ const reader = createInterface({ input, crlfDelay: Infinity })
74
+ let skipped = 0
75
+ try {
76
+ for await (const line of reader) {
77
+ if (skipped < skipCount) {
78
+ skipped += 1
79
+ continue
80
+ }
81
+ writer.write(line + NEWLINE)
82
+ }
83
+ await new Promise((resolve, reject) => {
84
+ writer.once('error', reject)
85
+ writer.once('close', resolve)
86
+ writer.end()
87
+ })
88
+ await closeInput(input)
89
+ renameSync(tmpTarget.path, filePath)
90
+ } catch (error) {
91
+ try { reader.close() } catch {}
92
+ try { input.destroy() } catch {}
93
+ try { writer.destroy() } catch {}
94
+ try { unlinkSync(tmpTarget.path) } catch {}
95
+ throw error
96
+ }
97
+ }
98
+
99
+ export async function pruneDiagnosticLogs(pathContext, options = {}) {
100
+ const settings = options !== null && typeof options === 'object' ? options : {}
101
+ const now = Number.isFinite(settings.now) ? settings.now : Date.now()
102
+ const root = pathContext !== null && typeof pathContext === 'object' ? pathContext.hostDataRoot : null
103
+ if (typeof root !== 'string' || root === '') return { status: 'skipped', reason: 'no-host-root' }
104
+ const dirTarget = resolveHostPath(pathContext, LOG_DIRECTORY, { purpose: PURPOSE })
105
+ if (!existsSync(dirTarget.path)) return { status: 'skipped', reason: 'no-log-directory' }
106
+ prepareWriteTarget(pathContext, dirTarget, { expectedType: 'directory', purpose: PURPOSE })
107
+ const directory = diagnosticReadTarget(pathContext, dirTarget.path, 'directory')
108
+ const names = readdirSync(directory.realPath).filter((name) => {
109
+ if (!name.endsWith('.jsonl') || EXCLUDED_LOG_FILES.includes(name)) return false
110
+ try {
111
+ diagnosticReadTarget(pathContext, join(dirTarget.path, name), 'file')
112
+ return true
113
+ } catch (error) {
114
+ if (error?.code === 'TARGET_MISSING' || error?.code === 'TARGET_TYPE') return false
115
+ throw error
116
+ }
117
+ }).sort()
118
+ let pruned = 0
119
+ let removedRows = 0
120
+ for (const name of names) {
121
+ const filePath = join(dirTarget.path, name)
122
+ const cutoffMs = beijingYesterdayCutoffMs(now)
123
+ const found = await findPrefixBoundary(filePath, cutoffMs, now, pathContext)
124
+ if (found.lines === 0 || found.boundary === 0) continue
125
+ prepareWriteTarget(pathContext, resolveHostPath(pathContext, filePath, { purpose: PURPOSE }), { expectedType: 'file', purpose: PURPOSE })
126
+ const tmpPath = join(dirTarget.path, name + '.prune-tmp-' + String(process.pid) + '-' + String(Date.now()))
127
+ removedRows += found.boundary === null ? found.lines : found.boundary
128
+ await copyFromBoundary(filePath, tmpPath, found.boundary === null ? found.lines : found.boundary, pathContext)
129
+ pruned += 1
130
+ }
131
+ return { status: pruned > 0 ? 'pruned' : 'up-to-date', scanned: names.length, pruned, removedRows }
132
+ }