@andorra-labs/code 0.1.4 → 0.1.6

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 (171) hide show
  1. package/dist/src/account-presentation.js +3 -3
  2. package/dist/src/agent-execution.d.ts +2 -0
  3. package/dist/src/agent-execution.js +126 -20
  4. package/dist/src/agent-mcp.d.ts +18 -1
  5. package/dist/src/agent-mcp.js +103 -8
  6. package/dist/src/app-server/protocol.d.ts +33 -3
  7. package/dist/src/app-server/protocol.js +14 -1
  8. package/dist/src/app-server/workspace.d.ts +1 -0
  9. package/dist/src/app-server/workspace.js +7 -1
  10. package/dist/src/app-server.d.ts +115 -41
  11. package/dist/src/app-server.js +1229 -219
  12. package/dist/src/automation-runner.d.ts +9 -0
  13. package/dist/src/automation-runner.js +22 -1
  14. package/dist/src/automation-tool.js +8 -1
  15. package/dist/src/automations.js +1 -1
  16. package/dist/src/browser-captcha-tool.d.ts +54 -0
  17. package/dist/src/browser-captcha-tool.js +374 -0
  18. package/dist/src/browser-panel-tool.d.ts +7 -0
  19. package/dist/src/browser-panel-tool.js +74 -3
  20. package/dist/src/browser-runner.js +19 -4
  21. package/dist/src/browser-server.js +21 -1
  22. package/dist/src/browser-session.d.ts +16 -0
  23. package/dist/src/browser-session.js +35 -0
  24. package/dist/src/browser-ui/app.js +193 -3
  25. package/dist/src/browser-ui/style.css +15 -1
  26. package/dist/src/browser-view.d.ts +72 -4
  27. package/dist/src/browser-view.js +229 -17
  28. package/dist/src/capabilities.js +13 -2
  29. package/dist/src/capsolver.d.ts +60 -0
  30. package/dist/src/capsolver.js +101 -0
  31. package/dist/src/claude-provider.d.ts +6 -0
  32. package/dist/src/claude-provider.js +34 -3
  33. package/dist/src/cli-executable.d.ts +33 -0
  34. package/dist/src/cli-executable.js +64 -0
  35. package/dist/src/cli-process.d.ts +47 -0
  36. package/dist/src/cli-process.js +113 -0
  37. package/dist/src/cli-sign-in.d.ts +68 -0
  38. package/dist/src/cli-sign-in.js +224 -0
  39. package/dist/src/cli.js +54 -23
  40. package/dist/src/code-intelligence/CodeIntelligenceManager.d.ts +1 -1
  41. package/dist/src/code-intelligence/CodeIntelligenceManager.js +5 -5
  42. package/dist/src/coding-tools.js +44 -5
  43. package/dist/src/command-output-tap.d.ts +16 -0
  44. package/dist/src/command-output-tap.js +45 -0
  45. package/dist/src/command-screens.js +3 -3
  46. package/dist/src/commands.d.ts +10 -1
  47. package/dist/src/commands.js +7 -7
  48. package/dist/src/completion.d.ts +23 -5
  49. package/dist/src/completion.js +334 -17
  50. package/dist/src/config.d.ts +13 -0
  51. package/dist/src/config.js +28 -2
  52. package/dist/src/deadline.js +6 -0
  53. package/dist/src/extensions.d.ts +1 -0
  54. package/dist/src/extensions.js +16 -3
  55. package/dist/src/graph-provider-portability.js +2 -2
  56. package/dist/src/graph-quota.d.ts +1 -1
  57. package/dist/src/graph-quota.js +1 -1
  58. package/dist/src/graph-runner.js +35 -21
  59. package/dist/src/graph-selection.d.ts +6 -0
  60. package/dist/src/graph-selection.js +10 -0
  61. package/dist/src/graph-server.d.ts +7 -0
  62. package/dist/src/graph-server.js +61 -3
  63. package/dist/src/graph-sync.d.ts +50 -0
  64. package/dist/src/graph-sync.js +383 -12
  65. package/dist/src/graph-ui/app.js +61 -8
  66. package/dist/src/graph-ui/icons.js +1 -0
  67. package/dist/src/graph-ui/index.html +1 -1
  68. package/dist/src/graph-ui/skill-picker.js +242 -0
  69. package/dist/src/graph-ui/style.css +19 -0
  70. package/dist/src/graphs.d.ts +46 -4
  71. package/dist/src/graphs.js +152 -27
  72. package/dist/src/grok-provider.d.ts +50 -0
  73. package/dist/src/grok-provider.js +186 -0
  74. package/dist/src/handoffs.d.ts +13 -0
  75. package/dist/src/handoffs.js +31 -1
  76. package/dist/src/managed-sign-in.d.ts +38 -0
  77. package/dist/src/managed-sign-in.js +169 -0
  78. package/dist/src/markdown.d.ts +5 -0
  79. package/dist/src/markdown.js +5 -2
  80. package/dist/src/mcp.js +11 -0
  81. package/dist/src/membership.d.ts +8 -1
  82. package/dist/src/membership.js +15 -5
  83. package/dist/src/model-metadata.js +14 -2
  84. package/dist/src/model-override.d.ts +10 -0
  85. package/dist/src/model-override.js +20 -0
  86. package/dist/src/opencode-cli-provider.d.ts +122 -0
  87. package/dist/src/opencode-cli-provider.js +415 -0
  88. package/dist/src/opencode-provider.js +23 -8
  89. package/dist/src/palette.d.ts +2 -0
  90. package/dist/src/palette.js +2 -0
  91. package/dist/src/permissions.d.ts +19 -1
  92. package/dist/src/permissions.js +30 -1
  93. package/dist/src/powershell-pool.d.ts +2 -2
  94. package/dist/src/powershell-pool.js +18 -5
  95. package/dist/src/provider-connection.js +36 -0
  96. package/dist/src/provider-engine.d.ts +2 -1
  97. package/dist/src/provider-engine.js +64 -13
  98. package/dist/src/provider-import.js +6 -1
  99. package/dist/src/provider-settings.js +22 -3
  100. package/dist/src/providers.d.ts +12 -1
  101. package/dist/src/providers.js +27 -8
  102. package/dist/src/pull-requests.d.ts +111 -17
  103. package/dist/src/pull-requests.js +308 -76
  104. package/dist/src/qa/qa-authorize.js +9 -1
  105. package/dist/src/react-runtime.js +76 -5
  106. package/dist/src/remote/engine-pool.js +1 -1
  107. package/dist/src/run-progress.js +6 -1
  108. package/dist/src/run-records.d.ts +133 -27
  109. package/dist/src/run-records.js +320 -40
  110. package/dist/src/runtime.d.ts +38 -1
  111. package/dist/src/runtime.js +27 -4
  112. package/dist/src/save-lock.d.ts +11 -0
  113. package/dist/src/save-lock.js +29 -2
  114. package/dist/src/sessions.js +4 -1
  115. package/dist/src/shell.js +4 -1
  116. package/dist/src/side-panel.d.ts +1 -1
  117. package/dist/src/side-panel.js +1 -1
  118. package/dist/src/skill-commands.d.ts +2 -0
  119. package/dist/src/skill-commands.js +2 -0
  120. package/dist/src/skills/bundled/create-agent/SKILL.md +81 -0
  121. package/dist/src/skills/bundled/create-skill/SKILL.md +81 -0
  122. package/dist/src/skills/bundled/doctor/SKILL.md +43 -0
  123. package/dist/src/skills/bundled/graph-manager/SKILL.md +97 -0
  124. package/dist/src/skills/bundled/graph-manager/errors.md +38 -0
  125. package/dist/src/skills/bundled/graph-manager/patterns.md +78 -0
  126. package/dist/src/skills/bundled/manage-mcp/SKILL.md +75 -0
  127. package/dist/src/skills/bundled/manage-mcp/probe.md +165 -0
  128. package/dist/src/skills/bundled/manage-skills/SKILL.md +67 -0
  129. package/dist/src/skills/bundled/provenance.json +50 -0
  130. package/dist/src/skills/bundled/write-instructions/SKILL.md +42 -0
  131. package/dist/src/skills/invocable-skills.d.ts +41 -0
  132. package/dist/src/skills/invocable-skills.js +49 -0
  133. package/dist/src/skills/prompt-skills.d.ts +1 -0
  134. package/dist/src/skills/prompt-skills.js +33 -0
  135. package/dist/src/skills/runtime-skills.d.ts +4 -0
  136. package/dist/src/skills/runtime-skills.js +21 -0
  137. package/dist/src/structured-step.d.ts +55 -0
  138. package/dist/src/structured-step.js +85 -0
  139. package/dist/src/subagent-run.d.ts +1 -1
  140. package/dist/src/subagent-run.js +29 -33
  141. package/dist/src/telemetry/schema.d.ts +2 -2
  142. package/dist/src/telemetry/schema.js +3 -2
  143. package/dist/src/terminal-ui.d.ts +29 -0
  144. package/dist/src/terminal-ui.js +112 -28
  145. package/dist/src/timers.d.ts +21 -2
  146. package/dist/src/timers.js +12 -4
  147. package/dist/src/tool-names.d.ts +18 -0
  148. package/dist/src/tool-names.js +26 -0
  149. package/dist/src/tools.js +45 -11
  150. package/dist/src/trajectory.js +32 -12
  151. package/dist/src/types.d.ts +23 -0
  152. package/dist/src/update.d.ts +26 -16
  153. package/dist/src/update.js +232 -275
  154. package/docs/agents/install-for-agents.md +15 -24
  155. package/docs/agents/mcp-server.md +13 -1
  156. package/docs/agents/subagent-mode.md +7 -4
  157. package/docs/concepts/security.md +2 -0
  158. package/docs/getting-started/README.md +14 -6
  159. package/docs/getting-started/configure-providers.md +29 -2
  160. package/docs/guides/README.md +1 -1
  161. package/docs/guides/browser.md +12 -0
  162. package/docs/guides/desktop-app.md +45 -9
  163. package/docs/guides/graph-builder.md +8 -0
  164. package/docs/guides/update.md +37 -16
  165. package/docs/reference/cli.md +1 -1
  166. package/docs/reference/config.md +2 -2
  167. package/docs/superpowers/plans/2026-11-06-graph-soft-delete.md +125 -0
  168. package/docs/superpowers/specs/2026-11-01-pr-section-design.md +7 -0
  169. package/docs/superpowers/specs/2026-11-06-bundled-skills-design.md +206 -0
  170. package/package.json +1 -1
  171. package/tests/permissions-test-plan.md +2 -1
