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

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 (103) 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 +20 -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-metavr-native/SKILL.md +216 -0
  14. package/dist/agent-guidance/files/.agents/skills/iwsdk-metavr-native/assets/iwn-host.mjs +71 -0
  15. package/dist/agent-guidance/files/.agents/skills/iwsdk-native-xr-test/SKILL.md +1 -1
  16. package/dist/agent-guidance/files/.agents/skills/iwsdk-offline/SKILL.md +217 -0
  17. package/dist/agent-guidance/files/.agents/skills/iwsdk-offline/assets/offline.ts.template +99 -0
  18. package/dist/agent-guidance/files/.agents/skills/iwsdk-offline/assets/sw.js.template +241 -0
  19. package/dist/agent-guidance/files/.agents/skills/iwsdk-offline/assets/write-service-worker.mjs.template +72 -0
  20. package/dist/agent-guidance/files/.agents/skills/iwsdk-offline/references/build-step.md +71 -0
  21. package/dist/agent-guidance/files/.agents/skills/iwsdk-offline/references/page.md +70 -0
  22. package/dist/agent-guidance/files/.agents/skills/iwsdk-offline/references/service-worker.md +107 -0
  23. package/dist/agent-guidance/files/.agents/skills/iwsdk-offline/references/testing.md +57 -0
  24. package/dist/agent-guidance/files/.agents/skills/iwsdk-physics/SKILL.md +1 -1
  25. package/dist/agent-guidance/files/.agents/skills/iwsdk-physics/references/tuning-and-config.md +1 -0
  26. package/dist/agent-guidance/files/.agents/skills/iwsdk-physics/references/workflows.md +9 -3
  27. package/dist/agent-guidance/files/.agents/skills/iwsdk-pwa-packaging/SKILL.md +18 -3
  28. package/dist/agent-guidance/files/.agents/skills/iwsdk-pwa-packaging/references/manifest-and-icons.md +1 -1
  29. package/dist/agent-guidance/files/.agents/skills/iwsdk-pwa-packaging/references/troubleshooting.md +30 -0
  30. package/dist/agent-guidance/files/.agents/skills/iwsdk-ray/SKILL.md +1 -1
  31. package/dist/agent-guidance/files/.agents/skills/iwsdk-ui/SKILL.md +12 -5
  32. package/dist/agent-guidance/files/.agents/skills/iwsdk-upgrade/SKILL.md +1 -1
  33. package/dist/agent-guidance/files/.claude/agents/iwsdk-project-code-reviewer.md +1 -1
  34. package/dist/agent-guidance/files/.claude/rules/assets-and-manifest.md +1 -1
  35. package/dist/agent-guidance/files/.claude/rules/ecs-api.md +1 -1
  36. package/dist/agent-guidance/files/.claude/rules/scene-json.md +1 -1
  37. package/dist/agent-guidance/files/.claude/rules/uikitml.md +1 -1
  38. package/dist/agent-guidance/files/.claude/settings.json +2 -0
  39. package/dist/agent-guidance/files/.claude/skills/iwsdk-build-model/SKILL.md +1 -1
  40. package/dist/agent-guidance/files/.claude/skills/iwsdk-compose-scene/SKILL.md +1 -1
  41. package/dist/agent-guidance/files/.claude/skills/iwsdk-debug/SKILL.md +1 -1
  42. package/dist/agent-guidance/files/.claude/skills/iwsdk-depth-occlusion/SKILL.md +1 -1
  43. package/dist/agent-guidance/files/.claude/skills/iwsdk-dev/SKILL.md +20 -1
  44. package/dist/agent-guidance/files/.claude/skills/iwsdk-dev/references/api-reference.md +2 -1
  45. package/dist/agent-guidance/files/.claude/skills/iwsdk-dev/references/headless-rendering.md +15 -1
  46. package/dist/agent-guidance/files/.claude/skills/iwsdk-dev/references/iterate.md +7 -3
  47. package/dist/agent-guidance/files/.claude/skills/iwsdk-glasses-test/SKILL.md +1 -1
  48. package/dist/agent-guidance/files/.claude/skills/iwsdk-grab/SKILL.md +1 -1
  49. package/dist/agent-guidance/files/.claude/skills/iwsdk-hosting/SKILL.md +3 -2
  50. package/dist/agent-guidance/files/.claude/skills/iwsdk-metavr-native/SKILL.md +216 -0
  51. package/dist/agent-guidance/files/.claude/skills/iwsdk-metavr-native/assets/iwn-host.mjs +71 -0
  52. package/dist/agent-guidance/files/.claude/skills/iwsdk-native-xr-test/SKILL.md +1 -1
  53. package/dist/agent-guidance/files/.claude/skills/iwsdk-offline/SKILL.md +217 -0
  54. package/dist/agent-guidance/files/.claude/skills/iwsdk-offline/assets/offline.ts.template +99 -0
  55. package/dist/agent-guidance/files/.claude/skills/iwsdk-offline/assets/sw.js.template +241 -0
  56. package/dist/agent-guidance/files/.claude/skills/iwsdk-offline/assets/write-service-worker.mjs.template +72 -0
  57. package/dist/agent-guidance/files/.claude/skills/iwsdk-offline/references/build-step.md +71 -0
  58. package/dist/agent-guidance/files/.claude/skills/iwsdk-offline/references/page.md +70 -0
  59. package/dist/agent-guidance/files/.claude/skills/iwsdk-offline/references/service-worker.md +107 -0
  60. package/dist/agent-guidance/files/.claude/skills/iwsdk-offline/references/testing.md +57 -0
  61. package/dist/agent-guidance/files/.claude/skills/iwsdk-physics/SKILL.md +1 -1
  62. package/dist/agent-guidance/files/.claude/skills/iwsdk-physics/references/tuning-and-config.md +1 -0
  63. package/dist/agent-guidance/files/.claude/skills/iwsdk-physics/references/workflows.md +9 -3
  64. package/dist/agent-guidance/files/.claude/skills/iwsdk-pwa-packaging/SKILL.md +18 -3
  65. package/dist/agent-guidance/files/.claude/skills/iwsdk-pwa-packaging/references/manifest-and-icons.md +1 -1
  66. package/dist/agent-guidance/files/.claude/skills/iwsdk-pwa-packaging/references/troubleshooting.md +30 -0
  67. package/dist/agent-guidance/files/.claude/skills/iwsdk-ray/SKILL.md +1 -1
  68. package/dist/agent-guidance/files/.claude/skills/iwsdk-ui/SKILL.md +12 -5
  69. package/dist/agent-guidance/files/.claude/skills/iwsdk-upgrade/SKILL.md +1 -1
  70. package/dist/agent-guidance/files/.cursor/rules/assets-and-manifest.mdc +1 -1
  71. package/dist/agent-guidance/files/.cursor/rules/ecs-api.mdc +1 -1
  72. package/dist/agent-guidance/files/.cursor/rules/scene-json.mdc +1 -1
  73. package/dist/agent-guidance/files/.cursor/rules/uikitml.mdc +1 -1
  74. package/dist/agent-guidance/files/.github/instructions/assets-and-manifest.instructions.md +1 -1
  75. package/dist/agent-guidance/files/.github/instructions/ecs-api.instructions.md +1 -1
  76. package/dist/agent-guidance/files/.github/instructions/scene-json.instructions.md +1 -1
  77. package/dist/agent-guidance/files/.github/instructions/uikitml.instructions.md +1 -1
  78. package/dist/agent-guidance/files/AGENTS.md +10 -1
  79. package/dist/agent-guidance/files/public/scenes/AGENTS.md +1 -1
  80. package/dist/agent-guidance/files/public/ui/AGENTS.md +1 -1
  81. package/dist/agent-guidance/files/src/AGENTS.md +1 -1
  82. package/dist/agent-guidance/manifest.json +142 -12
  83. package/dist/agent-guidance.d.ts +31 -4
  84. package/dist/agent-guidance.d.ts.map +1 -1
  85. package/dist/agent-guidance.js +269 -60
  86. package/dist/agent-guidance.js.map +1 -1
  87. package/dist/cli.js +1128 -131
  88. package/dist/cli.js.map +1 -1
  89. package/dist/commands/upgrade.d.ts +87 -0
  90. package/dist/commands/upgrade.d.ts.map +1 -1
  91. package/dist/guidance-refresh.d.ts +23 -3
  92. package/dist/guidance-refresh.d.ts.map +1 -1
  93. package/dist/help.d.ts.map +1 -1
  94. package/dist/index.d.ts.map +1 -1
  95. package/dist/index.js +1128 -131
  96. package/dist/index.js.map +1 -1
  97. package/dist/metavr-telemetry.d.ts +6 -0
  98. package/dist/metavr-telemetry.d.ts.map +1 -1
  99. package/dist/package-manager.d.ts +6 -0
  100. package/dist/package-manager.d.ts.map +1 -1
  101. package/dist/release-notes.json +183 -0
  102. package/dist/version.d.ts +1 -1
  103. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import require$$1, { createHash as createHash$2, randomUUID } from 'crypto';
3
- import { existsSync, readFileSync, realpathSync, openSync, closeSync } from 'fs';
4
- import { readFile, lstat, readdir, rm, mkdir, writeFile, rename, realpath, rmdir, mkdtemp, unlink, appendFile } from 'fs/promises';
3
+ import { existsSync, readFileSync, realpathSync, openSync, closeSync, rmSync } from 'fs';
4
+ import { readFile, lstat, readdir, realpath, rm, mkdir, writeFile, rename, rmdir, mkdtemp, unlink, appendFile } from 'fs/promises';
5
5
  import { createRequire } from 'module';
6
6
  import path from 'path';
7
7
  import require$$7, { fileURLToPath, pathToFileURL } from 'url';
8
- import { execFileSync, spawn, spawnSync } from 'child_process';
8
+ import { execFileSync, spawn, execFile, spawnSync } from 'child_process';
9
9
  import require$$3$1, { createConnection } from 'net';
10
10
  import require$$0$3 from 'events';
11
11
  import require$$1$1 from 'https';
@@ -14,7 +14,7 @@ import require$$4 from 'tls';
14
14
  import require$$0$2 from 'stream';
15
15
  import require$$0 from 'zlib';
16
16
  import require$$0$1 from 'buffer';
17
- import require$$2 from 'util';
17
+ import require$$2, { promisify } from 'util';
18
18
  import process$2 from 'node:process';
19
19
  import { randomUUID as randomUUID$1 } from 'node:crypto';
20
20
  import os from 'os';
@@ -2384,7 +2384,7 @@ function getUnsupportedNodeMessage(version, requiredRange) {
2384
2384
  }
2385
2385
 
2386
2386
  const NODE_ENGINE = ">=20.19.0 <21.0.0-0 || >=22.12.0 <23.0.0-0 || >=24.0.0";
2387
- const CLI_VERSION = "1.2.0-rc.0";
2387
+ const CLI_VERSION = "1.2.0-rc.2";
2388
2388
 
2389
2389
  /**
2390
2390
  * Copyright (c) Meta Platforms, Inc. and affiliates.
@@ -2405,6 +2405,8 @@ const GUIDANCE_TOOLS = [
2405
2405
  // test/agent-guidance.test.ts checks both sides against a fresh render.
2406
2406
  const GUIDANCE_FORMAT = 1;
2407
2407
  const BLOCK_NAME = 'iwsdk-agent-guidance';
2408
+ /** The root AGENTS.md block unit, which a CLAUDE.md import points at. */
2409
+ const ROOT_BLOCK = 'AGENTS.md';
2408
2410
  const STAMP_LINE = /^<!-- iwsdk-agent-guidance version=(\S+) sha256=([0-9a-f]{64})(?: name=(\S+))? [^\n]*-->\r?\n?/mu;
2409
2411
  const BLOCK_PATTERN = new RegExp(`<!-- BEGIN ${BLOCK_NAME} version=(\\S+) sha256=([0-9a-f]{64}) -->\\n([\\s\\S]*?)<!-- END ${BLOCK_NAME} -->\\n?`, 'u');
