@fenglimg/fabric-cli 2.0.0 → 2.1.0-rc.2

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 (86) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +6 -5
  3. package/dist/chunk-BATF4PEJ.js +361 -0
  4. package/dist/{chunk-OBQU6NHO.js → chunk-COI5VDFU.js} +0 -18
  5. package/dist/chunk-F46ORPOA.js +903 -0
  6. package/dist/chunk-HFQVXY6P.js +86 -0
  7. package/dist/chunk-L4Q55UC4.js +52 -0
  8. package/dist/chunk-LFIKMVY7.js +27 -0
  9. package/dist/chunk-MF3OTILQ.js +544 -0
  10. package/dist/chunk-PWLW3B57.js +18 -0
  11. package/dist/chunk-RYAFBNES.js +33 -0
  12. package/dist/chunk-T5RPGCCM.js +40 -0
  13. package/dist/chunk-WU6GAPKH.js +36 -0
  14. package/dist/config-XJIPZNUP.js +13 -0
  15. package/dist/doctor-QVNPHLJK.js +920 -0
  16. package/dist/index.js +23 -8
  17. package/dist/{init-BIRSIOXO.js → install-2HDO5FTQ.js} +807 -705
  18. package/dist/metrics-ACEQFPDU.js +122 -0
  19. package/dist/onboard-coverage-MFCAEBDO.js +220 -0
  20. package/dist/{plan-context-hint-QMUPAXIB.js → plan-context-hint-FC6P3WFE.js} +34 -28
  21. package/dist/scope-explain-2F2R5URO.js +33 -0
  22. package/dist/status-GLQWLWH6.js +23 -0
  23. package/dist/store-XTSE5TY6.js +105 -0
  24. package/dist/sync-BJCWDPNC.js +245 -0
  25. package/dist/uninstall-TAXSUSKH.js +1073 -0
  26. package/dist/whoami-B6AEMSEV.js +31 -0
  27. package/package.json +30 -5
  28. package/templates/hooks/cite-policy-evict.cjs +231 -0
  29. package/templates/hooks/configs/README.md +29 -6
  30. package/templates/hooks/configs/claude-code.json +14 -3
  31. package/templates/hooks/configs/codex-hooks.json +6 -3
  32. package/templates/hooks/configs/cursor-hooks.json +8 -10
  33. package/templates/hooks/fabric-hint.cjs +873 -105
  34. package/templates/hooks/knowledge-hint-broad.cjs +549 -135
  35. package/templates/hooks/knowledge-hint-narrow.cjs +830 -26
  36. package/templates/hooks/lib/banner-i18n.cjs +309 -0
  37. package/templates/hooks/lib/bindings-snapshot-reader.cjs +81 -0
  38. package/templates/hooks/lib/cite-contract-reminder.cjs +179 -0
  39. package/templates/hooks/lib/cite-line-parser.cjs +180 -0
  40. package/templates/hooks/lib/client-adapter.cjs +106 -0
  41. package/templates/hooks/lib/config-cache.cjs +107 -0
  42. package/templates/hooks/lib/state-store.cjs +84 -0
  43. package/templates/hooks/lib/summary-fallback.cjs +210 -0
  44. package/templates/skills/fabric-archive/SKILL.md +97 -419
  45. package/templates/skills/fabric-archive/ref/dry-run-scope.md +16 -0
  46. package/templates/skills/fabric-archive/ref/e5-cron-recap.md +58 -0
  47. package/templates/skills/fabric-archive/ref/i18n-policy.md +86 -0
  48. package/templates/skills/fabric-archive/ref/phase-0-range-resolution.md +156 -0
  49. package/templates/skills/fabric-archive/ref/phase-1-5-onboard.md +218 -0
  50. package/templates/skills/fabric-archive/ref/phase-1-cross-session.md +62 -0
  51. package/templates/skills/fabric-archive/ref/phase-2-5-viability.md +68 -0
  52. package/templates/skills/fabric-archive/ref/phase-3-5-scope.md +108 -0
  53. package/templates/skills/fabric-archive/ref/phase-3-classify.md +63 -0
  54. package/templates/skills/fabric-archive/ref/phase-4-5-emit.md +78 -0
  55. package/templates/skills/fabric-archive/ref/phase-4-mcp-persist.md +89 -0
  56. package/templates/skills/fabric-archive/ref/rc-history.md +38 -0
  57. package/templates/skills/fabric-archive/ref/worked-examples.md +78 -0
  58. package/templates/skills/fabric-import/SKILL.md +77 -514
  59. package/templates/skills/fabric-import/ref/checkpoint-state.md +85 -0
  60. package/templates/skills/fabric-import/ref/i18n-policy.md +79 -0
  61. package/templates/skills/fabric-import/ref/output-contract.md +61 -0
  62. package/templates/skills/fabric-import/ref/phase-2-mining.md +213 -0
  63. package/templates/skills/fabric-import/ref/phase-3-dedup.md +75 -0
  64. package/templates/skills/fabric-import/ref/state-recovery.md +57 -0
  65. package/templates/skills/fabric-import/ref/worked-examples.md +127 -0
  66. package/templates/skills/fabric-review/SKILL.md +90 -284
  67. package/templates/skills/fabric-review/ref/askuserquestion-policy.md +66 -0
  68. package/templates/skills/fabric-review/ref/i18n-policy.md +111 -0
  69. package/templates/skills/fabric-review/ref/modify-flow.md +103 -0
  70. package/templates/skills/fabric-review/ref/output-contract.md +58 -0
  71. package/templates/skills/fabric-review/ref/per-mode-flows.md +155 -0
  72. package/templates/skills/fabric-review/ref/semantic-check.md +26 -0
  73. package/templates/skills/fabric-review/ref/worked-examples.md +95 -0
  74. package/templates/skills/fabric-sync/SKILL.md +46 -0
  75. package/templates/skills/lib/shared-policy.md +69 -0
  76. package/dist/chunk-6ICJICVU.js +0 -10
  77. package/dist/chunk-74SZWYPH.js +0 -658
  78. package/dist/chunk-EYIDD2YS.js +0 -1000
  79. package/dist/doctor-T7JWODKG.js +0 -282
  80. package/dist/hooks-Y74Y5LQS.js +0 -12
  81. package/dist/scan-LMK3UCWL.js +0 -22
  82. package/dist/serve-H554BHLG.js +0 -124
  83. package/templates/agents-md/AGENTS.md.template +0 -59
  84. package/templates/bootstrap/CLAUDE.md +0 -8
  85. package/templates/bootstrap/codex-AGENTS-header.md +0 -6
  86. package/templates/bootstrap/cursor-fabric-bootstrap.mdc +0 -10
