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.
- package/LICENSE +21 -0
- package/README.md +179 -2
- package/assets/presets/extra-plan/agent.cordis.yml +580 -0
- package/assets/presets/extra-plan/preset-definition-extra-plan-executor.generated.yml +115 -0
- package/assets/presets/extra-plan/preset-definition-extra-plan-planner.generated.yml +113 -0
- package/assets/presets/extra-plan/preset-definition-extra-plan-prober.generated.yml +107 -0
- package/assets/presets/extra-plan/preset-definition-extra-plan-reviewer.generated.yml +115 -0
- package/assets/presets/extra-plan/preset-definition.generated.yml +335 -0
- package/assets/presets/extra-plan/preset.yml +2 -0
- package/cordis.patch.yml +7 -0
- package/index.js +1671 -0
- package/lib/agent-runtime.js +172 -0
- package/lib/agent-session.js +65 -0
- package/lib/assembly-presentation.js +267 -0
- package/lib/client-carrier.js +7 -0
- package/lib/client.js +314 -0
- package/lib/extra-plan-gate-tool.js +387 -0
- package/lib/gate-decisions.js +744 -0
- package/lib/gate-words.js +108 -0
- package/lib/live-config.js +293 -0
- package/lib/log-retention.js +132 -0
- package/lib/model-routing.js +648 -0
- package/lib/path-policy.js +464 -0
- package/lib/plan-draft-tool.js +294 -0
- package/lib/planner-budget.js +136 -0
- package/lib/preset-defaults.generated.js +17 -0
- package/lib/preset-settings.js +3 -0
- package/lib/preset-sync.js +809 -0
- package/lib/preset-yaml.js +438 -0
- package/lib/role-contract.js +11 -0
- package/lib/run-code-scanner.js +360 -0
- package/lib/run-code-static.js +621 -0
- package/lib/runtime-diagnostics.js +89 -0
- package/lib/runtime-lifecycle.js +162 -0
- package/lib/runtime-static.js +23 -0
- package/lib/save-contract.js +263 -0
- package/lib/save-persistence.js +223 -0
- package/lib/save-plan-markdown-parser.js +369 -0
- package/lib/save-plan-validation-diagnostics.js +49 -0
- package/lib/save-plan-validation.js +812 -0
- package/lib/save-probe-validation.js +173 -0
- package/lib/save-source-verification.js +195 -0
- package/lib/save-tool-factories.js +270 -0
- package/lib/sdk-text-cache.js +161 -0
- package/lib/settings-contract.js +191 -0
- package/lib/settings.js +369 -0
- package/lib/shell-mutation.js +484 -0
- package/lib/usage-ledger-background.js +214 -0
- package/lib/usage-ledger-worker.js +116 -0
- package/lib/usage-ledger.js +1393 -0
- package/locale/en.json +6 -0
- package/locale/settings/en.json +6 -0
- package/locale/settings/zh.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +56 -4
- package/scripts/generate-runtime-defaults.mjs +796 -0
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { mkdirSync, appendFileSync } from 'node:fs'
|
|
2
|
+
import { join, dirname, isAbsolute } from 'node:path'
|
|
3
|
+
import { resolveWorkspacePath, resolveHostPath, prepareWriteTarget } from './path-policy.js'
|
|
4
|
+
import { causeChainOf } from './runtime-static.js'
|
|
5
|
+
|
|
6
|
+
function resolveAbsoluteLogTarget(context, value, purpose) {
|
|
7
|
+
let hostError
|
|
8
|
+
let workspaceError
|
|
9
|
+
try { return resolveHostPath(context, value, { purpose }) } catch (error) { hostError = error }
|
|
10
|
+
try { return resolveWorkspacePath(context, value, { purpose }) } catch (error) { workspaceError = error }
|
|
11
|
+
throw hostError || workspaceError || new Error('诊断路径不在授权H/W根内')
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// 入口每个模块实例装配一次;读取路径事实仍发生在每次日志调用时。
|
|
15
|
+
export function createRuntimeDiagnostics({ sessionCwdOf, pathContextFor, profileFactsOf, absoluteRoot, defaultDiagnosticFile }) {
|
|
16
|
+
// ── agent/error 回合错误取证落盘(与 recordRequestError 同诊断模式) ──────
|
|
17
|
+
// 宿主在回合/步骤级错误时 emit 'agent/error'(payload = { agent, turn, step, error },
|
|
18
|
+
// error 为逐字原始错误;派发点 dsh-agent-loop throwError、签名 dsh-tool-cordis
|
|
19
|
+
// api-catalog),宿主不把该错误写 console → 由监听器逐字落盘留证。本插件每个会话
|
|
20
|
+
// 各持一份实例,主会话与全部子代理的任何 runTurn 级错误(含子代理"腰斩"的流建立
|
|
21
|
+
// 失败)都会留痕。
|
|
22
|
+
// 入口以模块级装配的同一绑定导出 recordAgentError 供回归直呼。与 recordRequestError
|
|
23
|
+
// 同模式——整体 try/catch 吞错、写失败一次性 console.warn 防刷屏;落盘文件与
|
|
24
|
+
// 诊断文件始终按已授权日志根解析;缺根时非阻断且不写包目录。
|
|
25
|
+
let agentErrorDiagWarned = false
|
|
26
|
+
|
|
27
|
+
function diagnosticTargetOf(ctx, agent, configured, purpose = 'diagnostics') {
|
|
28
|
+
const cwd = sessionCwdOf(agent)
|
|
29
|
+
const context = pathContextFor(ctx, cwd)
|
|
30
|
+
if (context === null) return null
|
|
31
|
+
const facts = profileFactsOf(ctx)
|
|
32
|
+
const value = typeof configured === 'string' && configured !== '' ? configured : defaultDiagnosticFile
|
|
33
|
+
const bare = !isAbsolute(value) && !/[\\/]/.test(value)
|
|
34
|
+
if (bare) {
|
|
35
|
+
if (facts.hostState === 'invalid' || facts.hostState === 'conflict') return null
|
|
36
|
+
if (facts.hostState === 'valid' && facts.hostDataRoot !== null) return resolveHostPath(context, join('logs', 'dsh-extra-plan', value), { purpose })
|
|
37
|
+
if (facts.hostState === 'missing' && absoluteRoot(cwd) !== null) return resolveWorkspacePath(context, join('.extra-plan', 'logs', value), { purpose })
|
|
38
|
+
return null
|
|
39
|
+
}
|
|
40
|
+
if (isAbsolute(value)) return resolveAbsoluteLogTarget(context, value, purpose)
|
|
41
|
+
return resolveWorkspacePath(context, value, { purpose })
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function prepareDiagnosticPath(ctx, agent, configured) {
|
|
45
|
+
try {
|
|
46
|
+
const target = diagnosticTargetOf(ctx, agent, configured)
|
|
47
|
+
if (target === null) return ''
|
|
48
|
+
const context = pathContextFor(ctx, sessionCwdOf(agent))
|
|
49
|
+
if (context === null) return ''
|
|
50
|
+
const parent = target.kind === 'host'
|
|
51
|
+
? resolveHostPath(context, dirname(target.path), { purpose: 'diagnostics' })
|
|
52
|
+
: resolveWorkspacePath(context, dirname(target.path), { purpose: 'diagnostics' })
|
|
53
|
+
prepareWriteTarget(context, parent, { expectedType: 'any', purpose: 'diagnostics' })
|
|
54
|
+
mkdirSync(parent.path, { recursive: true })
|
|
55
|
+
prepareWriteTarget(context, target, { expectedType: 'file', purpose: 'diagnostics' })
|
|
56
|
+
return target.path
|
|
57
|
+
} catch (error) {
|
|
58
|
+
return ''
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function appendDiagnostic(ctx, agent, configured, row) {
|
|
63
|
+
const path = prepareDiagnosticPath(ctx, agent, configured)
|
|
64
|
+
if (path === '') return false
|
|
65
|
+
appendFileSync(path, JSON.stringify(row) + '\n', { encoding: 'utf8' })
|
|
66
|
+
return true
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function recordAgentError(payload, options = {}) {
|
|
70
|
+
try {
|
|
71
|
+
const sessionId = payload?.agent?.session?.header?.id
|
|
72
|
+
const row = {
|
|
73
|
+
ts: new Date().toISOString(),
|
|
74
|
+
sessionId: typeof sessionId === 'string' ? sessionId : '',
|
|
75
|
+
turn: payload.turn,
|
|
76
|
+
step: payload.step,
|
|
77
|
+
chain: causeChainOf(payload.error, 8),
|
|
78
|
+
}
|
|
79
|
+
if (!appendDiagnostic(options.ctx, payload?.agent, 'extra-plan-agent-errors.jsonl', row)) throw new Error('agent diagnostics root unavailable')
|
|
80
|
+
} catch (error) {
|
|
81
|
+
if (!agentErrorDiagWarned) {
|
|
82
|
+
agentErrorDiagWarned = true
|
|
83
|
+
console.warn('extra-plan: agent-error diagnostics write failed: ' + (error instanceof Error ? error.message : String(error)))
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return { prepareDiagnosticPath, appendDiagnostic, recordAgentError }
|
|
89
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// per-apply runtime lifecycle:save 注册、probe 认领、计数器与 run_code 拒绝记录。
|
|
2
|
+
import { PROBER_PRESET_ID } from './role-contract.js'
|
|
3
|
+
|
|
4
|
+
export function createRuntimeLifecycle(options = {}) {
|
|
5
|
+
const {
|
|
6
|
+
defineSavePlan, defineSaveProbe, defineEditPlanDraft,
|
|
7
|
+
isBootstrapPhase,
|
|
8
|
+
isSubagentChild, isPlannerChild, toolSchemasOf, schemasHasWriteTools,
|
|
9
|
+
isRunCodeSubCall, runCodeDispatchCapText,
|
|
10
|
+
} = options
|
|
11
|
+
|
|
12
|
+
function registerTool(registered, toolName, defineFn, agent, when) {
|
|
13
|
+
if (registered.has(agent)) return
|
|
14
|
+
let tools
|
|
15
|
+
try {
|
|
16
|
+
tools = agent.ctx !== undefined && agent.ctx !== null && typeof agent.ctx.get === 'function' ? agent.ctx.get('tools') : undefined
|
|
17
|
+
} catch (error) {
|
|
18
|
+
tools = undefined
|
|
19
|
+
}
|
|
20
|
+
if (tools === undefined || tools === null || typeof tools.register !== 'function') {
|
|
21
|
+
console.warn('extra-plan: tools service unavailable — ' + toolName + ' not registered')
|
|
22
|
+
return
|
|
23
|
+
}
|
|
24
|
+
try {
|
|
25
|
+
tools.register(defineFn(), typeof when === 'function' ? { when } : undefined)
|
|
26
|
+
registered.add(agent)
|
|
27
|
+
} catch (error) {
|
|
28
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
29
|
+
if (error instanceof Error && message.includes('already registered')) {
|
|
30
|
+
registered.add(agent)
|
|
31
|
+
console.warn('extra-plan: ' + toolName + ' already registered in this scope — keeping the existing tool, no retry')
|
|
32
|
+
return
|
|
33
|
+
}
|
|
34
|
+
if (error instanceof Error && (error.name === 'JsonSchemaError' || error.name === 'TypeError' || message.includes('is reserved'))) {
|
|
35
|
+
registered.add(agent)
|
|
36
|
+
console.error('extra-plan: ' + toolName + ' registration failed permanently: ' + message)
|
|
37
|
+
return
|
|
38
|
+
}
|
|
39
|
+
console.error('extra-plan: ' + toolName + ' registration failed: ' + message)
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const savePlanRegistered = new WeakSet()
|
|
44
|
+
const saveProbeRegistered = new WeakSet()
|
|
45
|
+
const probeClaimed = new WeakSet()
|
|
46
|
+
const pendingProbeClaims = new Map()
|
|
47
|
+
const jobOutputCallCounters = new Map()
|
|
48
|
+
const jobOutputLastAnchors = new Map()
|
|
49
|
+
const pollGuardCounters = new Map()
|
|
50
|
+
const subCallCounters = new Map()
|
|
51
|
+
const toolJobsNoticesConsumed = new Map()
|
|
52
|
+
const runCodeDenyRecords = new Map()
|
|
53
|
+
|
|
54
|
+
function saveBootstrapWhen(context) {
|
|
55
|
+
try {
|
|
56
|
+
const agent = context !== null && typeof context === 'object' ? context.agent : undefined
|
|
57
|
+
if (agent === undefined) return true
|
|
58
|
+
return !(typeof isBootstrapPhase === 'function' && isBootstrapPhase(agent))
|
|
59
|
+
} catch (error) {
|
|
60
|
+
return true
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function registerSavePlan(agent) { registerTool(savePlanRegistered, 'save_plan', defineSavePlan, agent, saveBootstrapWhen) }
|
|
65
|
+
function registerSaveProbe(agent) { registerTool(saveProbeRegistered, 'save_probe', defineSaveProbe, agent, saveBootstrapWhen) }
|
|
66
|
+
// edit_plan_draft 与 save_plan/save_probe 同构注册:第 5 参复用同一个 saveBootstrapWhen 引用(不复制 when 函数),
|
|
67
|
+
// 弱集独立(editPlanDraftRegistered),不与 savePlanRegistered 共用。
|
|
68
|
+
const editPlanDraftRegistered = new WeakSet()
|
|
69
|
+
function registerEditPlanDraft(agent) { registerTool(editPlanDraftRegistered, 'edit_plan_draft', defineEditPlanDraft, agent, saveBootstrapWhen) }
|
|
70
|
+
|
|
71
|
+
// F1:prober 角色的预设身份判据。pendingProbeClaims 是 per-apply 实例 Map,父实例写入的
|
|
72
|
+
// 认领子实例读不到,故先按 session.header.agentPreset 的身份直接放行。本函数只读一个字符串
|
|
73
|
+
// 字段:header 缺失、agentPreset 非字符串或读取过程异常一律返回 false,绝不抛错
|
|
74
|
+
// (agent/created 与 agent/pre-step 都是禁抛点)。
|
|
75
|
+
function isProberRole(agent) {
|
|
76
|
+
try {
|
|
77
|
+
if (agent === undefined || agent === null) return false
|
|
78
|
+
const session = agent.session
|
|
79
|
+
if (session === undefined || session === null) return false
|
|
80
|
+
const header = session.header
|
|
81
|
+
if (header === undefined || header === null) return false
|
|
82
|
+
const agentPreset = header.agentPreset
|
|
83
|
+
if (typeof agentPreset !== 'string') return false
|
|
84
|
+
return agentPreset === PROBER_PRESET_ID
|
|
85
|
+
} catch (error) {
|
|
86
|
+
return false
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function probeClaimFor(agent) {
|
|
91
|
+
if (probeClaimed.has(agent)) return true
|
|
92
|
+
// 身份判据优先;未命中回退下面的 pendingProbeClaims 认领逻辑(写工具判定与计数扣减原样保留)。
|
|
93
|
+
if (isProberRole(agent)) return true
|
|
94
|
+
if (typeof isSubagentChild !== 'function' || !isSubagentChild(agent)) return false
|
|
95
|
+
if (typeof isPlannerChild === 'function' && isPlannerChild(agent)) return false
|
|
96
|
+
const header = agent.session.header
|
|
97
|
+
const parentSession = header !== undefined && header !== null ? header.parentSession : undefined
|
|
98
|
+
if (typeof parentSession !== 'string') return false
|
|
99
|
+
const pending = pendingProbeClaims.get(parentSession)
|
|
100
|
+
if (pending === undefined || typeof pending !== 'number' || pending <= 0) return false
|
|
101
|
+
const schemas = toolSchemasOf(agent)
|
|
102
|
+
if (schemas === undefined || schemasHasWriteTools(schemas)) return false
|
|
103
|
+
pendingProbeClaims.set(parentSession, pending - 1)
|
|
104
|
+
if (pending - 1 <= 0) pendingProbeClaims.delete(parentSession)
|
|
105
|
+
probeClaimed.add(agent)
|
|
106
|
+
return true
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function recordProbeClaim(sessionId) {
|
|
110
|
+
pendingProbeClaims.set(sessionId, (pendingProbeClaims.get(sessionId) || 0) + 1)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function noteRunCodeSubCall(sessionId, rid, cap) {
|
|
114
|
+
const bucket = subCallCounters.get(sessionId)
|
|
115
|
+
const passed = rid === '' || bucket === undefined ? 0 : (bucket.get(rid) || 0)
|
|
116
|
+
if (rid === '' || passed >= cap) return runCodeDispatchCapText(rid === '' ? '?' : rid, passed + 1, cap)
|
|
117
|
+
if (bucket === undefined) subCallCounters.set(sessionId, new Map([[rid, passed + 1]]))
|
|
118
|
+
else bucket.set(rid, passed + 1)
|
|
119
|
+
return null
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function recordRunCodeDeny(agent, exec, reason) {
|
|
123
|
+
if (!isRunCodeSubCall(exec)) return
|
|
124
|
+
if (typeof reason !== 'string' || reason === '') return
|
|
125
|
+
const sessionId = agent !== undefined && agent !== null && agent.session !== undefined && agent.session !== null && agent.session.header !== undefined && agent.session.header !== null ? agent.session.header.id : undefined
|
|
126
|
+
if (typeof sessionId !== 'string' || sessionId === '') return
|
|
127
|
+
const rid = typeof exec.rootCallId === 'string' && exec.rootCallId !== '' ? exec.rootCallId : (typeof exec.callId === 'string' ? exec.callId : '')
|
|
128
|
+
let byRoot = runCodeDenyRecords.get(sessionId)
|
|
129
|
+
if (byRoot === undefined) { byRoot = new Map(); runCodeDenyRecords.set(sessionId, byRoot) }
|
|
130
|
+
let reasons = byRoot.get(rid)
|
|
131
|
+
if (reasons === undefined) { reasons = new Set(); byRoot.set(rid, reasons) }
|
|
132
|
+
reasons.add(reason)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function takeRunCodeDenyRecords(sessionId, rootId) {
|
|
136
|
+
if (typeof sessionId !== 'string' || sessionId === '') return undefined
|
|
137
|
+
const byRoot = runCodeDenyRecords.get(sessionId)
|
|
138
|
+
if (byRoot === undefined) return undefined
|
|
139
|
+
const reasons = byRoot.get(rootId)
|
|
140
|
+
if (reasons === undefined) return undefined
|
|
141
|
+
byRoot.delete(rootId)
|
|
142
|
+
return reasons
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function disposeSession(sessionId) {
|
|
146
|
+
pendingProbeClaims.delete(sessionId)
|
|
147
|
+
runCodeDenyRecords.delete(sessionId)
|
|
148
|
+
jobOutputCallCounters.delete(sessionId)
|
|
149
|
+
jobOutputLastAnchors.delete(sessionId)
|
|
150
|
+
pollGuardCounters.delete(sessionId)
|
|
151
|
+
toolJobsNoticesConsumed.delete(sessionId)
|
|
152
|
+
subCallCounters.delete(sessionId)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
return {
|
|
156
|
+
registerSavePlan, registerSaveProbe, registerEditPlanDraft, probeClaimFor, recordProbeClaim,
|
|
157
|
+
pendingProbeClaims, jobOutputCallCounters, jobOutputLastAnchors, pollGuardCounters,
|
|
158
|
+
subCallCounters, toolJobsNoticesConsumed, runCodeDenyRecords,
|
|
159
|
+
noteRunCodeSubCall, recordRunCodeDeny, takeRunCodeDenyRecords, disposeSession,
|
|
160
|
+
pendingProbeCount: (sessionId) => pendingProbeClaims.get(sessionId) || 0,
|
|
161
|
+
}
|
|
162
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// 仅接受显式参数的纯 helper;不依赖 ctx,也不保存 per-apply 状态。
|
|
2
|
+
|
|
3
|
+
export function errorCodeOf(error) {
|
|
4
|
+
return error !== null && typeof error === 'object' && typeof error.code === 'string' ? error.code : ''
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function errorText(error) {
|
|
8
|
+
return error instanceof Error ? error.message : String(error)
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function causeChainOf(error, depth) {
|
|
12
|
+
const chain = []
|
|
13
|
+
let current = error
|
|
14
|
+
for (let i = 0; i < depth && current !== undefined && current !== null; i += 1) {
|
|
15
|
+
chain.push({
|
|
16
|
+
name: typeof current.name === 'string' ? current.name : '',
|
|
17
|
+
message: typeof current.message === 'string' ? current.message.slice(0, 400) : '',
|
|
18
|
+
...(current.code !== undefined ? { code: String(current.code) } : {}),
|
|
19
|
+
})
|
|
20
|
+
current = current.cause
|
|
21
|
+
}
|
|
22
|
+
return chain
|
|
23
|
+
}
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
// 任务短名净化:仅保留安全字符(字母/数字/下划线/连字符/中日韩文字),
|
|
2
|
+
// 其余字符折为连字符;≤PROBE_LIMITS.maxTaskNameLen 字;去首尾连字符。
|
|
3
|
+
// 净化失败或空串返回 '';工件 base 仅省略短名,仍保留可选会话标记及毫秒时间、PID、序号。
|
|
4
|
+
export function sanitizeTaskName(name) {
|
|
5
|
+
if (typeof name !== 'string') return ''
|
|
6
|
+
let out = ''
|
|
7
|
+
for (const ch of name) {
|
|
8
|
+
if (out.length >= PROBE_LIMITS.maxTaskNameLen) break
|
|
9
|
+
out += /[A-Za-z0-9_\-\u4e00-\u9fff]/.test(ch) ? ch : '-'
|
|
10
|
+
}
|
|
11
|
+
return out.replace(/^-+|-+$/g, '')
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// 本地时间戳 yyyyMMddHHmmss(保留既有公共格式合同)。
|
|
15
|
+
function timestampOf(date) {
|
|
16
|
+
const pad = (n) => String(n).padStart(2, '0')
|
|
17
|
+
return `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function timestamp() {
|
|
21
|
+
return timestampOf(new Date())
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// 会话标识段(T3):session header id 去除分隔符后前 8 位字母数字。单段、无连字符,
|
|
25
|
+
// 便于按「时间戳前一段」识别;取不到 id(测试夹具/异常会话)→ ''。
|
|
26
|
+
export function sessionTagOf(sessionId) {
|
|
27
|
+
return typeof sessionId === 'string' ? sessionId.replace(/[^A-Za-z0-9]/g, '').slice(0, 8) : ''
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// 工件 base 唯一真源:任务短名 + sessionTag + 本地毫秒时间 + process.pid + 进程内递增序号。
|
|
31
|
+
// 同一 task/session 在同一毫秒内连续调用也不会碰撞;save_plan/save_probe 共用此合同。
|
|
32
|
+
let artifactLastMillis = -1
|
|
33
|
+
let artifactSequence = 0
|
|
34
|
+
export function saveArtifactBase(nameSeg, sessionId) {
|
|
35
|
+
const now = new Date()
|
|
36
|
+
const millis = now.getTime()
|
|
37
|
+
if (millis === artifactLastMillis) artifactSequence += 1
|
|
38
|
+
else {
|
|
39
|
+
artifactLastMillis = millis
|
|
40
|
+
artifactSequence = 0
|
|
41
|
+
}
|
|
42
|
+
const tag = sessionTagOf(sessionId)
|
|
43
|
+
const stamp = timestampOf(now) + String(now.getMilliseconds()).padStart(3, '0')
|
|
44
|
+
const parts = []
|
|
45
|
+
if (nameSeg !== '') parts.push(nameSeg)
|
|
46
|
+
if (tag !== '') parts.push(tag)
|
|
47
|
+
parts.push(stamp, String(process.pid), String(artifactSequence))
|
|
48
|
+
return parts.join('-')
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export const SAVE_PLAN_LIMITS = Object.freeze({
|
|
52
|
+
maxTasks: 20,
|
|
53
|
+
maxSummaryChars: 24000
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
function summaryList(value) {
|
|
57
|
+
return Array.isArray(value) ? value.map((item) => String(item)).join('、') : ''
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function summaryBool(value) {
|
|
61
|
+
return value === true ? '是' : '否'
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// 只格式化确定性派遣正文;不包含本次落盘生成的方案/验收路径。
|
|
65
|
+
export function formatSavePlanSummary(summary) {
|
|
66
|
+
const value = summary !== null && typeof summary === 'object' ? summary : {}
|
|
67
|
+
const lines = []
|
|
68
|
+
lines.push('任务数=' + String(value.taskCount || 0) + ';任务文件数=' + String(value.taskFileCount || 0) + ';收尾文件数=' + String(value.closureFileCount || 0) + ';文件总数=' + String(value.fileCount || 0))
|
|
69
|
+
lines.push('执行组数=' + String(value.groupCount || 0) + ';验收组数=' + String(value.reviewGroupCount || 0) + ';检查数=' + String(value.checkCount || 0) + ';有收尾=' + summaryBool(value.hasClosure) + ';有全局验收=' + summaryBool(value.hasGlobalAcceptance))
|
|
70
|
+
for (const task of Array.isArray(value.tasks) ? value.tasks : []) {
|
|
71
|
+
lines.push('任务' + String(task.id) + '「' + String(task.title || '') + '」:主文件=' + summaryList(task.mainFiles) + ';关联文件=' + summaryList(task.relatedFiles) + ';执行组=' + String(task.executionGroup || task.group || '') + ';依赖=' + summaryList(task.dependencies) + ';依赖理由=' + String(task.dependencyReason || '') + ';分组理由=' + String(task.groupReason || '') + ';独占资源=' + summaryList(task.resources))
|
|
72
|
+
lines.push('任务' + String(task.id) + '修改=' + summaryList(task.modifications) + ';自检=' + summaryList(task.selfChecks))
|
|
73
|
+
for (const fileRecord of Array.isArray(task.fileRecords) ? task.fileRecords : []) {
|
|
74
|
+
lines.push('任务' + String(task.id) + '文件=' + String(fileRecord.path || '') + ';操作=' + String(fileRecord.operation || '') + ';角色=' + String(fileRecord.role || ''))
|
|
75
|
+
for (const point of Array.isArray(fileRecord.points) ? fileRecord.points : []) {
|
|
76
|
+
lines.push('任务' + String(task.id) + '文件点=' + String(fileRecord.path || '') + '#' + String(point.id || '') + ';操作=' + String(fileRecord.operation || '') + ';修改位置=' + String(point.modificationLocation || '') + ';锚点=' + String(point.anchor || ''))
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
for (const fileRecord of Array.isArray(task.acceptanceFileRecords) ? task.acceptanceFileRecords : []) {
|
|
80
|
+
for (const point of Array.isArray(fileRecord.points) ? fileRecord.points : []) {
|
|
81
|
+
lines.push('任务' + String(task.id) + '验收点=' + String(fileRecord.path || '') + '#' + String(point.id || '') + ';验收定位=' + String(point.acceptanceLocation || '') + ';客观期望=' + summaryList(point.expectations))
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
for (const group of Array.isArray(value.groups) ? value.groups : []) {
|
|
86
|
+
lines.push('执行组' + String(group.id || group.group || '') + ':成员=' + summaryList(group.members) + ';内部顺序=' + summaryList(group.internalOrder) + ';组外依赖=' + summaryList(group.groupDependsOn || group.externalDependencies) + ';initialState=' + String(group.initialState || '') + ';静态资格=' + String(group.staticEligibility || ''))
|
|
87
|
+
}
|
|
88
|
+
for (const check of Array.isArray(value.checks) ? value.checks : []) {
|
|
89
|
+
const coverage = check.coverage || {}
|
|
90
|
+
lines.push('检查' + String(check.id) + '「' + String(check.title || '') + '」:验收组=' + String(check.reviewGroup || '') + ';取证=' + String(check.evidenceMode || '') + ';目录=' + String(check.workdir || '') + ';覆盖任务=' + summaryList(coverage.tasks) + ';覆盖收尾=' + summaryBool(coverage.closure) + ';覆盖全局=' + summaryBool(coverage.global) + ';独占资源=' + summaryList(check.resources))
|
|
91
|
+
lines.push('检查' + String(check.id) + '动作=' + summaryList(check.checks) + ';证据=' + summaryList(check.evidence))
|
|
92
|
+
}
|
|
93
|
+
for (const group of Array.isArray(value.reviewGroups) ? value.reviewGroups : []) {
|
|
94
|
+
const coverage = group.coverage || {}
|
|
95
|
+
lines.push('验收组' + String(group.id || group.reviewGroup || '') + ':检查顺序=' + summaryList(group.checks) + ';覆盖任务=' + summaryList(coverage.tasks) + ';覆盖收尾=' + summaryBool(coverage.closure) + ';覆盖全局=' + summaryBool(coverage.global))
|
|
96
|
+
}
|
|
97
|
+
if (value.closure !== null && value.closure !== undefined) {
|
|
98
|
+
lines.push('收尾:文件=' + summaryList(value.closure.files) + ';依赖=' + summaryList(value.closure.dependencies) + ';正式验收=' + summaryList(value.closure.checkRefs) + ';coverageKey=' + String(value.closure.coverageKey || 'closure'))
|
|
99
|
+
for (const fileRecord of Array.isArray(value.closure.fileRecords) ? value.closure.fileRecords : []) {
|
|
100
|
+
lines.push('收尾文件点=' + String(fileRecord.path || '') + ';操作=' + String(fileRecord.operation || '') + ';角色=' + String(fileRecord.role || ''))
|
|
101
|
+
for (const point of Array.isArray(fileRecord.points) ? fileRecord.points : []) {
|
|
102
|
+
lines.push('收尾文件点=' + String(fileRecord.path || '') + '#' + String(point.id || '') + ';操作=' + String(fileRecord.operation || '') + ';修改位置=' + String(point.modificationLocation || '') + ';锚点=' + String(point.anchor || ''))
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
for (const fileRecord of Array.isArray(value.closure.acceptanceFileRecords) ? value.closure.acceptanceFileRecords : []) {
|
|
106
|
+
for (const point of Array.isArray(fileRecord.points) ? fileRecord.points : []) {
|
|
107
|
+
lines.push('收尾验收点=' + String(fileRecord.path || '') + '#' + String(point.id || '') + ';验收定位=' + String(point.acceptanceLocation || '') + ';客观期望=' + summaryList(point.expectations))
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
} else {
|
|
111
|
+
lines.push('收尾:无')
|
|
112
|
+
}
|
|
113
|
+
if (value.globalAcceptance !== null && value.globalAcceptance !== undefined) {
|
|
114
|
+
lines.push('全局验收:正式验收=' + summaryList(value.globalAcceptance.checkRefs) + ';coverageKey=' + String(value.globalAcceptance.coverageKey || 'global'))
|
|
115
|
+
} else {
|
|
116
|
+
lines.push('全局验收:无')
|
|
117
|
+
}
|
|
118
|
+
lines.push('职责:工具只校验并在单次调用内写入/发布;失败由本次调用有限清理并报错,主会话负责派遣、冻结与正式验收,工具不启动代理、不执行检查命令、不维护运行状态机。')
|
|
119
|
+
return lines.join('\n')
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// save_plan 结果的模型可见内容(v0.1.3 修复):output.render 契约必须返回
|
|
123
|
+
// ContentBlock[](宿主第一方工具均如此,见 dsh-tool-pwsh L355),不能返回裸
|
|
124
|
+
// 字符串——否则 DeepSeek 适配器 serializeMessages 的 flattenText 会对字符串调
|
|
125
|
+
// .filter 抛 TypeError,被外层包装成 TRANSPORT、重试 3 连败(毫秒级),表现为
|
|
126
|
+
// "save_plan 后子代理必死"。此函数导出供场景测试锁死契约。
|
|
127
|
+
export function renderSavePlan(value) {
|
|
128
|
+
const paths = value !== null && typeof value === 'object' && Array.isArray(value.paths) ? value.paths : []
|
|
129
|
+
return [{ type: 'text', text: paths.map((path) => String(path)).join('\n') }]
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// save_probe 数值限制的唯一现行来源;测试通过导出对象断言,文档只链接此符号,不复制运行时限制表。
|
|
133
|
+
// 条目数、单条长度与总量等限制均由 PROBE_LIMITS 统一提供,改动时保持实现、测试和文档同源。
|
|
134
|
+
export const PROBE_LIMITS = {
|
|
135
|
+
maxEntries: { // 各类集合/数组的最大条目数配置
|
|
136
|
+
fileMap: 50, // 文件映射表,例如 路径 -> 文件信息
|
|
137
|
+
focusAreas: 50, // 重点关注区域/重点模块
|
|
138
|
+
exclusions: 20, // 排除项,例如排除文件、目录、规则
|
|
139
|
+
background: 20, // 背景信息/上下文条目
|
|
140
|
+
},
|
|
141
|
+
maxPathLen: 1024, // 文件路径或目录路径最大长度
|
|
142
|
+
maxRangeLen: 20, // 范围字符串最大长度,例如 "L10-L20"、"123-456"
|
|
143
|
+
maxRelationLen: 400, // 关系描述最大长度,例如依赖、调用、关联关系
|
|
144
|
+
maxNoteLen: 400, // 备注/注释最大长度
|
|
145
|
+
maxTopicLen: 120, // 主题/标题最大长度
|
|
146
|
+
maxDetailLen: 1000, // 详细说明最大长度
|
|
147
|
+
maxTotalChars: 20000, // 四字段探测内容 JSON 序列化 .length 上限(不含 evidence)
|
|
148
|
+
rangePattern: '^L?0*[1-9]\\d*(?:-0*[1-9]\\d*)?$', // 范围格式正则:端点从 1 开始,匹配 123、L123、123-456、L123-456;L 可能表示 Line
|
|
149
|
+
maxEvidenceEntries: 150, // 证据条目最大数量
|
|
150
|
+
maxEvidenceLineLen: 20, // 证据行号字符串最大长度,例如 "L123"
|
|
151
|
+
maxEvidenceValueLen: 240, // 证据 value 字段最大长度
|
|
152
|
+
maxEvidenceTextLen: 1000, // 证据正文/文本内容最大长度
|
|
153
|
+
maxEvidenceNoteLen: 400, // 证据备注最大长度
|
|
154
|
+
maxEvidenceTotalChars: 32000, // 所有证据内容总字符数上限
|
|
155
|
+
evidenceLinePattern: '^L?0*[1-9]\\d*$', // 证据行号格式正则:端点从 1 开始,匹配 123 或 L123,不支持范围
|
|
156
|
+
maxTaskNameLen: 32, // 任务名称最大长度
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// line/range 格式提示统一文案(描述与报错共用;格式正则本体见 PROBE_LIMITS)。
|
|
160
|
+
export const LINE_FORMAT_HINT = '仅接受从 1 开始的单个行号(12 或 L12),禁止区间(如 L158-162),区间信息请写入 evidence.text 并取代表性行号'
|
|
161
|
+
export const RANGE_FORMAT_HINT = '仅 focusAreas.range 允许从 1 开始的区间(12 或 L12-34)'
|
|
162
|
+
|
|
163
|
+
// 线索/证据报告 Markdown 渲染(模板固定):标题 + 卷首声明 + 四节;evidence 非空时
|
|
164
|
+
// 标题/卷首切换为证据报告语义并追加「## 五、证据」节。导出供测试核对内容契约。
|
|
165
|
+
export function renderProbeMarkdown(args) {
|
|
166
|
+
const hasEvidence = Array.isArray(args.evidence) && args.evidence.length > 0
|
|
167
|
+
const lines = []
|
|
168
|
+
lines.push(hasEvidence ? '# 探查证据报告(探查者 save_probe 落盘)' : '# 探查线索(save_probe 落盘,非结论)')
|
|
169
|
+
lines.push('')
|
|
170
|
+
if (hasEvidence) {
|
|
171
|
+
lines.push('> 本文件为探查者已核实的证据报告:行号/数值/文案照实记录,可被规划子代理作为【探查者已核实】证据引用(引用时在方案中注明「证据来源:本文件路径」)')
|
|
172
|
+
} else {
|
|
173
|
+
lines.push('> 本文件只有定位线索、没有证据;不得引用本文件的行号/数值/文案作为【已探查核实】证据——证据须由规划子代理自行 read/glob/grep 核实')
|
|
174
|
+
}
|
|
175
|
+
lines.push('')
|
|
176
|
+
lines.push('## 一、文件地图')
|
|
177
|
+
for (const item of args.fileMap) lines.push(`- ${item.path}:${item.relation}`)
|
|
178
|
+
lines.push('')
|
|
179
|
+
lines.push('## 二、重点区域')
|
|
180
|
+
for (const item of args.focusAreas) {
|
|
181
|
+
lines.push(item.range !== undefined && item.range !== null && item.range !== '' ? `- ${item.path}(${item.range}):${item.note}` : `- ${item.path}:${item.note}`)
|
|
182
|
+
}
|
|
183
|
+
lines.push('')
|
|
184
|
+
lines.push('## 三、排除项')
|
|
185
|
+
for (const item of args.exclusions) {
|
|
186
|
+
lines.push(item.scope !== undefined && item.scope !== null && item.scope !== '' ? `- ${item.scope}:${item.note}` : `- (未指明范围):${item.note}`)
|
|
187
|
+
}
|
|
188
|
+
lines.push('')
|
|
189
|
+
lines.push('## 四、背景与意图')
|
|
190
|
+
for (const item of args.background) lines.push(`- ${item.topic}:${item.detail}`)
|
|
191
|
+
lines.push('')
|
|
192
|
+
if (hasEvidence) {
|
|
193
|
+
lines.push('## 五、证据')
|
|
194
|
+
for (const item of args.evidence) {
|
|
195
|
+
let line = `- ${item.path}`
|
|
196
|
+
if (item.line !== undefined && item.line !== null && item.line !== '') line += `(${item.line})`
|
|
197
|
+
line += ':'
|
|
198
|
+
if (item.value !== undefined && item.value !== null && item.value !== '') line += item.value
|
|
199
|
+
if (item.text !== undefined && item.text !== null && item.text !== '') line += `|${item.text}`
|
|
200
|
+
if (item.note !== undefined && item.note !== null && item.note !== '') line += `|${item.note}`
|
|
201
|
+
lines.push(line)
|
|
202
|
+
}
|
|
203
|
+
lines.push('')
|
|
204
|
+
}
|
|
205
|
+
return lines.join('\n')
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// 从【探查者已核实】标记提取证据文件路径;调用方与测试共用这个纯 helper。
|
|
209
|
+
// 捕获引用兼容「证据:<path>」和「证据来源:<path>」;装饰清洗不包含 . 或 /,因此路径语法保持不变。
|
|
210
|
+
const PROBE_EVIDENCE_RE = /【探查者已核实】[^\n]*?证据(?:来源)?[::]\s*([^\s,。;)】\n]+)/g
|
|
211
|
+
// 多个引用只按 、 ; ; | 拆分;空格已由捕获正则排除,半角逗号仍属于合法路径而不是分隔符。
|
|
212
|
+
// 后续 trimProbeEvidenceDecor 只清洗成对外层装饰,单侧装饰保留,避免误改文件名。
|
|
213
|
+
const PROBE_EVIDENCE_SPLIT_RE = /[、;;|]+/
|
|
214
|
+
// 成对装饰映射:开字符 → 对应闭字符(自配对字符首尾相同)。与上方一致**不含** `.` 与 `/`。
|
|
215
|
+
const PROBE_EVIDENCE_DECOR_PAIRS = {
|
|
216
|
+
'`': '`',
|
|
217
|
+
'*': '*',
|
|
218
|
+
_: '_',
|
|
219
|
+
'"': '"',
|
|
220
|
+
"'": "'",
|
|
221
|
+
'(': ')',
|
|
222
|
+
'[': ']',
|
|
223
|
+
'<': '>',
|
|
224
|
+
'(': ')',
|
|
225
|
+
'「': '」',
|
|
226
|
+
'『': '』',
|
|
227
|
+
'【': '】',
|
|
228
|
+
'《': '》',
|
|
229
|
+
}
|
|
230
|
+
// 反复剥除成对的外层装饰;必须匹配对应闭字符,且内部不能再出现该闭字符。
|
|
231
|
+
// 单侧装饰保留,仅 trim 外围空白;这样路径自身的首尾字符不会被误删。
|
|
232
|
+
function trimProbeEvidenceDecor(segment) {
|
|
233
|
+
let s = segment.trim()
|
|
234
|
+
for (;;) {
|
|
235
|
+
if (s.length < 2) break
|
|
236
|
+
const close = PROBE_EVIDENCE_DECOR_PAIRS[s[0]]
|
|
237
|
+
if (close === undefined || s[s.length - 1] !== close) break
|
|
238
|
+
const inner = s.slice(1, -1)
|
|
239
|
+
if (inner.includes(close)) break
|
|
240
|
+
s = inner.trim()
|
|
241
|
+
}
|
|
242
|
+
return s
|
|
243
|
+
}
|
|
244
|
+
export function extractProbeEvidenceRefs(plan) {
|
|
245
|
+
if (typeof plan !== 'string' || plan === '') return []
|
|
246
|
+
const refs = []
|
|
247
|
+
for (const m of plan.matchAll(PROBE_EVIDENCE_RE)) {
|
|
248
|
+
// 处理顺序固定:整体成对剥除(循环)→ 按拆分符拆分 → 每段成对剥除 + trim
|
|
249
|
+
// → 过滤空串 → 按出现顺序去重(step-00 E10-E12 覆盖单侧不剥与成对剥除)。
|
|
250
|
+
const wrapped = trimProbeEvidenceDecor(m[1])
|
|
251
|
+
for (const segment of wrapped.split(PROBE_EVIDENCE_SPLIT_RE)) {
|
|
252
|
+
const p = trimProbeEvidenceDecor(segment)
|
|
253
|
+
if (p !== '' && !refs.includes(p)) refs.push(p)
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
return refs
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// save_probe 结果的模型可见内容(与 renderSavePlan 同契约:ContentBlock[])。
|
|
260
|
+
// hasEvidence 二参由 output.render 传入(args.evidence 非空);缺省走线索文案。
|
|
261
|
+
export function renderSaveProbe(value, hasEvidence) {
|
|
262
|
+
return [{ type: 'text', text: (hasEvidence === true ? '探查证据报告已落盘:\n- ' : '探查线索已落盘:\n- ') + value.path }]
|
|
263
|
+
}
|