ntn-skills 2.1.0 → 2.2.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
@@ -1947,7 +1947,8 @@ function makeStoreService(overrides) {
1947
1947
  retentionDays = 14,
1948
1948
  repoTreeGraceMs = 3600000,
1949
1949
  repoSubtreeRetentionDays = 7,
1950
- repoGitRetentionDays = 14
1950
+ repoGitRetentionDays = 14,
1951
+ dryRun = false
1951
1952
  }) => Effect.tryPromise({
1952
1953
  try: async () => {
1953
1954
  const pruned = [];
@@ -2002,7 +2003,8 @@ function makeStoreService(overrides) {
2002
2003
  continue;
2003
2004
  if (normalizedProtected.has(v.dir) || normalizedProtected.has(v.realDir))
2004
2005
  continue;
2005
- await removeInternalCachePath(v.realDir);
2006
+ if (!dryRun)
2007
+ await removeInternalCachePath(v.realDir);
2006
2008
  pruned.push(v.realDir);
2007
2009
  }
2008
2010
  }
@@ -2034,7 +2036,8 @@ function makeStoreService(overrides) {
2034
2036
  if (nowMs - st.mtimeMs <= repoTreeGraceMs)
2035
2037
  continue;
2036
2038
  const real = await fsp.realpath(full).catch(() => nodePath.resolve(full));
2037
- await removeInternalCachePath(real);
2039
+ if (!dryRun)
2040
+ await removeInternalCachePath(real);
2038
2041
  pruned.push(real);
2039
2042
  }
2040
2043
  const subtreesRoot = nodePath.join(paths.reposRoot, "subtrees");
@@ -2058,7 +2061,8 @@ function makeStoreService(overrides) {
2058
2061
  if (nowMs - st.mtimeMs <= subRetMs)
2059
2062
  continue;
2060
2063
  const real = await fsp.realpath(full).catch(() => nodePath.resolve(full));
2061
- await removeInternalCachePath(real);
2064
+ if (!dryRun)
2065
+ await removeInternalCachePath(real);
2062
2066
  pruned.push(real);
2063
2067
  }
2064
2068
  const gitRoot = nodePath.join(paths.reposRoot, "git");
@@ -2073,7 +2077,8 @@ function makeStoreService(overrides) {
2073
2077
  if (nowMs - st.mtimeMs <= gitRetMs)
2074
2078
  continue;
2075
2079
  const real = await fsp.realpath(full).catch(() => nodePath.resolve(full));
2076
- await removeInternalCachePath(real);
2080
+ if (!dryRun)
2081
+ await removeInternalCachePath(real);
2077
2082
  pruned.push(real);
2078
2083
  }
2079
2084
  const tmpRoot = nodePath.join(paths.reposRoot, ".tmp");
@@ -2085,7 +2090,8 @@ function makeStoreService(overrides) {
2085
2090
  if (!st || !holderDead && nowMs - st.mtimeMs <= repoTreeGraceMs)
2086
2091
  continue;
2087
2092
  const real = await fsp.realpath(full).catch(() => nodePath.resolve(full));
2088
- await removeInternalCachePath(real);
2093
+ if (!dryRun)
2094
+ await removeInternalCachePath(real);
2089
2095
  pruned.push(real);
2090
2096
  }
2091
2097
  }
@@ -4695,6 +4701,191 @@ function materializeOneSkill(args) {
4695
4701
  };
4696
4702
  });
4697
4703
  }
