@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
@@ -12,28 +12,20 @@
12
12
  * narrow-injection sibling (E2, knowledge-hint-narrow.cjs) handles
13
13
  * per-Edit/Write hints with a session-hints cache.
14
14
  *
15
- * Output contract (stderr only):
15
+ * Output contract (W2 / KT-DEC-0027/0028/0029 — the SessionStart spine):
16
16
  *
17
- * When narrow count <= 30 (full per-type listing mode):
18
- * [fabric] Session start — N broad-scoped knowledge entries available:
19
- * [decision] (proven)
20
- * - <id> · <summary>
21
- * [pitfall] (verified)
22
- * - <id> · <summary>
23
- * ...
24
- * revision_hash: <hash>
25
- * Load full content: `fab_recall(paths)`, or `fab_plan_context` -> `fab_get_knowledge_sections` to trim first.
17
+ * AI sink (additionalContext) the dynamically generated "MEMORY.md":
18
+ * [fabric:SessionStart] <store>
19
+ * ALWAYS-ACTIVE RULES (no recall needed): # guideline/model — INDEX line only
20
+ * [guideline] team:KT-GLD-0001 · <summary> # KT-DEC-0036: no eager body
21
+ * REFERENCE (read on demand / fab_recall): # decision/pitfall/process — title + hook
22
+ * [decision] team:KT-DEC-0001 <must_read_if>
23
+ * … N more folded (broad index > backstop 50; run fabric-audit)
24
+ * Load full content: fab_recall(paths), or Read <store>/knowledge/<type>/<id>--*.md
26
25
  *
27
- * When narrow count > 30 (grouped-truncation mode, per type):
28
- * [fabric] Session start — N broad-scoped knowledge entries available (truncated):
29
- * [decision] proven (3):
30
- * - <id> · <summary>
31
- * - ...
32
- * [decision] verified (12): <id1>, <id2>, ...
33
- * [decision] draft: 7 entries
34
- * ...
35
- * revision_hash: <hash>
36
- * Load full content: `fab_recall(paths)`, or `fab_plan_context` -> `fab_get_knowledge_sections` to trim first.
26
+ * Human sink (systemMessage) broad-only census breadcrumb; SessionStart is
27
+ * SILENT about narrow-scoped knowledge (no on-demand counts, no
28
+ * dropped-other-project line).
37
29
  *
38
30
  * When 0 entries / CLI unavailable / CLI error / parse failure:
39
31
  * (no output — silent exit 0)
@@ -61,7 +53,6 @@ const { appendLockedLine } = require("./lib/injection-log.cjs");
61
53
  // (TASK-002). Variant is resolved ONCE per main() invocation via
62
54
  // readFabricLanguage(cwd) and threaded into renderBanner — no fs in render path.
63
55
  const { renderBanner, readFabricLanguage } = require("./lib/banner-i18n.cjs");
64
- const { resolveOpaqueSummaries } = require("./lib/summary-fallback.cjs");
65
56
  // v2.0.0-rc.37 NEW-19: shared fabric-config reader + sidecar I/O. Replaces the
66
57
  // five per-key readFileSync+parse config readers (one parse per fire now) and
67
58
  // the bespoke last-emit sidecar helpers. The L78 "refactor into lib/ if a
