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,43 +1,29 @@
1
- export const CAPTURE_NOTICE_SUMMARY = "经验与摩擦 · 当场判据";
1
+ export const CAPTURE_NOTICE_SUMMARY = "经验积累 · 当场判据";
2
2
 
3
3
  export const CAPTURE_ENTRY_POINTS = Object.freeze({
4
4
  experience: "experience-accumulation-system-foundation 的 when-it-applies、entry-prerequisite、context-supply、delegate-draft",
5
- friction: "friction-settlement-system-foundation 的 discovery-trigger、discovery-context、discovery-closed-set",
6
5
  failure: "ldvh-root 的 proxy-auxiliary-failure",
7
6
  });
8
7
 
9
- export function buildCaptureNotice({ experienceEnabled = false, frictionEnabled = false } = {}) {
10
- if (experienceEnabled !== true && frictionEnabled !== true) return "";
8
+ export function buildCaptureNotice({ experienceEnabled = false } = {}) {
9
+ if (experienceEnabled !== true) return "";
11
10
  const lines = [
12
- "【经验与摩擦 · 当场判据】",
11
+ "【经验积累 · 当场判据】",
13
12
  "每轮结束把「本轮有无可回指材料(原文+定位)」作为固定自查项过一遍:有材料就当场转发给独立零上下文代理,**主控不做查重、不做成立预判、不亲自落笔,派完即撒手**,以减少对主控上下文的干扰;无材料则无需强行记账。自查是每轮都做的本职,不是定时器驱动。",
14
- ];
15
- if (experienceEnabled === true) {
16
- lines.push(
17
- "",
18
- "- 经验:发现可回指材料(已查明验证、可能重现的失败机制,或非显而易见的避坑方案)时,主控只调 `ldvh_pitfall_arm_delegate` 授权并后台派发 `ldvh-experience-recorder`;由代理查重并直接 `ldvh_pitfall_write(action=\"create\")` 落盘,收到回执时顺手告知 Human。(仅无子代理宿主退化为直接调用。)",
19
- );
20
- }
21
- if (frictionEnabled === true) {
22
- lines.push(
23
- "",
24
- "- 摩擦:发现可回指材料(规则冲突、工具卡点、环境阻碍或重复返工的原话+定位)时,主控只整理有界材料后台派发 `ldvh-friction-recorder`;由代理查重并调用 `ldvh_friction_record_observation` 写入临时观察缓冲,同源累计 >= 3 次时由工具以代理签名自动晋升为待修 Friction(严禁要求代理直接调 `ldvh_friction_write`)。(仅无子代理宿主退化为直接调用。)",
25
- );
26
- }
27
- lines.push(
13
+ "",
14
+ "- 经验:发现可回指材料(已查明验证、可能重现的失败机制、反复卡点临时规避或非显而易见的避坑方案)时,主控只调 `ldvh_pitfall_arm_delegate` 授权并后台派发 `ldvh-experience-recorder`;由代理查重并直接 `ldvh_pitfall_write(action=\"create\")` 落盘,收到回执时顺手告知 Human。(仅无子代理宿主退化为直接调用。)",
28
15
  "",
29
16
  "- 失败按默认不放行(fail-closed):停止该次任务、保留已发生副作用并如实登记,不自行重试,也不把部分写入当作完成(" + CAPTURE_ENTRY_POINTS.failure + ")。",
30
- );
17
+ ];
31
18
  return lines.join("\n");
32
19
  }
33
20
 
34
21
  export function resolveCaptureSwitches(settings) {
35
22
  if (!settings || typeof settings !== "object") {
36
- return { experienceEnabled: false, frictionEnabled: false };
23
+ return { experienceEnabled: false };
37
24
  }
38
25
  const masterOn = settings.proxyAssistEnabled !== false && settings.idleAssistEnabled !== false;
39
26
  return {
40
27
  experienceEnabled: masterOn && settings.experienceAccumulationEnabled !== false,
41
- frictionEnabled: masterOn && settings.frictionDiscoveryEnabled !== false,
42
28
  };
43
29
  }
