ntn-skills 2.0.1 → 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,12 +1656,22 @@ 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"),
1314
1663
  locksRoot: nodePath.join(homeDir, ".locks")
1315
1664
  };
1316
1665
  }
1666
+ var DEAD_PROC_TMP_RE = /^(?:extract|sub|gsub|asset)-(\d+)-/;
1667
+ function repoGitCacheKey(repoUrl) {
1668
+ return sha256Hex(repoUrl.trim()).slice(0, 16);
1669
+ }
1670
+ async function removeInternalCachePath(absTargetPath) {
1671
+ const resolved = nodePath.resolve(absTargetPath);
1672
+ await makeTreeWritableBestEffort(resolved);
1673
+ await fsp.rm(resolved, { recursive: true, force: true });
1674
+ }
1317
1675
  async function moveToSystemTrash(absTargetPath) {
1318
1676
  const resolved = nodePath.resolve(absTargetPath);
1319
1677
  await makeTreeWritableBestEffort(resolved);
@@ -1366,13 +1724,16 @@ function isProcessAlive(pid) {
1366
1724
  return err?.code === "EPERM";
1367
1725
  }
1368
1726
  }
1369
- async function atomicWriteJson(filePath, data) {
1727
+ async function atomicWriteJson(filePath, data, options) {
1370
1728
  const dir = nodePath.dirname(filePath);
1371
1729
  await fsp.mkdir(dir, { recursive: true });
1372
1730
  const tmpPath = nodePath.join(dir, `.${nodePath.basename(filePath)}.${process.pid}.${randomUUID().slice(0, 8)}.tmp`);
1373
1731
  const payload = `${JSON.stringify(data, null, 2)}
1374
1732
  `;
1375
- 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
+ }
1376
1737
  await fsp.rename(tmpPath, filePath);
1377
1738
  }
1378
1739
 
@@ -1401,7 +1762,7 @@ function makeStoreService(overrides) {
1401
1762
  })
1402
1763
  }),
