@iwsdk/cli 1.2.0-rc.0 → 1.2.0-rc.1

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.
Files changed (99) hide show
  1. package/README.md +40 -13
  2. package/dist/agent-guidance/files/.agents/skills/iwsdk-build-model/SKILL.md +1 -1
  3. package/dist/agent-guidance/files/.agents/skills/iwsdk-compose-scene/SKILL.md +1 -1
  4. package/dist/agent-guidance/files/.agents/skills/iwsdk-debug/SKILL.md +1 -1
  5. package/dist/agent-guidance/files/.agents/skills/iwsdk-depth-occlusion/SKILL.md +1 -1
  6. package/dist/agent-guidance/files/.agents/skills/iwsdk-dev/SKILL.md +1 -1
  7. package/dist/agent-guidance/files/.agents/skills/iwsdk-dev/references/api-reference.md +2 -1
  8. package/dist/agent-guidance/files/.agents/skills/iwsdk-dev/references/headless-rendering.md +15 -1
  9. package/dist/agent-guidance/files/.agents/skills/iwsdk-dev/references/iterate.md +7 -3
  10. package/dist/agent-guidance/files/.agents/skills/iwsdk-glasses-test/SKILL.md +1 -1
  11. package/dist/agent-guidance/files/.agents/skills/iwsdk-grab/SKILL.md +1 -1
  12. package/dist/agent-guidance/files/.agents/skills/iwsdk-hosting/SKILL.md +3 -2
  13. package/dist/agent-guidance/files/.agents/skills/iwsdk-native-xr-test/SKILL.md +1 -1
  14. package/dist/agent-guidance/files/.agents/skills/iwsdk-offline/SKILL.md +217 -0
  15. package/dist/agent-guidance/files/.agents/skills/iwsdk-offline/assets/offline.ts.template +99 -0
  16. package/dist/agent-guidance/files/.agents/skills/iwsdk-offline/assets/sw.js.template +241 -0
  17. package/dist/agent-guidance/files/.agents/skills/iwsdk-offline/assets/write-service-worker.mjs.template +72 -0
  18. package/dist/agent-guidance/files/.agents/skills/iwsdk-offline/references/build-step.md +71 -0
  19. package/dist/agent-guidance/files/.agents/skills/iwsdk-offline/references/page.md +70 -0
  20. package/dist/agent-guidance/files/.agents/skills/iwsdk-offline/references/service-worker.md +107 -0
  21. package/dist/agent-guidance/files/.agents/skills/iwsdk-offline/references/testing.md +57 -0
  22. package/dist/agent-guidance/files/.agents/skills/iwsdk-physics/SKILL.md +1 -1
  23. package/dist/agent-guidance/files/.agents/skills/iwsdk-physics/references/tuning-and-config.md +1 -0
  24. package/dist/agent-guidance/files/.agents/skills/iwsdk-physics/references/workflows.md +9 -3
  25. package/dist/agent-guidance/files/.agents/skills/iwsdk-pwa-packaging/SKILL.md +13 -2
  26. package/dist/agent-guidance/files/.agents/skills/iwsdk-pwa-packaging/references/manifest-and-icons.md +1 -1
  27. package/dist/agent-guidance/files/.agents/skills/iwsdk-pwa-packaging/references/troubleshooting.md +30 -0
  28. package/dist/agent-guidance/files/.agents/skills/iwsdk-ray/SKILL.md +1 -1
  29. package/dist/agent-guidance/files/.agents/skills/iwsdk-ui/SKILL.md +12 -5
  30. package/dist/agent-guidance/files/.agents/skills/iwsdk-upgrade/SKILL.md +1 -1
  31. package/dist/agent-guidance/files/.claude/agents/iwsdk-project-code-reviewer.md +1 -1
  32. package/dist/agent-guidance/files/.claude/rules/assets-and-manifest.md +1 -1
  33. package/dist/agent-guidance/files/.claude/rules/ecs-api.md +1 -1
  34. package/dist/agent-guidance/files/.claude/rules/scene-json.md +1 -1
  35. package/dist/agent-guidance/files/.claude/rules/uikitml.md +1 -1
  36. package/dist/agent-guidance/files/.claude/settings.json +1 -0
  37. package/dist/agent-guidance/files/.claude/skills/iwsdk-build-model/SKILL.md +1 -1
  38. package/dist/agent-guidance/files/.claude/skills/iwsdk-compose-scene/SKILL.md +1 -1
  39. package/dist/agent-guidance/files/.claude/skills/iwsdk-debug/SKILL.md +1 -1
  40. package/dist/agent-guidance/files/.claude/skills/iwsdk-depth-occlusion/SKILL.md +1 -1
  41. package/dist/agent-guidance/files/.claude/skills/iwsdk-dev/SKILL.md +1 -1
  42. package/dist/agent-guidance/files/.claude/skills/iwsdk-dev/references/api-reference.md +2 -1
  43. package/dist/agent-guidance/files/.claude/skills/iwsdk-dev/references/headless-rendering.md +15 -1
  44. package/dist/agent-guidance/files/.claude/skills/iwsdk-dev/references/iterate.md +7 -3
  45. package/dist/agent-guidance/files/.claude/skills/iwsdk-glasses-test/SKILL.md +1 -1
  46. package/dist/agent-guidance/files/.claude/skills/iwsdk-grab/SKILL.md +1 -1
  47. package/dist/agent-guidance/files/.claude/skills/iwsdk-hosting/SKILL.md +3 -2
  48. package/dist/agent-guidance/files/.claude/skills/iwsdk-native-xr-test/SKILL.md +1 -1
  49. package/dist/agent-guidance/files/.claude/skills/iwsdk-offline/SKILL.md +217 -0
  50. package/dist/agent-guidance/files/.claude/skills/iwsdk-offline/assets/offline.ts.template +99 -0
  51. package/dist/agent-guidance/files/.claude/skills/iwsdk-offline/assets/sw.js.template +241 -0
  52. package/dist/agent-guidance/files/.claude/skills/iwsdk-offline/assets/write-service-worker.mjs.template +72 -0
  53. package/dist/agent-guidance/files/.claude/skills/iwsdk-offline/references/build-step.md +71 -0
  54. package/dist/agent-guidance/files/.claude/skills/iwsdk-offline/references/page.md +70 -0
  55. package/dist/agent-guidance/files/.claude/skills/iwsdk-offline/references/service-worker.md +107 -0
  56. package/dist/agent-guidance/files/.claude/skills/iwsdk-offline/references/testing.md +57 -0
  57. package/dist/agent-guidance/files/.claude/skills/iwsdk-physics/SKILL.md +1 -1
  58. package/dist/agent-guidance/files/.claude/skills/iwsdk-physics/references/tuning-and-config.md +1 -0
  59. package/dist/agent-guidance/files/.claude/skills/iwsdk-physics/references/workflows.md +9 -3
  60. package/dist/agent-guidance/files/.claude/skills/iwsdk-pwa-packaging/SKILL.md +13 -2
  61. package/dist/agent-guidance/files/.claude/skills/iwsdk-pwa-packaging/references/manifest-and-icons.md +1 -1
  62. package/dist/agent-guidance/files/.claude/skills/iwsdk-pwa-packaging/references/troubleshooting.md +30 -0
  63. package/dist/agent-guidance/files/.claude/skills/iwsdk-ray/SKILL.md +1 -1
  64. package/dist/agent-guidance/files/.claude/skills/iwsdk-ui/SKILL.md +12 -5
  65. package/dist/agent-guidance/files/.claude/skills/iwsdk-upgrade/SKILL.md +1 -1
  66. package/dist/agent-guidance/files/.cursor/rules/assets-and-manifest.mdc +1 -1
  67. package/dist/agent-guidance/files/.cursor/rules/ecs-api.mdc +1 -1
  68. package/dist/agent-guidance/files/.cursor/rules/scene-json.mdc +1 -1
  69. package/dist/agent-guidance/files/.cursor/rules/uikitml.mdc +1 -1
  70. package/dist/agent-guidance/files/.github/instructions/assets-and-manifest.instructions.md +1 -1
  71. package/dist/agent-guidance/files/.github/instructions/ecs-api.instructions.md +1 -1
  72. package/dist/agent-guidance/files/.github/instructions/scene-json.instructions.md +1 -1
  73. package/dist/agent-guidance/files/.github/instructions/uikitml.instructions.md +1 -1
  74. package/dist/agent-guidance/files/AGENTS.md +1 -1
  75. package/dist/agent-guidance/files/public/scenes/AGENTS.md +1 -1
  76. package/dist/agent-guidance/files/public/ui/AGENTS.md +1 -1
  77. package/dist/agent-guidance/files/src/AGENTS.md +1 -1
  78. package/dist/agent-guidance/manifest.json +111 -11
  79. package/dist/agent-guidance.d.ts +31 -4
  80. package/dist/agent-guidance.d.ts.map +1 -1
  81. package/dist/agent-guidance.js +269 -60
  82. package/dist/agent-guidance.js.map +1 -1
  83. package/dist/cli.js +1128 -131
  84. package/dist/cli.js.map +1 -1
  85. package/dist/commands/upgrade.d.ts +87 -0
  86. package/dist/commands/upgrade.d.ts.map +1 -1
  87. package/dist/guidance-refresh.d.ts +23 -3
  88. package/dist/guidance-refresh.d.ts.map +1 -1
  89. package/dist/help.d.ts.map +1 -1
  90. package/dist/index.d.ts.map +1 -1
  91. package/dist/index.js +1128 -131
  92. package/dist/index.js.map +1 -1
  93. package/dist/metavr-telemetry.d.ts +6 -0
  94. package/dist/metavr-telemetry.d.ts.map +1 -1
  95. package/dist/package-manager.d.ts +6 -0
  96. package/dist/package-manager.d.ts.map +1 -1
  97. package/dist/release-notes.json +132 -0
  98. package/dist/version.d.ts +1 -1
  99. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import require$$1, { createHash as createHash$2, randomUUID } from 'crypto';
2
- import { existsSync, readFileSync, realpathSync, openSync, closeSync } from 'fs';
3
- import { readFile, lstat, readdir, rm, mkdir, writeFile, rename, realpath, rmdir, mkdtemp, unlink, appendFile } from 'fs/promises';
2
+ import { existsSync, readFileSync, realpathSync, openSync, closeSync, rmSync } from 'fs';
3
+ import { readFile, lstat, readdir, realpath, rm, mkdir, writeFile, rename, rmdir, mkdtemp, unlink, appendFile } from 'fs/promises';
4
4
  import { createRequire } from 'module';
5
5
  import path from 'path';
6
6
  import require$$7, { fileURLToPath, pathToFileURL } from 'url';
7
- import { execFileSync, spawn, spawnSync } from 'child_process';
7
+ import { execFileSync, spawn, execFile, spawnSync } from 'child_process';
8
8
  import require$$3$1, { createConnection } from 'net';
9
9
  import require$$0$3 from 'events';
10
10
  import require$$1$1 from 'https';
@@ -13,7 +13,7 @@ import require$$4 from 'tls';
13
13
  import require$$0$2 from 'stream';
14
14
  import require$$0 from 'zlib';
15
15
  import require$$0$1 from 'buffer';
16
- import require$$2 from 'util';
16
+ import require$$2, { promisify } from 'util';
17
17
  import process$2 from 'node:process';
18
18
  import { randomUUID as randomUUID$1 } from 'node:crypto';
19
19
  import os from 'os';