@@ -43,9 +43,6 @@ export const GATE_RULES = Object.freeze({
43
43
  "validation/removal_basis_unquotable": Object.freeze({ severity: "blocking", description: "a 关键变更 item declares a §7.2 removal basis whose quoted sentence does not appear verbatim in the current §7.2 text" }),
44
44
  "validation/removal_basis_empty": Object.freeze({ severity: "blocking", description: "a §7.2 依据: declaration carries no quoted sentence" }),
45
45
  "validation/removal_basis_section_unreadable": Object.freeze({ severity: "blocking", description: "the candidate tree's §7.2 text could not be read, so a declared removal basis cannot be verified (fails closed)" }),
46
- "git/friction_commit_unresolvable": Object.freeze({ severity: "blocking", description: "a staged friction carrier's informs target names a commit that does not resolve in this repository (26 §11: 目标必须存在且可解析; commit 例外形态同口径) — re-asserted at the commit seam because the writer is bypassable by a direct file write" }),
47
- "git/friction_commit_malformed": Object.freeze({ severity: "blocking", description: "a staged friction carrier's informs target is not a 40-hex commit hash (02 §8.1 commit 形态)" }),
48
- "git/friction_commit_unverifiable": Object.freeze({ severity: "blocking", description: "friction commit targets could not be verified because no commit resolver was supplied — fails closed rather than passing an unverified carrier (26 §11)" }),
49
46
  "validation/lint_failed": Object.freeze({ severity: "blocking", description: "the pre-commit Hook's lint step refused: either eslint reported findings, or eslint could not run at all (missing binary, broken configuration). 06 §5 requires 提交前必须通过静态分析 and 09 §5.3 puts the check at the commit seam; both cases refuse rather than pass, and the message distinguishes them because the repair differs" }),
50
47
  "facts/carrier_uid_filename_mismatch": Object.freeze({ severity: "blocking", description: "a staged ldvh-base carrier's filename encodes one identity while its own `object_uid:` declaration states another (02 §7.1: the declaration is the identity authority; 02 §5 item 6 forbids silently consuming one of two disagreeing claims). 09 §8.1 item 2 领域增量,Human 批准 2026-11-04" }),
51
48
  "facts/carrier_uid_duplicate": Object.freeze({ severity: "blocking", description: "two or more staged ldvh-base carriers declare the same `object_uid` (02 §5 item 6: 载体重复/身份冲突时不得静默选择一份继续消费或写入). 09 §8.1 item 2 领域增量,Human 批准 2026-11-04" }),
@@ -481,71 +478,15 @@ export function isNormCarrierPath(path) {
481
478
  return path.startsWith(`${NORM_FACT_DIRECTORY}/`) && /\/norm-[^/]+\.md$/.test(path);
482
479
  }
483
480
 
484
- const FRICTION_FACT_DIRECTORY = "ldvh-base/frictions";
485
- const COMMIT_HASH_PATTERN = /^[0-9a-f]{40}$/i;
486
-
487
- export function isFrictionCarrierPath(path) {
488
- return path.startsWith(`${FRICTION_FACT_DIRECTORY}/`) && /\/friction-[^/]+\.md$/.test(path);
489
- }
490
-
491
- export function extractFrictionCommitTargets(content) {
492
- const targets = [];
493
- const lines = String(content ?? "").split(/\r?\n/);
494
- const start = lines.findIndex((line) => line.trim() === "---");
495
- if (start === -1) return targets;
496
- const end = lines.findIndex((line, index) => index > start && line.trim() === "---");
497
- if (end === -1) return targets;
498
-
499
- let inRelations = false;
500
- for (let index = start + 1; index < end; index += 1) {
501
- const line = lines[index];
502
- if (/^[A-Za-z_][A-Za-z0-9_]*\s*:/.test(line)) {
503
- inRelations = /^relations\s*:/.test(line);
504
- continue;
505
- }
506
- if (!inRelations) continue;
507
- const match = /^\s+commit\s*:\s*(.+?)\s*$/.exec(line);
508
- if (match) targets.push(match[1].replace(/^["']|["']$/g, ""));
509
- }
510
- return targets;
511
- }
512
-
513
- export async function checkFrictionCommitTargets(carriers, { resolves } = {}) {
514
- const issues = [];
515
- if (typeof resolves !== "function") {
516
- return {
517
- ok: false,
518
- issues: [newFinding("git/friction_commit_unverifiable", "cannot verify friction commit targets: no commit resolver was supplied (26 §11, fails closed)", null)],
519
- checked: 0,
520
- };
521
- }
522
- let checked = 0;
523
- for (const carrier of carriers ?? []) {
524
- for (const hash of extractFrictionCommitTargets(carrier.content)) {
525
- checked += 1;
526
- if (!COMMIT_HASH_PATTERN.test(hash)) {
527
- issues.push(newFinding("git/friction_commit_malformed", `${carrier.path}: relations target must be a 40-hex commit hash, got ${JSON.stringify(hash)} (02 §8.1 commit 形态)`, null));
528
- continue;
529
- }
530
- if (!(await resolves(hash))) {
531
- issues.push(newFinding("git/friction_commit_unresolvable", `${carrier.path}: commit ${hash} does not resolve to an existing commit in this repository (26 §11 — 目标必须存在且可解析)`, null));
532
- }
533
- }
534
- }
535
- return { ok: issues.length === 0, issues, checked };
536
- }
537
-
538
481
 
539
482
  const CARRIER_ID_SEGMENT =
540
483
  "(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|\\d{4,}|[0-7][0-9A-HJKMNP-TV-Z]{25})";
541
484
 
542
485
  const FACT_TYPE_PREFIXES = Object.freeze({
543
- "ldvh-base/frictions": "friction",
544
486
  "ldvh-base/norms": "norm",
545
487
  "ldvh-base/pitfalls": "pitfall",
546
488
  "ldvh-base/reports": "report",
547
489
  "ldvh-base/intents": "intent",
548
- "ldvh-base/milestones": "milestone",
549
490
  });
550
491
 
551
492
  export function factCarrierType(path) {
package/lib/data-paths.js CHANGED
@@ -12,7 +12,6 @@ export const DEFAULT_PLUGIN_SETTINGS = Object.freeze({
12
12
  researchConsultAskEnabled: false,
13
13
  reviewAskSilentRunEnabled: false,
14
14
  experienceAccumulationEnabled: true,
15
- frictionDiscoveryEnabled: true,
16
15
  });
17
16
 
18
17
  /**
@@ -38,14 +38,15 @@ export function createExperienceArming({ dshHomePath, logger = console, now = ()
38
38
  }
39
39
  }
40
40
 
41
- async function load() {
42
- if (loaded) return ok({ loaded: true, count: entries.size, source: "cache" });
41
+ async function load({ reload = false } = {}) {
42
+ if (loaded && !reload) return ok({ loaded: true, count: entries.size, source: "cache" });
43
43
  if (loading !== null) return loading;
44
44
  loading = (async () => {
45
45
  try {
46
46
  const text = await readFile(path(), "utf8");
47
47
  const parsed = JSON.parse(text);
48
48
  const list = Array.isArray(parsed?.entries) ? parsed.entries : [];
49
+ if (reload) entries.clear();
49
50
  for (const entry of list) {
50
51
  if (!isNonEmptyString(entry?.arming_id) || !isNonEmptyString(entry?.parent_session_id)) continue;
51
52
  entries.set(entry.arming_id, entry);
@@ -54,11 +55,12 @@ export function createExperienceArming({ dshHomePath, logger = console, now = ()
54
55
  loaded = true;
55
56
  return ok({ loaded: true, count: entries.size, source: "file" });
56
57
  } catch (error) {
58
+ if (reload && error?.code === "ENOENT") entries.clear();
57
59
  loaded = true;
58
60
  if (error?.code !== "ENOENT") {
59
61
  logger.warn("[dsh-ldvh] experience arming ledger unreadable, treated as empty: %s", String(error?.message ?? error));
60
62
  }
61
- return ok({ loaded: true, count: 0, source: error?.code === "ENOENT" ? "absent" : "unreadable" });
63
+ return ok({ loaded: true, count: entries.size, source: error?.code === "ENOENT" ? "absent" : "unreadable" });
62
64
  } finally {
63
65
  loading = null;
64
66
  }
@@ -171,5 +173,9 @@ export function createExperienceArming({ dshHomePath, logger = console, now = ()
171
173
  return [...entries.values()];
172
174
  }
173
175
 
174
- return { load, arm, bindForChild, verifyWrite, list, ledgerPath: path };
176
+ function flush() {
177
+ return writeChain;
178
+ }
179
+
180
+ return { load, arm, bindForChild, verifyWrite, list, flush, ledgerPath: path };
175
181
  }
@@ -4,7 +4,7 @@ import { withFileLock, writeFileAtomic } from "./atomic-write.js";
4
4
  export const GATE_EVENTS_RELATIVE_PATH = Object.freeze(["ldvh", "gate-events.jsonl"]);
5
5
  export const MAX_GATE_EVENTS = 500;
6
6
 
7
- const DETAIL_MAX_CHARS = 300;
7
+ const DETAIL_MAX_CHARS = 600;
8
8
 
9
9
  function clip(value, max) {
10
10
  const text = typeof value === "string" ? value : String(value ?? "");
@@ -15,7 +15,7 @@ function normalizeEvent(event) {
15
15
  const codes = Array.isArray(event?.codes)
16
16
  ? event.codes.filter((c) => typeof c === "string" && c.length > 0).map((c) => clip(c, 120))
17
17
  : [];
18
- return {
18
+ const normalized = {
19
19
  at: typeof event?.at === "string" && event.at.length > 0 ? event.at : new Date().toISOString(),
20
20
  tool: clip(event?.tool ?? "unknown", 120),
21
21
  status: clip(event?.status ?? "unknown", 60),
@@ -25,6 +25,10 @@ function normalizeEvent(event) {
25
25
  cwd: clip(event?.cwd ?? "", 260),
26
26
  source: clip(event?.source ?? "unknown", 40),
27
27
  };
28
+ if (typeof event?.durationMs === "number" && Number.isFinite(event.durationMs) && event.durationMs >= 0) {
29
+ normalized.durationMs = Math.round(event.durationMs);
30
+ }
31
+ return normalized;
28
32
  }
29
33
 
30
34
  function parseLines(text) {
@@ -47,6 +51,9 @@ function parseLines(text) {
47
51
  * 写入失败不得影响主流程,因此调用方应忽略返回的 ok=false。
48
52
  */
49
53
  export async function appendGateEvent(dataPath, event) {
54
+ if (process.env.LDVH_DISABLE_GATE_EVENTS === "1") {
55
+ return { ok: true, skipped: true };
56
+ }
50
57
  try {
51
58
  const filePath = dataPath(...GATE_EVENTS_RELATIVE_PATH);
52
59
  const normalized = normalizeEvent(event);
@@ -82,3 +89,21 @@ export async function readGateEvents(dataPath, { limit = MAX_GATE_EVENTS } = {})
82
89
  return [];
83
90
  }
84
91
  }
92
+
93
+ /**
94
+ * 原子清空 `${数据根}/ldvh/gate-events.jsonl`。
95
+ */
96
+ export async function clearGateEvents(dataPath) {
97
+ try {
98
+ const filePath = dataPath(...GATE_EVENTS_RELATIVE_PATH);
99
+ return await withFileLock(filePath, async () => {
100
+ await writeFileAtomic(filePath, "", {
101
+ mode: 0o600,
102
+ dirMode: 0o700,
103
+ });
104
+ return { ok: true };
105
+ });
106
+ } catch (error) {
107
+ return { ok: false, error: String(error?.message ?? error) };
108
+ }
109
+ }
@@ -5,11 +5,37 @@ import { createHash } from "node:crypto";
5
5
  import { isAbsolute, join, relative, resolve, sep } from "node:path";
6
6
  import { execFile } from "node:child_process";
7
7
  import { promisify } from "node:util";
8
- import { validateMessage, checkKeyChangesAgainstDiff, checkNormDirectionUniqueness, isNormCarrierPath, snapshotIdentity, SOURCE_FINGERPRINT, cleanGitEnvironment, newFinding, checkDocsReferences, isSpecOrFactCarrierPath, extractDiffPaths, isFrictionCarrierPath, checkFrictionCommitTargets, checkFactCarrierIdentity, factCarrierType, checkSignatureAgainstRoute, touchesGovernedContent } from "./commit-validation.js";
8
+ import { validateMessage, checkKeyChangesAgainstDiff, checkNormDirectionUniqueness, isNormCarrierPath, snapshotIdentity, SOURCE_FINGERPRINT, cleanGitEnvironment, newFinding, checkDocsReferences, isSpecOrFactCarrierPath, extractDiffPaths, checkFactCarrierIdentity, factCarrierType, checkSignatureAgainstRoute, touchesGovernedContent } from "./commit-validation.js";
9
9
  import { currentRouteValuesFromShellEnvironment } from "./session-signature.js";
10
+ import { createDataPathResolver } from "./data-paths.js";
11
+ import { appendGateEvent } from "./gate-events.js";
10
12
 
11
13
  const execFileAsync = promisify(execFile);
12
14
 
15
+ async function recordGitGateEvent({ command, status, codes = [], detail = "", cwd = process.cwd(), durationMs }) {
16
+ if (process.env.LDVH_PREFLIGHT_INDEX || process.env.LDVH_DISABLE_GATE_EVENTS === "1") {
17
+ return;
18
+ }
19
+ try {
20
+ const tool = command === "git-pre-commit"
21
+ ? "git-gate:pre-commit"
22
+ : command === "git-commit-msg"
23
+ ? "git-gate:commit-msg"
24
+ : "git-gate:unknown";
25
+ await appendGateEvent(createDataPathResolver(), {
26
+ tool,
27
+ status,
28
+ codes,
29
+ detail,
30
+ cwd,
31
+ durationMs,
32
+ source: "git-gate",
33
+ });
34
+ } catch {
35
+ // 诊断落账失败不得影响 Git Gate 校验结果
36
+ }
37
+ }
38
+
13
39
  function valueAfter(args, flag) {
14
40
  const index = args.indexOf(flag);
15
41
  return index >= 0 && index + 1 < args.length ? args[index + 1] : void 0;
@@ -155,37 +181,6 @@ async function runSharedChecks(root, indexFile, message) {
155
181
  const changedPaths = extractDiffPaths(diff);
156
182
  const correspondence = { changedPaths };
157
183
 
158
- {
159
- let staged = [];
160
- try {
161
- staged = (await git(root, ["ls-files", "--cached", "-z"], indexFile)).split("\0").filter(Boolean);
162
- } catch {
163
- staged = [];
164
- }
165
- const frictionCarriers = [];
166
- for (const path of staged) {
167
- if (!isFrictionCarrierPath(path)) continue;
168
- try {
169
- frictionCarriers.push({ path, content: await git(root, ["show", `:${path}`], indexFile) });
170
- } catch {
171
- frictionCarriers.push({ path, content: "" });
172
- }
173
- }
174
- if (frictionCarriers.length > 0) {
175
- const frictionCommits = await checkFrictionCommitTargets(frictionCarriers, {
176
- resolves: async (hash) => {
177
- try {
178
- await git(root, ["cat-file", "-e", `${hash}^{commit}`], indexFile);
179
- return true;
180
- } catch {
181
- return false;
182
- }
183
- },
184
- });
185
- if (!frictionCommits.ok) issues.push(...frictionCommits.issues);
186
- }
187
- }
188
-
189
184
  const normCarriers = await collectNormCarriers(root, correspondence.changedPaths ?? [], indexFile);
190
185
  if (normCarriers.length > 0) {
191
186
  const uniqueness = checkNormDirectionUniqueness(normCarriers);
@@ -243,6 +238,7 @@ function report(hookName, issues) {
243
238
  }
244
239
 
245
240
  async function runCommitMsgChecks(argv) {
241
+ const startedAt = Date.now();
246
242
  const workspaceRoot = valueAfter(argv, "--workspace-root");
247
243
  const worktree = valueAfter(argv, "--worktree");
248
244
  const messageFile = valueAfter(argv, "--message-file");
@@ -254,6 +250,14 @@ async function runCommitMsgChecks(argv) {
254
250
  const stagedPaths = extractDiffPaths(dispatchDiff);
255
251
  if (stagedPaths.length > 0 && !touchesGovernedContent(stagedPaths)) {
256
252
  process.stderr.write("LDVH Git Gate (commit-msg) passed: ordinary commit (no managed carrier, spec carrier, repository-root README.md touched) — controlled-commit checks skipped per 09 §5.5\n");
253
+ await recordGitGateEvent({
254
+ command: "git-commit-msg",
255
+ status: "completed",
256
+ codes: ["ordinary_commit"],
257
+ detail: "ordinary commit",
258
+ cwd: root,
259
+ durationMs: Date.now() - startedAt,
260
+ });
257
261
  return 0;
258
262
  }
259
263
  const shared = await runSharedChecks(root, indexFile, message);
@@ -266,13 +270,32 @@ async function runCommitMsgChecks(argv) {
266
270
  } else {
267
271
  issues.push(...checkSignatureAgainstRoute(message, route).issues);
268
272
  }
269
- if (issues.length > 0) return report("commit-msg", issues);
273
+ if (issues.length > 0) {
274
+ await recordGitGateEvent({
275
+ command: "git-commit-msg",
276
+ status: "rejected",
277
+ codes: issues.slice(0, 5).map((issue) => issue.rule),
278
+ detail: issues.map((issue) => `${issue.rule}: ${issue.message}`).join("; "),
279
+ cwd: root,
280
+ durationMs: Date.now() - startedAt,
281
+ });
282
+ return report("commit-msg", issues);
283
+ }
270
284
  const snapshot = snapshotIdentity(shared.diff, message);
271
285
  process.stderr.write(`LDVH Git Gate (commit-msg) passed: source_fingerprint=${SOURCE_FINGERPRINT} snapshot_identity=${snapshot}\n`);
286
+ await recordGitGateEvent({
287
+ command: "git-commit-msg",
288
+ status: "completed",
289
+ codes: [],
290
+ detail: "",
291
+ cwd: root,
292
+ durationMs: Date.now() - startedAt,
293
+ });
272
294
  return 0;
273
295
  }
274
296
 
275
297
  async function mainPreCommit(argv) {
298
+ const startedAt = Date.now();
276
299
  const workspaceRoot = valueAfter(argv, "--workspace-root");
277
300
  const worktree = valueAfter(argv, "--worktree");
278
301
  const indexFile = valueAfter(argv, "--index-file");
@@ -283,8 +306,26 @@ async function mainPreCommit(argv) {
283
306
  const lintFiles = await stagedLintFiles(lintRoot, root, indexFile);
284
307
  const lint = await checkLint(lintRoot, lintFiles);
285
308
  if (!lint.ok) issues.push(...lint.issues);
286
- if (issues.length > 0) return report("pre-commit", issues);
309
+ if (issues.length > 0) {
310
+ await recordGitGateEvent({
311
+ command: "git-pre-commit",
312
+ status: "rejected",
313
+ codes: issues.slice(0, 5).map((issue) => issue.rule),
314
+ detail: issues.map((issue) => `${issue.rule}: ${issue.message}`).join("; "),
315
+ cwd: root,
316
+ durationMs: Date.now() - startedAt,
317
+ });
318
+ return report("pre-commit", issues);
319
+ }
287
320
  process.stderr.write("LDVH Git Gate (pre-commit) passed\n");
321
+ await recordGitGateEvent({
322
+ command: "git-pre-commit",
323
+ status: "completed",
324
+ codes: [],
325
+ detail: "",
326
+ cwd: root,
327
+ durationMs: Date.now() - startedAt,
328
+ });
288
329
  return 0;
289
330
  }
290
331
 
@@ -436,6 +477,14 @@ if (invokedDirectly) {
436
477
  try {
437
478
  process.exitCode = await main(process.argv.slice(2));
438
479
  } catch (error) {
480
+ const argv = process.argv.slice(2);
481
+ await recordGitGateEvent({
482
+ command: argv[0],
483
+ status: "execution_error",
484
+ codes: ["git_gate_unavailable"],
485
+ detail: String(error?.message || error),
486
+ cwd: valueAfter(argv, "--worktree") ?? process.cwd(),
487
+ });
439
488
  process.stderr.write(`LDVH Git Gate (commit-msg) unavailable: ${String(error?.message || error)}\n`);
440
489
  process.exitCode = 1;
441
490
  }
@@ -1,12 +1,11 @@
1
1
  import { join } from "node:path";
2
2
 
3
3
  import { readGoalObject } from "./goal-writer.js";
4
- import { listMilestoneObjects } from "./milestone-writer.js";
5
4
 
6
5
  export const GOAL_ANCHOR_BUDGET_CHARS = 520;
7
6
 
8
- const ANCHOR_HEADER = "【项目目标与活跃里程碑 · 高优先锚点】";
9
- const ANCHOR_FOOTER = "(全量查询:ldvh_goal_read / ldvh_milestone_list;仅作方向锚点,不替代行动核对。)";
7
+ const ANCHOR_HEADER = "【项目目标 · 高优先锚点】";
8
+ const ANCHOR_FOOTER = "(全量查询:ldvh_goal_read;仅作方向锚点,不替代行动核对。)";
10
9
 
11
10
  function clipText(text, maxChars) {
12
11
  if (typeof text !== "string") return "";
@@ -26,75 +25,48 @@ function firstGoalStatementLine(bodyMarkdown) {
26
25
  }
27
26
 
28
27
  /**
29
- * 构建极简「项目目标与活跃里程碑」高优先常驻锚点(直读 goal.md 与 active milestones)。
28
+ * 构建极简「项目目标」高优先常驻锚点(仅直读并注入 goal.md 目标陈述)。
30
29
  */
31
30
  export async function buildGoalAnchorForRoot({ root, budgetChars = GOAL_ANCHOR_BUDGET_CHARS } = {}) {
32
31
  const limit = Number.isInteger(budgetChars) && budgetChars > 0 ? budgetChars : 0;
33
32
  if (typeof root !== "string" || root.trim() === "" || limit <= 0) {
34
- return { ok: true, text: "", goalPresent: false, milestoneCount: 0, truncated: false };
33
+ return { ok: true, text: "", goalPresent: false, truncated: false };
35
34
  }
36
35
 
37
36
  const factSourceRoot = join(root, "ldvh-base");
38
- const lines = [];
37
+ let goalLine = "";
39
38
  let goalPresent = false;
40
- let milestoneCount = 0;
41
39
 
42
40
  try {
43
41
  const goalRes = await readGoalObject({ factSourceRoot });
44
42
  if (goalRes?.ok && goalRes.value) {
45
43
  const fm = goalRes.value.frontmatter ?? {};
46
44
  const title = clipText(fm.title || "项目目标", 64);
47
- const summary = firstGoalStatementLine(goalRes.value.body_markdown ?? "");
48
- lines.push(summary ? `- [Goal] ${title} — ${summary}(ldvh-base/goal.md)` : `- [Goal] ${title}(ldvh-base/goal.md)`);
45
+ const summary = firstGoalStatementLine(goalRes.value.body_markdown ?? goalRes.value.body ?? "");
46
+ goalLine = summary ? `- [Goal] ${title} — ${summary}(ldvh-base/goal.md)` : `- [Goal] ${title}(ldvh-base/goal.md)`;
49
47
  goalPresent = true;
50
48
  }
51
49
  } catch {
52
50
  // 读取 Goal 失败不阻断锚点构建
53
51
  }
54
52
 
55
- try {
56
- const msRes = await listMilestoneObjects({ factSourceRoot, status: "active", limit: 5 });
57
- const items = Array.isArray(msRes?.value?.items) ? msRes.value.items : [];
58
- milestoneCount = items.length;
59
- for (const item of items.slice(0, 3)) {
60
- const title = clipText(item?.title || item?.object_uid || "Milestone", 56);
61
- const criterion = clipText(item?.criterion || "", 56);
62
- const relPath = item?.path || (item?.object_uid ? `ldvh-base/milestones/${item.object_uid}.md` : "");
63
- const loc = relPath ? `(${relPath})` : "";
64
- lines.push(criterion ? `- [Milestone/active] ${title} — 达成条件:${criterion}${loc}` : `- [Milestone/active] ${title}${loc}`);
65
- }
66
- } catch {
67
- // 读取 Milestone 失败不阻断锚点构建
53
+ if (!goalPresent || !goalLine) {
54
+ return { ok: true, text: "", goalPresent: false, truncated: false };
68
55
  }
69
56
 
70
- if (lines.length === 0) {
71
- return { ok: true, text: "", goalPresent: false, milestoneCount: 0, truncated: false };
72
- }
73
-
74
- const kept = [];
75
- let used = ANCHOR_HEADER.length + 1 + ANCHOR_FOOTER.length;
57
+ const overhead = ANCHOR_HEADER.length + 1 + ANCHOR_FOOTER.length;
58
+ let keptLine = goalLine;
76
59
  let truncated = false;
77
- for (const line of lines) {
78
- const cost = line.length + 1;
79
- if (used + cost > limit) {
80
- if (kept.length === 0) {
81
- const room = Math.max(24, limit - used - 1);
82
- kept.push(clipText(line, room));
83
- truncated = true;
84
- } else {
85
- truncated = true;
86
- }
87
- break;
88
- }
89
- kept.push(line);
90
- used += cost;
60
+ if (overhead + goalLine.length + 1 > limit) {
61
+ const room = Math.max(24, limit - overhead - 1);
62
+ keptLine = clipText(goalLine, room);
63
+ truncated = true;
91
64
  }
92
65
 
93
66
  return {
94
67
  ok: true,
95
- text: [ANCHOR_HEADER, ...kept, ANCHOR_FOOTER].join("\n"),
96
- goalPresent,
97
- milestoneCount,
68
+ text: [ANCHOR_HEADER, keptLine, ANCHOR_FOOTER].join("\n"),
69
+ goalPresent: true,
98
70
  truncated,
99
71
  };
100
72
  }
package/lib/goal-tools.js CHANGED
@@ -7,7 +7,6 @@ import {
7
7
  } from "./goal-writer.js";
8
8
  import { defineTool } from "./define-tool.js";
9
9
  import { toParameterSpec } from "./parameter-spec-adapter.js";
10
- import { listMilestoneObjects } from "./milestone-writer.js";
11
10
  import { currentRouteValues } from "./session-signature.js";
12
11
  import { FRONTMATTER_AFTER_DESCRIPTION, FRONTMATTER_REMOVALS_DESCRIPTION } from "./after-integrity.js";
13
12
  import { authoritativeSignature } from "./signature-channel.js";
@@ -22,7 +21,7 @@ import {
22
21
  const OPERATIONS = {
23
22
  "goal-read-object": {
24
23
  toolName: "ldvh_goal_read",
25
- summary: "Precise read of the singleton Goal object (ldvh-base/goal.md): frontmatter, body, milestone anchors and file fingerprint (specs/25 §12, specs/03 §9.2)",
24
+ summary: "Precise read of the singleton Goal object (ldvh-base/goal.md): frontmatter, body and file fingerprint (specs/25 §12, specs/03 §9.2)",
26
25
  effect: "read"
27
26
  },
28
27
  "goal-write-object": {
@@ -92,11 +91,6 @@ export function makeExecute(deps) {
92
91
  follow_up: read.error.code === "goal/not_initialised" ? ["run the project init conversation to create the goal"] : []
93
92
  });
94
93
  }
95
- const derived = await listMilestoneObjects({ factSourceRoot: `${governed.path}/ldvh-base`, status: "all" });
96
- const derivedItems = derived.ok ? derived.value.items : [];
97
- const derivedGaps = derived.ok
98
- ? []
99
- : [`milestone-derivation: ${derived.error.code}: ${derived.error.message}`];
100
94
  const prog = await applyProgressiveRead({
101
95
  filePath: read.value.file,
102
96
  body: read.value.body,
@@ -107,15 +101,6 @@ export function makeExecute(deps) {
107
101
  result: {
108
102
  status: read.value.frontmatter.status,
109
103
  title: read.value.frontmatter.title,
110
- milestones: derivedItems.map((item) => ({
111
- object_uid: item.object_uid,
112
- title: item.title,
113
- order: item.order,
114
- status: item.status,
115
- criterion: item.criterion,
116
- criterion_kind: item.criterion_kind,
117
- })),
118
- milestones_unresolved: derivedItems.length === 0,
119
104
  legacy_milestone_section: hasLegacyMilestoneSection(read.value.body),
120
105
  frontmatter: read.value.frontmatter,
121
106
  ...(prog.body_omitted ? {} : { body: prog.body }),
@@ -133,16 +118,9 @@ export function makeExecute(deps) {
133
118
  sources: [{ kind: "fact-object", path: read.value.file, content_fingerprint: read.value.fingerprint }],
134
119
  gaps: [
135
120
  ...read.value.body_issues,
136
- ...derivedGaps,
137
121
  ...prog.gaps,
138
- ...(derivedItems.length === 0
139
- ? ["milestone-empty: 本项目尚无任何里程碑对象——既可能未精化,也可能下游未声明;两种情形机械层不可区分(28 §8.1)"]
140
- : []),
141
- ...(hasLegacyMilestoneSection(read.value.body)
142
- ? ["goal/legacy_milestone_section: goal.md 仍带已移出的里程碑段,须迁移到 Milestone 载体后再删除(25 §7)"]
143
- : []),
144
122
  ],
145
- verification: { checks: ["carrier-present", "frontmatter-closed-set", "body-structure", "milestone-parse"], passed: read.value.body_valid },
123
+ verification: { checks: ["carrier-present", "frontmatter-closed-set", "body-structure"], passed: read.value.body_valid },
146
124
  follow_up: prog.isPartial
147
125
  ? [...prog.follow_up]
148
126
  : ["goal-write-object action=update with the observed fingerprint when a revision is needed"]
@@ -204,7 +182,7 @@ export function makeExecute(deps) {
204
182
  sources: [{ kind: "fact-object", path: created.value.file, content_fingerprint: created.value.fingerprint }],
205
183
  gaps: [],
206
184
  verification: { checks: ["singleton-absent", "goal-key", "status-active", "statement-present", "atomic-write", "read-back"], passed: true },
207
- follow_up: ["milestone refinement is a later controlled update (25 §7) — statement-only creation is a legal intermediate state"]
185
+ follow_up: ["Goal creation completed — revise via goal-write-object action=update if the goal statement changes"]
208
186
  });
209
187
  }
210
188
 
@@ -247,7 +225,7 @@ export function makeExecute(deps) {
247
225
  sources: [{ kind: "fact-object", path: updated.value.file, content_fingerprint: updated.value.fingerprint }],
248
226
  gaps: [],
249
227
  verification: { checks: ["cas-baseline", "anchor-stability", "frontmatter-closed-set", "body-structure", "atomic-write", "read-back"], passed: true },
250
- follow_up: ["Goal 陈述已修订:按 parent_goal → serves 两层反查,逐个核对下游里程碑的 alignment 与作用范围是否仍相容(20 §13 / 30 §8.5);每跳是标记非动作,Goal 侧不存储下游状态"]
228
+ follow_up: ["Goal 陈述已修订:请按需核对当前 open Intent 与在途工作是否仍与最新目标陈述保持一致"]
251
229
  });
252
230
  }
253
231