4704
+ function planExportTarget(args) {
4705
+ return Effect4.gen(function* () {
4706
+ const onConflict = args.onConflict ?? "error";
4707
+ const destRoot = resolveHomePath(args.target.dir);
4708
+ const wouldSkipConflicts = [];
4709
+ const warnings = [];
4710
+ const seenNames = new Map;
4711
+ const duplicateNames = new Map;
4712
+ for (const entry of args.selectedEntries) {
4713
+ const prev = seenNames.get(entry.name);
4714
+ if (prev && prev.skillId !== entry.skillId) {
4715
+ if (onConflict === "error") {
4716
+ return yield* Effect4.fail(new ConflictError({
4717
+ kind: "duplicate_name",
4718
+ message: `Duplicate active skill name '${entry.name}' in Notion (${prev.skillId} vs ${entry.skillId}); refusing export.`,
4719
+ details: [prev.skillId, entry.skillId]
4720
+ }));
4721
+ }
4722
+ const ids = duplicateNames.get(entry.name) ?? new Set([prev.skillId]);
4723
+ ids.add(entry.skillId);
4724
+ duplicateNames.set(entry.name, ids);
4725
+ continue;
4726
+ }
4727
+ seenNames.set(entry.name, entry);
4728
+ }
4729
+ for (const [dupName, ids] of duplicateNames) {
4730
+ seenNames.delete(dupName);
4731
+ const idList = [...ids].sort().join(", ");
4732
+ const entryPath = nodePath5.join(destRoot, dupName);
4733
+ const reason = `Duplicate active skill name '${dupName}' in Notion (${idList}); refusing export.`;
4734
+ wouldSkipConflicts.push({
4735
+ name: dupName,
4736
+ path: entryPath,
4737
+ kind: "duplicate_name",
4738
+ reason
4739
+ });
4740
+ warnings.push(`Skipped exporting '${dupName}' to '${entryPath}': duplicate active skill name in Notion (${idList}); resolve duplicate names in Notion and re-sync.`);
4741
+ }
4742
+ const storeRootResolved = nodePath5.resolve(args.storeRoot);
4743
+ const storeRootReal = yield* Effect4.promise(() => fsp5.realpath(storeRootResolved).catch(() => storeRootResolved));
4744
+ return yield* Effect4.tryPromise({
4745
+ try: async () => {
4746
+ const destExists = await fsp5.stat(destRoot).then((s) => s.isDirectory()).catch(() => false);
4747
+ const desiredNames = new Set([...seenNames.keys(), ...duplicateNames.keys()]);
4748
+ const wouldWrite = [];
4749
+ const wouldRemove = [];
4750
+ let publishableCount = 0;
4751
+ const isManagedStoreLink = (linkTargetAbs, linkTargetReal) => {
4752
+ const prefixes = [
4753
+ `${storeRootResolved}${nodePath5.sep}`,
4754
+ `${storeRootReal}${nodePath5.sep}`
4755
+ ];
4756
+ return prefixes.some((pref) => linkTargetAbs.startsWith(pref) || Boolean(linkTargetReal?.startsWith(pref)));
4757
+ };
4758
+ const isManagedCopyDir = async (dirPath) => fsp5.stat(nodePath5.join(dirPath, ".ntn-managed-copy.json")).then((s) => s.isFile()).catch(() => false);
4759
+ for (const [skillName, entry] of seenNames) {
4760
+ const storePath = entry.materializedPath;
4761
+ if (!storePath) {
4762
+ throw new Error(`Skill '${skillName}' has no planned or materialized store path ready for export.`);
4763
+ }
4764
+ const storePathResolved = nodePath5.resolve(storePath);
4765
+ const storePathReal = await fsp5.realpath(storePathResolved).catch(() => storePathResolved);
4766
+ if (!destExists) {
4767
+ publishableCount++;
4768
+ wouldWrite.push(skillName);
4769
+ continue;
4770
+ }
4771
+ const entryPath = nodePath5.join(destRoot, skillName);
4772
+ const lst = await fsp5.lstat(entryPath).catch(() => null);
4773
+ if (!lst) {
4774
+ publishableCount++;
4775
+ wouldWrite.push(skillName);
4776
+ continue;
4777
+ }
4778
+ if (lst.isSymbolicLink()) {
4779
+ const rawLink = await fsp5.readlink(entryPath);
4780
+ const resolvedLink = nodePath5.resolve(nodePath5.dirname(entryPath), rawLink);
4781
+ const realResolvedLink = await fsp5.realpath(resolvedLink).catch(() => resolvedLink);
4782
+ if (!isManagedStoreLink(resolvedLink, realResolvedLink)) {
4783
+ const reason = `Refusing to overwrite non-managed symlink '${entryPath}' -> '${rawLink}'.`;
4784
+ if (onConflict === "error") {
4785
+ throw new ConflictError({ kind: "foreign_target", message: reason });
4786
+ }
4787
+ wouldSkipConflicts.push({
4788
+ name: skillName,
4789
+ path: entryPath,
4790
+ kind: "foreign_symlink",
4791
+ linkTarget: rawLink,
4792
+ reason
4793
+ });
4794
+ warnings.push(`Skipped exporting '${skillName}' to '${entryPath}': non-managed symlink -> '${rawLink}' exists (left untouched; remove/relocate it or run 'ntn-skills doctor' to inspect).`);
4795
+ continue;
4796
+ }
4797
+ publishableCount++;
4798
+ if (args.target.mode === "symlink") {
4799
+ if (resolvedLink !== storePathResolved && realResolvedLink !== storePathReal) {
4800
+ wouldWrite.push(skillName);
4801
+ }
4802
+ } else {
4803
+ wouldWrite.push(skillName);
4804
+ }
4805
+ } else if (lst.isDirectory()) {
4806
+ if (!await isManagedCopyDir(entryPath)) {
4807
+ const reason = `Refusing to overwrite non-managed foreign directory '${entryPath}'.`;
4808
+ if (onConflict === "error") {
4809
+ throw new ConflictError({ kind: "foreign_target", message: reason });
4810
+ }
4811
+ wouldSkipConflicts.push({
4812
+ name: skillName,
4813
+ path: entryPath,
4814
+ kind: "foreign_directory",
4815
+ reason
4816
+ });
4817
+ 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).`);
4818
+ continue;
4819
+ }
4820
+ publishableCount++;
4821
+ if (args.target.mode === "symlink") {
4822
+ wouldWrite.push(skillName);
4823
+ } else {
4824
+ const markerFile = nodePath5.join(entryPath, ".ntn-managed-copy.json");
4825
+ const existingMarker = await fsp5.readFile(markerFile, "utf8").then((r) => JSON.parse(r)).catch(() => null);
4826
+ if (existingMarker?.effectiveRev !== entry.effectiveRev) {
4827
+ wouldWrite.push(skillName);
4828
+ }
4829
+ }
4830
+ } else {
4831
+ const reason = `Refusing to overwrite non-managed file '${entryPath}'.`;
4832
+ if (onConflict === "error") {
4833
+ throw new ConflictError({ kind: "foreign_target", message: reason });
4834
+ }
4835
+ wouldSkipConflicts.push({
4836
+ name: skillName,
4837
+ path: entryPath,
4838
+ kind: "foreign_file",
4839
+ reason
4840
+ });
4841
+ warnings.push(`Skipped exporting '${skillName}' to '${entryPath}': non-managed file exists (left untouched; remove/relocate it or run 'ntn-skills doctor' to inspect).`);
4842
+ }
4843
+ }
4844
+ if (destExists) {
4845
+ const existingEntries = await fsp5.readdir(destRoot);
4846
+ for (const name of existingEntries) {
4847
+ if (name.startsWith(".") || desiredNames.has(name))
4848
+ continue;
4849
+ const full = nodePath5.join(destRoot, name);
4850
+ const lst = await fsp5.lstat(full).catch(() => null);
4851
+ if (!lst)
4852
+ continue;
4853
+ if (lst.isSymbolicLink()) {
4854
+ const rawLink = await fsp5.readlink(full);
4855
+ const resolvedLink = nodePath5.resolve(nodePath5.dirname(full), rawLink);
4856
+ const realResolvedLink = await fsp5.realpath(resolvedLink).catch(() => resolvedLink);
4857
+ if (isManagedStoreLink(resolvedLink, realResolvedLink)) {
4858
+ if (resolvedLink.includes(`${nodePath5.sep}_bundled${nodePath5.sep}`)) {
4859
+ continue;
4860
+ }
4861
+ wouldRemove.push(name);
4862
+ }
4863
+ } else if (lst.isDirectory() && await isManagedCopyDir(full)) {
4864
+ const marker = await fsp5.readFile(nodePath5.join(full, ".ntn-managed-copy.json"), "utf8").then((raw) => JSON.parse(raw)).catch(() => null);
4865
+ if (marker?.bundled === true)
4866
+ continue;
4867
+ wouldRemove.push(name);
4868
+ }
4869
+ }
4870
+ }
4871
+ const routerName = args.routerSkill ?? null;
4872
+ const routerSkipped = Boolean(routerName && wouldSkipConflicts.some((c) => c.name === routerName));
4873
+ return {
4874
+ dest: destRoot,
4875
+ mode: args.target.mode,
4876
+ wouldWrite: wouldWrite.sort(),
4877
+ wouldRemove: wouldRemove.sort(),
4878
+ wouldSkipConflicts,
4879
+ routerIncluded: Boolean(routerName && !routerSkipped),
4880
+ routerSkill: routerName && !routerSkipped ? routerName : null,
4881
+ totalSkills: publishableCount,
4882
+ warnings
4883
+ };
4884
+ },
4885
+ catch: (err) => err instanceof ConflictError ? err : new StoreError({ path: destRoot, message: String(err) })
4886
+ });
4887
+ });
4888
+ }
4698
4889
  function publishExportTarget(args) {
4699
4890
  return Effect4.gen(function* () {
4700
4891
  const onConflict = args.onConflict ?? "error";
@@ -5007,7 +5198,8 @@ function syncCommand(options = {}) {
5007
5198
  const upstream = yield* UpstreamPort;
5008
5199
  const { config, libraryId, binding } = yield* loadResolvedLibrary(options.libraryId);
5009
5200
  const dedupeWindowMs = options.dedupeWindowMs ?? 5000;
5010
- return yield* store.withExclusiveLock(`sync-${libraryId.slice(0, 8)}`, Effect4.gen(function* () {
5201
+ const isDryRun = Boolean(options.dryRun);
5202
+ const runSync = Effect4.gen(function* () {
5011
5203
  const currentCatalog = yield* store.readCatalog();
5012
5204
  const prevLib = currentCatalog.libraries[libraryId] ?? {
5013
5205
  watermark: null,
@@ -5020,7 +5212,7 @@ function syncCommand(options = {}) {
5020
5212
  };
5021
5213
  const resolvedExports = yield* resolveConfiguredExports(config, store.paths.configPath);
5022
5214
  const allExportTargets = resolvedExports.targets.map((r) => r.target);
5023
- if (!options.full && prevLib.lastSyncedAt && dedupeWindowMs > 0) {
5215
+ if (!isDryRun && !options.full && prevLib.lastSyncedAt && dedupeWindowMs > 0) {
5024
5216
  const age = Date.now() - Date.parse(prevLib.lastSyncedAt);
5025
5217
  if (age >= 0 && age < dedupeWindowMs) {
5026
5218
  const libEntries = currentCatalog.entries.filter((e) => e.libraryId === libraryId);
@@ -5205,7 +5397,7 @@ function syncCommand(options = {}) {
5205
5397
  process.stderr.write(`[ntn-skills] ${msg}
5206
5398
  `);
5207
5399
  };
5208
- const saveIntermediateCheckpoint = (mainCacheSnapshot, fileCacheSnapshot) => store.writeCatalog({
5400
+ const saveIntermediateCheckpoint = (mainCacheSnapshot, fileCacheSnapshot) => isDryRun ? Effect4.void : store.writeCatalog({
5209
5401
  version: 2,
5210
5402
  updatedAt: currentCatalog.updatedAt || syncStartIso,
5211
5403
  libraries: {
@@ -5270,7 +5462,9 @@ function syncCommand(options = {}) {
5270
5462
  const mutableMainCache = {
5271
5463
  ...workingLibState.mainHashCache
5272
5464
  };
5273
- const mutableFileBodyCache = { ...workingLibState.fileBodyCache };
5465
+ const mutableFileBodyCache = {
5466
+ ...workingLibState.fileBodyCache
5467
+ };
5274
5468
  let mainCacheEvicted = false;
5275
5469
  for (const staleId of staleMainCacheIds) {
5276
5470
  if (staleId in mutableMainCache) {
@@ -5399,12 +5593,13 @@ function syncCommand(options = {}) {
5399
5593
  const prevEntryById = new Map(currentCatalog.entries.filter((e) => e.libraryId === libraryId).map((e) => [e.skillId, e]));
5400
5594
  const materializedPaths = new Map;
5401
5595
  let materializedCount = 0;
5596
+ const plannedMaterializations = [];
5402
5597
  const closureList = [...closureIds];
5403
5598
  const coldCandidates = closureList.filter((sid) => {
5404
5599
  const prev = prevEntryById.get(sid);
5405
5600
  return !prev?.materializedPath || prev.effectiveRev !== getEffectiveRevFor(sid);
5406
5601
  });
5407
- if (coldCandidates.length >= 5) {
5602
+ if (!isDryRun && coldCandidates.length >= 5) {
5408
5603
  emitSyncProgress(`Materializing ${coldCandidates.length} updated skill snapshot(s)...`);
5409
5604
  }
5410
5605
  let finishedColdMat = 0;
@@ -5436,6 +5631,18 @@ function syncCommand(options = {}) {
5436
5631
  revMemo.delete(sid);
5437
5632
  }
5438
5633
  const rev = getEffectiveRevFor(sid);
5634
+ if (isDryRun) {
5635
+ const alreadyReady = yield* store.hasVerifiedStorePackage(libraryId, sid, rev);
5636
+ const expectedDir = store.getStoreSkillDir(libraryId, sid, rev);
5637
+ if (alreadyReady) {
5638
+ const real = yield* Effect4.tryPromise(() => fsp5.realpath(expectedDir).catch(() => expectedDir)).pipe(Effect4.catch(() => Effect4.succeed(expectedDir)));
5639
+ materializedPaths.set(sid, real);
5640
+ } else {
5641
+ plannedMaterializations.push(sk.name);
5642
+ materializedPaths.set(sid, expectedDir);
5643
+ }
5644
+ return;
5645
+ }
5439
5646
  const matRes = yield* materializeOneSkill({
5440
5647
  libraryId,
5441
5648
  libState: workingLibState,
@@ -5567,7 +5774,7 @@ function syncCommand(options = {}) {
5567
5774
  byNameRoot: store.paths.byNameRoot
5568
5775
  });
5569
5776
  const routerSkillId = `_router-${routerName}`;
5570
- const routerStoreDir = yield* store.publishImmutablePackage({
5777
+ const routerStoreDir = isDryRun ? store.getStoreSkillDir(libraryId, routerSkillId, synth.effectiveRev) : yield* store.publishImmutablePackage({
5571
5778
  libraryId,
5572
5779
  skillId: routerSkillId,
5573
5780
  effectiveRev: synth.effectiveRev,
@@ -5601,7 +5808,11 @@ function syncCommand(options = {}) {
5601
5808
  };
5602
5809
  }
5603
5810
  const finalExportEntries = routerEntry ? [...selectedEntries, routerEntry] : selectedEntries;
5604
- preparedExports.push({ target: exp, finalExportEntries });
5811
+ preparedExports.push({
5812
+ target: exp,
5813
+ finalExportEntries,
5814
+ routerSkill: routerEntry ? routerName : null
5815
+ });
5605
5816
  manifestExports.push({
5606
5817
  dir: exp.dir,
5607
5818
  mode: exp.mode,
@@ -5636,13 +5847,6 @@ function syncCommand(options = {}) {
5636
5847
  sourcePath: e.sourcePath
5637
5848
  }))
5638
5849
  };
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
5850
  const otherLibEntries = currentCatalog.entries.filter((e) => e.libraryId !== libraryId);
5647
5851
  for (const e of otherLibEntries) {
5648
5852
  if (e.materializedPath)
@@ -5657,21 +5861,52 @@ function syncCommand(options = {}) {
5657
5861
  },
5658
5862
  entries: [...otherLibEntries, ...nextLibEntries]
5659
5863
  };
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
- });
5864
+ if (!isDryRun) {
5865
+ yield* Effect4.tryPromise({
5866
+ try: () => atomicWriteJson(store.paths.manifestPath, manifestDoc),
5867
+ catch: (err) => new StoreError({
5868
+ path: store.paths.manifestPath,
5869
+ message: `Failed writing manifest.json: ${String(err)}`
5870
+ })
5871
+ });
5872
+ yield* store.writeCatalog(nextCatalog);
5873
+ yield* Effect4.tryPromise({
5874
+ try: () => reconcileByNameDirectory({
5875
+ byNameRoot: store.paths.byNameRoot,
5876
+ entries: nextCatalog.entries,
5877
+ defaultLibraryId: normalizeUuid(config.default_library)
5878
+ }),
5879
+ catch: (err) => new StoreError({
5880
+ path: store.paths.byNameRoot,
5881
+ message: `Failed reconciling by-name links: ${String(err)}`
5882
+ })
5883
+ });
5884
+ }
5672
5885
  let exportedCount = 0;
5673
5886
  let allExportsScanned = true;
5674
- for (const { target: exp, finalExportEntries } of preparedExports) {
5887
+ const plannedExports = [];
5888
+ for (const { target: exp, finalExportEntries, routerSkill } of preparedExports) {
5889
+ if (isDryRun) {
5890
+ const planRes = yield* planExportTarget({
5891
+ target: exp,
5892
+ selectedEntries: finalExportEntries,
5893
+ storeRoot: store.paths.storeRoot,
5894
+ onConflict: "skip",
5895
+ routerSkill
5896
+ }).pipe(Effect4.result);
5897
+ if (planRes._tag === "Failure") {
5898
+ allExportsScanned = false;
5899
+ const err = planRes.failure;
5900
+ const errMsg = err && typeof err === "object" && "message" in err ? String(err.message) : String(err);
5901
+ warnings.push(`Export target '${exp.dir}' failed and was isolated: ${errMsg}`);
5902
+ continue;
5903
+ }
5904
+ const plan = planRes.success;
5905
+ plannedExports.push(plan);
5906
+ if (plan.warnings.length > 0)
5907
+ warnings.push(...plan.warnings);
5908
+ continue;
5909
+ }
5675
5910
  const pubResult = yield* publishExportTarget({
5676
5911
  target: exp,
5677
5912
  selectedEntries: finalExportEntries,
@@ -5711,7 +5946,12 @@ function syncCommand(options = {}) {
5711
5946
  });
5712
5947
  }
5713
5948
  }
5714
- const pruned = allExportsScanned ? yield* store.pruneStore({ protectedDirs, activeRepoCommits }) : [];
5949
+ const pruned = allExportsScanned ? yield* store.pruneStore({
5950
+ protectedDirs,
5951
+ activeRepoCommits,
5952
+ ...options.nowMs !== undefined ? { nowMs: options.nowMs } : {},
5953
+ dryRun: isDryRun
5954
+ }) : [];
5715
5955
  if (!allExportsScanned) {
5716
5956
  warnings.push("Skipped store GC pruning during this sync because one or more export targets failed to scan.");
5717
5957
  }
@@ -5746,6 +5986,7 @@ function syncCommand(options = {}) {
5746
5986
  })));
5747
5987
  return {
5748
5988
  libraryId,
5989
+ ...isDryRun ? { dryRun: true } : {},
5749
5990
  coalesced: false,
5750
5991
  full: isFull,
5751
5992
  catalogCount: nextLibEntries.length,
@@ -5754,9 +5995,14 @@ function syncCommand(options = {}) {
5754
5995
  discoverable: manifestDoc.counts.discoverable,
5755
5996
  manual: manifestDoc.counts.manual
5756
5997
  },
5757
- materializedCount,
5758
- exportedCount,
5759
- prunedCount: pruned.length,
5998
+ materializedCount: isDryRun ? 0 : materializedCount,
5999
+ exportedCount: isDryRun ? 0 : exportedCount,
6000
+ prunedCount: isDryRun ? 0 : pruned.length,
6001
+ ...isDryRun ? {
6002
+ plannedMaterializations: [...new Set(plannedMaterializations)].sort(),
6003
+ plannedPrunes: pruned,
6004
+ plannedExports
6005
+ } : {},
5760
6006
  pulled: {
5761
6007
  added: addedNames.sort(),
5762
6008
  updated: updatedNames.sort(),
@@ -5765,7 +6011,8 @@ function syncCommand(options = {}) {
5765
6011
  localPending,
5766
6012
  warnings
5767
6013
  };
5768
- }));
6014
+ });
6015
+ return isDryRun ? yield* runSync : yield* store.withExclusiveLock(`sync-${libraryId.slice(0, 8)}`, runSync);
5769
6016
  });
5770
6017
  }
5771
6018
  var SEARCH_STOP_WORDS = new Set([
@@ -6226,12 +6473,34 @@ function exportCommand(args) {
6226
6473
  }));
6227
6474
  }
6228
6475
  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);
6476
+ const isDryRun = Boolean(args.dryRun);
6229
6477
  if (!args.toDir && !args.specPath) {
6230
6478
  if (hasFilterFlags) {
6231
6479
  return yield* Effect4.fail(new ConfigError({
6232
6480
  message: "Export filter flags (--skills, --exclude, --with-requires, --no-requires, --no-router, --profile, --scene) require --to <dir> or --spec <file>."
6233
6481
  }));
6234
6482
  }
6483
+ if (isDryRun) {
6484
+ const syncRep = yield* syncCommand({ libraryId, dedupeWindowMs: 0, dryRun: true });
6485
+ const targetResults = (syncRep.plannedExports ?? []).map((pe) => ({
6486
+ dir: pe.dest,
6487
+ mode: pe.mode,
6488
+ exportedDirs: [],
6489
+ exportedCount: pe.totalSkills,
6490
+ routerSkill: pe.routerSkill,
6491
+ routerIncluded: pe.routerIncluded,
6492
+ wouldWrite: pe.wouldWrite,
6493
+ wouldRemove: pe.wouldRemove,
6494
+ wouldSkipConflicts: pe.wouldSkipConflicts,
6495
+ warnings: pe.warnings
6496
+ }));
6497
+ return {
6498
+ dryRun: true,
6499
+ exportedDirs: [],
6500
+ targets: targetResults,
6501
+ warnings: syncRep.warnings
6502
+ };
6503
+ }
6235
6504
  const syncRep = yield* syncCommand({ libraryId, dedupeWindowMs: 0 });
6236
6505
  const resolvedExports = yield* resolveConfiguredExports(config, store.paths.configPath);
6237
6506
  const allExported = [];
@@ -6311,18 +6580,124 @@ function exportCommand(args) {
6311
6580
  }
6312
6581
  ];
6313
6582
  }
6583
+ const notion = yield* NotionPort;
6584
+ const { binding } = yield* loadResolvedLibrary(args.libraryId);
6314
6585
  const catalog = yield* store.readCatalog();
6586
+ let freshCat = catalog;
6587
+ let freshLib;
6315
6588
  if (!catalog.libraries[libraryId]) {
6316
- yield* syncCommand({ libraryId, dedupeWindowMs: 0 });
6589
+ if (isDryRun) {
6590
+ const delta = yield* notion.queryDelta({
6591
+ libraryId,
6592
+ binding,
6593
+ watermarkIso: null
6594
+ });
6595
+ const sources = {};
6596
+ for (const s of delta.sources)
6597
+ sources[s.id] = s;
6598
+ const skills = {};
6599
+ for (const sk of delta.skills)
6600
+ skills[sk.id] = sk;
6601
+ const files = {};
6602
+ for (const f of delta.files)
6603
+ files[f.id] = f;
6604
+ freshLib = {
6605
+ watermark: null,
6606
+ lastSyncedAt: null,
6607
+ sources,
6608
+ skills,
6609
+ files,
6610
+ mainHashCache: {},
6611
+ fileBodyCache: {}
6612
+ };
6613
+ } else {
6614
+ yield* syncCommand({ libraryId, dedupeWindowMs: 0 });
6615
+ freshCat = yield* store.readCatalog();
6616
+ freshLib = freshCat.libraries[libraryId];
6617
+ }
6618
+ } else {
6619
+ freshLib = freshCat.libraries[libraryId];
6317
6620
  }
6318
- let freshCat = yield* store.readCatalog();
6319
- const freshLib = freshCat.libraries[libraryId];
6320
6621
  const sourcesById = new Map(Object.entries(freshLib.sources));
6321
6622
  const effective = filterEffectiveSkills(Object.values(freshLib.skills), sourcesById);
6322
6623
  const effectiveById = new Map(effective.map((s) => [s.id, s]));
6323
6624
  const catalogSkills = filterCatalogSkills(effective, config.profiles);
6625
+ const filesBySkillId = new Map;
6626
+ for (const f of Object.values(freshLib.files)) {
6627
+ const arr = filesBySkillId.get(f.skillId) ?? [];
6628
+ arr.push(f);
6629
+ filesBySkillId.set(f.skillId, arr);
6630
+ }
6324
6631
  const entryCacheById = new Map(freshCat.entries.filter((e) => e.libraryId === libraryId).map((e) => [e.skillId, e]));
6632
+ const buildDryRunPlannedEntry = (sk) => {
6633
+ const cached = entryCacheById.get(sk.id);
6634
+ if (cached) {
6635
+ return {
6636
+ ...cached,
6637
+ materializedPath: cached.materializedPath ?? store.getStoreSkillDir(libraryId, sk.id, cached.effectiveRev)
6638
+ };
6639
+ }
6640
+ const src = sk.originSourceId ? sourcesById.get(sk.originSourceId) ?? null : null;
6641
+ const overlayFiles = normalizeOverlayFiles(filesBySkillId.get(sk.id) ?? []);
6642
+ const subDigest = src ? extractSubtreeDigestFromRevision(sk.revision) : null;
6643
+ const commitId = src ? src.pinnedCommit || `ref:${src.ref}` : null;
6644
+ const baseIdentity = src ? subDigest ? `sub:${subDigest}` : commitId : null;
6645
+ const mainIdentity = !src || sk.customMain ? freshLib.mainHashCache[sk.id]?.rawBodySha256 ?? sk.lastEditedTime : `upstream:${baseIdentity}:${sk.sourcePath}`;
6646
+ const effectiveRev = computeEffectiveRev({
6647
+ originPinnedCommit: baseIdentity,
6648
+ sourcePath: sk.sourcePath,
6649
+ customMain: sk.customMain,
6650
+ name: sk.name,
6651
+ description: sk.description,
6652
+ mainContentIdentity: mainIdentity,
6653
+ overlays: overlayFiles.map((ov) => ({
6654
+ path: ov.path,
6655
+ status: ov.status === "delete" ? "delete" : "override",
6656
+ contentIdentity: ov.sha256 || ov.externalUrl || ov.lastEditedTime,
6657
+ executable: ov.executable
6658
+ })),
6659
+ requiresRevs: []
6660
+ });
6661
+ return {
6662
+ libraryId,
6663
+ skillId: sk.id,
6664
+ name: sk.name,
6665
+ description: sk.description,
6666
+ enabled: sk.enabled,
6667
+ visibility: sk.visibility,
6668
+ kind: sk.kind,
6669
+ profiles: [...sk.profiles],
6670
+ scenes: [...sk.scenes],
6671
+ requiresIds: [...sk.requiresIds],
6672
+ originSourceId: src?.id ?? null,
6673
+ originRepoUrl: src?.repoUrl ?? null,
6674
+ originRef: src?.ref ?? null,
6675
+ originPinnedCommit: commitId,
6676
+ sourcePath: sk.sourcePath,
6677
+ customMain: sk.customMain,
6678
+ revision: sk.revision,
6679
+ previewHash: sk.previewHash,
6680
+ effectiveRev,
6681
+ materializedPath: store.getStoreSkillDir(libraryId, sk.id, effectiveRev),
6682
+ warnings: [],
6683
+ overlays: overlayFiles.map((ov) => ({
6684
+ id: ov.id,
6685
+ path: ov.path,
6686
+ status: ov.status === "delete" ? "delete" : "override",
6687
+ externalUrl: ov.externalUrl,
6688
+ sha256: ov.sha256,
6689
+ executable: ov.executable,
6690
+ lastEditedTime: ov.lastEditedTime
6691
+ })),
6692
+ lastEditedTime: sk.lastEditedTime
6693
+ };
6694
+ };
6325
6695
  const ensureMaterializedEntry = (sk) => Effect4.gen(function* () {
6696
+ if (isDryRun) {
6697
+ const planned = buildDryRunPlannedEntry(sk);
6698
+ entryCacheById.set(sk.id, planned);
6699
+ return planned;
6700
+ }
6326
6701
  const cached = entryCacheById.get(sk.id);
6327
6702
  if (cached?.materializedPath && !cached.originPinnedCommit?.startsWith("ref:")) {
6328
6703
  const verified = yield* store.hasVerifiedStorePackage(libraryId, sk.id, cached.effectiveRev);
@@ -6377,7 +6752,7 @@ function exportCommand(args) {
6377
6752
  selectedEntries.push(yield* ensureMaterializedEntry(sk));
6378
6753
  }
6379
6754
  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()));
6755
+ const discoverableEntries = selection.discoverable.map((s) => entryCacheById.get(s.id) ?? (isDryRun ? buildDryRunPlannedEntry(s) : undefined)).filter((e) => Boolean(e) && !directNameSet.has(e.name.toLowerCase()));
6381
6756
  let routerEntry = null;
6382
6757
  const routerName = (target.router?.name ?? "skill-catalog").trim() || "skill-catalog";
6383
6758
  if (selection.resolvedRouterEnabled && discoverableEntries.length > 0 && !directNameSet.has(routerName.toLowerCase())) {
@@ -6388,7 +6763,7 @@ function exportCommand(args) {
6388
6763
  byNameRoot: store.paths.byNameRoot
6389
6764
  });
6390
6765
  const routerSkillId = `_router-${routerName}`;
6391
- const routerStoreDir = yield* store.publishImmutablePackage({
6766
+ const routerStoreDir = isDryRun ? store.getStoreSkillDir(libraryId, routerSkillId, synth.effectiveRev) : yield* store.publishImmutablePackage({
6392
6767
  libraryId,
6393
6768
  skillId: routerSkillId,
6394
6769
  effectiveRev: synth.effectiveRev,
@@ -6421,6 +6796,32 @@ function exportCommand(args) {
6421
6796
  };
6422
6797
  }
6423
6798
  const finalExportEntries = routerEntry ? [...selectedEntries, routerEntry] : selectedEntries;
6799
+ if (isDryRun) {
6800
+ const plan = yield* planExportTarget({
6801
+ target,
6802
+ selectedEntries: finalExportEntries,
6803
+ storeRoot: store.paths.storeRoot,
6804
+ ...args.onConflict ? { onConflict: args.onConflict } : {},
6805
+ routerSkill: routerEntry ? routerName : null
6806
+ });
6807
+ if (plan.warnings.length > 0) {
6808
+ targetWarnings.push(...plan.warnings);
6809
+ }
6810
+ allWarnings.push(...targetWarnings);
6811
+ targetResults.push({
6812
+ dir: plan.dest,
6813
+ mode: plan.mode,
6814
+ exportedDirs: [],
6815
+ exportedCount: plan.totalSkills,
6816
+ routerSkill: plan.routerSkill,
6817
+ routerIncluded: plan.routerIncluded,
6818
+ wouldWrite: plan.wouldWrite,
6819
+ wouldRemove: plan.wouldRemove,
6820
+ wouldSkipConflicts: plan.wouldSkipConflicts,
6821
+ warnings: targetWarnings
6822
+ });
6823
+ continue;
6824
+ }
6424
6825
  const pub = yield* publishExportTarget({
6425
6826
  target,
6426
6827
  selectedEntries: finalExportEntries,
@@ -6436,11 +6837,14 @@ function exportCommand(args) {
6436
6837
  dir: resolveHomePath(target.dir),
6437
6838
  mode: target.mode,
6438
6839
  exportedDirs: pub.exportedDirs,
6840
+ exportedCount: pub.exportedDirs.length,
6439
6841
  routerSkill: routerEntry ? routerName : null,
6842
+ routerIncluded: Boolean(routerEntry),
6440
6843
  warnings: targetWarnings
6441
6844
  });
6442
6845
  }
6443
6846
  return {
6847
+ ...isDryRun ? { dryRun: true } : {},
6444
6848
  exportedDirs: allExportedDirs,
6445
6849
  targets: targetResults,
6446
6850
  warnings: allWarnings
@@ -6497,79 +6901,212 @@ function statusCommand(args) {
6497
6901
  }
6498
6902
  // packages/core/src/edit/edit-engine.ts
6499
6903
  import { randomUUID as randomUUID5 } from "node:crypto";
6904
+ import * as fsp7 from "node:fs/promises";
6905
+ import * as nodePath7 from "node:path";
6906
+ import { Effect as Effect6, Option, Schema as Schema4 } from "effect";
6907
+
6908
+ // packages/core/src/edit/skill-dir-scan.ts
6500
6909
  import * as fsp6 from "node:fs/promises";
6501
6910
  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,
6911
+ import { Effect as Effect5 } from "effect";
6912
+ var IGNORED_SKILL_DIR_NAMES = new Set([
6913
+ ".ntn-skill.json",
6914
+ ".ntn-managed-copy.json",
6915
+ ".ntn-manifest.json",
6506
6916
  ".DS_Store",
6507
6917
  ".git",
6508
6918
  "node_modules",
6509
6919
  ".cache",
6510
6920
  ".state",
6511
6921
  ".venv",
6512
- "__pycache__",
6513
- ".env",
6514
- ".env.local"
6922
+ "__pycache__"
6515
6923
  ]);
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 });
6924
+ var ENV_TEMPLATE_ALLOWLIST = new Set([
6925
+ ".env.example",
6926
+ ".env.sample",
6927
+ ".env.template",
6928
+ ".env.dist"
6929
+ ]);
6930
+ var PRIVATE_KEY_EXACT_NAMES = new Set(["id_rsa", "id_ed25519", "id_ecdsa"]);
6931
+ var PRIVATE_KEY_EXTENSIONS = [".pem", ".key", ".p12", ".pfx"];
6932
+ function classifySensitiveFile(relPath, bytes) {
6933
+ const normalized = relPath.replace(/\\/g, "/");
6934
+ const base = nodePath6.posix.basename(normalized).toLowerCase();
6935
+ if (base === ".env" || base.startsWith(".env.") && !ENV_TEMPLATE_ALLOWLIST.has(base)) {
6936
+ return "environment secrets file";
6937
+ }
6938
+ if (PRIVATE_KEY_EXACT_NAMES.has(base) || PRIVATE_KEY_EXTENSIONS.some((ext) => base.endsWith(ext))) {
6939
+ return "private key or certificate";
6940
+ }
6941
+ if (base.endsWith(".json") && (base.includes("credentials") || base.includes("secret")) || base === "token.json" || base === "secrets.yaml" || base === "secrets.yml" || base === ".netrc") {
6942
+ return "credential or secret file";
6943
+ }
6944
+ if (base === ".npmrc") {
6945
+ if (!bytes) {
6946
+ return "npm credentials file";
6947
+ }
6948
+ const text = new TextDecoder("utf-8", { fatal: false }).decode(bytes);
6949
+ if (/_authtoken\s*=|\/\/.*:_authtoken/i.test(text)) {
6950
+ return "npm credentials file (_authToken)";
6532
6951
  }
6533
6952
  }
6534
- return map;
6535
- }
6536
- var UPSTREAM_SKILL_CONCURRENCY = 3;
6537
- function normalizeSourcePathKey(raw) {
6538
- const cleaned = raw.trim().replace(/^\.\/+|^\/+|\/+$/g, "");
6539
- return cleaned === "" ? "." : cleaned;
6540
- }
6541
- function makeRevisionStamp(subtreeDigest) {
6542
- const base = `rev-${Date.now().toString(36)}-${randomUUID5().slice(0, 6)}`;
6543
- return subtreeDigest ? `${base}-sub:${subtreeDigest}` : base;
6953
+ return null;
6544
6954
  }
6545
- function encodeSupportingFileEffect(bytes, filePath) {
6546
- return Effect5.try({
6547
- try: () => encodeSupportingFilePayload(bytes, filePath),
6548
- catch: (e) => e instanceof StoreError ? e : new StoreError({ path: filePath, message: String(e) })
6549
- });
6955
+ function formatBlockedFilesMessage(rootDir, blockedFiles) {
6956
+ const details = blockedFiles.map((b) => `${b.path} (${b.reason})`).join(", ");
6957
+ return `Refusing to upload skill directory '${rootDir}': blocked sensitive or unsafe file(s) detected: ${details}. Remove or relocate these files before uploading.`;
6550
6958
  }
6551
- function loadSyncedLibrary(explicitLibraryId) {
6552
- return Effect5.gen(function* () {
6553
- const store = yield* StorePort;
6554
- const { config, libraryId, binding } = yield* loadResolvedLibrary(explicitLibraryId);
6555
- yield* syncCommand({ libraryId, dedupeWindowMs: 0 });
6556
- const catalog = yield* store.readCatalog();
6557
- return { config, libraryId, binding, catalog, libState: catalog.libraries[libraryId] };
6558
- });
6959
+ function assertNoBlockedSkillFiles(scan) {
6960
+ if (scan.blockedFiles.length === 0) {
6961
+ return Effect5.void;
6962
+ }
6963
+ return Effect5.fail(new ConflictError({
6964
+ kind: "sensitive_files",
6965
+ message: formatBlockedFilesMessage(scan.rootDir, scan.blockedFiles),
6966
+ details: scan.blockedFiles.map((b) => `${b.path} (${b.reason})`)
6967
+ }));
6559
6968
  }
6560
- function loadTableMetadataLibrary(explicitLibraryId) {
6561
- return Effect5.gen(function* () {
6562
- const store = yield* StorePort;
6563
- const notion = yield* NotionPort;
6564
- const { config, libraryId, binding } = yield* loadResolvedLibrary(explicitLibraryId);
6565
- const catalog = yield* store.readCatalog();
6566
- const prevLib = catalog.libraries[libraryId] ?? {
6567
- watermark: null,
6568
- lastSyncedAt: null,
6569
- sources: {},
6570
- skills: {},
6571
- files: {},
6572
- mainHashCache: {},
6969
+ async function scanLocalSkillDirectory(rootDir) {
6970
+ const absRoot = nodePath6.resolve(rootDir);
6971
+ const realRoot = await fsp6.realpath(absRoot);
6972
+ const realRootPrefix = `${realRoot}${nodePath6.sep}`;
6973
+ const files = new Map;
6974
+ const blockedFiles = [];
6975
+ const visitedDirs = new Set([realRoot]);
6976
+ let totalBytes = 0;
6977
+ const isInsideRoot = (candidateReal) => candidateReal === realRoot || candidateReal.startsWith(realRootPrefix);
6978
+ const walk = async (curAbsDir, relPrefix) => {
6979
+ const entries = await fsp6.readdir(curAbsDir, { withFileTypes: true });
6980
+ entries.sort((a, b) => a.name.localeCompare(b.name));
6981
+ for (const entry of entries) {
6982
+ if (IGNORED_SKILL_DIR_NAMES.has(entry.name))
6983
+ continue;
6984
+ const childRel = relPrefix ? `${relPrefix}/${entry.name}` : entry.name;
6985
+ const fullPath = nodePath6.join(curAbsDir, entry.name);
6986
+ if (entry.isSymbolicLink()) {
6987
+ const targetReal = await fsp6.realpath(fullPath).catch(() => null);
6988
+ if (!targetReal || !isInsideRoot(targetReal)) {
6989
+ blockedFiles.push({
6990
+ path: childRel,
6991
+ reason: targetReal ? "symlink escapes skill root" : "broken symlink"
6992
+ });
6993
+ continue;
6994
+ }
6995
+ const targetStat = await fsp6.stat(targetReal).catch(() => null);
6996
+ if (!targetStat) {
6997
+ blockedFiles.push({ path: childRel, reason: "broken symlink" });
6998
+ continue;
6999
+ }
7000
+ if (targetStat.isDirectory()) {
7001
+ if (visitedDirs.has(targetReal))
7002
+ continue;
7003
+ visitedDirs.add(targetReal);
7004
+ await walk(fullPath, childRel);
7005
+ continue;
7006
+ }
7007
+ if (targetStat.isFile()) {
7008
+ const baseLower = entry.name.toLowerCase();
7009
+ const quickReason = baseLower === ".npmrc" ? null : classifySensitiveFile(childRel);
7010
+ if (quickReason) {
7011
+ blockedFiles.push({ path: childRel, reason: quickReason });
7012
+ continue;
7013
+ }
7014
+ const bytes = new Uint8Array(await fsp6.readFile(targetReal));
7015
+ const contentReason = baseLower === ".npmrc" ? classifySensitiveFile(childRel, bytes) : null;
7016
+ if (contentReason) {
7017
+ blockedFiles.push({ path: childRel, reason: contentReason });
7018
+ continue;
7019
+ }
7020
+ const executable = (targetStat.mode & 73) !== 0 || childRel.toLowerCase().endsWith(".sh");
7021
+ files.set(childRel, { path: childRel, bytes, executable });
7022
+ totalBytes += bytes.byteLength;
7023
+ }
7024
+ continue;
7025
+ }
7026
+ if (entry.isDirectory()) {
7027
+ const realSub = await fsp6.realpath(fullPath).catch(() => fullPath);
7028
+ if (!isInsideRoot(realSub)) {
7029
+ blockedFiles.push({ path: childRel, reason: "directory escapes skill root" });
7030
+ continue;
7031
+ }
7032
+ if (visitedDirs.has(realSub))
7033
+ continue;
7034
+ visitedDirs.add(realSub);
7035
+ await walk(fullPath, childRel);
7036
+ } else if (entry.isFile()) {
7037
+ const baseLower = entry.name.toLowerCase();
7038
+ const quickReason = baseLower === ".npmrc" ? null : classifySensitiveFile(childRel);
7039
+ if (quickReason) {
7040
+ blockedFiles.push({ path: childRel, reason: quickReason });
7041
+ continue;
7042
+ }
7043
+ const [rawBytes, st] = await Promise.all([fsp6.readFile(fullPath), fsp6.stat(fullPath)]);
7044
+ const bytes = new Uint8Array(rawBytes);
7045
+ const contentReason = baseLower === ".npmrc" ? classifySensitiveFile(childRel, bytes) : null;
7046
+ if (contentReason) {
7047
+ blockedFiles.push({ path: childRel, reason: contentReason });
7048
+ continue;
7049
+ }
7050
+ const executable = (st.mode & 73) !== 0 || childRel.toLowerCase().endsWith(".sh");
7051
+ files.set(childRel, { path: childRel, bytes, executable });
7052
+ totalBytes += bytes.byteLength;
7053
+ }
7054
+ }
7055
+ };
7056
+ await walk(absRoot, "");
7057
+ blockedFiles.sort((a, b) => a.path.localeCompare(b.path));
7058
+ return {
7059
+ rootDir: absRoot,
7060
+ files,
7061
+ blockedFiles,
7062
+ fileCount: files.size,
7063
+ totalBytes
7064
+ };
7065
+ }
7066
+
7067
+ // packages/core/src/edit/edit-engine.ts
7068
+ var WORK_META_FILE = ".ntn-skill.json";
7069
+ async function scanWorkdirFiles(workdir) {
7070
+ const scanned = await scanLocalSkillDirectory(workdir);
7071
+ return new Map(scanned.files);
7072
+ }
7073
+ var UPSTREAM_SKILL_CONCURRENCY = 3;
7074
+ function normalizeSourcePathKey(raw) {
7075
+ const cleaned = raw.trim().replace(/^\.\/+|^\/+|\/+$/g, "");
7076
+ return cleaned === "" ? "." : cleaned;
7077
+ }
7078
+ function makeRevisionStamp(subtreeDigest) {
7079
+ const base = `rev-${Date.now().toString(36)}-${randomUUID5().slice(0, 6)}`;
7080
+ return subtreeDigest ? `${base}-sub:${subtreeDigest}` : base;
7081
+ }
7082
+ function encodeSupportingFileEffect(bytes, filePath) {
7083
+ return Effect6.try({
7084
+ try: () => encodeSupportingFilePayload(bytes, filePath),
7085
+ catch: (e) => e instanceof StoreError ? e : new StoreError({ path: filePath, message: String(e) })
7086
+ });
7087
+ }
7088
+ function loadSyncedLibrary(explicitLibraryId) {
7089
+ return Effect6.gen(function* () {
7090
+ const store = yield* StorePort;
7091
+ const { config, libraryId, binding } = yield* loadResolvedLibrary(explicitLibraryId);
7092
+ yield* syncCommand({ libraryId, dedupeWindowMs: 0 });
7093
+ const catalog = yield* store.readCatalog();
7094
+ return { config, libraryId, binding, catalog, libState: catalog.libraries[libraryId] };
7095
+ });
7096
+ }
7097
+ function loadTableMetadataLibrary(explicitLibraryId) {
7098
+ return Effect6.gen(function* () {
7099
+ const store = yield* StorePort;
7100
+ const notion = yield* NotionPort;
7101
+ const { config, libraryId, binding } = yield* loadResolvedLibrary(explicitLibraryId);
7102
+ const catalog = yield* store.readCatalog();
7103
+ const prevLib = catalog.libraries[libraryId] ?? {
7104
+ watermark: null,
7105
+ lastSyncedAt: null,
7106
+ sources: {},
7107
+ skills: {},
7108
+ files: {},
7109
+ mainHashCache: {},
6573
7110
  fileBodyCache: {}
6574
7111
  };
6575
7112
  const isFull = !prevLib.watermark;
@@ -6600,31 +7137,31 @@ function findSkillOrFail(libState, name) {
6600
7137
  const needle = name.trim().toLowerCase();
6601
7138
  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));
6602
7139
  const found = candidates[0];
6603
- return found ? Effect5.succeed(found) : Effect5.fail(new NotFoundError({ entity: "skill", target: name, message: `Skill '${name}' not found.` }));
7140
+ return found ? Effect6.succeed(found) : Effect6.fail(new NotFoundError({ entity: "skill", target: name, message: `Skill '${name}' not found.` }));
6604
7141
  }
6605
7142
  function withRetryableReadback(writeOp, verifyReadback) {
6606
- return writeOp.pipe(Effect5.catchTag("NotionApiError", (err) => Effect5.gen(function* () {
7143
+ return writeOp.pipe(Effect6.catchTag("NotionApiError", (err) => Effect6.gen(function* () {
6607
7144
  if (!err.retryable)
6608
- return yield* Effect5.fail(err);
7145
+ return yield* Effect6.fail(err);
6609
7146
  const landed = yield* verifyReadback();
6610
7147
  return landed !== null ? landed : yield* writeOp;
6611
7148
  })));
6612
7149
  }
6613
7150
  function trashPathEffect(absPath) {
6614
- return Effect5.tryPromise({
7151
+ return Effect6.tryPromise({
6615
7152
  try: () => moveToSystemTrash(absPath),
6616
7153
  catch: (e) => new StoreError({ path: absPath, message: String(e) })
6617
7154
  });
6618
7155
  }
6619
7156
  function editOrPullSkillCommand(args) {
6620
- return Effect5.gen(function* () {
7157
+ return Effect6.gen(function* () {
6621
7158
  const notion = yield* NotionPort;
6622
7159
  const store = yield* StorePort;
6623
7160
  const upstream = yield* UpstreamPort;
6624
7161
  const { libraryId, binding, catalog, libState } = yield* loadSyncedLibrary(args.libraryId);
6625
7162
  const entry = catalog.entries.find((e) => e.libraryId === libraryId && e.name.toLowerCase() === args.name.trim().toLowerCase());
6626
7163
  if (!entry) {
6627
- return yield* Effect5.fail(new NotFoundError({
7164
+ return yield* Effect6.fail(new NotFoundError({
6628
7165
  entity: "skill",
6629
7166
  target: args.name,
6630
7167
  message: `Skill '${args.name}' not found in library ${libraryId}.`
@@ -6632,13 +7169,13 @@ function editOrPullSkillCommand(args) {
6632
7169
  }
6633
7170
  const liveSkill = yield* notion.getSkillRecord(entry.skillId);
6634
7171
  if (!liveSkill || !liveSkill.enabled) {
6635
- return yield* Effect5.fail(new NotFoundError({
7172
+ return yield* Effect6.fail(new NotFoundError({
6636
7173
  entity: "skill",
6637
7174
  target: args.name,
6638
7175
  message: `Skill '${args.name}' is disabled or deleted in Notion.`
6639
7176
  }));
6640
7177
  }
6641
- const [liveFiles, liveBody] = yield* Effect5.all([
7178
+ const [liveFiles, liveBody] = yield* Effect6.all([
6642
7179
  notion.getSkillFiles({ filesDs: binding.files_ds, skillId: liveSkill.id }),
6643
7180
  notion.readSkillBody(liveSkill.id)
6644
7181
  ]);
@@ -6696,12 +7233,12 @@ function editOrPullSkillCommand(args) {
6696
7233
  const mainBytes = new TextEncoder().encode(applyAuthoritativeFrontmatter(rawMainToUse, liveSkill.name, liveSkill.description));
6697
7234
  treeToWrite.set("SKILL.md", { path: "SKILL.md", bytes: mainBytes, executable: false });
6698
7235
  if (args.clean && !args.targetDir) {
6699
- return yield* Effect5.fail(new ConfigError({
7236
+ return yield* Effect6.fail(new ConfigError({
6700
7237
  message: "'ntn-skills pull --clean' requires an explicit target directory."
6701
7238
  }));
6702
7239
  }
6703
7240
  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)}`);
7241
+ const workdir = args.targetDir ? nodePath7.resolve(args.targetDir) : nodePath7.join(store.paths.workRoot, `${safeSlug}-${randomUUID5().slice(0, 8)}`);
6705
7242
  const meta = {
6706
7243
  version: 2,
6707
7244
  libraryId,
@@ -6720,34 +7257,34 @@ function editOrPullSkillCommand(args) {
6720
7257
  baseFiles,
6721
7258
  createdAt: new Date().toISOString()
6722
7259
  };
6723
- const removedStaleFiles = yield* Effect5.tryPromise({
7260
+ const removedStaleFiles = yield* Effect6.tryPromise({
6724
7261
  try: async () => {
6725
7262
  let staleCount = 0;
6726
7263
  if (args.clean) {
6727
- const existingStat = await fsp6.stat(workdir).catch(() => null);
7264
+ const existingStat = await fsp7.stat(workdir).catch(() => null);
6728
7265
  if (existingStat?.isDirectory()) {
6729
7266
  const existingFiles = await scanWorkdirFiles(workdir);
6730
7267
  for (const oldRel of existingFiles.keys()) {
6731
7268
  if (!treeToWrite.has(oldRel)) {
6732
- await moveToSystemTrash(nodePath6.join(workdir, oldRel));
7269
+ await moveToSystemTrash(nodePath7.join(workdir, oldRel));
6733
7270
  staleCount++;
6734
7271
  }
6735
7272
  }
6736
- const metaFile = nodePath6.join(workdir, WORK_META_FILE);
6737
- if (await fsp6.stat(metaFile).then(() => true).catch(() => false)) {
7273
+ const metaFile = nodePath7.join(workdir, WORK_META_FILE);
7274
+ if (await fsp7.stat(metaFile).then(() => true).catch(() => false)) {
6738
7275
  await moveToSystemTrash(metaFile);
6739
7276
  }
6740
7277
  }
6741
7278
  }
6742
- await fsp6.mkdir(workdir, { recursive: true });
7279
+ await fsp7.mkdir(workdir, { recursive: true });
6743
7280
  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);
7281
+ const dest = nodePath7.join(workdir, f.path);
7282
+ await fsp7.mkdir(nodePath7.dirname(dest), { recursive: true });
7283
+ await fsp7.writeFile(dest, f.bytes);
7284
+ await fsp7.chmod(dest, f.executable ? 493 : 420);
6748
7285
  }
6749
7286
  if (!args.clean) {
6750
- await atomicWriteJson(nodePath6.join(workdir, WORK_META_FILE), meta);
7287
+ await atomicWriteJson(nodePath7.join(workdir, WORK_META_FILE), meta);
6751
7288
  }
6752
7289
  return staleCount;
6753
7290
  },
@@ -6757,10 +7294,10 @@ function editOrPullSkillCommand(args) {
6757
7294
  });
6758
7295
  }
6759
7296
  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"))),
7297
+ const abs = nodePath7.resolve(workdir);
7298
+ const metaPath = nodePath7.join(abs, WORK_META_FILE);
7299
+ return Effect6.tryPromise({
7300
+ try: async () => Schema4.decodeUnknownSync(WorkMetaSchema)(JSON.parse(await fsp7.readFile(metaPath, "utf8"))),
6764
7301
  catch: (err) => err?.code === "ENOENT" ? new NotFoundError({
6765
7302
  entity: "workdir",
6766
7303
  target: abs,
@@ -6825,7 +7362,7 @@ async function computeLocalDiff(workdir, meta) {
6825
7362
  return { items, currentFiles, descriptionChanged };
6826
7363
  }
6827
7364
  function inspectRemoteDrift(args) {
6828
- return Effect5.gen(function* () {
7365
+ return Effect6.gen(function* () {
6829
7366
  const notion = yield* NotionPort;
6830
7367
  const drifts = [];
6831
7368
  const liveSkill = yield* notion.getSkillRecord(args.meta.skillId);
@@ -6837,7 +7374,7 @@ function inspectRemoteDrift(args) {
6837
7374
  if (liveSkill.revision !== args.meta.baseRevision) {
6838
7375
  drifts.push(`Notion Revision changed ('${args.meta.baseRevision}' -> '${liveSkill.revision}').`);
6839
7376
  }
6840
- const [liveBody, liveFiles] = yield* Effect5.all([
7377
+ const [liveBody, liveFiles] = yield* Effect6.all([
6841
7378
  notion.readSkillBody(args.meta.skillId),
6842
7379
  notion.getSkillFiles({ filesDs: args.filesDs, skillId: args.meta.skillId })
6843
7380
  ]);
@@ -6857,7 +7394,7 @@ function inspectRemoteDrift(args) {
6857
7394
  else if (lf.sha256 && lf.sha256 !== bf.sha256) {
6858
7395
  let actualLiveSha = lf.sha256;
6859
7396
  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)));
7397
+ const liveTxt = yield* notion.readFileBody({ filePageId: lf.id, filePath: lf.path }).pipe(Effect6.catch(() => Effect6.succeed(null)));
6861
7398
  if (liveTxt !== null) {
6862
7399
  try {
6863
7400
  actualLiveSha = sha256Hex(decodeSupportingFilePayload(liveTxt));
@@ -6882,10 +7419,10 @@ function inspectRemoteDrift(args) {
6882
7419
  });
6883
7420
  }
6884
7421
  function diffWorkdirCommand(args) {
6885
- return Effect5.gen(function* () {
6886
- const absWork = nodePath6.resolve(args.workdir);
7422
+ return Effect6.gen(function* () {
7423
+ const absWork = nodePath7.resolve(args.workdir);
6887
7424
  const meta = yield* readWorkMeta(absWork);
6888
- const local = yield* Effect5.tryPromise({
7425
+ const local = yield* Effect6.tryPromise({
6889
7426
  try: () => computeLocalDiff(absWork, meta),
6890
7427
  catch: (e) => new StoreError({ path: absWork, message: String(e) })
6891
7428
  });
@@ -6903,45 +7440,71 @@ function diffWorkdirCommand(args) {
6903
7440
  return { ...baseReport, remoteDrifted: drifts.length > 0, remoteDriftDetails: drifts };
6904
7441
  });
6905
7442
  }
6906
- function pushWorkdirCommand(args) {
6907
- return Effect5.gen(function* () {
7443
+ function pushSingleWorkdirInternal(args) {
7444
+ return Effect6.gen(function* () {
6908
7445
  const notion = yield* NotionPort;
6909
7446
  const store = yield* StorePort;
6910
- const absWork = nodePath6.resolve(args.workdir);
6911
- const meta = yield* readWorkMeta(absWork);
7447
+ const absWork = nodePath7.resolve(args.workdir);
7448
+ const meta = yield* readWorkMeta(absWork).pipe(Effect6.catchTag("NotFoundError", () => Effect6.fail(new ConfigError({
7449
+ path: absWork,
7450
+ 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).`
7451
+ }))));
6912
7452
  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({
7453
+ const runPush = Effect6.gen(function* () {
7454
+ const scan = yield* Effect6.tryPromise({
7455
+ try: () => scanLocalSkillDirectory(absWork),
7456
+ catch: (e) => new StoreError({ path: absWork, message: String(e) })
7457
+ });
7458
+ yield* assertNoBlockedSkillFiles(scan);
7459
+ const local = yield* Effect6.tryPromise({
6915
7460
  try: () => computeLocalDiff(absWork, meta),
6916
7461
  catch: (e) => new StoreError({ path: absWork, message: String(e) })
6917
7462
  });
6918
7463
  if (args.dryRun) {
6919
7464
  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
7465
+ report: {
7466
+ workdir: absWork,
7467
+ skillName: meta.skillName,
7468
+ dryRun: true,
7469
+ updatedFiles: local.items.filter((i) => i.path !== "SKILL.md").length,
7470
+ updatedMain: local.items.some((i) => i.path === "SKILL.md"),
7471
+ newRevision: null,
7472
+ workdirCleaned: false
7473
+ },
7474
+ libraryId,
7475
+ skillId: meta.skillId,
7476
+ touchedFileIds: [],
7477
+ archivedFileIds: [],
7478
+ wroteRemote: false,
7479
+ shouldTrash: false
6927
7480
  };
6928
7481
  }
6929
7482
  if (local.items.length === 0 && !local.descriptionChanged) {
6930
- yield* trashPathEffect(absWork);
7483
+ if (!args.deferSyncAndTrash) {
7484
+ yield* trashPathEffect(absWork);
7485
+ }
6931
7486
  return {
6932
- workdir: absWork,
6933
- skillName: meta.skillName,
6934
- dryRun: false,
6935
- updatedFiles: 0,
6936
- updatedMain: false,
6937
- newRevision: null,
6938
- workdirCleaned: true
7487
+ report: {
7488
+ workdir: absWork,
7489
+ skillName: meta.skillName,
7490
+ dryRun: false,
7491
+ updatedFiles: 0,
7492
+ updatedMain: false,
7493
+ newRevision: null,
7494
+ workdirCleaned: !args.deferSyncAndTrash
7495
+ },
7496
+ libraryId,
7497
+ skillId: meta.skillId,
7498
+ touchedFileIds: [],
7499
+ archivedFileIds: [],
7500
+ wroteRemote: false,
7501
+ shouldTrash: true
6939
7502
  };
6940
7503
  }
6941
7504
  if (!args.force) {
6942
7505
  const drifts = yield* inspectRemoteDrift({ meta, filesDs: binding.files_ds });
6943
7506
  if (drifts.length > 0) {
6944
- return yield* Effect5.fail(new ConflictError({
7507
+ return yield* Effect6.fail(new ConflictError({
6945
7508
  kind: "baseline_drift",
6946
7509
  message: `Remote skill '${meta.skillName}' drifted since edit baseline; refusing push (workdir preserved at ${absWork}). Pass --force to overwrite.`,
6947
7510
  details: drifts
@@ -6975,7 +7538,7 @@ function pushWorkdirCommand(args) {
6975
7538
  sha256: "",
6976
7539
  executable: false,
6977
7540
  textContent: ""
6978
- }), () => notion.getSkillFiles({ filesDs: binding.files_ds, skillId: meta.skillId }).pipe(Effect5.map((rf) => {
7541
+ }), () => notion.getSkillFiles({ filesDs: binding.files_ds, skillId: meta.skillId }).pipe(Effect6.map((rf) => {
6979
7542
  const landed = rf.find((f) => f.path === item.path && f.status === "delete");
6980
7543
  return landed ? { pageId: landed.id } : null;
6981
7544
  })));
@@ -6999,7 +7562,7 @@ function pushWorkdirCommand(args) {
6999
7562
  ...baseSha256 ? { baseSha256 } : {},
7000
7563
  executable: curFile.executable,
7001
7564
  textContent
7002
- }), () => Effect5.gen(function* () {
7565
+ }), () => Effect6.gen(function* () {
7003
7566
  const remoteFiles = yield* notion.getSkillFiles({
7004
7567
  filesDs: binding.files_ds,
7005
7568
  skillId: meta.skillId
@@ -7028,7 +7591,7 @@ function pushWorkdirCommand(args) {
7028
7591
  skillId: meta.skillId,
7029
7592
  markdownBody: mainText,
7030
7593
  preserveUpstreamChild: Boolean(meta.originSourceId)
7031
- }), () => notion.readSkillBody(meta.skillId).pipe(Effect5.map((rb) => rb.rawMarkdown.trim() === expectedPrepared.trim() ? { upstreamFilesPageId: rb.upstreamFilesPageId } : null)));
7594
+ }), () => notion.readSkillBody(meta.skillId).pipe(Effect6.map((rb) => rb.rawMarkdown.trim() === expectedPrepared.trim() ? { upstreamFilesPageId: rb.upstreamFilesPageId } : null)));
7032
7595
  }
7033
7596
  const preservedSubDigest = meta.originSourceId ? extractSubtreeDigestFromRevision(meta.baseRevision) : null;
7034
7597
  const newRevision = makeRevisionStamp(preservedSubDigest);
@@ -7039,45 +7602,59 @@ function pushWorkdirCommand(args) {
7039
7602
  ...meta.originSourceId && updatedMain ? { customMain: true } : {},
7040
7603
  revision: newRevision
7041
7604
  });
7042
- yield* syncCommand({
7043
- libraryId,
7044
- dedupeWindowMs: 0,
7045
- readYourWrites: { skillIds: [meta.skillId], fileIds: touchedFileIds, archivedFileIds }
7046
- });
7047
- yield* trashPathEffect(absWork);
7605
+ if (!args.deferSyncAndTrash) {
7606
+ yield* syncCommand({
7607
+ libraryId,
7608
+ dedupeWindowMs: 0,
7609
+ readYourWrites: { skillIds: [meta.skillId], fileIds: touchedFileIds, archivedFileIds }
7610
+ });
7611
+ yield* trashPathEffect(absWork);
7612
+ }
7048
7613
  return {
7049
- workdir: absWork,
7050
- skillName: meta.skillName,
7051
- dryRun: false,
7052
- updatedFiles: updatedFilesCount,
7053
- updatedMain,
7054
- newRevision,
7055
- workdirCleaned: true
7614
+ report: {
7615
+ workdir: absWork,
7616
+ skillName: meta.skillName,
7617
+ dryRun: false,
7618
+ updatedFiles: updatedFilesCount,
7619
+ updatedMain,
7620
+ newRevision,
7621
+ workdirCleaned: !args.deferSyncAndTrash
7622
+ },
7623
+ libraryId,
7624
+ skillId: meta.skillId,
7625
+ touchedFileIds,
7626
+ archivedFileIds,
7627
+ wroteRemote: true,
7628
+ shouldTrash: true
7056
7629
  };
7057
- }));
7630
+ });
7631
+ return args.dryRun ? yield* runPush : yield* store.withExclusiveLock(`push-${libraryId.slice(0, 8)}`, runPush);
7058
7632
  });
7059
7633
  }
7634
+ function pushWorkdirCommand(args) {
7635
+ return pushSingleWorkdirInternal(args).pipe(Effect6.map((r) => r.report));
7636
+ }
7060
7637
  function abortWorkdirCommand(workdir) {
7061
- return Effect5.gen(function* () {
7062
- const abs = nodePath6.resolve(workdir);
7638
+ return Effect6.gen(function* () {
7639
+ const abs = nodePath7.resolve(workdir);
7063
7640
  yield* readWorkMeta(abs);
7064
7641
  yield* trashPathEffect(abs);
7065
7642
  return abs;
7066
7643
  });
7067
7644
  }
7068
7645
  function listWorkdirsCommand() {
7069
- return Effect5.gen(function* () {
7646
+ return Effect6.gen(function* () {
7070
7647
  const store = yield* StorePort;
7071
- return yield* Effect5.tryPromise({
7648
+ return yield* Effect6.tryPromise({
7072
7649
  try: async () => {
7073
- const dirs = await fsp6.readdir(store.paths.workRoot).catch(() => []);
7650
+ const dirs = await fsp7.readdir(store.paths.workRoot).catch(() => []);
7074
7651
  const out = [];
7075
7652
  for (const d of dirs) {
7076
7653
  if (d.startsWith("."))
7077
7654
  continue;
7078
- const full = nodePath6.join(store.paths.workRoot, d);
7655
+ const full = nodePath7.join(store.paths.workRoot, d);
7079
7656
  try {
7080
- const raw = await fsp6.readFile(nodePath6.join(full, WORK_META_FILE), "utf8");
7657
+ const raw = await fsp7.readFile(nodePath7.join(full, WORK_META_FILE), "utf8");
7081
7658
  out.push({
7082
7659
  workdir: full,
7083
7660
  meta: Schema4.decodeUnknownSync(WorkMetaSchema)(JSON.parse(raw))
@@ -7091,7 +7668,7 @@ function listWorkdirsCommand() {
7091
7668
  });
7092
7669
  }
7093
7670
  function cleanWorkdirsCommand(olderThanDays = 7) {
7094
- return Effect5.gen(function* () {
7671
+ return Effect6.gen(function* () {
7095
7672
  const all = yield* listWorkdirsCommand();
7096
7673
  const cutoff = Date.now() - olderThanDays * 86400000;
7097
7674
  const cleaned = [];
@@ -7109,30 +7686,32 @@ function resolveImportedSkillVisibility(disableModelInvocation, requestedVisibil
7109
7686
  return disableModelInvocation ? "manual" : requestedVisibility ?? "manual";
7110
7687
  }
7111
7688
  function createNewSkillCommand(args) {
7112
- return Effect5.gen(function* () {
7689
+ return Effect6.gen(function* () {
7113
7690
  const notion = yield* NotionPort;
7114
7691
  const store = yield* StorePort;
7115
7692
  const config = yield* store.readConfig();
7116
7693
  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),
7694
+ const absDir = nodePath7.resolve(args.dir);
7695
+ const scan = yield* Effect6.tryPromise({
7696
+ try: () => scanLocalSkillDirectory(absDir),
7120
7697
  catch: (e) => new StoreError({
7121
7698
  path: absDir,
7122
7699
  message: `Cannot read skill directory ${absDir}: ${String(e)}`
7123
7700
  })
7124
7701
  });
7702
+ yield* assertNoBlockedSkillFiles(scan);
7703
+ const files = scan.files;
7125
7704
  const mainFile = files.get("SKILL.md");
7126
7705
  if (!mainFile)
7127
- return yield* Effect5.fail(new StoreError({ path: absDir, message: `Missing SKILL.md in ${absDir}.` }));
7706
+ return yield* Effect6.fail(new StoreError({ path: absDir, message: `Missing SKILL.md in ${absDir}.` }));
7128
7707
  const rawMain = new TextDecoder().decode(mainFile.bytes);
7129
7708
  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());
7709
+ const skillName = (args.name ?? parsed.name ?? nodePath7.basename(absDir)).trim();
7710
+ const duplicate = catalog.entries.find((e) => e.libraryId === libraryId && (e.name.toLowerCase() === skillName.toLowerCase() || normalizeSkillSlug(e.name) === normalizeSkillSlug(skillName)));
7132
7711
  if (duplicate) {
7133
- return yield* Effect5.fail(new ConflictError({
7712
+ return yield* Effect6.fail(new ConflictError({
7134
7713
  kind: "duplicate_name",
7135
- message: `Skill '${skillName}' already exists (${duplicate.skillId}). Use 'ntn-skills edit ${skillName}' instead.`
7714
+ message: `Skill '${skillName}' already exists (${duplicate.skillId}). Use 'ntn-skills push "${absDir}" --overwrite' or 'ntn-skills edit "${skillName}"' instead.`
7136
7715
  }));
7137
7716
  }
7138
7717
  const preparedSupporting = [];
@@ -7166,7 +7745,7 @@ function createNewSkillCommand(args) {
7166
7745
  previewHash: "",
7167
7746
  markdownBody: rawMain
7168
7747
  });
7169
- const createdFileIds = yield* Effect5.forEach(preparedSupporting, (sf) => notion.upsertFilePage({
7748
+ const createdFileIds = yield* Effect6.forEach(preparedSupporting, (sf) => notion.upsertFilePage({
7170
7749
  libraryId,
7171
7750
  filesDs: binding.files_ds,
7172
7751
  existingPageId: null,
@@ -7177,22 +7756,22 @@ function createNewSkillCommand(args) {
7177
7756
  sha256: sf.sha256,
7178
7757
  executable: sf.executable,
7179
7758
  textContent: sf.textContent
7180
- }).pipe(Effect5.map((up) => up.pageId)), { concurrency: UPSTREAM_SKILL_CONCURRENCY });
7759
+ }).pipe(Effect6.map((up) => up.pageId)), { concurrency: UPSTREAM_SKILL_CONCURRENCY });
7181
7760
  const resolvedExports = yield* resolveConfiguredExports(config, store.paths.configPath);
7182
- const isInExportRoot = yield* Effect5.tryPromise(async () => {
7183
- const lst = await fsp6.lstat(absDir).catch(() => null);
7761
+ const isInExportRoot = yield* Effect6.tryPromise(async () => {
7762
+ const lst = await fsp7.lstat(absDir).catch(() => null);
7184
7763
  if (!lst || lst.isSymbolicLink())
7185
7764
  return false;
7186
- const realAbsParent = await fsp6.realpath(nodePath6.dirname(absDir)).catch(() => nodePath6.dirname(absDir));
7765
+ const realAbsParent = await fsp7.realpath(nodePath7.dirname(absDir)).catch(() => nodePath7.dirname(absDir));
7187
7766
  for (const { target: exp } of resolvedExports.targets) {
7188
7767
  const expRoot = resolveHomePath(exp.dir);
7189
- const realExpRoot = await fsp6.realpath(expRoot).catch(() => expRoot);
7190
- if (nodePath6.dirname(absDir) === expRoot || realAbsParent === realExpRoot) {
7768
+ const realExpRoot = await fsp7.realpath(expRoot).catch(() => expRoot);
7769
+ if (nodePath7.dirname(absDir) === expRoot || realAbsParent === realExpRoot) {
7191
7770
  return true;
7192
7771
  }
7193
7772
  }
7194
7773
  return false;
7195
- }).pipe(Effect5.catch(() => Effect5.succeed(false)));
7774
+ }).pipe(Effect6.catch(() => Effect6.succeed(false)));
7196
7775
  const shouldAdopt = args.adopt === undefined ? isInExportRoot : args.adopt;
7197
7776
  let adoptedSourceDir = false;
7198
7777
  if (shouldAdopt) {
@@ -7204,18 +7783,18 @@ function createNewSkillCommand(args) {
7204
7783
  dedupeWindowMs: 0,
7205
7784
  readYourWrites: { skillIds: [created.id], fileIds: createdFileIds }
7206
7785
  });
7207
- const exportedAtSourcePath = adoptedSourceDir && isInExportRoot ? yield* Effect5.tryPromise(async () => {
7208
- const lst = await fsp6.lstat(absDir).catch(() => null);
7786
+ const exportedAtSourcePath = adoptedSourceDir && isInExportRoot ? yield* Effect6.tryPromise(async () => {
7787
+ const lst = await fsp7.lstat(absDir).catch(() => null);
7209
7788
  if (!lst)
7210
7789
  return false;
7211
7790
  if (lst.isSymbolicLink())
7212
7791
  return true;
7213
7792
  if (lst.isDirectory()) {
7214
- const marker = await fsp6.stat(nodePath6.join(absDir, ".ntn-managed-copy.json")).catch(() => null);
7793
+ const marker = await fsp7.stat(nodePath7.join(absDir, ".ntn-managed-copy.json")).catch(() => null);
7215
7794
  return Boolean(marker?.isFile());
7216
7795
  }
7217
7796
  return false;
7218
- }).pipe(Effect5.catch(() => Effect5.succeed(false))) : false;
7797
+ }).pipe(Effect6.catch(() => Effect6.succeed(false))) : false;
7219
7798
  return {
7220
7799
  skillId: created.id,
7221
7800
  name: skillName,
@@ -7228,12 +7807,12 @@ function createNewSkillCommand(args) {
7228
7807
  });
7229
7808
  }
7230
7809
  function setSkillMetaCommand(args) {
7231
- return Effect5.gen(function* () {
7810
+ return Effect6.gen(function* () {
7232
7811
  const notion = yield* NotionPort;
7233
7812
  const { libraryId, libState } = yield* loadSyncedLibrary(args.libraryId);
7234
7813
  const requestedNames = [...args.name ? [args.name] : [], ...args.names ?? []].map((n) => n.trim()).filter(Boolean);
7235
7814
  if (requestedNames.length === 0 && !args.sourceQuery?.trim()) {
7236
- return yield* Effect5.fail(new ConfigError({
7815
+ return yield* Effect6.fail(new ConfigError({
7237
7816
  message: "Specify at least one skill <name> or pass --source <source-name-or-id>."
7238
7817
  }));
7239
7818
  }
@@ -7260,7 +7839,7 @@ function setSkillMetaCommand(args) {
7260
7839
  for (const reqName of args.requireNames) {
7261
7840
  const found = yield* findSkillOrFail(libState, reqName);
7262
7841
  if (!found.enabled) {
7263
- return yield* Effect5.fail(new NotFoundError({
7842
+ return yield* Effect6.fail(new NotFoundError({
7264
7843
  entity: "skill",
7265
7844
  target: reqName,
7266
7845
  message: `Required skill '${reqName}' is disabled.`
@@ -7269,7 +7848,7 @@ function setSkillMetaCommand(args) {
7269
7848
  nextRequires.push(found.id);
7270
7849
  }
7271
7850
  }
7272
- yield* Effect5.forEach(targetList, (targetSkill) => Effect5.gen(function* () {
7851
+ yield* Effect6.forEach(targetList, (targetSkill) => Effect6.gen(function* () {
7273
7852
  const nextProfiles = new Set(targetSkill.profiles);
7274
7853
  for (const p of args.addProfiles ?? [])
7275
7854
  nextProfiles.add(p);
@@ -7301,17 +7880,17 @@ function setSkillMetaCommand(args) {
7301
7880
  });
7302
7881
  }
7303
7882
  function detachSkillCommand(args) {
7304
- return Effect5.gen(function* () {
7883
+ return Effect6.gen(function* () {
7305
7884
  const notion = yield* NotionPort;
7306
7885
  const { libraryId, binding } = yield* loadResolvedLibrary(args.libraryId);
7307
7886
  const pulled = yield* editOrPullSkillCommand({ name: args.name, libraryId });
7308
7887
  try {
7309
- const files = yield* Effect5.tryPromise({
7888
+ const files = yield* Effect6.tryPromise({
7310
7889
  try: () => scanWorkdirFiles(pulled.workdir),
7311
7890
  catch: (e) => new StoreError({ path: pulled.workdir, message: String(e) })
7312
7891
  });
7313
7892
  const supportingEntries = [...files.entries()].filter(([relPath]) => relPath !== "SKILL.md");
7314
- yield* Effect5.forEach(supportingEntries, ([relPath, f]) => Effect5.gen(function* () {
7893
+ yield* Effect6.forEach(supportingEntries, ([relPath, f]) => Effect6.gen(function* () {
7315
7894
  const base = pulled.meta.baseFiles[relPath];
7316
7895
  const encoded = base?.externalUrl ? null : yield* encodeSupportingFileEffect(f.bytes, relPath);
7317
7896
  yield* notion.upsertFilePage({
@@ -7352,7 +7931,7 @@ function detachSkillCommand(args) {
7352
7931
  revision: makeRevisionStamp()
7353
7932
  });
7354
7933
  } finally {
7355
- yield* trashPathEffect(pulled.workdir).pipe(Effect5.ignore);
7934
+ yield* trashPathEffect(pulled.workdir).pipe(Effect6.ignore);
7356
7935
  }
7357
7936
  yield* syncCommand({
7358
7937
  libraryId,
@@ -7366,14 +7945,14 @@ function detachSkillCommand(args) {
7366
7945
  });
7367
7946
  }
7368
7947
  function attachSkillCommand(args) {
7369
- return Effect5.gen(function* () {
7948
+ return Effect6.gen(function* () {
7370
7949
  const notion = yield* NotionPort;
7371
7950
  const upstream = yield* UpstreamPort;
7372
7951
  const { libraryId, binding, libState } = yield* loadSyncedLibrary(args.libraryId);
7373
7952
  const sk = yield* findSkillOrFail(libState, args.name);
7374
7953
  const src = yield* findSourceOrFail(libState, args.sourceQuery);
7375
7954
  if (!src.enabled) {
7376
- return yield* Effect5.fail(new NotFoundError({
7955
+ return yield* Effect6.fail(new NotFoundError({
7377
7956
  entity: "source",
7378
7957
  target: src.name,
7379
7958
  message: `Source '${src.name}' is disabled. Enable it with 'ntn-skills source set "${src.name}" --enable' first.`
@@ -7388,7 +7967,7 @@ function attachSkillCommand(args) {
7388
7967
  });
7389
7968
  const match = discovered.find((d) => d.name.toLowerCase() === sk.name.toLowerCase());
7390
7969
  if (!match) {
7391
- return yield* Effect5.fail(new NotFoundError({
7970
+ return yield* Effect6.fail(new NotFoundError({
7392
7971
  entity: "skill",
7393
7972
  target: sk.name,
7394
7973
  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 +7982,14 @@ function attachSkillCommand(args) {
7403
7982
  });
7404
7983
  const upstreamMain = subtreeFiles.find((f) => f.path === "SKILL.md");
7405
7984
  if (!upstreamMain) {
7406
- return yield* Effect5.fail(new StoreError({
7985
+ return yield* Effect6.fail(new StoreError({
7407
7986
  path: resolvedPath,
7408
7987
  message: `No SKILL.md found at '${resolvedPath}' in ${src.repoUrl}@${commitSha.slice(0, 12)}.`
7409
7988
  }));
7410
7989
  }
7411
7990
  const subDigest = computeSubtreeDigest(subtreeFiles);
7412
7991
  const upByPath = new Map(subtreeFiles.filter((f) => f.path !== "SKILL.md").map((f) => [f.path, f]));
7413
- const [liveFiles, liveBody] = yield* Effect5.all([
7992
+ const [liveFiles, liveBody] = yield* Effect6.all([
7414
7993
  notion.getSkillFiles({ filesDs: binding.files_ds, skillId: sk.id }),
7415
7994
  notion.readSkillBody(sk.id)
7416
7995
  ]);
@@ -7499,13 +8078,13 @@ function attachSkillCommand(args) {
7499
8078
  });
7500
8079
  }
7501
8080
  function resetOverlayCommand(args) {
7502
- return Effect5.gen(function* () {
8081
+ return Effect6.gen(function* () {
7503
8082
  const notion = yield* NotionPort;
7504
8083
  const upstream = yield* UpstreamPort;
7505
8084
  const { libraryId, binding, libState } = yield* loadSyncedLibrary(args.libraryId);
7506
8085
  const sk = yield* findSkillOrFail(libState, args.name);
7507
8086
  if (!sk.originSourceId) {
7508
- return yield* Effect5.fail(new NotFoundError({
8087
+ return yield* Effect6.fail(new NotFoundError({
7509
8088
  entity: "skill",
7510
8089
  target: args.name,
7511
8090
  message: `Skill '${args.name}' is not an upstream Git skill.`
@@ -7560,7 +8139,7 @@ function resetOverlayCommand(args) {
7560
8139
  });
7561
8140
  }
7562
8141
  function removeSkillCommand(args) {
7563
- return Effect5.gen(function* () {
8142
+ return Effect6.gen(function* () {
7564
8143
  const notion = yield* NotionPort;
7565
8144
  const { libraryId, libState } = yield* loadSyncedLibrary(args.libraryId);
7566
8145
  const sk = yield* findSkillOrFail(libState, args.name);
@@ -7576,10 +8155,10 @@ function removeSkillCommand(args) {
7576
8155
  });
7577
8156
  }
7578
8157
  function listSourcesCommand(args) {
7579
- return loadTableMetadataLibrary(args?.libraryId).pipe(Effect5.map(({ libState }) => Object.values(libState.sources).sort((a, b) => a.name.localeCompare(b.name))));
8158
+ return loadTableMetadataLibrary(args?.libraryId).pipe(Effect6.map(({ libState }) => Object.values(libState.sources).sort((a, b) => a.name.localeCompare(b.name))));
7580
8159
  }
7581
8160
  function addSourceCommand(args) {
7582
- return Effect5.gen(function* () {
8161
+ return Effect6.gen(function* () {
7583
8162
  const notion = yield* NotionPort;
7584
8163
  const upstream = yield* UpstreamPort;
7585
8164
  const { libraryId, binding, libState } = yield* loadSyncedLibrary(args.libraryId);
@@ -7610,7 +8189,7 @@ function addSourceCommand(args) {
7610
8189
  existingNames.add(lower);
7611
8190
  return true;
7612
8191
  });
7613
- const createdResults = yield* Effect5.forEach(toRegister, (d) => Effect5.gen(function* () {
8192
+ const createdResults = yield* Effect6.forEach(toRegister, (d) => Effect6.gen(function* () {
7614
8193
  const subtreeFiles = yield* upstream.fetchSubtree({
7615
8194
  repoUrl: cleanUrl,
7616
8195
  commitSha,
@@ -7679,14 +8258,14 @@ function findSourceOrFail(libState, sourceQuery) {
7679
8258
  const q = sourceQuery.trim().toLowerCase();
7680
8259
  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
8260
  const found = candidates[0];
7682
- return found ? Effect5.succeed(found) : Effect5.fail(new NotFoundError({
8261
+ return found ? Effect6.succeed(found) : Effect6.fail(new NotFoundError({
7683
8262
  entity: "source",
7684
8263
  target: sourceQuery,
7685
8264
  message: `Source '${sourceQuery}' not found.`
7686
8265
  }));
7687
8266
  }
7688
8267
  function setSourceMetaCommand(args) {
7689
- return Effect5.gen(function* () {
8268
+ return Effect6.gen(function* () {
7690
8269
  const notion = yield* NotionPort;
7691
8270
  const { libraryId, libState } = yield* loadTableMetadataLibrary(args.libraryId);
7692
8271
  const src = yield* findSourceOrFail(libState, args.sourceQuery);
@@ -7706,13 +8285,13 @@ function setSourceMetaCommand(args) {
7706
8285
  });
7707
8286
  }
7708
8287
  function syncSourceSkillsCommand(args) {
7709
- return Effect5.gen(function* () {
8288
+ return Effect6.gen(function* () {
7710
8289
  const notion = yield* NotionPort;
7711
8290
  const upstream = yield* UpstreamPort;
7712
8291
  const { libraryId, binding, libState } = yield* loadTableMetadataLibrary(args.libraryId);
7713
8292
  const src = yield* findSourceOrFail(libState, args.sourceQuery);
7714
8293
  if (!src.enabled) {
7715
- return yield* Effect5.fail(new NotFoundError({
8294
+ return yield* Effect6.fail(new NotFoundError({
7716
8295
  entity: "source",
7717
8296
  target: src.name,
7718
8297
  message: `Source '${src.name}' is disabled. Enable it with 'ntn-skills source set "${src.name}" --enable' first.`
@@ -7729,7 +8308,7 @@ function syncSourceSkillsCommand(args) {
7729
8308
  const existingSkills = Object.values(libState.skills).filter((s) => s.enabled);
7730
8309
  const existingByName = new Map(existingSkills.map((s) => [s.name.toLowerCase(), s]));
7731
8310
  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* () {
8311
+ const repairResults = yield* Effect6.forEach(toRepair, ({ sk, match }) => Effect6.gen(function* () {
7733
8312
  const subtreeFiles = yield* upstream.fetchSubtree({
7734
8313
  repoUrl: src.repoUrl,
7735
8314
  commitSha,
@@ -7765,7 +8344,7 @@ function syncSourceSkillsCommand(args) {
7765
8344
  seenNames.add(lower);
7766
8345
  return true;
7767
8346
  });
7768
- const createResults = yield* Effect5.forEach(toRegister, (d) => Effect5.gen(function* () {
8347
+ const createResults = yield* Effect6.forEach(toRegister, (d) => Effect6.gen(function* () {
7769
8348
  const subtreeFiles = yield* upstream.fetchSubtree({
7770
8349
  repoUrl: src.repoUrl,
7771
8350
  commitSha,
@@ -7840,12 +8419,12 @@ function syncSourceSkillsCommand(args) {
7840
8419
  });
7841
8420
  }
7842
8421
  function upstreamCheckOrApplyCommand(args) {
7843
- return Effect5.gen(function* () {
8422
+ return Effect6.gen(function* () {
7844
8423
  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." }));
8424
+ return yield* Effect6.fail(new ConfigError({ message: "--max-sources must be an integer >= 1." }));
7846
8425
  }
7847
8426
  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." }));
8427
+ return yield* Effect6.fail(new ConfigError({ message: "--timeout-sec must be greater than 0." }));
7849
8428
  }
7850
8429
  const notion = yield* NotionPort;
7851
8430
  const upstream = yield* UpstreamPort;
@@ -7853,7 +8432,7 @@ function upstreamCheckOrApplyCommand(args) {
7853
8432
  const startedMs = Date.now();
7854
8433
  const startedAt = new Date(startedMs).toISOString();
7855
8434
  const deadlineMs = args.timeoutSec !== undefined ? startedMs + Math.round(args.timeoutSec * 1000) : undefined;
7856
- const runCore = Effect5.gen(function* () {
8435
+ const runCore = Effect6.gen(function* () {
7857
8436
  const { libraryId, binding, libState } = yield* loadTableMetadataLibrary(args.libraryId);
7858
8437
  const filesBySkillId = new Map;
7859
8438
  for (const f of Object.values(libState.files)) {
@@ -7875,7 +8454,7 @@ function upstreamCheckOrApplyCommand(args) {
7875
8454
  return s.policy === "track";
7876
8455
  }).sort((a, b) => a.name.localeCompare(b.name));
7877
8456
  if (args.sourceQuery && candidateSources.length === 0) {
7878
- return yield* Effect5.fail(new NotFoundError({
8457
+ return yield* Effect6.fail(new NotFoundError({
7879
8458
  entity: "source",
7880
8459
  target: args.sourceQuery,
7881
8460
  message: `Enabled source '${args.sourceQuery}' not found in library ${libraryId}.`
@@ -7912,7 +8491,7 @@ function upstreamCheckOrApplyCommand(args) {
7912
8491
  });
7913
8492
  continue;
7914
8493
  }
7915
- const singleEffect = Effect5.gen(function* () {
8494
+ const singleEffect = Effect6.gen(function* () {
7916
8495
  const latestCommit = yield* upstream.resolveHeadCommit(src.repoUrl, src.ref);
7917
8496
  const hasUpdate = latestCommit !== src.pinnedCommit;
7918
8497
  if (!hasUpdate) {
@@ -7979,7 +8558,7 @@ function upstreamCheckOrApplyCommand(args) {
7979
8558
  const discoveredNewByPath = new Map(discoveredNew.map((d) => [normalizeSourcePathKey(d.sourcePath), d]));
7980
8559
  let oldSkillPaths = null;
7981
8560
  if (src.pinnedCommit) {
7982
- const oldDiscovered = yield* upstream.scanRepoSkills({ repoUrl: src.repoUrl, commitSha: src.pinnedCommit }).pipe(Effect5.catch(() => Effect5.succeed(null)));
8561
+ const oldDiscovered = yield* upstream.scanRepoSkills({ repoUrl: src.repoUrl, commitSha: src.pinnedCommit }).pipe(Effect6.catch(() => Effect6.succeed(null)));
7983
8562
  if (oldDiscovered !== null) {
7984
8563
  oldSkillPaths = new Set(oldDiscovered.map((d) => normalizeSourcePathKey(d.sourcePath)));
7985
8564
  }
@@ -7991,13 +8570,13 @@ function upstreamCheckOrApplyCommand(args) {
7991
8570
  const previewDriftWarnings = [];
7992
8571
  const localTouchedSkillIds = [];
7993
8572
  const localArchivedFileIds = [];
7994
- yield* Effect5.forEach(childSkills, (sk) => Effect5.gen(function* () {
8573
+ yield* Effect6.forEach(childSkills, (sk) => Effect6.gen(function* () {
7995
8574
  const sourcePath = normalizeSourcePathKey(sk.sourcePath);
7996
8575
  const subtreeOpt = yield* upstream.fetchSubtree({
7997
8576
  repoUrl: src.repoUrl,
7998
8577
  commitSha: latestCommit,
7999
8578
  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)));
8579
+ }).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
8580
  const activeOverlays = normalizeOverlayFiles(filesBySkillId.get(sk.id) ?? []);
8002
8581
  const overrideRows = activeOverlays.filter((ov) => ov.status === "override");
8003
8582
  if (subtreeOpt === null) {
@@ -8021,11 +8600,11 @@ function upstreamCheckOrApplyCommand(args) {
8021
8600
  repoUrl: src.repoUrl,
8022
8601
  commitSha: src.pinnedCommit,
8023
8602
  sourcePath
8024
- }).pipe(Effect5.catch(() => Effect5.succeed(null)));
8603
+ }).pipe(Effect6.catch(() => Effect6.succeed(null)));
8025
8604
  if (oldFiles !== null) {
8026
8605
  const overlayPathSet = new Set(activeOverlays.map((o) => o.path));
8027
8606
  const remainingBase = oldFiles.filter((f) => f.path !== "SKILL.md" && !overlayPathSet.has(f.path));
8028
- yield* Effect5.forEach(remainingBase, (bf) => Effect5.gen(function* () {
8607
+ yield* Effect6.forEach(remainingBase, (bf) => Effect6.gen(function* () {
8029
8608
  const encoded = yield* encodeSupportingFileEffect(bf.bytes, bf.path);
8030
8609
  yield* notion.upsertFilePage({
8031
8610
  libraryId,
@@ -8075,7 +8654,7 @@ function upstreamCheckOrApplyCommand(args) {
8075
8654
  repoUrl: src.repoUrl,
8076
8655
  commitSha: src.pinnedCommit,
8077
8656
  sourcePath
8078
- }).pipe(Effect5.catch(() => Effect5.succeed(null))) : null;
8657
+ }).pipe(Effect6.catch(() => Effect6.succeed(null))) : null;
8079
8658
  const oldDigest = oldSubtreeFiles ? computeSubtreeDigest(oldSubtreeFiles) : null;
8080
8659
  const oldShaByPath = new Map;
8081
8660
  for (const ofile of oldSubtreeFiles ?? []) {
@@ -8147,7 +8726,7 @@ function upstreamCheckOrApplyCommand(args) {
8147
8726
  let matchesTargetUpstream = false;
8148
8727
  if (rawMainText !== null) {
8149
8728
  const preparedTarget = prepareSkillMarkdownForNotionBody(rawMainText).cleanNotionMarkdown;
8150
- const renderedTarget = yield* Effect5.tryPromise(() => renderBlocksToMarkdown(markdownToBlocks(preparedTarget), async () => [])).pipe(Effect5.catch(() => Effect5.succeed("")));
8729
+ const renderedTarget = yield* Effect6.tryPromise(() => renderBlocksToMarkdown(markdownToBlocks(preparedTarget), async () => [])).pipe(Effect6.catch(() => Effect6.succeed("")));
8151
8730
  const trimmedLive = currentBody.rawMarkdown.trim();
8152
8731
  if (trimmedLive === preparedTarget.trim() || renderedTarget.length > 0 && trimmedLive === renderedTarget.trim()) {
8153
8732
  matchesTargetUpstream = true;
@@ -8212,7 +8791,7 @@ function upstreamCheckOrApplyCommand(args) {
8212
8791
  takenActiveNames.add(lowerName);
8213
8792
  return true;
8214
8793
  });
8215
- yield* Effect5.forEach(toAddSkills, (d) => Effect5.gen(function* () {
8794
+ yield* Effect6.forEach(toAddSkills, (d) => Effect6.gen(function* () {
8216
8795
  const subtreeFiles = yield* upstream.fetchSubtree({
8217
8796
  repoUrl: src.repoUrl,
8218
8797
  commitSha: latestCommit,
@@ -8286,7 +8865,7 @@ function upstreamCheckOrApplyCommand(args) {
8286
8865
  previewDriftWarnings
8287
8866
  };
8288
8867
  });
8289
- const isolatedEffect = (deadlineMs !== undefined ? singleEffect.pipe(Effect5.timeoutOption(Math.max(500, deadlineMs - Date.now())), Effect5.map((opt) => Option.isSome(opt) ? opt.value : {
8868
+ const isolatedEffect = (deadlineMs !== undefined ? singleEffect.pipe(Effect6.timeoutOption(Math.max(500, deadlineMs - Date.now())), Effect6.map((opt) => Option.isSome(opt) ? opt.value : {
8290
8869
  sourceId: src.id,
8291
8870
  sourceName: src.name,
8292
8871
  repoUrl: src.repoUrl,
@@ -8299,15 +8878,15 @@ function upstreamCheckOrApplyCommand(args) {
8299
8878
  previewDriftWarnings: [],
8300
8879
  error: `Source timed out before batch deadline (${args.timeoutSec}s).`,
8301
8880
  retryable: true
8302
- })) : singleEffect).pipe(Effect5.catch((err) => {
8881
+ })) : singleEffect).pipe(Effect6.catch((err) => {
8303
8882
  if (err._tag === "AuthError" && err.provider === "notion") {
8304
- return Effect5.fail(err);
8883
+ return Effect6.fail(err);
8305
8884
  }
8306
8885
  if (err._tag === "ConflictError" && err.kind === "production_guard") {
8307
- return Effect5.fail(err);
8886
+ return Effect6.fail(err);
8308
8887
  }
8309
8888
  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({
8889
+ return Effect6.succeed({
8311
8890
  sourceId: src.id,
8312
8891
  sourceName: src.name,
8313
8892
  repoUrl: src.repoUrl,
@@ -8357,56 +8936,1094 @@ function upstreamCheckOrApplyCommand(args) {
8357
8936
  break;
8358
8937
  }
8359
8938
  }
8360
- if (applied > 0) {
8939
+ if (applied > 0) {
8940
+ yield* syncCommand({
8941
+ libraryId,
8942
+ dedupeWindowMs: 0,
8943
+ readYourWrites: {
8944
+ sourceIds: rywSourceIds,
8945
+ skillIds: rywSkillIds,
8946
+ archivedFileIds: rywArchivedFileIds
8947
+ }
8948
+ });
8949
+ }
8950
+ const finishedMs = Date.now();
8951
+ const permanentFailures = failed - retryableFailures;
8952
+ const recommendedExitCode = permanentFailures > 0 ? 2 : retryableFailures > 0 || skippedDeadline > 0 ? 75 : args.strictDrift && driftWarningsCount > 0 ? 3 : 0;
8953
+ const report = {
8954
+ libraryId,
8955
+ mode: !args.apply ? "check" : args.dryRun ? "dry-run" : "apply",
8956
+ startedAt,
8957
+ finishedAt: new Date(finishedMs).toISOString(),
8958
+ durationMs: Math.max(0, finishedMs - startedMs),
8959
+ totalCandidates: candidateSources.length,
8960
+ checked,
8961
+ upToDate,
8962
+ updateAvailable,
8963
+ applied,
8964
+ skippedLimit,
8965
+ skippedDeadline,
8966
+ driftWarningsCount,
8967
+ failed,
8968
+ retryableFailures,
8969
+ recommendedExitCode,
8970
+ sources: sourcesOut
8971
+ };
8972
+ if (args.reportFile) {
8973
+ const outPath = resolveHomePath(args.reportFile);
8974
+ yield* Effect6.tryPromise({
8975
+ try: () => atomicWriteJson(outPath, report),
8976
+ catch: (e) => new StoreError({
8977
+ path: outPath,
8978
+ message: `Failed writing upstream report to ${outPath}: ${String(e)}`
8979
+ })
8980
+ });
8981
+ }
8982
+ return report;
8983
+ });
8984
+ if (args.apply && !args.dryRun) {
8985
+ const { libraryId } = yield* loadResolvedLibrary(args.libraryId);
8986
+ return yield* store.withExclusiveLock(`upstream-${libShortHash(libraryId)}`, runCore, 120000);
8987
+ }
8988
+ return yield* runCore;
8989
+ });
8990
+ }
8991
+ // packages/core/src/edit/batch-commands.ts
8992
+ import * as fsp8 from "node:fs/promises";
8993
+ import * as nodePath8 from "node:path";
8994
+ import { Effect as Effect7 } from "effect";
8995
+ var UPSTREAM_SKILL_CONCURRENCY2 = 3;
8996
+ function buildExcludeSet(exclude) {
8997
+ const set = new Set;
8998
+ for (const raw of exclude ?? []) {
8999
+ for (const part of raw.split(",")) {
9000
+ const trimmed = part.trim();
9001
+ if (!trimmed)
9002
+ continue;
9003
+ set.add(trimmed.toLowerCase());
9004
+ const slug = normalizeSkillSlug(trimmed);
9005
+ if (slug)
9006
+ set.add(slug);
9007
+ }
9008
+ }
9009
+ return set;
9010
+ }
9011
+ function matchesExclude(excludeSet, candidates) {
9012
+ if (excludeSet.size === 0)
9013
+ return false;
9014
+ for (const raw of candidates) {
9015
+ if (!raw)
9016
+ continue;
9017
+ const trimmed = raw.trim();
9018
+ if (!trimmed)
9019
+ continue;
9020
+ if (excludeSet.has(trimmed.toLowerCase()))
9021
+ return true;
9022
+ const slug = normalizeSkillSlug(trimmed);
9023
+ if (slug && excludeSet.has(slug))
9024
+ return true;
9025
+ }
9026
+ return false;
9027
+ }
9028
+ async function readFrontmatterNameBestEffort(dirPath) {
9029
+ try {
9030
+ const raw = await fsp8.readFile(nodePath8.join(dirPath, "SKILL.md"), "utf8");
9031
+ const parsed = parseSkillFrontmatter(raw);
9032
+ return parsed.name?.trim() || undefined;
9033
+ } catch {
9034
+ return;
9035
+ }
9036
+ }
9037
+ async function isManagedExportAtPath(absDir) {
9038
+ const lst = await fsp8.lstat(absDir).catch(() => null);
9039
+ if (!lst)
9040
+ return false;
9041
+ if (lst.isSymbolicLink())
9042
+ return true;
9043
+ if (lst.isDirectory()) {
9044
+ const marker = await fsp8.stat(nodePath8.join(absDir, ".ntn-managed-copy.json")).catch(() => null);
9045
+ return Boolean(marker?.isFile());
9046
+ }
9047
+ return false;
9048
+ }
9049
+ function createNewSkillsBatchCommand(args) {
9050
+ return Effect7.gen(function* () {
9051
+ const notion = yield* NotionPort;
9052
+ const store = yield* StorePort;
9053
+ const explicitDirs = (args.dirs ?? []).map((d) => d.trim()).filter(Boolean);
9054
+ const isPending = Boolean(args.pending);
9055
+ const isDryRun = Boolean(args.dryRun);
9056
+ if (explicitDirs.length === 0 && !isPending) {
9057
+ return yield* Effect7.fail(new ConfigError({
9058
+ message: "Specify at least one skill directory <dir...> or pass --pending to discover unmanaged local skills in configured export roots."
9059
+ }));
9060
+ }
9061
+ if ((explicitDirs.length > 1 || isPending) && args.name?.trim()) {
9062
+ return yield* Effect7.fail(new ConfigError({
9063
+ message: "Cannot pass --name when creating multiple skills or using --pending."
9064
+ }));
9065
+ }
9066
+ const explicitVisibility = args.visibility ?? (args.defaultContext !== undefined ? args.defaultContext ? "always" : "manual" : undefined);
9067
+ if (isPending && !explicitVisibility) {
9068
+ return yield* Effect7.fail(new ConfigError({
9069
+ 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"
9070
+ }));
9071
+ }
9072
+ const excludeSet = buildExcludeSet(args.exclude);
9073
+ const { config, libraryId, binding, libState } = yield* loadTableMetadataLibrary(args.libraryId);
9074
+ const resolvedExports = yield* resolveConfiguredExports(config, store.paths.configPath);
9075
+ const realStoreRoot = yield* Effect7.promise(() => fsp8.realpath(store.paths.storeRoot).catch(() => nodePath8.resolve(store.paths.storeRoot)));
9076
+ const storePrefixes = Array.from(new Set([
9077
+ `${nodePath8.resolve(store.paths.storeRoot)}${nodePath8.sep}`,
9078
+ `${realStoreRoot}${nodePath8.sep}`
9079
+ ]));
9080
+ const exportRootEntries = yield* Effect7.promise(async () => {
9081
+ const list = [];
9082
+ for (const resolved of resolvedExports.targets) {
9083
+ const absRoot = resolveHomePath(resolved.target.dir);
9084
+ const realRoot = await fsp8.realpath(absRoot).catch(() => absRoot);
9085
+ list.push({ resolved, absRoot, realRoot });
9086
+ }
9087
+ return list;
9088
+ });
9089
+ const skipped = [];
9090
+ const candidateDirs = [];
9091
+ const seenCanonicalPaths = new Set;
9092
+ const canonicalizePath = async (p) => {
9093
+ const abs = nodePath8.resolve(p);
9094
+ const real = await fsp8.realpath(abs).catch(() => abs);
9095
+ return real;
9096
+ };
9097
+ for (const rawDir of explicitDirs) {
9098
+ const absDir = resolveHomePath(rawDir);
9099
+ const canon = yield* Effect7.promise(() => canonicalizePath(absDir));
9100
+ if (seenCanonicalPaths.has(canon))
9101
+ continue;
9102
+ seenCanonicalPaths.add(canon);
9103
+ const dirName = nodePath8.basename(absDir);
9104
+ const fmName = yield* Effect7.promise(() => readFrontmatterNameBestEffort(absDir));
9105
+ if (matchesExclude(excludeSet, [dirName, fmName])) {
9106
+ skipped.push({
9107
+ dir: absDir,
9108
+ name: fmName ?? dirName,
9109
+ reason: "excluded"
9110
+ });
9111
+ continue;
9112
+ }
9113
+ candidateDirs.push(absDir);
9114
+ }
9115
+ if (isPending) {
9116
+ const seenEntryPaths = new Set;
9117
+ for (const expEntry of exportRootEntries) {
9118
+ const entries = yield* Effect7.promise(() => fsp8.readdir(expEntry.absRoot).catch(() => []));
9119
+ for (const entryName of entries.sort()) {
9120
+ if (entryName.startsWith("."))
9121
+ continue;
9122
+ const full = nodePath8.join(expEntry.absRoot, entryName);
9123
+ if (seenEntryPaths.has(full))
9124
+ continue;
9125
+ seenEntryPaths.add(full);
9126
+ const lst = yield* Effect7.promise(() => fsp8.lstat(full).catch(() => null));
9127
+ if (!lst)
9128
+ continue;
9129
+ if (lst.isSymbolicLink()) {
9130
+ const rawLink = yield* Effect7.promise(() => fsp8.readlink(full).catch(() => ""));
9131
+ const resolvedLink = nodePath8.resolve(expEntry.absRoot, rawLink);
9132
+ const realResolvedLink = yield* Effect7.promise(() => fsp8.realpath(resolvedLink).catch(() => resolvedLink));
9133
+ if (storePrefixes.some((pref) => resolvedLink.startsWith(pref) || realResolvedLink.startsWith(pref))) {
9134
+ continue;
9135
+ }
9136
+ if (!args.includeSymlinks) {
9137
+ skipped.push({
9138
+ dir: full,
9139
+ name: entryName,
9140
+ reason: "external_symlink",
9141
+ target: rawLink
9142
+ });
9143
+ continue;
9144
+ }
9145
+ const targetStat = yield* Effect7.promise(() => fsp8.stat(full).catch(() => null));
9146
+ if (!targetStat?.isDirectory()) {
9147
+ skipped.push({
9148
+ dir: full,
9149
+ name: entryName,
9150
+ reason: "not_a_directory",
9151
+ target: rawLink
9152
+ });
9153
+ continue;
9154
+ }
9155
+ } else if (lst.isDirectory()) {
9156
+ const managedMarker = yield* Effect7.promise(() => fsp8.stat(nodePath8.join(full, ".ntn-managed-copy.json")).catch(() => null));
9157
+ if (managedMarker?.isFile()) {
9158
+ continue;
9159
+ }
9160
+ } else {
9161
+ continue;
9162
+ }
9163
+ const canon = yield* Effect7.promise(() => canonicalizePath(full));
9164
+ if (seenCanonicalPaths.has(canon))
9165
+ continue;
9166
+ seenCanonicalPaths.add(canon);
9167
+ const skillMdStat = yield* Effect7.promise(() => fsp8.stat(nodePath8.join(full, "SKILL.md")).catch(() => null));
9168
+ if (!skillMdStat?.isFile()) {
9169
+ skipped.push({
9170
+ dir: full,
9171
+ name: entryName,
9172
+ reason: "missing_skill_md"
9173
+ });
9174
+ continue;
9175
+ }
9176
+ const fmName = yield* Effect7.promise(() => readFrontmatterNameBestEffort(full));
9177
+ if (matchesExclude(excludeSet, [entryName, fmName])) {
9178
+ skipped.push({
9179
+ dir: full,
9180
+ name: fmName ?? entryName,
9181
+ reason: "excluded"
9182
+ });
9183
+ continue;
9184
+ }
9185
+ candidateDirs.push(full);
9186
+ }
9187
+ }
9188
+ }
9189
+ const activeByKey = new Map;
9190
+ const registerActiveSkill = (id, name) => {
9191
+ activeByKey.set(name.toLowerCase(), { id, name });
9192
+ const slug = normalizeSkillSlug(name);
9193
+ if (slug)
9194
+ activeByKey.set(`slug:${slug}`, { id, name });
9195
+ };
9196
+ for (const sk of Object.values(libState.skills)) {
9197
+ if (sk.enabled) {
9198
+ registerActiveSkill(sk.id, sk.name);
9199
+ }
9200
+ }
9201
+ const sourcesById = new Map(Object.entries(libState.sources));
9202
+ const existingEffectiveSkills = filterEffectiveSkills(Object.values(libState.skills), sourcesById);
9203
+ const profiles = args.profiles?.length ? [...args.profiles] : ["default"];
9204
+ const scenes = args.scenes ? [...args.scenes] : [];
9205
+ const kind = args.kind ?? "skill";
9206
+ const findMatchingExportRoots = async (absDir) => {
9207
+ const lst = await fsp8.lstat(absDir).catch(() => null);
9208
+ if (!lst || lst.isSymbolicLink())
9209
+ return [];
9210
+ const parentAbs = nodePath8.dirname(absDir);
9211
+ const parentReal = await fsp8.realpath(parentAbs).catch(() => parentAbs);
9212
+ return exportRootEntries.filter((e) => parentAbs === e.absRoot || parentReal === e.realRoot);
9213
+ };
9214
+ const predictExportAtSourcePath = (matchingRoots, skillName, description, visibility) => {
9215
+ if (matchingRoots.length === 0)
9216
+ return false;
9217
+ const syntheticId = `__planned__:${skillName}`;
9218
+ const syntheticSkill = {
9219
+ id: syntheticId,
9220
+ name: skillName,
9221
+ description,
9222
+ enabled: true,
9223
+ visibility,
9224
+ kind,
9225
+ profiles,
9226
+ scenes,
9227
+ requiresIds: [],
9228
+ originSourceId: null,
9229
+ sourcePath: "",
9230
+ customMain: false,
9231
+ revision: "",
9232
+ previewHash: "",
9233
+ lastEditedTime: new Date().toISOString()
9234
+ };
9235
+ const allEffective = [...existingEffectiveSkills, syntheticSkill];
9236
+ const catSkills = filterCatalogSkills(allEffective, config.profiles);
9237
+ for (const rootEntry of matchingRoots) {
9238
+ const sel = resolveExportSelection({
9239
+ allEffectiveSkills: allEffective,
9240
+ catalogSkills: catSkills,
9241
+ target: rootEntry.resolved.target,
9242
+ bundles: rootEntry.resolved.bundles
9243
+ });
9244
+ if (sel.selected.some((s) => s.id === syntheticId)) {
9245
+ return true;
9246
+ }
9247
+ }
9248
+ return false;
9249
+ };
9250
+ const created = [];
9251
+ const failed = [];
9252
+ const createdSkillIds = [];
9253
+ const createdFileIds = [];
9254
+ for (const absDir of candidateDirs) {
9255
+ const fallbackName = nodePath8.basename(absDir);
9256
+ const scanRes = yield* Effect7.tryPromise({
9257
+ try: () => scanLocalSkillDirectory(absDir),
9258
+ catch: (e) => new StoreError({
9259
+ path: absDir,
9260
+ message: `Cannot read skill directory ${absDir}: ${String(e)}`
9261
+ })
9262
+ }).pipe(Effect7.result);
9263
+ if (scanRes._tag === "Failure") {
9264
+ failed.push({
9265
+ dir: absDir,
9266
+ name: fallbackName,
9267
+ blocked: false,
9268
+ blockedFiles: [],
9269
+ conflict: false,
9270
+ code: scanRes.failure._tag,
9271
+ error: scanRes.failure.message
9272
+ });
9273
+ continue;
9274
+ }
9275
+ const scan = scanRes.success;
9276
+ const mainFile = scan.files.get("SKILL.md");
9277
+ const rawMain = mainFile ? new TextDecoder().decode(mainFile.bytes) : "";
9278
+ const parsed = mainFile ? parseSkillFrontmatter(rawMain) : null;
9279
+ const skillName = ((explicitDirs.length === 1 && !isPending ? args.name : undefined) ?? parsed?.name ?? fallbackName).trim();
9280
+ const resolvedVisibility = explicitVisibility ?? (parsed?.disableModelInvocation ? "manual" : "discoverable");
9281
+ if (scan.blockedFiles.length > 0) {
9282
+ failed.push({
9283
+ dir: absDir,
9284
+ name: skillName || fallbackName,
9285
+ visibility: resolvedVisibility,
9286
+ fileCount: scan.fileCount,
9287
+ totalBytes: scan.totalBytes,
9288
+ blocked: true,
9289
+ blockedFiles: scan.blockedFiles,
9290
+ conflict: false,
9291
+ code: "sensitive_files",
9292
+ error: formatBlockedFilesMessage(absDir, scan.blockedFiles)
9293
+ });
9294
+ continue;
9295
+ }
9296
+ if (!mainFile || !parsed) {
9297
+ failed.push({
9298
+ dir: absDir,
9299
+ name: fallbackName,
9300
+ visibility: resolvedVisibility,
9301
+ fileCount: scan.fileCount,
9302
+ totalBytes: scan.totalBytes,
9303
+ blocked: false,
9304
+ blockedFiles: [],
9305
+ conflict: false,
9306
+ code: "missing_skill_md",
9307
+ error: `Missing SKILL.md in ${absDir}.`
9308
+ });
9309
+ continue;
9310
+ }
9311
+ if (!skillName) {
9312
+ failed.push({
9313
+ dir: absDir,
9314
+ name: null,
9315
+ visibility: resolvedVisibility,
9316
+ fileCount: scan.fileCount,
9317
+ totalBytes: scan.totalBytes,
9318
+ blocked: false,
9319
+ blockedFiles: [],
9320
+ conflict: false,
9321
+ code: "invalid_skill_name",
9322
+ error: `Could not resolve skill name for ${absDir}.`
9323
+ });
9324
+ continue;
9325
+ }
9326
+ const dup = activeByKey.get(skillName.toLowerCase()) ?? activeByKey.get(`slug:${normalizeSkillSlug(skillName)}`);
9327
+ if (dup) {
9328
+ failed.push({
9329
+ dir: absDir,
9330
+ name: skillName,
9331
+ visibility: resolvedVisibility,
9332
+ fileCount: scan.fileCount,
9333
+ totalBytes: scan.totalBytes,
9334
+ blocked: false,
9335
+ blockedFiles: [],
9336
+ conflict: true,
9337
+ conflictSkillId: dup.id,
9338
+ code: "duplicate_name",
9339
+ error: `Skill '${skillName}' already exists (${dup.id}). Use 'ntn-skills push "${absDir}" --overwrite' (or 'ntn-skills edit "${dup.name}"') instead.`
9340
+ });
9341
+ continue;
9342
+ }
9343
+ const preparedSupporting = [];
9344
+ let encodeErr = null;
9345
+ for (const [relPath, f] of scan.files) {
9346
+ if (relPath === "SKILL.md")
9347
+ continue;
9348
+ const enc = yield* encodeSupportingFileEffect(f.bytes, relPath).pipe(Effect7.result);
9349
+ if (enc._tag === "Failure") {
9350
+ encodeErr = enc.failure.message;
9351
+ break;
9352
+ }
9353
+ preparedSupporting.push({
9354
+ relPath,
9355
+ sha256: sha256Hex(f.bytes),
9356
+ executable: f.executable,
9357
+ textContent: enc.success
9358
+ });
9359
+ }
9360
+ if (encodeErr) {
9361
+ failed.push({
9362
+ dir: absDir,
9363
+ name: skillName,
9364
+ visibility: resolvedVisibility,
9365
+ fileCount: scan.fileCount,
9366
+ totalBytes: scan.totalBytes,
9367
+ blocked: false,
9368
+ blockedFiles: [],
9369
+ conflict: false,
9370
+ code: "invalid_supporting_file",
9371
+ error: encodeErr
9372
+ });
9373
+ continue;
9374
+ }
9375
+ const matchingExportRoots = yield* Effect7.promise(() => findMatchingExportRoots(absDir));
9376
+ const isInExportRoot = matchingExportRoots.length > 0;
9377
+ const willAdopt = args.adopt === undefined ? isInExportRoot : args.adopt;
9378
+ const willExportAtSourcePath = willAdopt && isInExportRoot && predictExportAtSourcePath(matchingExportRoots, skillName, (parsed.description ?? "").trim(), resolvedVisibility);
9379
+ if (isDryRun) {
9380
+ registerActiveSkill(`planned:${absDir}`, skillName);
9381
+ created.push({
9382
+ dir: absDir,
9383
+ skillId: null,
9384
+ name: skillName,
9385
+ visibility: resolvedVisibility,
9386
+ kind,
9387
+ fileCount: scan.fileCount,
9388
+ uploadedFiles: preparedSupporting.length,
9389
+ totalBytes: scan.totalBytes,
9390
+ blocked: false,
9391
+ blockedFiles: [],
9392
+ conflict: false,
9393
+ adoptedSourceDir: false,
9394
+ adoptedFromExportRoot: false,
9395
+ exportedAtSourcePath: false,
9396
+ willAdopt,
9397
+ willExportAtSourcePath
9398
+ });
9399
+ continue;
9400
+ }
9401
+ const uploadRes = yield* Effect7.gen(function* () {
9402
+ const createdPage = yield* notion.createSkillPage({
9403
+ libraryId,
9404
+ skillsDs: binding.skills_ds,
9405
+ name: skillName,
9406
+ description: (parsed.description ?? "").trim(),
9407
+ enabled: true,
9408
+ visibility: resolvedVisibility,
9409
+ kind,
9410
+ profiles,
9411
+ scenes,
9412
+ requiresIds: [],
9413
+ originSourceId: null,
9414
+ sourcePath: "",
9415
+ customMain: false,
9416
+ revision: makeRevisionStamp(),
9417
+ previewHash: "",
9418
+ markdownBody: rawMain
9419
+ });
9420
+ const uploadedIds = yield* Effect7.forEach(preparedSupporting, (sf) => notion.upsertFilePage({
9421
+ libraryId,
9422
+ filesDs: binding.files_ds,
9423
+ existingPageId: null,
9424
+ skillId: createdPage.id,
9425
+ path: sf.relPath,
9426
+ status: "override",
9427
+ externalUrl: "",
9428
+ sha256: sf.sha256,
9429
+ executable: sf.executable,
9430
+ textContent: sf.textContent
9431
+ }).pipe(Effect7.map((up) => up.pageId)), { concurrency: UPSTREAM_SKILL_CONCURRENCY2 });
9432
+ return { skillId: createdPage.id, fileIds: uploadedIds };
9433
+ }).pipe(Effect7.result);
9434
+ if (uploadRes._tag === "Failure") {
9435
+ const err = uploadRes.failure;
9436
+ failed.push({
9437
+ dir: absDir,
9438
+ name: skillName,
9439
+ visibility: resolvedVisibility,
9440
+ fileCount: scan.fileCount,
9441
+ totalBytes: scan.totalBytes,
9442
+ blocked: false,
9443
+ blockedFiles: [],
9444
+ conflict: err._tag === "ConflictError" && err.kind === "duplicate_name",
9445
+ code: err._tag,
9446
+ error: err.message
9447
+ });
9448
+ continue;
9449
+ }
9450
+ const { skillId, fileIds } = uploadRes.success;
9451
+ registerActiveSkill(skillId, skillName);
9452
+ createdSkillIds.push(skillId);
9453
+ createdFileIds.push(...fileIds);
9454
+ let adoptedSourceDir = false;
9455
+ if (willAdopt) {
9456
+ const trashRes = yield* trashPathEffect(absDir).pipe(Effect7.result);
9457
+ if (trashRes._tag === "Success") {
9458
+ adoptedSourceDir = true;
9459
+ }
9460
+ }
9461
+ created.push({
9462
+ dir: absDir,
9463
+ skillId,
9464
+ name: skillName,
9465
+ visibility: resolvedVisibility,
9466
+ kind,
9467
+ fileCount: scan.fileCount,
9468
+ uploadedFiles: fileIds.length,
9469
+ totalBytes: scan.totalBytes,
9470
+ blocked: false,
9471
+ blockedFiles: [],
9472
+ conflict: false,
9473
+ adoptedSourceDir,
9474
+ adoptedFromExportRoot: adoptedSourceDir && isInExportRoot,
9475
+ exportedAtSourcePath: false,
9476
+ willAdopt,
9477
+ willExportAtSourcePath
9478
+ });
9479
+ }
9480
+ let synced = false;
9481
+ if (!isDryRun && created.length > 0) {
9482
+ yield* syncCommand({
9483
+ libraryId,
9484
+ dedupeWindowMs: 0,
9485
+ readYourWrites: { skillIds: createdSkillIds, fileIds: createdFileIds }
9486
+ });
9487
+ synced = true;
9488
+ for (const item of created) {
9489
+ if (item.adoptedSourceDir && item.adoptedFromExportRoot) {
9490
+ item.exportedAtSourcePath = yield* Effect7.promise(() => isManagedExportAtPath(item.dir));
9491
+ }
9492
+ }
9493
+ }
9494
+ return {
9495
+ dryRun: isDryRun,
9496
+ created,
9497
+ skipped,
9498
+ failed,
9499
+ synced
9500
+ };
9501
+ });
9502
+ }
9503
+ function pushWorkdirsBatchCommand(args) {
9504
+ return Effect7.gen(function* () {
9505
+ const store = yield* StorePort;
9506
+ const explicitDirs = (args.dirs ?? []).map((d) => d.trim()).filter(Boolean);
9507
+ const isPending = Boolean(args.pending);
9508
+ const isDryRun = Boolean(args.dryRun);
9509
+ if (explicitDirs.length === 0 && !isPending) {
9510
+ return yield* Effect7.fail(new ConfigError({
9511
+ message: "Specify at least one edit workdir <dir...> or pass --pending to push all open workdirs."
9512
+ }));
9513
+ }
9514
+ const excludeSet = buildExcludeSet(args.exclude);
9515
+ const { libraryId: resolvedLibId } = yield* loadResolvedLibrary(args.libraryId);
9516
+ const skipped = [];
9517
+ const candidates = [];
9518
+ const seenAbsDirs = new Set;
9519
+ const inspectWorkdirMetaSkillName = async (dirPath) => {
9520
+ try {
9521
+ const raw = JSON.parse(await fsp8.readFile(nodePath8.join(dirPath, ".ntn-skill.json"), "utf8"));
9522
+ return raw?.skillName ? String(raw.skillName) : null;
9523
+ } catch {
9524
+ return null;
9525
+ }
9526
+ };
9527
+ for (const rawDir of explicitDirs) {
9528
+ const absDir = resolveHomePath(rawDir);
9529
+ if (seenAbsDirs.has(absDir))
9530
+ continue;
9531
+ seenAbsDirs.add(absDir);
9532
+ const hintSkillName = yield* Effect7.promise(() => inspectWorkdirMetaSkillName(absDir));
9533
+ if (matchesExclude(excludeSet, [nodePath8.basename(absDir), hintSkillName ?? undefined])) {
9534
+ skipped.push({ workdir: absDir, skillName: hintSkillName, reason: "excluded" });
9535
+ continue;
9536
+ }
9537
+ candidates.push({ dir: absDir, hintSkillName });
9538
+ }
9539
+ if (isPending) {
9540
+ const workEntries = yield* Effect7.promise(() => fsp8.readdir(store.paths.workRoot).catch(() => []));
9541
+ for (const name of workEntries.sort()) {
9542
+ if (name.startsWith("."))
9543
+ continue;
9544
+ const full = nodePath8.join(store.paths.workRoot, name);
9545
+ const rawMeta = yield* Effect7.promise(async () => {
9546
+ try {
9547
+ return JSON.parse(await fsp8.readFile(nodePath8.join(full, ".ntn-skill.json"), "utf8"));
9548
+ } catch {
9549
+ return null;
9550
+ }
9551
+ });
9552
+ if (!rawMeta)
9553
+ continue;
9554
+ if (rawMeta.libraryId && normalizeUuid(String(rawMeta.libraryId)) !== resolvedLibId) {
9555
+ continue;
9556
+ }
9557
+ if (seenAbsDirs.has(full))
9558
+ continue;
9559
+ seenAbsDirs.add(full);
9560
+ const skillName = rawMeta.skillName ? String(rawMeta.skillName) : name;
9561
+ if (matchesExclude(excludeSet, [name, skillName])) {
9562
+ skipped.push({ workdir: full, skillName, reason: "excluded" });
9563
+ continue;
9564
+ }
9565
+ candidates.push({ dir: full, hintSkillName: skillName });
9566
+ }
9567
+ }
9568
+ const pushedResults = [];
9569
+ const failed = [];
9570
+ for (const cand of candidates) {
9571
+ const res = yield* pushSingleWorkdirInternal({
9572
+ workdir: cand.dir,
9573
+ ...isDryRun ? { dryRun: true } : {},
9574
+ ...args.force ? { force: true } : {},
9575
+ deferSyncAndTrash: true
9576
+ }).pipe(Effect7.result);
9577
+ if (res._tag === "Failure") {
9578
+ const err = res.failure;
9579
+ const details = err._tag === "ConflictError" && err.details ? err.details : undefined;
9580
+ failed.push({
9581
+ workdir: cand.dir,
9582
+ skillName: cand.hintSkillName,
9583
+ code: err._tag === "ConflictError" ? err.kind : err._tag,
9584
+ error: err.message,
9585
+ ...details ? { details } : {}
9586
+ });
9587
+ continue;
9588
+ }
9589
+ pushedResults.push({
9590
+ internal: res.success,
9591
+ report: res.success.report
9592
+ });
9593
+ }
9594
+ let synced = false;
9595
+ if (!isDryRun && pushedResults.length > 0) {
9596
+ const rywByLib = new Map;
9597
+ for (const item of pushedResults) {
9598
+ if (!item.internal.wroteRemote)
9599
+ continue;
9600
+ const bucket = rywByLib.get(item.internal.libraryId) ?? {
9601
+ skillIds: new Set,
9602
+ fileIds: new Set,
9603
+ archivedFileIds: new Set
9604
+ };
9605
+ bucket.skillIds.add(item.internal.skillId);
9606
+ for (const fid of item.internal.touchedFileIds)
9607
+ bucket.fileIds.add(fid);
9608
+ for (const aid of item.internal.archivedFileIds)
9609
+ bucket.archivedFileIds.add(aid);
9610
+ rywByLib.set(item.internal.libraryId, bucket);
9611
+ }
9612
+ for (const [libId, bucket] of rywByLib) {
8361
9613
  yield* syncCommand({
8362
- libraryId,
9614
+ libraryId: libId,
8363
9615
  dedupeWindowMs: 0,
8364
9616
  readYourWrites: {
8365
- sourceIds: rywSourceIds,
8366
- skillIds: rywSkillIds,
8367
- archivedFileIds: rywArchivedFileIds
9617
+ skillIds: [...bucket.skillIds],
9618
+ fileIds: [...bucket.fileIds],
9619
+ archivedFileIds: [...bucket.archivedFileIds]
8368
9620
  }
8369
9621
  });
9622
+ synced = true;
8370
9623
  }
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
9624
+ for (const item of pushedResults) {
9625
+ if (item.internal.shouldTrash) {
9626
+ yield* trashPathEffect(item.report.workdir);
9627
+ item.report = { ...item.report, workdirCleaned: true };
9628
+ }
9629
+ }
9630
+ }
9631
+ return {
9632
+ dryRun: isDryRun,
9633
+ pushed: pushedResults.map((p) => p.report),
9634
+ skipped,
9635
+ failed,
9636
+ synced
9637
+ };
9638
+ });
9639
+ }
9640
+ function pushOverwriteDirectoryCommand(args) {
9641
+ return Effect7.gen(function* () {
9642
+ const notion = yield* NotionPort;
9643
+ const store = yield* StorePort;
9644
+ const upstream = yield* UpstreamPort;
9645
+ const absDir = resolveHomePath(args.dir);
9646
+ const isDryRun = Boolean(args.dryRun);
9647
+ const dirStat = yield* Effect7.tryPromise({
9648
+ try: () => fsp8.stat(absDir),
9649
+ catch: () => new NotFoundError({
9650
+ entity: "workdir",
9651
+ target: absDir,
9652
+ message: `Local skill directory not found: ${absDir}`
9653
+ })
9654
+ });
9655
+ if (!dirStat.isDirectory()) {
9656
+ return yield* Effect7.fail(new ConfigError({
9657
+ path: absDir,
9658
+ message: `Target path is not a directory: ${absDir}`
9659
+ }));
9660
+ }
9661
+ const existingMeta = yield* readWorkMeta(absDir).pipe(Effect7.catchTag("NotFoundError", () => Effect7.succeed(null)));
9662
+ if (existingMeta && args.toSkillName?.trim()) {
9663
+ const requested = args.toSkillName.trim();
9664
+ const metaName = existingMeta.skillName;
9665
+ const sameName = metaName.toLowerCase() === requested.toLowerCase() || normalizeSkillSlug(metaName) === normalizeSkillSlug(requested);
9666
+ if (!sameName) {
9667
+ return yield* Effect7.fail(new ConfigError({
9668
+ path: absDir,
9669
+ message: `Directory '${absDir}' is an edit workdir for '${metaName}', which does not match --to '${requested}'. Refusing to push to a different skill.`
9670
+ }));
9671
+ }
9672
+ }
9673
+ const scan = yield* Effect7.tryPromise({
9674
+ try: () => scanLocalSkillDirectory(absDir),
9675
+ catch: (e) => new StoreError({
9676
+ path: absDir,
9677
+ message: `Cannot read skill directory ${absDir}: ${String(e)}`
9678
+ })
9679
+ });
9680
+ const mainFile = scan.files.get("SKILL.md");
9681
+ if (!mainFile) {
9682
+ if (scan.blockedFiles.length > 0 && !isDryRun) {
9683
+ yield* assertNoBlockedSkillFiles(scan);
9684
+ }
9685
+ return yield* Effect7.fail(new ConfigError({
9686
+ path: absDir,
9687
+ message: `Missing SKILL.md in ${absDir}.`
9688
+ }));
9689
+ }
9690
+ const localRawMain = new TextDecoder().decode(mainFile.bytes);
9691
+ const parsedLocal = parseSkillFrontmatter(localRawMain);
9692
+ const targetQuery = (args.toSkillName?.trim() || parsedLocal.name?.trim() || "").trim();
9693
+ if (!targetQuery) {
9694
+ return yield* Effect7.fail(new ConfigError({
9695
+ path: absDir,
9696
+ message: `Cannot determine target skill name: SKILL.md frontmatter is missing 'name' and --to was not specified.`
9697
+ }));
9698
+ }
9699
+ const { libraryId, binding, libState } = yield* loadTableMetadataLibrary(args.libraryId);
9700
+ const activeSkills = Object.values(libState.skills).filter((s) => s.enabled);
9701
+ const queryLower = targetQuery.toLowerCase();
9702
+ const querySlug = normalizeSkillSlug(targetQuery);
9703
+ const exactMatches = activeSkills.filter((s) => s.name.toLowerCase() === queryLower);
9704
+ let targetSkill = exactMatches[0];
9705
+ if (!targetSkill && querySlug) {
9706
+ const slugMatches = activeSkills.filter((s) => normalizeSkillSlug(s.name) === querySlug);
9707
+ if (slugMatches.length > 1) {
9708
+ return yield* Effect7.fail(new ConflictError({
9709
+ kind: "duplicate_name",
9710
+ message: `Multiple active skills match slug '${querySlug}' (${slugMatches.map((s) => s.name).join(", ")}); specify the exact canonical name with --to.`
9711
+ }));
9712
+ }
9713
+ targetSkill = slugMatches[0];
9714
+ }
9715
+ if (!targetSkill) {
9716
+ return yield* Effect7.fail(new NotFoundError({
9717
+ entity: "skill",
9718
+ target: targetQuery,
9719
+ message: `Active skill '${targetQuery}' not found in Notion library ${libraryId}. Use 'ntn-skills new "${absDir}"' to create a new skill.`
9720
+ }));
9721
+ }
9722
+ if (scan.blockedFiles.length > 0) {
9723
+ if (!isDryRun) {
9724
+ yield* assertNoBlockedSkillFiles(scan);
9725
+ }
9726
+ return {
9727
+ dir: absDir,
9728
+ targetSkillId: targetSkill.id,
9729
+ targetSkillName: targetSkill.name,
9730
+ overwrite: true,
9731
+ dryRun: true,
9732
+ descriptionChanged: null,
9733
+ willSetCustomMain: false,
9734
+ updatedMain: false,
9735
+ updatedFiles: 0,
9736
+ items: [],
9737
+ newRevision: null,
9738
+ workdirCleaned: false,
9739
+ sourceDirPreserved: true,
9740
+ blocked: true,
9741
+ blockedFiles: scan.blockedFiles
8392
9742
  };
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
- })
9743
+ }
9744
+ const runOverwrite = Effect7.gen(function* () {
9745
+ const liveSkill = yield* notion.getSkillRecord(targetSkill.id);
9746
+ if (!liveSkill || !liveSkill.enabled) {
9747
+ return yield* Effect7.fail(new NotFoundError({
9748
+ entity: "skill",
9749
+ target: targetSkill.name,
9750
+ message: `Skill '${targetSkill.name}' is disabled or archived in Notion.`
9751
+ }));
9752
+ }
9753
+ const [liveFiles, liveBody] = yield* Effect7.all([
9754
+ notion.getSkillFiles({ filesDs: binding.files_ds, skillId: liveSkill.id }),
9755
+ notion.readSkillBody(liveSkill.id)
9756
+ ]);
9757
+ const src = liveSkill.originSourceId ? libState.sources[liveSkill.originSourceId] ?? null : null;
9758
+ const remoteEffectiveFiles = new Map;
9759
+ const upstreamShaByPath = new Map;
9760
+ const existingOverlayByPath = new Map;
9761
+ let upstreamMainMd = "";
9762
+ if (src) {
9763
+ const pinnedCommit = src.pinnedCommit || (yield* upstream.resolveHeadCommit(src.repoUrl, src.ref));
9764
+ const sub = yield* upstream.fetchSubtree({
9765
+ repoUrl: src.repoUrl,
9766
+ commitSha: pinnedCommit,
9767
+ sourcePath: liveSkill.sourcePath || "."
8401
9768
  });
9769
+ for (const f of sub) {
9770
+ if (f.path === "SKILL.md") {
9771
+ upstreamMainMd = new TextDecoder().decode(f.bytes);
9772
+ } else {
9773
+ const upSha = sha256Hex(f.bytes);
9774
+ upstreamShaByPath.set(f.path, upSha);
9775
+ remoteEffectiveFiles.set(f.path, {
9776
+ pageId: null,
9777
+ sha256: upSha,
9778
+ upstreamSha256: upSha,
9779
+ executable: f.executable,
9780
+ origin: "upstream",
9781
+ externalUrl: ""
9782
+ });
9783
+ }
9784
+ }
8402
9785
  }
8403
- return report;
9786
+ for (const ov of normalizeOverlayFiles(liveFiles)) {
9787
+ existingOverlayByPath.set(ov.path, ov);
9788
+ if (ov.status === "delete") {
9789
+ remoteEffectiveFiles.delete(ov.path);
9790
+ continue;
9791
+ }
9792
+ const bytes = yield* resolveOverlayBytes(ov);
9793
+ const exec = ov.executable || ov.path.toLowerCase().endsWith(".sh");
9794
+ const upSha = ov.baseSha256 ?? upstreamShaByPath.get(ov.path);
9795
+ remoteEffectiveFiles.set(ov.path, {
9796
+ pageId: ov.id,
9797
+ sha256: sha256Hex(bytes),
9798
+ ...upSha ? { upstreamSha256: upSha } : {},
9799
+ executable: exec,
9800
+ origin: src ? "override" : "native",
9801
+ externalUrl: ov.externalUrl
9802
+ });
9803
+ }
9804
+ const rawRemoteMain = !src || liveSkill.customMain ? liveBody.rawMarkdown : upstreamMainMd;
9805
+ const remoteAuthoritativeMain = applyAuthoritativeFrontmatter(rawRemoteMain, liveSkill.name, liveSkill.description);
9806
+ const nextDescription = parsedLocal.description !== undefined ? parsedLocal.description : liveSkill.description;
9807
+ const descriptionChanged = parsedLocal.description !== undefined && parsedLocal.description !== liveSkill.description ? { from: liveSkill.description, to: parsedLocal.description } : null;
9808
+ const localAuthoritativeMain = applyAuthoritativeFrontmatter(localRawMain, liveSkill.name, nextDescription);
9809
+ const localMainSha = sha256Hex(localAuthoritativeMain);
9810
+ const remoteMainSha = sha256Hex(remoteAuthoritativeMain);
9811
+ const updatedMain = localMainSha !== remoteMainSha;
9812
+ const willSetCustomMain = Boolean(liveSkill.originSourceId && updatedMain && !liveSkill.customMain);
9813
+ const items = [];
9814
+ if (updatedMain) {
9815
+ items.push({
9816
+ path: "SKILL.md",
9817
+ change: "modified",
9818
+ plannedAction: "update_skill_main",
9819
+ executable: false,
9820
+ sha256: localMainSha
9821
+ });
9822
+ }
9823
+ const allSubPaths = new Set([...remoteEffectiveFiles.keys(), ...scan.files.keys()]);
9824
+ allSubPaths.delete("SKILL.md");
9825
+ for (const relPath of [...allSubPaths].sort()) {
9826
+ const remote = remoteEffectiveFiles.get(relPath);
9827
+ const local = scan.files.get(relPath);
9828
+ if (!remote && local) {
9829
+ items.push({
9830
+ path: relPath,
9831
+ change: "added",
9832
+ plannedAction: "upsert_file_override",
9833
+ executable: local.executable,
9834
+ sha256: sha256Hex(local.bytes)
9835
+ });
9836
+ } else if (remote && !local) {
9837
+ const needsDeleteTombstone = Boolean(liveSkill.originSourceId && (upstreamShaByPath.has(relPath) || remote.origin === "upstream"));
9838
+ items.push({
9839
+ path: relPath,
9840
+ change: "deleted",
9841
+ plannedAction: needsDeleteTombstone ? "upsert_file_delete_overlay" : "archive_native_file",
9842
+ executable: false
9843
+ });
9844
+ } else if (remote && local) {
9845
+ const curSha = sha256Hex(local.bytes);
9846
+ if (curSha !== remote.sha256 || local.executable !== remote.executable) {
9847
+ items.push({
9848
+ path: relPath,
9849
+ change: "modified",
9850
+ plannedAction: "upsert_file_override",
9851
+ executable: local.executable,
9852
+ sha256: curSha
9853
+ });
9854
+ }
9855
+ }
9856
+ }
9857
+ const fileItemCount = items.filter((i) => i.path !== "SKILL.md").length;
9858
+ if (isDryRun) {
9859
+ return {
9860
+ dir: absDir,
9861
+ targetSkillId: liveSkill.id,
9862
+ targetSkillName: liveSkill.name,
9863
+ overwrite: true,
9864
+ dryRun: true,
9865
+ descriptionChanged,
9866
+ willSetCustomMain,
9867
+ updatedMain,
9868
+ updatedFiles: fileItemCount,
9869
+ items,
9870
+ newRevision: null,
9871
+ workdirCleaned: false,
9872
+ sourceDirPreserved: true,
9873
+ blocked: false,
9874
+ blockedFiles: []
9875
+ };
9876
+ }
9877
+ if (items.length === 0 && !descriptionChanged) {
9878
+ return {
9879
+ dir: absDir,
9880
+ targetSkillId: liveSkill.id,
9881
+ targetSkillName: liveSkill.name,
9882
+ overwrite: true,
9883
+ dryRun: false,
9884
+ descriptionChanged: null,
9885
+ willSetCustomMain: false,
9886
+ updatedMain: false,
9887
+ updatedFiles: 0,
9888
+ items: [],
9889
+ newRevision: null,
9890
+ workdirCleaned: false,
9891
+ sourceDirPreserved: true,
9892
+ blocked: false,
9893
+ blockedFiles: []
9894
+ };
9895
+ }
9896
+ const encodedSupporting = new Map;
9897
+ for (const item of items) {
9898
+ if (item.path === "SKILL.md" || item.plannedAction !== "upsert_file_override")
9899
+ continue;
9900
+ const localFile = scan.files.get(item.path);
9901
+ const textContent = yield* encodeSupportingFileEffect(localFile.bytes, item.path);
9902
+ encodedSupporting.set(item.path, {
9903
+ textContent,
9904
+ sha256: sha256Hex(localFile.bytes),
9905
+ file: localFile
9906
+ });
9907
+ }
9908
+ let updatedFilesCount = 0;
9909
+ const touchedFileIds = [];
9910
+ const archivedFileIds = [];
9911
+ for (const item of items) {
9912
+ if (item.path === "SKILL.md")
9913
+ continue;
9914
+ const existingOverlay = existingOverlayByPath.get(item.path);
9915
+ const remoteEntry = remoteEffectiveFiles.get(item.path);
9916
+ if (item.plannedAction === "archive_native_file") {
9917
+ const pageIdToArchive = remoteEntry?.pageId ?? existingOverlay?.id ?? null;
9918
+ if (pageIdToArchive) {
9919
+ yield* notion.archivePage({ libraryId, pageId: pageIdToArchive });
9920
+ archivedFileIds.push(pageIdToArchive);
9921
+ updatedFilesCount++;
9922
+ }
9923
+ continue;
9924
+ }
9925
+ if (item.plannedAction === "upsert_file_delete_overlay") {
9926
+ const delRes = yield* withRetryableReadback(notion.upsertFilePage({
9927
+ libraryId,
9928
+ filesDs: binding.files_ds,
9929
+ existingPageId: existingOverlay?.id ?? remoteEntry?.pageId ?? null,
9930
+ skillId: liveSkill.id,
9931
+ path: item.path,
9932
+ status: "delete",
9933
+ externalUrl: "",
9934
+ sha256: "",
9935
+ executable: false,
9936
+ textContent: ""
9937
+ }), () => notion.getSkillFiles({ filesDs: binding.files_ds, skillId: liveSkill.id }).pipe(Effect7.map((rf) => {
9938
+ const landed = rf.find((f) => f.path === item.path && f.status === "delete");
9939
+ return landed ? { pageId: landed.id } : null;
9940
+ })));
9941
+ touchedFileIds.push(delRes.pageId);
9942
+ updatedFilesCount++;
9943
+ continue;
9944
+ }
9945
+ const prepared = encodedSupporting.get(item.path);
9946
+ const baseSha256 = upstreamShaByPath.get(item.path) ?? remoteEntry?.upstreamSha256;
9947
+ const ovRes = yield* withRetryableReadback(notion.upsertFilePage({
9948
+ libraryId,
9949
+ filesDs: binding.files_ds,
9950
+ existingPageId: existingOverlay?.id ?? remoteEntry?.pageId ?? null,
9951
+ skillId: liveSkill.id,
9952
+ path: item.path,
9953
+ status: "override",
9954
+ externalUrl: "",
9955
+ sha256: prepared.sha256,
9956
+ ...baseSha256 ? { baseSha256 } : {},
9957
+ executable: prepared.file.executable,
9958
+ textContent: prepared.textContent
9959
+ }), () => Effect7.gen(function* () {
9960
+ const remoteFiles = yield* notion.getSkillFiles({
9961
+ filesDs: binding.files_ds,
9962
+ skillId: liveSkill.id
9963
+ });
9964
+ const candidate = remoteFiles.find((f) => f.path === item.path && f.status === "override");
9965
+ if (candidate && candidate.sha256 === prepared.sha256) {
9966
+ const remoteBody = yield* notion.readFileBody({
9967
+ filePageId: candidate.id,
9968
+ filePath: item.path
9969
+ });
9970
+ if (sha256Hex(decodeSupportingFilePayload(remoteBody)) === prepared.sha256) {
9971
+ return { pageId: candidate.id };
9972
+ }
9973
+ }
9974
+ return null;
9975
+ }));
9976
+ touchedFileIds.push(ovRes.pageId);
9977
+ updatedFilesCount++;
9978
+ }
9979
+ let nextPreviewHash;
9980
+ if (updatedMain) {
9981
+ const expectedPrepared = prepareSkillMarkdownForNotionBody(localRawMain).cleanNotionMarkdown;
9982
+ yield* withRetryableReadback(notion.writeSkillBody({
9983
+ libraryId,
9984
+ skillId: liveSkill.id,
9985
+ markdownBody: localRawMain,
9986
+ preserveUpstreamChild: Boolean(liveSkill.originSourceId)
9987
+ }), () => notion.readSkillBody(liveSkill.id).pipe(Effect7.map((rb) => rb.rawMarkdown.trim() === expectedPrepared.trim() ? { upstreamFilesPageId: rb.upstreamFilesPageId } : null)));
9988
+ if (liveSkill.originSourceId) {
9989
+ const afterBody = yield* notion.readSkillBody(liveSkill.id);
9990
+ nextPreviewHash = sha256Hex(afterBody.rawMarkdown);
9991
+ }
9992
+ }
9993
+ const preservedSubDigest = liveSkill.originSourceId ? extractSubtreeDigestFromRevision(liveSkill.revision) : null;
9994
+ const newRevision = makeRevisionStamp(preservedSubDigest);
9995
+ yield* notion.updateSkillProps({
9996
+ libraryId,
9997
+ skillId: liveSkill.id,
9998
+ ...descriptionChanged ? { description: descriptionChanged.to } : {},
9999
+ ...liveSkill.originSourceId && updatedMain ? { customMain: true } : {},
10000
+ ...nextPreviewHash !== undefined ? { previewHash: nextPreviewHash } : {},
10001
+ revision: newRevision
10002
+ });
10003
+ yield* syncCommand({
10004
+ libraryId,
10005
+ dedupeWindowMs: 0,
10006
+ readYourWrites: { skillIds: [liveSkill.id], fileIds: touchedFileIds, archivedFileIds }
10007
+ });
10008
+ return {
10009
+ dir: absDir,
10010
+ targetSkillId: liveSkill.id,
10011
+ targetSkillName: liveSkill.name,
10012
+ overwrite: true,
10013
+ dryRun: false,
10014
+ descriptionChanged,
10015
+ willSetCustomMain,
10016
+ updatedMain,
10017
+ updatedFiles: updatedFilesCount,
10018
+ items,
10019
+ newRevision,
10020
+ workdirCleaned: false,
10021
+ sourceDirPreserved: true,
10022
+ blocked: false,
10023
+ blockedFiles: []
10024
+ };
8404
10025
  });
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;
10026
+ return isDryRun ? yield* runOverwrite : yield* store.withExclusiveLock(`push-${libraryId.slice(0, 8)}`, runOverwrite);
8410
10027
  });
8411
10028
  }
8412
10029
  // packages/core/src/runtime/runtime.ts
@@ -8426,11 +10043,11 @@ function makeCoreLiveLayer(options) {
8426
10043
  }
8427
10044
  // packages/core/src/schedule/scheduler.ts
8428
10045
  import { spawn as spawn4 } from "node:child_process";
8429
- import * as fsp7 from "node:fs/promises";
10046
+ import * as fsp9 from "node:fs/promises";
8430
10047
  import * as os2 from "node:os";
8431
- import * as nodePath7 from "node:path";
10048
+ import * as nodePath9 from "node:path";
8432
10049
  import { fileURLToPath } from "node:url";
8433
- import { Effect as Effect6 } from "effect";
10050
+ import { Effect as Effect8 } from "effect";
8434
10051
  var DEFAULT_MAX_LOG_BYTES = 2 * 1024 * 1024;
8435
10052
  var LEGACY_DARWIN_LABELS = ["com.yoyo.ntn-skills-sync", "com.yoyo.ntn-skills-sync-full"];
8436
10053
  var MANAGED_UNITS = [
@@ -8453,7 +10070,7 @@ var MANAGED_UNITS = [
8453
10070
  function parseDurationSeconds(spec) {
8454
10071
  const m = spec.trim().toLowerCase().match(/^(\d+)\s*(s|m|h|d)?$/);
8455
10072
  if (!m) {
8456
- return Effect6.fail(new ConfigError({
10073
+ return Effect8.fail(new ConfigError({
8457
10074
  message: `Invalid duration '${spec}'. Expected formats like '12m', '1h', '90s', or '1d'.`
8458
10075
  }));
8459
10076
  }
@@ -8462,27 +10079,27 @@ function parseDurationSeconds(spec) {
8462
10079
  const mult = unit === "d" ? 86400 : unit === "h" ? 3600 : unit === "m" ? 60 : 1;
8463
10080
  const totalSec = value * mult;
8464
10081
  if (!Number.isSafeInteger(totalSec) || totalSec < 60) {
8465
- return Effect6.fail(new ConfigError({
10082
+ return Effect8.fail(new ConfigError({
8466
10083
  message: `Schedule interval '${spec}' (${totalSec}s) must be at least 60s.`
8467
10084
  }));
8468
10085
  }
8469
- return Effect6.succeed(totalSec);
10086
+ return Effect8.succeed(totalSec);
8470
10087
  }
8471
10088
  function parseDailyClock(spec) {
8472
10089
  const m = spec.trim().match(/^(\d{1,2}):(\d{2})$/);
8473
10090
  if (!m) {
8474
- return Effect6.fail(new ConfigError({
10091
+ return Effect8.fail(new ConfigError({
8475
10092
  message: `Invalid daily clock '${spec}'. Expected HH:MM (24-hour format, e.g. '04:12').`
8476
10093
  }));
8477
10094
  }
8478
10095
  const hour = Number(m[1]);
8479
10096
  const minute = Number(m[2]);
8480
10097
  if (hour < 0 || hour > 23 || minute < 0 || minute > 59) {
8481
- return Effect6.fail(new ConfigError({
10098
+ return Effect8.fail(new ConfigError({
8482
10099
  message: `Daily clock '${spec}' out of range (00:00..23:59).`
8483
10100
  }));
8484
10101
  }
8485
- return Effect6.succeed({
10102
+ return Effect8.succeed({
8486
10103
  hour,
8487
10104
  minute,
8488
10105
  normalized: `${String(hour).padStart(2, "0")}:${String(minute).padStart(2, "0")}`
@@ -8509,17 +10126,17 @@ function classifyErrorExitCode(err) {
8509
10126
  }
8510
10127
  }
8511
10128
  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);
10129
+ await fsp9.mkdir(nodePath9.dirname(logFile), { recursive: true });
10130
+ const st = await fsp9.stat(logFile).catch(() => null);
8514
10131
  if (st && st.size >= maxBytes) {
8515
- await fsp7.rename(logFile, `${logFile}.1`).catch(() => {
10132
+ await fsp9.rename(logFile, `${logFile}.1`).catch(() => {
8516
10133
  return;
8517
10134
  });
8518
10135
  }
8519
10136
  const normalized = line.endsWith(`
8520
10137
  `) ? line : `${line}
8521
10138
  `;
8522
- await fsp7.appendFile(logFile, normalized, "utf8");
10139
+ await fsp9.appendFile(logFile, normalized, "utf8");
8523
10140
  }
8524
10141
  function execSubprocess(bin, args, opts) {
8525
10142
  const timeoutMs = opts?.timeoutMs ?? 30000;
@@ -8559,18 +10176,18 @@ function execSubprocess(bin, args, opts) {
8559
10176
  });
8560
10177
  }
8561
10178
  function runScheduledJobCommand(args) {
8562
- return Effect6.gen(function* () {
10179
+ return Effect8.gen(function* () {
8563
10180
  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");
10181
+ const logsDir = nodePath9.join(store.paths.homeDir, "logs");
10182
+ const logFile = args.job === "upstream" ? nodePath9.join(logsDir, "upstream.log") : nodePath9.join(logsDir, "sync.log");
8566
10183
  const maxBytes = args.maxLogBytes ?? DEFAULT_MAX_LOG_BYTES;
8567
10184
  const startedMs = Date.now();
8568
10185
  const prevCaller = process.env.NTN_SKILLS_CALLER;
8569
10186
  process.env.NTN_SKILLS_CALLER = `schedule-${args.job}`;
8570
- yield* Effect6.promise(() => appendBoundedJobLog(logFile, `[${new Date(startedMs).toISOString()}] start job=${args.job}`, maxBytes).catch(() => {
10187
+ yield* Effect8.promise(() => appendBoundedJobLog(logFile, `[${new Date(startedMs).toISOString()}] start job=${args.job}`, maxBytes).catch(() => {
8571
10188
  return;
8572
10189
  }));
8573
- const outcome = yield* Effect6.gen(function* () {
10190
+ const outcome = yield* Effect8.gen(function* () {
8574
10191
  if (args.job === "sync") {
8575
10192
  const res = yield* syncCommand({
8576
10193
  ...args.libraryId ? { libraryId: args.libraryId } : {},
@@ -8606,7 +10223,7 @@ function runScheduledJobCommand(args) {
8606
10223
  summary
8607
10224
  };
8608
10225
  }
8609
- const reportFile = nodePath7.join(logsDir, "upstream-last-report.json");
10226
+ const reportFile = nodePath9.join(logsDir, "upstream-last-report.json");
8610
10227
  const rep = yield* upstreamCheckOrApplyCommand({
8611
10228
  apply: true,
8612
10229
  ...args.libraryId ? { libraryId: args.libraryId } : {},
@@ -8625,9 +10242,9 @@ function runScheduledJobCommand(args) {
8625
10242
  summary,
8626
10243
  upstreamReport: rep
8627
10244
  };
8628
- }).pipe(Effect6.catch((err) => {
10245
+ }).pipe(Effect8.catch((err) => {
8629
10246
  const code = classifyErrorExitCode(err);
8630
- return Effect6.succeed({
10247
+ return Effect8.succeed({
8631
10248
  job: args.job,
8632
10249
  ok: false,
8633
10250
  exitCode: code,
@@ -8641,44 +10258,44 @@ function runScheduledJobCommand(args) {
8641
10258
  } else {
8642
10259
  process.env.NTN_SKILLS_CALLER = prevCaller;
8643
10260
  }
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(() => {
10261
+ 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
10262
  return;
8646
10263
  }));
8647
10264
  return outcome;
8648
10265
  });
8649
10266
  }
8650
10267
  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}`)) {
10268
+ const norm = nodePath9.resolve(absPath);
10269
+ const normSafe = nodePath9.resolve(safeHomeDir);
10270
+ if (norm === normSafe || norm.startsWith(`${normSafe}${nodePath9.sep}`)) {
8654
10271
  return false;
8655
10272
  }
8656
10273
  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}`));
10274
+ const protectedRoots = ["Documents", "Desktop", "Downloads"].map((d) => nodePath9.join(home, d));
10275
+ return protectedRoots.some((r) => norm === r || norm.startsWith(`${r}${nodePath9.sep}`));
8659
10276
  }
8660
10277
  async function writeFileIfChanged(destPath, bytes, mode) {
8661
10278
  const buf = typeof bytes === "string" ? Buffer.from(bytes, "utf8") : Buffer.from(bytes);
8662
- const existing = await fsp7.readFile(destPath).catch(() => null);
10279
+ const existing = await fsp9.readFile(destPath).catch(() => null);
8663
10280
  if (existing && Buffer.compare(existing, buf) === 0) {
8664
10281
  if (mode !== undefined && process.platform !== "win32") {
8665
- const st = await fsp7.stat(destPath).catch(() => null);
10282
+ const st = await fsp9.stat(destPath).catch(() => null);
8666
10283
  if (st && (st.mode & 511) !== mode) {
8667
- await fsp7.chmod(destPath, mode);
10284
+ await fsp9.chmod(destPath, mode);
8668
10285
  }
8669
10286
  }
8670
10287
  return false;
8671
10288
  }
8672
- await fsp7.mkdir(nodePath7.dirname(destPath), { recursive: true });
8673
- await fsp7.writeFile(destPath, buf);
10289
+ await fsp9.mkdir(nodePath9.dirname(destPath), { recursive: true });
10290
+ await fsp9.writeFile(destPath, buf);
8674
10291
  if (mode !== undefined && process.platform !== "win32") {
8675
- await fsp7.chmod(destPath, mode);
10292
+ await fsp9.chmod(destPath, mode);
8676
10293
  }
8677
10294
  return true;
8678
10295
  }
8679
10296
  async function listRelativeFilesRecursive(rootDir, rel = "") {
8680
- const abs = rel ? nodePath7.join(rootDir, rel) : rootDir;
8681
- const entries = await fsp7.readdir(abs, { withFileTypes: true }).catch(() => []);
10297
+ const abs = rel ? nodePath9.join(rootDir, rel) : rootDir;
10298
+ const entries = await fsp9.readdir(abs, { withFileTypes: true }).catch(() => []);
8682
10299
  const out = [];
8683
10300
  for (const e of entries) {
8684
10301
  if (e.name === ".DS_Store" || e.name === "node_modules" || e.name === "dist")
@@ -8693,7 +10310,7 @@ async function listRelativeFilesRecursive(rootDir, rel = "") {
8693
10310
  return out;
8694
10311
  }
8695
10312
  async function syncReleaseSnapshotIdempotent(sourceRepoRoot, releaseRoot, bunBin) {
8696
- await fsp7.mkdir(releaseRoot, { recursive: true });
10313
+ await fsp9.mkdir(releaseRoot, { recursive: true });
8697
10314
  const staticFiles = [
8698
10315
  "package.json",
8699
10316
  "bun.lock",
@@ -8706,60 +10323,60 @@ async function syncReleaseSnapshotIdempotent(sourceRepoRoot, releaseRoot, bunBin
8706
10323
  "packages/pi-extension/tsconfig.json"
8707
10324
  ];
8708
10325
  for (const rel of staticFiles) {
8709
- const src = nodePath7.join(sourceRepoRoot, rel);
8710
- const bytes = await fsp7.readFile(src).catch(() => null);
10326
+ const src = nodePath9.join(sourceRepoRoot, rel);
10327
+ const bytes = await fsp9.readFile(src).catch(() => null);
8711
10328
  if (bytes) {
8712
- await writeFileIfChanged(nodePath7.join(releaseRoot, rel), bytes, 420);
10329
+ await writeFileIfChanged(nodePath9.join(releaseRoot, rel), bytes, 420);
8713
10330
  }
8714
10331
  }
8715
10332
  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");
10333
+ const srcDir = nodePath9.join(sourceRepoRoot, "packages", pkg, "src");
10334
+ const dstDir = nodePath9.join(releaseRoot, "packages", pkg, "src");
8718
10335
  const wantedRels = new Set(await listRelativeFilesRecursive(srcDir));
8719
10336
  for (const rel of wantedRels) {
8720
- const bytes = await fsp7.readFile(nodePath7.join(srcDir, rel));
8721
- await writeFileIfChanged(nodePath7.join(dstDir, rel), bytes, 420);
10337
+ const bytes = await fsp9.readFile(nodePath9.join(srcDir, rel));
10338
+ await writeFileIfChanged(nodePath9.join(dstDir, rel), bytes, 420);
8722
10339
  }
8723
10340
  const existingRels = await listRelativeFilesRecursive(dstDir);
8724
10341
  for (const rel of existingRels) {
8725
10342
  if (!wantedRels.has(rel)) {
8726
- await moveToSystemTrash(nodePath7.join(dstDir, rel)).catch(() => {
10343
+ await moveToSystemTrash(nodePath9.join(dstDir, rel)).catch(() => {
8727
10344
  return;
8728
10345
  });
8729
10346
  }
8730
10347
  }
8731
- const staleDist = nodePath7.join(releaseRoot, "packages", pkg, "dist");
8732
- if (await fsp7.stat(staleDist).then(() => true).catch(() => false)) {
10348
+ const staleDist = nodePath9.join(releaseRoot, "packages", pkg, "dist");
10349
+ if (await fsp9.stat(staleDist).then(() => true).catch(() => false)) {
8733
10350
  await moveToSystemTrash(staleDist).catch(() => {
8734
10351
  return;
8735
10352
  });
8736
10353
  }
8737
10354
  }
8738
- const srcSkillsDir = nodePath7.join(sourceRepoRoot, "skills");
8739
- const dstSkillsDir = nodePath7.join(releaseRoot, "skills");
10355
+ const srcSkillsDir = nodePath9.join(sourceRepoRoot, "skills");
10356
+ const dstSkillsDir = nodePath9.join(releaseRoot, "skills");
8740
10357
  const wantedSkillRels = new Set(await listRelativeFilesRecursive(srcSkillsDir));
8741
10358
  for (const rel of wantedSkillRels) {
8742
- const bytes = await fsp7.readFile(nodePath7.join(srcSkillsDir, rel));
8743
- await writeFileIfChanged(nodePath7.join(dstSkillsDir, rel), bytes, 420);
10359
+ const bytes = await fsp9.readFile(nodePath9.join(srcSkillsDir, rel));
10360
+ await writeFileIfChanged(nodePath9.join(dstSkillsDir, rel), bytes, 420);
8744
10361
  }
8745
10362
  for (const rel of await listRelativeFilesRecursive(dstSkillsDir)) {
8746
10363
  if (!wantedSkillRels.has(rel)) {
8747
- await moveToSystemTrash(nodePath7.join(dstSkillsDir, rel)).catch(() => {
10364
+ await moveToSystemTrash(nodePath9.join(dstSkillsDir, rel)).catch(() => {
8748
10365
  return;
8749
10366
  });
8750
10367
  }
8751
10368
  }
8752
- const staleScripts = nodePath7.join(releaseRoot, "scripts");
8753
- if (await fsp7.stat(staleScripts).then(() => true).catch(() => false)) {
10369
+ const staleScripts = nodePath9.join(releaseRoot, "scripts");
10370
+ if (await fsp9.stat(staleScripts).then(() => true).catch(() => false)) {
8754
10371
  await moveToSystemTrash(staleScripts).catch(() => {
8755
10372
  return;
8756
10373
  });
8757
10374
  }
8758
- const lockBytes = await fsp7.readFile(nodePath7.join(sourceRepoRoot, "bun.lock")).catch(() => null);
10375
+ const lockBytes = await fsp9.readFile(nodePath9.join(sourceRepoRoot, "bun.lock")).catch(() => null);
8759
10376
  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);
10377
+ const markerPath = nodePath9.join(releaseRoot, ".bun-lock.sha256");
10378
+ const prevSha = (await fsp9.readFile(markerPath, "utf8").catch(() => "")).trim();
10379
+ const hasNodeModules = await fsp9.stat(nodePath9.join(releaseRoot, "node_modules")).then((s) => s.isDirectory()).catch(() => false);
8763
10380
  if (!hasNodeModules || prevSha !== "" && prevSha !== lockSha) {
8764
10381
  const installRes = await execSubprocess(bunBin, ["install", "--frozen-lockfile", "--production"], {
8765
10382
  cwd: releaseRoot,
@@ -8770,10 +10387,10 @@ async function syncReleaseSnapshotIdempotent(sourceRepoRoot, releaseRoot, bunBin
8770
10387
  }
8771
10388
  }
8772
10389
  for (const relPeer of [
8773
- nodePath7.join(releaseRoot, "packages", "pi-extension", "node_modules", "typebox"),
8774
- nodePath7.join(releaseRoot, "node_modules", "typebox")
10390
+ nodePath9.join(releaseRoot, "packages", "pi-extension", "node_modules", "typebox"),
10391
+ nodePath9.join(releaseRoot, "node_modules", "typebox")
8775
10392
  ]) {
8776
- if (await fsp7.lstat(relPeer).then(() => true).catch(() => false)) {
10393
+ if (await fsp9.lstat(relPeer).then(() => true).catch(() => false)) {
8777
10394
  await moveToSystemTrash(relPeer).catch(() => {
8778
10395
  return;
8779
10396
  });
@@ -8851,11 +10468,11 @@ Persistent=true`;
8851
10468
  return { service, timer };
8852
10469
  }
8853
10470
  function resolveRepoRootFromModule() {
8854
- const here = nodePath7.dirname(fileURLToPath(import.meta.url));
8855
- return nodePath7.resolve(here, "../../../../");
10471
+ const here = nodePath9.dirname(fileURLToPath(import.meta.url));
10472
+ return nodePath9.resolve(here, "../../../../");
8856
10473
  }
8857
10474
  function installScheduleCommand(args) {
8858
- return Effect6.gen(function* () {
10475
+ return Effect8.gen(function* () {
8859
10476
  const store = yield* StorePort;
8860
10477
  const { libraryId } = yield* loadResolvedLibrary(args?.libraryId);
8861
10478
  const syncIntervalSec = yield* parseDurationSeconds(args?.syncEvery ?? "12m");
@@ -8863,12 +10480,12 @@ function installScheduleCommand(args) {
8863
10480
  const upstreamIntervalSec = args?.upstreamEvery ? yield* parseDurationSeconds(args.upstreamEvery) : null;
8864
10481
  const rawPlatform = args?.platformOverride ?? process.platform;
8865
10482
  if (rawPlatform !== "darwin" && rawPlatform !== "linux") {
8866
- return yield* Effect6.fail(new ConfigError({
10483
+ return yield* Effect8.fail(new ConfigError({
8867
10484
  message: `Unsupported OS platform '${rawPlatform}' for native schedule install. Use 'ntn-skills schedule export crontab' or 'dagu' instead.`
8868
10485
  }));
8869
10486
  }
8870
10487
  const platform = rawPlatform;
8871
- const credPath = yield* Effect6.tryPromise({
10488
+ const credPath = yield* Effect8.tryPromise({
8872
10489
  try: async () => {
8873
10490
  const stored = await readStoredCredentials(store.paths.configPath);
8874
10491
  const envNotion = (process.env.NOTION_TOKEN ?? process.env.NOTION_API_TOKEN ?? "").trim();
@@ -8895,9 +10512,9 @@ function installScheduleCommand(args) {
8895
10512
  const sourceRepoRoot = resolveRepoRootFromModule();
8896
10513
  const runtimeBin = process.execPath;
8897
10514
  const needReleaseCopy = platform === "darwin" && isMacOsTccProtectedPath(sourceRepoRoot, store.paths.homeDir);
8898
- const runtimeRoot = needReleaseCopy ? nodePath7.join(store.paths.homeDir, "release") : sourceRepoRoot;
10515
+ const runtimeRoot = needReleaseCopy ? nodePath9.join(store.paths.homeDir, "release") : sourceRepoRoot;
8899
10516
  if (needReleaseCopy) {
8900
- yield* Effect6.tryPromise({
10517
+ yield* Effect8.tryPromise({
8901
10518
  try: () => syncReleaseSnapshotIdempotent(sourceRepoRoot, runtimeRoot, runtimeBin),
8902
10519
  catch: (e) => new StoreError({
8903
10520
  path: runtimeRoot,
@@ -8905,10 +10522,10 @@ function installScheduleCommand(args) {
8905
10522
  })
8906
10523
  });
8907
10524
  }
8908
- const entryBinTs = nodePath7.join(runtimeRoot, "packages", "cli", "src", "bin.ts");
8909
- const wrapperPath = nodePath7.join(store.paths.homeDir, "bin", "ntn-skills");
10525
+ const entryBinTs = nodePath9.join(runtimeRoot, "packages", "cli", "src", "bin.ts");
10526
+ const wrapperPath = nodePath9.join(store.paths.homeDir, "bin", "ntn-skills");
8910
10527
  const binLinkPath = resolveHomePath(args?.binLinkPath ?? "~/.local/bin/ntn-skills");
8911
- yield* Effect6.tryPromise({
10528
+ yield* Effect8.tryPromise({
8912
10529
  try: async () => {
8913
10530
  const xdgLines = [
8914
10531
  ...process.env.XDG_DATA_HOME?.trim() ? [`export XDG_DATA_HOME="\${XDG_DATA_HOME:-${process.env.XDG_DATA_HOME.trim()}}"`] : [],
@@ -8926,16 +10543,16 @@ function installScheduleCommand(args) {
8926
10543
  ].join(`
8927
10544
  `);
8928
10545
  await writeFileIfChanged(wrapperPath, wrapperContent, 493);
8929
- await fsp7.mkdir(nodePath7.dirname(binLinkPath), { recursive: true });
8930
- const stLink = await fsp7.lstat(binLinkPath).catch(() => null);
10546
+ await fsp9.mkdir(nodePath9.dirname(binLinkPath), { recursive: true });
10547
+ const stLink = await fsp9.lstat(binLinkPath).catch(() => null);
8931
10548
  if (stLink) {
8932
- const curTarget = stLink.isSymbolicLink() ? await fsp7.readlink(binLinkPath).catch(() => "") : "";
8933
- if (nodePath7.resolve(nodePath7.dirname(binLinkPath), curTarget) !== wrapperPath) {
10549
+ const curTarget = stLink.isSymbolicLink() ? await fsp9.readlink(binLinkPath).catch(() => "") : "";
10550
+ if (nodePath9.resolve(nodePath9.dirname(binLinkPath), curTarget) !== wrapperPath) {
8934
10551
  await moveToSystemTrash(binLinkPath);
8935
- await fsp7.symlink(wrapperPath, binLinkPath);
10552
+ await fsp9.symlink(wrapperPath, binLinkPath);
8936
10553
  }
8937
10554
  } else {
8938
- await fsp7.symlink(wrapperPath, binLinkPath);
10555
+ await fsp9.symlink(wrapperPath, binLinkPath);
8939
10556
  }
8940
10557
  },
8941
10558
  catch: (e) => new StoreError({
@@ -8944,7 +10561,7 @@ function installScheduleCommand(args) {
8944
10561
  })
8945
10562
  });
8946
10563
  if (!args?.skipPreflight) {
8947
- const preflight = yield* Effect6.tryPromise({
10564
+ const preflight = yield* Effect8.tryPromise({
8948
10565
  try: () => {
8949
10566
  const cleanEnvArgs = [
8950
10567
  "-i",
@@ -8971,7 +10588,7 @@ function installScheduleCommand(args) {
8971
10588
  })
8972
10589
  });
8973
10590
  if (preflight.code !== 0) {
8974
- return yield* Effect6.fail(new AuthError({
10591
+ return yield* Effect8.fail(new AuthError({
8975
10592
  provider: "notion",
8976
10593
  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
10594
  }));
@@ -8980,18 +10597,18 @@ function installScheduleCommand(args) {
8980
10597
  const installedUnits = [];
8981
10598
  const retiredUnits = [];
8982
10599
  const libArgs = args?.libraryId ? ["--library", libraryId] : [];
8983
- const logsDir = nodePath7.join(store.paths.homeDir, "logs");
10600
+ const logsDir = nodePath9.join(store.paths.homeDir, "logs");
8984
10601
  if (platform === "darwin") {
8985
10602
  const agentsDir = resolveHomePath(args?.launchAgentsDir ?? "~/Library/LaunchAgents");
8986
- const errLogPath = nodePath7.join(logsDir, "launchd.err.log");
10603
+ const errLogPath = nodePath9.join(logsDir, "launchd.err.log");
8987
10604
  const uid = typeof process.getuid === "function" ? process.getuid() : 501;
8988
- yield* Effect6.tryPromise({
10605
+ yield* Effect8.tryPromise({
8989
10606
  try: async () => {
8990
- await fsp7.mkdir(agentsDir, { recursive: true });
8991
- await fsp7.mkdir(logsDir, { recursive: true });
10607
+ await fsp9.mkdir(agentsDir, { recursive: true });
10608
+ await fsp9.mkdir(logsDir, { recursive: true });
8992
10609
  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);
10610
+ const legacyPlist = nodePath9.join(agentsDir, `${legacyLabel}.plist`);
10611
+ const exists = await fsp9.stat(legacyPlist).then(() => true).catch(() => false);
8995
10612
  if (exists) {
8996
10613
  if (!args?.skipOsActivation) {
8997
10614
  await execSubprocess("launchctl", ["bootout", `gui/${uid}`, legacyPlist]).catch(() => {
@@ -9036,8 +10653,8 @@ function installScheduleCommand(args) {
9036
10653
  })
9037
10654
  });
9038
10655
  } else {
9039
- const optionalUpstreamPlist = nodePath7.join(agentsDir, "io.ntn-skills.upstream.plist");
9040
- if (await fsp7.stat(optionalUpstreamPlist).then(() => true).catch(() => false)) {
10656
+ const optionalUpstreamPlist = nodePath9.join(agentsDir, "io.ntn-skills.upstream.plist");
10657
+ if (await fsp9.stat(optionalUpstreamPlist).then(() => true).catch(() => false)) {
9041
10658
  if (!args?.skipOsActivation) {
9042
10659
  await execSubprocess("launchctl", [
9043
10660
  "bootout",
@@ -9052,7 +10669,7 @@ function installScheduleCommand(args) {
9052
10669
  }
9053
10670
  }
9054
10671
  for (const u of desiredDarwin) {
9055
- const plistPath = nodePath7.join(agentsDir, `${u.label}.plist`);
10672
+ const plistPath = nodePath9.join(agentsDir, `${u.label}.plist`);
9056
10673
  if (!args?.skipOsActivation) {
9057
10674
  await execSubprocess("launchctl", ["bootout", `gui/${uid}`, plistPath]).catch(() => {
9058
10675
  return;
@@ -9080,9 +10697,9 @@ function installScheduleCommand(args) {
9080
10697
  } else {
9081
10698
  const systemdDir = resolveHomePath(args?.systemdUserDir ?? "~/.config/systemd/user");
9082
10699
  const libSuffix = args?.libraryId ? ` --library ${libraryId}` : "";
9083
- yield* Effect6.tryPromise({
10700
+ yield* Effect8.tryPromise({
9084
10701
  try: async () => {
9085
- await fsp7.mkdir(systemdDir, { recursive: true });
10702
+ await fsp9.mkdir(systemdDir, { recursive: true });
9086
10703
  const unitsToWrite = [
9087
10704
  {
9088
10705
  base: "ntn-skills-sync",
@@ -9115,8 +10732,8 @@ function installScheduleCommand(args) {
9115
10732
  });
9116
10733
  } else {
9117
10734
  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)) {
10735
+ const p = nodePath9.join(systemdDir, `ntn-skills-upstream.${ext}`);
10736
+ if (await fsp9.stat(p).then(() => true).catch(() => false)) {
9120
10737
  if (!args?.skipOsActivation) {
9121
10738
  await execSubprocess("systemctl", [
9122
10739
  "--user",
@@ -9133,8 +10750,8 @@ function installScheduleCommand(args) {
9133
10750
  }
9134
10751
  }
9135
10752
  for (const u of unitsToWrite) {
9136
- const svcPath = nodePath7.join(systemdDir, `${u.base}.service`);
9137
- const tmrPath = nodePath7.join(systemdDir, `${u.base}.timer`);
10753
+ const svcPath = nodePath9.join(systemdDir, `${u.base}.service`);
10754
+ const tmrPath = nodePath9.join(systemdDir, `${u.base}.timer`);
9138
10755
  await writeFileIfChanged(svcPath, u.pair.service, 420);
9139
10756
  await writeFileIfChanged(tmrPath, u.pair.timer, 420);
9140
10757
  installedUnits.push(tmrPath);
@@ -9178,8 +10795,8 @@ function installScheduleCommand(args) {
9178
10795
  }
9179
10796
  async function readTailLine(filePath) {
9180
10797
  try {
9181
- const st = await fsp7.stat(filePath);
9182
- const raw = await fsp7.readFile(filePath, "utf8");
10798
+ const st = await fsp9.stat(filePath);
10799
+ const raw = await fsp9.readFile(filePath, "utf8");
9183
10800
  const lines = raw.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
9184
10801
  return { bytes: st.size, lastLine: lines.length > 0 ? lines[lines.length - 1] : null };
9185
10802
  } catch {
@@ -9187,23 +10804,23 @@ async function readTailLine(filePath) {
9187
10804
  }
9188
10805
  }
9189
10806
  function statusScheduleCommand(args) {
9190
- return Effect6.gen(function* () {
10807
+ return Effect8.gen(function* () {
9191
10808
  const store = yield* StorePort;
9192
10809
  const platform = args?.platformOverride ?? process.platform;
9193
- const wrapperPath = nodePath7.join(store.paths.homeDir, "bin", "ntn-skills");
10810
+ const wrapperPath = nodePath9.join(store.paths.homeDir, "bin", "ntn-skills");
9194
10811
  const binLinkPath = resolveHomePath(args?.binLinkPath ?? "~/.local/bin/ntn-skills");
9195
- return yield* Effect6.tryPromise({
10812
+ return yield* Effect8.tryPromise({
9196
10813
  try: async () => {
9197
- const wrapperExists = await fsp7.stat(wrapperPath).then((s) => s.isFile()).catch(() => false);
9198
- const binLinkTarget = await fsp7.readlink(binLinkPath).catch(() => null);
10814
+ const wrapperExists = await fsp9.stat(wrapperPath).then((s) => s.isFile()).catch(() => false);
10815
+ const binLinkTarget = await fsp9.readlink(binLinkPath).catch(() => null);
9199
10816
  const credentials = await inspectCredentialsStatus(store.paths.configPath);
9200
10817
  const units = [];
9201
10818
  if (platform === "darwin") {
9202
10819
  const agentsDir = resolveHomePath(args?.launchAgentsDir ?? "~/Library/LaunchAgents");
9203
10820
  const uid = typeof process.getuid === "function" ? process.getuid() : 501;
9204
10821
  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);
10822
+ const plistPath = nodePath9.join(agentsDir, `${u.darwinLabel}.plist`);
10823
+ const installed = await fsp9.stat(plistPath).then((s) => s.isFile()).catch(() => false);
9207
10824
  let active = false;
9208
10825
  if (installed && !args?.skipOsQuery) {
9209
10826
  const pr = await execSubprocess("launchctl", [
@@ -9224,8 +10841,8 @@ function statusScheduleCommand(args) {
9224
10841
  const systemdDir = resolveHomePath(args?.systemdUserDir ?? "~/.config/systemd/user");
9225
10842
  for (const u of MANAGED_UNITS) {
9226
10843
  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);
10844
+ const unitPath = nodePath9.join(systemdDir, timerName);
10845
+ const installed = await fsp9.stat(unitPath).then((s) => s.isFile()).catch(() => false);
9229
10846
  let active = false;
9230
10847
  if (installed && !args?.skipOsQuery) {
9231
10848
  const pr = await execSubprocess("systemctl", [
@@ -9244,16 +10861,16 @@ function statusScheduleCommand(args) {
9244
10861
  });
9245
10862
  }
9246
10863
  }
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");
10864
+ const logsDir = nodePath9.join(store.paths.homeDir, "logs");
10865
+ const syncLogPath = nodePath9.join(logsDir, "sync.log");
10866
+ const upstreamLogPath = nodePath9.join(logsDir, "upstream.log");
9250
10867
  const [syncTail, upstreamTail] = await Promise.all([
9251
10868
  readTailLine(syncLogPath),
9252
10869
  readTailLine(upstreamLogPath)
9253
10870
  ]);
9254
10871
  let lastUpstreamReport = null;
9255
10872
  try {
9256
- const rawRep = JSON.parse(await fsp7.readFile(nodePath7.join(logsDir, "upstream-last-report.json"), "utf8"));
10873
+ const rawRep = JSON.parse(await fsp9.readFile(nodePath9.join(logsDir, "upstream-last-report.json"), "utf8"));
9257
10874
  lastUpstreamReport = {
9258
10875
  finishedAt: rawRep.finishedAt,
9259
10876
  checked: rawRep.checked,
@@ -9286,18 +10903,18 @@ function statusScheduleCommand(args) {
9286
10903
  });
9287
10904
  }
9288
10905
  function uninstallScheduleCommand(args) {
9289
- return Effect6.gen(function* () {
10906
+ return Effect8.gen(function* () {
9290
10907
  const platform = args?.platformOverride ?? process.platform;
9291
10908
  const removedUnits = [];
9292
- yield* Effect6.tryPromise({
10909
+ yield* Effect8.tryPromise({
9293
10910
  try: async () => {
9294
10911
  if (platform === "darwin") {
9295
10912
  const agentsDir = resolveHomePath(args?.launchAgentsDir ?? "~/Library/LaunchAgents");
9296
10913
  const uid = typeof process.getuid === "function" ? process.getuid() : 501;
9297
10914
  const allLabels = [...MANAGED_UNITS.map((u) => u.darwinLabel), ...LEGACY_DARWIN_LABELS];
9298
10915
  for (const label of allLabels) {
9299
- const plistPath = nodePath7.join(agentsDir, `${label}.plist`);
9300
- const exists = await fsp7.stat(plistPath).then(() => true).catch(() => false);
10916
+ const plistPath = nodePath9.join(agentsDir, `${label}.plist`);
10917
+ const exists = await fsp9.stat(plistPath).then(() => true).catch(() => false);
9301
10918
  if (!exists)
9302
10919
  continue;
9303
10920
  if (!args?.skipOsActivation) {
@@ -9312,8 +10929,8 @@ function uninstallScheduleCommand(args) {
9312
10929
  const systemdDir = resolveHomePath(args?.systemdUserDir ?? "~/.config/systemd/user");
9313
10930
  for (const u of MANAGED_UNITS) {
9314
10931
  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);
10932
+ const p = nodePath9.join(systemdDir, `${u.systemdUnit}.${ext}`);
10933
+ const exists = await fsp9.stat(p).then(() => true).catch(() => false);
9317
10934
  if (!exists)
9318
10935
  continue;
9319
10936
  if (ext === "timer" && !args?.skipOsActivation) {
@@ -9352,7 +10969,7 @@ function durationSecToCronExpr(sec) {
9352
10969
  return "0 3 * * *";
9353
10970
  }
9354
10971
  function exportScheduleTemplateCommand(args) {
9355
- return Effect6.gen(function* () {
10972
+ return Effect8.gen(function* () {
9356
10973
  const { libraryId } = yield* loadResolvedLibrary(args.libraryId);
9357
10974
  const everySec = yield* parseDurationSeconds(args.every ?? "2h");
9358
10975
  const cronExpr = durationSecToCronExpr(everySec);
@@ -9443,14 +11060,14 @@ function exportScheduleTemplateCommand(args) {
9443
11060
  });
9444
11061
  }
9445
11062
  // packages/cli/src/main.ts
9446
- import { Console, Effect as Effect7, Layer as Layer5, Option as Option2 } from "effect";
11063
+ import { Console, Effect as Effect9, Layer as Layer5, Option as Option2 } from "effect";
9447
11064
  import { Argument, Command, Flag } from "effect/cli";
9448
11065
 
9449
11066
  // packages/cli/src/bundled-skill.ts
9450
11067
  import { createHash as createHash2, randomUUID as randomUUID6 } from "node:crypto";
9451
- import * as fsp8 from "node:fs/promises";
11068
+ import * as fsp10 from "node:fs/promises";
9452
11069
  import { createRequire } from "node:module";
9453
- import * as nodePath8 from "node:path";
11070
+ import * as nodePath10 from "node:path";
9454
11071
  import { fileURLToPath as fileURLToPath2 } from "node:url";
9455
11072
  var BUNDLED_SKILL_NAME = "ntn-skills";
9456
11073
  var cliRequire = createRequire(import.meta.url);
@@ -9466,7 +11083,7 @@ async function readBundledSkill() {
9466
11083
  ];
9467
11084
  for (const p of candidates) {
9468
11085
  try {
9469
- const markdown = await fsp8.readFile(p, "utf8");
11086
+ const markdown = await fsp10.readFile(p, "utf8");
9470
11087
  const sha256 = createHash2("sha256").update(markdown, "utf8").digest("hex");
9471
11088
  return {
9472
11089
  name: BUNDLED_SKILL_NAME,
@@ -9483,32 +11100,32 @@ async function readBundledSkill() {
9483
11100
  });
9484
11101
  }
9485
11102
  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);
11103
+ const revDir = nodePath10.join(storeRoot, "_bundled", BUNDLED_SKILL_NAME, payload.sha256);
11104
+ const mdFile = nodePath10.join(revDir, "SKILL.md");
11105
+ const existing = await fsp10.stat(mdFile).catch(() => null);
9489
11106
  if (existing?.isFile()) {
9490
11107
  return revDir;
9491
11108
  }
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, {
11109
+ const parentDir = nodePath10.dirname(revDir);
11110
+ await fsp10.mkdir(parentDir, { recursive: true });
11111
+ const stageDir = nodePath10.join(parentDir, `.tmp-bundled-${process.pid}-${randomUUID6().slice(0, 8)}`);
11112
+ await fsp10.mkdir(stageDir, { recursive: true });
11113
+ await fsp10.writeFile(nodePath10.join(stageDir, "SKILL.md"), payload.markdown, {
9497
11114
  encoding: "utf8",
9498
11115
  mode: 292
9499
11116
  });
9500
- await fsp8.writeFile(nodePath8.join(stageDir, ".ntn-manifest.json"), `${JSON.stringify({
11117
+ await fsp10.writeFile(nodePath10.join(stageDir, ".ntn-manifest.json"), `${JSON.stringify({
9501
11118
  skillId: BUNDLED_SKILL_NAME,
9502
11119
  effectiveRev: payload.sha256,
9503
11120
  publishedAt: new Date().toISOString(),
9504
11121
  bundled: true
9505
11122
  }, null, 2)}
9506
11123
  `, { encoding: "utf8", mode: 292 });
9507
- await fsp8.chmod(stageDir, 365);
11124
+ await fsp10.chmod(stageDir, 365);
9508
11125
  try {
9509
- await fsp8.rename(stageDir, revDir);
11126
+ await fsp10.rename(stageDir, revDir);
9510
11127
  } catch {
9511
- await fsp8.chmod(stageDir, 493).catch(() => {
11128
+ await fsp10.chmod(stageDir, 493).catch(() => {
9512
11129
  return;
9513
11130
  });
9514
11131
  await moveToSystemTrash(stageDir).catch(() => {
@@ -9520,21 +11137,21 @@ async function ensureBundledStoreDir(storeRoot, payload) {
9520
11137
  async function installBundledSkill(args) {
9521
11138
  const payload = await readBundledSkill();
9522
11139
  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));
11140
+ await fsp10.mkdir(destRoot, { recursive: true });
11141
+ const realStoreRoot = await fsp10.realpath(args.storeRoot).catch(() => nodePath10.resolve(args.storeRoot));
9525
11142
  const storePrefixes = Array.from(new Set([
9526
- `${nodePath8.resolve(args.storeRoot)}${nodePath8.sep}`,
9527
- `${realStoreRoot}${nodePath8.sep}`
11143
+ `${nodePath10.resolve(args.storeRoot)}${nodePath10.sep}`,
11144
+ `${realStoreRoot}${nodePath10.sep}`
9528
11145
  ]));
9529
11146
  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);
11147
+ const linkPath = nodePath10.join(destRoot, BUNDLED_SKILL_NAME);
11148
+ const lst = await fsp10.lstat(linkPath).catch(() => null);
9532
11149
  const bundledDir = await ensureBundledStoreDir(args.storeRoot, payload);
9533
11150
  if (lst) {
9534
11151
  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);
11152
+ const raw = await fsp10.readlink(linkPath);
11153
+ const resolved = nodePath10.resolve(destRoot, raw);
11154
+ const realResolved = await fsp10.realpath(resolved).catch(() => resolved);
9538
11155
  if (!isManagedStore(resolved) && !isManagedStore(realResolved)) {
9539
11156
  if (!args.force) {
9540
11157
  throw new ConflictError({
@@ -9544,7 +11161,7 @@ async function installBundledSkill(args) {
9544
11161
  }
9545
11162
  await moveToSystemTrash(linkPath);
9546
11163
  } else {
9547
- const isBundled = resolved.includes(`${nodePath8.sep}_bundled${nodePath8.sep}`) || realResolved.includes(`${nodePath8.sep}_bundled${nodePath8.sep}`);
11164
+ const isBundled = resolved.includes(`${nodePath10.sep}_bundled${nodePath10.sep}`) || realResolved.includes(`${nodePath10.sep}_bundled${nodePath10.sep}`);
9548
11165
  if (!isBundled && !args.force) {
9549
11166
  return {
9550
11167
  name: BUNDLED_SKILL_NAME,
@@ -9565,7 +11182,7 @@ async function installBundledSkill(args) {
9565
11182
  }
9566
11183
  }
9567
11184
  } 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);
11185
+ const marker = await fsp10.readFile(nodePath10.join(linkPath, ".ntn-managed-copy.json"), "utf8").then((raw) => JSON.parse(raw)).catch(() => null);
9569
11186
  if (marker && marker.skillId === BUNDLED_SKILL_NAME && marker.bundled === true) {
9570
11187
  if ((args.mode ?? "symlink") === "copy" && marker.effectiveRev === payload.sha256) {
9571
11188
  return {
@@ -9606,15 +11223,15 @@ async function installBundledSkill(args) {
9606
11223
  if (lst?.isSymbolicLink()) {
9607
11224
  await moveToSystemTrash(linkPath);
9608
11225
  }
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, {
11226
+ const stageCopy = nodePath10.join(destRoot, `.ntn-copy-${BUNDLED_SKILL_NAME}-${process.pid}-${randomUUID6().slice(0, 8)}`);
11227
+ await fsp10.mkdir(stageCopy, { recursive: true });
11228
+ await fsp10.writeFile(nodePath10.join(stageCopy, "SKILL.md"), payload.markdown, {
9612
11229
  encoding: "utf8",
9613
11230
  mode: 420
9614
11231
  });
9615
- await fsp8.writeFile(nodePath8.join(stageCopy, ".ntn-managed-copy.json"), `${JSON.stringify({ skillId: BUNDLED_SKILL_NAME, effectiveRev: payload.sha256, bundled: true }, null, 2)}
11232
+ await fsp10.writeFile(nodePath10.join(stageCopy, ".ntn-managed-copy.json"), `${JSON.stringify({ skillId: BUNDLED_SKILL_NAME, effectiveRev: payload.sha256, bundled: true }, null, 2)}
9616
11233
  `, "utf8");
9617
- await fsp8.rename(stageCopy, linkPath);
11234
+ await fsp10.rename(stageCopy, linkPath);
9618
11235
  return {
9619
11236
  name: BUNDLED_SKILL_NAME,
9620
11237
  status: "installed",
@@ -9623,9 +11240,9 @@ async function installBundledSkill(args) {
9623
11240
  sha256: payload.sha256
9624
11241
  };
9625
11242
  }
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);
11243
+ const tmpLink = nodePath10.join(destRoot, `.ntn-link-${BUNDLED_SKILL_NAME}-${process.pid}-${randomUUID6().slice(0, 8)}`);
11244
+ await fsp10.symlink(bundledDir, tmpLink);
11245
+ await fsp10.rename(tmpLink, linkPath);
9629
11246
  return {
9630
11247
  name: BUNDLED_SKILL_NAME,
9631
11248
  status: "installed",
@@ -9636,22 +11253,22 @@ async function installBundledSkill(args) {
9636
11253
  }
9637
11254
  async function uninstallBundledSkill(args) {
9638
11255
  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);
11256
+ const linkPath = nodePath10.join(destRoot, BUNDLED_SKILL_NAME);
11257
+ const lst = await fsp10.lstat(linkPath).catch(() => null);
9641
11258
  if (!lst) {
9642
11259
  return { name: BUNDLED_SKILL_NAME, status: "not_installed", linkPath };
9643
11260
  }
9644
11261
  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}`)) {
11262
+ const raw = await fsp10.readlink(linkPath);
11263
+ const resolved = nodePath10.resolve(destRoot, raw);
11264
+ if (resolved.includes(`${nodePath10.sep}_bundled${nodePath10.sep}`)) {
9648
11265
  await moveToSystemTrash(linkPath);
9649
11266
  return { name: BUNDLED_SKILL_NAME, status: "removed", linkPath };
9650
11267
  }
9651
- const realStoreRoot = await fsp8.realpath(args.storeRoot).catch(() => nodePath8.resolve(args.storeRoot));
11268
+ const realStoreRoot = await fsp10.realpath(args.storeRoot).catch(() => nodePath10.resolve(args.storeRoot));
9652
11269
  const storePrefixes = [
9653
- `${nodePath8.resolve(args.storeRoot)}${nodePath8.sep}`,
9654
- `${realStoreRoot}${nodePath8.sep}`
11270
+ `${nodePath10.resolve(args.storeRoot)}${nodePath10.sep}`,
11271
+ `${realStoreRoot}${nodePath10.sep}`
9655
11272
  ];
9656
11273
  if (storePrefixes.some((p) => resolved.startsWith(p))) {
9657
11274
  return { name: BUNDLED_SKILL_NAME, status: "managed_by_library", linkPath };
@@ -10076,12 +11693,12 @@ var initCmd = Command.make("init", {
10076
11693
  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
11694
  noSync: Flag.Boolean("no-sync").pipe(Flag.withDescription("Skip running initial full sync after writing config.json"), Flag.withDefault(false)),
10078
11695
  json: jsonFlag
10079
- }, (cfg) => Effect7.gen(function* () {
11696
+ }, (cfg) => Effect9.gen(function* () {
10080
11697
  const storeForInit = yield* StorePort;
10081
- const existingCfg = yield* storeForInit.readConfig().pipe(Effect7.catchTag("ConfigError", () => Effect7.succeed(null)));
11698
+ const existingCfg = yield* storeForInit.readConfig().pipe(Effect9.catchTag("ConfigError", () => Effect9.succeed(null)));
10082
11699
  const rootArg = Option2.getOrUndefined(cfg.root)?.trim() || process.env.NTN_SKILLS_LIBRARY?.trim() || existingCfg?.default_library?.trim() || "";
10083
11700
  if (!rootArg) {
10084
- return yield* Effect7.fail(new ConfigError({
11701
+ return yield* Effect9.fail(new ConfigError({
10085
11702
  message: `Missing Notion root page. Pass --root <notion-page-url> or set default_library in ${storeForInit.paths.configPath}.`
10086
11703
  }));
10087
11704
  }
@@ -10107,7 +11724,7 @@ var initCmd = Command.make("init", {
10107
11724
  libraryId: res.libraryId,
10108
11725
  full: true,
10109
11726
  dedupeWindowMs: 0
10110
- }).pipe(Effect7.result);
11727
+ }).pipe(Effect9.result);
10111
11728
  if (firstSync._tag === "Success") {
10112
11729
  syncedSummary = {
10113
11730
  catalogCount: firstSync.success.catalogCount,
@@ -10124,11 +11741,11 @@ var initCmd = Command.make("init", {
10124
11741
  if (!cfg.noSeedSelf && res.exports.length > 0) {
10125
11742
  const store = yield* StorePort;
10126
11743
  for (const exp of res.exports) {
10127
- const linkRes = yield* Effect7.tryPromise(() => installBundledSkill({
11744
+ const linkRes = yield* Effect9.tryPromise(() => installBundledSkill({
10128
11745
  destDir: exp.dir,
10129
11746
  storeRoot: store.paths.storeRoot,
10130
11747
  mode: exp.mode
10131
- })).pipe(Effect7.result);
11748
+ })).pipe(Effect9.result);
10132
11749
  if (linkRes._tag === "Success") {
10133
11750
  seededSelf = true;
10134
11751
  }
@@ -10160,10 +11777,10 @@ var initCmd = Command.make("init", {
10160
11777
  var doctorCmd = Command.make("doctor", {
10161
11778
  library: libraryFlag,
10162
11779
  json: jsonFlag
10163
- }, (cfg) => Effect7.gen(function* () {
11780
+ }, (cfg) => Effect9.gen(function* () {
10164
11781
  const libOpt = Option2.getOrUndefined(cfg.library);
10165
11782
  const report = yield* doctorCommand({ ...libOpt ? { libraryId: libOpt } : {} });
10166
- const sched = yield* statusScheduleCommand().pipe(Effect7.catch(() => Effect7.succeed(null)));
11783
+ const sched = yield* statusScheduleCommand().pipe(Effect9.catch(() => Effect9.succeed(null)));
10167
11784
  const syncActive = Boolean(sched?.units.some((u) => u.job === "sync" && u.active));
10168
11785
  const checks = [
10169
11786
  ...report.checks,
@@ -10192,15 +11809,17 @@ var doctorCmd = Command.make("doctor", {
10192
11809
  })).pipe(Command.withDescription("Diagnose credentials, Notion 3-table connectivity, exports, and background sync"));
10193
11810
  var syncCmd = Command.make("sync", {
10194
11811
  full: Flag.Boolean("full").pipe(Flag.withDescription("Run full reconciliation instead of overlap-window delta"), Flag.withDefault(false)),
11812
+ 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
11813
  coalesce: Flag.Boolean("coalesce").pipe(Flag.withDescription("Coalesce if synced within the last 5s (for background cron/hooks)"), Flag.withDefault(false)),
10196
11814
  library: libraryFlag,
10197
11815
  json: jsonFlag
10198
- }, (cfg) => Effect7.gen(function* () {
11816
+ }, (cfg) => Effect9.gen(function* () {
10199
11817
  const libOpt = Option2.getOrUndefined(cfg.library);
10200
11818
  const res = yield* syncCommand({
10201
11819
  ...libOpt ? { libraryId: libOpt } : {},
10202
11820
  full: cfg.full,
10203
- dedupeWindowMs: cfg.full || !cfg.coalesce ? 0 : 5000
11821
+ dryRun: cfg.dryRun,
11822
+ dedupeWindowMs: cfg.dryRun || cfg.full || !cfg.coalesce ? 0 : 5000
10204
11823
  });
10205
11824
  const fmtList = (items, max = 6) => items.length <= max ? items.join(", ") : `${items.slice(0, max).join(", ")}, ... (+${items.length - max} more)`;
10206
11825
  const formatSyncHuman = (r) => {
@@ -10219,28 +11838,41 @@ var syncCmd = Command.make("sync", {
10219
11838
  }
10220
11839
  const pulledLine = diffParts.length === 0 ? "up to date (0 skill changes)" : diffParts.join("; ");
10221
11840
  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}`;
11841
+ 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
11842
  const lp = r.localPending;
10224
11843
  const pendingLines = [];
10225
11844
  if (lp.openWorkdirs.length > 0) {
10226
11845
  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'`);
11846
+ pendingLines.push(` - ${lp.openWorkdirs.length} unpushed edit workdir(s): ${wList} -> run 'ntn-skills push --pending' (or 'push <workdir>' / 'abort')`);
10228
11847
  }
10229
11848
  if (lp.unmanagedLocalSkills.length > 0) {
10230
11849
  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)`);
11850
+ 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
11851
  }
10233
11852
  if (lp.uninitializedSources.length > 0) {
10234
11853
  pendingLines.push(` - ${lp.uninitializedSources.length} uninitialized Notion source(s): ${fmtList(lp.uninitializedSources)} -> run 'ntn-skills upstream apply <source>'`);
10235
11854
  }
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:
11855
+ 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"})`;
11856
+ const lines = [header, ` Pulled: ${pulledLine}`, ` Catalog: ${catalogLine}`];
11857
+ if (r.dryRun && r.plannedMaterializations && r.plannedMaterializations.length > 0) {
11858
+ lines.push(` Materialize: ${fmtList(r.plannedMaterializations, 10)}`);
11859
+ }
11860
+ if (r.dryRun && r.plannedExports && r.plannedExports.length > 0) {
11861
+ lines.push(" Planned Exports:");
11862
+ for (const pe of r.plannedExports) {
11863
+ const parts = [
11864
+ `total=${pe.totalSkills}`,
11865
+ `write=${pe.wouldWrite.length}${pe.wouldWrite.length > 0 ? ` (${fmtList(pe.wouldWrite)})` : ""}`,
11866
+ `remove=${pe.wouldRemove.length}${pe.wouldRemove.length > 0 ? ` (${fmtList(pe.wouldRemove)})` : ""}`,
11867
+ `conflicts=${pe.wouldSkipConflicts.length}`,
11868
+ `router=${pe.routerIncluded ? pe.routerSkill ?? "skill-catalog" : "none"}`
11869
+ ];
11870
+ lines.push(` - ${pe.dest} [${pe.mode}]: ${parts.join(", ")}`);
11871
+ }
11872
+ }
11873
+ lines.push(pendingLines.length === 0 ? " Local Pending: clean (0 unpushed workdirs, 0 unmanaged local skills)" : ` Local Pending:
10241
11874
  ${pendingLines.join(`
10242
- `)}`
10243
- ];
11875
+ `)}`);
10244
11876
  if (r.warnings.length > 0) {
10245
11877
  lines.push(` Warnings:
10246
11878
  ${r.warnings.map((w) => ` - ${w}`).join(`
@@ -10258,7 +11890,7 @@ var findCmd = Command.make("find", {
10258
11890
  kind: Flag.Literals("kind", ["skill", "router", "prompt"]).pipe(Flag.withDescription("Filter by Kind (skill | router | prompt)"), Flag.optional),
10259
11891
  library: libraryFlag,
10260
11892
  json: jsonFlag
10261
- }, (cfg) => Effect7.gen(function* () {
11893
+ }, (cfg) => Effect9.gen(function* () {
10262
11894
  const q = Option2.getOrUndefined(cfg.query);
10263
11895
  const sc = Option2.getOrUndefined(cfg.scene);
10264
11896
  const vis = Option2.getOrUndefined(cfg.visibility);
@@ -10284,7 +11916,7 @@ var loadCmd = Command.make("load", {
10284
11916
  pathOnly: Flag.Boolean("path-only").pipe(Flag.withDefault(false)),
10285
11917
  library: libraryFlag,
10286
11918
  json: jsonFlag
10287
- }, (cfg) => Effect7.gen(function* () {
11919
+ }, (cfg) => Effect9.gen(function* () {
10288
11920
  const lib = Option2.getOrUndefined(cfg.library);
10289
11921
  const res = yield* loadSkillCommand({
10290
11922
  name: cfg.name,
@@ -10306,7 +11938,7 @@ var infoCmd = Command.make("info", {
10306
11938
  name: Argument.String("name"),
10307
11939
  library: libraryFlag,
10308
11940
  json: jsonFlag
10309
- }, (cfg) => Effect7.gen(function* () {
11941
+ }, (cfg) => Effect9.gen(function* () {
10310
11942
  const lib = Option2.getOrUndefined(cfg.library);
10311
11943
  const items = yield* findSkillsCommand({
10312
11944
  query: cfg.name,
@@ -10340,7 +11972,7 @@ var statusCmd = Command.make("status", {
10340
11972
  days: Flag.Int("days").pipe(Flag.withDescription("Lookback window in days for local on-demand load frequency"), Flag.withDefault(30)),
10341
11973
  library: libraryFlag,
10342
11974
  json: jsonFlag
10343
- }, (cfg) => Effect7.gen(function* () {
11975
+ }, (cfg) => Effect9.gen(function* () {
10344
11976
  const lib = Option2.getOrUndefined(cfg.library);
10345
11977
  const rep = yield* statusCommand({
10346
11978
  days: cfg.days,
@@ -10369,11 +12001,12 @@ var exportCmd = Command.make("export", {
10369
12001
  scene: Flag.String("scene").pipe(Flag.optional),
10370
12002
  mode: Flag.Literals("mode", ["symlink", "copy"]).pipe(Flag.optional),
10371
12003
  includeNonDefault: Flag.Boolean("include-non-default").pipe(Flag.withDefault(false)),
12004
+ dryRun: Flag.Boolean("dry-run").pipe(Flag.withDescription("Preview planned exports, removals, and conflicts without touching disk"), Flag.withDefault(false)),
10372
12005
  library: libraryFlag,
10373
12006
  json: jsonFlag
10374
- }, (cfg) => Effect7.gen(function* () {
12007
+ }, (cfg) => Effect9.gen(function* () {
10375
12008
  if (cfg.withRequires && cfg.noRequires) {
10376
- return yield* Effect7.fail(new ConfigError({
12009
+ return yield* Effect9.fail(new ConfigError({
10377
12010
  message: "Cannot combine --with-requires and --no-requires."
10378
12011
  }));
10379
12012
  }
@@ -10397,9 +12030,18 @@ var exportCmd = Command.make("export", {
10397
12030
  ...sc ? { scene: sc } : {},
10398
12031
  ...md ? { mode: md } : {},
10399
12032
  ...cfg.includeNonDefault ? { includeNonDefault: true } : {},
12033
+ ...cfg.dryRun ? { dryRun: true } : {},
10400
12034
  ...lib ? { libraryId: lib } : {}
10401
12035
  });
10402
- const lines = [
12036
+ const lines = res.dryRun ? [
12037
+ `[dry-run] Export preview across ${res.targets.length} target(s) — no local files were modified:`,
12038
+ ...res.targets.map((t) => {
12039
+ const ww = t.wouldWrite ?? [];
12040
+ const wr = t.wouldRemove ?? [];
12041
+ const wc = t.wouldSkipConflicts ?? [];
12042
+ 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"}`;
12043
+ })
12044
+ ] : [
10403
12045
  `Exported ${res.exportedDirs.length} skill(s):`,
10404
12046
  ...res.exportedDirs.map((d) => ` ${d}`)
10405
12047
  ];
@@ -10416,7 +12058,7 @@ var editCmd = Command.make("edit", {
10416
12058
  name: Argument.String("name"),
10417
12059
  library: libraryFlag,
10418
12060
  json: jsonFlag
10419
- }, (cfg) => Effect7.gen(function* () {
12061
+ }, (cfg) => Effect9.gen(function* () {
10420
12062
  const lib = Option2.getOrUndefined(cfg.library);
10421
12063
  const res = yield* editOrPullSkillCommand({
10422
12064
  name: cfg.name,
@@ -10430,7 +12072,7 @@ var pullCmd = Command.make("pull", {
10430
12072
  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
12073
  library: libraryFlag,
10432
12074
  json: jsonFlag
10433
- }, (cfg) => Effect7.gen(function* () {
12075
+ }, (cfg) => Effect9.gen(function* () {
10434
12076
  const targetDir = Option2.getOrUndefined(cfg.dir);
10435
12077
  const lib = Option2.getOrUndefined(cfg.library);
10436
12078
  const res = yield* editOrPullSkillCommand({
@@ -10445,7 +12087,7 @@ var diffCmd = Command.make("diff", {
10445
12087
  workdir: Argument.String("workdir"),
10446
12088
  remote: Flag.Boolean("remote").pipe(Flag.withDefault(false)),
10447
12089
  json: jsonFlag
10448
- }, (cfg) => Effect7.gen(function* () {
12090
+ }, (cfg) => Effect9.gen(function* () {
10449
12091
  const res = yield* diffWorkdirCommand({ workdir: cfg.workdir, remote: cfg.remote });
10450
12092
  const lines = [`Workdir: ${res.workdir} (skill: ${res.skillName})`];
10451
12093
  if (res.descriptionChanged) {
@@ -10467,26 +12109,107 @@ ${(res.remoteDriftDetails ?? []).map((d) => ` - ${d}`).join(`
10467
12109
  `));
10468
12110
  })).pipe(Command.withDescription("Show local modifications, planned Notion overlay actions, and optional remote drift"));
10469
12111
  var pushCmd = Command.make("push", {
10470
- workdir: Argument.String("workdir"),
12112
+ dirs: Argument.String("dir").pipe(Argument.atLeast(0)),
12113
+ pending: Flag.Boolean("pending").pipe(Flag.withDescription("Push all open edit workdirs belonging to the target library"), Flag.withDefault(false)),
12114
+ exclude: Flag.String("exclude").pipe(Flag.withDescription("Workdirs or skill names to exclude (comma-separated or repeatable)"), Flag.atLeast(0)),
12115
+ to: Flag.String("to").pipe(Flag.withDescription("Target existing Notion skill name when directly overwriting from a plain local directory"), Flag.optional),
12116
+ 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
12117
  dryRun: Flag.Boolean("dry-run").pipe(Flag.withDefault(false)),
10472
12118
  force: Flag.Boolean("force").pipe(Flag.withDefault(false)),
12119
+ library: libraryFlag,
10473
12120
  json: jsonFlag
10474
- }, (cfg) => Effect7.gen(function* () {
10475
- const res = yield* pushWorkdirCommand({
10476
- workdir: cfg.workdir,
12121
+ }, (cfg) => Effect9.gen(function* () {
12122
+ const toOpt = Option2.getOrUndefined(cfg.to)?.trim() || undefined;
12123
+ const libOpt = Option2.getOrUndefined(cfg.library);
12124
+ const excludeList = splitMulti(cfg.exclude);
12125
+ const isOverwriteMode = Boolean(cfg.overwrite || toOpt);
12126
+ if (isOverwriteMode) {
12127
+ if (cfg.pending || cfg.dirs.length !== 1) {
12128
+ return yield* Effect9.fail(new ConfigError({
12129
+ message: "--overwrite / --to accepts exactly one explicit local directory <dir> and cannot be combined with --pending or multiple directories."
12130
+ }));
12131
+ }
12132
+ if (excludeList.length > 0) {
12133
+ return yield* Effect9.fail(new ConfigError({
12134
+ message: "Cannot combine --exclude with --overwrite / --to."
12135
+ }));
12136
+ }
12137
+ const res = yield* pushOverwriteDirectoryCommand({
12138
+ dir: cfg.dirs[0],
12139
+ ...toOpt ? { toSkillName: toOpt } : {},
12140
+ dryRun: cfg.dryRun,
12141
+ ...libOpt ? { libraryId: libOpt } : {}
12142
+ });
12143
+ const lines = [];
12144
+ if (res.blocked) {
12145
+ lines.push(`[dry-run] BLOCKED overwrite push for '${res.targetSkillName}' (${res.dir}): sensitive or unsafe file(s) detected:`);
12146
+ for (const bf of res.blockedFiles) {
12147
+ lines.push(` - ${bf.path} (${bf.reason})`);
12148
+ }
12149
+ } else if (res.dryRun) {
12150
+ 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)`);
12151
+ if (res.descriptionChanged) {
12152
+ lines.push(` Description: '${res.descriptionChanged.from}' -> '${res.descriptionChanged.to}'`);
12153
+ }
12154
+ for (const it of res.items) {
12155
+ lines.push(` [${it.change}] ${it.path} -> ${it.plannedAction}`);
12156
+ }
12157
+ if (res.items.length === 0 && !res.descriptionChanged) {
12158
+ lines.push(" (no differences against remote skill)");
12159
+ }
12160
+ } else {
12161
+ lines.push(`Overwrote '${res.targetSkillName}' (${res.targetSkillId}) from ${res.dir} (files=${res.updatedFiles}, main=${res.updatedMain}, rev=${res.newRevision ?? "none"}, sourceDirPreserved=true)`);
12162
+ }
12163
+ yield* printOut(cfg.json, res, lines.join(`
12164
+ `));
12165
+ if (res.blocked) {
12166
+ process.exitCode = 2;
12167
+ }
12168
+ return;
12169
+ }
12170
+ if (!cfg.pending && cfg.dirs.length === 1 && excludeList.length === 0) {
12171
+ const res = yield* pushWorkdirCommand({
12172
+ workdir: cfg.dirs[0],
12173
+ dryRun: cfg.dryRun,
12174
+ force: cfg.force
12175
+ });
12176
+ 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})`);
12177
+ return;
12178
+ }
12179
+ const res = yield* pushWorkdirsBatchCommand({
12180
+ dirs: cfg.dirs,
12181
+ pending: cfg.pending,
12182
+ exclude: excludeList,
10477
12183
  dryRun: cfg.dryRun,
10478
- force: cfg.force
12184
+ force: cfg.force,
12185
+ ...libOpt ? { libraryId: libOpt } : {}
10479
12186
  });
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"));
12187
+ const lines = [
12188
+ 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}`
12189
+ ];
12190
+ for (const item of res.pushed) {
12191
+ lines.push(` [ok] ${item.skillName}: files=${item.updatedFiles}, main=${item.updatedMain}, rev=${item.newRevision ?? "none"}, cleaned=${item.workdirCleaned}`);
12192
+ }
12193
+ for (const sk of res.skipped) {
12194
+ lines.push(` [skip] ${sk.skillName ?? sk.workdir}: ${sk.reason}`);
12195
+ }
12196
+ for (const fl of res.failed) {
12197
+ lines.push(` [fail] ${fl.skillName ?? fl.workdir} (${fl.code}): ${fl.error}`);
12198
+ }
12199
+ yield* printOut(cfg.json, res, lines.join(`
12200
+ `));
12201
+ if (res.failed.length > 0) {
12202
+ process.exitCode = 2;
12203
+ }
12204
+ })).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
12205
  var abortCmd = Command.make("abort", {
10483
12206
  workdir: Argument.String("workdir"),
10484
12207
  json: jsonFlag
10485
- }, (cfg) => Effect7.gen(function* () {
12208
+ }, (cfg) => Effect9.gen(function* () {
10486
12209
  const trashed = yield* abortWorkdirCommand(cfg.workdir);
10487
12210
  yield* printOut(cfg.json, { trashed }, `Moved workdir to system trash: ${trashed}`);
10488
12211
  })).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* () {
12212
+ var workListCmd = Command.make("list", { json: jsonFlag }, (cfg) => Effect9.gen(function* () {
10490
12213
  const items = yield* listWorkdirsCommand();
10491
12214
  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
12215
  `));
@@ -10494,13 +12217,16 @@ var workListCmd = Command.make("list", { json: jsonFlag }, (cfg) => Effect7.gen(
10494
12217
  var workCleanCmd = Command.make("clean", {
10495
12218
  days: Flag.Int("days").pipe(Flag.withDefault(7)),
10496
12219
  json: jsonFlag
10497
- }, (cfg) => Effect7.gen(function* () {
12220
+ }, (cfg) => Effect9.gen(function* () {
10498
12221
  const cleaned = yield* cleanWorkdirsCommand(cfg.days);
10499
12222
  yield* printOut(cfg.json, { cleaned }, `Cleaned ${cleaned.length} orphan workdir(s) older than ${cfg.days} day(s).`);
10500
12223
  }));
10501
12224
  var workCmd = Command.make("work").pipe(Command.withDescription("Inspect or clean isolated edit workspaces"), Command.withSubcommands([workListCmd, workCleanCmd]));
10502
12225
  var newCmd = Command.make("new", {
10503
- dir: Argument.String("dir"),
12226
+ dirs: Argument.String("dir").pipe(Argument.atLeast(0)),
12227
+ pending: Flag.Boolean("pending").pipe(Flag.withDescription("Discover unmanaged local skill directories inside configured export roots (requires explicit visibility flag)"), Flag.withDefault(false)),
12228
+ exclude: Flag.String("exclude").pipe(Flag.withDescription("Skill or directory names to exclude (comma-separated or repeatable)"), Flag.atLeast(0)),
12229
+ includeSymlinks: Flag.Boolean("include-symlinks").pipe(Flag.withDescription("Include external non-managed symlinks when scanning with --pending"), Flag.withDefault(false)),
10504
12230
  name: Flag.String("name").pipe(Flag.optional),
10505
12231
  profiles: Flag.String("profiles").pipe(Flag.atLeast(0)),
10506
12232
  scenes: Flag.String("scenes").pipe(Flag.atLeast(0)),
@@ -10510,18 +12236,20 @@ var newCmd = Command.make("new", {
10510
12236
  discoverable: Flag.Boolean("discoverable").pipe(Flag.withDescription("Shorthand for --visibility discoverable"), Flag.withDefault(false)),
10511
12237
  manual: Flag.Boolean("manual").pipe(Flag.withDescription("Shorthand for --visibility manual"), Flag.withDefault(false)),
10512
12238
  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")),
12239
+ 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>)")),
12240
+ 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")),
12241
+ 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
12242
  library: libraryFlag,
10516
12243
  json: jsonFlag
10517
- }, (cfg) => Effect7.gen(function* () {
12244
+ }, (cfg) => Effect9.gen(function* () {
10518
12245
  if (cfg.adopt && cfg.noAdopt) {
10519
- return yield* Effect7.fail(new ConfigError({ message: "Cannot pass both --adopt and --no-adopt." }));
12246
+ return yield* Effect9.fail(new ConfigError({ message: "Cannot pass both --adopt and --no-adopt." }));
10520
12247
  }
10521
12248
  const nm = Option2.getOrUndefined(cfg.name);
10522
12249
  const visOpt = Option2.getOrUndefined(cfg.visibility);
10523
12250
  const kindOpt = Option2.getOrUndefined(cfg.kind);
10524
12251
  const lib = Option2.getOrUndefined(cfg.library);
12252
+ const excludeList = splitMulti(cfg.exclude);
10525
12253
  const chosenVis = new Set;
10526
12254
  if (visOpt)
10527
12255
  chosenVis.add(visOpt);
@@ -10532,25 +12260,62 @@ var newCmd = Command.make("new", {
10532
12260
  if (cfg.manual)
10533
12261
  chosenVis.add("manual");
10534
12262
  if (chosenVis.size > 1) {
10535
- return yield* Effect7.fail(new ConfigError({
12263
+ return yield* Effect9.fail(new ConfigError({
10536
12264
  message: `Conflicting visibility flags specified (${Array.from(chosenVis).join(", ")}). Pick one.`
10537
12265
  }));
10538
12266
  }
10539
12267
  const visibility = Array.from(chosenVis)[0];
10540
12268
  const adoptOpt = cfg.adopt ? true : cfg.noAdopt ? false : undefined;
10541
- const res = yield* createNewSkillCommand({
10542
- dir: cfg.dir,
12269
+ if (!cfg.pending && cfg.dirs.length === 1 && !cfg.dryRun && excludeList.length === 0) {
12270
+ const res = yield* createNewSkillCommand({
12271
+ dir: cfg.dirs[0],
12272
+ ...nm ? { name: nm } : {},
12273
+ profiles: splitMulti(cfg.profiles),
12274
+ scenes: splitMulti(cfg.scenes),
12275
+ ...visibility ? { visibility } : {},
12276
+ ...kindOpt ? { kind: kindOpt } : {},
12277
+ ...adoptOpt !== undefined ? { adopt: adoptOpt } : {},
12278
+ ...lib ? { libraryId: lib } : {}
12279
+ });
12280
+ 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]" : "";
12281
+ yield* printOut(cfg.json, res, `Created native skill '${res.name}' (${res.skillId}, visibility=${res.visibility}), uploaded ${res.uploadedFiles} supporting file(s)${adoptNote}.`);
12282
+ return;
12283
+ }
12284
+ const res = yield* createNewSkillsBatchCommand({
12285
+ dirs: cfg.dirs,
12286
+ pending: cfg.pending,
12287
+ exclude: excludeList,
12288
+ includeSymlinks: cfg.includeSymlinks,
10543
12289
  ...nm ? { name: nm } : {},
10544
12290
  profiles: splitMulti(cfg.profiles),
10545
12291
  scenes: splitMulti(cfg.scenes),
10546
12292
  ...visibility ? { visibility } : {},
10547
12293
  ...kindOpt ? { kind: kindOpt } : {},
10548
12294
  ...adoptOpt !== undefined ? { adopt: adoptOpt } : {},
12295
+ dryRun: cfg.dryRun,
10549
12296
  ...lib ? { libraryId: lib } : {}
10550
12297
  });
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"));
12298
+ const lines = [
12299
+ 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}`
12300
+ ];
12301
+ for (const item of res.created) {
12302
+ const adoptSummary = res.dryRun ? item.willAdopt ? `, willAdopt=true, willExportAtSourcePath=${item.willExportAtSourcePath}` : ", willAdopt=false" : item.adoptedSourceDir ? `, adopted=true, exportedAtSourcePath=${item.exportedAtSourcePath}` : "";
12303
+ lines.push(` [${res.dryRun ? "plan" : "ok"}] ${item.name} (${item.visibility}, files=${item.fileCount}, bytes=${item.totalBytes}${adoptSummary}) <- ${item.dir}`);
12304
+ }
12305
+ for (const sk of res.skipped) {
12306
+ const tgt = sk.target ? ` -> ${sk.target}` : "";
12307
+ lines.push(` [skip] ${sk.name} (${sk.reason}${tgt}) <- ${sk.dir}`);
12308
+ }
12309
+ for (const fl of res.failed) {
12310
+ const tag = fl.blocked ? "blocked" : fl.conflict ? "conflict" : "fail";
12311
+ lines.push(` [${tag}] ${fl.name ?? fl.dir}: ${fl.error}`);
12312
+ }
12313
+ yield* printOut(cfg.json, res, lines.join(`
12314
+ `));
12315
+ if (res.failed.length > 0) {
12316
+ process.exitCode = 2;
12317
+ }
12318
+ })).pipe(Command.withDescription("Create one or more brand-new native skills in Notion from local directories (supports --pending and --dry-run)"));
10554
12319
  var setCmd = Command.make("set", {
10555
12320
  names: Argument.String("name").pipe(Argument.atLeast(0)),
10556
12321
  source: Flag.String("source").pipe(Flag.optional, Flag.withDescription("Batch-select all skills belonging to this upstream Git Source")),
@@ -10570,7 +12335,7 @@ var setCmd = Command.make("set", {
10570
12335
  require: Flag.String("require").pipe(Flag.atLeast(0)),
10571
12336
  library: libraryFlag,
10572
12337
  json: jsonFlag
10573
- }, (cfg) => Effect7.gen(function* () {
12338
+ }, (cfg) => Effect9.gen(function* () {
10574
12339
  const lib = Option2.getOrUndefined(cfg.library);
10575
12340
  const visOpt = Option2.getOrUndefined(cfg.visibility);
10576
12341
  const kindOpt = Option2.getOrUndefined(cfg.kind);
@@ -10600,7 +12365,7 @@ var attachCmd = Command.make("attach", {
10600
12365
  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
12366
  library: libraryFlag,
10602
12367
  json: jsonFlag
10603
- }, (cfg) => Effect7.gen(function* () {
12368
+ }, (cfg) => Effect9.gen(function* () {
10604
12369
  const sp = Option2.getOrUndefined(cfg.path);
10605
12370
  const lib = Option2.getOrUndefined(cfg.library);
10606
12371
  const res = yield* attachSkillCommand({
@@ -10615,7 +12380,7 @@ var detachCmd = Command.make("detach", {
10615
12380
  name: Argument.String("name"),
10616
12381
  library: libraryFlag,
10617
12382
  json: jsonFlag
10618
- }, (cfg) => Effect7.gen(function* () {
12383
+ }, (cfg) => Effect9.gen(function* () {
10619
12384
  const lib = Option2.getOrUndefined(cfg.library);
10620
12385
  const res = yield* detachSkillCommand({
10621
12386
  name: cfg.name,
@@ -10628,7 +12393,7 @@ var resetOverlayCmd = Command.make("reset-overlay", {
10628
12393
  path: Argument.String("path").pipe(Argument.optional),
10629
12394
  library: libraryFlag,
10630
12395
  json: jsonFlag
10631
- }, (cfg) => Effect7.gen(function* () {
12396
+ }, (cfg) => Effect9.gen(function* () {
10632
12397
  const p = Option2.getOrUndefined(cfg.path);
10633
12398
  const lib = Option2.getOrUndefined(cfg.library);
10634
12399
  const res = yield* resetOverlayCommand({
@@ -10642,7 +12407,7 @@ var rmCmd = Command.make("rm", {
10642
12407
  name: Argument.String("name"),
10643
12408
  library: libraryFlag,
10644
12409
  json: jsonFlag
10645
- }, (cfg) => Effect7.gen(function* () {
12410
+ }, (cfg) => Effect9.gen(function* () {
10646
12411
  const lib = Option2.getOrUndefined(cfg.library);
10647
12412
  yield* removeSkillCommand({
10648
12413
  name: cfg.name,
@@ -10653,7 +12418,7 @@ var rmCmd = Command.make("rm", {
10653
12418
  var sourceListCmd = Command.make("list", {
10654
12419
  library: libraryFlag,
10655
12420
  json: jsonFlag
10656
- }, (cfg) => Effect7.gen(function* () {
12421
+ }, (cfg) => Effect9.gen(function* () {
10657
12422
  const lib = Option2.getOrUndefined(cfg.library);
10658
12423
  const sources = yield* listSourcesCommand(lib ? { libraryId: lib } : undefined);
10659
12424
  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 +12436,7 @@ var sourceAddCmd = Command.make("add", {
10671
12436
  scenes: Flag.String("scenes").pipe(Flag.withDescription("Initial Scenes tags for discovered skills (comma-separated or repeatable)"), Flag.atLeast(0)),
10672
12437
  library: libraryFlag,
10673
12438
  json: jsonFlag
10674
- }, (cfg) => Effect7.gen(function* () {
12439
+ }, (cfg) => Effect9.gen(function* () {
10675
12440
  const nm = Option2.getOrUndefined(cfg.name);
10676
12441
  const rt = Option2.getOrUndefined(cfg.root);
10677
12442
  const lib = Option2.getOrUndefined(cfg.library);
@@ -10698,7 +12463,7 @@ var sourceSetCmd = Command.make("set", {
10698
12463
  disable: Flag.Boolean("disable").pipe(Flag.withDefault(false)),
10699
12464
  library: libraryFlag,
10700
12465
  json: jsonFlag
10701
- }, (cfg) => Effect7.gen(function* () {
12466
+ }, (cfg) => Effect9.gen(function* () {
10702
12467
  const pol = Option2.getOrUndefined(cfg.policy);
10703
12468
  const refVal = Option2.getOrUndefined(cfg.ref);
10704
12469
  const enable = cfg.enable ? true : cfg.disable ? false : undefined;
@@ -10718,7 +12483,7 @@ var sourceSyncCmd = Command.make("sync", {
10718
12483
  updatePinned: Flag.Boolean("update-pinned").pipe(Flag.withDefault(false)),
10719
12484
  library: libraryFlag,
10720
12485
  json: jsonFlag
10721
- }, (cfg) => Effect7.gen(function* () {
12486
+ }, (cfg) => Effect9.gen(function* () {
10722
12487
  const rt = Option2.getOrUndefined(cfg.root);
10723
12488
  const lib = Option2.getOrUndefined(cfg.library);
10724
12489
  const res = yield* syncSourceSkillsCommand({
@@ -10763,7 +12528,7 @@ var upstreamCheckCmd = Command.make("check", {
10763
12528
  strictDrift: Flag.Boolean("strict-drift").pipe(Flag.withDefault(false)),
10764
12529
  library: libraryFlag,
10765
12530
  json: jsonFlag
10766
- }, (cfg) => Effect7.gen(function* () {
12531
+ }, (cfg) => Effect9.gen(function* () {
10767
12532
  const sq = Option2.getOrUndefined(cfg.source);
10768
12533
  const tSec = Option2.getOrUndefined(cfg.timeoutSec);
10769
12534
  const repFile = Option2.getOrUndefined(cfg.reportFile);
@@ -10790,7 +12555,7 @@ var upstreamApplyCmd = Command.make("apply", {
10790
12555
  strictDrift: Flag.Boolean("strict-drift").pipe(Flag.withDefault(false)),
10791
12556
  library: libraryFlag,
10792
12557
  json: jsonFlag
10793
- }, (cfg) => Effect7.gen(function* () {
12558
+ }, (cfg) => Effect9.gen(function* () {
10794
12559
  const sq = Option2.getOrUndefined(cfg.source);
10795
12560
  const maxS = Option2.getOrUndefined(cfg.maxSources);
10796
12561
  const tSec = Option2.getOrUndefined(cfg.timeoutSec);
@@ -10818,7 +12583,7 @@ var scheduleInstallCmd = Command.make("install", {
10818
12583
  upstreamEvery: Flag.String("upstream-every").pipe(Flag.optional),
10819
12584
  library: libraryFlag,
10820
12585
  json: jsonFlag
10821
- }, (cfg) => Effect7.gen(function* () {
12586
+ }, (cfg) => Effect9.gen(function* () {
10822
12587
  const upEvery = Option2.getOrUndefined(cfg.upstreamEvery);
10823
12588
  const lib = Option2.getOrUndefined(cfg.library);
10824
12589
  const res = yield* installScheduleCommand({
@@ -10839,7 +12604,7 @@ var scheduleInstallCmd = Command.make("install", {
10839
12604
  `);
10840
12605
  yield* printOut(cfg.json, res, text);
10841
12606
  })).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* () {
12607
+ var scheduleStatusCmd = Command.make("status", { json: jsonFlag }, (cfg) => Effect9.gen(function* () {
10843
12608
  const res = yield* statusScheduleCommand();
10844
12609
  const lines = [
10845
12610
  `Platform: ${res.platform}`,
@@ -10857,7 +12622,7 @@ var scheduleStatusCmd = Command.make("status", { json: jsonFlag }, (cfg) => Effe
10857
12622
  yield* printOut(cfg.json, res, lines.join(`
10858
12623
  `));
10859
12624
  })).pipe(Command.withDescription("Inspect background timer health, credentials status, and logs"));
10860
- var scheduleUninstallCmd = Command.make("uninstall", { json: jsonFlag }, (cfg) => Effect7.gen(function* () {
12625
+ var scheduleUninstallCmd = Command.make("uninstall", { json: jsonFlag }, (cfg) => Effect9.gen(function* () {
10861
12626
  const res = yield* uninstallScheduleCommand();
10862
12627
  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
12628
  ${res.removedUnits.map((u) => ` ${u}`).join(`
@@ -10870,9 +12635,9 @@ var scheduleRunCmd = Command.make("run", {
10870
12635
  strictDrift: Flag.Boolean("strict-drift").pipe(Flag.withDefault(false)),
10871
12636
  library: libraryFlag,
10872
12637
  json: jsonFlag
10873
- }, (cfg) => Effect7.gen(function* () {
12638
+ }, (cfg) => Effect9.gen(function* () {
10874
12639
  if (cfg.job !== "sync" && cfg.job !== "sync-full" && cfg.job !== "upstream") {
10875
- return yield* Effect7.fail(new ConfigError({
12640
+ return yield* Effect9.fail(new ConfigError({
10876
12641
  message: `Unknown scheduled job '${cfg.job}'. Expected 'sync', 'sync-full', or 'upstream'.`
10877
12642
  }));
10878
12643
  }
@@ -10899,9 +12664,9 @@ var scheduleExportCmd = Command.make("export", {
10899
12664
  timeoutSec: Flag.Int("timeout-sec").pipe(Flag.withDefault(600)),
10900
12665
  library: libraryFlag,
10901
12666
  json: jsonFlag
10902
- }, (cfg) => Effect7.gen(function* () {
12667
+ }, (cfg) => Effect9.gen(function* () {
10903
12668
  if (cfg.target !== "dagu" && cfg.target !== "github-actions" && cfg.target !== "crontab") {
10904
- return yield* Effect7.fail(new ConfigError({
12669
+ return yield* Effect9.fail(new ConfigError({
10905
12670
  message: `Unknown export target '${cfg.target}'. Expected 'dagu', 'github-actions', or 'crontab'.`
10906
12671
  }));
10907
12672
  }
@@ -10926,8 +12691,8 @@ var scheduleCmd = Command.make("schedule").pipe(Command.withDescription("Manage
10926
12691
  var telemetryCmd = Command.make("telemetry", {
10927
12692
  hours: Flag.Int("hours").pipe(Flag.withDefault(24)),
10928
12693
  json: jsonFlag
10929
- }, (cfg) => Effect7.gen(function* () {
10930
- const rep = yield* Effect7.promise(() => summarizeTelemetry(cfg.hours));
12694
+ }, (cfg) => Effect9.gen(function* () {
12695
+ const rep = yield* Effect9.promise(() => summarizeTelemetry(cfg.hours));
10931
12696
  const lines = [
10932
12697
  `Window: last ${rep.windowHours}h | Total requests: ${rep.totalRequests} | Total bytes: ${rep.totalBytes} | Timeouts (>=60s): ${rep.timeoutsOver60s}`,
10933
12698
  ...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 +12707,14 @@ var skillCmd = Command.make("skill", {
10942
12707
  dest: Flag.String("dest").pipe(Flag.optional, Flag.withDescription("Target skills directory for --install/--uninstall (default: ~/.agents/skills)")),
10943
12708
  force: Flag.Boolean("force").pipe(Flag.withDefault(false), Flag.withDescription("Replace existing library-managed or foreign entry on --install")),
10944
12709
  json: jsonFlag
10945
- }, (cfg) => Effect7.gen(function* () {
12710
+ }, (cfg) => Effect9.gen(function* () {
10946
12711
  const store = yield* StorePort;
10947
12712
  const destDir = Option2.getOrUndefined(cfg.dest);
10948
12713
  if (cfg.install && cfg.uninstall) {
10949
- return yield* Effect7.fail(new ConfigError({ message: "Cannot pass both --install and --uninstall." }));
12714
+ return yield* Effect9.fail(new ConfigError({ message: "Cannot pass both --install and --uninstall." }));
10950
12715
  }
10951
12716
  if (cfg.install) {
10952
- const res = yield* Effect7.tryPromise({
12717
+ const res = yield* Effect9.tryPromise({
10953
12718
  try: () => installBundledSkill({
10954
12719
  ...destDir ? { destDir } : {},
10955
12720
  storeRoot: store.paths.storeRoot,
@@ -10961,7 +12726,7 @@ var skillCmd = Command.make("skill", {
10961
12726
  return;
10962
12727
  }
10963
12728
  if (cfg.uninstall) {
10964
- const res = yield* Effect7.tryPromise({
12729
+ const res = yield* Effect9.tryPromise({
10965
12730
  try: () => uninstallBundledSkill({
10966
12731
  ...destDir ? { destDir } : {},
10967
12732
  storeRoot: store.paths.storeRoot
@@ -10971,7 +12736,7 @@ var skillCmd = Command.make("skill", {
10971
12736
  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
12737
  return;
10973
12738
  }
10974
- const payload = yield* Effect7.tryPromise({
12739
+ const payload = yield* Effect9.tryPromise({
10975
12740
  try: () => readBundledSkill(),
10976
12741
  catch: (e) => e instanceof StoreError ? e : new StoreError({ path: "assets/ntn-skills/SKILL.md", message: String(e) })
10977
12742
  });
@@ -10990,17 +12755,17 @@ var mcpCmd = Command.make("mcp", {
10990
12755
  library: libraryFlag,
10991
12756
  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
12757
  instructions: Flag.String("instructions").pipe(Flag.withDescription("Override MCP initialize instructions text"), Flag.optional)
10993
- }, (cfg) => Effect7.gen(function* () {
12758
+ }, (cfg) => Effect9.gen(function* () {
10994
12759
  const lib = Option2.getOrUndefined(cfg.library);
10995
12760
  const customInstructions = Option2.getOrUndefined(cfg.instructions);
10996
12761
  const allowedScenes = splitMulti(cfg.scenes);
10997
- const services = yield* Effect7.context();
10998
- yield* Effect7.promise(() => runStdioMcpServer({
12762
+ const services = yield* Effect9.context();
12763
+ yield* Effect9.promise(() => runStdioMcpServer({
10999
12764
  version: BUNDLED_SKILL_VERSION,
11000
12765
  ...lib ? { libraryId: lib } : {},
11001
12766
  ...allowedScenes.length > 0 ? { allowedScenes } : {},
11002
12767
  ...customInstructions !== undefined ? { instructions: customInstructions } : {},
11003
- runCore: (eff) => Effect7.runPromise(eff.pipe(Effect7.provide(services)))
12768
+ runCore: (eff) => Effect9.runPromise(eff.pipe(Effect9.provide(services)))
11004
12769
  }));
11005
12770
  })).pipe(Command.withDescription("Run a read-only stdio JSON-RPC 2.0 MCP server exposing skill_find and skill_load"));
11006
12771
  var rootCommand = Command.make("ntn-skills").pipe(Command.withDescription("Notion 3-table skill control-plane synchronizer & local-native CLI (v2)"), Command.withSubcommands([
@@ -11043,10 +12808,10 @@ var DOMAIN_ERROR_TAGS = new Set([
11043
12808
  ]);
11044
12809
  function runCli(argv) {
11045
12810
  const appLayer = Layer5.mergeAll(NodeServices.layer, makeCoreLiveLayer());
11046
- return Command.runWith(rootCommand, { version: BUNDLED_SKILL_VERSION })(argv).pipe(Effect7.provide(appLayer), Effect7.catch((err) => {
12811
+ return Command.runWith(rootCommand, { version: BUNDLED_SKILL_VERSION })(argv).pipe(Effect9.provide(appLayer), Effect9.catch((err) => {
11047
12812
  const tag = err?._tag;
11048
12813
  if (!tag || !DOMAIN_ERROR_TAGS.has(tag)) {
11049
- return Effect7.fail(err);
12814
+ return Effect9.fail(err);
11050
12815
  }
11051
12816
  const code = classifyErrorExitCode(err);
11052
12817
  const msg = err && typeof err === "object" && "message" in err ? String(err.message) : String(err);