@fenglimg/fabric-cli 2.2.0-rc.4 → 2.2.0-rc.9

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 (73) hide show
  1. package/README.md +8 -5
  2. package/dist/{chunk-5JG4QJLO.js → chunk-27HK6H5Y.js} +10 -5
  3. package/dist/{chunk-F6ITRM7T.js → chunk-2KBCTMID.js} +29 -6
  4. package/dist/chunk-3D7B2UAZ.js +149 -0
  5. package/dist/{chunk-XC5RUHLK.js → chunk-3IOLS5EK.js} +23 -38
  6. package/dist/{chunk-XHHCRDIR.js → chunk-7ZDXBOOU.js} +174 -211
  7. package/dist/{doctor-U5W4CX5I.js → chunk-E7HJUU34.js} +103 -51
  8. package/dist/{chunk-XCBVSGCS.js → chunk-FNHDQTPC.js} +1 -10
  9. package/dist/{chunk-2CY4BMTH.js → chunk-HORSMSZL.js} +9 -5
  10. package/dist/{chunk-BO4XIZWZ.js → chunk-NLNH64A3.js} +5 -18
  11. package/dist/{chunk-H3FE6VIK.js → chunk-PTGQAZEW.js} +13 -3
  12. package/dist/chunk-QFIVFZRH.js +13 -0
  13. package/dist/{chunk-5SSNE5GM.js → chunk-QPAW6IYT.js} +125 -39
  14. package/dist/{chunk-COI5VDFU.js → chunk-WA3DYGSY.js} +1 -2
  15. package/dist/{plan-context-hint-CHVZGOZ5.js → chunk-YM4XATJF.js} +29 -4
  16. package/dist/{config-VJMXCLXW.js → config-A3LTECAY.js} +4 -3
  17. package/dist/context-7NUKXDB6.js +117 -0
  18. package/dist/doctor-MDTZWKBK.js +24 -0
  19. package/dist/index.d.ts +2 -2
  20. package/dist/index.js +131 -21
  21. package/dist/info-7FKBTMVO.js +139 -0
  22. package/dist/install-v2-I6PJ6IFT.js +3279 -0
  23. package/dist/{metrics-RER6NLFC.js → metrics-HMFH4YHK.js} +1 -1
  24. package/dist/{onboard-coverage-JWQWDZW7.js → onboard-coverage-XSG77LL3.js} +48 -27
  25. package/dist/plan-context-hint-G75R4P4J.js +12 -0
  26. package/dist/{scope-explain-BWRWBCCP.js → scope-explain-HLJZ2M33.js} +3 -2
  27. package/dist/{status-7UFLWRX7.js → status-4R3TM4FJ.js} +8 -5
  28. package/dist/{store-ZEZMQVG7.js → store-HOCORVL3.js} +96 -350
  29. package/dist/{sync-EA5HZMXM.js → sync-DT5UJMMR.js} +36 -13
  30. package/dist/{uninstall-F75MPKQC.js → uninstall-IFN2KYBK.js} +71 -140
  31. package/dist/{whoami-3FRWYGML.js → whoami-ITGEFWH4.js} +9 -7
  32. package/package.json +7 -5
  33. package/templates/hooks/cite-policy-evict.cjs +5 -5
  34. package/templates/hooks/configs/README.md +14 -27
  35. package/templates/hooks/configs/claude-code.json +1 -1
  36. package/templates/hooks/configs/codex-hooks.json +3 -3
  37. package/templates/hooks/fabric-hint.cjs +326 -161
  38. package/templates/hooks/knowledge-hint-broad.cjs +431 -271
  39. package/templates/hooks/knowledge-hint-narrow.cjs +64 -77
  40. package/templates/hooks/lib/banner-i18n.cjs +31 -0
  41. package/templates/hooks/lib/bindings-snapshot-reader.cjs +118 -7
  42. package/templates/hooks/lib/cite-line-parser.cjs +12 -20
  43. package/templates/hooks/lib/client-adapter.cjs +66 -7
  44. package/templates/hooks/lib/nudge-policy.cjs +117 -0
  45. package/templates/hooks/lib/state-store.cjs +60 -0
  46. package/templates/hooks/post-tooluse-mutation.cjs +112 -11
  47. package/templates/skills/fabric/SKILL.md +100 -0
  48. package/templates/skills/fabric-archive/SKILL.md +29 -26
  49. package/templates/skills/fabric-archive/ref/dry-run-scope.md +1 -1
  50. package/templates/skills/fabric-archive/ref/i18n-policy.md +2 -3
  51. package/templates/skills/fabric-archive/ref/phase-1-5-onboard.md +2 -3
  52. package/templates/skills/fabric-archive/ref/phase-1-cross-session.md +1 -1
  53. package/templates/skills/fabric-archive/ref/phase-2-5-viability.md +1 -1
  54. package/templates/skills/fabric-archive/ref/phase-3-6-related-edges.md +18 -0
  55. package/templates/skills/fabric-archive/ref/phase-3-7-semantic-scope.md +47 -0
  56. package/templates/skills/fabric-audit/SKILL.md +13 -3
  57. package/templates/skills/fabric-connect/SKILL.md +3 -3
  58. package/templates/skills/fabric-import/SKILL.md +7 -7
  59. package/templates/skills/fabric-import/ref/i18n-policy.md +2 -3
  60. package/templates/skills/fabric-import/ref/state-recovery.md +1 -2
  61. package/templates/skills/fabric-review/SKILL.md +5 -5
  62. package/templates/skills/fabric-review/ref/cite-contract.md +1 -1
  63. package/templates/skills/fabric-review/ref/i18n-policy.md +2 -3
  64. package/templates/skills/fabric-review/ref/output-contract.md +1 -1
  65. package/templates/skills/fabric-review/ref/per-mode-flows.md +2 -2
  66. package/templates/skills/fabric-review/ref/worked-examples.md +1 -1
  67. package/templates/skills/fabric-store/SKILL.md +1 -1
  68. package/templates/skills/fabric-sync/SKILL.md +1 -1
  69. package/templates/skills/lib/shared-policy.md +2 -2
  70. package/dist/install-7XJ64WSC.js +0 -2743
  71. package/templates/hooks/configs/cursor-hooks.json +0 -30
  72. package/templates/hooks/lib/cite-contract-reminder.cjs +0 -179
  73. package/templates/hooks/lib/summary-fallback.cjs +0 -210