@@ -1,15 +1,23 @@
1
1
  import { execFile, spawn } from 'node:child_process';
2
2
  import { randomUUID } from 'node:crypto';
3
- import { link, readFile, readdir, realpath, rename, stat, unlink, writeFile } from 'node:fs/promises';
4
- import { delimiter, dirname, join, resolve } from 'node:path';
3
+ import { link, lstat, mkdir, readFile, readdir, realpath, rename, rm, stat, unlink, writeFile } from 'node:fs/promises';
4
+ import { basename, delimiter, dirname, join, resolve } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { promisify } from 'node:util';
7
+ import semver from 'semver';
8
+ import { configDirectory } from './config.js';
7
9
  const executeFile = promisify(execFile);
10
+ /** The package `andorra update` installs. */
11
+ export const PACKAGE_NAME = '@andorra-labs/code';
12
+ /** The npm dist-tag the update follows. */
13
+ const RELEASE_TAG = 'latest';
8
14
  /** Bounded install attempts; only a failure that still looks transient is retried. */
9
15
  const INSTALL_ATTEMPTS = 3;
10
16
  const INSTALL_RETRY_DELAY_MS = 1_500;
11
17
  /** npm reports a Windows sharing violation as EPERM, EBUSY or errno -4048. */
12
18
  const LOCK_FAILURE = /EPERM|EBUSY|resource busy or locked|-4048/;
19
+ /** How much of npm's error output a failure keeps for its message. */
20
+ const OUTPUT_TAIL = 6_000;
13
21
  /** Bounded walk: a Windows sharing violation matters on a native module or a launcher. */
14
22
  const LOCK_PROBE_SCAN_LIMIT = 10_000;
