ntn-skills 2.0.2 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js CHANGED
@@ -85,6 +85,7 @@ var ExportRouterConfigSchema = Schema.Struct({
85
85
  enabled: Schema.Boolean,
86
86
  name: Schema.optional(Schema.String)
87
87
  });
88
+ var SkillBundlesSchema = Schema.Record(Schema.String, Schema.Array(Schema.String));
88
89
  var ExportTargetSchema = Schema.Struct({
89
90
  dir: Schema.String,
90
91
  profiles: Schema.optional(Schema.Array(Schema.String)),
@@ -92,15 +93,44 @@ var ExportTargetSchema = Schema.Struct({
92
93
  default_only: Schema.optional(Schema.Boolean),
93
94
  include_non_default: Schema.optional(Schema.Boolean),
94
95
  include_all: Schema.optional(Schema.Boolean),
96
+ skills: Schema.optional(Schema.Array(Schema.String)),
97
+ bundles: Schema.optional(Schema.Array(Schema.String)),
98
+ exclude: Schema.optional(Schema.Array(Schema.String)),
99
+ include_requires: Schema.optional(Schema.Boolean),
95
100
  router: Schema.optional(ExportRouterConfigSchema),
96
101
  mode: Schema.Literals(["symlink", "copy"])
97
102
  });
103
+ var ExportSpecTargetSchema = Schema.Struct({
104
+ dir: Schema.String,
105
+ profiles: Schema.optional(Schema.Array(Schema.String)),
106
+ scenes: Schema.optional(Schema.Array(Schema.String)),
107
+ default_only: Schema.optional(Schema.Boolean),
108
+ include_non_default: Schema.optional(Schema.Boolean),
109
+ include_all: Schema.optional(Schema.Boolean),
110
+ skills: Schema.optional(Schema.Array(Schema.String)),
111
+ bundles: Schema.optional(Schema.Array(Schema.String)),
112
+ exclude: Schema.optional(Schema.Array(Schema.String)),
113
+ include_requires: Schema.optional(Schema.Boolean),
114
+ router: Schema.optional(ExportRouterConfigSchema),
115
+ mode: Schema.optional(Schema.Literals(["symlink", "copy"]))
116
+ });
117
+ var ExportSpecObjectSchema = Schema.Struct({
118
+ bundles: Schema.optional(SkillBundlesSchema),
119
+ exports: Schema.Array(ExportSpecTargetSchema)
120
+ });
121
+ var ExportSpecFileSchema = Schema.Union([
122
+ ExportSpecObjectSchema,
123
+ Schema.Array(ExportSpecTargetSchema),
124
+ ExportSpecTargetSchema
125
+ ]);
98
126
  var ConfigFileSchema = Schema.Struct({
99
127
  version: Schema.Literal(2),
100
128
  default_library: Schema.String,
101
129
  libraries: Schema.Record(Schema.String, LibraryBindingSchema),
102
130
  profiles: Schema.optional(Schema.Array(Schema.String)),
103
131
  prefetch: Schema.optional(Schema.Literals(["exports-only", "discoverable", "all-profiles"])),
132
+ bundles: Schema.optional(SkillBundlesSchema),
133
+ include_exports: Schema.optional(Schema.Array(Schema.String)),
104
134
  exports: Schema.Array(ExportTargetSchema)
105
135
  });
106
136
  var CatalogFileOverlaySchema = Schema.Struct({
@@ -204,6 +234,9 @@ function normalizeUuid(raw) {
204
234
  function libShortHash(libraryId) {
205
235
  return normalizeUuid(libraryId).replace(/-/g, "").slice(0, 8);
206
236
  }
237
+ function normalizeSkillSlug(raw) {
238
+ return raw.trim().toLowerCase().replace(/[\s_]+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
239
+ }
207
240
  function computeOverlapWindowIso(watermarkIso, overlapMs = 120000) {
208
241
  const ms = Date.parse(watermarkIso);
209
242
  if (Number.isNaN(ms)) {
@@ -230,17 +263,32 @@ function parseSkillFrontmatter(markdown) {
230
263
  `);
231
264
  if (!normalized.startsWith(`---
232
265
  `) && normalized !== "---") {
233
- return { extraLines: [], body: normalized, hasFrontmatter: false };
266
+ return {
267
+ disableModelInvocation: false,
268
+ extraLines: [],
269
+ body: normalized,
270
+ hasFrontmatter: false
271
+ };
234
272
  }
235
273
  const closeIdx = normalized.indexOf(`
236
274
  ---`, 3);
237
275
  if (closeIdx < 0) {
238
- return { extraLines: [], body: normalized, hasFrontmatter: false };
276
+ return {
277
+ disableModelInvocation: false,
278
+ extraLines: [],
279
+ body: normalized,
280
+ hasFrontmatter: false
281
+ };
239
282
  }
240
283
  const afterClose = closeIdx + 4;
241
284
  if (afterClose < normalized.length && normalized[afterClose] !== `
242
285
  `) {
243
- return { extraLines: [], body: normalized, hasFrontmatter: false };
286
+ return {
287
+ disableModelInvocation: false,
288
+ extraLines: [],
289
+ body: normalized,
290
+ hasFrontmatter: false
291
+ };
244
292
  }
245
293
  const fmBlock = normalized.slice(4, closeIdx);
246
294
  const restBody = normalized.slice(afterClose).replace(/^\n+/, "");
@@ -248,11 +296,12 @@ function parseSkillFrontmatter(markdown) {
248
296
  `);
249
297
  let name;
250
298
  let description;
299
+ let disableModelInvocation = false;
251
300
  const extraLines = [];
252
301
  let i = 0;
253
302
  while (i < lines.length) {
254
303
  const line = lines[i];
255
- const keyMatch = line.match(/^([A-Za-z0-9_-]+|"[^"]+")\s*:\s*(.*)$/);
304
+ const keyMatch = line.match(/^([A-Za-z0-9_-]+|"[^"]+"|'[^']+')\s*:\s*(.*)$/);
256
305
  if (!keyMatch) {
257
306
  if (line.trim().length > 0)
258
307
  extraLines.push(line);
@@ -281,12 +330,17 @@ function parseSkillFrontmatter(markdown) {
281
330
  description = unquoteYamlScalar(rhs);
282
331
  }
283
332
  } else {
333
+ if (rawKey === "disable-model-invocation") {
334
+ const scalar = rhs.replace(/\s+#.*$/, "").trim();
335
+ disableModelInvocation = /^['"]?(true|yes|1)['"]?$/i.test(scalar);
336
+ }
284
337
  extraLines.push(...blockLines);
285
338
  }
286
339
  }
287
340
  return {
288
341
  ...name !== undefined ? { name } : {},
289
342
  ...description !== undefined ? { description } : {},
343
+ disableModelInvocation,
290
344
  extraLines,
291
345
  body: restBody,
292
346
  hasFrontmatter: true
@@ -476,12 +530,156 @@ function selectDiscoverableSkills(catalogSkills, target) {
476
530
  return sk.visibility === "discoverable";
477
531
  });
478
532
  }
533
+ function matchesSkillNameOrSlug(skillName, query) {
534
+ const trimmed = query.trim();
535
+ if (!trimmed)
536
+ return false;
537
+ if (skillName.toLowerCase() === trimmed.toLowerCase())
538
+ return true;
539
+ const querySlug = normalizeSkillSlug(trimmed);
540
+ return querySlug.length > 0 && normalizeSkillSlug(skillName) === querySlug;
541
+ }
542
+ function findSkillByNameOrSlug(skills, query) {
543
+ const trimmed = query.trim();
544
+ if (!trimmed)
545
+ return;
546
+ const lower = trimmed.toLowerCase();
547
+ const exact = skills.find((sk) => sk.name.toLowerCase() === lower);
548
+ if (exact)
549
+ return exact;
550
+ const slug = normalizeSkillSlug(trimmed);
551
+ if (!slug)
552
+ return;
553
+ return skills.find((sk) => normalizeSkillSlug(sk.name) === slug);
554
+ }
555
+ function isSkillExcluded(skill, excludeList) {
556
+ if (!excludeList || excludeList.length === 0)
557
+ return false;
558
+ return excludeList.some((ex) => matchesSkillNameOrSlug(skill.name, ex));
559
+ }
560
+ function expandBundlesAndSkills(target, bundles) {
561
+ const explicitNames = [];
562
+ const seenNames = new Set;
563
+ const missingBundles = [];
564
+ const seenMissingBundles = new Set;
565
+ const visitedBundles = new Set;
566
+ const pushSkillName = (raw) => {
567
+ const trimmed = raw.trim();
568
+ if (!trimmed || seenNames.has(trimmed))
569
+ return;
570
+ seenNames.add(trimmed);
571
+ explicitNames.push(trimmed);
572
+ };
573
+ const hasBundle = (name) => Boolean(bundles && Object.prototype.hasOwnProperty.call(bundles, name));
574
+ const expandBundle = (rawBundleName) => {
575
+ const bundleName = rawBundleName.trim();
576
+ if (!bundleName || visitedBundles.has(bundleName))
577
+ return;
578
+ visitedBundles.add(bundleName);
579
+ if (!hasBundle(bundleName)) {
580
+ if (!seenMissingBundles.has(bundleName)) {
581
+ seenMissingBundles.add(bundleName);
582
+ missingBundles.push(bundleName);
583
+ }
584
+ return;
585
+ }
586
+ const items = bundles[bundleName] ?? [];
587
+ for (const rawItem of items) {
588
+ const item = rawItem.trim();
589
+ if (!item)
590
+ continue;
591
+ if (hasBundle(item) && item !== bundleName) {
592
+ expandBundle(item);
593
+ } else {
594
+ pushSkillName(item);
595
+ }
596
+ }
597
+ };
598
+ for (const b of target.bundles ?? []) {
599
+ expandBundle(b);
600
+ }
601
+ for (const s of target.skills ?? []) {
602
+ pushSkillName(s);
603
+ }
604
+ const isExplicitMode = target.skills !== undefined || target.bundles !== undefined || explicitNames.length > 0 || missingBundles.length > 0;
605
+ return { explicitNames, missingBundles, isExplicitMode };
606
+ }
607
+ function resolveExportSelection(input) {
608
+ const { allEffectiveSkills, catalogSkills, target, bundles } = input;
609
+ const effectiveById = new Map(allEffectiveSkills.map((sk) => [sk.id, sk]));
610
+ const expanded = expandBundlesAndSkills(target, bundles);
611
+ if (expanded.isExplicitMode) {
612
+ const seedIds = new Set;
613
+ const missingSkills = [];
614
+ const seenMissing = new Set;
615
+ for (const rawName of expanded.explicitNames) {
616
+ const matched = findSkillByNameOrSlug(allEffectiveSkills, rawName);
617
+ if (matched) {
618
+ seedIds.add(matched.id);
619
+ } else if (!seenMissing.has(rawName)) {
620
+ seenMissing.add(rawName);
621
+ missingSkills.push(rawName);
622
+ }
623
+ }
624
+ const shouldIncludeRequires = target.include_requires ?? true;
625
+ let selectedIds;
626
+ let missingOrDisabledRequires;
627
+ if (shouldIncludeRequires) {
628
+ const closure = computeRequiresClosure(seedIds, effectiveById);
629
+ selectedIds = closure.closureIds;
630
+ missingOrDisabledRequires = closure.missingOrDisabled;
631
+ } else {
632
+ selectedIds = seedIds;
633
+ missingOrDisabledRequires = new Map;
634
+ }
635
+ const selected = [...selectedIds].map((id) => effectiveById.get(id)).filter((sk) => Boolean(sk) && !isSkillExcluded(sk, target.exclude)).sort((a, b) => a.name.localeCompare(b.name));
636
+ const routerName = (target.router?.name ?? "skill-catalog").trim() || "skill-catalog";
637
+ const routerExcluded = Boolean(target.exclude?.some((ex) => matchesSkillNameOrSlug(routerName, ex)));
638
+ const resolvedRouterEnabled = !routerExcluded && (target.router ? target.router.enabled : false);
639
+ const discoverable = resolvedRouterEnabled ? catalogSkills.filter((sk) => matchesProfiles(sk.profiles, target.profiles) && sk.visibility === "discoverable" && !isSkillExcluded(sk, target.exclude)) : [];
640
+ return {
641
+ mode: "explicit",
642
+ selected,
643
+ discoverable,
644
+ missingSkills,
645
+ missingBundles: expanded.missingBundles,
646
+ missingOrDisabledRequires,
647
+ resolvedRouterEnabled
648
+ };
649
+ }
650
+ const baseSelected = selectExportSkills(catalogSkills, target);
651
+ let selectedCandidates;
652
+ let missingOrDisabledRequires;
653
+ if (target.include_requires === true) {
654
+ const closure = computeRequiresClosure(baseSelected.map((sk) => sk.id), effectiveById);
655
+ selectedCandidates = [...closure.closureIds].map((id) => effectiveById.get(id)).filter((sk) => Boolean(sk));
656
+ missingOrDisabledRequires = closure.missingOrDisabled;
657
+ } else {
658
+ selectedCandidates = baseSelected;
659
+ missingOrDisabledRequires = new Map;
660
+ }
661
+ const selected = selectedCandidates.filter((sk) => !isSkillExcluded(sk, target.exclude)).sort((a, b) => a.name.localeCompare(b.name));
662
+ const routerName = (target.router?.name ?? "skill-catalog").trim() || "skill-catalog";
663
+ const routerExcluded = Boolean(target.exclude?.some((ex) => matchesSkillNameOrSlug(routerName, ex)));
664
+ const resolvedRouterEnabled = !routerExcluded && target.router?.enabled !== false;
665
+ const discoverable = selectDiscoverableSkills(catalogSkills, target).filter((sk) => !isSkillExcluded(sk, target.exclude));
666
+ return {
667
+ mode: "filtered",
668
+ selected,
669
+ discoverable,
670
+ missingSkills: [],
671
+ missingBundles: [],
672
+ missingOrDisabledRequires,
673
+ resolvedRouterEnabled
674
+ };
675
+ }
479
676
  function sanitizeSceneSlug(raw) {
480
677
  const slug = raw.trim().toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
481
678
  return slug || "general";
482
679
  }
483
680
  function synthesizeSkillCatalogPackage(args) {
484
681
  const enc = new TextEncoder;
682
+ const normalizedByNameRoot = args.byNameRoot?.trim().replace(/\/+$/, "");
485
683
  const sorted = [...args.discoverableEntries].sort((a, b) => {
486
684
  if (a.kind === "router" && b.kind !== "router")
487
685
  return -1;
@@ -489,22 +687,13 @@ function synthesizeSkillCatalogPackage(args) {
489
687
  return 1;
490
688
  return a.name.localeCompare(b.name);
491
689
  });
492
- const formatHowToLoad = (e) => {
493
- if (e.materializedPath) {
494
- return `Read \`${e.materializedPath}/SKILL.md\``;
495
- }
496
- return `Run \`ntn-skills load "${e.name}" --path-only </dev/null\` then read \`<dir>/SKILL.md\``;
497
- };
498
690
  const formatEntryBullet = (e) => {
499
691
  const reqNames = e.requiresIds.map((id) => args.allEntriesById.get(id)?.name).filter((n) => Boolean(n));
500
692
  const kindBadge = e.kind === "router" ? " `[strategy-router]`" : "";
501
693
  const desc = e.description.replace(/\s+/g, " ").trim() || "(no description)";
502
- const lines = [`- **${e.name}**${kindBadge}: ${desc}`, ` - Entry: ${formatHowToLoad(e)}`];
503
- if (reqNames.length > 0) {
504
- lines.push(` - Requires: ${reqNames.map((n) => `\`${n}\``).join(", ")}`);
505
- }
506
- return lines.join(`
507
- `);
694
+ const reqSuffix = reqNames.length > 0 ? ` *(requires: ${reqNames.join(", ")})*` : "";
695
+ const unmaterializedSuffix = !e.materializedPath ? ` *(load via \`ntn-skills load "${e.name}" --path-only </dev/null\`)*` : "";
696
+ return `- **${e.name}**${kindBadge}: ${desc}${reqSuffix}${unmaterializedSuffix}`;
508
697
  };
509
698
  const groups = new Map;
510
699
  for (const e of sorted) {
@@ -524,15 +713,17 @@ function synthesizeSkillCatalogPackage(args) {
524
713
  });
525
714
  const files = [];
526
715
  const groupSummaryLines = [];
716
+ const sceneLoadLine = normalizedByNameRoot ? `Load a skill by reading \`${normalizedByNameRoot}/<name>/SKILL.md\`.` : 'Load a skill via `ntn-skills load "<name>" --path-only </dev/null` then read `<dir>/SKILL.md`.';
527
717
  for (const gk of orderedGroupKeys) {
528
718
  const items = groups.get(gk);
529
719
  const relPath = `references/${gk}.md`;
530
- const sampleNames = items.slice(0, 5).map((i) => `\`${i.name}\``).join(", ");
531
- groupSummaryLines.push(`| \`${gk}\` | ${items.length} | [references/${gk}.md](${relPath}) | ${sampleNames}${items.length > 5 ? ", ..." : ""} |`);
720
+ const previewCandidates = items.filter((i) => i.kind !== "router");
721
+ const sampleNames = previewCandidates.slice(0, 4).map((i) => i.name);
722
+ const sampleSuffix = sampleNames.length > 0 ? `: ${sampleNames.join(", ")}${previewCandidates.length > 4 ? "..." : ""}` : "";
723
+ groupSummaryLines.push(`- \`${relPath}\` (${items.length})${sampleSuffix}`);
532
724
  const refMd = [
533
- `# ${args.routerName} — ${gk} (${items.length})`,
534
- "",
535
- "Read the target skill's `SKILL.md` directly when a local `store/` path is listed, or materialize it on demand via `ntn-skills load`.",
725
+ `# ${gk} (${items.length})`,
726
+ sceneLoadLine,
536
727
  "",
537
728
  ...items.map(formatEntryBullet),
538
729
  ""
@@ -546,28 +737,28 @@ function synthesizeSkillCatalogPackage(args) {
546
737
  }
547
738
  const strategyRouters = sorted.filter((e) => e.kind === "router");
548
739
  const routerSection = strategyRouters.length > 0 ? [
549
- "## 1. Domain Strategy Routers (Check First)",
550
- "",
551
- ...strategyRouters.map(formatEntryBullet),
740
+ "## Strategy Routers",
741
+ ...strategyRouters.map((e) => {
742
+ const desc = e.description.replace(/\s+/g, " ").trim() || "(no description)";
743
+ const unmat = !e.materializedPath ? ` (run: ntn-skills load "${e.name}" --path-only </dev/null)` : "";
744
+ return `- **${e.name}**: ${desc}${unmat}`;
745
+ }),
552
746
  ""
553
747
  ] : [];
748
+ const topLoadInstruction = normalizedByNameRoot ? `Open the matching scene file below, then read \`${normalizedByNameRoot}/<name>/SKILL.md\`.` : 'Open the matching scene file below, then run `ntn-skills load "<name>" --path-only </dev/null` and read `<dir>/SKILL.md`.';
749
+ const byNameDescClause = normalizedByNameRoot ? `; skill files live at ${normalizedByNameRoot}/<name>/SKILL.md` : "";
750
+ const topDescription = `On-demand index of ${sorted.length} specialized skills by scene (${orderedGroupKeys.join(", ")})${byNameDescClause}. Read ONLY when top-level skills do not cover a specialized workflow/tool in these scenes; skip for routine coding/Q&A, or use skill_find directly if available.`;
554
751
  const mainMd = [
555
752
  "---",
556
753
  `name: ${JSON.stringify(args.routerName)}`,
557
- `description: ${JSON.stringify(`Local directory of ${sorted.length} discoverable on-demand skills grouped by domain/scene. Read this catalog whenever a task touches a specialized workflow, tool, or domain not covered by top-level always-visible skills.`)}`,
754
+ `description: ${JSON.stringify(topDescription)}`,
558
755
  "---",
559
756
  "",
560
- `# ${args.routerName} (${sorted.length} Discoverable Skills)`,
561
- "",
562
- "Use this local index to discover and load specialized skills without cluttering default context:",
563
- "1. Check **Strategy Routers** below (if any match your domain) or open the matching domain file under `references/`.",
564
- '2. Follow the **Entry** instruction for the chosen skill (`Read` its immutable `SKILL.md` path directly, or run `ntn-skills load "<name>" --path-only </dev/null` if not yet materialized).',
757
+ `# ${args.routerName} (${sorted.length})`,
758
+ topLoadInstruction,
565
759
  "",
566
760
  ...routerSection,
567
- "## Domain Index",
568
- "",
569
- "| Domain / Scene | Count | Index File | Highlights |",
570
- "| :--- | :---: | :--- | :--- |",
761
+ "## Scenes",
571
762
  ...groupSummaryLines,
572
763
  ""
573
764
  ].join(`
@@ -580,6 +771,79 @@ function synthesizeSkillCatalogPackage(args) {
580
771
  const effectiveRev = sha256Hex(JSON.stringify(files.map((f) => [f.path, sha256Hex(f.bytes)])));
581
772
  return { effectiveRev, files };
582
773
  }
774
+ function matchesAllowedScenes(entryScenes, allowedScenes) {
775
+ if (!allowedScenes || allowedScenes.length === 0)
776
+ return true;
777
+ const allowedLower = new Set(allowedScenes.map((s) => s.trim().toLowerCase()).filter(Boolean));
778
+ if (allowedLower.size === 0)
779
+ return true;
780
+ return entryScenes.some((s) => allowedLower.has(s.trim().toLowerCase()));
781
+ }
782
+ function formatSkillCatalogOverview(entries, options) {
783
+ const allowedScenes = (options?.allowedScenes ?? []).map((s) => s.trim()).filter(Boolean);
784
+ const allowedLower = allowedScenes.length > 0 ? new Set(allowedScenes.map((s) => s.toLowerCase())) : null;
785
+ if (entries.length === 0) {
786
+ return {
787
+ text: allowedScenes.length > 0 ? `Catalog is empty (scoped to scenes: ${allowedScenes.join(", ")}).` : "Catalog is empty.",
788
+ discoverableCount: 0,
789
+ totalCount: 0
790
+ };
791
+ }
792
+ const disc = entries.filter((e) => e.visibility === "discoverable");
793
+ const sceneCounts = new Map;
794
+ for (const e of disc) {
795
+ const rawScenes = e.scenes.length > 0 ? e.scenes : ["general"];
796
+ const scs = allowedLower ? rawScenes.filter((s) => allowedLower.has(s.trim().toLowerCase())) : rawScenes;
797
+ for (const s of scs) {
798
+ sceneCounts.set(s, (sceneCounts.get(s) ?? 0) + 1);
799
+ }
800
+ }
801
+ const summary = [...sceneCounts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([s, c]) => `${s} (${c})`).join(", ") || "(none)";
802
+ const scopePrefix = allowedScenes.length > 0 ? ` (scenes: ${allowedScenes.join(", ")})` : "";
803
+ const text = `Catalog overview${scopePrefix}: ${disc.length} discoverable skills (${entries.length} total) across scenes: ${summary}.
804
+ Pass \`query\` (keywords) and/or \`scene\` to search specific skills.`;
805
+ return {
806
+ text,
807
+ discoverableCount: disc.length,
808
+ totalCount: entries.length
809
+ };
810
+ }
811
+ function formatSkillFindResults(args) {
812
+ const rawLimit = typeof args.limit === "number" && Number.isFinite(args.limit) ? args.limit : 20;
813
+ const maxLimit = Math.min(50, Math.max(1, Math.floor(rawLimit)));
814
+ const shown = args.items.slice(0, maxLimit);
815
+ const fmt = (i) => {
816
+ const visTag = i.visibility !== "discoverable" ? ` [${i.visibility}]` : "";
817
+ const routerTag = i.kind === "router" ? " [router]" : "";
818
+ const sceneTag = !args.hasSceneFilter && i.scenes.length > 0 ? ` (${i.scenes.join(",")})` : "";
819
+ const flatDesc = i.description.replace(/\s+/g, " ").trim();
820
+ const shortDesc = flatDesc.length > 200 ? `${flatDesc.slice(0, 197)}...` : flatDesc;
821
+ return `- ${i.name}${visTag}${routerTag}${sceneTag}: ${shortDesc}`;
822
+ };
823
+ const lines = shown.length === 0 ? ["No matching skills found in catalog."] : shown.map(fmt);
824
+ if (args.items.length > maxLimit) {
825
+ lines.push(`... showing top ${maxLimit} of ${args.items.length} matches (narrow \`query\` or pass \`scene\`/\`visibility\`).`);
826
+ }
827
+ if (args.omittedManualCount && args.omittedManualCount > 0 && args.sceneName) {
828
+ lines.push(`(${args.omittedManualCount} manual skill(s) in scene '${args.sceneName}' omitted; pass \`query\` or \`visibility: "manual"\` to search them.)`);
829
+ }
830
+ return {
831
+ text: lines.join(`
832
+ `),
833
+ shownCount: shown.length,
834
+ totalCount: args.items.length
835
+ };
836
+ }
837
+ function formatLoadedSkillBlock(args) {
838
+ const pairs = Object.entries(args.requiresPaths ?? {}).map(([k, v]) => `${k}=${v}`);
839
+ const reqLine = pairs.length > 0 ? `
840
+ Requires: ${pairs.join(", ")}` : "";
841
+ return `<skill name="${args.name}" location="${args.dir}" path="${args.dir}">
842
+ References are relative to ${args.dir}.${reqLine}
843
+
844
+ ${args.markdown.trim()}
845
+ </skill>`;
846
+ }
583
847
  // packages/core/src/notion/markdown-blocks.ts
584
848
  var MAX_RICH_TEXT_CHARS = 1800;
585
849
  var MAX_RICH_TEXT_ITEMS = 95;
@@ -829,6 +1093,34 @@ function markdownToBlocks(markdown) {
829
1093
  i = endIdx + 1;
830
1094
  }
831
1095
  }
1096
+ let activeListParent = null;
1097
+ const computeLeadingIndent = (rawLine) => {
1098
+ let cols = 0;
1099
+ for (let k = 0;k < rawLine.length; k++) {
1100
+ const ch = rawLine[k];
1101
+ if (ch === " ")
1102
+ cols += 1;
1103
+ else if (ch === "\t")
1104
+ cols += 2;
1105
+ else
1106
+ break;
1107
+ }
1108
+ return cols;
1109
+ };
1110
+ const pushListItemBlock = (indent, type, block) => {
1111
+ if (activeListParent && indent > activeListParent.indent) {
1112
+ const parentPayload = activeListParent.block[activeListParent.type];
1113
+ if (!parentPayload.children) {
1114
+ parentPayload.children = [];
1115
+ }
1116
+ if (parentPayload.children.length < 95) {
1117
+ parentPayload.children.push(block);
1118
+ return;
1119
+ }
1120
+ }
1121
+ blocks.push(block);
1122
+ activeListParent = { indent, type, block };
1123
+ };
832
1124
  while (i < lines.length) {
833
1125
  const line = lines[i];
834
1126
  if (line.trim() === "") {
@@ -853,6 +1145,7 @@ function markdownToBlocks(markdown) {
853
1145
  }
854
1146
  const codeText = codeLines.join(`
855
1147
  `);
1148
+ activeListParent = null;
856
1149
  const chunks = chunkText(codeText);
857
1150
  for (let c = 0;c < Math.max(1, chunks.length); c += MAX_RICH_TEXT_ITEMS) {
858
1151
  const slice = chunks.slice(c, c + MAX_RICH_TEXT_ITEMS);
@@ -871,6 +1164,7 @@ function markdownToBlocks(markdown) {
871
1164
  continue;
872
1165
  }
873
1166
  if (/^(-{3,}|\*{3,}|_{3,})\s*$/.test(line)) {
1167
+ activeListParent = null;
874
1168
  blocks.push({ object: "block", type: "divider", divider: {} });
875
1169
  i++;
876
1170
  continue;
@@ -879,6 +1173,7 @@ function markdownToBlocks(markdown) {
879
1173
  if (hMatch) {
880
1174
  const depth = Math.min(3, hMatch[1].length);
881
1175
  const key = `heading_${depth}`;
1176
+ activeListParent = null;
882
1177
  blocks.push({
883
1178
  object: "block",
884
1179
  type: key,
@@ -902,6 +1197,7 @@ function markdownToBlocks(markdown) {
902
1197
  rows.push(normalizedRow);
903
1198
  i++;
904
1199
  }
1200
+ activeListParent = null;
905
1201
  blocks.push({
906
1202
  object: "block",
907
1203
  type: "table",
@@ -920,9 +1216,9 @@ function markdownToBlocks(markdown) {
920
1216
  });
921
1217
  continue;
922
1218
  }
923
- const todoMatch = line.match(/^\s*[-*]\s+\[([ xX])\]\s+(.*)$/);
1219
+ const todoMatch = line.match(/^[ \t]*[-*]\s+\[([ xX])\]\s+(.*)$/);
924
1220
  if (todoMatch) {
925
- blocks.push({
1221
+ pushListItemBlock(computeLeadingIndent(line), "to_do", {
926
1222
  object: "block",
927
1223
  type: "to_do",
928
1224
  to_do: {
@@ -933,9 +1229,9 @@ function markdownToBlocks(markdown) {
933
1229
  i++;
934
1230
  continue;
935
1231
  }
936
- const ulMatch = line.match(/^\s*[-*+]\s+(.*)$/);
1232
+ const ulMatch = line.match(/^[ \t]*[-*+]\s+(.*)$/);
937
1233
  if (ulMatch) {
938
- blocks.push({
1234
+ pushListItemBlock(computeLeadingIndent(line), "bulleted_list_item", {
939
1235
  object: "block",
940
1236
  type: "bulleted_list_item",
941
1237
  bulleted_list_item: { rich_text: inlineMarkdownToRichText(ulMatch[1]) }
@@ -943,9 +1239,9 @@ function markdownToBlocks(markdown) {
943
1239
  i++;
944
1240
  continue;
945
1241
  }
946
- const olMatch = line.match(/^\s*\d+\.\s+(.*)$/);
1242
+ const olMatch = line.match(/^[ \t]*\d+\.\s+(.*)$/);
947
1243
  if (olMatch) {
948
- blocks.push({
1244
+ pushListItemBlock(computeLeadingIndent(line), "numbered_list_item", {
949
1245
  object: "block",
950
1246
  type: "numbered_list_item",
951
1247
  numbered_list_item: { rich_text: inlineMarkdownToRichText(olMatch[1]) }
@@ -953,6 +1249,7 @@ function markdownToBlocks(markdown) {
953
1249
  i++;
954
1250
  continue;
955
1251
  }
1252
+ activeListParent = null;
956
1253
  const qMatch = line.match(/^>\s?(.*)$/);
957
1254
  if (qMatch) {
958
1255
  const qLines = [qMatch[1]];
@@ -1075,7 +1372,58 @@ function normalizeNotionCodeLang(lang) {
1075
1372
  const mapped = aliases[lang] ?? lang;
1076
1373
  return VALID_NOTION_LANGS.has(mapped) ? mapped : "plain text";
1077
1374
  }
1375
+ var CHILD_BEARING_BLOCK_TYPES = new Set([
1376
+ "heading_1",
1377
+ "heading_2",
1378
+ "heading_3",
1379
+ "bulleted_list_item",
1380
+ "numbered_list_item",
1381
+ "to_do",
1382
+ "quote",
1383
+ "callout",
1384
+ "table",
1385
+ "toggle"
1386
+ ]);
1387
+ var SIBLING_CHILDREN_CONCURRENCY = 4;
1388
+ async function mapWithConcurrency(items, concurrency, fn) {
1389
+ if (items.length === 0)
1390
+ return [];
1391
+ const results = new Array(items.length);
1392
+ let nextIdx = 0;
1393
+ const workers = Math.min(Math.max(1, concurrency), items.length);
1394
+ await Promise.all(Array.from({ length: workers }, async () => {
1395
+ while (true) {
1396
+ const cur = nextIdx++;
1397
+ if (cur >= items.length)
1398
+ break;
1399
+ results[cur] = await fn(items[cur]);
1400
+ }
1401
+ }));
1402
+ return results;
1403
+ }
1078
1404
  async function renderBlocksToMarkdown(blocks, fetchChildren, indent = "") {
1405
+ const siblingIds = [];
1406
+ const seenSiblingIds = new Set;
1407
+ for (const b of blocks) {
1408
+ if (b.has_children && typeof b.id === "string" && b.id && CHILD_BEARING_BLOCK_TYPES.has(b.type) && !seenSiblingIds.has(b.id)) {
1409
+ seenSiblingIds.add(b.id);
1410
+ siblingIds.push(b.id);
1411
+ }
1412
+ }
1413
+ const prefetchedChildren = new Map;
1414
+ if (siblingIds.length > 0) {
1415
+ const fetched = await mapWithConcurrency(siblingIds, SIBLING_CHILDREN_CONCURRENCY, async (id) => ({ id, kids: await fetchChildren(id) }));
1416
+ for (const item of fetched) {
1417
+ prefetchedChildren.set(item.id, item.kids);
1418
+ }
1419
+ }
1420
+ const getDirectChildren = (b, blockType) => {
1421
+ if (b.has_children && typeof b.id === "string" && prefetchedChildren.has(b.id)) {
1422
+ return prefetchedChildren.get(b.id);
1423
+ }
1424
+ const inlineKids = b[blockType]?.children;
1425
+ return Array.isArray(inlineKids) ? inlineKids : [];
1426
+ };
1079
1427
  const sections = [];
1080
1428
  let numberedIndex = 0;
1081
1429
  for (let idx = 0;idx < blocks.length; idx++) {
@@ -1101,8 +1449,8 @@ ${fm}
1101
1449
  } else if (t === "heading_1" || t === "heading_2" || t === "heading_3") {
1102
1450
  const depth = t === "heading_1" ? "#" : t === "heading_2" ? "##" : "###";
1103
1451
  let text = `${indent}${depth} ${richTextToInlineMarkdown(b[t]?.rich_text)}`;
1104
- if (b.has_children) {
1105
- const kids = await fetchChildren(b.id);
1452
+ const kids = getDirectChildren(b, t);
1453
+ if (kids.length > 0) {
1106
1454
  const kidMd = await renderBlocksToMarkdown(kids, fetchChildren, indent);
1107
1455
  if (kidMd)
1108
1456
  text += `
@@ -1112,8 +1460,8 @@ ${kidMd}`;
1112
1460
  sections.push(text);
1113
1461
  } else if (t === "bulleted_list_item") {
1114
1462
  let text = `${indent}- ${richTextToInlineMarkdown(b.bulleted_list_item?.rich_text)}`;
1115
- if (b.has_children) {
1116
- const kids = await fetchChildren(b.id);
1463
+ const kids = getDirectChildren(b, t);
1464
+ if (kids.length > 0) {
1117
1465
  const kidMd = await renderBlocksToMarkdown(kids, fetchChildren, `${indent} `);
1118
1466
  if (kidMd)
1119
1467
  text += `
@@ -1123,8 +1471,8 @@ ${kidMd}`;
1123
1471
  } else if (t === "numbered_list_item") {
1124
1472
  numberedIndex++;
1125
1473
  let text = `${indent}${numberedIndex}. ${richTextToInlineMarkdown(b.numbered_list_item?.rich_text)}`;
1126
- if (b.has_children) {
1127
- const kids = await fetchChildren(b.id);
1474
+ const kids = getDirectChildren(b, t);
1475
+ if (kids.length > 0) {
1128
1476
  const kidMd = await renderBlocksToMarkdown(kids, fetchChildren, `${indent} `);
1129
1477
  if (kidMd)
1130
1478
  text += `
@@ -1134,8 +1482,8 @@ ${kidMd}`;
1134
1482
  } else if (t === "to_do") {
1135
1483
  const mark = b.to_do?.checked ? "x" : " ";
1136
1484
  let text = `${indent}- [${mark}] ${richTextToInlineMarkdown(b.to_do?.rich_text)}`;
1137
- if (b.has_children) {
1138
- const kids = await fetchChildren(b.id);
1485
+ const kids = getDirectChildren(b, t);
1486
+ if (kids.length > 0) {
1139
1487
  const kidMd = await renderBlocksToMarkdown(kids, fetchChildren, `${indent} `);
1140
1488
  if (kidMd)
1141
1489
  text += `
@@ -1148,8 +1496,8 @@ ${kidMd}`;
1148
1496
  let quoted = raw.split(`
1149
1497
  `).map((l) => `${indent}> ${l}`).join(`
1150
1498
  `);
1151
- if (b.has_children) {
1152
- const kids = await fetchChildren(b.id);
1499
+ const kids = getDirectChildren(b, t);
1500
+ if (kids.length > 0) {
1153
1501
  const kidMd = await renderBlocksToMarkdown(kids, fetchChildren, "");
1154
1502
  if (kidMd) {
1155
1503
  quoted += `
@@ -1171,7 +1519,7 @@ ${indent}${fence}`);
1171
1519
  } else if (t === "divider") {
1172
1520
  sections.push(`${indent}---`);
1173
1521
  } else if (t === "table") {
1174
- const rows = b.has_children ? await fetchChildren(b.id) : b.table?.children ?? [];
1522
+ const rows = getDirectChildren(b, t);
1175
1523
  const renderedRows = [];
1176
1524
  rows.forEach((r, rIdx) => {
1177
1525
  const cells = r.table_row?.cells ?? [];
@@ -1186,8 +1534,8 @@ ${indent}${fence}`);
1186
1534
  `));
1187
1535
  } else if (t === "toggle") {
1188
1536
  let text = `${indent}- ${richTextToInlineMarkdown(b.toggle?.rich_text)}`;
1189
- if (b.has_children) {
1190
- const kids = await fetchChildren(b.id);
1537
+ const kids = getDirectChildren(b, t);
1538
+ if (kids.length > 0) {
1191
1539
  const kidMd = await renderBlocksToMarkdown(kids, fetchChildren, `${indent} `);
1192
1540
  if (kidMd)
1193
1541
  text += `
@@ -1308,6 +1656,7 @@ function resolveStorePaths(overrides) {
1308
1656
  catalogPath: nodePath.join(homeDir, "catalog.json"),
1309
1657
  manifestPath: nodePath.join(homeDir, "manifest.json"),
1310
1658
  storeRoot: nodePath.join(homeDir, "store"),
1659
+ byNameRoot: nodePath.join(homeDir, "by-name"),
1311
1660
  reposRoot: nodePath.join(homeDir, "repos"),
1312
1661
  assetsRoot: nodePath.join(homeDir, "assets"),
1313
1662
  workRoot: nodePath.join(homeDir, "work"),
@@ -1375,13 +1724,16 @@ function isProcessAlive(pid) {
1375
1724
  return err?.code === "EPERM";
1376
1725
  }
1377
1726
  }
1378
- async function atomicWriteJson(filePath, data) {
1727
+ async function atomicWriteJson(filePath, data, options) {
1379
1728
  const dir = nodePath.dirname(filePath);
1380
1729
  await fsp.mkdir(dir, { recursive: true });
1381
1730
  const tmpPath = nodePath.join(dir, `.${nodePath.basename(filePath)}.${process.pid}.${randomUUID().slice(0, 8)}.tmp`);
1382
1731
  const payload = `${JSON.stringify(data, null, 2)}
1383
1732
  `;
1384
- await fsp.writeFile(tmpPath, payload, "utf8");
1733
+ await fsp.writeFile(tmpPath, payload, options?.mode !== undefined ? { encoding: "utf8", mode: options.mode } : "utf8");
1734
+ if (options?.mode !== undefined && process.platform !== "win32") {
1735
+ await fsp.chmod(tmpPath, options.mode);
1736
+ }
1385
1737
  await fsp.rename(tmpPath, filePath);
1386
1738
  }
1387
1739
 
@@ -1410,7 +1762,7 @@ function makeStoreService(overrides) {
1410
1762
  })
1411
1763
  }),
1412
1764
  writeConfig: (config) => Effect.tryPromise({
1413
- try: () => atomicWriteJson(paths.configPath, config),
1765
+ try: () => atomicWriteJson(paths.configPath, config, { mode: 384 }),
1414
1766
  catch: (err) => new StoreError({
1415
1767
  path: paths.configPath,
1416
1768
  message: `Failed writing config: ${String(err)}`
@@ -2668,17 +3020,25 @@ function makeNotionServiceFromTransport(transport) {
2668
3020
  });
2669
3021
  return pages.map(decodeFilePage).filter((f) => f !== null);
2670
3022
  }),
2671
- readSkillBody: (skillPageId) => wrap(async () => {
3023
+ readSkillBody: (skillPageId, opts) => wrap(async () => {
2672
3024
  const pid = normalizeUuid(skillPageId);
2673
- const [page, topBlocks] = await Promise.all([
2674
- transport.requestJson("GET", `/v1/pages/${pid}`),
2675
- listAllBlockChildren(pid)
2676
- ]);
3025
+ let lastEditedTime = new Date(0).toISOString();
3026
+ let topBlocks;
3027
+ if (opts?.skipPageMeta) {
3028
+ topBlocks = await listAllBlockChildren(pid);
3029
+ } else {
3030
+ const [page, blocks] = await Promise.all([
3031
+ transport.requestJson("GET", `/v1/pages/${pid}`),
3032
+ listAllBlockChildren(pid)
3033
+ ]);
3034
+ topBlocks = blocks;
3035
+ lastEditedTime = page.last_edited_time ?? lastEditedTime;
3036
+ }
2677
3037
  const extracted = await extractSkillPageContent(topBlocks, listAllBlockChildren);
2678
3038
  return {
2679
3039
  rawMarkdown: extracted.rawMarkdown,
2680
3040
  upstreamFilesPageId: extracted.upstreamFilesPageId,
2681
- lastEditedTime: page.last_edited_time ?? new Date(0).toISOString()
3041
+ lastEditedTime
2682
3042
  };
2683
3043
  }),
2684
3044
  readFileBody: ({ filePageId, filePath }) => wrap(async () => {
@@ -3591,6 +3951,7 @@ var UpstreamLiveLayer = Layer3.effect(UpstreamPort, Effect3.gen(function* () {
3591
3951
  discoveredGh.push({
3592
3952
  name: finalName,
3593
3953
  description: parsed.description || "",
3954
+ disableModelInvocation: parsed.disableModelInvocation,
3594
3955
  sourcePath: dir,
3595
3956
  rawSkillMarkdown: rawText,
3596
3957
  relativeFiles: relFiles
@@ -3634,6 +3995,7 @@ var UpstreamLiveLayer = Layer3.effect(UpstreamPort, Effect3.gen(function* () {
3634
3995
  discovered.push({
3635
3996
  name: finalName,
3636
3997
  description: parsed.description || "",
3998
+ disableModelInvocation: parsed.disableModelInvocation,
3637
3999
  sourcePath: dir,
3638
4000
  rawSkillMarkdown: rawText,
3639
4001
  relativeFiles: relFiles
@@ -3762,7 +4124,114 @@ var UpstreamLiveLayer = Layer3.effect(UpstreamPort, Effect3.gen(function* () {
3762
4124
  import { randomUUID as randomUUID4 } from "node:crypto";
3763
4125
  import * as fsp5 from "node:fs/promises";
3764
4126
  import * as nodePath5 from "node:path";
3765
- import { Effect as Effect4 } from "effect";
4127
+ import { Effect as Effect4, Schema as Schema3 } from "effect";
4128
+ function isHomeOrEnvPrefixed(raw) {
4129
+ return raw === "~" || raw.startsWith("~/") || raw === "$HOME" || raw.startsWith("$HOME/") || raw === "${HOME}" || raw.startsWith("${HOME}/") || raw === "$XDG_CONFIG_HOME" || raw.startsWith("$XDG_CONFIG_HOME/") || raw === "${XDG_CONFIG_HOME}" || raw.startsWith("${XDG_CONFIG_HOME}/") || raw === "$XDG_DATA_HOME" || raw.startsWith("$XDG_DATA_HOME/") || raw === "${XDG_DATA_HOME}" || raw.startsWith("${XDG_DATA_HOME}/");
4130
+ }
4131
+ function resolveSpecRelativePath(rawPath, specFilePath) {
4132
+ const trimmed = rawPath.trim();
4133
+ const baseDir = nodePath5.dirname(nodePath5.resolve(specFilePath));
4134
+ if (!trimmed)
4135
+ return baseDir;
4136
+ if (isHomeOrEnvPrefixed(trimmed)) {
4137
+ return resolveHomePath(trimmed);
4138
+ }
4139
+ if (nodePath5.isAbsolute(trimmed)) {
4140
+ return nodePath5.resolve(trimmed);
4141
+ }
4142
+ return nodePath5.resolve(baseDir, trimmed);
4143
+ }
4144
+ function normalizeSpecTarget(raw, specFilePath, defaultMode) {
4145
+ return {
4146
+ dir: resolveSpecRelativePath(raw.dir, specFilePath),
4147
+ ...raw.profiles !== undefined ? { profiles: [...raw.profiles] } : {},
4148
+ ...raw.scenes !== undefined ? { scenes: [...raw.scenes] } : {},
4149
+ ...raw.default_only !== undefined ? { default_only: raw.default_only } : {},
4150
+ ...raw.include_non_default !== undefined ? { include_non_default: raw.include_non_default } : {},
4151
+ ...raw.include_all !== undefined ? { include_all: raw.include_all } : {},
4152
+ ...raw.skills !== undefined ? { skills: [...raw.skills] } : {},
4153
+ ...raw.bundles !== undefined ? { bundles: [...raw.bundles] } : {},
4154
+ ...raw.exclude !== undefined ? { exclude: [...raw.exclude] } : {},
4155
+ ...raw.include_requires !== undefined ? { include_requires: raw.include_requires } : {},
4156
+ ...raw.router !== undefined ? { router: raw.router } : {},
4157
+ mode: raw.mode ?? defaultMode ?? "symlink"
4158
+ };
4159
+ }
4160
+ function loadExportSpecFile(args) {
4161
+ const absSpecPath = resolveHomePath(args.specPath);
4162
+ return Effect4.tryPromise({
4163
+ try: async () => {
4164
+ const rawText = await fsp5.readFile(absSpecPath, "utf8");
4165
+ const parsed = JSON.parse(rawText);
4166
+ const decoded = Schema3.decodeUnknownSync(ExportSpecFileSchema)(parsed);
4167
+ let localBundles = {};
4168
+ let rawTargets;
4169
+ if (Array.isArray(decoded)) {
4170
+ rawTargets = decoded;
4171
+ } else if ("exports" in decoded) {
4172
+ localBundles = decoded.bundles ?? {};
4173
+ rawTargets = decoded.exports;
4174
+ } else if ("dir" in decoded) {
4175
+ rawTargets = [decoded];
4176
+ } else {
4177
+ throw new Error("Unsupported export spec shape.");
4178
+ }
4179
+ const mergedBundles = {
4180
+ ...args.baseBundles ?? {},
4181
+ ...localBundles
4182
+ };
4183
+ const targets = rawTargets.map((t) => normalizeSpecTarget(t, absSpecPath, args.defaultMode));
4184
+ return {
4185
+ specPath: absSpecPath,
4186
+ bundles: mergedBundles,
4187
+ targets
4188
+ };
4189
+ },
4190
+ catch: (err) => new ConfigError({
4191
+ path: absSpecPath,
4192
+ message: `Invalid export spec file at ${absSpecPath}: ${String(err)}`
4193
+ })
4194
+ });
4195
+ }
4196
+ function resolveConfiguredExports(config, configPath) {
4197
+ return Effect4.gen(function* () {
4198
+ const baseBundles = config.bundles ?? {};
4199
+ const targets = [];
4200
+ const warnings = [];
4201
+ const seenDirs = new Map;
4202
+ const registerTarget = (target, bundles, sourceFile) => {
4203
+ const resolvedDir = resolveHomePath(target.dir);
4204
+ const prevOwner = seenDirs.get(resolvedDir);
4205
+ if (prevOwner !== undefined) {
4206
+ warnings.push(`Duplicate export target directory '${resolvedDir}' (${sourceFile ?? "config.exports"} conflicts with ${prevOwner}); skipped duplicate target to avoid clobbering.`);
4207
+ return;
4208
+ }
4209
+ seenDirs.set(resolvedDir, sourceFile ?? "config.exports");
4210
+ targets.push({ target, bundles, sourceFile });
4211
+ };
4212
+ for (const target of config.exports) {
4213
+ registerTarget(target, baseBundles, null);
4214
+ }
4215
+ for (const rawIncludePath of config.include_exports ?? []) {
4216
+ const trimmed = rawIncludePath.trim();
4217
+ if (!trimmed)
4218
+ continue;
4219
+ const absIncludePath = resolveSpecRelativePath(trimmed, configPath);
4220
+ const loadedRes = yield* loadExportSpecFile({
4221
+ specPath: absIncludePath,
4222
+ baseBundles
4223
+ }).pipe(Effect4.result);
4224
+ if (loadedRes._tag === "Failure") {
4225
+ warnings.push(`Failed to load include_exports '${trimmed}' (${absIncludePath}): ${loadedRes.failure.message}; skipped.`);
4226
+ continue;
4227
+ }
4228
+ for (const target of loadedRes.success.targets) {
4229
+ registerTarget(target, loadedRes.success.bundles, loadedRes.success.specPath);
4230
+ }
4231
+ }
4232
+ return { targets, warnings };
4233
+ });
4234
+ }
3766
4235
  async function inspectLocalPendingState(args) {
3767
4236
  const openWorkdirs = [];
3768
4237
  const workEntries = await fsp5.readdir(args.workRoot).catch(() => []);
@@ -3912,7 +4381,7 @@ function initLibraryCommand(args) {
3912
4381
  default_only: true,
3913
4382
  mode: parsed.mode
3914
4383
  };
3915
- }) : existing && existing.exports.length > 0 ? [...existing.exports] : args.addDefaultExports !== false ? [
4384
+ }) : existing && (existing.exports.length > 0 || existing.include_exports !== undefined && existing.include_exports.length > 0) ? [...existing.exports] : args.addDefaultExports !== false ? [
3916
4385
  {
3917
4386
  dir: "~/.agents/skills",
3918
4387
  profiles: targetProfiles,
@@ -3930,6 +4399,8 @@ function initLibraryCommand(args) {
3930
4399
  libraries: nextLibraries,
3931
4400
  prefetch: args.prefetch ?? existing?.prefetch ?? "discoverable",
3932
4401
  ...resolvedProfiles && resolvedProfiles.length > 0 ? { profiles: resolvedProfiles } : {},
4402
+ ...existing?.bundles ? { bundles: existing.bundles } : {},
4403
+ ...existing?.include_exports ? { include_exports: existing.include_exports } : {},
3933
4404
  exports: resolvedExports
3934
4405
  };
3935
4406
  yield* store.writeConfig(nextConfig);
@@ -3988,6 +4459,7 @@ function doctorCommand(args) {
3988
4459
  checks
3989
4460
  };
3990
4461
  }
4462
+ const resolvedExports = yield* resolveConfiguredExports(cfg, store.paths.configPath);
3991
4463
  libraryId = normalizeUuid(args.libraryId ?? cfg.default_library);
3992
4464
  const binding = cfg.libraries[libraryId];
3993
4465
  if (!binding) {
@@ -3998,10 +4470,19 @@ function doctorCommand(args) {
3998
4470
  hint: `Run: ntn-skills init --root ${libraryId}`
3999
4471
  });
4000
4472
  } else {
4473
+ const includeSuffix = cfg.include_exports && cfg.include_exports.length > 0 ? ` (including ${cfg.include_exports.length} include_exports file(s))` : "";
4001
4474
  checks.push({
4002
4475
  name: "config",
4003
4476
  status: "pass",
4004
- detail: `Library ${libraryId} configured with ${cfg.exports.length} export target(s).`
4477
+ detail: `Library ${libraryId} configured with ${resolvedExports.targets.length} export target(s)${includeSuffix}.`
4478
+ });
4479
+ }
4480
+ if (resolvedExports.warnings.length > 0) {
4481
+ checks.push({
4482
+ name: "include_exports",
4483
+ status: "warn",
4484
+ detail: resolvedExports.warnings.join(" | "),
4485
+ hint: "Check or fix invalid file paths declared in config.json include_exports."
4005
4486
  });
4006
4487
  }
4007
4488
  if (hasNotionToken && libraryId) {
@@ -4046,12 +4527,12 @@ function doctorCommand(args) {
4046
4527
  }
4047
4528
  const realStoreRoot = yield* Effect4.tryPromise(() => fsp5.realpath(store.paths.storeRoot)).pipe(Effect4.catch(() => Effect4.succeed(store.paths.storeRoot)));
4048
4529
  const storePrefixes = Array.from(new Set([`${store.paths.storeRoot}${nodePath5.sep}`, `${realStoreRoot}${nodePath5.sep}`]));
4049
- for (const target of cfg.exports) {
4530
+ for (const { target } of resolvedExports.targets) {
4050
4531
  const targetDir = resolveHomePath(target.dir);
4051
4532
  const inspectTarget = yield* Effect4.tryPromise(async () => {
4052
4533
  let entries;
4053
4534
  try {
4054
- entries = await fsp5.readdir(targetDir);
4535
+ entries = (await fsp5.readdir(targetDir)).sort();
4055
4536
  } catch {
4056
4537
  return { exists: false, managed: 0, foreign: [] };
4057
4538
  }
@@ -4125,7 +4606,7 @@ function materializeOneSkill(args) {
4125
4606
  try: () => fsp5.realpath(store.getStoreSkillDir(args.libraryId, args.skill.id, args.effectiveRev)),
4126
4607
  catch: (e) => new StoreError({ message: String(e) })
4127
4608
  });
4128
- return { storeDir: real, updatedLibState: args.libState };
4609
+ return { storeDir: real, updatedLibState: args.libState, hotHit: true };
4129
4610
  }
4130
4611
  }
4131
4612
  const fileMap = new Map;
@@ -4153,7 +4634,7 @@ function materializeOneSkill(args) {
4153
4634
  if (cached && !args.forceRefreshBodies && cached.lastEditedTime === args.skill.lastEditedTime) {
4154
4635
  rawMainMarkdown = cached.rawBody;
4155
4636
  } else {
4156
- const fetched = yield* notion.readSkillBody(args.skill.id);
4637
+ const fetched = yield* notion.readSkillBody(args.skill.id, { skipPageMeta: true });
4157
4638
  rawMainMarkdown = fetched.rawMarkdown;
4158
4639
  nextMainCache[args.skill.id] = {
4159
4640
  lastEditedTime: args.skill.lastEditedTime,
@@ -4209,25 +4690,49 @@ function materializeOneSkill(args) {
4209
4690
  ...args.libState,
4210
4691
  mainHashCache: nextMainCache,
4211
4692
  fileBodyCache: nextFileBodyCache
4212
- }
4693
+ },
4694
+ hotHit: false
4213
4695
  };
4214
4696
  });
4215
4697
  }
4216
4698
  function publishExportTarget(args) {
4217
4699
  return Effect4.gen(function* () {
4700
+ const onConflict = args.onConflict ?? "error";
4701
+ const destRoot = resolveHomePath(args.target.dir);
4702
+ const skippedConflicts = [];
4703
+ const warnings = [];
4218
4704
  const seenNames = new Map;
4705
+ const duplicateNames = new Map;
4219
4706
  for (const entry of args.selectedEntries) {
4220
4707
  const prev = seenNames.get(entry.name);
4221
4708
  if (prev && prev.skillId !== entry.skillId) {
4222
- return yield* Effect4.fail(new ConflictError({
4223
- kind: "duplicate_name",
4224
- message: `Duplicate active skill name '${entry.name}' in Notion (${prev.skillId} vs ${entry.skillId}); refusing export.`,
4225
- details: [prev.skillId, entry.skillId]
4226
- }));
4709
+ if (onConflict === "error") {
4710
+ return yield* Effect4.fail(new ConflictError({
4711
+ kind: "duplicate_name",
4712
+ message: `Duplicate active skill name '${entry.name}' in Notion (${prev.skillId} vs ${entry.skillId}); refusing export.`,
4713
+ details: [prev.skillId, entry.skillId]
4714
+ }));
4715
+ }
4716
+ const ids = duplicateNames.get(entry.name) ?? new Set([prev.skillId]);
4717
+ ids.add(entry.skillId);
4718
+ duplicateNames.set(entry.name, ids);
4719
+ continue;
4227
4720
  }
4228
4721
  seenNames.set(entry.name, entry);
4229
4722
  }
4230
- const destRoot = resolveHomePath(args.target.dir);
4723
+ for (const [dupName, ids] of duplicateNames) {
4724
+ seenNames.delete(dupName);
4725
+ const idList = [...ids].sort().join(", ");
4726
+ const entryPath = nodePath5.join(destRoot, dupName);
4727
+ const reason = `Duplicate active skill name '${dupName}' in Notion (${idList}); refusing export.`;
4728
+ skippedConflicts.push({
4729
+ name: dupName,
4730
+ path: entryPath,
4731
+ kind: "duplicate_name",
4732
+ reason
4733
+ });
4734
+ warnings.push(`Skipped exporting '${dupName}' to '${entryPath}': duplicate active skill name in Notion (${idList}); resolve duplicate names in Notion and re-sync.`);
4735
+ }
4231
4736
  const storeRootResolved = nodePath5.resolve(args.storeRoot);
4232
4737
  const storeRootReal = yield* Effect4.promise(() => fsp5.realpath(storeRootResolved).catch(() => storeRootResolved));
4233
4738
  return yield* Effect4.tryPromise({
@@ -4235,9 +4740,16 @@ function publishExportTarget(args) {
4235
4740
  await fsp5.mkdir(destRoot, { recursive: true });
4236
4741
  const exportedDirs = [];
4237
4742
  const activeStoreTargets = new Set;
4238
- const desiredNames = new Set(seenNames.keys());
4239
- const isManagedStoreLink = (linkTargetAbs) => linkTargetAbs.startsWith(`${storeRootResolved}${nodePath5.sep}`) || linkTargetAbs.startsWith(`${storeRootReal}${nodePath5.sep}`);
4743
+ const desiredNames = new Set([...seenNames.keys(), ...duplicateNames.keys()]);
4744
+ const isManagedStoreLink = (linkTargetAbs, linkTargetReal) => {
4745
+ const prefixes = [
4746
+ `${storeRootResolved}${nodePath5.sep}`,
4747
+ `${storeRootReal}${nodePath5.sep}`
4748
+ ];
4749
+ return prefixes.some((pref) => linkTargetAbs.startsWith(pref) || Boolean(linkTargetReal?.startsWith(pref)));
4750
+ };
4240
4751
  const isManagedCopyDir = async (dirPath) => fsp5.stat(nodePath5.join(dirPath, ".ntn-managed-copy.json")).then((s) => s.isFile()).catch(() => false);
4752
+ const publishableEntries = new Map;
4241
4753
  for (const [skillName, entry] of seenNames) {
4242
4754
  if (!entry.materializedPath) {
4243
4755
  throw new Error(`Skill '${skillName}' has no materialized store path ready for export.`);
@@ -4249,28 +4761,64 @@ function publishExportTarget(args) {
4249
4761
  if (lst.isSymbolicLink()) {
4250
4762
  const rawLink = await fsp5.readlink(entryPath);
4251
4763
  const resolvedLink = nodePath5.resolve(nodePath5.dirname(entryPath), rawLink);
4252
- if (!isManagedStoreLink(resolvedLink)) {
4253
- throw new ConflictError({
4254
- kind: "foreign_target",
4255
- message: `Refusing to overwrite non-managed symlink '${entryPath}' -> '${rawLink}'.`
4764
+ const realResolvedLink = await fsp5.realpath(resolvedLink).catch(() => resolvedLink);
4765
+ if (!isManagedStoreLink(resolvedLink, realResolvedLink)) {
4766
+ const reason = `Refusing to overwrite non-managed symlink '${entryPath}' -> '${rawLink}'.`;
4767
+ if (onConflict === "error") {
4768
+ throw new ConflictError({
4769
+ kind: "foreign_target",
4770
+ message: reason
4771
+ });
4772
+ }
4773
+ skippedConflicts.push({
4774
+ name: skillName,
4775
+ path: entryPath,
4776
+ kind: "foreign_symlink",
4777
+ linkTarget: rawLink,
4778
+ reason
4256
4779
  });
4780
+ warnings.push(`Skipped exporting '${skillName}' to '${entryPath}': non-managed symlink -> '${rawLink}' exists (left untouched; remove/relocate it or run 'ntn-skills doctor' to inspect).`);
4781
+ continue;
4257
4782
  }
4258
4783
  } else if (lst.isDirectory()) {
4259
4784
  if (!await isManagedCopyDir(entryPath)) {
4785
+ const reason = `Refusing to overwrite non-managed foreign directory '${entryPath}'.`;
4786
+ if (onConflict === "error") {
4787
+ throw new ConflictError({
4788
+ kind: "foreign_target",
4789
+ message: reason
4790
+ });
4791
+ }
4792
+ skippedConflicts.push({
4793
+ name: skillName,
4794
+ path: entryPath,
4795
+ kind: "foreign_directory",
4796
+ reason
4797
+ });
4798
+ warnings.push(`Skipped exporting '${skillName}' to '${entryPath}': non-managed directory exists without .ntn-managed-copy.json (left untouched; migrate via 'ntn-skills new' or remove it, and run 'ntn-skills doctor' to inspect).`);
4799
+ continue;
4800
+ }
4801
+ } else {
4802
+ const reason = `Refusing to overwrite non-managed file '${entryPath}'.`;
4803
+ if (onConflict === "error") {
4260
4804
  throw new ConflictError({
4261
4805
  kind: "foreign_target",
4262
- message: `Refusing to overwrite non-managed foreign directory '${entryPath}'.`
4806
+ message: reason
4263
4807
  });
4264
4808
  }
4265
- } else {
4266
- throw new ConflictError({
4267
- kind: "foreign_target",
4268
- message: `Refusing to overwrite non-managed file '${entryPath}'.`
4809
+ skippedConflicts.push({
4810
+ name: skillName,
4811
+ path: entryPath,
4812
+ kind: "foreign_file",
4813
+ reason
4269
4814
  });
4815
+ warnings.push(`Skipped exporting '${skillName}' to '${entryPath}': non-managed file exists (left untouched; remove/relocate it or run 'ntn-skills doctor' to inspect).`);
4816
+ continue;
4270
4817
  }
4271
4818
  }
4819
+ publishableEntries.set(skillName, entry);
4272
4820
  }
4273
- for (const [skillName, entry] of seenNames) {
4821
+ for (const [skillName, entry] of publishableEntries) {
4274
4822
  const storePath = entry.materializedPath;
4275
4823
  const destPath = nodePath5.join(destRoot, skillName);
4276
4824
  if (args.target.mode === "symlink") {
@@ -4322,7 +4870,8 @@ function publishExportTarget(args) {
4322
4870
  if (lst.isSymbolicLink()) {
4323
4871
  const rawLink = await fsp5.readlink(full);
4324
4872
  const resolvedLink = nodePath5.resolve(nodePath5.dirname(full), rawLink);
4325
- if (isManagedStoreLink(resolvedLink)) {
4873
+ const realResolvedLink = await fsp5.realpath(resolvedLink).catch(() => resolvedLink);
4874
+ if (isManagedStoreLink(resolvedLink, realResolvedLink)) {
4326
4875
  if (resolvedLink.includes(`${nodePath5.sep}_bundled${nodePath5.sep}`)) {
4327
4876
  activeStoreTargets.add(resolvedLink);
4328
4877
  continue;
@@ -4337,7 +4886,7 @@ function publishExportTarget(args) {
4337
4886
  await moveToSystemTrash(full);
4338
4887
  }
4339
4888
  }
4340
- return { exportedDirs, activeStoreTargets };
4889
+ return { exportedDirs, activeStoreTargets, skippedConflicts, warnings };
4341
4890
  },
4342
4891
  catch: (err) => err instanceof ConflictError ? err : new StoreError({ path: destRoot, message: String(err) })
4343
4892
  });
@@ -4361,6 +4910,96 @@ async function copyDirectoryContentsWritable(srcDir, dstDir) {
4361
4910
  }
4362
4911
  }
4363
4912
  }
4913
+ async function upsertByNameSymlink(byNameRoot, skillName, targetDir) {
4914
+ const trimmed = skillName.trim();
4915
+ if (!trimmed || trimmed === "." || trimmed === ".." || trimmed.startsWith(".") || nodePath5.basename(trimmed) !== trimmed) {
4916
+ return;
4917
+ }
4918
+ const targetStat = await fsp5.stat(targetDir).catch(() => null);
4919
+ if (!targetStat?.isDirectory())
4920
+ return;
4921
+ await fsp5.mkdir(byNameRoot, { recursive: true });
4922
+ const resolvedTarget = nodePath5.resolve(targetDir);
4923
+ const linkPath = nodePath5.join(byNameRoot, trimmed);
4924
+ const lst = await fsp5.lstat(linkPath).catch(() => null);
4925
+ if (lst?.isSymbolicLink()) {
4926
+ const rawLink = await fsp5.readlink(linkPath).catch(() => "");
4927
+ const curTarget = rawLink ? nodePath5.resolve(nodePath5.dirname(linkPath), rawLink) : "";
4928
+ if (curTarget === resolvedTarget) {
4929
+ return;
4930
+ }
4931
+ } else if (lst) {
4932
+ await removeInternalCachePath(linkPath);
4933
+ }
4934
+ const tmpLink = nodePath5.join(byNameRoot, `.ntn-byname-${trimmed}-${process.pid}-${randomUUID4().slice(0, 8)}`);
4935
+ try {
4936
+ await fsp5.symlink(resolvedTarget, tmpLink);
4937
+ await fsp5.rename(tmpLink, linkPath);
4938
+ } catch (err) {
4939
+ await fsp5.unlink(tmpLink).catch(() => {
4940
+ return;
4941
+ });
4942
+ throw err;
4943
+ }
4944
+ }
4945
+ async function reconcileByNameDirectory(args) {
4946
+ await fsp5.mkdir(args.byNameRoot, { recursive: true });
4947
+ const ordered = [...args.entries].sort((a, b) => {
4948
+ const aDef = a.libraryId === args.defaultLibraryId ? 0 : 1;
4949
+ const bDef = b.libraryId === args.defaultLibraryId ? 0 : 1;
4950
+ if (aDef !== bDef)
4951
+ return aDef - bDef;
4952
+ const libCmp = a.libraryId.localeCompare(b.libraryId);
4953
+ if (libCmp !== 0)
4954
+ return libCmp;
4955
+ return a.name.localeCompare(b.name);
4956
+ });
4957
+ const desired = new Map;
4958
+ for (const e of ordered) {
4959
+ if (!e.enabled || !e.materializedPath)
4960
+ continue;
4961
+ const trimmed = e.name.trim();
4962
+ if (!trimmed || trimmed === "." || trimmed === ".." || trimmed.startsWith(".") || nodePath5.basename(trimmed) !== trimmed || desired.has(trimmed)) {
4963
+ continue;
4964
+ }
4965
+ const st = await fsp5.stat(e.materializedPath).catch(() => null);
4966
+ if (!st?.isDirectory())
4967
+ continue;
4968
+ desired.set(trimmed, nodePath5.resolve(e.materializedPath));
4969
+ }
4970
+ for (const [name, targetDir] of desired) {
4971
+ await upsertByNameSymlink(args.byNameRoot, name, targetDir);
4972
+ }
4973
+ const existing = await fsp5.readdir(args.byNameRoot).catch(() => []);
4974
+ for (const name of existing) {
4975
+ const full = nodePath5.join(args.byNameRoot, name);
4976
+ const lst = await fsp5.lstat(full).catch(() => null);
4977
+ if (!lst)
4978
+ continue;
4979
+ if (name.startsWith(".ntn-byname-")) {
4980
+ if (lst.isSymbolicLink())
4981
+ await fsp5.unlink(full).catch(() => {
4982
+ return;
4983
+ });
4984
+ else
4985
+ await removeInternalCachePath(full);
4986
+ continue;
4987
+ }
4988
+ const wantTarget = desired.get(name);
4989
+ if (wantTarget && lst.isSymbolicLink()) {
4990
+ const raw = await fsp5.readlink(full).catch(() => "");
4991
+ const resolved = raw ? nodePath5.resolve(nodePath5.dirname(full), raw) : "";
4992
+ const targetOk = resolved === wantTarget && Boolean((await fsp5.stat(full).catch(() => null))?.isDirectory());
4993
+ if (targetOk)
4994
+ continue;
4995
+ }
4996
+ if (lst.isSymbolicLink()) {
4997
+ await fsp5.unlink(full);
4998
+ } else {
4999
+ await removeInternalCachePath(full);
5000
+ }
5001
+ }
5002
+ }
4364
5003
  function syncCommand(options = {}) {
4365
5004
  return Effect4.gen(function* () {
4366
5005
  const notion = yield* NotionPort;
@@ -4379,6 +5018,8 @@ function syncCommand(options = {}) {
4379
5018
  mainHashCache: {},
4380
5019
  fileBodyCache: {}
4381
5020
  };
5021
+ const resolvedExports = yield* resolveConfiguredExports(config, store.paths.configPath);
5022
+ const allExportTargets = resolvedExports.targets.map((r) => r.target);
4382
5023
  if (!options.full && prevLib.lastSyncedAt && dedupeWindowMs > 0) {
4383
5024
  const age = Date.now() - Date.parse(prevLib.lastSyncedAt);
4384
5025
  if (age >= 0 && age < dedupeWindowMs) {
@@ -4387,7 +5028,7 @@ function syncCommand(options = {}) {
4387
5028
  libraryId,
4388
5029
  workRoot: store.paths.workRoot,
4389
5030
  storeRoot: store.paths.storeRoot,
4390
- exports: config.exports,
5031
+ exports: allExportTargets,
4391
5032
  sources: prevLib.sources,
4392
5033
  skills: prevLib.skills
4393
5034
  })).pipe(Effect4.catch(() => Effect4.succeed({
@@ -4410,7 +5051,7 @@ function syncCommand(options = {}) {
4410
5051
  prunedCount: 0,
4411
5052
  pulled: { added: [], updated: [], removed: [] },
4412
5053
  localPending: pending,
4413
- warnings: []
5054
+ warnings: resolvedExports.warnings
4414
5055
  };
4415
5056
  }
4416
5057
  }
@@ -4512,15 +5153,33 @@ function syncCommand(options = {}) {
4512
5153
  arr.push(f);
4513
5154
  filesBySkillId.set(f.skillId, arr);
4514
5155
  }
5156
+ const warnings = [...resolvedExports.warnings];
5157
+ const exportSelections = resolvedExports.targets.map((resolved) => ({
5158
+ resolved,
5159
+ selection: resolveExportSelection({
5160
+ allEffectiveSkills: effectiveSkills,
5161
+ catalogSkills,
5162
+ target: resolved.target,
5163
+ bundles: resolved.bundles
5164
+ })
5165
+ }));
4515
5166
  const exportSeedIds = new Set;
5167
+ for (const { resolved, selection } of exportSelections) {
5168
+ if (selection.missingBundles.length > 0) {
5169
+ warnings.push(`Export target '${resolved.target.dir}' references unknown bundle(s): ${selection.missingBundles.join(", ")}.`);
5170
+ }
5171
+ if (selection.missingSkills.length > 0) {
5172
+ warnings.push(`Export target '${resolved.target.dir}' references unknown or disabled skill(s): ${selection.missingSkills.join(", ")}.`);
5173
+ }
5174
+ for (const sk of selection.selected)
5175
+ exportSeedIds.add(sk.id);
5176
+ }
4516
5177
  if (config.prefetch === "all-profiles") {
4517
5178
  for (const sk of catalogSkills)
4518
5179
  exportSeedIds.add(sk.id);
4519
5180
  } else if (config.prefetch === "discoverable") {
4520
- for (const exp of config.exports) {
4521
- for (const sk of selectExportSkills(catalogSkills, exp))
4522
- exportSeedIds.add(sk.id);
4523
- for (const sk of selectDiscoverableSkills(catalogSkills, exp))
5181
+ for (const { selection } of exportSelections) {
5182
+ for (const sk of selection.discoverable)
4524
5183
  exportSeedIds.add(sk.id);
4525
5184
  }
4526
5185
  for (const sk of catalogSkills) {
@@ -4528,16 +5187,10 @@ function syncCommand(options = {}) {
4528
5187
  exportSeedIds.add(sk.id);
4529
5188
  }
4530
5189
  }
4531
- } else {
4532
- for (const exp of config.exports) {
4533
- for (const sk of selectExportSkills(catalogSkills, exp))
4534
- exportSeedIds.add(sk.id);
4535
- }
4536
5190
  }
4537
5191
  const { closureIds, missingOrDisabled } = computeRequiresClosure(exportSeedIds, effectiveById);
4538
5192
  const previouslyMaterializedIds = new Set(currentCatalog.entries.filter((e) => e.libraryId === libraryId && e.materializedPath).map((e) => e.skillId));
4539
5193
  const deltaSkillIds = new Set([...delta.skills.map((s) => s.id), ...rywSkillSet]);
4540
- const warnings = [];
4541
5194
  const skillWarnings = new Map;
4542
5195
  for (const [sid, badReqs] of missingOrDisabled) {
4543
5196
  const skName = effectiveById.get(sid)?.name ?? sid;
@@ -4570,31 +5223,74 @@ function syncCommand(options = {}) {
4570
5223
  const currentNowMs = options.nowMs ?? Date.now();
4571
5224
  const hasPriorWatermark = Boolean(prevLib.watermark);
4572
5225
  const bodyCheckTasks = [];
5226
+ const staleMainCacheIds = new Set;
5227
+ for (const cachedSkillId of Object.keys(workingLibState.mainHashCache)) {
5228
+ if (!effectiveById.has(cachedSkillId) && !mergedSkills[cachedSkillId]) {
5229
+ staleMainCacheIds.add(cachedSkillId);
5230
+ }
5231
+ }
4573
5232
  for (const sk of effectiveSkills) {
4574
5233
  const cached = workingLibState.mainHashCache[sk.id];
4575
5234
  const inCurrentDelta = deltaSkillIds.has(sk.id);
4576
5235
  const isMinuteSettled = maxServerMs - Date.parse(sk.lastEditedTime) >= 120000 || currentNowMs - Date.parse(sk.lastEditedTime) >= 120000;
4577
- const staleOrUnsettled = !cached || cached.lastEditedTime !== sk.lastEditedTime || inCurrentDelta && cached.settled !== true;
5236
+ const needsSettleRecheck = Boolean(cached && cached.settled !== true && isMinuteSettled);
5237
+ const staleOrUnsettled = !cached || cached.lastEditedTime !== sk.lastEditedTime || (inCurrentDelta || isMinuteSettled) && cached.settled !== true;
4578
5238
  const isHotOrDefault = closureIds.has(sk.id) || sk.visibility === "always" || previouslyMaterializedIds.has(sk.id);
4579
5239
  const prevSk = prevLib.skills[sk.id];
4580
5240
  const metaUnchanged = Boolean(prevSk && prevSk.name === sk.name && prevSk.description === sk.description && prevSk.enabled === sk.enabled && prevSk.visibility === sk.visibility && prevSk.kind === sk.kind && prevSk.customMain === sk.customMain && prevSk.revision === sk.revision && prevSk.previewHash === sk.previewHash && prevSk.profiles.join("\x00") === sk.profiles.join("\x00") && prevSk.scenes.join("\x00") === sk.scenes.join("\x00") && prevSk.requiresIds.join("\x00") === sk.requiresIds.join("\x00"));
4581
5241
  const suspectedWebEdit = Boolean(metaUnchanged && prevSk && (prevSk.lastEditedTime !== sk.lastEditedTime || !isMinuteSettled));
4582
- const needsBodyCheck = !sk.originSourceId || sk.customMain ? staleOrUnsettled && (isHotOrDefault || !isFull && hasPriorWatermark && inCurrentDelta) : Boolean(sk.previewHash && !isFull && hasPriorWatermark && inCurrentDelta && staleOrUnsettled && suspectedWebEdit);
4583
- if (needsBodyCheck) {
5242
+ if (!sk.originSourceId || sk.customMain) {
5243
+ const needsBodyCheck = staleOrUnsettled && (isHotOrDefault || needsSettleRecheck || !isFull && hasPriorWatermark && inCurrentDelta);
5244
+ if (needsBodyCheck) {
5245
+ bodyCheckTasks.push({ sk, settled: isMinuteSettled });
5246
+ }
5247
+ continue;
5248
+ }
5249
+ const previewContractChanged = Boolean(prevSk && (prevSk.previewHash !== sk.previewHash || prevSk.customMain !== sk.customMain));
5250
+ const cachedTimestampStale = Boolean(cached && cached.lastEditedTime !== sk.lastEditedTime);
5251
+ const cachedHadDrift = Boolean(cached && sk.previewHash && cached.rawBodySha256 !== sk.previewHash);
5252
+ if (!sk.previewHash) {
5253
+ if (cached)
5254
+ staleMainCacheIds.add(sk.id);
5255
+ continue;
5256
+ }
5257
+ if (previewContractChanged) {
5258
+ if (cached)
5259
+ staleMainCacheIds.add(sk.id);
5260
+ continue;
5261
+ }
5262
+ const shouldRecheckExistingDrift = Boolean(cachedHadDrift && (cachedTimestampStale || isFull));
5263
+ const shouldDetectWebEdit = Boolean(!isFull && hasPriorWatermark && inCurrentDelta && staleOrUnsettled && suspectedWebEdit);
5264
+ if (shouldRecheckExistingDrift || needsSettleRecheck || shouldDetectWebEdit) {
4584
5265
  bodyCheckTasks.push({ sk, settled: isMinuteSettled });
5266
+ } else if (cachedTimestampStale) {
5267
+ staleMainCacheIds.add(sk.id);
4585
5268
  }
4586
5269
  }
4587
5270
  const mutableMainCache = {
4588
5271
  ...workingLibState.mainHashCache
4589
5272
  };
4590
5273
  const mutableFileBodyCache = { ...workingLibState.fileBodyCache };
5274
+ let mainCacheEvicted = false;
5275
+ for (const staleId of staleMainCacheIds) {
5276
+ if (staleId in mutableMainCache) {
5277
+ delete mutableMainCache[staleId];
5278
+ mainCacheEvicted = true;
5279
+ }
5280
+ }
5281
+ if (mainCacheEvicted) {
5282
+ workingLibState = {
5283
+ ...workingLibState,
5284
+ mainHashCache: { ...mutableMainCache }
5285
+ };
5286
+ }
4591
5287
  if (bodyCheckTasks.length > 0) {
4592
5288
  if (bodyCheckTasks.length >= 20) {
4593
5289
  emitSyncProgress(`Fetching ${bodyCheckTasks.length} Notion skill page(s)...`);
4594
5290
  }
4595
5291
  let fetchedBodies = 0;
4596
5292
  yield* Effect4.forEach(bodyCheckTasks, ({ sk, settled }) => Effect4.gen(function* () {
4597
- const body = yield* notion.readSkillBody(sk.id);
5293
+ const body = yield* notion.readSkillBody(sk.id, { skipPageMeta: true });
4598
5294
  const rawHash = sha256Hex(body.rawMarkdown);
4599
5295
  mutableMainCache[sk.id] = {
4600
5296
  lastEditedTime: sk.lastEditedTime,
@@ -4619,9 +5315,9 @@ function syncCommand(options = {}) {
4619
5315
  }
4620
5316
  for (const sk of effectiveSkills) {
4621
5317
  if (sk.originSourceId && !sk.customMain && sk.previewHash) {
4622
- const latestBodyHash = workingLibState.mainHashCache[sk.id]?.rawBodySha256;
4623
- if (latestBodyHash && latestBodyHash !== sk.previewHash) {
4624
- const msg = `Skill '${sk.name}': 网页预览存在未进入消费的修改(Custom Main=false),请勾选 Custom Main 或执行 'ntn-skills detach ${sk.name}'。`;
5318
+ const cachedBody = workingLibState.mainHashCache[sk.id];
5319
+ if (cachedBody && cachedBody.lastEditedTime === sk.lastEditedTime && cachedBody.rawBodySha256 && cachedBody.rawBodySha256 !== sk.previewHash) {
5320
+ const msg = `Skill '${sk.name}': 网页预览存在未进入消费的修改(Custom Main=false);若要丢弃网页误改请执行 'ntn-skills reset-overlay "${sk.name}" SKILL.md',若要正式接管请执行 'ntn-skills edit "${sk.name}"' 并 'push'(自动勾选 Custom Main=true)。`;
4625
5321
  warnings.push(msg);
4626
5322
  skillWarnings.set(sk.id, [...skillWarnings.get(sk.id) ?? [], msg]);
4627
5323
  }
@@ -4652,7 +5348,7 @@ function syncCommand(options = {}) {
4652
5348
  } else if (cachedSourceCommits.has(src.id)) {
4653
5349
  resolvedCommits.set(src.id, cachedSourceCommits.get(src.id));
4654
5350
  } else if (!resolvedCommits.has(src.id) && !failedSourceHeadErrors.has(src.id)) {
4655
- if (sk.visibility === "always" || config.prefetch === "discoverable" && sk.visibility === "discoverable" || config.prefetch === "all-profiles") {
5351
+ if (closureIds.has(sk.id) || sk.visibility === "always" || config.prefetch === "discoverable" && sk.visibility === "discoverable" || config.prefetch === "all-profiles") {
4656
5352
  const shaOrErr = yield* upstream.resolveHeadCommit(src.repoUrl, src.ref).pipe(Effect4.result);
4657
5353
  if (shaOrErr._tag === "Success") {
4658
5354
  resolvedCommits.set(src.id, shaOrErr.success);
@@ -4704,10 +5400,14 @@ function syncCommand(options = {}) {
4704
5400
  const materializedPaths = new Map;
4705
5401
  let materializedCount = 0;
4706
5402
  const closureList = [...closureIds];
4707
- if (closureList.length >= 20) {
4708
- emitSyncProgress(`Materializing ${closureList.length} skill snapshot(s)...`);
5403
+ const coldCandidates = closureList.filter((sid) => {
5404
+ const prev = prevEntryById.get(sid);
5405
+ return !prev?.materializedPath || prev.effectiveRev !== getEffectiveRevFor(sid);
5406
+ });
5407
+ if (coldCandidates.length >= 5) {
5408
+ emitSyncProgress(`Materializing ${coldCandidates.length} updated skill snapshot(s)...`);
4709
5409
  }
4710
- let finishedMat = 0;
5410
+ let finishedColdMat = 0;
4711
5411
  yield* Effect4.forEach(closureList, (sid) => Effect4.gen(function* () {
4712
5412
  const sk = effectiveById.get(sid);
4713
5413
  const src = sk.originSourceId ? sourcesById.get(sk.originSourceId) ?? null : null;
@@ -4770,12 +5470,14 @@ function syncCommand(options = {}) {
4770
5470
  }
4771
5471
  materializedPaths.set(sid, mat.storeDir);
4772
5472
  materializedCount++;
4773
- finishedMat++;
4774
- if (finishedMat % 25 === 0) {
4775
- if (closureList.length >= 20) {
4776
- emitSyncProgress(`Materialized ${finishedMat}/${closureList.length} skill snapshot(s)...`);
5473
+ if (!mat.hotHit) {
5474
+ finishedColdMat++;
5475
+ if (finishedColdMat % 25 === 0) {
5476
+ if (coldCandidates.length >= 5) {
5477
+ emitSyncProgress(`Materialized ${finishedColdMat}/${coldCandidates.length} updated skill snapshot(s)...`);
5478
+ }
5479
+ yield* saveIntermediateCheckpoint(mutableMainCache, mutableFileBodyCache);
4777
5480
  }
4778
- yield* saveIntermediateCheckpoint(mutableMainCache, mutableFileBodyCache);
4779
5481
  }
4780
5482
  }), { concurrency: 4 });
4781
5483
  workingLibState = {
@@ -4783,8 +5485,7 @@ function syncCommand(options = {}) {
4783
5485
  mainHashCache: { ...mutableMainCache },
4784
5486
  fileBodyCache: { ...mutableFileBodyCache }
4785
5487
  };
4786
- const nextLibEntries = [];
4787
- for (const sk of catalogSkills) {
5488
+ const buildCatalogEntryForSkill = (sk) => Effect4.gen(function* () {
4788
5489
  const src = sk.originSourceId ? sourcesById.get(sk.originSourceId) ?? null : null;
4789
5490
  const rev = getEffectiveRevFor(sk.id);
4790
5491
  let matPath = materializedPaths.get(sk.id) ?? null;
@@ -4796,7 +5497,7 @@ function syncCommand(options = {}) {
4796
5497
  matPath = prevEntry.materializedPath;
4797
5498
  }
4798
5499
  }
4799
- nextLibEntries.push({
5500
+ return {
4800
5501
  libraryId,
4801
5502
  skillId: sk.id,
4802
5503
  name: sk.name,
@@ -4828,29 +5529,42 @@ function syncCommand(options = {}) {
4828
5529
  lastEditedTime: ov.lastEditedTime
4829
5530
  })),
4830
5531
  lastEditedTime: sk.lastEditedTime
4831
- });
5532
+ };
5533
+ });
5534
+ const nextLibEntries = [];
5535
+ for (const sk of catalogSkills) {
5536
+ nextLibEntries.push(yield* buildCatalogEntryForSkill(sk));
4832
5537
  }
4833
5538
  nextLibEntries.sort((a, b) => a.name.localeCompare(b.name));
4834
5539
  const entryMapById = new Map(nextLibEntries.map((e) => [e.skillId, e]));
5540
+ const exportEntryMapById = new Map(entryMapById);
5541
+ for (const { selection } of exportSelections) {
5542
+ for (const sk of selection.selected) {
5543
+ if (!exportEntryMapById.has(sk.id)) {
5544
+ exportEntryMapById.set(sk.id, yield* buildCatalogEntryForSkill(sk));
5545
+ }
5546
+ }
5547
+ }
4835
5548
  const protectedDirs = new Set;
4836
- for (const e of nextLibEntries) {
5549
+ for (const e of exportEntryMapById.values()) {
4837
5550
  if (e.materializedPath)
4838
5551
  protectedDirs.add(e.materializedPath);
4839
5552
  }
4840
- let exportedCount = 0;
4841
5553
  const manifestExports = [];
4842
- for (const exp of config.exports) {
4843
- const selectedSkills = selectExportSkills(catalogSkills, exp);
4844
- const selectedEntries = selectedSkills.map((s) => entryMapById.get(s.id)).filter((e) => Boolean(e?.materializedPath));
5554
+ const preparedExports = [];
5555
+ for (const { resolved, selection } of exportSelections) {
5556
+ const exp = resolved.target;
5557
+ const selectedEntries = selection.selected.map((s) => exportEntryMapById.get(s.id)).filter((e) => Boolean(e?.materializedPath));
4845
5558
  const directNameSet = new Set(selectedEntries.map((e) => e.name.toLowerCase()));
4846
- const discoverableEntries = selectDiscoverableSkills(catalogSkills, exp).map((s) => entryMapById.get(s.id)).filter((e) => Boolean(e) && !directNameSet.has(e.name.toLowerCase()));
5559
+ const discoverableEntries = selection.discoverable.map((s) => exportEntryMapById.get(s.id)).filter((e) => Boolean(e) && !directNameSet.has(e.name.toLowerCase()));
4847
5560
  let routerEntry = null;
4848
5561
  const routerName = (exp.router?.name ?? "skill-catalog").trim() || "skill-catalog";
4849
- if (discoverableEntries.length > 0 && exp.router?.enabled !== false && !directNameSet.has(routerName.toLowerCase())) {
5562
+ if (selection.resolvedRouterEnabled && discoverableEntries.length > 0 && !directNameSet.has(routerName.toLowerCase())) {
4850
5563
  const synth = synthesizeSkillCatalogPackage({
4851
5564
  routerName,
4852
5565
  discoverableEntries,
4853
- allEntriesById: entryMapById
5566
+ allEntriesById: exportEntryMapById,
5567
+ byNameRoot: store.paths.byNameRoot
4854
5568
  });
4855
5569
  const routerSkillId = `_router-${routerName}`;
4856
5570
  const routerStoreDir = yield* store.publishImmutablePackage({
@@ -4887,14 +5601,7 @@ function syncCommand(options = {}) {
4887
5601
  };
4888
5602
  }
4889
5603
  const finalExportEntries = routerEntry ? [...selectedEntries, routerEntry] : selectedEntries;
4890
- const pub = yield* publishExportTarget({
4891
- target: exp,
4892
- selectedEntries: finalExportEntries,
4893
- storeRoot: store.paths.storeRoot
4894
- });
4895
- exportedCount += pub.exportedDirs.length;
4896
- for (const p of pub.activeStoreTargets)
4897
- protectedDirs.add(p);
5604
+ preparedExports.push({ target: exp, finalExportEntries });
4898
5605
  manifestExports.push({
4899
5606
  dir: exp.dir,
4900
5607
  mode: exp.mode,
@@ -4937,6 +5644,10 @@ function syncCommand(options = {}) {
4937
5644
  })
4938
5645
  });
4939
5646
  const otherLibEntries = currentCatalog.entries.filter((e) => e.libraryId !== libraryId);
5647
+ for (const e of otherLibEntries) {
5648
+ if (e.materializedPath)
5649
+ protectedDirs.add(e.materializedPath);
5650
+ }
4940
5651
  const nextCatalog = {
4941
5652
  version: 2,
4942
5653
  updatedAt: syncStartIso,
@@ -4947,9 +5658,43 @@ function syncCommand(options = {}) {
4947
5658
  entries: [...otherLibEntries, ...nextLibEntries]
4948
5659
  };
4949
5660
  yield* store.writeCatalog(nextCatalog);
4950
- const activeRepoCommits = [];
4951
- for (const libSnapshot of Object.values(nextCatalog.libraries)) {
4952
- for (const src of Object.values(libSnapshot.sources)) {
5661
+ yield* Effect4.tryPromise({
5662
+ try: () => reconcileByNameDirectory({
5663
+ byNameRoot: store.paths.byNameRoot,
5664
+ entries: nextCatalog.entries,
5665
+ defaultLibraryId: normalizeUuid(config.default_library)
5666
+ }),
5667
+ catch: (err) => new StoreError({
5668
+ path: store.paths.byNameRoot,
5669
+ message: `Failed reconciling by-name links: ${String(err)}`
5670
+ })
5671
+ });
5672
+ let exportedCount = 0;
5673
+ let allExportsScanned = true;
5674
+ for (const { target: exp, finalExportEntries } of preparedExports) {
5675
+ const pubResult = yield* publishExportTarget({
5676
+ target: exp,
5677
+ selectedEntries: finalExportEntries,
5678
+ storeRoot: store.paths.storeRoot,
5679
+ onConflict: "skip"
5680
+ }).pipe(Effect4.result);
5681
+ if (pubResult._tag === "Failure") {
5682
+ allExportsScanned = false;
5683
+ const err = pubResult.failure;
5684
+ const errMsg = err && typeof err === "object" && "message" in err ? String(err.message) : String(err);
5685
+ warnings.push(`Export target '${exp.dir}' failed and was isolated: ${errMsg}`);
5686
+ continue;
5687
+ }
5688
+ const pub = pubResult.success;
5689
+ exportedCount += pub.exportedDirs.length;
5690
+ for (const p of pub.activeStoreTargets)
5691
+ protectedDirs.add(p);
5692
+ if (pub.warnings.length > 0)
5693
+ warnings.push(...pub.warnings);
5694
+ }
5695
+ const activeRepoCommits = [];
5696
+ for (const libSnapshot of Object.values(nextCatalog.libraries)) {
5697
+ for (const src of Object.values(libSnapshot.sources)) {
4953
5698
  if (src.enabled && src.repoUrl) {
4954
5699
  activeRepoCommits.push({
4955
5700
  repoUrl: src.repoUrl,
@@ -4966,7 +5711,10 @@ function syncCommand(options = {}) {
4966
5711
  });
4967
5712
  }
4968
5713
  }
4969
- const pruned = yield* store.pruneStore({ protectedDirs, activeRepoCommits });
5714
+ const pruned = allExportsScanned ? yield* store.pruneStore({ protectedDirs, activeRepoCommits }) : [];
5715
+ if (!allExportsScanned) {
5716
+ warnings.push("Skipped store GC pruning during this sync because one or more export targets failed to scan.");
5717
+ }
4970
5718
  const nextEntryById = new Map(nextLibEntries.map((e) => [e.skillId, e]));
4971
5719
  const addedNames = [];
4972
5720
  const updatedNames = [];
@@ -4988,7 +5736,7 @@ function syncCommand(options = {}) {
4988
5736
  libraryId,
4989
5737
  workRoot: store.paths.workRoot,
4990
5738
  storeRoot: store.paths.storeRoot,
4991
- exports: config.exports,
5739
+ exports: allExportTargets,
4992
5740
  sources: workingLibState.sources,
4993
5741
  skills: workingLibState.skills
4994
5742
  })).pipe(Effect4.catch(() => Effect4.succeed({
@@ -5020,6 +5768,91 @@ function syncCommand(options = {}) {
5020
5768
  }));
5021
5769
  });
5022
5770
  }
5771
+ var SEARCH_STOP_WORDS = new Set([
5772
+ "a",
5773
+ "an",
5774
+ "the",
5775
+ "to",
5776
+ "for",
5777
+ "of",
5778
+ "in",
5779
+ "on",
5780
+ "at",
5781
+ "by",
5782
+ "with",
5783
+ "from",
5784
+ "and",
5785
+ "or",
5786
+ "is",
5787
+ "are",
5788
+ "be",
5789
+ "as",
5790
+ "use",
5791
+ "when",
5792
+ "how",
5793
+ "our",
5794
+ "my",
5795
+ "new",
5796
+ "skill",
5797
+ "skills"
5798
+ ]);
5799
+ function tokenizeMultiWordQuery(q) {
5800
+ if (!/\s/.test(q))
5801
+ return [];
5802
+ const parts = q.toLowerCase().split(/[^a-z0-9\u4e00-\u9fff-]+/i).map((t) => t.replace(/^-+|-+$/g, "").trim()).filter((t) => t.length >= 2 && !SEARCH_STOP_WORDS.has(t));
5803
+ return [...new Set(parts)];
5804
+ }
5805
+ function scoreCatalogEntryForQuery(e, q, qSlug, tokens) {
5806
+ const nameLower = e.name.toLowerCase();
5807
+ const nameSlug = normalizeSkillSlug(e.name);
5808
+ const descLower = e.description.toLowerCase();
5809
+ const scenesLower = e.scenes.map((s) => s.toLowerCase());
5810
+ let score = 0;
5811
+ let fullHit = false;
5812
+ if (nameLower === q || qSlug.length > 0 && nameSlug === qSlug) {
5813
+ score += 1000;
5814
+ fullHit = true;
5815
+ } else if (nameLower.includes(q) || qSlug.length >= 3 && nameSlug.includes(qSlug)) {
5816
+ score += 350;
5817
+ fullHit = true;
5818
+ }
5819
+ if (scenesLower.some((s) => s === q || s.includes(q))) {
5820
+ score += 200;
5821
+ fullHit = true;
5822
+ }
5823
+ if (descLower.includes(q)) {
5824
+ score += 150;
5825
+ fullHit = true;
5826
+ }
5827
+ if (tokens.length <= 1) {
5828
+ return fullHit ? score : 0;
5829
+ }
5830
+ let matchedCount = 0;
5831
+ let nameHitCount = 0;
5832
+ for (const tok of tokens) {
5833
+ const tokSlug = normalizeSkillSlug(tok);
5834
+ let hit = false;
5835
+ if (nameLower.includes(tok) || tokSlug.length >= 2 && nameSlug.includes(tokSlug)) {
5836
+ score += 55;
5837
+ nameHitCount++;
5838
+ hit = true;
5839
+ }
5840
+ if (scenesLower.some((s) => s.includes(tok))) {
5841
+ score += 25;
5842
+ hit = true;
5843
+ }
5844
+ if (descLower.includes(tok)) {
5845
+ score += 12;
5846
+ hit = true;
5847
+ }
5848
+ if (hit)
5849
+ matchedCount++;
5850
+ }
5851
+ if (fullHit)
5852
+ return score;
5853
+ const minRequired = tokens.length <= 3 ? 2 : nameHitCount >= 1 ? 2 : Math.min(3, Math.ceil(tokens.length * 0.34));
5854
+ return matchedCount >= minRequired ? score : 0;
5855
+ }
5023
5856
  function findSkillsCommand(args) {
5024
5857
  return Effect4.gen(function* () {
5025
5858
  const store = yield* StorePort;
@@ -5028,7 +5861,7 @@ function findSkillsCommand(args) {
5028
5861
  const catalog = yield* store.readCatalog();
5029
5862
  const q = (args.query ?? "").trim().toLowerCase();
5030
5863
  const scene = args.scene?.trim();
5031
- const matched = catalog.entries.filter((e) => {
5864
+ const candidates = catalog.entries.filter((e) => {
5032
5865
  if (e.libraryId !== targetLib)
5033
5866
  return false;
5034
5867
  if (scene && !e.scenes.includes(scene))
@@ -5037,23 +5870,39 @@ function findSkillsCommand(args) {
5037
5870
  return false;
5038
5871
  if (args.kind && e.kind !== args.kind)
5039
5872
  return false;
5040
- if (!q)
5041
- return true;
5042
- return e.name.toLowerCase().includes(q) || e.description.toLowerCase().includes(q) || e.scenes.some((s) => s.toLowerCase().includes(q));
5873
+ return true;
5043
5874
  });
5044
- return matched.sort((a, b) => {
5045
- if (q) {
5046
- const aExact = a.name.toLowerCase() === q ? 1 : 0;
5047
- const bExact = b.name.toLowerCase() === q ? 1 : 0;
5048
- if (aExact !== bExact)
5049
- return bExact - aExact;
5050
- }
5051
- if (a.kind === "router" && b.kind !== "router")
5875
+ if (!q) {
5876
+ return candidates.sort((a, b) => {
5877
+ if (a.kind === "router" && b.kind !== "router")
5878
+ return -1;
5879
+ if (a.kind !== "router" && b.kind === "router")
5880
+ return 1;
5881
+ return a.name.localeCompare(b.name);
5882
+ });
5883
+ }
5884
+ const qSlug = normalizeSkillSlug(q);
5885
+ const tokens = tokenizeMultiWordQuery(q);
5886
+ const scored = [];
5887
+ for (const e of candidates) {
5888
+ const score = scoreCatalogEntryForQuery(e, q, qSlug, tokens);
5889
+ if (score > 0)
5890
+ scored.push({ entry: e, score });
5891
+ }
5892
+ const visRank = (v) => v === "always" ? 0 : v === "discoverable" ? 1 : 2;
5893
+ scored.sort((a, b) => {
5894
+ if (b.score !== a.score)
5895
+ return b.score - a.score;
5896
+ const vr = visRank(a.entry.visibility) - visRank(b.entry.visibility);
5897
+ if (vr !== 0)
5898
+ return vr;
5899
+ if (a.entry.kind === "router" && b.entry.kind !== "router")
5052
5900
  return -1;
5053
- if (a.kind !== "router" && b.kind === "router")
5901
+ if (a.entry.kind !== "router" && b.entry.kind === "router")
5054
5902
  return 1;
5055
- return a.name.localeCompare(b.name);
5903
+ return a.entry.name.localeCompare(b.entry.name);
5056
5904
  });
5905
+ return scored.map((s) => s.entry);
5057
5906
  });
5058
5907
  }
5059
5908
  function loadSkillCommand(args) {
@@ -5064,12 +5913,22 @@ function loadSkillCommand(args) {
5064
5913
  if (args.refresh) {
5065
5914
  yield* syncCommand({ libraryId, dedupeWindowMs: 0 });
5066
5915
  }
5916
+ const findEntryByNameOrSlug = (entries) => {
5917
+ const targetLower = args.name.trim().toLowerCase();
5918
+ const exact = entries.find((e) => e.libraryId === libraryId && e.name.toLowerCase() === targetLower);
5919
+ if (exact)
5920
+ return exact;
5921
+ const targetSlug = normalizeSkillSlug(args.name);
5922
+ if (!targetSlug)
5923
+ return;
5924
+ return entries.find((e) => e.libraryId === libraryId && normalizeSkillSlug(e.name) === targetSlug);
5925
+ };
5067
5926
  let catalog = yield* store.readCatalog();
5068
- let entry = catalog.entries.find((e) => e.libraryId === libraryId && e.name.toLowerCase() === args.name.trim().toLowerCase());
5927
+ let entry = findEntryByNameOrSlug(catalog.entries);
5069
5928
  if (!entry && !args.refresh) {
5070
5929
  yield* syncCommand({ libraryId, dedupeWindowMs: 0 });
5071
5930
  catalog = yield* store.readCatalog();
5072
- entry = catalog.entries.find((e) => e.libraryId === libraryId && e.name.toLowerCase() === args.name.trim().toLowerCase());
5931
+ entry = findEntryByNameOrSlug(catalog.entries);
5073
5932
  }
5074
5933
  if (!entry) {
5075
5934
  return yield* Effect4.fail(new NotFoundError({
@@ -5121,6 +5980,17 @@ function loadSkillCommand(args) {
5121
5980
  catch: (e) => new StoreError({ message: String(e) })
5122
5981
  });
5123
5982
  }
5983
+ yield* Effect4.tryPromise(async () => {
5984
+ if (entry.enabled) {
5985
+ await upsertByNameSymlink(store.paths.byNameRoot, entry.name, storeDir);
5986
+ }
5987
+ for (const [reqName, reqDir] of Object.entries(reqPaths)) {
5988
+ await upsertByNameSymlink(store.paths.byNameRoot, reqName, reqDir);
5989
+ }
5990
+ }).pipe(Effect4.mapError((err) => new StoreError({
5991
+ path: store.paths.byNameRoot,
5992
+ message: `Failed updating by-name link on load: ${String(err)}`
5993
+ })));
5124
5994
  yield* Effect4.tryPromise(() => appendSkillUsageEvent({ action: "load", skillName: entry.name, libraryId }, store.paths.homeDir)).pipe(Effect4.catch(() => Effect4.void));
5125
5995
  return {
5126
5996
  entry: { ...entry, materializedPath: storeDir },
@@ -5198,6 +6068,18 @@ function loadSkillCommand(args) {
5198
6068
  libraries: { ...freshCat.libraries, [libraryId]: workingLib },
5199
6069
  entries: updatedEntries
5200
6070
  });
6071
+ yield* Effect4.tryPromise(async () => {
6072
+ for (const cid of closureIds) {
6073
+ const sk = effectiveById.get(cid);
6074
+ const matDir = matDirs.get(cid);
6075
+ if (sk?.enabled && matDir) {
6076
+ await upsertByNameSymlink(store.paths.byNameRoot, sk.name, matDir);
6077
+ }
6078
+ }
6079
+ }).pipe(Effect4.mapError((err) => new StoreError({
6080
+ path: store.paths.byNameRoot,
6081
+ message: `Failed updating by-name link on load: ${String(err)}`
6082
+ })));
5201
6083
  const finalStoreDir = matDirs.get(entry.skillId);
5202
6084
  const mdPath = nodePath5.join(finalStoreDir, "SKILL.md");
5203
6085
  const md = yield* Effect4.tryPromise({
@@ -5223,52 +6105,346 @@ function loadSkillCommand(args) {
5223
6105
  }));
5224
6106
  });
5225
6107
  }
6108
+ function materializeSkillOutsideCatalog(args) {
6109
+ return Effect4.gen(function* () {
6110
+ const notion = yield* NotionPort;
6111
+ const store = yield* StorePort;
6112
+ const upstream = yield* UpstreamPort;
6113
+ return yield* store.withExclusiveLock(`load-${args.libraryId.slice(0, 8)}`, Effect4.gen(function* () {
6114
+ const freshCat = yield* store.readCatalog();
6115
+ let workingLib = freshCat.libraries[args.libraryId];
6116
+ const filesBySkill = new Map;
6117
+ for (const f of Object.values(workingLib.files)) {
6118
+ const arr = filesBySkill.get(f.skillId) ?? [];
6119
+ arr.push(f);
6120
+ filesBySkill.set(f.skillId, arr);
6121
+ }
6122
+ const sk = workingLib.skills[args.skill.id] ?? args.skill;
6123
+ let src = sk.originSourceId ? workingLib.sources[sk.originSourceId] ?? args.sourcesById.get(sk.originSourceId) ?? null : null;
6124
+ let commitSha = src?.pinnedCommit ?? null;
6125
+ if (src && !commitSha) {
6126
+ commitSha = yield* upstream.resolveHeadCommit(src.repoUrl, src.ref);
6127
+ src = { ...src, pinnedCommit: commitSha };
6128
+ }
6129
+ if (!src || sk.customMain) {
6130
+ const cachedMain = workingLib.mainHashCache[sk.id];
6131
+ if (!cachedMain || cachedMain.lastEditedTime !== sk.lastEditedTime) {
6132
+ const fetched = yield* notion.readSkillBody(sk.id, { skipPageMeta: true });
6133
+ workingLib = {
6134
+ ...workingLib,
6135
+ mainHashCache: {
6136
+ ...workingLib.mainHashCache,
6137
+ [sk.id]: {
6138
+ lastEditedTime: sk.lastEditedTime,
6139
+ rawBody: fetched.rawMarkdown,
6140
+ rawBodySha256: sha256Hex(fetched.rawMarkdown),
6141
+ upstreamFilesPageId: fetched.upstreamFilesPageId
6142
+ }
6143
+ }
6144
+ };
6145
+ }
6146
+ }
6147
+ const overlayFiles = normalizeOverlayFiles(filesBySkill.get(sk.id) ?? []);
6148
+ const subDigest = src ? extractSubtreeDigestFromRevision(sk.revision) : null;
6149
+ const baseIdentity = src ? subDigest ? `sub:${subDigest}` : commitSha : null;
6150
+ const mainIdentity = !src || sk.customMain ? workingLib.mainHashCache[sk.id]?.rawBodySha256 ?? sk.lastEditedTime : `upstream:${baseIdentity}:${sk.sourcePath}`;
6151
+ const effectiveRev = computeEffectiveRev({
6152
+ originPinnedCommit: baseIdentity,
6153
+ sourcePath: sk.sourcePath,
6154
+ customMain: sk.customMain,
6155
+ name: sk.name,
6156
+ description: sk.description,
6157
+ mainContentIdentity: mainIdentity,
6158
+ overlays: overlayFiles.map((ov) => ({
6159
+ path: ov.path,
6160
+ status: ov.status === "delete" ? "delete" : "override",
6161
+ contentIdentity: ov.sha256 || ov.externalUrl || ov.lastEditedTime,
6162
+ executable: ov.executable
6163
+ })),
6164
+ requiresRevs: []
6165
+ });
6166
+ const mat = yield* materializeOneSkill({
6167
+ libraryId: args.libraryId,
6168
+ libState: workingLib,
6169
+ skill: sk,
6170
+ source: src,
6171
+ overlayFiles,
6172
+ effectiveRev
6173
+ });
6174
+ workingLib = mat.updatedLibState;
6175
+ yield* store.writeCatalog({
6176
+ ...freshCat,
6177
+ updatedAt: new Date().toISOString(),
6178
+ libraries: { ...freshCat.libraries, [args.libraryId]: workingLib }
6179
+ });
6180
+ if (sk.enabled) {
6181
+ yield* Effect4.tryPromise(() => upsertByNameSymlink(store.paths.byNameRoot, sk.name, mat.storeDir)).pipe(Effect4.catch(() => Effect4.void));
6182
+ }
6183
+ return {
6184
+ libraryId: args.libraryId,
6185
+ skillId: sk.id,
6186
+ name: sk.name,
6187
+ description: sk.description,
6188
+ enabled: sk.enabled,
6189
+ visibility: sk.visibility,
6190
+ kind: sk.kind,
6191
+ profiles: [...sk.profiles],
6192
+ scenes: [...sk.scenes],
6193
+ requiresIds: [...sk.requiresIds],
6194
+ originSourceId: src?.id ?? null,
6195
+ originRepoUrl: src?.repoUrl ?? null,
6196
+ originRef: src?.ref ?? null,
6197
+ originPinnedCommit: commitSha,
6198
+ sourcePath: sk.sourcePath,
6199
+ customMain: sk.customMain,
6200
+ revision: sk.revision,
6201
+ previewHash: sk.previewHash,
6202
+ effectiveRev,
6203
+ materializedPath: mat.storeDir,
6204
+ warnings: [],
6205
+ overlays: overlayFiles.map((ov) => ({
6206
+ id: ov.id,
6207
+ path: ov.path,
6208
+ status: ov.status === "delete" ? "delete" : "override",
6209
+ externalUrl: ov.externalUrl,
6210
+ sha256: ov.sha256,
6211
+ executable: ov.executable,
6212
+ lastEditedTime: ov.lastEditedTime
6213
+ })),
6214
+ lastEditedTime: sk.lastEditedTime
6215
+ };
6216
+ }));
6217
+ });
6218
+ }
5226
6219
  function exportCommand(args) {
5227
6220
  return Effect4.gen(function* () {
5228
6221
  const store = yield* StorePort;
5229
6222
  const { config, libraryId } = yield* loadResolvedLibrary(args.libraryId);
5230
- if (!args.toDir) {
5231
- yield* syncCommand({ libraryId, dedupeWindowMs: 0 });
6223
+ if (args.specPath && args.toDir) {
6224
+ return yield* Effect4.fail(new ConfigError({
6225
+ message: "Cannot combine --spec with --to; choose either a spec file or a single target directory."
6226
+ }));
6227
+ }
6228
+ const hasFilterFlags = Boolean(args.skills && args.skills.length > 0 || args.bundles && args.bundles.length > 0 || args.exclude && args.exclude.length > 0 || args.includeRequires !== undefined || args.noRouter || args.profile || args.scene || args.includeNonDefault);
6229
+ if (!args.toDir && !args.specPath) {
6230
+ if (hasFilterFlags) {
6231
+ return yield* Effect4.fail(new ConfigError({
6232
+ message: "Export filter flags (--skills, --exclude, --with-requires, --no-requires, --no-router, --profile, --scene) require --to <dir> or --spec <file>."
6233
+ }));
6234
+ }
6235
+ const syncRep = yield* syncCommand({ libraryId, dedupeWindowMs: 0 });
6236
+ const resolvedExports = yield* resolveConfiguredExports(config, store.paths.configPath);
5232
6237
  const allExported = [];
5233
- for (const exp of config.exports) {
6238
+ const targetResults = [];
6239
+ for (const { target: exp } of resolvedExports.targets) {
5234
6240
  const root = resolveHomePath(exp.dir);
5235
6241
  const names = yield* Effect4.tryPromise(() => fsp5.readdir(root)).pipe(Effect4.catch(() => Effect4.succeed([])));
5236
- for (const n of names.sort()) {
5237
- if (!n.startsWith("."))
5238
- allExported.push(nodePath5.join(root, n));
6242
+ const dirs = names.filter((n) => !n.startsWith(".")).sort().map((n) => nodePath5.join(root, n));
6243
+ allExported.push(...dirs);
6244
+ targetResults.push({
6245
+ dir: root,
6246
+ mode: exp.mode,
6247
+ exportedDirs: dirs,
6248
+ routerSkill: null,
6249
+ warnings: []
6250
+ });
6251
+ }
6252
+ return { exportedDirs: allExported, targets: targetResults, warnings: syncRep.warnings };
6253
+ }
6254
+ let planItems;
6255
+ if (args.specPath) {
6256
+ if (args.skills && args.skills.length > 0 || args.bundles && args.bundles.length > 0 || args.profile || args.scene || args.includeNonDefault) {
6257
+ return yield* Effect4.fail(new ConfigError({
6258
+ message: "Cannot combine --spec with --skills, --profile, --scene, or --include-non-default; declare target selectors inside the spec file (only --exclude, --with-requires/--no-requires, --no-router, and default --mode may override a spec)."
6259
+ }));
6260
+ }
6261
+ const loadedSpec = yield* loadExportSpecFile({
6262
+ specPath: args.specPath,
6263
+ ...config.bundles ? { baseBundles: config.bundles } : {},
6264
+ ...args.mode ? { defaultMode: args.mode } : {}
6265
+ });
6266
+ const seenSpecDirs = new Set;
6267
+ for (const rawTarget of loadedSpec.targets) {
6268
+ const resolvedDir = resolveHomePath(rawTarget.dir);
6269
+ if (seenSpecDirs.has(resolvedDir)) {
6270
+ return yield* Effect4.fail(new ConfigError({
6271
+ path: loadedSpec.specPath,
6272
+ message: `Spec file declares duplicate export target directory '${resolvedDir}'; each target directory must be unique.`
6273
+ }));
5239
6274
  }
6275
+ seenSpecDirs.add(resolvedDir);
5240
6276
  }
5241
- return { exportedDirs: allExported };
6277
+ const cliExcludes = args.exclude ?? [];
6278
+ planItems = loadedSpec.targets.map((rawTarget) => {
6279
+ const mergedExclude = cliExcludes.length > 0 ? Array.from(new Set([...rawTarget.exclude ?? [], ...cliExcludes])) : rawTarget.exclude;
6280
+ const target = {
6281
+ ...rawTarget,
6282
+ ...mergedExclude !== undefined ? { exclude: mergedExclude } : {},
6283
+ ...args.includeRequires !== undefined ? { include_requires: args.includeRequires } : {},
6284
+ ...args.noRouter ? { router: { enabled: false } } : {}
6285
+ };
6286
+ return {
6287
+ target,
6288
+ bundles: loadedSpec.bundles,
6289
+ sourceFile: loadedSpec.specPath
6290
+ };
6291
+ });
6292
+ } else {
6293
+ const adhocTarget = {
6294
+ dir: args.toDir,
6295
+ ...args.profile ? { profiles: [args.profile] } : {},
6296
+ ...args.scene ? { scenes: [args.scene] } : {},
6297
+ ...args.skills && args.skills.length > 0 ? { skills: [...args.skills] } : {},
6298
+ ...args.bundles && args.bundles.length > 0 ? { bundles: [...args.bundles] } : {},
6299
+ ...args.exclude && args.exclude.length > 0 ? { exclude: [...args.exclude] } : {},
6300
+ ...args.includeRequires !== undefined ? { include_requires: args.includeRequires } : {},
6301
+ ...args.noRouter ? { router: { enabled: false } } : {},
6302
+ default_only: !args.includeNonDefault && !args.scene,
6303
+ ...args.includeNonDefault ? { include_non_default: true } : {},
6304
+ mode: args.mode ?? "symlink"
6305
+ };
6306
+ planItems = [
6307
+ {
6308
+ target: adhocTarget,
6309
+ bundles: config.bundles ?? {},
6310
+ sourceFile: null
6311
+ }
6312
+ ];
5242
6313
  }
5243
- const adhocTarget = {
5244
- dir: args.toDir,
5245
- ...args.profile ? { profiles: [args.profile] } : {},
5246
- ...args.scene ? { scenes: [args.scene] } : {},
5247
- default_only: !args.includeNonDefault && !args.scene,
5248
- ...args.includeNonDefault ? { include_non_default: true } : {},
5249
- mode: args.mode ?? "symlink"
5250
- };
5251
6314
  const catalog = yield* store.readCatalog();
5252
- const libState = catalog.libraries[libraryId];
5253
- if (!libState) {
6315
+ if (!catalog.libraries[libraryId]) {
5254
6316
  yield* syncCommand({ libraryId, dedupeWindowMs: 0 });
5255
6317
  }
5256
- const freshCat = yield* store.readCatalog();
6318
+ let freshCat = yield* store.readCatalog();
5257
6319
  const freshLib = freshCat.libraries[libraryId];
5258
6320
  const sourcesById = new Map(Object.entries(freshLib.sources));
5259
6321
  const effective = filterEffectiveSkills(Object.values(freshLib.skills), sourcesById);
5260
- const selectedSkills = selectExportSkills(effective, adhocTarget);
5261
- const selectedEntries = [];
5262
- for (const sk of selectedSkills) {
5263
- const loaded = yield* loadSkillCommand({ name: sk.name, libraryId });
5264
- selectedEntries.push(loaded.entry);
5265
- }
5266
- const pub = yield* publishExportTarget({
5267
- target: adhocTarget,
5268
- selectedEntries,
5269
- storeRoot: store.paths.storeRoot
6322
+ const effectiveById = new Map(effective.map((s) => [s.id, s]));
6323
+ const catalogSkills = filterCatalogSkills(effective, config.profiles);
6324
+ const entryCacheById = new Map(freshCat.entries.filter((e) => e.libraryId === libraryId).map((e) => [e.skillId, e]));
6325
+ const ensureMaterializedEntry = (sk) => Effect4.gen(function* () {
6326
+ const cached = entryCacheById.get(sk.id);
6327
+ if (cached?.materializedPath && !cached.originPinnedCommit?.startsWith("ref:")) {
6328
+ const verified = yield* store.hasVerifiedStorePackage(libraryId, sk.id, cached.effectiveRev);
6329
+ if (verified) {
6330
+ yield* Effect4.tryPromise(() => upsertByNameSymlink(store.paths.byNameRoot, cached.name, cached.materializedPath)).pipe(Effect4.catch(() => Effect4.void));
6331
+ return cached;
6332
+ }
6333
+ }
6334
+ if (cached) {
6335
+ const loaded = yield* loadSkillCommand({ name: sk.name, libraryId });
6336
+ freshCat = yield* store.readCatalog();
6337
+ for (const e of freshCat.entries) {
6338
+ if (e.libraryId === libraryId)
6339
+ entryCacheById.set(e.skillId, e);
6340
+ }
6341
+ entryCacheById.set(sk.id, loaded.entry);
6342
+ return loaded.entry;
6343
+ }
6344
+ const outsideEntry = yield* materializeSkillOutsideCatalog({
6345
+ libraryId,
6346
+ skill: sk,
6347
+ sourcesById
6348
+ });
6349
+ entryCacheById.set(sk.id, outsideEntry);
6350
+ return outsideEntry;
5270
6351
  });
5271
- return { exportedDirs: pub.exportedDirs };
6352
+ const allExportedDirs = [];
6353
+ const targetResults = [];
6354
+ const allWarnings = [];
6355
+ const nowIso = new Date().toISOString();
6356
+ for (const planItem of planItems) {
6357
+ const target = planItem.target;
6358
+ const selection = resolveExportSelection({
6359
+ allEffectiveSkills: effective,
6360
+ catalogSkills,
6361
+ target,
6362
+ bundles: planItem.bundles
6363
+ });
6364
+ const targetWarnings = [];
6365
+ if (selection.missingBundles.length > 0) {
6366
+ targetWarnings.push(`Export target '${target.dir}' references unknown bundle(s): ${selection.missingBundles.join(", ")}.`);
6367
+ }
6368
+ if (selection.missingSkills.length > 0) {
6369
+ targetWarnings.push(`Export target '${target.dir}' references unknown or disabled skill(s): ${selection.missingSkills.join(", ")}.`);
6370
+ }
6371
+ for (const [sid, badReqs] of selection.missingOrDisabledRequires) {
6372
+ const skName = effectiveById.get(sid)?.name ?? sid;
6373
+ targetWarnings.push(`Skill '${skName}' has disabled or missing Requires (${badReqs.join(", ")}); skipped without resurrecting.`);
6374
+ }
6375
+ const selectedEntries = [];
6376
+ for (const sk of selection.selected) {
6377
+ selectedEntries.push(yield* ensureMaterializedEntry(sk));
6378
+ }
6379
+ const directNameSet = new Set(selectedEntries.map((e) => e.name.toLowerCase()));
6380
+ const discoverableEntries = selection.discoverable.map((s) => entryCacheById.get(s.id)).filter((e) => Boolean(e) && !directNameSet.has(e.name.toLowerCase()));
6381
+ let routerEntry = null;
6382
+ const routerName = (target.router?.name ?? "skill-catalog").trim() || "skill-catalog";
6383
+ if (selection.resolvedRouterEnabled && discoverableEntries.length > 0 && !directNameSet.has(routerName.toLowerCase())) {
6384
+ const synth = synthesizeSkillCatalogPackage({
6385
+ routerName,
6386
+ discoverableEntries,
6387
+ allEntriesById: entryCacheById,
6388
+ byNameRoot: store.paths.byNameRoot
6389
+ });
6390
+ const routerSkillId = `_router-${routerName}`;
6391
+ const routerStoreDir = yield* store.publishImmutablePackage({
6392
+ libraryId,
6393
+ skillId: routerSkillId,
6394
+ effectiveRev: synth.effectiveRev,
6395
+ files: synth.files
6396
+ });
6397
+ routerEntry = {
6398
+ libraryId,
6399
+ skillId: routerSkillId,
6400
+ name: routerName,
6401
+ description: `Auto-generated local catalog of ${discoverableEntries.length} discoverable skills`,
6402
+ enabled: true,
6403
+ visibility: "always",
6404
+ kind: "router",
6405
+ profiles: target.profiles ? [...target.profiles] : ["default"],
6406
+ scenes: [],
6407
+ requiresIds: [],
6408
+ originSourceId: null,
6409
+ originRepoUrl: null,
6410
+ originRef: null,
6411
+ originPinnedCommit: null,
6412
+ sourcePath: "",
6413
+ customMain: false,
6414
+ revision: synth.effectiveRev.slice(0, 12),
6415
+ previewHash: "",
6416
+ effectiveRev: synth.effectiveRev,
6417
+ materializedPath: routerStoreDir,
6418
+ warnings: [],
6419
+ overlays: [],
6420
+ lastEditedTime: nowIso
6421
+ };
6422
+ }
6423
+ const finalExportEntries = routerEntry ? [...selectedEntries, routerEntry] : selectedEntries;
6424
+ const pub = yield* publishExportTarget({
6425
+ target,
6426
+ selectedEntries: finalExportEntries,
6427
+ storeRoot: store.paths.storeRoot,
6428
+ ...args.onConflict ? { onConflict: args.onConflict } : {}
6429
+ });
6430
+ if (pub.warnings.length > 0) {
6431
+ targetWarnings.push(...pub.warnings);
6432
+ }
6433
+ allExportedDirs.push(...pub.exportedDirs);
6434
+ allWarnings.push(...targetWarnings);
6435
+ targetResults.push({
6436
+ dir: resolveHomePath(target.dir),
6437
+ mode: target.mode,
6438
+ exportedDirs: pub.exportedDirs,
6439
+ routerSkill: routerEntry ? routerName : null,
6440
+ warnings: targetWarnings
6441
+ });
6442
+ }
6443
+ return {
6444
+ exportedDirs: allExportedDirs,
6445
+ targets: targetResults,
6446
+ warnings: allWarnings
6447
+ };
5272
6448
  });
5273
6449
  }
5274
6450
  function statusCommand(args) {
@@ -5323,7 +6499,7 @@ function statusCommand(args) {
5323
6499
  import { randomUUID as randomUUID5 } from "node:crypto";
5324
6500
  import * as fsp6 from "node:fs/promises";
5325
6501
  import * as nodePath6 from "node:path";
5326
- import { Effect as Effect5, Option, Schema as Schema3 } from "effect";
6502
+ import { Effect as Effect5, Option, Schema as Schema4 } from "effect";
5327
6503
  var WORK_META_FILE = ".ntn-skill.json";
5328
6504
  var IGNORED_WORKDIR_NAMES = new Set([
5329
6505
  WORK_META_FILE,
@@ -5584,7 +6760,7 @@ function readWorkMeta(workdir) {
5584
6760
  const abs = nodePath6.resolve(workdir);
5585
6761
  const metaPath = nodePath6.join(abs, WORK_META_FILE);
5586
6762
  return Effect5.tryPromise({
5587
- try: async () => Schema3.decodeUnknownSync(WorkMetaSchema)(JSON.parse(await fsp6.readFile(metaPath, "utf8"))),
6763
+ try: async () => Schema4.decodeUnknownSync(WorkMetaSchema)(JSON.parse(await fsp6.readFile(metaPath, "utf8"))),
5588
6764
  catch: (err) => err?.code === "ENOENT" ? new NotFoundError({
5589
6765
  entity: "workdir",
5590
6766
  target: abs,
@@ -5904,7 +7080,7 @@ function listWorkdirsCommand() {
5904
7080
  const raw = await fsp6.readFile(nodePath6.join(full, WORK_META_FILE), "utf8");
5905
7081
  out.push({
5906
7082
  workdir: full,
5907
- meta: Schema3.decodeUnknownSync(WorkMetaSchema)(JSON.parse(raw))
7083
+ meta: Schema4.decodeUnknownSync(WorkMetaSchema)(JSON.parse(raw))
5908
7084
  });
5909
7085
  } catch {}
5910
7086
  }
@@ -5929,6 +7105,9 @@ function cleanWorkdirsCommand(olderThanDays = 7) {
5929
7105
  return cleaned;
5930
7106
  });
5931
7107
  }
7108
+ function resolveImportedSkillVisibility(disableModelInvocation, requestedVisibility) {
7109
+ return disableModelInvocation ? "manual" : requestedVisibility ?? "manual";
7110
+ }
5932
7111
  function createNewSkillCommand(args) {
5933
7112
  return Effect5.gen(function* () {
5934
7113
  const notion = yield* NotionPort;
@@ -5968,13 +7147,14 @@ function createNewSkillCommand(args) {
5968
7147
  textContent
5969
7148
  });
5970
7149
  }
7150
+ const resolvedVisibility = args.visibility ?? (args.defaultContext !== undefined ? args.defaultContext ? "always" : "manual" : parsed.disableModelInvocation ? "manual" : "discoverable");
5971
7151
  const created = yield* notion.createSkillPage({
5972
7152
  libraryId,
5973
7153
  skillsDs: binding.skills_ds,
5974
7154
  name: skillName,
5975
7155
  description: (parsed.description ?? "").trim(),
5976
7156
  enabled: true,
5977
- visibility: args.visibility ?? (args.defaultContext !== undefined ? args.defaultContext ? "always" : "manual" : "discoverable"),
7157
+ visibility: resolvedVisibility,
5978
7158
  ...args.kind ? { kind: args.kind } : {},
5979
7159
  profiles: args.profiles?.length ? args.profiles : ["default"],
5980
7160
  scenes: args.scenes ?? [],
@@ -5998,12 +7178,13 @@ function createNewSkillCommand(args) {
5998
7178
  executable: sf.executable,
5999
7179
  textContent: sf.textContent
6000
7180
  }).pipe(Effect5.map((up) => up.pageId)), { concurrency: UPSTREAM_SKILL_CONCURRENCY });
7181
+ const resolvedExports = yield* resolveConfiguredExports(config, store.paths.configPath);
6001
7182
  const isInExportRoot = yield* Effect5.tryPromise(async () => {
6002
7183
  const lst = await fsp6.lstat(absDir).catch(() => null);
6003
7184
  if (!lst || lst.isSymbolicLink())
6004
7185
  return false;
6005
7186
  const realAbsParent = await fsp6.realpath(nodePath6.dirname(absDir)).catch(() => nodePath6.dirname(absDir));
6006
- for (const exp of config.exports) {
7187
+ for (const { target: exp } of resolvedExports.targets) {
6007
7188
  const expRoot = resolveHomePath(exp.dir);
6008
7189
  const realExpRoot = await fsp6.realpath(expRoot).catch(() => expRoot);
6009
7190
  if (nodePath6.dirname(absDir) === expRoot || realAbsParent === realExpRoot) {
@@ -6012,8 +7193,9 @@ function createNewSkillCommand(args) {
6012
7193
  }
6013
7194
  return false;
6014
7195
  }).pipe(Effect5.catch(() => Effect5.succeed(false)));
7196
+ const shouldAdopt = args.adopt === undefined ? isInExportRoot : args.adopt;
6015
7197
  let adoptedSourceDir = false;
6016
- if (isInExportRoot || args.adopt === true) {
7198
+ if (shouldAdopt) {
6017
7199
  yield* trashPathEffect(absDir);
6018
7200
  adoptedSourceDir = true;
6019
7201
  }
@@ -6022,11 +7204,26 @@ function createNewSkillCommand(args) {
6022
7204
  dedupeWindowMs: 0,
6023
7205
  readYourWrites: { skillIds: [created.id], fileIds: createdFileIds }
6024
7206
  });
7207
+ const exportedAtSourcePath = adoptedSourceDir && isInExportRoot ? yield* Effect5.tryPromise(async () => {
7208
+ const lst = await fsp6.lstat(absDir).catch(() => null);
7209
+ if (!lst)
7210
+ return false;
7211
+ if (lst.isSymbolicLink())
7212
+ return true;
7213
+ if (lst.isDirectory()) {
7214
+ const marker = await fsp6.stat(nodePath6.join(absDir, ".ntn-managed-copy.json")).catch(() => null);
7215
+ return Boolean(marker?.isFile());
7216
+ }
7217
+ return false;
7218
+ }).pipe(Effect5.catch(() => Effect5.succeed(false))) : false;
6025
7219
  return {
6026
7220
  skillId: created.id,
6027
7221
  name: skillName,
7222
+ visibility: resolvedVisibility,
6028
7223
  uploadedFiles: createdFileIds.length,
6029
- adoptedSourceDir
7224
+ adoptedSourceDir,
7225
+ adoptedFromExportRoot: adoptedSourceDir && isInExportRoot,
7226
+ exportedAtSourcePath
6030
7227
  };
6031
7228
  });
6032
7229
  }
@@ -6426,7 +7623,7 @@ function addSourceCommand(args) {
6426
7623
  name: d.name,
6427
7624
  description: d.description,
6428
7625
  enabled: true,
6429
- visibility: args.visibility ?? "manual",
7626
+ visibility: resolveImportedSkillVisibility(d.disableModelInvocation, args.visibility),
6430
7627
  profiles: ["default"],
6431
7628
  scenes: args.scenes ? [...args.scenes] : [],
6432
7629
  requiresIds: [],
@@ -6581,7 +7778,7 @@ function syncSourceSkillsCommand(args) {
6581
7778
  name: d.name,
6582
7779
  description: d.description,
6583
7780
  enabled: true,
6584
- visibility: "manual",
7781
+ visibility: resolveImportedSkillVisibility(d.disableModelInvocation),
6585
7782
  profiles: ["default"],
6586
7783
  scenes: [],
6587
7784
  requiresIds: [],
@@ -6944,25 +8141,40 @@ function upstreamCheckOrApplyCommand(args) {
6944
8141
  let nextDesc;
6945
8142
  if (!sk.customMain) {
6946
8143
  const currentBody = yield* notion.readSkillBody(sk.id);
8144
+ const upstreamMain = subtreeFiles.find((f) => f.path === "SKILL.md");
8145
+ const rawMainText = upstreamMain ? new TextDecoder().decode(upstreamMain.bytes) : null;
6947
8146
  if (sk.previewHash && sha256Hex(currentBody.rawMarkdown) !== sk.previewHash) {
6948
- previewDriftWarnings.push(`Skill '${sk.name}': 网页预览已被修改但未勾选 Custom Main(修改尚未进入消费),已拒绝静默覆盖预览正文。`);
6949
- } else {
6950
- const upstreamMain = subtreeFiles.find((f) => f.path === "SKILL.md");
6951
- if (upstreamMain) {
6952
- const rawMainText = new TextDecoder().decode(upstreamMain.bytes);
8147
+ let matchesTargetUpstream = false;
8148
+ if (rawMainText !== null) {
8149
+ const preparedTarget = prepareSkillMarkdownForNotionBody(rawMainText).cleanNotionMarkdown;
8150
+ const renderedTarget = yield* Effect5.tryPromise(() => renderBlocksToMarkdown(markdownToBlocks(preparedTarget), async () => [])).pipe(Effect5.catch(() => Effect5.succeed("")));
8151
+ const trimmedLive = currentBody.rawMarkdown.trim();
8152
+ if (trimmedLive === preparedTarget.trim() || renderedTarget.length > 0 && trimmedLive === renderedTarget.trim()) {
8153
+ matchesTargetUpstream = true;
8154
+ }
8155
+ }
8156
+ if (matchesTargetUpstream && rawMainText !== null) {
6953
8157
  const parsedMain = parseSkillFrontmatter(rawMainText);
6954
8158
  if (parsedMain.description !== undefined && parsedMain.description !== sk.description) {
6955
8159
  nextDesc = parsedMain.description;
6956
8160
  }
6957
- yield* notion.writeSkillBody({
6958
- libraryId,
6959
- skillId: sk.id,
6960
- markdownBody: rawMainText,
6961
- preserveUpstreamChild: true
6962
- });
6963
- const afterBody = yield* notion.readSkillBody(sk.id);
6964
- nextPreviewHash = sha256Hex(afterBody.rawMarkdown);
8161
+ nextPreviewHash = sha256Hex(currentBody.rawMarkdown);
8162
+ } else {
8163
+ previewDriftWarnings.push(`Skill '${sk.name}': 网页预览已被修改但未勾选 Custom Main(修改尚未进入消费),已拒绝静默覆盖预览正文。`);
6965
8164
  }
8165
+ } else if (rawMainText !== null) {
8166
+ const parsedMain = parseSkillFrontmatter(rawMainText);
8167
+ if (parsedMain.description !== undefined && parsedMain.description !== sk.description) {
8168
+ nextDesc = parsedMain.description;
8169
+ }
8170
+ yield* notion.writeSkillBody({
8171
+ libraryId,
8172
+ skillId: sk.id,
8173
+ markdownBody: rawMainText,
8174
+ preserveUpstreamChild: true
8175
+ });
8176
+ const afterBody = yield* notion.readSkillBody(sk.id);
8177
+ nextPreviewHash = sha256Hex(afterBody.rawMarkdown);
6966
8178
  }
6967
8179
  }
6968
8180
  yield* notion.updateSkillProps({
@@ -7013,7 +8225,7 @@ function upstreamCheckOrApplyCommand(args) {
7013
8225
  name: d.name,
7014
8226
  description: d.description,
7015
8227
  enabled: true,
7016
- visibility: "manual",
8228
+ visibility: resolveImportedSkillVisibility(d.disableModelInvocation),
7017
8229
  profiles: ["default"],
7018
8230
  scenes: [],
7019
8231
  requiresIds: [],
@@ -7365,7 +8577,8 @@ function runScheduledJobCommand(args) {
7365
8577
  full: false,
7366
8578
  dedupeWindowMs: 5000
7367
8579
  });
7368
- const summary = res.coalesced ? `coalesced library=${res.libraryId} catalog=${res.catalogCount}` : `library=${res.libraryId} catalog=${res.catalogCount} materialized=${res.materializedCount} exported=${res.exportedCount}`;
8580
+ const warnSuffix = res.warnings.length > 0 ? ` warnings=${res.warnings.length}` : "";
8581
+ const summary = res.coalesced ? `coalesced library=${res.libraryId} catalog=${res.catalogCount}` : `library=${res.libraryId} catalog=${res.catalogCount} materialized=${res.materializedCount} exported=${res.exportedCount}${warnSuffix}`;
7369
8582
  return {
7370
8583
  job: args.job,
7371
8584
  ok: true,
@@ -7382,7 +8595,8 @@ function runScheduledJobCommand(args) {
7382
8595
  dedupeWindowMs: 0
7383
8596
  });
7384
8597
  const cleaned = yield* cleanWorkdirsCommand(7);
7385
- const summary = `library=${res.libraryId} catalog=${res.catalogCount} materialized=${res.materializedCount} exported=${res.exportedCount} pruned=${res.prunedCount} cleanedWorkdirs=${cleaned.length}`;
8598
+ const warnSuffix = res.warnings.length > 0 ? ` warnings=${res.warnings.length}` : "";
8599
+ const summary = `library=${res.libraryId} catalog=${res.catalogCount} materialized=${res.materializedCount} exported=${res.exportedCount} pruned=${res.prunedCount} cleanedWorkdirs=${cleaned.length}${warnSuffix}`;
7386
8600
  return {
7387
8601
  job: args.job,
7388
8602
  ok: true,
@@ -8449,6 +9663,399 @@ async function uninstallBundledSkill(args) {
8449
9663
  });
8450
9664
  }
8451
9665
 
9666
+ // packages/cli/src/mcp-server.ts
9667
+ var DEFAULT_MCP_PROTOCOL_VERSION = "2025-03-26";
9668
+ var SUPPORTED_MCP_PROTOCOL_VERSIONS = new Set(["2024-11-05", "2025-03-26", "2025-06-18"]);
9669
+ var DEFAULT_MCP_INSTRUCTIONS = "On-demand Notion skills catalog. Use skill_find to discover specialized skills not already in top-level context and skill_load to read a matched skill; skip for routine coding/Q&A.";
9670
+ var VALID_VISIBILITIES = new Set(["always", "discoverable", "manual"]);
9671
+ var VALID_KINDS = new Set(["skill", "router", "prompt"]);
9672
+ var READ_ONLY_TOOL_ANNOTATIONS = {
9673
+ readOnlyHint: true,
9674
+ destructiveHint: false,
9675
+ idempotentHint: true,
9676
+ openWorldHint: false
9677
+ };
9678
+ function formatErrorMessage(err) {
9679
+ if (err && typeof err === "object" && "message" in err) {
9680
+ return String(err.message);
9681
+ }
9682
+ return String(err);
9683
+ }
9684
+ function makeToolResult(text, isError = false) {
9685
+ return {
9686
+ content: [{ type: "text", text }],
9687
+ ...isError ? { isError: true } : {}
9688
+ };
9689
+ }
9690
+ function buildResolvedInstructions(customInstructions, allowedScenes) {
9691
+ const base = customInstructions !== undefined ? customInstructions.trim() : DEFAULT_MCP_INSTRUCTIONS;
9692
+ if (allowedScenes.length === 0)
9693
+ return base;
9694
+ const scopeNote = `Scoped to scenes: ${allowedScenes.join(", ")}.`;
9695
+ return base ? `${base} ${scopeNote}` : scopeNote;
9696
+ }
9697
+ function buildToolDefinitions(allowedScenes) {
9698
+ const scopeSuffix = allowedScenes.length > 0 ? ` Scoped to scenes: ${allowedScenes.join(", ")}.` : "";
9699
+ return [
9700
+ {
9701
+ name: "skill_find",
9702
+ description: `Search the local skills catalog by keyword query and/or scene (returns top ranked matches; omit all filters to view scene summary). Call skill_load(name) to read a matched skill.${scopeSuffix}`,
9703
+ inputSchema: {
9704
+ type: "object",
9705
+ properties: {
9706
+ query: {
9707
+ type: "string",
9708
+ description: "Keywords matching skill name, description, or scene"
9709
+ },
9710
+ scene: {
9711
+ type: "string",
9712
+ description: "Exact scene filter (e.g. ops, coding)"
9713
+ },
9714
+ visibility: {
9715
+ type: "string",
9716
+ enum: ["always", "discoverable", "manual"],
9717
+ description: "Optional visibility filter (defaults to discoverable when only scene is set)"
9718
+ },
9719
+ kind: {
9720
+ type: "string",
9721
+ enum: ["skill", "router", "prompt"],
9722
+ description: "Exact kind filter (skill | router | prompt)"
9723
+ },
9724
+ limit: {
9725
+ type: "integer",
9726
+ minimum: 1,
9727
+ maximum: 50,
9728
+ default: 20,
9729
+ description: "Max results to return (default 20, max 50)"
9730
+ }
9731
+ },
9732
+ additionalProperties: false
9733
+ },
9734
+ annotations: READ_ONLY_TOOL_ANNOTATIONS
9735
+ },
9736
+ {
9737
+ name: "skill_load",
9738
+ description: `Load one skill by canonical name (or hyphenated slug) and return its SKILL.md content, local directory path, and Requires paths.${scopeSuffix}`,
9739
+ inputSchema: {
9740
+ type: "object",
9741
+ properties: {
9742
+ name: {
9743
+ type: "string",
9744
+ description: "Exact skill name or hyphenated slug to materialize and read"
9745
+ },
9746
+ refresh: {
9747
+ type: "boolean",
9748
+ description: "Force an incremental sync before loading"
9749
+ }
9750
+ },
9751
+ required: ["name"],
9752
+ additionalProperties: false
9753
+ },
9754
+ annotations: READ_ONLY_TOOL_ANNOTATIONS
9755
+ }
9756
+ ];
9757
+ }
9758
+ function createMcpMessageHandler(options) {
9759
+ const allowedScenes = (options.allowedScenes ?? []).map((s) => s.trim()).filter(Boolean);
9760
+ const allowedSceneLower = new Set(allowedScenes.map((s) => s.toLowerCase()));
9761
+ const resolvedInstructions = buildResolvedInstructions(options.instructions, allowedScenes);
9762
+ const tools = buildToolDefinitions(allowedScenes);
9763
+ const libOpt = options.libraryId ? { libraryId: options.libraryId } : {};
9764
+ const queryCatalogWithColdSync = async (args) => {
9765
+ const queryArgs = { ...args, ...libOpt };
9766
+ try {
9767
+ const items = await options.runCore(findSkillsCommand(queryArgs));
9768
+ if (items.length > 0 || args.query || args.scene || args.visibility || args.kind) {
9769
+ return items;
9770
+ }
9771
+ await options.runCore(syncCommand({ ...libOpt, dedupeWindowMs: 5000 })).catch(() => {
9772
+ return;
9773
+ });
9774
+ return await options.runCore(findSkillsCommand(queryArgs));
9775
+ } catch {
9776
+ await options.runCore(syncCommand({ ...libOpt, dedupeWindowMs: 0 }));
9777
+ return await options.runCore(findSkillsCommand(queryArgs));
9778
+ }
9779
+ };
9780
+ const handleSkillFind = async (rawArgs) => {
9781
+ const query = typeof rawArgs.query === "string" ? rawArgs.query.trim() : "";
9782
+ const scene = typeof rawArgs.scene === "string" ? rawArgs.scene.trim() : "";
9783
+ const rawVis = rawArgs.visibility;
9784
+ const rawKind = rawArgs.kind;
9785
+ const rawLimit = rawArgs.limit;
9786
+ if (rawArgs.query !== undefined && typeof rawArgs.query !== "string") {
9787
+ return makeToolResult("Invalid argument 'query': expected string.", true);
9788
+ }
9789
+ if (rawArgs.scene !== undefined && typeof rawArgs.scene !== "string") {
9790
+ return makeToolResult("Invalid argument 'scene': expected string.", true);
9791
+ }
9792
+ let visibility;
9793
+ if (rawVis !== undefined) {
9794
+ if (typeof rawVis !== "string" || !VALID_VISIBILITIES.has(rawVis)) {
9795
+ return makeToolResult("Invalid argument 'visibility': expected 'always', 'discoverable', or 'manual'.", true);
9796
+ }
9797
+ visibility = rawVis;
9798
+ }
9799
+ let kind;
9800
+ if (rawKind !== undefined) {
9801
+ if (typeof rawKind !== "string" || !VALID_KINDS.has(rawKind)) {
9802
+ return makeToolResult("Invalid argument 'kind': expected 'skill', 'router', or 'prompt'.", true);
9803
+ }
9804
+ kind = rawKind;
9805
+ }
9806
+ let limit;
9807
+ if (rawLimit !== undefined) {
9808
+ if (typeof rawLimit !== "number" || !Number.isFinite(rawLimit)) {
9809
+ return makeToolResult("Invalid argument 'limit': expected number.", true);
9810
+ }
9811
+ limit = rawLimit;
9812
+ }
9813
+ const hasQuery = query.length > 0;
9814
+ const hasScene = scene.length > 0;
9815
+ const hasVis = visibility !== undefined;
9816
+ const hasKind = kind !== undefined;
9817
+ if (hasScene && allowedSceneLower.size > 0 && !allowedSceneLower.has(scene.toLowerCase())) {
9818
+ return makeToolResult(`No matching skills found in allowed scenes (${allowedScenes.join(", ")}).`);
9819
+ }
9820
+ if (!hasQuery && !hasScene && !hasVis && !hasKind) {
9821
+ const all = await queryCatalogWithColdSync({});
9822
+ const scoped = allowedScenes.length > 0 ? all.filter((e) => matchesAllowedScenes(e.scenes, allowedScenes)) : all;
9823
+ const overview = formatSkillCatalogOverview(scoped, { allowedScenes });
9824
+ return makeToolResult(overview.text);
9825
+ }
9826
+ const effectiveVisibility = hasScene && !hasQuery && !hasVis ? "discoverable" : visibility;
9827
+ const rawItems = await queryCatalogWithColdSync({
9828
+ ...hasQuery ? { query } : {},
9829
+ ...hasScene ? { scene } : {},
9830
+ ...effectiveVisibility ? { visibility: effectiveVisibility } : {},
9831
+ ...hasKind ? { kind } : {}
9832
+ });
9833
+ const scopedItems = allowedScenes.length > 0 ? rawItems.filter((e) => matchesAllowedScenes(e.scenes, allowedScenes)) : rawItems;
9834
+ let omittedManualCount = 0;
9835
+ if (hasScene && !hasQuery && !hasVis) {
9836
+ const manualItems = await options.runCore(findSkillsCommand({ scene, visibility: "manual", ...libOpt })).catch(() => []);
9837
+ omittedManualCount = allowedScenes.length > 0 ? manualItems.filter((e) => matchesAllowedScenes(e.scenes, allowedScenes)).length : manualItems.length;
9838
+ }
9839
+ const formatted = formatSkillFindResults({
9840
+ items: scopedItems,
9841
+ ...limit !== undefined ? { limit } : {},
9842
+ hasSceneFilter: hasScene,
9843
+ ...omittedManualCount > 0 && hasScene ? { omittedManualCount, sceneName: scene } : {}
9844
+ });
9845
+ return makeToolResult(formatted.text);
9846
+ };
9847
+ const handleSkillLoad = async (rawArgs) => {
9848
+ const rawName = rawArgs.name;
9849
+ if (typeof rawName !== "string" || !rawName.trim()) {
9850
+ return makeToolResult("Missing required argument 'name' (non-empty string).", true);
9851
+ }
9852
+ if (rawArgs.refresh !== undefined && typeof rawArgs.refresh !== "boolean") {
9853
+ return makeToolResult("Invalid argument 'refresh': expected boolean.", true);
9854
+ }
9855
+ const name = rawName.trim();
9856
+ const refresh = rawArgs.refresh === true;
9857
+ if (allowedScenes.length > 0 && !refresh) {
9858
+ const all = await options.runCore(findSkillsCommand({ ...libOpt })).catch(() => []);
9859
+ const lower = name.toLowerCase();
9860
+ const slug = normalizeSkillSlug(name);
9861
+ const localMatch = all.find((e) => e.name.toLowerCase() === lower) ?? (slug ? all.find((e) => normalizeSkillSlug(e.name) === slug) : undefined);
9862
+ if (localMatch && !matchesAllowedScenes(localMatch.scenes, allowedScenes)) {
9863
+ return makeToolResult(`Skill '${localMatch.name}' is outside allowed scenes (${allowedScenes.join(", ")}).`, true);
9864
+ }
9865
+ }
9866
+ const loaded = await options.runCore(loadSkillCommand({
9867
+ name,
9868
+ refresh,
9869
+ ...libOpt
9870
+ }));
9871
+ if (allowedScenes.length > 0 && !matchesAllowedScenes(loaded.entry.scenes, allowedScenes)) {
9872
+ return makeToolResult(`Skill '${loaded.entry.name}' is outside allowed scenes (${allowedScenes.join(", ")}).`, true);
9873
+ }
9874
+ const text = formatLoadedSkillBlock({
9875
+ name: loaded.entry.name,
9876
+ dir: loaded.storeDir,
9877
+ markdown: loaded.skillMarkdown,
9878
+ requiresPaths: loaded.requiresPaths
9879
+ });
9880
+ return makeToolResult(text);
9881
+ };
9882
+ return async function handleMessage(raw) {
9883
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
9884
+ return {
9885
+ jsonrpc: "2.0",
9886
+ id: null,
9887
+ error: { code: -32600, message: "Invalid Request" }
9888
+ };
9889
+ }
9890
+ const msg = raw;
9891
+ const hasId = Object.prototype.hasOwnProperty.call(msg, "id") && msg.id !== undefined;
9892
+ const id = hasId ? msg.id ?? null : null;
9893
+ if (typeof msg.method !== "string" || !msg.method) {
9894
+ if (!hasId)
9895
+ return null;
9896
+ return {
9897
+ jsonrpc: "2.0",
9898
+ id,
9899
+ error: { code: -32600, message: "Invalid Request: missing string 'method'" }
9900
+ };
9901
+ }
9902
+ if (!hasId) {
9903
+ return null;
9904
+ }
9905
+ const params = msg.params && typeof msg.params === "object" && !Array.isArray(msg.params) ? msg.params : {};
9906
+ if (msg.method === "initialize") {
9907
+ const requestedVersion = typeof params.protocolVersion === "string" ? params.protocolVersion.trim() : "";
9908
+ const protocolVersion = SUPPORTED_MCP_PROTOCOL_VERSIONS.has(requestedVersion) ? requestedVersion : DEFAULT_MCP_PROTOCOL_VERSION;
9909
+ return {
9910
+ jsonrpc: "2.0",
9911
+ id,
9912
+ result: {
9913
+ protocolVersion,
9914
+ capabilities: {
9915
+ tools: {
9916
+ listChanged: false
9917
+ }
9918
+ },
9919
+ serverInfo: {
9920
+ name: "ntn-skills",
9921
+ version: options.version
9922
+ },
9923
+ instructions: resolvedInstructions
9924
+ }
9925
+ };
9926
+ }
9927
+ if (msg.method === "ping") {
9928
+ return {
9929
+ jsonrpc: "2.0",
9930
+ id,
9931
+ result: {}
9932
+ };
9933
+ }
9934
+ if (msg.method === "tools/list") {
9935
+ return {
9936
+ jsonrpc: "2.0",
9937
+ id,
9938
+ result: {
9939
+ tools
9940
+ }
9941
+ };
9942
+ }
9943
+ if (msg.method === "tools/call") {
9944
+ const toolName = typeof params.name === "string" ? params.name : "";
9945
+ const toolArgs = params.arguments && typeof params.arguments === "object" && !Array.isArray(params.arguments) ? params.arguments : {};
9946
+ try {
9947
+ if (toolName === "skill_find") {
9948
+ return {
9949
+ jsonrpc: "2.0",
9950
+ id,
9951
+ result: await handleSkillFind(toolArgs)
9952
+ };
9953
+ }
9954
+ if (toolName === "skill_load") {
9955
+ return {
9956
+ jsonrpc: "2.0",
9957
+ id,
9958
+ result: await handleSkillLoad(toolArgs)
9959
+ };
9960
+ }
9961
+ return {
9962
+ jsonrpc: "2.0",
9963
+ id,
9964
+ result: makeToolResult(`Unknown tool: '${toolName}'.`, true)
9965
+ };
9966
+ } catch (err) {
9967
+ return {
9968
+ jsonrpc: "2.0",
9969
+ id,
9970
+ result: makeToolResult(formatErrorMessage(err), true)
9971
+ };
9972
+ }
9973
+ }
9974
+ return {
9975
+ jsonrpc: "2.0",
9976
+ id,
9977
+ error: {
9978
+ code: -32601,
9979
+ message: `Method not found: ${msg.method}`
9980
+ }
9981
+ };
9982
+ };
9983
+ }
9984
+ async function runStdioMcpServer(options) {
9985
+ const input = options.input ?? process.stdin;
9986
+ const output = options.output ?? process.stdout;
9987
+ const handleMessage = createMcpMessageHandler(options);
9988
+ const prevQuiet = process.env.NTN_SKILLS_QUIET;
9989
+ if (prevQuiet === undefined) {
9990
+ process.env.NTN_SKILLS_QUIET = "1";
9991
+ }
9992
+ const writeResponse = async (resp) => {
9993
+ const line = `${JSON.stringify(resp)}
9994
+ `;
9995
+ if (!output.write(line)) {
9996
+ await new Promise((resolve) => {
9997
+ output.once("drain", resolve);
9998
+ });
9999
+ }
10000
+ };
10001
+ let chain = Promise.resolve();
10002
+ const enqueueLine = (rawLine) => {
10003
+ const trimmed = rawLine.trim();
10004
+ if (!trimmed)
10005
+ return;
10006
+ chain = chain.then(async () => {
10007
+ let parsed;
10008
+ try {
10009
+ parsed = JSON.parse(trimmed);
10010
+ } catch {
10011
+ await writeResponse({
10012
+ jsonrpc: "2.0",
10013
+ id: null,
10014
+ error: { code: -32700, message: "Parse error" }
10015
+ });
10016
+ return;
10017
+ }
10018
+ const resp = await handleMessage(parsed);
10019
+ if (resp !== null) {
10020
+ await writeResponse(resp);
10021
+ }
10022
+ });
10023
+ };
10024
+ let buffer = "";
10025
+ try {
10026
+ await new Promise((resolve, reject) => {
10027
+ input.setEncoding("utf8");
10028
+ input.on("data", (chunk) => {
10029
+ buffer += chunk;
10030
+ let idx = buffer.indexOf(`
10031
+ `);
10032
+ while (idx !== -1) {
10033
+ const line = buffer.slice(0, idx).replace(/\r$/, "");
10034
+ buffer = buffer.slice(idx + 1);
10035
+ enqueueLine(line);
10036
+ idx = buffer.indexOf(`
10037
+ `);
10038
+ }
10039
+ });
10040
+ input.on("end", () => {
10041
+ if (buffer.trim().length > 0) {
10042
+ enqueueLine(buffer.replace(/\r$/, ""));
10043
+ buffer = "";
10044
+ }
10045
+ chain.then(resolve, reject);
10046
+ });
10047
+ input.on("error", reject);
10048
+ if (typeof input.resume === "function") {
10049
+ input.resume();
10050
+ }
10051
+ });
10052
+ } finally {
10053
+ if (prevQuiet === undefined) {
10054
+ Reflect.deleteProperty(process.env, "NTN_SKILLS_QUIET");
10055
+ }
10056
+ }
10057
+ }
10058
+
8452
10059
  // packages/cli/src/main.ts
8453
10060
  function splitMulti(values) {
8454
10061
  return values.flatMap((v) => v.split(",")).map((s) => s.trim()).filter(Boolean);
@@ -8558,7 +10165,7 @@ var doctorCmd = Command.make("doctor", {
8558
10165
  const report = yield* doctorCommand({ ...libOpt ? { libraryId: libOpt } : {} });
8559
10166
  const sched = yield* statusScheduleCommand().pipe(Effect7.catch(() => Effect7.succeed(null)));
8560
10167
  const syncActive = Boolean(sched?.units.some((u) => u.job === "sync" && u.active));
8561
- const allChecks = [
10168
+ const checks = [
8562
10169
  ...report.checks,
8563
10170
  {
8564
10171
  name: "background_sync",
@@ -8567,13 +10174,14 @@ var doctorCmd = Command.make("doctor", {
8567
10174
  ...syncActive ? {} : { hint: "Run: ntn-skills schedule install" }
8568
10175
  }
8569
10176
  ];
8570
- const fullReport = { ...report, checks: allChecks };
10177
+ const ok = checks.every((c) => c.status !== "fail");
10178
+ const fullReport = { ...report, ok, checks };
8571
10179
  if (!fullReport.ok) {
8572
10180
  process.exitCode = 1;
8573
10181
  }
8574
10182
  const lines = [
8575
10183
  `ntn-skills doctor: ${fullReport.ok ? "OK" : "ISSUES FOUND"}`,
8576
- ...allChecks.map((c) => {
10184
+ ...checks.map((c) => {
8577
10185
  const icon = c.status === "pass" ? "✓" : c.status === "warn" ? "!" : "✗";
8578
10186
  return ` [${icon}] ${c.name}: ${c.detail}${c.hint ? `
8579
10187
  hint: ${c.hint}` : ""}`;
@@ -8620,7 +10228,7 @@ var syncCmd = Command.make("sync", {
8620
10228
  }
8621
10229
  if (lp.unmanagedLocalSkills.length > 0) {
8622
10230
  const uList = lp.unmanagedLocalSkills.map((u) => `${u.name} (${u.path})`).join(", ");
8623
- pendingLines.push(` - ${lp.unmanagedLocalSkills.length} local skill(s) not in Notion: ${uList} -> run 'ntn-skills new <path>' to save`);
10231
+ pendingLines.push(` - ${lp.unmanagedLocalSkills.length} local skill(s) not in Notion: ${uList} -> run 'ntn-skills new <path> --always' (keep exported) or 'ntn-skills new <path> --discoverable' (index in skill-catalog)`);
8624
10232
  }
8625
10233
  if (lp.uninitializedSources.length > 0) {
8626
10234
  pendingLines.push(` - ${lp.uninitializedSources.length} uninitialized Notion source(s): ${fmtList(lp.uninitializedSources)} -> run 'ntn-skills upstream apply <source>'`);
@@ -8750,7 +10358,13 @@ var statusCmd = Command.make("status", {
8750
10358
  `));
8751
10359
  })).pipe(Command.withDescription("Show Visibility distribution, draft buffer, active upstream overlays, and on-demand load frequency"));
8752
10360
  var exportCmd = Command.make("export", {
8753
- to: Flag.String("to").pipe(Flag.optional),
10361
+ to: Flag.String("to").pipe(Flag.withDescription("Target host directory for ad-hoc export"), Flag.optional),
10362
+ spec: Flag.String("spec").pipe(Flag.withDescription("Declarative export spec JSON file (supports { bundles?, exports }, ExportTarget[], or single ExportTarget)"), Flag.optional),
10363
+ skills: Flag.String("skills").pipe(Flag.withDescription("Exact skill allowlist (comma-separated or repeatable; matches canonical name or slug)"), Flag.atLeast(0)),
10364
+ exclude: Flag.String("exclude").pipe(Flag.withDescription("Skills to exclude from the final export set (comma-separated or repeatable)"), Flag.atLeast(0)),
10365
+ withRequires: Flag.Boolean("with-requires").pipe(Flag.withDescription("Recursively expand transitive Requires dependencies"), Flag.withDefault(false)),
10366
+ noRequires: Flag.Boolean("no-requires").pipe(Flag.withDescription("Disable automatic Requires dependency closure in exact --skills mode"), Flag.withDefault(false)),
10367
+ noRouter: Flag.Boolean("no-router").pipe(Flag.withDescription("Disable auto-generated skill-catalog router skill"), Flag.withDefault(false)),
8754
10368
  profile: Flag.String("profile").pipe(Flag.optional),
8755
10369
  scene: Flag.String("scene").pipe(Flag.optional),
8756
10370
  mode: Flag.Literals("mode", ["symlink", "copy"]).pipe(Flag.optional),
@@ -8758,23 +10372,46 @@ var exportCmd = Command.make("export", {
8758
10372
  library: libraryFlag,
8759
10373
  json: jsonFlag
8760
10374
  }, (cfg) => Effect7.gen(function* () {
10375
+ if (cfg.withRequires && cfg.noRequires) {
10376
+ return yield* Effect7.fail(new ConfigError({
10377
+ message: "Cannot combine --with-requires and --no-requires."
10378
+ }));
10379
+ }
8761
10380
  const toDir = Option2.getOrUndefined(cfg.to);
10381
+ const specPath = Option2.getOrUndefined(cfg.spec);
8762
10382
  const prof = Option2.getOrUndefined(cfg.profile);
8763
10383
  const sc = Option2.getOrUndefined(cfg.scene);
8764
10384
  const md = Option2.getOrUndefined(cfg.mode);
8765
10385
  const lib = Option2.getOrUndefined(cfg.library);
10386
+ const skillList = splitMulti(cfg.skills);
10387
+ const excludeList = splitMulti(cfg.exclude);
10388
+ const includeRequires = cfg.withRequires ? true : cfg.noRequires ? false : undefined;
8766
10389
  const res = yield* exportCommand({
8767
10390
  ...toDir ? { toDir } : {},
10391
+ ...specPath ? { specPath } : {},
10392
+ ...skillList.length > 0 ? { skills: skillList } : {},
10393
+ ...excludeList.length > 0 ? { exclude: excludeList } : {},
10394
+ ...includeRequires !== undefined ? { includeRequires } : {},
10395
+ ...cfg.noRouter ? { noRouter: true } : {},
8768
10396
  ...prof ? { profile: prof } : {},
8769
10397
  ...sc ? { scene: sc } : {},
8770
10398
  ...md ? { mode: md } : {},
8771
- includeNonDefault: cfg.includeNonDefault,
10399
+ ...cfg.includeNonDefault ? { includeNonDefault: true } : {},
8772
10400
  ...lib ? { libraryId: lib } : {}
8773
10401
  });
8774
- yield* printOut(cfg.json, res, `Exported ${res.exportedDirs.length} skill(s):
8775
- ${res.exportedDirs.map((d) => ` ${d}`).join(`
8776
- `)}`);
8777
- })).pipe(Command.withDescription("Idempotently publish store skills to host directories via symlink or copy"));
10402
+ const lines = [
10403
+ `Exported ${res.exportedDirs.length} skill(s):`,
10404
+ ...res.exportedDirs.map((d) => ` ${d}`)
10405
+ ];
10406
+ if (res.warnings.length > 0) {
10407
+ lines.push("Warnings:");
10408
+ for (const w of res.warnings) {
10409
+ lines.push(` - ${w}`);
10410
+ }
10411
+ }
10412
+ yield* printOut(cfg.json, res, lines.join(`
10413
+ `));
10414
+ })).pipe(Command.withDescription("Idempotently publish store skills to host directories via symlink, copy, allowlist, or declarative spec"));
8778
10415
  var editCmd = Command.make("edit", {
8779
10416
  name: Argument.String("name"),
8780
10417
  library: libraryFlag,
@@ -8867,31 +10504,52 @@ var newCmd = Command.make("new", {
8867
10504
  name: Flag.String("name").pipe(Flag.optional),
8868
10505
  profiles: Flag.String("profiles").pipe(Flag.atLeast(0)),
8869
10506
  scenes: Flag.String("scenes").pipe(Flag.atLeast(0)),
8870
- visibility: Flag.Literals("visibility", ["always", "discoverable", "manual"]).pipe(Flag.withDescription("Visibility tier (default: discoverable)"), Flag.optional),
10507
+ visibility: Flag.Literals("visibility", ["always", "discoverable", "manual"]).pipe(Flag.withDescription("Visibility tier (default: discoverable, or manual when SKILL.md sets disable-model-invocation: true)"), Flag.optional),
8871
10508
  kind: Flag.Literals("kind", ["skill", "router", "prompt"]).pipe(Flag.withDescription("Skill kind (default: skill)"), Flag.optional),
8872
10509
  always: Flag.Boolean("always").pipe(Flag.withDescription("Shorthand for --visibility always"), Flag.withDefault(false)),
10510
+ discoverable: Flag.Boolean("discoverable").pipe(Flag.withDescription("Shorthand for --visibility discoverable"), Flag.withDefault(false)),
10511
+ manual: Flag.Boolean("manual").pipe(Flag.withDescription("Shorthand for --visibility manual"), Flag.withDefault(false)),
8873
10512
  default: Flag.Boolean("default").pipe(Flag.withDescription("Alias for --always"), Flag.withDefault(false)),
8874
10513
  adopt: Flag.Boolean("adopt").pipe(Flag.withDefault(false), Flag.withDescription("Move the local source directory to OS Trash after Notion upload succeeds (automatic when <dir> is inside a configured export root like ~/.agents/skills/<name>)")),
10514
+ noAdopt: Flag.Boolean("no-adopt").pipe(Flag.withDefault(false), Flag.withDescription("Keep the local source directory untouched even when <dir> is inside a configured export root")),
8875
10515
  library: libraryFlag,
8876
10516
  json: jsonFlag
8877
10517
  }, (cfg) => Effect7.gen(function* () {
10518
+ if (cfg.adopt && cfg.noAdopt) {
10519
+ return yield* Effect7.fail(new ConfigError({ message: "Cannot pass both --adopt and --no-adopt." }));
10520
+ }
8878
10521
  const nm = Option2.getOrUndefined(cfg.name);
8879
10522
  const visOpt = Option2.getOrUndefined(cfg.visibility);
8880
10523
  const kindOpt = Option2.getOrUndefined(cfg.kind);
8881
10524
  const lib = Option2.getOrUndefined(cfg.library);
8882
- const visibility = visOpt ?? (cfg.always || cfg.default ? "always" : "discoverable");
10525
+ const chosenVis = new Set;
10526
+ if (visOpt)
10527
+ chosenVis.add(visOpt);
10528
+ if (cfg.always || cfg.default)
10529
+ chosenVis.add("always");
10530
+ if (cfg.discoverable)
10531
+ chosenVis.add("discoverable");
10532
+ if (cfg.manual)
10533
+ chosenVis.add("manual");
10534
+ if (chosenVis.size > 1) {
10535
+ return yield* Effect7.fail(new ConfigError({
10536
+ message: `Conflicting visibility flags specified (${Array.from(chosenVis).join(", ")}). Pick one.`
10537
+ }));
10538
+ }
10539
+ const visibility = Array.from(chosenVis)[0];
10540
+ const adoptOpt = cfg.adopt ? true : cfg.noAdopt ? false : undefined;
8883
10541
  const res = yield* createNewSkillCommand({
8884
10542
  dir: cfg.dir,
8885
10543
  ...nm ? { name: nm } : {},
8886
10544
  profiles: splitMulti(cfg.profiles),
8887
10545
  scenes: splitMulti(cfg.scenes),
8888
- visibility,
10546
+ ...visibility ? { visibility } : {},
8889
10547
  ...kindOpt ? { kind: kindOpt } : {},
8890
- adopt: cfg.adopt,
10548
+ ...adoptOpt !== undefined ? { adopt: adoptOpt } : {},
8891
10549
  ...lib ? { libraryId: lib } : {}
8892
10550
  });
8893
- const adoptNote = res.adoptedSourceDir ? " [adopted local directory -> Trash]" : "";
8894
- yield* printOut(cfg.json, res, `Created native skill '${res.name}' (${res.skillId}, visibility=${visibility}), uploaded ${res.uploadedFiles} supporting file(s)${adoptNote}.`);
10551
+ const adoptNote = res.adoptedSourceDir ? res.adoptedFromExportRoot ? res.exportedAtSourcePath ? " [adopted local directory -> Trash; replaced with managed export]" : ` [adopted local directory -> Trash; visibility=${res.visibility} is not exported directly into this export root — run 'ntn-skills set "${res.name}" --always' to keep it exported directly]` : " [adopted local directory -> Trash]" : "";
10552
+ yield* printOut(cfg.json, res, `Created native skill '${res.name}' (${res.skillId}, visibility=${res.visibility}), uploaded ${res.uploadedFiles} supporting file(s)${adoptNote}.`);
8895
10553
  })).pipe(Command.withDescription("Create a brand-new native skill in Notion from a local directory"));
8896
10554
  var setCmd = Command.make("set", {
8897
10555
  names: Argument.String("name").pipe(Argument.atLeast(0)),
@@ -9328,10 +10986,28 @@ var skillCmd = Command.make("skill", {
9328
10986
  }
9329
10987
  yield* printOut(cfg.json, payload, payload.markdown.trimEnd());
9330
10988
  })).pipe(Command.withDescription("Print or install the built-in ntn-skills agent guide shipped with this CLI binary"));
10989
+ var mcpCmd = Command.make("mcp", {
10990
+ library: libraryFlag,
10991
+ scenes: Flag.String("scenes").pipe(Flag.withDescription("Restrict skill_find and skill_load to specific scene(s) (comma-separated or repeatable)"), Flag.atLeast(0)),
10992
+ instructions: Flag.String("instructions").pipe(Flag.withDescription("Override MCP initialize instructions text"), Flag.optional)
10993
+ }, (cfg) => Effect7.gen(function* () {
10994
+ const lib = Option2.getOrUndefined(cfg.library);
10995
+ const customInstructions = Option2.getOrUndefined(cfg.instructions);
10996
+ const allowedScenes = splitMulti(cfg.scenes);
10997
+ const services = yield* Effect7.context();
10998
+ yield* Effect7.promise(() => runStdioMcpServer({
10999
+ version: BUNDLED_SKILL_VERSION,
11000
+ ...lib ? { libraryId: lib } : {},
11001
+ ...allowedScenes.length > 0 ? { allowedScenes } : {},
11002
+ ...customInstructions !== undefined ? { instructions: customInstructions } : {},
11003
+ runCore: (eff) => Effect7.runPromise(eff.pipe(Effect7.provide(services)))
11004
+ }));
11005
+ })).pipe(Command.withDescription("Run a read-only stdio JSON-RPC 2.0 MCP server exposing skill_find and skill_load"));
9331
11006
  var rootCommand = Command.make("ntn-skills").pipe(Command.withDescription("Notion 3-table skill control-plane synchronizer & local-native CLI (v2)"), Command.withSubcommands([
9332
11007
  initCmd,
9333
11008
  doctorCmd,
9334
11009
  skillCmd,
11010
+ mcpCmd,
9335
11011
  syncCmd,
9336
11012
  findCmd,
9337
11013
  loadCmd,