@@ -75,15 +75,13 @@ const {
75
75
  } = require("node:fs");
76
76
  const { dirname, join } = require("node:path");
77
77
 
78
- // rc.35 TASK-06 (P0-10.b): summary-fallback. Substitutes opaque entries
79
- // (where description.summary === stable_id) with a snippet read from the
80
- // entry's .md `## Summary` section. Caches results in
81
- // `.fabric/.cache/summary-fallback.json` keyed by revision_hash.
82
- const { resolveOpaqueSummaries } = require("./lib/summary-fallback.cjs");
78
+ // KT-GLD-0006: the rc.35 opaque-summary substitution (resolveOpaqueSummaries) is
79
+ // retired the write-time mechanical floor in extractKnowledge prevents
80
+ // degenerate summaries at the source, so the narrow hook no longer band-aids them.
83
81
  // v2.0.0-rc.37 NEW-17: shared sidecar I/O for the plan-context-hint result
84
82
  // cache (skips a redundant CLI cold-start spawn when the same path-set is
85
83
  // re-edited within a session and the knowledge graph hasn't changed).
86
- const { readJsonState, writeJsonState } = require("./lib/state-store.cjs");
84
+ const { readJsonStateAsync, writeJsonStateAsync } = require("./lib/state-store.cjs");
87
85
  // W1-01 (ISS-011): the PreToolUse hook is the highest-frequency, most
88
86
  // concurrency-exposed write surface in Fabric. Multi-window edits spawn
89
87
  // concurrent hook processes that all append to the SAME non-session-scoped
@@ -93,7 +91,18 @@ const { readJsonState, writeJsonState } = require("./lib/state-store.cjs");
93
91
  const { appendLockedLine } = require("./lib/injection-log.cjs");
94
92
  // lifecycle-refactor W1-T2: client discriminator for the hook_surface_emitted
95
93
  // event (schema requires the `client` enum). Mirrors the broad hook's import.
96
- const { detectClient } = require("./lib/client-adapter.cjs");
94
+ // v2.2 dual-sink (Goal A): + emitDualSink (PreToolUse two-channel emit).
95
+ const { detectClient, emitDualSink } = require("./lib/client-adapter.cjs");
96
+ // v2.2 dual-sink (Goal A / D4 + C5): human-output gate. On a narrow HIT the human
97
+ // systemMessage is gated by nudge_mode (a miss is already a silent early-return
98
+ // above); the AI additionalContext is emitted regardless (flow ⊥ observation).
99
+ // Optional require so an old install degrades to "always emit human".
100
+ let nudgePolicy = null;
101
+ try {
102
+ nudgePolicy = require("./lib/nudge-policy.cjs");
103
+ } catch {
104
+ // Lib missing (old install) — human sink always emits (legacy behavior).
105
+ }
97
106
  // v2.1.0-rc.1 P4 (F4/S63): hook-side reader for the CLI pre-generated
98
107
  // resolved-bindings snapshot. Store-aware hint surfaces the write-target store
99
108
  // for the edited file WITHOUT re-resolving or walking store trees. Best-effort.