1403
1764
  writeConfig: (config) => Effect.tryPromise({
1404
- try: () => atomicWriteJson(paths.configPath, config),
1765
+ try: () => atomicWriteJson(paths.configPath, config, { mode: 384 }),
1405
1766
  catch: (err) => new StoreError({
1406
1767
  path: paths.configPath,
1407
1768
  message: `Failed writing config: ${String(err)}`
@@ -1454,7 +1815,7 @@ function makeStoreService(overrides) {
1454
1815
  await fsp.rename(lockDir, staleTmp).catch(() => {
1455
1816
  return;
1456
1817
  });
1457
- await moveToSystemTrash(staleTmp).catch(() => {
1818
+ await removeInternalCachePath(staleTmp).catch(() => {
1458
1819
  return;
1459
1820
  });
1460
1821
  continue;
@@ -1520,11 +1881,11 @@ function makeStoreService(overrides) {
1520
1881
  const code = err?.code;
1521
1882
  if (code === "EEXIST" || code === "ENOTEMPTY" || code === "EACCES" || code === "EPERM") {
1522
1883
  if (await verifyStorePackageDir(targetDir, effectiveRev)) {
1523
- await moveToSystemTrash(stagingDir);
1884
+ await removeInternalCachePath(stagingDir);
1524
1885
  return await fsp.realpath(targetDir);
1525
1886
  }
1526
1887
  if (await fsp.stat(targetDir).then(() => true).catch(() => false)) {
1527
- await moveToSystemTrash(targetDir);
1888
+ await removeInternalCachePath(targetDir);
1528
1889
  await fsp.rename(stagingDir, targetDir);
1529
1890
  } else {
1530
1891
  throw err;
@@ -1536,7 +1897,7 @@ function makeStoreService(overrides) {
1536
1897
  await sealDirectoriesReadOnly(targetDir);
1537
1898
  return await fsp.realpath(targetDir);
1538
1899
  } catch (err) {
1539
- await moveToSystemTrash(stagingDir).catch(() => {
1900
+ await removeInternalCachePath(stagingDir).catch(() => {
1540
1901
  return;
1541
1902
  });
1542
1903
  throw err;
@@ -1551,7 +1912,7 @@ function makeStoreService(overrides) {
1551
1912
  const bytes = await fsp.readFile(p);
1552
1913
  if (sha256Hex(bytes) === sha256.toLowerCase())
1553
1914
  return new Uint8Array(bytes);
1554
- await moveToSystemTrash(p).catch(() => {
1915
+ await removeInternalCachePath(p).catch(() => {
1555
1916
  return;
1556
1917
  });
1557
1918
  return null;
@@ -1641,7 +2002,7 @@ function makeStoreService(overrides) {
1641
2002
  continue;
1642
2003
  if (normalizedProtected.has(v.dir) || normalizedProtected.has(v.realDir))
1643
2004
  continue;
1644
- await moveToSystemTrash(v.realDir);
2005
+ await removeInternalCachePath(v.realDir);
1645
2006
  pruned.push(v.realDir);
1646
2007
  }
1647
2008
  }
@@ -1655,6 +2016,7 @@ function makeStoreService(overrides) {
1655
2016
  const commitSha = rc.commitSha.trim();
1656
2017
  if (!repoUrl)
1657
2018
  continue;
2019
+ protectedGitKeys.add(repoGitCacheKey(repoUrl));
1658
2020
  protectedGitKeys.add(sha256Hex(repoUrl).slice(0, 20));
1659
2021
  if (commitSha) {
1660
2022
  protectedTreeKeys.add(sha256Hex(`${repoUrl}@${commitSha}`).slice(0, 24));
@@ -1672,7 +2034,7 @@ function makeStoreService(overrides) {
1672
2034
  if (nowMs - st.mtimeMs <= repoTreeGraceMs)
1673
2035
  continue;
1674
2036
  const real = await fsp.realpath(full).catch(() => nodePath.resolve(full));
1675
- await moveToSystemTrash(real);
2037
+ await removeInternalCachePath(real);
1676
2038
  pruned.push(real);
1677
2039
  }
1678
2040
  const subtreesRoot = nodePath.join(paths.reposRoot, "subtrees");
@@ -1696,7 +2058,7 @@ function makeStoreService(overrides) {
1696
2058
  if (nowMs - st.mtimeMs <= subRetMs)
1697
2059
  continue;
1698
2060
  const real = await fsp.realpath(full).catch(() => nodePath.resolve(full));
1699
- await moveToSystemTrash(real);
2061
+ await removeInternalCachePath(real);
1700
2062
  pruned.push(real);
1701
2063
  }
1702
2064
  const gitRoot = nodePath.join(paths.reposRoot, "git");
@@ -1711,17 +2073,19 @@ function makeStoreService(overrides) {
1711
2073
  if (nowMs - st.mtimeMs <= gitRetMs)
1712
2074
  continue;
1713
2075
  const real = await fsp.realpath(full).catch(() => nodePath.resolve(full));
1714
- await moveToSystemTrash(real);
2076
+ await removeInternalCachePath(real);
1715
2077
  pruned.push(real);
1716
2078
  }
1717
2079
  const tmpRoot = nodePath.join(paths.reposRoot, ".tmp");
1718
2080
  for (const name of await fsp.readdir(tmpRoot).catch(() => [])) {
1719
2081
  const full = nodePath.join(tmpRoot, name);
1720
2082
  const st = await fsp.stat(full).catch(() => null);
1721
- if (!st || nowMs - st.mtimeMs <= repoTreeGraceMs)
2083
+ const pidMatch = name.match(DEAD_PROC_TMP_RE);
2084
+ const holderDead = pidMatch ? !isProcessAlive(Number(pidMatch[1])) : false;
2085
+ if (!st || !holderDead && nowMs - st.mtimeMs <= repoTreeGraceMs)
1722
2086
  continue;
1723
2087
  const real = await fsp.realpath(full).catch(() => nodePath.resolve(full));
1724
- await moveToSystemTrash(real);
2088
+ await removeInternalCachePath(real);
1725
2089
  pruned.push(real);
1726
2090
  }
1727
2091
  }
@@ -2656,17 +3020,25 @@ function makeNotionServiceFromTransport(transport) {
2656
3020
  });
2657
3021
  return pages.map(decodeFilePage).filter((f) => f !== null);
2658
3022
  }),
2659
- readSkillBody: (skillPageId) => wrap(async () => {
3023
+ readSkillBody: (skillPageId, opts) => wrap(async () => {
2660
3024
  const pid = normalizeUuid(skillPageId);
2661
- const [page, topBlocks] = await Promise.all([
2662
- transport.requestJson("GET", `/v1/pages/${pid}`),
2663
- listAllBlockChildren(pid)
2664
- ]);
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
+ }
2665
3037
  const extracted = await extractSkillPageContent(topBlocks, listAllBlockChildren);
2666
3038
  return {
2667
3039
  rawMarkdown: extracted.rawMarkdown,
2668
3040
  upstreamFilesPageId: extracted.upstreamFilesPageId,
2669
- lastEditedTime: page.last_edited_time ?? new Date(0).toISOString()
3041
+ lastEditedTime
2670
3042
  };
2671
3043
  }),
2672
3044
  readFileBody: ({ filePageId, filePath }) => wrap(async () => {
@@ -3042,6 +3414,30 @@ function buildSubprocessEnv(bypassProxy) {
3042
3414
  }
3043
3415
  return env;
3044
3416
  }
3417
+ var STALE_GIT_LOCK_FILES = [
3418
+ "shallow.lock",
3419
+ "config.lock",
3420
+ "HEAD.lock",
3421
+ "index.lock",
3422
+ "packed-refs.lock"
3423
+ ];
3424
+ async function cleanStaleGitRepoLocks(gitCacheDir) {
3425
+ await Promise.all(STALE_GIT_LOCK_FILES.map((name) => fsp4.rm(nodePath4.join(gitCacheDir, name), { force: true }).catch(() => {
3426
+ return;
3427
+ })));
3428
+ }
3429
+ async function sweepDeadProcessRepoTmpDirs(reposRoot) {
3430
+ const tmpRoot = nodePath4.join(reposRoot, ".tmp");
3431
+ const names = await fsp4.readdir(tmpRoot).catch(() => []);
3432
+ await Promise.all(names.map(async (name) => {
3433
+ const m = name.match(DEAD_PROC_TMP_RE);
3434
+ if (m && !isProcessAlive(Number(m[1]))) {
3435
+ await removeInternalCachePath(nodePath4.join(tmpRoot, name)).catch(() => {
3436
+ return;
3437
+ });
3438
+ }
3439
+ }));
3440
+ }
3045
3441
  var repoGitLocks = new Map;
3046
3442
  async function withRepoGitLock(key, fn) {
3047
3443
  const prev = repoGitLocks.get(key) ?? Promise.resolve();
@@ -3135,6 +3531,28 @@ async function readAllTreeFiles(rootDir, currentRel = "") {
3135
3531
  }
3136
3532
  var UpstreamLiveLayer = Layer3.effect(UpstreamPort, Effect3.gen(function* () {
3137
3533
  const store = yield* StorePort;
3534
+ let sweptDeadTmpOnce = false;
3535
+ const ensureDeadTmpSwept = async () => {
3536
+ if (sweptDeadTmpOnce)
3537
+ return;
3538
+ sweptDeadTmpOnce = true;
3539
+ await sweepDeadProcessRepoTmpDirs(store.paths.reposRoot);
3540
+ };
3541
+ const withCrossProcessRepoGitLock = (repoLockKey, gitCacheDir, fn) => withRepoGitLock(repoLockKey, async () => {
3542
+ await ensureDeadTmpSwept();
3543
+ await fsp4.mkdir(gitCacheDir, { recursive: true });
3544
+ const outcome = await Effect3.runPromise(store.withExclusiveLock(`repo-git-${repoLockKey}`, Effect3.promise(async () => {
3545
+ await cleanStaleGitRepoLocks(gitCacheDir);
3546
+ try {
3547
+ return { ok: true, value: await fn() };
3548
+ } catch (error) {
3549
+ return { ok: false, error };
3550
+ }
3551
+ }), 180000));
3552
+ if (!outcome.ok)
3553
+ throw outcome.error;
3554
+ return outcome.value;
3555
+ });
3138
3556
  const fullTreeInFlight = new Map;
3139
3557
  const ensureFullCommitTree = (repoUrl, commitSha) => {
3140
3558
  const treeKey = sha256Hex(`${repoUrl.trim()}@${commitSha.trim()}`).slice(0, 24);
@@ -3148,6 +3566,7 @@ var UpstreamLiveLayer = Layer3.effect(UpstreamPort, Effect3.gen(function* () {
3148
3566
  return p;
3149
3567
  };
3150
3568
  const ensureFullCommitTreeImpl = async (repoUrl, commitSha, treeKey) => {
3569
+ await ensureDeadTmpSwept();
3151
3570
  const cachedTreeDir = nodePath4.join(store.paths.reposRoot, "trees", treeKey);
3152
3571
  const marker = nodePath4.join(cachedTreeDir, ".ntn-tree-ready");
3153
3572
  if (await fsp4.stat(marker).then(() => true).catch(() => false)) {
@@ -3195,10 +3614,9 @@ var UpstreamLiveLayer = Layer3.effect(UpstreamPort, Effect3.gen(function* () {
3195
3614
  }
3196
3615
  if (!extractedRoot) {
3197
3616
  const bypassProxy = shouldBypassProxyForUrl(repoUrl);
3198
- const repoLockKey = sha256Hex(repoUrl.trim()).slice(0, 16);
3617
+ const repoLockKey = repoGitCacheKey(repoUrl);
3199
3618
  const gitCacheDir = nodePath4.join(store.paths.reposRoot, "git", repoLockKey);
3200
- extractedRoot = await withRepoGitLock(repoLockKey, async () => {
3201
- await fsp4.mkdir(gitCacheDir, { recursive: true });
3619
+ extractedRoot = await withCrossProcessRepoGitLock(repoLockKey, gitCacheDir, async () => {
3202
3620
  const hasHead = await fsp4.stat(nodePath4.join(gitCacheDir, "HEAD")).then(() => true).catch(() => false);
3203
3621
  if (!hasHead) {
3204
3622
  await runCmd("git", ["init", "--bare"], { cwd: gitCacheDir });
@@ -3256,7 +3674,7 @@ var UpstreamLiveLayer = Layer3.effect(UpstreamPort, Effect3.gen(function* () {
3256
3674
  }
3257
3675
  return cachedTreeDir;
3258
3676
  } finally {
3259
- await moveToSystemTrash(tmpBase).catch(() => {
3677
+ await removeInternalCachePath(tmpBase).catch(() => {
3260
3678
  return;
3261
3679
  });
3262
3680
  }
@@ -3380,7 +3798,7 @@ var UpstreamLiveLayer = Layer3.effect(UpstreamPort, Effect3.gen(function* () {
3380
3798
  });
3381
3799
  return (await readAllTreeFiles(subCacheDir)).filter((f) => f.path !== ".ntn-tree-ready");
3382
3800
  } finally {
3383
- await moveToSystemTrash(tmpSub).catch(() => {
3801
+ await removeInternalCachePath(tmpSub).catch(() => {
3384
3802
  return;
3385
3803
  });
3386
3804
  }
@@ -3389,15 +3807,16 @@ var UpstreamLiveLayer = Layer3.effect(UpstreamPort, Effect3.gen(function* () {
3389
3807
  } catch {}
3390
3808
  }
3391
3809
  const bypassProxy = shouldBypassProxyForUrl(repoUrl);
3392
- const repoLockKey = sha256Hex(repoUrl.trim()).slice(0, 16);
3810
+ const repoLockKey = repoGitCacheKey(repoUrl);
3393
3811
  const gitCacheDir = nodePath4.join(store.paths.reposRoot, "git", repoLockKey);
3394
- const sparseArchive = await withRepoGitLock(repoLockKey, async () => {
3395
- await fsp4.mkdir(gitCacheDir, { recursive: true });
3812
+ const sparseArchive = await withCrossProcessRepoGitLock(repoLockKey, gitCacheDir, async () => {
3396
3813
  const hasHead = await fsp4.stat(nodePath4.join(gitCacheDir, "HEAD")).then(() => true).catch(() => false);
3397
3814
  if (!hasHead) {
3398
3815
  await runCmd("git", ["init", "--bare"], { cwd: gitCacheDir });
3399
3816
  }
3400
- await runCmd("git", ["config", "remote.origin.url", repoUrl], { cwd: gitCacheDir });
3817
+ await runCmd("git", ["config", "remote.origin.url", repoUrl], {
3818
+ cwd: gitCacheDir
3819
+ });
3401
3820
  await runCmd("git", ["config", "remote.origin.promisor", "true"], {
3402
3821
  cwd: gitCacheDir
3403
3822
  });
@@ -3433,7 +3852,7 @@ var UpstreamLiveLayer = Layer3.effect(UpstreamPort, Effect3.gen(function* () {
3433
3852
  }
3434
3853
  }
3435
3854
  } finally {
3436
- await moveToSystemTrash(tmpSub).catch(() => {
3855
+ await removeInternalCachePath(tmpSub).catch(() => {
3437
3856
  return;
3438
3857
  });
3439
3858
  }
@@ -3532,6 +3951,7 @@ var UpstreamLiveLayer = Layer3.effect(UpstreamPort, Effect3.gen(function* () {
3532
3951
  discoveredGh.push({
3533
3952
  name: finalName,
3534
3953
  description: parsed.description || "",
3954
+ disableModelInvocation: parsed.disableModelInvocation,
3535
3955
  sourcePath: dir,
3536
3956
  rawSkillMarkdown: rawText,
3537
3957
  relativeFiles: relFiles
@@ -3575,6 +3995,7 @@ var UpstreamLiveLayer = Layer3.effect(UpstreamPort, Effect3.gen(function* () {
3575
3995
  discovered.push({
3576
3996
  name: finalName,
3577
3997
  description: parsed.description || "",
3998
+ disableModelInvocation: parsed.disableModelInvocation,
3578
3999
  sourcePath: dir,
3579
4000
  rawSkillMarkdown: rawText,
3580
4001
  relativeFiles: relFiles
@@ -3646,7 +4067,7 @@ var UpstreamLiveLayer = Layer3.effect(UpstreamPort, Effect3.gen(function* () {
3646
4067
  return new Uint8Array(buf);
3647
4068
  }
3648
4069
  } finally {
3649
- await moveToSystemTrash(tmpAsset).catch(() => {
4070
+ await removeInternalCachePath(tmpAsset).catch(() => {
3650
4071
  return;
3651
4072
  });
3652
4073
  }
@@ -3703,7 +4124,114 @@ var UpstreamLiveLayer = Layer3.effect(UpstreamPort, Effect3.gen(function* () {
3703
4124
  import { randomUUID as randomUUID4 } from "node:crypto";
3704
4125
  import * as fsp5 from "node:fs/promises";
3705
4126
  import * as nodePath5 from "node:path";
3706
- 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
+ }
3707
4235
  async function inspectLocalPendingState(args) {
3708
4236
  const openWorkdirs = [];
3709
4237
  const workEntries = await fsp5.readdir(args.workRoot).catch(() => []);
@@ -3853,7 +4381,7 @@ function initLibraryCommand(args) {
3853
4381
  default_only: true,
3854
4382
  mode: parsed.mode
3855
4383
  };
3856
- }) : 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 ? [
3857
4385
  {
3858
4386
  dir: "~/.agents/skills",
3859
4387
  profiles: targetProfiles,
@@ -3871,6 +4399,8 @@ function initLibraryCommand(args) {
3871
4399
  libraries: nextLibraries,
3872
4400
  prefetch: args.prefetch ?? existing?.prefetch ?? "discoverable",
3873
4401
  ...resolvedProfiles && resolvedProfiles.length > 0 ? { profiles: resolvedProfiles } : {},
4402
+ ...existing?.bundles ? { bundles: existing.bundles } : {},
4403
+ ...existing?.include_exports ? { include_exports: existing.include_exports } : {},
3874
4404
  exports: resolvedExports
3875
4405
  };
3876
4406
  yield* store.writeConfig(nextConfig);
@@ -3929,6 +4459,7 @@ function doctorCommand(args) {
3929
4459
  checks
3930
4460
  };
3931
4461
  }
4462
+ const resolvedExports = yield* resolveConfiguredExports(cfg, store.paths.configPath);
3932
4463
  libraryId = normalizeUuid(args.libraryId ?? cfg.default_library);
3933
4464
  const binding = cfg.libraries[libraryId];
3934
4465
  if (!binding) {
@@ -3939,10 +4470,19 @@ function doctorCommand(args) {
3939
4470
  hint: `Run: ntn-skills init --root ${libraryId}`
3940
4471
  });
3941
4472
  } else {
4473
+ const includeSuffix = cfg.include_exports && cfg.include_exports.length > 0 ? ` (including ${cfg.include_exports.length} include_exports file(s))` : "";
3942
4474
  checks.push({
3943
4475
  name: "config",
3944
4476
  status: "pass",
3945
- 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."
3946
4486
  });
3947
4487
  }
3948
4488
  if (hasNotionToken && libraryId) {
@@ -3987,12 +4527,12 @@ function doctorCommand(args) {
3987
4527
  }
3988
4528
  const realStoreRoot = yield* Effect4.tryPromise(() => fsp5.realpath(store.paths.storeRoot)).pipe(Effect4.catch(() => Effect4.succeed(store.paths.storeRoot)));
3989
4529
  const storePrefixes = Array.from(new Set([`${store.paths.storeRoot}${nodePath5.sep}`, `${realStoreRoot}${nodePath5.sep}`]));
3990
- for (const target of cfg.exports) {
4530
+ for (const { target } of resolvedExports.targets) {
3991
4531
  const targetDir = resolveHomePath(target.dir);
3992
4532
  const inspectTarget = yield* Effect4.tryPromise(async () => {
3993
4533
  let entries;
3994
4534
  try {
3995
- entries = await fsp5.readdir(targetDir);
4535
+ entries = (await fsp5.readdir(targetDir)).sort();
3996
4536
  } catch {
3997
4537
  return { exists: false, managed: 0, foreign: [] };
3998
4538
  }
@@ -4066,7 +4606,7 @@ function materializeOneSkill(args) {
4066
4606
  try: () => fsp5.realpath(store.getStoreSkillDir(args.libraryId, args.skill.id, args.effectiveRev)),
4067
4607
  catch: (e) => new StoreError({ message: String(e) })
4068
4608
  });
4069
- return { storeDir: real, updatedLibState: args.libState };
4609
+ return { storeDir: real, updatedLibState: args.libState, hotHit: true };
4070
4610
  }
4071
4611
  }
4072
4612
  const fileMap = new Map;
@@ -4094,7 +4634,7 @@ function materializeOneSkill(args) {
4094
4634
  if (cached && !args.forceRefreshBodies && cached.lastEditedTime === args.skill.lastEditedTime) {
4095
4635
  rawMainMarkdown = cached.rawBody;
4096
4636
  } else {
4097
- const fetched = yield* notion.readSkillBody(args.skill.id);
4637
+ const fetched = yield* notion.readSkillBody(args.skill.id, { skipPageMeta: true });
4098
4638
  rawMainMarkdown = fetched.rawMarkdown;
4099
4639
  nextMainCache[args.skill.id] = {
4100
4640
  lastEditedTime: args.skill.lastEditedTime,
@@ -4150,25 +4690,49 @@ function materializeOneSkill(args) {
4150
4690
  ...args.libState,
4151
4691
  mainHashCache: nextMainCache,
4152
4692
  fileBodyCache: nextFileBodyCache
4153
- }
4693
+ },
4694
+ hotHit: false
4154
4695
  };
4155
4696
  });
4156
4697
  }
4157
4698
  function publishExportTarget(args) {
4158
4699
  return Effect4.gen(function* () {
4700
+ const onConflict = args.onConflict ?? "error";
4701
+ const destRoot = resolveHomePath(args.target.dir);
4702
+ const skippedConflicts = [];
4703
+ const warnings = [];
4159
4704
  const seenNames = new Map;
4705
+ const duplicateNames = new Map;
4160
4706
  for (const entry of args.selectedEntries) {
4161
4707
  const prev = seenNames.get(entry.name);
4162
4708
  if (prev && prev.skillId !== entry.skillId) {
4163
- return yield* Effect4.fail(new ConflictError({
4164
- kind: "duplicate_name",
4165
- message: `Duplicate active skill name '${entry.name}' in Notion (${prev.skillId} vs ${entry.skillId}); refusing export.`,
4166
- details: [prev.skillId, entry.skillId]
4167
- }));
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;
4168
4720
  }
4169
4721
  seenNames.set(entry.name, entry);
4170
4722
  }
4171
- 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
+ }
4172
4736
  const storeRootResolved = nodePath5.resolve(args.storeRoot);
4173
4737
  const storeRootReal = yield* Effect4.promise(() => fsp5.realpath(storeRootResolved).catch(() => storeRootResolved));
4174
4738
  return yield* Effect4.tryPromise({
@@ -4176,9 +4740,16 @@ function publishExportTarget(args) {
4176
4740
  await fsp5.mkdir(destRoot, { recursive: true });
4177
4741
  const exportedDirs = [];
4178
4742
  const activeStoreTargets = new Set;
4179
- const desiredNames = new Set(seenNames.keys());
4180
- 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
+ };
4181
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;
4182
4753
  for (const [skillName, entry] of seenNames) {
4183
4754
  if (!entry.materializedPath) {
4184
4755
  throw new Error(`Skill '${skillName}' has no materialized store path ready for export.`);
@@ -4190,28 +4761,64 @@ function publishExportTarget(args) {
4190
4761
  if (lst.isSymbolicLink()) {
4191
4762
  const rawLink = await fsp5.readlink(entryPath);
4192
4763
  const resolvedLink = nodePath5.resolve(nodePath5.dirname(entryPath), rawLink);
4193
- if (!isManagedStoreLink(resolvedLink)) {
4194
- throw new ConflictError({
4195
- kind: "foreign_target",
4196
- 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
4197
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;
4198
4782
  }
4199
4783
  } else if (lst.isDirectory()) {
4200
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") {
4201
4804
  throw new ConflictError({
4202
4805
  kind: "foreign_target",
4203
- message: `Refusing to overwrite non-managed foreign directory '${entryPath}'.`
4806
+ message: reason
4204
4807
  });
4205
4808
  }
4206
- } else {
4207
- throw new ConflictError({
4208
- kind: "foreign_target",
4209
- message: `Refusing to overwrite non-managed file '${entryPath}'.`
4809
+ skippedConflicts.push({
4810
+ name: skillName,
4811
+ path: entryPath,
4812
+ kind: "foreign_file",
4813
+ reason
4210
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;
4211
4817
  }
4212
4818
  }
4819
+ publishableEntries.set(skillName, entry);
4213
4820
  }
4214
- for (const [skillName, entry] of seenNames) {
4821
+ for (const [skillName, entry] of publishableEntries) {
4215
4822
  const storePath = entry.materializedPath;
4216
4823
  const destPath = nodePath5.join(destRoot, skillName);
4217
4824
  if (args.target.mode === "symlink") {
@@ -4263,7 +4870,8 @@ function publishExportTarget(args) {
4263
4870
  if (lst.isSymbolicLink()) {
4264
4871
  const rawLink = await fsp5.readlink(full);
4265
4872
  const resolvedLink = nodePath5.resolve(nodePath5.dirname(full), rawLink);
4266
- if (isManagedStoreLink(resolvedLink)) {
4873
+ const realResolvedLink = await fsp5.realpath(resolvedLink).catch(() => resolvedLink);
4874
+ if (isManagedStoreLink(resolvedLink, realResolvedLink)) {
4267
4875
  if (resolvedLink.includes(`${nodePath5.sep}_bundled${nodePath5.sep}`)) {
4268
4876
  activeStoreTargets.add(resolvedLink);
4269
4877
  continue;
@@ -4278,7 +4886,7 @@ function publishExportTarget(args) {
4278
4886
  await moveToSystemTrash(full);
4279
4887
  }
4280
4888
  }
4281
- return { exportedDirs, activeStoreTargets };
4889
+ return { exportedDirs, activeStoreTargets, skippedConflicts, warnings };
4282
4890
  },
4283
4891
  catch: (err) => err instanceof ConflictError ? err : new StoreError({ path: destRoot, message: String(err) })
4284
4892
  });
@@ -4302,6 +4910,96 @@ async function copyDirectoryContentsWritable(srcDir, dstDir) {
4302
4910
  }
4303
4911
  }
4304
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
+ }
4305
5003
  function syncCommand(options = {}) {
4306
5004
  return Effect4.gen(function* () {
4307
5005
  const notion = yield* NotionPort;
@@ -4320,6 +5018,8 @@ function syncCommand(options = {}) {
4320
5018
  mainHashCache: {},
4321
5019
  fileBodyCache: {}
4322
5020
  };
5021
+ const resolvedExports = yield* resolveConfiguredExports(config, store.paths.configPath);
5022
+ const allExportTargets = resolvedExports.targets.map((r) => r.target);
4323
5023
  if (!options.full && prevLib.lastSyncedAt && dedupeWindowMs > 0) {
4324
5024
  const age = Date.now() - Date.parse(prevLib.lastSyncedAt);
4325
5025
  if (age >= 0 && age < dedupeWindowMs) {
@@ -4328,7 +5028,7 @@ function syncCommand(options = {}) {
4328
5028
  libraryId,
4329
5029
  workRoot: store.paths.workRoot,
4330
5030
  storeRoot: store.paths.storeRoot,
4331
- exports: config.exports,
5031
+ exports: allExportTargets,
4332
5032
  sources: prevLib.sources,
4333
5033
  skills: prevLib.skills
4334
5034
  })).pipe(Effect4.catch(() => Effect4.succeed({
@@ -4351,7 +5051,7 @@ function syncCommand(options = {}) {
4351
5051
  prunedCount: 0,
4352
5052
  pulled: { added: [], updated: [], removed: [] },
4353
5053
  localPending: pending,
4354
- warnings: []
5054
+ warnings: resolvedExports.warnings
4355
5055
  };
4356
5056
  }
4357
5057
  }
@@ -4453,15 +5153,33 @@ function syncCommand(options = {}) {
4453
5153
  arr.push(f);
4454
5154
  filesBySkillId.set(f.skillId, arr);
4455
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
+ }));
4456
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
+ }
4457
5177
  if (config.prefetch === "all-profiles") {
4458
5178
  for (const sk of catalogSkills)
4459
5179
  exportSeedIds.add(sk.id);
4460
5180
  } else if (config.prefetch === "discoverable") {
4461
- for (const exp of config.exports) {
4462
- for (const sk of selectExportSkills(catalogSkills, exp))
4463
- exportSeedIds.add(sk.id);
4464
- for (const sk of selectDiscoverableSkills(catalogSkills, exp))
5181
+ for (const { selection } of exportSelections) {
5182
+ for (const sk of selection.discoverable)
4465
5183
  exportSeedIds.add(sk.id);
4466
5184
  }
4467
5185
  for (const sk of catalogSkills) {
@@ -4469,16 +5187,10 @@ function syncCommand(options = {}) {
4469
5187
  exportSeedIds.add(sk.id);
4470
5188
  }
4471
5189
  }
4472
- } else {
4473
- for (const exp of config.exports) {
4474
- for (const sk of selectExportSkills(catalogSkills, exp))
4475
- exportSeedIds.add(sk.id);
4476
- }
4477
5190
  }
4478
5191
  const { closureIds, missingOrDisabled } = computeRequiresClosure(exportSeedIds, effectiveById);
4479
5192
  const previouslyMaterializedIds = new Set(currentCatalog.entries.filter((e) => e.libraryId === libraryId && e.materializedPath).map((e) => e.skillId));
4480
5193
  const deltaSkillIds = new Set([...delta.skills.map((s) => s.id), ...rywSkillSet]);
4481
- const warnings = [];
4482
5194
  const skillWarnings = new Map;
4483
5195
  for (const [sid, badReqs] of missingOrDisabled) {
4484
5196
  const skName = effectiveById.get(sid)?.name ?? sid;
@@ -4511,31 +5223,74 @@ function syncCommand(options = {}) {
4511
5223
  const currentNowMs = options.nowMs ?? Date.now();
4512
5224
  const hasPriorWatermark = Boolean(prevLib.watermark);
4513
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
+ }
4514
5232
  for (const sk of effectiveSkills) {
4515
5233
  const cached = workingLibState.mainHashCache[sk.id];
4516
5234
  const inCurrentDelta = deltaSkillIds.has(sk.id);
4517
5235
  const isMinuteSettled = maxServerMs - Date.parse(sk.lastEditedTime) >= 120000 || currentNowMs - Date.parse(sk.lastEditedTime) >= 120000;
4518
- 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;
4519
5238
  const isHotOrDefault = closureIds.has(sk.id) || sk.visibility === "always" || previouslyMaterializedIds.has(sk.id);
4520
5239
  const prevSk = prevLib.skills[sk.id];
4521
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"));
4522
5241
  const suspectedWebEdit = Boolean(metaUnchanged && prevSk && (prevSk.lastEditedTime !== sk.lastEditedTime || !isMinuteSettled));
4523
- const needsBodyCheck = !sk.originSourceId || sk.customMain ? staleOrUnsettled && (isHotOrDefault || !isFull && hasPriorWatermark && inCurrentDelta) : Boolean(sk.previewHash && !isFull && hasPriorWatermark && inCurrentDelta && staleOrUnsettled && suspectedWebEdit);
4524
- 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) {
4525
5265
  bodyCheckTasks.push({ sk, settled: isMinuteSettled });
5266
+ } else if (cachedTimestampStale) {
5267
+ staleMainCacheIds.add(sk.id);
4526
5268
  }
4527
5269
  }
4528
5270
  const mutableMainCache = {
4529
5271
  ...workingLibState.mainHashCache
4530
5272
  };
4531
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
+ }
4532
5287
  if (bodyCheckTasks.length > 0) {
4533
5288
  if (bodyCheckTasks.length >= 20) {
4534
5289
  emitSyncProgress(`Fetching ${bodyCheckTasks.length} Notion skill page(s)...`);
4535
5290
  }
4536
5291
  let fetchedBodies = 0;
4537
5292
  yield* Effect4.forEach(bodyCheckTasks, ({ sk, settled }) => Effect4.gen(function* () {
4538
- const body = yield* notion.readSkillBody(sk.id);
5293
+ const body = yield* notion.readSkillBody(sk.id, { skipPageMeta: true });
4539
5294
  const rawHash = sha256Hex(body.rawMarkdown);
4540
5295
  mutableMainCache[sk.id] = {
4541
5296
  lastEditedTime: sk.lastEditedTime,
@@ -4560,9 +5315,9 @@ function syncCommand(options = {}) {
4560
5315
  }
4561
5316
  for (const sk of effectiveSkills) {
4562
5317
  if (sk.originSourceId && !sk.customMain && sk.previewHash) {
4563
- const latestBodyHash = workingLibState.mainHashCache[sk.id]?.rawBodySha256;
4564
- if (latestBodyHash && latestBodyHash !== sk.previewHash) {
4565
- 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)。`;
4566
5321
  warnings.push(msg);
4567
5322
  skillWarnings.set(sk.id, [...skillWarnings.get(sk.id) ?? [], msg]);
4568
5323
  }
@@ -4593,7 +5348,7 @@ function syncCommand(options = {}) {
4593
5348
  } else if (cachedSourceCommits.has(src.id)) {
4594
5349
  resolvedCommits.set(src.id, cachedSourceCommits.get(src.id));
4595
5350
  } else if (!resolvedCommits.has(src.id) && !failedSourceHeadErrors.has(src.id)) {
4596
- 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") {
4597
5352
  const shaOrErr = yield* upstream.resolveHeadCommit(src.repoUrl, src.ref).pipe(Effect4.result);
4598
5353
  if (shaOrErr._tag === "Success") {
4599
5354
  resolvedCommits.set(src.id, shaOrErr.success);
@@ -4645,10 +5400,14 @@ function syncCommand(options = {}) {
4645
5400
  const materializedPaths = new Map;
4646
5401
  let materializedCount = 0;
4647
5402
  const closureList = [...closureIds];
4648
- if (closureList.length >= 20) {
4649
- 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)...`);
4650
5409
  }
4651
- let finishedMat = 0;
5410
+ let finishedColdMat = 0;
4652
5411
  yield* Effect4.forEach(closureList, (sid) => Effect4.gen(function* () {
4653
5412
  const sk = effectiveById.get(sid);
4654
5413
  const src = sk.originSourceId ? sourcesById.get(sk.originSourceId) ?? null : null;
@@ -4711,12 +5470,14 @@ function syncCommand(options = {}) {
4711
5470
  }
4712
5471
  materializedPaths.set(sid, mat.storeDir);
4713
5472
  materializedCount++;
4714
- finishedMat++;
4715
- if (finishedMat % 25 === 0) {
4716
- if (closureList.length >= 20) {
4717
- 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);
4718
5480
  }
4719
- yield* saveIntermediateCheckpoint(mutableMainCache, mutableFileBodyCache);
4720
5481
  }
4721
5482
  }), { concurrency: 4 });
4722
5483
  workingLibState = {
@@ -4724,8 +5485,7 @@ function syncCommand(options = {}) {
4724
5485
  mainHashCache: { ...mutableMainCache },
4725
5486
  fileBodyCache: { ...mutableFileBodyCache }
4726
5487
  };
4727
- const nextLibEntries = [];
4728
- for (const sk of catalogSkills) {
5488
+ const buildCatalogEntryForSkill = (sk) => Effect4.gen(function* () {
4729
5489
  const src = sk.originSourceId ? sourcesById.get(sk.originSourceId) ?? null : null;
4730
5490
  const rev = getEffectiveRevFor(sk.id);
4731
5491
  let matPath = materializedPaths.get(sk.id) ?? null;
@@ -4737,7 +5497,7 @@ function syncCommand(options = {}) {
4737
5497
  matPath = prevEntry.materializedPath;
4738
5498
  }
4739
5499
  }
4740
- nextLibEntries.push({
5500
+ return {
4741
5501
  libraryId,
4742
5502
  skillId: sk.id,
4743
5503
  name: sk.name,
@@ -4769,29 +5529,42 @@ function syncCommand(options = {}) {
4769
5529
  lastEditedTime: ov.lastEditedTime
4770
5530
  })),
4771
5531
  lastEditedTime: sk.lastEditedTime
4772
- });
5532
+ };
5533
+ });
5534
+ const nextLibEntries = [];
5535
+ for (const sk of catalogSkills) {
5536
+ nextLibEntries.push(yield* buildCatalogEntryForSkill(sk));
4773
5537
  }
4774
5538
  nextLibEntries.sort((a, b) => a.name.localeCompare(b.name));
4775
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
+ }
4776
5548
  const protectedDirs = new Set;
4777
- for (const e of nextLibEntries) {
5549
+ for (const e of exportEntryMapById.values()) {
4778
5550
  if (e.materializedPath)
4779
5551
  protectedDirs.add(e.materializedPath);
4780
5552
  }
4781
- let exportedCount = 0;
4782
5553
  const manifestExports = [];
4783
- for (const exp of config.exports) {
4784
- const selectedSkills = selectExportSkills(catalogSkills, exp);
4785
- 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));
4786
5558
  const directNameSet = new Set(selectedEntries.map((e) => e.name.toLowerCase()));
4787
- 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()));
4788
5560
  let routerEntry = null;
4789
5561
  const routerName = (exp.router?.name ?? "skill-catalog").trim() || "skill-catalog";
4790
- if (discoverableEntries.length > 0 && exp.router?.enabled !== false && !directNameSet.has(routerName.toLowerCase())) {
5562
+ if (selection.resolvedRouterEnabled && discoverableEntries.length > 0 && !directNameSet.has(routerName.toLowerCase())) {
4791
5563
  const synth = synthesizeSkillCatalogPackage({
4792
5564
  routerName,
4793
5565
  discoverableEntries,
4794
- allEntriesById: entryMapById
5566
+ allEntriesById: exportEntryMapById,
5567
+ byNameRoot: store.paths.byNameRoot
4795
5568
  });
4796
5569
  const routerSkillId = `_router-${routerName}`;
4797
5570
  const routerStoreDir = yield* store.publishImmutablePackage({
@@ -4828,14 +5601,7 @@ function syncCommand(options = {}) {
4828
5601
  };
4829
5602
  }
4830
5603
  const finalExportEntries = routerEntry ? [...selectedEntries, routerEntry] : selectedEntries;
4831
- const pub = yield* publishExportTarget({
4832
- target: exp,
4833
- selectedEntries: finalExportEntries,
4834
- storeRoot: store.paths.storeRoot
4835
- });
4836
- exportedCount += pub.exportedDirs.length;
4837
- for (const p of pub.activeStoreTargets)
4838
- protectedDirs.add(p);
5604
+ preparedExports.push({ target: exp, finalExportEntries });
4839
5605
  manifestExports.push({
4840
5606
  dir: exp.dir,
4841
5607
  mode: exp.mode,
@@ -4878,6 +5644,10 @@ function syncCommand(options = {}) {
4878
5644
  })
4879
5645
  });
4880
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
+ }
4881
5651
  const nextCatalog = {
4882
5652
  version: 2,
4883
5653
  updatedAt: syncStartIso,
@@ -4888,6 +5658,40 @@ function syncCommand(options = {}) {
4888
5658
  entries: [...otherLibEntries, ...nextLibEntries]
4889
5659
  };
4890
5660
  yield* store.writeCatalog(nextCatalog);
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
+ }
4891
5695
  const activeRepoCommits = [];
4892
5696
  for (const libSnapshot of Object.values(nextCatalog.libraries)) {
4893
5697
  for (const src of Object.values(libSnapshot.sources)) {
@@ -4907,7 +5711,10 @@ function syncCommand(options = {}) {
4907
5711
  });
4908
5712
  }
4909
5713
  }
4910
- 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
+ }
4911
5718
  const nextEntryById = new Map(nextLibEntries.map((e) => [e.skillId, e]));
4912
5719
  const addedNames = [];
4913
5720
  const updatedNames = [];
@@ -4929,7 +5736,7 @@ function syncCommand(options = {}) {
4929
5736
  libraryId,
4930
5737
  workRoot: store.paths.workRoot,
4931
5738
  storeRoot: store.paths.storeRoot,
4932
- exports: config.exports,
5739
+ exports: allExportTargets,
4933
5740
  sources: workingLibState.sources,
4934
5741
  skills: workingLibState.skills
4935
5742
  })).pipe(Effect4.catch(() => Effect4.succeed({
@@ -4961,6 +5768,91 @@ function syncCommand(options = {}) {
4961
5768
  }));
4962
5769
  });
4963
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
+ }
4964
5856
  function findSkillsCommand(args) {
4965
5857
  return Effect4.gen(function* () {
4966
5858
  const store = yield* StorePort;
@@ -4969,7 +5861,7 @@ function findSkillsCommand(args) {
4969
5861
  const catalog = yield* store.readCatalog();
4970
5862
  const q = (args.query ?? "").trim().toLowerCase();
4971
5863
  const scene = args.scene?.trim();
4972
- const matched = catalog.entries.filter((e) => {
5864
+ const candidates = catalog.entries.filter((e) => {
4973
5865
  if (e.libraryId !== targetLib)
4974
5866
  return false;
4975
5867
  if (scene && !e.scenes.includes(scene))
@@ -4978,23 +5870,39 @@ function findSkillsCommand(args) {
4978
5870
  return false;
4979
5871
  if (args.kind && e.kind !== args.kind)
4980
5872
  return false;
4981
- if (!q)
4982
- return true;
4983
- return e.name.toLowerCase().includes(q) || e.description.toLowerCase().includes(q) || e.scenes.some((s) => s.toLowerCase().includes(q));
5873
+ return true;
4984
5874
  });
4985
- return matched.sort((a, b) => {
4986
- if (q) {
4987
- const aExact = a.name.toLowerCase() === q ? 1 : 0;
4988
- const bExact = b.name.toLowerCase() === q ? 1 : 0;
4989
- if (aExact !== bExact)
4990
- return bExact - aExact;
4991
- }
4992
- 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")
4993
5900
  return -1;
4994
- if (a.kind !== "router" && b.kind === "router")
5901
+ if (a.entry.kind !== "router" && b.entry.kind === "router")
4995
5902
  return 1;
4996
- return a.name.localeCompare(b.name);
5903
+ return a.entry.name.localeCompare(b.entry.name);
4997
5904
  });
5905
+ return scored.map((s) => s.entry);
4998
5906
  });
4999
5907
  }
5000
5908
  function loadSkillCommand(args) {
@@ -5005,12 +5913,22 @@ function loadSkillCommand(args) {
5005
5913
  if (args.refresh) {
5006
5914
  yield* syncCommand({ libraryId, dedupeWindowMs: 0 });
5007
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
+ };
5008
5926
  let catalog = yield* store.readCatalog();
5009
- let entry = catalog.entries.find((e) => e.libraryId === libraryId && e.name.toLowerCase() === args.name.trim().toLowerCase());
5927
+ let entry = findEntryByNameOrSlug(catalog.entries);
5010
5928
  if (!entry && !args.refresh) {
5011
5929
  yield* syncCommand({ libraryId, dedupeWindowMs: 0 });
5012
5930
  catalog = yield* store.readCatalog();
5013
- entry = catalog.entries.find((e) => e.libraryId === libraryId && e.name.toLowerCase() === args.name.trim().toLowerCase());
5931
+ entry = findEntryByNameOrSlug(catalog.entries);
5014
5932
  }
5015
5933
  if (!entry) {
5016
5934
  return yield* Effect4.fail(new NotFoundError({
@@ -5062,6 +5980,17 @@ function loadSkillCommand(args) {
5062
5980
  catch: (e) => new StoreError({ message: String(e) })
5063
5981
  });
5064
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
+ })));
5065
5994
  yield* Effect4.tryPromise(() => appendSkillUsageEvent({ action: "load", skillName: entry.name, libraryId }, store.paths.homeDir)).pipe(Effect4.catch(() => Effect4.void));
5066
5995
  return {
5067
5996
  entry: { ...entry, materializedPath: storeDir },
@@ -5139,6 +6068,18 @@ function loadSkillCommand(args) {
5139
6068
  libraries: { ...freshCat.libraries, [libraryId]: workingLib },
5140
6069
  entries: updatedEntries
5141
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
+ })));
5142
6083
  const finalStoreDir = matDirs.get(entry.skillId);
5143
6084
  const mdPath = nodePath5.join(finalStoreDir, "SKILL.md");
5144
6085
  const md = yield* Effect4.tryPromise({
@@ -5164,52 +6105,346 @@ function loadSkillCommand(args) {
5164
6105
  }));
5165
6106
  });
5166
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
+ }
5167
6219
  function exportCommand(args) {
5168
6220
  return Effect4.gen(function* () {
5169
6221
  const store = yield* StorePort;
5170
6222
  const { config, libraryId } = yield* loadResolvedLibrary(args.libraryId);
5171
- if (!args.toDir) {
5172
- 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);
5173
6237
  const allExported = [];
5174
- for (const exp of config.exports) {
6238
+ const targetResults = [];
6239
+ for (const { target: exp } of resolvedExports.targets) {
5175
6240
  const root = resolveHomePath(exp.dir);
5176
6241
  const names = yield* Effect4.tryPromise(() => fsp5.readdir(root)).pipe(Effect4.catch(() => Effect4.succeed([])));
5177
- for (const n of names.sort()) {
5178
- if (!n.startsWith("."))
5179
- 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
+ }));
5180
6274
  }
6275
+ seenSpecDirs.add(resolvedDir);
5181
6276
  }
5182
- 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
+ ];
5183
6313
  }
5184
- const adhocTarget = {
5185
- dir: args.toDir,
5186
- ...args.profile ? { profiles: [args.profile] } : {},
5187
- ...args.scene ? { scenes: [args.scene] } : {},
5188
- default_only: !args.includeNonDefault && !args.scene,
5189
- ...args.includeNonDefault ? { include_non_default: true } : {},
5190
- mode: args.mode ?? "symlink"
5191
- };
5192
6314
  const catalog = yield* store.readCatalog();
5193
- const libState = catalog.libraries[libraryId];
5194
- if (!libState) {
6315
+ if (!catalog.libraries[libraryId]) {
5195
6316
  yield* syncCommand({ libraryId, dedupeWindowMs: 0 });
5196
6317
  }
5197
- const freshCat = yield* store.readCatalog();
6318
+ let freshCat = yield* store.readCatalog();
5198
6319
  const freshLib = freshCat.libraries[libraryId];
5199
6320
  const sourcesById = new Map(Object.entries(freshLib.sources));
5200
6321
  const effective = filterEffectiveSkills(Object.values(freshLib.skills), sourcesById);
5201
- const selectedSkills = selectExportSkills(effective, adhocTarget);
5202
- const selectedEntries = [];
5203
- for (const sk of selectedSkills) {
5204
- const loaded = yield* loadSkillCommand({ name: sk.name, libraryId });
5205
- selectedEntries.push(loaded.entry);
5206
- }
5207
- const pub = yield* publishExportTarget({
5208
- target: adhocTarget,
5209
- selectedEntries,
5210
- 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;
5211
6351
  });
5212
- 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
+ };
5213
6448
  });
5214
6449
  }
5215
6450
  function statusCommand(args) {
@@ -5264,7 +6499,7 @@ function statusCommand(args) {
5264
6499
  import { randomUUID as randomUUID5 } from "node:crypto";
5265
6500
  import * as fsp6 from "node:fs/promises";
5266
6501
  import * as nodePath6 from "node:path";
5267
- import { Effect as Effect5, Option, Schema as Schema3 } from "effect";
6502
+ import { Effect as Effect5, Option, Schema as Schema4 } from "effect";
5268
6503
  var WORK_META_FILE = ".ntn-skill.json";
5269
6504
  var IGNORED_WORKDIR_NAMES = new Set([
5270
6505
  WORK_META_FILE,
@@ -5525,7 +6760,7 @@ function readWorkMeta(workdir) {
5525
6760
  const abs = nodePath6.resolve(workdir);
5526
6761
  const metaPath = nodePath6.join(abs, WORK_META_FILE);
5527
6762
  return Effect5.tryPromise({
5528
- 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"))),
5529
6764
  catch: (err) => err?.code === "ENOENT" ? new NotFoundError({
5530
6765
  entity: "workdir",
5531
6766
  target: abs,
@@ -5845,7 +7080,7 @@ function listWorkdirsCommand() {
5845
7080
  const raw = await fsp6.readFile(nodePath6.join(full, WORK_META_FILE), "utf8");
5846
7081
  out.push({
5847
7082
  workdir: full,
5848
- meta: Schema3.decodeUnknownSync(WorkMetaSchema)(JSON.parse(raw))
7083
+ meta: Schema4.decodeUnknownSync(WorkMetaSchema)(JSON.parse(raw))
5849
7084
  });
5850
7085
  } catch {}
5851
7086
  }
@@ -5870,6 +7105,9 @@ function cleanWorkdirsCommand(olderThanDays = 7) {
5870
7105
  return cleaned;
5871
7106
  });
5872
7107
  }
7108
+ function resolveImportedSkillVisibility(disableModelInvocation, requestedVisibility) {
7109
+ return disableModelInvocation ? "manual" : requestedVisibility ?? "manual";
7110
+ }
5873
7111
  function createNewSkillCommand(args) {
5874
7112
  return Effect5.gen(function* () {
5875
7113
  const notion = yield* NotionPort;
@@ -5909,13 +7147,14 @@ function createNewSkillCommand(args) {
5909
7147
  textContent
5910
7148
  });
5911
7149
  }
7150
+ const resolvedVisibility = args.visibility ?? (args.defaultContext !== undefined ? args.defaultContext ? "always" : "manual" : parsed.disableModelInvocation ? "manual" : "discoverable");
5912
7151
  const created = yield* notion.createSkillPage({
5913
7152
  libraryId,
5914
7153
  skillsDs: binding.skills_ds,
5915
7154
  name: skillName,
5916
7155
  description: (parsed.description ?? "").trim(),
5917
7156
  enabled: true,
5918
- visibility: args.visibility ?? (args.defaultContext !== undefined ? args.defaultContext ? "always" : "manual" : "discoverable"),
7157
+ visibility: resolvedVisibility,
5919
7158
  ...args.kind ? { kind: args.kind } : {},
5920
7159
  profiles: args.profiles?.length ? args.profiles : ["default"],
5921
7160
  scenes: args.scenes ?? [],
@@ -5939,12 +7178,13 @@ function createNewSkillCommand(args) {
5939
7178
  executable: sf.executable,
5940
7179
  textContent: sf.textContent
5941
7180
  }).pipe(Effect5.map((up) => up.pageId)), { concurrency: UPSTREAM_SKILL_CONCURRENCY });
7181
+ const resolvedExports = yield* resolveConfiguredExports(config, store.paths.configPath);
5942
7182
  const isInExportRoot = yield* Effect5.tryPromise(async () => {
5943
7183
  const lst = await fsp6.lstat(absDir).catch(() => null);
5944
7184
  if (!lst || lst.isSymbolicLink())
5945
7185
  return false;
5946
7186
  const realAbsParent = await fsp6.realpath(nodePath6.dirname(absDir)).catch(() => nodePath6.dirname(absDir));
5947
- for (const exp of config.exports) {
7187
+ for (const { target: exp } of resolvedExports.targets) {
5948
7188
  const expRoot = resolveHomePath(exp.dir);
5949
7189
  const realExpRoot = await fsp6.realpath(expRoot).catch(() => expRoot);
5950
7190
  if (nodePath6.dirname(absDir) === expRoot || realAbsParent === realExpRoot) {
@@ -5953,8 +7193,9 @@ function createNewSkillCommand(args) {
5953
7193
  }
5954
7194
  return false;
5955
7195
  }).pipe(Effect5.catch(() => Effect5.succeed(false)));
7196
+ const shouldAdopt = args.adopt === undefined ? isInExportRoot : args.adopt;
5956
7197
  let adoptedSourceDir = false;
5957
- if (isInExportRoot || args.adopt === true) {
7198
+ if (shouldAdopt) {
5958
7199
  yield* trashPathEffect(absDir);
5959
7200
  adoptedSourceDir = true;
5960
7201
  }
@@ -5963,11 +7204,26 @@ function createNewSkillCommand(args) {
5963
7204
  dedupeWindowMs: 0,
5964
7205
  readYourWrites: { skillIds: [created.id], fileIds: createdFileIds }
5965
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;
5966
7219
  return {
5967
7220
  skillId: created.id,
5968
7221
  name: skillName,
7222
+ visibility: resolvedVisibility,
5969
7223
  uploadedFiles: createdFileIds.length,
5970
- adoptedSourceDir
7224
+ adoptedSourceDir,
7225
+ adoptedFromExportRoot: adoptedSourceDir && isInExportRoot,
7226
+ exportedAtSourcePath
5971
7227
  };
5972
7228
  });
5973
7229
  }
@@ -6367,7 +7623,7 @@ function addSourceCommand(args) {
6367
7623
  name: d.name,
6368
7624
  description: d.description,
6369
7625
  enabled: true,
6370
- visibility: args.visibility ?? "manual",
7626
+ visibility: resolveImportedSkillVisibility(d.disableModelInvocation, args.visibility),
6371
7627
  profiles: ["default"],
6372
7628
  scenes: args.scenes ? [...args.scenes] : [],
6373
7629
  requiresIds: [],
@@ -6522,7 +7778,7 @@ function syncSourceSkillsCommand(args) {
6522
7778
  name: d.name,
6523
7779
  description: d.description,
6524
7780
  enabled: true,
6525
- visibility: "manual",
7781
+ visibility: resolveImportedSkillVisibility(d.disableModelInvocation),
6526
7782
  profiles: ["default"],
6527
7783
  scenes: [],
6528
7784
  requiresIds: [],
@@ -6885,25 +8141,40 @@ function upstreamCheckOrApplyCommand(args) {
6885
8141
  let nextDesc;
6886
8142
  if (!sk.customMain) {
6887
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;
6888
8146
  if (sk.previewHash && sha256Hex(currentBody.rawMarkdown) !== sk.previewHash) {
6889
- previewDriftWarnings.push(`Skill '${sk.name}': 网页预览已被修改但未勾选 Custom Main(修改尚未进入消费),已拒绝静默覆盖预览正文。`);
6890
- } else {
6891
- const upstreamMain = subtreeFiles.find((f) => f.path === "SKILL.md");
6892
- if (upstreamMain) {
6893
- 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) {
6894
8157
  const parsedMain = parseSkillFrontmatter(rawMainText);
6895
8158
  if (parsedMain.description !== undefined && parsedMain.description !== sk.description) {
6896
8159
  nextDesc = parsedMain.description;
6897
8160
  }
6898
- yield* notion.writeSkillBody({
6899
- libraryId,
6900
- skillId: sk.id,
6901
- markdownBody: rawMainText,
6902
- preserveUpstreamChild: true
6903
- });
6904
- const afterBody = yield* notion.readSkillBody(sk.id);
6905
- nextPreviewHash = sha256Hex(afterBody.rawMarkdown);
8161
+ nextPreviewHash = sha256Hex(currentBody.rawMarkdown);
8162
+ } else {
8163
+ previewDriftWarnings.push(`Skill '${sk.name}': 网页预览已被修改但未勾选 Custom Main(修改尚未进入消费),已拒绝静默覆盖预览正文。`);
6906
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);
6907
8178
  }
6908
8179
  }
6909
8180
  yield* notion.updateSkillProps({
@@ -6954,7 +8225,7 @@ function upstreamCheckOrApplyCommand(args) {
6954
8225
  name: d.name,
6955
8226
  description: d.description,
6956
8227
  enabled: true,
6957
- visibility: "manual",
8228
+ visibility: resolveImportedSkillVisibility(d.disableModelInvocation),
6958
8229
  profiles: ["default"],
6959
8230
  scenes: [],
6960
8231
  requiresIds: [],
@@ -7306,7 +8577,8 @@ function runScheduledJobCommand(args) {
7306
8577
  full: false,
7307
8578
  dedupeWindowMs: 5000
7308
8579
  });
7309
- 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}`;
7310
8582
  return {
7311
8583
  job: args.job,
7312
8584
  ok: true,
@@ -7323,7 +8595,8 @@ function runScheduledJobCommand(args) {
7323
8595
  dedupeWindowMs: 0
7324
8596
  });
7325
8597
  const cleaned = yield* cleanWorkdirsCommand(7);
7326
- 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}`;
7327
8600
  return {
7328
8601
  job: args.job,
7329
8602
  ok: true,
@@ -8390,6 +9663,399 @@ async function uninstallBundledSkill(args) {
8390
9663
  });
8391
9664
  }
8392
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
+
8393
10059
  // packages/cli/src/main.ts
8394
10060
  function splitMulti(values) {
8395
10061
  return values.flatMap((v) => v.split(",")).map((s) => s.trim()).filter(Boolean);
@@ -8499,7 +10165,7 @@ var doctorCmd = Command.make("doctor", {
8499
10165
  const report = yield* doctorCommand({ ...libOpt ? { libraryId: libOpt } : {} });
8500
10166
  const sched = yield* statusScheduleCommand().pipe(Effect7.catch(() => Effect7.succeed(null)));
8501
10167
  const syncActive = Boolean(sched?.units.some((u) => u.job === "sync" && u.active));
8502
- const allChecks = [
10168
+ const checks = [
8503
10169
  ...report.checks,
8504
10170
  {
8505
10171
  name: "background_sync",
@@ -8508,13 +10174,14 @@ var doctorCmd = Command.make("doctor", {
8508
10174
  ...syncActive ? {} : { hint: "Run: ntn-skills schedule install" }
8509
10175
  }
8510
10176
  ];
8511
- const fullReport = { ...report, checks: allChecks };
10177
+ const ok = checks.every((c) => c.status !== "fail");
10178
+ const fullReport = { ...report, ok, checks };
8512
10179
  if (!fullReport.ok) {
8513
10180
  process.exitCode = 1;
8514
10181
  }
8515
10182
  const lines = [
8516
10183
  `ntn-skills doctor: ${fullReport.ok ? "OK" : "ISSUES FOUND"}`,
8517
- ...allChecks.map((c) => {
10184
+ ...checks.map((c) => {
8518
10185
  const icon = c.status === "pass" ? "✓" : c.status === "warn" ? "!" : "✗";
8519
10186
  return ` [${icon}] ${c.name}: ${c.detail}${c.hint ? `
8520
10187
  hint: ${c.hint}` : ""}`;
@@ -8561,7 +10228,7 @@ var syncCmd = Command.make("sync", {
8561
10228
  }
8562
10229
  if (lp.unmanagedLocalSkills.length > 0) {
8563
10230
  const uList = lp.unmanagedLocalSkills.map((u) => `${u.name} (${u.path})`).join(", ");
8564
- 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)`);
8565
10232
  }
8566
10233
  if (lp.uninitializedSources.length > 0) {
8567
10234
  pendingLines.push(` - ${lp.uninitializedSources.length} uninitialized Notion source(s): ${fmtList(lp.uninitializedSources)} -> run 'ntn-skills upstream apply <source>'`);
@@ -8691,7 +10358,13 @@ var statusCmd = Command.make("status", {
8691
10358
  `));
8692
10359
  })).pipe(Command.withDescription("Show Visibility distribution, draft buffer, active upstream overlays, and on-demand load frequency"));
8693
10360
  var exportCmd = Command.make("export", {
8694
- 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)),
8695
10368
  profile: Flag.String("profile").pipe(Flag.optional),
8696
10369
  scene: Flag.String("scene").pipe(Flag.optional),
8697
10370
  mode: Flag.Literals("mode", ["symlink", "copy"]).pipe(Flag.optional),
@@ -8699,23 +10372,46 @@ var exportCmd = Command.make("export", {
8699
10372
  library: libraryFlag,
8700
10373
  json: jsonFlag
8701
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
+ }
8702
10380
  const toDir = Option2.getOrUndefined(cfg.to);
10381
+ const specPath = Option2.getOrUndefined(cfg.spec);
8703
10382
  const prof = Option2.getOrUndefined(cfg.profile);
8704
10383
  const sc = Option2.getOrUndefined(cfg.scene);
8705
10384
  const md = Option2.getOrUndefined(cfg.mode);
8706
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;
8707
10389
  const res = yield* exportCommand({
8708
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 } : {},
8709
10396
  ...prof ? { profile: prof } : {},
8710
10397
  ...sc ? { scene: sc } : {},
8711
10398
  ...md ? { mode: md } : {},
8712
- includeNonDefault: cfg.includeNonDefault,
10399
+ ...cfg.includeNonDefault ? { includeNonDefault: true } : {},
8713
10400
  ...lib ? { libraryId: lib } : {}
8714
10401
  });
8715
- yield* printOut(cfg.json, res, `Exported ${res.exportedDirs.length} skill(s):
8716
- ${res.exportedDirs.map((d) => ` ${d}`).join(`
8717
- `)}`);
8718
- })).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"));
8719
10415
  var editCmd = Command.make("edit", {
8720
10416
  name: Argument.String("name"),
8721
10417
  library: libraryFlag,
@@ -8808,31 +10504,52 @@ var newCmd = Command.make("new", {
8808
10504
  name: Flag.String("name").pipe(Flag.optional),
8809
10505
  profiles: Flag.String("profiles").pipe(Flag.atLeast(0)),
8810
10506
  scenes: Flag.String("scenes").pipe(Flag.atLeast(0)),
8811
- 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),
8812
10508
  kind: Flag.Literals("kind", ["skill", "router", "prompt"]).pipe(Flag.withDescription("Skill kind (default: skill)"), Flag.optional),
8813
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)),
8814
10512
  default: Flag.Boolean("default").pipe(Flag.withDescription("Alias for --always"), Flag.withDefault(false)),
8815
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")),
8816
10515
  library: libraryFlag,
8817
10516
  json: jsonFlag
8818
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
+ }
8819
10521
  const nm = Option2.getOrUndefined(cfg.name);
8820
10522
  const visOpt = Option2.getOrUndefined(cfg.visibility);
8821
10523
  const kindOpt = Option2.getOrUndefined(cfg.kind);
8822
10524
  const lib = Option2.getOrUndefined(cfg.library);
8823
- 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;
8824
10541
  const res = yield* createNewSkillCommand({
8825
10542
  dir: cfg.dir,
8826
10543
  ...nm ? { name: nm } : {},
8827
10544
  profiles: splitMulti(cfg.profiles),
8828
10545
  scenes: splitMulti(cfg.scenes),
8829
- visibility,
10546
+ ...visibility ? { visibility } : {},
8830
10547
  ...kindOpt ? { kind: kindOpt } : {},
8831
- adopt: cfg.adopt,
10548
+ ...adoptOpt !== undefined ? { adopt: adoptOpt } : {},
8832
10549
  ...lib ? { libraryId: lib } : {}
8833
10550
  });
8834
- const adoptNote = res.adoptedSourceDir ? " [adopted local directory -> Trash]" : "";
8835
- 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}.`);
8836
10553
  })).pipe(Command.withDescription("Create a brand-new native skill in Notion from a local directory"));
8837
10554
  var setCmd = Command.make("set", {
8838
10555
  names: Argument.String("name").pipe(Argument.atLeast(0)),
@@ -9269,10 +10986,28 @@ var skillCmd = Command.make("skill", {
9269
10986
  }
9270
10987
  yield* printOut(cfg.json, payload, payload.markdown.trimEnd());
9271
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"));
9272
11006
  var rootCommand = Command.make("ntn-skills").pipe(Command.withDescription("Notion 3-table skill control-plane synchronizer & local-native CLI (v2)"), Command.withSubcommands([
9273
11007
  initCmd,
9274
11008
  doctorCmd,
9275
11009
  skillCmd,
11010
+ mcpCmd,
9276
11011
  syncCmd,
9277
11012
  findCmd,
9278
11013
  loadCmd,