focus-guard 3.0.7 → 3.4.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 +683 -21
- package/NOTICE +25 -0
- package/README.md +14 -9
- package/README.zh-CN.md +12 -9
- package/docs/AB-PROMPTS.md +123 -0
- package/docs/AB-SESSION.md +161 -0
- package/docs/ARCH-MAP.md +148 -0
- package/docs/BENCH-BASELINE.json +95 -0
- package/docs/BENCH.md +323 -0
- package/docs/GATE-INPUTS.json +10 -0
- package/docs/HANDOFF-2026-10-27.md +736 -0
- package/docs/HOOK-ORDERING.md +139 -0
- package/docs/LEGISLATION-LAW.md +4 -2
- package/docs/MCP-4.0-PLAN.md +184 -0
- package/docs/MEMORY-4.5-PLAN.md +415 -0
- package/docs/PROFILE-TUNING.md +147 -0
- package/docs/RATCHET.json +48 -0
- package/docs/RELEASE-POLICY.md +163 -0
- package/docs/RULES.md +95 -14
- package/docs/THREAT-MODEL.md +68 -0
- package/docs/TOOL-SCHEMA.json +6 -0
- package/docs/VERSION-PLAN.md +532 -0
- package/docs/WRITING-STYLE.md +109 -0
- package/docs/architecture-map.mermaid +186 -0
- package/docs/deepseek-pricing-audit.md +2 -0
- package/hooks/guard.mjs +92 -56
- package/package.json +34 -5
- package/skills/focus-thinking/SKILL.md +9 -7
- package/src/adapters/dsh/eligibility-gate.mjs +446 -23
- package/src/adapters/dsh/tool-kinds.mjs +81 -0
- package/src/core/approval.mjs +2 -8
- package/src/core/approvals.mjs +208 -0
- package/src/core/audit-writer.mjs +297 -0
- package/src/core/audit.mjs +46 -16
- package/src/core/backup.mjs +37 -11
- package/src/core/checkEligibility.mjs +7 -4
- package/src/core/constants.mjs +67 -22
- package/src/core/decisionEngine.mjs +12 -0
- package/src/core/env.mjs +147 -19
- package/src/core/grants.mjs +54 -13
- package/src/core/kpi.mjs +16 -0
- package/src/core/outputGate.mjs +77 -0
- package/src/core/patterns.mjs +129 -0
- package/src/core/prefixStability.mjs +143 -0
- package/src/core/profileLoader.mjs +40 -5
- package/src/core/progressPolicy.mjs +65 -0
- package/src/core/redlines.mjs +49 -5
- package/src/core/risk.mjs +94 -15
- package/src/core/schemaDrift.mjs +125 -0
- package/src/core/sessionScratch.mjs +147 -0
- package/src/core/stageGraph.mjs +104 -0
- package/src/core/staleCleanup.mjs +153 -0
- package/src/core/state.mjs +215 -81
- package/src/core/stopPolicy.mjs +97 -0
- package/src/core/tempPath.mjs +23 -0
- package/src/dsh/audit.mjs +168 -118
- package/src/dsh/compactionWatch/announce.mjs +117 -0
- package/src/dsh/compactionWatch.mjs +68 -153
- package/src/dsh/guard/authz.mjs +97 -0
- package/src/dsh/guard/evidence.mjs +308 -0
- package/src/dsh/guard/hardCheck.mjs +85 -0
- package/src/dsh/guard/redline.mjs +62 -0
- package/src/dsh/guard/risk.mjs +196 -0
- package/src/dsh/guard/runtime.mjs +162 -0
- package/src/dsh/guard/superpowers.mjs +70 -0
- package/src/dsh/guard/tooling.mjs +177 -0
- package/src/dsh/guard/volume.mjs +181 -0
- package/src/dsh/guard/wholeFile.mjs +109 -0
- package/src/dsh/heartbeat.mjs +76 -13
- package/src/dsh/hookOrder.mjs +101 -0
- package/src/dsh/index.js +247 -15
- package/src/dsh/pipeline.mjs +77 -854
- package/src/dsh/policy-audit.mjs +84 -0
- package/src/dsh/postProgress.mjs +400 -274
- package/src/dsh/preGuard.mjs +249 -228
- package/src/dsh/repeatGuard.mjs +98 -0
- package/src/dsh/seams/pre-step.mjs +186 -0
- package/src/dsh/seams/prompt-rules.mjs +59 -0
- package/src/dsh/seams/session-start.mjs +297 -0
- package/src/dsh/seams/shared.mjs +109 -0
- package/src/dsh/seams.mjs +95 -408
- package/src/dsh/search-hints.mjs +136 -0
- package/src/dsh/sessionScope.mjs +28 -0
- package/src/dsh/status.mjs +7 -0
- package/src/dsh/stopGuard.mjs +225 -164
- package/src/dsh/testRuntime.mjs +62 -0
- package/src/dsh/toolKindAudit.mjs +66 -0
- package/src/dsh/tools.mjs +81 -5
- package/src/dsh/traceMeta.mjs +125 -0
- package/src/dsh/value-gate.mjs +93 -0
- package/src/dsh/workspace.mjs +3 -143
- package/src/memory/index.mjs +15 -0
- package/src/memory/tags.mjs +30 -0
- package/src/memory/workspace.mjs +283 -0
- package/src/peak-cost.mjs +1 -1
- package/src/profiles/deepseek-flash.mjs +7 -1
- package/src/profiles/deepseek-pro.mjs +6 -1
- package/src/profiles/default.mjs +6 -1
- package/src/profiles/glm.mjs +6 -1
- package/src/profiles/gpt-astra.mjs +6 -1
- package/tools/bench-ab.mjs +240 -0
- package/tools/bench-cost.mjs +176 -0
- package/tools/brain-cosmic.mjs +43 -0
- package/tools/brain-view.html +853 -0
- package/tools/brain.mjs +317 -0
- package/tools/capture-fixtures.mjs +182 -0
- package/tools/case-audit.mjs +114 -0
- package/tools/collect-panel.mjs +218 -0
- package/tools/dead-export.mjs +60 -0
- package/tools/docs-lint.mjs +82 -0
- package/tools/env-fingerprint.mjs +126 -33
- package/tools/first-run-sweep.mjs +123 -0
- package/tools/focusguard.mjs +155 -0
- package/tools/gate-audit.mjs +140 -0
- package/tools/gate-inputs.mjs +115 -0
- package/tools/handoff.mjs +56 -0
- package/tools/health.mjs +182 -0
- package/tools/knowledge.mjs +118 -0
- package/tools/layering-audit.mjs +105 -0
- package/tools/lib/book-style.mjs +136 -0
- package/tools/lib/brain-core.mjs +342 -0
- package/tools/lib/brain-docs.mjs +293 -0
- package/tools/lib/brain-regions.mjs +169 -0
- package/tools/lib/brain-relate.mjs +235 -0
- package/tools/lib/brain-text.mjs +121 -0
- package/tools/lib/case-tool.mjs +186 -0
- package/tools/lib/docs-core.mjs +392 -0
- package/tools/lib/docs-version.mjs +66 -0
- package/tools/lib/envMap.mjs +31 -0
- package/tools/lib/health-core.mjs +94 -0
- package/tools/lib/import-graph.mjs +118 -0
- package/tools/lib/index-io.mjs +70 -0
- package/tools/lib/open.mjs +32 -0
- package/tools/lib/prefix-cost.mjs +143 -0
- package/tools/lib/ratchet.mjs +174 -0
- package/tools/lib/reach.mjs +28 -0
- package/tools/lib/sessionDump.mjs +80 -0
- package/tools/lib/source-text.mjs +112 -0
- package/tools/library-book.mjs +313 -0
- package/tools/library-build.mjs +50 -12
- package/tools/library-index.mjs +91 -0
- package/tools/lint.mjs +282 -0
- package/tools/log-audit.mjs +108 -0
- package/tools/manifest-sync.mjs +111 -0
- package/tools/memory-audit.mjs +67 -0
- package/tools/module-audit.mjs +56 -0
- package/tools/mutate.mjs +316 -0
- package/tools/prefix-audit.mjs +122 -0
- package/tools/prefix-drift.mjs +325 -0
- package/tools/privacy-guard.mjs +352 -0
- package/tools/quality-audit.mjs +166 -0
- package/tools/schema-fingerprint.mjs +191 -0
- package/{src/dsh → tools}/selftest.mjs +75 -22
- package/tools/smells.mjs +398 -0
- package/tools/verify-case-paths.mjs +93 -0
- package/tools/version.mjs +191 -0
- package/docs/MASTER-PLAN-2.0.0.md +0 -133
- package/docs/MASTER-PLAN-3.0.0.md +0 -76
- package/src/adapters/dsh/fg-appeal-tool.mjs +0 -47
- package/src/adapters/dsh/fg-apply-tool.mjs +0 -68
- /package/{src/adapters/dsh → hooks}/protocol.mjs +0 -0
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 测试运行时判定 —— 「关闭闸门」类开关的唯一准入条件(2026-10-29)。
|
|
3
|
+
*
|
|
4
|
+
* ── 为什么有这个文件 ──────────────────────────────────────────────────
|
|
5
|
+
* 立法:**不允许关闭任何一个功能**。闸门只有「开」这一种状态。
|
|
6
|
+
*
|
|
7
|
+
* 但测试要验「闸拦住了」,就必须能造出「闸关掉」的对照组,否则只能测放行分支。
|
|
8
|
+
* 折中:关闭能力只在**测试运行时**存在。生产环境里 `FG_EVIDENCE_GATE=0` 被读到
|
|
9
|
+
* 也不生效——不是「设了无效」,是代码里根本没有那个分支可走(`gateSwitch` 恒返 true)。
|
|
10
|
+
*
|
|
11
|
+
* ── 判据为什么不用 `NODE_ENV === 'test'` ──────────────────────────────
|
|
12
|
+
* 本仓测试跑法是 `node --test`,实测 `NODE_ENV` 为 `undefined`。用它做判据,
|
|
13
|
+
* 等于把闸门的关闭权交给一个「谁都能随手设」的普通变量——比现在更糟。
|
|
14
|
+
* `NODE_TEST_CONTEXT` 由 `node --test` 子进程自动注入(实测值 `child-v8`),
|
|
15
|
+
* 生产环境不存在,无法被普通用户伪造。
|
|
16
|
+
*
|
|
17
|
+
* ── 与 `FG_*` 其他变量的关系 ─────────────────────────────────────────
|
|
18
|
+
* 只有「关闭型」开关走本模块。调阈值(`FG_AUDIT_MAX_BYTES`)、换路径
|
|
19
|
+
* (`FG_AUDIT_FILE`)、指执行体(`FG_SHELL`)不受影响——那些不关功能。
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* 是否运行在测试里。
|
|
24
|
+
*
|
|
25
|
+
* 判据(任一成立):
|
|
26
|
+
* 1. `NODE_TEST_CONTEXT` 存在 —— `node --test` 子进程自动设置
|
|
27
|
+
* 2. `FG_TEST_MODE=1` —— 显式声明,给不走 `node --test` 的夹具/脚本用
|
|
28
|
+
*
|
|
29
|
+
* @returns {boolean}
|
|
30
|
+
*/
|
|
31
|
+
export function isTestRuntime() {
|
|
32
|
+
return Boolean(process.env.NODE_TEST_CONTEXT) || process.env.FG_TEST_MODE === '1'
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* 布尔型关闭开关:`offValue` 视为「关闭」,其余一律「开」。
|
|
37
|
+
*
|
|
38
|
+
* 生产环境恒 true —— 传什么值都关不掉。
|
|
39
|
+
*
|
|
40
|
+
* @param {string} name 环境变量名
|
|
41
|
+
* @param {string} [offValue='0'] 视为关闭的值
|
|
42
|
+
* @returns {boolean}
|
|
43
|
+
*/
|
|
44
|
+
export function gateSwitch(name, offValue = '0') {
|
|
45
|
+
if (!isTestRuntime()) return true
|
|
46
|
+
return process.env[name] !== offValue
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 数字型阈值兼开关(0 = 关闭):生产环境下限 1,测试环境保留 0。
|
|
51
|
+
*
|
|
52
|
+
* 只禁「关掉」,不禁「调大调小」——`FG_RESULT_ADMIT_BUDGET=5` 在生产仍生效。
|
|
53
|
+
*
|
|
54
|
+
* @param {string} name 环境变量名
|
|
55
|
+
* @param {number} fallback 缺省值
|
|
56
|
+
* @returns {number}
|
|
57
|
+
*/
|
|
58
|
+
export function gateThreshold(name, fallback) {
|
|
59
|
+
const raw = Number(process.env[name] ?? fallback)
|
|
60
|
+
const n = Number.isFinite(raw) ? raw : fallback
|
|
61
|
+
return isTestRuntime() ? n : Math.max(1, n)
|
|
62
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 工具类别覆盖自检(Tool-Kind Coverage,2026-10-29)
|
|
3
|
+
*
|
|
4
|
+
* 背景:`core/risk.mjs` 的工具语义表是**白名单**——没登记的名字一律 `other`。
|
|
5
|
+
* `other` 的后果不是"不管",是两件很具体的事:
|
|
6
|
+
* ① 熔断期 `gateFused` 只放行 `isInvestigation`,`other` 落到 deny 分支
|
|
7
|
+
* (`dsh/preGuard.mjs:223`)——外部插件的查询工具会被当成"改动类"拒掉,理由还是错的;
|
|
8
|
+
* ② `poolOf` 把它算进**执行池**而不是侦查池(`core/progressPolicy.mjs:62`)——
|
|
9
|
+
* 只读的检索动作去抢写入配额(默认 10 次/回合)。
|
|
10
|
+
*
|
|
11
|
+
* 装一个带十几个工具的记忆插件而不登记,就是十几个工具在熔断期被误拒、还抢写入配额。
|
|
12
|
+
*
|
|
13
|
+
* 本模块在会话启动时扫一遍真实工具表,把未登记的挑出来报一句。只报不改,
|
|
14
|
+
* 与 `policy-audit.mjs` / `hookOrder.mjs` 同纪律:失败 sink 到 warn,不影响执法缝。
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { toolKindOf } from '../core/risk.mjs'
|
|
18
|
+
|
|
19
|
+
/** 从 `ctx.tools.schemas()` 的元素里取工具名(兼容 `{name}` 与 OpenAI 的 `{function:{name}}`)。 */
|
|
20
|
+
export function toolNameOf(schema) {
|
|
21
|
+
if (!schema || typeof schema !== 'object') return ''
|
|
22
|
+
const direct = schema.name
|
|
23
|
+
if (typeof direct === 'string' && direct) return direct
|
|
24
|
+
const fn = schema.function
|
|
25
|
+
if (fn && typeof fn === 'object' && typeof fn.name === 'string' && fn.name) return fn.name
|
|
26
|
+
return ''
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 找出未登记语义类别的工具。
|
|
31
|
+
*
|
|
32
|
+
* `prefix` 默认只查 `mcp__`:内置工具漏登记是 FG 自己的欠账(该在 `adapters/dsh/tool-kinds.mjs`
|
|
33
|
+
* 补齐,不是每次启动提醒用户);外部插件才是名字不可预知、必须现场发现的那一类。
|
|
34
|
+
*
|
|
35
|
+
* @param {{ schemas?: any[], allow?: string[], prefix?: string }} opts
|
|
36
|
+
* @returns {{ unknown: string[], scanned: number, registered: number }}
|
|
37
|
+
*/
|
|
38
|
+
export function auditToolKinds({ schemas = [], allow = [], prefix = 'mcp__' } = {}) {
|
|
39
|
+
const skip = new Set((allow || []).map((s) => String(s || '').toLowerCase()))
|
|
40
|
+
const wantPrefix = String(prefix || '').toLowerCase()
|
|
41
|
+
const unknown = []
|
|
42
|
+
let registered = 0
|
|
43
|
+
for (const schema of schemas || []) {
|
|
44
|
+
const name = toolNameOf(schema)
|
|
45
|
+
if (!name) continue
|
|
46
|
+
const key = name.toLowerCase()
|
|
47
|
+
if (skip.has(key)) continue
|
|
48
|
+
if (wantPrefix && !key.startsWith(wantPrefix)) continue
|
|
49
|
+
if (toolKindOf(name) === 'other') unknown.push(name)
|
|
50
|
+
else registered += 1
|
|
51
|
+
}
|
|
52
|
+
unknown.sort()
|
|
53
|
+
return { unknown, scanned: registered + unknown.length, registered }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** 一句话结论(给 warn 用)。无未登记工具时返回空串——调用方据此决定要不要出声。 */
|
|
57
|
+
export function renderToolKindNotice({ unknown = [], scanned = 0 } = {}) {
|
|
58
|
+
if (!unknown.length) return ''
|
|
59
|
+
const head = unknown.slice(0, 6).join('、')
|
|
60
|
+
const more = unknown.length > 6 ? ` 等 ${unknown.length} 个` : ''
|
|
61
|
+
return (
|
|
62
|
+
`工具类别自检:${unknown.length}/${scanned} 个 MCP 工具未登记语义类别(${head}${more})。` +
|
|
63
|
+
`未登记=other:熔断期会被误拒,且占执行池而非侦查池。` +
|
|
64
|
+
`到 adapters/dsh/tool-kinds.mjs 用 registerToolKind 登记。`
|
|
65
|
+
)
|
|
66
|
+
}
|
package/src/dsh/tools.mjs
CHANGED
|
@@ -4,16 +4,19 @@
|
|
|
4
4
|
* 背景:资格闸会拦高危操作(`npm publish` 之类),但 `fg_apply` / `fg_appeal` 两个工具
|
|
5
5
|
* **从未接进装配层**——被拦后模型无路可走,只能让人绕过 DSH。本文件补这条通道。
|
|
6
6
|
*
|
|
7
|
-
*
|
|
7
|
+
* 为什么自己构造而不复用早期版本(`adapters/dsh/fg-apply-tool.mjs` 已于 2026-10-25 删除):
|
|
8
8
|
* ① `@deepseek-ai/dsh-tools` 在 FG 安装目录下不可解析(peerDependency 未随包安装);
|
|
9
|
-
* ②
|
|
9
|
+
* ② 早期那两个文件调 `defineTool` 时没传 `output`,而 defineTool 会读 `options.output.render`
|
|
10
10
|
* → 一导入就抛,说明它们从未被真正执行过(本次才第一次接线)。
|
|
11
11
|
* 故按宿主 register 的既证形状直接构造:`{ name, description, parameters(JSON Schema),
|
|
12
12
|
* output: { schema, render }, execute }`——与 dsh-memory 的 state_checkpoint 同构。
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
|
+
import { readFileSync, writeFileSync } from 'node:fs'
|
|
16
|
+
import { join } from 'node:path'
|
|
15
17
|
import { applyEligibility, grantFromAppeal, FG_APPLY_TOOL_SPEC, FG_APPEAL_TOOL_SPEC } from '../adapters/dsh/eligibility-gate.mjs'
|
|
16
|
-
import { ABSOLUTE_REDLINES } from '
|
|
18
|
+
import { ABSOLUTE_REDLINES } from '../core/redlines.mjs'
|
|
19
|
+
import { livenessBadge } from './heartbeat.mjs'
|
|
17
20
|
|
|
18
21
|
/** 简化参数表({type,required,description,enum})→ JSON Schema。 */
|
|
19
22
|
function specToJsonSchema(spec = {}) {
|
|
@@ -67,13 +70,85 @@ export function buildApplyTool() {
|
|
|
67
70
|
target: args.target,
|
|
68
71
|
}
|
|
69
72
|
const result = await applyEligibility({ session: sessionOf(exec), ...spec, redlines: ABSOLUTE_REDLINES, model: null })
|
|
70
|
-
|
|
73
|
+
// 按需自证(2026-10-19):fg_apply 是第二个局部点——申请/审核结果里附带一次存活徽标。
|
|
74
|
+
return { decision: result.decision, text: `${renderApply(result, spec)}\n${livenessBadge()}` }
|
|
71
75
|
},
|
|
72
76
|
}
|
|
73
77
|
}
|
|
74
78
|
|
|
79
|
+
/**
|
|
80
|
+
* 构造 fg_env 工具定义(2026-11-09)。
|
|
81
|
+
*
|
|
82
|
+
* 为什么需要这个工具:环境档案是**探测**出来的,而探测只看得到 PATH 与 `--version`。
|
|
83
|
+
* 它看不出「这个 pwsh7 是 scoop 装的」「bash 其实是 WSL」「grep 3.0 的 -P 有坑」——
|
|
84
|
+
* 这些只有模型(或人类)在真用过之后才知道。工具给一条**写回**的通道,探测与经验互补。
|
|
85
|
+
*
|
|
86
|
+
* 不传 note 就是只读查询:模型可以随时确认"这台机器到底有什么",不必靠猜。
|
|
87
|
+
*/
|
|
88
|
+
/** fg_env 的执行体(抽出来是为了不让 buildEnvTool 的嵌套超阈值)。 */
|
|
89
|
+
async function runEnvArchive(args = {}, exec) {
|
|
90
|
+
const projDir =
|
|
91
|
+
(exec && exec.agent && exec.agent.session && exec.agent.session.header && exec.agent.session.header.cwd) ||
|
|
92
|
+
process.env.FG_PROJECT_DIR ||
|
|
93
|
+
process.cwd()
|
|
94
|
+
const fp = join(projDir, '.ai', 'env-fingerprint.json')
|
|
95
|
+
let data
|
|
96
|
+
try {
|
|
97
|
+
data = JSON.parse(readFileSync(fp, 'utf8'))
|
|
98
|
+
} catch {
|
|
99
|
+
return { text: `[环境档案] 尚未生成:${fp}\n会话启动会自动探测(后台);也可手动跑 packages/core/tools/env-fingerprint.mjs` }
|
|
100
|
+
}
|
|
101
|
+
const note = String(args.note || '').trim()
|
|
102
|
+
if (note) {
|
|
103
|
+
data.notes = Array.isArray(data.notes) ? data.notes : []
|
|
104
|
+
data.notes.push({ at: new Date().toISOString(), by: 'model', text: note.slice(0, 500) })
|
|
105
|
+
try {
|
|
106
|
+
writeFileSync(fp, JSON.stringify(data, null, 2) + '\n')
|
|
107
|
+
} catch (error) {
|
|
108
|
+
return { text: `[环境档案] 反馈写入失败(不阻塞):${(error && error.message) || error}` }
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
const shells = (data.shells || [])
|
|
112
|
+
.map((s) => `${s.id}(${s.origin === 'builtin' ? '自带' : '额外'})`)
|
|
113
|
+
.join(' ')
|
|
114
|
+
const cmds = Object.entries(data.commands || {})
|
|
115
|
+
.map(([k, v]) => `${k}=${v.impl}${v.version ? ' ' + v.version : ''}`)
|
|
116
|
+
.join(' / ')
|
|
117
|
+
const probe = data.probe || {}
|
|
118
|
+
const lines = [
|
|
119
|
+
`[环境档案] 机器 ${data.machine?.id || '?'} · ${data.machine?.host || '?'} · ${data.platform?.osLabel || data.platform?.os || '?'}`,
|
|
120
|
+
`执行体 ${data.platform?.shell || '?'}(来源 ${data.platform?.shellSource || '?'})/ 可用 ${shells || '-'}`,
|
|
121
|
+
`命令语法 ${cmds || '-'}`,
|
|
122
|
+
`探测 ${probe.at || '-'} · 下次重探 ${probe.nextAt || '-'}(${Math.round((probe.ttlMs || 0) / 3600e3)}h,连续未变 ${probe.streak ?? '-'} 次)`,
|
|
123
|
+
]
|
|
124
|
+
const notes = Array.isArray(data.notes) ? data.notes : []
|
|
125
|
+
if (notes.length) {
|
|
126
|
+
lines.push(`反馈 ${notes.length} 条:`)
|
|
127
|
+
for (const n of notes.slice(-5)) lines.push(` · ${n.text}`)
|
|
128
|
+
}
|
|
129
|
+
if (note) lines.push(`已记录反馈:${note.slice(0, 120)}`)
|
|
130
|
+
return { text: lines.join('\n') }
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function buildEnvTool() {
|
|
134
|
+
return {
|
|
135
|
+
name: 'fg_env',
|
|
136
|
+
description:
|
|
137
|
+
'查看本机环境档案(机器编号 / 操作系统 / 可用终端 / 命令语法新旧 / 探测 TTL),或回填一条补充说明。' +
|
|
138
|
+
'探测只能看到 PATH 与版本号,看不到「这个终端是谁装的」「某个命令在本机有特殊行为」——这些用 note 写回来。',
|
|
139
|
+
parameters: specToJsonSchema({
|
|
140
|
+
note: {
|
|
141
|
+
type: 'string',
|
|
142
|
+
description: '本机环境的补充说明,例如「pwsh7 是 scoop 装的,非系统自带」「bash 实为 WSL」「grep 3.0 不支持 -P 的某些写法」',
|
|
143
|
+
},
|
|
144
|
+
}),
|
|
145
|
+
output: TEXT_OUTPUT,
|
|
146
|
+
execute: runEnvArchive,
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
75
150
|
/** 构造 fg_appeal 工具定义。 */
|
|
76
|
-
|
|
151
|
+
function buildAppealTool() {
|
|
77
152
|
return {
|
|
78
153
|
name: FG_APPEAL_TOOL_SPEC.name,
|
|
79
154
|
description: FG_APPEAL_TOOL_SPEC.description,
|
|
@@ -103,6 +178,7 @@ export function registerGateTools(ctx, { warn } = {}) {
|
|
|
103
178
|
for (const [label, build] of [
|
|
104
179
|
['fg_apply', buildApplyTool],
|
|
105
180
|
['fg_appeal', buildAppealTool],
|
|
181
|
+
['fg_env', buildEnvTool],
|
|
106
182
|
]) {
|
|
107
183
|
try {
|
|
108
184
|
ctx.tools.register(build())
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* focus-guard 原生插件 · 审计位置元数据(turn / step)—— 2026-10-19 人类批示
|
|
3
|
+
*
|
|
4
|
+
* 为什么需要:AUDIT.log 原来只有 `seq`(进程内单调序号,跨会话不可比),
|
|
5
|
+
* 于是"熔断后到底浪费了几步"算不出来 —— `stalledFuse.threshold` 该松该紧无从判断(ARCH-MAP 缺口 #3)。
|
|
6
|
+
*
|
|
7
|
+
* 位置数据从哪来(这是唯一来源,不是猜的):
|
|
8
|
+
* 宿主 `agent/pre-step` 的载荷是 `{ messages, turn, step, signal }`
|
|
9
|
+
* (`@deepseek-ai/dsh-agent-loop/lib/index.js:956-959` 传 `{ turn, step }`),
|
|
10
|
+
* 而 `tools/pre-execute` 的 exec 只有 `{ token, callId, rootCallId, name, signal, agent, parent, schema, arguments }`
|
|
11
|
+
* (`@deepseek-ai/dsh-tools/lib/index.js:3239-3264`)——**没有** turn/step。
|
|
12
|
+
* 所以位置只能由 pre-step 缝记录,再由 `core/audit-writer.mjs` 的 provider 钩子统一注入到每条审计行。
|
|
13
|
+
*
|
|
14
|
+
* 语义(写死,别改口径):
|
|
15
|
+
* - `turn`:回合号,宿主从 1 递增;每回合重置 step。
|
|
16
|
+
* - `step`:回合内步号,宿主从 1 递增。
|
|
17
|
+
* - 熔断点:本回合第一次写 `stall-fuse` 时的 (turn, step)。
|
|
18
|
+
* - 熔断浪费 `wastedSteps` = 同回合结束时 step − 熔断点 step(被拦的步也算一步;deny 另有行可查)。
|
|
19
|
+
* - **按会话独立计数**:每个会话的 step 从 1 重新开始,跨会话不可相加。
|
|
20
|
+
*
|
|
21
|
+
* 落盘:回合结束时由 `recordFuseWaste()` 写一行 `action:"fuse-waste"`(**只在真熔断过的回合**写,不是每步一行)。
|
|
22
|
+
*/
|
|
23
|
+
import { appendAudit, buildAuditRow, setTraceMetaProvider } from '../core/audit-writer.mjs'
|
|
24
|
+
|
|
25
|
+
/** sid → { turn, step, fuseTurn, fuseStep } */
|
|
26
|
+
const sessions = new Map()
|
|
27
|
+
|
|
28
|
+
/** 会话键:接受 agent 对象或 session id 字符串。 */
|
|
29
|
+
function keyOf(agentOrSession) {
|
|
30
|
+
if (typeof agentOrSession === 'string') return agentOrSession || 'dsh-native'
|
|
31
|
+
const agent = agentOrSession
|
|
32
|
+
return (
|
|
33
|
+
(agent &&
|
|
34
|
+
((agent.session && agent.session.header && agent.session.header.id) ||
|
|
35
|
+
agent.sessionId ||
|
|
36
|
+
agent.id)) ||
|
|
37
|
+
'dsh-native'
|
|
38
|
+
)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* 记录一步的位置。只在 pre-step 缝调用。
|
|
43
|
+
* 换回合(turn 变化)时作废上一回合的熔断点——熔断语义是"本回合内"。
|
|
44
|
+
* @returns {{turn:number, step:number}|null} 当前位置(入参非法时为原值或 null)
|
|
45
|
+
*/
|
|
46
|
+
export function noteTracePosition(agentOrSession, turn, step) {
|
|
47
|
+
const key = keyOf(agentOrSession)
|
|
48
|
+
const t = Number(turn)
|
|
49
|
+
const s = Number(step)
|
|
50
|
+
if (!Number.isInteger(t) || !Number.isInteger(s) || t < 0 || s < 0) return sessions.get(key) || null
|
|
51
|
+
const prev = sessions.get(key)
|
|
52
|
+
if (!prev || prev.turn !== t) {
|
|
53
|
+
sessions.set(key, { turn: t, step: s, fuseTurn: null, fuseStep: null })
|
|
54
|
+
} else {
|
|
55
|
+
prev.step = s
|
|
56
|
+
}
|
|
57
|
+
return { turn: t, step: s }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** 当前位置(只读探测,测试用)。 */
|
|
61
|
+
export function currentPosition(agentOrSession) {
|
|
62
|
+
const pos = sessions.get(keyOf(agentOrSession))
|
|
63
|
+
return pos ? { turn: pos.turn, step: pos.step, fuseTurn: pos.fuseTurn, fuseStep: pos.fuseStep } : null
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* provider 实现:给审计行补 turn/step;顺带在遇到 `stall-fuse` 行时钉住熔断点。
|
|
68
|
+
* 有副作用是刻意的——所有 stall-fuse 写点(seams / postProgress / stopGuard)都经 appendAudit,
|
|
69
|
+
* 在写入器这一处识别比逐个改调用点更不容易漏。
|
|
70
|
+
*/
|
|
71
|
+
function traceMetaOf(session, row) {
|
|
72
|
+
const key = String(session || 'dsh-native')
|
|
73
|
+
const pos = sessions.get(key)
|
|
74
|
+
if (!pos) return null
|
|
75
|
+
if (row && row.action === 'stall-fuse' && pos.fuseTurn === null) {
|
|
76
|
+
pos.fuseTurn = pos.turn
|
|
77
|
+
pos.fuseStep = pos.step
|
|
78
|
+
}
|
|
79
|
+
return { turn: pos.turn, step: pos.step }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* 回合结束结算:本回合真熔断过才写一行 `fuse-waste`。
|
|
84
|
+
* 由 `agent/turn-stopping` 调用(index.js 的 turn-stopping 包装里)。
|
|
85
|
+
* @returns {{session:string, turn:number, fuseStep:number, lastStep:number, wastedSteps:number}|null}
|
|
86
|
+
*/
|
|
87
|
+
export function recordFuseWaste(agentOrSession) {
|
|
88
|
+
const key = keyOf(agentOrSession)
|
|
89
|
+
const pos = sessions.get(key)
|
|
90
|
+
if (!pos || pos.fuseTurn === null) return null
|
|
91
|
+
const report = {
|
|
92
|
+
session: key,
|
|
93
|
+
turn: pos.fuseTurn,
|
|
94
|
+
fuseStep: pos.fuseStep,
|
|
95
|
+
lastStep: pos.step,
|
|
96
|
+
wastedSteps: Math.max(0, pos.step - pos.fuseStep),
|
|
97
|
+
}
|
|
98
|
+
pos.fuseTurn = null
|
|
99
|
+
pos.fuseStep = null
|
|
100
|
+
try {
|
|
101
|
+
// 2026-10-29:改走 buildAuditRow——此前这里手写行,漏了 trigger/level,
|
|
102
|
+
// 真实日志里 11 条 fuse-waste 因此成为唯一一批"没有触发条件"的记录。
|
|
103
|
+
appendAudit(
|
|
104
|
+
buildAuditRow(key, 'fuse-waste', {
|
|
105
|
+
evidence: `熔断后步数=${report.wastedSteps}(熔断 step ${report.fuseStep} → 回合末 step ${report.lastStep})`,
|
|
106
|
+
extra: { turn: report.turn, step: report.fuseStep, wasted: report.wastedSteps },
|
|
107
|
+
}),
|
|
108
|
+
)
|
|
109
|
+
} catch {
|
|
110
|
+
/* fail-open:结算是可观测性,不阻断回合 */
|
|
111
|
+
}
|
|
112
|
+
return report
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** 装上 provider(插件 apply 时调用一次)。返回卸载函数。 */
|
|
116
|
+
export function installTraceMeta() {
|
|
117
|
+
setTraceMetaProvider(traceMetaOf)
|
|
118
|
+
return () => setTraceMetaProvider(null)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** 清空内存并卸载 provider(仅测试用)。 */
|
|
122
|
+
export function resetTraceMeta() {
|
|
123
|
+
sessions.clear()
|
|
124
|
+
setTraceMetaProvider(null)
|
|
125
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 改动面闸(Blast-Radius Gate,2026-10-25)
|
|
3
|
+
*
|
|
4
|
+
* 人类原话:"需要改大量文件,结果只是实现一个小彩灯"。
|
|
5
|
+
* 所以判据不是 token ROI,而是 **改动面 × 收益量级**:
|
|
6
|
+
* - 改动面:新建架构敏感文件(src/、packages/ 下)/ 加依赖 / 一次动 ≥N 个文件
|
|
7
|
+
* - 收益:必须能一句话说清"用户可见/可测的改善";说不清 = 小彩灯
|
|
8
|
+
*
|
|
9
|
+
* 设计纪律(与既有闸一致):
|
|
10
|
+
* ① **只拒一次**:同一条调用第二次即放行(不死锁,不替人类做最终决定)
|
|
11
|
+
* ② 不预测数字:不要求"省 X%",只要求"收益是什么 + 更小的替代是什么"
|
|
12
|
+
* ③ 只覆盖架构敏感面:文档、测试、示例不受本闸影响
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const SENSITIVE_RE = /(^|[\\/])(src|packages)[\\/]/i
|
|
16
|
+
|
|
17
|
+
/** 是否为"新建架构敏感文件"(路径不存在 + 落在 src/ 或 packages/ 下)。 */
|
|
18
|
+
function isNewSensitiveFile(filePath, exists) {
|
|
19
|
+
const p = String(filePath || '')
|
|
20
|
+
if (!p || !SENSITIVE_RE.test(p)) return false
|
|
21
|
+
try {
|
|
22
|
+
return exists ? !exists(p) : false
|
|
23
|
+
} catch {
|
|
24
|
+
return false
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** 依赖安装动作(`npm install` / `yarn add` / `pip install` …),捕获其后的参数串。 */
|
|
29
|
+
const DEP_CMD_RE = /\b(?:npm|pnpm|yarn|bun|pip3?|poetry|uv)\s+(?:install|add|i)\b([\s\S]*)/i
|
|
30
|
+
/** 开发依赖标记:不进产物,维护负担远小于生产依赖。 */
|
|
31
|
+
const DEV_FLAG_RE = /^(?:-D|--save-dev|--dev|--development)$/i
|
|
32
|
+
/** 带参数的 flag:紧跟的那个 token 是路径/约束文件,不是包名。 */
|
|
33
|
+
const FLAG_WITH_ARG_RE =
|
|
34
|
+
/^(?:-r|--requirement|-c|--constraint|-e|--editable|-f|--find-links|--index-url|--registry|--prefix|--target)$/i
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* 本次命令是否在**新增**依赖(2026-10-29,台账 T7)。
|
|
38
|
+
*
|
|
39
|
+
* 原实现把任何 `npm install` 都算新增,于是任务基准 T40(`npm install`)与
|
|
40
|
+
* T41(`npm install --save-dev vitest`)双双被拦,误伤 2/57。
|
|
41
|
+
* 但本闸的立意是「**新增**依赖 = 引入长期维护负担」,按这个立意收窄:
|
|
42
|
+
* · 裸 `install` / `ci` / `--production` → 装 package.json 已声明的,不新增 → 不拦
|
|
43
|
+
* · 只装开发依赖(`-D` / `--save-dev`) → 不进产物,负担小 → 不拦
|
|
44
|
+
* · 带包名的生产依赖 → 拦(这才是要问"收益是什么"的那类)
|
|
45
|
+
*
|
|
46
|
+
* 边界:`pip install -r req.txt` 的 `req.txt` 是文件不是包名,靠 `FLAG_WITH_ARG_RE` 跳过。
|
|
47
|
+
*/
|
|
48
|
+
export function isNewDependency(cmd) {
|
|
49
|
+
const m = DEP_CMD_RE.exec(String(cmd || ''))
|
|
50
|
+
if (!m) return false
|
|
51
|
+
const tokens = (m[1] || '').split(/\s+/).filter(Boolean)
|
|
52
|
+
let dev = false
|
|
53
|
+
const pkgs = []
|
|
54
|
+
for (let i = 0; i < tokens.length; i += 1) {
|
|
55
|
+
const t = tokens[i]
|
|
56
|
+
if (t.startsWith('-')) {
|
|
57
|
+
if (DEV_FLAG_RE.test(t)) dev = true
|
|
58
|
+
if (FLAG_WITH_ARG_RE.test(t)) i += 1 // 跳过它带的参数
|
|
59
|
+
continue
|
|
60
|
+
}
|
|
61
|
+
if (/^[|&;]/.test(t)) break // 管道/串联之后是另一条命令,不算本次安装
|
|
62
|
+
pkgs.push(t)
|
|
63
|
+
}
|
|
64
|
+
if (!pkgs.length) return false
|
|
65
|
+
return !dev
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** 是否需要本闸介入(新建敏感文件 / 新增生产依赖)。 */
|
|
69
|
+
export function shouldGate({ filePath, exists, command }) {
|
|
70
|
+
if (isNewSensitiveFile(filePath, exists)) return true
|
|
71
|
+
// 加依赖 = 引入长期维护负担,同样要求一句话收益。
|
|
72
|
+
// 2026-10-25 修:原条件要求命令里出现 package.json 字样,而 `npm install x` 并不会带文件名 → 永不触发。
|
|
73
|
+
// 2026-10-29 再修:只认「新增生产依赖」,裸 install 与开发依赖放行(见 isNewDependency)。
|
|
74
|
+
return isNewDependency(command)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** 一次性拦截的理由:给模板,不替人类判断。 */
|
|
78
|
+
export function gateReason({ filePath, kind }) {
|
|
79
|
+
const what = kind === 'dep' ? '新增依赖' : `新建架构文件 ${String(filePath || '').split(/[\\/]/).pop()}`
|
|
80
|
+
return (
|
|
81
|
+
`focus-guard-native: 改动面闸——${what}。先回三行(每条 ≤40 字):\n` +
|
|
82
|
+
'1) 收益:这个改动让用户/指标看到什么变化(说不清就是小彩灯)\n' +
|
|
83
|
+
'2) 改动面:预计要碰几个文件、是否跨层(core/adapter/seam)\n' +
|
|
84
|
+
'3) 替代:更小的做法是什么(不加文件/不改依赖能否达成)\n' +
|
|
85
|
+
'回完直接重试本条即放行(只拒一次,不重复劝)。'
|
|
86
|
+
)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** 解析人类指令里是否已声明收益(有则无需再拦)。 */
|
|
90
|
+
export function promptDeclaresBenefit(prompt) {
|
|
91
|
+
const t = String(prompt || '')
|
|
92
|
+
return /(收益|用户可见|可测|提升|减少|避免|加速|降本)/.test(t) && t.length >= 10
|
|
93
|
+
}
|
package/src/dsh/workspace.mjs
CHANGED
|
@@ -1,145 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
* DCR 的替代品,但**只做一件 DCR 没做对的事**:把持久状态绑死在工作区身份上。
|
|
5
|
-
* DCR 的实测缺陷(见 AGENTS.md 卸载记录):删会话、摘工作区、甚至**改文件夹名**之后,
|
|
6
|
-
* 旧状态照样注入——因为它没有"这份状态属于哪个路径"的概念。
|
|
7
|
-
*
|
|
8
|
-
* 本模块的身份就是路径哈希:
|
|
9
|
-
* workspace_hash = sha256(realpath(cwd)) 前 16 位
|
|
10
|
-
* 读的时候 hash 对不上 → 一条都不注入(路径不匹配即彻底屏蔽,零污染)
|
|
11
|
-
*
|
|
12
|
-
* 纪律(对齐 DCR 死因):
|
|
13
|
-
* · 不 cancel、不 reject、不写 surface —— 只读文件、只追加系统提示 section;
|
|
14
|
-
* · 不伪造 user 消息(DSH 0.2 的 UserMessage 走 runtime context 投影,硬塞会断);
|
|
15
|
-
* · 写失败只 warn,绝不阻断回合。
|
|
2
|
+
* 兼容转发(4.5 M1,2026-11-02)。
|
|
3
|
+
* 实现已迁入 `src/memory/workspace.mjs`;这里只做旧路径转发,调用方无需改动。
|
|
16
4
|
*/
|
|
17
|
-
|
|
18
|
-
import { createHash } from 'node:crypto'
|
|
19
|
-
import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs'
|
|
20
|
-
import { dirname } from 'node:path'
|
|
21
|
-
import { fileURLToPath } from 'node:url'
|
|
22
|
-
import { statePath, loadState } from '../core/state.mjs'
|
|
23
|
-
|
|
24
|
-
/** 默认落点:仓库根 `.focus-guard/workspace.json`(该目录已在 .gitignore)。 */
|
|
25
|
-
export const WORKSPACE_FILE = fileURLToPath(new URL('../../../../.focus-guard/workspace.json', import.meta.url))
|
|
26
|
-
|
|
27
|
-
/** `FG_WORKSPACE_FILE` 可重定向——测试必须用它,否则会写进真实工作区。 */
|
|
28
|
-
export function workspaceFilePath() {
|
|
29
|
-
return process.env.FG_WORKSPACE_FILE || WORKSPACE_FILE
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
/** 条目上限:每类最多 10 条、每条 ≤200 字、注入正文 ≤1200 字。 */
|
|
33
|
-
const MAX_ITEMS = 10
|
|
34
|
-
const MAX_CHARS = 200
|
|
35
|
-
const MAX_RENDER = 1200
|
|
36
|
-
|
|
37
|
-
/** 工作区身份:realpath 的 sha256 前 16 位。路径不存在时退回 cwd 原样。 */
|
|
38
|
-
export function workspaceHash(cwd) {
|
|
39
|
-
const raw = String(cwd || '')
|
|
40
|
-
if (!raw) return null
|
|
41
|
-
let real = raw
|
|
42
|
-
try {
|
|
43
|
-
real = realpathSync(raw)
|
|
44
|
-
} catch {
|
|
45
|
-
/* 路径还不存在:用原字符串,仍然稳定 */
|
|
46
|
-
}
|
|
47
|
-
return createHash('sha256').update(real.replace(/\\/g, '/').toLowerCase()).digest('hex').slice(0, 16)
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
/** 读卷宗;hash 不匹配或文件缺失返回 null(= 不注入)。 */
|
|
51
|
-
export function readWorkspace(cwd) {
|
|
52
|
-
const file = workspaceFilePath()
|
|
53
|
-
const hash = workspaceHash(cwd)
|
|
54
|
-
if (!hash || !existsSync(file)) return null
|
|
55
|
-
try {
|
|
56
|
-
const parsed = JSON.parse(readFileSync(file, 'utf8'))
|
|
57
|
-
if (!parsed || parsed.workspace_hash !== hash) return null
|
|
58
|
-
return parsed
|
|
59
|
-
} catch {
|
|
60
|
-
return null
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
function clean(list) {
|
|
65
|
-
if (!Array.isArray(list)) return []
|
|
66
|
-
const out = []
|
|
67
|
-
for (const item of list) {
|
|
68
|
-
const text = String(item ?? '').trim().slice(0, MAX_CHARS)
|
|
69
|
-
if (text && !out.includes(text)) out.push(text)
|
|
70
|
-
if (out.length >= MAX_ITEMS) break
|
|
71
|
-
}
|
|
72
|
-
return out
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
/** 合并写入(去重、截断、原子替换)。返回写入后的记录。 */
|
|
76
|
-
export function mergeWorkspace(cwd, patch = {}) {
|
|
77
|
-
const file = workspaceFilePath()
|
|
78
|
-
const hash = workspaceHash(cwd)
|
|
79
|
-
if (!hash) throw new Error('workspaceHash: cwd 为空')
|
|
80
|
-
let prev = {}
|
|
81
|
-
try {
|
|
82
|
-
if (existsSync(file)) {
|
|
83
|
-
const parsed = JSON.parse(readFileSync(file, 'utf8'))
|
|
84
|
-
if (parsed && parsed.workspace_hash === hash) prev = parsed
|
|
85
|
-
}
|
|
86
|
-
} catch {
|
|
87
|
-
/* 损坏就重建,不阻断 */
|
|
88
|
-
}
|
|
89
|
-
const next = {
|
|
90
|
-
schema: 1,
|
|
91
|
-
workspace_hash: hash,
|
|
92
|
-
workspace_path: String(cwd || ''),
|
|
93
|
-
updated_at: new Date().toISOString(),
|
|
94
|
-
decisions: clean([...(prev.decisions || []), ...(patch.decisions || [])]),
|
|
95
|
-
constraints: clean([...(prev.constraints || []), ...(patch.constraints || [])]),
|
|
96
|
-
next_action: clean([...(prev.next_action || []), ...(patch.next_action || [])]),
|
|
97
|
-
}
|
|
98
|
-
mkdirSync(dirname(file), { recursive: true })
|
|
99
|
-
const tmp = `${file}.tmp`
|
|
100
|
-
writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`)
|
|
101
|
-
renameSync(tmp, file)
|
|
102
|
-
return next
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
/** 渲染成系统提示 section;无内容返回 null(正常路径零注入)。 */
|
|
106
|
-
export function renderWorkspaceSection(record) {
|
|
107
|
-
if (!record) return null
|
|
108
|
-
const block = (label, items) => (items && items.length ? `${label}:${items.map((x) => `「${x}」`).join('、')}` : '')
|
|
109
|
-
const lines = [
|
|
110
|
-
block('决策', record.decisions),
|
|
111
|
-
block('约束', record.constraints),
|
|
112
|
-
block('下一步', record.next_action),
|
|
113
|
-
].filter(Boolean)
|
|
114
|
-
if (!lines.length) return null
|
|
115
|
-
const text = `[FG-WORKSPACE] 本工作区跨会话卷宗(hash=${record.workspace_hash},仅当前路径可见):\n${lines.join('\n')}`
|
|
116
|
-
return text.slice(0, MAX_RENDER)
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
/**
|
|
120
|
-
* 回合结束落账:只记 FG **亲眼看到**的三类事实,不推断、不编造。
|
|
121
|
-
* decisions ← 本轮人类指令原文(≤200 字)
|
|
122
|
-
* constraints← 人类明确否决过的命令(state.rejectedCmds 的键)
|
|
123
|
-
* next_action← FG 不知道,留空(宁可空,不猜)
|
|
124
|
-
*/
|
|
125
|
-
export function recordWorkspaceTurn(agent) {
|
|
126
|
-
const cwd = agent && agent.session && agent.session.header && agent.session.header.cwd
|
|
127
|
-
if (!cwd) return null
|
|
128
|
-
const sid =
|
|
129
|
-
(agent && agent.session && agent.session.header && agent.session.header.id) ||
|
|
130
|
-
(agent && (agent.sessionId || agent.id)) ||
|
|
131
|
-
'dsh-native'
|
|
132
|
-
let state = {}
|
|
133
|
-
try {
|
|
134
|
-
state = loadState(statePath(sid)) || {}
|
|
135
|
-
} catch {
|
|
136
|
-
state = {}
|
|
137
|
-
}
|
|
138
|
-
const prompt = String(state.turnPromptFull || state.turnPrompt || '').trim()
|
|
139
|
-
const rejected = Object.keys(state.rejectedCmds || {})
|
|
140
|
-
return mergeWorkspace(cwd, {
|
|
141
|
-
decisions: prompt ? [prompt.slice(0, MAX_CHARS)] : [],
|
|
142
|
-
constraints: rejected.slice(0, MAX_ITEMS),
|
|
143
|
-
next_action: [],
|
|
144
|
-
})
|
|
145
|
-
}
|
|
5
|
+
export * from '../memory/index.mjs'
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 记忆模块唯一入口(4.5 M1,2026-11-02)。
|
|
3
|
+
*
|
|
4
|
+
* 分层纪律:本模块不 import 任何 `src/dsh/`;宿主适配层只准 import 这里。
|
|
5
|
+
* 旧路径 `src/dsh/workspace.mjs` 保留转发,调用方不必改。
|
|
6
|
+
*
|
|
7
|
+
* 注入边界(2026-11-02 人类批示):
|
|
8
|
+
* ① 不新开 `focus-guard-memory` 段——记忆只并进已有的 `focus-guard-workspace`,
|
|
9
|
+
* 同一 owner、同一尾部位置,避免与宿主记忆插件抢段。
|
|
10
|
+
* ② FG 只注入**约束类**内容(决策 / 被否决的命令 / 熔断);
|
|
11
|
+
* 用户偏好归 DSH 的 self-improvement,两边不重复写。
|
|
12
|
+
* ③ 静态知识库与人格档**不进注入**:前者只在 `tools/` 离线落索引,后者待裁决。
|
|
13
|
+
*/
|
|
14
|
+
export * from './workspace.mjs'
|
|
15
|
+
export * from './tags.mjs'
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 卷宗条目标签(M1 抽出,2026-11-02)。
|
|
3
|
+
*
|
|
4
|
+
* 只有四个状态,自由标签会失控:
|
|
5
|
+
* [goal] 长期目标——上限淘汰时永不挤掉
|
|
6
|
+
* [done] 已完成——**不注入**(僵尸记忆的主要来源)
|
|
7
|
+
* [note] 备注——**不注入**
|
|
8
|
+
* 无标签 普通决策——按 FIFO
|
|
9
|
+
*
|
|
10
|
+
* 用文本前缀而不是结构化字段:零 schema 变更、可逆、人可直接编辑文件。
|
|
11
|
+
*/
|
|
12
|
+
export const CASE_TAGS = Object.freeze(['goal', 'done', 'note'])
|
|
13
|
+
const TAG_RE = /^\[(goal|done|note)\]\s*/i
|
|
14
|
+
|
|
15
|
+
/** 取标签;无标签返回 null。 */
|
|
16
|
+
export function parseTag(text) {
|
|
17
|
+
const m = TAG_RE.exec(String(text ?? ''))
|
|
18
|
+
return m ? m[1].toLowerCase() : null
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** 去掉标签前缀(注入时用,别把标记塞进系统提示)。 */
|
|
22
|
+
export function stripTag(text) {
|
|
23
|
+
return String(text ?? '').replace(TAG_RE, '')
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** 不注入的标签:已完成 / 备注。 */
|
|
27
|
+
export function isHiddenTag(text) {
|
|
28
|
+
const t = parseTag(text)
|
|
29
|
+
return t === 'done' || t === 'note'
|
|
30
|
+
}
|