@fenglimg/fabric-cli 2.0.0-rc.26 → 2.0.0-rc.28

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.
@@ -148,6 +148,7 @@ async function installFabricArchiveSkill(projectRoot, _options = {}) {
148
148
  for (const target of targets) {
149
149
  results.push(await copyTextIdempotent("skill", source, target));
150
150
  }
151
+ results.push(...await installSkillRefFiles(projectRoot, "fabric-archive"));
151
152
  return results;
152
153
  }
153
154
  async function installFabricReviewSkill(projectRoot, _options = {}) {
@@ -157,6 +158,7 @@ async function installFabricReviewSkill(projectRoot, _options = {}) {
157
158
  for (const target of targets) {
158
159
  results.push(await copyTextIdempotent("skill-review", source, target));
159
160
  }
161
+ results.push(...await installSkillRefFiles(projectRoot, "fabric-review"));
160
162
  return results;
161
163
  }
162
164
  async function installFabricImportSkill(projectRoot, _options = {}) {
@@ -166,6 +168,67 @@ async function installFabricImportSkill(projectRoot, _options = {}) {
166
168
  for (const target of targets) {
167
169
  results.push(await copyTextIdempotent("skill-import", source, target));
168
170
  }
171
+ results.push(...await installSkillRefFiles(projectRoot, "fabric-import"));
172
+ return results;
173
+ }
174
+ async function installSkillRefFiles(projectRoot, skillSlug) {
175
+ let refTemplateDir;
176
+ try {
177
+ refTemplateDir = findTemplatePath(`skills/${skillSlug}/ref`);
178
+ } catch {
179
+ return [
180
+ {
181
+ step: "skill-ref",
182
+ path: `skills/${skillSlug}/ref`,
183
+ status: "skipped",
184
+ message: `no-ref-dir: ${skillSlug}`
185
+ }
186
+ ];
187
+ }
188
+ let refFiles;
189
+ try {
190
+ refFiles = readdirSync(refTemplateDir).filter((name) => name.endsWith(".md"));
191
+ } catch {
192
+ return [
193
+ {
194
+ step: "skill-ref",
195
+ path: refTemplateDir,
196
+ status: "skipped",
197
+ message: `no-ref-files: ${skillSlug}`
198
+ }
199
+ ];
200
+ }
201
+ if (refFiles.length === 0) {
202
+ return [
203
+ {
204
+ step: "skill-ref",
205
+ path: refTemplateDir,
206
+ status: "skipped",
207
+ message: `no-ref-files: ${skillSlug}`
208
+ }
209
+ ];
210
+ }
211
+ const clientPrefixes = [".claude", ".codex"];
212
+ const results = [];
213
+ for (const refFile of refFiles) {
214
+ const sourcePath = join2(refTemplateDir, refFile);
215
+ let source;
216
+ try {
217
+ source = readFileSync2(sourcePath, "utf8");
218
+ } catch (error) {
219
+ results.push({
220
+ step: "skill-ref",
221
+ path: sourcePath,
222
+ status: "error",
223
+ message: error instanceof Error ? error.message : String(error)
224
+ });
225
+ continue;
226
+ }
227
+ for (const prefix of clientPrefixes) {
228
+ const target = join2(projectRoot, prefix, "skills", skillSlug, "ref", refFile);
229
+ results.push(await copyTextIdempotent("skill-ref", source, target));
230
+ }
231
+ }
169
232
  return results;
170
233
  }
171
234
  async function installArchiveHintHook(projectRoot, _options = {}) {
@@ -513,9 +576,83 @@ async function copyTextIdempotent(step, source, target) {
513
576
  await atomicWriteText2(target, source);
514
577
  return { step, path: target, status: "written" };
515
578
  }
579
+ var FABRIC_HOOK_SCRIPT_BASENAMES = /* @__PURE__ */ new Set([
580
+ "fabric-hint.cjs",
581
+ "knowledge-hint-broad.cjs",
582
+ "knowledge-hint-narrow.cjs",
583
+ // rc.5 TASK-010 rename — old hook scripts that pre-upgrade workspaces
584
+ // may still have registered. Sweeping them prevents the double-fire
585
+ // documented in audit §2.6.
586
+ "archive-hint.cjs"
587
+ ]);
588
+ function commandBasename(command) {
589
+ const trimmed = command.trim().replace(/^"+|"+$/g, "");
590
+ const match = /([^/\\]+\.cjs)$/u.exec(trimmed);
591
+ return match === null ? null : match[1];
592
+ }
593
+ function stripStaleHookEntries(existing, arrayAppendPaths) {
594
+ const swept = JSON.parse(JSON.stringify(existing));
595
+ let removed = 0;
596
+ for (const dottedPath of arrayAppendPaths) {
597
+ const segments = dottedPath.split(".");
598
+ let cursor = swept;
599
+ for (let i = 0; i < segments.length - 1; i++) {
600
+ const seg = segments[i];
601
+ if (cursor === null || typeof cursor !== "object" || Array.isArray(cursor)) {
602
+ cursor = void 0;
603
+ break;
604
+ }
605
+ cursor = cursor[seg];
606
+ }
607
+ if (cursor === null || cursor === void 0 || typeof cursor !== "object" || Array.isArray(cursor)) {
608
+ continue;
609
+ }
610
+ const finalSeg = segments[segments.length - 1];
611
+ const arr = cursor[finalSeg];
612
+ if (!Array.isArray(arr)) continue;
613
+ const filtered = [];
614
+ for (const item of arr) {
615
+ if (item === null || typeof item !== "object") {
616
+ filtered.push(item);
617
+ continue;
618
+ }
619
+ const entry = item;
620
+ const hooks = entry.hooks;
621
+ let isFabricOwned = false;
622
+ if (Array.isArray(hooks)) {
623
+ for (const h of hooks) {
624
+ if (h !== null && typeof h === "object") {
625
+ const cmd = h.command;
626
+ if (typeof cmd === "string") {
627
+ const base = commandBasename(cmd);
628
+ if (base !== null && FABRIC_HOOK_SCRIPT_BASENAMES.has(base)) {
629
+ isFabricOwned = true;
630
+ break;
631
+ }
632
+ }
633
+ }
634
+ }
635
+ }
636
+ if (!isFabricOwned && typeof entry.command === "string") {
637
+ const base = commandBasename(entry.command);
638
+ if (base !== null && FABRIC_HOOK_SCRIPT_BASENAMES.has(base)) {
639
+ isFabricOwned = true;
640
+ }
641
+ }
642
+ if (isFabricOwned) {
643
+ removed += 1;
644
+ } else {
645
+ filtered.push(item);
646
+ }
647
+ }
648
+ cursor[finalSeg] = filtered;
649
+ }
650
+ return { swept, removed };
651
+ }
516
652
  async function mergeJsonIdempotent(step, target, fragment, arrayAppendPaths) {
517
653
  const existing = await readJsonObjectOrEmpty(target);
518
- const merged = deepMerge(existing, fragment, { arrayAppendPaths });
654
+ const { swept } = stripStaleHookEntries(existing, arrayAppendPaths);
655
+ const merged = deepMerge(swept, fragment, { arrayAppendPaths });
519
656
  if (jsonEqual(existing, merged)) {
520
657
  return { step, path: target, status: "skipped", message: "up-to-date" };
521
658
  }
package/dist/index.js CHANGED
@@ -11,12 +11,12 @@ import { defineCommand, runMain } from "citty";
11
11
 
12
12
  // src/commands/index.ts
13
13
  var allCommands = {
14
- install: () => import("./install-3MWBW6N7.js").then((module) => module.default),
14
+ install: () => import("./install-MPSTI654.js").then((module) => module.default),
15
15
  doctor: () => import("./doctor-ZIQXN2T2.js").then((module) => module.default),
16
16
  serve: () => import("./serve-U3TPWDOB.js").then((module) => module.default),
17
- uninstall: () => import("./uninstall-SUSIZHGL.js").then((module) => module.default),
17
+ uninstall: () => import("./uninstall-VLLJG7JT.js").then((module) => module.default),
18
18
  config: () => import("./config-5CH4EJQ2.js").then((module) => module.default),
19
- "plan-context-hint": () => import("./plan-context-hint-KPGOW3QC.js").then((module) => module.default),
19
+ "plan-context-hint": () => import("./plan-context-hint-CXTLNVSV.js").then((module) => module.default),
20
20
  // v2.0.0-rc.23 TASK-014 (F8c): S5 onboard-slot coverage. Used by the
21
21
  // fabric-archive Skill's first-run phase to detect unclaimed slots.
22
22
  "onboard-coverage": () => import("./onboard-coverage-JJ5NGU7I.js").then((module) => module.default)
@@ -26,7 +26,7 @@ var allCommands = {
26
26
  var main = defineCommand({
27
27
  meta: {
28
28
  name: "fabric",
29
- version: "2.0.0-rc.26",
29
+ version: "2.0.0-rc.28",
30
30
  description: t("cli.main.description")
31
31
  },
32
32
  subCommands: allCommands
@@ -18,7 +18,7 @@ import {
18
18
  writeCodexBootstrapManagedBlock,
19
19
  writeCursorBootstrapManagedBlock,
20
20
  writeFabricAgentsSnapshot
21
- } from "./chunk-AXKII55Y.js";
21
+ } from "./chunk-PNRWNUFX.js";
22
22
  import {
23
23
  detectClientSupports
24
24
  } from "./chunk-MF3OTILQ.js";
@@ -1348,7 +1348,7 @@ function readProjectName(target) {
1348
1348
  return basename(target);
1349
1349
  }
1350
1350
  function getCliVersion() {
1351
- return true ? "2.0.0-rc.26" : "unknown";
1351
+ return true ? "2.0.0-rc.28" : "unknown";
1352
1352
  }
1353
1353
  function sortRecord(record) {
1354
1354
  return Object.fromEntries(Object.entries(record).sort(([left], [right]) => left.localeCompare(right)));
@@ -70,14 +70,29 @@ async function runPlanContextHint(opts) {
70
70
  id: item.stable_id,
71
71
  type: item.type ?? item.description.knowledge_type ?? "",
72
72
  maturity: item.maturity ?? item.description.maturity ?? "",
73
- summary: item.description.summary
73
+ summary: item.description.summary,
74
+ // v2.0.0-rc.27 TASK-002 (§2.5/§2.7): forward the server-side scope.
75
+ // RuleDescriptionIndexItem already carries this field — knowledge-meta-
76
+ // builder defaults to "broad" for entries without an explicit
77
+ // relevance_scope frontmatter, so this read is total and never undefined.
78
+ relevance_scope: item.relevance_scope ?? "broad"
74
79
  }));
80
+ let narrow_count = 0;
81
+ let broad_only_count = 0;
82
+ for (const e of entries) {
83
+ if (e.relevance_scope === "narrow") narrow_count += 1;
84
+ else broad_only_count += 1;
85
+ }
75
86
  const output = {
76
87
  version: 2,
77
88
  revision_hash: result.revision_hash,
78
89
  target_paths: targetPaths,
79
90
  entries,
80
- broad_count: sharedIndex.length
91
+ // Legacy field — preserved for v2 consumers that haven't migrated. Value
92
+ // semantics unchanged from rc.18 (sharedIndex total).
93
+ broad_count: sharedIndex.length,
94
+ narrow_count,
95
+ broad_only_count
81
96
  };
82
97
  if (result.auto_healed === true) {
83
98
  output.auto_healed = true;
@@ -7,7 +7,7 @@ import {
7
7
  HOOK_SCRIPT_DESTINATIONS,
8
8
  SKILL_DESTINATIONS,
9
9
  fabricAgentsSnapshotPath
10
- } from "./chunk-AXKII55Y.js";
10
+ } from "./chunk-PNRWNUFX.js";
11
11
  import {
12
12
  detectClientSupports,
13
13
  resolveClients
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fenglimg/fabric-cli",
3
- "version": "2.0.0-rc.26",
3
+ "version": "2.0.0-rc.28",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "fab": "dist/index.js",
@@ -20,8 +20,8 @@
20
20
  "tree-sitter-javascript": "^0.25.0",
21
21
  "tree-sitter-typescript": "^0.23.2",
22
22
  "web-tree-sitter": "^0.26.8",
23
- "@fenglimg/fabric-server": "2.0.0-rc.26",
24
- "@fenglimg/fabric-shared": "2.0.0-rc.26"
23
+ "@fenglimg/fabric-server": "2.0.0-rc.28",
24
+ "@fenglimg/fabric-shared": "2.0.0-rc.28"
25
25
  },
26
26
  "devDependencies": {
27
27
  "@types/node": "^22.15.0",
@@ -477,14 +477,49 @@ function getTopEditedDirectories(projectRoot, topN, anchorTs) {
477
477
  // any leading "./". POSIX-style only — the hook ships under POSIX
478
478
  // path conventions even on Windows (the project doesn't currently
479
479
  // ship a CRLF/backslash test matrix for the sidecar).
480
- const norm = p.replace(/\\/g, "/").replace(/^\.\//, "");
480
+ //
481
+ // v2.0.0-rc.27 TASK-005 (audit §2.8 leak surface): absolute paths
482
+ // already accumulated in legacy sidecars start with `/`. We strip
483
+ // the leading slash and also reject buckets that resolve to user-home
484
+ // segments (`Users/<name>/...`, `home/<name>/...`) so historical
485
+ // pollution from absolute-path writes doesn't surface the user's
486
+ // $HOME in the archive banner. The rc.27 appendEditCounter no longer
487
+ // writes such paths, but the sidecar is append-only so old lines
488
+ // persist until rotation.
489
+ let norm = p.replace(/\\/g, "/").replace(/^\.\//, "");
490
+ // Strip leading `/` so a stale absolute entry doesn't generate a leak.
491
+ while (norm.startsWith("/")) norm = norm.slice(1);
481
492
  const segs = norm.split("/").filter((s) => s.length > 0);
493
+ // Reject any bucket whose top segments look like a host-system home
494
+ // prefix. The pattern is `<top>/<user>/...` where top ∈ Users|home|root.
495
+ // This silently drops legacy absolute-path entries from $HOME without
496
+ // mangling the buckets for legitimate project-relative `Users/...`
497
+ // (unlikely but possible) — the heuristic favours $HOME leak prevention
498
+ // over false-positive bucketing of project paths named after Unix
499
+ // conventions.
500
+ if (segs.length >= 2 && (segs[0] === "Users" || segs[0] === "home" || segs[0] === "root")) {
501
+ continue;
502
+ }
503
+ // v2.0.0-rc.27 TASK-005 (audit §2.8 file-as-dir): when segs[1] looks
504
+ // like a file (contains a dot-extension at the end), surface segs[0]
505
+ // alone instead of `segs[0]/segs[1]/` — a 2-seg path of the form
506
+ // `assets/foo.ts` would otherwise render as "assets/foo.ts/" which
507
+ // misleads the operator about whether they're seeing a file or a
508
+ // directory. The extension regex is permissive: any `.X` where X is
509
+ // 1-8 alphanumerics counts. README.md / package.json / foo.ts all
510
+ // match; "v1.2" or "dotted.module" do too — acceptable false-positive
511
+ // rate, since the worst outcome is over-aggregation to the parent.
512
+ const looksLikeFile = (segment) => /\.[A-Za-z0-9]{1,8}$/u.test(segment);
482
513
  let bucket;
483
514
  if (segs.length >= 2) {
484
- // Leading 2 segments: "packages/cli", "docs/decisions", etc. We
485
- // trail with "/" so the banner reads "packages/cli/" — clearly a
486
- // directory rather than a file basename.
487
- bucket = `${segs[0]}/${segs[1]}/`;
515
+ if (looksLikeFile(segs[1])) {
516
+ bucket = `${segs[0]}/`;
517
+ } else {
518
+ // Leading 2 segments: "packages/cli", "docs/decisions", etc. We
519
+ // trail with "/" so the banner reads "packages/cli/" — clearly a
520
+ // directory rather than a file basename.
521
+ bucket = `${segs[0]}/${segs[1]}/`;
522
+ }
488
523
  } else if (segs.length === 1) {
489
524
  // Single segment — treat the basename as its own bucket. Bare
490
525
  // root-level files (README.md, package.json) get some signal too.
@@ -653,13 +688,25 @@ function decide(events, now, pendingStats, underseedStats, editCounterStats, thr
653
688
  // - "<editCount> 次编辑"
654
689
  // - "阈值 <N>"
655
690
  // - "fabric-archive"
691
+ // v2.0.0-rc.27 TASK-005 (audit §2.17): parts now assembled per-variant
692
+ // via banner-i18n's archivePartsHours / archivePartsEdits so en mode
693
+ // gets fully-English fragments instead of mixed-language output. zh-CN
694
+ // / zh-CN-hybrid still render the original substring contract verbatim.
656
695
  const parts = [];
657
696
  if (triggerByHours) {
658
- parts.push(`已过 ${hoursElapsed.toFixed(1)}h(阈值 ${archiveHintHours}h)`);
697
+ parts.push(
698
+ renderBanner("archivePartsHours", variant, {
699
+ hoursFixed: hoursElapsed.toFixed(1),
700
+ threshold: archiveHintHours,
701
+ }),
702
+ );
659
703
  }
660
704
  if (triggerByEdits) {
661
705
  parts.push(
662
- `累计 ${editStats.editsSinceLastProposed} 次编辑(阈值 ${editStats.threshold})`,
706
+ renderBanner("archivePartsEdits", variant, {
707
+ count: editStats.editsSinceLastProposed,
708
+ threshold: editStats.threshold,
709
+ }),
663
710
  );
664
711
  }
665
712
  // rc.16 TASK-002: 5-banner i18n via lib/banner-i18n.cjs. Substring
@@ -1236,11 +1283,21 @@ function summarizeTranscript(transcriptPath) {
1236
1283
  if (envelope === null || typeof envelope !== "object") continue;
1237
1284
  envelopeIndex += 1;
1238
1285
 
1239
- // User text message — Claude Code shape: { role: "user", content: [...] }
1240
- // OR nested under `message.role`. Be generous.
1241
- const role = envelope.role || (envelope.message && envelope.message.role);
1286
+ // v2.0.0-rc.27 TASK-009 (audit §2.16): Codex CLI uses a different
1287
+ // envelope shape { type:"response_item", payload:{ type:"message",
1288
+ // role, content:[{type:"input_text"|"output_text", text}] } } vs Claude
1289
+ // Code's { type:"user", message:{ role, content } }. Resolve role +
1290
+ // content from whichever shape is present; without this, every Codex
1291
+ // session's digest came out empty (audit §2.16 — fixed here).
1292
+ const role =
1293
+ envelope.role ||
1294
+ (envelope.message && envelope.message.role) ||
1295
+ (envelope.payload && envelope.payload.role);
1242
1296
  if (role === "user") {
1243
- const content = envelope.content || (envelope.message && envelope.message.content);
1297
+ const content =
1298
+ envelope.content ||
1299
+ (envelope.message && envelope.message.content) ||
1300
+ (envelope.payload && envelope.payload.content);
1244
1301
  if (typeof content === "string") {
1245
1302
  out.user_messages.push(content);
1246
1303
  } else if (Array.isArray(content)) {
@@ -1257,7 +1314,10 @@ function summarizeTranscript(transcriptPath) {
1257
1314
  // entry per assistant envelope (even when no KB: line) so downstream can
1258
1315
  // distinguish "turn observed, no KB" (kb_line_raw=null) from "no turn".
1259
1316
  if (role === "assistant") {
1260
- const content = envelope.content || (envelope.message && envelope.message.content);
1317
+ const content =
1318
+ envelope.content ||
1319
+ (envelope.message && envelope.message.content) ||
1320
+ (envelope.payload && envelope.payload.content);
1261
1321
  let firstText = null;
1262
1322
  if (typeof content === "string") {
1263
1323
  firstText = content;
@@ -1277,6 +1337,17 @@ function summarizeTranscript(transcriptPath) {
1277
1337
  // with cite_ids). Sentinel `KB: none` contributes a `cite_tags=["none"]`
1278
1338
  // entry but no commitment — matches the parseCiteLine index contract.
1279
1339
  let citeCommitments = [];
1340
+ // v2.0.0-rc.27 TASK-009: Codex assistant blocks carry text under
1341
+ // `type:"output_text"` (not `type:"text"`). Fall back when no text-typed
1342
+ // block matched but a typed output_text block exists.
1343
+ if (firstText === null && Array.isArray(content)) {
1344
+ for (const block of content) {
1345
+ if (block && typeof block === "object" && block.type === "output_text" && typeof block.text === "string") {
1346
+ firstText = block.text;
1347
+ break;
1348
+ }
1349
+ }
1350
+ }
1280
1351
  if (typeof firstText === "string" && firstText.length > 0) {
1281
1352
  // First non-empty line.
1282
1353
  const linesOfText = firstText.split(/\r?\n/);
@@ -1342,6 +1413,27 @@ function summarizeTranscript(transcriptPath) {
1342
1413
  }
1343
1414
  }
1344
1415
  }
1416
+
1417
+ // v2.0.0-rc.27 TASK-009 (audit §2.16): Codex apply_patch path. Codex
1418
+ // emits one response_item envelope per file-edit invocation with payload
1419
+ // shape { type:"custom_tool_call", name:"apply_patch", input:<patch
1420
+ // string> }. The patch body lists target files via `*** Update File:`,
1421
+ // `*** Add File:`, `*** Delete File:` directives — harvest those.
1422
+ if (
1423
+ envelope.type === "response_item" &&
1424
+ envelope.payload &&
1425
+ envelope.payload.type === "custom_tool_call" &&
1426
+ envelope.payload.name === "apply_patch" &&
1427
+ typeof envelope.payload.input === "string"
1428
+ ) {
1429
+ const patchInput = envelope.payload.input;
1430
+ const fileDirectiveRe = /^\*\*\*\s+(?:Update|Add|Delete)\s+File:\s+(.+?)\s*$/gm;
1431
+ let m;
1432
+ while ((m = fileDirectiveRe.exec(patchInput)) !== null) {
1433
+ const fp = m[1].trim();
1434
+ if (fp.length > 0) out.edit_paths.push(fp);
1435
+ }
1436
+ }
1345
1437
  }
1346
1438
  // 1-line title = first non-empty user message (trimmed). Falls back to "".
1347
1439
  if (out.user_messages.length > 0) {
@@ -267,8 +267,34 @@ function appendEditCounter(projectRoot, now, paths) {
267
267
  mkdirSync(dir, { recursive: true });
268
268
  }
269
269
  const iso = now instanceof Date ? now.toISOString() : new Date(now).toISOString();
270
+ // v2.0.0-rc.27 TASK-005 (audit §2.8): normalize every path to a
271
+ // project-relative form BEFORE persistence. rc.26 wrote whatever the
272
+ // tool_input handed in — frequently absolute paths like
273
+ // `/Users/wepie/.../foo.ts` — which then leaked into the archive banner's
274
+ // "recent activity centered on: Users/wepie/" prose (the dirname pass
275
+ // stripped the leading `/` but produced a $HOME-prefix surface). The
276
+ // normalize-on-write keeps the sidecar containing only project-internal
277
+ // paths so downstream banner rendering can't accidentally surface
278
+ // host-system paths.
279
+ //
280
+ // Strategy: for each path, attempt path.relative(projectRoot, abs). When
281
+ // the result starts with `..` (path is outside the project tree) we
282
+ // silently drop the entry — out-of-tree edits are not meaningful
283
+ // activity for THIS project's banner. Bare relative paths (already in
284
+ // canonical form) round-trip through relative() unchanged.
285
+ const { isAbsolute: pathIsAbsolute, relative: pathRelative } = require("node:path");
270
286
  const pathList = Array.isArray(paths)
271
- ? paths.filter((p) => typeof p === "string" && p.length > 0)
287
+ ? paths
288
+ .filter((p) => typeof p === "string" && p.length > 0)
289
+ .map((p) => {
290
+ if (pathIsAbsolute(p)) {
291
+ const rel = pathRelative(projectRoot, p);
292
+ // path.relative returns `..` segments when p escapes projectRoot.
293
+ return rel.startsWith("..") ? null : rel;
294
+ }
295
+ return p;
296
+ })
297
+ .filter((p) => typeof p === "string" && p.length > 0)
272
298
  : [];
273
299
  const line = JSON.stringify({ ts: iso, paths: pathList });
274
300
  appendFileSync(file, `${line}\n`, "utf8");
@@ -723,7 +749,20 @@ function main(env, stdio) {
723
749
  if (cliPayload === null || cliPayload === undefined) return;
724
750
 
725
751
  // Protocol v2 (rc.18 TASK-005): wire field is `entries`, no v1 shim.
726
- const narrow = Array.isArray(cliPayload.entries) ? cliPayload.entries : [];
752
+ //
753
+ // v2.0.0-rc.27 TASK-005 (audit §2.5/§2.7): filter to entries whose
754
+ // `relevance_scope === "narrow"` so broad cross-cutting entries do NOT
755
+ // pollute the PreToolUse banner. rc.26 emitted broad + narrow as a
756
+ // single list — every Edit fired a hint even for paths the entry never
757
+ // anchored against (audit §2.5 reproduction). Broad entries are already
758
+ // surfaced once per session by the SessionStart hook so the PreToolUse
759
+ // surface should be narrow-only by design.
760
+ //
761
+ // Defensive default: when the CLI omits `relevance_scope` (older server
762
+ // / malformed item) we treat it as broad and skip — pre-rc.27 entries
763
+ // without the field are exactly the broad-leak surface §2.5 calls out.
764
+ const allEntries = Array.isArray(cliPayload.entries) ? cliPayload.entries : [];
765
+ const narrow = allEntries.filter((entry) => entry && entry.relevance_scope === "narrow");
727
766
  if (narrow.length === 0) {
728
767
  // rc.6 TASK-023 (E6): silence-counter — matched-narrow == 0. The CLI
729
768
  // had a chance to match against the extracted paths but came back
@@ -116,12 +116,39 @@ const STRINGS = {
116
116
  // ---- Signal A: archive ----------------------------------------------------
117
117
  // Source (zh-CN): fabric-hint.cjs:614 `📋 Fabric: 距上次归档 ${parts}。`
118
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).
119
127
  archiveLine1: {
120
128
  "zh-CN": (p) => `📋 Fabric: 距上次归档 ${p.parts}。`,
121
129
  en: (p) => `📋 Fabric: ${p.parts} since last archive.`,
122
130
  "zh-CN-hybrid": (p) => `📋 Fabric: 距上次归档 ${p.parts}。`,
123
131
  },
124
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
+
125
152
  // Source (zh-CN): fabric-hint.cjs:619 ` 最近活动集中在: ${activity}。`
126
153
  // params: { activity }
127
154
  archiveActivity: {
@@ -28,8 +28,11 @@
28
28
 
29
29
  const ID_RE = /^K[TP]-[A-Z]+-\d+$/;
30
30
  const SENTINEL_RE = /^KB:\s*none\b\s*(?:\[[^\]]*\])?\s*$/i;
31
+ // v2.0.0-rc.27 TASK-003 (audit §2.18): multi-id citations supported via
32
+ // comma-separated ID group. Mirrors packages/shared/src/cite-line-parser.ts.
31
33
  const FULL_RE =
32
- /^KB:\s+(K[TP]-[A-Z]+-\d+)(?:\s+\(([^)]*)\))?(?:\s+\[([^\]]+)\])?(?:\s+→\s*(.+))?\s*$/;
34
+ /^KB:\s+(K[TP]-[A-Z]+-\d+(?:\s*,\s*K[TP]-[A-Z]+-\d+)*)(?:\s+\(([^)]*)\))?(?:\s+\[([^\]]+)\])?(?:\s+→\s*(.+))?\s*$/;
35
+ const CHAINED_FROM_ID_RE = /chained-from\s+(K[TP]-[A-Z]+-\d+)/i;
33
36
 
34
37
  const ALLOWED_TAGS = new Set([
35
38
  "planned",
@@ -80,15 +83,32 @@ function parseLine(line) {
80
83
  const trimmed = line.trim();
81
84
  if (trimmed.length === 0) return null;
82
85
  if (SENTINEL_RE.test(trimmed)) {
83
- return { id: null, tag: "none", commitment: null };
86
+ return { ids: [], tag: "none", commitment: null };
84
87
  }
85
88
  const fullMatch = trimmed.match(FULL_RE);
86
89
  if (fullMatch) {
87
- const id = fullMatch[1];
88
- if (!ID_RE.test(id)) return null;
90
+ // v2.0.0-rc.27 TASK-003 (audit §2.18): split + revalidate each id;
91
+ // capture chained-from tail id when present.
92
+ const primaryIds = fullMatch[1]
93
+ .split(",")
94
+ .map((part) => part.trim())
95
+ .filter((part) => part.length > 0);
96
+ if (primaryIds.some((id) => !ID_RE.test(id))) return null;
97
+
98
+ const rawTag = fullMatch[3];
99
+ const tag = parseTag(rawTag);
100
+
101
+ const chainedIds = [];
102
+ if (rawTag) {
103
+ const chained = CHAINED_FROM_ID_RE.exec(rawTag);
104
+ if (chained && ID_RE.test(chained[1])) {
105
+ chainedIds.push(chained[1]);
106
+ }
107
+ }
108
+
89
109
  return {
90
- id,
91
- tag: parseTag(fullMatch[3]),
110
+ ids: primaryIds.concat(chainedIds),
111
+ tag,
92
112
  commitment: parseContractTail(fullMatch[4]),
93
113
  };
94
114
  }
@@ -99,6 +119,10 @@ function parseLine(line) {
99
119
  * Parse one or more newline-separated `KB:` cite lines into structured arrays
100
120
  * matching the assistant_turn_observed event-ledger fields. Tolerates
101
121
  * whitespace, CR/LF, blank lines, interleaved prose. Never throws.
122
+ *
123
+ * v2.0.0-rc.27 TASK-003 (audit §2.18): supports multi-id citations
124
+ * (`KB: KT-DEC-0001, KT-PIT-0005 ...`) and surfaces `chained-from <id>`'s
125
+ * embedded id as an additional cite_id. cite_tags carries one tag per LINE.
102
126
  */
103
127
  function parseCiteLine(raw) {
104
128
  const result = { cite_ids: [], cite_tags: [], cite_commitments: [] };
@@ -107,9 +131,19 @@ function parseCiteLine(raw) {
107
131
  const parsed = parseLine(line);
108
132
  if (!parsed) continue;
109
133
  result.cite_tags.push(parsed.tag);
110
- if (parsed.id !== null) result.cite_ids.push(parsed.id);
134
+ for (const id of parsed.ids) {
135
+ result.cite_ids.push(id);
136
+ }
111
137
  if (parsed.commitment !== null) {
112
- result.cite_commitments.push(parsed.commitment);
138
+ // v2.0.0-rc.27.1 (Codex review fix): cite_commitments MUST be index-
139
+ // aligned with cite_ids per the schema doc on event-ledger.ts:428.
140
+ // Multi-id citations share ONE parsed contract — propagate it across
141
+ // every id slot so downstream consumers (`doctor.ts` per-cite walk +
142
+ // `cite-contract-reminder.cjs`) can look up `commitments[i]` for any
143
+ // valid `i < cite_ids.length` without falling into an undefined slot.
144
+ for (let i = 0; i < parsed.ids.length; i += 1) {
145
+ result.cite_commitments.push(parsed.commitment);
146
+ }
113
147
  }
114
148
  }
115
149
  return result;