2410
2412
  const BLOCK_BEGIN = new RegExp(`<!-- BEGIN ${BLOCK_NAME}\\b`, 'gu');
@@ -2454,6 +2456,10 @@ function directoryUnitHash(files) {
2454
2456
  function blockUnitHash(body) {
2455
2457
  return sha256(withTrailingNewline(normalizeText(body)));
2456
2458
  }
2459
+ /** The release stamped on the iwsdk-agent-guidance block in `text`, if any. */
2460
+ function readGuidanceBlockVersion(text) {
2461
+ return normalizeText(text).match(BLOCK_PATTERN)?.[1] ?? null;
2462
+ }
2457
2463
  function isTextFile(name) {
2458
2464
  return !/\.(png|jpe?g|webp|gif|glb|mp3|ktx2)$/iu.test(name);
2459
2465
  }
@@ -2516,6 +2522,12 @@ async function loadGuidanceSource(root, origin = 'explicit') {
2516
2522
  assertRelativeUnitPath(file);
2517
2523
  }
2518
2524
  }
2525
+ for (const [retired, successors] of Object.entries(manifest.successors ?? {})) {
2526
+ assertRelativeUnitPath(retired);
2527
+ for (const successor of successors) {
2528
+ assertRelativeUnitPath(successor);
2529
+ }
2530
+ }
2519
2531
  return { root, manifest, origin };
2520
2532
  }
2521
2533
  function bundledGuidanceRoot() {
@@ -2618,11 +2630,14 @@ async function isSameFile(first, second) {
2618
2630
  return false;
2619
2631
  }
2620
2632
  }
2621
- /** Temporary siblings a sync left behind when it was killed mid-swap. */
2622
- const TEMPORARY_SIBLING = /^\..+\.iwsdk-(?:new|old)-(\d+)-(\d+)$/u;
2633
+ /**
2634
+ * Temporary siblings a sync left behind when it was killed mid-swap: the
2635
+ * name they stand in for, `new` or `old`, the process id and the time.
2636
+ */
2637
+ const TEMPORARY_SIBLING = /^\.(.+)\.iwsdk-(new|old)-(\d+)-(\d+)$/u;
2623
2638
  /** A temporary sibling that a sync running right now may still need. */
2624
2639
  function isInUse(name) {
2625
- const [, pid, createdAt] = TEMPORARY_SIBLING.exec(name) ?? [];
2640
+ const [, , , pid, createdAt] = TEMPORARY_SIBLING.exec(name) ?? [];
2626
2641
  if (Date.now() - Number(createdAt) < 10 * 60_000) {
2627
2642
  return true;
2628
2643
  }
@@ -2779,6 +2794,19 @@ function replacementResult(unit, ownership, force) {
2779
2794
  }
2780
2795
  return null;
2781
2796
  }
