ntn-skills 2.1.0 → 2.3.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
@@ -234,8 +234,27 @@ function normalizeUuid(raw) {
234
234
  function libShortHash(libraryId) {
235
235
  return normalizeUuid(libraryId).replace(/-/g, "").slice(0, 8);
236
236
  }
237
+ var SKILL_SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
238
+ function isValidSkillSlug(raw) {
239
+ return SKILL_SLUG_RE.test(raw);
240
+ }
237
241
  function normalizeSkillSlug(raw) {
238
- return raw.trim().toLowerCase().replace(/[\s_]+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
242
+ return raw.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
243
+ }
244
+ function resolveCanonicalSkillName(preferred, fallback) {
245
+ const pref = (preferred ?? "").trim();
246
+ if (pref && isValidSkillSlug(pref))
247
+ return pref;
248
+ const isAsciiOnly = pref.length > 0 && /^[\x20-\x7E]+$/.test(pref);
249
+ if (isAsciiOnly) {
250
+ const prefSlug = normalizeSkillSlug(pref);
251
+ if (prefSlug)
252
+ return prefSlug;
253
+ }
254
+ const fbSlug = normalizeSkillSlug(fallback ?? "");
255
+ if (fbSlug)
256
+ return fbSlug;
257
+ return normalizeSkillSlug(pref);
239
258
  }
240
259
  function computeOverlapWindowIso(watermarkIso, overlapMs = 120000) {
241
260
  const ms = Date.parse(watermarkIso);
@@ -346,22 +365,26 @@ function parseSkillFrontmatter(markdown) {
346
365
  hasFrontmatter: true
347
366
  };
348
367
  }
349
- function applyAuthoritativeFrontmatter(rawMarkdown, authoritativeName, authoritativeDescription) {
368
+ function applyAuthoritativeFrontmatter(rawMarkdown, authoritativeName, authoritativeDescription, requiresPaths) {
350
369
  const parsed = parseSkillFrontmatter(rawMarkdown);
370
+ const canonicalName = normalizeSkillSlug(authoritativeName) || authoritativeName.trim();
351
371
  const headerLines = [
352
372
  "---",
353
- `name: ${JSON.stringify(authoritativeName)}`,
373
+ `name: ${JSON.stringify(canonicalName)}`,
354
374
  `description: ${JSON.stringify(authoritativeDescription)}`,
355
375
  ...parsed.extraLines,
356
376
  "---"
357
377
  ];
378
+ const reqPairs = Object.entries(requiresPaths ?? {}).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${k}=${v}`);
379
+ const reqLine = reqPairs.length > 0 ? `
380
+ Requires: ${reqPairs.join(", ")}
381
+ ` : "";
358
382
  const cleanBody = parsed.body.replace(/^\n+/, "").replace(/\s+$/, "");
359
383
  return cleanBody.length > 0 ? `${headerLines.join(`
360
- `)}
361
-
384
+ `)}${reqLine}
362
385
  ${cleanBody}
363
386
  ` : `${headerLines.join(`
364
- `)}
387
+ `)}${reqLine}
365
388
  `;
366
389
  }
367
390
  function computeEffectiveRev(input) {
@@ -677,9 +700,25 @@ function sanitizeSceneSlug(raw) {
677
700
  const slug = raw.trim().toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
678
701
  return slug || "general";
679
702
  }
703
+ function summarizeCatalogDescription(raw, maxChars = 140) {
704
+ const flat = raw.replace(/\s+/g, " ").trim();
705
+ if (!flat)
706
+ return "(no description)";
707
+ if (flat.length <= maxChars)
708
+ return flat;
709
+ const window = flat.slice(0, maxChars);
710
+ const sentenceEnd = window.search(/(?:\.\s+|。\s*|;\s*)/);
711
+ if (sentenceEnd >= 24 && sentenceEnd <= maxChars - 1) {
712
+ const endChar = window[sentenceEnd];
713
+ const cut = endChar === "." ? sentenceEnd + 1 : sentenceEnd + 1;
714
+ return window.slice(0, cut).trim();
715
+ }
716
+ return `${flat.slice(0, maxChars - 3).trimEnd()}...`;
717
+ }
680
718
  function synthesizeSkillCatalogPackage(args) {
681
719
  const enc = new TextEncoder;
682
720
  const normalizedByNameRoot = args.byNameRoot?.trim().replace(/\/+$/, "");
721
+ const cliCmd = args.cliCommand?.trim() || "ntn-skills";
683
722
  const sorted = [...args.discoverableEntries].sort((a, b) => {
684
723
  if (a.kind === "router" && b.kind !== "router")
685
724
  return -1;
@@ -688,12 +727,16 @@ function synthesizeSkillCatalogPackage(args) {
688
727
  return a.name.localeCompare(b.name);
689
728
  });
690
729
  const formatEntryBullet = (e) => {
691
- const reqNames = e.requiresIds.map((id) => args.allEntriesById.get(id)?.name).filter((n) => Boolean(n));
730
+ const slug = normalizeSkillSlug(e.name) || e.name;
731
+ const reqNames = e.requiresIds.map((id) => {
732
+ const n = args.allEntriesById.get(id)?.name;
733
+ return n ? normalizeSkillSlug(n) || n : undefined;
734
+ }).filter((n) => Boolean(n));
692
735
  const kindBadge = e.kind === "router" ? " `[strategy-router]`" : "";
693
- const desc = e.description.replace(/\s+/g, " ").trim() || "(no description)";
736
+ const desc = summarizeCatalogDescription(e.description, 140);
694
737
  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}`;
738
+ const unmaterializedSuffix = !e.materializedPath ? ` *(load via \`${cliCmd} load "${slug}" --path-only </dev/null\`)*` : "";
739
+ return `- **${slug}**${kindBadge}: ${desc}${reqSuffix}${unmaterializedSuffix}`;
697
740
  };
698
741
  const groups = new Map;
699
742
  for (const e of sorted) {
@@ -713,12 +756,12 @@ function synthesizeSkillCatalogPackage(args) {
713
756
  });
714
757
  const files = [];
715
758
  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`.';
759
+ const sceneLoadLine = normalizedByNameRoot ? `Load a skill by reading \`${normalizedByNameRoot}/<name>/SKILL.md\`.` : `Load a skill via \`${cliCmd} load "<name>" --path-only </dev/null\` then read \`<dir>/SKILL.md\`.`;
717
760
  for (const gk of orderedGroupKeys) {
718
761
  const items = groups.get(gk);
719
762
  const relPath = `references/${gk}.md`;
720
763
  const previewCandidates = items.filter((i) => i.kind !== "router");
721
- const sampleNames = previewCandidates.slice(0, 4).map((i) => i.name);
764
+ const sampleNames = previewCandidates.slice(0, 4).map((i) => normalizeSkillSlug(i.name) || i.name);
722
765
  const sampleSuffix = sampleNames.length > 0 ? `: ${sampleNames.join(", ")}${previewCandidates.length > 4 ? "..." : ""}` : "";
723
766
  groupSummaryLines.push(`- \`${relPath}\` (${items.length})${sampleSuffix}`);
724
767
  const refMd = [
@@ -739,15 +782,17 @@ function synthesizeSkillCatalogPackage(args) {
739
782
  const routerSection = strategyRouters.length > 0 ? [
740
783
  "## Strategy Routers",
741
784
  ...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}`;
785
+ const slug = normalizeSkillSlug(e.name) || e.name;
786
+ const desc = summarizeCatalogDescription(e.description, 140);
787
+ const unmat = !e.materializedPath ? ` (run: ${cliCmd} load "${slug}" --path-only </dev/null)` : "";
788
+ return `- **${slug}**: ${desc}${unmat}`;
745
789
  }),
746
790
  ""
747
791
  ] : [];
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`.';
792
+ const topLoadInstruction = normalizedByNameRoot ? `Open the matching scene file below, then read \`${normalizedByNameRoot}/<name>/SKILL.md\`.` : `Open the matching scene file below, then run \`${cliCmd} load "<name>" --path-only </dev/null\` and read \`<dir>/SKILL.md\`.`;
793
+ const cliSearchInstruction = `To search all skills (including manual skills) or materialize on demand, run \`${cliCmd} find "<query>" </dev/null\` and \`${cliCmd} load "<name>" --path-only </dev/null\`.`;
749
794
  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.`;
795
+ const topDescription = `On-demand index of ${sorted.length} specialized skills by scene${byNameDescClause}. Read ONLY when top-level skills do not cover a specialized workflow or tool; skip for routine coding/Q&A, or use skill_find directly if available.`;
751
796
  const mainMd = [
752
797
  "---",
753
798
  `name: ${JSON.stringify(args.routerName)}`,
@@ -756,6 +801,7 @@ function synthesizeSkillCatalogPackage(args) {
756
801
  "",
757
802
  `# ${args.routerName} (${sorted.length})`,
758
803
  topLoadInstruction,
804
+ cliSearchInstruction,
759
805
  "",
760
806
  ...routerSection,
761
807
  "## Scenes",
@@ -835,13 +881,29 @@ function formatSkillFindResults(args) {
835
881
  };
836
882
  }
837
883
  function formatLoadedSkillBlock(args) {
884
+ const parsed = parseSkillFrontmatter(args.markdown);
885
+ let bodyText = parsed.hasFrontmatter ? parsed.body.replace(/^\n+/, "") : args.markdown;
886
+ let inlineReqLine = "";
887
+ const leadingReqMatch = bodyText.match(/^Requires:\s*([^\n]+)\n+/);
888
+ if (leadingReqMatch) {
889
+ inlineReqLine = leadingReqMatch[1].trim();
890
+ bodyText = bodyText.slice(leadingReqMatch[0].length);
891
+ }
838
892
  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}">
893
+ const mergedReq = pairs.length > 0 ? pairs.join(", ") : inlineReqLine;
894
+ const reqLine = mergedReq ? `
895
+ Requires: ${mergedReq}` : "";
896
+ const extraFrontmatter = parsed.hasFrontmatter && parsed.extraLines.length > 0 ? `---
897
+ ${parsed.extraLines.join(`
898
+ `)}
899
+ ---
900
+
901
+ ` : "";
902
+ const cleanPayload = `${extraFrontmatter}${bodyText.trim()}`.trim();
903
+ return `<skill name="${args.name}" path="${args.dir}">
842
904
  References are relative to ${args.dir}.${reqLine}
843
905
 
844
- ${args.markdown.trim()}
906
+ ${cleanPayload}
845
907
  </skill>`;
846
908
  }
847
909
  // packages/core/src/notion/markdown-blocks.ts
@@ -1947,7 +2009,8 @@ function makeStoreService(overrides) {
1947
2009
  retentionDays = 14,
1948
2010
  repoTreeGraceMs = 3600000,
1949
2011
  repoSubtreeRetentionDays = 7,
1950
- repoGitRetentionDays = 14
2012
+ repoGitRetentionDays = 14,
2013
+ dryRun = false
1951
2014
  }) => Effect.tryPromise({
1952
2015
  try: async () => {
1953
2016
  const pruned = [];
@@ -2002,7 +2065,8 @@ function makeStoreService(overrides) {
2002
2065
  continue;
2003
2066
  if (normalizedProtected.has(v.dir) || normalizedProtected.has(v.realDir))
2004
2067
  continue;
2005
- await removeInternalCachePath(v.realDir);
2068
+ if (!dryRun)
2069
+ await removeInternalCachePath(v.realDir);
2006
2070
  pruned.push(v.realDir);
2007
2071
  }
2008
2072
  }
@@ -2034,7 +2098,8 @@ function makeStoreService(overrides) {
2034
2098
  if (nowMs - st.mtimeMs <= repoTreeGraceMs)
2035
2099
  continue;
2036
2100
  const real = await fsp.realpath(full).catch(() => nodePath.resolve(full));
2037
- await removeInternalCachePath(real);
2101
+ if (!dryRun)
2102
+ await removeInternalCachePath(real);
2038
2103
  pruned.push(real);
2039
2104
  }
2040
2105
  const subtreesRoot = nodePath.join(paths.reposRoot, "subtrees");
@@ -2058,7 +2123,8 @@ function makeStoreService(overrides) {
2058
2123
  if (nowMs - st.mtimeMs <= subRetMs)
2059
2124
  continue;
2060
2125
  const real = await fsp.realpath(full).catch(() => nodePath.resolve(full));
2061
- await removeInternalCachePath(real);
2126
+ if (!dryRun)
2127
+ await removeInternalCachePath(real);
2062
2128
  pruned.push(real);
2063
2129
  }
2064
2130
  const gitRoot = nodePath.join(paths.reposRoot, "git");
@@ -2073,7 +2139,8 @@ function makeStoreService(overrides) {
2073
2139
  if (nowMs - st.mtimeMs <= gitRetMs)
2074
2140
  continue;
2075
2141
  const real = await fsp.realpath(full).catch(() => nodePath.resolve(full));
2076
- await removeInternalCachePath(real);
2142
+ if (!dryRun)
2143
+ await removeInternalCachePath(real);
2077
2144
  pruned.push(real);
2078
2145
  }
2079
2146
  const tmpRoot = nodePath.join(paths.reposRoot, ".tmp");
@@ -2085,7 +2152,8 @@ function makeStoreService(overrides) {
2085
2152
  if (!st || !holderDead && nowMs - st.mtimeMs <= repoTreeGraceMs)
2086
2153
  continue;
2087
2154
  const real = await fsp.realpath(full).catch(() => nodePath.resolve(full));
2088
- await removeInternalCachePath(real);
2155
+ if (!dryRun)
2156
+ await removeInternalCachePath(real);
2089
2157
  pruned.push(real);
2090
2158
  }
2091
2159
  }
@@ -3944,7 +4012,7 @@ var UpstreamLiveLayer = Layer3.effect(UpstreamPort, Effect3.gen(function* () {
3944
4012
  const rawText = mdTexts.get(smd.path) ?? "";
3945
4013
  const parsed = parseSkillFrontmatter(rawText);
3946
4014
  const fallbackName = dir === "." ? repoUrl.replace(/\.git$/i, "").split("/").pop() : dir.split("/").pop();
3947
- const finalName = (parsed.name || fallbackName).trim();
4015
+ const finalName = resolveCanonicalSkillName(parsed.name, fallbackName);
3948
4016
  if (!finalName || seenGh.has(finalName.toLowerCase()))
3949
4017
  continue;
3950
4018
  seenGh.add(finalName.toLowerCase());
@@ -3988,7 +4056,7 @@ var UpstreamLiveLayer = Layer3.effect(UpstreamPort, Effect3.gen(function* () {
3988
4056
  const rawText = new TextDecoder().decode(smd.bytes);
3989
4057
  const parsed = parseSkillFrontmatter(rawText);
3990
4058
  const fallbackName = dir === "." ? repoUrl.replace(/\.git$/i, "").split("/").pop() : dir.split("/").pop();
3991
- const finalName = (parsed.name || fallbackName).trim();
4059
+ const finalName = resolveCanonicalSkillName(parsed.name, fallbackName);
3992
4060
  if (!finalName || seenNames.has(finalName.toLowerCase()))
3993
4061
  continue;
3994
4062
  seenNames.add(finalName.toLowerCase());
@@ -4123,6 +4191,7 @@ var UpstreamLiveLayer = Layer3.effect(UpstreamPort, Effect3.gen(function* () {
4123
4191
  // packages/core/src/sync/sync-engine.ts
4124
4192
  import { randomUUID as randomUUID4 } from "node:crypto";
4125
4193
  import * as fsp5 from "node:fs/promises";
4194
+ import * as os2 from "node:os";
4126
4195
  import * as nodePath5 from "node:path";
4127
4196
  import { Effect as Effect4, Schema as Schema3 } from "effect";
4128
4197
  function isHomeOrEnvPrefixed(raw) {
@@ -4413,6 +4482,26 @@ function initLibraryCommand(args) {
4413
4482
  };
4414
4483
  });
4415
4484
  }
4485
+ async function resolveLocalCliCommandHint(homeDir) {
4486
+ const isExec = async (p) => fsp5.access(p, fsp5.constants.X_OK).then(() => true).catch(() => false);
4487
+ for (const seg of (process.env.PATH ?? "").split(nodePath5.delimiter)) {
4488
+ const dir = seg.trim();
4489
+ if (!dir)
4490
+ continue;
4491
+ if (await isExec(nodePath5.join(dir, "ntn-skills"))) {
4492
+ return "ntn-skills";
4493
+ }
4494
+ }
4495
+ const candidates = [
4496
+ nodePath5.join(process.env.HOME?.trim() || os2.homedir(), ".local", "bin", "ntn-skills"),
4497
+ nodePath5.join(homeDir, "bin", "ntn-skills")
4498
+ ];
4499
+ for (const c of candidates) {
4500
+ if (await isExec(c))
4501
+ return c;
4502
+ }
4503
+ return "ntn-skills";
4504
+ }
4416
4505
  function doctorCommand(args) {
4417
4506
  return Effect4.gen(function* () {
4418
4507
  const notion = yield* NotionPort;
@@ -4524,6 +4613,23 @@ function doctorCommand(args) {
4524
4613
  status: "pass",
4525
4614
  detail: `Synced catalog: ${activeSources} source(s), ${activeSkills} active skill(s), ${activeFiles} file row(s) (lastSync=${libState.lastSyncedAt ?? libState.watermark ?? "unknown"}).`
4526
4615
  });
4616
+ const nonSlugSkills = Object.values(libState.skills).filter((s) => s.enabled && !isValidSkillSlug(s.name)).map((s) => s.name).sort();
4617
+ if (nonSlugSkills.length > 0) {
4618
+ const sample = nonSlugSkills.slice(0, 6).join(", ");
4619
+ const more = nonSlugSkills.length > 6 ? `, +${nonSlugSkills.length - 6} more` : "";
4620
+ checks.push({
4621
+ name: "skill_names",
4622
+ status: "warn",
4623
+ detail: `${nonSlugSkills.length} active skill(s) use non-slug names (${sample}${more}); local exports fall back to normalized lowercase slugs.`,
4624
+ hint: "Rename Skills.Name in Notion to lowercase hyphenated slugs (a-z, 0-9, -) for clean cross-agent compatibility."
4625
+ });
4626
+ } else {
4627
+ checks.push({
4628
+ name: "skill_names",
4629
+ status: "pass",
4630
+ detail: `All ${activeSkills} active skill name(s) conform to lowercase hyphenated slug format.`
4631
+ });
4632
+ }
4527
4633
  }
4528
4634
  const realStoreRoot = yield* Effect4.tryPromise(() => fsp5.realpath(store.paths.storeRoot)).pipe(Effect4.catch(() => Effect4.succeed(store.paths.storeRoot)));
4529
4635
  const storePrefixes = Array.from(new Set([`${store.paths.storeRoot}${nodePath5.sep}`, `${realStoreRoot}${nodePath5.sep}`]));
@@ -4644,7 +4750,7 @@ function materializeOneSkill(args) {
4644
4750
  };
4645
4751
  }
4646
4752
  }
4647
- const authoritativeSkillMd = applyAuthoritativeFrontmatter(rawMainMarkdown, args.skill.name, args.skill.description);
4753
+ const authoritativeSkillMd = applyAuthoritativeFrontmatter(rawMainMarkdown, args.skill.name, args.skill.description, args.requiresPaths);
4648
4754
  fileMap.set("SKILL.md", {
4649
4755
  path: "SKILL.md",
4650
4756
  bytes: new TextEncoder().encode(authoritativeSkillMd),
@@ -4695,6 +4801,192 @@ function materializeOneSkill(args) {
4695
4801
  };
4696
4802
  });
4697
4803
  }
4804
+ function planExportTarget(args) {
4805
+ return Effect4.gen(function* () {
4806
+ const onConflict = args.onConflict ?? "error";
4807
+ const destRoot = resolveHomePath(args.target.dir);
4808
+ const wouldSkipConflicts = [];
4809
+ const warnings = [];
4810
+ const seenNames = new Map;
4811
+ const duplicateNames = new Map;
4812
+ for (const entry of args.selectedEntries) {
4813
+ const exportName = normalizeSkillSlug(entry.name) || entry.name.trim();
4814
+ const prev = seenNames.get(exportName);
4815
+ if (prev && prev.skillId !== entry.skillId) {
4816
+ if (onConflict === "error") {
4817
+ return yield* Effect4.fail(new ConflictError({
4818
+ kind: "duplicate_name",
4819
+ message: `Duplicate active skill name '${exportName}' in Notion (${prev.skillId} vs ${entry.skillId}); refusing export.`,
4820
+ details: [prev.skillId, entry.skillId]
4821
+ }));
4822
+ }
4823
+ const ids = duplicateNames.get(exportName) ?? new Set([prev.skillId]);
4824
+ ids.add(entry.skillId);
4825
+ duplicateNames.set(exportName, ids);
4826
+ continue;
4827
+ }
4828
+ seenNames.set(exportName, entry);
4829
+ }
4830
+ for (const [dupName, ids] of duplicateNames) {
4831
+ seenNames.delete(dupName);
4832
+ const idList = [...ids].sort().join(", ");
4833
+ const entryPath = nodePath5.join(destRoot, dupName);
4834
+ const reason = `Duplicate active skill name '${dupName}' in Notion (${idList}); refusing export.`;
4835
+ wouldSkipConflicts.push({
4836
+ name: dupName,
4837
+ path: entryPath,
4838
+ kind: "duplicate_name",
4839
+ reason
4840
+ });
4841
+ warnings.push(`Skipped exporting '${dupName}' to '${entryPath}': duplicate active skill name in Notion (${idList}); resolve duplicate names in Notion and re-sync.`);
4842
+ }
4843
+ const storeRootResolved = nodePath5.resolve(args.storeRoot);
4844
+ const storeRootReal = yield* Effect4.promise(() => fsp5.realpath(storeRootResolved).catch(() => storeRootResolved));
4845
+ return yield* Effect4.tryPromise({
4846
+ try: async () => {
4847
+ const destExists = await fsp5.stat(destRoot).then((s) => s.isDirectory()).catch(() => false);
4848
+ const desiredNames = new Set([...seenNames.keys(), ...duplicateNames.keys()]);
4849
+ const wouldWrite = [];
4850
+ const wouldRemove = [];
4851
+ let publishableCount = 0;
4852
+ const isManagedStoreLink = (linkTargetAbs, linkTargetReal) => {
4853
+ const prefixes = [
4854
+ `${storeRootResolved}${nodePath5.sep}`,
4855
+ `${storeRootReal}${nodePath5.sep}`
4856
+ ];
4857
+ return prefixes.some((pref) => linkTargetAbs.startsWith(pref) || Boolean(linkTargetReal?.startsWith(pref)));
4858
+ };
4859
+ const isManagedCopyDir = async (dirPath) => fsp5.stat(nodePath5.join(dirPath, ".ntn-managed-copy.json")).then((s) => s.isFile()).catch(() => false);
4860
+ for (const [skillName, entry] of seenNames) {
4861
+ const storePath = entry.materializedPath;
4862
+ if (!storePath) {
4863
+ throw new Error(`Skill '${skillName}' has no planned or materialized store path ready for export.`);
4864
+ }
4865
+ const storePathResolved = nodePath5.resolve(storePath);
4866
+ const storePathReal = await fsp5.realpath(storePathResolved).catch(() => storePathResolved);
4867
+ if (!destExists) {
4868
+ publishableCount++;
4869
+ wouldWrite.push(skillName);
4870
+ continue;
4871
+ }
4872
+ const entryPath = nodePath5.join(destRoot, skillName);
4873
+ const lst = await fsp5.lstat(entryPath).catch(() => null);
4874
+ if (!lst) {
4875
+ publishableCount++;
4876
+ wouldWrite.push(skillName);
4877
+ continue;
4878
+ }
4879
+ if (lst.isSymbolicLink()) {
4880
+ const rawLink = await fsp5.readlink(entryPath);
4881
+ const resolvedLink = nodePath5.resolve(nodePath5.dirname(entryPath), rawLink);
4882
+ const realResolvedLink = await fsp5.realpath(resolvedLink).catch(() => resolvedLink);
4883
+ if (!isManagedStoreLink(resolvedLink, realResolvedLink)) {
4884
+ const reason = `Refusing to overwrite non-managed symlink '${entryPath}' -> '${rawLink}'.`;
4885
+ if (onConflict === "error") {
4886
+ throw new ConflictError({ kind: "foreign_target", message: reason });
4887
+ }
4888
+ wouldSkipConflicts.push({
4889
+ name: skillName,
4890
+ path: entryPath,
4891
+ kind: "foreign_symlink",
4892
+ linkTarget: rawLink,
4893
+ reason
4894
+ });
4895
+ warnings.push(`Skipped exporting '${skillName}' to '${entryPath}': non-managed symlink -> '${rawLink}' exists (left untouched; remove/relocate it or run 'ntn-skills doctor' to inspect).`);
4896
+ continue;
4897
+ }
4898
+ publishableCount++;
4899
+ if (args.target.mode === "symlink") {
4900
+ if (resolvedLink !== storePathResolved && realResolvedLink !== storePathReal) {
4901
+ wouldWrite.push(skillName);
4902
+ }
4903
+ } else {
4904
+ wouldWrite.push(skillName);
4905
+ }
4906
+ } else if (lst.isDirectory()) {
4907
+ if (!await isManagedCopyDir(entryPath)) {
4908
+ const reason = `Refusing to overwrite non-managed foreign directory '${entryPath}'.`;
4909
+ if (onConflict === "error") {
4910
+ throw new ConflictError({ kind: "foreign_target", message: reason });
4911
+ }
4912
+ wouldSkipConflicts.push({
4913
+ name: skillName,
4914
+ path: entryPath,
4915
+ kind: "foreign_directory",
4916
+ reason
4917
+ });
4918
+ 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).`);
4919
+ continue;
4920
+ }
4921
+ publishableCount++;
4922
+ if (args.target.mode === "symlink") {
4923
+ wouldWrite.push(skillName);
4924
+ } else {
4925
+ const markerFile = nodePath5.join(entryPath, ".ntn-managed-copy.json");
4926
+ const existingMarker = await fsp5.readFile(markerFile, "utf8").then((r) => JSON.parse(r)).catch(() => null);
4927
+ if (existingMarker?.effectiveRev !== entry.effectiveRev) {
4928
+ wouldWrite.push(skillName);
4929
+ }
4930
+ }
4931
+ } else {
4932
+ const reason = `Refusing to overwrite non-managed file '${entryPath}'.`;
4933
+ if (onConflict === "error") {
4934
+ throw new ConflictError({ kind: "foreign_target", message: reason });
4935
+ }
4936
+ wouldSkipConflicts.push({
4937
+ name: skillName,
4938
+ path: entryPath,
4939
+ kind: "foreign_file",
4940
+ reason
4941
+ });
4942
+ warnings.push(`Skipped exporting '${skillName}' to '${entryPath}': non-managed file exists (left untouched; remove/relocate it or run 'ntn-skills doctor' to inspect).`);
4943
+ }
4944
+ }
4945
+ if (destExists) {
4946
+ const existingEntries = await fsp5.readdir(destRoot);
4947
+ for (const name of existingEntries) {
4948
+ if (name.startsWith(".") || desiredNames.has(name))
4949
+ continue;
4950
+ const full = nodePath5.join(destRoot, name);
4951
+ const lst = await fsp5.lstat(full).catch(() => null);
4952
+ if (!lst)
4953
+ continue;
4954
+ if (lst.isSymbolicLink()) {
4955
+ const rawLink = await fsp5.readlink(full);
4956
+ const resolvedLink = nodePath5.resolve(nodePath5.dirname(full), rawLink);
4957
+ const realResolvedLink = await fsp5.realpath(resolvedLink).catch(() => resolvedLink);
4958
+ if (isManagedStoreLink(resolvedLink, realResolvedLink)) {
4959
+ if (resolvedLink.includes(`${nodePath5.sep}_bundled${nodePath5.sep}`)) {
4960
+ continue;
4961
+ }
4962
+ wouldRemove.push(name);
4963
+ }
4964
+ } else if (lst.isDirectory() && await isManagedCopyDir(full)) {
4965
+ const marker = await fsp5.readFile(nodePath5.join(full, ".ntn-managed-copy.json"), "utf8").then((raw) => JSON.parse(raw)).catch(() => null);
4966
+ if (marker?.bundled === true)
4967
+ continue;
4968
+ wouldRemove.push(name);
4969
+ }
4970
+ }
4971
+ }
4972
+ const routerName = args.routerSkill ?? null;
4973
+ const routerSkipped = Boolean(routerName && wouldSkipConflicts.some((c) => c.name === routerName));
4974
+ return {
4975
+ dest: destRoot,
4976
+ mode: args.target.mode,
4977
+ wouldWrite: wouldWrite.sort(),
4978
+ wouldRemove: wouldRemove.sort(),
4979
+ wouldSkipConflicts,
4980
+ routerIncluded: Boolean(routerName && !routerSkipped),
4981
+ routerSkill: routerName && !routerSkipped ? routerName : null,
4982
+ totalSkills: publishableCount,
4983
+ warnings
4984
+ };
4985
+ },
4986
+ catch: (err) => err instanceof ConflictError ? err : new StoreError({ path: destRoot, message: String(err) })
4987
+ });
4988
+ });
4989
+ }
4698
4990
  function publishExportTarget(args) {
4699
4991
  return Effect4.gen(function* () {
4700
4992
  const onConflict = args.onConflict ?? "error";
@@ -4704,21 +4996,22 @@ function publishExportTarget(args) {
4704
4996
  const seenNames = new Map;
4705
4997
  const duplicateNames = new Map;
4706
4998
  for (const entry of args.selectedEntries) {
4707
- const prev = seenNames.get(entry.name);
4999
+ const exportName = normalizeSkillSlug(entry.name) || entry.name.trim();
5000
+ const prev = seenNames.get(exportName);
4708
5001
  if (prev && prev.skillId !== entry.skillId) {
4709
5002
  if (onConflict === "error") {
4710
5003
  return yield* Effect4.fail(new ConflictError({
4711
5004
  kind: "duplicate_name",
4712
- message: `Duplicate active skill name '${entry.name}' in Notion (${prev.skillId} vs ${entry.skillId}); refusing export.`,
5005
+ message: `Duplicate active skill name '${exportName}' in Notion (${prev.skillId} vs ${entry.skillId}); refusing export.`,
4713
5006
  details: [prev.skillId, entry.skillId]
4714
5007
  }));
4715
5008
  }
4716
- const ids = duplicateNames.get(entry.name) ?? new Set([prev.skillId]);
5009
+ const ids = duplicateNames.get(exportName) ?? new Set([prev.skillId]);
4717
5010
  ids.add(entry.skillId);
4718
- duplicateNames.set(entry.name, ids);
5011
+ duplicateNames.set(exportName, ids);
4719
5012
  continue;
4720
5013
  }
4721
- seenNames.set(entry.name, entry);
5014
+ seenNames.set(exportName, entry);
4722
5015
  }
4723
5016
  for (const [dupName, ids] of duplicateNames) {
4724
5017
  seenNames.delete(dupName);
@@ -4911,7 +5204,7 @@ async function copyDirectoryContentsWritable(srcDir, dstDir) {
4911
5204
  }
4912
5205
  }
4913
5206
  async function upsertByNameSymlink(byNameRoot, skillName, targetDir) {
4914
- const trimmed = skillName.trim();
5207
+ const trimmed = normalizeSkillSlug(skillName) || skillName.trim();
4915
5208
  if (!trimmed || trimmed === "." || trimmed === ".." || trimmed.startsWith(".") || nodePath5.basename(trimmed) !== trimmed) {
4916
5209
  return;
4917
5210
  }
@@ -4958,7 +5251,7 @@ async function reconcileByNameDirectory(args) {
4958
5251
  for (const e of ordered) {
4959
5252
  if (!e.enabled || !e.materializedPath)
4960
5253
  continue;
4961
- const trimmed = e.name.trim();
5254
+ const trimmed = normalizeSkillSlug(e.name) || e.name.trim();
4962
5255
  if (!trimmed || trimmed === "." || trimmed === ".." || trimmed.startsWith(".") || nodePath5.basename(trimmed) !== trimmed || desired.has(trimmed)) {
4963
5256
  continue;
4964
5257
  }
@@ -5007,7 +5300,8 @@ function syncCommand(options = {}) {
5007
5300
  const upstream = yield* UpstreamPort;
5008
5301
  const { config, libraryId, binding } = yield* loadResolvedLibrary(options.libraryId);
5009
5302
  const dedupeWindowMs = options.dedupeWindowMs ?? 5000;
5010
- return yield* store.withExclusiveLock(`sync-${libraryId.slice(0, 8)}`, Effect4.gen(function* () {
5303
+ const isDryRun = Boolean(options.dryRun);
5304
+ const runSync = Effect4.gen(function* () {
5011
5305
  const currentCatalog = yield* store.readCatalog();
5012
5306
  const prevLib = currentCatalog.libraries[libraryId] ?? {
5013
5307
  watermark: null,
@@ -5020,7 +5314,7 @@ function syncCommand(options = {}) {
5020
5314
  };
5021
5315
  const resolvedExports = yield* resolveConfiguredExports(config, store.paths.configPath);
5022
5316
  const allExportTargets = resolvedExports.targets.map((r) => r.target);
5023
- if (!options.full && prevLib.lastSyncedAt && dedupeWindowMs > 0) {
5317
+ if (!isDryRun && !options.full && prevLib.lastSyncedAt && dedupeWindowMs > 0) {
5024
5318
  const age = Date.now() - Date.parse(prevLib.lastSyncedAt);
5025
5319
  if (age >= 0 && age < dedupeWindowMs) {
5026
5320
  const libEntries = currentCatalog.entries.filter((e) => e.libraryId === libraryId);
@@ -5205,7 +5499,7 @@ function syncCommand(options = {}) {
5205
5499
  process.stderr.write(`[ntn-skills] ${msg}
5206
5500
  `);
5207
5501
  };
5208
- const saveIntermediateCheckpoint = (mainCacheSnapshot, fileCacheSnapshot) => store.writeCatalog({
5502
+ const saveIntermediateCheckpoint = (mainCacheSnapshot, fileCacheSnapshot) => isDryRun ? Effect4.void : store.writeCatalog({
5209
5503
  version: 2,
5210
5504
  updatedAt: currentCatalog.updatedAt || syncStartIso,
5211
5505
  libraries: {
@@ -5270,7 +5564,9 @@ function syncCommand(options = {}) {
5270
5564
  const mutableMainCache = {
5271
5565
  ...workingLibState.mainHashCache
5272
5566
  };
5273
- const mutableFileBodyCache = { ...workingLibState.fileBodyCache };
5567
+ const mutableFileBodyCache = {
5568
+ ...workingLibState.fileBodyCache
5569
+ };
5274
5570
  let mainCacheEvicted = false;
5275
5571
  for (const staleId of staleMainCacheIds) {
5276
5572
  if (staleId in mutableMainCache) {
@@ -5399,12 +5695,13 @@ function syncCommand(options = {}) {
5399
5695
  const prevEntryById = new Map(currentCatalog.entries.filter((e) => e.libraryId === libraryId).map((e) => [e.skillId, e]));
5400
5696
  const materializedPaths = new Map;
5401
5697
  let materializedCount = 0;
5698
+ const plannedMaterializations = [];
5402
5699
  const closureList = [...closureIds];
5403
5700
  const coldCandidates = closureList.filter((sid) => {
5404
5701
  const prev = prevEntryById.get(sid);
5405
5702
  return !prev?.materializedPath || prev.effectiveRev !== getEffectiveRevFor(sid);
5406
5703
  });
5407
- if (coldCandidates.length >= 5) {
5704
+ if (!isDryRun && coldCandidates.length >= 5) {
5408
5705
  emitSyncProgress(`Materializing ${coldCandidates.length} updated skill snapshot(s)...`);
5409
5706
  }
5410
5707
  let finishedColdMat = 0;
@@ -5436,6 +5733,26 @@ function syncCommand(options = {}) {
5436
5733
  revMemo.delete(sid);
5437
5734
  }
5438
5735
  const rev = getEffectiveRevFor(sid);
5736
+ const reqPathsForMat = {};
5737
+ for (const reqId of sk.requiresIds) {
5738
+ const reqSkill = effectiveById.get(reqId);
5739
+ if (!reqSkill)
5740
+ continue;
5741
+ const reqSlug = normalizeSkillSlug(reqSkill.name) || reqSkill.name.trim();
5742
+ reqPathsForMat[reqSlug] = store.getStoreSkillDir(libraryId, reqId, getEffectiveRevFor(reqId));
5743
+ }
5744
+ if (isDryRun) {
5745
+ const alreadyReady = yield* store.hasVerifiedStorePackage(libraryId, sid, rev);
5746
+ const expectedDir = store.getStoreSkillDir(libraryId, sid, rev);
5747
+ if (alreadyReady) {
5748
+ const real = yield* Effect4.tryPromise(() => fsp5.realpath(expectedDir).catch(() => expectedDir)).pipe(Effect4.catch(() => Effect4.succeed(expectedDir)));
5749
+ materializedPaths.set(sid, real);
5750
+ } else {
5751
+ plannedMaterializations.push(sk.name);
5752
+ materializedPaths.set(sid, expectedDir);
5753
+ }
5754
+ return;
5755
+ }
5439
5756
  const matRes = yield* materializeOneSkill({
5440
5757
  libraryId,
5441
5758
  libState: workingLibState,
@@ -5445,7 +5762,8 @@ function syncCommand(options = {}) {
5445
5762
  pinnedCommit: src.pinnedCommit || (resolvedCommits.get(src.id) ?? "")
5446
5763
  } : null,
5447
5764
  overlayFiles: filesBySkillId.get(sid) ?? [],
5448
- effectiveRev: rev
5765
+ effectiveRev: rev,
5766
+ requiresPaths: reqPathsForMat
5449
5767
  }).pipe(Effect4.map((ok) => ({ ok: true, value: ok })), Effect4.catchTag("UpstreamError", (err) => Effect4.succeed({ ok: false, err })));
5450
5768
  if (!matRes.ok) {
5451
5769
  const warnMsg = `Skill '${sk.name}' skipped materialization due to upstream fetch error: ${matRes.err.message}`;
@@ -5552,6 +5870,7 @@ function syncCommand(options = {}) {
5552
5870
  }
5553
5871
  const manifestExports = [];
5554
5872
  const preparedExports = [];
5873
+ const cliCommand = yield* Effect4.promise(() => resolveLocalCliCommandHint(store.paths.homeDir));
5555
5874
  for (const { resolved, selection } of exportSelections) {
5556
5875
  const exp = resolved.target;
5557
5876
  const selectedEntries = selection.selected.map((s) => exportEntryMapById.get(s.id)).filter((e) => Boolean(e?.materializedPath));
@@ -5564,10 +5883,11 @@ function syncCommand(options = {}) {
5564
5883
  routerName,
5565
5884
  discoverableEntries,
5566
5885
  allEntriesById: exportEntryMapById,
5567
- byNameRoot: store.paths.byNameRoot
5886
+ byNameRoot: store.paths.byNameRoot,
5887
+ cliCommand
5568
5888
  });
5569
5889
  const routerSkillId = `_router-${routerName}`;
5570
- const routerStoreDir = yield* store.publishImmutablePackage({
5890
+ const routerStoreDir = isDryRun ? store.getStoreSkillDir(libraryId, routerSkillId, synth.effectiveRev) : yield* store.publishImmutablePackage({
5571
5891
  libraryId,
5572
5892
  skillId: routerSkillId,
5573
5893
  effectiveRev: synth.effectiveRev,
@@ -5601,7 +5921,11 @@ function syncCommand(options = {}) {
5601
5921
  };
5602
5922
  }
5603
5923
  const finalExportEntries = routerEntry ? [...selectedEntries, routerEntry] : selectedEntries;
5604
- preparedExports.push({ target: exp, finalExportEntries });
5924
+ preparedExports.push({
5925
+ target: exp,
5926
+ finalExportEntries,
5927
+ routerSkill: routerEntry ? routerName : null
5928
+ });
5605
5929
  manifestExports.push({
5606
5930
  dir: exp.dir,
5607
5931
  mode: exp.mode,
@@ -5636,13 +5960,6 @@ function syncCommand(options = {}) {
5636
5960
  sourcePath: e.sourcePath
5637
5961
  }))
5638
5962
  };
5639
- yield* Effect4.tryPromise({
5640
- try: () => atomicWriteJson(store.paths.manifestPath, manifestDoc),
5641
- catch: (err) => new StoreError({
5642
- path: store.paths.manifestPath,
5643
- message: `Failed writing manifest.json: ${String(err)}`
5644
- })
5645
- });
5646
5963
  const otherLibEntries = currentCatalog.entries.filter((e) => e.libraryId !== libraryId);
5647
5964
  for (const e of otherLibEntries) {
5648
5965
  if (e.materializedPath)
@@ -5657,21 +5974,52 @@ function syncCommand(options = {}) {
5657
5974
  },
5658
5975
  entries: [...otherLibEntries, ...nextLibEntries]
5659
5976
  };
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
- });
5977
+ if (!isDryRun) {
5978
+ yield* Effect4.tryPromise({
5979
+ try: () => atomicWriteJson(store.paths.manifestPath, manifestDoc),
5980
+ catch: (err) => new StoreError({
5981
+ path: store.paths.manifestPath,
5982
+ message: `Failed writing manifest.json: ${String(err)}`
5983
+ })
5984
+ });
5985
+ yield* store.writeCatalog(nextCatalog);
5986
+ yield* Effect4.tryPromise({
5987
+ try: () => reconcileByNameDirectory({
5988
+ byNameRoot: store.paths.byNameRoot,
5989
+ entries: nextCatalog.entries,
5990
+ defaultLibraryId: normalizeUuid(config.default_library)
5991
+ }),
5992
+ catch: (err) => new StoreError({
5993
+ path: store.paths.byNameRoot,
5994
+ message: `Failed reconciling by-name links: ${String(err)}`
5995
+ })
5996
+ });
5997
+ }
5672
5998
  let exportedCount = 0;
5673
5999
  let allExportsScanned = true;
5674
- for (const { target: exp, finalExportEntries } of preparedExports) {
6000
+ const plannedExports = [];
6001
+ for (const { target: exp, finalExportEntries, routerSkill } of preparedExports) {
6002
+ if (isDryRun) {
6003
+ const planRes = yield* planExportTarget({
6004
+ target: exp,
6005
+ selectedEntries: finalExportEntries,
6006
+ storeRoot: store.paths.storeRoot,
6007
+ onConflict: "skip",
6008
+ routerSkill
6009
+ }).pipe(Effect4.result);
6010
+ if (planRes._tag === "Failure") {
6011
+ allExportsScanned = false;
6012
+ const err = planRes.failure;
6013
+ const errMsg = err && typeof err === "object" && "message" in err ? String(err.message) : String(err);
6014
+ warnings.push(`Export target '${exp.dir}' failed and was isolated: ${errMsg}`);
6015
+ continue;
6016
+ }
6017
+ const plan = planRes.success;
6018
+ plannedExports.push(plan);
6019
+ if (plan.warnings.length > 0)
6020
+ warnings.push(...plan.warnings);
6021
+ continue;
6022
+ }
5675
6023
  const pubResult = yield* publishExportTarget({
5676
6024
  target: exp,
5677
6025
  selectedEntries: finalExportEntries,
@@ -5711,7 +6059,12 @@ function syncCommand(options = {}) {
5711
6059
  });
5712
6060
  }
5713
6061
  }
5714
- const pruned = allExportsScanned ? yield* store.pruneStore({ protectedDirs, activeRepoCommits }) : [];
6062
+ const pruned = allExportsScanned ? yield* store.pruneStore({
6063
+ protectedDirs,
6064
+ activeRepoCommits,
6065
+ ...options.nowMs !== undefined ? { nowMs: options.nowMs } : {},
6066
+ dryRun: isDryRun
6067
+ }) : [];
5715
6068
  if (!allExportsScanned) {
5716
6069
  warnings.push("Skipped store GC pruning during this sync because one or more export targets failed to scan.");
5717
6070
  }
@@ -5746,6 +6099,7 @@ function syncCommand(options = {}) {
5746
6099
  })));
5747
6100
  return {
5748
6101
  libraryId,
6102
+ ...isDryRun ? { dryRun: true } : {},
5749
6103
  coalesced: false,
5750
6104
  full: isFull,
5751
6105
  catalogCount: nextLibEntries.length,
@@ -5754,9 +6108,14 @@ function syncCommand(options = {}) {
5754
6108
  discoverable: manifestDoc.counts.discoverable,
5755
6109
  manual: manifestDoc.counts.manual
5756
6110
  },
5757
- materializedCount,
5758
- exportedCount,
5759
- prunedCount: pruned.length,
6111
+ materializedCount: isDryRun ? 0 : materializedCount,
6112
+ exportedCount: isDryRun ? 0 : exportedCount,
6113
+ prunedCount: isDryRun ? 0 : pruned.length,
6114
+ ...isDryRun ? {
6115
+ plannedMaterializations: [...new Set(plannedMaterializations)].sort(),
6116
+ plannedPrunes: pruned,
6117
+ plannedExports
6118
+ } : {},
5760
6119
  pulled: {
5761
6120
  added: addedNames.sort(),
5762
6121
  updated: updatedNames.sort(),
@@ -5765,7 +6124,8 @@ function syncCommand(options = {}) {
5765
6124
  localPending,
5766
6125
  warnings
5767
6126
  };
5768
- }));
6127
+ });
6128
+ return isDryRun ? yield* runSync : yield* store.withExclusiveLock(`sync-${libraryId.slice(0, 8)}`, runSync);
5769
6129
  });
5770
6130
  }
5771
6131
  var SEARCH_STOP_WORDS = new Set([
@@ -6042,6 +6402,17 @@ function loadSkillCommand(args) {
6042
6402
  requiresRevs: []
6043
6403
  });
6044
6404
  }
6405
+ const reqPathsForLoad = {};
6406
+ for (const reqId of sk.requiresIds) {
6407
+ const reqSkill = effectiveById.get(reqId);
6408
+ if (!reqSkill)
6409
+ continue;
6410
+ const reqSlug = normalizeSkillSlug(reqSkill.name) || reqSkill.name.trim();
6411
+ const knownDir = matDirs.get(reqId);
6412
+ if (knownDir) {
6413
+ reqPathsForLoad[reqSlug] = knownDir;
6414
+ }
6415
+ }
6045
6416
  const mat = yield* materializeOneSkill({
6046
6417
  libraryId,
6047
6418
  libState: workingLib,
@@ -6049,7 +6420,8 @@ function loadSkillCommand(args) {
6049
6420
  source: src,
6050
6421
  overlayFiles: filesBySkill.get(cid) ?? [],
6051
6422
  effectiveRev: targetRev,
6052
- forceRefreshBodies: Boolean(args.refresh)
6423
+ forceRefreshBodies: Boolean(args.refresh),
6424
+ requiresPaths: reqPathsForLoad
6053
6425
  });
6054
6426
  workingLib = mat.updatedLibState;
6055
6427
  matDirs.set(cid, mat.storeDir);
@@ -6226,12 +6598,34 @@ function exportCommand(args) {
6226
6598
  }));
6227
6599
  }
6228
6600
  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);
6601
+ const isDryRun = Boolean(args.dryRun);
6229
6602
  if (!args.toDir && !args.specPath) {
6230
6603
  if (hasFilterFlags) {
6231
6604
  return yield* Effect4.fail(new ConfigError({
6232
6605
  message: "Export filter flags (--skills, --exclude, --with-requires, --no-requires, --no-router, --profile, --scene) require --to <dir> or --spec <file>."
6233
6606
  }));
6234
6607
  }
6608
+ if (isDryRun) {
6609
+ const syncRep = yield* syncCommand({ libraryId, dedupeWindowMs: 0, dryRun: true });
6610
+ const targetResults = (syncRep.plannedExports ?? []).map((pe) => ({
6611
+ dir: pe.dest,
6612
+ mode: pe.mode,
6613
+ exportedDirs: [],
6614
+ exportedCount: pe.totalSkills,
6615
+ routerSkill: pe.routerSkill,
6616
+ routerIncluded: pe.routerIncluded,
6617
+ wouldWrite: pe.wouldWrite,
6618
+ wouldRemove: pe.wouldRemove,
6619
+ wouldSkipConflicts: pe.wouldSkipConflicts,
6620
+ warnings: pe.warnings
6621
+ }));
6622
+ return {
6623
+ dryRun: true,
6624
+ exportedDirs: [],
6625
+ targets: targetResults,
6626
+ warnings: syncRep.warnings
6627
+ };
6628
+ }
6235
6629
  const syncRep = yield* syncCommand({ libraryId, dedupeWindowMs: 0 });
6236
6630
  const resolvedExports = yield* resolveConfiguredExports(config, store.paths.configPath);
6237
6631
  const allExported = [];
@@ -6311,18 +6705,124 @@ function exportCommand(args) {
6311
6705
  }
6312
6706
  ];
6313
6707
  }
6708
+ const notion = yield* NotionPort;
6709
+ const { binding } = yield* loadResolvedLibrary(args.libraryId);
6314
6710
  const catalog = yield* store.readCatalog();
6711
+ let freshCat = catalog;
6712
+ let freshLib;
6315
6713
  if (!catalog.libraries[libraryId]) {
6316
- yield* syncCommand({ libraryId, dedupeWindowMs: 0 });
6714
+ if (isDryRun) {
6715
+ const delta = yield* notion.queryDelta({
6716
+ libraryId,
6717
+ binding,
6718
+ watermarkIso: null
6719
+ });
6720
+ const sources = {};
6721
+ for (const s of delta.sources)
6722
+ sources[s.id] = s;
6723
+ const skills = {};
6724
+ for (const sk of delta.skills)
6725
+ skills[sk.id] = sk;
6726
+ const files = {};
6727
+ for (const f of delta.files)
6728
+ files[f.id] = f;
6729
+ freshLib = {
6730
+ watermark: null,
6731
+ lastSyncedAt: null,
6732
+ sources,
6733
+ skills,
6734
+ files,
6735
+ mainHashCache: {},
6736
+ fileBodyCache: {}
6737
+ };
6738
+ } else {
6739
+ yield* syncCommand({ libraryId, dedupeWindowMs: 0 });
6740
+ freshCat = yield* store.readCatalog();
6741
+ freshLib = freshCat.libraries[libraryId];
6742
+ }
6743
+ } else {
6744
+ freshLib = freshCat.libraries[libraryId];
6317
6745
  }
6318
- let freshCat = yield* store.readCatalog();
6319
- const freshLib = freshCat.libraries[libraryId];
6320
6746
  const sourcesById = new Map(Object.entries(freshLib.sources));
6321
6747
  const effective = filterEffectiveSkills(Object.values(freshLib.skills), sourcesById);
6322
6748
  const effectiveById = new Map(effective.map((s) => [s.id, s]));
6323
6749
  const catalogSkills = filterCatalogSkills(effective, config.profiles);
6750
+ const filesBySkillId = new Map;
6751
+ for (const f of Object.values(freshLib.files)) {
6752
+ const arr = filesBySkillId.get(f.skillId) ?? [];
6753
+ arr.push(f);
6754
+ filesBySkillId.set(f.skillId, arr);
6755
+ }
6324
6756
  const entryCacheById = new Map(freshCat.entries.filter((e) => e.libraryId === libraryId).map((e) => [e.skillId, e]));
6757
+ const buildDryRunPlannedEntry = (sk) => {
6758
+ const cached = entryCacheById.get(sk.id);
6759
+ if (cached) {
6760
+ return {
6761
+ ...cached,
6762
+ materializedPath: cached.materializedPath ?? store.getStoreSkillDir(libraryId, sk.id, cached.effectiveRev)
6763
+ };
6764
+ }
6765
+ const src = sk.originSourceId ? sourcesById.get(sk.originSourceId) ?? null : null;
6766
+ const overlayFiles = normalizeOverlayFiles(filesBySkillId.get(sk.id) ?? []);
6767
+ const subDigest = src ? extractSubtreeDigestFromRevision(sk.revision) : null;
6768
+ const commitId = src ? src.pinnedCommit || `ref:${src.ref}` : null;
6769
+ const baseIdentity = src ? subDigest ? `sub:${subDigest}` : commitId : null;
6770
+ const mainIdentity = !src || sk.customMain ? freshLib.mainHashCache[sk.id]?.rawBodySha256 ?? sk.lastEditedTime : `upstream:${baseIdentity}:${sk.sourcePath}`;
6771
+ const effectiveRev = computeEffectiveRev({
6772
+ originPinnedCommit: baseIdentity,
6773
+ sourcePath: sk.sourcePath,
6774
+ customMain: sk.customMain,
6775
+ name: sk.name,
6776
+ description: sk.description,
6777
+ mainContentIdentity: mainIdentity,
6778
+ overlays: overlayFiles.map((ov) => ({
6779
+ path: ov.path,
6780
+ status: ov.status === "delete" ? "delete" : "override",
6781
+ contentIdentity: ov.sha256 || ov.externalUrl || ov.lastEditedTime,
6782
+ executable: ov.executable
6783
+ })),
6784
+ requiresRevs: []
6785
+ });
6786
+ return {
6787
+ libraryId,
6788
+ skillId: sk.id,
6789
+ name: sk.name,
6790
+ description: sk.description,
6791
+ enabled: sk.enabled,
6792
+ visibility: sk.visibility,
6793
+ kind: sk.kind,
6794
+ profiles: [...sk.profiles],
6795
+ scenes: [...sk.scenes],
6796
+ requiresIds: [...sk.requiresIds],
6797
+ originSourceId: src?.id ?? null,
6798
+ originRepoUrl: src?.repoUrl ?? null,
6799
+ originRef: src?.ref ?? null,
6800
+ originPinnedCommit: commitId,
6801
+ sourcePath: sk.sourcePath,
6802
+ customMain: sk.customMain,
6803
+ revision: sk.revision,
6804
+ previewHash: sk.previewHash,
6805
+ effectiveRev,
6806
+ materializedPath: store.getStoreSkillDir(libraryId, sk.id, effectiveRev),
6807
+ warnings: [],
6808
+ overlays: overlayFiles.map((ov) => ({
6809
+ id: ov.id,
6810
+ path: ov.path,
6811
+ status: ov.status === "delete" ? "delete" : "override",
6812
+ externalUrl: ov.externalUrl,
6813
+ sha256: ov.sha256,
6814
+ executable: ov.executable,
6815
+ lastEditedTime: ov.lastEditedTime
6816
+ })),
6817
+ lastEditedTime: sk.lastEditedTime
6818
+ };
6819
+ };
6325
6820
  const ensureMaterializedEntry = (sk) => Effect4.gen(function* () {
6821
+ if (isDryRun) {
6822
+ const planned = buildDryRunPlannedEntry(sk);
6823
+ entryCacheById.set(sk.id, planned);
6824
+ return planned;
6825
+ }
6326
6826
  const cached = entryCacheById.get(sk.id);
6327
6827
  if (cached?.materializedPath && !cached.originPinnedCommit?.startsWith("ref:")) {
6328
6828
  const verified = yield* store.hasVerifiedStorePackage(libraryId, sk.id, cached.effectiveRev);
@@ -6377,18 +6877,20 @@ function exportCommand(args) {
6377
6877
  selectedEntries.push(yield* ensureMaterializedEntry(sk));
6378
6878
  }
6379
6879
  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()));
6880
+ const discoverableEntries = selection.discoverable.map((s) => entryCacheById.get(s.id) ?? (isDryRun ? buildDryRunPlannedEntry(s) : undefined)).filter((e) => Boolean(e) && !directNameSet.has(e.name.toLowerCase()));
6381
6881
  let routerEntry = null;
6382
6882
  const routerName = (target.router?.name ?? "skill-catalog").trim() || "skill-catalog";
6383
6883
  if (selection.resolvedRouterEnabled && discoverableEntries.length > 0 && !directNameSet.has(routerName.toLowerCase())) {
6884
+ const cliCommand = yield* Effect4.promise(() => resolveLocalCliCommandHint(store.paths.homeDir));
6384
6885
  const synth = synthesizeSkillCatalogPackage({
6385
6886
  routerName,
6386
6887
  discoverableEntries,
6387
6888
  allEntriesById: entryCacheById,
6388
- byNameRoot: store.paths.byNameRoot
6889
+ byNameRoot: store.paths.byNameRoot,
6890
+ cliCommand
6389
6891
  });
6390
6892
  const routerSkillId = `_router-${routerName}`;
6391
- const routerStoreDir = yield* store.publishImmutablePackage({
6893
+ const routerStoreDir = isDryRun ? store.getStoreSkillDir(libraryId, routerSkillId, synth.effectiveRev) : yield* store.publishImmutablePackage({
6392
6894
  libraryId,
6393
6895
  skillId: routerSkillId,
6394
6896
  effectiveRev: synth.effectiveRev,
@@ -6421,6 +6923,32 @@ function exportCommand(args) {
6421
6923
  };
6422
6924
  }
6423
6925
  const finalExportEntries = routerEntry ? [...selectedEntries, routerEntry] : selectedEntries;
6926
+ if (isDryRun) {
6927
+ const plan = yield* planExportTarget({
6928
+ target,
6929
+ selectedEntries: finalExportEntries,
6930
+ storeRoot: store.paths.storeRoot,
6931
+ ...args.onConflict ? { onConflict: args.onConflict } : {},
6932
+ routerSkill: routerEntry ? routerName : null
6933
+ });
6934
+ if (plan.warnings.length > 0) {
6935
+ targetWarnings.push(...plan.warnings);
6936
+ }
6937
+ allWarnings.push(...targetWarnings);
6938
+ targetResults.push({
6939
+ dir: plan.dest,
6940
+ mode: plan.mode,
6941
+ exportedDirs: [],
6942
+ exportedCount: plan.totalSkills,
6943
+ routerSkill: plan.routerSkill,
6944
+ routerIncluded: plan.routerIncluded,
6945
+ wouldWrite: plan.wouldWrite,
6946
+ wouldRemove: plan.wouldRemove,
6947
+ wouldSkipConflicts: plan.wouldSkipConflicts,
6948
+ warnings: targetWarnings
6949
+ });
6950
+ continue;
6951
+ }
6424
6952
  const pub = yield* publishExportTarget({
6425
6953
  target,
6426
6954
  selectedEntries: finalExportEntries,
@@ -6436,11 +6964,14 @@ function exportCommand(args) {
6436
6964
  dir: resolveHomePath(target.dir),
6437
6965
  mode: target.mode,
6438
6966
  exportedDirs: pub.exportedDirs,
6967
+ exportedCount: pub.exportedDirs.length,
6439
6968
  routerSkill: routerEntry ? routerName : null,
6969
+ routerIncluded: Boolean(routerEntry),
6440
6970
  warnings: targetWarnings
6441
6971
  });
6442
6972
  }
6443
6973
  return {
6974
+ ...isDryRun ? { dryRun: true } : {},
6444
6975
  exportedDirs: allExportedDirs,
6445
6976
  targets: targetResults,
6446
6977
  warnings: allWarnings
@@ -6497,59 +7028,192 @@ function statusCommand(args) {
6497
7028
  }
6498
7029
  // packages/core/src/edit/edit-engine.ts
6499
7030
  import { randomUUID as randomUUID5 } from "node:crypto";
7031
+ import * as fsp7 from "node:fs/promises";
7032
+ import * as nodePath7 from "node:path";
7033
+ import { Effect as Effect6, Option, Schema as Schema4 } from "effect";
7034
+
7035
+ // packages/core/src/edit/skill-dir-scan.ts
6500
7036
  import * as fsp6 from "node:fs/promises";
6501
7037
  import * as nodePath6 from "node:path";
6502
- import { Effect as Effect5, Option, Schema as Schema4 } from "effect";
6503
- var WORK_META_FILE = ".ntn-skill.json";
6504
- var IGNORED_WORKDIR_NAMES = new Set([
6505
- WORK_META_FILE,
7038
+ import { Effect as Effect5 } from "effect";
7039
+ var IGNORED_SKILL_DIR_NAMES = new Set([
7040
+ ".ntn-skill.json",
7041
+ ".ntn-managed-copy.json",
7042
+ ".ntn-manifest.json",
6506
7043
  ".DS_Store",
6507
7044
  ".git",
6508
7045
  "node_modules",
6509
7046
  ".cache",
6510
7047
  ".state",
6511
7048
  ".venv",
6512
- "__pycache__",
6513
- ".env",
6514
- ".env.local"
7049
+ "__pycache__"
6515
7050
  ]);
6516
- async function scanWorkdirFiles(workdir, rel = "") {
6517
- const dir = rel ? nodePath6.join(workdir, rel) : workdir;
6518
- const entries = await fsp6.readdir(dir, { withFileTypes: true });
6519
- const map = new Map;
6520
- for (const e of entries) {
6521
- if (IGNORED_WORKDIR_NAMES.has(e.name))
6522
- continue;
6523
- const childRel = rel ? `${rel}/${e.name}` : e.name;
6524
- const full = nodePath6.join(workdir, childRel);
6525
- if (e.isDirectory()) {
6526
- for (const [k, v] of await scanWorkdirFiles(workdir, childRel))
6527
- map.set(k, v);
6528
- } else if (e.isFile()) {
6529
- const [bytes, st] = await Promise.all([fsp6.readFile(full), fsp6.stat(full)]);
6530
- const executable = (st.mode & 73) !== 0 || childRel.toLowerCase().endsWith(".sh");
6531
- map.set(childRel, { path: childRel, bytes: new Uint8Array(bytes), executable });
7051
+ var ENV_TEMPLATE_ALLOWLIST = new Set([
7052
+ ".env.example",
7053
+ ".env.sample",
7054
+ ".env.template",
7055
+ ".env.dist"
7056
+ ]);
7057
+ var PRIVATE_KEY_EXACT_NAMES = new Set(["id_rsa", "id_ed25519", "id_ecdsa"]);
7058
+ var PRIVATE_KEY_EXTENSIONS = [".pem", ".key", ".p12", ".pfx"];
7059
+ function classifySensitiveFile(relPath, bytes) {
7060
+ const normalized = relPath.replace(/\\/g, "/");
7061
+ const base = nodePath6.posix.basename(normalized).toLowerCase();
7062
+ if (base === ".env" || base.startsWith(".env.") && !ENV_TEMPLATE_ALLOWLIST.has(base)) {
7063
+ return "environment secrets file";
7064
+ }
7065
+ if (PRIVATE_KEY_EXACT_NAMES.has(base) || PRIVATE_KEY_EXTENSIONS.some((ext) => base.endsWith(ext))) {
7066
+ return "private key or certificate";
7067
+ }
7068
+ if (base.endsWith(".json") && (base.includes("credentials") || base.includes("secret")) || base === "token.json" || base === "secrets.yaml" || base === "secrets.yml" || base === ".netrc") {
7069
+ return "credential or secret file";
7070
+ }
7071
+ if (base === ".npmrc") {
7072
+ if (!bytes) {
7073
+ return "npm credentials file";
7074
+ }
7075
+ const text = new TextDecoder("utf-8", { fatal: false }).decode(bytes);
7076
+ if (/_authtoken\s*=|\/\/.*:_authtoken/i.test(text)) {
7077
+ return "npm credentials file (_authToken)";
6532
7078
  }
6533
7079
  }
6534
- return map;
7080
+ return null;
6535
7081
  }
6536
- var UPSTREAM_SKILL_CONCURRENCY = 3;
6537
- function normalizeSourcePathKey(raw) {
6538
- const cleaned = raw.trim().replace(/^\.\/+|^\/+|\/+$/g, "");
6539
- return cleaned === "" ? "." : cleaned;
7082
+ function formatBlockedFilesMessage(rootDir, blockedFiles) {
7083
+ const details = blockedFiles.map((b) => `${b.path} (${b.reason})`).join(", ");
7084
+ return `Refusing to upload skill directory '${rootDir}': blocked sensitive or unsafe file(s) detected: ${details}. Remove or relocate these files before uploading.`;
7085
+ }
7086
+ function assertNoBlockedSkillFiles(scan) {
7087
+ if (scan.blockedFiles.length === 0) {
7088
+ return Effect5.void;
7089
+ }
7090
+ return Effect5.fail(new ConflictError({
7091
+ kind: "sensitive_files",
7092
+ message: formatBlockedFilesMessage(scan.rootDir, scan.blockedFiles),
7093
+ details: scan.blockedFiles.map((b) => `${b.path} (${b.reason})`)
7094
+ }));
7095
+ }
7096
+ async function scanLocalSkillDirectory(rootDir) {
7097
+ const absRoot = nodePath6.resolve(rootDir);
7098
+ const realRoot = await fsp6.realpath(absRoot);
7099
+ const realRootPrefix = `${realRoot}${nodePath6.sep}`;
7100
+ const files = new Map;
7101
+ const blockedFiles = [];
7102
+ const visitedDirs = new Set([realRoot]);
7103
+ let totalBytes = 0;
7104
+ const isInsideRoot = (candidateReal) => candidateReal === realRoot || candidateReal.startsWith(realRootPrefix);
7105
+ const walk = async (curAbsDir, relPrefix) => {
7106
+ const entries = await fsp6.readdir(curAbsDir, { withFileTypes: true });
7107
+ entries.sort((a, b) => a.name.localeCompare(b.name));
7108
+ for (const entry of entries) {
7109
+ if (IGNORED_SKILL_DIR_NAMES.has(entry.name))
7110
+ continue;
7111
+ const childRel = relPrefix ? `${relPrefix}/${entry.name}` : entry.name;
7112
+ const fullPath = nodePath6.join(curAbsDir, entry.name);
7113
+ if (entry.isSymbolicLink()) {
7114
+ const targetReal = await fsp6.realpath(fullPath).catch(() => null);
7115
+ if (!targetReal || !isInsideRoot(targetReal)) {
7116
+ blockedFiles.push({
7117
+ path: childRel,
7118
+ reason: targetReal ? "symlink escapes skill root" : "broken symlink"
7119
+ });
7120
+ continue;
7121
+ }
7122
+ const targetStat = await fsp6.stat(targetReal).catch(() => null);
7123
+ if (!targetStat) {
7124
+ blockedFiles.push({ path: childRel, reason: "broken symlink" });
7125
+ continue;
7126
+ }
7127
+ if (targetStat.isDirectory()) {
7128
+ if (visitedDirs.has(targetReal))
7129
+ continue;
7130
+ visitedDirs.add(targetReal);
7131
+ await walk(fullPath, childRel);
7132
+ continue;
7133
+ }
7134
+ if (targetStat.isFile()) {
7135
+ const baseLower = entry.name.toLowerCase();
7136
+ const quickReason = baseLower === ".npmrc" ? null : classifySensitiveFile(childRel);
7137
+ if (quickReason) {
7138
+ blockedFiles.push({ path: childRel, reason: quickReason });
7139
+ continue;
7140
+ }
7141
+ const bytes = new Uint8Array(await fsp6.readFile(targetReal));
7142
+ const contentReason = baseLower === ".npmrc" ? classifySensitiveFile(childRel, bytes) : null;
7143
+ if (contentReason) {
7144
+ blockedFiles.push({ path: childRel, reason: contentReason });
7145
+ continue;
7146
+ }
7147
+ const executable = (targetStat.mode & 73) !== 0 || childRel.toLowerCase().endsWith(".sh");
7148
+ files.set(childRel, { path: childRel, bytes, executable });
7149
+ totalBytes += bytes.byteLength;
7150
+ }
7151
+ continue;
7152
+ }
7153
+ if (entry.isDirectory()) {
7154
+ const realSub = await fsp6.realpath(fullPath).catch(() => fullPath);
7155
+ if (!isInsideRoot(realSub)) {
7156
+ blockedFiles.push({ path: childRel, reason: "directory escapes skill root" });
7157
+ continue;
7158
+ }
7159
+ if (visitedDirs.has(realSub))
7160
+ continue;
7161
+ visitedDirs.add(realSub);
7162
+ await walk(fullPath, childRel);
7163
+ } else if (entry.isFile()) {
7164
+ const baseLower = entry.name.toLowerCase();
7165
+ const quickReason = baseLower === ".npmrc" ? null : classifySensitiveFile(childRel);
7166
+ if (quickReason) {
7167
+ blockedFiles.push({ path: childRel, reason: quickReason });
7168
+ continue;
7169
+ }
7170
+ const [rawBytes, st] = await Promise.all([fsp6.readFile(fullPath), fsp6.stat(fullPath)]);
7171
+ const bytes = new Uint8Array(rawBytes);
7172
+ const contentReason = baseLower === ".npmrc" ? classifySensitiveFile(childRel, bytes) : null;
7173
+ if (contentReason) {
7174
+ blockedFiles.push({ path: childRel, reason: contentReason });
7175
+ continue;
7176
+ }
7177
+ const executable = (st.mode & 73) !== 0 || childRel.toLowerCase().endsWith(".sh");
7178
+ files.set(childRel, { path: childRel, bytes, executable });
7179
+ totalBytes += bytes.byteLength;
7180
+ }
7181
+ }
7182
+ };
7183
+ await walk(absRoot, "");
7184
+ blockedFiles.sort((a, b) => a.path.localeCompare(b.path));
7185
+ return {
7186
+ rootDir: absRoot,
7187
+ files,
7188
+ blockedFiles,
7189
+ fileCount: files.size,
7190
+ totalBytes
7191
+ };
7192
+ }
7193
+
7194
+ // packages/core/src/edit/edit-engine.ts
7195
+ var WORK_META_FILE = ".ntn-skill.json";
7196
+ async function scanWorkdirFiles(workdir) {
7197
+ const scanned = await scanLocalSkillDirectory(workdir);
7198
+ return new Map(scanned.files);
7199
+ }
7200
+ var UPSTREAM_SKILL_CONCURRENCY = 3;
7201
+ function normalizeSourcePathKey(raw) {
7202
+ const cleaned = raw.trim().replace(/^\.\/+|^\/+|\/+$/g, "");
7203
+ return cleaned === "" ? "." : cleaned;
6540
7204
  }
6541
7205
  function makeRevisionStamp(subtreeDigest) {
6542
7206
  const base = `rev-${Date.now().toString(36)}-${randomUUID5().slice(0, 6)}`;
6543
7207
  return subtreeDigest ? `${base}-sub:${subtreeDigest}` : base;
6544
7208
  }
6545
7209
  function encodeSupportingFileEffect(bytes, filePath) {
6546
- return Effect5.try({
7210
+ return Effect6.try({
6547
7211
  try: () => encodeSupportingFilePayload(bytes, filePath),
6548
7212
  catch: (e) => e instanceof StoreError ? e : new StoreError({ path: filePath, message: String(e) })
6549
7213
  });
6550
7214
  }
6551
7215
  function loadSyncedLibrary(explicitLibraryId) {
6552
- return Effect5.gen(function* () {
7216
+ return Effect6.gen(function* () {
6553
7217
  const store = yield* StorePort;
6554
7218
  const { config, libraryId, binding } = yield* loadResolvedLibrary(explicitLibraryId);
6555
7219
  yield* syncCommand({ libraryId, dedupeWindowMs: 0 });
@@ -6558,7 +7222,7 @@ function loadSyncedLibrary(explicitLibraryId) {
6558
7222
  });
6559
7223
  }
6560
7224
  function loadTableMetadataLibrary(explicitLibraryId) {
6561
- return Effect5.gen(function* () {
7225
+ return Effect6.gen(function* () {
6562
7226
  const store = yield* StorePort;
6563
7227
  const notion = yield* NotionPort;
6564
7228
  const { config, libraryId, binding } = yield* loadResolvedLibrary(explicitLibraryId);
@@ -6598,33 +7262,36 @@ function loadTableMetadataLibrary(explicitLibraryId) {
6598
7262
  }
6599
7263
  function findSkillOrFail(libState, name) {
6600
7264
  const needle = name.trim().toLowerCase();
6601
- const candidates = Object.values(libState.skills).filter((s) => s.name.toLowerCase() === needle).sort((a, b) => Number(b.enabled) - Number(a.enabled) || b.lastEditedTime.localeCompare(a.lastEditedTime));
7265
+ const needleSlug = normalizeSkillSlug(name);
7266
+ const candidates = Object.values(libState.skills).filter((s) => s.name.toLowerCase() === needle || needleSlug.length > 0 && normalizeSkillSlug(s.name) === needleSlug).sort((a, b) => Number(b.enabled) - Number(a.enabled) || b.lastEditedTime.localeCompare(a.lastEditedTime));
6602
7267
  const found = candidates[0];
6603
- return found ? Effect5.succeed(found) : Effect5.fail(new NotFoundError({ entity: "skill", target: name, message: `Skill '${name}' not found.` }));
7268
+ return found ? Effect6.succeed(found) : Effect6.fail(new NotFoundError({ entity: "skill", target: name, message: `Skill '${name}' not found.` }));
6604
7269
  }
6605
7270
  function withRetryableReadback(writeOp, verifyReadback) {
6606
- return writeOp.pipe(Effect5.catchTag("NotionApiError", (err) => Effect5.gen(function* () {
7271
+ return writeOp.pipe(Effect6.catchTag("NotionApiError", (err) => Effect6.gen(function* () {
6607
7272
  if (!err.retryable)
6608
- return yield* Effect5.fail(err);
7273
+ return yield* Effect6.fail(err);
6609
7274
  const landed = yield* verifyReadback();
6610
7275
  return landed !== null ? landed : yield* writeOp;
6611
7276
  })));
6612
7277
  }
6613
7278
  function trashPathEffect(absPath) {
6614
- return Effect5.tryPromise({
7279
+ return Effect6.tryPromise({
6615
7280
  try: () => moveToSystemTrash(absPath),
6616
7281
  catch: (e) => new StoreError({ path: absPath, message: String(e) })
6617
7282
  });
6618
7283
  }
6619
7284
  function editOrPullSkillCommand(args) {
6620
- return Effect5.gen(function* () {
7285
+ return Effect6.gen(function* () {
6621
7286
  const notion = yield* NotionPort;
6622
7287
  const store = yield* StorePort;
6623
7288
  const upstream = yield* UpstreamPort;
6624
7289
  const { libraryId, binding, catalog, libState } = yield* loadSyncedLibrary(args.libraryId);
6625
- const entry = catalog.entries.find((e) => e.libraryId === libraryId && e.name.toLowerCase() === args.name.trim().toLowerCase());
7290
+ const targetLower = args.name.trim().toLowerCase();
7291
+ const targetSlug = normalizeSkillSlug(args.name);
7292
+ const entry = catalog.entries.find((e) => e.libraryId === libraryId && (e.name.toLowerCase() === targetLower || targetSlug.length > 0 && normalizeSkillSlug(e.name) === targetSlug));
6626
7293
  if (!entry) {
6627
- return yield* Effect5.fail(new NotFoundError({
7294
+ return yield* Effect6.fail(new NotFoundError({
6628
7295
  entity: "skill",
6629
7296
  target: args.name,
6630
7297
  message: `Skill '${args.name}' not found in library ${libraryId}.`
@@ -6632,13 +7299,13 @@ function editOrPullSkillCommand(args) {
6632
7299
  }
6633
7300
  const liveSkill = yield* notion.getSkillRecord(entry.skillId);
6634
7301
  if (!liveSkill || !liveSkill.enabled) {
6635
- return yield* Effect5.fail(new NotFoundError({
7302
+ return yield* Effect6.fail(new NotFoundError({
6636
7303
  entity: "skill",
6637
7304
  target: args.name,
6638
7305
  message: `Skill '${args.name}' is disabled or deleted in Notion.`
6639
7306
  }));
6640
7307
  }
6641
- const [liveFiles, liveBody] = yield* Effect5.all([
7308
+ const [liveFiles, liveBody] = yield* Effect6.all([
6642
7309
  notion.getSkillFiles({ filesDs: binding.files_ds, skillId: liveSkill.id }),
6643
7310
  notion.readSkillBody(liveSkill.id)
6644
7311
  ]);
@@ -6696,12 +7363,12 @@ function editOrPullSkillCommand(args) {
6696
7363
  const mainBytes = new TextEncoder().encode(applyAuthoritativeFrontmatter(rawMainToUse, liveSkill.name, liveSkill.description));
6697
7364
  treeToWrite.set("SKILL.md", { path: "SKILL.md", bytes: mainBytes, executable: false });
6698
7365
  if (args.clean && !args.targetDir) {
6699
- return yield* Effect5.fail(new ConfigError({
7366
+ return yield* Effect6.fail(new ConfigError({
6700
7367
  message: "'ntn-skills pull --clean' requires an explicit target directory."
6701
7368
  }));
6702
7369
  }
6703
7370
  const safeSlug = liveSkill.name.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "skill";
6704
- const workdir = args.targetDir ? nodePath6.resolve(args.targetDir) : nodePath6.join(store.paths.workRoot, `${safeSlug}-${randomUUID5().slice(0, 8)}`);
7371
+ const workdir = args.targetDir ? nodePath7.resolve(args.targetDir) : nodePath7.join(store.paths.workRoot, `${safeSlug}-${randomUUID5().slice(0, 8)}`);
6705
7372
  const meta = {
6706
7373
  version: 2,
6707
7374
  libraryId,
@@ -6720,34 +7387,34 @@ function editOrPullSkillCommand(args) {
6720
7387
  baseFiles,
6721
7388
  createdAt: new Date().toISOString()
6722
7389
  };
6723
- const removedStaleFiles = yield* Effect5.tryPromise({
7390
+ const removedStaleFiles = yield* Effect6.tryPromise({
6724
7391
  try: async () => {
6725
7392
  let staleCount = 0;
6726
7393
  if (args.clean) {
6727
- const existingStat = await fsp6.stat(workdir).catch(() => null);
7394
+ const existingStat = await fsp7.stat(workdir).catch(() => null);
6728
7395
  if (existingStat?.isDirectory()) {
6729
7396
  const existingFiles = await scanWorkdirFiles(workdir);
6730
7397
  for (const oldRel of existingFiles.keys()) {
6731
7398
  if (!treeToWrite.has(oldRel)) {
6732
- await moveToSystemTrash(nodePath6.join(workdir, oldRel));
7399
+ await moveToSystemTrash(nodePath7.join(workdir, oldRel));
6733
7400
  staleCount++;
6734
7401
  }
6735
7402
  }
6736
- const metaFile = nodePath6.join(workdir, WORK_META_FILE);
6737
- if (await fsp6.stat(metaFile).then(() => true).catch(() => false)) {
7403
+ const metaFile = nodePath7.join(workdir, WORK_META_FILE);
7404
+ if (await fsp7.stat(metaFile).then(() => true).catch(() => false)) {
6738
7405
  await moveToSystemTrash(metaFile);
6739
7406
  }
6740
7407
  }
6741
7408
  }
6742
- await fsp6.mkdir(workdir, { recursive: true });
7409
+ await fsp7.mkdir(workdir, { recursive: true });
6743
7410
  for (const f of treeToWrite.values()) {
6744
- const dest = nodePath6.join(workdir, f.path);
6745
- await fsp6.mkdir(nodePath6.dirname(dest), { recursive: true });
6746
- await fsp6.writeFile(dest, f.bytes);
6747
- await fsp6.chmod(dest, f.executable ? 493 : 420);
7411
+ const dest = nodePath7.join(workdir, f.path);
7412
+ await fsp7.mkdir(nodePath7.dirname(dest), { recursive: true });
7413
+ await fsp7.writeFile(dest, f.bytes);
7414
+ await fsp7.chmod(dest, f.executable ? 493 : 420);
6748
7415
  }
6749
7416
  if (!args.clean) {
6750
- await atomicWriteJson(nodePath6.join(workdir, WORK_META_FILE), meta);
7417
+ await atomicWriteJson(nodePath7.join(workdir, WORK_META_FILE), meta);
6751
7418
  }
6752
7419
  return staleCount;
6753
7420
  },
@@ -6757,10 +7424,10 @@ function editOrPullSkillCommand(args) {
6757
7424
  });
6758
7425
  }
6759
7426
  function readWorkMeta(workdir) {
6760
- const abs = nodePath6.resolve(workdir);
6761
- const metaPath = nodePath6.join(abs, WORK_META_FILE);
6762
- return Effect5.tryPromise({
6763
- try: async () => Schema4.decodeUnknownSync(WorkMetaSchema)(JSON.parse(await fsp6.readFile(metaPath, "utf8"))),
7427
+ const abs = nodePath7.resolve(workdir);
7428
+ const metaPath = nodePath7.join(abs, WORK_META_FILE);
7429
+ return Effect6.tryPromise({
7430
+ try: async () => Schema4.decodeUnknownSync(WorkMetaSchema)(JSON.parse(await fsp7.readFile(metaPath, "utf8"))),
6764
7431
  catch: (err) => err?.code === "ENOENT" ? new NotFoundError({
6765
7432
  entity: "workdir",
6766
7433
  target: abs,
@@ -6825,7 +7492,7 @@ async function computeLocalDiff(workdir, meta) {
6825
7492
  return { items, currentFiles, descriptionChanged };
6826
7493
  }
6827
7494
  function inspectRemoteDrift(args) {
6828
- return Effect5.gen(function* () {
7495
+ return Effect6.gen(function* () {
6829
7496
  const notion = yield* NotionPort;
6830
7497
  const drifts = [];
6831
7498
  const liveSkill = yield* notion.getSkillRecord(args.meta.skillId);
@@ -6837,7 +7504,7 @@ function inspectRemoteDrift(args) {
6837
7504
  if (liveSkill.revision !== args.meta.baseRevision) {
6838
7505
  drifts.push(`Notion Revision changed ('${args.meta.baseRevision}' -> '${liveSkill.revision}').`);
6839
7506
  }
6840
- const [liveBody, liveFiles] = yield* Effect5.all([
7507
+ const [liveBody, liveFiles] = yield* Effect6.all([
6841
7508
  notion.readSkillBody(args.meta.skillId),
6842
7509
  notion.getSkillFiles({ filesDs: args.filesDs, skillId: args.meta.skillId })
6843
7510
  ]);
@@ -6857,7 +7524,7 @@ function inspectRemoteDrift(args) {
6857
7524
  else if (lf.sha256 && lf.sha256 !== bf.sha256) {
6858
7525
  let actualLiveSha = lf.sha256;
6859
7526
  if (!lf.externalUrl && lf.attachmentUrls.length === 0) {
6860
- const liveTxt = yield* notion.readFileBody({ filePageId: lf.id, filePath: lf.path }).pipe(Effect5.catch(() => Effect5.succeed(null)));
7527
+ const liveTxt = yield* notion.readFileBody({ filePageId: lf.id, filePath: lf.path }).pipe(Effect6.catch(() => Effect6.succeed(null)));
6861
7528
  if (liveTxt !== null) {
6862
7529
  try {
6863
7530
  actualLiveSha = sha256Hex(decodeSupportingFilePayload(liveTxt));
@@ -6882,10 +7549,10 @@ function inspectRemoteDrift(args) {
6882
7549
  });
6883
7550
  }
6884
7551
  function diffWorkdirCommand(args) {
6885
- return Effect5.gen(function* () {
6886
- const absWork = nodePath6.resolve(args.workdir);
7552
+ return Effect6.gen(function* () {
7553
+ const absWork = nodePath7.resolve(args.workdir);
6887
7554
  const meta = yield* readWorkMeta(absWork);
6888
- const local = yield* Effect5.tryPromise({
7555
+ const local = yield* Effect6.tryPromise({
6889
7556
  try: () => computeLocalDiff(absWork, meta),
6890
7557
  catch: (e) => new StoreError({ path: absWork, message: String(e) })
6891
7558
  });
@@ -6903,45 +7570,71 @@ function diffWorkdirCommand(args) {
6903
7570
  return { ...baseReport, remoteDrifted: drifts.length > 0, remoteDriftDetails: drifts };
6904
7571
  });
6905
7572
  }
6906
- function pushWorkdirCommand(args) {
6907
- return Effect5.gen(function* () {
7573
+ function pushSingleWorkdirInternal(args) {
7574
+ return Effect6.gen(function* () {
6908
7575
  const notion = yield* NotionPort;
6909
7576
  const store = yield* StorePort;
6910
- const absWork = nodePath6.resolve(args.workdir);
6911
- const meta = yield* readWorkMeta(absWork);
7577
+ const absWork = nodePath7.resolve(args.workdir);
7578
+ const meta = yield* readWorkMeta(absWork).pipe(Effect6.catchTag("NotFoundError", () => Effect6.fail(new ConfigError({
7579
+ path: absWork,
7580
+ message: `Directory '${absWork}' is not an 'ntn-skills edit' workspace (missing ${WORK_META_FILE}). To overwrite an existing Notion skill directly from a plain local directory, pass --overwrite or --to <skill-name> (preview changes first with --dry-run).`
7581
+ }))));
6912
7582
  const { libraryId, binding } = yield* loadResolvedLibrary(meta.libraryId);
6913
- return yield* store.withExclusiveLock(`push-${libraryId.slice(0, 8)}`, Effect5.gen(function* () {
6914
- const local = yield* Effect5.tryPromise({
7583
+ const runPush = Effect6.gen(function* () {
7584
+ const scan = yield* Effect6.tryPromise({
7585
+ try: () => scanLocalSkillDirectory(absWork),
7586
+ catch: (e) => new StoreError({ path: absWork, message: String(e) })
7587
+ });
7588
+ yield* assertNoBlockedSkillFiles(scan);
7589
+ const local = yield* Effect6.tryPromise({
6915
7590
  try: () => computeLocalDiff(absWork, meta),
6916
7591
  catch: (e) => new StoreError({ path: absWork, message: String(e) })
6917
7592
  });
6918
7593
  if (args.dryRun) {
6919
7594
  return {
6920
- workdir: absWork,
6921
- skillName: meta.skillName,
6922
- dryRun: true,
6923
- updatedFiles: local.items.filter((i) => i.path !== "SKILL.md").length,
6924
- updatedMain: local.items.some((i) => i.path === "SKILL.md"),
6925
- newRevision: null,
6926
- workdirCleaned: false
7595
+ report: {
7596
+ workdir: absWork,
7597
+ skillName: meta.skillName,
7598
+ dryRun: true,
7599
+ updatedFiles: local.items.filter((i) => i.path !== "SKILL.md").length,
7600
+ updatedMain: local.items.some((i) => i.path === "SKILL.md"),
7601
+ newRevision: null,
7602
+ workdirCleaned: false
7603
+ },
7604
+ libraryId,
7605
+ skillId: meta.skillId,
7606
+ touchedFileIds: [],
7607
+ archivedFileIds: [],
7608
+ wroteRemote: false,
7609
+ shouldTrash: false
6927
7610
  };
6928
7611
  }
6929
7612
  if (local.items.length === 0 && !local.descriptionChanged) {
6930
- yield* trashPathEffect(absWork);
7613
+ if (!args.deferSyncAndTrash) {
7614
+ yield* trashPathEffect(absWork);
7615
+ }
6931
7616
  return {
6932
- workdir: absWork,
6933
- skillName: meta.skillName,
6934
- dryRun: false,
6935
- updatedFiles: 0,
6936
- updatedMain: false,
6937
- newRevision: null,
6938
- workdirCleaned: true
7617
+ report: {
7618
+ workdir: absWork,
7619
+ skillName: meta.skillName,
7620
+ dryRun: false,
7621
+ updatedFiles: 0,
7622
+ updatedMain: false,
7623
+ newRevision: null,
7624
+ workdirCleaned: !args.deferSyncAndTrash
7625
+ },
7626
+ libraryId,
7627
+ skillId: meta.skillId,
7628
+ touchedFileIds: [],
7629
+ archivedFileIds: [],
7630
+ wroteRemote: false,
7631
+ shouldTrash: true
6939
7632
  };
6940
7633
  }
6941
7634
  if (!args.force) {
6942
7635
  const drifts = yield* inspectRemoteDrift({ meta, filesDs: binding.files_ds });
6943
7636
  if (drifts.length > 0) {
6944
- return yield* Effect5.fail(new ConflictError({
7637
+ return yield* Effect6.fail(new ConflictError({
6945
7638
  kind: "baseline_drift",
6946
7639
  message: `Remote skill '${meta.skillName}' drifted since edit baseline; refusing push (workdir preserved at ${absWork}). Pass --force to overwrite.`,
6947
7640
  details: drifts
@@ -6975,7 +7668,7 @@ function pushWorkdirCommand(args) {
6975
7668
  sha256: "",
6976
7669
  executable: false,
6977
7670
  textContent: ""
6978
- }), () => notion.getSkillFiles({ filesDs: binding.files_ds, skillId: meta.skillId }).pipe(Effect5.map((rf) => {
7671
+ }), () => notion.getSkillFiles({ filesDs: binding.files_ds, skillId: meta.skillId }).pipe(Effect6.map((rf) => {
6979
7672
  const landed = rf.find((f) => f.path === item.path && f.status === "delete");
6980
7673
  return landed ? { pageId: landed.id } : null;
6981
7674
  })));
@@ -6999,7 +7692,7 @@ function pushWorkdirCommand(args) {
6999
7692
  ...baseSha256 ? { baseSha256 } : {},
7000
7693
  executable: curFile.executable,
7001
7694
  textContent
7002
- }), () => Effect5.gen(function* () {
7695
+ }), () => Effect6.gen(function* () {
7003
7696
  const remoteFiles = yield* notion.getSkillFiles({
7004
7697
  filesDs: binding.files_ds,
7005
7698
  skillId: meta.skillId
@@ -7028,7 +7721,7 @@ function pushWorkdirCommand(args) {
7028
7721
  skillId: meta.skillId,
7029
7722
  markdownBody: mainText,
7030
7723
  preserveUpstreamChild: Boolean(meta.originSourceId)
7031
- }), () => notion.readSkillBody(meta.skillId).pipe(Effect5.map((rb) => rb.rawMarkdown.trim() === expectedPrepared.trim() ? { upstreamFilesPageId: rb.upstreamFilesPageId } : null)));
7724
+ }), () => notion.readSkillBody(meta.skillId).pipe(Effect6.map((rb) => rb.rawMarkdown.trim() === expectedPrepared.trim() ? { upstreamFilesPageId: rb.upstreamFilesPageId } : null)));
7032
7725
  }
7033
7726
  const preservedSubDigest = meta.originSourceId ? extractSubtreeDigestFromRevision(meta.baseRevision) : null;
7034
7727
  const newRevision = makeRevisionStamp(preservedSubDigest);
@@ -7039,45 +7732,59 @@ function pushWorkdirCommand(args) {
7039
7732
  ...meta.originSourceId && updatedMain ? { customMain: true } : {},
7040
7733
  revision: newRevision
7041
7734
  });
7042
- yield* syncCommand({
7043
- libraryId,
7044
- dedupeWindowMs: 0,
7045
- readYourWrites: { skillIds: [meta.skillId], fileIds: touchedFileIds, archivedFileIds }
7046
- });
7047
- yield* trashPathEffect(absWork);
7735
+ if (!args.deferSyncAndTrash) {
7736
+ yield* syncCommand({
7737
+ libraryId,
7738
+ dedupeWindowMs: 0,
7739
+ readYourWrites: { skillIds: [meta.skillId], fileIds: touchedFileIds, archivedFileIds }
7740
+ });
7741
+ yield* trashPathEffect(absWork);
7742
+ }
7048
7743
  return {
7049
- workdir: absWork,
7050
- skillName: meta.skillName,
7051
- dryRun: false,
7052
- updatedFiles: updatedFilesCount,
7053
- updatedMain,
7054
- newRevision,
7055
- workdirCleaned: true
7744
+ report: {
7745
+ workdir: absWork,
7746
+ skillName: meta.skillName,
7747
+ dryRun: false,
7748
+ updatedFiles: updatedFilesCount,
7749
+ updatedMain,
7750
+ newRevision,
7751
+ workdirCleaned: !args.deferSyncAndTrash
7752
+ },
7753
+ libraryId,
7754
+ skillId: meta.skillId,
7755
+ touchedFileIds,
7756
+ archivedFileIds,
7757
+ wroteRemote: true,
7758
+ shouldTrash: true
7056
7759
  };
7057
- }));
7760
+ });
7761
+ return args.dryRun ? yield* runPush : yield* store.withExclusiveLock(`push-${libraryId.slice(0, 8)}`, runPush);
7058
7762
  });
7059
7763
  }
7764
+ function pushWorkdirCommand(args) {
7765
+ return pushSingleWorkdirInternal(args).pipe(Effect6.map((r) => r.report));
7766
+ }
7060
7767
  function abortWorkdirCommand(workdir) {
7061
- return Effect5.gen(function* () {
7062
- const abs = nodePath6.resolve(workdir);
7768
+ return Effect6.gen(function* () {
7769
+ const abs = nodePath7.resolve(workdir);
7063
7770
  yield* readWorkMeta(abs);
7064
7771
  yield* trashPathEffect(abs);
7065
7772
  return abs;
7066
7773
  });
7067
7774
  }
7068
7775
  function listWorkdirsCommand() {
7069
- return Effect5.gen(function* () {
7776
+ return Effect6.gen(function* () {
7070
7777
  const store = yield* StorePort;
7071
- return yield* Effect5.tryPromise({
7778
+ return yield* Effect6.tryPromise({
7072
7779
  try: async () => {
7073
- const dirs = await fsp6.readdir(store.paths.workRoot).catch(() => []);
7780
+ const dirs = await fsp7.readdir(store.paths.workRoot).catch(() => []);
7074
7781
  const out = [];
7075
7782
  for (const d of dirs) {
7076
7783
  if (d.startsWith("."))
7077
7784
  continue;
7078
- const full = nodePath6.join(store.paths.workRoot, d);
7785
+ const full = nodePath7.join(store.paths.workRoot, d);
7079
7786
  try {
7080
- const raw = await fsp6.readFile(nodePath6.join(full, WORK_META_FILE), "utf8");
7787
+ const raw = await fsp7.readFile(nodePath7.join(full, WORK_META_FILE), "utf8");
7081
7788
  out.push({
7082
7789
  workdir: full,
7083
7790
  meta: Schema4.decodeUnknownSync(WorkMetaSchema)(JSON.parse(raw))
@@ -7091,7 +7798,7 @@ function listWorkdirsCommand() {
7091
7798
  });
7092
7799
  }
7093
7800
  function cleanWorkdirsCommand(olderThanDays = 7) {
7094
- return Effect5.gen(function* () {
7801
+ return Effect6.gen(function* () {
7095
7802
  const all = yield* listWorkdirsCommand();
7096
7803
  const cutoff = Date.now() - olderThanDays * 86400000;
7097
7804
  const cleaned = [];
@@ -7109,30 +7816,37 @@ function resolveImportedSkillVisibility(disableModelInvocation, requestedVisibil
7109
7816
  return disableModelInvocation ? "manual" : requestedVisibility ?? "manual";
7110
7817
  }
7111
7818
  function createNewSkillCommand(args) {
7112
- return Effect5.gen(function* () {
7819
+ return Effect6.gen(function* () {
7113
7820
  const notion = yield* NotionPort;
7114
7821
  const store = yield* StorePort;
7115
7822
  const config = yield* store.readConfig();
7116
7823
  const { libraryId, binding, catalog } = yield* loadSyncedLibrary(args.libraryId);
7117
- const absDir = nodePath6.resolve(args.dir);
7118
- const files = yield* Effect5.tryPromise({
7119
- try: () => scanWorkdirFiles(absDir),
7824
+ const absDir = nodePath7.resolve(args.dir);
7825
+ const scan = yield* Effect6.tryPromise({
7826
+ try: () => scanLocalSkillDirectory(absDir),
7120
7827
  catch: (e) => new StoreError({
7121
7828
  path: absDir,
7122
7829
  message: `Cannot read skill directory ${absDir}: ${String(e)}`
7123
7830
  })
7124
7831
  });
7832
+ yield* assertNoBlockedSkillFiles(scan);
7833
+ const files = scan.files;
7125
7834
  const mainFile = files.get("SKILL.md");
7126
7835
  if (!mainFile)
7127
- return yield* Effect5.fail(new StoreError({ path: absDir, message: `Missing SKILL.md in ${absDir}.` }));
7836
+ return yield* Effect6.fail(new StoreError({ path: absDir, message: `Missing SKILL.md in ${absDir}.` }));
7128
7837
  const rawMain = new TextDecoder().decode(mainFile.bytes);
7129
7838
  const parsed = parseSkillFrontmatter(rawMain);
7130
- const skillName = (args.name ?? parsed.name ?? nodePath6.basename(absDir)).trim();
7131
- const duplicate = catalog.entries.find((e) => e.libraryId === libraryId && e.name.toLowerCase() === skillName.toLowerCase());
7839
+ const skillName = args.name?.trim() ? normalizeSkillSlug(args.name) : resolveCanonicalSkillName(parsed.name, nodePath7.basename(absDir));
7840
+ if (!skillName || !isValidSkillSlug(skillName)) {
7841
+ return yield* Effect6.fail(new ConfigError({
7842
+ message: `Invalid skill name for ${absDir}: must form a lowercase hyphenated English slug (a-z, 0-9, -). Pass --name <slug>.`
7843
+ }));
7844
+ }
7845
+ const duplicate = catalog.entries.find((e) => e.libraryId === libraryId && (e.name.toLowerCase() === skillName.toLowerCase() || normalizeSkillSlug(e.name) === normalizeSkillSlug(skillName)));
7132
7846
  if (duplicate) {
7133
- return yield* Effect5.fail(new ConflictError({
7847
+ return yield* Effect6.fail(new ConflictError({
7134
7848
  kind: "duplicate_name",
7135
- message: `Skill '${skillName}' already exists (${duplicate.skillId}). Use 'ntn-skills edit ${skillName}' instead.`
7849
+ message: `Skill '${skillName}' already exists (${duplicate.skillId}). Use 'ntn-skills push "${absDir}" --overwrite' or 'ntn-skills edit "${skillName}"' instead.`
7136
7850
  }));
7137
7851
  }
7138
7852
  const preparedSupporting = [];
@@ -7166,7 +7880,7 @@ function createNewSkillCommand(args) {
7166
7880
  previewHash: "",
7167
7881
  markdownBody: rawMain
7168
7882
  });
7169
- const createdFileIds = yield* Effect5.forEach(preparedSupporting, (sf) => notion.upsertFilePage({
7883
+ const createdFileIds = yield* Effect6.forEach(preparedSupporting, (sf) => notion.upsertFilePage({
7170
7884
  libraryId,
7171
7885
  filesDs: binding.files_ds,
7172
7886
  existingPageId: null,
@@ -7177,22 +7891,22 @@ function createNewSkillCommand(args) {
7177
7891
  sha256: sf.sha256,
7178
7892
  executable: sf.executable,
7179
7893
  textContent: sf.textContent
7180
- }).pipe(Effect5.map((up) => up.pageId)), { concurrency: UPSTREAM_SKILL_CONCURRENCY });
7894
+ }).pipe(Effect6.map((up) => up.pageId)), { concurrency: UPSTREAM_SKILL_CONCURRENCY });
7181
7895
  const resolvedExports = yield* resolveConfiguredExports(config, store.paths.configPath);
7182
- const isInExportRoot = yield* Effect5.tryPromise(async () => {
7183
- const lst = await fsp6.lstat(absDir).catch(() => null);
7896
+ const isInExportRoot = yield* Effect6.tryPromise(async () => {
7897
+ const lst = await fsp7.lstat(absDir).catch(() => null);
7184
7898
  if (!lst || lst.isSymbolicLink())
7185
7899
  return false;
7186
- const realAbsParent = await fsp6.realpath(nodePath6.dirname(absDir)).catch(() => nodePath6.dirname(absDir));
7900
+ const realAbsParent = await fsp7.realpath(nodePath7.dirname(absDir)).catch(() => nodePath7.dirname(absDir));
7187
7901
  for (const { target: exp } of resolvedExports.targets) {
7188
7902
  const expRoot = resolveHomePath(exp.dir);
7189
- const realExpRoot = await fsp6.realpath(expRoot).catch(() => expRoot);
7190
- if (nodePath6.dirname(absDir) === expRoot || realAbsParent === realExpRoot) {
7903
+ const realExpRoot = await fsp7.realpath(expRoot).catch(() => expRoot);
7904
+ if (nodePath7.dirname(absDir) === expRoot || realAbsParent === realExpRoot) {
7191
7905
  return true;
7192
7906
  }
7193
7907
  }
7194
7908
  return false;
7195
- }).pipe(Effect5.catch(() => Effect5.succeed(false)));
7909
+ }).pipe(Effect6.catch(() => Effect6.succeed(false)));
7196
7910
  const shouldAdopt = args.adopt === undefined ? isInExportRoot : args.adopt;
7197
7911
  let adoptedSourceDir = false;
7198
7912
  if (shouldAdopt) {
@@ -7204,18 +7918,18 @@ function createNewSkillCommand(args) {
7204
7918
  dedupeWindowMs: 0,
7205
7919
  readYourWrites: { skillIds: [created.id], fileIds: createdFileIds }
7206
7920
  });
7207
- const exportedAtSourcePath = adoptedSourceDir && isInExportRoot ? yield* Effect5.tryPromise(async () => {
7208
- const lst = await fsp6.lstat(absDir).catch(() => null);
7921
+ const exportedAtSourcePath = adoptedSourceDir && isInExportRoot ? yield* Effect6.tryPromise(async () => {
7922
+ const lst = await fsp7.lstat(absDir).catch(() => null);
7209
7923
  if (!lst)
7210
7924
  return false;
7211
7925
  if (lst.isSymbolicLink())
7212
7926
  return true;
7213
7927
  if (lst.isDirectory()) {
7214
- const marker = await fsp6.stat(nodePath6.join(absDir, ".ntn-managed-copy.json")).catch(() => null);
7928
+ const marker = await fsp7.stat(nodePath7.join(absDir, ".ntn-managed-copy.json")).catch(() => null);
7215
7929
  return Boolean(marker?.isFile());
7216
7930
  }
7217
7931
  return false;
7218
- }).pipe(Effect5.catch(() => Effect5.succeed(false))) : false;
7932
+ }).pipe(Effect6.catch(() => Effect6.succeed(false))) : false;
7219
7933
  return {
7220
7934
  skillId: created.id,
7221
7935
  name: skillName,
@@ -7228,12 +7942,12 @@ function createNewSkillCommand(args) {
7228
7942
  });
7229
7943
  }
7230
7944
  function setSkillMetaCommand(args) {
7231
- return Effect5.gen(function* () {
7945
+ return Effect6.gen(function* () {
7232
7946
  const notion = yield* NotionPort;
7233
7947
  const { libraryId, libState } = yield* loadSyncedLibrary(args.libraryId);
7234
7948
  const requestedNames = [...args.name ? [args.name] : [], ...args.names ?? []].map((n) => n.trim()).filter(Boolean);
7235
7949
  if (requestedNames.length === 0 && !args.sourceQuery?.trim()) {
7236
- return yield* Effect5.fail(new ConfigError({
7950
+ return yield* Effect6.fail(new ConfigError({
7237
7951
  message: "Specify at least one skill <name> or pass --source <source-name-or-id>."
7238
7952
  }));
7239
7953
  }
@@ -7260,7 +7974,7 @@ function setSkillMetaCommand(args) {
7260
7974
  for (const reqName of args.requireNames) {
7261
7975
  const found = yield* findSkillOrFail(libState, reqName);
7262
7976
  if (!found.enabled) {
7263
- return yield* Effect5.fail(new NotFoundError({
7977
+ return yield* Effect6.fail(new NotFoundError({
7264
7978
  entity: "skill",
7265
7979
  target: reqName,
7266
7980
  message: `Required skill '${reqName}' is disabled.`
@@ -7269,7 +7983,7 @@ function setSkillMetaCommand(args) {
7269
7983
  nextRequires.push(found.id);
7270
7984
  }
7271
7985
  }
7272
- yield* Effect5.forEach(targetList, (targetSkill) => Effect5.gen(function* () {
7986
+ yield* Effect6.forEach(targetList, (targetSkill) => Effect6.gen(function* () {
7273
7987
  const nextProfiles = new Set(targetSkill.profiles);
7274
7988
  for (const p of args.addProfiles ?? [])
7275
7989
  nextProfiles.add(p);
@@ -7301,17 +8015,17 @@ function setSkillMetaCommand(args) {
7301
8015
  });
7302
8016
  }
7303
8017
  function detachSkillCommand(args) {
7304
- return Effect5.gen(function* () {
8018
+ return Effect6.gen(function* () {
7305
8019
  const notion = yield* NotionPort;
7306
8020
  const { libraryId, binding } = yield* loadResolvedLibrary(args.libraryId);
7307
8021
  const pulled = yield* editOrPullSkillCommand({ name: args.name, libraryId });
7308
8022
  try {
7309
- const files = yield* Effect5.tryPromise({
8023
+ const files = yield* Effect6.tryPromise({
7310
8024
  try: () => scanWorkdirFiles(pulled.workdir),
7311
8025
  catch: (e) => new StoreError({ path: pulled.workdir, message: String(e) })
7312
8026
  });
7313
8027
  const supportingEntries = [...files.entries()].filter(([relPath]) => relPath !== "SKILL.md");
7314
- yield* Effect5.forEach(supportingEntries, ([relPath, f]) => Effect5.gen(function* () {
8028
+ yield* Effect6.forEach(supportingEntries, ([relPath, f]) => Effect6.gen(function* () {
7315
8029
  const base = pulled.meta.baseFiles[relPath];
7316
8030
  const encoded = base?.externalUrl ? null : yield* encodeSupportingFileEffect(f.bytes, relPath);
7317
8031
  yield* notion.upsertFilePage({
@@ -7352,7 +8066,7 @@ function detachSkillCommand(args) {
7352
8066
  revision: makeRevisionStamp()
7353
8067
  });
7354
8068
  } finally {
7355
- yield* trashPathEffect(pulled.workdir).pipe(Effect5.ignore);
8069
+ yield* trashPathEffect(pulled.workdir).pipe(Effect6.ignore);
7356
8070
  }
7357
8071
  yield* syncCommand({
7358
8072
  libraryId,
@@ -7366,14 +8080,14 @@ function detachSkillCommand(args) {
7366
8080
  });
7367
8081
  }
7368
8082
  function attachSkillCommand(args) {
7369
- return Effect5.gen(function* () {
8083
+ return Effect6.gen(function* () {
7370
8084
  const notion = yield* NotionPort;
7371
8085
  const upstream = yield* UpstreamPort;
7372
8086
  const { libraryId, binding, libState } = yield* loadSyncedLibrary(args.libraryId);
7373
8087
  const sk = yield* findSkillOrFail(libState, args.name);
7374
8088
  const src = yield* findSourceOrFail(libState, args.sourceQuery);
7375
8089
  if (!src.enabled) {
7376
- return yield* Effect5.fail(new NotFoundError({
8090
+ return yield* Effect6.fail(new NotFoundError({
7377
8091
  entity: "source",
7378
8092
  target: src.name,
7379
8093
  message: `Source '${src.name}' is disabled. Enable it with 'ntn-skills source set "${src.name}" --enable' first.`
@@ -7388,7 +8102,7 @@ function attachSkillCommand(args) {
7388
8102
  });
7389
8103
  const match = discovered.find((d) => d.name.toLowerCase() === sk.name.toLowerCase());
7390
8104
  if (!match) {
7391
- return yield* Effect5.fail(new NotFoundError({
8105
+ return yield* Effect6.fail(new NotFoundError({
7392
8106
  entity: "skill",
7393
8107
  target: sk.name,
7394
8108
  message: `Could not auto-discover '${sk.name}' in source '${src.name}'@${commitSha.slice(0, 12)}. Commit and push it to the Git repo first, or pass --path <subdir>.`
@@ -7403,14 +8117,14 @@ function attachSkillCommand(args) {
7403
8117
  });
7404
8118
  const upstreamMain = subtreeFiles.find((f) => f.path === "SKILL.md");
7405
8119
  if (!upstreamMain) {
7406
- return yield* Effect5.fail(new StoreError({
8120
+ return yield* Effect6.fail(new StoreError({
7407
8121
  path: resolvedPath,
7408
8122
  message: `No SKILL.md found at '${resolvedPath}' in ${src.repoUrl}@${commitSha.slice(0, 12)}.`
7409
8123
  }));
7410
8124
  }
7411
8125
  const subDigest = computeSubtreeDigest(subtreeFiles);
7412
8126
  const upByPath = new Map(subtreeFiles.filter((f) => f.path !== "SKILL.md").map((f) => [f.path, f]));
7413
- const [liveFiles, liveBody] = yield* Effect5.all([
8127
+ const [liveFiles, liveBody] = yield* Effect6.all([
7414
8128
  notion.getSkillFiles({ filesDs: binding.files_ds, skillId: sk.id }),
7415
8129
  notion.readSkillBody(sk.id)
7416
8130
  ]);
@@ -7499,13 +8213,13 @@ function attachSkillCommand(args) {
7499
8213
  });
7500
8214
  }
7501
8215
  function resetOverlayCommand(args) {
7502
- return Effect5.gen(function* () {
8216
+ return Effect6.gen(function* () {
7503
8217
  const notion = yield* NotionPort;
7504
8218
  const upstream = yield* UpstreamPort;
7505
8219
  const { libraryId, binding, libState } = yield* loadSyncedLibrary(args.libraryId);
7506
8220
  const sk = yield* findSkillOrFail(libState, args.name);
7507
8221
  if (!sk.originSourceId) {
7508
- return yield* Effect5.fail(new NotFoundError({
8222
+ return yield* Effect6.fail(new NotFoundError({
7509
8223
  entity: "skill",
7510
8224
  target: args.name,
7511
8225
  message: `Skill '${args.name}' is not an upstream Git skill.`
@@ -7560,7 +8274,7 @@ function resetOverlayCommand(args) {
7560
8274
  });
7561
8275
  }
7562
8276
  function removeSkillCommand(args) {
7563
- return Effect5.gen(function* () {
8277
+ return Effect6.gen(function* () {
7564
8278
  const notion = yield* NotionPort;
7565
8279
  const { libraryId, libState } = yield* loadSyncedLibrary(args.libraryId);
7566
8280
  const sk = yield* findSkillOrFail(libState, args.name);
@@ -7576,10 +8290,10 @@ function removeSkillCommand(args) {
7576
8290
  });
7577
8291
  }
7578
8292
  function listSourcesCommand(args) {
7579
- return loadTableMetadataLibrary(args?.libraryId).pipe(Effect5.map(({ libState }) => Object.values(libState.sources).sort((a, b) => a.name.localeCompare(b.name))));
8293
+ return loadTableMetadataLibrary(args?.libraryId).pipe(Effect6.map(({ libState }) => Object.values(libState.sources).sort((a, b) => a.name.localeCompare(b.name))));
7580
8294
  }
7581
8295
  function addSourceCommand(args) {
7582
- return Effect5.gen(function* () {
8296
+ return Effect6.gen(function* () {
7583
8297
  const notion = yield* NotionPort;
7584
8298
  const upstream = yield* UpstreamPort;
7585
8299
  const { libraryId, binding, libState } = yield* loadSyncedLibrary(args.libraryId);
@@ -7610,7 +8324,7 @@ function addSourceCommand(args) {
7610
8324
  existingNames.add(lower);
7611
8325
  return true;
7612
8326
  });
7613
- const createdResults = yield* Effect5.forEach(toRegister, (d) => Effect5.gen(function* () {
8327
+ const createdResults = yield* Effect6.forEach(toRegister, (d) => Effect6.gen(function* () {
7614
8328
  const subtreeFiles = yield* upstream.fetchSubtree({
7615
8329
  repoUrl: cleanUrl,
7616
8330
  commitSha,
@@ -7679,14 +8393,14 @@ function findSourceOrFail(libState, sourceQuery) {
7679
8393
  const q = sourceQuery.trim().toLowerCase();
7680
8394
  const candidates = Object.values(libState.sources).filter((s) => s.name.toLowerCase() === q || s.id === normalizeUuid(q)).sort((a, b) => Number(b.enabled) - Number(a.enabled) || b.lastEditedTime.localeCompare(a.lastEditedTime));
7681
8395
  const found = candidates[0];
7682
- return found ? Effect5.succeed(found) : Effect5.fail(new NotFoundError({
8396
+ return found ? Effect6.succeed(found) : Effect6.fail(new NotFoundError({
7683
8397
  entity: "source",
7684
8398
  target: sourceQuery,
7685
8399
  message: `Source '${sourceQuery}' not found.`
7686
8400
  }));
7687
8401
  }
7688
8402
  function setSourceMetaCommand(args) {
7689
- return Effect5.gen(function* () {
8403
+ return Effect6.gen(function* () {
7690
8404
  const notion = yield* NotionPort;
7691
8405
  const { libraryId, libState } = yield* loadTableMetadataLibrary(args.libraryId);
7692
8406
  const src = yield* findSourceOrFail(libState, args.sourceQuery);
@@ -7706,13 +8420,13 @@ function setSourceMetaCommand(args) {
7706
8420
  });
7707
8421
  }
7708
8422
  function syncSourceSkillsCommand(args) {
7709
- return Effect5.gen(function* () {
8423
+ return Effect6.gen(function* () {
7710
8424
  const notion = yield* NotionPort;
7711
8425
  const upstream = yield* UpstreamPort;
7712
8426
  const { libraryId, binding, libState } = yield* loadTableMetadataLibrary(args.libraryId);
7713
8427
  const src = yield* findSourceOrFail(libState, args.sourceQuery);
7714
8428
  if (!src.enabled) {
7715
- return yield* Effect5.fail(new NotFoundError({
8429
+ return yield* Effect6.fail(new NotFoundError({
7716
8430
  entity: "source",
7717
8431
  target: src.name,
7718
8432
  message: `Source '${src.name}' is disabled. Enable it with 'ntn-skills source set "${src.name}" --enable' first.`
@@ -7729,7 +8443,7 @@ function syncSourceSkillsCommand(args) {
7729
8443
  const existingSkills = Object.values(libState.skills).filter((s) => s.enabled);
7730
8444
  const existingByName = new Map(existingSkills.map((s) => [s.name.toLowerCase(), s]));
7731
8445
  const toRepair = existingSkills.filter((sk) => sk.originSourceId === src.id && !sk.sourcePath).map((sk) => ({ sk, match: discoveredByName.get(sk.name.toLowerCase()) })).filter((x) => x.match !== undefined);
7732
- const repairResults = yield* Effect5.forEach(toRepair, ({ sk, match }) => Effect5.gen(function* () {
8446
+ const repairResults = yield* Effect6.forEach(toRepair, ({ sk, match }) => Effect6.gen(function* () {
7733
8447
  const subtreeFiles = yield* upstream.fetchSubtree({
7734
8448
  repoUrl: src.repoUrl,
7735
8449
  commitSha,
@@ -7765,7 +8479,7 @@ function syncSourceSkillsCommand(args) {
7765
8479
  seenNames.add(lower);
7766
8480
  return true;
7767
8481
  });
7768
- const createResults = yield* Effect5.forEach(toRegister, (d) => Effect5.gen(function* () {
8482
+ const createResults = yield* Effect6.forEach(toRegister, (d) => Effect6.gen(function* () {
7769
8483
  const subtreeFiles = yield* upstream.fetchSubtree({
7770
8484
  repoUrl: src.repoUrl,
7771
8485
  commitSha,
@@ -7840,12 +8554,12 @@ function syncSourceSkillsCommand(args) {
7840
8554
  });
7841
8555
  }
7842
8556
  function upstreamCheckOrApplyCommand(args) {
7843
- return Effect5.gen(function* () {
8557
+ return Effect6.gen(function* () {
7844
8558
  if (args.maxSources !== undefined && (!Number.isInteger(args.maxSources) || args.maxSources < 1)) {
7845
- return yield* Effect5.fail(new ConfigError({ message: "--max-sources must be an integer >= 1." }));
8559
+ return yield* Effect6.fail(new ConfigError({ message: "--max-sources must be an integer >= 1." }));
7846
8560
  }
7847
8561
  if (args.timeoutSec !== undefined && (!Number.isFinite(args.timeoutSec) || args.timeoutSec <= 0)) {
7848
- return yield* Effect5.fail(new ConfigError({ message: "--timeout-sec must be greater than 0." }));
8562
+ return yield* Effect6.fail(new ConfigError({ message: "--timeout-sec must be greater than 0." }));
7849
8563
  }
7850
8564
  const notion = yield* NotionPort;
7851
8565
  const upstream = yield* UpstreamPort;
@@ -7853,7 +8567,7 @@ function upstreamCheckOrApplyCommand(args) {
7853
8567
  const startedMs = Date.now();
7854
8568
  const startedAt = new Date(startedMs).toISOString();
7855
8569
  const deadlineMs = args.timeoutSec !== undefined ? startedMs + Math.round(args.timeoutSec * 1000) : undefined;
7856
- const runCore = Effect5.gen(function* () {
8570
+ const runCore = Effect6.gen(function* () {
7857
8571
  const { libraryId, binding, libState } = yield* loadTableMetadataLibrary(args.libraryId);
7858
8572
  const filesBySkillId = new Map;
7859
8573
  for (const f of Object.values(libState.files)) {
@@ -7875,7 +8589,7 @@ function upstreamCheckOrApplyCommand(args) {
7875
8589
  return s.policy === "track";
7876
8590
  }).sort((a, b) => a.name.localeCompare(b.name));
7877
8591
  if (args.sourceQuery && candidateSources.length === 0) {
7878
- return yield* Effect5.fail(new NotFoundError({
8592
+ return yield* Effect6.fail(new NotFoundError({
7879
8593
  entity: "source",
7880
8594
  target: args.sourceQuery,
7881
8595
  message: `Enabled source '${args.sourceQuery}' not found in library ${libraryId}.`
@@ -7912,7 +8626,7 @@ function upstreamCheckOrApplyCommand(args) {
7912
8626
  });
7913
8627
  continue;
7914
8628
  }
7915
- const singleEffect = Effect5.gen(function* () {
8629
+ const singleEffect = Effect6.gen(function* () {
7916
8630
  const latestCommit = yield* upstream.resolveHeadCommit(src.repoUrl, src.ref);
7917
8631
  const hasUpdate = latestCommit !== src.pinnedCommit;
7918
8632
  if (!hasUpdate) {
@@ -7979,7 +8693,7 @@ function upstreamCheckOrApplyCommand(args) {
7979
8693
  const discoveredNewByPath = new Map(discoveredNew.map((d) => [normalizeSourcePathKey(d.sourcePath), d]));
7980
8694
  let oldSkillPaths = null;
7981
8695
  if (src.pinnedCommit) {
7982
- const oldDiscovered = yield* upstream.scanRepoSkills({ repoUrl: src.repoUrl, commitSha: src.pinnedCommit }).pipe(Effect5.catch(() => Effect5.succeed(null)));
8696
+ const oldDiscovered = yield* upstream.scanRepoSkills({ repoUrl: src.repoUrl, commitSha: src.pinnedCommit }).pipe(Effect6.catch(() => Effect6.succeed(null)));
7983
8697
  if (oldDiscovered !== null) {
7984
8698
  oldSkillPaths = new Set(oldDiscovered.map((d) => normalizeSourcePathKey(d.sourcePath)));
7985
8699
  }
@@ -7991,13 +8705,13 @@ function upstreamCheckOrApplyCommand(args) {
7991
8705
  const previewDriftWarnings = [];
7992
8706
  const localTouchedSkillIds = [];
7993
8707
  const localArchivedFileIds = [];
7994
- yield* Effect5.forEach(childSkills, (sk) => Effect5.gen(function* () {
8708
+ yield* Effect6.forEach(childSkills, (sk) => Effect6.gen(function* () {
7995
8709
  const sourcePath = normalizeSourcePathKey(sk.sourcePath);
7996
8710
  const subtreeOpt = yield* upstream.fetchSubtree({
7997
8711
  repoUrl: src.repoUrl,
7998
8712
  commitSha: latestCommit,
7999
8713
  sourcePath
8000
- }).pipe(Effect5.map((files) => discoveredNewByPath.has(sourcePath) || files.some((f) => f.path === "SKILL.md") ? files : null), Effect5.catchTag("UpstreamError", (err) => /not found in|http 404/i.test(err.message) ? Effect5.succeed(null) : Effect5.fail(err)));
8714
+ }).pipe(Effect6.map((files) => discoveredNewByPath.has(sourcePath) || files.some((f) => f.path === "SKILL.md") ? files : null), Effect6.catchTag("UpstreamError", (err) => /not found in|http 404/i.test(err.message) ? Effect6.succeed(null) : Effect6.fail(err)));
8001
8715
  const activeOverlays = normalizeOverlayFiles(filesBySkillId.get(sk.id) ?? []);
8002
8716
  const overrideRows = activeOverlays.filter((ov) => ov.status === "override");
8003
8717
  if (subtreeOpt === null) {
@@ -8021,11 +8735,11 @@ function upstreamCheckOrApplyCommand(args) {
8021
8735
  repoUrl: src.repoUrl,
8022
8736
  commitSha: src.pinnedCommit,
8023
8737
  sourcePath
8024
- }).pipe(Effect5.catch(() => Effect5.succeed(null)));
8738
+ }).pipe(Effect6.catch(() => Effect6.succeed(null)));
8025
8739
  if (oldFiles !== null) {
8026
8740
  const overlayPathSet = new Set(activeOverlays.map((o) => o.path));
8027
8741
  const remainingBase = oldFiles.filter((f) => f.path !== "SKILL.md" && !overlayPathSet.has(f.path));
8028
- yield* Effect5.forEach(remainingBase, (bf) => Effect5.gen(function* () {
8742
+ yield* Effect6.forEach(remainingBase, (bf) => Effect6.gen(function* () {
8029
8743
  const encoded = yield* encodeSupportingFileEffect(bf.bytes, bf.path);
8030
8744
  yield* notion.upsertFilePage({
8031
8745
  libraryId,
@@ -8075,7 +8789,7 @@ function upstreamCheckOrApplyCommand(args) {
8075
8789
  repoUrl: src.repoUrl,
8076
8790
  commitSha: src.pinnedCommit,
8077
8791
  sourcePath
8078
- }).pipe(Effect5.catch(() => Effect5.succeed(null))) : null;
8792
+ }).pipe(Effect6.catch(() => Effect6.succeed(null))) : null;
8079
8793
  const oldDigest = oldSubtreeFiles ? computeSubtreeDigest(oldSubtreeFiles) : null;
8080
8794
  const oldShaByPath = new Map;
8081
8795
  for (const ofile of oldSubtreeFiles ?? []) {
@@ -8147,7 +8861,7 @@ function upstreamCheckOrApplyCommand(args) {
8147
8861
  let matchesTargetUpstream = false;
8148
8862
  if (rawMainText !== null) {
8149
8863
  const preparedTarget = prepareSkillMarkdownForNotionBody(rawMainText).cleanNotionMarkdown;
8150
- const renderedTarget = yield* Effect5.tryPromise(() => renderBlocksToMarkdown(markdownToBlocks(preparedTarget), async () => [])).pipe(Effect5.catch(() => Effect5.succeed("")));
8864
+ const renderedTarget = yield* Effect6.tryPromise(() => renderBlocksToMarkdown(markdownToBlocks(preparedTarget), async () => [])).pipe(Effect6.catch(() => Effect6.succeed("")));
8151
8865
  const trimmedLive = currentBody.rawMarkdown.trim();
8152
8866
  if (trimmedLive === preparedTarget.trim() || renderedTarget.length > 0 && trimmedLive === renderedTarget.trim()) {
8153
8867
  matchesTargetUpstream = true;
@@ -8212,7 +8926,7 @@ function upstreamCheckOrApplyCommand(args) {
8212
8926
  takenActiveNames.add(lowerName);
8213
8927
  return true;
8214
8928
  });
8215
- yield* Effect5.forEach(toAddSkills, (d) => Effect5.gen(function* () {
8929
+ yield* Effect6.forEach(toAddSkills, (d) => Effect6.gen(function* () {
8216
8930
  const subtreeFiles = yield* upstream.fetchSubtree({
8217
8931
  repoUrl: src.repoUrl,
8218
8932
  commitSha: latestCommit,
@@ -8286,7 +9000,7 @@ function upstreamCheckOrApplyCommand(args) {
8286
9000
  previewDriftWarnings
8287
9001
  };
8288
9002
  });
8289
- const isolatedEffect = (deadlineMs !== undefined ? singleEffect.pipe(Effect5.timeoutOption(Math.max(500, deadlineMs - Date.now())), Effect5.map((opt) => Option.isSome(opt) ? opt.value : {
9003
+ const isolatedEffect = (deadlineMs !== undefined ? singleEffect.pipe(Effect6.timeoutOption(Math.max(500, deadlineMs - Date.now())), Effect6.map((opt) => Option.isSome(opt) ? opt.value : {
8290
9004
  sourceId: src.id,
8291
9005
  sourceName: src.name,
8292
9006
  repoUrl: src.repoUrl,
@@ -8299,15 +9013,15 @@ function upstreamCheckOrApplyCommand(args) {
8299
9013
  previewDriftWarnings: [],
8300
9014
  error: `Source timed out before batch deadline (${args.timeoutSec}s).`,
8301
9015
  retryable: true
8302
- })) : singleEffect).pipe(Effect5.catch((err) => {
9016
+ })) : singleEffect).pipe(Effect6.catch((err) => {
8303
9017
  if (err._tag === "AuthError" && err.provider === "notion") {
8304
- return Effect5.fail(err);
9018
+ return Effect6.fail(err);
8305
9019
  }
8306
9020
  if (err._tag === "ConflictError" && err.kind === "production_guard") {
8307
- return Effect5.fail(err);
9021
+ return Effect6.fail(err);
8308
9022
  }
8309
9023
  const isRetryable = err._tag === "NotionApiError" ? Boolean(err.retryable) : err._tag === "UpstreamError" ? !/not found in|unexpected commit sha|http 404/i.test(err.message) : false;
8310
- return Effect5.succeed({
9024
+ return Effect6.succeed({
8311
9025
  sourceId: src.id,
8312
9026
  sourceName: src.name,
8313
9027
  repoUrl: src.repoUrl,
@@ -8357,56 +9071,1095 @@ function upstreamCheckOrApplyCommand(args) {
8357
9071
  break;
8358
9072
  }
8359
9073
  }
8360
- if (applied > 0) {
9074
+ if (applied > 0) {
9075
+ yield* syncCommand({
9076
+ libraryId,
9077
+ dedupeWindowMs: 0,
9078
+ readYourWrites: {
9079
+ sourceIds: rywSourceIds,
9080
+ skillIds: rywSkillIds,
9081
+ archivedFileIds: rywArchivedFileIds
9082
+ }
9083
+ });
9084
+ }
9085
+ const finishedMs = Date.now();
9086
+ const permanentFailures = failed - retryableFailures;
9087
+ const recommendedExitCode = permanentFailures > 0 ? 2 : retryableFailures > 0 || skippedDeadline > 0 ? 75 : args.strictDrift && driftWarningsCount > 0 ? 3 : 0;
9088
+ const report = {
9089
+ libraryId,
9090
+ mode: !args.apply ? "check" : args.dryRun ? "dry-run" : "apply",
9091
+ startedAt,
9092
+ finishedAt: new Date(finishedMs).toISOString(),
9093
+ durationMs: Math.max(0, finishedMs - startedMs),
9094
+ totalCandidates: candidateSources.length,
9095
+ checked,
9096
+ upToDate,
9097
+ updateAvailable,
9098
+ applied,
9099
+ skippedLimit,
9100
+ skippedDeadline,
9101
+ driftWarningsCount,
9102
+ failed,
9103
+ retryableFailures,
9104
+ recommendedExitCode,
9105
+ sources: sourcesOut
9106
+ };
9107
+ if (args.reportFile) {
9108
+ const outPath = resolveHomePath(args.reportFile);
9109
+ yield* Effect6.tryPromise({
9110
+ try: () => atomicWriteJson(outPath, report),
9111
+ catch: (e) => new StoreError({
9112
+ path: outPath,
9113
+ message: `Failed writing upstream report to ${outPath}: ${String(e)}`
9114
+ })
9115
+ });
9116
+ }
9117
+ return report;
9118
+ });
9119
+ if (args.apply && !args.dryRun) {
9120
+ const { libraryId } = yield* loadResolvedLibrary(args.libraryId);
9121
+ return yield* store.withExclusiveLock(`upstream-${libShortHash(libraryId)}`, runCore, 120000);
9122
+ }
9123
+ return yield* runCore;
9124
+ });
9125
+ }
9126
+ // packages/core/src/edit/batch-commands.ts
9127
+ import * as fsp8 from "node:fs/promises";
9128
+ import * as nodePath8 from "node:path";
9129
+ import { Effect as Effect7 } from "effect";
9130
+ var UPSTREAM_SKILL_CONCURRENCY2 = 3;
9131
+ function buildExcludeSet(exclude) {
9132
+ const set = new Set;
9133
+ for (const raw of exclude ?? []) {
9134
+ for (const part of raw.split(",")) {
9135
+ const trimmed = part.trim();
9136
+ if (!trimmed)
9137
+ continue;
9138
+ set.add(trimmed.toLowerCase());
9139
+ const slug = normalizeSkillSlug(trimmed);
9140
+ if (slug)
9141
+ set.add(slug);
9142
+ }
9143
+ }
9144
+ return set;
9145
+ }
9146
+ function matchesExclude(excludeSet, candidates) {
9147
+ if (excludeSet.size === 0)
9148
+ return false;
9149
+ for (const raw of candidates) {
9150
+ if (!raw)
9151
+ continue;
9152
+ const trimmed = raw.trim();
9153
+ if (!trimmed)
9154
+ continue;
9155
+ if (excludeSet.has(trimmed.toLowerCase()))
9156
+ return true;
9157
+ const slug = normalizeSkillSlug(trimmed);
9158
+ if (slug && excludeSet.has(slug))
9159
+ return true;
9160
+ }
9161
+ return false;
9162
+ }
9163
+ async function readFrontmatterNameBestEffort(dirPath) {
9164
+ try {
9165
+ const raw = await fsp8.readFile(nodePath8.join(dirPath, "SKILL.md"), "utf8");
9166
+ const parsed = parseSkillFrontmatter(raw);
9167
+ return parsed.name?.trim() || undefined;
9168
+ } catch {
9169
+ return;
9170
+ }
9171
+ }
9172
+ async function isManagedExportAtPath(absDir) {
9173
+ const lst = await fsp8.lstat(absDir).catch(() => null);
9174
+ if (!lst)
9175
+ return false;
9176
+ if (lst.isSymbolicLink())
9177
+ return true;
9178
+ if (lst.isDirectory()) {
9179
+ const marker = await fsp8.stat(nodePath8.join(absDir, ".ntn-managed-copy.json")).catch(() => null);
9180
+ return Boolean(marker?.isFile());
9181
+ }
9182
+ return false;
9183
+ }
9184
+ function createNewSkillsBatchCommand(args) {
9185
+ return Effect7.gen(function* () {
9186
+ const notion = yield* NotionPort;
9187
+ const store = yield* StorePort;
9188
+ const explicitDirs = (args.dirs ?? []).map((d) => d.trim()).filter(Boolean);
9189
+ const isPending = Boolean(args.pending);
9190
+ const isDryRun = Boolean(args.dryRun);
9191
+ if (explicitDirs.length === 0 && !isPending) {
9192
+ return yield* Effect7.fail(new ConfigError({
9193
+ message: "Specify at least one skill directory <dir...> or pass --pending to discover unmanaged local skills in configured export roots."
9194
+ }));
9195
+ }
9196
+ if ((explicitDirs.length > 1 || isPending) && args.name?.trim()) {
9197
+ return yield* Effect7.fail(new ConfigError({
9198
+ message: "Cannot pass --name when creating multiple skills or using --pending."
9199
+ }));
9200
+ }
9201
+ const explicitVisibility = args.visibility ?? (args.defaultContext !== undefined ? args.defaultContext ? "always" : "manual" : undefined);
9202
+ if (isPending && !explicitVisibility) {
9203
+ return yield* Effect7.fail(new ConfigError({
9204
+ message: "--pending requires an explicit visibility tier (--visibility always|discoverable|manual, or shorthand --always / --discoverable / --manual / --default). Example: ntn-skills new --pending --always or ntn-skills new --pending --discoverable"
9205
+ }));
9206
+ }
9207
+ const excludeSet = buildExcludeSet(args.exclude);
9208
+ const { config, libraryId, binding, libState } = yield* loadTableMetadataLibrary(args.libraryId);
9209
+ const resolvedExports = yield* resolveConfiguredExports(config, store.paths.configPath);
9210
+ const realStoreRoot = yield* Effect7.promise(() => fsp8.realpath(store.paths.storeRoot).catch(() => nodePath8.resolve(store.paths.storeRoot)));
9211
+ const storePrefixes = Array.from(new Set([
9212
+ `${nodePath8.resolve(store.paths.storeRoot)}${nodePath8.sep}`,
9213
+ `${realStoreRoot}${nodePath8.sep}`
9214
+ ]));
9215
+ const exportRootEntries = yield* Effect7.promise(async () => {
9216
+ const list = [];
9217
+ for (const resolved of resolvedExports.targets) {
9218
+ const absRoot = resolveHomePath(resolved.target.dir);
9219
+ const realRoot = await fsp8.realpath(absRoot).catch(() => absRoot);
9220
+ list.push({ resolved, absRoot, realRoot });
9221
+ }
9222
+ return list;
9223
+ });
9224
+ const skipped = [];
9225
+ const candidateDirs = [];
9226
+ const seenCanonicalPaths = new Set;
9227
+ const canonicalizePath = async (p) => {
9228
+ const abs = nodePath8.resolve(p);
9229
+ const real = await fsp8.realpath(abs).catch(() => abs);
9230
+ return real;
9231
+ };
9232
+ for (const rawDir of explicitDirs) {
9233
+ const absDir = resolveHomePath(rawDir);
9234
+ const canon = yield* Effect7.promise(() => canonicalizePath(absDir));
9235
+ if (seenCanonicalPaths.has(canon))
9236
+ continue;
9237
+ seenCanonicalPaths.add(canon);
9238
+ const dirName = nodePath8.basename(absDir);
9239
+ const fmName = yield* Effect7.promise(() => readFrontmatterNameBestEffort(absDir));
9240
+ if (matchesExclude(excludeSet, [dirName, fmName])) {
9241
+ skipped.push({
9242
+ dir: absDir,
9243
+ name: fmName ?? dirName,
9244
+ reason: "excluded"
9245
+ });
9246
+ continue;
9247
+ }
9248
+ candidateDirs.push(absDir);
9249
+ }
9250
+ if (isPending) {
9251
+ const seenEntryPaths = new Set;
9252
+ for (const expEntry of exportRootEntries) {
9253
+ const entries = yield* Effect7.promise(() => fsp8.readdir(expEntry.absRoot).catch(() => []));
9254
+ for (const entryName of entries.sort()) {
9255
+ if (entryName.startsWith("."))
9256
+ continue;
9257
+ const full = nodePath8.join(expEntry.absRoot, entryName);
9258
+ if (seenEntryPaths.has(full))
9259
+ continue;
9260
+ seenEntryPaths.add(full);
9261
+ const lst = yield* Effect7.promise(() => fsp8.lstat(full).catch(() => null));
9262
+ if (!lst)
9263
+ continue;
9264
+ if (lst.isSymbolicLink()) {
9265
+ const rawLink = yield* Effect7.promise(() => fsp8.readlink(full).catch(() => ""));
9266
+ const resolvedLink = nodePath8.resolve(expEntry.absRoot, rawLink);
9267
+ const realResolvedLink = yield* Effect7.promise(() => fsp8.realpath(resolvedLink).catch(() => resolvedLink));
9268
+ if (storePrefixes.some((pref) => resolvedLink.startsWith(pref) || realResolvedLink.startsWith(pref))) {
9269
+ continue;
9270
+ }
9271
+ if (!args.includeSymlinks) {
9272
+ skipped.push({
9273
+ dir: full,
9274
+ name: entryName,
9275
+ reason: "external_symlink",
9276
+ target: rawLink
9277
+ });
9278
+ continue;
9279
+ }
9280
+ const targetStat = yield* Effect7.promise(() => fsp8.stat(full).catch(() => null));
9281
+ if (!targetStat?.isDirectory()) {
9282
+ skipped.push({
9283
+ dir: full,
9284
+ name: entryName,
9285
+ reason: "not_a_directory",
9286
+ target: rawLink
9287
+ });
9288
+ continue;
9289
+ }
9290
+ } else if (lst.isDirectory()) {
9291
+ const managedMarker = yield* Effect7.promise(() => fsp8.stat(nodePath8.join(full, ".ntn-managed-copy.json")).catch(() => null));
9292
+ if (managedMarker?.isFile()) {
9293
+ continue;
9294
+ }
9295
+ } else {
9296
+ continue;
9297
+ }
9298
+ const canon = yield* Effect7.promise(() => canonicalizePath(full));
9299
+ if (seenCanonicalPaths.has(canon))
9300
+ continue;
9301
+ seenCanonicalPaths.add(canon);
9302
+ const skillMdStat = yield* Effect7.promise(() => fsp8.stat(nodePath8.join(full, "SKILL.md")).catch(() => null));
9303
+ if (!skillMdStat?.isFile()) {
9304
+ skipped.push({
9305
+ dir: full,
9306
+ name: entryName,
9307
+ reason: "missing_skill_md"
9308
+ });
9309
+ continue;
9310
+ }
9311
+ const fmName = yield* Effect7.promise(() => readFrontmatterNameBestEffort(full));
9312
+ if (matchesExclude(excludeSet, [entryName, fmName])) {
9313
+ skipped.push({
9314
+ dir: full,
9315
+ name: fmName ?? entryName,
9316
+ reason: "excluded"
9317
+ });
9318
+ continue;
9319
+ }
9320
+ candidateDirs.push(full);
9321
+ }
9322
+ }
9323
+ }
9324
+ const activeByKey = new Map;
9325
+ const registerActiveSkill = (id, name) => {
9326
+ activeByKey.set(name.toLowerCase(), { id, name });
9327
+ const slug = normalizeSkillSlug(name);
9328
+ if (slug)
9329
+ activeByKey.set(`slug:${slug}`, { id, name });
9330
+ };
9331
+ for (const sk of Object.values(libState.skills)) {
9332
+ if (sk.enabled) {
9333
+ registerActiveSkill(sk.id, sk.name);
9334
+ }
9335
+ }
9336
+ const sourcesById = new Map(Object.entries(libState.sources));
9337
+ const existingEffectiveSkills = filterEffectiveSkills(Object.values(libState.skills), sourcesById);
9338
+ const profiles = args.profiles?.length ? [...args.profiles] : ["default"];
9339
+ const scenes = args.scenes ? [...args.scenes] : [];
9340
+ const kind = args.kind ?? "skill";
9341
+ const findMatchingExportRoots = async (absDir) => {
9342
+ const lst = await fsp8.lstat(absDir).catch(() => null);
9343
+ if (!lst || lst.isSymbolicLink())
9344
+ return [];
9345
+ const parentAbs = nodePath8.dirname(absDir);
9346
+ const parentReal = await fsp8.realpath(parentAbs).catch(() => parentAbs);
9347
+ return exportRootEntries.filter((e) => parentAbs === e.absRoot || parentReal === e.realRoot);
9348
+ };
9349
+ const predictExportAtSourcePath = (matchingRoots, skillName, description, visibility) => {
9350
+ if (matchingRoots.length === 0)
9351
+ return false;
9352
+ const syntheticId = `__planned__:${skillName}`;
9353
+ const syntheticSkill = {
9354
+ id: syntheticId,
9355
+ name: skillName,
9356
+ description,
9357
+ enabled: true,
9358
+ visibility,
9359
+ kind,
9360
+ profiles,
9361
+ scenes,
9362
+ requiresIds: [],
9363
+ originSourceId: null,
9364
+ sourcePath: "",
9365
+ customMain: false,
9366
+ revision: "",
9367
+ previewHash: "",
9368
+ lastEditedTime: new Date().toISOString()
9369
+ };
9370
+ const allEffective = [...existingEffectiveSkills, syntheticSkill];
9371
+ const catSkills = filterCatalogSkills(allEffective, config.profiles);
9372
+ for (const rootEntry of matchingRoots) {
9373
+ const sel = resolveExportSelection({
9374
+ allEffectiveSkills: allEffective,
9375
+ catalogSkills: catSkills,
9376
+ target: rootEntry.resolved.target,
9377
+ bundles: rootEntry.resolved.bundles
9378
+ });
9379
+ if (sel.selected.some((s) => s.id === syntheticId)) {
9380
+ return true;
9381
+ }
9382
+ }
9383
+ return false;
9384
+ };
9385
+ const created = [];
9386
+ const failed = [];
9387
+ const createdSkillIds = [];
9388
+ const createdFileIds = [];
9389
+ for (const absDir of candidateDirs) {
9390
+ const fallbackName = nodePath8.basename(absDir);
9391
+ const scanRes = yield* Effect7.tryPromise({
9392
+ try: () => scanLocalSkillDirectory(absDir),
9393
+ catch: (e) => new StoreError({
9394
+ path: absDir,
9395
+ message: `Cannot read skill directory ${absDir}: ${String(e)}`
9396
+ })
9397
+ }).pipe(Effect7.result);
9398
+ if (scanRes._tag === "Failure") {
9399
+ failed.push({
9400
+ dir: absDir,
9401
+ name: fallbackName,
9402
+ blocked: false,
9403
+ blockedFiles: [],
9404
+ conflict: false,
9405
+ code: scanRes.failure._tag,
9406
+ error: scanRes.failure.message
9407
+ });
9408
+ continue;
9409
+ }
9410
+ const scan = scanRes.success;
9411
+ const mainFile = scan.files.get("SKILL.md");
9412
+ const rawMain = mainFile ? new TextDecoder().decode(mainFile.bytes) : "";
9413
+ const parsed = mainFile ? parseSkillFrontmatter(rawMain) : null;
9414
+ const explicitName = explicitDirs.length === 1 && !isPending ? args.name?.trim() : undefined;
9415
+ const skillName = explicitName ? normalizeSkillSlug(explicitName) : resolveCanonicalSkillName(parsed?.name, fallbackName);
9416
+ const resolvedVisibility = explicitVisibility ?? (parsed?.disableModelInvocation ? "manual" : "discoverable");
9417
+ if (scan.blockedFiles.length > 0) {
9418
+ failed.push({
9419
+ dir: absDir,
9420
+ name: skillName || fallbackName,
9421
+ visibility: resolvedVisibility,
9422
+ fileCount: scan.fileCount,
9423
+ totalBytes: scan.totalBytes,
9424
+ blocked: true,
9425
+ blockedFiles: scan.blockedFiles,
9426
+ conflict: false,
9427
+ code: "sensitive_files",
9428
+ error: formatBlockedFilesMessage(absDir, scan.blockedFiles)
9429
+ });
9430
+ continue;
9431
+ }
9432
+ if (!mainFile || !parsed) {
9433
+ failed.push({
9434
+ dir: absDir,
9435
+ name: fallbackName,
9436
+ visibility: resolvedVisibility,
9437
+ fileCount: scan.fileCount,
9438
+ totalBytes: scan.totalBytes,
9439
+ blocked: false,
9440
+ blockedFiles: [],
9441
+ conflict: false,
9442
+ code: "missing_skill_md",
9443
+ error: `Missing SKILL.md in ${absDir}.`
9444
+ });
9445
+ continue;
9446
+ }
9447
+ if (!skillName || !isValidSkillSlug(skillName)) {
9448
+ failed.push({
9449
+ dir: absDir,
9450
+ name: skillName || null,
9451
+ visibility: resolvedVisibility,
9452
+ fileCount: scan.fileCount,
9453
+ totalBytes: scan.totalBytes,
9454
+ blocked: false,
9455
+ blockedFiles: [],
9456
+ conflict: false,
9457
+ code: "invalid_skill_name",
9458
+ error: `Skill name for ${absDir} must form a lowercase hyphenated English slug (a-z, 0-9, -).`
9459
+ });
9460
+ continue;
9461
+ }
9462
+ const dup = activeByKey.get(skillName.toLowerCase()) ?? activeByKey.get(`slug:${normalizeSkillSlug(skillName)}`);
9463
+ if (dup) {
9464
+ failed.push({
9465
+ dir: absDir,
9466
+ name: skillName,
9467
+ visibility: resolvedVisibility,
9468
+ fileCount: scan.fileCount,
9469
+ totalBytes: scan.totalBytes,
9470
+ blocked: false,
9471
+ blockedFiles: [],
9472
+ conflict: true,
9473
+ conflictSkillId: dup.id,
9474
+ code: "duplicate_name",
9475
+ error: `Skill '${skillName}' already exists (${dup.id}). Use 'ntn-skills push "${absDir}" --overwrite' (or 'ntn-skills edit "${dup.name}"') instead.`
9476
+ });
9477
+ continue;
9478
+ }
9479
+ const preparedSupporting = [];
9480
+ let encodeErr = null;
9481
+ for (const [relPath, f] of scan.files) {
9482
+ if (relPath === "SKILL.md")
9483
+ continue;
9484
+ const enc = yield* encodeSupportingFileEffect(f.bytes, relPath).pipe(Effect7.result);
9485
+ if (enc._tag === "Failure") {
9486
+ encodeErr = enc.failure.message;
9487
+ break;
9488
+ }
9489
+ preparedSupporting.push({
9490
+ relPath,
9491
+ sha256: sha256Hex(f.bytes),
9492
+ executable: f.executable,
9493
+ textContent: enc.success
9494
+ });
9495
+ }
9496
+ if (encodeErr) {
9497
+ failed.push({
9498
+ dir: absDir,
9499
+ name: skillName,
9500
+ visibility: resolvedVisibility,
9501
+ fileCount: scan.fileCount,
9502
+ totalBytes: scan.totalBytes,
9503
+ blocked: false,
9504
+ blockedFiles: [],
9505
+ conflict: false,
9506
+ code: "invalid_supporting_file",
9507
+ error: encodeErr
9508
+ });
9509
+ continue;
9510
+ }
9511
+ const matchingExportRoots = yield* Effect7.promise(() => findMatchingExportRoots(absDir));
9512
+ const isInExportRoot = matchingExportRoots.length > 0;
9513
+ const willAdopt = args.adopt === undefined ? isInExportRoot : args.adopt;
9514
+ const willExportAtSourcePath = willAdopt && isInExportRoot && predictExportAtSourcePath(matchingExportRoots, skillName, (parsed.description ?? "").trim(), resolvedVisibility);
9515
+ if (isDryRun) {
9516
+ registerActiveSkill(`planned:${absDir}`, skillName);
9517
+ created.push({
9518
+ dir: absDir,
9519
+ skillId: null,
9520
+ name: skillName,
9521
+ visibility: resolvedVisibility,
9522
+ kind,
9523
+ fileCount: scan.fileCount,
9524
+ uploadedFiles: preparedSupporting.length,
9525
+ totalBytes: scan.totalBytes,
9526
+ blocked: false,
9527
+ blockedFiles: [],
9528
+ conflict: false,
9529
+ adoptedSourceDir: false,
9530
+ adoptedFromExportRoot: false,
9531
+ exportedAtSourcePath: false,
9532
+ willAdopt,
9533
+ willExportAtSourcePath
9534
+ });
9535
+ continue;
9536
+ }
9537
+ const uploadRes = yield* Effect7.gen(function* () {
9538
+ const createdPage = yield* notion.createSkillPage({
9539
+ libraryId,
9540
+ skillsDs: binding.skills_ds,
9541
+ name: skillName,
9542
+ description: (parsed.description ?? "").trim(),
9543
+ enabled: true,
9544
+ visibility: resolvedVisibility,
9545
+ kind,
9546
+ profiles,
9547
+ scenes,
9548
+ requiresIds: [],
9549
+ originSourceId: null,
9550
+ sourcePath: "",
9551
+ customMain: false,
9552
+ revision: makeRevisionStamp(),
9553
+ previewHash: "",
9554
+ markdownBody: rawMain
9555
+ });
9556
+ const uploadedIds = yield* Effect7.forEach(preparedSupporting, (sf) => notion.upsertFilePage({
9557
+ libraryId,
9558
+ filesDs: binding.files_ds,
9559
+ existingPageId: null,
9560
+ skillId: createdPage.id,
9561
+ path: sf.relPath,
9562
+ status: "override",
9563
+ externalUrl: "",
9564
+ sha256: sf.sha256,
9565
+ executable: sf.executable,
9566
+ textContent: sf.textContent
9567
+ }).pipe(Effect7.map((up) => up.pageId)), { concurrency: UPSTREAM_SKILL_CONCURRENCY2 });
9568
+ return { skillId: createdPage.id, fileIds: uploadedIds };
9569
+ }).pipe(Effect7.result);
9570
+ if (uploadRes._tag === "Failure") {
9571
+ const err = uploadRes.failure;
9572
+ failed.push({
9573
+ dir: absDir,
9574
+ name: skillName,
9575
+ visibility: resolvedVisibility,
9576
+ fileCount: scan.fileCount,
9577
+ totalBytes: scan.totalBytes,
9578
+ blocked: false,
9579
+ blockedFiles: [],
9580
+ conflict: err._tag === "ConflictError" && err.kind === "duplicate_name",
9581
+ code: err._tag,
9582
+ error: err.message
9583
+ });
9584
+ continue;
9585
+ }
9586
+ const { skillId, fileIds } = uploadRes.success;
9587
+ registerActiveSkill(skillId, skillName);
9588
+ createdSkillIds.push(skillId);
9589
+ createdFileIds.push(...fileIds);
9590
+ let adoptedSourceDir = false;
9591
+ if (willAdopt) {
9592
+ const trashRes = yield* trashPathEffect(absDir).pipe(Effect7.result);
9593
+ if (trashRes._tag === "Success") {
9594
+ adoptedSourceDir = true;
9595
+ }
9596
+ }
9597
+ created.push({
9598
+ dir: absDir,
9599
+ skillId,
9600
+ name: skillName,
9601
+ visibility: resolvedVisibility,
9602
+ kind,
9603
+ fileCount: scan.fileCount,
9604
+ uploadedFiles: fileIds.length,
9605
+ totalBytes: scan.totalBytes,
9606
+ blocked: false,
9607
+ blockedFiles: [],
9608
+ conflict: false,
9609
+ adoptedSourceDir,
9610
+ adoptedFromExportRoot: adoptedSourceDir && isInExportRoot,
9611
+ exportedAtSourcePath: false,
9612
+ willAdopt,
9613
+ willExportAtSourcePath
9614
+ });
9615
+ }
9616
+ let synced = false;
9617
+ if (!isDryRun && created.length > 0) {
9618
+ yield* syncCommand({
9619
+ libraryId,
9620
+ dedupeWindowMs: 0,
9621
+ readYourWrites: { skillIds: createdSkillIds, fileIds: createdFileIds }
9622
+ });
9623
+ synced = true;
9624
+ for (const item of created) {
9625
+ if (item.adoptedSourceDir && item.adoptedFromExportRoot) {
9626
+ item.exportedAtSourcePath = yield* Effect7.promise(() => isManagedExportAtPath(item.dir));
9627
+ }
9628
+ }
9629
+ }
9630
+ return {
9631
+ dryRun: isDryRun,
9632
+ created,
9633
+ skipped,
9634
+ failed,
9635
+ synced
9636
+ };
9637
+ });
9638
+ }
9639
+ function pushWorkdirsBatchCommand(args) {
9640
+ return Effect7.gen(function* () {
9641
+ const store = yield* StorePort;
9642
+ const explicitDirs = (args.dirs ?? []).map((d) => d.trim()).filter(Boolean);
9643
+ const isPending = Boolean(args.pending);
9644
+ const isDryRun = Boolean(args.dryRun);
9645
+ if (explicitDirs.length === 0 && !isPending) {
9646
+ return yield* Effect7.fail(new ConfigError({
9647
+ message: "Specify at least one edit workdir <dir...> or pass --pending to push all open workdirs."
9648
+ }));
9649
+ }
9650
+ const excludeSet = buildExcludeSet(args.exclude);
9651
+ const { libraryId: resolvedLibId } = yield* loadResolvedLibrary(args.libraryId);
9652
+ const skipped = [];
9653
+ const candidates = [];
9654
+ const seenAbsDirs = new Set;
9655
+ const inspectWorkdirMetaSkillName = async (dirPath) => {
9656
+ try {
9657
+ const raw = JSON.parse(await fsp8.readFile(nodePath8.join(dirPath, ".ntn-skill.json"), "utf8"));
9658
+ return raw?.skillName ? String(raw.skillName) : null;
9659
+ } catch {
9660
+ return null;
9661
+ }
9662
+ };
9663
+ for (const rawDir of explicitDirs) {
9664
+ const absDir = resolveHomePath(rawDir);
9665
+ if (seenAbsDirs.has(absDir))
9666
+ continue;
9667
+ seenAbsDirs.add(absDir);
9668
+ const hintSkillName = yield* Effect7.promise(() => inspectWorkdirMetaSkillName(absDir));
9669
+ if (matchesExclude(excludeSet, [nodePath8.basename(absDir), hintSkillName ?? undefined])) {
9670
+ skipped.push({ workdir: absDir, skillName: hintSkillName, reason: "excluded" });
9671
+ continue;
9672
+ }
9673
+ candidates.push({ dir: absDir, hintSkillName });
9674
+ }
9675
+ if (isPending) {
9676
+ const workEntries = yield* Effect7.promise(() => fsp8.readdir(store.paths.workRoot).catch(() => []));
9677
+ for (const name of workEntries.sort()) {
9678
+ if (name.startsWith("."))
9679
+ continue;
9680
+ const full = nodePath8.join(store.paths.workRoot, name);
9681
+ const rawMeta = yield* Effect7.promise(async () => {
9682
+ try {
9683
+ return JSON.parse(await fsp8.readFile(nodePath8.join(full, ".ntn-skill.json"), "utf8"));
9684
+ } catch {
9685
+ return null;
9686
+ }
9687
+ });
9688
+ if (!rawMeta)
9689
+ continue;
9690
+ if (rawMeta.libraryId && normalizeUuid(String(rawMeta.libraryId)) !== resolvedLibId) {
9691
+ continue;
9692
+ }
9693
+ if (seenAbsDirs.has(full))
9694
+ continue;
9695
+ seenAbsDirs.add(full);
9696
+ const skillName = rawMeta.skillName ? String(rawMeta.skillName) : name;
9697
+ if (matchesExclude(excludeSet, [name, skillName])) {
9698
+ skipped.push({ workdir: full, skillName, reason: "excluded" });
9699
+ continue;
9700
+ }
9701
+ candidates.push({ dir: full, hintSkillName: skillName });
9702
+ }
9703
+ }
9704
+ const pushedResults = [];
9705
+ const failed = [];
9706
+ for (const cand of candidates) {
9707
+ const res = yield* pushSingleWorkdirInternal({
9708
+ workdir: cand.dir,
9709
+ ...isDryRun ? { dryRun: true } : {},
9710
+ ...args.force ? { force: true } : {},
9711
+ deferSyncAndTrash: true
9712
+ }).pipe(Effect7.result);
9713
+ if (res._tag === "Failure") {
9714
+ const err = res.failure;
9715
+ const details = err._tag === "ConflictError" && err.details ? err.details : undefined;
9716
+ failed.push({
9717
+ workdir: cand.dir,
9718
+ skillName: cand.hintSkillName,
9719
+ code: err._tag === "ConflictError" ? err.kind : err._tag,
9720
+ error: err.message,
9721
+ ...details ? { details } : {}
9722
+ });
9723
+ continue;
9724
+ }
9725
+ pushedResults.push({
9726
+ internal: res.success,
9727
+ report: res.success.report
9728
+ });
9729
+ }
9730
+ let synced = false;
9731
+ if (!isDryRun && pushedResults.length > 0) {
9732
+ const rywByLib = new Map;
9733
+ for (const item of pushedResults) {
9734
+ if (!item.internal.wroteRemote)
9735
+ continue;
9736
+ const bucket = rywByLib.get(item.internal.libraryId) ?? {
9737
+ skillIds: new Set,
9738
+ fileIds: new Set,
9739
+ archivedFileIds: new Set
9740
+ };
9741
+ bucket.skillIds.add(item.internal.skillId);
9742
+ for (const fid of item.internal.touchedFileIds)
9743
+ bucket.fileIds.add(fid);
9744
+ for (const aid of item.internal.archivedFileIds)
9745
+ bucket.archivedFileIds.add(aid);
9746
+ rywByLib.set(item.internal.libraryId, bucket);
9747
+ }
9748
+ for (const [libId, bucket] of rywByLib) {
8361
9749
  yield* syncCommand({
8362
- libraryId,
9750
+ libraryId: libId,
8363
9751
  dedupeWindowMs: 0,
8364
9752
  readYourWrites: {
8365
- sourceIds: rywSourceIds,
8366
- skillIds: rywSkillIds,
8367
- archivedFileIds: rywArchivedFileIds
9753
+ skillIds: [...bucket.skillIds],
9754
+ fileIds: [...bucket.fileIds],
9755
+ archivedFileIds: [...bucket.archivedFileIds]
8368
9756
  }
8369
9757
  });
9758
+ synced = true;
8370
9759
  }
8371
- const finishedMs = Date.now();
8372
- const permanentFailures = failed - retryableFailures;
8373
- const recommendedExitCode = permanentFailures > 0 ? 2 : retryableFailures > 0 || skippedDeadline > 0 ? 75 : args.strictDrift && driftWarningsCount > 0 ? 3 : 0;
8374
- const report = {
8375
- libraryId,
8376
- mode: !args.apply ? "check" : args.dryRun ? "dry-run" : "apply",
8377
- startedAt,
8378
- finishedAt: new Date(finishedMs).toISOString(),
8379
- durationMs: Math.max(0, finishedMs - startedMs),
8380
- totalCandidates: candidateSources.length,
8381
- checked,
8382
- upToDate,
8383
- updateAvailable,
8384
- applied,
8385
- skippedLimit,
8386
- skippedDeadline,
8387
- driftWarningsCount,
8388
- failed,
8389
- retryableFailures,
8390
- recommendedExitCode,
8391
- sources: sourcesOut
9760
+ for (const item of pushedResults) {
9761
+ if (item.internal.shouldTrash) {
9762
+ yield* trashPathEffect(item.report.workdir);
9763
+ item.report = { ...item.report, workdirCleaned: true };
9764
+ }
9765
+ }
9766
+ }
9767
+ return {
9768
+ dryRun: isDryRun,
9769
+ pushed: pushedResults.map((p) => p.report),
9770
+ skipped,
9771
+ failed,
9772
+ synced
9773
+ };
9774
+ });
9775
+ }
9776
+ function pushOverwriteDirectoryCommand(args) {
9777
+ return Effect7.gen(function* () {
9778
+ const notion = yield* NotionPort;
9779
+ const store = yield* StorePort;
9780
+ const upstream = yield* UpstreamPort;
9781
+ const absDir = resolveHomePath(args.dir);
9782
+ const isDryRun = Boolean(args.dryRun);
9783
+ const dirStat = yield* Effect7.tryPromise({
9784
+ try: () => fsp8.stat(absDir),
9785
+ catch: () => new NotFoundError({
9786
+ entity: "workdir",
9787
+ target: absDir,
9788
+ message: `Local skill directory not found: ${absDir}`
9789
+ })
9790
+ });
9791
+ if (!dirStat.isDirectory()) {
9792
+ return yield* Effect7.fail(new ConfigError({
9793
+ path: absDir,
9794
+ message: `Target path is not a directory: ${absDir}`
9795
+ }));
9796
+ }
9797
+ const existingMeta = yield* readWorkMeta(absDir).pipe(Effect7.catchTag("NotFoundError", () => Effect7.succeed(null)));
9798
+ if (existingMeta && args.toSkillName?.trim()) {
9799
+ const requested = args.toSkillName.trim();
9800
+ const metaName = existingMeta.skillName;
9801
+ const sameName = metaName.toLowerCase() === requested.toLowerCase() || normalizeSkillSlug(metaName) === normalizeSkillSlug(requested);
9802
+ if (!sameName) {
9803
+ return yield* Effect7.fail(new ConfigError({
9804
+ path: absDir,
9805
+ message: `Directory '${absDir}' is an edit workdir for '${metaName}', which does not match --to '${requested}'. Refusing to push to a different skill.`
9806
+ }));
9807
+ }
9808
+ }
9809
+ const scan = yield* Effect7.tryPromise({
9810
+ try: () => scanLocalSkillDirectory(absDir),
9811
+ catch: (e) => new StoreError({
9812
+ path: absDir,
9813
+ message: `Cannot read skill directory ${absDir}: ${String(e)}`
9814
+ })
9815
+ });
9816
+ const mainFile = scan.files.get("SKILL.md");
9817
+ if (!mainFile) {
9818
+ if (scan.blockedFiles.length > 0 && !isDryRun) {
9819
+ yield* assertNoBlockedSkillFiles(scan);
9820
+ }
9821
+ return yield* Effect7.fail(new ConfigError({
9822
+ path: absDir,
9823
+ message: `Missing SKILL.md in ${absDir}.`
9824
+ }));
9825
+ }
9826
+ const localRawMain = new TextDecoder().decode(mainFile.bytes);
9827
+ const parsedLocal = parseSkillFrontmatter(localRawMain);
9828
+ const targetQuery = (args.toSkillName?.trim() || parsedLocal.name?.trim() || "").trim();
9829
+ if (!targetQuery) {
9830
+ return yield* Effect7.fail(new ConfigError({
9831
+ path: absDir,
9832
+ message: `Cannot determine target skill name: SKILL.md frontmatter is missing 'name' and --to was not specified.`
9833
+ }));
9834
+ }
9835
+ const { libraryId, binding, libState } = yield* loadTableMetadataLibrary(args.libraryId);
9836
+ const activeSkills = Object.values(libState.skills).filter((s) => s.enabled);
9837
+ const queryLower = targetQuery.toLowerCase();
9838
+ const querySlug = normalizeSkillSlug(targetQuery);
9839
+ const exactMatches = activeSkills.filter((s) => s.name.toLowerCase() === queryLower);
9840
+ let targetSkill = exactMatches[0];
9841
+ if (!targetSkill && querySlug) {
9842
+ const slugMatches = activeSkills.filter((s) => normalizeSkillSlug(s.name) === querySlug);
9843
+ if (slugMatches.length > 1) {
9844
+ return yield* Effect7.fail(new ConflictError({
9845
+ kind: "duplicate_name",
9846
+ message: `Multiple active skills match slug '${querySlug}' (${slugMatches.map((s) => s.name).join(", ")}); specify the exact canonical name with --to.`
9847
+ }));
9848
+ }
9849
+ targetSkill = slugMatches[0];
9850
+ }
9851
+ if (!targetSkill) {
9852
+ return yield* Effect7.fail(new NotFoundError({
9853
+ entity: "skill",
9854
+ target: targetQuery,
9855
+ message: `Active skill '${targetQuery}' not found in Notion library ${libraryId}. Use 'ntn-skills new "${absDir}"' to create a new skill.`
9856
+ }));
9857
+ }
9858
+ if (scan.blockedFiles.length > 0) {
9859
+ if (!isDryRun) {
9860
+ yield* assertNoBlockedSkillFiles(scan);
9861
+ }
9862
+ return {
9863
+ dir: absDir,
9864
+ targetSkillId: targetSkill.id,
9865
+ targetSkillName: targetSkill.name,
9866
+ overwrite: true,
9867
+ dryRun: true,
9868
+ descriptionChanged: null,
9869
+ willSetCustomMain: false,
9870
+ updatedMain: false,
9871
+ updatedFiles: 0,
9872
+ items: [],
9873
+ newRevision: null,
9874
+ workdirCleaned: false,
9875
+ sourceDirPreserved: true,
9876
+ blocked: true,
9877
+ blockedFiles: scan.blockedFiles
8392
9878
  };
8393
- if (args.reportFile) {
8394
- const outPath = resolveHomePath(args.reportFile);
8395
- yield* Effect5.tryPromise({
8396
- try: () => atomicWriteJson(outPath, report),
8397
- catch: (e) => new StoreError({
8398
- path: outPath,
8399
- message: `Failed writing upstream report to ${outPath}: ${String(e)}`
8400
- })
9879
+ }
9880
+ const runOverwrite = Effect7.gen(function* () {
9881
+ const liveSkill = yield* notion.getSkillRecord(targetSkill.id);
9882
+ if (!liveSkill || !liveSkill.enabled) {
9883
+ return yield* Effect7.fail(new NotFoundError({
9884
+ entity: "skill",
9885
+ target: targetSkill.name,
9886
+ message: `Skill '${targetSkill.name}' is disabled or archived in Notion.`
9887
+ }));
9888
+ }
9889
+ const [liveFiles, liveBody] = yield* Effect7.all([
9890
+ notion.getSkillFiles({ filesDs: binding.files_ds, skillId: liveSkill.id }),
9891
+ notion.readSkillBody(liveSkill.id)
9892
+ ]);
9893
+ const src = liveSkill.originSourceId ? libState.sources[liveSkill.originSourceId] ?? null : null;
9894
+ const remoteEffectiveFiles = new Map;
9895
+ const upstreamShaByPath = new Map;
9896
+ const existingOverlayByPath = new Map;
9897
+ let upstreamMainMd = "";
9898
+ if (src) {
9899
+ const pinnedCommit = src.pinnedCommit || (yield* upstream.resolveHeadCommit(src.repoUrl, src.ref));
9900
+ const sub = yield* upstream.fetchSubtree({
9901
+ repoUrl: src.repoUrl,
9902
+ commitSha: pinnedCommit,
9903
+ sourcePath: liveSkill.sourcePath || "."
8401
9904
  });
9905
+ for (const f of sub) {
9906
+ if (f.path === "SKILL.md") {
9907
+ upstreamMainMd = new TextDecoder().decode(f.bytes);
9908
+ } else {
9909
+ const upSha = sha256Hex(f.bytes);
9910
+ upstreamShaByPath.set(f.path, upSha);
9911
+ remoteEffectiveFiles.set(f.path, {
9912
+ pageId: null,
9913
+ sha256: upSha,
9914
+ upstreamSha256: upSha,
9915
+ executable: f.executable,
9916
+ origin: "upstream",
9917
+ externalUrl: ""
9918
+ });
9919
+ }
9920
+ }
8402
9921
  }
8403
- return report;
9922
+ for (const ov of normalizeOverlayFiles(liveFiles)) {
9923
+ existingOverlayByPath.set(ov.path, ov);
9924
+ if (ov.status === "delete") {
9925
+ remoteEffectiveFiles.delete(ov.path);
9926
+ continue;
9927
+ }
9928
+ const bytes = yield* resolveOverlayBytes(ov);
9929
+ const exec = ov.executable || ov.path.toLowerCase().endsWith(".sh");
9930
+ const upSha = ov.baseSha256 ?? upstreamShaByPath.get(ov.path);
9931
+ remoteEffectiveFiles.set(ov.path, {
9932
+ pageId: ov.id,
9933
+ sha256: sha256Hex(bytes),
9934
+ ...upSha ? { upstreamSha256: upSha } : {},
9935
+ executable: exec,
9936
+ origin: src ? "override" : "native",
9937
+ externalUrl: ov.externalUrl
9938
+ });
9939
+ }
9940
+ const rawRemoteMain = !src || liveSkill.customMain ? liveBody.rawMarkdown : upstreamMainMd;
9941
+ const remoteAuthoritativeMain = applyAuthoritativeFrontmatter(rawRemoteMain, liveSkill.name, liveSkill.description);
9942
+ const nextDescription = parsedLocal.description !== undefined ? parsedLocal.description : liveSkill.description;
9943
+ const descriptionChanged = parsedLocal.description !== undefined && parsedLocal.description !== liveSkill.description ? { from: liveSkill.description, to: parsedLocal.description } : null;
9944
+ const localAuthoritativeMain = applyAuthoritativeFrontmatter(localRawMain, liveSkill.name, nextDescription);
9945
+ const localMainSha = sha256Hex(localAuthoritativeMain);
9946
+ const remoteMainSha = sha256Hex(remoteAuthoritativeMain);
9947
+ const updatedMain = localMainSha !== remoteMainSha;
9948
+ const willSetCustomMain = Boolean(liveSkill.originSourceId && updatedMain && !liveSkill.customMain);
9949
+ const items = [];
9950
+ if (updatedMain) {
9951
+ items.push({
9952
+ path: "SKILL.md",
9953
+ change: "modified",
9954
+ plannedAction: "update_skill_main",
9955
+ executable: false,
9956
+ sha256: localMainSha
9957
+ });
9958
+ }
9959
+ const allSubPaths = new Set([...remoteEffectiveFiles.keys(), ...scan.files.keys()]);
9960
+ allSubPaths.delete("SKILL.md");
9961
+ for (const relPath of [...allSubPaths].sort()) {
9962
+ const remote = remoteEffectiveFiles.get(relPath);
9963
+ const local = scan.files.get(relPath);
9964
+ if (!remote && local) {
9965
+ items.push({
9966
+ path: relPath,
9967
+ change: "added",
9968
+ plannedAction: "upsert_file_override",
9969
+ executable: local.executable,
9970
+ sha256: sha256Hex(local.bytes)
9971
+ });
9972
+ } else if (remote && !local) {
9973
+ const needsDeleteTombstone = Boolean(liveSkill.originSourceId && (upstreamShaByPath.has(relPath) || remote.origin === "upstream"));
9974
+ items.push({
9975
+ path: relPath,
9976
+ change: "deleted",
9977
+ plannedAction: needsDeleteTombstone ? "upsert_file_delete_overlay" : "archive_native_file",
9978
+ executable: false
9979
+ });
9980
+ } else if (remote && local) {
9981
+ const curSha = sha256Hex(local.bytes);
9982
+ if (curSha !== remote.sha256 || local.executable !== remote.executable) {
9983
+ items.push({
9984
+ path: relPath,
9985
+ change: "modified",
9986
+ plannedAction: "upsert_file_override",
9987
+ executable: local.executable,
9988
+ sha256: curSha
9989
+ });
9990
+ }
9991
+ }
9992
+ }
9993
+ const fileItemCount = items.filter((i) => i.path !== "SKILL.md").length;
9994
+ if (isDryRun) {
9995
+ return {
9996
+ dir: absDir,
9997
+ targetSkillId: liveSkill.id,
9998
+ targetSkillName: liveSkill.name,
9999
+ overwrite: true,
10000
+ dryRun: true,
10001
+ descriptionChanged,
10002
+ willSetCustomMain,
10003
+ updatedMain,
10004
+ updatedFiles: fileItemCount,
10005
+ items,
10006
+ newRevision: null,
10007
+ workdirCleaned: false,
10008
+ sourceDirPreserved: true,
10009
+ blocked: false,
10010
+ blockedFiles: []
10011
+ };
10012
+ }
10013
+ if (items.length === 0 && !descriptionChanged) {
10014
+ return {
10015
+ dir: absDir,
10016
+ targetSkillId: liveSkill.id,
10017
+ targetSkillName: liveSkill.name,
10018
+ overwrite: true,
10019
+ dryRun: false,
10020
+ descriptionChanged: null,
10021
+ willSetCustomMain: false,
10022
+ updatedMain: false,
10023
+ updatedFiles: 0,
10024
+ items: [],
10025
+ newRevision: null,
10026
+ workdirCleaned: false,
10027
+ sourceDirPreserved: true,
10028
+ blocked: false,
10029
+ blockedFiles: []
10030
+ };
10031
+ }
10032
+ const encodedSupporting = new Map;
10033
+ for (const item of items) {
10034
+ if (item.path === "SKILL.md" || item.plannedAction !== "upsert_file_override")
10035
+ continue;
10036
+ const localFile = scan.files.get(item.path);
10037
+ const textContent = yield* encodeSupportingFileEffect(localFile.bytes, item.path);
10038
+ encodedSupporting.set(item.path, {
10039
+ textContent,
10040
+ sha256: sha256Hex(localFile.bytes),
10041
+ file: localFile
10042
+ });
10043
+ }
10044
+ let updatedFilesCount = 0;
10045
+ const touchedFileIds = [];
10046
+ const archivedFileIds = [];
10047
+ for (const item of items) {
10048
+ if (item.path === "SKILL.md")
10049
+ continue;
10050
+ const existingOverlay = existingOverlayByPath.get(item.path);
10051
+ const remoteEntry = remoteEffectiveFiles.get(item.path);
10052
+ if (item.plannedAction === "archive_native_file") {
10053
+ const pageIdToArchive = remoteEntry?.pageId ?? existingOverlay?.id ?? null;
10054
+ if (pageIdToArchive) {
10055
+ yield* notion.archivePage({ libraryId, pageId: pageIdToArchive });
10056
+ archivedFileIds.push(pageIdToArchive);
10057
+ updatedFilesCount++;
10058
+ }
10059
+ continue;
10060
+ }
10061
+ if (item.plannedAction === "upsert_file_delete_overlay") {
10062
+ const delRes = yield* withRetryableReadback(notion.upsertFilePage({
10063
+ libraryId,
10064
+ filesDs: binding.files_ds,
10065
+ existingPageId: existingOverlay?.id ?? remoteEntry?.pageId ?? null,
10066
+ skillId: liveSkill.id,
10067
+ path: item.path,
10068
+ status: "delete",
10069
+ externalUrl: "",
10070
+ sha256: "",
10071
+ executable: false,
10072
+ textContent: ""
10073
+ }), () => notion.getSkillFiles({ filesDs: binding.files_ds, skillId: liveSkill.id }).pipe(Effect7.map((rf) => {
10074
+ const landed = rf.find((f) => f.path === item.path && f.status === "delete");
10075
+ return landed ? { pageId: landed.id } : null;
10076
+ })));
10077
+ touchedFileIds.push(delRes.pageId);
10078
+ updatedFilesCount++;
10079
+ continue;
10080
+ }
10081
+ const prepared = encodedSupporting.get(item.path);
10082
+ const baseSha256 = upstreamShaByPath.get(item.path) ?? remoteEntry?.upstreamSha256;
10083
+ const ovRes = yield* withRetryableReadback(notion.upsertFilePage({
10084
+ libraryId,
10085
+ filesDs: binding.files_ds,
10086
+ existingPageId: existingOverlay?.id ?? remoteEntry?.pageId ?? null,
10087
+ skillId: liveSkill.id,
10088
+ path: item.path,
10089
+ status: "override",
10090
+ externalUrl: "",
10091
+ sha256: prepared.sha256,
10092
+ ...baseSha256 ? { baseSha256 } : {},
10093
+ executable: prepared.file.executable,
10094
+ textContent: prepared.textContent
10095
+ }), () => Effect7.gen(function* () {
10096
+ const remoteFiles = yield* notion.getSkillFiles({
10097
+ filesDs: binding.files_ds,
10098
+ skillId: liveSkill.id
10099
+ });
10100
+ const candidate = remoteFiles.find((f) => f.path === item.path && f.status === "override");
10101
+ if (candidate && candidate.sha256 === prepared.sha256) {
10102
+ const remoteBody = yield* notion.readFileBody({
10103
+ filePageId: candidate.id,
10104
+ filePath: item.path
10105
+ });
10106
+ if (sha256Hex(decodeSupportingFilePayload(remoteBody)) === prepared.sha256) {
10107
+ return { pageId: candidate.id };
10108
+ }
10109
+ }
10110
+ return null;
10111
+ }));
10112
+ touchedFileIds.push(ovRes.pageId);
10113
+ updatedFilesCount++;
10114
+ }
10115
+ let nextPreviewHash;
10116
+ if (updatedMain) {
10117
+ const expectedPrepared = prepareSkillMarkdownForNotionBody(localRawMain).cleanNotionMarkdown;
10118
+ yield* withRetryableReadback(notion.writeSkillBody({
10119
+ libraryId,
10120
+ skillId: liveSkill.id,
10121
+ markdownBody: localRawMain,
10122
+ preserveUpstreamChild: Boolean(liveSkill.originSourceId)
10123
+ }), () => notion.readSkillBody(liveSkill.id).pipe(Effect7.map((rb) => rb.rawMarkdown.trim() === expectedPrepared.trim() ? { upstreamFilesPageId: rb.upstreamFilesPageId } : null)));
10124
+ if (liveSkill.originSourceId) {
10125
+ const afterBody = yield* notion.readSkillBody(liveSkill.id);
10126
+ nextPreviewHash = sha256Hex(afterBody.rawMarkdown);
10127
+ }
10128
+ }
10129
+ const preservedSubDigest = liveSkill.originSourceId ? extractSubtreeDigestFromRevision(liveSkill.revision) : null;
10130
+ const newRevision = makeRevisionStamp(preservedSubDigest);
10131
+ yield* notion.updateSkillProps({
10132
+ libraryId,
10133
+ skillId: liveSkill.id,
10134
+ ...descriptionChanged ? { description: descriptionChanged.to } : {},
10135
+ ...liveSkill.originSourceId && updatedMain ? { customMain: true } : {},
10136
+ ...nextPreviewHash !== undefined ? { previewHash: nextPreviewHash } : {},
10137
+ revision: newRevision
10138
+ });
10139
+ yield* syncCommand({
10140
+ libraryId,
10141
+ dedupeWindowMs: 0,
10142
+ readYourWrites: { skillIds: [liveSkill.id], fileIds: touchedFileIds, archivedFileIds }
10143
+ });
10144
+ return {
10145
+ dir: absDir,
10146
+ targetSkillId: liveSkill.id,
10147
+ targetSkillName: liveSkill.name,
10148
+ overwrite: true,
10149
+ dryRun: false,
10150
+ descriptionChanged,
10151
+ willSetCustomMain,
10152
+ updatedMain,
10153
+ updatedFiles: updatedFilesCount,
10154
+ items,
10155
+ newRevision,
10156
+ workdirCleaned: false,
10157
+ sourceDirPreserved: true,
10158
+ blocked: false,
10159
+ blockedFiles: []
10160
+ };
8404
10161
  });
8405
- if (args.apply && !args.dryRun) {
8406
- const { libraryId } = yield* loadResolvedLibrary(args.libraryId);
8407
- return yield* store.withExclusiveLock(`upstream-${libShortHash(libraryId)}`, runCore, 120000);
8408
- }
8409
- return yield* runCore;
10162
+ return isDryRun ? yield* runOverwrite : yield* store.withExclusiveLock(`push-${libraryId.slice(0, 8)}`, runOverwrite);
8410
10163
  });
8411
10164
  }
8412
10165
  // packages/core/src/runtime/runtime.ts
@@ -8426,11 +10179,11 @@ function makeCoreLiveLayer(options) {
8426
10179
  }
8427
10180
  // packages/core/src/schedule/scheduler.ts
8428
10181
  import { spawn as spawn4 } from "node:child_process";
8429
- import * as fsp7 from "node:fs/promises";
8430
- import * as os2 from "node:os";
8431
- import * as nodePath7 from "node:path";
10182
+ import * as fsp9 from "node:fs/promises";
10183
+ import * as os3 from "node:os";
10184
+ import * as nodePath9 from "node:path";
8432
10185
  import { fileURLToPath } from "node:url";
8433
- import { Effect as Effect6 } from "effect";
10186
+ import { Effect as Effect8 } from "effect";
8434
10187
  var DEFAULT_MAX_LOG_BYTES = 2 * 1024 * 1024;
8435
10188
  var LEGACY_DARWIN_LABELS = ["com.yoyo.ntn-skills-sync", "com.yoyo.ntn-skills-sync-full"];
8436
10189
  var MANAGED_UNITS = [
@@ -8453,7 +10206,7 @@ var MANAGED_UNITS = [
8453
10206
  function parseDurationSeconds(spec) {
8454
10207
  const m = spec.trim().toLowerCase().match(/^(\d+)\s*(s|m|h|d)?$/);
8455
10208
  if (!m) {
8456
- return Effect6.fail(new ConfigError({
10209
+ return Effect8.fail(new ConfigError({
8457
10210
  message: `Invalid duration '${spec}'. Expected formats like '12m', '1h', '90s', or '1d'.`
8458
10211
  }));
8459
10212
  }
@@ -8462,27 +10215,27 @@ function parseDurationSeconds(spec) {
8462
10215
  const mult = unit === "d" ? 86400 : unit === "h" ? 3600 : unit === "m" ? 60 : 1;
8463
10216
  const totalSec = value * mult;
8464
10217
  if (!Number.isSafeInteger(totalSec) || totalSec < 60) {
8465
- return Effect6.fail(new ConfigError({
10218
+ return Effect8.fail(new ConfigError({
8466
10219
  message: `Schedule interval '${spec}' (${totalSec}s) must be at least 60s.`
8467
10220
  }));
8468
10221
  }
8469
- return Effect6.succeed(totalSec);
10222
+ return Effect8.succeed(totalSec);
8470
10223
  }
8471
10224
  function parseDailyClock(spec) {
8472
10225
  const m = spec.trim().match(/^(\d{1,2}):(\d{2})$/);
8473
10226
  if (!m) {
8474
- return Effect6.fail(new ConfigError({
10227
+ return Effect8.fail(new ConfigError({
8475
10228
  message: `Invalid daily clock '${spec}'. Expected HH:MM (24-hour format, e.g. '04:12').`
8476
10229
  }));
8477
10230
  }
8478
10231
  const hour = Number(m[1]);
8479
10232
  const minute = Number(m[2]);
8480
10233
  if (hour < 0 || hour > 23 || minute < 0 || minute > 59) {
8481
- return Effect6.fail(new ConfigError({
10234
+ return Effect8.fail(new ConfigError({
8482
10235
  message: `Daily clock '${spec}' out of range (00:00..23:59).`
8483
10236
  }));
8484
10237
  }
8485
- return Effect6.succeed({
10238
+ return Effect8.succeed({
8486
10239
  hour,
8487
10240
  minute,
8488
10241
  normalized: `${String(hour).padStart(2, "0")}:${String(minute).padStart(2, "0")}`
@@ -8509,17 +10262,17 @@ function classifyErrorExitCode(err) {
8509
10262
  }
8510
10263
  }
8511
10264
  async function appendBoundedJobLog(logFile, line, maxBytes = DEFAULT_MAX_LOG_BYTES) {
8512
- await fsp7.mkdir(nodePath7.dirname(logFile), { recursive: true });
8513
- const st = await fsp7.stat(logFile).catch(() => null);
10265
+ await fsp9.mkdir(nodePath9.dirname(logFile), { recursive: true });
10266
+ const st = await fsp9.stat(logFile).catch(() => null);
8514
10267
  if (st && st.size >= maxBytes) {
8515
- await fsp7.rename(logFile, `${logFile}.1`).catch(() => {
10268
+ await fsp9.rename(logFile, `${logFile}.1`).catch(() => {
8516
10269
  return;
8517
10270
  });
8518
10271
  }
8519
10272
  const normalized = line.endsWith(`
8520
10273
  `) ? line : `${line}
8521
10274
  `;
8522
- await fsp7.appendFile(logFile, normalized, "utf8");
10275
+ await fsp9.appendFile(logFile, normalized, "utf8");
8523
10276
  }
8524
10277
  function execSubprocess(bin, args, opts) {
8525
10278
  const timeoutMs = opts?.timeoutMs ?? 30000;
@@ -8559,18 +10312,18 @@ function execSubprocess(bin, args, opts) {
8559
10312
  });
8560
10313
  }
8561
10314
  function runScheduledJobCommand(args) {
8562
- return Effect6.gen(function* () {
10315
+ return Effect8.gen(function* () {
8563
10316
  const store = yield* StorePort;
8564
- const logsDir = nodePath7.join(store.paths.homeDir, "logs");
8565
- const logFile = args.job === "upstream" ? nodePath7.join(logsDir, "upstream.log") : nodePath7.join(logsDir, "sync.log");
10317
+ const logsDir = nodePath9.join(store.paths.homeDir, "logs");
10318
+ const logFile = args.job === "upstream" ? nodePath9.join(logsDir, "upstream.log") : nodePath9.join(logsDir, "sync.log");
8566
10319
  const maxBytes = args.maxLogBytes ?? DEFAULT_MAX_LOG_BYTES;
8567
10320
  const startedMs = Date.now();
8568
10321
  const prevCaller = process.env.NTN_SKILLS_CALLER;
8569
10322
  process.env.NTN_SKILLS_CALLER = `schedule-${args.job}`;
8570
- yield* Effect6.promise(() => appendBoundedJobLog(logFile, `[${new Date(startedMs).toISOString()}] start job=${args.job}`, maxBytes).catch(() => {
10323
+ yield* Effect8.promise(() => appendBoundedJobLog(logFile, `[${new Date(startedMs).toISOString()}] start job=${args.job}`, maxBytes).catch(() => {
8571
10324
  return;
8572
10325
  }));
8573
- const outcome = yield* Effect6.gen(function* () {
10326
+ const outcome = yield* Effect8.gen(function* () {
8574
10327
  if (args.job === "sync") {
8575
10328
  const res = yield* syncCommand({
8576
10329
  ...args.libraryId ? { libraryId: args.libraryId } : {},
@@ -8606,7 +10359,7 @@ function runScheduledJobCommand(args) {
8606
10359
  summary
8607
10360
  };
8608
10361
  }
8609
- const reportFile = nodePath7.join(logsDir, "upstream-last-report.json");
10362
+ const reportFile = nodePath9.join(logsDir, "upstream-last-report.json");
8610
10363
  const rep = yield* upstreamCheckOrApplyCommand({
8611
10364
  apply: true,
8612
10365
  ...args.libraryId ? { libraryId: args.libraryId } : {},
@@ -8625,9 +10378,9 @@ function runScheduledJobCommand(args) {
8625
10378
  summary,
8626
10379
  upstreamReport: rep
8627
10380
  };
8628
- }).pipe(Effect6.catch((err) => {
10381
+ }).pipe(Effect8.catch((err) => {
8629
10382
  const code = classifyErrorExitCode(err);
8630
- return Effect6.succeed({
10383
+ return Effect8.succeed({
8631
10384
  job: args.job,
8632
10385
  ok: false,
8633
10386
  exitCode: code,
@@ -8641,44 +10394,44 @@ function runScheduledJobCommand(args) {
8641
10394
  } else {
8642
10395
  process.env.NTN_SKILLS_CALLER = prevCaller;
8643
10396
  }
8644
- yield* Effect6.promise(() => appendBoundedJobLog(logFile, `[${new Date().toISOString()}] ${outcome.ok ? "done" : "error"} job=${args.job} exit=${outcome.exitCode} durationMs=${outcome.durationMs} ${outcome.summary}`, maxBytes).catch(() => {
10397
+ yield* Effect8.promise(() => appendBoundedJobLog(logFile, `[${new Date().toISOString()}] ${outcome.ok ? "done" : "error"} job=${args.job} exit=${outcome.exitCode} durationMs=${outcome.durationMs} ${outcome.summary}`, maxBytes).catch(() => {
8645
10398
  return;
8646
10399
  }));
8647
10400
  return outcome;
8648
10401
  });
8649
10402
  }
8650
10403
  function isMacOsTccProtectedPath(absPath, safeHomeDir) {
8651
- const norm = nodePath7.resolve(absPath);
8652
- const normSafe = nodePath7.resolve(safeHomeDir);
8653
- if (norm === normSafe || norm.startsWith(`${normSafe}${nodePath7.sep}`)) {
10404
+ const norm = nodePath9.resolve(absPath);
10405
+ const normSafe = nodePath9.resolve(safeHomeDir);
10406
+ if (norm === normSafe || norm.startsWith(`${normSafe}${nodePath9.sep}`)) {
8654
10407
  return false;
8655
10408
  }
8656
- const home = process.env.HOME?.trim() || os2.homedir();
8657
- const protectedRoots = ["Documents", "Desktop", "Downloads"].map((d) => nodePath7.join(home, d));
8658
- return protectedRoots.some((r) => norm === r || norm.startsWith(`${r}${nodePath7.sep}`));
10409
+ const home = process.env.HOME?.trim() || os3.homedir();
10410
+ const protectedRoots = ["Documents", "Desktop", "Downloads"].map((d) => nodePath9.join(home, d));
10411
+ return protectedRoots.some((r) => norm === r || norm.startsWith(`${r}${nodePath9.sep}`));
8659
10412
  }
8660
10413
  async function writeFileIfChanged(destPath, bytes, mode) {
8661
10414
  const buf = typeof bytes === "string" ? Buffer.from(bytes, "utf8") : Buffer.from(bytes);
8662
- const existing = await fsp7.readFile(destPath).catch(() => null);
10415
+ const existing = await fsp9.readFile(destPath).catch(() => null);
8663
10416
  if (existing && Buffer.compare(existing, buf) === 0) {
8664
10417
  if (mode !== undefined && process.platform !== "win32") {
8665
- const st = await fsp7.stat(destPath).catch(() => null);
10418
+ const st = await fsp9.stat(destPath).catch(() => null);
8666
10419
  if (st && (st.mode & 511) !== mode) {
8667
- await fsp7.chmod(destPath, mode);
10420
+ await fsp9.chmod(destPath, mode);
8668
10421
  }
8669
10422
  }
8670
10423
  return false;
8671
10424
  }
8672
- await fsp7.mkdir(nodePath7.dirname(destPath), { recursive: true });
8673
- await fsp7.writeFile(destPath, buf);
10425
+ await fsp9.mkdir(nodePath9.dirname(destPath), { recursive: true });
10426
+ await fsp9.writeFile(destPath, buf);
8674
10427
  if (mode !== undefined && process.platform !== "win32") {
8675
- await fsp7.chmod(destPath, mode);
10428
+ await fsp9.chmod(destPath, mode);
8676
10429
  }
8677
10430
  return true;
8678
10431
  }
8679
10432
  async function listRelativeFilesRecursive(rootDir, rel = "") {
8680
- const abs = rel ? nodePath7.join(rootDir, rel) : rootDir;
8681
- const entries = await fsp7.readdir(abs, { withFileTypes: true }).catch(() => []);
10433
+ const abs = rel ? nodePath9.join(rootDir, rel) : rootDir;
10434
+ const entries = await fsp9.readdir(abs, { withFileTypes: true }).catch(() => []);
8682
10435
  const out = [];
8683
10436
  for (const e of entries) {
8684
10437
  if (e.name === ".DS_Store" || e.name === "node_modules" || e.name === "dist")
@@ -8693,7 +10446,7 @@ async function listRelativeFilesRecursive(rootDir, rel = "") {
8693
10446
  return out;
8694
10447
  }
8695
10448
  async function syncReleaseSnapshotIdempotent(sourceRepoRoot, releaseRoot, bunBin) {
8696
- await fsp7.mkdir(releaseRoot, { recursive: true });
10449
+ await fsp9.mkdir(releaseRoot, { recursive: true });
8697
10450
  const staticFiles = [
8698
10451
  "package.json",
8699
10452
  "bun.lock",
@@ -8706,60 +10459,60 @@ async function syncReleaseSnapshotIdempotent(sourceRepoRoot, releaseRoot, bunBin
8706
10459
  "packages/pi-extension/tsconfig.json"
8707
10460
  ];
8708
10461
  for (const rel of staticFiles) {
8709
- const src = nodePath7.join(sourceRepoRoot, rel);
8710
- const bytes = await fsp7.readFile(src).catch(() => null);
10462
+ const src = nodePath9.join(sourceRepoRoot, rel);
10463
+ const bytes = await fsp9.readFile(src).catch(() => null);
8711
10464
  if (bytes) {
8712
- await writeFileIfChanged(nodePath7.join(releaseRoot, rel), bytes, 420);
10465
+ await writeFileIfChanged(nodePath9.join(releaseRoot, rel), bytes, 420);
8713
10466
  }
8714
10467
  }
8715
10468
  for (const pkg of ["core", "cli", "pi-extension"]) {
8716
- const srcDir = nodePath7.join(sourceRepoRoot, "packages", pkg, "src");
8717
- const dstDir = nodePath7.join(releaseRoot, "packages", pkg, "src");
10469
+ const srcDir = nodePath9.join(sourceRepoRoot, "packages", pkg, "src");
10470
+ const dstDir = nodePath9.join(releaseRoot, "packages", pkg, "src");
8718
10471
  const wantedRels = new Set(await listRelativeFilesRecursive(srcDir));
8719
10472
  for (const rel of wantedRels) {
8720
- const bytes = await fsp7.readFile(nodePath7.join(srcDir, rel));
8721
- await writeFileIfChanged(nodePath7.join(dstDir, rel), bytes, 420);
10473
+ const bytes = await fsp9.readFile(nodePath9.join(srcDir, rel));
10474
+ await writeFileIfChanged(nodePath9.join(dstDir, rel), bytes, 420);
8722
10475
  }
8723
10476
  const existingRels = await listRelativeFilesRecursive(dstDir);
8724
10477
  for (const rel of existingRels) {
8725
10478
  if (!wantedRels.has(rel)) {
8726
- await moveToSystemTrash(nodePath7.join(dstDir, rel)).catch(() => {
10479
+ await moveToSystemTrash(nodePath9.join(dstDir, rel)).catch(() => {
8727
10480
  return;
8728
10481
  });
8729
10482
  }
8730
10483
  }
8731
- const staleDist = nodePath7.join(releaseRoot, "packages", pkg, "dist");
8732
- if (await fsp7.stat(staleDist).then(() => true).catch(() => false)) {
10484
+ const staleDist = nodePath9.join(releaseRoot, "packages", pkg, "dist");
10485
+ if (await fsp9.stat(staleDist).then(() => true).catch(() => false)) {
8733
10486
  await moveToSystemTrash(staleDist).catch(() => {
8734
10487
  return;
8735
10488
  });
8736
10489
  }
8737
10490
  }
8738
- const srcSkillsDir = nodePath7.join(sourceRepoRoot, "skills");
8739
- const dstSkillsDir = nodePath7.join(releaseRoot, "skills");
10491
+ const srcSkillsDir = nodePath9.join(sourceRepoRoot, "skills");
10492
+ const dstSkillsDir = nodePath9.join(releaseRoot, "skills");
8740
10493
  const wantedSkillRels = new Set(await listRelativeFilesRecursive(srcSkillsDir));
8741
10494
  for (const rel of wantedSkillRels) {
8742
- const bytes = await fsp7.readFile(nodePath7.join(srcSkillsDir, rel));
8743
- await writeFileIfChanged(nodePath7.join(dstSkillsDir, rel), bytes, 420);
10495
+ const bytes = await fsp9.readFile(nodePath9.join(srcSkillsDir, rel));
10496
+ await writeFileIfChanged(nodePath9.join(dstSkillsDir, rel), bytes, 420);
8744
10497
  }
8745
10498
  for (const rel of await listRelativeFilesRecursive(dstSkillsDir)) {
8746
10499
  if (!wantedSkillRels.has(rel)) {
8747
- await moveToSystemTrash(nodePath7.join(dstSkillsDir, rel)).catch(() => {
10500
+ await moveToSystemTrash(nodePath9.join(dstSkillsDir, rel)).catch(() => {
8748
10501
  return;
8749
10502
  });
8750
10503
  }
8751
10504
  }
8752
- const staleScripts = nodePath7.join(releaseRoot, "scripts");
8753
- if (await fsp7.stat(staleScripts).then(() => true).catch(() => false)) {
10505
+ const staleScripts = nodePath9.join(releaseRoot, "scripts");
10506
+ if (await fsp9.stat(staleScripts).then(() => true).catch(() => false)) {
8754
10507
  await moveToSystemTrash(staleScripts).catch(() => {
8755
10508
  return;
8756
10509
  });
8757
10510
  }
8758
- const lockBytes = await fsp7.readFile(nodePath7.join(sourceRepoRoot, "bun.lock")).catch(() => null);
10511
+ const lockBytes = await fsp9.readFile(nodePath9.join(sourceRepoRoot, "bun.lock")).catch(() => null);
8759
10512
  const lockSha = lockBytes ? sha256Hex(lockBytes) : "no-lock";
8760
- const markerPath = nodePath7.join(releaseRoot, ".bun-lock.sha256");
8761
- const prevSha = (await fsp7.readFile(markerPath, "utf8").catch(() => "")).trim();
8762
- const hasNodeModules = await fsp7.stat(nodePath7.join(releaseRoot, "node_modules")).then((s) => s.isDirectory()).catch(() => false);
10513
+ const markerPath = nodePath9.join(releaseRoot, ".bun-lock.sha256");
10514
+ const prevSha = (await fsp9.readFile(markerPath, "utf8").catch(() => "")).trim();
10515
+ const hasNodeModules = await fsp9.stat(nodePath9.join(releaseRoot, "node_modules")).then((s) => s.isDirectory()).catch(() => false);
8763
10516
  if (!hasNodeModules || prevSha !== "" && prevSha !== lockSha) {
8764
10517
  const installRes = await execSubprocess(bunBin, ["install", "--frozen-lockfile", "--production"], {
8765
10518
  cwd: releaseRoot,
@@ -8770,10 +10523,10 @@ async function syncReleaseSnapshotIdempotent(sourceRepoRoot, releaseRoot, bunBin
8770
10523
  }
8771
10524
  }
8772
10525
  for (const relPeer of [
8773
- nodePath7.join(releaseRoot, "packages", "pi-extension", "node_modules", "typebox"),
8774
- nodePath7.join(releaseRoot, "node_modules", "typebox")
10526
+ nodePath9.join(releaseRoot, "packages", "pi-extension", "node_modules", "typebox"),
10527
+ nodePath9.join(releaseRoot, "node_modules", "typebox")
8775
10528
  ]) {
8776
- if (await fsp7.lstat(relPeer).then(() => true).catch(() => false)) {
10529
+ if (await fsp9.lstat(relPeer).then(() => true).catch(() => false)) {
8777
10530
  await moveToSystemTrash(relPeer).catch(() => {
8778
10531
  return;
8779
10532
  });
@@ -8851,11 +10604,11 @@ Persistent=true`;
8851
10604
  return { service, timer };
8852
10605
  }
8853
10606
  function resolveRepoRootFromModule() {
8854
- const here = nodePath7.dirname(fileURLToPath(import.meta.url));
8855
- return nodePath7.resolve(here, "../../../../");
10607
+ const here = nodePath9.dirname(fileURLToPath(import.meta.url));
10608
+ return nodePath9.resolve(here, "../../../../");
8856
10609
  }
8857
10610
  function installScheduleCommand(args) {
8858
- return Effect6.gen(function* () {
10611
+ return Effect8.gen(function* () {
8859
10612
  const store = yield* StorePort;
8860
10613
  const { libraryId } = yield* loadResolvedLibrary(args?.libraryId);
8861
10614
  const syncIntervalSec = yield* parseDurationSeconds(args?.syncEvery ?? "12m");
@@ -8863,12 +10616,12 @@ function installScheduleCommand(args) {
8863
10616
  const upstreamIntervalSec = args?.upstreamEvery ? yield* parseDurationSeconds(args.upstreamEvery) : null;
8864
10617
  const rawPlatform = args?.platformOverride ?? process.platform;
8865
10618
  if (rawPlatform !== "darwin" && rawPlatform !== "linux") {
8866
- return yield* Effect6.fail(new ConfigError({
10619
+ return yield* Effect8.fail(new ConfigError({
8867
10620
  message: `Unsupported OS platform '${rawPlatform}' for native schedule install. Use 'ntn-skills schedule export crontab' or 'dagu' instead.`
8868
10621
  }));
8869
10622
  }
8870
10623
  const platform = rawPlatform;
8871
- const credPath = yield* Effect6.tryPromise({
10624
+ const credPath = yield* Effect8.tryPromise({
8872
10625
  try: async () => {
8873
10626
  const stored = await readStoredCredentials(store.paths.configPath);
8874
10627
  const envNotion = (process.env.NOTION_TOKEN ?? process.env.NOTION_API_TOKEN ?? "").trim();
@@ -8895,9 +10648,9 @@ function installScheduleCommand(args) {
8895
10648
  const sourceRepoRoot = resolveRepoRootFromModule();
8896
10649
  const runtimeBin = process.execPath;
8897
10650
  const needReleaseCopy = platform === "darwin" && isMacOsTccProtectedPath(sourceRepoRoot, store.paths.homeDir);
8898
- const runtimeRoot = needReleaseCopy ? nodePath7.join(store.paths.homeDir, "release") : sourceRepoRoot;
10651
+ const runtimeRoot = needReleaseCopy ? nodePath9.join(store.paths.homeDir, "release") : sourceRepoRoot;
8899
10652
  if (needReleaseCopy) {
8900
- yield* Effect6.tryPromise({
10653
+ yield* Effect8.tryPromise({
8901
10654
  try: () => syncReleaseSnapshotIdempotent(sourceRepoRoot, runtimeRoot, runtimeBin),
8902
10655
  catch: (e) => new StoreError({
8903
10656
  path: runtimeRoot,
@@ -8905,10 +10658,10 @@ function installScheduleCommand(args) {
8905
10658
  })
8906
10659
  });
8907
10660
  }
8908
- const entryBinTs = nodePath7.join(runtimeRoot, "packages", "cli", "src", "bin.ts");
8909
- const wrapperPath = nodePath7.join(store.paths.homeDir, "bin", "ntn-skills");
10661
+ const entryBinTs = nodePath9.join(runtimeRoot, "packages", "cli", "src", "bin.ts");
10662
+ const wrapperPath = nodePath9.join(store.paths.homeDir, "bin", "ntn-skills");
8910
10663
  const binLinkPath = resolveHomePath(args?.binLinkPath ?? "~/.local/bin/ntn-skills");
8911
- yield* Effect6.tryPromise({
10664
+ yield* Effect8.tryPromise({
8912
10665
  try: async () => {
8913
10666
  const xdgLines = [
8914
10667
  ...process.env.XDG_DATA_HOME?.trim() ? [`export XDG_DATA_HOME="\${XDG_DATA_HOME:-${process.env.XDG_DATA_HOME.trim()}}"`] : [],
@@ -8926,16 +10679,16 @@ function installScheduleCommand(args) {
8926
10679
  ].join(`
8927
10680
  `);
8928
10681
  await writeFileIfChanged(wrapperPath, wrapperContent, 493);
8929
- await fsp7.mkdir(nodePath7.dirname(binLinkPath), { recursive: true });
8930
- const stLink = await fsp7.lstat(binLinkPath).catch(() => null);
10682
+ await fsp9.mkdir(nodePath9.dirname(binLinkPath), { recursive: true });
10683
+ const stLink = await fsp9.lstat(binLinkPath).catch(() => null);
8931
10684
  if (stLink) {
8932
- const curTarget = stLink.isSymbolicLink() ? await fsp7.readlink(binLinkPath).catch(() => "") : "";
8933
- if (nodePath7.resolve(nodePath7.dirname(binLinkPath), curTarget) !== wrapperPath) {
10685
+ const curTarget = stLink.isSymbolicLink() ? await fsp9.readlink(binLinkPath).catch(() => "") : "";
10686
+ if (nodePath9.resolve(nodePath9.dirname(binLinkPath), curTarget) !== wrapperPath) {
8934
10687
  await moveToSystemTrash(binLinkPath);
8935
- await fsp7.symlink(wrapperPath, binLinkPath);
10688
+ await fsp9.symlink(wrapperPath, binLinkPath);
8936
10689
  }
8937
10690
  } else {
8938
- await fsp7.symlink(wrapperPath, binLinkPath);
10691
+ await fsp9.symlink(wrapperPath, binLinkPath);
8939
10692
  }
8940
10693
  },
8941
10694
  catch: (e) => new StoreError({
@@ -8944,12 +10697,12 @@ function installScheduleCommand(args) {
8944
10697
  })
8945
10698
  });
8946
10699
  if (!args?.skipPreflight) {
8947
- const preflight = yield* Effect6.tryPromise({
10700
+ const preflight = yield* Effect8.tryPromise({
8948
10701
  try: () => {
8949
10702
  const cleanEnvArgs = [
8950
10703
  "-i",
8951
- `HOME=${process.env.HOME?.trim() || os2.homedir()}`,
8952
- `USER=${os2.userInfo().username}`,
10704
+ `HOME=${process.env.HOME?.trim() || os3.homedir()}`,
10705
+ `USER=${os3.userInfo().username}`,
8953
10706
  "PATH=/usr/bin:/bin",
8954
10707
  ...process.env.XDG_DATA_HOME?.trim() ? [`XDG_DATA_HOME=${process.env.XDG_DATA_HOME.trim()}`] : [],
8955
10708
  ...process.env.XDG_CONFIG_HOME?.trim() ? [`XDG_CONFIG_HOME=${process.env.XDG_CONFIG_HOME.trim()}`] : [],
@@ -8971,7 +10724,7 @@ function installScheduleCommand(args) {
8971
10724
  })
8972
10725
  });
8973
10726
  if (preflight.code !== 0) {
8974
- return yield* Effect6.fail(new AuthError({
10727
+ return yield* Effect8.fail(new AuthError({
8975
10728
  provider: "notion",
8976
10729
  message: `Headless sandbox preflight (env -i) exited ${preflight.code}. Ensure NOTION_TOKEN is exported or stored in ${credPath} (0600). Output: ${(preflight.stderr || preflight.stdout).trim().slice(0, 320)}`
8977
10730
  }));
@@ -8980,18 +10733,18 @@ function installScheduleCommand(args) {
8980
10733
  const installedUnits = [];
8981
10734
  const retiredUnits = [];
8982
10735
  const libArgs = args?.libraryId ? ["--library", libraryId] : [];
8983
- const logsDir = nodePath7.join(store.paths.homeDir, "logs");
10736
+ const logsDir = nodePath9.join(store.paths.homeDir, "logs");
8984
10737
  if (platform === "darwin") {
8985
10738
  const agentsDir = resolveHomePath(args?.launchAgentsDir ?? "~/Library/LaunchAgents");
8986
- const errLogPath = nodePath7.join(logsDir, "launchd.err.log");
10739
+ const errLogPath = nodePath9.join(logsDir, "launchd.err.log");
8987
10740
  const uid = typeof process.getuid === "function" ? process.getuid() : 501;
8988
- yield* Effect6.tryPromise({
10741
+ yield* Effect8.tryPromise({
8989
10742
  try: async () => {
8990
- await fsp7.mkdir(agentsDir, { recursive: true });
8991
- await fsp7.mkdir(logsDir, { recursive: true });
10743
+ await fsp9.mkdir(agentsDir, { recursive: true });
10744
+ await fsp9.mkdir(logsDir, { recursive: true });
8992
10745
  for (const legacyLabel of LEGACY_DARWIN_LABELS) {
8993
- const legacyPlist = nodePath7.join(agentsDir, `${legacyLabel}.plist`);
8994
- const exists = await fsp7.stat(legacyPlist).then(() => true).catch(() => false);
10746
+ const legacyPlist = nodePath9.join(agentsDir, `${legacyLabel}.plist`);
10747
+ const exists = await fsp9.stat(legacyPlist).then(() => true).catch(() => false);
8995
10748
  if (exists) {
8996
10749
  if (!args?.skipOsActivation) {
8997
10750
  await execSubprocess("launchctl", ["bootout", `gui/${uid}`, legacyPlist]).catch(() => {
@@ -9036,8 +10789,8 @@ function installScheduleCommand(args) {
9036
10789
  })
9037
10790
  });
9038
10791
  } else {
9039
- const optionalUpstreamPlist = nodePath7.join(agentsDir, "io.ntn-skills.upstream.plist");
9040
- if (await fsp7.stat(optionalUpstreamPlist).then(() => true).catch(() => false)) {
10792
+ const optionalUpstreamPlist = nodePath9.join(agentsDir, "io.ntn-skills.upstream.plist");
10793
+ if (await fsp9.stat(optionalUpstreamPlist).then(() => true).catch(() => false)) {
9041
10794
  if (!args?.skipOsActivation) {
9042
10795
  await execSubprocess("launchctl", [
9043
10796
  "bootout",
@@ -9052,7 +10805,7 @@ function installScheduleCommand(args) {
9052
10805
  }
9053
10806
  }
9054
10807
  for (const u of desiredDarwin) {
9055
- const plistPath = nodePath7.join(agentsDir, `${u.label}.plist`);
10808
+ const plistPath = nodePath9.join(agentsDir, `${u.label}.plist`);
9056
10809
  if (!args?.skipOsActivation) {
9057
10810
  await execSubprocess("launchctl", ["bootout", `gui/${uid}`, plistPath]).catch(() => {
9058
10811
  return;
@@ -9080,9 +10833,9 @@ function installScheduleCommand(args) {
9080
10833
  } else {
9081
10834
  const systemdDir = resolveHomePath(args?.systemdUserDir ?? "~/.config/systemd/user");
9082
10835
  const libSuffix = args?.libraryId ? ` --library ${libraryId}` : "";
9083
- yield* Effect6.tryPromise({
10836
+ yield* Effect8.tryPromise({
9084
10837
  try: async () => {
9085
- await fsp7.mkdir(systemdDir, { recursive: true });
10838
+ await fsp9.mkdir(systemdDir, { recursive: true });
9086
10839
  const unitsToWrite = [
9087
10840
  {
9088
10841
  base: "ntn-skills-sync",
@@ -9115,8 +10868,8 @@ function installScheduleCommand(args) {
9115
10868
  });
9116
10869
  } else {
9117
10870
  for (const ext of ["service", "timer"]) {
9118
- const p = nodePath7.join(systemdDir, `ntn-skills-upstream.${ext}`);
9119
- if (await fsp7.stat(p).then(() => true).catch(() => false)) {
10871
+ const p = nodePath9.join(systemdDir, `ntn-skills-upstream.${ext}`);
10872
+ if (await fsp9.stat(p).then(() => true).catch(() => false)) {
9120
10873
  if (!args?.skipOsActivation) {
9121
10874
  await execSubprocess("systemctl", [
9122
10875
  "--user",
@@ -9133,8 +10886,8 @@ function installScheduleCommand(args) {
9133
10886
  }
9134
10887
  }
9135
10888
  for (const u of unitsToWrite) {
9136
- const svcPath = nodePath7.join(systemdDir, `${u.base}.service`);
9137
- const tmrPath = nodePath7.join(systemdDir, `${u.base}.timer`);
10889
+ const svcPath = nodePath9.join(systemdDir, `${u.base}.service`);
10890
+ const tmrPath = nodePath9.join(systemdDir, `${u.base}.timer`);
9138
10891
  await writeFileIfChanged(svcPath, u.pair.service, 420);
9139
10892
  await writeFileIfChanged(tmrPath, u.pair.timer, 420);
9140
10893
  installedUnits.push(tmrPath);
@@ -9178,8 +10931,8 @@ function installScheduleCommand(args) {
9178
10931
  }
9179
10932
  async function readTailLine(filePath) {
9180
10933
  try {
9181
- const st = await fsp7.stat(filePath);
9182
- const raw = await fsp7.readFile(filePath, "utf8");
10934
+ const st = await fsp9.stat(filePath);
10935
+ const raw = await fsp9.readFile(filePath, "utf8");
9183
10936
  const lines = raw.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
9184
10937
  return { bytes: st.size, lastLine: lines.length > 0 ? lines[lines.length - 1] : null };
9185
10938
  } catch {
@@ -9187,23 +10940,23 @@ async function readTailLine(filePath) {
9187
10940
  }
9188
10941
  }
9189
10942
  function statusScheduleCommand(args) {
9190
- return Effect6.gen(function* () {
10943
+ return Effect8.gen(function* () {
9191
10944
  const store = yield* StorePort;
9192
10945
  const platform = args?.platformOverride ?? process.platform;
9193
- const wrapperPath = nodePath7.join(store.paths.homeDir, "bin", "ntn-skills");
10946
+ const wrapperPath = nodePath9.join(store.paths.homeDir, "bin", "ntn-skills");
9194
10947
  const binLinkPath = resolveHomePath(args?.binLinkPath ?? "~/.local/bin/ntn-skills");
9195
- return yield* Effect6.tryPromise({
10948
+ return yield* Effect8.tryPromise({
9196
10949
  try: async () => {
9197
- const wrapperExists = await fsp7.stat(wrapperPath).then((s) => s.isFile()).catch(() => false);
9198
- const binLinkTarget = await fsp7.readlink(binLinkPath).catch(() => null);
10950
+ const wrapperExists = await fsp9.stat(wrapperPath).then((s) => s.isFile()).catch(() => false);
10951
+ const binLinkTarget = await fsp9.readlink(binLinkPath).catch(() => null);
9199
10952
  const credentials = await inspectCredentialsStatus(store.paths.configPath);
9200
10953
  const units = [];
9201
10954
  if (platform === "darwin") {
9202
10955
  const agentsDir = resolveHomePath(args?.launchAgentsDir ?? "~/Library/LaunchAgents");
9203
10956
  const uid = typeof process.getuid === "function" ? process.getuid() : 501;
9204
10957
  for (const u of MANAGED_UNITS) {
9205
- const plistPath = nodePath7.join(agentsDir, `${u.darwinLabel}.plist`);
9206
- const installed = await fsp7.stat(plistPath).then((s) => s.isFile()).catch(() => false);
10958
+ const plistPath = nodePath9.join(agentsDir, `${u.darwinLabel}.plist`);
10959
+ const installed = await fsp9.stat(plistPath).then((s) => s.isFile()).catch(() => false);
9207
10960
  let active = false;
9208
10961
  if (installed && !args?.skipOsQuery) {
9209
10962
  const pr = await execSubprocess("launchctl", [
@@ -9224,8 +10977,8 @@ function statusScheduleCommand(args) {
9224
10977
  const systemdDir = resolveHomePath(args?.systemdUserDir ?? "~/.config/systemd/user");
9225
10978
  for (const u of MANAGED_UNITS) {
9226
10979
  const timerName = `${u.systemdUnit}.timer`;
9227
- const unitPath = nodePath7.join(systemdDir, timerName);
9228
- const installed = await fsp7.stat(unitPath).then((s) => s.isFile()).catch(() => false);
10980
+ const unitPath = nodePath9.join(systemdDir, timerName);
10981
+ const installed = await fsp9.stat(unitPath).then((s) => s.isFile()).catch(() => false);
9229
10982
  let active = false;
9230
10983
  if (installed && !args?.skipOsQuery) {
9231
10984
  const pr = await execSubprocess("systemctl", [
@@ -9244,16 +10997,16 @@ function statusScheduleCommand(args) {
9244
10997
  });
9245
10998
  }
9246
10999
  }
9247
- const logsDir = nodePath7.join(store.paths.homeDir, "logs");
9248
- const syncLogPath = nodePath7.join(logsDir, "sync.log");
9249
- const upstreamLogPath = nodePath7.join(logsDir, "upstream.log");
11000
+ const logsDir = nodePath9.join(store.paths.homeDir, "logs");
11001
+ const syncLogPath = nodePath9.join(logsDir, "sync.log");
11002
+ const upstreamLogPath = nodePath9.join(logsDir, "upstream.log");
9250
11003
  const [syncTail, upstreamTail] = await Promise.all([
9251
11004
  readTailLine(syncLogPath),
9252
11005
  readTailLine(upstreamLogPath)
9253
11006
  ]);
9254
11007
  let lastUpstreamReport = null;
9255
11008
  try {
9256
- const rawRep = JSON.parse(await fsp7.readFile(nodePath7.join(logsDir, "upstream-last-report.json"), "utf8"));
11009
+ const rawRep = JSON.parse(await fsp9.readFile(nodePath9.join(logsDir, "upstream-last-report.json"), "utf8"));
9257
11010
  lastUpstreamReport = {
9258
11011
  finishedAt: rawRep.finishedAt,
9259
11012
  checked: rawRep.checked,
@@ -9286,18 +11039,18 @@ function statusScheduleCommand(args) {
9286
11039
  });
9287
11040
  }
9288
11041
  function uninstallScheduleCommand(args) {
9289
- return Effect6.gen(function* () {
11042
+ return Effect8.gen(function* () {
9290
11043
  const platform = args?.platformOverride ?? process.platform;
9291
11044
  const removedUnits = [];
9292
- yield* Effect6.tryPromise({
11045
+ yield* Effect8.tryPromise({
9293
11046
  try: async () => {
9294
11047
  if (platform === "darwin") {
9295
11048
  const agentsDir = resolveHomePath(args?.launchAgentsDir ?? "~/Library/LaunchAgents");
9296
11049
  const uid = typeof process.getuid === "function" ? process.getuid() : 501;
9297
11050
  const allLabels = [...MANAGED_UNITS.map((u) => u.darwinLabel), ...LEGACY_DARWIN_LABELS];
9298
11051
  for (const label of allLabels) {
9299
- const plistPath = nodePath7.join(agentsDir, `${label}.plist`);
9300
- const exists = await fsp7.stat(plistPath).then(() => true).catch(() => false);
11052
+ const plistPath = nodePath9.join(agentsDir, `${label}.plist`);
11053
+ const exists = await fsp9.stat(plistPath).then(() => true).catch(() => false);
9301
11054
  if (!exists)
9302
11055
  continue;
9303
11056
  if (!args?.skipOsActivation) {
@@ -9312,8 +11065,8 @@ function uninstallScheduleCommand(args) {
9312
11065
  const systemdDir = resolveHomePath(args?.systemdUserDir ?? "~/.config/systemd/user");
9313
11066
  for (const u of MANAGED_UNITS) {
9314
11067
  for (const ext of ["timer", "service"]) {
9315
- const p = nodePath7.join(systemdDir, `${u.systemdUnit}.${ext}`);
9316
- const exists = await fsp7.stat(p).then(() => true).catch(() => false);
11068
+ const p = nodePath9.join(systemdDir, `${u.systemdUnit}.${ext}`);
11069
+ const exists = await fsp9.stat(p).then(() => true).catch(() => false);
9317
11070
  if (!exists)
9318
11071
  continue;
9319
11072
  if (ext === "timer" && !args?.skipOsActivation) {
@@ -9352,7 +11105,7 @@ function durationSecToCronExpr(sec) {
9352
11105
  return "0 3 * * *";
9353
11106
  }
9354
11107
  function exportScheduleTemplateCommand(args) {
9355
- return Effect6.gen(function* () {
11108
+ return Effect8.gen(function* () {
9356
11109
  const { libraryId } = yield* loadResolvedLibrary(args.libraryId);
9357
11110
  const everySec = yield* parseDurationSeconds(args.every ?? "2h");
9358
11111
  const cronExpr = durationSecToCronExpr(everySec);
@@ -9443,14 +11196,14 @@ function exportScheduleTemplateCommand(args) {
9443
11196
  });
9444
11197
  }
9445
11198
  // packages/cli/src/main.ts
9446
- import { Console, Effect as Effect7, Layer as Layer5, Option as Option2 } from "effect";
11199
+ import { Console, Effect as Effect9, Layer as Layer5, Option as Option2 } from "effect";
9447
11200
  import { Argument, Command, Flag } from "effect/cli";
9448
11201
 
9449
11202
  // packages/cli/src/bundled-skill.ts
9450
11203
  import { createHash as createHash2, randomUUID as randomUUID6 } from "node:crypto";
9451
- import * as fsp8 from "node:fs/promises";
11204
+ import * as fsp10 from "node:fs/promises";
9452
11205
  import { createRequire } from "node:module";
9453
- import * as nodePath8 from "node:path";
11206
+ import * as nodePath10 from "node:path";
9454
11207
  import { fileURLToPath as fileURLToPath2 } from "node:url";
9455
11208
  var BUNDLED_SKILL_NAME = "ntn-skills";
9456
11209
  var cliRequire = createRequire(import.meta.url);
@@ -9466,7 +11219,7 @@ async function readBundledSkill() {
9466
11219
  ];
9467
11220
  for (const p of candidates) {
9468
11221
  try {
9469
- const markdown = await fsp8.readFile(p, "utf8");
11222
+ const markdown = await fsp10.readFile(p, "utf8");
9470
11223
  const sha256 = createHash2("sha256").update(markdown, "utf8").digest("hex");
9471
11224
  return {
9472
11225
  name: BUNDLED_SKILL_NAME,
@@ -9483,32 +11236,32 @@ async function readBundledSkill() {
9483
11236
  });
9484
11237
  }
9485
11238
  async function ensureBundledStoreDir(storeRoot, payload) {
9486
- const revDir = nodePath8.join(storeRoot, "_bundled", BUNDLED_SKILL_NAME, payload.sha256);
9487
- const mdFile = nodePath8.join(revDir, "SKILL.md");
9488
- const existing = await fsp8.stat(mdFile).catch(() => null);
11239
+ const revDir = nodePath10.join(storeRoot, "_bundled", BUNDLED_SKILL_NAME, payload.sha256);
11240
+ const mdFile = nodePath10.join(revDir, "SKILL.md");
11241
+ const existing = await fsp10.stat(mdFile).catch(() => null);
9489
11242
  if (existing?.isFile()) {
9490
11243
  return revDir;
9491
11244
  }
9492
- const parentDir = nodePath8.dirname(revDir);
9493
- await fsp8.mkdir(parentDir, { recursive: true });
9494
- const stageDir = nodePath8.join(parentDir, `.tmp-bundled-${process.pid}-${randomUUID6().slice(0, 8)}`);
9495
- await fsp8.mkdir(stageDir, { recursive: true });
9496
- await fsp8.writeFile(nodePath8.join(stageDir, "SKILL.md"), payload.markdown, {
11245
+ const parentDir = nodePath10.dirname(revDir);
11246
+ await fsp10.mkdir(parentDir, { recursive: true });
11247
+ const stageDir = nodePath10.join(parentDir, `.tmp-bundled-${process.pid}-${randomUUID6().slice(0, 8)}`);
11248
+ await fsp10.mkdir(stageDir, { recursive: true });
11249
+ await fsp10.writeFile(nodePath10.join(stageDir, "SKILL.md"), payload.markdown, {
9497
11250
  encoding: "utf8",
9498
11251
  mode: 292
9499
11252
  });
9500
- await fsp8.writeFile(nodePath8.join(stageDir, ".ntn-manifest.json"), `${JSON.stringify({
11253
+ await fsp10.writeFile(nodePath10.join(stageDir, ".ntn-manifest.json"), `${JSON.stringify({
9501
11254
  skillId: BUNDLED_SKILL_NAME,
9502
11255
  effectiveRev: payload.sha256,
9503
11256
  publishedAt: new Date().toISOString(),
9504
11257
  bundled: true
9505
11258
  }, null, 2)}
9506
11259
  `, { encoding: "utf8", mode: 292 });
9507
- await fsp8.chmod(stageDir, 365);
11260
+ await fsp10.chmod(stageDir, 365);
9508
11261
  try {
9509
- await fsp8.rename(stageDir, revDir);
11262
+ await fsp10.rename(stageDir, revDir);
9510
11263
  } catch {
9511
- await fsp8.chmod(stageDir, 493).catch(() => {
11264
+ await fsp10.chmod(stageDir, 493).catch(() => {
9512
11265
  return;
9513
11266
  });
9514
11267
  await moveToSystemTrash(stageDir).catch(() => {
@@ -9520,21 +11273,21 @@ async function ensureBundledStoreDir(storeRoot, payload) {
9520
11273
  async function installBundledSkill(args) {
9521
11274
  const payload = await readBundledSkill();
9522
11275
  const destRoot = expandHome(args.destDir ?? "~/.agents/skills");
9523
- await fsp8.mkdir(destRoot, { recursive: true });
9524
- const realStoreRoot = await fsp8.realpath(args.storeRoot).catch(() => nodePath8.resolve(args.storeRoot));
11276
+ await fsp10.mkdir(destRoot, { recursive: true });
11277
+ const realStoreRoot = await fsp10.realpath(args.storeRoot).catch(() => nodePath10.resolve(args.storeRoot));
9525
11278
  const storePrefixes = Array.from(new Set([
9526
- `${nodePath8.resolve(args.storeRoot)}${nodePath8.sep}`,
9527
- `${realStoreRoot}${nodePath8.sep}`
11279
+ `${nodePath10.resolve(args.storeRoot)}${nodePath10.sep}`,
11280
+ `${realStoreRoot}${nodePath10.sep}`
9528
11281
  ]));
9529
11282
  const isManagedStore = (p) => storePrefixes.some((pref) => p.startsWith(pref));
9530
- const linkPath = nodePath8.join(destRoot, BUNDLED_SKILL_NAME);
9531
- const lst = await fsp8.lstat(linkPath).catch(() => null);
11283
+ const linkPath = nodePath10.join(destRoot, BUNDLED_SKILL_NAME);
11284
+ const lst = await fsp10.lstat(linkPath).catch(() => null);
9532
11285
  const bundledDir = await ensureBundledStoreDir(args.storeRoot, payload);
9533
11286
  if (lst) {
9534
11287
  if (lst.isSymbolicLink()) {
9535
- const raw = await fsp8.readlink(linkPath);
9536
- const resolved = nodePath8.resolve(destRoot, raw);
9537
- const realResolved = await fsp8.realpath(resolved).catch(() => resolved);
11288
+ const raw = await fsp10.readlink(linkPath);
11289
+ const resolved = nodePath10.resolve(destRoot, raw);
11290
+ const realResolved = await fsp10.realpath(resolved).catch(() => resolved);
9538
11291
  if (!isManagedStore(resolved) && !isManagedStore(realResolved)) {
9539
11292
  if (!args.force) {
9540
11293
  throw new ConflictError({
@@ -9544,7 +11297,7 @@ async function installBundledSkill(args) {
9544
11297
  }
9545
11298
  await moveToSystemTrash(linkPath);
9546
11299
  } else {
9547
- const isBundled = resolved.includes(`${nodePath8.sep}_bundled${nodePath8.sep}`) || realResolved.includes(`${nodePath8.sep}_bundled${nodePath8.sep}`);
11300
+ const isBundled = resolved.includes(`${nodePath10.sep}_bundled${nodePath10.sep}`) || realResolved.includes(`${nodePath10.sep}_bundled${nodePath10.sep}`);
9548
11301
  if (!isBundled && !args.force) {
9549
11302
  return {
9550
11303
  name: BUNDLED_SKILL_NAME,
@@ -9565,7 +11318,7 @@ async function installBundledSkill(args) {
9565
11318
  }
9566
11319
  }
9567
11320
  } else if (lst.isDirectory()) {
9568
- const marker = await fsp8.readFile(nodePath8.join(linkPath, ".ntn-managed-copy.json"), "utf8").then((raw) => JSON.parse(raw)).catch(() => null);
11321
+ const marker = await fsp10.readFile(nodePath10.join(linkPath, ".ntn-managed-copy.json"), "utf8").then((raw) => JSON.parse(raw)).catch(() => null);
9569
11322
  if (marker && marker.skillId === BUNDLED_SKILL_NAME && marker.bundled === true) {
9570
11323
  if ((args.mode ?? "symlink") === "copy" && marker.effectiveRev === payload.sha256) {
9571
11324
  return {
@@ -9606,15 +11359,15 @@ async function installBundledSkill(args) {
9606
11359
  if (lst?.isSymbolicLink()) {
9607
11360
  await moveToSystemTrash(linkPath);
9608
11361
  }
9609
- const stageCopy = nodePath8.join(destRoot, `.ntn-copy-${BUNDLED_SKILL_NAME}-${process.pid}-${randomUUID6().slice(0, 8)}`);
9610
- await fsp8.mkdir(stageCopy, { recursive: true });
9611
- await fsp8.writeFile(nodePath8.join(stageCopy, "SKILL.md"), payload.markdown, {
11362
+ const stageCopy = nodePath10.join(destRoot, `.ntn-copy-${BUNDLED_SKILL_NAME}-${process.pid}-${randomUUID6().slice(0, 8)}`);
11363
+ await fsp10.mkdir(stageCopy, { recursive: true });
11364
+ await fsp10.writeFile(nodePath10.join(stageCopy, "SKILL.md"), payload.markdown, {
9612
11365
  encoding: "utf8",
9613
11366
  mode: 420
9614
11367
  });
9615
- await fsp8.writeFile(nodePath8.join(stageCopy, ".ntn-managed-copy.json"), `${JSON.stringify({ skillId: BUNDLED_SKILL_NAME, effectiveRev: payload.sha256, bundled: true }, null, 2)}
11368
+ await fsp10.writeFile(nodePath10.join(stageCopy, ".ntn-managed-copy.json"), `${JSON.stringify({ skillId: BUNDLED_SKILL_NAME, effectiveRev: payload.sha256, bundled: true }, null, 2)}
9616
11369
  `, "utf8");
9617
- await fsp8.rename(stageCopy, linkPath);
11370
+ await fsp10.rename(stageCopy, linkPath);
9618
11371
  return {
9619
11372
  name: BUNDLED_SKILL_NAME,
9620
11373
  status: "installed",
@@ -9623,9 +11376,9 @@ async function installBundledSkill(args) {
9623
11376
  sha256: payload.sha256
9624
11377
  };
9625
11378
  }
9626
- const tmpLink = nodePath8.join(destRoot, `.ntn-link-${BUNDLED_SKILL_NAME}-${process.pid}-${randomUUID6().slice(0, 8)}`);
9627
- await fsp8.symlink(bundledDir, tmpLink);
9628
- await fsp8.rename(tmpLink, linkPath);
11379
+ const tmpLink = nodePath10.join(destRoot, `.ntn-link-${BUNDLED_SKILL_NAME}-${process.pid}-${randomUUID6().slice(0, 8)}`);
11380
+ await fsp10.symlink(bundledDir, tmpLink);
11381
+ await fsp10.rename(tmpLink, linkPath);
9629
11382
  return {
9630
11383
  name: BUNDLED_SKILL_NAME,
9631
11384
  status: "installed",
@@ -9636,22 +11389,22 @@ async function installBundledSkill(args) {
9636
11389
  }
9637
11390
  async function uninstallBundledSkill(args) {
9638
11391
  const destRoot = expandHome(args.destDir ?? "~/.agents/skills");
9639
- const linkPath = nodePath8.join(destRoot, BUNDLED_SKILL_NAME);
9640
- const lst = await fsp8.lstat(linkPath).catch(() => null);
11392
+ const linkPath = nodePath10.join(destRoot, BUNDLED_SKILL_NAME);
11393
+ const lst = await fsp10.lstat(linkPath).catch(() => null);
9641
11394
  if (!lst) {
9642
11395
  return { name: BUNDLED_SKILL_NAME, status: "not_installed", linkPath };
9643
11396
  }
9644
11397
  if (lst.isSymbolicLink()) {
9645
- const raw = await fsp8.readlink(linkPath);
9646
- const resolved = nodePath8.resolve(destRoot, raw);
9647
- if (resolved.includes(`${nodePath8.sep}_bundled${nodePath8.sep}`)) {
11398
+ const raw = await fsp10.readlink(linkPath);
11399
+ const resolved = nodePath10.resolve(destRoot, raw);
11400
+ if (resolved.includes(`${nodePath10.sep}_bundled${nodePath10.sep}`)) {
9648
11401
  await moveToSystemTrash(linkPath);
9649
11402
  return { name: BUNDLED_SKILL_NAME, status: "removed", linkPath };
9650
11403
  }
9651
- const realStoreRoot = await fsp8.realpath(args.storeRoot).catch(() => nodePath8.resolve(args.storeRoot));
11404
+ const realStoreRoot = await fsp10.realpath(args.storeRoot).catch(() => nodePath10.resolve(args.storeRoot));
9652
11405
  const storePrefixes = [
9653
- `${nodePath8.resolve(args.storeRoot)}${nodePath8.sep}`,
9654
- `${realStoreRoot}${nodePath8.sep}`
11406
+ `${nodePath10.resolve(args.storeRoot)}${nodePath10.sep}`,
11407
+ `${realStoreRoot}${nodePath10.sep}`
9655
11408
  ];
9656
11409
  if (storePrefixes.some((p) => resolved.startsWith(p))) {
9657
11410
  return { name: BUNDLED_SKILL_NAME, status: "managed_by_library", linkPath };
@@ -10076,12 +11829,12 @@ var initCmd = Command.make("init", {
10076
11829
  noSeedSelf: Flag.Boolean("no-seed-self").pipe(Flag.withDescription("Skip linking the built-in ntn-skills guide into configured export directories"), Flag.withDefault(false)),
10077
11830
  noSync: Flag.Boolean("no-sync").pipe(Flag.withDescription("Skip running initial full sync after writing config.json"), Flag.withDefault(false)),
10078
11831
  json: jsonFlag
10079
- }, (cfg) => Effect7.gen(function* () {
11832
+ }, (cfg) => Effect9.gen(function* () {
10080
11833
  const storeForInit = yield* StorePort;
10081
- const existingCfg = yield* storeForInit.readConfig().pipe(Effect7.catchTag("ConfigError", () => Effect7.succeed(null)));
11834
+ const existingCfg = yield* storeForInit.readConfig().pipe(Effect9.catchTag("ConfigError", () => Effect9.succeed(null)));
10082
11835
  const rootArg = Option2.getOrUndefined(cfg.root)?.trim() || process.env.NTN_SKILLS_LIBRARY?.trim() || existingCfg?.default_library?.trim() || "";
10083
11836
  if (!rootArg) {
10084
- return yield* Effect7.fail(new ConfigError({
11837
+ return yield* Effect9.fail(new ConfigError({
10085
11838
  message: `Missing Notion root page. Pass --root <notion-page-url> or set default_library in ${storeForInit.paths.configPath}.`
10086
11839
  }));
10087
11840
  }
@@ -10107,7 +11860,7 @@ var initCmd = Command.make("init", {
10107
11860
  libraryId: res.libraryId,
10108
11861
  full: true,
10109
11862
  dedupeWindowMs: 0
10110
- }).pipe(Effect7.result);
11863
+ }).pipe(Effect9.result);
10111
11864
  if (firstSync._tag === "Success") {
10112
11865
  syncedSummary = {
10113
11866
  catalogCount: firstSync.success.catalogCount,
@@ -10124,11 +11877,11 @@ var initCmd = Command.make("init", {
10124
11877
  if (!cfg.noSeedSelf && res.exports.length > 0) {
10125
11878
  const store = yield* StorePort;
10126
11879
  for (const exp of res.exports) {
10127
- const linkRes = yield* Effect7.tryPromise(() => installBundledSkill({
11880
+ const linkRes = yield* Effect9.tryPromise(() => installBundledSkill({
10128
11881
  destDir: exp.dir,
10129
11882
  storeRoot: store.paths.storeRoot,
10130
11883
  mode: exp.mode
10131
- })).pipe(Effect7.result);
11884
+ })).pipe(Effect9.result);
10132
11885
  if (linkRes._tag === "Success") {
10133
11886
  seededSelf = true;
10134
11887
  }
@@ -10160,10 +11913,10 @@ var initCmd = Command.make("init", {
10160
11913
  var doctorCmd = Command.make("doctor", {
10161
11914
  library: libraryFlag,
10162
11915
  json: jsonFlag
10163
- }, (cfg) => Effect7.gen(function* () {
11916
+ }, (cfg) => Effect9.gen(function* () {
10164
11917
  const libOpt = Option2.getOrUndefined(cfg.library);
10165
11918
  const report = yield* doctorCommand({ ...libOpt ? { libraryId: libOpt } : {} });
10166
- const sched = yield* statusScheduleCommand().pipe(Effect7.catch(() => Effect7.succeed(null)));
11919
+ const sched = yield* statusScheduleCommand().pipe(Effect9.catch(() => Effect9.succeed(null)));
10167
11920
  const syncActive = Boolean(sched?.units.some((u) => u.job === "sync" && u.active));
10168
11921
  const checks = [
10169
11922
  ...report.checks,
@@ -10192,15 +11945,17 @@ var doctorCmd = Command.make("doctor", {
10192
11945
  })).pipe(Command.withDescription("Diagnose credentials, Notion 3-table connectivity, exports, and background sync"));
10193
11946
  var syncCmd = Command.make("sync", {
10194
11947
  full: Flag.Boolean("full").pipe(Flag.withDescription("Run full reconciliation instead of overlap-window delta"), Flag.withDefault(false)),
11948
+ dryRun: Flag.Boolean("dry-run").pipe(Flag.withDescription("Preview remote changes, planned materializations, export diffs, and store GC without modifying any local files"), Flag.withDefault(false)),
10195
11949
  coalesce: Flag.Boolean("coalesce").pipe(Flag.withDescription("Coalesce if synced within the last 5s (for background cron/hooks)"), Flag.withDefault(false)),
10196
11950
  library: libraryFlag,
10197
11951
  json: jsonFlag
10198
- }, (cfg) => Effect7.gen(function* () {
11952
+ }, (cfg) => Effect9.gen(function* () {
10199
11953
  const libOpt = Option2.getOrUndefined(cfg.library);
10200
11954
  const res = yield* syncCommand({
10201
11955
  ...libOpt ? { libraryId: libOpt } : {},
10202
11956
  full: cfg.full,
10203
- dedupeWindowMs: cfg.full || !cfg.coalesce ? 0 : 5000
11957
+ dryRun: cfg.dryRun,
11958
+ dedupeWindowMs: cfg.dryRun || cfg.full || !cfg.coalesce ? 0 : 5000
10204
11959
  });
10205
11960
  const fmtList = (items, max = 6) => items.length <= max ? items.join(", ") : `${items.slice(0, max).join(", ")}, ... (+${items.length - max} more)`;
10206
11961
  const formatSyncHuman = (r) => {
@@ -10219,28 +11974,41 @@ var syncCmd = Command.make("sync", {
10219
11974
  }
10220
11975
  const pulledLine = diffParts.length === 0 ? "up to date (0 skill changes)" : diffParts.join("; ");
10221
11976
  const vc = r.visibilityCounts;
10222
- const catalogLine = `${r.catalogCount} enabled [always=${vc.always}, discoverable=${vc.discoverable}, manual=${vc.manual}] · exported=${r.exportedCount}, materialized=${r.materializedCount}, pruned=${r.prunedCount}`;
11977
+ const catalogLine = r.dryRun ? `${r.catalogCount} enabled [always=${vc.always}, discoverable=${vc.discoverable}, manual=${vc.manual}] · plannedMaterializations=${r.plannedMaterializations?.length ?? 0}, plannedPrunes=${r.plannedPrunes?.length ?? 0}` : `${r.catalogCount} enabled [always=${vc.always}, discoverable=${vc.discoverable}, manual=${vc.manual}] · exported=${r.exportedCount}, materialized=${r.materializedCount}, pruned=${r.prunedCount}`;
10223
11978
  const lp = r.localPending;
10224
11979
  const pendingLines = [];
10225
11980
  if (lp.openWorkdirs.length > 0) {
10226
11981
  const wList = lp.openWorkdirs.map((w) => `${w.skillName} (${w.workdir})`).join(", ");
10227
- pendingLines.push(` - ${lp.openWorkdirs.length} unpushed edit workdir(s): ${wList} -> run 'ntn-skills push <workdir>' or 'abort'`);
11982
+ pendingLines.push(` - ${lp.openWorkdirs.length} unpushed edit workdir(s): ${wList} -> run 'ntn-skills push --pending' (or 'push <workdir>' / 'abort')`);
10228
11983
  }
10229
11984
  if (lp.unmanagedLocalSkills.length > 0) {
10230
11985
  const uList = lp.unmanagedLocalSkills.map((u) => `${u.name} (${u.path})`).join(", ");
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)`);
11986
+ pendingLines.push(` - ${lp.unmanagedLocalSkills.length} local skill(s) not in Notion: ${uList} -> run 'ntn-skills new --pending --always' (or '--discoverable', preview with '--dry-run')`);
10232
11987
  }
10233
11988
  if (lp.uninitializedSources.length > 0) {
10234
11989
  pendingLines.push(` - ${lp.uninitializedSources.length} uninitialized Notion source(s): ${fmtList(lp.uninitializedSources)} -> run 'ntn-skills upstream apply <source>'`);
10235
11990
  }
10236
- const lines = [
10237
- `Synced ${r.libraryId} (${r.full ? "full" : "incremental"})`,
10238
- ` Pulled: ${pulledLine}`,
10239
- ` Catalog: ${catalogLine}`,
10240
- pendingLines.length === 0 ? " Local Pending: clean (0 unpushed workdirs, 0 unmanaged local skills)" : ` Local Pending:
11991
+ const header = r.dryRun ? `[dry-run] Sync preview for ${r.libraryId} (${r.full ? "full" : "incremental"}) — no local files were modified` : `Synced ${r.libraryId} (${r.full ? "full" : "incremental"})`;
11992
+ const lines = [header, ` Pulled: ${pulledLine}`, ` Catalog: ${catalogLine}`];
11993
+ if (r.dryRun && r.plannedMaterializations && r.plannedMaterializations.length > 0) {
11994
+ lines.push(` Materialize: ${fmtList(r.plannedMaterializations, 10)}`);
11995
+ }
11996
+ if (r.dryRun && r.plannedExports && r.plannedExports.length > 0) {
11997
+ lines.push(" Planned Exports:");
11998
+ for (const pe of r.plannedExports) {
11999
+ const parts = [
12000
+ `total=${pe.totalSkills}`,
12001
+ `write=${pe.wouldWrite.length}${pe.wouldWrite.length > 0 ? ` (${fmtList(pe.wouldWrite)})` : ""}`,
12002
+ `remove=${pe.wouldRemove.length}${pe.wouldRemove.length > 0 ? ` (${fmtList(pe.wouldRemove)})` : ""}`,
12003
+ `conflicts=${pe.wouldSkipConflicts.length}`,
12004
+ `router=${pe.routerIncluded ? pe.routerSkill ?? "skill-catalog" : "none"}`
12005
+ ];
12006
+ lines.push(` - ${pe.dest} [${pe.mode}]: ${parts.join(", ")}`);
12007
+ }
12008
+ }
12009
+ lines.push(pendingLines.length === 0 ? " Local Pending: clean (0 unpushed workdirs, 0 unmanaged local skills)" : ` Local Pending:
10241
12010
  ${pendingLines.join(`
10242
- `)}`
10243
- ];
12011
+ `)}`);
10244
12012
  if (r.warnings.length > 0) {
10245
12013
  lines.push(` Warnings:
10246
12014
  ${r.warnings.map((w) => ` - ${w}`).join(`
@@ -10258,7 +12026,7 @@ var findCmd = Command.make("find", {
10258
12026
  kind: Flag.Literals("kind", ["skill", "router", "prompt"]).pipe(Flag.withDescription("Filter by Kind (skill | router | prompt)"), Flag.optional),
10259
12027
  library: libraryFlag,
10260
12028
  json: jsonFlag
10261
- }, (cfg) => Effect7.gen(function* () {
12029
+ }, (cfg) => Effect9.gen(function* () {
10262
12030
  const q = Option2.getOrUndefined(cfg.query);
10263
12031
  const sc = Option2.getOrUndefined(cfg.scene);
10264
12032
  const vis = Option2.getOrUndefined(cfg.visibility);
@@ -10284,7 +12052,7 @@ var loadCmd = Command.make("load", {
10284
12052
  pathOnly: Flag.Boolean("path-only").pipe(Flag.withDefault(false)),
10285
12053
  library: libraryFlag,
10286
12054
  json: jsonFlag
10287
- }, (cfg) => Effect7.gen(function* () {
12055
+ }, (cfg) => Effect9.gen(function* () {
10288
12056
  const lib = Option2.getOrUndefined(cfg.library);
10289
12057
  const res = yield* loadSkillCommand({
10290
12058
  name: cfg.name,
@@ -10306,7 +12074,7 @@ var infoCmd = Command.make("info", {
10306
12074
  name: Argument.String("name"),
10307
12075
  library: libraryFlag,
10308
12076
  json: jsonFlag
10309
- }, (cfg) => Effect7.gen(function* () {
12077
+ }, (cfg) => Effect9.gen(function* () {
10310
12078
  const lib = Option2.getOrUndefined(cfg.library);
10311
12079
  const items = yield* findSkillsCommand({
10312
12080
  query: cfg.name,
@@ -10340,7 +12108,7 @@ var statusCmd = Command.make("status", {
10340
12108
  days: Flag.Int("days").pipe(Flag.withDescription("Lookback window in days for local on-demand load frequency"), Flag.withDefault(30)),
10341
12109
  library: libraryFlag,
10342
12110
  json: jsonFlag
10343
- }, (cfg) => Effect7.gen(function* () {
12111
+ }, (cfg) => Effect9.gen(function* () {
10344
12112
  const lib = Option2.getOrUndefined(cfg.library);
10345
12113
  const rep = yield* statusCommand({
10346
12114
  days: cfg.days,
@@ -10369,11 +12137,12 @@ var exportCmd = Command.make("export", {
10369
12137
  scene: Flag.String("scene").pipe(Flag.optional),
10370
12138
  mode: Flag.Literals("mode", ["symlink", "copy"]).pipe(Flag.optional),
10371
12139
  includeNonDefault: Flag.Boolean("include-non-default").pipe(Flag.withDefault(false)),
12140
+ dryRun: Flag.Boolean("dry-run").pipe(Flag.withDescription("Preview planned exports, removals, and conflicts without touching disk"), Flag.withDefault(false)),
10372
12141
  library: libraryFlag,
10373
12142
  json: jsonFlag
10374
- }, (cfg) => Effect7.gen(function* () {
12143
+ }, (cfg) => Effect9.gen(function* () {
10375
12144
  if (cfg.withRequires && cfg.noRequires) {
10376
- return yield* Effect7.fail(new ConfigError({
12145
+ return yield* Effect9.fail(new ConfigError({
10377
12146
  message: "Cannot combine --with-requires and --no-requires."
10378
12147
  }));
10379
12148
  }
@@ -10397,9 +12166,18 @@ var exportCmd = Command.make("export", {
10397
12166
  ...sc ? { scene: sc } : {},
10398
12167
  ...md ? { mode: md } : {},
10399
12168
  ...cfg.includeNonDefault ? { includeNonDefault: true } : {},
12169
+ ...cfg.dryRun ? { dryRun: true } : {},
10400
12170
  ...lib ? { libraryId: lib } : {}
10401
12171
  });
10402
- const lines = [
12172
+ const lines = res.dryRun ? [
12173
+ `[dry-run] Export preview across ${res.targets.length} target(s) — no local files were modified:`,
12174
+ ...res.targets.map((t) => {
12175
+ const ww = t.wouldWrite ?? [];
12176
+ const wr = t.wouldRemove ?? [];
12177
+ const wc = t.wouldSkipConflicts ?? [];
12178
+ return ` - ${t.dir} [${t.mode}]: total=${t.exportedCount ?? 0}, write=${ww.length}${ww.length > 0 ? ` (${ww.join(", ")})` : ""}, remove=${wr.length}${wr.length > 0 ? ` (${wr.join(", ")})` : ""}, conflicts=${wc.length}, router=${t.routerIncluded ? t.routerSkill ?? "skill-catalog" : "none"}`;
12179
+ })
12180
+ ] : [
10403
12181
  `Exported ${res.exportedDirs.length} skill(s):`,
10404
12182
  ...res.exportedDirs.map((d) => ` ${d}`)
10405
12183
  ];
@@ -10416,7 +12194,7 @@ var editCmd = Command.make("edit", {
10416
12194
  name: Argument.String("name"),
10417
12195
  library: libraryFlag,
10418
12196
  json: jsonFlag
10419
- }, (cfg) => Effect7.gen(function* () {
12197
+ }, (cfg) => Effect9.gen(function* () {
10420
12198
  const lib = Option2.getOrUndefined(cfg.library);
10421
12199
  const res = yield* editOrPullSkillCommand({
10422
12200
  name: cfg.name,
@@ -10430,7 +12208,7 @@ var pullCmd = Command.make("pull", {
10430
12208
  clean: Flag.Boolean("clean").pipe(Flag.withDescription("Export clean synthesized file tree (no .ntn-skill.json, removes stale files) for committing into a Git repo"), Flag.withDefault(false)),
10431
12209
  library: libraryFlag,
10432
12210
  json: jsonFlag
10433
- }, (cfg) => Effect7.gen(function* () {
12211
+ }, (cfg) => Effect9.gen(function* () {
10434
12212
  const targetDir = Option2.getOrUndefined(cfg.dir);
10435
12213
  const lib = Option2.getOrUndefined(cfg.library);
10436
12214
  const res = yield* editOrPullSkillCommand({
@@ -10445,7 +12223,7 @@ var diffCmd = Command.make("diff", {
10445
12223
  workdir: Argument.String("workdir"),
10446
12224
  remote: Flag.Boolean("remote").pipe(Flag.withDefault(false)),
10447
12225
  json: jsonFlag
10448
- }, (cfg) => Effect7.gen(function* () {
12226
+ }, (cfg) => Effect9.gen(function* () {
10449
12227
  const res = yield* diffWorkdirCommand({ workdir: cfg.workdir, remote: cfg.remote });
10450
12228
  const lines = [`Workdir: ${res.workdir} (skill: ${res.skillName})`];
10451
12229
  if (res.descriptionChanged) {
@@ -10467,26 +12245,107 @@ ${(res.remoteDriftDetails ?? []).map((d) => ` - ${d}`).join(`
10467
12245
  `));
10468
12246
  })).pipe(Command.withDescription("Show local modifications, planned Notion overlay actions, and optional remote drift"));
10469
12247
  var pushCmd = Command.make("push", {
10470
- workdir: Argument.String("workdir"),
12248
+ dirs: Argument.String("dir").pipe(Argument.atLeast(0)),
12249
+ pending: Flag.Boolean("pending").pipe(Flag.withDescription("Push all open edit workdirs belonging to the target library"), Flag.withDefault(false)),
12250
+ exclude: Flag.String("exclude").pipe(Flag.withDescription("Workdirs or skill names to exclude (comma-separated or repeatable)"), Flag.atLeast(0)),
12251
+ to: Flag.String("to").pipe(Flag.withDescription("Target existing Notion skill name when directly overwriting from a plain local directory"), Flag.optional),
12252
+ overwrite: Flag.Boolean("overwrite").pipe(Flag.withDescription("Overwrite an existing Notion skill directly from a plain local directory without .ntn-skill.json (preserves source dir)"), Flag.withDefault(false)),
10471
12253
  dryRun: Flag.Boolean("dry-run").pipe(Flag.withDefault(false)),
10472
12254
  force: Flag.Boolean("force").pipe(Flag.withDefault(false)),
12255
+ library: libraryFlag,
10473
12256
  json: jsonFlag
10474
- }, (cfg) => Effect7.gen(function* () {
10475
- const res = yield* pushWorkdirCommand({
10476
- workdir: cfg.workdir,
12257
+ }, (cfg) => Effect9.gen(function* () {
12258
+ const toOpt = Option2.getOrUndefined(cfg.to)?.trim() || undefined;
12259
+ const libOpt = Option2.getOrUndefined(cfg.library);
12260
+ const excludeList = splitMulti(cfg.exclude);
12261
+ const isOverwriteMode = Boolean(cfg.overwrite || toOpt);
12262
+ if (isOverwriteMode) {
12263
+ if (cfg.pending || cfg.dirs.length !== 1) {
12264
+ return yield* Effect9.fail(new ConfigError({
12265
+ message: "--overwrite / --to accepts exactly one explicit local directory <dir> and cannot be combined with --pending or multiple directories."
12266
+ }));
12267
+ }
12268
+ if (excludeList.length > 0) {
12269
+ return yield* Effect9.fail(new ConfigError({
12270
+ message: "Cannot combine --exclude with --overwrite / --to."
12271
+ }));
12272
+ }
12273
+ const res = yield* pushOverwriteDirectoryCommand({
12274
+ dir: cfg.dirs[0],
12275
+ ...toOpt ? { toSkillName: toOpt } : {},
12276
+ dryRun: cfg.dryRun,
12277
+ ...libOpt ? { libraryId: libOpt } : {}
12278
+ });
12279
+ const lines = [];
12280
+ if (res.blocked) {
12281
+ lines.push(`[dry-run] BLOCKED overwrite push for '${res.targetSkillName}' (${res.dir}): sensitive or unsafe file(s) detected:`);
12282
+ for (const bf of res.blockedFiles) {
12283
+ lines.push(` - ${bf.path} (${bf.reason})`);
12284
+ }
12285
+ } else if (res.dryRun) {
12286
+ lines.push(`[dry-run] Overwrite preview for '${res.targetSkillName}' (${res.targetSkillId}) from ${res.dir}: updatedMain=${res.updatedMain}, updatedFiles=${res.updatedFiles}, willSetCustomMain=${res.willSetCustomMain} (source directory preserved)`);
12287
+ if (res.descriptionChanged) {
12288
+ lines.push(` Description: '${res.descriptionChanged.from}' -> '${res.descriptionChanged.to}'`);
12289
+ }
12290
+ for (const it of res.items) {
12291
+ lines.push(` [${it.change}] ${it.path} -> ${it.plannedAction}`);
12292
+ }
12293
+ if (res.items.length === 0 && !res.descriptionChanged) {
12294
+ lines.push(" (no differences against remote skill)");
12295
+ }
12296
+ } else {
12297
+ lines.push(`Overwrote '${res.targetSkillName}' (${res.targetSkillId}) from ${res.dir} (files=${res.updatedFiles}, main=${res.updatedMain}, rev=${res.newRevision ?? "none"}, sourceDirPreserved=true)`);
12298
+ }
12299
+ yield* printOut(cfg.json, res, lines.join(`
12300
+ `));
12301
+ if (res.blocked) {
12302
+ process.exitCode = 2;
12303
+ }
12304
+ return;
12305
+ }
12306
+ if (!cfg.pending && cfg.dirs.length === 1 && excludeList.length === 0) {
12307
+ const res = yield* pushWorkdirCommand({
12308
+ workdir: cfg.dirs[0],
12309
+ dryRun: cfg.dryRun,
12310
+ force: cfg.force
12311
+ });
12312
+ yield* printOut(cfg.json, res, res.dryRun ? `[dry-run] Skill '${res.skillName}': updatedFiles=${res.updatedFiles}, updatedMain=${res.updatedMain} (workdir retained)` : `Pushed '${res.skillName}' (files=${res.updatedFiles}, main=${res.updatedMain}, rev=${res.newRevision ?? "none"}, workdirCleaned=${res.workdirCleaned})`);
12313
+ return;
12314
+ }
12315
+ const res = yield* pushWorkdirsBatchCommand({
12316
+ dirs: cfg.dirs,
12317
+ pending: cfg.pending,
12318
+ exclude: excludeList,
10477
12319
  dryRun: cfg.dryRun,
10478
- force: cfg.force
12320
+ force: cfg.force,
12321
+ ...libOpt ? { libraryId: libOpt } : {}
10479
12322
  });
10480
- yield* printOut(cfg.json, res, res.dryRun ? `[dry-run] Skill '${res.skillName}': updatedFiles=${res.updatedFiles}, updatedMain=${res.updatedMain} (workdir retained)` : `Pushed '${res.skillName}' (files=${res.updatedFiles}, main=${res.updatedMain}, rev=${res.newRevision ?? "none"}, workdirCleaned=${res.workdirCleaned})`);
10481
- })).pipe(Command.withDescription("Check baseline, push Files then SKILL.md to Notion, sync local store, and trash workdir"));
12323
+ const lines = [
12324
+ res.dryRun ? `[dry-run] Batch push preview: pushed=${res.pushed.length}, skipped=${res.skipped.length}, failed=${res.failed.length}` : `Batch push complete: pushed=${res.pushed.length}, skipped=${res.skipped.length}, failed=${res.failed.length}, synced=${res.synced}`
12325
+ ];
12326
+ for (const item of res.pushed) {
12327
+ lines.push(` [ok] ${item.skillName}: files=${item.updatedFiles}, main=${item.updatedMain}, rev=${item.newRevision ?? "none"}, cleaned=${item.workdirCleaned}`);
12328
+ }
12329
+ for (const sk of res.skipped) {
12330
+ lines.push(` [skip] ${sk.skillName ?? sk.workdir}: ${sk.reason}`);
12331
+ }
12332
+ for (const fl of res.failed) {
12333
+ lines.push(` [fail] ${fl.skillName ?? fl.workdir} (${fl.code}): ${fl.error}`);
12334
+ }
12335
+ yield* printOut(cfg.json, res, lines.join(`
12336
+ `));
12337
+ if (res.failed.length > 0) {
12338
+ process.exitCode = 2;
12339
+ }
12340
+ })).pipe(Command.withDescription("Push one or more edit workdirs (--pending supported), or directly overwrite an existing Notion skill from a plain directory (--overwrite / --to)"));
10482
12341
  var abortCmd = Command.make("abort", {
10483
12342
  workdir: Argument.String("workdir"),
10484
12343
  json: jsonFlag
10485
- }, (cfg) => Effect7.gen(function* () {
12344
+ }, (cfg) => Effect9.gen(function* () {
10486
12345
  const trashed = yield* abortWorkdirCommand(cfg.workdir);
10487
12346
  yield* printOut(cfg.json, { trashed }, `Moved workdir to system trash: ${trashed}`);
10488
12347
  })).pipe(Command.withDescription("Discard an edit workdir by moving it to the system trash"));
10489
- var workListCmd = Command.make("list", { json: jsonFlag }, (cfg) => Effect7.gen(function* () {
12348
+ var workListCmd = Command.make("list", { json: jsonFlag }, (cfg) => Effect9.gen(function* () {
10490
12349
  const items = yield* listWorkdirsCommand();
10491
12350
  yield* printOut(cfg.json, items, items.length === 0 ? "No active edit workdirs." : items.map((i) => `${i.workdir} (${i.meta.skillName}, created ${i.meta.createdAt})`).join(`
10492
12351
  `));
@@ -10494,13 +12353,16 @@ var workListCmd = Command.make("list", { json: jsonFlag }, (cfg) => Effect7.gen(
10494
12353
  var workCleanCmd = Command.make("clean", {
10495
12354
  days: Flag.Int("days").pipe(Flag.withDefault(7)),
10496
12355
  json: jsonFlag
10497
- }, (cfg) => Effect7.gen(function* () {
12356
+ }, (cfg) => Effect9.gen(function* () {
10498
12357
  const cleaned = yield* cleanWorkdirsCommand(cfg.days);
10499
12358
  yield* printOut(cfg.json, { cleaned }, `Cleaned ${cleaned.length} orphan workdir(s) older than ${cfg.days} day(s).`);
10500
12359
  }));
10501
12360
  var workCmd = Command.make("work").pipe(Command.withDescription("Inspect or clean isolated edit workspaces"), Command.withSubcommands([workListCmd, workCleanCmd]));
10502
12361
  var newCmd = Command.make("new", {
10503
- dir: Argument.String("dir"),
12362
+ dirs: Argument.String("dir").pipe(Argument.atLeast(0)),
12363
+ pending: Flag.Boolean("pending").pipe(Flag.withDescription("Discover unmanaged local skill directories inside configured export roots (requires explicit visibility flag)"), Flag.withDefault(false)),
12364
+ exclude: Flag.String("exclude").pipe(Flag.withDescription("Skill or directory names to exclude (comma-separated or repeatable)"), Flag.atLeast(0)),
12365
+ includeSymlinks: Flag.Boolean("include-symlinks").pipe(Flag.withDescription("Include external non-managed symlinks when scanning with --pending"), Flag.withDefault(false)),
10504
12366
  name: Flag.String("name").pipe(Flag.optional),
10505
12367
  profiles: Flag.String("profiles").pipe(Flag.atLeast(0)),
10506
12368
  scenes: Flag.String("scenes").pipe(Flag.atLeast(0)),
@@ -10510,18 +12372,20 @@ var newCmd = Command.make("new", {
10510
12372
  discoverable: Flag.Boolean("discoverable").pipe(Flag.withDescription("Shorthand for --visibility discoverable"), Flag.withDefault(false)),
10511
12373
  manual: Flag.Boolean("manual").pipe(Flag.withDescription("Shorthand for --visibility manual"), Flag.withDefault(false)),
10512
12374
  default: Flag.Boolean("default").pipe(Flag.withDescription("Alias for --always"), Flag.withDefault(false)),
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")),
12375
+ adopt: Flag.Boolean("adopt").pipe(Flag.withDefault(false), Flag.withDescription("Move local source directory to OS Trash after Notion upload succeeds (automatic when <dir> is inside a configured export root like ~/.agents/skills/<name>)")),
12376
+ noAdopt: Flag.Boolean("no-adopt").pipe(Flag.withDefault(false), Flag.withDescription("Keep local source directory untouched even when <dir> is inside a configured export root")),
12377
+ dryRun: Flag.Boolean("dry-run").pipe(Flag.withDescription("Validate candidate directories, check sensitive files & remote conflicts, and preview adopt/export without writing"), Flag.withDefault(false)),
10515
12378
  library: libraryFlag,
10516
12379
  json: jsonFlag
10517
- }, (cfg) => Effect7.gen(function* () {
12380
+ }, (cfg) => Effect9.gen(function* () {
10518
12381
  if (cfg.adopt && cfg.noAdopt) {
10519
- return yield* Effect7.fail(new ConfigError({ message: "Cannot pass both --adopt and --no-adopt." }));
12382
+ return yield* Effect9.fail(new ConfigError({ message: "Cannot pass both --adopt and --no-adopt." }));
10520
12383
  }
10521
12384
  const nm = Option2.getOrUndefined(cfg.name);
10522
12385
  const visOpt = Option2.getOrUndefined(cfg.visibility);
10523
12386
  const kindOpt = Option2.getOrUndefined(cfg.kind);
10524
12387
  const lib = Option2.getOrUndefined(cfg.library);
12388
+ const excludeList = splitMulti(cfg.exclude);
10525
12389
  const chosenVis = new Set;
10526
12390
  if (visOpt)
10527
12391
  chosenVis.add(visOpt);
@@ -10532,25 +12396,62 @@ var newCmd = Command.make("new", {
10532
12396
  if (cfg.manual)
10533
12397
  chosenVis.add("manual");
10534
12398
  if (chosenVis.size > 1) {
10535
- return yield* Effect7.fail(new ConfigError({
12399
+ return yield* Effect9.fail(new ConfigError({
10536
12400
  message: `Conflicting visibility flags specified (${Array.from(chosenVis).join(", ")}). Pick one.`
10537
12401
  }));
10538
12402
  }
10539
12403
  const visibility = Array.from(chosenVis)[0];
10540
12404
  const adoptOpt = cfg.adopt ? true : cfg.noAdopt ? false : undefined;
10541
- const res = yield* createNewSkillCommand({
10542
- dir: cfg.dir,
12405
+ if (!cfg.pending && cfg.dirs.length === 1 && !cfg.dryRun && excludeList.length === 0) {
12406
+ const res = yield* createNewSkillCommand({
12407
+ dir: cfg.dirs[0],
12408
+ ...nm ? { name: nm } : {},
12409
+ profiles: splitMulti(cfg.profiles),
12410
+ scenes: splitMulti(cfg.scenes),
12411
+ ...visibility ? { visibility } : {},
12412
+ ...kindOpt ? { kind: kindOpt } : {},
12413
+ ...adoptOpt !== undefined ? { adopt: adoptOpt } : {},
12414
+ ...lib ? { libraryId: lib } : {}
12415
+ });
12416
+ 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]" : "";
12417
+ yield* printOut(cfg.json, res, `Created native skill '${res.name}' (${res.skillId}, visibility=${res.visibility}), uploaded ${res.uploadedFiles} supporting file(s)${adoptNote}.`);
12418
+ return;
12419
+ }
12420
+ const res = yield* createNewSkillsBatchCommand({
12421
+ dirs: cfg.dirs,
12422
+ pending: cfg.pending,
12423
+ exclude: excludeList,
12424
+ includeSymlinks: cfg.includeSymlinks,
10543
12425
  ...nm ? { name: nm } : {},
10544
12426
  profiles: splitMulti(cfg.profiles),
10545
12427
  scenes: splitMulti(cfg.scenes),
10546
12428
  ...visibility ? { visibility } : {},
10547
12429
  ...kindOpt ? { kind: kindOpt } : {},
10548
12430
  ...adoptOpt !== undefined ? { adopt: adoptOpt } : {},
12431
+ dryRun: cfg.dryRun,
10549
12432
  ...lib ? { libraryId: lib } : {}
10550
12433
  });
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}.`);
10553
- })).pipe(Command.withDescription("Create a brand-new native skill in Notion from a local directory"));
12434
+ const lines = [
12435
+ res.dryRun ? `[dry-run] New skill preview: ready=${res.created.length}, skipped=${res.skipped.length}, blocked/failed=${res.failed.length} (no Notion or local changes)` : `Batch new complete: created=${res.created.length}, skipped=${res.skipped.length}, failed=${res.failed.length}, synced=${res.synced}`
12436
+ ];
12437
+ for (const item of res.created) {
12438
+ const adoptSummary = res.dryRun ? item.willAdopt ? `, willAdopt=true, willExportAtSourcePath=${item.willExportAtSourcePath}` : ", willAdopt=false" : item.adoptedSourceDir ? `, adopted=true, exportedAtSourcePath=${item.exportedAtSourcePath}` : "";
12439
+ lines.push(` [${res.dryRun ? "plan" : "ok"}] ${item.name} (${item.visibility}, files=${item.fileCount}, bytes=${item.totalBytes}${adoptSummary}) <- ${item.dir}`);
12440
+ }
12441
+ for (const sk of res.skipped) {
12442
+ const tgt = sk.target ? ` -> ${sk.target}` : "";
12443
+ lines.push(` [skip] ${sk.name} (${sk.reason}${tgt}) <- ${sk.dir}`);
12444
+ }
12445
+ for (const fl of res.failed) {
12446
+ const tag = fl.blocked ? "blocked" : fl.conflict ? "conflict" : "fail";
12447
+ lines.push(` [${tag}] ${fl.name ?? fl.dir}: ${fl.error}`);
12448
+ }
12449
+ yield* printOut(cfg.json, res, lines.join(`
12450
+ `));
12451
+ if (res.failed.length > 0) {
12452
+ process.exitCode = 2;
12453
+ }
12454
+ })).pipe(Command.withDescription("Create one or more brand-new native skills in Notion from local directories (supports --pending and --dry-run)"));
10554
12455
  var setCmd = Command.make("set", {
10555
12456
  names: Argument.String("name").pipe(Argument.atLeast(0)),
10556
12457
  source: Flag.String("source").pipe(Flag.optional, Flag.withDescription("Batch-select all skills belonging to this upstream Git Source")),
@@ -10570,7 +12471,7 @@ var setCmd = Command.make("set", {
10570
12471
  require: Flag.String("require").pipe(Flag.atLeast(0)),
10571
12472
  library: libraryFlag,
10572
12473
  json: jsonFlag
10573
- }, (cfg) => Effect7.gen(function* () {
12474
+ }, (cfg) => Effect9.gen(function* () {
10574
12475
  const lib = Option2.getOrUndefined(cfg.library);
10575
12476
  const visOpt = Option2.getOrUndefined(cfg.visibility);
10576
12477
  const kindOpt = Option2.getOrUndefined(cfg.kind);
@@ -10600,7 +12501,7 @@ var attachCmd = Command.make("attach", {
10600
12501
  path: Flag.String("path").pipe(Flag.optional, Flag.withDescription("Skill directory path relative to Git repo root (e.g. skills/my-skill); omit to auto-discover by name under source Subdir")),
10601
12502
  library: libraryFlag,
10602
12503
  json: jsonFlag
10603
- }, (cfg) => Effect7.gen(function* () {
12504
+ }, (cfg) => Effect9.gen(function* () {
10604
12505
  const sp = Option2.getOrUndefined(cfg.path);
10605
12506
  const lib = Option2.getOrUndefined(cfg.library);
10606
12507
  const res = yield* attachSkillCommand({
@@ -10615,7 +12516,7 @@ var detachCmd = Command.make("detach", {
10615
12516
  name: Argument.String("name"),
10616
12517
  library: libraryFlag,
10617
12518
  json: jsonFlag
10618
- }, (cfg) => Effect7.gen(function* () {
12519
+ }, (cfg) => Effect9.gen(function* () {
10619
12520
  const lib = Option2.getOrUndefined(cfg.library);
10620
12521
  const res = yield* detachSkillCommand({
10621
12522
  name: cfg.name,
@@ -10628,7 +12529,7 @@ var resetOverlayCmd = Command.make("reset-overlay", {
10628
12529
  path: Argument.String("path").pipe(Argument.optional),
10629
12530
  library: libraryFlag,
10630
12531
  json: jsonFlag
10631
- }, (cfg) => Effect7.gen(function* () {
12532
+ }, (cfg) => Effect9.gen(function* () {
10632
12533
  const p = Option2.getOrUndefined(cfg.path);
10633
12534
  const lib = Option2.getOrUndefined(cfg.library);
10634
12535
  const res = yield* resetOverlayCommand({
@@ -10642,7 +12543,7 @@ var rmCmd = Command.make("rm", {
10642
12543
  name: Argument.String("name"),
10643
12544
  library: libraryFlag,
10644
12545
  json: jsonFlag
10645
- }, (cfg) => Effect7.gen(function* () {
12546
+ }, (cfg) => Effect9.gen(function* () {
10646
12547
  const lib = Option2.getOrUndefined(cfg.library);
10647
12548
  yield* removeSkillCommand({
10648
12549
  name: cfg.name,
@@ -10653,7 +12554,7 @@ var rmCmd = Command.make("rm", {
10653
12554
  var sourceListCmd = Command.make("list", {
10654
12555
  library: libraryFlag,
10655
12556
  json: jsonFlag
10656
- }, (cfg) => Effect7.gen(function* () {
12557
+ }, (cfg) => Effect9.gen(function* () {
10657
12558
  const lib = Option2.getOrUndefined(cfg.library);
10658
12559
  const sources = yield* listSourcesCommand(lib ? { libraryId: lib } : undefined);
10659
12560
  yield* printOut(cfg.json, sources, sources.length === 0 ? "No upstream sources registered." : sources.map((s) => `${s.enabled ? "[on]" : "[off]"} ${s.name} (${s.policy}) — ${s.repoUrl}@${s.ref} [${s.pinnedCommit.slice(0, 12) || "unpinned"}]`).join(`
@@ -10671,7 +12572,7 @@ var sourceAddCmd = Command.make("add", {
10671
12572
  scenes: Flag.String("scenes").pipe(Flag.withDescription("Initial Scenes tags for discovered skills (comma-separated or repeatable)"), Flag.atLeast(0)),
10672
12573
  library: libraryFlag,
10673
12574
  json: jsonFlag
10674
- }, (cfg) => Effect7.gen(function* () {
12575
+ }, (cfg) => Effect9.gen(function* () {
10675
12576
  const nm = Option2.getOrUndefined(cfg.name);
10676
12577
  const rt = Option2.getOrUndefined(cfg.root);
10677
12578
  const lib = Option2.getOrUndefined(cfg.library);
@@ -10698,7 +12599,7 @@ var sourceSetCmd = Command.make("set", {
10698
12599
  disable: Flag.Boolean("disable").pipe(Flag.withDefault(false)),
10699
12600
  library: libraryFlag,
10700
12601
  json: jsonFlag
10701
- }, (cfg) => Effect7.gen(function* () {
12602
+ }, (cfg) => Effect9.gen(function* () {
10702
12603
  const pol = Option2.getOrUndefined(cfg.policy);
10703
12604
  const refVal = Option2.getOrUndefined(cfg.ref);
10704
12605
  const enable = cfg.enable ? true : cfg.disable ? false : undefined;
@@ -10718,7 +12619,7 @@ var sourceSyncCmd = Command.make("sync", {
10718
12619
  updatePinned: Flag.Boolean("update-pinned").pipe(Flag.withDefault(false)),
10719
12620
  library: libraryFlag,
10720
12621
  json: jsonFlag
10721
- }, (cfg) => Effect7.gen(function* () {
12622
+ }, (cfg) => Effect9.gen(function* () {
10722
12623
  const rt = Option2.getOrUndefined(cfg.root);
10723
12624
  const lib = Option2.getOrUndefined(cfg.library);
10724
12625
  const res = yield* syncSourceSkillsCommand({
@@ -10763,7 +12664,7 @@ var upstreamCheckCmd = Command.make("check", {
10763
12664
  strictDrift: Flag.Boolean("strict-drift").pipe(Flag.withDefault(false)),
10764
12665
  library: libraryFlag,
10765
12666
  json: jsonFlag
10766
- }, (cfg) => Effect7.gen(function* () {
12667
+ }, (cfg) => Effect9.gen(function* () {
10767
12668
  const sq = Option2.getOrUndefined(cfg.source);
10768
12669
  const tSec = Option2.getOrUndefined(cfg.timeoutSec);
10769
12670
  const repFile = Option2.getOrUndefined(cfg.reportFile);
@@ -10790,7 +12691,7 @@ var upstreamApplyCmd = Command.make("apply", {
10790
12691
  strictDrift: Flag.Boolean("strict-drift").pipe(Flag.withDefault(false)),
10791
12692
  library: libraryFlag,
10792
12693
  json: jsonFlag
10793
- }, (cfg) => Effect7.gen(function* () {
12694
+ }, (cfg) => Effect9.gen(function* () {
10794
12695
  const sq = Option2.getOrUndefined(cfg.source);
10795
12696
  const maxS = Option2.getOrUndefined(cfg.maxSources);
10796
12697
  const tSec = Option2.getOrUndefined(cfg.timeoutSec);
@@ -10818,7 +12719,7 @@ var scheduleInstallCmd = Command.make("install", {
10818
12719
  upstreamEvery: Flag.String("upstream-every").pipe(Flag.optional),
10819
12720
  library: libraryFlag,
10820
12721
  json: jsonFlag
10821
- }, (cfg) => Effect7.gen(function* () {
12722
+ }, (cfg) => Effect9.gen(function* () {
10822
12723
  const upEvery = Option2.getOrUndefined(cfg.upstreamEvery);
10823
12724
  const lib = Option2.getOrUndefined(cfg.library);
10824
12725
  const res = yield* installScheduleCommand({
@@ -10839,7 +12740,7 @@ var scheduleInstallCmd = Command.make("install", {
10839
12740
  `);
10840
12741
  yield* printOut(cfg.json, res, text);
10841
12742
  })).pipe(Command.withDescription("Install OS-native background sync timers (launchd / systemd --user) with clean-room preflight"));
10842
- var scheduleStatusCmd = Command.make("status", { json: jsonFlag }, (cfg) => Effect7.gen(function* () {
12743
+ var scheduleStatusCmd = Command.make("status", { json: jsonFlag }, (cfg) => Effect9.gen(function* () {
10843
12744
  const res = yield* statusScheduleCommand();
10844
12745
  const lines = [
10845
12746
  `Platform: ${res.platform}`,
@@ -10857,7 +12758,7 @@ var scheduleStatusCmd = Command.make("status", { json: jsonFlag }, (cfg) => Effe
10857
12758
  yield* printOut(cfg.json, res, lines.join(`
10858
12759
  `));
10859
12760
  })).pipe(Command.withDescription("Inspect background timer health, credentials status, and logs"));
10860
- var scheduleUninstallCmd = Command.make("uninstall", { json: jsonFlag }, (cfg) => Effect7.gen(function* () {
12761
+ var scheduleUninstallCmd = Command.make("uninstall", { json: jsonFlag }, (cfg) => Effect9.gen(function* () {
10861
12762
  const res = yield* uninstallScheduleCommand();
10862
12763
  yield* printOut(cfg.json, res, res.removedUnits.length === 0 ? "No installed ntn-skills schedule units found." : `Uninstalled and moved ${res.removedUnits.length} unit(s) to system trash:
10863
12764
  ${res.removedUnits.map((u) => ` ${u}`).join(`
@@ -10870,9 +12771,9 @@ var scheduleRunCmd = Command.make("run", {
10870
12771
  strictDrift: Flag.Boolean("strict-drift").pipe(Flag.withDefault(false)),
10871
12772
  library: libraryFlag,
10872
12773
  json: jsonFlag
10873
- }, (cfg) => Effect7.gen(function* () {
12774
+ }, (cfg) => Effect9.gen(function* () {
10874
12775
  if (cfg.job !== "sync" && cfg.job !== "sync-full" && cfg.job !== "upstream") {
10875
- return yield* Effect7.fail(new ConfigError({
12776
+ return yield* Effect9.fail(new ConfigError({
10876
12777
  message: `Unknown scheduled job '${cfg.job}'. Expected 'sync', 'sync-full', or 'upstream'.`
10877
12778
  }));
10878
12779
  }
@@ -10899,9 +12800,9 @@ var scheduleExportCmd = Command.make("export", {
10899
12800
  timeoutSec: Flag.Int("timeout-sec").pipe(Flag.withDefault(600)),
10900
12801
  library: libraryFlag,
10901
12802
  json: jsonFlag
10902
- }, (cfg) => Effect7.gen(function* () {
12803
+ }, (cfg) => Effect9.gen(function* () {
10903
12804
  if (cfg.target !== "dagu" && cfg.target !== "github-actions" && cfg.target !== "crontab") {
10904
- return yield* Effect7.fail(new ConfigError({
12805
+ return yield* Effect9.fail(new ConfigError({
10905
12806
  message: `Unknown export target '${cfg.target}'. Expected 'dagu', 'github-actions', or 'crontab'.`
10906
12807
  }));
10907
12808
  }
@@ -10926,8 +12827,8 @@ var scheduleCmd = Command.make("schedule").pipe(Command.withDescription("Manage
10926
12827
  var telemetryCmd = Command.make("telemetry", {
10927
12828
  hours: Flag.Int("hours").pipe(Flag.withDefault(24)),
10928
12829
  json: jsonFlag
10929
- }, (cfg) => Effect7.gen(function* () {
10930
- const rep = yield* Effect7.promise(() => summarizeTelemetry(cfg.hours));
12830
+ }, (cfg) => Effect9.gen(function* () {
12831
+ const rep = yield* Effect9.promise(() => summarizeTelemetry(cfg.hours));
10931
12832
  const lines = [
10932
12833
  `Window: last ${rep.windowHours}h | Total requests: ${rep.totalRequests} | Total bytes: ${rep.totalBytes} | Timeouts (>=60s): ${rep.timeoutsOver60s}`,
10933
12834
  ...Object.entries(rep.byCaller).map(([k, b]) => ` [${k}] req=${b.requests}, bytes=${b.bytes}, maxMs=${b.maxDurationMs}, timeouts60s=${b.timeoutsOver60s}, errors=${b.errors}`)
@@ -10942,14 +12843,14 @@ var skillCmd = Command.make("skill", {
10942
12843
  dest: Flag.String("dest").pipe(Flag.optional, Flag.withDescription("Target skills directory for --install/--uninstall (default: ~/.agents/skills)")),
10943
12844
  force: Flag.Boolean("force").pipe(Flag.withDefault(false), Flag.withDescription("Replace existing library-managed or foreign entry on --install")),
10944
12845
  json: jsonFlag
10945
- }, (cfg) => Effect7.gen(function* () {
12846
+ }, (cfg) => Effect9.gen(function* () {
10946
12847
  const store = yield* StorePort;
10947
12848
  const destDir = Option2.getOrUndefined(cfg.dest);
10948
12849
  if (cfg.install && cfg.uninstall) {
10949
- return yield* Effect7.fail(new ConfigError({ message: "Cannot pass both --install and --uninstall." }));
12850
+ return yield* Effect9.fail(new ConfigError({ message: "Cannot pass both --install and --uninstall." }));
10950
12851
  }
10951
12852
  if (cfg.install) {
10952
- const res = yield* Effect7.tryPromise({
12853
+ const res = yield* Effect9.tryPromise({
10953
12854
  try: () => installBundledSkill({
10954
12855
  ...destDir ? { destDir } : {},
10955
12856
  storeRoot: store.paths.storeRoot,
@@ -10961,7 +12862,7 @@ var skillCmd = Command.make("skill", {
10961
12862
  return;
10962
12863
  }
10963
12864
  if (cfg.uninstall) {
10964
- const res = yield* Effect7.tryPromise({
12865
+ const res = yield* Effect9.tryPromise({
10965
12866
  try: () => uninstallBundledSkill({
10966
12867
  ...destDir ? { destDir } : {},
10967
12868
  storeRoot: store.paths.storeRoot
@@ -10971,7 +12872,7 @@ var skillCmd = Command.make("skill", {
10971
12872
  yield* printOut(cfg.json, res, res.status === "managed_by_library" ? `Skipped: ${res.linkPath} is managed by Notion sync, not bundled install.` : `Bundled skill (${res.status}): ${res.linkPath}`);
10972
12873
  return;
10973
12874
  }
10974
- const payload = yield* Effect7.tryPromise({
12875
+ const payload = yield* Effect9.tryPromise({
10975
12876
  try: () => readBundledSkill(),
10976
12877
  catch: (e) => e instanceof StoreError ? e : new StoreError({ path: "assets/ntn-skills/SKILL.md", message: String(e) })
10977
12878
  });
@@ -10990,17 +12891,17 @@ var mcpCmd = Command.make("mcp", {
10990
12891
  library: libraryFlag,
10991
12892
  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
12893
  instructions: Flag.String("instructions").pipe(Flag.withDescription("Override MCP initialize instructions text"), Flag.optional)
10993
- }, (cfg) => Effect7.gen(function* () {
12894
+ }, (cfg) => Effect9.gen(function* () {
10994
12895
  const lib = Option2.getOrUndefined(cfg.library);
10995
12896
  const customInstructions = Option2.getOrUndefined(cfg.instructions);
10996
12897
  const allowedScenes = splitMulti(cfg.scenes);
10997
- const services = yield* Effect7.context();
10998
- yield* Effect7.promise(() => runStdioMcpServer({
12898
+ const services = yield* Effect9.context();
12899
+ yield* Effect9.promise(() => runStdioMcpServer({
10999
12900
  version: BUNDLED_SKILL_VERSION,
11000
12901
  ...lib ? { libraryId: lib } : {},
11001
12902
  ...allowedScenes.length > 0 ? { allowedScenes } : {},
11002
12903
  ...customInstructions !== undefined ? { instructions: customInstructions } : {},
11003
- runCore: (eff) => Effect7.runPromise(eff.pipe(Effect7.provide(services)))
12904
+ runCore: (eff) => Effect9.runPromise(eff.pipe(Effect9.provide(services)))
11004
12905
  }));
11005
12906
  })).pipe(Command.withDescription("Run a read-only stdio JSON-RPC 2.0 MCP server exposing skill_find and skill_load"));
11006
12907
  var rootCommand = Command.make("ntn-skills").pipe(Command.withDescription("Notion 3-table skill control-plane synchronizer & local-native CLI (v2)"), Command.withSubcommands([
@@ -11043,10 +12944,10 @@ var DOMAIN_ERROR_TAGS = new Set([
11043
12944
  ]);
11044
12945
  function runCli(argv) {
11045
12946
  const appLayer = Layer5.mergeAll(NodeServices.layer, makeCoreLiveLayer());
11046
- return Command.runWith(rootCommand, { version: BUNDLED_SKILL_VERSION })(argv).pipe(Effect7.provide(appLayer), Effect7.catch((err) => {
12947
+ return Command.runWith(rootCommand, { version: BUNDLED_SKILL_VERSION })(argv).pipe(Effect9.provide(appLayer), Effect9.catch((err) => {
11047
12948
  const tag = err?._tag;
11048
12949
  if (!tag || !DOMAIN_ERROR_TAGS.has(tag)) {
11049
- return Effect7.fail(err);
12950
+ return Effect9.fail(err);
11050
12951
  }
11051
12952
  const code = classifyErrorExitCode(err);
11052
12953
  const msg = err && typeof err === "object" && "message" in err ? String(err.message) : String(err);