ld-vibe-harness 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/.claude-plugin/plugin.json +2 -2
  2. package/.codex-plugin/plugin.json +4 -4
  3. package/CHANGELOG.md +32 -0
  4. package/README.en.md +13 -12
  5. package/README.md +20 -20
  6. package/adapters/antigravity/installer.js +26 -8
  7. package/adapters/dsh/index.js +0 -3
  8. package/adapters/dsh/package.json +2 -2
  9. package/agents/ldvh-experience-recorder.md +2 -3
  10. package/agents/ldvh-post-work-reviewer.md +0 -1
  11. package/agents/ldvh-pre-action-reviewer.md +0 -1
  12. package/agents/ldvh-researcher.md +1 -2
  13. package/cli/ldvh.mjs +137 -5
  14. package/docs/ARCHITECTURE.md +37 -37
  15. package/docs/PRIVACY.md +7 -6
  16. package/hooks/_client.mjs +1 -12
  17. package/hooks/hook-engine.js +684 -84
  18. package/lib/capture-notice.js +8 -22
  19. package/lib/commit-validation.js +0 -59
  20. package/lib/data-paths.js +0 -1
  21. package/lib/experience-arming.js +10 -4
  22. package/lib/gate-events.js +27 -2
  23. package/lib/git-gate-runner.js +83 -34
  24. package/lib/goal-anchor.js +17 -45
  25. package/lib/goal-tools.js +4 -26
  26. package/lib/goal-writer.js +5 -18
  27. package/lib/governed-projects.js +18 -7
  28. package/lib/guidance-budget.js +2 -2
  29. package/lib/guidance-text.js +7 -7
  30. package/lib/hook-manager.js +40 -14
  31. package/lib/hook-repair.js +77 -13
  32. package/lib/host-api.js +7 -3
  33. package/lib/host-seams.js +78 -57
  34. package/lib/idle-settings.js +1 -4
  35. package/lib/intent-tools.js +6 -14
  36. package/lib/intent-writer.js +12 -45
  37. package/lib/ldvh-tools.js +26 -61
  38. package/lib/object-identifier.js +0 -2
  39. package/lib/object-reference.js +0 -2
  40. package/lib/operation-declarations.bundle.json +1 -64
  41. package/lib/recall-criteria.bundle.json +2 -67
  42. package/lib/recall-criteria.js +0 -2
  43. package/lib/recall-injection.js +1 -5
  44. package/lib/recall-synonyms.js +1 -3
  45. package/lib/research-consult-tools.js +201 -19
  46. package/lib/research-consult.js +49 -27
  47. package/lib/review-ask-tool.js +75 -11
  48. package/lib/review-ask.js +12 -9
  49. package/lib/source-recall.js +6 -16
  50. package/lib/web-preferences.js +2 -2
  51. package/package.json +2 -2
  52. package/plugin-specs/experience-accumulation-system-foundation.yaml +5 -25
  53. package/plugin-specs/fact-model-common.yaml +3 -14
  54. package/plugin-specs/gate-consult-system-foundation.yaml +39 -29
  55. package/plugin-specs/goal-fact-type.yaml +20 -67
  56. package/plugin-specs/goal-planning-system-foundation.yaml +27 -98
  57. package/plugin-specs/intent-fact-type.yaml +13 -22
  58. package/plugin-specs/intent-record-system-foundation.yaml +1 -2
  59. package/plugin-specs/ldvh-root.yaml +6 -6
  60. package/plugin-specs/norm-fact-type.yaml +1 -1
  61. package/plugin-specs/pitfall-fact-type.yaml +5 -49
  62. package/plugin-specs/report-fact-type.yaml +1 -1
  63. package/plugin-specs/research-system-foundation.yaml +12 -9
  64. package/plugin.json +4 -4
  65. package/rules/AGENTS.md +3 -3
  66. package/server/local-daemon.js +86 -28
  67. package/server/mcp-server.js +211 -53
  68. package/server/tool-registry.js +0 -23
  69. package/skills/ldvh-governance-flow/SKILL.md +10 -19
  70. package/skills/ldvh-onboarding/SKILL.md +2 -2
  71. package/agents/ldvh-friction-recorder.md +0 -27
  72. package/lib/aux-task-registry.js +0 -129
  73. package/lib/friction-discovery.js +0 -383
  74. package/lib/friction-failure-registration.js +0 -56
  75. package/lib/friction-observation-buffer.js +0 -889
  76. package/lib/friction-promotion-lock.js +0 -124
  77. package/lib/friction-review-promotion.js +0 -193
  78. package/lib/friction-tools.js +0 -829
  79. package/lib/friction-writer.js +0 -1123
  80. package/lib/milestone-tools.js +0 -684
  81. package/lib/milestone-writer.js +0 -707
  82. package/lib/verification-run.js +0 -195
  83. package/plugin-specs/friction-fact-type.yaml +0 -333
  84. package/plugin-specs/friction-settlement-system-foundation.yaml +0 -334
  85. package/plugin-specs/milestone-fact-type.yaml +0 -212
@@ -1,7 +1,7 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { createHash } from "node:crypto";
3
3
  import { realpathSync } from "node:fs";
4
- import { readdir, readFile, stat, unlink } from "node:fs/promises";
4
+ import { open, readdir, readFile, stat, unlink } from "node:fs/promises";
5
5
  import { basename, dirname, join, relative, resolve } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { promisify } from "node:util";
@@ -27,6 +27,9 @@ import { recordRun } from "../lib/idle-runlog.js";
27
27
  import { withFileLock, writeFileAtomic } from "../lib/atomic-write.js";
28
28
  import { appendGateEvent } from "../lib/gate-events.js";
29
29
  import { buildCaptureNotice, resolveCaptureSwitches } from "../lib/capture-notice.js";
30
+ import { buildResearchFingerprintTask } from "../lib/research-consult.js";
31
+ import { readIntentObject } from "../lib/intent-writer.js";
32
+ import { readNormObject } from "../lib/norm-writer.js";
30
33
 
31
34
  const execFileAsync = promisify(execFile);
32
35
  const REPO_ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
@@ -34,16 +37,26 @@ const RUNNER_PATH = join(REPO_ROOT, "lib", "git-gate-runner.js");
34
37
  const TURN_STATE_TTL_MS = 15 * 60 * 1000;
35
38
  const TURN_STATE_MAX_ENTRIES = 20;
36
39
 
40
+ export const HUMAN_GATE_APPROVE_OPTION = "确认执行";
41
+ export const HUMAN_GATE_REJECT_OPTION = "拒绝取消";
42
+ export const HUMAN_GATE_OPTIONS = Object.freeze([
43
+ HUMAN_GATE_APPROVE_OPTION,
44
+ HUMAN_GATE_REJECT_OPTION,
45
+ ]);
46
+ export const HUMAN_GATE_TTL_MS = 10 * 60 * 1000;
47
+ export const SUBAGENT_SESSION_TTL_MS = 60 * 60 * 1000;
48
+ export const PENDING_ASK_TTL_MS = 10 * 60 * 1000;
49
+ const TRANSCRIPT_TAIL_BYTES = 512 * 1024;
50
+ const HUMAN_GATE_OPTION_SET = new Set(HUMAN_GATE_OPTIONS);
51
+
37
52
  const EXTRA_WRITE_TOOLS = new Set([
38
53
  "ldvh_register_governed_project",
39
54
  "ldvh_unregister_governed_project",
40
55
  "ldvh_goal_write",
41
- "ldvh_milestone_write",
42
56
  "ldvh_intent_write",
43
57
  "ldvh_norm_write",
44
58
  "ldvh_report_write",
45
59
  "ldvh_pitfall_write",
46
- "ldvh_friction_write",
47
60
  ]);