15
23
  /**
@@ -17,36 +25,42 @@ const LOCK_PROBE_SCAN_LIMIT = 10_000;
17
25
  * build/Release/*.node, so a shallow limit would miss exactly the file this guard exists for.
18
26
  */
19
27
  const LOCK_PROBE_DEPTH = 6;
20
- const runCommand = async (program, args, cwd) => {
21
- try {
22
- const pathKey = process.platform === 'win32' ? Object.keys(process.env).find(key => key.toLowerCase() === 'path') ?? 'PATH' : 'PATH';
23
- const env = { ...process.env, [pathKey]: dirname(process.execPath) + delimiter + (process.env[pathKey] ?? '') };
24
- if (program === process.execPath) {
25
- // npm lifecycle scripts can outlive npm if a timeout kills only its parent.
26
- // Stream their output and retain the updater lock until npm actually closes.
27
- return await new Promise((resolve, reject) => {
28
- const child = spawn(program, args, { cwd, env, windowsHide: true, stdio: 'inherit' });
29
- child.once('error', reject);
30
- child.once('close', (code, signal) => {
31
- if (code === 0 && !signal)
32
- resolve('');
33
- else
34
- reject(new Error(`npm exited with ${signal ?? `code ${code}`}; see the command output above.`));
35
- });
28
+ const runCommand = async (program, args, cwd, options = {}) => {
29
+ const pathKey = process.platform === 'win32' ? Object.keys(process.env).find(key => key.toLowerCase() === 'path') ?? 'PATH' : 'PATH';
30
+ const env = { ...process.env, [pathKey]: dirname(process.execPath) + delimiter + (process.env[pathKey] ?? '') };
31
+ const command = `${program} ${args.join(' ')}`;
32
+ if (options.stream) {
33
+ // npm lifecycle scripts can outlive npm if a timeout kills only its parent, so there is no
34
+ // timeout here: the updater lock is held until npm actually closes. Its error output is shown
35
+ // as it arrives and kept, so a failure can still name the file Windows refused to replace.
36
+ return new Promise((resolvePromise, reject) => {
37
+ const child = spawn(program, args, { cwd, env, windowsHide: true, stdio: ['inherit', 'inherit', 'pipe'] });
38
+ let errors = '';
39
+ child.stderr?.on('data', (chunk) => {
40
+ process.stderr.write(chunk);
41
+ errors = (errors + chunk.toString('utf8')).slice(-OUTPUT_TAIL);
36
42
  });
37
- }
43
+ child.once('error', error => reject(new Error(`${command} could not start: ${error.message}`)));
44
+ child.once('close', (code, signal) => {
45
+ if (code === 0 && !signal) {
46
+ resolvePromise('');
47
+ return;
48
+ }
49
+ const detail = errors.trim();
50
+ reject(new Error(`${command} exited with ${signal ?? `code ${code}`}${detail ? `:\n${detail}` : '; see the npm output above.'}`));
51
+ });
52
+ });
53
+ }
54
+ try {
38
55
  const result = await executeFile(program, args, { cwd, env, windowsHide: true, timeout: 600_000, maxBuffer: 8_388_608 });
39
56
  return result.stdout;
40
57
  }
41
58
  catch (error) {
42
59
  const failure = error;
43
- const detail = (failure.stderr || failure.stdout || failure.message).trim().slice(-6_000);
44
- throw new Error(`${program} ${args.join(' ')} failed${detail ? `:\n${detail}` : ''}`);
60
+ const detail = (failure.stderr || failure.stdout || failure.message).trim().slice(-OUTPUT_TAIL);
61
+ throw new Error(`${command} failed${detail ? `:\n${detail}` : ''}`);
45
62
  }
46
63
  };
47
- function canonicalOrigin(origin) {
48
- return /^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)Andorra-Labs\/Andorra-Code(?:\.git)?\/?$/i.test(origin);
49
- }
50
64
  async function npmCli() {
51
65
  const nodeDirectory = dirname(await realpath(process.execPath));
52
66
  const candidates = [
@@ -68,119 +82,52 @@ function containsPath(text, path) {
68
82
  const target = resolve(path);
69
83
  return normalizePathText(text).includes(normalizePathText(target));
70
84
  }
71
- /**
72
- * The dependency fingerprint: everything an install materializes from. When the fetched revision
73
- * leaves both files byte-identical, the installed tree already satisfies this revision.
74
- */
75
- async function dependencyFingerprint(checkout) {
76
- const parts = [];
77
- for (const name of ['package.json', 'package-lock.json']) {
78
- const value = normalizePathText(await readFile(join(checkout, name), 'utf8').then(text => text, () => ''));
79
- parts.push(`${name}:${value.length}:${value}`);
80
- }
81
- return parts.join('\n');
85
+ /** Paths compare case-insensitively on Windows, where the filesystem does. */
86
+ function samePath(a, b) {
87
+ const left = resolve(a);
88
+ const right = resolve(b);
89
+ return process.platform === 'win32' ? normalizePathText(left) === normalizePathText(right) : left === right;
82
90
  }
83
- /** npm's hidden lockfile is written by npm itself, only after an install completed. */
84
- async function readLockfile(path) {
91
+ const exists = (path) => stat(path).then(() => true, () => false);
92
+ const isDirectory = (path) => stat(path).then(info => info.isDirectory(), () => false);
93
+ /** The name and version a package directory declares, or undefined when it holds no readable manifest. */
94
+ async function readManifest(directory) {
85
95
  try {
86
- const value = JSON.parse(await readFile(path, 'utf8'));
87
- if (!value || typeof value !== 'object')
88
- return undefined;
89
- const { lockfileVersion, packages } = value;
90
- if (typeof lockfileVersion !== 'number' || lockfileVersion < 2)
91
- return undefined;
92
- if (!packages || typeof packages !== 'object')
93
- return undefined;
94
- return packages;
96
+ const value = JSON.parse(await readFile(join(directory, 'package.json'), 'utf8'));
97
+ return value && typeof value === 'object' ? value : undefined;
95
98
  }
96
99
  catch {
97
100
  return undefined;
98
101
  }
99
102
  }
100
- /**
101
- * True when the installed tree is provably complete for the lockfile the checkout carries: both the
102
- * root lockfile and npm's own hidden lockfile parse, every package npm recorded still matches the
103
- * version and hash the root lockfile pins, and every direct dependency the package declares is
104
- * present. The hidden lockfile is written only by a completed install, and it omits the root entry,
105
- * so a legitimate tree has one fewer entry than the lockfile — it is never compared by count, and it
106
- * is never trusted on its own, because a failed install can leave a stale one behind.
107
- */
108
- export async function dependenciesSatisfied(checkout) {
109
- const modules = join(checkout, 'node_modules');
110
- const topLevel = await readLockfile(join(checkout, 'package-lock.json'));
111
- const installed = await readLockfile(join(modules, '.package-lock.json'));
112
- if (!topLevel || !installed)
113
- return false;
114
- let packages = 0;
115
- for (const [key, raw] of Object.entries(installed)) {
116
- if (key === '')
117
- continue;
118
- if (!key.startsWith('node_modules/'))
119
- return false;
120
- if (!raw || typeof raw !== 'object')
121
- return false;
122
- const entry = raw;
123
- if (typeof entry.link === 'boolean') {
124
- const local = typeof entry.resolved === 'string' ? resolve(modules, entry.resolved) : undefined;
125
- if (!local || !(await stat(local).then(info => info.isDirectory(), () => false)))
126
- return false;
127
- }
128
- else {
129
- if (typeof entry.version !== 'string')
130
- return false;
131
- const pinned = topLevel[key];
132
- if (!pinned || typeof pinned !== 'object')
133
- return false;
134
- const expected = pinned;
135
- if (typeof expected.version !== 'string' || expected.version !== entry.version)
136
- return false;
137
- if (typeof expected.integrity === 'string' && expected.integrity !== entry.integrity)
138
- return false;
139
- }
140
- packages += 1;
141
- }
142
- if (packages === 0)
143
- return false;
144
- return directDependenciesInstalled(checkout, topLevel, installed);
103
+ /** The installed release's version, when the directory holds this package. */
104
+ async function installedVersion(directory) {
105
+ const manifest = await readManifest(directory);
106
+ return manifest?.name === PACKAGE_NAME && typeof manifest.version === 'string' ? manifest.version : undefined;
145
107
  }
146
- /**
147
- * Every dependency the package declares must be in the lockfile the hidden lockfile agreed with.
148
- * A package that declares none has nothing to check, which is not a reason to reinstall it.
149
- */
150
- async function directDependenciesInstalled(checkout, topLevel, installed) {
151
- let manifest;
152
- try {
153
- manifest = JSON.parse(await readFile(join(checkout, 'package.json'), 'utf8'));
154
- }
155
- catch {
156
- return false;
157
- }
158
- const fields = ['dependencies', 'devDependencies', 'optionalDependencies'];
159
- for (const field of fields) {
160
- const declared = manifest[field];
161
- if (!declared || typeof declared !== 'object')
162
- continue;
163
- for (const [name, spec] of Object.entries(declared)) {
164
- const key = `node_modules/${name}`;
165
- if (!topLevel[key] || !installed[key])
166
- return false;
167
- // An aliased range pins a different package name, so only its presence can be checked.
168
- if (typeof spec !== 'string' || spec.startsWith('npm:'))
169
- continue;
170
- const expected = topLevel[key];
171
- const actual = installed[key];
172
- if (typeof expected.version !== 'string' || expected.version !== actual.version)
173
- return false;
174
- }
175
- }
176
- return true;
108
+ /** npm prints the answer to `root` and `view` on its last line; anything before it is a notice. */
109
+ function lastLine(output) {
110
+ return output.split(/\r?\n/).map(line => line.trim()).filter(Boolean).at(-1) ?? '';
111
+ }
112
+ function checkoutRefusal(packageRoot) {
113
+ return new Error([
114
+ `andorra update installs releases from npm, but this andorra runs from a source checkout at ${packageRoot}, so nothing was changed.`,
115
+ `To switch to the npm release, run: npm install -g ${PACKAGE_NAME}@latest`,
116
+ 'That replaces an andorra command linked with npm link, and leaves the checkout itself as it is.',
117
+ 'To keep using the checkout, update it from the checkout instead: git pull --ff-only, then npm ci and npm run build.',
118
+ ].join('\n'));
119
+ }
120
+ function notGlobalRefusal(packageRoot, entry) {
121
+ return new Error([
122
+ `andorra update replaces the global npm installation of ${PACKAGE_NAME} (${entry}), but this andorra runs from ${packageRoot}, so nothing was changed.`,
123
+ `Update that copy the way it was installed, or install the CLI globally with: npm install -g ${PACKAGE_NAME}@latest`,
124
+ ].join('\n'));
177
125
  }
178
126
  /**
179
127
  * Walk each installed package directory — the top level and its scope directories — for the files
180
128
  * npm materializes wholesale and Windows can hold open: native modules, which a live process loads
181
- * as a DLL, and launchers, which a running build holds. A scope directory does not consume depth,
182
- * so a scoped package like @scope/pkg/... is reached. Symlinks are skipped so a link into a
183
- * workspace package is never probed twice.
129
+ * as a DLL. A scope directory does not consume depth, so a scoped package like @scope/pkg/... is
130
+ * reached. Symlinks are skipped so a linked package is never probed twice.
184
131
  */
185
132
  async function lockProbeTargets(modules) {
186
133
  const targets = [];
@@ -215,61 +162,87 @@ async function lockProbeTargets(modules) {
215
162
  /** Suffix of the same-directory rename the probe performs and then undoes. */
216
163
  const REPLACEABLE_SUFFIX = '.andorra-replaceable';
217
164
  /**
218
- * Decide whether the installed dependency tree can be replaced in place before an install touches
219
- * it. npm ci deletes the whole tree first, so a single file held open by a live process turns a
220
- * routine update into a broken installation. A same-directory rename is exactly the operation that
221
- * fails with EPERM or EBUSY while a file is in Windows' pending-delete state, and it changes nothing.
165
+ * Decide whether npm can replace the installed package before it tries. npm replaces a global
166
+ * package by moving its directory aside and deleting it afterwards. On Windows the move fails while
167
+ * something inside is open without delete sharing — a process whose working directory is inside the
168
+ * package, or a file already waiting to be deleted. A native module a live process has loaded does
169
+ * not stop the move, only the delete afterwards; sweepRetired deals with that copy. A same-directory
170
+ * rename is exactly the operation that fails, and it changes nothing. Each native module is tried
171
+ * first, so a refusal can name the file.
222
172
  */
223
- async function probeReinstall(checkout) {
224
- const modules = join(checkout, 'node_modules');
225
- if (!(await stat(modules).then(info => info.isDirectory(), () => false))) {
226
- return { state: 'clear', detail: 'nothing is installed yet, so there is nothing to replace' };
227
- }
228
- for (const target of await lockProbeTargets(modules)) {
229
- const probe = `${target}${REPLACEABLE_SUFFIX}`;
230
- try {
231
- await rename(target, probe);
232
- await rename(probe, target);
233
- }
234
- catch (error) {
235
- if (error.code === 'ENOENT')
236
- continue;
237
- const held = await stat(target).then(() => true, () => false);
238
- if (!held)
239
- continue;
240
- return { state: 'locked', path: target, detail: error.message };
173
+ async function probeReplace(packageRoot) {
174
+ const modules = join(packageRoot, 'node_modules');
175
+ if (await isDirectory(modules)) {
176
+ for (const target of await lockProbeTargets(modules)) {
177
+ const probe = `${target}${REPLACEABLE_SUFFIX}`;
178
+ try {
179
+ await rename(target, probe);
180
+ await rename(probe, target);
181
+ }
182
+ catch (error) {
183
+ if (error.code === 'ENOENT')
184
+ continue;
185
+ if (!(await exists(target)))
186
+ continue;
187
+ return { state: 'locked', path: target, detail: error.message };
188
+ }
241
189
  }
242
190
  }
243
191
  try {
244
- const probe = `${modules}${REPLACEABLE_SUFFIX}`;
245
- await rename(modules, probe);
192
+ const probe = `${packageRoot}${REPLACEABLE_SUFFIX}`;
193
+ await rename(packageRoot, probe);
246
194
  try {
247
- await rename(probe, modules);
195
+ await rename(probe, packageRoot);
248
196
  }
249
197
  catch (error) {
250
- throw new Error(`this update moved ${modules} to ${probe} and could not move it back (${error.message}); rename the directory back to node_modules before retrying.`);
198
+ throw new Error(`this update moved ${packageRoot} to ${probe} and could not move it back (${error.message}); rename the directory back before retrying.`);
251
199
  }
252
200
  }
253
201
  catch (error) {
254
- const stillThere = await stat(modules).then(() => true, () => false);
255
- if (stillThere)
256
- return { state: 'locked', path: modules, detail: error.message };
257
- return { state: 'unknown', detail: error.message, path: modules };
202
+ if (await exists(packageRoot))
203
+ return { state: 'locked', path: packageRoot, detail: error.message };
204
+ return { state: 'unknown', detail: error.message, path: packageRoot };
258
205
  }
259
- return { state: 'clear', detail: 'every installed native module and launcher could be replaced' };
206
+ return { state: 'clear', detail: 'the installed package and every native module in it could be replaced' };
260
207
  }
261
- function probeRefusal(checkout, probe) {
262
- const target = probe.path ?? join(checkout, 'node_modules');
263
- const where = normalizePathText(target) === normalizePathText(join(checkout, 'node_modules'))
264
- ? `the installed dependency directory itself (${target})`
265
- : `the installed file ${target}`;
208
+ function probeRefusal(packageRoot, probe) {
209
+ const target = probe.path ?? packageRoot;
210
+ const where = samePath(target, packageRoot) ? `the installed package directory itself (${target})` : `the installed file ${target}`;
266
211
  const guidance = probe.state === 'locked'
267
- ? `A running process holds it open, and Windows keeps it in a pending-delete state until that process exits or unloads the module. CodeGraph holds the codegraph-kernel native module that way. Stop that process — a plain retry cannot release the file — then run andorra update again.`
268
- : `The installed tree could not be inspected or replaced in place. Close any process working in this checkout and check the permissions on ${target}, then run andorra update again.`;
269
- return new Error(`Refusing to reinstall dependencies in ${checkout}: ${where} cannot be replaced.\n${guidance}\nNothing was changed: the existing installation is untouched and the source checkout has not been advanced.`);
212
+ ? 'Something has it open in a way Windows will not let it be moved: most often a terminal or program whose working directory is inside the package, or a file that is still waiting to be deleted while a process holds it. Close that program — a plain retry cannot release it — then run andorra update again.'
213
+ : `The installed package could not be inspected or moved. Close any process using it and check the permissions on ${target}, then run andorra update again.`;
214
+ return new Error(`Refusing to update ${packageRoot}: ${where} cannot be replaced.\n${guidance}\nNothing was changed: the installed Andorra is untouched.`);
215
+ }
216
+ /**
217
+ * npm moves the release it replaces aside, as `.<name>-<random>` beside the package, and deletes it
218
+ * once the new release is in place. On Windows a native module that a running process still has
219
+ * loaded — another Andorra session, CodeGraph — survives that delete, so the copy stays behind and npm
220
+ * only warns. Every update deletes whatever such copies it can, its own and earlier ones, and returns
221
+ * the ones a process still holds. Only directories, never links, and only that exact name pattern.
222
+ */
223
+ async function sweepRetired(entry) {
224
+ const scope = dirname(entry);
225
+ const retired = new RegExp(`^\\.${basename(entry).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}-[A-Za-z0-9_-]+$`);
226
+ const held = [];
227
+ for (const item of await readdir(scope, { withFileTypes: true }).catch(() => [])) {
228
+ if (!item.isDirectory() || !retired.test(item.name))
229
+ continue;
230
+ const path = join(scope, item.name);
231
+ try {
232
+ await rm(path, { recursive: true, force: true });
233
+ }
234
+ catch {
235
+ held.push(path);
236
+ }
237
+ }
238
+ return held;
239
+ }
240
+ function heldNote(held) {
241
+ const one = held.length === 1;
242
+ return `npm could not delete ${one ? 'a replaced copy' : `${held.length} replaced copies`} of Andorra because a running process still has a file in ${one ? 'it' : 'them'} loaded: ${held.join(', ')}. The andorra command no longer uses ${one ? 'it' : 'them'}; andorra update deletes ${one ? 'it' : 'them'} once that process has exited.`;
270
243
  }
271
244
  /** Recover the concrete locked path from the failure npm actually reported, when it named one. */
272
- function reportedLockedFile(message, checkout) {
245
+ function reportedLockedFile(message, packageRoot) {
273
246
  const patterns = [
274
247
  /npm error syscall[^\n]*\n\s*npm error (?:path|dest)\s+(.+)/,
275
248
  /npm error path\s+(.+)/,
@@ -285,61 +258,47 @@ function reportedLockedFile(message, checkout) {
285
258
  candidates.push(match[0].trim().replace(/[.,;:)\]]+$/, ''));
286
259
  for (const candidate of candidates) {
287
260
  const normalized = candidate.replace(/[.,;:)\]]+$/, '');
288
- if (normalized.includes('node_modules') && (containsPath(normalized, checkout) || !/^[A-Za-z]:[\\/]/.test(normalized)))
261
+ if (containsPath(normalized, packageRoot) || containsPath(normalized, dirname(packageRoot)))
289
262
  return normalized;
290
263
  }
291
264
  return undefined;
292
265
  }
293
266
  /**
294
- * Describe a failed dependency install from what is actually on disk afterwards. The wording must
295
- * not promise that a plain retry recovers the installation: a locked file stays locked until the
296
- * process holding it exits, and any part of the tree npm already removed is still missing.
267
+ * Describe a failed install from what is actually on disk afterwards. npm moves the previous
268
+ * release back when an install fails, so the old version usually still runs — but the message says
269
+ * so only after reading it, and never promises that a plain retry releases a locked file.
297
270
  */
298
- function installFailureMessage(checkout, outcome, cause) {
299
- const front = `Source checkout was updated, but reconciling dependencies with npm install failed in ${checkout}; the update is incomplete.`;
271
+ function installFailureMessage(entry, version, outcome, cause) {
272
+ const front = `npm install --global ${PACKAGE_NAME}@${version} failed, so the update did not complete.`;
300
273
  const blocked = outcome.locked
301
- ? `\nThe locked path npm reported is ${outcome.locked}. A running process holds it open, and Windows keeps it in a pending-delete state until that process exits or unloads the module — CodeGraph holds the codegraph-kernel native module that way. Stop that process; a plain retry cannot release the file.`
274
+ ? `\nThe locked path npm reported is ${outcome.locked}. Windows refused to replace it while a process holds it open. Stop that process; a plain retry cannot release the file.`
302
275
  : '';
303
- const damage = outcome.destroyed
304
- ? `\nThe dependency directory is missing, so the andorra CLI will not run and dist/ may be missing too. Free the lock first, then run andorra update again to install dependencies and rebuild the CLI.`
305
- : `\nThe installed dependency tree survived this attempt, so the existing andorra CLI still runs, but this checkout now needs a dependency installation that did not complete. Fix the reported problem and run andorra update again.`;
306
- return `${front}${blocked}${damage}\n${cause.message}`;
276
+ const state = outcome.installed
277
+ ? `\nThe installed Andorra at ${entry} is still version ${outcome.installed}, so the andorra command still runs. Fix the reported problem and run andorra update again.`
278
+ : `\nThe installed Andorra at ${entry} is missing or unreadable, so the andorra command may not run. Fix the reported problem, then reinstall with npm install -g ${PACKAGE_NAME}@latest.`;
279
+ return `${front}${blocked}${state}\n${cause.message}`;
307
280
  }
308
281
  /**
309
- * Reconcile the installed dependencies with npm install, never npm ci.
310
- *
311
- * npm ci deletes node_modules in its first phase and installs afterwards, so one file it cannot
312
- * delete — on Windows a native module a live process has open — destroys the installation: the tree
313
- * is already gone when npm reports the error, and the CLI no longer runs. npm install reconciles the
314
- * tree in place instead, leaving a dependency that already satisfies package-lock.json untouched, so
315
- * a locked native module inside it is not fatal. Do not "simplify" this back to npm ci: the
316
- * destructive first phase is precisely what broke a working installation.
317
- *
318
- * The probe still runs first, so a tree that genuinely cannot be replaced is refused before npm
319
- * touches anything rather than failing half way through.
282
+ * Install one exact release globally. A failure that left the previous release in place and still
283
+ * looks like a transient Windows sharing violation is retried a bounded number of times, after
284
+ * checking that the package can be moved again; anything else is reported at once.
320
285
  */
321
- async function installDependencies(run, sleep, probe, npm, checkout) {
322
- const before = await probe(checkout);
323
- if (before.state !== 'clear')
324
- throw probeRefusal(checkout, before);
286
+ async function installRelease(run, sleep, probe, npm, cwd, packageRoot, entry, version, previous) {
325
287
  for (let attempt = 1; attempt <= INSTALL_ATTEMPTS; attempt += 1) {
326
288
  try {
327
- await run(process.execPath, [npm, 'install', '--include=dev'], checkout);
289
+ await run(process.execPath, [npm, 'install', '--global', `${PACKAGE_NAME}@${version}`, '--prefer-online', '--no-audit', '--no-fund'], cwd, { stream: true });
328
290
  return { ok: true };
329
291
  }
330
292
  catch (error) {
331
293
  const cause = error;
332
- const after = await probe(checkout);
333
- const locked = after.state === 'clear'
334
- ? undefined
335
- : after.path ?? `the installed dependency directory ${join(checkout, 'node_modules')} itself`;
336
- const named = reportedLockedFile(cause.message, checkout);
337
- const destroyed = !(await stat(join(checkout, 'node_modules')).then(info => info.isDirectory(), () => false));
338
- // Retry only a failure that left a complete tree behind: it is transient by definition, and a
339
- // retry can no longer compound damage now that the install reconciles instead of deleting.
340
- if (attempt === INSTALL_ATTEMPTS || destroyed || locked || !LOCK_FAILURE.test(cause.message)) {
341
- return { ok: false, cause, locked: named ?? locked, destroyed };
294
+ const installed = await installedVersion(entry);
295
+ const named = reportedLockedFile(cause.message, packageRoot);
296
+ if (attempt === INSTALL_ATTEMPTS || installed !== previous || !LOCK_FAILURE.test(cause.message)) {
297
+ return { ok: false, cause, locked: named, installed };
342
298
  }
299
+ const again = await probe(packageRoot);
300
+ if (again.state !== 'clear')
301
+ return { ok: false, cause, locked: named ?? again.path, installed };
343
302
  await sleep(INSTALL_RETRY_DELAY_MS);
344
303
  }
345
304
  }
@@ -520,93 +479,91 @@ async function releaseUpdateLock(lockPath, record, sleep) {
520
479
  await unlink(guard).catch(() => { });
521
480
  }
522
481
  }
523
- /** Update the linked installation checkout, never the caller's working directory. */
482
+ /**
483
+ * Replace the global npm installation this command runs from with the latest npm release.
484
+ *
485
+ * Only a global npm installation is updated. A source checkout — one that `npm link` exposes as the
486
+ * global command, or one started directly — is refused without changing anything, and so is any
487
+ * other copy (a project's own dependency, the desktop client's engine): each is updated the way it
488
+ * was installed. The release is resolved from the `latest` dist-tag once and installed by its exact
489
+ * version, so a tag that moves mid-update cannot install something other than what was reported,
490
+ * and a tag that points below the installed version is never followed down.
491
+ */
524
492
  export async function updateInstallation(options = {}) {
525
493
  const run = options.run ?? runCommand;
526
494
  const sleep = options.sleep ?? ((ms) => new Promise(resolve => setTimeout(resolve, ms)));
527
- const probe = options.probe ?? probeReinstall;
495
+ const probe = options.probe ?? probeReplace;
528
496
  const modulePath = await realpath(fileURLToPath(options.moduleUrl ?? import.meta.url));
529
- const checkout = await realpath(resolve(dirname(modulePath), '..', '..'));
530
- let packageName;
497
+ const packageRoot = await realpath(resolve(dirname(modulePath), '..', '..'));
498
+ const manifest = await readManifest(packageRoot);
499
+ if (!manifest)
500
+ throw new Error(`This andorra does not run from an installed ${PACKAGE_NAME} package (no readable package.json in ${packageRoot}), so andorra update cannot update it.`);
501
+ if (manifest.name !== PACKAGE_NAME)
502
+ throw new Error(`Refusing to update an unrelated package: expected ${PACKAGE_NAME} in ${packageRoot}.`);
503
+ const current = typeof manifest.version === 'string' ? semver.valid(manifest.version) : null;
504
+ if (!current)
505
+ throw new Error(`The installed ${PACKAGE_NAME} at ${packageRoot} declares no valid version, so andorra update cannot compare it with npm's release. Reinstall it with npm install -g ${PACKAGE_NAME}@latest.`);
506
+ // A checkout is refused before npm is even located: nothing about it is this updater's to change.
507
+ if (await exists(join(packageRoot, '.git')))
508
+ throw checkoutRefusal(packageRoot);
509
+ const npm = options.npm ?? await npmCli();
510
+ const home = options.lockDirectory ?? configDirectory();
511
+ await mkdir(home, { recursive: true });
512
+ // npm runs outside the package it replaces: a working directory inside it would keep Windows from
513
+ // moving it, and a project's .npmrc in the caller's directory has no say over a global install.
514
+ const cwd = home;
515
+ let globalRoot;
531
516
  try {
532
- packageName = JSON.parse(await readFile(join(checkout, 'package.json'), 'utf8')).name;
533
- }
534
- catch {
535
- throw new Error('This installation is not an Andorra source checkout. Link a clone of Andorra-Labs/Andorra-Code to use andorra update.');
536
- }
537
- if (packageName !== '@andorra-labs/code')
538
- throw new Error('Refusing to update an unrelated package: expected @andorra-labs/code.');
539
- let gitRoot;
540
- try {
541
- gitRoot = await realpath((await run('git', ['rev-parse', '--show-toplevel'], checkout)).trim());
542
- }
543
- catch {
544
- throw new Error('This installation is not a Git source checkout. Link a clone of Andorra-Labs/Andorra-Code to use andorra update.');
517
+ globalRoot = lastLine(await run(process.execPath, [npm, 'root', '--global'], cwd));
545
518
  }
546
- if (gitRoot !== checkout)
547
- throw new Error('Refusing to update: the installation package is not at its Git repository root.');
548
- const lockPath = resolve(checkout, (await run('git', ['rev-parse', '--git-path', 'andorra-update.lock'], checkout)).trim());
519
+ catch (error) {
520
+ throw new Error(`Could not ask npm where global packages are installed, so nothing was changed.\n${error.message}`);
521
+ }
522
+ if (!globalRoot)
523
+ throw new Error('npm did not report where global packages are installed, so nothing was changed.');
524
+ const entry = join(globalRoot, ...PACKAGE_NAME.split('/'));
525
+ const linked = await lstat(entry).then(info => info.isSymbolicLink(), () => false);
526
+ const resolvedEntry = await realpath(entry).catch(() => undefined);
527
+ const isEntry = resolvedEntry !== undefined && samePath(resolvedEntry, packageRoot);
528
+ if (isEntry && linked)
529
+ throw checkoutRefusal(packageRoot);
530
+ if (!isEntry)
531
+ throw notGlobalRefusal(packageRoot, entry);
532
+ const lockPath = join(home, 'update.lock');
549
533
  const lock = await acquireUpdateLock(lockPath, { breakLock: options.breakLock, isRunning: options.isRunning, notify: options.notify, sleep });
550
534
  try {
551
- const branch = (await run('git', ['branch', '--show-current'], checkout)).trim();
552
- if (branch !== 'main')
553
- throw new Error(`Refusing to update branch ${branch || '(detached HEAD)'}. Switch the installation checkout to main yourself, then retry: ${checkout}`);
554
- if ((await run('git', ['status', '--porcelain', '--untracked-files=all'], checkout)).trim()) {
555
- throw new Error(`Refusing to update a dirty installation checkout. Commit, stash, or move your changes first: ${checkout}`);
556
- }
557
- const origin = (await run('git', ['remote', 'get-url', 'origin'], checkout)).trim();
558
- if (!canonicalOrigin(origin))
559
- throw new Error('Refusing to update: origin must be the canonical GitHub HTTPS or SSH URL for Andorra-Labs/Andorra-Code.');
560
- // Resolve prerequisites before advancing the checkout, avoiding a preventable partial update.
561
- const npm = await npmCli();
562
- // Record the dependency fingerprint before the merge: if the fetched revision leaves it
563
- // identical, the installed tree already satisfies it and no install is needed.
564
- const dependenciesBefore = await dependencyFingerprint(checkout);
565
- // Before the checkout is advanced, refuse an installation whose dependency tree cannot be
566
- // replaced at all. Nothing has changed yet at this point, so the refusal costs the user nothing.
567
- const reinstall = await probe(checkout);
568
- if (reinstall.state !== 'clear')
569
- throw probeRefusal(checkout, reinstall);
570
- await run('git', ['fetch', 'origin', 'main'], checkout);
571
- const fetched = (await run('git', ['rev-parse', 'FETCH_HEAD'], checkout)).trim();
572
- if (!/^[a-f0-9]{40,64}$/i.test(fetched))
573
- throw new Error('Git did not return a valid fetched commit; update stopped.');
574
- // A concurrent user edit during fetch must not be carried into the installation update.
575
- if ((await run('git', ['branch', '--show-current'], checkout)).trim() !== 'main'
576
- || (await run('git', ['status', '--porcelain', '--untracked-files=all'], checkout)).trim()) {
577
- throw new Error('The installation branch or files changed during fetch; update stopped without merging.');
578
- }
535
+ let reported;
579
536
  try {
580
- await run('git', ['merge-base', '--is-ancestor', 'HEAD', fetched], checkout);
581
- await run('git', ['merge', '--ff-only', fetched], checkout);
537
+ reported = lastLine(await run(process.execPath, [npm, 'view', `${PACKAGE_NAME}@${RELEASE_TAG}`, 'version', '--prefer-online'], cwd));
582
538
  }
583
539
  catch (error) {
584
- throw new Error(`Cannot fast-forward the installation checkout. Resolve any local divergence on main yourself; no reset or branch switch was performed.\n${error.message}`);
540
+ throw new Error(`Could not look up the latest ${PACKAGE_NAME} release on npm, so nothing was changed. Check the network connection and npm registry settings, then run andorra update again.\n${error.message}`);
585
541
  }
586
- if ((await run('git', ['rev-parse', 'HEAD'], checkout)).trim() !== fetched)
587
- throw new Error('Installation HEAD changed during update; dependencies were not installed. Inspect the checkout before retrying.');
588
- const dependenciesChanged = dependenciesBefore !== await dependencyFingerprint(checkout);
589
- // When package.json and package-lock.json are byte-identical across the update, the installed
590
- // tree already satisfies the fetched revision, so no install is needed at all. This is the case
591
- // that broke: an ordinary source-only update reinstalled everything for no reason.
592
- const reused = !dependenciesChanged && await dependenciesSatisfied(checkout);
593
- if (!reused) {
594
- // The pre-fetch probe proved the tree was replaceable then; re-check it now, because the
595
- // fetch and merge are exactly the window in which a process can take a new lock on it.
596
- const outcome = await installDependencies(run, sleep, probe, npm, checkout);
597
- if (!outcome.ok) {
598
- throw new Error(installFailureMessage(checkout, { locked: outcome.locked, destroyed: outcome.destroyed }, outcome.cause));
599
- }
542
+ const latest = semver.valid(reported);
543
+ if (!latest)
544
+ throw new Error(`npm reported "${reported}" as the latest ${PACKAGE_NAME} release, which is not a version, so nothing was changed.`);
545
+ // Copies an earlier update could not delete are swept whenever the installation ends up current,
546
+ // so they go on the first run after the process holding them has exited.
547
+ const withSweep = async (summary) => {
548
+ const held = await sweepRetired(entry);
549
+ return held.length ? `${summary}\n${heldNote(held)}` : summary;
550
+ };
551
+ if (semver.eq(latest, current))
552
+ return withSweep(`Andorra ${current} is already the latest release on npm; nothing was installed.`);
553
+ if (semver.lt(latest, current)) {
554
+ return `The latest ${PACKAGE_NAME} release on npm is ${latest}, older than the installed ${current}. andorra update never downgrades, so nothing was changed.`;
600
555
  }
601
- try {
602
- await run(process.execPath, [npm, 'run', 'build'], checkout);
603
- }
604
- catch (error) {
605
- const cause = error;
606
- throw new Error(`Source checkout was updated but the CLI build failed. The update is incomplete; fix the reported problem and run andorra update again.\n${cause.message}`);
556
+ const replaceable = await probe(packageRoot);
557
+ if (replaceable.state !== 'clear')
558
+ throw probeRefusal(packageRoot, replaceable);
559
+ const outcome = await installRelease(run, sleep, probe, npm, cwd, packageRoot, entry, latest, current);
560
+ if (!outcome.ok)
561
+ throw new Error(installFailureMessage(entry, latest, { locked: outcome.locked, installed: outcome.installed }, outcome.cause));
562
+ const installed = await installedVersion(entry);
563
+ if (installed !== latest) {
564
+ throw new Error(`npm reported success, but ${entry} now holds ${installed ? `version ${installed}` : 'no readable release'} instead of ${latest}. Check it with andorra --version, then run andorra update again.`);
607
565
  }
608
- const revision = (await run('git', ['rev-parse', '--short=12', 'HEAD'], checkout)).trim();
609
- return `Updated Andorra at ${checkout}\nRevision: ${revision}\nDependencies ${reused ? 'already satisfied this revision, so nothing was installed' : 'reconciled with npm install'} and CLI build completed.`;
566
+ return withSweep(`Updated Andorra from ${current} to ${latest}.\nInstalled ${PACKAGE_NAME}@${latest} from npm into ${entry}.`);
610
567
  }
611
568
  finally {
612
569
  await releaseUpdateLock(lockPath, lock, sleep);