@@ -2387,6 +2387,8 @@ const GUIDANCE_TOOLS = [
2387
2387
  // test/agent-guidance.test.ts checks both sides against a fresh render.
2388
2388
  const GUIDANCE_FORMAT = 1;
2389
2389
  const BLOCK_NAME = 'iwsdk-agent-guidance';
2390
+ /** The root AGENTS.md block unit, which a CLAUDE.md import points at. */
2391
+ const ROOT_BLOCK = 'AGENTS.md';
2390
2392
  const STAMP_LINE = /^<!-- iwsdk-agent-guidance version=(\S+) sha256=([0-9a-f]{64})(?: name=(\S+))? [^\n]*-->\r?\n?/mu;
2391
2393
  const BLOCK_PATTERN = new RegExp(`<!-- BEGIN ${BLOCK_NAME} version=(\\S+) sha256=([0-9a-f]{64}) -->\\n([\\s\\S]*?)<!-- END ${BLOCK_NAME} -->\\n?`, 'u');
2392
2394
  const BLOCK_BEGIN = new RegExp(`<!-- BEGIN ${BLOCK_NAME}\\b`, 'gu');
@@ -2436,6 +2438,10 @@ function directoryUnitHash(files) {
2436
2438
  function blockUnitHash(body) {
2437
2439
  return sha256(withTrailingNewline(normalizeText(body)));
2438
2440
  }
2441
+ /** The release stamped on the iwsdk-agent-guidance block in `text`, if any. */
2442
+ function readGuidanceBlockVersion(text) {
2443
+ return normalizeText(text).match(BLOCK_PATTERN)?.[1] ?? null;
2444
+ }
2439
2445
  function isTextFile(name) {
2440
2446
  return !/\.(png|jpe?g|webp|gif|glb|mp3|ktx2)$/iu.test(name);
2441
2447
  }
@@ -2498,6 +2504,12 @@ async function loadGuidanceSource(root, origin = 'explicit') {
2498
2504
  assertRelativeUnitPath(file);
2499
2505
  }
2500
2506
  }
2507
+ for (const [retired, successors] of Object.entries(manifest.successors ?? {})) {
2508
+ assertRelativeUnitPath(retired);
2509
+ for (const successor of successors) {
2510
+ assertRelativeUnitPath(successor);
2511
+ }
2512
+ }
2501
2513
  return { root, manifest, origin };
2502
2514
  }
2503
2515
  function bundledGuidanceRoot() {
@@ -2600,11 +2612,14 @@ async function isSameFile(first, second) {
2600
2612
  return false;
2601
2613
  }
2602
2614
  }
2603
- /** Temporary siblings a sync left behind when it was killed mid-swap. */
2604
- const TEMPORARY_SIBLING = /^\..+\.iwsdk-(?:new|old)-(\d+)-(\d+)$/u;
2615
+ /**
2616
+ * Temporary siblings a sync left behind when it was killed mid-swap: the
2617
+ * name they stand in for, `new` or `old`, the process id and the time.
2618
+ */
2619
+ const TEMPORARY_SIBLING = /^\.(.+)\.iwsdk-(new|old)-(\d+)-(\d+)$/u;
2605
2620
  /** A temporary sibling that a sync running right now may still need. */
2606
2621
  function isInUse(name) {
2607
- const [, pid, createdAt] = TEMPORARY_SIBLING.exec(name) ?? [];
2622
+ const [, , , pid, createdAt] = TEMPORARY_SIBLING.exec(name) ?? [];
2608
2623
  if (Date.now() - Number(createdAt) < 10 * 60_000) {
2609
2624
  return true;
2610
2625
  }
@@ -2761,6 +2776,19 @@ function replacementResult(unit, ownership, force) {
2761
2776
  }
2762
2777
  return null;
2763
2778
  }
