ld-vibe-harness 0.1.0 → 0.2.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/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/CHANGELOG.md +33 -0
- package/README.en.md +8 -8
- package/README.md +12 -11
- package/adapters/antigravity/installer.js +43 -4
- package/adapters/dsh/index.js +84 -1
- package/adapters/dsh/package.json +1 -1
- package/agents/ldvh-friction-recorder.md +27 -0
- package/hooks/_client.mjs +20 -0
- package/hooks/hook-engine.js +496 -22
- package/hooks.json +1 -1
- package/lib/capture-notice.js +43 -0
- package/lib/carrier-ref.js +11 -0
- package/lib/commit-validation.js +2 -2
- package/lib/friction-tools.js +38 -7
- package/lib/goal-anchor.js +100 -0
- package/lib/goal-tools.js +28 -5
- package/lib/guidance-text.js +4 -4
- package/lib/host-seams.js +48 -24
- package/lib/intent-tools.js +38 -7
- package/lib/ldvh-tools.js +77 -249
- package/lib/milestone-tools.js +40 -8
- package/lib/norm-tools.js +44 -9
- package/lib/operation-declarations.bundle.json +313 -0
- package/lib/pitfall-tools.js +38 -7
- package/lib/progressive-read.js +250 -0
- package/lib/read-body-render.js +27 -3
- package/lib/recall-criteria.bundle.json +209 -0
- package/lib/recall-criteria.js +246 -0
- package/lib/recall-injection.js +161 -68
- package/lib/recall-synonyms.js +99 -0
- package/lib/report-tools.js +44 -13
- package/lib/review-ask-tool.js +191 -63
- package/lib/review-ask.js +70 -23
- package/lib/review-dispatch-template.js +75 -40
- package/lib/runtime-carrier-reader.js +811 -0
- package/lib/runtime-carrier-validator.js +948 -0
- package/lib/source-recall.js +445 -147
- package/lib/spec-registry.js +121 -5
- package/package.json +10 -4
- package/plugin-specs/controlled-commit.yaml +233 -0
- package/plugin-specs/experience-accumulation-system-foundation.yaml +308 -0
- package/plugin-specs/fact-model-common.yaml +313 -0
- package/plugin-specs/friction-fact-type.yaml +333 -0
- package/plugin-specs/friction-settlement-system-foundation.yaml +334 -0
- package/plugin-specs/gate-consult-system-foundation.yaml +337 -0
- package/plugin-specs/goal-fact-type.yaml +205 -0
- package/plugin-specs/goal-planning-system-foundation.yaml +296 -0
- package/plugin-specs/intent-fact-type.yaml +243 -0
- package/plugin-specs/intent-record-system-foundation.yaml +281 -0
- package/plugin-specs/ldvh-root.yaml +251 -0
- package/plugin-specs/milestone-fact-type.yaml +212 -0
- package/plugin-specs/norm-fact-type.yaml +172 -0
- package/plugin-specs/pitfall-fact-type.yaml +292 -0
- package/plugin-specs/report-fact-type.yaml +152 -0
- package/plugin-specs/research-system-foundation.yaml +306 -0
- package/plugin-specs/rule-compliance-recall.yaml +250 -0
- package/plugin-specs/rule-compliance-verification.yaml +207 -0
- package/plugin-specs/service-contract.yaml +218 -0
- package/plugin.json +1 -1
- package/rules/AGENTS.md +4 -4
- package/server/local-daemon.js +43 -2
- package/server/mcp-app-html.js +44 -1
- package/server/mcp-server.js +21 -0
- package/skills/ldvh-governance-flow/SKILL.md +10 -11
- package/specs/00-/347/220/206/345/277/265/344/270/216/346/236/204/346/210/220.md +0 -304
- package/specs/01-/350/247/204/350/214/203/346/272/220/344/270/216/350/247/204/350/214/203/346/250/241/345/236/213/345/237/272/347/241/200/350/247/204/350/214/203.md +0 -611
- package/specs/02-/344/272/213/345/256/236/346/272/220/344/270/216/344/272/213/345/256/236/346/250/241/345/236/213/345/237/272/347/241/200/350/247/204/350/214/203.md +0 -646
- package/specs/03-/344/270/232/345/212/241/347/263/273/347/273/237/345/237/272/347/241/200/350/247/204/350/214/203.md +0 -518
- package/specs/04-/346/243/200/346/237/245/344/270/216/350/276/205/345/212/251/346/234/272/345/210/266/350/247/204/350/214/203.md +0 -326
- package/specs/05-LDVH CLI /347/241/256/345/256/232/346/200/247/346/234/215/345/212/241/350/247/204/350/214/203.md" +0 -289
- package/specs/06-Code /345/256/236/350/267/265/344/270/216/346/265/213/350/257/225/350/247/204/350/214/203.md" +0 -364
- package/specs/07-Web /345/221/210/347/216/260/344/270/216/344/272/244/344/272/222/350/247/204/350/214/203.md" +0 -280
- package/specs/08-/347/256/241/350/276/226/350/214/203/345/233/264/350/247/204/350/214/203.md +0 -262
- package/specs/09-/345/217/227/346/216/247/346/217/220/344/272/244/344/270/216/346/234/272/346/242/260/345/256/210/346/212/244/350/247/204/350/214/203.md +0 -291
- package/specs/10-DSH /347/216/257/345/242/203/346/216/245/345/205/245/344/270/216/346/217/222/344/273/266/345/217/221/345/270/203/350/247/204/350/214/203.md" +0 -317
- package/specs/20-Goal-/351/241/271/347/233/256/347/233/256/346/240/207.md +0 -271
- package/specs/21-Milestone-/351/207/214/347/250/213/347/242/221.md +0 -413
- package/specs/22-Intent-/346/204/217/345/233/276.md +0 -459
- package/specs/23-Norm-/344/272/213/345/256/236/350/247/204/350/214/203.md +0 -397
- package/specs/24-Report-/346/212/245/345/221/212.md +0 -562
- package/specs/25-Pitfall-/350/270/251/345/235/221/347/273/217/351/252/214.md +0 -358
- package/specs/26-Friction-/346/221/251/346/223/246/350/264/246/346/234/254.md +0 -409
- package/specs/30-/347/233/256/346/240/207/350/247/204/345/210/222/347/263/273/347/273/237/350/247/204/350/214/203.md +0 -408
- package/specs/31-/346/204/217/345/233/276/350/256/260/345/275/225/347/263/273/347/273/237/350/247/204/350/214/203.md +0 -463
- package/specs/32-/346/212/212/345/205/263/350/257/267/347/244/272/347/263/273/347/273/237/350/247/204/350/214/203.md +0 -420
- package/specs/33-/350/260/203/347/240/224/345/220/270/346/224/266/347/263/273/347/273/237/350/247/204/350/214/203.md +0 -653
- package/specs/34-/345/217/214/346/272/220/345/217/254/345/233/236/347/263/273/347/273/237/350/247/204/350/214/203.md +0 -492
- package/specs/35-/347/273/217/351/252/214/347/247/257/347/264/257/347/263/273/347/273/237/350/247/204/350/214/203.md +0 -471
- package/specs/36-/346/221/251/346/223/246/351/224/200/350/264/246/347/263/273/347/273/237/350/247/204/350/214/203.md +0 -488
- package/specs/attachments/01.Att.01-LDVH/345/217/214/350/257/255/346/234/257/350/257/255/350/241/250.md +0 -128
- package/specs/attachments/01.Att.02-/350/247/204/350/214/203/350/272/253/344/273/275/345/255/227/346/256/265/350/241/250.md +0 -107
- package/specs/attachments/01.Att.03-/350/247/204/350/214/203/345/205/263/347/263/273/344/270/216/345/261/202/347/272/247/350/241/250.md +0 -63
- package/specs/attachments/02.Att.01-/344/272/213/345/256/236/345/217/254/345/233/236/345/210/206/345/261/202/350/241/250.md +0 -22
- package/specs/attachments/08.Att.01-/347/256/241/350/276/226/347/231/273/350/256/260/350/275/275/344/275/223Schema/350/241/250.md +0 -29
- package/specs/attachments/23.Att.01-Norm/346/226/271/345/220/221/346/270/205/345/215/225.md +0 -102
package/hooks/hook-engine.js
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { realpathSync } from "node:fs";
|
|
4
|
+
import { readdir, readFile, stat, unlink } from "node:fs/promises";
|
|
5
|
+
import { basename, dirname, join, relative, resolve } from "node:path";
|
|
3
6
|
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { promisify } from "node:util";
|
|
4
8
|
import { createDataPathResolver, readPluginSettings } from "../lib/data-paths.js";
|
|
5
9
|
import { ensureRegistrationCarrier } from "../lib/governed-projects.js";
|
|
6
10
|
import { repairHooksOnStartup } from "../lib/hook-repair.js";
|
|
@@ -8,8 +12,9 @@ import { resolveGovernanceScope } from "../lib/governance-scope.js";
|
|
|
8
12
|
import { buildGuidance } from "../lib/guidance-budget.js";
|
|
9
13
|
import { migrationLineFor, noticeTextFor } from "../lib/guidance-text.js";
|
|
10
14
|
import { buildRecallInjection } from "../lib/recall-injection.js";
|
|
11
|
-
import { recallLimitForBudget, resolveInjectionBudget } from "../lib/source-recall.js";
|
|
15
|
+
import { recallByFilePaths, recallLimitForBudget, resolveInjectionBudget } from "../lib/source-recall.js";
|
|
12
16
|
import { buildNormDirectoryForRoot, NORM_DIRECTORY_BUDGET_CHARS } from "../lib/norm-directory.js";
|
|
17
|
+
import { buildGoalAnchorForRoot, GOAL_ANCHOR_BUDGET_CHARS } from "../lib/goal-anchor.js";
|
|
13
18
|
import { writeShapedTools } from "../lib/host-seams.js";
|
|
14
19
|
import {
|
|
15
20
|
REVIEW_ASK_ANSWERS,
|
|
@@ -19,11 +24,15 @@ import {
|
|
|
19
24
|
} from "../lib/review-ask.js";
|
|
20
25
|
import { createExperienceArming } from "../lib/experience-arming.js";
|
|
21
26
|
import { recordRun } from "../lib/idle-runlog.js";
|
|
22
|
-
import { writeFileAtomic } from "../lib/atomic-write.js";
|
|
27
|
+
import { withFileLock, writeFileAtomic } from "../lib/atomic-write.js";
|
|
23
28
|
import { appendGateEvent } from "../lib/gate-events.js";
|
|
29
|
+
import { buildCaptureNotice, resolveCaptureSwitches } from "../lib/capture-notice.js";
|
|
24
30
|
|
|
31
|
+
const execFileAsync = promisify(execFile);
|
|
25
32
|
const REPO_ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
|
|
26
33
|
const RUNNER_PATH = join(REPO_ROOT, "lib", "git-gate-runner.js");
|
|
34
|
+
const TURN_STATE_TTL_MS = 15 * 60 * 1000;
|
|
35
|
+
const TURN_STATE_MAX_ENTRIES = 20;
|
|
27
36
|
|
|
28
37
|
const EXTRA_WRITE_TOOLS = new Set([
|
|
29
38
|
"ldvh_register_governed_project",
|
|
@@ -135,6 +144,33 @@ function normalizePathKey(targetPath, cwd) {
|
|
|
135
144
|
return process.platform === "win32" ? abs.toLowerCase() : abs;
|
|
136
145
|
}
|
|
137
146
|
|
|
147
|
+
function safeRealpathDeep(target) {
|
|
148
|
+
let current = resolve(target);
|
|
149
|
+
const tail = [];
|
|
150
|
+
while (true) {
|
|
151
|
+
try {
|
|
152
|
+
const real = (realpathSync.native ?? realpathSync)(current);
|
|
153
|
+
return tail.length > 0 ? join(real, ...tail.reverse()) : real;
|
|
154
|
+
} catch {
|
|
155
|
+
const parent = dirname(current);
|
|
156
|
+
if (parent === current) return resolve(target);
|
|
157
|
+
tail.push(basename(current));
|
|
158
|
+
current = parent;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function isInsideLdvhBase(targetPath, cwd, projectPath) {
|
|
164
|
+
if (typeof targetPath !== "string" || targetPath.trim().length === 0) return false;
|
|
165
|
+
if (typeof projectPath !== "string" || projectPath.trim().length === 0) return false;
|
|
166
|
+
const resolvedBase = safeRealpathDeep(join(projectPath, "ldvh-base"));
|
|
167
|
+
const resolvedTarget = safeRealpathDeep(resolve(cwd || projectPath, targetPath));
|
|
168
|
+
const normBase = process.platform === "win32" ? resolvedBase.toLowerCase() : resolvedBase;
|
|
169
|
+
const normTarget = process.platform === "win32" ? resolvedTarget.toLowerCase() : resolvedTarget;
|
|
170
|
+
const sepChar = process.platform === "win32" ? "\\" : "/";
|
|
171
|
+
return normTarget === normBase || normTarget.startsWith(`${normBase}${sepChar}`);
|
|
172
|
+
}
|
|
173
|
+
|
|
138
174
|
function isWriteShapedLdvhTool(ldvhName) {
|
|
139
175
|
if (!ldvhName) return false;
|
|
140
176
|
if (EXTRA_WRITE_TOOLS.has(ldvhName)) return true;
|
|
@@ -180,26 +216,138 @@ function buildReviewSwitchHint(settings) {
|
|
|
180
216
|
}
|
|
181
217
|
|
|
182
218
|
function buildAssistSwitchHint(settings) {
|
|
183
|
-
const
|
|
184
|
-
|
|
185
|
-
lines.push("经验积累已开启:解决了非显而易见的坑后,可经 ldvh_pitfall_arm_delegate 授权并后台派发 ldvh-experience-recorder 沉淀 Pitfall。");
|
|
186
|
-
}
|
|
187
|
-
if (settings?.frictionDiscoveryEnabled !== false) {
|
|
188
|
-
lines.push("摩擦发现已开启:遇到规则冲突、工具卡点或重复返工时,可用 ldvh_friction_record_observation 记一条观察(同类累计到阈值自动入账)。");
|
|
189
|
-
}
|
|
190
|
-
return lines.length === 0 ? "" : `【LDVH 协助开关】${lines.join("")}`;
|
|
219
|
+
const switches = resolveCaptureSwitches(settings);
|
|
220
|
+
return buildCaptureNotice(switches);
|
|
191
221
|
}
|
|
192
222
|
|
|
193
223
|
function describeRecall(recall) {
|
|
194
224
|
const result = recall?.result ?? {};
|
|
195
225
|
const facts = Array.isArray(result.facts) ? result.facts.length : 0;
|
|
226
|
+
const carriers = Array.isArray(result.runtimeCarriers?.candidates)
|
|
227
|
+
? result.runtimeCarriers.candidates.length
|
|
228
|
+
: (Array.isArray(result.carriers) ? result.carriers.length : 0);
|
|
196
229
|
const specs = Array.isArray(result.specs) ? result.specs.length : 0;
|
|
197
|
-
|
|
198
|
-
|
|
230
|
+
const rulesCount = carriers + specs;
|
|
231
|
+
if (facts + rulesCount > 0) {
|
|
232
|
+
return `**LDVH 自主召回**:已注入 ${facts} 条事实候选、${rulesCount} 条运行期规则载体`;
|
|
199
233
|
}
|
|
200
234
|
return "**LDVH 常驻索引**:已载入当前项目的规范与经验索引";
|
|
201
235
|
}
|
|
202
236
|
|
|
237
|
+
function toProjectRelativeSourcePath(targetPath, cwd, projectPath) {
|
|
238
|
+
if (typeof targetPath !== "string" || targetPath.trim() === "" || typeof projectPath !== "string" || projectPath.trim() === "") {
|
|
239
|
+
return null;
|
|
240
|
+
}
|
|
241
|
+
const realProject = safeRealpathDeep(projectPath);
|
|
242
|
+
const realTarget = safeRealpathDeep(resolve(cwd || process.cwd(), targetPath));
|
|
243
|
+
const rel = relative(realProject, realTarget).replace(/\\/g, "/");
|
|
244
|
+
if (!rel || rel === "." || rel.startsWith("..") || rel.includes(":/") || rel.startsWith("/")) {
|
|
245
|
+
return null;
|
|
246
|
+
}
|
|
247
|
+
if (rel === "ldvh-base" || rel.startsWith("ldvh-base/")) {
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
250
|
+
return rel;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function turnPathStateFile(dataPath, conversationId) {
|
|
254
|
+
return dataPath("ldvh", "turn-paths", `${sha256Text(conversationId || "default").slice(0, 16)}.json`);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
async function readTurnPathState(file) {
|
|
258
|
+
try {
|
|
259
|
+
const raw = await readFile(file, "utf8");
|
|
260
|
+
const parsed = JSON.parse(raw);
|
|
261
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
262
|
+
if (!Number.isFinite(parsed.at) || (Date.now() - parsed.at) > TURN_STATE_TTL_MS) return null;
|
|
263
|
+
return {
|
|
264
|
+
at: parsed.at,
|
|
265
|
+
readOnlyTurn: parsed.readOnlyTurn === true,
|
|
266
|
+
pendingPaths: Array.isArray(parsed.pendingPaths) ? parsed.pendingPaths.filter((p) => typeof p === "string") : [],
|
|
267
|
+
notifiedUids: Array.isArray(parsed.notifiedUids) ? parsed.notifiedUids.filter((u) => typeof u === "string") : [],
|
|
268
|
+
};
|
|
269
|
+
} catch {
|
|
270
|
+
return null;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
async function pruneStaleTurnPathFiles(dir) {
|
|
275
|
+
try {
|
|
276
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
277
|
+
let checked = 0;
|
|
278
|
+
const now = Date.now();
|
|
279
|
+
for (const entry of entries) {
|
|
280
|
+
if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
|
|
281
|
+
checked += 1;
|
|
282
|
+
if (checked > 30) break;
|
|
283
|
+
const full = join(dir, entry.name);
|
|
284
|
+
try {
|
|
285
|
+
const info = await stat(full);
|
|
286
|
+
if (now - info.mtimeMs > TURN_STATE_TTL_MS) {
|
|
287
|
+
await unlink(full).catch(() => {});
|
|
288
|
+
}
|
|
289
|
+
} catch {
|
|
290
|
+
// 忽略单个文件清理异常
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
} catch {
|
|
294
|
+
// 目录不存在时忽略
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function sha256Text(text) {
|
|
299
|
+
return createHash("sha256").update(String(text ?? ""), "utf8").digest("hex");
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function turnStateKey(conversationId, cwd) {
|
|
303
|
+
return `${conversationId || "default"}|${cwd || ""}`;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
async function readTurnStateFile(stateFile) {
|
|
307
|
+
try {
|
|
308
|
+
const raw = await readFile(stateFile, "utf8");
|
|
309
|
+
const parsed = JSON.parse(raw);
|
|
310
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
311
|
+
} catch {
|
|
312
|
+
return {};
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function pruneTurnState(mapObj, now = Date.now()) {
|
|
317
|
+
const entries = Object.entries(mapObj).filter(([, v]) => (
|
|
318
|
+
v && typeof v === "object" && typeof v.hash === "string" && Number.isFinite(v.at) && (now - v.at) <= TURN_STATE_TTL_MS
|
|
319
|
+
));
|
|
320
|
+
entries.sort((a, b) => b[1].at - a[1].at);
|
|
321
|
+
return Object.fromEntries(entries.slice(0, TURN_STATE_MAX_ENTRIES));
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
async function collectGitChangedPaths(root) {
|
|
325
|
+
if (typeof root !== "string" || root.trim() === "") return [];
|
|
326
|
+
try {
|
|
327
|
+
const { stdout } = await execFileAsync(
|
|
328
|
+
"git",
|
|
329
|
+
["-C", root, "-c", "core.quotepath=false", "status", "--porcelain", "-uall"],
|
|
330
|
+
{ timeout: 200, windowsHide: true, maxBuffer: 256 * 1024 },
|
|
331
|
+
);
|
|
332
|
+
const out = [];
|
|
333
|
+
for (const line of String(stdout ?? "").split(/\r?\n/)) {
|
|
334
|
+
if (line.length < 4) continue;
|
|
335
|
+
let pathPart = line.slice(3).trim();
|
|
336
|
+
const arrowIdx = pathPart.indexOf(" -> ");
|
|
337
|
+
if (arrowIdx !== -1) pathPart = pathPart.slice(arrowIdx + 4).trim();
|
|
338
|
+
if (pathPart.startsWith('"') && pathPart.endsWith('"')) pathPart = pathPart.slice(1, -1);
|
|
339
|
+
const normalized = pathPart.replace(/\\/g, "/");
|
|
340
|
+
if (!normalized || normalized.endsWith("/")) continue;
|
|
341
|
+
if (normalized === "ldvh-base" || normalized.startsWith("ldvh-base/")) continue;
|
|
342
|
+
out.push(normalized);
|
|
343
|
+
if (out.length >= 20) break;
|
|
344
|
+
}
|
|
345
|
+
return out;
|
|
346
|
+
} catch {
|
|
347
|
+
return [];
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
203
351
|
function resolveCwd(payload) {
|
|
204
352
|
if (typeof payload?.cwd === "string" && payload.cwd.trim().length > 0) return payload.cwd.trim();
|
|
205
353
|
if (Array.isArray(payload?.workspacePaths) && typeof payload.workspacePaths[0] === "string") {
|
|
@@ -283,12 +431,39 @@ export function createHookEngine(options = {}) {
|
|
|
283
431
|
const key = conversationId || "default";
|
|
284
432
|
let entry = state.turnCache.get(key);
|
|
285
433
|
if (!entry) {
|
|
286
|
-
entry = {
|
|
434
|
+
entry = {
|
|
435
|
+
lastUserInput: null,
|
|
436
|
+
lastScopeState: null,
|
|
437
|
+
injectedInputs: new Set(),
|
|
438
|
+
editedFiles: new Set(),
|
|
439
|
+
pendingPaths: new Set(),
|
|
440
|
+
notifiedUids: new Set(),
|
|
441
|
+
readOnlyTurn: false,
|
|
442
|
+
errorSignals: 0,
|
|
443
|
+
hadFailureThenEdit: false,
|
|
444
|
+
calledPostWorkAsk: false,
|
|
445
|
+
calledExperienceAction: false,
|
|
446
|
+
calledFrictionAction: false,
|
|
447
|
+
stopGuardTriggered: false,
|
|
448
|
+
};
|
|
287
449
|
state.turnCache.set(key, entry);
|
|
288
450
|
}
|
|
289
451
|
return entry;
|
|
290
452
|
}
|
|
291
453
|
|
|
454
|
+
function resetTurnSignals(entry) {
|
|
455
|
+
entry.editedFiles = new Set();
|
|
456
|
+
entry.pendingPaths = new Set();
|
|
457
|
+
entry.notifiedUids = new Set();
|
|
458
|
+
entry.readOnlyTurn = false;
|
|
459
|
+
entry.errorSignals = 0;
|
|
460
|
+
entry.hadFailureThenEdit = false;
|
|
461
|
+
entry.calledPostWorkAsk = false;
|
|
462
|
+
entry.calledExperienceAction = false;
|
|
463
|
+
entry.calledFrictionAction = false;
|
|
464
|
+
entry.stopGuardTriggered = false;
|
|
465
|
+
}
|
|
466
|
+
|
|
292
467
|
async function handleSessionStart(payload = {}) {
|
|
293
468
|
const cwd = resolveCwd(payload);
|
|
294
469
|
const conversationId = payload.conversationId || "default";
|
|
@@ -301,6 +476,7 @@ export function createHookEngine(options = {}) {
|
|
|
301
476
|
}
|
|
302
477
|
|
|
303
478
|
const scope = await resolveGovernanceScope(dataPath, cwd);
|
|
479
|
+
|
|
304
480
|
const entry = getTurnEntry(conversationId);
|
|
305
481
|
entry.lastScopeState = scope.state;
|
|
306
482
|
|
|
@@ -334,8 +510,7 @@ export function createHookEngine(options = {}) {
|
|
|
334
510
|
injectSteps: [
|
|
335
511
|
{
|
|
336
512
|
systemMessage: {
|
|
337
|
-
systemMessage: combined
|
|
338
|
-
metadata: { user_markdown: label },
|
|
513
|
+
systemMessage: `${label}\n\n${combined}`,
|
|
339
514
|
},
|
|
340
515
|
},
|
|
341
516
|
],
|
|
@@ -347,6 +522,7 @@ export function createHookEngine(options = {}) {
|
|
|
347
522
|
const conversationId = payload.conversationId || "default";
|
|
348
523
|
const lastUserInput = typeof payload.lastUserInput === "string" ? payload.lastUserInput : "";
|
|
349
524
|
const scope = await resolveGovernanceScope(dataPath, cwd);
|
|
525
|
+
|
|
350
526
|
const entry = getTurnEntry(conversationId);
|
|
351
527
|
|
|
352
528
|
const blocks = [];
|
|
@@ -364,20 +540,150 @@ export function createHookEngine(options = {}) {
|
|
|
364
540
|
};
|
|
365
541
|
}
|
|
366
542
|
|
|
367
|
-
|
|
368
|
-
|
|
543
|
+
const turnStateFile = dataPath("ldvh", "hook-turn-state.json");
|
|
544
|
+
const inputHash = lastUserInput.length > 0 ? sha256Text(lastUserInput) : "";
|
|
545
|
+
const stateKey = turnStateKey(conversationId, cwd);
|
|
546
|
+
|
|
547
|
+
// 同回合(相同 lastUserInput)只注入一次,避免多轮 tool loop 与冷启动回退反复膨胀上下文
|
|
548
|
+
let persistedDuplicate = false;
|
|
549
|
+
if (inputHash !== "" && entry.lastUserInput !== lastUserInput) {
|
|
550
|
+
try {
|
|
551
|
+
const persisted = await readTurnStateFile(turnStateFile);
|
|
552
|
+
const rec = persisted[stateKey];
|
|
553
|
+
if (rec && rec.hash === inputHash && Number.isFinite(rec.at) && (Date.now() - rec.at) <= TURN_STATE_TTL_MS) {
|
|
554
|
+
persistedDuplicate = true;
|
|
555
|
+
entry.lastUserInput = lastUserInput;
|
|
556
|
+
}
|
|
557
|
+
} catch {
|
|
558
|
+
// 读状态失败按 fail-open 放行
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
if (lastUserInput.length > 0 && (entry.lastUserInput === lastUserInput || persistedDuplicate)) {
|
|
562
|
+
const pathFile = turnPathStateFile(dataPath, conversationId);
|
|
563
|
+
let consumedPaths = [...entry.pendingPaths];
|
|
564
|
+
let notifiedSet = new Set(entry.notifiedUids);
|
|
565
|
+
let isReadOnlyTurn = entry.readOnlyTurn === true;
|
|
566
|
+
entry.pendingPaths.clear();
|
|
567
|
+
try {
|
|
568
|
+
await withFileLock(pathFile, async () => {
|
|
569
|
+
const disk = await readTurnPathState(pathFile);
|
|
570
|
+
if (disk) {
|
|
571
|
+
if (disk.readOnlyTurn === true) isReadOnlyTurn = true;
|
|
572
|
+
for (const p of disk.pendingPaths) consumedPaths.push(p);
|
|
573
|
+
for (const u of disk.notifiedUids) notifiedSet.add(u);
|
|
574
|
+
if (disk.pendingPaths.length > 0) {
|
|
575
|
+
await writeFileAtomic(pathFile, `${JSON.stringify({
|
|
576
|
+
at: Date.now(),
|
|
577
|
+
readOnlyTurn: isReadOnlyTurn,
|
|
578
|
+
pendingPaths: [],
|
|
579
|
+
notifiedUids: [...notifiedSet],
|
|
580
|
+
}, null, 2)}\n`, { mode: 0o600, dirMode: 0o700 });
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
}, { timeoutMs: 2000, staleMs: 5000 });
|
|
584
|
+
} catch {
|
|
585
|
+
// 读/消费路径状态失败按 fail-open 放行
|
|
586
|
+
}
|
|
587
|
+
consumedPaths = [...new Set(consumedPaths)];
|
|
588
|
+
if (!isReadOnlyTurn && consumedPaths.length > 0 && scope.project?.path) {
|
|
589
|
+
try {
|
|
590
|
+
const pathRecall = await recallByFilePaths({
|
|
591
|
+
root: scope.project.path,
|
|
592
|
+
paths: consumedPaths,
|
|
593
|
+
excludeUids: [...notifiedSet],
|
|
594
|
+
});
|
|
595
|
+
if (pathRecall?.text) {
|
|
596
|
+
for (const uid of pathRecall.matchedUids ?? []) {
|
|
597
|
+
entry.notifiedUids.add(uid);
|
|
598
|
+
notifiedSet.add(uid);
|
|
599
|
+
}
|
|
600
|
+
try {
|
|
601
|
+
await withFileLock(pathFile, async () => {
|
|
602
|
+
const disk = await readTurnPathState(pathFile);
|
|
603
|
+
const mergedUids = new Set([...(disk?.notifiedUids ?? []), ...notifiedSet]);
|
|
604
|
+
await writeFileAtomic(pathFile, `${JSON.stringify({
|
|
605
|
+
at: Date.now(),
|
|
606
|
+
readOnlyTurn: isReadOnlyTurn,
|
|
607
|
+
pendingPaths: disk?.pendingPaths ?? [],
|
|
608
|
+
notifiedUids: [...mergedUids],
|
|
609
|
+
}, null, 2)}\n`, { mode: 0o600, dirMode: 0o700 });
|
|
610
|
+
}, { timeoutMs: 2000, staleMs: 5000 });
|
|
611
|
+
} catch {
|
|
612
|
+
// 回写已通知 uid 失败不阻断提醒注入
|
|
613
|
+
}
|
|
614
|
+
try {
|
|
615
|
+
await appendGateEvent(dataPath, {
|
|
616
|
+
tool: "hook:path_recall",
|
|
617
|
+
status: "completed",
|
|
618
|
+
codes: [scope.state],
|
|
619
|
+
detail: `路径增量提醒 ${pathRecall.shown ?? 0} 条`,
|
|
620
|
+
sessionId: conversationId,
|
|
621
|
+
cwd,
|
|
622
|
+
source: "hook",
|
|
623
|
+
});
|
|
624
|
+
} catch {
|
|
625
|
+
// 事件记账失败不阻断
|
|
626
|
+
}
|
|
627
|
+
blocks.push(pathRecall.text);
|
|
628
|
+
}
|
|
629
|
+
} catch {
|
|
630
|
+
// 路径增量提醒失败不阻断模型调用
|
|
631
|
+
}
|
|
632
|
+
}
|
|
369
633
|
if (blocks.length === 0) return {};
|
|
370
634
|
return {
|
|
371
635
|
injectSteps: [{ systemMessage: { systemMessage: blocks.join("\n\n") } }],
|
|
372
636
|
};
|
|
373
637
|
}
|
|
374
638
|
entry.lastUserInput = lastUserInput;
|
|
639
|
+
resetTurnSignals(entry);
|
|
640
|
+
if (inputHash !== "") {
|
|
641
|
+
try {
|
|
642
|
+
await withFileLock(turnStateFile, async () => {
|
|
643
|
+
const cur = pruneTurnState(await readTurnStateFile(turnStateFile));
|
|
644
|
+
cur[stateKey] = { hash: inputHash, at: Date.now() };
|
|
645
|
+
await writeFileAtomic(turnStateFile, `${JSON.stringify(cur, null, 2)}\n`, { mode: 0o600, dirMode: 0o700 });
|
|
646
|
+
}, { timeoutMs: 500, staleMs: 5000 });
|
|
647
|
+
} catch {
|
|
648
|
+
// 落盘去重失败按 fail-open 不阻断模型调用
|
|
649
|
+
}
|
|
650
|
+
}
|
|
375
651
|
|
|
376
652
|
const settings = await readPluginSettings(dataPath).catch(() => ({}));
|
|
377
653
|
const budgetInfo = resolveInjectionBudget(settings.injectionBudgetTier);
|
|
378
654
|
const limit = recallLimitForBudget(budgetInfo.bytes);
|
|
379
655
|
|
|
656
|
+
try {
|
|
657
|
+
const anchor = await buildGoalAnchorForRoot({
|
|
658
|
+
root: scope.project.path,
|
|
659
|
+
budgetChars: GOAL_ANCHOR_BUDGET_CHARS,
|
|
660
|
+
});
|
|
661
|
+
if (anchor?.text) {
|
|
662
|
+
blocks.push(anchor.text);
|
|
663
|
+
}
|
|
664
|
+
} catch {
|
|
665
|
+
// 目标锚点构建失败不阻断模型调用
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
const contextPathSet = new Set();
|
|
669
|
+
for (const p of entry.editedFiles) {
|
|
670
|
+
const rel = toProjectRelativeSourcePath(p, cwd, scope.project.path);
|
|
671
|
+
if (rel) contextPathSet.add(rel);
|
|
672
|
+
}
|
|
673
|
+
const convObserved = state.observedFiles.get(conversationId);
|
|
674
|
+
if (convObserved) {
|
|
675
|
+
for (const p of convObserved.keys()) {
|
|
676
|
+
const rel = toProjectRelativeSourcePath(p, cwd, scope.project.path);
|
|
677
|
+
if (rel) contextPathSet.add(rel);
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
for (const p of await collectGitChangedPaths(scope.project.path)) {
|
|
681
|
+
contextPathSet.add(p);
|
|
682
|
+
}
|
|
683
|
+
|
|
380
684
|
let recallNote = "";
|
|
685
|
+
let isReadOnlyTurn = false;
|
|
686
|
+
let deliveredFactUids = [];
|
|
381
687
|
if (lastUserInput.trim().length > 0) {
|
|
382
688
|
try {
|
|
383
689
|
const recall = await buildRecallInjection({
|
|
@@ -385,7 +691,12 @@ export function createHookEngine(options = {}) {
|
|
|
385
691
|
projectRoot: scope.project.path,
|
|
386
692
|
budgetBytes: budgetInfo.bytes,
|
|
387
693
|
limit,
|
|
694
|
+
contextPaths: [...contextPathSet],
|
|
388
695
|
});
|
|
696
|
+
isReadOnlyTurn = recall?.result?.baselineOnlyCause === "excluded-by-34-6";
|
|
697
|
+
deliveredFactUids = Array.isArray(recall?.result?.render?.renderedFactUids)
|
|
698
|
+
? recall.result.render.renderedFactUids
|
|
699
|
+
: [];
|
|
389
700
|
if (recall?.inject === true && typeof recall.text === "string" && recall.text.trim().length > 0) {
|
|
390
701
|
blocks.push(recall.text.trim());
|
|
391
702
|
recallNote = describeRecall(recall);
|
|
@@ -394,6 +705,21 @@ export function createHookEngine(options = {}) {
|
|
|
394
705
|
// 召回失败不阻断模型调用
|
|
395
706
|
}
|
|
396
707
|
}
|
|
708
|
+
entry.readOnlyTurn = isReadOnlyTurn;
|
|
709
|
+
entry.notifiedUids = new Set(deliveredFactUids);
|
|
710
|
+
const pathFile = turnPathStateFile(dataPath, conversationId);
|
|
711
|
+
try {
|
|
712
|
+
await withFileLock(pathFile, async () => {
|
|
713
|
+
await writeFileAtomic(pathFile, `${JSON.stringify({
|
|
714
|
+
at: Date.now(),
|
|
715
|
+
readOnlyTurn: isReadOnlyTurn,
|
|
716
|
+
pendingPaths: [],
|
|
717
|
+
notifiedUids: deliveredFactUids,
|
|
718
|
+
}, null, 2)}\n`, { mode: 0o600, dirMode: 0o700 });
|
|
719
|
+
}, { timeoutMs: 2000, staleMs: 5000 });
|
|
720
|
+
} catch {
|
|
721
|
+
// 写入路径状态失败按 fail-open 不阻断模型调用
|
|
722
|
+
}
|
|
397
723
|
|
|
398
724
|
try {
|
|
399
725
|
const directory = await buildNormDirectoryForRoot({
|
|
@@ -414,6 +740,9 @@ export function createHookEngine(options = {}) {
|
|
|
414
740
|
if (assistHint) blocks.push(assistHint);
|
|
415
741
|
|
|
416
742
|
if (blocks.length === 0) return {};
|
|
743
|
+
if (recallNote) {
|
|
744
|
+
blocks.unshift(recallNote);
|
|
745
|
+
}
|
|
417
746
|
try {
|
|
418
747
|
await appendGateEvent(dataPath, {
|
|
419
748
|
tool: "hook:pre_invocation",
|
|
@@ -431,7 +760,6 @@ export function createHookEngine(options = {}) {
|
|
|
431
760
|
injectSteps: [{
|
|
432
761
|
systemMessage: {
|
|
433
762
|
systemMessage: blocks.join("\n\n"),
|
|
434
|
-
...(recallNote ? { metadata: { user_markdown: recallNote } } : {}),
|
|
435
763
|
},
|
|
436
764
|
}],
|
|
437
765
|
};
|
|
@@ -439,6 +767,10 @@ export function createHookEngine(options = {}) {
|
|
|
439
767
|
|
|
440
768
|
async function handlePreToolUse(payload = {}) {
|
|
441
769
|
const result = await handlePreToolUseCore(payload);
|
|
770
|
+
if (result?.decision === "deny") {
|
|
771
|
+
const entry = getTurnEntry(payload?.conversationId || "default");
|
|
772
|
+
entry.errorSignals += 1;
|
|
773
|
+
}
|
|
442
774
|
if (result?.decision === "deny" || result?.decision === "force_ask") {
|
|
443
775
|
const unwrapped = unwrapLdvhToolCall(payload?.toolCall?.name, payload?.toolCall?.args);
|
|
444
776
|
await appendGateEvent(dataPath, {
|
|
@@ -495,6 +827,12 @@ export function createHookEngine(options = {}) {
|
|
|
495
827
|
reason: "子代理不得调用 ldvh_pitfall_arm_delegate(25 §13 仅主控会话可授权)",
|
|
496
828
|
};
|
|
497
829
|
}
|
|
830
|
+
if (ldvhName === "ldvh_friction_write") {
|
|
831
|
+
return {
|
|
832
|
+
decision: "deny",
|
|
833
|
+
reason: "子代理禁止直接调用 ldvh_friction_write,请改用 ldvh_friction_record_observation 写入观察缓冲(同源满 3 次由工具以代理签名自动晋升)",
|
|
834
|
+
};
|
|
835
|
+
}
|
|
498
836
|
if (ldvhName === "ldvh_pitfall_write") {
|
|
499
837
|
if (toolArgs.action !== "create") {
|
|
500
838
|
return {
|
|
@@ -558,6 +896,12 @@ export function createHookEngine(options = {}) {
|
|
|
558
896
|
|
|
559
897
|
if ((rawName === "write_file" || rawName === "edit_file") && scope.state === "governed") {
|
|
560
898
|
const targetPath = args.Path ?? args.path;
|
|
899
|
+
if (isInsideLdvhBase(targetPath, cwd, scope.project?.path)) {
|
|
900
|
+
return {
|
|
901
|
+
decision: "deny",
|
|
902
|
+
reason: `LDVH 事实源守卫:禁止直接写入受管辖项目 ldvh-base/ 下的事实文件(${targetPath}),请改用对应的 ldvh_*_write 受控写入工具`,
|
|
903
|
+
};
|
|
904
|
+
}
|
|
561
905
|
if (typeof targetPath === "string" && targetPath.trim().length > 0) {
|
|
562
906
|
const key = normalizePathKey(targetPath, cwd);
|
|
563
907
|
const convObserved = state.observedFiles.get(conversationId);
|
|
@@ -613,14 +957,26 @@ export function createHookEngine(options = {}) {
|
|
|
613
957
|
const cwd = resolveCwd(payload);
|
|
614
958
|
const conversationId = payload.conversationId || "default";
|
|
615
959
|
const transcriptPath = typeof payload.transcriptPath === "string" ? payload.transcriptPath : null;
|
|
960
|
+
const entry = getTurnEntry(conversationId);
|
|
616
961
|
|
|
962
|
+
if (typeof payload.error === "string" && payload.error.trim().length > 0) {
|
|
963
|
+
entry.errorSignals += 1;
|
|
964
|
+
return {};
|
|
965
|
+
}
|
|
617
966
|
if (payload.error) {
|
|
967
|
+
entry.errorSignals += 1;
|
|
618
968
|
return {};
|
|
619
969
|
}
|
|
620
970
|
|
|
621
971
|
if (rawName === "read_file" || rawName === "write_file" || rawName === "edit_file") {
|
|
622
972
|
const targetPath = args.Path ?? args.path;
|
|
623
973
|
if (typeof targetPath === "string" && targetPath.trim().length > 0) {
|
|
974
|
+
if (rawName === "write_file" || rawName === "edit_file") {
|
|
975
|
+
entry.editedFiles.add(normalizePathKey(targetPath, cwd));
|
|
976
|
+
if (entry.errorSignals > 0) {
|
|
977
|
+
entry.hadFailureThenEdit = true;
|
|
978
|
+
}
|
|
979
|
+
}
|
|
624
980
|
try {
|
|
625
981
|
const info = await stat(resolve(cwd || process.cwd(), targetPath));
|
|
626
982
|
let convMap = state.observedFiles.get(conversationId);
|
|
@@ -635,11 +991,40 @@ export function createHookEngine(options = {}) {
|
|
|
635
991
|
} catch {
|
|
636
992
|
// 读取不存在或无法 stat 的路径忽略
|
|
637
993
|
}
|
|
994
|
+
try {
|
|
995
|
+
const scope = await resolveGovernanceScope(dataPath, cwd);
|
|
996
|
+
if (scope.state === "governed" && scope.project?.path) {
|
|
997
|
+
const relSource = toProjectRelativeSourcePath(targetPath, cwd, scope.project.path);
|
|
998
|
+
if (relSource) {
|
|
999
|
+
entry.pendingPaths.add(relSource);
|
|
1000
|
+
const pathFile = turnPathStateFile(dataPath, conversationId);
|
|
1001
|
+
await withFileLock(pathFile, async () => {
|
|
1002
|
+
const disk = await readTurnPathState(pathFile);
|
|
1003
|
+
const merged = [...new Set([...(disk?.pendingPaths ?? []), relSource])].slice(-12);
|
|
1004
|
+
await writeFileAtomic(pathFile, `${JSON.stringify({
|
|
1005
|
+
at: Date.now(),
|
|
1006
|
+
readOnlyTurn: disk?.readOnlyTurn ?? entry.readOnlyTurn === true,
|
|
1007
|
+
pendingPaths: merged,
|
|
1008
|
+
notifiedUids: disk?.notifiedUids ?? [...entry.notifiedUids],
|
|
1009
|
+
}, null, 2)}\n`, { mode: 0o600, dirMode: 0o700 });
|
|
1010
|
+
}, { timeoutMs: 2000, staleMs: 5000 });
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
} catch {
|
|
1014
|
+
// 记录待提醒路径失败不阻断工具返回
|
|
1015
|
+
}
|
|
638
1016
|
}
|
|
639
1017
|
return {};
|
|
640
1018
|
}
|
|
641
1019
|
|
|
642
1020
|
if (rawName === "invoke_subagent") {
|
|
1021
|
+
const subagentType = String(args.TypeName ?? args.typeName ?? args.type ?? "");
|
|
1022
|
+
if (subagentType === "ldvh-experience-recorder") {
|
|
1023
|
+
entry.calledExperienceAction = true;
|
|
1024
|
+
}
|
|
1025
|
+
if (subagentType === "ldvh-friction-recorder") {
|
|
1026
|
+
entry.calledFrictionAction = true;
|
|
1027
|
+
}
|
|
643
1028
|
const childId = typeof args.conversationId === "string" && args.conversationId.length > 0
|
|
644
1029
|
? args.conversationId
|
|
645
1030
|
: extractSubagentIdFromTranscript(await readJsonLinesTail(transcriptPath));
|
|
@@ -664,8 +1049,17 @@ export function createHookEngine(options = {}) {
|
|
|
664
1049
|
}
|
|
665
1050
|
|
|
666
1051
|
const unwrapped = unwrapLdvhToolCall(rawName, args);
|
|
1052
|
+
if (unwrapped?.ldvhName === "ldvh_pitfall_arm_delegate" || unwrapped?.ldvhName === "ldvh_pitfall_write") {
|
|
1053
|
+
entry.calledExperienceAction = true;
|
|
1054
|
+
}
|
|
1055
|
+
if (unwrapped?.ldvhName === "ldvh_friction_record_observation") {
|
|
1056
|
+
entry.calledFrictionAction = true;
|
|
1057
|
+
}
|
|
667
1058
|
if (unwrapped && (unwrapped.ldvhName === "ldvh_review_ask" || unwrapped.ldvhName === "ldvh_research_consult")) {
|
|
668
1059
|
const { ldvhName, toolArgs } = unwrapped;
|
|
1060
|
+
if (ldvhName === "ldvh_review_ask" && toolArgs.point === REVIEW_ASK_POINTS.POST_WORK) {
|
|
1061
|
+
entry.calledPostWorkAsk = true;
|
|
1062
|
+
}
|
|
669
1063
|
const point = ldvhName === "ldvh_research_consult"
|
|
670
1064
|
? REVIEW_ASK_POINTS.RESEARCH
|
|
671
1065
|
: (toolArgs.point === REVIEW_ASK_POINTS.POST_WORK ? REVIEW_ASK_POINTS.POST_WORK : REVIEW_ASK_POINTS.PRE_ACTION);
|
|
@@ -715,8 +1109,9 @@ export function createHookEngine(options = {}) {
|
|
|
715
1109
|
async function handleStop(payload = {}) {
|
|
716
1110
|
const cwd = resolveCwd(payload);
|
|
717
1111
|
const conversationId = payload.conversationId || "default";
|
|
1112
|
+
let scope = { state: "not_governed", project: null };
|
|
718
1113
|
try {
|
|
719
|
-
|
|
1114
|
+
scope = await resolveGovernanceScope(dataPath, cwd);
|
|
720
1115
|
if (scope.state === "governed") {
|
|
721
1116
|
await recordRun(dataPath, {
|
|
722
1117
|
stage: "antigravity/stop",
|
|
@@ -729,7 +1124,86 @@ export function createHookEngine(options = {}) {
|
|
|
729
1124
|
} catch {
|
|
730
1125
|
// 日志记录失败不阻断结束
|
|
731
1126
|
}
|
|
732
|
-
|
|
1127
|
+
|
|
1128
|
+
if (scope.state !== "governed") return { decision: "allow" };
|
|
1129
|
+
if (state.subagents.has(conversationId)) return { decision: "allow" };
|
|
1130
|
+
if (payload.continuationActive === true) return { decision: "allow" };
|
|
1131
|
+
if (payload.terminationReason && payload.terminationReason !== "NO_TOOL_CALL") {
|
|
1132
|
+
return { decision: "allow" };
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
const turnStateFile = dataPath("ldvh", "hook-turn-state.json");
|
|
1136
|
+
try {
|
|
1137
|
+
await withFileLock(turnStateFile, async () => {
|
|
1138
|
+
const cur = await readTurnStateFile(turnStateFile);
|
|
1139
|
+
const prefix = `${conversationId}|`;
|
|
1140
|
+
let changed = false;
|
|
1141
|
+
for (const k of Object.keys(cur)) {
|
|
1142
|
+
if (k.startsWith(prefix)) {
|
|
1143
|
+
delete cur[k];
|
|
1144
|
+
changed = true;
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
if (changed) {
|
|
1148
|
+
await writeFileAtomic(turnStateFile, `${JSON.stringify(pruneTurnState(cur), null, 2)}\n`, { mode: 0o600, dirMode: 0o700 });
|
|
1149
|
+
}
|
|
1150
|
+
}, { timeoutMs: 500, staleMs: 5000 });
|
|
1151
|
+
} catch {
|
|
1152
|
+
// 清理去重状态失败不阻断结束
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
try {
|
|
1156
|
+
await unlink(turnPathStateFile(dataPath, conversationId)).catch(() => {});
|
|
1157
|
+
await pruneStaleTurnPathFiles(dataPath("ldvh", "turn-paths"));
|
|
1158
|
+
} catch {
|
|
1159
|
+
// 清理路径状态失败不阻断结束
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
const entry = getTurnEntry(conversationId);
|
|
1163
|
+
if (entry.stopGuardTriggered === true) return { decision: "allow" };
|
|
1164
|
+
if (entry.editedFiles.size === 0 && entry.errorSignals === 0) {
|
|
1165
|
+
return { decision: "allow" };
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
const settings = await readPluginSettings(dataPath).catch(() => ({}));
|
|
1169
|
+
const reviewSettings = resolveReviewAskSettings(settings);
|
|
1170
|
+
const captureSwitches = resolveCaptureSwitches(settings);
|
|
1171
|
+
const reminders = [];
|
|
1172
|
+
|
|
1173
|
+
if (reviewSettings.postWork && entry.editedFiles.size >= 2 && !entry.calledPostWorkAsk) {
|
|
1174
|
+
reminders.push(
|
|
1175
|
+
`本回合修改了 ${entry.editedFiles.size} 个文件且已开启「收口前复核」开关,请先调用 \`ldvh_review_ask(point="post-work", conclusion_summary=...)\` 请示或派发复核,再向用户做最终交付。`,
|
|
1176
|
+
);
|
|
1177
|
+
}
|
|
1178
|
+
if (captureSwitches.experienceEnabled && entry.hadFailureThenEdit && !entry.calledExperienceAction) {
|
|
1179
|
+
reminders.push(
|
|
1180
|
+
"本回合经历了报错/拦截并随后修改了文件,请完成当场经验自查:主控不自行查重或落笔,若有可回指的失败机制材料,请调用 `ldvh_pitfall_arm_delegate` 授权并后台派发 `ldvh-experience-recorder`(派完即撒手);若无则简述跳过原因。",
|
|
1181
|
+
);
|
|
1182
|
+
}
|
|
1183
|
+
if (captureSwitches.frictionEnabled && entry.errorSignals >= 2 && !entry.calledFrictionAction) {
|
|
1184
|
+
reminders.push(
|
|
1185
|
+
`本回合出现了 ${entry.errorSignals} 次工具失败或拦截信号,请检查是否存在重复卡点或规则冲突;主控不亲自落笔,若有可回指材料,请后台派发 \`ldvh-friction-recorder\` 写入观察缓冲(满 3 次由工具以代理签名自动晋升),若无则简述跳过。`,
|
|
1186
|
+
);
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
if (reminders.length === 0) return { decision: "allow" };
|
|
1190
|
+
|
|
1191
|
+
entry.stopGuardTriggered = true;
|
|
1192
|
+
const reason = `【LDVH 收口前护栏(本回合仅触发一次)】\n${reminders.map((item, idx) => `${idx + 1}. ${item}`).join("\n")}`;
|
|
1193
|
+
try {
|
|
1194
|
+
await appendGateEvent(dataPath, {
|
|
1195
|
+
tool: "hook:stop",
|
|
1196
|
+
status: "completed",
|
|
1197
|
+
codes: ["continue"],
|
|
1198
|
+
detail: reminders.join(" | "),
|
|
1199
|
+
sessionId: conversationId,
|
|
1200
|
+
cwd,
|
|
1201
|
+
source: "hook",
|
|
1202
|
+
});
|
|
1203
|
+
} catch {
|
|
1204
|
+
// 观测记账失败不阻断继续
|
|
1205
|
+
}
|
|
1206
|
+
return { decision: "continue", reason };
|
|
733
1207
|
}
|
|
734
1208
|
|
|
735
1209
|
return {
|