48
61
 
49
62
  /**
@@ -205,13 +218,142 @@ function isHumanGateAction(ldvhName, args) {
205
218
  return { gated: false, label: "" };
206
219
  }
207
220
 
221
+ function clipText(value, max = 120) {
222
+ const s = typeof value === "string" ? value.trim() : "";
223
+ if (!s) return "";
224
+ return s.length > max ? `${s.slice(0, max - 1)}…` : s;
225
+ }
226
+
227
+ async function resolveHumanGateSpec(ldvhName, args, { scope, cwd, conversationId } = {}) {
228
+ const quick = isHumanGateAction(ldvhName, args);
229
+ if (!quick.gated) return { gated: false };
230
+
231
+ const projectRoot = scope?.project?.path ?? cwd ?? "";
232
+ const factSourceRoot = projectRoot ? join(projectRoot, "ldvh-base") : "";
233
+ const projectId = scope?.project?.id;
234
+ let action = "";
235
+ let targetKey = "";
236
+ let nextStatus = "";
237
+ let title = "";
238
+ let label = quick.label;
239
+ let question = "";
240
+
241
+ if (ldvhName === "ldvh_register_governed_project" || ldvhName === "ldvh_unregister_governed_project") {
242
+ const isUnreg = ldvhName === "ldvh_unregister_governed_project";
243
+ action = isUnreg ? "unregister" : "register";
244
+ const targetPath = typeof args?.path === "string" && args.path.trim().length > 0 ? args.path.trim() : (cwd || "");
245
+ const projId = typeof args?.id === "string" && args.id.trim().length > 0 ? args.id.trim() : (basename(targetPath) || "(未命名项目)");
246
+ title = projId;
247
+ targetKey = `${projId}|${targetPath}`;
248
+ const actionLabel = isUnreg ? "取消项目管辖" : "登记受管辖项目";
249
+ label = `${actionLabel}:${projId}${targetPath ? `(${targetPath})` : ""}`;
250
+ question = `LDVH Human Gate - 是否${actionLabel}:${projId}${targetPath ? `(${targetPath})` : ""}?`;
251
+ } else if (ldvhName === "ldvh_intent_write") {
252
+ action = args?.action === "create" ? "create" : "update";
253
+ if (action === "create") {
254
+ const draftTitle = typeof args?.frontmatter_draft?.title === "string" ? args.frontmatter_draft.title.trim() : "";
255
+ title = draftTitle || "(未填标题)";
256
+ targetKey = title;
257
+ label = `创建 Intent:${title}`;
258
+ question = `LDVH Human Gate - 是否创建 Intent:${title}?`;
259
+ } else {
260
+ nextStatus = String(args?.frontmatter_after?.status ?? "");
261
+ let resolvedUid = typeof args?.object_uid === "string" ? args.object_uid.trim() : "";
262
+ let resolvedTitle = typeof args?.frontmatter_after?.title === "string" ? args.frontmatter_after.title.trim() : "";
263
+ if (!resolvedTitle && factSourceRoot && resolvedUid) {
264
+ try {
265
+ const readRes = await readIntentObject({
266
+ factSourceRoot,
267
+ objectUid: resolvedUid,
268
+ currentProjectId: projectId,
269
+ });
270
+ if (readRes?.ok && readRes.value) {
271
+ resolvedUid = readRes.value.object_uid ?? resolvedUid;
272
+ resolvedTitle = typeof readRes.value.frontmatter?.title === "string"
273
+ ? readRes.value.frontmatter.title.trim()
274
+ : "";
275
+ }
276
+ } catch {
277
+ // 读取失败时回退到 UID
278
+ }
279
+ }
280
+ title = resolvedTitle || resolvedUid || "(未知 Intent)";
281
+ targetKey = resolvedUid || title;
282
+ const verb = nextStatus === "implemented" ? "落实" : "废弃";
283
+ const reasonText = clipText(args?.frontmatter_after?.disposition || args?.change_summary, 100);
284
+ label = `${verb} Intent:${title}${reasonText ? `(理由:${reasonText})` : ""}`;
285
+ question = `LDVH Human Gate - 是否${verb} Intent:${title}?${reasonText ? `(理由:${reasonText})` : ""}`;
286
+ }
287
+ } else if (ldvhName === "ldvh_norm_write") {
288
+ action = args?.action === "create" ? "create" : "update";
289
+ if (action === "create") {
290
+ const draftTitle = typeof args?.frontmatter_draft?.title === "string" ? args.frontmatter_draft.title.trim() : "";
291
+ title = draftTitle || "(未填标题)";
292
+ targetKey = title;
293
+ const dirKey = clipText(args?.frontmatter_draft?.direction_key, 60);
294
+ label = `创建 Norm:${title}${dirKey ? `(方向键:${dirKey})` : ""}`;
295
+ question = `LDVH Human Gate - 是否创建 Norm:${title}${dirKey ? `(方向键:${dirKey})` : ""}?`;
296
+ } else {
297
+ nextStatus = "retired";
298
+ let resolvedUid = typeof args?.object_uid === "string" ? args.object_uid.trim() : "";
299
+ let resolvedTitle = typeof args?.frontmatter_after?.title === "string" ? args.frontmatter_after.title.trim() : "";
300
+ if (!resolvedTitle && factSourceRoot && resolvedUid) {
301
+ try {
302
+ const readRes = await readNormObject({
303
+ factSourceRoot,
304
+ objectUid: resolvedUid,
305
+ currentProjectId: projectId,
306
+ });
307
+ if (readRes?.ok && readRes.value) {
308
+ resolvedUid = readRes.value.object_uid ?? resolvedUid;
309
+ resolvedTitle = typeof readRes.value.frontmatter?.title === "string"
310
+ ? readRes.value.frontmatter.title.trim()
311
+ : "";
312
+ }
313
+ } catch {
314
+ // 读取失败时回退到 UID
315
+ }
316
+ }
317
+ title = resolvedTitle || resolvedUid || "(未知 Norm)";
318
+ targetKey = resolvedUid || title;
319
+ const reasonText = clipText(args?.frontmatter_after?.retirement_reason || args?.change_summary, 100);
320
+ label = `退役 Norm:${title}${reasonText ? `(理由:${reasonText})` : ""}`;
321
+ question = `LDVH Human Gate - 是否退役 Norm:${title}?${reasonText ? `(理由:${reasonText})` : ""}`;
322
+ }
323
+ }
324
+
325
+ if (!question) {
326
+ question = `LDVH Human Gate - 是否执行:${label}?`;
327
+ }
328
+ const fingerprint = sha256Text([
329
+ conversationId || "default",
330
+ projectRoot,
331
+ ldvhName,
332
+ action,
333
+ targetKey,
334
+ nextStatus,
335
+ title,
336
+ ].join("|"));
337
+
338
+ return {
339
+ gated: true,
340
+ ldvhName,
341
+ action,
342
+ title,
343
+ label,
344
+ question,
345
+ fingerprint,
346
+ options: [...HUMAN_GATE_OPTIONS],
347
+ };
348
+ }
349
+
208
350
  function buildReviewSwitchHint(settings) {
209
351
  const active = [];
210
352
  if (settings.preAction) active.push("行动前审查");
211
353
  if (settings.postWork) active.push("收口前复核");
212
354
  if (settings.researchConsult) active.push("遇难题联网调查提请");
213
355
  if (active.length === 0) return "";
214
- const mode = settings.silentRun ? "静默执行(直接给派发模板)" : "征询模式(经 ldvh_review_ask / ask_question 请示)";
356
+ const mode = settings.silentRun ? "静默执行(仅作用于前两处直接给派发模板;第三处联网调查始终征询)" : "征询模式(经 ldvh_review_ask / ask_question 请示)";
215
357
  return `【LDVH 把关请示开关】已开启:${active.join("、")}|模式:${mode}。`;
216
358
  }
217
359
 
@@ -361,17 +503,31 @@ function isGitCommitCommand(commandLine) {
361
503
  return /(?:^|[;&|\s])git(?:\.exe)?\b[\s\S]*\bcommit\b/i.test(commandLine);
362
504
  }
363
505
 
364
- async function readJsonLinesTail(filePath, maxBytes = 64 * 1024) {
506
+ async function readJsonLinesTail(filePath, maxBytes = TRANSCRIPT_TAIL_BYTES) {
365
507
  if (typeof filePath !== "string" || filePath.length === 0) return [];
366
- let text;
508
+ let text = "";
509
+ let fh = null;
367
510
  try {
368
- text = await readFile(filePath, "utf8");
511
+ fh = await open(filePath, "r");
512
+ const info = await fh.stat();
513
+ const size = Number(info.size ?? 0);
514
+ if (size <= 0) return [];
515
+ const start = Math.max(0, size - maxBytes);
516
+ const len = size - start;
517
+ const buf = Buffer.alloc(len);
518
+ const { bytesRead } = await fh.read(buf, 0, len, start);
519
+ text = buf.toString("utf8", 0, bytesRead);
520
+ if (start > 0) {
521
+ const firstNewline = text.indexOf("\n");
522
+ text = firstNewline >= 0 ? text.slice(firstNewline + 1) : "";
523
+ }
369
524
  } catch {
370
525
  return [];
526
+ } finally {
527
+ await fh?.close().catch(() => {});
371
528
  }
372
- const sliced = text.length > maxBytes ? text.slice(-maxBytes) : text;
373
529
  const lines = [];
374
- for (const line of sliced.split(/\r?\n/)) {
530
+ for (const line of text.split(/\r?\n/)) {
375
531
  const trimmed = line.trim();
376
532
  if (!trimmed) continue;
377
533
  try {
@@ -383,26 +539,192 @@ async function readJsonLinesTail(filePath, maxBytes = 64 * 1024) {
383
539
  return lines;
384
540
  }
385
541
 
386
- function extractSubagentIdFromTranscript(events) {
542
+ function parseStrictAskAnswerLine(text, allowedSet) {
543
+ if (typeof text !== "string") return null;
544
+ const meaningfulLines = text
545
+ .replace(/\r\n?/g, "\n")
546
+ .split("\n")
547
+ .map((line) => line.trim())
548
+ .filter((line) => line.length > 0 && !/^(?:Created At|Completed At):/.test(line));
549
+ if (meaningfulLines.length !== 1) return null;
550
+ const match = /^A1:\s*(.+)$/.exec(meaningfulLines[0]);
551
+ if (!match) return null;
552
+ const value = match[1].trim();
553
+ return allowedSet.has(value) ? value : null;
554
+ }
555
+
556
+ function extractSubagentIdFromTranscript(events, afterStepIndex = null) {
557
+ const afterMatches = (ev) => afterStepIndex === null
558
+ || typeof ev?.step_index !== "number"
559
+ || ev.step_index > afterStepIndex;
560
+ const matchEvent = (ev) => {
561
+ const raw = JSON.stringify(ev);
562
+ const match = /\\?"(?:conversationId|childConversationId)\\?"\s*:\s*\\?"([^"\\]+)\\?"/.exec(raw);
563
+ return match && match[1] ? match[1] : null;
564
+ };
387
565
  for (let i = events.length - 1; i >= 0; i -= 1) {
388
- const raw = JSON.stringify(events[i]);
389
- const match = /"conversationId"\s*:\s*"([^"]+)"/.exec(raw)
390
- ?? /"childConversationId"\s*:\s*"([^"]+)"/.exec(raw);
391
- if (match && match[1]) return match[1];
566
+ const ev = events[i];
567
+ if (ev?.type !== "GENERIC" || ev?.status !== "DONE") continue;
568
+ if (!afterMatches(ev)) continue;
569
+ const hit = matchEvent(ev);
570
+ if (hit) return hit;
571
+ }
572
+ for (let i = events.length - 1; i >= 0; i -= 1) {
573
+ const ev = events[i];
574
+ if (ev?.type === "PLANNER_RESPONSE") continue;
575
+ if (!afterMatches(ev)) continue;
576
+ const hit = matchEvent(ev);
577
+ if (hit) return hit;
392
578
  }
393
579
  return null;
394
580
  }
395
581
 
396
- function extractAskAnswerFromTranscript(events) {
397
- const candidateLabels = ["安排代理", "跳过,直接推进", "联网调查", "先不查"];
582
+ function extractAskAnswerFromTranscript(events, afterStepIndex = null) {
583
+ const candidateLabels = [
584
+ "代理审核",
585
+ "主控自审",
586
+ "代理复核",
587
+ "主控自查",
588
+ "直接推进",
589
+ "安排代理",
590
+ "跳过,直接推进",
591
+ "联网调查",
592
+ "不调查",
593
+ ];
594
+ const labelSet = new Set(candidateLabels);
595
+ const pickSelected = (raw) => {
596
+ if (Array.isArray(raw)) return raw.length === 1 && typeof raw[0] === "string" ? raw[0].trim() : null;
597
+ return typeof raw === "string" ? raw.trim() : null;
598
+ };
398
599
  for (let i = events.length - 1; i >= 0; i -= 1) {
399
600
  const ev = events[i];
400
- const text = JSON.stringify(ev);
401
- if (!text.includes("ask_question") && !candidateLabels.some((lbl) => text.includes(lbl))) continue;
402
- for (const label of candidateLabels) {
403
- if (text.includes(label)) return label;
601
+ if (ev?.type === "PLANNER_RESPONSE") continue;
602
+ if (afterStepIndex !== null && typeof ev?.step_index === "number" && ev.step_index <= afterStepIndex) {
603
+ continue;
604
+ }
605
+ const structured = [
606
+ ev?.selected,
607
+ ev?.answer,
608
+ ev?.result?.selected,
609
+ ev?.result?.answer,
610
+ ev?.toolResult?.selected,
611
+ ev?.toolResult?.answer,
612
+ ];
613
+ for (const candidate of structured) {
614
+ const value = pickSelected(candidate);
615
+ if (value && labelSet.has(value)) return value;
616
+ }
617
+ if (ev?.type === "GENERIC" && ev?.status === "DONE") {
618
+ const strict = parseStrictAskAnswerLine(ev?.content, labelSet);
619
+ if (strict) return strict;
620
+ }
621
+ }
622
+ return null;
623
+ }
624
+
625
+ function humanGateStateFile(dataPath, conversationId) {
626
+ return dataPath("ldvh", "human-gate-state", `${sha256Text(conversationId || "default").slice(0, 16)}.json`);
627
+ }
628
+
629
+ function pendingAskFile(dataPath, conversationId) {
630
+ return dataPath("ldvh", "pending-asks", `${sha256Text(conversationId || "default").slice(0, 16)}.json`);
631
+ }
632
+
633
+ function subagentSessionsFile(dataPath) {
634
+ return dataPath("ldvh", "subagent-sessions.json");
635
+ }
636
+
637
+ function isInsideProtectedHookState(targetPath, cwd, dataPath) {
638
+ if (typeof targetPath !== "string" || targetPath.trim().length === 0) return false;
639
+ const resolvedTarget = safeRealpathDeep(resolve(cwd || process.cwd(), targetPath));
640
+ const normTarget = process.platform === "win32" ? resolvedTarget.toLowerCase() : resolvedTarget;
641
+ const sepChar = process.platform === "win32" ? "\\" : "/";
642
+ for (const protectedPath of [
643
+ dataPath("ldvh", "human-gate-state"),
644
+ subagentSessionsFile(dataPath),
645
+ ]) {
646
+ const resolvedProtected = safeRealpathDeep(protectedPath);
647
+ const normProtected = process.platform === "win32" ? resolvedProtected.toLowerCase() : resolvedProtected;
648
+ if (normTarget === normProtected || normTarget.startsWith(`${normProtected}${sepChar}`)) {
649
+ return true;
404
650
  }
405
651
  }
652
+ return false;
653
+ }
654
+
655
+ function pruneExpiredHumanGateState(raw, now = Date.now()) {
656
+ const pending = raw?.pending && typeof raw.pending === "object" && Number(raw.pending.expiresAt) > now
657
+ ? raw.pending
658
+ : null;
659
+ const grant = raw?.grant && typeof raw.grant === "object" && Number(raw.grant.expiresAt) > now
660
+ ? raw.grant
661
+ : null;
662
+ return { pending, grant };
663
+ }
664
+
665
+ async function readHumanGateState(dataPath, conversationId) {
666
+ const file = humanGateStateFile(dataPath, conversationId);
667
+ try {
668
+ const raw = JSON.parse(await readFile(file, "utf8"));
669
+ return pruneExpiredHumanGateState(raw);
670
+ } catch {
671
+ return { pending: null, grant: null };
672
+ }
673
+ }
674
+
675
+ async function mutateHumanGateState(dataPath, conversationId, mutator) {
676
+ const file = humanGateStateFile(dataPath, conversationId);
677
+ return withFileLock(file, async () => {
678
+ let current = { pending: null, grant: null };
679
+ try {
680
+ current = pruneExpiredHumanGateState(JSON.parse(await readFile(file, "utf8")));
681
+ } catch {
682
+ current = { pending: null, grant: null };
683
+ }
684
+ const next = pruneExpiredHumanGateState(await mutator(current));
685
+ await writeFileAtomic(file, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600, dirMode: 0o700 });
686
+ return next;
687
+ }, { timeoutMs: 3000, staleMs: 5000 });
688
+ }
689
+
690
+ function latestStepIndexFromTranscript(events) {
691
+ let maxStep = null;
692
+ for (const ev of events ?? []) {
693
+ if (typeof ev?.step_index === "number" && (maxStep === null || ev.step_index > maxStep)) {
694
+ maxStep = ev.step_index;
695
+ }
696
+ }
697
+ return maxStep;
698
+ }
699
+
700
+ function extractHumanGateAnswer(payload, events, afterStepIndex = null) {
701
+ const pickExact = (raw) => {
702
+ if (Array.isArray(raw)) return raw.length === 1 && typeof raw[0] === "string" ? raw[0].trim() : null;
703
+ return typeof raw === "string" ? raw.trim() : null;
704
+ };
705
+ const directCandidates = [payload?.toolResult, payload?.toolResponse, payload?.output];
706
+ for (const item of directCandidates) {
707
+ if (typeof item === "string") {
708
+ const hit = parseStrictAskAnswerLine(item, HUMAN_GATE_OPTION_SET);
709
+ if (hit) return hit;
710
+ } else if (item && typeof item === "object") {
711
+ for (const candidate of [item.selected, item.answer, item.A1]) {
712
+ const val = pickExact(candidate);
713
+ if (val && HUMAN_GATE_OPTION_SET.has(val)) return val;
714
+ }
715
+ if (typeof item.content === "string") {
716
+ const hit = parseStrictAskAnswerLine(item.content, HUMAN_GATE_OPTION_SET);
717
+ if (hit) return hit;
718
+ }
719
+ }
720
+ }
721
+ for (let i = (events?.length ?? 0) - 1; i >= 0; i -= 1) {
722
+ const ev = events[i];
723
+ if (ev?.type !== "GENERIC" || ev?.status !== "DONE") continue;
724
+ if (afterStepIndex !== null && (typeof ev?.step_index !== "number" || ev.step_index <= afterStepIndex)) continue;
725
+ const hit = parseStrictAskAnswerLine(ev?.content, HUMAN_GATE_OPTION_SET);
726
+ if (hit) return hit;
727
+ }
406
728
  return null;
407
729
  }
408
730
 
@@ -412,6 +734,7 @@ export function createHookSharedState() {
412
734
  observedFiles: new Map(),
413
735
  subagents: new Map(),
414
736
  pendingAsks: new Map(),
737
+ pendingSubagentSpawns: new Map(),
415
738
  };
416
739
  }
417
740
 
@@ -443,7 +766,6 @@ export function createHookEngine(options = {}) {
443
766
  hadFailureThenEdit: false,
444
767
  calledPostWorkAsk: false,
445
768
  calledExperienceAction: false,
446
- calledFrictionAction: false,
447
769
  stopGuardTriggered: false,
448
770
  };
449
771
  state.turnCache.set(key, entry);
@@ -460,10 +782,130 @@ export function createHookEngine(options = {}) {
460
782
  entry.hadFailureThenEdit = false;
461
783
  entry.calledPostWorkAsk = false;
462
784
  entry.calledExperienceAction = false;
463
- entry.calledFrictionAction = false;
464
785
  entry.stopGuardTriggered = false;
465
786
  }
466
787
 
788
+ async function registerSubagentSession(childId, meta) {
789
+ if (typeof childId !== "string" || childId.trim().length === 0) return;
790
+ const id = childId.trim();
791
+ state.subagents.set(id, meta);
792
+ const file = subagentSessionsFile(dataPath);
793
+ try {
794
+ await withFileLock(file, async () => {
795
+ let cur = {};
796
+ try {
797
+ cur = JSON.parse(await readFile(file, "utf8"));
798
+ if (!cur || typeof cur !== "object" || Array.isArray(cur)) cur = {};
799
+ } catch {
800
+ cur = {};
801
+ }
802
+ const now = Date.now();
803
+ const pruned = {};
804
+ for (const [k, v] of Object.entries(cur)) {
805
+ if (v && typeof v === "object" && Number(v.expiresAt) > now) pruned[k] = v;
806
+ }
807
+ pruned[id] = { ...meta, expiresAt: now + SUBAGENT_SESSION_TTL_MS };
808
+ await writeFileAtomic(file, `${JSON.stringify(pruned, null, 2)}\n`, { mode: 0o600, dirMode: 0o700 });
809
+ }, { timeoutMs: 2000, staleMs: 5000 });
810
+ } catch {
811
+ // 持久化失败时仍保留内存登记
812
+ }
813
+ }
814
+
815
+ async function isKnownSubagent(conversationId) {
816
+ if (typeof conversationId !== "string" || conversationId.trim().length === 0) return false;
817
+ if (state.subagents.has(conversationId)) return true;
818
+ try {
819
+ const parsed = JSON.parse(await readFile(subagentSessionsFile(dataPath), "utf8"));
820
+ const rec = parsed?.[conversationId];
821
+ if (rec && typeof rec === "object" && Number(rec.expiresAt) > Date.now()) {
822
+ state.subagents.set(conversationId, rec);
823
+ return true;
824
+ }
825
+ } catch {
826
+ // 无持久化记录时按非子代理处理
827
+ }
828
+ return false;
829
+ }
830
+
831
+ async function readPendingAsk(conversationId) {
832
+ const mem = state.pendingAsks.get(conversationId);
833
+ if (mem && Number(mem.expiresAt ?? (mem.at + PENDING_ASK_TTL_MS)) > Date.now()) {
834
+ return mem;
835
+ }
836
+ state.pendingAsks.delete(conversationId);
837
+ try {
838
+ const disk = JSON.parse(await readFile(pendingAskFile(dataPath, conversationId), "utf8"));
839
+ if (disk && typeof disk === "object" && Number(disk.expiresAt) > Date.now()) {
840
+ state.pendingAsks.set(conversationId, disk);
841
+ return disk;
842
+ }
843
+ } catch {
844
+ // 无挂起请示
845
+ }
846
+ return null;
847
+ }
848
+
849
+ async function writePendingAsk(conversationId, record) {
850
+ const now = Date.now();
851
+ const next = { ...record, at: now, expiresAt: now + PENDING_ASK_TTL_MS };
852
+ state.pendingAsks.set(conversationId, next);
853
+ const file = pendingAskFile(dataPath, conversationId);
854
+ try {
855
+ await withFileLock(file, async () => {
856
+ await writeFileAtomic(file, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600, dirMode: 0o700 });
857
+ }, { timeoutMs: 2000, staleMs: 5000 });
858
+ } catch {
859
+ // 写盘失败保留内存状态
860
+ }
861
+ }
862
+
863
+ async function clearPendingAsk(conversationId) {
864
+ state.pendingAsks.delete(conversationId);
865
+ await unlink(pendingAskFile(dataPath, conversationId)).catch(() => {});
866
+ }
867
+
868
+ async function settlePendingReviewAsk(conversationId, cwd, transcriptPath) {
869
+ if (typeof transcriptPath !== "string" || transcriptPath.length === 0) return false;
870
+ const pending = await readPendingAsk(conversationId);
871
+ if (!pending) return false;
872
+ const events = await readJsonLinesTail(transcriptPath);
873
+ const answerLabel = extractAskAnswerFromTranscript(events, pending.afterStepIndex ?? null);
874
+ if (!answerLabel) return false;
875
+ let answer = null;
876
+ if (pending.point === REVIEW_ASK_POINTS.RESEARCH) {
877
+ if (answerLabel === "联网调查") answer = REVIEW_ASK_ANSWERS.REVIEW;
878
+ else if (answerLabel === "不调查") answer = REVIEW_ASK_ANSWERS.SKIP;
879
+ } else {
880
+ if (answerLabel === "代理审核" || answerLabel === "代理复核" || answerLabel === "安排代理") {
881
+ answer = REVIEW_ASK_ANSWERS.REVIEW;
882
+ } else if (answerLabel === "主控自审" || answerLabel === "主控自查") {
883
+ answer = REVIEW_ASK_ANSWERS.SELF;
884
+ } else if (answerLabel === "直接推进" || answerLabel === "跳过,直接推进") {
885
+ answer = REVIEW_ASK_ANSWERS.SKIP;
886
+ }
887
+ }
888
+ if (answer !== null) {
889
+ const scopeKey = `session:${conversationId}${cwd ? `|cwd:${cwd}` : ""}`;
890
+ const { reviewAskFingerprint } = await import("../lib/review-ask.js");
891
+ const fingerprint = pending.fingerprint || reviewAskFingerprint({
892
+ point: pending.point,
893
+ task: pending.task,
894
+ scope: scopeKey,
895
+ candidate_summary: pending.candidate_summary,
896
+ conclusion_summary: pending.conclusion_summary,
897
+ });
898
+ await recordReviewAskDecision(dataPath, {
899
+ fingerprint,
900
+ point: pending.point,
901
+ answer,
902
+ task: pending.task,
903
+ });
904
+ }
905
+ await clearPendingAsk(conversationId);
906
+ return true;
907
+ }
908
+
467
909
  async function handleSessionStart(payload = {}) {
468
910
  const cwd = resolveCwd(payload);
469
911
  const conversationId = payload.conversationId || "default";
@@ -521,6 +963,9 @@ export function createHookEngine(options = {}) {
521
963
  const cwd = resolveCwd(payload);
522
964
  const conversationId = payload.conversationId || "default";
523
965
  const lastUserInput = typeof payload.lastUserInput === "string" ? payload.lastUserInput : "";
966
+ if (typeof payload.transcriptPath === "string" && payload.transcriptPath.length > 0) {
967
+ await settlePendingReviewAsk(conversationId, cwd, payload.transcriptPath).catch(() => {});
968
+ }
524
969
  const scope = await resolveGovernanceScope(dataPath, cwd);
525
970
 
526
971
  const entry = getTurnEntry(conversationId);
@@ -767,23 +1212,27 @@ export function createHookEngine(options = {}) {
767
1212
 
768
1213
  async function handlePreToolUse(payload = {}) {
769
1214
  const result = await handlePreToolUseCore(payload);
770
- if (result?.decision === "deny") {
1215
+ const isHumanGatePrompt = result?._humanGateEvent === true;
1216
+ const publicResult = isHumanGatePrompt
1217
+ ? { decision: result.decision, reason: result.reason }
1218
+ : result;
1219
+ if (publicResult?.decision === "deny" && !isHumanGatePrompt) {
771
1220
  const entry = getTurnEntry(payload?.conversationId || "default");
772
1221
  entry.errorSignals += 1;
773
1222
  }
774
- if (result?.decision === "deny" || result?.decision === "force_ask") {
1223
+ if (publicResult?.decision === "deny" || publicResult?.decision === "force_ask") {
775
1224
  const unwrapped = unwrapLdvhToolCall(payload?.toolCall?.name, payload?.toolCall?.args);
776
1225
  await appendGateEvent(dataPath, {
777
1226
  tool: unwrapped?.ldvhName ?? payload?.toolCall?.name ?? "unknown",
778
- status: result.decision === "force_ask" ? "needs_human_gate" : "rejected",
779
- codes: [result.decision],
780
- detail: result.reason ?? "",
1227
+ status: (isHumanGatePrompt || publicResult.decision === "force_ask") ? "needs_human_gate" : "rejected",
1228
+ codes: [isHumanGatePrompt ? "human_gate_ask_required" : publicResult.decision],
1229
+ detail: publicResult.reason ?? "",
781
1230
  sessionId: payload?.conversationId ?? "",
782
1231
  cwd: resolveCwd(payload),
783
1232
  source: "hook",
784
1233
  });
785
1234
  }
786
- return result;
1235
+ return publicResult;
787
1236
  }
788
1237
 
789
1238
  async function handlePreToolUseCore(payload = {}) {
@@ -798,8 +1247,11 @@ export function createHookEngine(options = {}) {
798
1247
  ? payload.modelName.trim()
799
1248
  : "auto";
800
1249
  const transcriptPath = typeof payload.transcriptPath === "string" ? payload.transcriptPath : null;
1250
+ if (rawName !== "ask_question" && transcriptPath) {
1251
+ await settlePendingReviewAsk(conversationId, cwd, transcriptPath).catch(() => {});
1252
+ }
801
1253
  const scope = await resolveGovernanceScope(dataPath, cwd);
802
- const isSubagent = state.subagents.has(conversationId);
1254
+ const isSubagent = await isKnownSubagent(conversationId);
803
1255
 
804
1256
  const unwrapped = unwrapLdvhToolCall(rawName, args);
805
1257
  if (unwrapped !== null) {
@@ -827,12 +1279,6 @@ export function createHookEngine(options = {}) {
827
1279
  reason: "子代理不得调用 ldvh_pitfall_arm_delegate(25 §13 仅主控会话可授权)",
828
1280
  };
829
1281
  }
830
- if (ldvhName === "ldvh_friction_write") {
831
- return {
832
- decision: "deny",
833
- reason: "子代理禁止直接调用 ldvh_friction_write,请改用 ldvh_friction_record_observation 写入观察缓冲(同源满 3 次由工具以代理签名自动晋升)",
834
- };
835
- }
836
1282
  if (ldvhName === "ldvh_pitfall_write") {
837
1283
  if (toolArgs.action !== "create") {
838
1284
  return {
@@ -840,7 +1286,7 @@ export function createHookEngine(options = {}) {
840
1286
  reason: "子代理仅允许创建 Pitfall(action=create),禁止修改或终态转换(25 §13)",
841
1287
  };
842
1288
  }
843
- await experienceArming.load();
1289
+ await experienceArming.load({ reload: true });
844
1290
  const verified = experienceArming.verifyWrite({
845
1291
  childSessionId: conversationId,
846
1292
  projectPath: scope?.project?.path ?? cwd,
@@ -861,13 +1307,94 @@ export function createHookEngine(options = {}) {
861
1307
  }
862
1308
  }
863
1309
 
864
- const gate = isHumanGateAction(ldvhName, toolArgs);
1310
+ const gate = await resolveHumanGateSpec(ldvhName, toolArgs, { scope, cwd, conversationId });
865
1311
  if (gate.gated) {
866
- trustedCtx.humanApprovedViaHook = true;
1312
+ const currentGateState = await readHumanGateState(dataPath, conversationId);
1313
+ if (currentGateState.grant && currentGateState.grant.fingerprint === gate.fingerprint) {
1314
+ await mutateHumanGateState(dataPath, conversationId, (st) => ({
1315
+ pending: st.pending,
1316
+ grant: null,
1317
+ }));
1318
+ trustedCtx.humanApprovedViaHook = true;
1319
+ return {
1320
+ decision: "allow",
1321
+ overwrite: buildOverwriteWithContext(unwrapped, args, trustedCtx),
1322
+ };
1323
+ }
1324
+ if (
1325
+ currentGateState.pending
1326
+ && currentGateState.pending.fingerprint === gate.fingerprint
1327
+ && currentGateState.pending.askVerified === true
1328
+ && transcriptPath
1329
+ ) {
1330
+ const events = await readJsonLinesTail(transcriptPath);
1331
+ const transcriptAnswer = extractHumanGateAnswer(
1332
+ {},
1333
+ events,
1334
+ currentGateState.pending.afterStepIndex ?? null,
1335
+ );
1336
+ if (transcriptAnswer === HUMAN_GATE_APPROVE_OPTION) {
1337
+ await mutateHumanGateState(dataPath, conversationId, () => ({
1338
+ pending: null,
1339
+ grant: null,
1340
+ }));
1341
+ trustedCtx.humanApprovedViaHook = true;
1342
+ return {
1343
+ decision: "allow",
1344
+ overwrite: buildOverwriteWithContext(unwrapped, args, trustedCtx),
1345
+ };
1346
+ }
1347
+ if (transcriptAnswer === HUMAN_GATE_REJECT_OPTION) {
1348
+ await mutateHumanGateState(dataPath, conversationId, () => ({
1349
+ pending: null,
1350
+ grant: null,
1351
+ }));
1352
+ return {
1353
+ decision: "deny",
1354
+ _humanGateEvent: true,
1355
+ reason: `LDVH Human Gate:Human 已选择「${HUMAN_GATE_REJECT_OPTION}」,已终止执行「${gate.label}」。`,
1356
+ };
1357
+ }
1358
+ }
1359
+ const reuseVerifiedPending = currentGateState.pending
1360
+ && currentGateState.pending.fingerprint === gate.fingerprint
1361
+ && currentGateState.pending.askVerified === true;
1362
+ const events = !reuseVerifiedPending && transcriptPath
1363
+ ? await readJsonLinesTail(transcriptPath)
1364
+ : [];
1365
+ const afterStepIndex = reuseVerifiedPending
1366
+ ? (currentGateState.pending.afterStepIndex ?? null)
1367
+ : (transcriptPath ? latestStepIndexFromTranscript(events) : null);
1368
+ const now = Date.now();
1369
+ await mutateHumanGateState(dataPath, conversationId, () => ({
1370
+ pending: {
1371
+ fingerprint: gate.fingerprint,
1372
+ ldvhName: gate.ldvhName,
1373
+ action: gate.action,
1374
+ title: gate.title,
1375
+ label: gate.label,
1376
+ question: gate.question,
1377
+ options: gate.options,
1378
+ afterStepIndex,
1379
+ askVerified: reuseVerifiedPending === true,
1380
+ ...(reuseVerifiedPending && currentGateState.pending.askVerifiedAt
1381
+ ? { askVerifiedAt: currentGateState.pending.askVerifiedAt }
1382
+ : {}),
1383
+ at: now,
1384
+ expiresAt: now + HUMAN_GATE_TTL_MS,
1385
+ },
1386
+ grant: null,
1387
+ }));
867
1388
  return {
868
- decision: "force_ask",
869
- reason: `LDVH Human Gate:请确认是否执行「${gate.label}」`,
870
- overwrite: buildOverwriteWithContext(unwrapped, args, trustedCtx),
1389
+ decision: "deny",
1390
+ _humanGateEvent: true,
1391
+ reason: [
1392
+ `LDVH Human Gate:该操作需先向 Human 呈报依据并通过 ask_question 取得确认。`,
1393
+ `待确认对象与动作:${gate.label}`,
1394
+ `请先在正文向 Human 呈报完整依据,再原样使用以下参数调用 ask_question(必须保留对象标题且仅提供 2 个选项):`,
1395
+ `- questions: ${JSON.stringify([{ question: gate.question, options: gate.options }])}`,
1396
+ `取得「${HUMAN_GATE_APPROVE_OPTION}」后直接重试本次工具调用,Hook 将自动放行。`,
1397
+ ].join("\n"),
871
1398
  };
872
1399
  }
873
1400
 
@@ -891,9 +1418,54 @@ export function createHookEngine(options = {}) {
891
1418
  return { decision: "deny", reason: `LDVH 提问守卫:第 ${i + 1} 题缺少非空 question 标题` };
892
1419
  }
893
1420
  }
1421
+ const gateState = await readHumanGateState(dataPath, conversationId);
1422
+ if (gateState.pending && questions.length === 1) {
1423
+ const q = questions[0];
1424
+ const opts = Array.isArray(q.options) ? q.options : [];
1425
+ const looksLikeHumanGate = q.question.includes("Human Gate")
1426
+ || opts.includes(HUMAN_GATE_APPROVE_OPTION)
1427
+ || opts.includes(HUMAN_GATE_REJECT_OPTION);
1428
+ if (looksLikeHumanGate) {
1429
+ if (gateState.pending.title && !q.question.includes(gateState.pending.title)) {
1430
+ return {
1431
+ decision: "deny",
1432
+ reason: `LDVH Human Gate 提问守卫:question 必须包含待确认对象标题「${gateState.pending.title}」`,
1433
+ };
1434
+ }
1435
+ if (opts.length !== 2 || opts[0] !== HUMAN_GATE_APPROVE_OPTION || opts[1] !== HUMAN_GATE_REJECT_OPTION) {
1436
+ return {
1437
+ decision: "deny",
1438
+ reason: `LDVH Human Gate 提问守卫:options 必须恰好为 ${JSON.stringify(HUMAN_GATE_OPTIONS)}(仅 2 项)`,
1439
+ };
1440
+ }
1441
+ await mutateHumanGateState(dataPath, conversationId, (st) => ({
1442
+ pending: st.pending ? {
1443
+ ...st.pending,
1444
+ askVerified: true,
1445
+ askVerifiedAt: Date.now(),
1446
+ } : null,
1447
+ grant: st.grant,
1448
+ }));
1449
+ }
1450
+ }
894
1451
  return { decision: "allow" };
895
1452
  }
896
1453
 
1454
+ if (rawName === "invoke_subagent" && transcriptPath) {
1455
+ const events = await readJsonLinesTail(transcriptPath);
1456
+ state.pendingSubagentSpawns.set(conversationId, latestStepIndexFromTranscript(events));
1457
+ }
1458
+
1459
+ if (rawName === "write_file" || rawName === "edit_file") {
1460
+ const targetPath = args.Path ?? args.path;
1461
+ if (isInsideProtectedHookState(targetPath, cwd, dataPath)) {
1462
+ return {
1463
+ decision: "deny",
1464
+ reason: "LDVH Human Gate 守卫:禁止直接修改 human-gate-state 或 subagent-sessions 状态文件",
1465
+ };
1466
+ }
1467
+ }
1468
+
897
1469
  if ((rawName === "write_file" || rawName === "edit_file") && scope.state === "governed") {
898
1470
  const targetPath = args.Path ?? args.path;
899
1471
  if (isInsideLdvhBase(targetPath, cwd, scope.project?.path)) {
@@ -928,6 +1500,13 @@ export function createHookEngine(options = {}) {
928
1500
  return { decision: "allow" };
929
1501
  }
930
1502
 
1503
+ if (rawName === "run_command" && typeof args.CommandLine === "string" && /human-gate-state|subagent-sessions\.json/i.test(args.CommandLine)) {
1504
+ return {
1505
+ decision: "deny",
1506
+ reason: "LDVH Human Gate 守卫:禁止通过终端命令访问或篡改 human-gate-state 或 subagent-sessions 状态文件",
1507
+ };
1508
+ }
1509
+
931
1510
  if (rawName === "run_command" && isGitCommitCommand(args.CommandLine)) {
932
1511
  try {
933
1512
  await writeFileAtomic(
@@ -1022,27 +1601,34 @@ export function createHookEngine(options = {}) {
1022
1601
  if (subagentType === "ldvh-experience-recorder") {
1023
1602
  entry.calledExperienceAction = true;
1024
1603
  }
1025
- if (subagentType === "ldvh-friction-recorder") {
1026
- entry.calledFrictionAction = true;
1027
- }
1028
- const childId = typeof args.conversationId === "string" && args.conversationId.length > 0
1604
+ const afterStepIndex = state.pendingSubagentSpawns.get(conversationId) ?? null;
1605
+ state.pendingSubagentSpawns.delete(conversationId);
1606
+ let childId = typeof args.conversationId === "string" && args.conversationId.length > 0
1029
1607
  ? args.conversationId
1030
- : extractSubagentIdFromTranscript(await readJsonLinesTail(transcriptPath));
1608
+ : null;
1609
+ if (!childId && transcriptPath) {
1610
+ childId = extractSubagentIdFromTranscript(await readJsonLinesTail(transcriptPath), afterStepIndex);
1611
+ if (!childId) {
1612
+ await new Promise((r) => setTimeout(r, 80));
1613
+ childId = extractSubagentIdFromTranscript(await readJsonLinesTail(transcriptPath), afterStepIndex);
1614
+ }
1615
+ }
1031
1616
  if (childId) {
1032
1617
  const scope = await resolveGovernanceScope(dataPath, cwd);
1033
- state.subagents.set(childId, {
1618
+ await registerSubagentSession(childId, {
1034
1619
  parentId: conversationId,
1035
1620
  startedAt: new Date().toISOString(),
1036
1621
  scopeState: scope.state,
1037
1622
  conclusion: null,
1038
1623
  });
1039
1624
  if (scope.state === "governed" && scope.project?.path) {
1040
- await experienceArming.load();
1625
+ await experienceArming.load({ reload: true });
1041
1626
  experienceArming.bindForChild({
1042
1627
  parentSessionId: conversationId,
1043
1628
  childSessionId: childId,
1044
1629
  projectPath: scope.project.path,
1045
1630
  });
1631
+ await experienceArming.flush();
1046
1632
  }
1047
1633
  }
1048
1634
  return {};
@@ -1052,52 +1638,71 @@ export function createHookEngine(options = {}) {
1052
1638
  if (unwrapped?.ldvhName === "ldvh_pitfall_arm_delegate" || unwrapped?.ldvhName === "ldvh_pitfall_write") {
1053
1639
  entry.calledExperienceAction = true;
1054
1640
  }
1055
- if (unwrapped?.ldvhName === "ldvh_friction_record_observation") {
1056
- entry.calledFrictionAction = true;
1057
- }
1058
1641
  if (unwrapped && (unwrapped.ldvhName === "ldvh_review_ask" || unwrapped.ldvhName === "ldvh_research_consult")) {
1059
1642
  const { ldvhName, toolArgs } = unwrapped;
1060
1643
  if (ldvhName === "ldvh_review_ask" && toolArgs.point === REVIEW_ASK_POINTS.POST_WORK) {
1061
1644
  entry.calledPostWorkAsk = true;
1062
1645
  }
1063
- const point = ldvhName === "ldvh_research_consult"
1646
+ if (toolArgs.human_requested === true || (typeof toolArgs.record_decision === "string" && toolArgs.record_decision.length > 0)) {
1647
+ await clearPendingAsk(conversationId);
1648
+ return {};
1649
+ }
1650
+ const point = ldvhName === "ldvh_research_consult" || toolArgs.point === REVIEW_ASK_POINTS.RESEARCH
1064
1651
  ? REVIEW_ASK_POINTS.RESEARCH
1065
1652
  : (toolArgs.point === REVIEW_ASK_POINTS.POST_WORK ? REVIEW_ASK_POINTS.POST_WORK : REVIEW_ASK_POINTS.PRE_ACTION);
1066
- const task = ldvhName === "ldvh_research_consult"
1067
- ? [toolArgs.need, toolArgs.scope, ...(Array.isArray(toolArgs.keywords) ? toolArgs.keywords : [])].filter(Boolean).join(" | ")
1653
+ const task = point === REVIEW_ASK_POINTS.RESEARCH
1654
+ ? buildResearchFingerprintTask({
1655
+ need: toolArgs.need,
1656
+ purpose: toolArgs.purpose,
1657
+ scope: toolArgs.scope,
1658
+ keywords: toolArgs.keywords,
1659
+ })
1068
1660
  : (toolArgs.task ?? "");
1069
- state.pendingAsks.set(conversationId, {
1661
+ const events = transcriptPath ? await readJsonLinesTail(transcriptPath) : [];
1662
+ const afterStepIndex = transcriptPath ? latestStepIndexFromTranscript(events) : null;
1663
+ await writePendingAsk(conversationId, {
1070
1664
  point,
1071
1665
  task,
1666
+ candidate_summary: toolArgs.candidate_summary,
1667
+ conclusion_summary: toolArgs.conclusion_summary,
1072
1668
  fingerprint: payload?.toolResult?.fingerprint ?? null,
1073
- at: Date.now(),
1669
+ afterStepIndex,
1074
1670
  });
1075
1671
  return {};
1076
1672
  }
1077
1673
 
1078
1674
  if (rawName === "ask_question") {
1079
- const pending = state.pendingAsks.get(conversationId);
1080
- if (pending && transcriptPath) {
1081
- const events = await readJsonLinesTail(transcriptPath);
1082
- const answerLabel = extractAskAnswerFromTranscript(events);
1083
- if (answerLabel) {
1084
- const answer = (answerLabel === "安排代理" || answerLabel === "联网调查")
1085
- ? REVIEW_ASK_ANSWERS.REVIEW
1086
- : REVIEW_ASK_ANSWERS.SKIP;
1087
- const scopeKey = `session:${conversationId}${cwd ? `|cwd:${cwd}` : ""}`;
1088
- const { reviewAskFingerprint } = await import("../lib/review-ask.js");
1089
- const fingerprint = pending.fingerprint || reviewAskFingerprint({
1090
- point: pending.point,
1091
- task: pending.task,
1092
- scope: scopeKey,
1093
- });
1094
- await recordReviewAskDecision(dataPath, {
1095
- fingerprint,
1096
- point: pending.point,
1097
- answer,
1098
- task: pending.task,
1099
- });
1100
- state.pendingAsks.delete(conversationId);
1675
+ const gateState = await readHumanGateState(dataPath, conversationId);
1676
+ if (gateState.pending) {
1677
+ let events = transcriptPath ? await readJsonLinesTail(transcriptPath) : [];
1678
+ let gateAnswer = extractHumanGateAnswer(payload, events, gateState.pending.afterStepIndex ?? null);
1679
+ if (!gateAnswer && transcriptPath) {
1680
+ await new Promise((r) => setTimeout(r, 80));
1681
+ events = await readJsonLinesTail(transcriptPath);
1682
+ gateAnswer = extractHumanGateAnswer(payload, events, gateState.pending.afterStepIndex ?? null);
1683
+ }
1684
+ if (gateAnswer === HUMAN_GATE_APPROVE_OPTION) {
1685
+ const now = Date.now();
1686
+ await mutateHumanGateState(dataPath, conversationId, (st) => ({
1687
+ pending: null,
1688
+ grant: st.pending ? {
1689
+ fingerprint: st.pending.fingerprint,
1690
+ ldvhName: st.pending.ldvhName,
1691
+ action: st.pending.action,
1692
+ title: st.pending.title,
1693
+ grantedAt: now,
1694
+ expiresAt: now + HUMAN_GATE_TTL_MS,
1695
+ } : null,
1696
+ }));
1697
+ } else if (gateAnswer === HUMAN_GATE_REJECT_OPTION) {
1698
+ await mutateHumanGateState(dataPath, conversationId, () => ({ pending: null, grant: null }));
1699
+ }
1700
+ }
1701
+ if (transcriptPath) {
1702
+ const settled = await settlePendingReviewAsk(conversationId, cwd, transcriptPath);
1703
+ if (!settled) {
1704
+ await new Promise((r) => setTimeout(r, 80));
1705
+ await settlePendingReviewAsk(conversationId, cwd, transcriptPath);
1101
1706
  }
1102
1707
  }
1103
1708
  return {};
@@ -1126,7 +1731,7 @@ export function createHookEngine(options = {}) {
1126
1731
  }
1127
1732
 
1128
1733
  if (scope.state !== "governed") return { decision: "allow" };
1129
- if (state.subagents.has(conversationId)) return { decision: "allow" };
1734
+ if (await isKnownSubagent(conversationId)) return { decision: "allow" };
1130
1735
  if (payload.continuationActive === true) return { decision: "allow" };
1131
1736
  if (payload.terminationReason && payload.terminationReason !== "NO_TOOL_CALL") {
1132
1737
  return { decision: "allow" };
@@ -1180,11 +1785,6 @@ export function createHookEngine(options = {}) {
1180
1785
  "本回合经历了报错/拦截并随后修改了文件,请完成当场经验自查:主控不自行查重或落笔,若有可回指的失败机制材料,请调用 `ldvh_pitfall_arm_delegate` 授权并后台派发 `ldvh-experience-recorder`(派完即撒手);若无则简述跳过原因。",
1181
1786
  );
1182
1787
  }
1183
- if (captureSwitches.frictionEnabled && entry.errorSignals >= 2 && !entry.calledFrictionAction) {
1184
- reminders.push(
1185
- `本回合出现了 ${entry.errorSignals} 次工具失败或拦截信号,请检查是否存在重复卡点或规则冲突;主控不亲自落笔,若有可回指材料,请后台派发 \`ldvh-friction-recorder\` 写入观察缓冲(满 3 次由工具以代理签名自动晋升),若无则简述跳过。`,
1186
- );
1187
- }
1188
1788
 
1189
1789
  if (reminders.length === 0) return { decision: "allow" };
1190
1790