@@ -74,7 +65,18 @@ const {
74
65
  const { readTextState, writeTextState } = require("./lib/state-store.cjs");
75
66
  // v2.0.0-rc.37 NEW-30: shared client detection (replaces the inline
76
67
  // CLAUDE_PROJECT_DIR single-bit check below).
77
- const { isClaudeCode, detectClient } = require("./lib/client-adapter.cjs");
68
+ // v2.2 dual-sink (Goal A): + emitDualSink (two-channel SessionStart emit).
69
+ const { isClaudeCode, detectClient, emitDualSink } = require("./lib/client-adapter.cjs");
70
+ // v2.2 dual-sink (Goal A / D4): human-output gate (nudge_mode + observe.*). Only
71
+ // governs the human systemMessage — the AI additionalContext is emitted
72
+ // regardless (flow ⊥ observation). Optional require so an old install lacking the
73
+ // lib degrades to "always emit human" (the pre-dual-sink default).
74
+ let nudgePolicy = null;
75
+ try {
76
+ nudgePolicy = require("./lib/nudge-policy.cjs");
77
+ } catch {
78
+ // Lib missing (old install) — human sink always emits (legacy behavior).
79
+ }
78
80
  // v2.1.0-rc.1 P4 (F4/S63): hook-side reader for the CLI pre-generated
79
81
  // resolved-bindings snapshot. The hook NEVER re-resolves stores or walks store
80
82
  // trees — it only echoes the read-set the CLI already computed. Best-effort.
@@ -94,19 +96,62 @@ try {
94
96
  // Lib missing (old install) — injection telemetry degrades to silent absence.
95
97
  }
96
98
 
97
- // Read the project's own `project_id` from `.fabric/fabric-config.json` (the
98
- // snapshot key). Reading the PROJECT config is not a store-tree read — it is how
99
- // the hook learns which snapshot to fetch. Returns null on any failure.
100
- function readProjectId(cwd) {
99
+ // Read the workspace binding id from `.fabric/fabric-config.json` (the snapshot
100
+ // key). Defaults to project_id when workspace_binding_id is absent.
101
+ function readWorkspaceBindingId(cwd) {
101
102
  try {
102
103
  const raw = readFileSync(join(cwd, ".fabric", "fabric-config.json"), "utf8");
103
104
  const parsed = JSON.parse(raw);
105
+ if (typeof parsed.workspace_binding_id === "string") return parsed.workspace_binding_id;
104
106
  return typeof parsed.project_id === "string" ? parsed.project_id : null;
105
107
  } catch {
106
108
  return null;
107
109
  }
108
110
  }
109
111
 
112
+ function readSnapshotCanonicalCount(projectRoot) {
113
+ // No reader / not bound → degrade to an empty corpus (0), the documented
114
+ // store-only behavior (KT-DEC-0007). Only the "snapshot EXISTS but predates
115
+ // knowledge_store_dirs" case below is undeterminable → null (skip).
116
+ if (bindingsSnapshotReader === null) {
117
+ return 0;
118
+ }
119
+ const bindingId = readWorkspaceBindingId(projectRoot);
120
+ if (bindingId === null) {
121
+ return 0;
122
+ }
123
+ try {
124
+ const snapshot = bindingsSnapshotReader.readBindingsSnapshot(bindingId);
125
+ // No snapshot file at all → treat as an empty corpus (KT-DEC-0007),
126
+ // preserving the fresh-project underseed nudge.
127
+ if (!snapshot) {
128
+ return 0;
129
+ }
130
+ // LIVE recount off the snapshot's resolved store dirs. The cached
131
+ // knowledge_stats.canonical_count is frozen at snapshot-write time and goes
132
+ // stale when store content syncs in out-of-band (e.g. the store grew from 1
133
+ // → 57 nodes via a `git pull`/cross-workspace sync that never regenerated
134
+ // THIS workspace's snapshot), which mis-fired the "knowledge sparse"
135
+ // underseed nudge (KT-PIT-0017, same stale-projection root cause).
136
+ const live = bindingsSnapshotReader.liveKnowledgeStats(snapshot);
137
+ // #3: a snapshot that predates knowledge_store_dirs makes liveKnowledgeStats
138
+ // return null — the count is undeterminable and the cached projection is
139
+ // unreliable. Return null (not 0) so countCanonicalNodes / shouldRecommendImport
140
+ // SKIP the nudge instead of false-firing on stale data; the snapshot
141
+ // self-heals on the next install/sync. A genuine live 0 (dirs present, no
142
+ // *.md) still returns 0 and fires correctly.
143
+ if (live === null) {
144
+ return null;
145
+ }
146
+ return Number.isFinite(live.canonicalCount) ? Math.floor(live.canonicalCount) : 0;
147
+ } catch {
148
+ // Read/parse fault → degrade to empty (0), preserving prior behavior. The
149
+ // only undeterminable→skip path is the explicit live===null above.
150
+ return 0;
151
+ }
152
+ }
153
+
154
+
110
155
  // -----------------------------------------------------------------------------
111
156
  // rc.12: SessionStart broad-menu is now unconditionally emitted on every
112
157
  // SessionStart fire (matching Skill-style progressive disclosure). Prior
@@ -124,7 +169,6 @@ const FABRIC_DIR_REL = ".fabric";
124
169
  // cannot `require` each other. If a third hook ever needs the same logic,
125
170
  // refactor into packages/cli/templates/hooks/lib/. Keep these values in sync
126
171
  // with packages/cli/templates/hooks/fabric-hint.cjs.
127
- const AGENTS_META_FILE = "agents.meta.json";
128
172
  const IMPORT_STATE_FILE = ".import-state.json";
129
173
  const KNOWLEDGE_CANONICAL_TYPES = [
130
174
  "decisions",
@@ -135,11 +179,12 @@ const KNOWLEDGE_CANONICAL_TYPES = [
135
179
  ];
136
180
  const DEFAULT_UNDERSEED_NODE_THRESHOLD = 10;
137
181
 
138
- // v2.0.0-rc.33 W2-1 (P0-9): TopK upper bound on broad-scoped entries surfaced
139
- // per SessionStart fire. Keeps the banner inside ~1 screenful so the agent
140
- // actually reads the top-priority entries instead of triaging a wall of text.
141
- // Overridable via fabric-config.json#hint_broad_top_k (range 1..50).
142
- const DEFAULT_HINT_BROAD_TOP_K = 8;
182
+ // W2-1 (KT-DEC-0028): the broad index is shown in FULL (no top-K hard cap). The
183
+ // only scale guard is a backstop: when the rendered broad index exceeds this
184
+ // many lines, the overflow tail folds into one marker that doubles as a drift
185
+ // signal (the W4 doctor `broad-index-drift` lint is the authoritative detector).
186
+ // Overridable via fabric-config.json#broad_index_backstop (W4 schema range 20..500).
187
+ const DEFAULT_HINT_BROAD_INDEX_BACKSTOP = 50;
143
188
 
144
189
  // v2.0.0-rc.33 W2-5 (P1-8): cooldown (in hours) between broad-hint re-emits.
145
190
  // Default 0 preserves rc.32 behavior — every SessionStart re-fires the banner.
@@ -169,37 +214,15 @@ const DEFAULT_HINT_REMINDER_TO_CONTEXT = true;
169
214
  // -----------------------------------------------------------------------------
170
215
 
171
216
  /**
172
- * Count canonical knowledge entries across the five canonical type subdirs
173
- * (decisions / pitfalls / guidelines / models / processes). Pending entries
174
- * are NOT counted they are proposals, not seeded knowledge.
175
- *
176
- * Returns the integer count. ENOENT / unreadable subdir → silently treated as
177
- * zero (preserves never-block-on-failure invariant). Filters on `.md` suffix
178
- * only; the more-precise canonical filename pattern check is owned by
179
- * doctor.ts (the hook is a coarse signal, not a lint).
217
+ * Count canonical knowledge entries from the CLI-generated resolved-bindings
218
+ * snapshot. Store-only: hooks never walk project-local knowledge or store
219
+ * trees a missing snapshot degrades to zero (KT-DEC-0007).
180
220
  */
181
221
  function countCanonicalNodes(projectRoot) {
182
- const knowledgeRoot = join(projectRoot, FABRIC_DIR_REL, "knowledge");
183
- if (!existsSync(knowledgeRoot)) {
184
- return 0;
185
- }
186
- let count = 0;
187
- for (const type of KNOWLEDGE_CANONICAL_TYPES) {
188
- const typeDir = join(knowledgeRoot, type);
189
- if (!existsSync(typeDir)) continue;
190
- let entries;
191
- try {
192
- entries = readdirSync(typeDir);
193
- } catch {
194
- continue;
195
- }
196
- for (const entry of entries) {
197
- if (entry.endsWith(".md")) {
198
- count += 1;
199
- }
200
- }
201
- }
202
- return count;
222
+ // #3: null = undeterminable (old snapshot lacking store dirs, or no binding
223
+ // context). Propagate it — shouldRecommendImport SKIPS on null rather than
224
+ // treating it as zero and false-firing the underseed nudge on a stale corpus.
225
+ return readSnapshotCanonicalCount(projectRoot);
203
226
  }
204
227
 
205
228
  /**
@@ -216,14 +239,15 @@ function readUnderseedThreshold(projectRoot) {
216
239
  }
217
240
 
218
241
  /**
219
- * v2.0.0-rc.33 W2-1: resolve hint_broad_top_k from fabric-config.json. Slices
220
- * the broad entry list to TopK before group/truncation render. Validates the
221
- * schema's 1..50 range inline so a malformed config silently falls back.
242
+ * W2-1 (KT-DEC-0028): resolve broad_index_backstop from fabric-config.json. Caps
243
+ * the rendered broad index line count; the overflow tail folds into a drift
244
+ * marker. Validates the W4 schema's 20..500 range inline so a malformed config
245
+ * silently falls back to the default.
222
246
  */
223
- function readBroadTopK(projectRoot) {
224
- return readConfigNumber(projectRoot, "hint_broad_top_k", DEFAULT_HINT_BROAD_TOP_K, {
225
- min: 1,
226
- max: 50,
247
+ function readBroadIndexBackstop(projectRoot) {
248
+ return readConfigNumber(projectRoot, "broad_index_backstop", DEFAULT_HINT_BROAD_INDEX_BACKSTOP, {
249
+ min: 20,
250
+ max: 500,
227
251
  floor: true,
228
252
  });
229
253
  }
@@ -309,9 +333,11 @@ function isImportTouched(projectRoot) {
309
333
  * surface the one-line `/fabric-import` recommendation banner.
310
334
  *
311
335
  * Three-condition truth table (ALL must hold to return true):
312
- * 1. `.fabric/agents.meta.json` exists
313
- * (workspace has been `fabric init`-ed; otherwise the recommendation
314
- * is meaningless — `fabric-import` requires init's baseline scan).
336
+ * 1. the workspace is fabric-bound — readWorkspaceBindingId(cwd) !== null
337
+ * (a resolved binding id in fabric-config.json; otherwise the
338
+ * recommendation is meaningless — `fabric-import` requires a bound
339
+ * workspace. Store-only: replaces the legacy derived-index-file
340
+ * existence probe.)
315
341
  * 2. countCanonicalNodes(cwd) < readUnderseedThreshold(cwd)
316
342
  * (knowledge graph is sparse — import would meaningfully enrich it).
317
343
  * 3. isImportTouched(cwd) === 'absent'
@@ -324,11 +350,14 @@ function isImportTouched(projectRoot) {
324
350
  */
325
351
  function shouldRecommendImport(projectRoot) {
326
352
  try {
327
- const metaPath = join(projectRoot, FABRIC_DIR_REL, AGENTS_META_FILE);
328
- if (!existsSync(metaPath)) return false;
353
+ if (readWorkspaceBindingId(projectRoot) === null) return false;
329
354
 
330
355
  const threshold = readUnderseedThreshold(projectRoot);
331
356
  const nodeCount = countCanonicalNodes(projectRoot);
357
+ // #3: undeterminable count (old snapshot predating knowledge_store_dirs) →
358
+ // skip. `null < threshold` coerces to true in JS, so an explicit guard is
359
+ // required — otherwise the stale-snapshot case would still false-fire.
360
+ if (nodeCount === null) return false;
332
361
  if (nodeCount >= threshold) return false;
333
362
 
334
363
  if (isImportTouched(projectRoot) !== "absent") return false;
@@ -365,65 +394,6 @@ const CLI_TIMEOUT_MS = 2000;
365
394
  // `hint_summary_max_len` in fabric-config overrides this default (range 40..240).
366
395
  const DEFAULT_SUMMARY_MAX_LEN = 80;
367
396
 
368
- // v2.2 HK2-degrade (W2-T2): char budget for the rendered broad-menu BODY. The
369
- // hook already degrades by COUNT (hint_broad_top_k slice + TRUNCATION_THRESHOLD
370
- // grouped mode), but nothing bounded the total rendered SIZE — a corpus with
371
- // many types or long (near-maxLen) summaries could still emit a wall of text
372
- // that displaces the agent's working memory. Borrowing the maestro
373
- // context-budget idea, this is the final rung of the degradation ladder: once
374
- // the body exceeds the budget, the tail collapses to a single "N more omitted"
375
- // marker. Default 2000 chars ≈ one screenful. Overridable via
376
- // fabric-config.json#hint_broad_budget_chars (range 200..20000); 0 disables.
377
- const DEFAULT_HINT_BROAD_BUDGET_CHARS = 2000;
378
-
379
- // v2.2 C5-budget (W2-T3): bind the injection char budget to the layered retrieval
380
- // budget profile. Mirrors the injectionChars column of shared/retrieval-budget.ts
381
- // PROFILES (kept in sync — the hook cannot require the TS resolver). The explicit
382
- // `hint_broad_budget_chars` knob still wins; the profile only supplies the
383
- // default. `balanced` (and an absent/unknown profile) keeps the historical 2000.
384
- const RETRIEVAL_BUDGET_INJECTION_CHARS = {
385
- conservative: 1000,
386
- balanced: 2000,
387
- generous: 4000,
388
- };
389
-
390
- function readBroadBudgetChars(projectRoot) {
391
- const profile = readConfigString(projectRoot, "retrieval_budget_profile", "balanced");
392
- const profileDefault =
393
- RETRIEVAL_BUDGET_INJECTION_CHARS[profile] ?? DEFAULT_HINT_BROAD_BUDGET_CHARS;
394
- return readConfigNumber(projectRoot, "hint_broad_budget_chars", profileDefault, {
395
- min: 0,
396
- max: 20000,
397
- floor: true,
398
- });
399
- }
400
-
401
- // v2.2 HK2-degrade (W2-T2): cap the rendered body to `budgetChars`, collapsing
402
- // the overflow tail into one marker line. Structural lines (banner, revision_hash,
403
- // footer) are appended by renderSummary AFTER this pass, so they always survive —
404
- // only entry/group body lines are subject to the budget. `budgetChars` of 0 or
405
- // undefined is a no-op (preserves the pre-HK2 unbounded behavior and all
406
- // existing snapshot tests).
407
- function capBodyToBudget(body, budgetChars) {
408
- if (!budgetChars || budgetChars <= 0) return body;
409
- const kept = [];
410
- let total = 0;
411
- for (let i = 0; i < body.length; i += 1) {
412
- const line = body[i];
413
- // +1 for the newline each line costs once joined.
414
- if (kept.length > 0 && total + line.length + 1 > budgetChars) {
415
- const remaining = body.length - i;
416
- kept.push(
417
- ` … ${remaining} more entr${remaining === 1 ? "y" : "ies"} omitted (injection budget ${budgetChars} chars; raise hint_broad_budget_chars or narrow scope)`,
418
- );
419
- return kept;
420
- }
421
- kept.push(line);
422
- total += line.length + 1;
423
- }
424
- return kept;
425
- }
426
-
427
397
  function readSummaryMaxLen(projectRoot) {
428
398
  return readConfigNumber(projectRoot, "hint_summary_max_len", DEFAULT_SUMMARY_MAX_LEN, {
429
399
  min: 40,
@@ -673,7 +643,7 @@ function renderTruncated(narrow, maxLen) {
673
643
  * after writing exactly one stderr breadcrumb so operators grepping a stuck-
674
644
  * banner report can diagnose the version drift without source-diving.
675
645
  */
676
- function renderSummary(payload, maxLen, budgetChars) {
646
+ function renderSummary(payload, maxLen) {
677
647
  if (!payload || payload.version !== 2) {
678
648
  if (payload && payload.version !== undefined) {
679
649
  try {
@@ -696,9 +666,9 @@ function renderSummary(payload, maxLen, budgetChars) {
696
666
  ? `[fabric] Session start — ${entries.length} broad-scoped knowledge entries available (truncated):`
697
667
  : `[fabric] Session start — ${entries.length} broad-scoped knowledge entries available:`;
698
668
 
699
- const renderedBody = truncated ? renderTruncated(entries, maxLen) : renderFull(entries, maxLen);
700
- // v2.2 HK2-degrade (W2-T2): final budget rung cap the body's rendered size.
701
- const body = capBodyToBudget(renderedBody, budgetChars);
669
+ // KT-DEC-0028 completeness: the rendered census is bounded by the per-line
670
+ // maxLen + TRUNCATION_THRESHOLD grouped mode, not by a body char budget.
671
+ const body = truncated ? renderTruncated(entries, maxLen) : renderFull(entries, maxLen);
702
672
 
703
673
  const lines = [banner, ...body];
704
674
  const revHash = typeof payload.revision_hash === "string" ? payload.revision_hash : null;
@@ -745,26 +715,307 @@ function renderSummary(payload, maxLen, budgetChars) {
745
715
  }
746
716
  }
747
717
 
748
- // v2.2 MC3-fix-guidance (W1-T5): unify the footer with the canonical recall
749
- // flow. The prior text ("Use `fab_get_knowledge_sections` to fetch full
750
- // content.") told the agent to call a tool that REQUIRES a selection_token it
751
- // does not yet have — directly contradicting the bilingual next-step nudge
752
- // (and AGENTS.md) which leads with `fab_recall`. Footer now states the same
753
- // two-path model: single-step `fab_recall`, or `fab_plan_context` →
754
- // `fab_get_knowledge_sections` when the bodies must be trimmed first. Keeps
755
- // the `fab_get_knowledge_sections` token (downstream substring contracts) but
756
- // sequences it correctly behind the token-issuing `fab_plan_context`.
718
+ // W2-4 (KT-DEC-0026): single lean retrieval flow. The two-step
719
+ // fab_plan_context fab_get_knowledge_sections footer is retired fab_recall
720
+ // returns descriptions + read paths, and bodies load via a native Read.
757
721
  lines.push(
758
- " Load full content: `fab_recall(paths)` (one step), or `fab_plan_context` `fab_get_knowledge_sections` to trim first.",
722
+ " Load full content: `fab_recall(paths)`, or Read `<store>/knowledge/<type>/<id>--*.md` directly.",
759
723
  );
760
724
  return lines;
761
725
  }
762
726
 
727
+ // -----------------------------------------------------------------------------
728
+ // v2.2 dual-sink (Goal A): two-sink SessionStart rendering.
729
+ //
730
+ // HUMAN sink (systemMessage): a grouped census (§3 / D8) — always-loaded vs
731
+ // on-demand split + [team]/[personal] + ✗ dropped-other-project. Count-summary
732
+ // form (not a per-entry wall of text); the verbose nudge_mode appends the legacy
733
+ // per-entry renderSummary listing on top.
734
+ //
735
+ // AI sink (additionalContext): the always-active (guideline/model) BODIES (§3 /
736
+ // D9), bounded by the injection char budget with overflow degrading to summary +
737
+ // a recall pointer, followed by on-demand category counts. Replaces the legacy
738
+ // top_k=8 id-list that used to be the AI payload.
739
+ // -----------------------------------------------------------------------------
740
+
741
+ // Singular display label for a plural knowledge_type.
742
+ const TYPE_SINGULAR = {
743
+ decisions: "decision",
744
+ pitfalls: "pitfall",
745
+ guidelines: "guideline",
746
+ models: "model",
747
+ processes: "process",
748
+ };
749
+
750
+ const ALWAYS_TYPES = ["guidelines", "models"];
751
+
752
+ // Normalize a knowledge_type to its canonical PLURAL form. Frontmatter / entries
753
+ // may carry the singular ("decision") while the census keys on the plural enum
754
+ // ("decisions"); fold both so counting + display stay consistent.
755
+ const TYPE_TO_PLURAL = {
756
+ decision: "decisions",
757
+ pitfall: "pitfalls",
758
+ guideline: "guidelines",
759
+ model: "models",
760
+ process: "processes",
761
+ };
762
+ function toPluralType(type) {
763
+ return TYPE_TO_PLURAL[type] || type;
764
+ }
765
+
766
+ // Fallback census when payload.census is absent (old CLI / unit-test payloads):
767
+ // count the (possibly sliced) entries by knowledge_type so the human banner still
768
+ // has something to group. Production payloads always carry the unsliced census.
769
+ function deriveCensusFromEntries(entries) {
770
+ const census = { by_type: {}, by_layer: { team: 0, personal: 0, project: 0 }, dropped_other_project: 0, total: 0 };
771
+ if (!Array.isArray(entries)) return census;
772
+ for (const e of entries) {
773
+ const type = e && typeof e.type === "string" ? toPluralType(e.type) : null;
774
+ if (type === null) continue;
775
+ census.by_type[type] = (census.by_type[type] || 0) + 1;
776
+ census.total += 1;
777
+ }
778
+ return census;
779
+ }
780
+
781
+ // Render the human-facing grouped census (§3). `lang` is "zh-CN" | other (en).
782
+ // Returns an array of lines (may be empty when the census is empty).
783
+ function renderHumanCensus(census, opts) {
784
+ const { lang } = opts || {};
785
+ const c = census || {};
786
+ const byType = c.by_type || {};
787
+ const total = typeof c.total === "number" ? c.total : 0;
788
+ if (total === 0 && (c.dropped_other_project || 0) === 0) return [];
789
+ const zh = lang === "zh-CN";
790
+
791
+ const typeCounts = (types) =>
792
+ types
793
+ .filter((t) => (byType[t] || 0) > 0)
794
+ .map((t) => `${TYPE_SINGULAR[t] || t} ${byType[t]}`)
795
+ .join(" · ");
796
+
797
+ const lines = [];
798
+ // `total` is the read-set ENTRY COUNT (not bytes) — label it as 条/entries.
799
+ lines.push(`▸ [fabric] SessionStart (${total} ${zh ? "条" : total === 1 ? "entry" : "entries"})`);
800
+ // W2-2/W2-3 (KT-DEC-0027/0029): the human breadcrumb shows only the
801
+ // always-loaded (guideline/model) census. The on-demand (decision/pitfall/
802
+ // process) count line and the dropped-other-project line are retired — the
803
+ // decision/pitfall/process REFERENCE lives in the AI sink (title + must_read_if),
804
+ // and SessionStart stays silent about narrow-scoped knowledge.
805
+ const alwaysCounts = typeCounts(ALWAYS_TYPES);
806
+ lines.push(zh ? " ─ always-loaded(AI 也收到正文)─" : " ─ always-loaded (AI also gets bodies) ─");
807
+ lines.push(` ${alwaysCounts.length > 0 ? alwaysCounts : zh ? "(无)" : "(none)"}`);
808
+ const layer = c.by_layer || {};
809
+ const teamCount = layer.team || 0;
810
+ const personalCount = layer.personal || 0;
811
+ const projectCount = layer.project || 0;
812
+ if (teamCount > 0 || personalCount > 0 || projectCount > 0) {
813
+ const segs = [`[team] ${teamCount}`];
814
+ if (projectCount > 0) segs.push(`[project] ${projectCount}`);
815
+ segs.push(`[personal] ${personalCount}`);
816
+ lines.push(` ${segs.join(" · ")}`);
817
+ }
818
+ return lines;
819
+ }
820
+
821
+ // W2 (KT-DEC-0027/0028/0029): render the AI-facing sink — the dynamically
822
+ // generated "MEMORY.md" spine injected into the SessionStart context. Two
823
+ // type-tiered sections over the BROAD knowledge (narrow stays silent — D0029):
824
+ //
825
+ // ALWAYS-ACTIVE RULES (guideline/model): INDEX LINE only (title + summary) —
826
+ // never the eager body (KT-DEC-0036). The body is one cheap on-demand fetch
827
+ // away, so injecting it on every SessionStart is a permanent context tax
828
+ // (KT-GLD-0005) we no longer pay; each entry stays individually visible.
829
+ // REFERENCE (decision/pitfall/process): TITLE + must_read_if hook only
830
+ // (situational; the agent Reads the body on demand) — never the body.
831
+ //
832
+ // `broadIndexBackstop` (D0028) caps the total rendered index lines; the overflow
833
+ // tail folds into one marker that doubles as the drift signal (fabric-audit /
834
+ // the W4 doctor lint is the authoritative detector). `entries` is the broad
835
+ // plan-context-hint entry list ({id,type,maturity,summary,relevance_scope,
836
+ // must_read_if}); `alwaysBodies` is always_bodies[] ({id,type,layer,summary,body}).
837
+ const REFERENCE_TYPES = new Set(["decision", "pitfall", "process"]);
838
+
839
+ function renderAiSink(opts) {
840
+ const { entries, alwaysBodies, storeLabel, broadIndexBackstop, summaryMaxLen, lang } =
841
+ opts || {};
842
+ const zh = lang === "zh-CN";
843
+ const bodies = Array.isArray(alwaysBodies) ? alwaysBodies : [];
844
+ // REFERENCE = broad decision/pitfall/process. narrow entries stay silent (D0029).
845
+ const referenceEntries = (Array.isArray(entries) ? entries : []).filter((e) => {
846
+ if (!e || e.relevance_scope === "narrow") return false;
847
+ return REFERENCE_TYPES.has(TYPE_SINGULAR[toPluralType(e.type)] || e.type);
848
+ });
849
+ // Nothing to inject → empty so main() stays silent on an empty knowledge base.
850
+ if (bodies.length === 0 && referenceEntries.length === 0) return "";
851
+
852
+ const backstop =
853
+ typeof broadIndexBackstop === "number" && broadIndexBackstop > 0 ? broadIndexBackstop : 0;
854
+ let indexCount = 0; // total rendered index lines (always + reference), for the backstop.
855
+
856
+ const lines = [];
857
+ lines.push(`[fabric:SessionStart] ${storeLabel || "store"}`);
858
+
859
+ // ALWAYS-ACTIVE RULES — index-only (title + summary), never the eager body.
860
+ lines.push(zh ? "ALWAYS-ACTIVE RULES (无需再 recall):" : "ALWAYS-ACTIVE RULES (no recall needed):");
861
+ if (bodies.length === 0) {
862
+ lines.push(zh ? " (无 always-active 条目)" : " (none)");
863
+ } else {
864
+ // KT-DEC-0036: render each always-active entry as a single index line
865
+ // (title + summary). The body is one cheap on-demand fetch away (see footer),
866
+ // so injecting it on every SessionStart is a permanent context tax
867
+ // (KT-GLD-0005) we no longer pay.
868
+ for (const b of bodies) {
869
+ const label = `[${TYPE_SINGULAR[b.type] || b.type}] ${b.id}`;
870
+ const summary = typeof b.summary === "string" ? b.summary.trim() : "";
871
+ lines.push(summary.length > 0 ? ` ${label} · ${summary}` : ` ${label}`);
872
+ indexCount += 1;
873
+ }
874
+ }
875
+
876
+ // REFERENCE — broad decision/pitfall/process: title + must_read_if hook.
877
+ if (referenceEntries.length > 0) {
878
+ lines.push(zh ? "REFERENCE (按需 Read / fab_recall):" : "REFERENCE (read on demand / fab_recall):");
879
+ let folded = 0;
880
+ for (const e of referenceEntries) {
881
+ if (backstop > 0 && indexCount >= backstop) {
882
+ folded += 1;
883
+ continue;
884
+ }
885
+ const type = TYPE_SINGULAR[toPluralType(e.type)] || e.type;
886
+ const rawHook =
887
+ typeof e.must_read_if === "string" && e.must_read_if.length > 0
888
+ ? e.must_read_if
889
+ : typeof e.summary === "string"
890
+ ? e.summary
891
+ : "";
892
+ const hookText = truncateSummary(rawHook, summaryMaxLen);
893
+ lines.push(hookText.length > 0 ? ` [${type}] ${e.id} — ${hookText}` : ` [${type}] ${e.id}`);
894
+ indexCount += 1;
895
+ }
896
+ // D0028 backstop: fold the overflow tail into one marker + drift signal.
897
+ if (folded > 0) {
898
+ lines.push(
899
+ zh
900
+ ? ` … 另 ${folded} 条 broad 条目折叠 (broad index > backstop ${backstop}; 跑 fabric-audit)`
901
+ : ` … ${folded} more broad entr${folded === 1 ? "y" : "ies"} folded (broad index > backstop ${backstop}; run fabric-audit)`,
902
+ );
903
+ }
904
+ }
905
+
906
+ // W2-4 footer: single lean retrieval flow — no two-step.
907
+ lines.push(
908
+ zh
909
+ ? "取正文: fab_recall(paths), 或 Read <store>/knowledge/<type>/<id>--*.md"
910
+ : "Load full content: fab_recall(paths), or Read <store>/knowledge/<type>/<id>--*.md",
911
+ );
912
+ return lines.join("\n");
913
+ }
914
+
763
915
  // -----------------------------------------------------------------------------
764
916
  // Main entry — invoked both as a CLI (require.main === module) and in-process
765
917
  // by tests. Wraps the entire flow in try/catch: ANY error → silent exit 0.
766
918
  // -----------------------------------------------------------------------------
767
919
 
920
+ // Block 5 (Option X): build the two SessionStart sinks (human systemMessage +
921
+ // AI additionalContext) from a plan-context-hint payload, WITHOUT emitting or
922
+ // recording telemetry. This is the single shared renderer: main() calls it then
923
+ // emits + logs; `fabric context` calls it then prints (byte-identical injection
924
+ // by construction — same code, same config/FS reads). Pure-ish: it reads config
925
+ // + snapshot + .md summaries for `cwd` but has no stdout/ledger side effects.
926
+ //
927
+ // Returns:
928
+ // human — gated final human text (null when gated off / empty)
929
+ // ai — gated final AI text (null when reminder-to-context off / empty)
930
+ // resolvedPayload — the plan-context payload, passed through unchanged (for telemetry / --explain)
931
+ // hasRenderedContent — true when ANY sink rendered content (main's silent-exit gate)
932
+ // reminderToContext — readReminderToContext(cwd) (telemetry target-channel)
933
+ function buildSessionStartSinks(cwd, payload, env) {
934
+ // KT-GLD-0006: the rc.35 opaque-summary runtime substitution
935
+ // (resolveOpaqueSummaries) is retired. The write-time mechanical floor in
936
+ // extractKnowledge (summary !== stable_id/slug + length floor) prevents
937
+ // degenerate summaries at the source, so SessionStart no longer band-aids them
938
+ // at render time; surviving legacy opaque summaries are fixed by the
939
+ // review-time cold-eval audit pass.
940
+ const resolvedPayload = payload;
941
+
942
+ const recommendImport = shouldRecommendImport(cwd);
943
+ const summaryMaxLen = readSummaryMaxLen(cwd);
944
+ const fabricLanguageForEmit = readFabricLanguage(cwd);
945
+
946
+ const census =
947
+ env && env.census !== undefined
948
+ ? env.census
949
+ : payload && payload.census
950
+ ? payload.census
951
+ : deriveCensusFromEntries(resolvedPayload && resolvedPayload.entries);
952
+ const alwaysBodies =
953
+ env && env.alwaysBodies !== undefined
954
+ ? env.alwaysBodies
955
+ : payload && Array.isArray(payload.always_bodies)
956
+ ? payload.always_bodies
957
+ : [];
958
+
959
+ const humanGate =
960
+ nudgePolicy !== null
961
+ ? nudgePolicy.resolveHumanSink(cwd, "session_start", {})
962
+ : { emitHuman: true, verbosity: "normal" };
963
+
964
+ // ---- HUMAN sink: §3 grouped census (+ verbose per-entry detail). ----
965
+ const humanLines = renderHumanCensus(census, { lang: fabricLanguageForEmit });
966
+ if (humanLines.length > 0 && humanGate.verbosity === "verbose") {
967
+ const detail = renderSummary(resolvedPayload, summaryMaxLen);
968
+ humanLines.push(...detail);
969
+ }
970
+ if (bindingsSnapshotReader !== null && humanLines.length > 0) {
971
+ try {
972
+ const bindingId = readWorkspaceBindingId(cwd);
973
+ if (bindingId) {
974
+ const label = bindingsSnapshotReader.formatStoreLabels(
975
+ bindingsSnapshotReader.readBindingsSnapshot(bindingId),
976
+ );
977
+ if (label) humanLines.push(label);
978
+ }
979
+ } catch {
980
+ // store labels are decorative provenance — never crash the hook
981
+ }
982
+ }
983
+ if (recommendImport && humanLines.length > 0 && fabricLanguageForEmit !== null) {
984
+ humanLines.push(renderBanner("broadImportBanner", fabricLanguageForEmit, {}));
985
+ }
986
+ if (humanLines.length > 0) {
987
+ humanLines.push(
988
+ fabricLanguageForEmit === "zh-CN"
989
+ ? "下一步: 改相关文件前调 fab_recall(paths) 拿 KB 条目的描述+读路径;按需 Read 路径取正文。"
990
+ : "Next: before editing related files, call fab_recall(paths) for the KB entries' descriptions + read paths; Read a path on demand for the body.",
991
+ );
992
+ // Block 5 (Option X): point to the byte-identical inspector for this injection.
993
+ humanLines.push(
994
+ fabricLanguageForEmit === "zh-CN"
995
+ ? "看具体注入: fabric context (--explain 看每条来源)"
996
+ : "Inspect this injection: fabric context (--explain for per-entry provenance)",
997
+ );
998
+ }
999
+
1000
+ // ---- AI sink: spine — always-active INDEX lines (no eager body, KT-DEC-0036)
1001
+ // + reference, bounded by the broad_index_backstop fold. ----
1002
+ const broadIndexBackstop = readBroadIndexBackstop(cwd);
1003
+ const aiText = renderAiSink({
1004
+ entries: resolvedPayload && Array.isArray(resolvedPayload.entries) ? resolvedPayload.entries : [],
1005
+ alwaysBodies,
1006
+ broadIndexBackstop,
1007
+ summaryMaxLen,
1008
+ lang: fabricLanguageForEmit,
1009
+ });
1010
+
1011
+ const hasRenderedContent = humanLines.length > 0 || (typeof aiText === "string" && aiText.length > 0);
1012
+ const human = humanGate.emitHuman && humanLines.length > 0 ? humanLines.join("\n") : null;
1013
+ const reminderToContext = readReminderToContext(cwd);
1014
+ const ai = reminderToContext && aiText && aiText.length > 0 ? aiText : null;
1015
+
1016
+ return { human, ai, resolvedPayload, hasRenderedContent, reminderToContext };
1017
+ }
1018
+
768
1019
  function main(env, stdio) {
769
1020
  try {
770
1021
  const cwd = (env && env.cwd) || process.cwd();
@@ -802,96 +1053,31 @@ function main(env, stdio) {
802
1053
  env && env.payload !== undefined ? env.payload : invokePlanContextHint(cwd);
803
1054
  if (payload === null || payload === undefined) return; // silent
804
1055
 
805
- // v2.0.0-rc.33 W2-1 (P0-9): apply TopK slice BEFORE renderSummary so the
806
- // grouped/truncation rendering operates on the bounded set. Slicing here
807
- // (not inside renderSummary) keeps the formatter pure it never has to
808
- // know about the cap.
809
- const topK = readBroadTopK(cwd);
810
- const slicedPayload =
811
- payload && Array.isArray(payload.entries) && payload.entries.length > topK
812
- ? { ...payload, entries: payload.entries.slice(0, topK) }
813
- : payload;
814
-
815
- // rc.35 TASK-06 (P0-10.b): summary-fallback substitution. Entries whose
816
- // description.summary equals stable_id render as "<id> · <id>" and the
817
- // AI skips fetching them; the fallback reads `## Summary` from the
818
- // entry's .md file and swaps in the first paragraph. Best-effort
819
- // failure leaves the original opaque summary untouched.
820
- let resolvedPayload = slicedPayload;
821
- try {
822
- if (slicedPayload && Array.isArray(slicedPayload.entries)) {
823
- const resolvedEntries = resolveOpaqueSummaries(
824
- slicedPayload.entries,
825
- cwd,
826
- typeof slicedPayload.revision_hash === "string" ? slicedPayload.revision_hash : "",
827
- );
828
- resolvedPayload = { ...slicedPayload, entries: resolvedEntries };
829
- }
830
- } catch {
831
- // resolveOpaqueSummaries swallows its own errors; this catch is belt
832
- // + suspenders for any unexpected exception from the lib layer.
833
- }
834
-
835
- // rc.8 underseed self-check: decide whether to surface the one-line
836
- // `/fabric-import` recommendation banner alongside the broad summary.
837
- const recommendImport = shouldRecommendImport(cwd);
838
-
839
- // rc.12: broad-summary body is unconditionally rendered on every
840
- // SessionStart fire (Skill-style progressive disclosure). The prior
841
- // revision_hash cooldown gate (rc.7 T8 — rc.11) was removed because
842
- // compact/clear-triggered SessionStart re-fires must re-inject the menu
843
- // for the agent's working memory. rc.33 W2-5 reintroduces an opt-in
844
- // hours-based cooldown via fabric-config (see gate above).
845
- const summaryMaxLen = readSummaryMaxLen(cwd);
846
- // v2.2 HK2-degrade (W2-T2): thread the injection char-budget into the renderer.
847
- const broadBudgetChars = readBroadBudgetChars(cwd);
848
- const lines = renderSummary(resolvedPayload, summaryMaxLen, broadBudgetChars);
849
-
850
- // v2.0.0-rc.37 NEW-23: resolve fabric_language ONCE per emit path —
851
- // shared between the (existing) broadImportBanner branch and the new
852
- // 'next step' nudge tail added below. 'match-existing' / unknown variants
853
- // fold to 'en' inside renderBanner per UX i18n Policy class 1.
854
- const fabricLanguageForEmit = lines.length > 0 || recommendImport ? readFabricLanguage(cwd) : null;
855
- if (recommendImport && fabricLanguageForEmit !== null) {
856
- lines.push(renderBanner("broadImportBanner", fabricLanguageForEmit, {}));
857
- }
858
-
859
- if (lines.length === 0) return; // nothing to say — silent exit
860
-
861
- // v2.1.0-rc.1 P4 (F4/S63): append a per-store read-set label from the
862
- // CLI-pre-generated bindings snapshot so the session opens aware of which
863
- // stores it reads and where writes land. Best-effort, never blocks: a
864
- // missing snapshot / single-store setup just omits the line.
865
- if (bindingsSnapshotReader !== null) {
866
- try {
867
- const projectId = readProjectId(cwd);
868
- if (projectId) {
869
- const label = bindingsSnapshotReader.formatStoreLabels(
870
- bindingsSnapshotReader.readBindingsSnapshot(projectId),
871
- );
872
- if (label) lines.push(label);
873
- }
874
- } catch {
875
- // store labels are decorative provenance — never crash the hook
876
- }
877
- }
878
-
879
- // v2.0.0-rc.37 NEW-23: SessionStart 索引末尾"下一步"引导。Tail line that
880
- // tells the AI what to do with the broad index it just received. Without
881
- // this, the model often parses the index and moves on without ever calling
882
- // fab_recall / fab_plan_context. One-line nudge, bilingual.
883
- // v2.2 W1-REVIEW codex LOW-6: `description_index` was renamed to `candidates`
884
- // in rc.38 UX-1; the nudge now uses the current field name so the guidance
885
- // matches the actual MCP response shape.
886
- const nextStepNudge =
887
- fabricLanguageForEmit === "zh-CN"
888
- ? "下一步: 调 fab_recall(paths) 拿 KB 相关条目;或调 fab_plan_context 先看候选描述(candidates)。"
889
- : "Next: call fab_recall(paths) to fetch related KB entries, or fab_plan_context to preview the candidate descriptions first.";
890
- lines.push(nextStepNudge);
891
-
892
- // Stderr: always emit (human-facing breadcrumb + legacy contract).
893
- for (const line of lines) {
894
- err.write(`${line}\n`);
1056
+ // W2-1 (KT-DEC-0028): broad 全显示 the legacy hint_broad_top_k hard cap is
1057
+ // retired. SessionStart must SEE every broad entry; scale is bounded by the
1058
+ // per-line char cap + broad_index_backstop fold, not by dropping entries.
1059
+
1060
+ // Block 5 (Option X): build both sinks via the shared renderer (same code
1061
+ // `fabric context` uses → byte-identical injection). Side-effect-free; the
1062
+ // emit + telemetry below stay in main().
1063
+ const { human, ai, resolvedPayload, hasRenderedContent, reminderToContext } =
1064
+ buildSessionStartSinks(cwd, payload, env);
1065
+
1066
+ // Nothing to say at all → silent exit (preserves the empty-payload contract).
1067
+ if (!hasRenderedContent) return;
1068
+
1069
+ // v2.2 dual-sink (Goal A / D7): emit both channels in one render. The human
1070
+ // systemMessage is gated by nudge_mode (emitHuman); the AI additionalContext
1071
+ // is emitted regardless. emitDualSink shapes the protocol per client (CC/Codex
1072
+ // camelCase nested envelope; unknown → stderr).
1073
+ if (!(env && env.skipStdout === true)) {
1074
+ emitDualSink(
1075
+ { human, ai },
1076
+ { client: detectClient(), eventName: "SessionStart", streams: { stdout: out, stderr: err } },
1077
+ );
1078
+ } else if (human !== null) {
1079
+ // skipStdout test seam: still surface the human breadcrumb to stderr.
1080
+ err.write(`${human}\n`);
895
1081
  }
896
1082
 
897
1083
  // v2.2 HK3-telemetry (W3-T1): record the injection side. We just OFFERED the
@@ -914,37 +1100,10 @@ function main(env, stdio) {
914
1100
  });
915
1101
  }
916
1102
 
917
- // v2.0.0-rc.33 W2-6 (P0-7): stdout JSON envelope. When
918
- // hint_reminder_to_context is true (default), serialize the same banner
919
- // body as Claude Code's SessionStart hookSpecificOutput shape so the model
920
- // receives the reminder IN-CONTEXT (rc.32 baseline cite-coverage 3.1%
921
- // root cause: reminders never entered model context). Stderr stays the
922
- // host-facing channel.
923
- //
924
- // Failure to write JSON envelope must NOT crash the hook — stderr already
925
- // delivered, the stdout layer is best-effort.
926
- // v2.0.0-rc.33 W4 review-fix (gemini High-1): the stdout JSON envelope
927
- // is Claude Code-specific (hookSpecificOutput.additionalContext contract).
928
- // Codex CLI / Cursor don't parse it — leaking it to their stdout risks
929
- // either polluting the terminal or crashing the host's hook-parsing
930
- // pipeline. CLAUDE_PROJECT_DIR is set by CC when invoking hooks (see
931
- // packages/cli/templates/hooks/configs/claude-code.json sigil paths);
932
- // its presence is the single-bit "this is Claude Code" signal (now via
933
- // the shared client-adapter, rc.37 NEW-30).
934
- const reminderToContext = readReminderToContext(cwd) && isClaudeCode();
935
- if (reminderToContext && !(env && env.skipStdout === true)) {
936
- try {
937
- const envelope = {
938
- hookSpecificOutput: {
939
- hookEventName: "SessionStart",
940
- additionalContext: lines.join("\n"),
941
- },
942
- };
943
- out.write(`${JSON.stringify(envelope)}\n`);
944
- } catch {
945
- // Best-effort — stderr is the durable contract
946
- }
947
- }
1103
+ // v2.2 dual-sink (Goal A): the legacy rc.33 W2-6 stdout JSON envelope is
1104
+ // replaced by emitDualSink above (which carries BOTH the human systemMessage
1105
+ // and the AI additionalContext, shaped per client). hint_reminder_to_context
1106
+ // still gates whether the AI sink is populated (see `ai` above).
948
1107
 
949
1108
  // v2.1 NEW-N-3 (ADJ-NEWN-3): hook_surface_emitted instrumentation. One
950
1109
  // best-effort ledger row recording WHICH broad-scoped ids were surfaced
@@ -953,7 +1112,7 @@ function main(env, stdio) {
953
1112
  // per session boot so this never bloats the ledger. Never blocks the hook
954
1113
  // (KT-DEC-0007): any failure (no .fabric/, undetected client, write error)
955
1114
  // degrades to silent skip. Client is omitted-by-skip when undetectable
956
- // because the schema's `client` enum admits only cc/codex/cursor.
1115
+ // because the schema's `client` enum admits only cc/codex.
957
1116
  try {
958
1117
  const surfaceClient = detectClient();
959
1118
  const fabricDir = join(cwd, FABRIC_DIR_REL);
@@ -1002,6 +1161,7 @@ function main(env, stdio) {
1002
1161
 
1003
1162
  module.exports = {
1004
1163
  main,
1164
+ buildSessionStartSinks,
1005
1165
  invokePlanContextHint,
1006
1166
  groupEntries,
1007
1167
  renderFull,
@@ -1013,8 +1173,8 @@ module.exports = {
1013
1173
  readUnderseedThreshold,
1014
1174
  isImportTouched,
1015
1175
  shouldRecommendImport,
1016
- // v2.0.0-rc.33 W2-1 / W2-5 / W2-6 helpers.
1017
- readBroadTopK,
1176
+ // W2-1 (KT-DEC-0028) + rc.33 W2-5 / W2-6 helpers.
1177
+ readBroadIndexBackstop,
1018
1178
  readBroadCooldownHours,
1019
1179
  readReminderToContext,
1020
1180
  readBroadLastEmit,
@@ -1031,7 +1191,7 @@ module.exports = {
1031
1191
  MATURITY_DRAFT,
1032
1192
  DEFAULT_UNDERSEED_NODE_THRESHOLD,
1033
1193
  KNOWLEDGE_CANONICAL_TYPES,
1034
- DEFAULT_HINT_BROAD_TOP_K,
1194
+ DEFAULT_HINT_BROAD_INDEX_BACKSTOP,
1035
1195
  DEFAULT_HINT_BROAD_COOLDOWN_HOURS,
1036
1196
  DEFAULT_HINT_REMINDER_TO_CONTEXT,
1037
1197
  HINT_BROAD_LAST_EMIT_FILE_NAME,