2797
+ /**
2798
+ * A unit that `onlyExisting` left out because the project does not have it.
2799
+ * `lacks` names what an existing file is missing.
2800
+ */
2801
+ function missingResult(unit, unitPath = unit.path, lacks) {
2802
+ return {
2803
+ path: unitPath,
2804
+ kind: unit.kind,
2805
+ action: 'skipped',
2806
+ reason: 'missing',
2807
+ ...(lacks ? { detail: lacks } : {}),
2808
+ };
2809
+ }
2782
2810
  async function pathKind(filePath) {
2783
2811
  try {
2784
2812
  const stat = await lstat(filePath);
@@ -2791,7 +2819,13 @@ async function pathKind(filePath) {
2791
2819
  throw error;
2792
2820
  }
2793
2821
  }
2794
- async function syncDirectoryUnit(unit, source, writer, force) {
2822
+ /**
2823
+ * The unit syncs below take `create`: whether a unit the project lacks (a
2824
+ * missing file or folder, or a block or import missing from a file) may be
2825
+ * written. `onlyExisting` allows it only for units that replace guidance
2826
+ * this run retires, and for folders a killed sync was replacing.
2827
+ */
2828
+ async function syncDirectoryUnit(unit, source, writer, force, create) {
2795
2829
  const localRoot = path.join(writer.projectRoot, unit.path);
2796
2830
  const replace = async () => {
2797
2831
  const files = [];
@@ -2803,6 +2837,9 @@ async function syncDirectoryUnit(unit, source, writer, force) {
2803
2837
  const kind = await pathKind(localRoot);
2804
2838
  const localFiles = kind === 'directory' ? await readTree(localRoot) : null;
2805
2839
  if (kind === 'missing' || localFiles?.size === 0) {
2840
+ if (!create) {
2841
+ return missingResult(unit);
2842
+ }
2806
2843
  await replace();
2807
2844
  return { path: unit.path, kind: unit.kind, action: 'created' };
2808
2845
  }
@@ -2836,10 +2873,13 @@ async function syncDirectoryUnit(unit, source, writer, force) {
2836
2873
  }
2837
2874
  return result;
2838
2875
  }
2839
- async function syncFileUnit(unit, source, writer, force) {
2876
+ async function syncFileUnit(unit, source, writer, force, create) {
2840
2877
  const local = await readTextIfExists(path.join(writer.projectRoot, unit.path));
2841
2878
  const next = await readSourceFile(source, unit.path);
2842
2879
  if (local == null) {
2880
+ if (!create) {
2881
+ return missingResult(unit);
2882
+ }
2843
2883
  await writer.write(unit.path, next);
2844
2884
  return { path: unit.path, kind: unit.kind, action: 'created' };
2845
2885
  }
@@ -2853,10 +2893,13 @@ async function syncFileUnit(unit, source, writer, force) {
2853
2893
  }
2854
2894
  return result;
2855
2895
  }
2856
- async function syncBlockUnit(unit, source, writer, force) {
2896
+ async function syncBlockUnit(unit, source, writer, force, create) {
2857
2897
  const local = await readTextIfExists(path.join(writer.projectRoot, unit.path));
2858
2898
  const block = (await readSourceFile(source, unit.path)).toString('utf8');
2859
2899
  if (local == null) {
2900
+ if (!create) {
2901
+ return missingResult(unit);
2902
+ }
2860
2903
  await writer.write(unit.path, block);
2861
2904
  return { path: unit.path, kind: unit.kind, action: 'created' };
2862
2905
  }
@@ -2915,6 +2958,10 @@ async function syncBlockUnit(unit, source, writer, force) {
2915
2958
  reason: 'forced',
2916
2959
  };
2917
2960
  }
2961
+ if (!create) {
2962
+ // No IWSDK block: the developer removed it or replaced the file.
2963
+ return missingResult(unit, unit.path, 'no iwsdk-agent-guidance block');
2964
+ }
2918
2965
  await writer.write(unit.path, withLineEndings(`${withTrailingNewline(normalized)}${normalized.trim() ? '\n' : ''}${block}`, local));
2919
2966
  return {
2920
2967
  path: unit.path,
@@ -2923,23 +2970,54 @@ async function syncBlockUnit(unit, source, writer, force) {
2923
2970
  reason: 'appended',
2924
2971
  };
2925
2972
  }
2926
- async function syncClaudeImport(unit, source, writer, force) {
2973
+ /**
2974
+ * A root CLAUDE.md that holds the full guidance of a release before 1.0, as
2975
+ * that release wrote it. It is replaced with an `@AGENTS.md` import, so the
2976
+ * guidance it held now comes from the AGENTS.md block.
2977
+ */
2978
+ async function holdsLegacyClaudeGuidance(unit, source, projectRoot) {
2979
+ const filePath = path.join(projectRoot, unit.path);
2980
+ const rootFile = await readTextIfExists(filePath);
2981
+ if (rootFile == null ||
2982
+ (await isSameFile(filePath, path.join(projectRoot, ROOT_BLOCK)))) {
2983
+ return false;
2984
+ }
2985
+ const hash = fileUnitHash(rootFile);
2986
+ return (hash !==
2987
+ fileUnitHash((await readSourceFile(source, unit.path)).toString()) &&
2988
+ (source.manifest.legacy[unit.path]?.includes(hash) ?? false));
2989
+ }
2990
+ /**
2991
+ * `replaceLegacy`: whether a CLAUDE.md holding the full guidance of a release
2992
+ * before 1.0 may become an import, which needs the AGENTS.md block in place.
2993
+ */
2994
+ async function syncClaudeImport(unit, source, writer, force, create, replaceLegacy) {
2927
2995
  const rootFile = await readTextIfExists(path.join(writer.projectRoot, unit.path));
2928
2996
  const nestedFile = await readTextIfExists(path.join(writer.projectRoot, '.claude', 'CLAUDE.md'));
2929
2997
  const next = await readSourceFile(source, unit.path);
2930
2998
  if (rootFile == null && nestedFile == null) {
2999
+ if (!create) {
3000
+ return missingResult(unit);
3001
+ }
2931
3002
  await writer.write(unit.path, next);
2932
3003
  return { path: unit.path, kind: unit.kind, action: 'created' };
2933
3004
  }
2934
3005
  if (rootFile != null &&
2935
- (await isSameFile(path.join(writer.projectRoot, unit.path), path.join(writer.projectRoot, 'AGENTS.md')))) {
3006
+ (await isSameFile(path.join(writer.projectRoot, unit.path), path.join(writer.projectRoot, ROOT_BLOCK)))) {
2936
3007
  // CLAUDE.md is a link to AGENTS.md: Claude already reads the guidance.
2937
3008
  return { path: unit.path, kind: unit.kind, action: 'unchanged' };
2938
3009
  }
2939
- if (rootFile != null &&
2940
- fileUnitHash(rootFile) !== fileUnitHash(next.toString('utf8')) &&
2941
- source.manifest.legacy[unit.path]?.includes(fileUnitHash(rootFile))) {
3010
+ if (await holdsLegacyClaudeGuidance(unit, source, writer.projectRoot)) {
2942
3011
  // Releases before 1.0 put the full guidance in CLAUDE.md.
3012
+ if (!replaceLegacy) {
3013
+ return {
3014
+ path: unit.path,
3015
+ kind: unit.kind,
3016
+ action: 'skipped',
3017
+ reason: 'retired',
3018
+ 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.',
3019
+ };
3020
+ }
2943
3021
  await writer.write(unit.path, withLineEndings(next.toString('utf8'), rootFile));
2944
3022
  return {
2945
3023
  path: unit.path,
@@ -2972,6 +3050,10 @@ async function syncClaudeImport(unit, source, writer, force) {
2972
3050
  (nestedFile != null && /^@\.\.\/AGENTS\.md\s*$/mu.test(nestedFile))) {
2973
3051
  return { path: unit.path, kind: unit.kind, action: 'unchanged' };
2974
3052
  }
3053
+ if (!create) {
3054
+ // The import was removed, or CLAUDE.md replaced.
3055
+ return missingResult(unit, rootFile != null ? unit.path : '.claude/CLAUDE.md', 'no @AGENTS.md import');
3056
+ }
2975
3057
  if (rootFile != null) {
2976
3058
  await writer.write(unit.path, withLineEndings(`${withTrailingNewline(rootFile)}\n@AGENTS.md\n`, rootFile));
2977
3059
  return {
@@ -3005,9 +3087,12 @@ function ownedSkillNames(manifest) {
3005
3087
  }
3006
3088
  return names;
3007
3089
  }
3008
- async function syncClaudeSettings$1(unit, source, writer, installedSkills, retiredSkills, force) {
3090
+ async function syncClaudeSettings$1(unit, source, writer, skills, force, onlyExisting, create) {
3009
3091
  const filePath = path.join(writer.projectRoot, unit.path);
3010
3092
  const raw = await readTextIfExists(filePath);
3093
+ if (raw == null && !create) {
3094
+ return missingResult(unit);
3095
+ }
3011
3096
  let settings = {};
3012
3097
  if (raw != null) {
3013
3098
  let parsed;
@@ -3039,24 +3124,34 @@ async function syncClaudeSettings$1(unit, source, writer, installedSkills, retir
3039
3124
  const shipped = new Set(unit.skills ?? []);
3040
3125
  const owned = new Set([
3041
3126
  ...ownedSkillNames(source.manifest),
3042
- ...retiredSkills,
3127
+ ...skills.removed,
3043
3128
  ]);
3129
+ const skillOf = (rule) => typeof rule === 'string' ? rule.match(SKILL_PERMISSION)?.[1] : undefined;
3130
+ const allowed = new Set(allow.map(skillOf));
3044
3131
  // Grant skills this sync installed (all of them for a new settings file);
3045
3132
  // a permission the developer removed for an untouched skill stays removed.
3046
3133
  // Grant every shipped skill when the file is new, when --force is given, or
3047
3134
  // when no IWSDK skill permission is left (after `adapter prune`, say).
3135
+ // `onlyExisting` grants a skill only the permission of the retired skill it
3136
+ // replaces, and keeps the permissions of retired skills that stay.
3048
3137
  const grantAll = raw == null ||
3049
3138
  force ||
3050
3139
  !allow.some((rule) => {
3051
- const name = typeof rule === 'string'
3052
- ? rule.match(SKILL_PERMISSION)?.[1]
3053
- : undefined;
3140
+ const name = skillOf(rule);
3054
3141
  return name != null && owned.has(name);
3055
3142
  });
3056
- const grant = [...shipped].filter((name) => grantAll || installedSkills.has(name));
3143
+ const grant = onlyExisting && raw != null
3144
+ ? [...skills.replacedBy]
3145
+ .filter(([retired]) => allowed.has(retired))
3146
+ .flatMap(([, successors]) => successors)
3147
+ .filter((name) => shipped.has(name))
3148
+ : [...shipped].filter((name) => grantAll || skills.installed.has(name));
3057
3149
  const isRetired = (rule) => {
3058
- const name = typeof rule === 'string' ? rule.match(SKILL_PERMISSION)?.[1] : undefined;
3059
- return name != null && owned.has(name) && !shipped.has(name);
3150
+ const name = skillOf(rule);
3151
+ return (name != null &&
3152
+ owned.has(name) &&
3153
+ !shipped.has(name) &&
3154
+ !(onlyExisting && skills.kept.has(name)));
3060
3155
  };
3061
3156
  const nextAllow = allow.filter((rule) => !isRetired(rule));
3062
3157
  for (const name of grant) {
@@ -3134,7 +3229,14 @@ function toolsForPath(unitPath) {
3134
3229
  }
3135
3230
  return GUIDANCE_TOOLS;
3136
3231
  }
3137
- async function pruneRetiredUnits(source, tools, writer) {
3232
+ /**
3233
+ * IWSDK units in the project that this release no longer ships, for the
3234
+ * selected tools. Also returns the temporary siblings a killed sync left
3235
+ * behind, for the caller to delete once its writes are done, and the units
3236
+ * such a sync was replacing when it was killed (their folder is gone, so
3237
+ * they count as present).
3238
+ */
3239
+ async function findRetiredUnits(source, tools, writer) {
3138
3240
  const shipped = new Set(source.manifest.units.map((unit) => unit.path));
3139
3241
  const blocks = new Set(source.manifest.units
3140
3242
  .filter((unit) => unit.kind === 'block' || unit.kind === 'claude-import')
@@ -3172,8 +3274,9 @@ async function pruneRetiredUnits(source, tools, writer) {
3172
3274
  }
3173
3275
  }
3174
3276
  }
3175
- const results = [];
3176
- const removedSkills = new Set();
3277
+ const retired = [];
3278
+ const interrupted = new Set();
3279
+ const leftovers = [];
3177
3280
  for (const directory of ['.', ...PRUNE_ROOTS.map((root) => root.directory)]) {
3178
3281
  let entries;
3179
3282
  try {
@@ -3183,7 +3286,15 @@ async function pruneRetiredUnits(source, tools, writer) {
3183
3286
  continue;
3184
3287
  }
3185
3288
  for (const name of entries.filter((entry) => TEMPORARY_SIBLING.test(entry) && !isInUse(entry))) {
3186
- await writer.remove(path.posix.join(directory, name));
3289
+ const [, original, label] = TEMPORARY_SIBLING.exec(name);
3290
+ const originalPath = path.posix.join(directory, original);
3291
+ if (label === 'old' &&
3292
+ (await pathKind(path.join(writer.projectRoot, originalPath))) ===
3293
+ 'missing') {
3294
+ // Killed between the two renames of replaceDirectory.
3295
+ interrupted.add(originalPath);
3296
+ }
3297
+ leftovers.push(path.posix.join(directory, name));
3187
3298
  }
3188
3299
  }
3189
3300
  for (const [unitPath, kind] of candidates) {
@@ -3209,24 +3320,13 @@ async function pruneRetiredUnits(source, tools, writer) {
3209
3320
  continue;
3210
3321
  }
3211
3322
  const ownership = classify(localHash, undefined, stamp, source.manifest.legacy[unitPath], source.manifest.version);
3212
- if (ownership === 'managed' || ownership === 'legacy') {
3213
- await writer.remove(unitPath);
3214
- results.push({ path: unitPath, kind, action: 'removed' });
3215
- if (kind === 'directory') {
3216
- removedSkills.add(name);
3217
- }
3218
- }
3219
- else if (ownership === 'modified') {
3220
- // A retired IWSDK unit the developer edited: keep it, but say so.
3221
- results.push({
3222
- path: unitPath,
3223
- kind,
3224
- action: 'skipped',
3225
- reason: 'modified',
3226
- });
3323
+ if (ownership === 'managed' ||
3324
+ ownership === 'legacy' ||
3325
+ ownership === 'modified') {
3326
+ retired.push({ path: unitPath, kind, ownership });
3227
3327
  }
3228
3328
  }
3229
- return { results, removedSkills };
3329
+ return { retired, interrupted, leftovers };
3230
3330
  }
3231
3331
  function readSkillDescription(text) {
3232
3332
  const frontmatter = normalizeText(text).match(/^---\n([\s\S]*?)\n---/u)?.[1];
@@ -3305,44 +3405,153 @@ function buildAgentNotice(source, skills, dryRun, changedCount) {
3305
3405
  /**
3306
3406
  * Write a guidance release into a project. Files IWSDK wrote and nobody edited
3307
3407
  * are replaced; edited files and files IWSDK does not own are reported and left
3308
- * alone unless `force` is set; retired IWSDK files are removed.
3408
+ * alone unless `force` is set; retired IWSDK files are removed once what
3409
+ * replaces them is in place. Missing units are created unless `onlyExisting`
3410
+ * is set (see there).
3309
3411
  */
3310
- async function syncAgentGuidance({ projectRoot, source, tools = [...GUIDANCE_TOOLS], force = false, dryRun = false, }) {
3412
+ async function syncAgentGuidance({ projectRoot, source, tools = [...GUIDANCE_TOOLS], force = false, dryRun = false, onlyExisting = false, }) {
3311
3413
  const writer = createWriter(projectRoot, dryRun);
3312
- const pruned = await pruneRetiredUnits(source, tools, writer);
3414
+ const { retired, interrupted, leftovers } = await findRetiredUnits(source, tools, writer);
3415
+ const units = selectedUnits(source.manifest, tools);
3416
+ const shipped = new Set(source.manifest.units.map((unit) => unit.path));
3417
+ const selected = new Map(units.map((unit) => [unit.path, unit.kind]));
3418
+ // A successor for a coding tool the project does not use is not this
3419
+ // project's, and settings replace no guidance (permissions follow the
3420
+ // skills); one this release does not ship can never be written.
3421
+ const counts = (successor) => shipped.has(successor)
3422
+ ? (selected.get(successor) ?? 'claude-settings') !== 'claude-settings'
3423
+ : true;
3424
+ // Retired units IWSDK wrote and nobody edited are replaced: removed once
3425
+ // the units that replace them are in place. `onlyExisting` replaces only
3426
+ // the ones the release names successors for, and keeps the rest.
3427
+ const replacing = new Map();
3428
+ for (const unit of retired) {
3429
+ const successors = source.manifest.successors?.[unit.path];
3430
+ if (unit.ownership !== 'modified' && (successors || !onlyExisting)) {
3431
+ replacing.set(unit.path, (successors ?? []).filter(counts));
3432
+ }
3433
+ }
3434
+ const claudeImport = units.find((unit) => unit.kind === 'claude-import');
3435
+ const migratesClaude = onlyExisting &&
3436
+ claudeImport != null &&
3437
+ (await holdsLegacyClaudeGuidance(claudeImport, source, projectRoot));
3438
+ // What `onlyExisting` may add: the successors of the guidance this run
3439
+ // replaces, and folders a killed sync was replacing.
3440
+ const additions = new Set([
3441
+ ...[...replacing.values()].flat(),
3442
+ ...(migratesClaude ? [ROOT_BLOCK] : []),
3443
+ ...interrupted,
3444
+ ]);
3445
+ const create = (unit) => !onlyExisting || additions.has(unit.path);
3313
3446
  const results = [];
3447
+ const resultsByUnit = new Map();
3448
+ // In the project once this run is done (in a dry run, once it would be).
3449
+ const present = (unitPath) => {
3450
+ const result = resultsByUnit.get(unitPath);
3451
+ return result !== undefined && result.reason !== 'missing';
3452
+ };
3453
+ // AGENTS.md holds the iwsdk-agent-guidance block once this run is done: not
3454
+ // when it is missing, holds edited guidance from before the block, or has
3455
+ // broken markers.
3456
+ const holdsRootBlock = () => {
3457
+ const reason = resultsByUnit.get(ROOT_BLOCK)?.reason;
3458
+ return (present(ROOT_BLOCK) &&
3459
+ reason !== 'legacy-modified' &&
3460
+ reason !== 'malformed-block');
3461
+ };
3314
3462
  const installedSkills = new Set();
3315
- const units = selectedUnits(source.manifest, tools);
3316
- // Settings last: they grant the skills this run installed.
3317
- for (const unit of [
3318
- ...units.filter((candidate) => candidate.kind !== 'claude-settings'),
3319
- ...units.filter((candidate) => candidate.kind === 'claude-settings'),
3320
- ]) {
3463
+ // The CLAUDE.md import after the AGENTS.md block it points at. Settings
3464
+ // last, once the skills and retired units are settled.
3465
+ const position = (unit) => unit.kind === 'claude-import' ? 1 : unit.kind === 'claude-settings' ? 2 : 0;
3466
+ for (const unit of [...units].sort((left, right) => position(left) - position(right))) {
3467
+ let result;
3321
3468
  switch (unit.kind) {
3322
- case 'directory': {
3323
- const result = await syncDirectoryUnit(unit, source, writer, force);
3469
+ case 'directory':
3470
+ result = await syncDirectoryUnit(unit, source, writer, force, create(unit));
3324
3471
  if (unit.path.startsWith('.claude/') &&
3325
3472
  (result.action === 'created' || result.action === 'updated')) {
3326
3473
  installedSkills.add(path.posix.basename(unit.path));
3327
3474
  }
3328
- results.push(result);
3329
3475
  break;
3330
- }
3331
3476
  case 'file':
3332
- results.push(await syncFileUnit(unit, source, writer, force));
3477
+ result = await syncFileUnit(unit, source, writer, force, create(unit));
3333
3478
  break;
3334
3479
  case 'block':
3335
- results.push(await syncBlockUnit(unit, source, writer, force));
3480
+ result = await syncBlockUnit(unit, source, writer, force, create(unit));
3336
3481
  break;
3337
3482
  case 'claude-import':
3338
- results.push(await syncClaudeImport(unit, source, writer, force));
3483
+ result = await syncClaudeImport(unit, source, writer, force, create(unit), !onlyExisting || holdsRootBlock());
3339
3484
  break;
3340
3485
  case 'claude-settings':
3341
- results.push(await syncClaudeSettings$1(unit, source, writer, installedSkills, pruned.removedSkills, force));
3342
- break;
3486
+ continue;
3343
3487
  }
3488
+ results.push(result);
3489
+ resultsByUnit.set(unit.path, result);
3344
3490
  }
3345
- results.push(...pruned.results);
3491
+ const removals = [];
3492
+ const retiredResults = [];
3493
+ for (const unit of retired) {
3494
+ const successors = replacing.get(unit.path);
3495
+ const result = { path: unit.path, kind: unit.kind };
3496
+ if (unit.ownership === 'modified') {
3497
+ // A retired IWSDK unit the developer edited: keep it, but say so.
3498
+ retiredResults.push({ ...result, action: 'skipped', reason: 'modified' });
3499
+ }
3500
+ else if (successors == null) {
3501
+ retiredResults.push({
3502
+ ...result,
3503
+ action: 'skipped',
3504
+ reason: 'retired',
3505
+ detail: `IWSDK ${source.manifest.version} no longer ships it and does not name a replacement; \`npx @iwsdk/cli@latest agents sync\` removes it.`,
3506
+ });
3507
+ }
3508
+ else if (!successors.every(present)) {
3509
+ // Never leave a project with less guidance than it had.
3510
+ retiredResults.push({
3511
+ ...result,
3512
+ action: 'skipped',
3513
+ reason: 'retired',
3514
+ detail: `It stays until ${successors.filter((successor) => !present(successor)).join(', ')} can be written in its place.`,
3515
+ });
3516
+ }
3517
+ else {
3518
+ removals.push(unit);
3519
+ retiredResults.push({
3520
+ ...result,
3521
+ action: 'removed',
3522
+ ...(successors.length > 0 ? { replacedBy: successors } : {}),
3523
+ });
3524
+ }
3525
+ }
3526
+ const settings = units.find((unit) => unit.kind === 'claude-settings');
3527
+ if (settings) {
3528
+ const claudeSkill = (unitPath) => unitPath.startsWith('.claude/skills/');
3529
+ const name = (unitPath) => path.posix.basename(unitPath);
3530
+ results.push(await syncClaudeSettings$1(settings, source, writer, {
3531
+ installed: installedSkills,
3532
+ removed: new Set(removals
3533
+ .filter((unit) => unit.kind === 'directory')
3534
+ .map((unit) => name(unit.path))),
3535
+ kept: new Set(retired
3536
+ .filter((unit) => claudeSkill(unit.path) && !removals.includes(unit))
3537
+ .map((unit) => name(unit.path))),
3538
+ replacedBy: new Map(removals
3539
+ .filter((unit) => claudeSkill(unit.path))
3540
+ .map((unit) => [
3541
+ name(unit.path),
3542
+ replacing.get(unit.path).filter(claudeSkill).map(name),
3543
+ ])),
3544
+ }, force, onlyExisting, create(settings)));
3545
+ }
3546
+ for (const unit of removals) {
3547
+ await writer.remove(unit.path);
3548
+ }
3549
+ // Last: until a folder that a killed sync moved aside is written again,
3550
+ // its moved-aside copy is what tells the next sync to write it.
3551
+ for (const leftover of leftovers) {
3552
+ await writer.remove(leftover);
3553
+ }
3554
+ results.push(...retiredResults);
3346
3555
  const skills = await summarizeSkills(source, tools);
3347
3556
  const changedCount = results.filter((result) => result.action !== 'unchanged' && result.action !== 'skipped').length;
3348
3557
  return {
@@ -14233,23 +14442,24 @@ const LOCKFILES = [
14233
14442
  ['package-lock.json', 'npm'],
14234
14443
  ['npm-shrinkwrap.json', 'npm'],
14235
14444
  ];
14236
- function declaredPackageManager(directory) {
14445
+ /** The `packageManager` field of the package.json in `directory`, or ''. */
14446
+ function packageManagerField(directory) {
14237
14447
  try {
14238
14448
  const manifest = JSON.parse(readFileSync(path.join(directory, 'package.json'), 'utf8'));
14239
- const name = typeof manifest.packageManager === 'string'
14240
- ? manifest.packageManager.split('@')[0]
14449
+ return typeof manifest.packageManager === 'string'
14450
+ ? manifest.packageManager
14241
14451
  : '';
14242
- return name === 'npm' ||
14243
- name === 'pnpm' ||
14244
- name === 'yarn' ||
14245
- name === 'bun'
14246
- ? name
14247
- : null;
14248
14452
  }
14249
14453
  catch {
14250
- return null;
14454
+ return '';
14251
14455
  }
14252
14456
  }
14457
+ function declaredPackageManager(directory) {
14458
+ const name = packageManagerField(directory).split('@')[0];
14459
+ return name === 'npm' || name === 'pnpm' || name === 'yarn' || name === 'bun'
14460
+ ? name
14461
+ : null;
14462
+ }
14253
14463
  /**
14254
14464
  * True for a pnpm-workspace.yaml that lists packages besides the directory
14255
14465
  * itself. Generated apps carry one with `packages: ['.']` whatever their
@@ -14335,6 +14545,34 @@ function findPackageManager(projectRoot) {
14335
14545
  current = parent;
14336
14546
  }
14337
14547
  }
14548
+ /**
14549
+ * True when the project installs with Yarn 2 or later, which takes its
14550
+ * registry from .yarnrc.yml rather than .npmrc: its `packageManager` field
14551
+ * says so, or, without one, it has a .yarnrc.yml or a Yarn 2+ lockfile.
14552
+ */
14553
+ function usesYarnBerry(projectRoot, info = findPackageManager(projectRoot)) {
14554
+ if (info.name !== 'yarn') {
14555
+ return false;
14556
+ }
14557
+ const directories = [path.resolve(projectRoot), info.root];
14558
+ for (const directory of directories) {
14559
+ const major = packageManagerField(directory).match(/^yarn@(\d+)/u)?.[1];
14560
+ if (major) {
14561
+ return Number(major) >= 2;
14562
+ }
14563
+ }
14564
+ if (directories.some((directory) => existsSync(path.join(directory, '.yarnrc.yml')))) {
14565
+ return true;
14566
+ }
14567
+ try {
14568
+ // Yarn 1 lockfiles have no __metadata block.
14569
+ return (info.lockfile != null &&
14570
+ /^__metadata:/mu.test(readFileSync(info.lockfile, 'utf8')));
14571
+ }
14572
+ catch {
14573
+ return false;
14574
+ }
14575
+ }
14338
14576
  /**
14339
14577
  * The @iwsdk/core version the lockfile resolves for this project, or null
14340
14578
  * when there is no lockfile this can read. Handles workspace lockfiles, where
@@ -14491,18 +14729,77 @@ function resolveAgentGuidanceMode(projectRoot, env = process.env) {
14491
14729
  /** The release recorded in the project's AGENTS.md guidance block. */
14492
14730
  function readGuidanceVersion(projectRoot) {
14493
14731
  try {
14494
- const agents = readFileSync(path.join(projectRoot, 'AGENTS.md'), 'utf8');
14495
- return (agents.match(/<!-- BEGIN iwsdk-agent-guidance version=(\S+) /u)?.[1] ??
14496
- null);
14732
+ return readGuidanceBlockVersion(readFileSync(path.join(projectRoot, 'AGENTS.md'), 'utf8'));
14497
14733
  }
14498
14734
  catch {
14499
14735
  return null;
14500
14736
  }
14501
14737
  }
14738
+ function isChange(entry) {
14739
+ return entry.action !== 'unchanged' && entry.action !== 'skipped';
14740
+ }
14741
+ function isMissing(entry) {
14742
+ return entry.reason === 'missing';
14743
+ }
14744
+ function formatList(items, limit) {
14745
+ const more = items.length - limit;
14746
+ return `${items.slice(0, limit).join(', ')}${more > 0 ? ` and ${more} more` : ''}`;
14747
+ }
14748
+ function formatMissingNotice(version, missing) {
14749
+ if (missing.length === 0) {
14750
+ return '';
14751
+ }
14752
+ const one = missing.length === 1;
14753
+ // Files first: a missing block or import matters more than one more skill.
14754
+ const ordered = [...missing].sort((left, right) => Number(left.kind === 'directory') - Number(right.kind === 'directory'));
14755
+ 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'}.`;
14756
+ }
14757
+ /** The notice for a refresh that wrote `applied` and left `skipped` alone. */
14758
+ function formatRefreshNotice(previousVersion, version, applied, skipped) {
14759
+ const written = applied.filter((entry) => entry.action !== 'removed');
14760
+ const removed = applied.filter((entry) => entry.action === 'removed');
14761
+ const edited = skipped.filter((entry) => entry.reason !== 'retired');
14762
+ const kept = skipped.filter((entry) => entry.reason === 'retired');
14763
+ // What agents read: skill permissions in settings are not guidance.
14764
+ const reread = applied.filter((entry) => entry.kind !== 'claude-settings');
14765
+ const rootBlock = written.some((entry) => entry.path === 'AGENTS.md');
14766
+ const others = reread.length > (rootBlock ? 1 : 0);
14767
+ return [
14768
+ `[IWSDK] Updated coding-agent guidance${previousVersion && previousVersion !== version ? ` from ${previousVersion}` : ''} to the installed IWSDK ${version}${written.length > 0 ? `: ${written.map((entry) => entry.path).join(', ')}` : ''}.`,
14769
+ ...(removed.length > 0
14770
+ ? [
14771
+ `Removed retired guidance: ${removed
14772
+ .map((entry) => entry.replacedBy?.length
14773
+ ? `${entry.path} (replaced by ${formatList(entry.replacedBy, 3)})`
14774
+ : entry.path)
14775
+ .join(', ')}.`,
14776
+ ]
14777
+ : []),
14778
+ ...(reread.length > 0
14779
+ ? [
14780
+ `Agents: re-read ${rootBlock ? `the iwsdk-agent-guidance block in AGENTS.md${others ? ' and the other changed guidance' : ''}` : 'the changed guidance'} before continuing.`,
14781
+ ]
14782
+ : []),
14783
+ ...(edited.length > 0
14784
+ ? [
14785
+ `Left edited files alone: ${edited.map((entry) => entry.path).join(', ')} (\`npx @iwsdk/cli@latest agents sync --force\` replaces them).`,
14786
+ ]
14787
+ : []),
14788
+ ...kept.map((entry) => `Kept retired guidance ${entry.path}: ${entry.detail}`),
14789
+ ];
14790
+ }
14502
14791
  /**
14503
- * Called by `iwsdk dev up`/`restart`. When the installed @iwsdk/core ships
14504
- * different guidance than the project has, refresh the files nobody edited,
14505
- * or report it when refreshing is not safe. Never throws.
14792
+ * Called by `iwsdk dev up`/`restart`. Brings the guidance a project already
14793
+ * has up to the installed @iwsdk/core: files IWSDK wrote and nobody edited are
14794
+ * updated. A retired unit is replaced whole: removed, with its successors
14795
+ * written in the same run when the release names them (and kept otherwise),
14796
+ * so a refresh never leaves less guidance than it found. Apart from those
14797
+ * successors it never adds a skill, file, AGENTS.md block, CLAUDE.md import
14798
+ * or skill permission the project lacks, since the developer may have
14799
+ * removed it on purpose; units new in the release are not added either. A
14800
+ * refresh lists them, and `iwsdk agents sync` adds them. In CI, in warn mode,
14801
+ * or when node_modules disagrees with the lockfile it only reports. Returns
14802
+ * null when nothing needs refreshing; never throws.
14506
14803
  */
14507
14804
  async function refreshAgentGuidanceForDev(projectRoot, env = process.env) {
14508
14805
  try {
@@ -14527,6 +14824,7 @@ async function refreshAgentGuidanceForDev(projectRoot, env = process.env) {
14527
14824
  version,
14528
14825
  changed: [],
14529
14826
  skipped: [],
14827
+ missing: [],
14530
14828
  migrations: [],
14531
14829
  notice: `[IWSDK] This project has no IWSDK ${version} coding-agent guidance. Run \`npx @iwsdk/cli@latest agents sync\` to install it.`,
14532
14830
  };
@@ -14536,6 +14834,7 @@ async function refreshAgentGuidanceForDev(projectRoot, env = process.env) {
14536
14834
  source,
14537
14835
  tools,
14538
14836
  dryRun: true,
14837
+ onlyExisting: true,
14539
14838
  });
14540
14839
  if (!plan.changed) {
14541
14840
  return null;
@@ -14549,23 +14848,37 @@ async function refreshAgentGuidanceForDev(projectRoot, env = process.env) {
14549
14848
  : locked != null && installed != null && locked !== installed
14550
14849
  ? 'lockfile-mismatch'
14551
14850
  : undefined;
14552
- const changed = plan.results.filter((result) => result.action !== 'unchanged' && result.action !== 'skipped');
14851
+ const changed = plan.results.filter(isChange);
14553
14852
  if (reason) {
14853
+ const missing = plan.skipped.filter(isMissing);
14554
14854
  return {
14555
14855
  action: 'stale',
14556
14856
  previousVersion,
14557
14857
  version,
14558
14858
  reason,
14559
14859
  changed,
14560
- skipped: plan.skipped,
14860
+ skipped: plan.skipped.filter((entry) => !isMissing(entry)),
14861
+ missing,
14561
14862
  migrations: [],
14562
14863
  notice: reason === 'lockfile-mismatch'
14563
14864
  ? `[IWSDK] node_modules has @iwsdk/core ${installed} but the lockfile resolves ${locked}; agent guidance was not refreshed. Run your package manager's install.`
14564
- : `[IWSDK] Coding-agent guidance differs from the installed IWSDK ${version} in ${changed.length} place(s). Run \`npx @iwsdk/cli@latest agents sync\`.`,
14865
+ : [
14866
+ `[IWSDK] Coding-agent guidance differs from the installed IWSDK ${version} in ${changed.length} place(s). Run \`npx @iwsdk/cli@latest agents sync\`.`,
14867
+ formatMissingNotice(version, missing),
14868
+ ]
14869
+ .filter(Boolean)
14870
+ .join('\n'),
14565
14871
  };
14566
14872
  }
14567
- const result = await syncAgentGuidance({ projectRoot, source, tools });
14568
- const applied = result.results.filter((entry) => entry.action !== 'unchanged' && entry.action !== 'skipped');
14873
+ const result = await syncAgentGuidance({
14874
+ projectRoot,
14875
+ source,
14876
+ tools,
14877
+ onlyExisting: true,
14878
+ });
14879
+ const applied = result.results.filter(isChange);
14880
+ const skipped = result.skipped.filter((entry) => !isMissing(entry));
14881
+ const missing = result.skipped.filter(isMissing);
14569
14882
  const migrations = await materializeMigrations(projectRoot, migrationsBetween(previousVersion, version));
14570
14883
  const releaseNotes = previousVersion && previousVersion !== version
14571
14884
  ? await writeReleaseNotes(projectRoot, previousVersion, version)
@@ -14576,23 +14889,18 @@ async function refreshAgentGuidanceForDev(projectRoot, env = process.env) {
14576
14889
  ]
14577
14890
  .filter(Boolean)
14578
14891
  .join('\n');
14892
+ const missingNotice = formatMissingNotice(version, missing);
14579
14893
  return {
14580
14894
  action: 'refreshed',
14581
14895
  previousVersion,
14582
14896
  version,
14583
14897
  changed: applied,
14584
- skipped: result.skipped,
14898
+ skipped,
14899
+ missing,
14585
14900
  migrations,
14586
14901
  notice: [
14587
- `[IWSDK] Updated coding-agent guidance${previousVersion ? ` from ${previousVersion}` : ''} to the installed IWSDK ${version}: ${applied
14588
- .map((entry) => entry.path)
14589
- .join(', ')}.`,
14590
- 'Agents: re-read the iwsdk-agent-guidance block in AGENTS.md and any changed skill before continuing.',
14591
- ...(result.skipped.length > 0
14592
- ? [
14593
- `Left edited files alone: ${result.skipped.map((entry) => entry.path).join(', ')} (\`npx @iwsdk/cli@latest agents sync --force\` replaces them).`,
14594
- ]
14595
- : []),
14902
+ ...formatRefreshNotice(previousVersion, version, applied, skipped),
14903
+ ...(missingNotice ? [missingNotice] : []),
14596
14904
  ...(migrationNotice ? [migrationNotice] : []),
14597
14905
  ].join('\n'),
14598
14906
  };
@@ -32726,6 +33034,59 @@ function resolveMetaVrEntrypoint() {
32726
33034
  return null;
32727
33035
  }
32728
33036
  }
33037
+ // At most this many MetaVR processes run at once. Each event is its own
33038
+ // Node process that lives under a second; a caller that issues commands
33039
+ // faster than that (an agent's check script calling runCli in a loop, the MCP
33040
+ // server) would otherwise start one per command with nothing waiting for
33041
+ // them, and thousands piled up on a devserver.
33042
+ const MAX_RUNNING = 4;
33043
+ // Events waiting beyond this are dropped, so telemetry never grows without
33044
+ // bound when a caller outpaces MetaVR for a long time.
33045
+ const MAX_QUEUED = 1000;
33046
+ const queued = [];
33047
+ let running = 0;
33048
+ let exitHookInstalled = false;
33049
+ function launch(argv) {
33050
+ running++;
33051
+ let finished = false;
33052
+ const finish = () => {
33053
+ if (finished) {
33054
+ return;
33055
+ }
33056
+ finished = true;
33057
+ running--;
33058
+ drain();
33059
+ };
33060
+ try {
33061
+ const child = spawn(process.execPath, argv, {
33062
+ stdio: 'ignore',
33063
+ windowsHide: true,
33064
+ });
33065
+ child.on('error', finish);
33066
+ child.on('exit', finish);
33067
+ child.unref();
33068
+ }
33069
+ catch {
33070
+ finish();
33071
+ }
33072
+ }
33073
+ function drain() {
33074
+ while (running < MAX_RUNNING && queued.length > 0) {
33075
+ launch(queued.shift());
33076
+ }
33077
+ }
33078
+ /**
33079
+ * Starts up to MAX_RUNNING of the events still waiting and drops the rest.
33080
+ * Runs when the process exits, so a burst at the end neither floods the
33081
+ * machine nor keeps the process alive.
33082
+ */
33083
+ function flushQueuedTelemetry() {
33084
+ const remaining = queued.splice(0, MAX_RUNNING);
33085
+ queued.length = 0;
33086
+ for (const argv of remaining) {
33087
+ launch(argv);
33088
+ }
33089
+ }
32729
33090
  function metaVrTelemetry(args, clientVersion) {
32730
33091
  const entrypoint = resolveMetaVrEntrypoint();
32731
33092
  if (entrypoint == null) {
@@ -32735,12 +33096,15 @@ function metaVrTelemetry(args, clientVersion) {
32735
33096
  {
32736
33097
  globalArgs.push('--client-version', clientVersion);
32737
33098
  }
32738
- const child = spawn(process.execPath, [entrypoint, ...globalArgs, ...args], {
32739
- stdio: 'ignore',
32740
- windowsHide: true,
32741
- });
32742
- child.on('error', () => { });
32743
- child.unref();
33099
+ if (!exitHookInstalled) {
33100
+ exitHookInstalled = true;
33101
+ process.once('exit', flushQueuedTelemetry);
33102
+ }
33103
+ if (queued.length >= MAX_QUEUED) {
33104
+ return;
33105
+ }
33106
+ queued.push([entrypoint, ...globalArgs, ...args]);
33107
+ drain();
32744
33108
  }
32745
33109
  function reportToolCall(toolName, success, durationMs, error, sessionId, clientVersion) {
32746
33110
  const args = [
@@ -33712,15 +34076,39 @@ function bumpedSpec(current, to) {
33712
34076
  const operator = current.trim().match(/^[\^~]/u)?.[0] ?? '';
33713
34077
  return `${operator}${to}`;
33714
34078
  }
34079
+ /**
34080
+ * Thrown when the upgrade stops before writing anything; `code` becomes the
34081
+ * error code of the CLI's JSON failure.
34082
+ */
34083
+ class UpgradeError extends Error {
34084
+ constructor(message, code, details) {
34085
+ super(message);
34086
+ this.code = code;
34087
+ this.details = details;
34088
+ this.name = 'UpgradeError';
34089
+ }
34090
+ }
34091
+ /**
34092
+ * How to start a package manager. On Windows npm, pnpm and yarn are .cmd
34093
+ * shims, which Node starts only through a shell, so they get one command
34094
+ * line: a shell plus an argument list is deprecated (DEP0190). Callers pass
34095
+ * arguments that need no quoting.
34096
+ */
34097
+ function commandLine(command, args) {
34098
+ return process.platform === 'win32'
34099
+ ? { file: [command, ...args].join(' '), args: [], shell: true }
34100
+ : { file: command, args, shell: false };
34101
+ }
33715
34102
  /**
33716
34103
  * Install with the project's package manager. Output streams to stderr so
33717
34104
  * stdout stays a single JSON result.
33718
34105
  */
33719
34106
  function runInstall(packageManager, projectRoot) {
33720
- const result = spawnSync(packageManager, ['install'], {
34107
+ const command = commandLine(packageManager, ['install']);
34108
+ const result = spawnSync(command.file, command.args, {
33721
34109
  cwd: projectRoot,
33722
34110
  stdio: ['ignore', 2, 2],
33723
- shell: process.platform === 'win32',
34111
+ shell: command.shell,
33724
34112
  });
33725
34113
  if (result.error) {
33726
34114
  throw new Error(`${packageManager} could not start (${result.error.message}). Install ${packageManager} or enable it with Corepack.`);
@@ -33729,17 +34117,521 @@ function runInstall(packageManager, projectRoot) {
33729
34117
  throw new Error(`${packageManager} install failed (exit ${result.status ?? result.signal}).`);
33730
34118
  }
33731
34119
  }
34120
+ const execFileAsync = promisify(execFile);
34121
+ /**
34122
+ * How long one registry command may run (the lookups run in parallel) before
34123
+ * the upgrade goes on without the check.
34124
+ */
34125
+ const REGISTRY_TIMEOUT_MS = 20_000;
34126
+ /**
34127
+ * One retry, a second later, a 10 s response timeout and no check for a newer
34128
+ * npm. npm's defaults retry twice, 10 and 60 s apart, and wait 5 minutes for
34129
+ * a response, so a lookup without a network took over a minute to fail.
34130
+ */
34131
+ const NPM_FETCH_FLAGS = [
34132
+ '--fetch-retries=1',
34133
+ '--fetch-retry-mintimeout=1000',
34134
+ '--fetch-retry-maxtimeout=2000',
34135
+ '--fetch-timeout=10000',
34136
+ '--no-update-notifier',
34137
+ ];
34138
+ /** The same bounds for Yarn, which reads them from the environment. */
34139
+ const YARN_FETCH_ENV = { YARN_HTTP_RETRY: '1', YARN_HTTP_TIMEOUT: '10000' };
34140
+ /** Names a registry npm asks but would not print. */
34141
+ const UNNAMED_NPM_REGISTRY = "npm's configured registry";
34142
+ async function runRegistryClient(client, args, cwd, timeoutMs, env = {}) {
34143
+ const command = commandLine(client, args);
34144
+ const overrides = {
34145
+ // Corepack would ask before downloading a pinned version; nobody answers.
34146
+ COREPACK_ENABLE_DOWNLOAD_PROMPT: '0',
34147
+ ...(client === 'yarn' ? YARN_FETCH_ENV : {}),
34148
+ ...env,
34149
+ };
34150
+ // npm reads NPM_CONFIG_CACHE and npm_config_cache alike: an override
34151
+ // replaces every spelling of its name.
34152
+ const replaced = new Set(Object.keys(overrides).map((name) => name.toLowerCase()));
34153
+ const { stdout } = await execFileAsync(command.file, command.args, {
34154
+ cwd,
34155
+ shell: command.shell,
34156
+ timeout: timeoutMs,
34157
+ encoding: 'utf8',
34158
+ env: {
34159
+ ...Object.fromEntries(Object.entries(process.env).filter(([name]) => !replaced.has(name.toLowerCase()))),
34160
+ ...overrides,
34161
+ },
34162
+ });
34163
+ return stdout;
34164
+ }
34165
+ /** The JSON value npm printed, or each JSON line Yarn printed. */
34166
+ function jsonOutput(client, stdout) {
34167
+ return (client === 'npm' ? [stdout] : stdout.split(/\r?\n/u)).flatMap((chunk) => {
34168
+ try {
34169
+ return [JSON.parse(chunk)];
34170
+ }
34171
+ catch {
34172
+ return [];
34173
+ }
34174
+ });
34175
+ }
34176
+ /**
34177
+ * Hides the credentials a registry URL can carry, as npm does in its logs: up
34178
+ * to the last @ before the host, since a password can hold an unencoded @.
34179
+ */
34180
+ function redactUrls(text) {
34181
+ return text.replace(/\b([a-z][a-z\d+.-]*:\/\/)[^/\s]*@/giu, '$1***@');
34182
+ }
34183
+ /**
34184
+ * Why a registry command failed, and whether it means the registry does not
34185
+ * have the package: `version` when it has the package but not that version,
34186
+ * `package` when it has no such package (registries answer that too when you
34187
+ * may not access it). A missing npm, a network error or a timeout says
34188
+ * nothing about the release.
34189
+ */
34190
+ function registryFailure(client, error, timeoutMs) {
34191
+ const failure = error;
34192
+ if (failure.syscall?.startsWith('spawn')) {
34193
+ return {
34194
+ notFound: null,
34195
+ reason: `${client} could not start: ${failure.message}`,
34196
+ };
34197
+ }
34198
+ if (failure.killed) {
34199
+ return {
34200
+ notFound: null,
34201
+ reason: `${client} did not answer within ${timeoutMs / 1000} s`,
34202
+ };
34203
+ }
34204
+ const stdout = failure.stdout ?? '';
34205
+ const stderr = failure.stderr ?? '';
34206
+ // npm: {"error":{"code","summary"}}. Yarn: a {"type":"error","data"} line
34207
+ // per message, the first line of each data the gist.
34208
+ const messages = jsonOutput(client, stdout).flatMap((value) => isRecord(value) && isRecord(value.error)
34209
+ ? [`${String(value.error.code)}: ${String(value.error.summary)}`]
34210
+ : isRecord(value) && value.type === 'error'
34211
+ ? [String(value.data).split('\n')[0].trim()]
34212
+ : []);
34213
+ const output = `${stdout}\n${stderr}`;
34214
+ return {
34215
+ notFound: /\bETARGET\b|No match found for version|No matching version found/u.test(output)
34216
+ ? 'version'
34217
+ : /\bE404\b|Response Code: 404\b/u.test(output)
34218
+ ? 'package'
34219
+ : null,
34220
+ reason: redactUrls(messages.slice(0, 2).join('; ') ||
34221
+ stderr
34222
+ .split(/\r?\n/u)
34223
+ .find((line) => line.trim() !== '')
34224
+ ?.trim() ||
34225
+ (failure.message ?? String(error))),
34226
+ };
34227
+ }
34228
+ /** `name<separator>value` lines as a map; the first line for a name wins. */
34229
+ function settingLines(text, line, decode = (value) => value) {
34230
+ const values = new Map();
34231
+ for (const match of text.split(/\r?\n/u).map((entry) => entry.match(line))) {
34232
+ if (match && !values.has(match[1])) {
34233
+ try {
34234
+ const value = decode(match[2].trim());
34235
+ if (typeof value === 'string') {
34236
+ values.set(match[1], value);
34237
+ }
34238
+ }
34239
+ catch {
34240
+ // Not a value.
34241
+ }
34242
+ }
34243
+ }
34244
+ return values;
34245
+ }
34246
+ /**
34247
+ * The registry npm takes @iwsdk packages from, run with `npmArgs` and the
34248
+ * variables in `env` in `cwd`.
34249
+ */
34250
+ async function npmRegistry(cwd, npmArgs, env, timeoutMs) {
34251
+ const npm = (args) => runRegistryClient('npm', [...args, '--no-update-notifier', ...npmArgs], cwd, timeoutMs, env);
34252
+ let output;
34253
+ try {
34254
+ output = await npm(['config', 'get', '@iwsdk:registry', 'registry']);
34255
+ }
34256
+ catch (error) {
34257
+ const stderr = String(error.stderr ?? '');
34258
+ if (/\bENOWORKSPACES\b/u.test(stderr)) {
34259
+ // `npm config` does not run in an npm workspace package. `npm view`
34260
+ // does, with the workspace root's settings, as `npm install` there.
34261
+ return { url: null, scoped: false };
34262
+ }
34263
+ if (!/option is protected/u.test(stderr)) {
34264
+ throw error;
34265
+ }
34266
+ // npm 10 and 11 do not print a registry URL that has a password in it,
34267
+ // and npm view still uses it. `npm config ls` prints it with the
34268
+ // password hidden: the first uncommented line for a setting holds the
34269
+ // value in effect (publishConfig values follow).
34270
+ const shown = settingLines(await npm(['config', 'ls']).catch(() => ''), /^(\S+) = (".*")$/u, (value) => JSON.parse(value));
34271
+ const scoped = shown.get('@iwsdk:registry');
34272
+ return scoped
34273
+ ? { url: scoped, scoped: true }
34274
+ : { url: shown.get('registry') ?? null, scoped: false };
34275
+ }
34276
+ // key=value lines; @iwsdk:registry=undefined without a scope registry.
34277
+ const values = settingLines(output, /^([^=]+)=(.*)$/u);
34278
+ const scoped = values.get('@iwsdk:registry');
34279
+ return scoped && scoped !== 'undefined'
34280
+ ? { url: scoped, scoped: true }
34281
+ : { url: values.get('registry') ?? '', scoped: false };
34282
+ }
34283
+ /**
34284
+ * The registry Yarn 1 installs @iwsdk packages from, configured in `cwd`.
34285
+ * Yarn 1 reads .npmrc and .yarnrc files (the project's, the user's, and those
34286
+ * above the project) and npm_config_* and yarn_* variables, and takes an npm
34287
+ * setting over a Yarn one: the @iwsdk scope's registry, then the default
34288
+ * registry, then registry.yarnpkg.com. `yarn config get registry` prefers the
34289
+ * Yarn setting, so it can name another registry than the one Yarn installs
34290
+ * from.
34291
+ */
34292
+ async function yarnClassicRegistry(cwd, timeoutMs) {
34293
+ // {"type":"info","data":"yarn config"}, then {"type":"inspect","data":{…}};
34294
+ // the same for "npm config".
34295
+ const configs = new Map();
34296
+ let name = '';
34297
+ for (const value of jsonOutput('yarn', await runRegistryClient('yarn', ['config', 'list', '--json'], cwd, timeoutMs))) {
34298
+ if (isRecord(value) && value.type === 'info') {
34299
+ name = String(value.data);
34300
+ }
34301
+ else if (isRecord(value) &&
34302
+ value.type === 'inspect' &&
34303
+ isRecord(value.data)) {
34304
+ configs.set(name, value.data);
34305
+ }
34306
+ }
34307
+ const yarn = configs.get('yarn config');
34308
+ if (!yarn) {
34309
+ throw new Error('yarn config list printed no Yarn settings');
34310
+ }
34311
+ const npm = configs.get('npm config') ?? {};
34312
+ const setting = (config, key) => typeof config[key] === 'string' && config[key] !== ''
34313
+ ? config[key]
34314
+ : undefined;
34315
+ const scoped = setting(npm, '@iwsdk:registry') ?? setting(yarn, '@iwsdk:registry');
34316
+ return scoped
34317
+ ? { url: scoped, scoped: true }
34318
+ : {
34319
+ url: setting(npm, 'registry') ??
34320
+ setting(yarn, 'registry') ??
34321
+ 'https://registry.yarnpkg.com',
34322
+ scoped: false,
34323
+ };
34324
+ }
34325
+ /** The registry Yarn 2+ takes @iwsdk packages from, configured in `cwd`. */
34326
+ async function yarnBerryRegistry(cwd, timeoutMs) {
34327
+ const [scopes, server] = await Promise.all([
34328
+ runRegistryClient('yarn', ['config', 'get', 'npmScopes', '--json'], cwd, timeoutMs),
34329
+ runRegistryClient('yarn', ['config', 'get', 'npmRegistryServer'], cwd, timeoutMs),
34330
+ ]);
34331
+ const scoped = jsonOutput('npm', scopes).map((value) => isRecord(value) && isRecord(value.iwsdk)
34332
+ ? value.iwsdk.npmRegistryServer
34333
+ : undefined)[0];
34334
+ return typeof scoped === 'string' && scoped !== ''
34335
+ ? { url: scoped, scoped: true }
34336
+ : { url: server.trim(), scoped: false };
34337
+ }
34338
+ /** One package at `version`, from the registry; Yarn prints every field. */
34339
+ async function viewRelease({ client, cwd, npmArgs = [] }, name, version, fields, timeoutMs, env) {
34340
+ let stdout;
34341
+ try {
34342
+ stdout = await runRegistryClient(client, client === 'npm'
34343
+ ? [
34344
+ 'view',
34345
+ `${name}@${version}`,
34346
+ ...fields,
34347
+ '--json',
34348
+ ...NPM_FETCH_FLAGS,
34349
+ ...npmArgs,
34350
+ ]
34351
+ : ['npm', 'info', `${name}@${version}`, '--json'], cwd, timeoutMs, env);
34352
+ }
34353
+ catch (error) {
34354
+ const failure = registryFailure(client, error, timeoutMs);
34355
+ return failure.notFound
34356
+ ? {
34357
+ kind: 'missing',
34358
+ reason: failure.reason,
34359
+ packageNotFound: failure.notFound === 'package',
34360
+ }
34361
+ : { kind: 'failed', reason: failure.reason };
34362
+ }
34363
+ // npm prints the bare value when only one field has one. Yarn prints a
34364
+ // line per package and, for a version it does not have, the latest one.
34365
+ const manifest = jsonOutput(client, stdout)
34366
+ .map((value) => typeof value === 'string'
34367
+ ? { version: value }
34368
+ : isRecord(value) && (client === 'npm' || value.name === name)
34369
+ ? value
34370
+ : null)
34371
+ .find((value) => value != null);
34372
+ return manifest?.version === version
34373
+ ? { kind: 'found', manifest }
34374
+ : {
34375
+ kind: 'missing',
34376
+ reason: `No match found for version ${version}`,
34377
+ packageNotFound: false,
34378
+ };
34379
+ }
34380
+ /**
34381
+ * Removal of a temporary npm cache retries for up to 3 s: on Windows, an npm
34382
+ * that a timeout left running (it stops only the cmd.exe that started npm)
34383
+ * can keep the folder busy.
34384
+ */
34385
+ const CACHE_REMOVAL = {
34386
+ recursive: true,
34387
+ force: true,
34388
+ maxRetries: 5,
34389
+ retryDelay: 200,
34390
+ };
33732
34391
  /**
33733
- * Align the app's Three.js alias with the one the installed core uses,
33734
- * wherever the package manager reads it, and the app's `@types/three` with
33735
- * core's, so the app type-checks against one Three.js. Returns what changed
33736
- * and what the developer has to change by hand.
34392
+ * Runs `run` with a new, empty npm cache folder, removed afterwards or, if it
34393
+ * is still busy then, when the CLI exits. Until then, an interrupt removes it
34394
+ * too: SIGINT and SIGTERM are handled only when nothing else handles them,
34395
+ * and raised again, so they still end the CLI. Rejects when no folder can be
34396
+ * made.
33737
34397
  */
33738
- async function alignThree(projectRoot, packageJson, packageManagerRoot) {
34398
+ async function withEmptyNpmCache(run) {
34399
+ const cache = await mkdtemp(path.join(os.tmpdir(), 'iwsdk-npm-cache-'));
34400
+ const removeNow = () => {
34401
+ try {
34402
+ rmSync(cache, { recursive: true, force: true });
34403
+ }
34404
+ catch {
34405
+ // Left to the system's temporary-file cleanup.
34406
+ }
34407
+ };
34408
+ const interrupted = (signal) => {
34409
+ removeNow();
34410
+ process.kill(process.pid, signal);
34411
+ };
34412
+ const signals = ['SIGINT', 'SIGTERM'].filter((signal) => process.listenerCount(signal) === 0);
34413
+ process.once('exit', removeNow);
34414
+ for (const signal of signals) {
34415
+ process.once(signal, interrupted);
34416
+ }
34417
+ try {
34418
+ return await run(cache);
34419
+ }
34420
+ finally {
34421
+ const removed = await rm(cache, CACHE_REMOVAL).then(() => true, () => false);
34422
+ for (const signal of signals) {
34423
+ process.off(signal, interrupted);
34424
+ }
34425
+ if (removed) {
34426
+ process.off('exit', removeNow);
34427
+ }
34428
+ }
34429
+ }
34430
+ /**
34431
+ * Ask the registry for every package at `version` before anything is
34432
+ * written, the way the install will ask it (see `registryLookup`). Says which
34433
+ * registry it asks on `stderr`.
34434
+ */
34435
+ async function checkRegistry({ names, version, stderr, timeoutMs = REGISTRY_TIMEOUT_MS, ...lookup }) {
34436
+ // Which client names the registry: Yarn in any Yarn project.
34437
+ const namedBy = lookup.yarnClassicCwd
34438
+ ? 'yarn'
34439
+ : lookup.client;
34440
+ let configured;
34441
+ try {
34442
+ configured =
34443
+ lookup.client === 'yarn'
34444
+ ? await yarnBerryRegistry(lookup.cwd, timeoutMs)
34445
+ : lookup.yarnClassicCwd
34446
+ ? await yarnClassicRegistry(lookup.yarnClassicCwd, timeoutMs)
34447
+ : await npmRegistry(lookup.cwd, lookup.npmArgs ?? [], lookup.env ?? {}, timeoutMs);
34448
+ }
34449
+ catch (error) {
34450
+ return {
34451
+ status: 'unavailable',
34452
+ registry: null,
34453
+ reason: registryFailure(namedBy, error, timeoutMs).reason,
34454
+ };
34455
+ }
34456
+ if (configured.url != null && !/^https?:\/\//iu.test(configured.url)) {
34457
+ // Yarn 1 answers "undefined" for Yarn 2+ settings.
34458
+ return {
34459
+ status: 'unavailable',
34460
+ registry: null,
34461
+ reason: `${namedBy} reported no registry URL ("${redactUrls(configured.url)}")`,
34462
+ };
34463
+ }
34464
+ const registry = configured.url == null ? UNNAMED_NPM_REGISTRY : redactUrls(configured.url);
34465
+ // In a Yarn 1 project, npm asks the registry Yarn installs from.
34466
+ const env = {
34467
+ ...lookup.env,
34468
+ ...(lookup.yarnClassicCwd && configured.url
34469
+ ? { npm_config_registry: configured.url }
34470
+ : {}),
34471
+ };
34472
+ stderr.write(`[IWSDK] Checking ${registry} for IWSDK ${version} ...\n`);
34473
+ const view = (name, cache) => viewRelease(lookup, name, version, name === '@iwsdk/core'
34474
+ ? ['version', 'dependencies', 'versions']
34475
+ : ['version'], timeoutMs, cache ? { ...env, npm_config_cache: cache } : env);
34476
+ let results = await Promise.all(names.map((name) => view(name)));
34477
+ if (lookup.client === 'npm' &&
34478
+ results.some((result) => result.kind === 'missing')) {
34479
+ // Without a network, npm answers from its cache, and a package cached
34480
+ // before the release was published says the release does not exist. A
34481
+ // published version never changes, so a cached answer that has it stands;
34482
+ // one without it is asked again with an empty cache, which only the
34483
+ // registry can answer. Without an empty cache, it stays unchecked.
34484
+ const cached = results;
34485
+ 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'
34486
+ ? {
34487
+ kind: 'failed',
34488
+ 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)}`,
34489
+ }
34490
+ : result));
34491
+ }
34492
+ const missing = [];
34493
+ let failure = null;
34494
+ let core;
34495
+ results.forEach((result, index) => {
34496
+ if (result.kind === 'found') {
34497
+ core = names[index] === '@iwsdk/core' ? result.manifest : core;
34498
+ }
34499
+ else if (result.kind === 'missing') {
34500
+ missing.push({
34501
+ spec: `${names[index]}@${version}`,
34502
+ reason: result.reason,
34503
+ packageNotFound: result.packageNotFound,
34504
+ });
34505
+ }
34506
+ else {
34507
+ failure ??= result.reason;
34508
+ }
34509
+ });
34510
+ if (missing.length > 0) {
34511
+ return { status: 'missing', registry, missing, scoped: configured.scoped };
34512
+ }
34513
+ if (failure != null) {
34514
+ return { status: 'unavailable', registry, reason: failure };
34515
+ }
34516
+ return { status: 'found', registry, core };
34517
+ }
34518
+ /** A .npmrc value as npm's ini parser reads it. */
34519
+ function iniValue(raw) {
34520
+ const value = raw.trim();
34521
+ if (value.length > 1 && value.startsWith("'") && value.endsWith("'")) {
34522
+ return value.slice(1, -1);
34523
+ }
34524
+ if (value.length > 1 && value.startsWith('"') && value.endsWith('"')) {
34525
+ try {
34526
+ return String(JSON.parse(value));
34527
+ }
34528
+ catch {
34529
+ return value;
34530
+ }
34531
+ }
34532
+ // Up to a ; or # comment; a backslash escapes either.
34533
+ return (value.match(/^(?:\\.?|[^\\;#])*/su)?.[0] ?? '')
34534
+ .replace(/\\([\\;#])/gu, '$1')
34535
+ .trim();
34536
+ }
34537
+ /**
34538
+ * The settings in the .npmrc in `directory` that pick the registry of @iwsdk
34539
+ * packages or authenticate with one: `registry`, `@iwsdk:registry` and the
34540
+ * `//<registry>/:<setting>` keys. Lines after a [section] hold no settings.
34541
+ */
34542
+ function npmrcRegistrySettings(directory) {
34543
+ const settings = new Map();
34544
+ let text;
34545
+ try {
34546
+ text = readFileSync(path.join(directory, '.npmrc'), 'utf8');
34547
+ }
34548
+ catch {
34549
+ return settings;
34550
+ }
34551
+ for (const line of text.split(/[\r\n]+/u)) {
34552
+ if (/^\s*\[/u.test(line)) {
34553
+ break;
34554
+ }
34555
+ const match = line.match(/^\s*([^\s;#=][^=]*)=(.*)$/u);
34556
+ const key = match?.[1].trim() ?? '';
34557
+ if (key === 'registry' ||
34558
+ key === '@iwsdk:registry' ||
34559
+ key.startsWith('//')) {
34560
+ settings.set(key, iniValue(match[2]));
34561
+ }
34562
+ }
34563
+ return settings;
34564
+ }
34565
+ /** The settings npm_config_* variables set, under npm's names for them. */
34566
+ function environmentSettings() {
34567
+ return new Set(Object.entries(process.env)
34568
+ .filter(([name, value]) => /^npm_config_./iu.test(name) && value !== '')
34569
+ .map(([name]) => {
34570
+ const key = name.slice('npm_config_'.length);
34571
+ return key.startsWith('//')
34572
+ ? key
34573
+ : key.replace(/(?!^)_/gu, '-').toLowerCase();
34574
+ }));
34575
+ }
34576
+ /**
34577
+ * How to ask the registry the install will use. The install runs in the
34578
+ * project directory.
34579
+ * - npm installs there with the workspace root's .npmrc and ignores the
34580
+ * project's own, so npm runs in the workspace root.
34581
+ * - pnpm and Yarn 1 merge the project's own .npmrc over the workspace root's,
34582
+ * setting by setting: a scope registry or a token only the root sets still
34583
+ * applies. When both set the registry or auth, npm runs in the workspace
34584
+ * root and gets the project's registry and auth settings as npm_config_*
34585
+ * variables, which npm takes over any .npmrc (unless the environment
34586
+ * already sets them, as pnpm and Yarn 1 then do too). Otherwise npm runs in
34587
+ * whichever directory sets them, the root when neither does. npm gets
34588
+ * --no-workspaces, so that it reads the .npmrc there and not that of a root
34589
+ * whose package.json declares workspaces.
34590
+ * - Yarn 1 also takes the registry from .yarnrc, so Yarn names it.
34591
+ * - Yarn 2+ reads only .yarnrc.yml, and is asked itself.
34592
+ */
34593
+ function registryLookup(projectRoot, info) {
34594
+ if (usesYarnBerry(projectRoot, info)) {
34595
+ return { client: 'yarn', cwd: info.root };
34596
+ }
34597
+ if (info.name !== 'pnpm' && info.name !== 'yarn') {
34598
+ return { client: 'npm', cwd: info.root };
34599
+ }
34600
+ const project = path.resolve(projectRoot);
34601
+ const own = npmrcRegistrySettings(project);
34602
+ const root = path.resolve(info.root) === project
34603
+ ? new Map()
34604
+ : npmrcRegistrySettings(info.root);
34605
+ const merge = own.size > 0 && root.size > 0;
34606
+ const inEnvironment = merge ? environmentSettings() : new Set();
34607
+ return {
34608
+ client: 'npm',
34609
+ cwd: own.size > 0 && !merge ? project : info.root,
34610
+ npmArgs: ['--no-workspaces'],
34611
+ ...(merge
34612
+ ? {
34613
+ env: Object.fromEntries([...own]
34614
+ .filter(([key]) => !inEnvironment.has(key))
34615
+ .map(([key, value]) => [`npm_config_${key}`, value])),
34616
+ }
34617
+ : {}),
34618
+ ...(info.name === 'yarn' ? { yarnClassicCwd: project } : {}),
34619
+ };
34620
+ }
34621
+ /** The dependencies of the @iwsdk/core installed in the project. */
34622
+ function installedCoreDependencies(projectRoot) {
33739
34623
  const corePackageJson = resolveInstalledCorePackageJson(projectRoot);
33740
- const coreDependencies = corePackageJson
34624
+ return corePackageJson
33741
34625
  ? JSON.parse(readFileSync(corePackageJson, 'utf8')).dependencies
33742
34626
  : undefined;
34627
+ }
34628
+ /**
34629
+ * Align the app's Three.js alias with the one core uses, wherever the
34630
+ * package manager reads it, and the app's `@types/three` with core's, so the
34631
+ * app type-checks against one Three.js. Returns what changed and what the
34632
+ * developer has to change by hand; `write: false` only plans.
34633
+ */
34634
+ async function alignThree(projectRoot, packageJson, packageManagerRoot, coreDependencies, write) {
33743
34635
  const coreThree = coreDependencies?.three;
33744
34636
  if (!coreThree) {
33745
34637
  return { bumps: [], manualSteps: [] };
@@ -33789,7 +34681,9 @@ async function alignThree(projectRoot, packageJson, packageManagerRoot) {
33789
34681
  const current = match?.[1]?.replace(/^['"]|['"]$/gu, '');
33790
34682
  if (match && current && current !== coreThree) {
33791
34683
  if (path.resolve(packageManagerRoot) === path.resolve(projectRoot)) {
33792
- await writeFile(workspaceFile, text.replace(match[0], match[0].replace(/three:[ \t]*\S+/u, `three: ${coreThree}`)));
34684
+ if (write) {
34685
+ await writeFile(workspaceFile, text.replace(match[0], match[0].replace(/three:[ \t]*\S+/u, `three: ${coreThree}`)));
34686
+ }
33793
34687
  bumps.push({
33794
34688
  field: 'pnpm-workspace.yaml overrides',
33795
34689
  name: 'three',
@@ -33859,13 +34753,16 @@ async function handleUpgrade(options, io) {
33859
34753
  if (!isRecord(packageJson)) {
33860
34754
  throw new Error('package.json must contain a JSON object.');
33861
34755
  }
33862
- const to = typeof options.to === 'string' ? options.to : CLI_VERSION;
33863
- if (semver$1.valid(to) == null) {
33864
- throw new Error(`--to must be an exact IWSDK version, got "${to}".`);
34756
+ const requested = typeof options.to === 'string' ? options.to : CLI_VERSION;
34757
+ // Normalized: v1.2.0 and 1.2.0 name the same release.
34758
+ const to = semver$1.valid(requested);
34759
+ if (to == null) {
34760
+ throw new Error(`--to must be an exact IWSDK version, got "${requested}".`);
33865
34761
  }
33866
34762
  const packages = [];
33867
34763
  const keptSpecs = [];
33868
34764
  const outsideRelease = [];
34765
+ const fromRegistry = new Set();
33869
34766
  let declaresIwsdk = false;
33870
34767
  for (const field of DEPENDENCY_FIELDS) {
33871
34768
  const dependencies = packageJson[field];
@@ -33884,8 +34781,11 @@ async function handleUpgrade(options, io) {
33884
34781
  // workspace:, file:, link:, catalog:, git and npm: aliases.
33885
34782
  keptSpecs.push(`${name}@${spec}`);
33886
34783
  }
33887
- else if (bumpedSpec(spec, to) !== spec) {
33888
- packages.push({ field, name, from: spec, to: bumpedSpec(spec, to) });
34784
+ else {
34785
+ fromRegistry.add(name);
34786
+ if (bumpedSpec(spec, to) !== spec) {
34787
+ packages.push({ field, name, from: spec, to: bumpedSpec(spec, to) });
34788
+ }
33889
34789
  }
33890
34790
  }
33891
34791
  }
@@ -33912,6 +34812,84 @@ async function handleUpgrade(options, io) {
33912
34812
  if (outsideRelease.length > 0) {
33913
34813
  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.' : ''}`);
33914
34814
  }
34815
+ // Before anything is written: a registry without the release (a mirror
34816
+ // that has not synced it) stops the upgrade here, not with package.json
34817
+ // half changed, and three follows the new core's even when nothing gets
34818
+ // installed. A registry that cannot be asked does not stop it; three is
34819
+ // then aligned with the core the install brings.
34820
+ const lookup = registryLookup(root, packageManagerInfo);
34821
+ const release = fromRegistry.size > 0
34822
+ ? await checkRegistry({
34823
+ names: [...fromRegistry],
34824
+ version: to,
34825
+ ...lookup,
34826
+ stderr: io.stderr,
34827
+ })
34828
+ : null;
34829
+ if (release?.status === 'missing') {
34830
+ // Packages missing at that version, then packages missing altogether,
34831
+ // which a registry also answers for packages you may not access.
34832
+ const specs = (entries) => entries.map((entry) => entry.spec).join(', ');
34833
+ const noVersion = release.missing.filter((entry) => !entry.packageNotFound);
34834
+ const noPackage = release.missing.filter((entry) => entry.packageNotFound);
34835
+ const absent = [
34836
+ noVersion.length > 0
34837
+ ? `${specs(noVersion)} (${noVersion[0].reason})`
34838
+ : '',
34839
+ noPackage.length > 0
34840
+ ? `${specs(noPackage)}, or you do not have permission to access ${noPackage.length === 1 ? 'it' : 'them'} (${noPackage[0].reason})`
34841
+ : '',
34842
+ ]
34843
+ .filter(Boolean)
34844
+ .join(', and does not have ');
34845
+ // npm, pnpm and Yarn 1 take the variable over .npmrc and .yarnrc; it does
34846
+ // not replace a registry set for the @iwsdk scope.
34847
+ const override = lookup.client === 'npm' && packageManager !== 'bun' && !release.scoped
34848
+ ? ' (the npm_config_registry environment variable overrides the configured one)'
34849
+ : '';
34850
+ 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', {
34851
+ registry: release.registry,
34852
+ version: to,
34853
+ missing: release.missing.map((entry) => entry.spec),
34854
+ });
34855
+ }
34856
+ for (const bump of packages) {
34857
+ packageJson[bump.field][bump.name] = bump.to;
34858
+ }
34859
+ const publishedCore = release?.status === 'found' ? release.core : undefined;
34860
+ const three = await alignThree(root, packageJson, packageManagerInfo.root, publishedCore?.dependencies, !dryRun);
34861
+ packages.push(...three.bumps);
34862
+ manualSteps.push(...three.manualSteps);
34863
+ // True until three is aligned with the core the install brings.
34864
+ let threePending = false;
34865
+ if (release?.status === 'unavailable') {
34866
+ const unchecked = `Could not check ${release.registry ?? 'the registry'} for IWSDK ${to} (${release.reason})`;
34867
+ if (dryRun) {
34868
+ manualSteps.push(`${unchecked}: three alignment will be decided after install.`);
34869
+ }
34870
+ else {
34871
+ io.stderr.write(`[IWSDK] ${unchecked}; upgrading without it.\n`);
34872
+ threePending = true;
34873
+ if (!install) {
34874
+ 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.`);
34875
+ }
34876
+ }
34877
+ }
34878
+ // three now follows core `to`. Without an install, nothing re-checks it
34879
+ // when a ^ or ~ range brings in a newer core instead.
34880
+ const coreSpec = DEPENDENCY_FIELDS.map((field) => isRecord(packageJson[field])
34881
+ ? packageJson[field]['@iwsdk/core']
34882
+ : undefined).find((spec) => typeof spec === 'string');
34883
+ const newerCore = !install &&
34884
+ publishedCore?.dependencies?.three &&
34885
+ Array.isArray(publishedCore.versions) &&
34886
+ coreSpec &&
34887
+ /^[\^~]/u.test(coreSpec.trim())
34888
+ ? semver$1.maxSatisfying(publishedCore.versions, coreSpec)
34889
+ : null;
34890
+ if (newerCore && semver$1.gt(newerCore, to)) {
34891
+ 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}\`.`);
34892
+ }
33915
34893
  if (dryRun) {
33916
34894
  return createSuccess({
33917
34895
  projectRoot: root,
@@ -33931,9 +34909,6 @@ async function handleUpgrade(options, io) {
33931
34909
  manualSteps,
33932
34910
  });
33933
34911
  }
33934
- for (const bump of packages) {
33935
- packageJson[bump.field][bump.name] = bump.to;
33936
- }
33937
34912
  if (packages.length > 0) {
33938
34913
  await writeFile(packageJsonPath, formatJson(packageJson, rawPackageJson));
33939
34914
  }
@@ -33955,7 +34930,9 @@ async function handleUpgrade(options, io) {
33955
34930
  catch (error) {
33956
34931
  throw new Error([
33957
34932
  error instanceof Error ? error.message : String(error),
33958
- `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\`.`,
34933
+ threePending
34934
+ ? `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.`
34935
+ : `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\`.`,
33959
34936
  migrationNotice,
33960
34937
  ...manualSteps,
33961
34938
  ]
@@ -33968,10 +34945,14 @@ async function handleUpgrade(options, io) {
33968
34945
  let configIssues = [];
33969
34946
  if (install) {
33970
34947
  installOrExplain();
33971
- const three = await alignThree(root, packageJson, packageManagerInfo.root);
33972
- manualSteps.push(...three.manualSteps);
33973
- if (three.bumps.length > 0) {
33974
- packages.push(...three.bumps);
34948
+ // The installed core can still differ from the registry's: a file: or
34949
+ // workspace: core, or a ^ range that resolved past the target. And when
34950
+ // the registry could not be checked, this is the only alignment.
34951
+ const installedThree = await alignThree(root, packageJson, packageManagerInfo.root, installedCoreDependencies(root), true);
34952
+ threePending = false;
34953
+ manualSteps.push(...installedThree.manualSteps.filter((step) => !manualSteps.includes(step)));
34954
+ if (installedThree.bumps.length > 0) {
34955
+ packages.push(...installedThree.bumps);
33975
34956
  await writeFile(packageJsonPath, formatJson(packageJson, rawPackageJson));
33976
34957
  installOrExplain();
33977
34958
  }
@@ -34019,6 +35000,15 @@ async function handleUpgrade(options, io) {
34019
35000
  .join('; ')}. The migration guides and release notes say what replaced each setting.`);
34020
35001
  }
34021
35002
  }
35003
+ else if (threePending) {
35004
+ // The step that says to run upgrade again, which installs, aligns three
35005
+ // and syncs the guidance, stands for "install, then agents sync": that
35006
+ // would leave three as declared.
35007
+ guidance = {
35008
+ status: 'pending',
35009
+ message: 'Dependencies were not installed.',
35010
+ };
35011
+ }
34022
35012
  else {
34023
35013
  guidance = {
34024
35014
  status: 'pending',
@@ -34351,17 +35341,22 @@ function buildUpgradeCommandHelp() {
34351
35341
  'Usage: npx @iwsdk/cli@latest upgrade [--to <version>] [--dry-run] [--no-install] [--workspace <path>]',
34352
35342
  '',
34353
35343
  'Upgrades every @iwsdk/* dependency in the release group to this CLI release',
34354
- "(or --to), keeping ^ and ~ ranges, and installs with the project's package",
34355
- 'manager (found from the nearest lockfile). Then it aligns the Three.js alias',
34356
- 'with @iwsdk/core, refreshes the coding-agent guidance the project already has,',
34357
- 'and checks iwsdk.config.json against the new release. It writes to',
34358
- '.iwsdk/migrations/ (gitignored) a migration guide for each release boundary',
34359
- 'crossed and release-notes.md with every change in between. Run it with',
34360
- '@latest so the newest migration guides and release notes are available.',
35344
+ '(or --to), keeping ^ and ~ ranges, and aligns the Three.js alias with the new',
35345
+ '@iwsdk/core. First it asks the registry the install will use (from the npm or',
35346
+ 'Yarn settings the install reads; npm_config_registry overrides it for npm,',
35347
+ 'pnpm and Yarn 1 unless an @iwsdk scope registry is set) for the release, and',
35348
+ 'changes nothing if the release is missing there; if the registry cannot be',
35349
+ 'asked, it goes on and aligns Three.js after the install. Then it installs with',
35350
+ "the project's package manager (found from the nearest lockfile), refreshes the",
35351
+ 'coding-agent guidance the project already has, and checks iwsdk.config.json',
35352
+ 'against the new release. It writes to .iwsdk/migrations/ (gitignored) a',
35353
+ 'migration guide for each release boundary crossed and release-notes.md with',
35354
+ 'every change in between. Run it with @latest so the newest migration guides',
35355
+ 'and release notes are available.',
34361
35356
  '',
34362
35357
  'Options:',
34363
35358
  ' --to <version> target IWSDK version (default: this CLI version)',
34364
- ' --dry-run report the version change, migration guides and release-note count only',
35359
+ ' --dry-run report the planned changes without writing anything (asks the registry)',
34365
35360
  ' --no-install update package.json without installing',
34366
35361
  ' --workspace <path> project directory',
34367
35362
  ];
@@ -34580,7 +35575,9 @@ async function runCli(argv, io = {}) {
34580
35575
  })
34581
35576
  : error instanceof GuidanceSourceError
34582
35577
  ? createFailure(error.message, error.code)
34583
- : createFailure(error instanceof Error ? error.message : String(error));
35578
+ : error instanceof UpgradeError
35579
+ ? createFailure(error.message, error.code, error.details)
35580
+ : createFailure(error instanceof Error ? error.message : String(error));
34584
35581
  // Set by `dev up` when the guidance refresh ran before startup threw.
34585
35582
  const agentGuidance = error
34586
35583
  ?.agentGuidance;