@@ -0,0 +1,309 @@
1
+ /**
2
+ * v2.0.0-rc.16 TASK-001 (F2-prep): shared banner-i18n library for hook scripts.
3
+ *
4
+ * Provides:
5
+ * - readFabricLanguage(projectRoot) → 'zh-CN' | 'en' | 'zh-CN-hybrid' | 'match-existing'
6
+ * Synchronously reads `fabric_language` from `.fabric/fabric-config.json`.
7
+ * Mirrors the never-throw contract of the existing config readers in
8
+ * fabric-hint.cjs (readReviewHintPendingCount, readMaintenanceHintDays, etc.):
9
+ * missing file / parse error / missing field → returns 'zh-CN' (the
10
+ * documented BACKWARD-COMPAT default — preserves rc.15 hard-coded zh-CN
11
+ * hook output when fabric_language was never a configurable key).
12
+ *
13
+ * 'match-existing' is ONLY returned when explicitly set in config; per UX
14
+ * i18n Policy class 1, renderBanner then folds 'match-existing' (and any
15
+ * unknown variant) down to 'en'.
16
+ *
17
+ * RC.16 TASK-002 NOTE: this default was originally 'match-existing' in
18
+ * TASK-001 but was tightened to 'zh-CN' here so that the existing rc.7+
19
+ * fabric-hint test fixtures (which never set fabric_language and expect
20
+ * zh-CN substrings byte-identically) continue passing without modification.
21
+ * Pre-user clean-slate policy: no shim, but back-compat for in-tree tests
22
+ * is the right line — they encode the rc.15 user-visible contract.
23
+ *
24
+ * - renderBanner(key, variant, params) → string
25
+ * Renders one of the 11 banner fragments for the requested variant.
26
+ * Variant fallback: STRINGS[key][variant] ?? STRINGS[key]['en'].
27
+ * Unknown / 'match-existing' / missing → 'en' table.
28
+ *
29
+ * - STRINGS — exported for test introspection only (read-only by convention).
30
+ *
31
+ * Banner keys (11 total):
32
+ * Signal A (archive): archiveLine1, archiveActivity, archiveCta
33
+ * Signal B (review): reviewLine1, reviewCta
34
+ * Signal C (import): importLine1, importCta
35
+ * Signal D (maintenance): maintenanceLine1Never, maintenanceLine1Aged, maintenanceLine2
36
+ * Broad hook: broadImportBanner
37
+ *
38
+ * Protected tokens — NEVER translated, kept verbatim across all 4 variants:
39
+ * - Slash commands: /fabric-archive, /fabric-review, /fabric-import
40
+ * - CLI commands: `fabric doctor --lint`
41
+ * - Numeric / template substrings the existing tests assert on:
42
+ * "${hoursElapsed.toFixed(1)}h" (e.g. "25.0h"), "阈值 ${N}h",
43
+ * "${count} 条", "${nodeCount}/${threshold}", "${days} 天"
44
+ * - 📋 Fabric: emoji prefix
45
+ *
46
+ * zh-CN-hybrid policy: Chinese narrative prose with English protected tokens
47
+ * preserved verbatim. In practice this matches zh-CN exactly because the
48
+ * banners already inline slash commands + CLI commands without translation;
49
+ * we keep the variant entries explicit anyway for forward-compat (future copy
50
+ * may diverge, e.g. mixing English connector words).
51
+ *
52
+ * match-existing policy: per UX i18n Policy class 1, falls back to 'en' at
53
+ * render time. The fallback decision is centralized in renderBanner; only an
54
+ * EXPLICIT `fabric_language: "match-existing"` in config triggers the en
55
+ * fallback. Unset / missing config defaults to 'zh-CN' (rc.15 back-compat).
56
+ *
57
+ * Pattern reference:
58
+ * - Never-throw fs read: fabric-hint.cjs `_readConfigNumber`,
59
+ * `readReviewHintPendingCount` (lines 720-743)
60
+ * - hooks/lib/*.cjs precedent: session-digest-writer.cjs
61
+ */
62
+ "use strict";
63
+
64
+ const { existsSync, readFileSync } = require("node:fs");
65
+ const { join } = require("node:path");
66
+
67
+ const FABRIC_DIR = ".fabric";
68
+ const CONFIG_FILE = "fabric-config.json";
69
+
70
+ const VALID_LANGUAGES = ["zh-CN", "en", "zh-CN-hybrid", "match-existing"];
71
+ // rc.16 TASK-002: backward-compat default. rc.15 and earlier hardcoded
72
+ // zh-CN in the hook scripts; preserving zh-CN as the unset-default keeps
73
+ // the rc.7+ fabric-hint test fixtures (which assert Chinese substrings
74
+ // without ever setting fabric_language) green and matches the user-visible
75
+ // contract real workspaces have observed since rc.7.
76
+ const DEFAULT_LANGUAGE = "zh-CN";
77
+ const RENDER_FALLBACK_VARIANT = "en";
78
+
79
+ /**
80
+ * Read `fabric_language` from <projectRoot>/.fabric/fabric-config.json.
81
+ *
82
+ * Returns one of the four valid language codes. Missing file, malformed JSON,
83
+ * missing/unknown field value → DEFAULT_LANGUAGE ('zh-CN' — see comment on
84
+ * the constant for the back-compat rationale). NEVER throws — config-read
85
+ * failure must not block any hook.
86
+ */
87
+ function readFabricLanguage(projectRoot) {
88
+ if (typeof projectRoot !== "string" || projectRoot.length === 0) {
89
+ return DEFAULT_LANGUAGE;
90
+ }
91
+ const configPath = join(projectRoot, FABRIC_DIR, CONFIG_FILE);
92
+ if (!existsSync(configPath)) return DEFAULT_LANGUAGE;
93
+ try {
94
+ const parsed = JSON.parse(readFileSync(configPath, "utf8"));
95
+ const v = parsed && parsed.fabric_language;
96
+ if (typeof v === "string" && VALID_LANGUAGES.indexOf(v) !== -1) {
97
+ return v;
98
+ }
99
+ } catch {
100
+ // fall through to default
101
+ }
102
+ return DEFAULT_LANGUAGE;
103
+ }
104
+
105
+ // ---------------------------------------------------------------------------
106
+ // String table
107
+ // ---------------------------------------------------------------------------
108
+ //
109
+ // Each key maps variant -> (params) => string. Templates intentionally use
110
+ // the same parameter names across all four variants so call sites pass one
111
+ // shape. Substring contracts (see file header) are preserved verbatim across
112
+ // translations; only narrative connector words shift.
113
+ // ---------------------------------------------------------------------------
114
+
115
+ const STRINGS = {
116
+ // ---- Signal A: archive ----------------------------------------------------
117
+ // Source (zh-CN): fabric-hint.cjs:614 `📋 Fabric: 距上次归档 ${parts}。`
118
+ // params: { parts } where parts is pre-joined `已过 25.0h(阈值 24h)` etc.
119
+ //
120
+ // v2.0.0-rc.27 TASK-005 (audit §2.17): `parts` is now constructed by the
121
+ // sibling archivePartsHours / archivePartsEdits keys (also per-variant) so
122
+ // the caller never hardcodes Chinese into the en banner. The substring
123
+ // contract on "25.0h" / "阈值 N" / "次编辑" is preserved per-variant but
124
+ // each variant gets a coherent monolingual rendering — pre-rc.27 produced
125
+ // mixed-language output like `📋 Fabric: 已过 25.0h since last archive.`
126
+ // (audit §2.17 reproduction).
127
+ archiveLine1: {
128
+ "zh-CN": (p) => `📋 Fabric: 距上次归档 ${p.parts}。`,
129
+ en: (p) => `📋 Fabric: ${p.parts} since last archive.`,
130
+ "zh-CN-hybrid": (p) => `📋 Fabric: 距上次归档 ${p.parts}。`,
131
+ },
132
+
133
+ // v2.0.0-rc.27 TASK-005 (audit §2.17): per-variant assembly of the
134
+ // hours-trigger fragment. zh-CN tightens to the original substring
135
+ // contract (`已过 25.0h(阈值 24h)`); en variant translates the prose
136
+ // while preserving the numeric tokens; hybrid mirrors zh-CN.
137
+ // params: { hoursFixed: string (already toFixed(1)), threshold: number }
138
+ archivePartsHours: {
139
+ "zh-CN": (p) => `已过 ${p.hoursFixed}h(阈值 ${p.threshold}h)`,
140
+ en: (p) => `${p.hoursFixed}h elapsed (threshold ${p.threshold}h)`,
141
+ "zh-CN-hybrid": (p) => `已过 ${p.hoursFixed}h(阈值 ${p.threshold}h)`,
142
+ },
143
+
144
+ // v2.0.0-rc.27 TASK-005 (audit §2.17): edits-trigger fragment.
145
+ // params: { count: number, threshold: number }
146
+ archivePartsEdits: {
147
+ "zh-CN": (p) => `累计 ${p.count} 次编辑(阈值 ${p.threshold})`,
148
+ en: (p) => `${p.count} edits since last archive (threshold ${p.threshold})`,
149
+ "zh-CN-hybrid": (p) => `累计 ${p.count} 次编辑(阈值 ${p.threshold})`,
150
+ },
151
+
152
+ // Source (zh-CN): fabric-hint.cjs:619 ` 最近活动集中在: ${activity}。`
153
+ // params: { activity }
154
+ archiveActivity: {
155
+ "zh-CN": (p) => ` 最近活动集中在: ${p.activity}。`,
156
+ en: (p) => ` Recent activity centered on: ${p.activity}.`,
157
+ "zh-CN-hybrid": (p) => ` 最近活动集中在: ${p.activity}。`,
158
+ },
159
+
160
+ // Source (zh-CN): fabric-hint.cjs:621 ` 是否调 /fabric-archive 检查值得归档的决策/踩坑/复用?`
161
+ // params: {} — protected token /fabric-archive verbatim across all variants.
162
+ archiveCta: {
163
+ "zh-CN": () => " 是否调 /fabric-archive 检查值得归档的决策/踩坑/复用?",
164
+ en: () => " Run /fabric-archive to review decisions/pitfalls/reusables worth archiving?",
165
+ "zh-CN-hybrid": () => " 是否调 /fabric-archive 检查值得归档的决策/踩坑/复用?",
166
+ },
167
+
168
+ // ---- Signal B: review -----------------------------------------------------
169
+ // Source (zh-CN): fabric-hint.cjs:651 `📋 Fabric: 已积累 ${stats.count} 条待审核知识${ageSuffix}。`
170
+ // params: { count, ageSuffix } — ageSuffix is " / 最早一条 N.N 天前" or "" (zh-CN only)
171
+ // For en variant we shape the suffix inline to keep substring "${count}" addressable.
172
+ reviewLine1: {
173
+ "zh-CN": (p) => `📋 Fabric: 已积累 ${p.count} 条待审核知识${p.ageSuffix || ""}。`,
174
+ en: (p) => {
175
+ const suffix =
176
+ p.ageSuffix && p.ageSuffix.length > 0
177
+ ? p.ageSuffix
178
+ .replace(" / 最早一条 ", " / oldest is ")
179
+ .replace(" 天前", "d old")
180
+ : "";
181
+ return `📋 Fabric: ${p.count} pending knowledge entries accumulated${suffix}.`;
182
+ },
183
+ "zh-CN-hybrid": (p) => `📋 Fabric: 已积累 ${p.count} 条待审核知识${p.ageSuffix || ""}。`,
184
+ },
185
+
186
+ // Source (zh-CN): fabric-hint.cjs:652 ` 是否调 /fabric-review 审核 pending/ 条目?`
187
+ // params: {} — protected token /fabric-review verbatim across all variants.
188
+ reviewCta: {
189
+ "zh-CN": () => " 是否调 /fabric-review 审核 pending/ 条目?",
190
+ en: () => " Run /fabric-review to triage pending/ entries?",
191
+ "zh-CN-hybrid": () => " 是否调 /fabric-review 审核 pending/ 条目?",
192
+ },
193
+
194
+ // ---- Signal C: import (underseed) ----------------------------------------
195
+ // Source (zh-CN): fabric-hint.cjs:697 `📋 Fabric: 知识库节点数 ${nodeCount}/${threshold},距 init_scan_completed ${hoursSinceInit.toFixed(1)}h。`
196
+ // params: { nodeCount, threshold, hoursSinceInit } — caller supplies hoursSinceInit
197
+ // already toFixed(1)'d (i.e. as string "24.5") to keep all rendering pure.
198
+ importLine1: {
199
+ "zh-CN": (p) =>
200
+ `📋 Fabric: 知识库节点数 ${p.nodeCount}/${p.threshold},距 init_scan_completed ${p.hoursSinceInit}h。`,
201
+ en: (p) =>
202
+ `📋 Fabric: knowledge node count ${p.nodeCount}/${p.threshold}, ${p.hoursSinceInit}h since init_scan_completed.`,
203
+ "zh-CN-hybrid": (p) =>
204
+ `📋 Fabric: 知识库节点数 ${p.nodeCount}/${p.threshold},距 init_scan_completed ${p.hoursSinceInit}h。`,
205
+ },
206
+
207
+ // Source (zh-CN): fabric-hint.cjs:698 ` 是否调 /fabric-import 从 git 历史与现有文档回灌知识?`
208
+ // params: {} — protected token /fabric-import verbatim across all variants.
209
+ importCta: {
210
+ "zh-CN": () => " 是否调 /fabric-import 从 git 历史与现有文档回灌知识?",
211
+ en: () => " Run /fabric-import to backfill knowledge from git history and existing docs?",
212
+ "zh-CN-hybrid": () => " 是否调 /fabric-import 从 git 历史与现有文档回灌知识?",
213
+ },
214
+
215
+ // ---- Signal D: maintenance -----------------------------------------------
216
+ // Source (zh-CN): fabric-hint.cjs:931 `📋 Fabric: 从未运行 lint 检查。`
217
+ // params: {} — substring "从未运行 lint 检查" is test-asserted (zh-CN test).
218
+ maintenanceLine1Never: {
219
+ "zh-CN": () => "📋 Fabric: 从未运行 lint 检查。",
220
+ en: () => "📋 Fabric: lint check has never been run.",
221
+ "zh-CN-hybrid": () => "📋 Fabric: 从未运行 lint 检查。",
222
+ },
223
+
224
+ // Source (zh-CN): fabric-hint.cjs:932 `📋 Fabric: 已 ${days} 天未跑 lint 检查(实际 ${ageDays.toFixed(1)}d)。`
225
+ // params: { days, ageDays } — ageDays caller-supplied as already-toFixed(1) string.
226
+ // Substring "已 N 天未跑 lint" is test-asserted (zh-CN test).
227
+ maintenanceLine1Aged: {
228
+ "zh-CN": (p) => `📋 Fabric: 已 ${p.days} 天未跑 lint 检查(实际 ${p.ageDays}d)。`,
229
+ en: (p) => `📋 Fabric: ${p.days} days since the last lint check (actual ${p.ageDays}d).`,
230
+ "zh-CN-hybrid": (p) => `📋 Fabric: 已 ${p.days} 天未跑 lint 检查(实际 ${p.ageDays}d)。`,
231
+ },
232
+
233
+ // Source (zh-CN): fabric-hint.cjs:929 ` 是否调 \`fabric doctor --lint\` 看看知识库健康度?`
234
+ // params: {} — protected token `fabric doctor --lint` (with backticks) verbatim.
235
+ maintenanceLine2: {
236
+ "zh-CN": () => " 是否调 `fabric doctor --lint` 看看知识库健康度?",
237
+ en: () => " Run `fabric doctor --lint` to check knowledge-base health?",
238
+ "zh-CN-hybrid": () => " 是否调 `fabric doctor --lint` 看看知识库健康度?",
239
+ },
240
+
241
+ // ---- Broad hook: import recommendation ------------------------------------
242
+ // Source (zh-CN): knowledge-hint-broad.cjs:262
243
+ // " 📋 Fabric: 知识库稀疏,是否调 /fabric-import 从 git 历史与现有文档回灌知识?"
244
+ // Note: leading two spaces are intentional (existing banner indent).
245
+ // params: {} — protected token /fabric-import verbatim.
246
+ broadImportBanner: {
247
+ "zh-CN": () => " 📋 Fabric: 知识库稀疏,是否调 /fabric-import 从 git 历史与现有文档回灌知识?",
248
+ en: () =>
249
+ " 📋 Fabric: knowledge base is sparse — run /fabric-import to backfill from git history and existing docs?",
250
+ "zh-CN-hybrid": () =>
251
+ " 📋 Fabric: 知识库稀疏,是否调 /fabric-import 从 git 历史与现有文档回灌知识?",
252
+ },
253
+
254
+ // ---- Broad hook: meta auto-refresh breadcrumb (rc.22 Scope D T-D4) -------
255
+ // Surfaced ONLY when planContext() detected meta drift and rebuilt the meta
256
+ // in-place (server emits `auto_healed: true` in plan-context-hint payload).
257
+ // Single informational line — operators need a breadcrumb when meta auto-
258
+ // heals so a "why did revision change?" question has a paper trail.
259
+ //
260
+ // Two render shapes:
261
+ // - metaAutoRefreshedBanner: full transition with prev → cur 8-char hash
262
+ // prefixes. Used when both previous_revision_hash + revision_hash present.
263
+ // - metaAutoRefreshedBannerGeneric: defensive fallback when the server
264
+ // emitted `auto_healed: true` but did not include previous_revision_hash
265
+ // (T10 noted this edge case). No hash transition shown.
266
+ //
267
+ // Note: 🔄 emoji prefix is intentional (matches the project's general "no
268
+ // emoji" rule's exception for explicit user request — see TASK-011 description).
269
+ // params: { prev, cur } — both already 8-char hex strings, caller-supplied.
270
+ metaAutoRefreshedBanner: {
271
+ "zh-CN": (p) => ` 🔄 Fabric: 元数据已自动刷新(sha ${p.prev} → ${p.cur})`,
272
+ en: (p) => ` 🔄 Fabric: meta auto-refreshed (sha ${p.prev} → ${p.cur})`,
273
+ "zh-CN-hybrid": (p) => ` 🔄 Fabric: 元数据已自动刷新(sha ${p.prev} → ${p.cur})`,
274
+ },
275
+
276
+ // Generic variant — no hash transition. Used when auto_healed:true but
277
+ // previous_revision_hash is missing from the payload.
278
+ metaAutoRefreshedBannerGeneric: {
279
+ "zh-CN": () => " 🔄 Fabric: 元数据已自动刷新",
280
+ en: () => " 🔄 Fabric: meta auto-refreshed",
281
+ "zh-CN-hybrid": () => " 🔄 Fabric: 元数据已自动刷新",
282
+ },
283
+ };
284
+
285
+ /**
286
+ * Render a banner fragment for the requested variant.
287
+ *
288
+ * Variant resolution:
289
+ * 1. If STRINGS[key][variant] exists → use it.
290
+ * 2. Else fall back to STRINGS[key][RENDER_FALLBACK_VARIANT] ('en').
291
+ * 3. If key itself is unknown → returns "" (defensive; never throws).
292
+ *
293
+ * 'match-existing' is intentionally NOT in the STRINGS table so it folds
294
+ * down to the 'en' fallback per UX i18n Policy class 1.
295
+ */
296
+ function renderBanner(key, variant, params) {
297
+ const entry = STRINGS[key];
298
+ if (!entry) return "";
299
+ const tmpl = entry[variant] || entry[RENDER_FALLBACK_VARIANT];
300
+ if (typeof tmpl !== "function") return "";
301
+ try {
302
+ return tmpl(params || {});
303
+ } catch {
304
+ // Defensive: a missing param shouldn't crash the hook.
305
+ return "";
306
+ }
307
+ }
308
+
309
+ module.exports = { readFabricLanguage, renderBanner, STRINGS };
@@ -0,0 +1,81 @@
1
+ #!/usr/bin/env node
2
+ // v2.1.0-rc.1 P4 — hook-side resolved-bindings snapshot reader (F4/S63/S65).
3
+ //
4
+ // Hooks are a REMINDER layer (KT-DEC-0007) and must never block. They are also
5
+ // FORBIDDEN from re-resolving stores or walking `.fabric` store trees directly
6
+ // — a hook reads ONLY the CLI-pre-generated snapshot at
7
+ // `~/.fabric/state/bindings/<project_id>_resolved.json` (written by P3
8
+ // install/sync/bind). This keeps the resolver logic in one place (the CLI) and
9
+ // keeps hooks a thin, store-unaware-by-construction projection. Missing /
10
+ // unreadable / malformed snapshot → null (harmless degrade; the hook proceeds
11
+ // without store labels). Zero-dep CJS so it inline-loads at hook runtime.
12
+
13
+ const { existsSync, readFileSync } = require("node:fs");
14
+ const { join } = require("node:path");
15
+ const { homedir } = require("node:os");
16
+
17
+ // `~/.fabric` (FABRIC_HOME override mirrors the CLI's resolveGlobalRoot).
18
+ function resolveGlobalRoot() {
19
+ return join(process.env.FABRIC_HOME || homedir(), ".fabric");
20
+ }
21
+
22
+ function bindingsSnapshotPath(projectId, globalRoot) {
23
+ return join(
24
+ globalRoot || resolveGlobalRoot(),
25
+ "state",
26
+ "bindings",
27
+ projectId + "_resolved.json",
28
+ );
29
+ }
30
+
31
+ // Read + shallow-validate the snapshot. Returns the parsed object, or null when
32
+ // absent / unreadable / not the expected shape. NEVER throws.
33
+ function readBindingsSnapshot(projectId, globalRoot) {
34
+ if (typeof projectId !== "string" || projectId.length === 0) {
35
+ return null;
36
+ }
37
+ const path = bindingsSnapshotPath(projectId, globalRoot);
38
+ if (!existsSync(path)) {
39
+ return null;
40
+ }
41
+ try {
42
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
43
+ if (
44
+ parsed &&
45
+ typeof parsed === "object" &&
46
+ parsed.read_set &&
47
+ Array.isArray(parsed.read_set.stores)
48
+ ) {
49
+ return parsed;
50
+ }
51
+ return null;
52
+ } catch {
53
+ return null;
54
+ }
55
+ }
56
+
57
+ // Render a compact, per-store label line for a SessionStart / Stop hook from a
58
+ // snapshot. Empty string when there is nothing to show (degrade silently). The
59
+ // label is provenance only — it never re-resolves; it just echoes the read-set
60
+ // the CLI already computed, with the write-target flagged (F4 store labels).
61
+ function formatStoreLabels(snapshot) {
62
+ if (!snapshot || !snapshot.read_set || !Array.isArray(snapshot.read_set.stores)) {
63
+ return "";
64
+ }
65
+ const writeAlias = snapshot.write_target && snapshot.write_target.alias;
66
+ const parts = snapshot.read_set.stores.map((store) => {
67
+ const tag = store.alias === writeAlias ? " (write)" : store.writable ? "" : " (ro)";
68
+ return store.alias + tag;
69
+ });
70
+ if (parts.length === 0) {
71
+ return "";
72
+ }
73
+ return "[fabric] read-set stores: " + parts.join(", ");
74
+ }
75
+
76
+ module.exports = {
77
+ resolveGlobalRoot,
78
+ bindingsSnapshotPath,
79
+ readBindingsSnapshot,
80
+ formatStoreLabels,
81
+ };
@@ -0,0 +1,179 @@
1
+ // v2.0.0-rc.24 TASK-05: L1 Stop hook soft reminder for missing cite contract.
2
+ //
3
+ // Reads `.fabric/agents.meta.json` to build a stable_id → knowledge_type lookup
4
+ // map, then scans summarised assistant turns (cite_ids + cite_tags +
5
+ // cite_commitments parallel arrays produced by lib/cite-line-parser.cjs) for
6
+ // turns that cited a decision-class or pitfall-class id with [applied] tag
7
+ // but no operator commitment and no skip:<reason>. (v2.1.0-rc.1 ADJ-P4-1:
8
+ // legacy [recalled] is remapped to [applied] by the parser upstream.)
9
+ //
10
+ // Emits one reminder line per offending id (deduplicated across the turn
11
+ // summary). Non-blocking — caller writes the lines to stderr; failure to
12
+ // load the meta file or absence of offenders means zero output.
13
+ //
14
+ // Reminder template (rc.24 lock B2 / L1 enforcement layer):
15
+ // ⚠ KB: <id> cited as [applied] but missing contract; add → edit:<glob>
16
+ // or → skip:<reason> next turn
17
+ //
18
+ // Type filter rationale: only `decision` and `pitfall` types are contract-
19
+ // required per rc.24 design lock B6 (idTypeMap routing). `model`,
20
+ // `guideline`, `process` use reference-cite or LLM-judge (deferred to rc.25+)
21
+ // and are intentionally skipped here to avoid false-positive nudges.
22
+ //
23
+ // agents.meta.json schema note: `description.knowledge_type` values are
24
+ // SINGULAR (`decision`, `pitfall`, `model`, `guideline`, `process`) per
25
+ // packages/shared/src/schemas/agents-meta.ts. The reminder filter normalises
26
+ // any plural input defensively but the canonical contract is singular.
27
+ //
28
+ // Reading happens once per hook invocation (caller passes the projectRoot;
29
+ // the lib does the fs read internally). The map is small (<200 entries in
30
+ // typical corpora) so caching beyond the per-invocation scope is unnecessary.
31
+
32
+ const { existsSync, readFileSync } = require("node:fs");
33
+ const { join } = require("node:path");
34
+
35
+ const FABRIC_DIR = ".fabric";
36
+ const AGENTS_META_FILE = "agents.meta.json";
37
+
38
+ // Knowledge types that require contract commitments on [applied] cites.
39
+ // Matches the singular form persisted by `withDerivedAgentsMetaNodeDefaults`
40
+ // in packages/shared/src/schemas/agents-meta.ts. We accept both singular
41
+ // and plural defensively so a future schema change to plurals doesn't
42
+ // silently break the filter.
43
+ const CONTRACT_REQUIRED_TYPES = new Set([
44
+ "decision",
45
+ "decisions",
46
+ "pitfall",
47
+ "pitfalls",
48
+ ]);
49
+
50
+ /**
51
+ * Build a Map<stable_id, knowledge_type> from <projectRoot>/.fabric/agents.meta.json.
52
+ *
53
+ * Never throws — missing file, malformed JSON, missing nodes key, etc. all
54
+ * yield an empty Map. The caller's downstream filter then becomes a no-op
55
+ * (no id resolves → no reminders).
56
+ *
57
+ * @param {string} projectRoot - workspace root
58
+ * @returns {Map<string, string>} stable_id → knowledge_type (singular)
59
+ */
60
+ function readKnowledgeTypeMap(projectRoot) {
61
+ const out = new Map();
62
+ if (typeof projectRoot !== "string" || projectRoot.length === 0) return out;
63
+
64
+ const metaPath = join(projectRoot, FABRIC_DIR, AGENTS_META_FILE);
65
+ if (!existsSync(metaPath)) return out;
66
+
67
+ let raw;
68
+ try {
69
+ raw = readFileSync(metaPath, "utf8");
70
+ } catch {
71
+ return out;
72
+ }
73
+
74
+ let parsed;
75
+ try {
76
+ parsed = JSON.parse(raw);
77
+ } catch {
78
+ return out;
79
+ }
80
+
81
+ if (parsed === null || typeof parsed !== "object") return out;
82
+ const nodes = parsed.nodes;
83
+ if (nodes === null || typeof nodes !== "object") return out;
84
+
85
+ for (const [id, node] of Object.entries(nodes)) {
86
+ if (node === null || typeof node !== "object") continue;
87
+ const description = node.description;
88
+ if (description === null || typeof description !== "object") continue;
89
+ const kt = description.knowledge_type;
90
+ if (typeof kt !== "string" || kt.length === 0) continue;
91
+ out.set(id, kt);
92
+ }
93
+
94
+ return out;
95
+ }
96
+
97
+ /**
98
+ * Scan parsed assistant turns for cites that should have a contract but
99
+ * don't, returning the reminder lines to emit.
100
+ *
101
+ * Filter (all must hold for a given index i within a turn):
102
+ * 1. cite_tags includes "applied" (turn-level — applies to the cited id)
103
+ * 2. cite_commitments[i].operators is empty AND cite_commitments[i].skip_reason is null
104
+ * 3. idTypeMap.get(cite_ids[i]) is in {decision, pitfall}
105
+ *
106
+ * v2.1.0-rc.1 (ADJ-P4-1, full remap): the gate is the rc.37 NEW-1 `applied`
107
+ * tag. Legacy [recalled] cites are remapped to [applied] by the parser before
108
+ * they reach here, so gating on "applied" covers both old and new authoring.
109
+ *
110
+ * Tag-level filter clarification: rc.20 cite_tags is parallel to ALL parsed
111
+ * lines (including sentinels), but for the contract-missing reminder we use
112
+ * the turn-level semantic — if the assistant tagged the cite as [applied],
113
+ * the operator-or-skip contract applies. Per TASK-04 invariant, cite_ids and
114
+ * cite_commitments are parallel index-aligned arrays (length-N each).
115
+ *
116
+ * Sentinel turns (cite_ids=[], cite_tags=["none"]) contribute no offenders
117
+ * because the cite_ids loop has zero iterations.
118
+ *
119
+ * Offenders are deduplicated by id across the entire turn array; multiple
120
+ * turns citing the same id yield ONE reminder line.
121
+ *
122
+ * @param {Object} args
123
+ * @param {Array<{cite_ids: string[], cite_tags: string[], cite_commitments: Array<{operators: Array<unknown>, skip_reason: string|null}>}>} args.assistant_turns
124
+ * @param {Map<string, string>} args.idTypeMap
125
+ * @returns {string[]} reminder lines (empty when no offenders)
126
+ */
127
+ function formatContractMissingReminders({ assistant_turns, idTypeMap }) {
128
+ if (!Array.isArray(assistant_turns) || assistant_turns.length === 0) return [];
129
+ if (!(idTypeMap instanceof Map) || idTypeMap.size === 0) return [];
130
+
131
+ const offenders = new Set();
132
+
133
+ for (const turn of assistant_turns) {
134
+ if (turn === null || typeof turn !== "object") continue;
135
+ const citeIds = Array.isArray(turn.cite_ids) ? turn.cite_ids : [];
136
+ const citeTags = Array.isArray(turn.cite_tags) ? turn.cite_tags : [];
137
+ const commitments = Array.isArray(turn.cite_commitments) ? turn.cite_commitments : [];
138
+
139
+ // Turn-level: the [applied] tag must appear in the turn's tag set
140
+ // (v2.1.0-rc.1 ADJ-P4-1: legacy [recalled] is remapped to [applied]).
141
+ if (!citeTags.includes("applied")) continue;
142
+
143
+ // Iterate by cite_ids.length — sentinel entries don't have ids so they
144
+ // contribute zero iterations even if cite_tags carries "none".
145
+ for (let i = 0; i < citeIds.length; i += 1) {
146
+ const id = citeIds[i];
147
+ if (typeof id !== "string" || id.length === 0) continue;
148
+
149
+ const type = idTypeMap.get(id);
150
+ if (!CONTRACT_REQUIRED_TYPES.has(type)) continue;
151
+
152
+ const commitment = commitments[i];
153
+ if (commitment === null || typeof commitment !== "object") continue;
154
+ const operators = Array.isArray(commitment.operators) ? commitment.operators : [];
155
+ const skipReason = commitment.skip_reason;
156
+ const hasContract = operators.length > 0 || (typeof skipReason === "string" && skipReason.length > 0);
157
+ if (hasContract) continue;
158
+
159
+ offenders.add(id);
160
+ }
161
+ }
162
+
163
+ if (offenders.size === 0) return [];
164
+
165
+ // Stable order: insertion order is the order ids first appeared across turns.
166
+ const reminders = [];
167
+ for (const id of offenders) {
168
+ reminders.push(
169
+ `⚠ KB: ${id} cited as [applied] but missing contract; add \`→ edit:<glob>\` or \`→ skip:<reason>\` next turn`,
170
+ );
171
+ }
172
+ return reminders;
173
+ }
174
+
175
+ module.exports = {
176
+ readKnowledgeTypeMap,
177
+ formatContractMissingReminders,
178
+ CONTRACT_REQUIRED_TYPES,
179
+ };