focus-guard 3.5.2 → 3.5.4
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/README.md +15 -3
- package/README.zh-CN.md +14 -4
- package/assets/NOTICE.md +3 -1
- package/docs/ARCH-MAP.md +302 -74
- package/docs/BENCH.md +28 -13
- package/docs/RELEASE-POLICY.md +74 -17
- package/docs/RULES.md +98 -60
- package/docs/THREAT-MODEL.md +3 -3
- package/docs/WRITING-STYLE.md +40 -2
- package/package.json +11 -5
- package/skills/focus-plan/SKILL.md +77 -0
- package/skills/focus-rules/SKILL.md +267 -0
- package/skills/focus-thinking/SKILL.md +8 -255
- package/src/adapters/dsh/eligibility-gate.mjs +75 -35
- package/src/adapters/dsh/session.mjs +22 -0
- package/src/{dsh → adapters/dsh}/toolName.mjs +6 -0
- package/src/core/approvals.mjs +10 -4
- package/src/core/audit-writer.mjs +5 -2
- package/src/core/auditActions.mjs +214 -0
- package/src/core/checkEligibility.mjs +193 -130
- package/src/core/constants.mjs +8 -4
- package/src/core/decisionEngine.mjs +16 -13
- package/src/core/env.mjs +37 -2
- package/src/core/patterns.mjs +3 -1
- package/src/core/prefixStability.mjs +27 -3
- package/src/core/profileLoader.mjs +96 -3
- package/src/core/scratch.mjs +288 -0
- package/src/core/session.mjs +23 -0
- package/src/core/state.mjs +3 -3
- package/src/dsh/audit.mjs +45 -170
- package/src/dsh/bridgeCheck.mjs +81 -0
- package/src/dsh/compactionWatch/announce.mjs +2 -1
- package/src/dsh/compactionWatch.mjs +2 -1
- package/src/dsh/cost-ledger.mjs +174 -0
- package/src/dsh/guard/authz.mjs +3 -3
- package/src/dsh/guard/evidence.mjs +19 -0
- package/src/dsh/guard/retryGuard.mjs +96 -0
- package/src/dsh/guard/risk.mjs +61 -16
- package/src/dsh/guard/tooling.mjs +20 -13
- package/src/dsh/{value-gate.mjs → guard/value-gate.mjs} +6 -0
- package/src/dsh/guard/writing-gate.mjs +117 -0
- package/src/dsh/index.js +4 -7
- package/src/dsh/pipeline.mjs +72 -8
- package/src/dsh/postProgress.mjs +81 -40
- package/src/dsh/preGuard.mjs +12 -3
- package/src/dsh/repeatGuard.mjs +5 -4
- package/src/dsh/seams/pre-step.mjs +74 -23
- package/src/dsh/seams/prompt-rules.mjs +91 -5
- package/src/dsh/{guard → seams}/runtime.mjs +41 -10
- package/src/dsh/seams/session-start.mjs +33 -10
- package/src/dsh/seams/shared.mjs +8 -5
- package/src/dsh/search-hints.mjs +15 -1
- package/src/dsh/sessionScope.mjs +11 -11
- package/src/dsh/stopGuard.mjs +2 -7
- package/src/dsh/tools.mjs +39 -1
- package/src/dsh/traceMeta.mjs +5 -11
- package/src/memory/index.mjs +7 -5
- package/src/memory/workspace.mjs +41 -19
- package/src/profiles/deepseek-flash.mjs +10 -8
- package/src/profiles/deepseek-pro.mjs +9 -8
- package/src/profiles/default.mjs +14 -8
- package/src/profiles/glm.mjs +9 -8
- package/src/profiles/gpt-astra.mjs +11 -9
- package/tools/audit-chain.mjs +29 -4
- package/tools/collect-panel.mjs +3 -24
- package/tools/dead-export.mjs +2 -17
- package/tools/docs-book.mjs +234 -0
- package/tools/docs-drift.mjs +143 -0
- package/tools/docs-lint.mjs +76 -9
- package/tools/docs-refs.mjs +343 -0
- package/tools/gate-audit.mjs +3 -24
- package/tools/handoff.mjs +4 -2
- package/tools/index-stale.mjs +124 -0
- package/tools/install-check.mjs +107 -9
- package/tools/knowledge.mjs +53 -4
- package/tools/layering-audit.mjs +7 -1
- package/tools/legacy-audit.mjs +83 -0
- package/tools/lib/book-style.mjs +42 -1
- package/tools/lib/case-tool.mjs +9 -3
- package/tools/lib/cli.mjs +35 -0
- package/tools/lib/docs-ack.mjs +97 -0
- package/tools/lib/docs-core.mjs +84 -45
- package/tools/lib/docs-files.mjs +73 -0
- package/tools/lib/docs-scope.mjs +46 -0
- package/tools/lib/docs-status.mjs +148 -0
- package/tools/lib/docs-typography.mjs +91 -0
- package/tools/lib/docs-version.mjs +8 -5
- package/tools/lib/dup-block.mjs +117 -0
- package/tools/lib/idioms.mjs +149 -0
- package/tools/lib/import-graph.mjs +8 -3
- package/tools/lib/index-io.mjs +4 -4
- package/tools/lib/index-registry.mjs +101 -0
- package/tools/lib/legacy-core.mjs +178 -0
- package/tools/lib/markdown.mjs +202 -0
- package/tools/lib/modules-doc.mjs +103 -0
- package/tools/lib/modules-list.mjs +396 -0
- package/tools/lib/modules.mjs +360 -0
- package/tools/lib/mutation-ops.mjs +63 -0
- package/tools/lib/parse-block.mjs +58 -0
- package/tools/lib/prefix-cost.mjs +5 -3
- package/tools/lib/ratchet.mjs +22 -8
- package/tools/lib/release-faces.mjs +144 -0
- package/tools/lib/repo-copy.mjs +34 -0
- package/tools/lib/survey-report.mjs +57 -0
- package/tools/lib/where.mjs +139 -0
- package/tools/library-book.mjs +7 -92
- package/tools/library-build.mjs +15 -3
- package/tools/lint.mjs +24 -13
- package/tools/log-audit.mjs +76 -0
- package/tools/memory-audit.mjs +32 -6
- package/tools/memory-distill.mjs +14 -1
- package/tools/memory-recall-eval.mjs +408 -0
- package/tools/module-audit.mjs +2 -17
- package/tools/modules-audit.mjs +110 -0
- package/tools/mutate.mjs +120 -74
- package/tools/panel-baseline.mjs +172 -0
- package/tools/prefix-audit.mjs +10 -2
- package/tools/prefix-drift.mjs +10 -5
- package/tools/registry-check.mjs +200 -0
- package/tools/release.mjs +322 -0
- package/tools/smells.mjs +97 -139
- package/tools/version.mjs +12 -8
- package/docs/AB-PROMPTS.md +0 -123
- package/docs/AB-SESSION.md +0 -161
- package/docs/BENCH-BASELINE.json +0 -95
- package/docs/BRAIN-VIZ.md +0 -94
- package/docs/GATE-INPUTS.json +0 -10
- package/docs/HANDOFF-2026-10-27.md +0 -736
- package/docs/HOOK-ORDERING.md +0 -139
- package/docs/LEGISLATION-LAW.md +0 -104
- package/docs/MCP-4.0-PLAN.md +0 -184
- package/docs/MEMORY-4.5-PLAN.md +0 -415
- package/docs/PROFILE-TUNING.md +0 -147
- package/docs/RATCHET.json +0 -80
- package/docs/TOOL-SCHEMA.json +0 -6
- package/docs/VERSION-PLAN.md +0 -604
- package/docs/architecture-map.mermaid +0 -186
- package/docs/deepseek-pricing-audit.md +0 -65
- package/src/core/staleCleanup.mjs +0 -224
- package/src/dsh/guard/superpowers.mjs +0 -70
- package/src/dsh/workspace.mjs +0 -5
- package/tools/library-index.mjs +0 -91
package/src/dsh/postProgress.mjs
CHANGED
|
@@ -30,12 +30,15 @@ import { statSync } from 'node:fs'
|
|
|
30
30
|
import { statePath as guardStateFile, loadState, saveState, fingerprint, gitDirty, casePath, loadCaseRecords, saveCaseRecords } from '../core/state.mjs'
|
|
31
31
|
import { auditChainInit } from '../core/audit.mjs'
|
|
32
32
|
import { collectStrings, callHash, isInvestigation } from '../core/risk.mjs'
|
|
33
|
-
import { zcodeToolName } from '
|
|
33
|
+
import { zcodeToolName } from '../adapters/dsh/toolName.mjs'
|
|
34
34
|
import { isDangerousCmd, SCRIPT_FILE_RE } from '../core/redlines.mjs'
|
|
35
35
|
import { appendAudit, buildAuditRow } from './audit.mjs'
|
|
36
36
|
import { normalizePath as normalize, projDirOf, sidOf } from './sessionScope.mjs'
|
|
37
|
+
import { noteNativeRead } from './guard/evidence.mjs'
|
|
37
38
|
import { gateSwitch } from './testRuntime.mjs'
|
|
38
39
|
import { budgetVerdict, stallVerdict, invPoolOverLimit, judgeProgress, poolOf } from '../core/progressPolicy.mjs'
|
|
40
|
+
import { loadProfile, governanceLimitsOf } from '../core/profileLoader.mjs'
|
|
41
|
+
import { modelIdOf } from './guard/tooling.mjs'
|
|
39
42
|
import {
|
|
40
43
|
BLOCKS_RE,
|
|
41
44
|
BUDGET_CAP,
|
|
@@ -102,6 +105,11 @@ function trackReadSet(ctx) {
|
|
|
102
105
|
if (isFail) return
|
|
103
106
|
state.readSet = state.readSet || {}
|
|
104
107
|
if (ti.file_path && (RE_READ.test(tool) || RE_WRITE.test(tool))) state.readSet[normalize(ti.file_path)] = 1
|
|
108
|
+
// 2026-11-28:**同时**记进内存 Set。此前只写状态文件,而查证侧(`isReadRecorded`)
|
|
109
|
+
// 先查内存、再查状态;状态读不出来时「读过」就凭空消失。两处 key 一律由 evidenceKeyOf 算。
|
|
110
|
+
if (ti.file_path && (RE_READ.test(tool) || RE_WRITE.test(tool) || RE_GREP.test(tool))) {
|
|
111
|
+
noteNativeRead(exec, ti.file_path)
|
|
112
|
+
}
|
|
105
113
|
if (RE_WRITE.test(tool) && ti.file_path && SCRIPT_FILE_RE.test(String(ti.file_path))) {
|
|
106
114
|
state.scriptFiles = state.scriptFiles || {}
|
|
107
115
|
const body = String(ti.content ?? '') + String(ti.old_string ?? '') + String(ti.new_string ?? '')
|
|
@@ -154,6 +162,10 @@ function trackReadSet(ctx) {
|
|
|
154
162
|
* 写审计、给提示。行为细节(刻意保留原语义):
|
|
155
163
|
* - 侦查池超限会**覆盖**同一次调用里已产生的续杯/熔断 reason——原实现如此,未改;
|
|
156
164
|
* - 工具失败(`isFail`)时 `progress` 恒为 false,走停滞分支,因此失败也计入 `ineffCalls`。
|
|
165
|
+
*
|
|
166
|
+
* 2026-11-29(T9):阈值不再取常量,取 `ctx.limits`——由 `loadProfile(modelIdOf(exec))`
|
|
167
|
+
* 经 `governanceLimitsOf` 解析,常量只是兜底。此前这两个字段在画像里写了两个月,
|
|
168
|
+
* 全仓零读取点,改画像不会改变任何行为,也不会有测试变红。
|
|
157
169
|
*/
|
|
158
170
|
/** 进度判定:失败调用不算进度;签名(响应前 1500 字 + 入参哈希)变化即算。 */
|
|
159
171
|
function detectProgress({ tool, ti, isFail, state, respText }) {
|
|
@@ -172,8 +184,32 @@ function detectProgress({ tool, ti, isFail, state, respText }) {
|
|
|
172
184
|
return progress
|
|
173
185
|
}
|
|
174
186
|
|
|
187
|
+
/** 阈值来源的可读标注:审计里必须看得出这个数来自画像还是常量,否则下次仍然查不到。 */
|
|
188
|
+
function limitWhy(slot, profile) {
|
|
189
|
+
if (slot.source === 'const') return '常量兜底'
|
|
190
|
+
const id = String((profile && profile.id) || 'default')
|
|
191
|
+
if (!slot.source.startsWith('profile:clamped')) return `画像 ${id}`
|
|
192
|
+
const raw = slot.source.slice(slot.source.indexOf('(') + 1, -1)
|
|
193
|
+
return `画像 ${id}(夹取自 ${raw})`
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* 熔断跃迁点记账(2026-10-27 修掉的重复记账,现在两处熔断共用)。
|
|
198
|
+
*
|
|
199
|
+
* 病根:判据是「计数 ≥ 阈值」,一旦越线就永远成立——原来每次调用都再写一条 `stall-fuse`,
|
|
200
|
+
* 实测同一会话写了 61 条「有效调用达 200」而真实熔断只有 1 次;停滞侧更狠,一秒内写了 17 条。
|
|
201
|
+
* 只在「未熔断 → 熔断」的跃迁点留痕,重复期间静默。返回是否本次首次熔断。
|
|
202
|
+
*/
|
|
203
|
+
function fuseOnce(state, sid, evidence) {
|
|
204
|
+
const firstFuse = !state.fused
|
|
205
|
+
state.fused = true
|
|
206
|
+
state.violations = Math.max(state.violations || 0, 3)
|
|
207
|
+
if (firstFuse) audit(sid, 'stall-fuse', { level: 3, evidence })
|
|
208
|
+
return firstFuse
|
|
209
|
+
}
|
|
210
|
+
|
|
175
211
|
function judgeBudgetPools(ctx) {
|
|
176
|
-
const { sid, tool, ti, isFail, state, inv, respText, guardDeny } = ctx
|
|
212
|
+
const { sid, tool, ti, isFail, state, inv, respText, guardDeny, limits } = ctx
|
|
177
213
|
// 2026-10-28(熔断太容易):闸门拒绝不是"模型空转"——它是**判定生效**。
|
|
178
214
|
// 原实现把 deny 当失败 → 无 progress → stalledStreak+1,连改 3 个被拦文件就熔断。
|
|
179
215
|
// 被拒调用对进度与停滞都记中性(不 += 也不清零),由 repeatGuard 的换法提示负责纠偏。
|
|
@@ -188,31 +224,38 @@ function judgeBudgetPools(ctx) {
|
|
|
188
224
|
if (pool === 'investigate') state.invCalls = (state.invCalls || 0) + 1
|
|
189
225
|
else if (pool === 'execute') state.effectiveCalls = (state.effectiveCalls || 0) + 1
|
|
190
226
|
// 判定来自母版 `core/progressPolicy.mjs`(阶段 2):本文件只做落状态 + 审计 + 提示。
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
//
|
|
199
|
-
//
|
|
200
|
-
//
|
|
201
|
-
|
|
202
|
-
const
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
state.taskBudget = budget.nextBudget
|
|
211
|
-
audit(sid, 'budget-extend', {
|
|
212
|
-
level: null,
|
|
213
|
-
evidence: `自动续杯 budget=${state.taskBudget} eff=${state.effectiveCalls} stall=0`,
|
|
227
|
+
// 上限取画像 `budgetGate.ceiling`(T11),常量 BUDGET_CAP 只在画像缺字段时兜底。
|
|
228
|
+
// 注意是包裹而非提前 return:后面的侦查池提醒与预算无关,不能被预算开关顺带关掉。
|
|
229
|
+
if (limits.budget.enabled) {
|
|
230
|
+
// 熔断线 = max(画像 ceiling, 显式额度 taskBudget)。两条线各管各的,不互相覆盖:
|
|
231
|
+
// ceiling 管「**自动续杯**能长到多高」——系统自己发额度,上限由画像定;
|
|
232
|
+
// taskBudget 管「显式额度」——【任务规模】声明与『追加额度』批示抬高它。
|
|
233
|
+
// 反过来取 min 会让画像架空显式授权:批了 200 次却在第 100 次熔断。
|
|
234
|
+
// 注意 taskBudget 的**来源无法在算法上分辨**:pre-step 的关键词档位与 stop 的【任务规模】
|
|
235
|
+
// 声明都会抬高它,后者出自模型自己的收尾文本(stopGuard.applyTaskScale),因此审计写
|
|
236
|
+
// 「声明额度」而不是「人类批示」——见 docs/PROFILE-TUNING.md T13 的遗留风险。
|
|
237
|
+
const declared = Math.max(0, state.taskBudget || BUDGET_DEFAULT)
|
|
238
|
+
const profileCap = limits.budget.value
|
|
239
|
+
const cap = Math.max(profileCap, declared)
|
|
240
|
+
const capWhy = declared > profileCap ? `声明额度 ${declared} 覆盖画像 ${profileCap}` : limitWhy(limits.budget, ctx.profile)
|
|
241
|
+
const budget = budgetVerdict({
|
|
242
|
+
effectiveCalls: state.effectiveCalls || 0,
|
|
243
|
+
taskBudget: declared,
|
|
244
|
+
cap,
|
|
245
|
+
refill: REFILL,
|
|
214
246
|
})
|
|
215
|
-
|
|
247
|
+
if (budget.kind === 'fuse') {
|
|
248
|
+
if (fuseOnce(state, sid, `硬上限:有效调用达 ${cap}(${capWhy})`)) {
|
|
249
|
+
reason = `[触发④·L3]硬上限 ${cap} 次,强制熔断。输出『${FUSE_PHRASE}』+三行降级方案,等批示。`
|
|
250
|
+
}
|
|
251
|
+
} else if (budget.kind === 'refill') {
|
|
252
|
+
state.taskBudget = budget.nextBudget
|
|
253
|
+
audit(sid, 'budget-extend', {
|
|
254
|
+
level: null,
|
|
255
|
+
evidence: `自动续杯 budget=${state.taskBudget} eff=${state.effectiveCalls} stall=0(上限 ${cap}/${capWhy})`,
|
|
256
|
+
})
|
|
257
|
+
reason = `[触发④]续杯:执行池 ${state.effectiveCalls} 次达阈值,预算+${REFILL}→${state.taskBudget}。任务继续,自查是否收敛。`
|
|
258
|
+
}
|
|
216
259
|
}
|
|
217
260
|
if (inv && !state.invWarned && invPoolOverLimit({ invCalls: state.invCalls || 0, invCap: state.invCap || INV_POOL_DEFAULT })) {
|
|
218
261
|
state.invWarned = true
|
|
@@ -225,21 +268,14 @@ function judgeBudgetPools(ctx) {
|
|
|
225
268
|
} else {
|
|
226
269
|
state.stalledStreak = (state.stalledStreak || 0) + 1
|
|
227
270
|
state.ineffCalls = (state.ineffCalls || 0) + 1
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
state.fused = true
|
|
234
|
-
state.violations = Math.max(state.violations || 0, 3)
|
|
235
|
-
if (firstFuse) {
|
|
236
|
-
audit(sid, 'stall-fuse', {
|
|
237
|
-
level: 3,
|
|
238
|
-
evidence: `连续 ${state.stalledStreak} 次无效调用 eff=${state.effectiveCalls || 0}`,
|
|
239
|
-
})
|
|
271
|
+
// 阈值取画像 `stalledFuse.threshold`(T10);`enabled:false` 的画像(gpt-astra)到此不再判熔断。
|
|
272
|
+
const stallThreshold = limits.stall.value
|
|
273
|
+
if (limits.stall.enabled && stallVerdict({ stalledStreak: state.stalledStreak || 0, threshold: stallThreshold }).fuse) {
|
|
274
|
+
const why = `连续 ${state.stalledStreak} 次无效调用 eff=${state.effectiveCalls || 0} 阈值=${stallThreshold}(${limitWhy(limits.stall, ctx.profile)})`
|
|
275
|
+
if (fuseOnce(state, sid, why)) {
|
|
240
276
|
reason = `[触发④·L3]真失控:连续 ${state.stalledStreak} 次无效调用。停止探索,输出『${FUSE_PHRASE}』+三行降级方案,或等批示。`
|
|
241
277
|
}
|
|
242
|
-
} else if ((state.stalledStreak || 0) ===
|
|
278
|
+
} else if (limits.stall.enabled && (state.stalledStreak || 0) === stallThreshold - 1) {
|
|
243
279
|
audit(sid, 'stall-warning', {
|
|
244
280
|
level: null,
|
|
245
281
|
evidence: `停滞 ${state.stalledStreak} 次 eff=${state.effectiveCalls || 0}`,
|
|
@@ -463,7 +499,12 @@ export function postProgressListener({ warn } = {}) {
|
|
|
463
499
|
// 执行池被只读调用提前耗尽(2026-10-10 由批 5 的用例连带抓出本批缺陷)。
|
|
464
500
|
const inv = isInvestigation(zcodeToolName(tool), ti)
|
|
465
501
|
|
|
466
|
-
|
|
502
|
+
// 画像 → 治理阈值(T9 接线)。取不到 modelId 时 loadProfile(null) 落 default:
|
|
503
|
+
// 那是最严兜底,也是本文件 2026-11-29 之前恒定的行为,故「拿不到模型」不会放松任何东西。
|
|
504
|
+
const profile = loadProfile(modelIdOf(exec))
|
|
505
|
+
const limits = governanceLimitsOf(profile, { stallThreshold: STALL_FUSE, budgetCeiling: BUDGET_CAP })
|
|
506
|
+
|
|
507
|
+
const ctx = { exec, sid, tool, ti, isFail, guardDeny, state, respText, respProbe, inv, profile, limits }
|
|
467
508
|
|
|
468
509
|
settleForcedInvestigate(ctx)
|
|
469
510
|
trackReadSet(ctx)
|
package/src/dsh/preGuard.mjs
CHANGED
|
@@ -21,11 +21,11 @@ import { dirname, basename } from 'node:path'
|
|
|
21
21
|
import { readdirSync } from 'node:fs'
|
|
22
22
|
import { statePath as guardStateFile, loadState, saveState, fingerprint, gitDirty, resolveTTL } from '../core/state.mjs'
|
|
23
23
|
import { backupBeforeEdit } from '../core/backup.mjs'
|
|
24
|
-
import { platformBashViolation } from '../core/env.mjs'
|
|
24
|
+
import { platformBashViolation, shellIdForTool } from '../core/env.mjs'
|
|
25
25
|
import { isDangerousCmd } from '../core/redlines.mjs'
|
|
26
26
|
import { isInvestigation, isMutating, penalize } from '../core/risk.mjs'
|
|
27
27
|
import '../adapters/dsh/tool-kinds.mjs' // 分层纪律:宿主工具名在适配层注册成语义类别
|
|
28
|
-
import { zcodeToolName } from '
|
|
28
|
+
import { zcodeToolName } from '../adapters/dsh/toolName.mjs'
|
|
29
29
|
import { appendAudit, buildAuditRow } from './audit.mjs'
|
|
30
30
|
import { normalizePath as normalize, projDirOf, sidOf } from './sessionScope.mjs'
|
|
31
31
|
import { BLOCKS_RE, DELEGATE_DEFAULT, DOWNGRADE_MSG, LIBRARY_RE } from '../core/constants.mjs'
|
|
@@ -79,10 +79,19 @@ function collectContext(exec) {
|
|
|
79
79
|
search: RE_SEARCH.test(tool),
|
|
80
80
|
file,
|
|
81
81
|
state,
|
|
82
|
-
|
|
82
|
+
// 2026-11-22:执行体按工具判,不按会话判。envCache 是会话级的(常写成 bash),
|
|
83
|
+
// 但本次调用可能是 pwsh 工具——不改就会把合法 cmdlet 判成「bash 里没有」。
|
|
84
|
+
env: withToolShell(state.envCache, tool),
|
|
83
85
|
}
|
|
84
86
|
}
|
|
85
87
|
|
|
88
|
+
/** 用工具名覆盖 env.shellIdKey(不改缓存本身,避免一次 pwsh 调用污染会话指纹)。 */
|
|
89
|
+
function withToolShell(env, tool) {
|
|
90
|
+
const shell = shellIdForTool(tool)
|
|
91
|
+
if (!env || !shell || env.shellIdKey === shell) return env
|
|
92
|
+
return { ...env, shellIdKey: shell }
|
|
93
|
+
}
|
|
94
|
+
|
|
86
95
|
/** ===== 资料分层隔离:静态资料区与派生积木区均不得直写(防自我投毒)===== */
|
|
87
96
|
function checkLibraryWrite({ sid, tool, filePath }) {
|
|
88
97
|
if (!RE_WRITE.test(tool) || !filePath) return null
|
package/src/dsh/repeatGuard.mjs
CHANGED
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
|
|
13
13
|
const MAX_TRACK = 200
|
|
14
14
|
import { detectSearchBackends, retrievalHint } from './search-hints.mjs'
|
|
15
|
+
import { sidOf as sidOfAny } from './sessionScope.mjs'
|
|
15
16
|
const counts = new Map()
|
|
16
17
|
// 会话级被拦总数:≥5 次时给**一次**"先停手"提示(实测被拦后越试越乱)。
|
|
17
18
|
// 2026-10-28:原实现随每次 deny 重复追加,等于每拒一次多付一段提示;改为每会话只一次。
|
|
@@ -19,9 +20,9 @@ const sessionDenies = new Map()
|
|
|
19
20
|
const sessionHinted = new Set()
|
|
20
21
|
const SESSION_HINT_AT = 5
|
|
21
22
|
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
23
|
+
// 会话标识与 audit / grant 同口径:实现只在 sessionScope 一处(此前这里用 '-' 作哨兵,
|
|
24
|
+
// 且漏读 header.id,于是所有会话共用一个桶)。
|
|
25
|
+
const sidOf = (exec) => String(sidOfAny(exec))
|
|
25
26
|
|
|
26
27
|
function keyOf(exec) {
|
|
27
28
|
const tool = String((exec && exec.name) || '')
|
|
@@ -31,7 +32,7 @@ function keyOf(exec) {
|
|
|
31
32
|
} catch {
|
|
32
33
|
args = ''
|
|
33
34
|
}
|
|
34
|
-
const sid = (exec
|
|
35
|
+
const sid = sidOf(exec)
|
|
35
36
|
return `${sid}::${tool}::${args.length > 500 ? args.slice(0, 500) : args}`
|
|
36
37
|
}
|
|
37
38
|
|
|
@@ -51,8 +51,25 @@ export function preStepListener({ warn } = {}) {
|
|
|
51
51
|
}
|
|
52
52
|
const promptText = humanTextOf(messages)
|
|
53
53
|
const short = promptText.trim()
|
|
54
|
-
|
|
55
|
-
|
|
54
|
+
// 换回合判定**提前**算:残留核验与 reset-fired 都只在换回合时留痕。
|
|
55
|
+
//
|
|
56
|
+
// `agent/pre-step` 每个 step 都触发,而原实现两处都无条件落账 → 实测
|
|
57
|
+
// (2026-11-28,session-c00d686c):63 个真实回合记出 831 行 reset-fired
|
|
58
|
+
// (avg 13、max 56)与 776 行 residue-check(avg 13.4)。整份日志 2104 行里
|
|
59
|
+
// 有 1607 行是这两项,等于 76% 在记"同一个回合内的第 N 步照例又跑了一遍"。
|
|
60
|
+
//
|
|
61
|
+
// 「回合重置」按其语义就是回合级的:同一回合内的后续 step 不该再报一次"重置了"。
|
|
62
|
+
// 单独算、不动 `saveResetState` 的 `isNewTurn`——那里同时控制
|
|
63
|
+
// fused/effectiveCalls/invCalls 的归零,改它等于改执法行为,风险不对等。
|
|
64
|
+
const prevTurn = state.lastTurn
|
|
65
|
+
// 无 turn 的宿主(老版本/测试直调)退回「prompt 文本变了才算换回合」——
|
|
66
|
+
// 比原来的 `Boolean(short)` 更严:只要有文本就算换回合,会让同一回合的每一步
|
|
67
|
+
// 重新执行一遍批示识别(budget-extend 重复加额度就是这么来的)。
|
|
68
|
+
const isTurnStart = Number.isInteger(turn)
|
|
69
|
+
? turn !== prevTurn
|
|
70
|
+
: Boolean(short) && promptText.slice(0, 4000) !== state.turnPromptFull
|
|
71
|
+
const flags = detectDirectives({ sid, state, promptText, short, isTurnStart })
|
|
72
|
+
auditResidues(sid, state, flags.stopOrdered, isTurnStart)
|
|
56
73
|
// 额度核定
|
|
57
74
|
const kw = KEY50_RE.test(promptText) ? 50 : KEY15_RE.test(promptText) ? 15 : BUDGET_DEFAULT
|
|
58
75
|
state.taskBudget = Math.max(kw, state.declaredBudget || 0, state.taskBudget || BUDGET_DEFAULT)
|
|
@@ -60,11 +77,13 @@ export function preStepListener({ warn } = {}) {
|
|
|
60
77
|
state.ineffCalls = 0
|
|
61
78
|
const chain = 'T' + Date.now().toString(36)
|
|
62
79
|
saveResetState({ file, state, turn, promptText, chain, flags })
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
80
|
+
if (isTurnStart) {
|
|
81
|
+
auditRow(
|
|
82
|
+
sid,
|
|
83
|
+
'reset-fired',
|
|
84
|
+
`prompt:${promptText ? '有' : '无'}(${promptText.length}字) kw=${kw} budget=${state.taskBudget} eff=${state.effectiveCalls || 0} inv=${state.invCalls || 0} stall=${state.stalledStreak || 0}${flags.creditGranted ? ' 信用延期' : ''}${flags.mercy ? ' 特赦' : ''}`,
|
|
85
|
+
)
|
|
86
|
+
}
|
|
68
87
|
} catch (error) {
|
|
69
88
|
if (typeof warn === 'function') warn('回合重置缝异常(不阻塞):', (error && error.message) || error)
|
|
70
89
|
}
|
|
@@ -75,8 +94,17 @@ export function preStepListener({ warn } = {}) {
|
|
|
75
94
|
/**
|
|
76
95
|
* 批示识别(特赦 / 目标预授权 / 信用延期 / 停止令 / 追加额度)。
|
|
77
96
|
* 顺序与原实现一致:每条的审计行必须在自己的状态变更之后落。
|
|
97
|
+
*
|
|
98
|
+
* 只在**换回合**时识别(2026-11-28):同一回合内 `messages` 不变,每步重判等于把同一句批示
|
|
99
|
+
* 记多次。实测 goal-preauth 6 行同属 1 个回合、budget-extend 7 行只分 3 组——
|
|
100
|
+
* 后者不只是多记,是**真的多加了额度**(同一句「追加额度」加 3 次 REFILL)。
|
|
101
|
+
* 不换回合时沿用上一轮已认定的 mercy / goalPush,否则 saveResetState 会把它们覆写成 false,
|
|
102
|
+
* 特赦在回合中途失效。
|
|
78
103
|
*/
|
|
79
|
-
function detectDirectives({ sid, state, promptText, short }) {
|
|
104
|
+
function detectDirectives({ sid, state, promptText, short, isTurnStart }) {
|
|
105
|
+
if (!isTurnStart) {
|
|
106
|
+
return { mercy: !!state.mercy, goalPush: !!state.goalPush, creditGranted: false, stopOrdered: false }
|
|
107
|
+
}
|
|
80
108
|
// 特赦识别
|
|
81
109
|
const grant = promptText.match(MERCY_RE)
|
|
82
110
|
const mercy = !!(grant && short.length <= MERCY_SHORT)
|
|
@@ -131,7 +159,7 @@ function applyBudgetExtend({ sid, state, short }) {
|
|
|
131
159
|
}
|
|
132
160
|
|
|
133
161
|
/** 43条 状态重置核验:上一回合残留 → 记档后清理。 */
|
|
134
|
-
function auditResidues(sid, state, stopOrdered) {
|
|
162
|
+
function auditResidues(sid, state, stopOrdered, isTurnStart) {
|
|
135
163
|
const residues = []
|
|
136
164
|
if ((state.turnCount || 0) > 0) residues.push(`turnCount=${state.turnCount}`)
|
|
137
165
|
if ((state.stalledStreak || 0) > 0) residues.push(`stall=${state.stalledStreak}`)
|
|
@@ -139,7 +167,17 @@ function auditResidues(sid, state, stopOrdered) {
|
|
|
139
167
|
if (state.forcedInvestigate) residues.push('forcedInvestigate')
|
|
140
168
|
if (state.stopBlocked) residues.push('stopBlocked')
|
|
141
169
|
if (state.readSet && Object.keys(state.readSet).length) residues.push(`readSet=${Object.keys(state.readSet).length}`)
|
|
142
|
-
|
|
170
|
+
// 有残留、**且确实在换回合**才记。
|
|
171
|
+
//
|
|
172
|
+
// 43条 的原意是「上一回合的残留,本回合核验后清理」——它天生是回合级的。
|
|
173
|
+
// 原实现只判 `residues.length`,于是同一回合内的每一步都在报"又清理了一次":
|
|
174
|
+
// 实测 776 行里 turnCount 773 / readSet 352 / stall 48,而 fused /
|
|
175
|
+
// forcedInvestigate / stopBlocked **一条都没有**——从没记下过一次执法状态的清理。
|
|
176
|
+
// 这些行分不出「回合开始清上一回合的账」和「本回合第 7 步例行归零」,
|
|
177
|
+
// 混在一起就被读成「残留一直在产生」。
|
|
178
|
+
if (isTurnStart && residues.length) {
|
|
179
|
+
auditRow(sid, 'residue-check', `43条 残留(已清理): ${residues.join(' ')}`)
|
|
180
|
+
}
|
|
143
181
|
}
|
|
144
182
|
|
|
145
183
|
/**
|
|
@@ -150,34 +188,47 @@ function auditResidues(sid, state, stopOrdered) {
|
|
|
150
188
|
* 实测 turn 128:step 19 硬上限熔断,step 20 起 eff 仍 200→206、inv 787→793,白走 16 步。
|
|
151
189
|
* 设计意图本就是"回合级状态"(下方 residue-check 已把 fused 列为待清残留)。
|
|
152
190
|
* 改为:只在**换回合**(turn 变化)时重置 fused;同一回合内保留熔断。
|
|
153
|
-
*
|
|
154
|
-
*
|
|
191
|
+
*
|
|
192
|
+
* 2026-11-28(同日补):当时注释写着「只动 fused,其余字段保持每步重置的现状不动」——
|
|
193
|
+
* 那是在不知道代价时的最小改动。实测(session-c00d686c,2107 行日志)发现其余字段的语义
|
|
194
|
+
* 同样都是「本回合 / 本任务」,每步重置等于**把执法骨架逐条关掉**:
|
|
195
|
+
* violations → `penalize` 的三级递进(≥2 强制调查 / ≥3 熔断 / ≥5 察看)每步归零,永不成立
|
|
196
|
+
* turnCount → `stopPolicy` 的「本回合调用 ≥N 步」与 stopGuard 的「≥5 步」同样永不成立
|
|
197
|
+
* readSet → Read 记的账下一步就没了 → 日志里 24 条 deny **全部**落在「未取证」
|
|
198
|
+
* editedFiles → blast-radius 阈值 6 从未触发(2107 行 0 条),批量场景(≥5 文件)同病
|
|
199
|
+
* kpiScolded → 同一回合反复扣分(turn 100 的 step 3 与 step 12 各 -5,全日志 78 次)
|
|
200
|
+
* delegated → 「已委派过」每步丢失,是上一条扣分的放大器
|
|
201
|
+
* kpiDelegatedAwarded → +5 可反复给
|
|
202
|
+
* probation / forcedInvestigate / stopBlocked / randomFusePending → 状态活不过一步
|
|
203
|
+
* 故一并改为回合级。**只有 lastSig/lastInput 仍按步重置**——「无效调用」判定依赖单步比较,
|
|
204
|
+
* 跨步共享会放大停滞误判。
|
|
155
205
|
*/
|
|
156
206
|
function saveResetState({ file, state, turn, promptText, chain, flags }) {
|
|
157
207
|
const isNewTurn = Number.isInteger(turn) ? turn !== state.lastTurn : true
|
|
158
208
|
saveState(file, {
|
|
159
209
|
...state, // envCache/caseCache(侦查缓存)随 spread 保留;kpi/delegateUsed 跨回合保留
|
|
160
210
|
lastTurn: Number.isInteger(turn) ? turn : state.lastTurn,
|
|
161
|
-
|
|
211
|
+
// ── 以下 11 项均为回合级:同一回合内保留,换回合才清 ──
|
|
212
|
+
turnCount: isNewTurn ? 0 : state.turnCount || 0,
|
|
213
|
+
stopBlocked: isNewTurn ? false : !!state.stopBlocked,
|
|
214
|
+
randomFusePending: isNewTurn ? false : !!state.randomFusePending,
|
|
215
|
+
violations: isNewTurn ? (flags.stopOrdered ? Math.max(state.violations || 0, 3) : 0) : state.violations || 0,
|
|
216
|
+
forcedInvestigate: isNewTurn ? false : !!state.forcedInvestigate,
|
|
217
|
+
probation: isNewTurn ? false : !!state.probation,
|
|
218
|
+
readSet: isNewTurn ? {} : state.readSet || {},
|
|
219
|
+
delegated: isNewTurn ? false : !!state.delegated,
|
|
220
|
+
editedFiles: isNewTurn ? {} : state.editedFiles || {},
|
|
221
|
+
kpiScolded: isNewTurn ? {} : state.kpiScolded || {},
|
|
222
|
+
kpiDelegatedAwarded: isNewTurn ? false : !!state.kpiDelegatedAwarded,
|
|
162
223
|
fused: isNewTurn ? flags.stopOrdered : state.fused,
|
|
163
|
-
stopBlocked: false,
|
|
164
224
|
// 2026-10-28 修(熔断太容易):`effectiveCalls`/`invCalls` 是**回合级**计数
|
|
165
225
|
// (预算与硬上限都按"本回合有效调用"判),原实现跨回合累计且从不归零——
|
|
166
226
|
// 一旦会话累计到 BUDGET_CAP,之后每个有效调用都重新置 fused,换回合也解不开。
|
|
167
227
|
effectiveCalls: isNewTurn ? 0 : state.effectiveCalls,
|
|
168
228
|
invCalls: isNewTurn ? 0 : state.invCalls,
|
|
169
229
|
invWarned: isNewTurn ? false : state.invWarned,
|
|
170
|
-
randomFusePending: false, // 反规避抽查B:检查点属回合内状态,换回合作废(写操作计数 fuseOps 保留)
|
|
171
230
|
mercy: flags.mercy,
|
|
172
231
|
goalPush: flags.goalPush,
|
|
173
|
-
violations: flags.stopOrdered ? Math.max(state.violations || 0, 3) : 0,
|
|
174
|
-
forcedInvestigate: false,
|
|
175
|
-
probation: false,
|
|
176
|
-
readSet: {},
|
|
177
|
-
delegated: false,
|
|
178
|
-
editedFiles: {},
|
|
179
|
-
kpiScolded: {},
|
|
180
|
-
kpiDelegatedAwarded: false,
|
|
181
232
|
turnPrompt: promptText.slice(0, 500),
|
|
182
233
|
turnPromptFull: promptText.slice(0, 4000),
|
|
183
234
|
taskBudget: state.taskBudget,
|
|
@@ -10,14 +10,22 @@
|
|
|
10
10
|
*/
|
|
11
11
|
import { SESSION_RULES } from '../../core/constants.mjs'
|
|
12
12
|
import { pendingPatternStubs } from '../../core/patterns.mjs'
|
|
13
|
-
import {
|
|
13
|
+
import { probeShells } from '../../core/env.mjs'
|
|
14
|
+
import { loadState, saveState, statePath } from '../../core/state.mjs'
|
|
15
|
+
import { projDirOf, sidOf } from './shared.mjs'
|
|
14
16
|
|
|
15
17
|
export function systemPromptRulesListener({ warn } = {}) {
|
|
16
18
|
return async (assembly, context, next) => {
|
|
17
19
|
let downstream
|
|
18
20
|
try {
|
|
19
21
|
downstream = await next()
|
|
20
|
-
|
|
22
|
+
// 顺序有意:常量段(执行体)在前,可变段(经验库)垫尾。
|
|
23
|
+
// section 是按序拼接的,把「会消失的那段」放最后,它消失时前缀不跟着变。
|
|
24
|
+
return withRulesSection(downstream, [
|
|
25
|
+
['focus-guard-env', execNotice()],
|
|
26
|
+
['focus-guard-patterns', patternsNotice(context)],
|
|
27
|
+
['focus-guard-scratch', scratchNotice(context)],
|
|
28
|
+
])
|
|
21
29
|
} catch (error) {
|
|
22
30
|
if (typeof warn === 'function') warn('常驻规则注入异常(不阻塞):', (error && error.message) || error)
|
|
23
31
|
return downstream
|
|
@@ -25,6 +33,51 @@ export function systemPromptRulesListener({ warn } = {}) {
|
|
|
25
33
|
}
|
|
26
34
|
}
|
|
27
35
|
|
|
36
|
+
/**
|
|
37
|
+
* 执行体约束(2026-11-28)。
|
|
38
|
+
*
|
|
39
|
+
* 病根:`platform-deny` 拦得对,但**只拦不前置**。实测 19 天审计日志:
|
|
40
|
+
* bash 里敲 `Select-Object` 被拦 11 次(跨 8 个回合、跨 2 天),pwsh 里用 `&&`
|
|
41
|
+
* 被拦 8 次(跨 6 个回合)。不是同一回合试错——是跨回合遗忘。
|
|
42
|
+
* 拦下只改当次调用,改不了下一回合的默认写法,于是同一条命令被拦第二遍。
|
|
43
|
+
*
|
|
44
|
+
* 为什么独立 section 而不写进 `SESSION_RULES`:那段是逐字镜像,222 字基准被
|
|
45
|
+
* `RULES.md` 第四部分与 `BENCH.md` 同时锁着,改它要动三处口径;而且它对所有平台
|
|
46
|
+
* 都成立,塞进平台专用文本会让非 Windows 用户白付这段字。
|
|
47
|
+
*
|
|
48
|
+
* 为什么按「本机有没有这个 shell」生成、不按会话:`shellIdForTool` 已经确立了
|
|
49
|
+
* 「执行体按工具判」——同一会话 bash / PowerShell 可以并存(本机就是)。所以这段
|
|
50
|
+
* 描述的是**闸门会怎么判**,不是「你这个会话是什么」。两者混着写,迟早对不上。
|
|
51
|
+
*
|
|
52
|
+
* 字节稳定:模块级 lazy 常量,本进程只算一次;非 Windows 返回空串,零注入成本。
|
|
53
|
+
*/
|
|
54
|
+
let execNoticeCache
|
|
55
|
+
function execNotice() {
|
|
56
|
+
if (execNoticeCache !== undefined) return execNoticeCache
|
|
57
|
+
execNoticeCache = ''
|
|
58
|
+
try {
|
|
59
|
+
if (process.platform !== 'win32') return execNoticeCache
|
|
60
|
+
const shells = probeShells()
|
|
61
|
+
const parts = []
|
|
62
|
+
if (shells.includes('bash')) {
|
|
63
|
+
parts.push('bash 工具跑 bash:Select-Object / Get-ChildItem 等 PowerShell cmdlet 不存在,改用 cat / grep / sed / tee')
|
|
64
|
+
}
|
|
65
|
+
if (shells.includes('powershell') || shells.includes('pwsh7')) {
|
|
66
|
+
// 2026-11-28:原先一律写「PowerShell 工具禁 &&」。实测本机 pwsh 与 DSH 的 PowerShell
|
|
67
|
+
// 工具都是 7.7 Core,`&&` 合法——把 5.1 的限制套到 7 上,等于教模型写更啰嗦的命令。
|
|
68
|
+
parts.push(
|
|
69
|
+
shells.includes('pwsh7')
|
|
70
|
+
? 'PowerShell:pwsh7 可用 &&,5.1 禁 &&;两者都禁 bash 管道工具'
|
|
71
|
+
: 'Windows PowerShell 5.1 禁 &&(用 ;)与 bash 管道工具',
|
|
72
|
+
)
|
|
73
|
+
}
|
|
74
|
+
if (parts.length) execNoticeCache = `【执行体】${parts.join(';')}。拦下≠环境故障。`
|
|
75
|
+
} catch {
|
|
76
|
+
execNoticeCache = ''
|
|
77
|
+
}
|
|
78
|
+
return execNoticeCache
|
|
79
|
+
}
|
|
80
|
+
|
|
28
81
|
/**
|
|
29
82
|
* 经验库「教训」待补提醒(2026-11-08)。
|
|
30
83
|
*
|
|
@@ -48,11 +101,44 @@ function patternsNotice(context) {
|
|
|
48
101
|
}
|
|
49
102
|
}
|
|
50
103
|
|
|
51
|
-
/**
|
|
52
|
-
|
|
104
|
+
/**
|
|
105
|
+
* 临时资源清理失败的整改要求(2026-11-28)。
|
|
106
|
+
*
|
|
107
|
+
* 为什么要有这一段:清理器原来把失败全吞进 `catch {}`,于是「删不掉」与「没有可删」
|
|
108
|
+
* 在外部完全同形——三次失效(旧位置误删 / 测试产物不清 / 目录漏清)全靠人翻 `%TEMP%`
|
|
109
|
+
* 才发现。失败现在由 `session-start` 写进 `state.scratchAlert`,这里取出并**报告一次**。
|
|
110
|
+
*
|
|
111
|
+
* 只报一次是有意的:同一条失败每步复述,模型会当背景噪声忽略;而它下次会话启动
|
|
112
|
+
* 若仍失败,会重新写入——所以「持续失败」照样会被看见,只是不刷屏。
|
|
113
|
+
*
|
|
114
|
+
* 不作判定:清理不了是环境问题(文件被占用)还是判据问题(名字对不上),
|
|
115
|
+
* 上下文只有模型有——例如它刚跑过测试、或知道某个进程还没退。
|
|
116
|
+
*/
|
|
117
|
+
function scratchNotice(context) {
|
|
118
|
+
try {
|
|
119
|
+
const sid = sidOf(context && context.agent)
|
|
120
|
+
if (!sid) return ''
|
|
121
|
+
const file = statePath(sid)
|
|
122
|
+
const st = loadState(file)
|
|
123
|
+
if (!st || !st.scratchAlert) return ''
|
|
124
|
+
const line = String(st.scratchAlert)
|
|
125
|
+
st.scratchAlert = null
|
|
126
|
+
saveState(file, st)
|
|
127
|
+
return line
|
|
128
|
+
} catch {
|
|
129
|
+
return ''
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* 下游是预期 assembly 形状时追加独立 section;否则原样透传(不强行改写)。
|
|
135
|
+
*
|
|
136
|
+
* `extras` 是 `[段名, 文本]` 对:文本为空即跳过,所以「本机不适用」的段一个字节都不占。
|
|
137
|
+
*/
|
|
138
|
+
function withRulesSection(downstream, extras = []) {
|
|
53
139
|
if (downstream && typeof downstream === 'object' && Array.isArray(downstream.sections)) {
|
|
54
140
|
const sections = [...downstream.sections, { name: 'focus-guard-rules', text: SESSION_RULES }]
|
|
55
|
-
if (
|
|
141
|
+
for (const [name, text] of extras) if (text) sections.push({ name, text })
|
|
56
142
|
return { ...downstream, sections }
|
|
57
143
|
}
|
|
58
144
|
return downstream
|
|
@@ -4,12 +4,20 @@
|
|
|
4
4
|
* ① system-prompt/assemble:峰谷成本提示行注入;
|
|
5
5
|
* ② tools/post-execute:token 用量折算 → 成本台账落卷(只观测,不改决策)。
|
|
6
6
|
* 外加「磁盘代码 vs 内存实例」一致性提示(FG 是 link 挂载,启动后改盘不会热更)。
|
|
7
|
+
*
|
|
8
|
+
* 2026-11-30 从 `guard/` 移入 `seams/`:本文件导出的是两条缝的监听器
|
|
9
|
+
* (`systemPromptListener` / `postExecuteListener`),由 `index.js` 注册到
|
|
10
|
+
* `system-prompt/assemble` 与 `tools/post-execute`,判定链上没有「版本/成本」这一段。
|
|
11
|
+
* 此前住在闸目录里,`pipeline.mjs` 的头注释便把它当成「各层实现」之一列出——
|
|
12
|
+
* 目录放错会让读代码的人误判判定链有几段。
|
|
7
13
|
*/
|
|
8
14
|
import { statSync } from 'node:fs'
|
|
9
15
|
import { fileURLToPath } from 'node:url'
|
|
10
|
-
import { appendCostRow } from '../
|
|
16
|
+
import { appendCostRow } from '../cost-ledger.mjs'
|
|
11
17
|
import { projDirOf } from '../sessionScope.mjs'
|
|
12
18
|
import { isPeakAt, isSaveStreamEnabled } from '../../peak-cost.mjs'
|
|
19
|
+
import { recordToolResult } from '../guard/retryGuard.mjs'
|
|
20
|
+
import { modelIdOf } from '../guard/tooling.mjs'
|
|
13
21
|
import { fmtTime } from '../../core/state.mjs'
|
|
14
22
|
|
|
15
23
|
/** 每次改动流水线递增;用于磁盘/内存版本一致性提示 */
|
|
@@ -58,8 +66,18 @@ export function checkDiskVersion(warn = console.warn) {
|
|
|
58
66
|
|
|
59
67
|
export { PIPELINE_VERSION_INFO }
|
|
60
68
|
|
|
61
|
-
/**
|
|
62
|
-
|
|
69
|
+
/**
|
|
70
|
+
* 成本提示行(≤30 字;省流开启时追加后缀)。
|
|
71
|
+
*
|
|
72
|
+
* 2026-11-21:**按会话冻结**。原先每步按当前时钟/省流开关重算,峰谷切换或开一次省流
|
|
73
|
+
* 都会改写 system 段 → 宿主 `in-history` 追加一条新 system 消息(约 2.5k tokens)。
|
|
74
|
+
* 冻结后同一会话内该段字节恒定,跨峰谷也不再抖。
|
|
75
|
+
*/
|
|
76
|
+
const costLineBySession = new Map()
|
|
77
|
+
const COST_LINE_MAX = 64
|
|
78
|
+
|
|
79
|
+
function promptCostLine(sid) {
|
|
80
|
+
if (sid && costLineBySession.has(sid)) return costLineBySession.get(sid)
|
|
63
81
|
let base
|
|
64
82
|
try {
|
|
65
83
|
base = isPeakAt(new Date()).inPeak
|
|
@@ -68,11 +86,19 @@ function promptCostLine() {
|
|
|
68
86
|
} catch {
|
|
69
87
|
base = '【成本】低谷时段,可放心输出。'
|
|
70
88
|
}
|
|
89
|
+
let line
|
|
71
90
|
try {
|
|
72
|
-
|
|
91
|
+
line = isSaveStreamEnabled() ? base + '(主动省流已开)' : base
|
|
73
92
|
} catch {
|
|
74
|
-
|
|
93
|
+
line = base
|
|
75
94
|
}
|
|
95
|
+
if (sid) {
|
|
96
|
+
if (costLineBySession.size >= COST_LINE_MAX) {
|
|
97
|
+
costLineBySession.delete(costLineBySession.keys().next().value)
|
|
98
|
+
}
|
|
99
|
+
costLineBySession.set(sid, line)
|
|
100
|
+
}
|
|
101
|
+
return line
|
|
76
102
|
}
|
|
77
103
|
|
|
78
104
|
/** 兼容多家常字段名的用量提取;无用量返回 null */
|
|
@@ -115,7 +141,8 @@ export function systemPromptListener({ warn }) {
|
|
|
115
141
|
let downstream
|
|
116
142
|
try {
|
|
117
143
|
downstream = await next()
|
|
118
|
-
|
|
144
|
+
const header = context && context.agent && context.agent.session ? context.agent.session.header : null
|
|
145
|
+
return appendCostLine(downstream, promptCostLine(header ? header.id : null))
|
|
119
146
|
} catch (error) {
|
|
120
147
|
warn('system-prompt 注入异常,原样放行:', (error && error.message) || error)
|
|
121
148
|
}
|
|
@@ -126,6 +153,11 @@ export function systemPromptListener({ warn }) {
|
|
|
126
153
|
/** ③ 工具执行后:用量折算落台账(只观测;next 缺失时兜底 undefined,不影响下游默认决策) */
|
|
127
154
|
export function postExecuteListener({ warn }) {
|
|
128
155
|
return async (exec, result, next) => {
|
|
156
|
+
try {
|
|
157
|
+
recordToolResult(exec, result)
|
|
158
|
+
} catch {
|
|
159
|
+
/* 重复命令闸记录失败不影响成本核算 */
|
|
160
|
+
}
|
|
129
161
|
try {
|
|
130
162
|
const usage =
|
|
131
163
|
usageOf(result && result.usage) ||
|
|
@@ -133,10 +165,9 @@ export function postExecuteListener({ warn }) {
|
|
|
133
165
|
usageOf(result && result.meta && result.meta.usage)
|
|
134
166
|
if (usage) {
|
|
135
167
|
costMissStreak = 0
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
'unknown'
|
|
168
|
+
// 模型标识与画像共用同一个出口(tooling.modelIdOf):两处各写一份时,补了会话头路径的
|
|
169
|
+
// 那份会生效、漏补的那份恒记 unknown——成本台账与画像就会指向两个不同的模型。
|
|
170
|
+
const model = modelIdOf(exec) || (result && result.model) || 'unknown'
|
|
140
171
|
const { inPeak } = isPeakAt(new Date())
|
|
141
172
|
// 传会话项目目录:成本台账必须落进**这份**卷宗,而不是插件安装目录下的另一份。
|
|
142
173
|
// 时间走 fmtTime(本地、无 `Z`):同一份卷宗里【一】【三】【四】都是本地时间,
|