2779
+ /**
2780
+ * A unit that `onlyExisting` left out because the project does not have it.
2781
+ * `lacks` names what an existing file is missing.
2782
+ */
2783
+ function missingResult(unit, unitPath = unit.path, lacks) {
2784
+ return {
2785
+ path: unitPath,
2786
+ kind: unit.kind,
2787
+ action: 'skipped',
2788
+ reason: 'missing',
2789
+ ...(lacks ? { detail: lacks } : {}),
2790
+ };
2791
+ }
2764
2792
  async function pathKind(filePath) {
2765
2793
  try {
2766
2794
  const stat = await lstat(filePath);
@@ -2773,7 +2801,13 @@ async function pathKind(filePath) {
2773
2801
  throw error;
2774
2802
  }
2775
2803
  }
2776
- async function syncDirectoryUnit(unit, source, writer, force) {
2804
+ /**
2805
+ * The unit syncs below take `create`: whether a unit the project lacks (a
2806
+ * missing file or folder, or a block or import missing from a file) may be
2807
+ * written. `onlyExisting` allows it only for units that replace guidance
2808
+ * this run retires, and for folders a killed sync was replacing.
2809
+ */
2810
+ async function syncDirectoryUnit(unit, source, writer, force, create) {
2777
2811
  const localRoot = path.join(writer.projectRoot, unit.path);
2778
2812
  const replace = async () => {
2779
2813
  const files = [];
@@ -2785,6 +2819,9 @@ async function syncDirectoryUnit(unit, source, writer, force) {
2785
2819
  const kind = await pathKind(localRoot);
2786
2820
  const localFiles = kind === 'directory' ? await readTree(localRoot) : null;
2787
2821
  if (kind === 'missing' || localFiles?.size === 0) {
2822
+ if (!create) {
2823
+ return missingResult(unit);
2824
+ }
2788
2825
  await replace();
2789
2826
  return { path: unit.path, kind: unit.kind, action: 'created' };
2790
2827
  }
@@ -2818,10 +2855,13 @@ async function syncDirectoryUnit(unit, source, writer, force) {
2818
2855
  }
2819
2856
  return result;
2820
2857
  }
2821
- async function syncFileUnit(unit, source, writer, force) {
2858
+ async function syncFileUnit(unit, source, writer, force, create) {
2822
2859
  const local = await readTextIfExists(path.join(writer.projectRoot, unit.path));
2823
2860
  const next = await readSourceFile(source, unit.path);
2824
2861
  if (local == null) {
2862
+ if (!create) {
2863
+ return missingResult(unit);
2864
+ }
2825
2865
  await writer.write(unit.path, next);
2826
2866
  return { path: unit.path, kind: unit.kind, action: 'created' };
2827
2867
  }
@@ -2835,10 +2875,13 @@ async function syncFileUnit(unit, source, writer, force) {
2835
2875
  }
2836
2876
  return result;
2837
2877
  }
2838
- async function syncBlockUnit(unit, source, writer, force) {
2878
+ async function syncBlockUnit(unit, source, writer, force, create) {
2839
2879
  const local = await readTextIfExists(path.join(writer.projectRoot, unit.path));
2840
2880
  const block = (await readSourceFile(source, unit.path)).toString('utf8');
2841
2881
  if (local == null) {
2882
+ if (!create) {
2883
+ return missingResult(unit);
2884
+ }
2842
2885
  await writer.write(unit.path, block);
2843
2886
  return { path: unit.path, kind: unit.kind, action: 'created' };
2844
2887
  }
@@ -2897,6 +2940,10 @@ async function syncBlockUnit(unit, source, writer, force) {
2897
2940
  reason: 'forced',
2898
2941
  };
2899
2942
  }
2943
+ if (!create) {
2944
+ // No IWSDK block: the developer removed it or replaced the file.
2945
+ return missingResult(unit, unit.path, 'no iwsdk-agent-guidance block');
2946
+ }
2900
2947
  await writer.write(unit.path, withLineEndings(`${withTrailingNewline(normalized)}${normalized.trim() ? '\n' : ''}${block}`, local));
2901
2948
  return {
2902
2949
  path: unit.path,
@@ -2905,23 +2952,54 @@ async function syncBlockUnit(unit, source, writer, force) {
2905
2952
  reason: 'appended',
2906
2953
  };
2907
2954
  }
2908
- async function syncClaudeImport(unit, source, writer, force) {
2955
+ /**
2956
+ * A root CLAUDE.md that holds the full guidance of a release before 1.0, as
2957
+ * that release wrote it. It is replaced with an `@AGENTS.md` import, so the
2958
+ * guidance it held now comes from the AGENTS.md block.
2959
+ */
2960
+ async function holdsLegacyClaudeGuidance(unit, source, projectRoot) {
2961
+ const filePath = path.join(projectRoot, unit.path);
2962
+ const rootFile = await readTextIfExists(filePath);
2963
+ if (rootFile == null ||
2964
+ (await isSameFile(filePath, path.join(projectRoot, ROOT_BLOCK)))) {
2965
+ return false;
2966
+ }
2967
+ const hash = fileUnitHash(rootFile);
2968
+ return (hash !==
2969
+ fileUnitHash((await readSourceFile(source, unit.path)).toString()) &&
2970
+ (source.manifest.legacy[unit.path]?.includes(hash) ?? false));
2971
+ }
2972
+ /**
2973
+ * `replaceLegacy`: whether a CLAUDE.md holding the full guidance of a release
2974
+ * before 1.0 may become an import, which needs the AGENTS.md block in place.
2975
+ */
2976
+ async function syncClaudeImport(unit, source, writer, force, create, replaceLegacy) {
2909
2977
  const rootFile = await readTextIfExists(path.join(writer.projectRoot, unit.path));
2910
2978
  const nestedFile = await readTextIfExists(path.join(writer.projectRoot, '.claude', 'CLAUDE.md'));
2911
2979
  const next = await readSourceFile(source, unit.path);
2912
2980
  if (rootFile == null && nestedFile == null) {
2981
+ if (!create) {
2982
+ return missingResult(unit);
2983
+ }
2913
2984
  await writer.write(unit.path, next);
2914
2985
  return { path: unit.path, kind: unit.kind, action: 'created' };
2915
2986
  }
2916
2987
  if (rootFile != null &&
2917
- (await isSameFile(path.join(writer.projectRoot, unit.path), path.join(writer.projectRoot, 'AGENTS.md')))) {
2988
+ (await isSameFile(path.join(writer.projectRoot, unit.path), path.join(writer.projectRoot, ROOT_BLOCK)))) {
2918
2989
  // CLAUDE.md is a link to AGENTS.md: Claude already reads the guidance.
2919
2990
  return { path: unit.path, kind: unit.kind, action: 'unchanged' };
2920
2991
  }
2921
- if (rootFile != null &&
2922
- fileUnitHash(rootFile) !== fileUnitHash(next.toString('utf8')) &&
2923
- source.manifest.legacy[unit.path]?.includes(fileUnitHash(rootFile))) {
2992
+ if (await holdsLegacyClaudeGuidance(unit, source, writer.projectRoot)) {
2924
2993
  // Releases before 1.0 put the full guidance in CLAUDE.md.
2994
+ if (!replaceLegacy) {
2995
+ return {
2996
+ path: unit.path,
2997
+ kind: unit.kind,
2998
+ action: 'skipped',
2999
+ reason: 'retired',
3000
+ detail: 'It holds the full guidance of an IWSDK release before 1.0, and becomes an @AGENTS.md import once AGENTS.md has the iwsdk-agent-guidance block.',
3001
+ };
3002
+ }
2925
3003
  await writer.write(unit.path, withLineEndings(next.toString('utf8'), rootFile));
2926
3004
  return {
2927
3005
  path: unit.path,
@@ -2954,6 +3032,10 @@ async function syncClaudeImport(unit, source, writer, force) {
2954
3032
  (nestedFile != null && /^@\.\.\/AGENTS\.md\s*$/mu.test(nestedFile))) {
2955
3033
  return { path: unit.path, kind: unit.kind, action: 'unchanged' };
2956
3034
  }
3035
+ if (!create) {
3036
+ // The import was removed, or CLAUDE.md replaced.
3037
+ return missingResult(unit, rootFile != null ? unit.path : '.claude/CLAUDE.md', 'no @AGENTS.md import');
3038
+ }
2957
3039
  if (rootFile != null) {
2958
3040
  await writer.write(unit.path, withLineEndings(`${withTrailingNewline(rootFile)}\n@AGENTS.md\n`, rootFile));
2959
3041
  return {
@@ -2987,9 +3069,12 @@ function ownedSkillNames(manifest) {
2987
3069
  }
2988
3070
  return names;
2989
3071
  }
2990
- async function syncClaudeSettings$1(unit, source, writer, installedSkills, retiredSkills, force) {
3072
+ async function syncClaudeSettings$1(unit, source, writer, skills, force, onlyExisting, create) {
2991
3073
  const filePath = path.join(writer.projectRoot, unit.path);
2992
3074
  const raw = await readTextIfExists(filePath);
3075
+ if (raw == null && !create) {
3076
+ return missingResult(unit);
3077
+ }
2993
3078
  let settings = {};
2994
3079
  if (raw != null) {
2995
3080
  let parsed;
@@ -3021,24 +3106,34 @@ async function syncClaudeSettings$1(unit, source, writer, installedSkills, retir
3021
3106
  const shipped = new Set(unit.skills ?? []);
3022
3107
  const owned = new Set([
3023
3108
  ...ownedSkillNames(source.manifest),
3024
- ...retiredSkills,
3109
+ ...skills.removed,
3025
3110
  ]);
3111
+ const skillOf = (rule) => typeof rule === 'string' ? rule.match(SKILL_PERMISSION)?.[1] : undefined;
3112
+ const allowed = new Set(allow.map(skillOf));
3026
3113
  // Grant skills this sync installed (all of them for a new settings file);
3027
3114
  // a permission the developer removed for an untouched skill stays removed.
3028
3115
  // Grant every shipped skill when the file is new, when --force is given, or
3029
3116
  // when no IWSDK skill permission is left (after `adapter prune`, say).
3117
+ // `onlyExisting` grants a skill only the permission of the retired skill it
3118
+ // replaces, and keeps the permissions of retired skills that stay.
3030
3119
  const grantAll = raw == null ||
3031
3120
  force ||
3032
3121
  !allow.some((rule) => {
3033
- const name = typeof rule === 'string'
3034
- ? rule.match(SKILL_PERMISSION)?.[1]
3035
- : undefined;
3122
+ const name = skillOf(rule);
3036
3123
  return name != null && owned.has(name);
3037
3124
  });
3038
- const grant = [...shipped].filter((name) => grantAll || installedSkills.has(name));
3125
+ const grant = onlyExisting && raw != null
3126
+ ? [...skills.replacedBy]
3127
+ .filter(([retired]) => allowed.has(retired))
3128
+ .flatMap(([, successors]) => successors)
3129
+ .filter((name) => shipped.has(name))
3130
+ : [...shipped].filter((name) => grantAll || skills.installed.has(name));
3039
3131
  const isRetired = (rule) => {
3040
- const name = typeof rule === 'string' ? rule.match(SKILL_PERMISSION)?.[1] : undefined;
3041
- return name != null && owned.has(name) && !shipped.has(name);
3132
+ const name = skillOf(rule);
3133
+ return (name != null &&
3134
+ owned.has(name) &&
3135
+ !shipped.has(name) &&
3136
+ !(onlyExisting && skills.kept.has(name)));
3042
3137
  };
3043
3138
  const nextAllow = allow.filter((rule) => !isRetired(rule));
3044
3139
  for (const name of grant) {
@@ -3116,7 +3211,14 @@ function toolsForPath(unitPath) {
3116
3211
  }
3117
3212
  return GUIDANCE_TOOLS;
3118
3213
  }
3119
- async function pruneRetiredUnits(source, tools, writer) {
3214
+ /**
3215
+ * IWSDK units in the project that this release no longer ships, for the
3216
+ * selected tools. Also returns the temporary siblings a killed sync left
3217
+ * behind, for the caller to delete once its writes are done, and the units
3218
+ * such a sync was replacing when it was killed (their folder is gone, so
3219
+ * they count as present).
3220
+ */
3221
+ async function findRetiredUnits(source, tools, writer) {
3120
3222
  const shipped = new Set(source.manifest.units.map((unit) => unit.path));
3121
3223
  const blocks = new Set(source.manifest.units
3122
3224
  .filter((unit) => unit.kind === 'block' || unit.kind === 'claude-import')
@@ -3154,8 +3256,9 @@ async function pruneRetiredUnits(source, tools, writer) {
3154
3256
  }
3155
3257
  }
3156
3258
  }
3157
- const results = [];
3158
- const removedSkills = new Set();
3259
+ const retired = [];
3260
+ const interrupted = new Set();
3261
+ const leftovers = [];
3159
3262
  for (const directory of ['.', ...PRUNE_ROOTS.map((root) => root.directory)]) {
3160
3263
  let entries;
3161
3264
  try {
@@ -3165,7 +3268,15 @@ async function pruneRetiredUnits(source, tools, writer) {
3165
3268
  continue;
3166
3269
  }
3167
3270
  for (const name of entries.filter((entry) => TEMPORARY_SIBLING.test(entry) && !isInUse(entry))) {
3168
- await writer.remove(path.posix.join(directory, name));
3271
+ const [, original, label] = TEMPORARY_SIBLING.exec(name);
3272
+ const originalPath = path.posix.join(directory, original);
3273
+ if (label === 'old' &&
3274
+ (await pathKind(path.join(writer.projectRoot, originalPath))) ===
3275
+ 'missing') {
3276
+ // Killed between the two renames of replaceDirectory.
3277
+ interrupted.add(originalPath);
3278
+ }
3279
+ leftovers.push(path.posix.join(directory, name));
3169
3280
  }
3170
3281
  }
3171
3282
  for (const [unitPath, kind] of candidates) {
@@ -3191,24 +3302,13 @@ async function pruneRetiredUnits(source, tools, writer) {
3191
3302
  continue;
3192
3303
  }
3193
3304
  const ownership = classify(localHash, undefined, stamp, source.manifest.legacy[unitPath], source.manifest.version);
3194
- if (ownership === 'managed' || ownership === 'legacy') {
3195
- await writer.remove(unitPath);
3196
- results.push({ path: unitPath, kind, action: 'removed' });
3197
- if (kind === 'directory') {
3198
- removedSkills.add(name);
3199
- }
3200
- }
3201
- else if (ownership === 'modified') {
3202
- // A retired IWSDK unit the developer edited: keep it, but say so.
3203
- results.push({
3204
- path: unitPath,
3205
- kind,
3206
- action: 'skipped',
3207
- reason: 'modified',
3208
- });
3305
+ if (ownership === 'managed' ||
3306
+ ownership === 'legacy' ||
3307
+ ownership === 'modified') {
3308
+ retired.push({ path: unitPath, kind, ownership });
3209
3309
  }
3210
3310
  }
3211
- return { results, removedSkills };
3311
+ return { retired, interrupted, leftovers };
3212
3312
  }
3213
3313
  function readSkillDescription(text) {
3214
3314
  const frontmatter = normalizeText(text).match(/^---\n([\s\S]*?)\n---/u)?.[1];
@@ -3287,44 +3387,153 @@ function buildAgentNotice(source, skills, dryRun, changedCount) {
3287
3387
  /**
3288
3388
  * Write a guidance release into a project. Files IWSDK wrote and nobody edited
3289
3389
  * are replaced; edited files and files IWSDK does not own are reported and left
3290
- * alone unless `force` is set; retired IWSDK files are removed.
3390
+ * alone unless `force` is set; retired IWSDK files are removed once what
3391
+ * replaces them is in place. Missing units are created unless `onlyExisting`
3392
+ * is set (see there).
3291
3393
  */
3292
- async function syncAgentGuidance({ projectRoot, source, tools = [...GUIDANCE_TOOLS], force = false, dryRun = false, }) {
3394
+ async function syncAgentGuidance({ projectRoot, source, tools = [...GUIDANCE_TOOLS], force = false, dryRun = false, onlyExisting = false, }) {
3293
3395
  const writer = createWriter(projectRoot, dryRun);
3294
- const pruned = await pruneRetiredUnits(source, tools, writer);
3396
+ const { retired, interrupted, leftovers } = await findRetiredUnits(source, tools, writer);
3397
+ const units = selectedUnits(source.manifest, tools);
3398
+ const shipped = new Set(source.manifest.units.map((unit) => unit.path));
3399
+ const selected = new Map(units.map((unit) => [unit.path, unit.kind]));
3400
+ // A successor for a coding tool the project does not use is not this
3401
+ // project's, and settings replace no guidance (permissions follow the
3402
+ // skills); one this release does not ship can never be written.
3403
+ const counts = (successor) => shipped.has(successor)
3404
+ ? (selected.get(successor) ?? 'claude-settings') !== 'claude-settings'
3405
+ : true;
3406
+ // Retired units IWSDK wrote and nobody edited are replaced: removed once
3407
+ // the units that replace them are in place. `onlyExisting` replaces only
3408
+ // the ones the release names successors for, and keeps the rest.
3409
+ const replacing = new Map();
3410
+ for (const unit of retired) {
3411
+ const successors = source.manifest.successors?.[unit.path];
3412
+ if (unit.ownership !== 'modified' && (successors || !onlyExisting)) {
3413
+ replacing.set(unit.path, (successors ?? []).filter(counts));
3414
+ }
3415
+ }
3416
+ const claudeImport = units.find((unit) => unit.kind === 'claude-import');
3417
+ const migratesClaude = onlyExisting &&
3418
+ claudeImport != null &&
3419
+ (await holdsLegacyClaudeGuidance(claudeImport, source, projectRoot));
3420
+ // What `onlyExisting` may add: the successors of the guidance this run
3421
+ // replaces, and folders a killed sync was replacing.
3422
+ const additions = new Set([
3423
+ ...[...replacing.values()].flat(),
3424
+ ...(migratesClaude ? [ROOT_BLOCK] : []),
3425
+ ...interrupted,
3426
+ ]);
3427
+ const create = (unit) => !onlyExisting || additions.has(unit.path);
3295
3428
  const results = [];
3429
+ const resultsByUnit = new Map();
3430
+ // In the project once this run is done (in a dry run, once it would be).
3431
+ const present = (unitPath) => {
3432
+ const result = resultsByUnit.get(unitPath);
3433
+ return result !== undefined && result.reason !== 'missing';
3434
+ };
3435
+ // AGENTS.md holds the iwsdk-agent-guidance block once this run is done: not
3436
+ // when it is missing, holds edited guidance from before the block, or has
3437
+ // broken markers.
3438
+ const holdsRootBlock = () => {
3439
+ const reason = resultsByUnit.get(ROOT_BLOCK)?.reason;
3440
+ return (present(ROOT_BLOCK) &&
3441
+ reason !== 'legacy-modified' &&
3442
+ reason !== 'malformed-block');
3443
+ };
3296
3444
  const installedSkills = new Set();
3297
- const units = selectedUnits(source.manifest, tools);
3298
- // Settings last: they grant the skills this run installed.
3299
- for (const unit of [
3300
- ...units.filter((candidate) => candidate.kind !== 'claude-settings'),
3301
- ...units.filter((candidate) => candidate.kind === 'claude-settings'),
3302
- ]) {
3445
+ // The CLAUDE.md import after the AGENTS.md block it points at. Settings
3446
+ // last, once the skills and retired units are settled.
3447
+ const position = (unit) => unit.kind === 'claude-import' ? 1 : unit.kind === 'claude-settings' ? 2 : 0;
3448
+ for (const unit of [...units].sort((left, right) => position(left) - position(right))) {
3449
+ let result;
3303
3450
  switch (unit.kind) {
3304
- case 'directory': {
3305
- const result = await syncDirectoryUnit(unit, source, writer, force);
3451
+ case 'directory':
3452
+ result = await syncDirectoryUnit(unit, source, writer, force, create(unit));
3306
3453
  if (unit.path.startsWith('.claude/') &&
3307
3454
  (result.action === 'created' || result.action === 'updated')) {
3308
3455
  installedSkills.add(path.posix.basename(unit.path));
3309
3456
  }
3310
- results.push(result);
3311
3457
  break;
3312
- }
3313
3458
  case 'file':
3314
- results.push(await syncFileUnit(unit, source, writer, force));
3459
+ result = await syncFileUnit(unit, source, writer, force, create(unit));
3315
3460
  break;
3316
3461
  case 'block':
3317
- results.push(await syncBlockUnit(unit, source, writer, force));
3462
+ result = await syncBlockUnit(unit, source, writer, force, create(unit));
3318
3463
  break;
3319
3464
  case 'claude-import':
3320
- results.push(await syncClaudeImport(unit, source, writer, force));
3465
+ result = await syncClaudeImport(unit, source, writer, force, create(unit), !onlyExisting || holdsRootBlock());
3321
3466
  break;
3322
3467
  case 'claude-settings':
3323
- results.push(await syncClaudeSettings$1(unit, source, writer, installedSkills, pruned.removedSkills, force));
3324
- break;
3468
+ continue;
3325
3469
  }
3470
+ results.push(result);
3471
+ resultsByUnit.set(unit.path, result);
3326
3472
  }
3327
- results.push(...pruned.results);
3473
+ const removals = [];
3474
+ const retiredResults = [];
3475
+ for (const unit of retired) {
3476
+ const successors = replacing.get(unit.path);
3477
+ const result = { path: unit.path, kind: unit.kind };
3478
+ if (unit.ownership === 'modified') {
3479
+ // A retired IWSDK unit the developer edited: keep it, but say so.
3480
+ retiredResults.push({ ...result, action: 'skipped', reason: 'modified' });
3481
+ }
3482
+ else if (successors == null) {
3483
+ retiredResults.push({
3484
+ ...result,
3485
+ action: 'skipped',
3486
+ reason: 'retired',
3487
+ detail: `IWSDK ${source.manifest.version} no longer ships it and does not name a replacement; \`npx @iwsdk/cli@latest agents sync\` removes it.`,
3488
+ });
3489
+ }
3490
+ else if (!successors.every(present)) {
3491
+ // Never leave a project with less guidance than it had.
3492
+ retiredResults.push({
3493
+ ...result,
3494
+ action: 'skipped',
3495
+ reason: 'retired',
3496
+ detail: `It stays until ${successors.filter((successor) => !present(successor)).join(', ')} can be written in its place.`,
3497
+ });
3498
+ }
3499
+ else {
3500
+ removals.push(unit);
3501
+ retiredResults.push({
3502
+ ...result,
3503
+ action: 'removed',
3504
+ ...(successors.length > 0 ? { replacedBy: successors } : {}),
3505
+ });
3506
+ }
3507
+ }
3508
+ const settings = units.find((unit) => unit.kind === 'claude-settings');
3509
+ if (settings) {
3510
+ const claudeSkill = (unitPath) => unitPath.startsWith('.claude/skills/');
3511
+ const name = (unitPath) => path.posix.basename(unitPath);
3512
+ results.push(await syncClaudeSettings$1(settings, source, writer, {
3513
+ installed: installedSkills,
3514
+ removed: new Set(removals
3515
+ .filter((unit) => unit.kind === 'directory')
3516
+ .map((unit) => name(unit.path))),
3517
+ kept: new Set(retired
3518
+ .filter((unit) => claudeSkill(unit.path) && !removals.includes(unit))
3519
+ .map((unit) => name(unit.path))),
3520
+ replacedBy: new Map(removals
3521
+ .filter((unit) => claudeSkill(unit.path))
3522
+ .map((unit) => [
3523
+ name(unit.path),
3524
+ replacing.get(unit.path).filter(claudeSkill).map(name),
3525
+ ])),
3526
+ }, force, onlyExisting, create(settings)));
3527
+ }
3528
+ for (const unit of removals) {
3529
+ await writer.remove(unit.path);
3530
+ }
3531
+ // Last: until a folder that a killed sync moved aside is written again,
3532
+ // its moved-aside copy is what tells the next sync to write it.
3533
+ for (const leftover of leftovers) {
3534
+ await writer.remove(leftover);
3535
+ }
3536
+ results.push(...retiredResults);
3328
3537
  const skills = await summarizeSkills(source, tools);
3329
3538
  const changedCount = results.filter((result) => result.action !== 'unchanged' && result.action !== 'skipped').length;
3330
3539
  return {
@@ -14215,23 +14424,24 @@ const LOCKFILES = [
14215
14424
  ['package-lock.json', 'npm'],
14216
14425
  ['npm-shrinkwrap.json', 'npm'],
14217
14426
  ];
14218
- function declaredPackageManager(directory) {
14427
+ /** The `packageManager` field of the package.json in `directory`, or ''. */
14428
+ function packageManagerField(directory) {
14219
14429
  try {
14220
14430
  const manifest = JSON.parse(readFileSync(path.join(directory, 'package.json'), 'utf8'));
14221
- const name = typeof manifest.packageManager === 'string'
14222
- ? manifest.packageManager.split('@')[0]
14431
+ return typeof manifest.packageManager === 'string'
14432
+ ? manifest.packageManager
14223
14433
  : '';
14224
- return name === 'npm' ||
14225
- name === 'pnpm' ||
14226
- name === 'yarn' ||
14227
- name === 'bun'
14228
- ? name
14229
- : null;
14230
14434
  }
14231
14435
  catch {
14232
- return null;
14436
+ return '';
14233
14437
  }
14234
14438
  }
14439
+ function declaredPackageManager(directory) {
14440
+ const name = packageManagerField(directory).split('@')[0];
14441
+ return name === 'npm' || name === 'pnpm' || name === 'yarn' || name === 'bun'
14442
+ ? name
14443
+ : null;
14444
+ }
14235
14445
  /**
14236
14446
  * True for a pnpm-workspace.yaml that lists packages besides the directory
14237
14447
  * itself. Generated apps carry one with `packages: ['.']` whatever their
@@ -14317,6 +14527,34 @@ function findPackageManager(projectRoot) {
14317
14527
  current = parent;
14318
14528
  }
14319
14529
  }
14530
+ /**
14531
+ * True when the project installs with Yarn 2 or later, which takes its
14532
+ * registry from .yarnrc.yml rather than .npmrc: its `packageManager` field
14533
+ * says so, or, without one, it has a .yarnrc.yml or a Yarn 2+ lockfile.
14534
+ */
14535
+ function usesYarnBerry(projectRoot, info = findPackageManager(projectRoot)) {
14536
+ if (info.name !== 'yarn') {
14537
+ return false;
14538
+ }
14539
+ const directories = [path.resolve(projectRoot), info.root];
14540
+ for (const directory of directories) {
14541
+ const major = packageManagerField(directory).match(/^yarn@(\d+)/u)?.[1];
14542
+ if (major) {
14543
+ return Number(major) >= 2;
14544
+ }
14545
+ }
14546
+ if (directories.some((directory) => existsSync(path.join(directory, '.yarnrc.yml')))) {
14547
+ return true;
14548
+ }
14549
+ try {
14550
+ // Yarn 1 lockfiles have no __metadata block.
14551
+ return (info.lockfile != null &&
14552
+ /^__metadata:/mu.test(readFileSync(info.lockfile, 'utf8')));
14553
+ }
14554
+ catch {
14555
+ return false;
14556
+ }
14557
+ }
14320
14558
  /**
14321
14559
  * The @iwsdk/core version the lockfile resolves for this project, or null
14322
14560
  * when there is no lockfile this can read. Handles workspace lockfiles, where
@@ -14473,18 +14711,77 @@ function resolveAgentGuidanceMode(projectRoot, env = process.env) {
14473
14711
  /** The release recorded in the project's AGENTS.md guidance block. */
14474
14712
  function readGuidanceVersion(projectRoot) {
14475
14713
  try {
14476
- const agents = readFileSync(path.join(projectRoot, 'AGENTS.md'), 'utf8');
14477
- return (agents.match(/<!-- BEGIN iwsdk-agent-guidance version=(\S+) /u)?.[1] ??
14478
- null);
14714
+ return readGuidanceBlockVersion(readFileSync(path.join(projectRoot, 'AGENTS.md'), 'utf8'));
14479
14715
  }
14480
14716
  catch {
14481
14717
  return null;
14482
14718
  }
14483
14719
  }
14720
+ function isChange(entry) {
14721
+ return entry.action !== 'unchanged' && entry.action !== 'skipped';
14722
+ }
14723
+ function isMissing(entry) {
14724
+ return entry.reason === 'missing';
14725
+ }
14726
+ function formatList(items, limit) {
14727
+ const more = items.length - limit;
14728
+ return `${items.slice(0, limit).join(', ')}${more > 0 ? ` and ${more} more` : ''}`;
14729
+ }
14730
+ function formatMissingNotice(version, missing) {
14731
+ if (missing.length === 0) {
14732
+ return '';
14733
+ }
14734
+ const one = missing.length === 1;
14735
+ // Files first: a missing block or import matters more than one more skill.
14736
+ const ordered = [...missing].sort((left, right) => Number(left.kind === 'directory') - Number(right.kind === 'directory'));
14737
+ return `Not added: ${missing.length} part${one ? '' : 's'} of the IWSDK ${version} guidance that this project does not have (removed or replaced here, or new in this release): ${formatList(ordered.map((entry) => entry.detail ? `${entry.path} (${entry.detail})` : entry.path), 6)}. \`npx @iwsdk/cli@latest agents sync\` adds ${one ? 'it' : 'them'}.`;
14738
+ }
14739
+ /** The notice for a refresh that wrote `applied` and left `skipped` alone. */
14740
+ function formatRefreshNotice(previousVersion, version, applied, skipped) {
14741
+ const written = applied.filter((entry) => entry.action !== 'removed');
14742
+ const removed = applied.filter((entry) => entry.action === 'removed');
14743
+ const edited = skipped.filter((entry) => entry.reason !== 'retired');
14744
+ const kept = skipped.filter((entry) => entry.reason === 'retired');
14745
+ // What agents read: skill permissions in settings are not guidance.
14746
+ const reread = applied.filter((entry) => entry.kind !== 'claude-settings');
14747
+ const rootBlock = written.some((entry) => entry.path === 'AGENTS.md');
14748
+ const others = reread.length > (rootBlock ? 1 : 0);
14749
+ return [
14750
+ `[IWSDK] Updated coding-agent guidance${previousVersion && previousVersion !== version ? ` from ${previousVersion}` : ''} to the installed IWSDK ${version}${written.length > 0 ? `: ${written.map((entry) => entry.path).join(', ')}` : ''}.`,
14751
+ ...(removed.length > 0
14752
+ ? [
14753
+ `Removed retired guidance: ${removed
14754
+ .map((entry) => entry.replacedBy?.length
14755
+ ? `${entry.path} (replaced by ${formatList(entry.replacedBy, 3)})`
14756
+ : entry.path)
14757
+ .join(', ')}.`,
14758
+ ]
14759
+ : []),
14760
+ ...(reread.length > 0
14761
+ ? [
14762
+ `Agents: re-read ${rootBlock ? `the iwsdk-agent-guidance block in AGENTS.md${others ? ' and the other changed guidance' : ''}` : 'the changed guidance'} before continuing.`,
14763
+ ]
14764
+ : []),
14765
+ ...(edited.length > 0
14766
+ ? [
14767
+ `Left edited files alone: ${edited.map((entry) => entry.path).join(', ')} (\`npx @iwsdk/cli@latest agents sync --force\` replaces them).`,
14768
+ ]
14769
+ : []),
14770
+ ...kept.map((entry) => `Kept retired guidance ${entry.path}: ${entry.detail}`),
14771
+ ];
14772
+ }
14484
14773
  /**
14485
- * Called by `iwsdk dev up`/`restart`. When the installed @iwsdk/core ships
14486
- * different guidance than the project has, refresh the files nobody edited,
14487
- * or report it when refreshing is not safe. Never throws.
14774
+ * Called by `iwsdk dev up`/`restart`. Brings the guidance a project already
14775
+ * has up to the installed @iwsdk/core: files IWSDK wrote and nobody edited are
14776
+ * updated. A retired unit is replaced whole: removed, with its successors
14777
+ * written in the same run when the release names them (and kept otherwise),
14778
+ * so a refresh never leaves less guidance than it found. Apart from those
14779
+ * successors it never adds a skill, file, AGENTS.md block, CLAUDE.md import
14780
+ * or skill permission the project lacks, since the developer may have
14781
+ * removed it on purpose; units new in the release are not added either. A
14782
+ * refresh lists them, and `iwsdk agents sync` adds them. In CI, in warn mode,
14783
+ * or when node_modules disagrees with the lockfile it only reports. Returns
14784
+ * null when nothing needs refreshing; never throws.
14488
14785
  */
14489
14786
  async function refreshAgentGuidanceForDev(projectRoot, env = process.env) {
14490
14787
  try {
@@ -14509,6 +14806,7 @@ async function refreshAgentGuidanceForDev(projectRoot, env = process.env) {
14509
14806
  version,
14510
14807
  changed: [],
14511
14808
  skipped: [],
14809
+ missing: [],
14512
14810
  migrations: [],
14513
14811
  notice: `[IWSDK] This project has no IWSDK ${version} coding-agent guidance. Run \`npx @iwsdk/cli@latest agents sync\` to install it.`,
14514
14812
  };
@@ -14518,6 +14816,7 @@ async function refreshAgentGuidanceForDev(projectRoot, env = process.env) {
14518
14816
  source,
14519
14817
  tools,
14520
14818
  dryRun: true,
14819
+ onlyExisting: true,
14521
14820
  });
14522
14821
  if (!plan.changed) {
14523
14822
  return null;
@@ -14531,23 +14830,37 @@ async function refreshAgentGuidanceForDev(projectRoot, env = process.env) {
14531
14830
  : locked != null && installed != null && locked !== installed
14532
14831
  ? 'lockfile-mismatch'
14533
14832
  : undefined;
14534
- const changed = plan.results.filter((result) => result.action !== 'unchanged' && result.action !== 'skipped');
14833
+ const changed = plan.results.filter(isChange);
14535
14834
  if (reason) {
14835
+ const missing = plan.skipped.filter(isMissing);
14536
14836
  return {
14537
14837
  action: 'stale',
14538
14838
  previousVersion,
14539
14839
  version,
14540
14840
  reason,
14541
14841
  changed,
14542
- skipped: plan.skipped,
14842
+ skipped: plan.skipped.filter((entry) => !isMissing(entry)),
14843
+ missing,
14543
14844
  migrations: [],
14544
14845
  notice: reason === 'lockfile-mismatch'
14545
14846
  ? `[IWSDK] node_modules has @iwsdk/core ${installed} but the lockfile resolves ${locked}; agent guidance was not refreshed. Run your package manager's install.`
14546
- : `[IWSDK] Coding-agent guidance differs from the installed IWSDK ${version} in ${changed.length} place(s). Run \`npx @iwsdk/cli@latest agents sync\`.`,
14847
+ : [
14848
+ `[IWSDK] Coding-agent guidance differs from the installed IWSDK ${version} in ${changed.length} place(s). Run \`npx @iwsdk/cli@latest agents sync\`.`,
14849
+ formatMissingNotice(version, missing),
14850
+ ]
14851
+ .filter(Boolean)
14852
+ .join('\n'),
14547
14853
  };
14548
14854
  }
14549
- const result = await syncAgentGuidance({ projectRoot, source, tools });
14550
- const applied = result.results.filter((entry) => entry.action !== 'unchanged' && entry.action !== 'skipped');
14855
+ const result = await syncAgentGuidance({
14856
+ projectRoot,
14857
+ source,
14858
+ tools,
14859
+ onlyExisting: true,
14860
+ });
14861
+ const applied = result.results.filter(isChange);
14862
+ const skipped = result.skipped.filter((entry) => !isMissing(entry));
14863
+ const missing = result.skipped.filter(isMissing);
14551
14864
  const migrations = await materializeMigrations(projectRoot, migrationsBetween(previousVersion, version));
14552
14865
  const releaseNotes = previousVersion && previousVersion !== version
14553
14866
  ? await writeReleaseNotes(projectRoot, previousVersion, version)
@@ -14558,23 +14871,18 @@ async function refreshAgentGuidanceForDev(projectRoot, env = process.env) {
14558
14871
  ]
14559
14872
  .filter(Boolean)
14560
14873
  .join('\n');
14874
+ const missingNotice = formatMissingNotice(version, missing);
14561
14875
  return {
14562
14876
  action: 'refreshed',
14563
14877
  previousVersion,
14564
14878
  version,
14565
14879
  changed: applied,
14566
- skipped: result.skipped,
14880
+ skipped,
14881
+ missing,
14567
14882
  migrations,
14568
14883
  notice: [
14569
- `[IWSDK] Updated coding-agent guidance${previousVersion ? ` from ${previousVersion}` : ''} to the installed IWSDK ${version}: ${applied
14570
- .map((entry) => entry.path)
14571
- .join(', ')}.`,
14572
- 'Agents: re-read the iwsdk-agent-guidance block in AGENTS.md and any changed skill before continuing.',
14573
- ...(result.skipped.length > 0
14574
- ? [
14575
- `Left edited files alone: ${result.skipped.map((entry) => entry.path).join(', ')} (\`npx @iwsdk/cli@latest agents sync --force\` replaces them).`,
14576
- ]
14577
- : []),
14884
+ ...formatRefreshNotice(previousVersion, version, applied, skipped),
14885
+ ...(missingNotice ? [missingNotice] : []),
14578
14886
  ...(migrationNotice ? [migrationNotice] : []),
14579
14887
  ].join('\n'),
14580
14888
  };
@@ -32708,6 +33016,59 @@ function resolveMetaVrEntrypoint() {
32708
33016
  return null;
32709
33017
  }
32710
33018
  }
33019
+ // At most this many MetaVR processes run at once. Each event is its own
33020
+ // Node process that lives under a second; a caller that issues commands
33021
+ // faster than that (an agent's check script calling runCli in a loop, the MCP
33022
+ // server) would otherwise start one per command with nothing waiting for
33023
+ // them, and thousands piled up on a devserver.
33024
+ const MAX_RUNNING = 4;
33025
+ // Events waiting beyond this are dropped, so telemetry never grows without
33026
+ // bound when a caller outpaces MetaVR for a long time.
33027
+ const MAX_QUEUED = 1000;
33028
+ const queued = [];
33029
+ let running = 0;
33030
+ let exitHookInstalled = false;
33031
+ function launch(argv) {
33032
+ running++;
33033
+ let finished = false;
33034
+ const finish = () => {
33035
+ if (finished) {
33036
+ return;
33037
+ }
33038
+ finished = true;
33039
+ running--;
33040
+ drain();
33041
+ };
33042
+ try {
33043
+ const child = spawn(process.execPath, argv, {
33044
+ stdio: 'ignore',
33045
+ windowsHide: true,
33046
+ });
33047
+ child.on('error', finish);
33048
+ child.on('exit', finish);
33049
+ child.unref();
33050
+ }
33051
+ catch {
33052
+ finish();
33053
+ }
33054
+ }
33055
+ function drain() {
33056
+ while (running < MAX_RUNNING && queued.length > 0) {
33057
+ launch(queued.shift());
33058
+ }
33059
+ }
33060
+ /**
33061
+ * Starts up to MAX_RUNNING of the events still waiting and drops the rest.
33062
+ * Runs when the process exits, so a burst at the end neither floods the
33063
+ * machine nor keeps the process alive.
33064
+ */
33065
+ function flushQueuedTelemetry() {
33066
+ const remaining = queued.splice(0, MAX_RUNNING);
33067
+ queued.length = 0;
33068
+ for (const argv of remaining) {
33069
+ launch(argv);
33070
+ }
33071
+ }
32711
33072
  function metaVrTelemetry(args, clientVersion) {
32712
33073
  const entrypoint = resolveMetaVrEntrypoint();
32713
33074
  if (entrypoint == null) {
@@ -32717,12 +33078,15 @@ function metaVrTelemetry(args, clientVersion) {
32717
33078
  {
32718
33079
  globalArgs.push('--client-version', clientVersion);
32719
33080
  }
32720
- const child = spawn(process.execPath, [entrypoint, ...globalArgs, ...args], {
32721
- stdio: 'ignore',
32722
- windowsHide: true,
32723
- });
32724
- child.on('error', () => { });
32725
- child.unref();
33081
+ if (!exitHookInstalled) {
33082
+ exitHookInstalled = true;
33083
+ process.once('exit', flushQueuedTelemetry);
33084
+ }
33085
+ if (queued.length >= MAX_QUEUED) {
33086
+ return;
33087
+ }
33088
+ queued.push([entrypoint, ...globalArgs, ...args]);
33089
+ drain();
32726
33090
  }
32727
33091
  function reportToolCall(toolName, success, durationMs, error, sessionId, clientVersion) {
32728
33092
  const args = [
@@ -32746,7 +33110,7 @@ function reportToolCall(toolName, success, durationMs, error, sessionId, clientV
32746
33110
  metaVrTelemetry(args, clientVersion);
32747
33111
  }
32748
33112
 
32749
- const CLI_VERSION = "1.2.0-rc.0";
33113
+ const CLI_VERSION = "1.2.0-rc.1";
32750
33114
 
32751
33115
  /**
32752
33116
  * Copyright (c) Meta Platforms, Inc. and affiliates.
@@ -33696,15 +34060,39 @@ function bumpedSpec(current, to) {
33696
34060
  const operator = current.trim().match(/^[\^~]/u)?.[0] ?? '';
33697
34061
  return `${operator}${to}`;
33698
34062
  }
34063
+ /**
34064
+ * Thrown when the upgrade stops before writing anything; `code` becomes the
34065
+ * error code of the CLI's JSON failure.
34066
+ */
34067
+ class UpgradeError extends Error {
34068
+ constructor(message, code, details) {
34069
+ super(message);
34070
+ this.code = code;
34071
+ this.details = details;
34072
+ this.name = 'UpgradeError';
34073
+ }
34074
+ }
34075
+ /**
34076
+ * How to start a package manager. On Windows npm, pnpm and yarn are .cmd
34077
+ * shims, which Node starts only through a shell, so they get one command
34078
+ * line: a shell plus an argument list is deprecated (DEP0190). Callers pass
34079
+ * arguments that need no quoting.
34080
+ */
34081
+ function commandLine(command, args) {
34082
+ return process.platform === 'win32'
34083
+ ? { file: [command, ...args].join(' '), args: [], shell: true }
34084
+ : { file: command, args, shell: false };
34085
+ }
33699
34086
  /**
33700
34087
  * Install with the project's package manager. Output streams to stderr so
33701
34088
  * stdout stays a single JSON result.
33702
34089
  */
33703
34090
  function runInstall(packageManager, projectRoot) {
33704
- const result = spawnSync(packageManager, ['install'], {
34091
+ const command = commandLine(packageManager, ['install']);
34092
+ const result = spawnSync(command.file, command.args, {
33705
34093
  cwd: projectRoot,
33706
34094
  stdio: ['ignore', 2, 2],
33707
- shell: process.platform === 'win32',
34095
+ shell: command.shell,
33708
34096
  });
33709
34097
  if (result.error) {
33710
34098
  throw new Error(`${packageManager} could not start (${result.error.message}). Install ${packageManager} or enable it with Corepack.`);
@@ -33713,17 +34101,521 @@ function runInstall(packageManager, projectRoot) {
33713
34101
  throw new Error(`${packageManager} install failed (exit ${result.status ?? result.signal}).`);
33714
34102
  }
33715
34103
  }
34104
+ const execFileAsync = promisify(execFile);
34105
+ /**
34106
+ * How long one registry command may run (the lookups run in parallel) before
34107
+ * the upgrade goes on without the check.
34108
+ */
34109
+ const REGISTRY_TIMEOUT_MS = 20_000;
34110
+ /**
34111
+ * One retry, a second later, a 10 s response timeout and no check for a newer
34112
+ * npm. npm's defaults retry twice, 10 and 60 s apart, and wait 5 minutes for
34113
+ * a response, so a lookup without a network took over a minute to fail.
34114
+ */
34115
+ const NPM_FETCH_FLAGS = [
34116
+ '--fetch-retries=1',
34117
+ '--fetch-retry-mintimeout=1000',
34118
+ '--fetch-retry-maxtimeout=2000',
34119
+ '--fetch-timeout=10000',
34120
+ '--no-update-notifier',
34121
+ ];
34122
+ /** The same bounds for Yarn, which reads them from the environment. */
34123
+ const YARN_FETCH_ENV = { YARN_HTTP_RETRY: '1', YARN_HTTP_TIMEOUT: '10000' };
34124
+ /** Names a registry npm asks but would not print. */
34125
+ const UNNAMED_NPM_REGISTRY = "npm's configured registry";
34126
+ async function runRegistryClient(client, args, cwd, timeoutMs, env = {}) {
34127
+ const command = commandLine(client, args);
34128
+ const overrides = {
34129
+ // Corepack would ask before downloading a pinned version; nobody answers.
34130
+ COREPACK_ENABLE_DOWNLOAD_PROMPT: '0',
34131
+ ...(client === 'yarn' ? YARN_FETCH_ENV : {}),
34132
+ ...env,
34133
+ };
34134
+ // npm reads NPM_CONFIG_CACHE and npm_config_cache alike: an override
34135
+ // replaces every spelling of its name.
34136
+ const replaced = new Set(Object.keys(overrides).map((name) => name.toLowerCase()));
34137
+ const { stdout } = await execFileAsync(command.file, command.args, {
34138
+ cwd,
34139
+ shell: command.shell,
34140
+ timeout: timeoutMs,
34141
+ encoding: 'utf8',
34142
+ env: {
34143
+ ...Object.fromEntries(Object.entries(process.env).filter(([name]) => !replaced.has(name.toLowerCase()))),
34144
+ ...overrides,
34145
+ },
34146
+ });
34147
+ return stdout;
34148
+ }
34149
+ /** The JSON value npm printed, or each JSON line Yarn printed. */
34150
+ function jsonOutput(client, stdout) {
34151
+ return (client === 'npm' ? [stdout] : stdout.split(/\r?\n/u)).flatMap((chunk) => {
34152
+ try {
34153
+ return [JSON.parse(chunk)];
34154
+ }
34155
+ catch {
34156
+ return [];
34157
+ }
34158
+ });
34159
+ }
34160
+ /**
34161
+ * Hides the credentials a registry URL can carry, as npm does in its logs: up
34162
+ * to the last @ before the host, since a password can hold an unencoded @.
34163
+ */
34164
+ function redactUrls(text) {
34165
+ return text.replace(/\b([a-z][a-z\d+.-]*:\/\/)[^/\s]*@/giu, '$1***@');
34166
+ }
34167
+ /**
34168
+ * Why a registry command failed, and whether it means the registry does not
34169
+ * have the package: `version` when it has the package but not that version,
34170
+ * `package` when it has no such package (registries answer that too when you
34171
+ * may not access it). A missing npm, a network error or a timeout says
34172
+ * nothing about the release.
34173
+ */
34174
+ function registryFailure(client, error, timeoutMs) {
34175
+ const failure = error;
34176
+ if (failure.syscall?.startsWith('spawn')) {
34177
+ return {
34178
+ notFound: null,
34179
+ reason: `${client} could not start: ${failure.message}`,
34180
+ };
34181
+ }
34182
+ if (failure.killed) {
34183
+ return {
34184
+ notFound: null,
34185
+ reason: `${client} did not answer within ${timeoutMs / 1000} s`,
34186
+ };
34187
+ }
34188
+ const stdout = failure.stdout ?? '';
34189
+ const stderr = failure.stderr ?? '';
34190
+ // npm: {"error":{"code","summary"}}. Yarn: a {"type":"error","data"} line
34191
+ // per message, the first line of each data the gist.
34192
+ const messages = jsonOutput(client, stdout).flatMap((value) => isRecord(value) && isRecord(value.error)
34193
+ ? [`${String(value.error.code)}: ${String(value.error.summary)}`]
34194
+ : isRecord(value) && value.type === 'error'
34195
+ ? [String(value.data).split('\n')[0].trim()]
34196
+ : []);
34197
+ const output = `${stdout}\n${stderr}`;
34198
+ return {
34199
+ notFound: /\bETARGET\b|No match found for version|No matching version found/u.test(output)
34200
+ ? 'version'
34201
+ : /\bE404\b|Response Code: 404\b/u.test(output)
34202
+ ? 'package'
34203
+ : null,
34204
+ reason: redactUrls(messages.slice(0, 2).join('; ') ||
34205
+ stderr
34206
+ .split(/\r?\n/u)
34207
+ .find((line) => line.trim() !== '')
34208
+ ?.trim() ||
34209
+ (failure.message ?? String(error))),
34210
+ };
34211
+ }
34212
+ /** `name<separator>value` lines as a map; the first line for a name wins. */
34213
+ function settingLines(text, line, decode = (value) => value) {
34214
+ const values = new Map();
34215
+ for (const match of text.split(/\r?\n/u).map((entry) => entry.match(line))) {
34216
+ if (match && !values.has(match[1])) {
34217
+ try {
34218
+ const value = decode(match[2].trim());
34219
+ if (typeof value === 'string') {
34220
+ values.set(match[1], value);
34221
+ }
34222
+ }
34223
+ catch {
34224
+ // Not a value.
34225
+ }
34226
+ }
34227
+ }
34228
+ return values;
34229
+ }
34230
+ /**
34231
+ * The registry npm takes @iwsdk packages from, run with `npmArgs` and the
34232
+ * variables in `env` in `cwd`.
34233
+ */
34234
+ async function npmRegistry(cwd, npmArgs, env, timeoutMs) {
34235
+ const npm = (args) => runRegistryClient('npm', [...args, '--no-update-notifier', ...npmArgs], cwd, timeoutMs, env);
34236
+ let output;
34237
+ try {
34238
+ output = await npm(['config', 'get', '@iwsdk:registry', 'registry']);
34239
+ }
34240
+ catch (error) {
34241
+ const stderr = String(error.stderr ?? '');
34242
+ if (/\bENOWORKSPACES\b/u.test(stderr)) {
34243
+ // `npm config` does not run in an npm workspace package. `npm view`
34244
+ // does, with the workspace root's settings, as `npm install` there.
34245
+ return { url: null, scoped: false };
34246
+ }
34247
+ if (!/option is protected/u.test(stderr)) {
34248
+ throw error;
34249
+ }
34250
+ // npm 10 and 11 do not print a registry URL that has a password in it,
34251
+ // and npm view still uses it. `npm config ls` prints it with the
34252
+ // password hidden: the first uncommented line for a setting holds the
34253
+ // value in effect (publishConfig values follow).
34254
+ const shown = settingLines(await npm(['config', 'ls']).catch(() => ''), /^(\S+) = (".*")$/u, (value) => JSON.parse(value));
34255
+ const scoped = shown.get('@iwsdk:registry');
34256
+ return scoped
34257
+ ? { url: scoped, scoped: true }
34258
+ : { url: shown.get('registry') ?? null, scoped: false };
34259
+ }
34260
+ // key=value lines; @iwsdk:registry=undefined without a scope registry.
34261
+ const values = settingLines(output, /^([^=]+)=(.*)$/u);
34262
+ const scoped = values.get('@iwsdk:registry');
34263
+ return scoped && scoped !== 'undefined'
34264
+ ? { url: scoped, scoped: true }
34265
+ : { url: values.get('registry') ?? '', scoped: false };
34266
+ }
34267
+ /**
34268
+ * The registry Yarn 1 installs @iwsdk packages from, configured in `cwd`.
34269
+ * Yarn 1 reads .npmrc and .yarnrc files (the project's, the user's, and those
34270
+ * above the project) and npm_config_* and yarn_* variables, and takes an npm
34271
+ * setting over a Yarn one: the @iwsdk scope's registry, then the default
34272
+ * registry, then registry.yarnpkg.com. `yarn config get registry` prefers the
34273
+ * Yarn setting, so it can name another registry than the one Yarn installs
34274
+ * from.
34275
+ */
34276
+ async function yarnClassicRegistry(cwd, timeoutMs) {
34277
+ // {"type":"info","data":"yarn config"}, then {"type":"inspect","data":{…}};
34278
+ // the same for "npm config".
34279
+ const configs = new Map();
34280
+ let name = '';
34281
+ for (const value of jsonOutput('yarn', await runRegistryClient('yarn', ['config', 'list', '--json'], cwd, timeoutMs))) {
34282
+ if (isRecord(value) && value.type === 'info') {
34283
+ name = String(value.data);
34284
+ }
34285
+ else if (isRecord(value) &&
34286
+ value.type === 'inspect' &&
34287
+ isRecord(value.data)) {
34288
+ configs.set(name, value.data);
34289
+ }
34290
+ }
34291
+ const yarn = configs.get('yarn config');
34292
+ if (!yarn) {
34293
+ throw new Error('yarn config list printed no Yarn settings');
34294
+ }
34295
+ const npm = configs.get('npm config') ?? {};
34296
+ const setting = (config, key) => typeof config[key] === 'string' && config[key] !== ''
34297
+ ? config[key]
34298
+ : undefined;
34299
+ const scoped = setting(npm, '@iwsdk:registry') ?? setting(yarn, '@iwsdk:registry');
34300
+ return scoped
34301
+ ? { url: scoped, scoped: true }
34302
+ : {
34303
+ url: setting(npm, 'registry') ??
34304
+ setting(yarn, 'registry') ??
34305
+ 'https://registry.yarnpkg.com',
34306
+ scoped: false,
34307
+ };
34308
+ }
34309
+ /** The registry Yarn 2+ takes @iwsdk packages from, configured in `cwd`. */
34310
+ async function yarnBerryRegistry(cwd, timeoutMs) {
34311
+ const [scopes, server] = await Promise.all([
34312
+ runRegistryClient('yarn', ['config', 'get', 'npmScopes', '--json'], cwd, timeoutMs),
34313
+ runRegistryClient('yarn', ['config', 'get', 'npmRegistryServer'], cwd, timeoutMs),
34314
+ ]);
34315
+ const scoped = jsonOutput('npm', scopes).map((value) => isRecord(value) && isRecord(value.iwsdk)
34316
+ ? value.iwsdk.npmRegistryServer
34317
+ : undefined)[0];
34318
+ return typeof scoped === 'string' && scoped !== ''
34319
+ ? { url: scoped, scoped: true }
34320
+ : { url: server.trim(), scoped: false };
34321
+ }
34322
+ /** One package at `version`, from the registry; Yarn prints every field. */
34323
+ async function viewRelease({ client, cwd, npmArgs = [] }, name, version, fields, timeoutMs, env) {
34324
+ let stdout;
34325
+ try {
34326
+ stdout = await runRegistryClient(client, client === 'npm'
34327
+ ? [
34328
+ 'view',
34329
+ `${name}@${version}`,
34330
+ ...fields,
34331
+ '--json',
34332
+ ...NPM_FETCH_FLAGS,
34333
+ ...npmArgs,
34334
+ ]
34335
+ : ['npm', 'info', `${name}@${version}`, '--json'], cwd, timeoutMs, env);
34336
+ }
34337
+ catch (error) {
34338
+ const failure = registryFailure(client, error, timeoutMs);
34339
+ return failure.notFound
34340
+ ? {
34341
+ kind: 'missing',
34342
+ reason: failure.reason,
34343
+ packageNotFound: failure.notFound === 'package',
34344
+ }
34345
+ : { kind: 'failed', reason: failure.reason };
34346
+ }
34347
+ // npm prints the bare value when only one field has one. Yarn prints a
34348
+ // line per package and, for a version it does not have, the latest one.
34349
+ const manifest = jsonOutput(client, stdout)
34350
+ .map((value) => typeof value === 'string'
34351
+ ? { version: value }
34352
+ : isRecord(value) && (client === 'npm' || value.name === name)
34353
+ ? value
34354
+ : null)
34355
+ .find((value) => value != null);
34356
+ return manifest?.version === version
34357
+ ? { kind: 'found', manifest }
34358
+ : {
34359
+ kind: 'missing',
34360
+ reason: `No match found for version ${version}`,
34361
+ packageNotFound: false,
34362
+ };
34363
+ }
34364
+ /**
34365
+ * Removal of a temporary npm cache retries for up to 3 s: on Windows, an npm
34366
+ * that a timeout left running (it stops only the cmd.exe that started npm)
34367
+ * can keep the folder busy.
34368
+ */
34369
+ const CACHE_REMOVAL = {
34370
+ recursive: true,
34371
+ force: true,
34372
+ maxRetries: 5,
34373
+ retryDelay: 200,
34374
+ };
33716
34375
  /**
33717
- * Align the app's Three.js alias with the one the installed core uses,
33718
- * wherever the package manager reads it, and the app's `@types/three` with
33719
- * core's, so the app type-checks against one Three.js. Returns what changed
33720
- * and what the developer has to change by hand.
34376
+ * Runs `run` with a new, empty npm cache folder, removed afterwards or, if it
34377
+ * is still busy then, when the CLI exits. Until then, an interrupt removes it
34378
+ * too: SIGINT and SIGTERM are handled only when nothing else handles them,
34379
+ * and raised again, so they still end the CLI. Rejects when no folder can be
34380
+ * made.
33721
34381
  */
33722
- async function alignThree(projectRoot, packageJson, packageManagerRoot) {
34382
+ async function withEmptyNpmCache(run) {
34383
+ const cache = await mkdtemp(path.join(os.tmpdir(), 'iwsdk-npm-cache-'));
34384
+ const removeNow = () => {
34385
+ try {
34386
+ rmSync(cache, { recursive: true, force: true });
34387
+ }
34388
+ catch {
34389
+ // Left to the system's temporary-file cleanup.
34390
+ }
34391
+ };
34392
+ const interrupted = (signal) => {
34393
+ removeNow();
34394
+ process.kill(process.pid, signal);
34395
+ };
34396
+ const signals = ['SIGINT', 'SIGTERM'].filter((signal) => process.listenerCount(signal) === 0);
34397
+ process.once('exit', removeNow);
34398
+ for (const signal of signals) {
34399
+ process.once(signal, interrupted);
34400
+ }
34401
+ try {
34402
+ return await run(cache);
34403
+ }
34404
+ finally {
34405
+ const removed = await rm(cache, CACHE_REMOVAL).then(() => true, () => false);
34406
+ for (const signal of signals) {
34407
+ process.off(signal, interrupted);
34408
+ }
34409
+ if (removed) {
34410
+ process.off('exit', removeNow);
34411
+ }
34412
+ }
34413
+ }
34414
+ /**
34415
+ * Ask the registry for every package at `version` before anything is
34416
+ * written, the way the install will ask it (see `registryLookup`). Says which
34417
+ * registry it asks on `stderr`.
34418
+ */
34419
+ async function checkRegistry({ names, version, stderr, timeoutMs = REGISTRY_TIMEOUT_MS, ...lookup }) {
34420
+ // Which client names the registry: Yarn in any Yarn project.
34421
+ const namedBy = lookup.yarnClassicCwd
34422
+ ? 'yarn'
34423
+ : lookup.client;
34424
+ let configured;
34425
+ try {
34426
+ configured =
34427
+ lookup.client === 'yarn'
34428
+ ? await yarnBerryRegistry(lookup.cwd, timeoutMs)
34429
+ : lookup.yarnClassicCwd
34430
+ ? await yarnClassicRegistry(lookup.yarnClassicCwd, timeoutMs)
34431
+ : await npmRegistry(lookup.cwd, lookup.npmArgs ?? [], lookup.env ?? {}, timeoutMs);
34432
+ }
34433
+ catch (error) {
34434
+ return {
34435
+ status: 'unavailable',
34436
+ registry: null,
34437
+ reason: registryFailure(namedBy, error, timeoutMs).reason,
34438
+ };
34439
+ }
34440
+ if (configured.url != null && !/^https?:\/\//iu.test(configured.url)) {
34441
+ // Yarn 1 answers "undefined" for Yarn 2+ settings.
34442
+ return {
34443
+ status: 'unavailable',
34444
+ registry: null,
34445
+ reason: `${namedBy} reported no registry URL ("${redactUrls(configured.url)}")`,
34446
+ };
34447
+ }
34448
+ const registry = configured.url == null ? UNNAMED_NPM_REGISTRY : redactUrls(configured.url);
34449
+ // In a Yarn 1 project, npm asks the registry Yarn installs from.
34450
+ const env = {
34451
+ ...lookup.env,
34452
+ ...(lookup.yarnClassicCwd && configured.url
34453
+ ? { npm_config_registry: configured.url }
34454
+ : {}),
34455
+ };
34456
+ stderr.write(`[IWSDK] Checking ${registry} for IWSDK ${version} ...\n`);
34457
+ const view = (name, cache) => viewRelease(lookup, name, version, name === '@iwsdk/core'
34458
+ ? ['version', 'dependencies', 'versions']
34459
+ : ['version'], timeoutMs, cache ? { ...env, npm_config_cache: cache } : env);
34460
+ let results = await Promise.all(names.map((name) => view(name)));
34461
+ if (lookup.client === 'npm' &&
34462
+ results.some((result) => result.kind === 'missing')) {
34463
+ // Without a network, npm answers from its cache, and a package cached
34464
+ // before the release was published says the release does not exist. A
34465
+ // published version never changes, so a cached answer that has it stands;
34466
+ // one without it is asked again with an empty cache, which only the
34467
+ // registry can answer. Without an empty cache, it stays unchecked.
34468
+ const cached = results;
34469
+ results = await withEmptyNpmCache((cache) => Promise.all(cached.map((result, index) => result.kind === 'missing' ? view(names[index], cache) : result))).catch((error) => cached.map((result) => result.kind === 'missing'
34470
+ ? {
34471
+ kind: 'failed',
34472
+ reason: `${result.reason}, maybe from npm's cache, and no empty cache could be created to ask the registry: ${error instanceof Error ? error.message : String(error)}`,
34473
+ }
34474
+ : result));
34475
+ }
34476
+ const missing = [];
34477
+ let failure = null;
34478
+ let core;
34479
+ results.forEach((result, index) => {
34480
+ if (result.kind === 'found') {
34481
+ core = names[index] === '@iwsdk/core' ? result.manifest : core;
34482
+ }
34483
+ else if (result.kind === 'missing') {
34484
+ missing.push({
34485
+ spec: `${names[index]}@${version}`,
34486
+ reason: result.reason,
34487
+ packageNotFound: result.packageNotFound,
34488
+ });
34489
+ }
34490
+ else {
34491
+ failure ??= result.reason;
34492
+ }
34493
+ });
34494
+ if (missing.length > 0) {
34495
+ return { status: 'missing', registry, missing, scoped: configured.scoped };
34496
+ }
34497
+ if (failure != null) {
34498
+ return { status: 'unavailable', registry, reason: failure };
34499
+ }
34500
+ return { status: 'found', registry, core };
34501
+ }
34502
+ /** A .npmrc value as npm's ini parser reads it. */
34503
+ function iniValue(raw) {
34504
+ const value = raw.trim();
34505
+ if (value.length > 1 && value.startsWith("'") && value.endsWith("'")) {
34506
+ return value.slice(1, -1);
34507
+ }
34508
+ if (value.length > 1 && value.startsWith('"') && value.endsWith('"')) {
34509
+ try {
34510
+ return String(JSON.parse(value));
34511
+ }
34512
+ catch {
34513
+ return value;
34514
+ }
34515
+ }
34516
+ // Up to a ; or # comment; a backslash escapes either.
34517
+ return (value.match(/^(?:\\.?|[^\\;#])*/su)?.[0] ?? '')
34518
+ .replace(/\\([\\;#])/gu, '$1')
34519
+ .trim();
34520
+ }
34521
+ /**
34522
+ * The settings in the .npmrc in `directory` that pick the registry of @iwsdk
34523
+ * packages or authenticate with one: `registry`, `@iwsdk:registry` and the
34524
+ * `//<registry>/:<setting>` keys. Lines after a [section] hold no settings.
34525
+ */
34526
+ function npmrcRegistrySettings(directory) {
34527
+ const settings = new Map();
34528
+ let text;
34529
+ try {
34530
+ text = readFileSync(path.join(directory, '.npmrc'), 'utf8');
34531
+ }
34532
+ catch {
34533
+ return settings;
34534
+ }
34535
+ for (const line of text.split(/[\r\n]+/u)) {
34536
+ if (/^\s*\[/u.test(line)) {
34537
+ break;
34538
+ }
34539
+ const match = line.match(/^\s*([^\s;#=][^=]*)=(.*)$/u);
34540
+ const key = match?.[1].trim() ?? '';
34541
+ if (key === 'registry' ||
34542
+ key === '@iwsdk:registry' ||
34543
+ key.startsWith('//')) {
34544
+ settings.set(key, iniValue(match[2]));
34545
+ }
34546
+ }
34547
+ return settings;
34548
+ }
34549
+ /** The settings npm_config_* variables set, under npm's names for them. */
34550
+ function environmentSettings() {
34551
+ return new Set(Object.entries(process.env)
34552
+ .filter(([name, value]) => /^npm_config_./iu.test(name) && value !== '')
34553
+ .map(([name]) => {
34554
+ const key = name.slice('npm_config_'.length);
34555
+ return key.startsWith('//')
34556
+ ? key
34557
+ : key.replace(/(?!^)_/gu, '-').toLowerCase();
34558
+ }));
34559
+ }
34560
+ /**
34561
+ * How to ask the registry the install will use. The install runs in the
34562
+ * project directory.
34563
+ * - npm installs there with the workspace root's .npmrc and ignores the
34564
+ * project's own, so npm runs in the workspace root.
34565
+ * - pnpm and Yarn 1 merge the project's own .npmrc over the workspace root's,
34566
+ * setting by setting: a scope registry or a token only the root sets still
34567
+ * applies. When both set the registry or auth, npm runs in the workspace
34568
+ * root and gets the project's registry and auth settings as npm_config_*
34569
+ * variables, which npm takes over any .npmrc (unless the environment
34570
+ * already sets them, as pnpm and Yarn 1 then do too). Otherwise npm runs in
34571
+ * whichever directory sets them, the root when neither does. npm gets
34572
+ * --no-workspaces, so that it reads the .npmrc there and not that of a root
34573
+ * whose package.json declares workspaces.
34574
+ * - Yarn 1 also takes the registry from .yarnrc, so Yarn names it.
34575
+ * - Yarn 2+ reads only .yarnrc.yml, and is asked itself.
34576
+ */
34577
+ function registryLookup(projectRoot, info) {
34578
+ if (usesYarnBerry(projectRoot, info)) {
34579
+ return { client: 'yarn', cwd: info.root };
34580
+ }
34581
+ if (info.name !== 'pnpm' && info.name !== 'yarn') {
34582
+ return { client: 'npm', cwd: info.root };
34583
+ }
34584
+ const project = path.resolve(projectRoot);
34585
+ const own = npmrcRegistrySettings(project);
34586
+ const root = path.resolve(info.root) === project
34587
+ ? new Map()
34588
+ : npmrcRegistrySettings(info.root);
34589
+ const merge = own.size > 0 && root.size > 0;
34590
+ const inEnvironment = merge ? environmentSettings() : new Set();
34591
+ return {
34592
+ client: 'npm',
34593
+ cwd: own.size > 0 && !merge ? project : info.root,
34594
+ npmArgs: ['--no-workspaces'],
34595
+ ...(merge
34596
+ ? {
34597
+ env: Object.fromEntries([...own]
34598
+ .filter(([key]) => !inEnvironment.has(key))
34599
+ .map(([key, value]) => [`npm_config_${key}`, value])),
34600
+ }
34601
+ : {}),
34602
+ ...(info.name === 'yarn' ? { yarnClassicCwd: project } : {}),
34603
+ };
34604
+ }
34605
+ /** The dependencies of the @iwsdk/core installed in the project. */
34606
+ function installedCoreDependencies(projectRoot) {
33723
34607
  const corePackageJson = resolveInstalledCorePackageJson(projectRoot);
33724
- const coreDependencies = corePackageJson
34608
+ return corePackageJson
33725
34609
  ? JSON.parse(readFileSync(corePackageJson, 'utf8')).dependencies
33726
34610
  : undefined;
34611
+ }
34612
+ /**
34613
+ * Align the app's Three.js alias with the one core uses, wherever the
34614
+ * package manager reads it, and the app's `@types/three` with core's, so the
34615
+ * app type-checks against one Three.js. Returns what changed and what the
34616
+ * developer has to change by hand; `write: false` only plans.
34617
+ */
34618
+ async function alignThree(projectRoot, packageJson, packageManagerRoot, coreDependencies, write) {
33727
34619
  const coreThree = coreDependencies?.three;
33728
34620
  if (!coreThree) {
33729
34621
  return { bumps: [], manualSteps: [] };
@@ -33773,7 +34665,9 @@ async function alignThree(projectRoot, packageJson, packageManagerRoot) {
33773
34665
  const current = match?.[1]?.replace(/^['"]|['"]$/gu, '');
33774
34666
  if (match && current && current !== coreThree) {
33775
34667
  if (path.resolve(packageManagerRoot) === path.resolve(projectRoot)) {
33776
- await writeFile(workspaceFile, text.replace(match[0], match[0].replace(/three:[ \t]*\S+/u, `three: ${coreThree}`)));
34668
+ if (write) {
34669
+ await writeFile(workspaceFile, text.replace(match[0], match[0].replace(/three:[ \t]*\S+/u, `three: ${coreThree}`)));
34670
+ }
33777
34671
  bumps.push({
33778
34672
  field: 'pnpm-workspace.yaml overrides',
33779
34673
  name: 'three',
@@ -33843,13 +34737,16 @@ async function handleUpgrade(options, io) {
33843
34737
  if (!isRecord(packageJson)) {
33844
34738
  throw new Error('package.json must contain a JSON object.');
33845
34739
  }
33846
- const to = typeof options.to === 'string' ? options.to : CLI_VERSION;
33847
- if (semver$1.valid(to) == null) {
33848
- throw new Error(`--to must be an exact IWSDK version, got "${to}".`);
34740
+ const requested = typeof options.to === 'string' ? options.to : CLI_VERSION;
34741
+ // Normalized: v1.2.0 and 1.2.0 name the same release.
34742
+ const to = semver$1.valid(requested);
34743
+ if (to == null) {
34744
+ throw new Error(`--to must be an exact IWSDK version, got "${requested}".`);
33849
34745
  }
33850
34746
  const packages = [];
33851
34747
  const keptSpecs = [];
33852
34748
  const outsideRelease = [];
34749
+ const fromRegistry = new Set();
33853
34750
  let declaresIwsdk = false;
33854
34751
  for (const field of DEPENDENCY_FIELDS) {
33855
34752
  const dependencies = packageJson[field];
@@ -33868,8 +34765,11 @@ async function handleUpgrade(options, io) {
33868
34765
  // workspace:, file:, link:, catalog:, git and npm: aliases.
33869
34766
  keptSpecs.push(`${name}@${spec}`);
33870
34767
  }
33871
- else if (bumpedSpec(spec, to) !== spec) {
33872
- packages.push({ field, name, from: spec, to: bumpedSpec(spec, to) });
34768
+ else {
34769
+ fromRegistry.add(name);
34770
+ if (bumpedSpec(spec, to) !== spec) {
34771
+ packages.push({ field, name, from: spec, to: bumpedSpec(spec, to) });
34772
+ }
33873
34773
  }
33874
34774
  }
33875
34775
  }
@@ -33896,6 +34796,84 @@ async function handleUpgrade(options, io) {
33896
34796
  if (outsideRelease.length > 0) {
33897
34797
  manualSteps.push(`${outsideRelease.join(', ')} ${outsideRelease.length === 1 ? 'is' : 'are'} not part of the IWSDK release and ${outsideRelease.length === 1 ? 'was' : 'were'} left as declared.${guides.length > 0 ? ' If a migration guide lists one as retired, remove it as the guide says.' : ''}`);
33898
34798
  }
34799
+ // Before anything is written: a registry without the release (a mirror
34800
+ // that has not synced it) stops the upgrade here, not with package.json
34801
+ // half changed, and three follows the new core's even when nothing gets
34802
+ // installed. A registry that cannot be asked does not stop it; three is
34803
+ // then aligned with the core the install brings.
34804
+ const lookup = registryLookup(root, packageManagerInfo);
34805
+ const release = fromRegistry.size > 0
34806
+ ? await checkRegistry({
34807
+ names: [...fromRegistry],
34808
+ version: to,
34809
+ ...lookup,
34810
+ stderr: io.stderr,
34811
+ })
34812
+ : null;
34813
+ if (release?.status === 'missing') {
34814
+ // Packages missing at that version, then packages missing altogether,
34815
+ // which a registry also answers for packages you may not access.
34816
+ const specs = (entries) => entries.map((entry) => entry.spec).join(', ');
34817
+ const noVersion = release.missing.filter((entry) => !entry.packageNotFound);
34818
+ const noPackage = release.missing.filter((entry) => entry.packageNotFound);
34819
+ const absent = [
34820
+ noVersion.length > 0
34821
+ ? `${specs(noVersion)} (${noVersion[0].reason})`
34822
+ : '',
34823
+ noPackage.length > 0
34824
+ ? `${specs(noPackage)}, or you do not have permission to access ${noPackage.length === 1 ? 'it' : 'them'} (${noPackage[0].reason})`
34825
+ : '',
34826
+ ]
34827
+ .filter(Boolean)
34828
+ .join(', and does not have ');
34829
+ // npm, pnpm and Yarn 1 take the variable over .npmrc and .yarnrc; it does
34830
+ // not replace a registry set for the @iwsdk scope.
34831
+ const override = lookup.client === 'npm' && packageManager !== 'bun' && !release.scoped
34832
+ ? ' (the npm_config_registry environment variable overrides the configured one)'
34833
+ : '';
34834
+ throw new UpgradeError(`${release.registry} does not have ${absent}. Nothing was changed. A registry mirror can lag behind a release: upgrade once it has IWSDK ${to}, or point the project at a registry that does${override}.`, 'release_not_on_registry', {
34835
+ registry: release.registry,
34836
+ version: to,
34837
+ missing: release.missing.map((entry) => entry.spec),
34838
+ });
34839
+ }
34840
+ for (const bump of packages) {
34841
+ packageJson[bump.field][bump.name] = bump.to;
34842
+ }
34843
+ const publishedCore = release?.status === 'found' ? release.core : undefined;
34844
+ const three = await alignThree(root, packageJson, packageManagerInfo.root, publishedCore?.dependencies, !dryRun);
34845
+ packages.push(...three.bumps);
34846
+ manualSteps.push(...three.manualSteps);
34847
+ // True until three is aligned with the core the install brings.
34848
+ let threePending = false;
34849
+ if (release?.status === 'unavailable') {
34850
+ const unchecked = `Could not check ${release.registry ?? 'the registry'} for IWSDK ${to} (${release.reason})`;
34851
+ if (dryRun) {
34852
+ manualSteps.push(`${unchecked}: three alignment will be decided after install.`);
34853
+ }
34854
+ else {
34855
+ io.stderr.write(`[IWSDK] ${unchecked}; upgrading without it.\n`);
34856
+ threePending = true;
34857
+ if (!install) {
34858
+ manualSteps.push(`${unchecked}, so three was left as declared: run \`npx @iwsdk/cli@latest upgrade --to ${to}\` again, without --no-install, to align it with the new @iwsdk/core.`);
34859
+ }
34860
+ }
34861
+ }
34862
+ // three now follows core `to`. Without an install, nothing re-checks it
34863
+ // when a ^ or ~ range brings in a newer core instead.
34864
+ const coreSpec = DEPENDENCY_FIELDS.map((field) => isRecord(packageJson[field])
34865
+ ? packageJson[field]['@iwsdk/core']
34866
+ : undefined).find((spec) => typeof spec === 'string');
34867
+ const newerCore = !install &&
34868
+ publishedCore?.dependencies?.three &&
34869
+ Array.isArray(publishedCore.versions) &&
34870
+ coreSpec &&
34871
+ /^[\^~]/u.test(coreSpec.trim())
34872
+ ? semver$1.maxSatisfying(publishedCore.versions, coreSpec)
34873
+ : null;
34874
+ if (newerCore && semver$1.gt(newerCore, to)) {
34875
+ manualSteps.push(`@iwsdk/core ${coreSpec} also matches ${newerCore}, which an install can pick instead of ${to}, and three was aligned with ${to}. Pin @iwsdk/core to ${to}, or if ${newerCore} is installed, run \`npx @iwsdk/cli@latest upgrade --to ${newerCore}\`.`);
34876
+ }
33899
34877
  if (dryRun) {
33900
34878
  return createSuccess({
33901
34879
  projectRoot: root,
@@ -33915,9 +34893,6 @@ async function handleUpgrade(options, io) {
33915
34893
  manualSteps,
33916
34894
  });
33917
34895
  }
33918
- for (const bump of packages) {
33919
- packageJson[bump.field][bump.name] = bump.to;
33920
- }
33921
34896
  if (packages.length > 0) {
33922
34897
  await writeFile(packageJsonPath, formatJson(packageJson, rawPackageJson));
33923
34898
  }
@@ -33939,7 +34914,9 @@ async function handleUpgrade(options, io) {
33939
34914
  catch (error) {
33940
34915
  throw new Error([
33941
34916
  error instanceof Error ? error.message : String(error),
33942
- `package.json already lists IWSDK ${to}. Fix the error, run \`${packageManager} install\`${packageManagerInfo.root !== root ? ` (workspace root: ${packageManagerInfo.root})` : ''}, then \`npx @iwsdk/cli@latest agents sync\`.`,
34917
+ threePending
34918
+ ? `package.json already lists IWSDK ${to}. Fix the error, then run \`npx @iwsdk/cli@latest upgrade --to ${to}\` again: three still has to be aligned with the new @iwsdk/core.`
34919
+ : `package.json already lists IWSDK ${to}. Fix the error, run \`${packageManager} install\`${packageManagerInfo.root !== root ? ` (workspace root: ${packageManagerInfo.root})` : ''}, then \`npx @iwsdk/cli@latest agents sync\`.`,
33943
34920
  migrationNotice,
33944
34921
  ...manualSteps,
33945
34922
  ]
@@ -33952,10 +34929,14 @@ async function handleUpgrade(options, io) {
33952
34929
  let configIssues = [];
33953
34930
  if (install) {
33954
34931
  installOrExplain();
33955
- const three = await alignThree(root, packageJson, packageManagerInfo.root);
33956
- manualSteps.push(...three.manualSteps);
33957
- if (three.bumps.length > 0) {
33958
- packages.push(...three.bumps);
34932
+ // The installed core can still differ from the registry's: a file: or
34933
+ // workspace: core, or a ^ range that resolved past the target. And when
34934
+ // the registry could not be checked, this is the only alignment.
34935
+ const installedThree = await alignThree(root, packageJson, packageManagerInfo.root, installedCoreDependencies(root), true);
34936
+ threePending = false;
34937
+ manualSteps.push(...installedThree.manualSteps.filter((step) => !manualSteps.includes(step)));
34938
+ if (installedThree.bumps.length > 0) {
34939
+ packages.push(...installedThree.bumps);
33959
34940
  await writeFile(packageJsonPath, formatJson(packageJson, rawPackageJson));
33960
34941
  installOrExplain();
33961
34942
  }
@@ -34003,6 +34984,15 @@ async function handleUpgrade(options, io) {
34003
34984
  .join('; ')}. The migration guides and release notes say what replaced each setting.`);
34004
34985
  }
34005
34986
  }
34987
+ else if (threePending) {
34988
+ // The step that says to run upgrade again, which installs, aligns three
34989
+ // and syncs the guidance, stands for "install, then agents sync": that
34990
+ // would leave three as declared.
34991
+ guidance = {
34992
+ status: 'pending',
34993
+ message: 'Dependencies were not installed.',
34994
+ };
34995
+ }
34006
34996
  else {
34007
34997
  guidance = {
34008
34998
  status: 'pending',
@@ -34335,17 +35325,22 @@ function buildUpgradeCommandHelp() {
34335
35325
  'Usage: npx @iwsdk/cli@latest upgrade [--to <version>] [--dry-run] [--no-install] [--workspace <path>]',
34336
35326
  '',
34337
35327
  'Upgrades every @iwsdk/* dependency in the release group to this CLI release',
34338
- "(or --to), keeping ^ and ~ ranges, and installs with the project's package",
34339
- 'manager (found from the nearest lockfile). Then it aligns the Three.js alias',
34340
- 'with @iwsdk/core, refreshes the coding-agent guidance the project already has,',
34341
- 'and checks iwsdk.config.json against the new release. It writes to',
34342
- '.iwsdk/migrations/ (gitignored) a migration guide for each release boundary',
34343
- 'crossed and release-notes.md with every change in between. Run it with',
34344
- '@latest so the newest migration guides and release notes are available.',
35328
+ '(or --to), keeping ^ and ~ ranges, and aligns the Three.js alias with the new',
35329
+ '@iwsdk/core. First it asks the registry the install will use (from the npm or',
35330
+ 'Yarn settings the install reads; npm_config_registry overrides it for npm,',
35331
+ 'pnpm and Yarn 1 unless an @iwsdk scope registry is set) for the release, and',
35332
+ 'changes nothing if the release is missing there; if the registry cannot be',
35333
+ 'asked, it goes on and aligns Three.js after the install. Then it installs with',
35334
+ "the project's package manager (found from the nearest lockfile), refreshes the",
35335
+ 'coding-agent guidance the project already has, and checks iwsdk.config.json',
35336
+ 'against the new release. It writes to .iwsdk/migrations/ (gitignored) a',
35337
+ 'migration guide for each release boundary crossed and release-notes.md with',
35338
+ 'every change in between. Run it with @latest so the newest migration guides',
35339
+ 'and release notes are available.',
34345
35340
  '',
34346
35341
  'Options:',
34347
35342
  ' --to <version> target IWSDK version (default: this CLI version)',
34348
- ' --dry-run report the version change, migration guides and release-note count only',
35343
+ ' --dry-run report the planned changes without writing anything (asks the registry)',
34349
35344
  ' --no-install update package.json without installing',
34350
35345
  ' --workspace <path> project directory',
34351
35346
  ];
@@ -34564,7 +35559,9 @@ async function runCli(argv, io = {}) {
34564
35559
  })
34565
35560
  : error instanceof GuidanceSourceError
34566
35561
  ? createFailure(error.message, error.code)
34567
- : createFailure(error instanceof Error ? error.message : String(error));
35562
+ : error instanceof UpgradeError
35563
+ ? createFailure(error.message, error.code, error.details)
35564
+ : createFailure(error instanceof Error ? error.message : String(error));
34568
35565
  // Set by `dev up` when the guidance refresh ran before startup threw.
34569
35566
  const agentGuidance = error
34570
35567
  ?.agentGuidance;