@@ -242,8 +251,8 @@ function readPayload(rawStdin) {
242
251
  } catch (e) {
243
252
  // v2.0.0-rc.29 REVIEW (codex LOW-1): apply BUG-L1's malformed-input
244
253
  // diagnostic uniformly across hook scripts. fabric-hint.cjs got the stderr
245
- // trace in TASK-008; without this matching write here, a broken Codex /
246
- // Cursor host payload silently kills the narrow hint with no operator
254
+ // trace in TASK-008; without this matching write here, a broken Codex
255
+ // host payload silently kills the narrow hint with no operator
247
256
  // signal at all. Best-effort: a failed stderr write must not throw upward
248
257
  // (hook contract — never crash the host's edit pipeline).
249
258
  try {
@@ -257,32 +266,27 @@ function readPayload(rawStdin) {
257
266
  }
258
267
 
259
268
  /**
260
- * Extract the tool name from a hook payload. Clients differ in casing /
261
- * field placement; we probe the conventional shapes:
269
+ * Extract the tool name from a hook payload. Both supported clients use the
270
+ * same shape:
262
271
  * - Claude Code: { tool_name, tool_input: { ... } }
263
272
  * - Codex CLI: { tool_name, tool_input: { ... } } (mirrors Claude)
264
- * - Cursor: { tool, input: { ... } } (legacy variant)
265
273
  * Returns null when no recognizable shape is present.
266
274
  */
267
275
  function extractToolName(payload) {
268
276
  if (!payload || typeof payload !== "object") return null;
269
277
  if (typeof payload.tool_name === "string") return payload.tool_name;
270
- if (typeof payload.tool === "string") return payload.tool;
271
278
  return null;
272
279
  }
273
280
 
274
281
  /**
275
- * Extract the tool_input object from a hook payload, accepting both the
276
- * `tool_input` (Claude/Codex) and `input` (Cursor) conventions.
282
+ * Extract the tool_input object from a hook payload (the `tool_input`
283
+ * convention shared by Claude Code and Codex CLI).
277
284
  */
278
285
  function extractToolInput(payload) {
279
286
  if (!payload || typeof payload !== "object") return null;
280
287
  if (payload.tool_input && typeof payload.tool_input === "object") {
281
288
  return payload.tool_input;
282
289
  }
283
- if (payload.input && typeof payload.input === "object") {
284
- return payload.input;
285
- }
286
290
  return null;
287
291
  }
288
292
 
@@ -292,8 +296,8 @@ function extractToolInput(payload) {
292
296
  * - bulk variant: { file_paths: ["src/foo.ts", "src/bar.ts"] }
293
297
  * - MultiEdit: { file_path: "...", edits: [{file_path?, ...}, ...] }
294
298
  * (Claude Code's MultiEdit currently issues per-edit operations against
295
- * a single `file_path`; older drafts and Cursor's variant carried
296
- * per-edit `file_path`. We accept both to be defensive.)
299
+ * a single `file_path`; older drafts carried per-edit `file_path`. We
300
+ * accept both to be defensive.)
297
301
  *
298
302
  * Returns a deduped array of strings — empty when no path is recognizable.
299
303
  * Order: first occurrence wins (stable across re-renders of the same payload).
@@ -523,7 +527,7 @@ function appendHintSilenceCounter(projectRoot, now) {
523
527
  /**
524
528
  * Resolve the session id used to key the cache file. Priority:
525
529
  * 1. payload.session_id (string, non-empty) — preferred; threads through
526
- * from the client hook payload (Claude Code / Codex CLI / Cursor).
530
+ * from the client hook payload (Claude Code / Codex CLI).
527
531
  * 2. process.env.FABRIC_SESSION_ID — environment fallback.
528
532
  * 3. SYNTHETIC_SESSION_ID — a process-lifetime UUID, generated lazily so
529
533
  * tests can stub it (see resetSyntheticSessionId).
@@ -865,9 +869,9 @@ function pathSetKey(paths) {
865
869
 
866
870
  // Returns the cached cliPayload for `paths` iff the cache's meta token matches
867
871
  // the current knowledge-graph freshness, else null (caller spawns the CLI).
868
- function readNarrowResultCache(cwd, sessionId, paths, metaToken) {
872
+ async function readNarrowResultCache(cwd, sessionId, paths, metaToken) {
869
873
  if (metaToken === null) return null;
870
- const cache = readJsonState(
874
+ const cache = await readJsonStateAsync(
871
875
  cwd,
872
876
  narrowResultCacheFileName(sessionId),
873
877
  (parsed) => parsed && typeof parsed === "object" && parsed.results && typeof parsed.results === "object",
@@ -880,10 +884,10 @@ function readNarrowResultCache(cwd, sessionId, paths, metaToken) {
880
884
  // Persist `cliPayload` under the path-set key. Resets the map when the meta
881
885
  // token changed (stale graph) and caps the map size (FIFO-ish: drop oldest
882
886
  // insertion-order keys). Best-effort — never throws.
883
- function writeNarrowResultCache(cwd, sessionId, paths, metaToken, cliPayload) {
887
+ async function writeNarrowResultCache(cwd, sessionId, paths, metaToken, cliPayload) {
884
888
  if (metaToken === null) return;
885
889
  const fileName = narrowResultCacheFileName(sessionId);
886
- const prior = readJsonState(
890
+ const prior = await readJsonStateAsync(
887
891
  cwd,
888
892
  fileName,
889
893
  (parsed) => parsed && typeof parsed === "object" && parsed.results && typeof parsed.results === "object",
@@ -897,7 +901,7 @@ function writeNarrowResultCache(cwd, sessionId, paths, metaToken, cliPayload) {
897
901
  delete results[stale];
898
902
  }
899
903
  }
900
- writeJsonState(cwd, fileName, { meta_token: metaToken, results });
904
+ await writeJsonStateAsync(cwd, fileName, { meta_token: metaToken, results });
901
905
  }
902
906
 
903
907
  // -----------------------------------------------------------------------------
@@ -1246,7 +1250,7 @@ function renderSummary(payload, maxLen) {
1246
1250
  // Main — invoked as a CLI (require.main === module) and in-process by tests
1247
1251
  // -----------------------------------------------------------------------------
1248
1252
 
1249
- function main(env, stdio) {
1253
+ async function main(env, stdio) {
1250
1254
  try {
1251
1255
  const cwd = (env && env.cwd) || process.cwd();
1252
1256
  const now = (env && env.now) || new Date();
@@ -1348,14 +1352,14 @@ function main(env, stdio) {
1348
1352
  const useResultCache = !(env && env.skipResultCache === true);
1349
1353
  const metaToken = useResultCache ? metaFreshnessToken(cwd) : null;
1350
1354
  const cached = useResultCache
1351
- ? readNarrowResultCache(cwd, sessionId, paths, metaToken)
1355
+ ? await readNarrowResultCache(cwd, sessionId, paths, metaToken)
1352
1356
  : null;
1353
1357
  if (cached !== null) {
1354
1358
  cliPayload = cached;
1355
1359
  } else {
1356
1360
  cliPayload = invokePlanContextHint(cwd, paths);
1357
1361
  if (useResultCache && cliPayload !== null && cliPayload !== undefined) {
1358
- writeNarrowResultCache(cwd, sessionId, paths, metaToken, cliPayload);
1362
+ await writeNarrowResultCache(cwd, sessionId, paths, metaToken, cliPayload);
1359
1363
  }
1360
1364
  }
1361
1365
  }
@@ -1486,21 +1490,10 @@ function main(env, stdio) {
1486
1490
  }
1487
1491
 
1488
1492
  const summaryMaxLen = readSummaryMaxLen(cwd);
1489
- // rc.35 TASK-06 (P0-10.b): substitute opaque summaries before render.
1490
- // Same lib used by the broad hook — opaque entries seen from both call
1491
- // sites share a single .fabric/.cache/summary-fallback.json file.
1492
- // Best-effort any failure leaves the original opaque summary intact.
1493
- let resolvedEntries = dedupDecision.filtered;
1494
- try {
1495
- resolvedEntries = resolveOpaqueSummaries(
1496
- dedupDecision.filtered,
1497
- cwd,
1498
- currentRevisionHash,
1499
- );
1500
- } catch {
1501
- // resolveOpaqueSummaries swallows its own errors; defensive catch.
1502
- }
1503
- const lines = renderSummary({ ...cliPayload, entries: resolvedEntries }, summaryMaxLen);
1493
+ // KT-GLD-0006: the rc.35 opaque-summary runtime substitution is retired the
1494
+ // write-time mechanical floor in extractKnowledge prevents degenerate summaries
1495
+ // at the source, so the narrow hook renders the description summary as-is.
1496
+ const lines = renderSummary({ ...cliPayload, entries: dedupDecision.filtered }, summaryMaxLen);
1504
1497
  if (lines.length === 0) return;
1505
1498
 
1506
1499
  // v2.1.0-rc.1 P4 (F4/S63): store-aware hint — append the write-target store
@@ -1522,9 +1515,27 @@ function main(env, stdio) {
1522
1515
  }
1523
1516
  }
1524
1517
 
1525
- // Stderr: human-facing breadcrumb + legacy contract.
1526
- for (const line of lines) {
1527
- err.write(`${line}\n`);
1518
+ // v2.2 dual-sink (Goal A / C5): a narrow HIT emits BOTH channels. The human
1519
+ // systemMessage is gated by nudge_mode (a MISS already returned silently far
1520
+ // above — narrow.length===0 / gate-skip / dedup-filter); the AI
1521
+ // additionalContext is emitted regardless (gated only by reminder_to_context),
1522
+ // preserving flow ⊥ observation (D5). emitDualSink shapes the protocol per
1523
+ // client (CC/Codex camelCase nested; unknown → stderr).
1524
+ const text = lines.join("\n");
1525
+ const humanGate =
1526
+ nudgePolicy !== null
1527
+ ? nudgePolicy.resolveHumanSink(cwd, "pre_tool_use", { hit: true })
1528
+ : { emitHuman: true };
1529
+ const human = humanGate.emitHuman ? text : null;
1530
+ const ai = readReminderToContext(cwd) ? text : null;
1531
+ if (!(env && env.skipStdout === true)) {
1532
+ emitDualSink(
1533
+ { human, ai },
1534
+ { client: detectClient(), eventName: "PreToolUse", streams: { stdout: out, stderr: err } },
1535
+ );
1536
+ } else if (human !== null) {
1537
+ // skipStdout test seam: still surface the human breadcrumb to stderr.
1538
+ err.write(`${text}\n`);
1528
1539
  }
1529
1540
 
1530
1541
  // lifecycle-refactor W1-T2: hook_surface_emitted — record WHICH narrow-scoped
@@ -1540,7 +1551,7 @@ function main(env, stdio) {
1540
1551
  const surfaceClient = detectClient();
1541
1552
  const fabricDir = join(cwd, FABRIC_DIR_REL);
1542
1553
  if (surfaceClient !== undefined && existsSync(fabricDir)) {
1543
- const renderedIds = resolvedEntries
1554
+ const renderedIds = dedupDecision.filtered
1544
1555
  .map((e) => (e && typeof e.id === "string" ? e.id : null))
1545
1556
  .filter((x) => x !== null);
1546
1557
  const realSessionId =
@@ -1569,33 +1580,10 @@ function main(env, stdio) {
1569
1580
  // best-effort telemetry — never block the edit
1570
1581
  }
1571
1582
 
1572
- // v2.0.0-rc.33 W2-6 (P0-7): stdout JSON envelope. When
1573
- // hint_reminder_to_context is true (default), serialize the same banner
1574
- // body as Claude Code's PreToolUse hookSpecificOutput shape so the model
1575
- // receives the reminder IN-CONTEXT (rc.32 baseline cite-coverage 3.1%
1576
- // root cause: reminders never entered model context). PreToolUse hook
1577
- // contract: stdout JSON with hookSpecificOutput.additionalContext is
1578
- // injected into the model's context window; the hook DOES NOT block the
1579
- // edit (additionalContext is informational, not a permissionDecision).
1580
- // v2.0.0-rc.33 W4 review-fix (gemini High-1): CC-specific stdout envelope.
1581
- // See knowledge-hint-broad.cjs companion for rationale — CLAUDE_PROJECT_DIR
1582
- // is the CC presence signal; Codex CLI / Cursor don't set it.
1583
- const _isClaudeCode =
1584
- typeof process.env.CLAUDE_PROJECT_DIR === "string" &&
1585
- process.env.CLAUDE_PROJECT_DIR.length > 0;
1586
- if (!(env && env.skipStdout === true) && _isClaudeCode && readReminderToContext(cwd)) {
1587
- try {
1588
- const envelope = {
1589
- hookSpecificOutput: {
1590
- hookEventName: "PreToolUse",
1591
- additionalContext: lines.join("\n"),
1592
- },
1593
- };
1594
- out.write(`${JSON.stringify(envelope)}\n`);
1595
- } catch {
1596
- // Best-effort — stderr is the durable contract.
1597
- }
1598
- }
1583
+ // v2.2 dual-sink (Goal A): the legacy rc.33 W2-6 CC-only stdout envelope is
1584
+ // replaced by emitDualSink above (which carries BOTH the human systemMessage
1585
+ // and the AI additionalContext, shaped per client). reminder_to_context still
1586
+ // gates whether the AI sink is populated (see `ai` above).
1599
1587
 
1600
1588
  // v2.0.0-rc.33 W2-5: record successful emit for cooldown gate.
1601
1589
  if (cooldownHours > 0 && !(env && env.skipCooldownWrite === true)) {
@@ -1684,6 +1672,5 @@ if (require.main === module) {
1684
1672
  main(
1685
1673
  { cwd: process.cwd(), now: new Date(), stdin: stdinRaw },
1686
1674
  { stderr: process.stderr },
1687
- );
1688
- process.exit(0);
1675
+ ).finally(() => process.exit(0));
1689
1676
  }
@@ -238,6 +238,37 @@ const STRINGS = {
238
238
  "zh-CN-hybrid": () => " 是否调 `fabric doctor --lint` 看看知识库健康度?",
239
239
  },
240
240
 
241
+ // ---- Stop hook: session-activity status (human trust anchor) -------------
242
+ // Observability grill (a): a no-signal Stop currently returns SILENT — the
243
+ // human only ever hears from Fabric when there is a nudge to act on, never a
244
+ // "here is what I did" status, which reads as "Fabric does nothing". This line
245
+ // is the trust anchor: session-scoped counts from events.jsonl (edits +
246
+ // knowledge pulls by the AI + pending backlog). Cadence is gated by nudge_mode
247
+ // (silent=never, normal=once/session, verbose=every turn) at the call site.
248
+ // params: { edits, consumed, pending } — all numbers.
249
+ statusLine: {
250
+ "zh-CN": (p) =>
251
+ `📋 Fabric 本会话 · 改 ${p.edits} 文件 · AI 取用知识 ${p.consumed} 次 · 待审 ${p.pending} 条`,
252
+ en: (p) =>
253
+ `📋 Fabric this session · ${p.edits} files edited · ${p.consumed} KB pulls by AI · ${p.pending} pending`,
254
+ "zh-CN-hybrid": (p) =>
255
+ `📋 Fabric 本会话 · 改 ${p.edits} 文件 · AI 取用知识 ${p.consumed} 次 · 待审 ${p.pending} 条`,
256
+ },
257
+
258
+ // ---- Stop hook: nudge_mode tier guidance (discoverability) ---------------
259
+ // Observability grill (Q4): users did not know the human-channel volume knob
260
+ // (nudge_mode) exists, so they assumed the hooks never surface to humans. This
261
+ // line names the current tier and the levers. params: { mode } — current
262
+ // nudge_mode. Protected token: nudge_mode + the config path verbatim.
263
+ statusTier: {
264
+ "zh-CN": (p) =>
265
+ ` 音量 ${p.mode}:verbose=每步可见 / silent=静音(.fabric/fabric-config.json nudge_mode)`,
266
+ en: (p) =>
267
+ ` volume ${p.mode}: verbose=show every step / silent=mute (.fabric/fabric-config.json nudge_mode)`,
268
+ "zh-CN-hybrid": (p) =>
269
+ ` 音量 ${p.mode}:verbose=每步可见 / silent=静音(.fabric/fabric-config.json nudge_mode)`,
270
+ },
271
+
241
272
  // ---- Broad hook: import recommendation ------------------------------------
242
273
  // Source (zh-CN): knowledge-hint-broad.cjs:262
243
274
  // " 📋 Fabric: 知识库稀疏,是否调 /fabric-import 从 git 历史与现有文档回灌知识?"
@@ -4,37 +4,50 @@
4
4
  // Hooks are a REMINDER layer (KT-DEC-0007) and must never block. They are also
5
5
  // FORBIDDEN from re-resolving stores or walking `.fabric` store trees directly
6
6
  // — a hook reads ONLY the CLI-pre-generated snapshot at
7
- // `~/.fabric/state/bindings/<project_id>_resolved.json` (written by P3
7
+ // `~/.fabric/state/bindings/<workspace_binding_id>_resolved.json` (written by P3
8
8
  // install/sync/bind). This keeps the resolver logic in one place (the CLI) and
9
9
  // keeps hooks a thin, store-unaware-by-construction projection. Missing /
10
10
  // unreadable / malformed snapshot → null (harmless degrade; the hook proceeds
11
11
  // without store labels). Zero-dep CJS so it inline-loads at hook runtime.
12
12
 
13
- const { existsSync, readFileSync } = require("node:fs");
13
+ const { existsSync, readFileSync, readdirSync, statSync } = require("node:fs");
14
14
  const { join } = require("node:path");
15
15
  const { homedir } = require("node:os");
16
16
 
17
+ // Canonical knowledge type dirs (mirror STORE_KNOWLEDGE_TYPE_DIRS in
18
+ // packages/shared/src/schemas/store.ts). Kept inline — this zero-dep reader
19
+ // runs in user repos without node_modules access.
20
+ const KNOWLEDGE_CANONICAL_TYPES = [
21
+ "decisions",
22
+ "pitfalls",
23
+ "guidelines",
24
+ "models",
25
+ "processes",
26
+ ];
27
+ const KNOWLEDGE_SUBDIR = "knowledge";
28
+ const PENDING_SUBDIR = "pending";
29
+
17
30
  // `~/.fabric` (FABRIC_HOME override mirrors the CLI's resolveGlobalRoot).
18
31
  function resolveGlobalRoot() {
19
32
  return join(process.env.FABRIC_HOME || homedir(), ".fabric");
20
33
  }
21
34
 
22
- function bindingsSnapshotPath(projectId, globalRoot) {
35
+ function bindingsSnapshotPath(bindingId, globalRoot) {
23
36
  return join(
24
37
  globalRoot || resolveGlobalRoot(),
25
38
  "state",
26
39
  "bindings",
27
- projectId + "_resolved.json",
40
+ bindingId + "_resolved.json",
28
41
  );
29
42
  }
30
43
 
31
44
  // Read + shallow-validate the snapshot. Returns the parsed object, or null when
32
45
  // absent / unreadable / not the expected shape. NEVER throws.
33
- function readBindingsSnapshot(projectId, globalRoot) {
34
- if (typeof projectId !== "string" || projectId.length === 0) {
46
+ function readBindingsSnapshot(bindingId, globalRoot) {
47
+ if (typeof bindingId !== "string" || bindingId.length === 0) {
35
48
  return null;
36
49
  }
37
- const path = bindingsSnapshotPath(projectId, globalRoot);
50
+ const path = bindingsSnapshotPath(bindingId, globalRoot);
38
51
  if (!existsSync(path)) {
39
52
  return null;
40
53
  }
@@ -54,6 +67,103 @@ function readBindingsSnapshot(projectId, globalRoot) {
54
67
  }
55
68
  }
56
69
 
70
+ // Recursively count *.md files under `dir`, tracking the oldest mtime. Missing
71
+ // / unreadable dirs contribute zero (degrade silently — a hook never throws).
72
+ function countMarkdownFiles(dir) {
73
+ let count = 0;
74
+ let oldestMtimeMs = null;
75
+ let entries;
76
+ try {
77
+ entries = readdirSync(dir, { withFileTypes: true });
78
+ } catch {
79
+ return { count, oldestMtimeMs };
80
+ }
81
+ for (const entry of entries) {
82
+ const fullPath = join(dir, entry.name);
83
+ if (entry.isDirectory()) {
84
+ const nested = countMarkdownFiles(fullPath);
85
+ count += nested.count;
86
+ if (
87
+ nested.oldestMtimeMs !== null &&
88
+ (oldestMtimeMs === null || nested.oldestMtimeMs < oldestMtimeMs)
89
+ ) {
90
+ oldestMtimeMs = nested.oldestMtimeMs;
91
+ }
92
+ continue;
93
+ }
94
+ if (!entry.isFile() || !entry.name.endsWith(".md")) {
95
+ continue;
96
+ }
97
+ let mtimeMs;
98
+ try {
99
+ mtimeMs = statSync(fullPath).mtimeMs;
100
+ } catch {
101
+ continue;
102
+ }
103
+ count += 1;
104
+ if (oldestMtimeMs === null || mtimeMs < oldestMtimeMs) {
105
+ oldestMtimeMs = mtimeMs;
106
+ }
107
+ }
108
+ return { count, oldestMtimeMs };
109
+ }
110
+
111
+ // LIVE store-backed knowledge counts for nudges (underseed canonical_count,
112
+ // review-backlog pending_count). The snapshot's cached `knowledge_stats` is a
113
+ // store-global projection frozen at write time, so it goes stale whenever store
114
+ // content changes out-of-band (a `git pull` in the store repo, a sync run from a
115
+ // *different* bound workspace) — that staleness is the root cause of the phantom
116
+ // review-backlog (KT-PIT-0017) and the false "knowledge sparse" underseed nudge.
117
+ //
118
+ // Fix: the snapshot persists the resolved store ROOT dirs (`knowledge_store_dirs`,
119
+ // stable across content sync — they only change when mounts/bindings change,
120
+ // which regenerates the snapshot). Recount the *.md files under those dirs LIVE
121
+ // so the numbers are always fresh regardless of how content changed. Falls back
122
+ // to the cached `knowledge_stats` for snapshots written before this field
123
+ // existed. Returns null only when neither source is available.
124
+ function liveKnowledgeStats(snapshot) {
125
+ if (!snapshot || typeof snapshot !== "object") {
126
+ return null;
127
+ }
128
+ const dirs = snapshot.knowledge_store_dirs;
129
+ if (Array.isArray(dirs) && dirs.length > 0) {
130
+ let pendingCount = 0;
131
+ let canonicalCount = 0;
132
+ let oldestPendingMtimeMs = null;
133
+ for (const storeDir of dirs) {
134
+ if (typeof storeDir !== "string" || storeDir.length === 0) {
135
+ continue;
136
+ }
137
+ for (const type of KNOWLEDGE_CANONICAL_TYPES) {
138
+ canonicalCount += countMarkdownFiles(join(storeDir, KNOWLEDGE_SUBDIR, type)).count;
139
+ }
140
+ const pending = countMarkdownFiles(join(storeDir, KNOWLEDGE_SUBDIR, PENDING_SUBDIR));
141
+ pendingCount += pending.count;
142
+ if (
143
+ pending.oldestMtimeMs !== null &&
144
+ (oldestPendingMtimeMs === null || pending.oldestMtimeMs < oldestPendingMtimeMs)
145
+ ) {
146
+ oldestPendingMtimeMs = pending.oldestMtimeMs;
147
+ }
148
+ }
149
+ return { pendingCount, canonicalCount, oldestPendingMtimeMs };
150
+ }
151
+ // #3 (GH issue): snapshot predates knowledge_store_dirs. The cached
152
+ // `knowledge_stats` projection is frozen at snapshot-write time and goes stale
153
+ // out-of-band (store grew via git pull / cross-workspace sync), so trusting it
154
+ // re-introduced exactly the false-nudge this whole field cures — observed a
155
+ // store with 61 live canonical entries whose cached count was frozen at 1,
156
+ // mis-firing the "knowledge sparse → /fabric-import" underseed nudge AND
157
+ // defeating the fabric-import `canonical > 50 → SKIP` guard. read_set carries
158
+ // no resolved store root either (alias/uuid only), so a live recount is
159
+ // impossible without re-resolution (which hooks must not do). Return null
160
+ // ("undeterminable") so callers SKIP the nudge rather than act on a stale
161
+ // count — old snapshots self-heal on the next install/sync/store-op (which
162
+ // regenerates the snapshot WITH knowledge_store_dirs). 宁可不弹也别误弹
163
+ // (KT-DEC-0007: hook = nudge, never a false-positive gate).
164
+ return null;
165
+ }
166
+
57
167
  // Render a compact, per-store label line for a SessionStart / Stop hook from a
58
168
  // snapshot. Empty string when there is nothing to show (degrade silently). The
59
169
  // label is provenance only — it never re-resolves; it just echoes the read-set
@@ -77,5 +187,6 @@ module.exports = {
77
187
  resolveGlobalRoot,
78
188
  bindingsSnapshotPath,
79
189
  readBindingsSnapshot,
190
+ liveKnowledgeStats,
80
191
  formatStoreLabels,
81
192
  };
@@ -15,13 +15,12 @@
15
15
  // hand-syncing is cheaper than introducing transpile machinery.
16
16
  // - The existing `installHookLibs` pipeline auto-copies every `.cjs` under
17
17
  // templates/hooks/lib/ to each client's hooks/lib/ dir, so this file
18
- // auto-ships to cc/codex/cursor with no install pipeline change.
18
+ // auto-ships to cc/codex with no install pipeline change.
19
19
  //
20
20
  // Vocabulary contract (mirrored 1:1 with the TS source):
21
- // - cite_tags enum: applied | dismissed | none (rc.37 NEW-1 2-state vocab).
22
- // v2.1.0-rc.1 (ADJ-P4-1, full remap): legacy rc≤36 tags (planned / recalled
23
- // / chained-from) are REMAPPED to `applied` here accepted as input but no
24
- // longer emitted verbatim, so the TS source and this twin stay in lockstep.
21
+ // - cite_tags enum: applied | dismissed | none (2-state vocab). Pre-user
22
+ // clean-slate: unrecognized tags degrade to `none` (no legacy remap), so
23
+ // the TS source and this twin stay in lockstep.
25
24
  // - operator kinds: edit | not_edit | require | forbid
26
25
  // (source token `!edit:` → schema kind `not_edit`)
27
26
  // - skip:<reason> captures everything after the first colon, so
@@ -52,24 +51,17 @@ function splitStorePrefix(token) {
52
51
  : { store: token.slice(0, colon), id: token.slice(colon + 1) };
53
52
  }
54
53
 
55
- // v2.1.0-rc.1 (ADJ-P4-1, full remap): legacy rc≤36 tags collapse to `applied`.
56
- // Mirrors LEGACY_CITE_TAG_REMAP / normalizeCiteTag in the TS source — accepted
57
- // as input but emitted as the 2-state vocab so cite-coverage never undercounts.
58
- const LEGACY_CITE_TAG_REMAP = {
59
- planned: "applied",
60
- recalled: "applied",
61
- "chained-from": "applied",
62
- };
63
-
54
+ // Mirrors normalizeCiteTag in the TS source: applied/dismissed/none pass
55
+ // through; anything else degrades to `none` (no legacy remap).
64
56
  function parseTag(rawTag) {
65
57
  if (!rawTag) return "none";
66
- // Tags may carry tails like `chained-from KT-DEC-0001` or
67
- // `dismissed:scope-mismatch`; head token (whitespace/colon-bounded) wins.
58
+ // Tags may carry tails like `dismissed:scope-mismatch`; the head token
59
+ // (whitespace/colon-bounded) wins.
68
60
  const head = rawTag.trim().split(/[\s:]+/)[0].toLowerCase();
69
61
  if (head === "applied" || head === "dismissed" || head === "none") {
70
62
  return head;
71
63
  }
72
- return LEGACY_CITE_TAG_REMAP[head] || "none";
64
+ return "none";
73
65
  }
74
66
 
75
67
  function parseContractTail(tail) {
@@ -166,9 +158,9 @@ function parseCiteLine(raw) {
166
158
  // v2.0.0-rc.27.1 (Codex review fix): cite_commitments MUST be index-
167
159
  // aligned with cite_ids per the schema doc on event-ledger.ts:428.
168
160
  // Multi-id citations share ONE parsed contract — propagate it across
169
- // every id slot so downstream consumers (`doctor.ts` per-cite walk +
170
- // `cite-contract-reminder.cjs`) can look up `commitments[i]` for any
171
- // valid `i < cite_ids.length` without falling into an undefined slot.
161
+ // every id slot so the downstream consumer (`doctor.ts` per-cite
162
+ // cite-coverage walk) can look up `commitments[i]` for any valid
163
+ // `i < cite_ids.length` without falling into an undefined slot.
172
164
  for (let i = 0; i < parsed.ids.length; i += 1) {
173
165
  result.cite_commitments.push(parsed.commitment);
174
166
  }