korveniq 1.0.2 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -69,6 +69,31 @@ This installs the `korveniq` command globally:
69
69
  korveniq --version
70
70
  ```
71
71
 
72
+ ### Updates
73
+
74
+ **On 1.0.3 or earlier, upgrade once by hand** (those versions cannot update themselves). Your login and settings are kept:
75
+
76
+ ```bash
77
+ npm install -g korveniq@latest
78
+ korveniq --version
79
+ ```
80
+
81
+ If `korveniq --version` still shows the old number, you have more than one installation: `which -a korveniq` lists
82
+ them, and `npm install -g korveniq@latest --prefix <folder>` updates the one in `<folder>/bin`.
83
+
84
+ From 1.0.4 on, a global npm installation on macOS or Linux that your user owns updates itself: during an interactive session a newer
85
+ stable release is downloaded and verified, and it is installed after you exit. Scripts, pipes, `-p` and `--agent` runs
86
+ are never affected.
87
+
88
+ ```bash
89
+ korveniq update --check # is there a newer version?
90
+ korveniq update # install it now
91
+ korveniq config set autoUpdate false # only be told about new versions
92
+ ```
93
+
94
+ Other installations get the command to run by hand. Details, limits and the checks a release must pass:
95
+ [docs/auto-update.md](docs/auto-update.md).
96
+
72
97
  ---
73
98
 
74
99
  ## 🚀 Quick start
@@ -750,6 +775,8 @@ Colours are plain ANSI, so they follow your terminal's light or dark theme.
750
775
  | `KORVENIQ_NO_ANIMATION` | `1`: no animations (spinner shimmer, smooth streaming, the logo fade-in). |
751
776
  | `KORVENIQ_MARKDOWN` | `0`: show replies as raw Markdown instead of formatted text. |
752
777
  | `KORVENIQ_AUTOCOMPLETE` | `0` / `1`: live suggestions at the prompt off / on. |
778
+ | `KORVENIQ_AUTO_UPDATE` | `0` / `1`: automatic updates off / on, whatever the setting says. |
779
+ | `KORVENIQ_UPDATE_CHECK` | `0`: never look for new versions on its own. |
753
780
  | `KORVENIQ_TIMEOUT_MS` | Per-request timeout in milliseconds (default `60000`). A reply whose status cannot be fetched for twice this long is given up on. |
754
781
  | `KORVENIQ_SEARCH_TIMEOUT_MS` | Deadline of one find_files / search_files call in milliseconds (default `30000`). When it passes, the partial result is returned and marked incomplete. |
755
782
  | `KORVENIQ_SEARCH_STALL_MS` | How long a search may make no progress before it is stopped as a stuck pattern (default `3000`). |
@@ -770,8 +797,8 @@ as the bundled `endpoints.json`).
770
797
 
771
798
  ## 🖥️ Platform notes
772
799
 
773
- Developed and tested on Linux. macOS should behave the same (POSIX shell and
774
- signals) but is not covered by the test run. On **Windows**:
800
+ The test suite runs on macOS and Linux; Windows is not covered by it. On
801
+ **Windows**:
775
802
 
776
803
  - Agent commands run in `cmd.exe`. A `cd` inside a longer command does not
777
804
  carry over to later commands (only a plain `cd <dir>` does), because the
@@ -796,9 +823,11 @@ commands, the browser) inherits it.
796
823
  terminal may be left in raw mode (type `stty sane` or `reset` to fix it), and
797
824
  commands the agent was running keep running in their own process group.
798
825
 
799
- **Tested runtimes.** The suite runs on Node.js 18.17, 20.18, 22.12 and 26.7
800
- (Linux). The installed package (`npm pack` + `npm install -g`) passes the same
801
- end-to-end tests: `KORVENIQ_TEST_BIN=$(which korveniq) npm test`.
826
+ **Tested runtimes (1.0.4).** The full suite runs on Node.js 24.11.1 (macOS and
827
+ Ubuntu 24.04), and the updater tests also on 18.17, 20.18 and 22.12 (Linux). On
828
+ Node.js 18.17 some of the project's test and benchmark tooling does not run (the
829
+ CLI's tests pass on Linux when that is worked around). To run the end-to-end
830
+ tests against an installed package: `KORVENIQ_TEST_BIN=$(which korveniq) npm test`.
802
831
 
803
832
  ---
804
833
 
package/bin/index.js CHANGED
@@ -17,6 +17,8 @@
17
17
  * korveniq login --token <t> sign in with an existing token
18
18
  * korveniq logout remove stored credentials
19
19
  * korveniq whoami show the logged-in user
20
+ * korveniq update [--check] install (or only look for) a newer version
21
+ * korveniq config set <k> <v> change a setting (autoUpdate, updateCheckInterval)
20
22
  *
21
23
  * Global options: --debug (timestamped event log on stderr, stack traces),
22
24
  * --no-color. Exit codes: see lib/errors.js (0 ok, 1 failed, 2 usage,
@@ -30,6 +32,15 @@ if (major < 18 || (major === 18 && minor < 17)) {
30
32
  process.exit(1);
31
33
  }
32
34
 
35
+ // Before anything else is loaded: record that this installation is in use, so an update never replaces files under a
36
+ // running session; if one is replacing them right now, wait and start again with the new files (lib/update-state.js).
37
+ // (--version alone is how the updater checks a new installation, while it holds that lock.)
38
+ const versionOnly = process.argv.length === 3 && ['--version', '-v'].includes(process.argv[2]);
39
+ if (!versionOnly && require('../lib/update-state').startSession()) {
40
+ const again = require('child_process').spawnSync(process.execPath, [...process.execArgv, ...process.argv.slice(1)], { stdio: 'inherit' });
41
+ process.exit(again.status === null ? 1 : again.status);
42
+ }
43
+
33
44
  // Before anything is loaded, so every module sees the same mode.
34
45
  if (process.argv.includes('--debug')) process.env.KORVENIQ_DEBUG = '1';
35
46
 
@@ -204,6 +215,30 @@ program
204
215
  .description('Show the currently logged-in user')
205
216
  .action(() => require('../lib/auth').whoami());
206
217
 
218
+ program
219
+ .command('update')
220
+ .description('Install the latest version of Korveniq')
221
+ .option('--check', 'only say whether a newer version exists')
222
+ .allowExcessArguments(false)
223
+ .action((opts) => require('../lib/update-commands').update(opts));
224
+
225
+ const configCommand = program.command('config').description('Show or change settings (autoUpdate, updateCheckInterval)').allowExcessArguments(false);
226
+ configCommand
227
+ .command('set <key> <value>')
228
+ .description('Change a setting, e.g. config set autoUpdate false')
229
+ .allowExcessArguments(false)
230
+ .action((key, value) => require('../lib/update-commands').configSet(key, value));
231
+ configCommand
232
+ .command('get <key>')
233
+ .description('Print one setting')
234
+ .allowExcessArguments(false)
235
+ .action((key) => require('../lib/update-commands').configGet(key));
236
+ configCommand
237
+ .command('list', { isDefault: true })
238
+ .description('Print the settings')
239
+ .allowExcessArguments(false)
240
+ .action(() => require('../lib/update-commands').configList());
241
+
207
242
  program.addHelpText(
208
243
  'after',
209
244
  `
@@ -214,6 +249,8 @@ Examples:
214
249
  $ cat error.log | korveniq -p "what is wrong?"
215
250
  $ korveniq -p "fix the failing test" --agent --allow edit,shell --output json
216
251
  $ korveniq chats
252
+ $ korveniq update --check
253
+ $ korveniq config set autoUpdate false
217
254
  $ korveniq --resume <chatId>
218
255
  $ korveniq login --token paste a token at a hidden prompt
219
256
  $ korveniq login --token < token.txt
@@ -227,6 +264,8 @@ Environment:
227
264
  KORVENIQ_ASCII=1 ASCII symbols instead of Unicode
228
265
  KORVENIQ_NOTIFICATIONS=0|1 desktop notifications off / on (overrides the setting)
229
266
  KORVENIQ_AUTOCOMPLETE=0|1 live suggestions at the prompt off / on
267
+ KORVENIQ_AUTO_UPDATE=0|1 automatic updates off / on (overrides the setting)
268
+ KORVENIQ_UPDATE_CHECK=0 never look for new versions on its own
230
269
  NO_COLOR=1 same as --no-color
231
270
  `
232
271
  );
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "profile": "beta",
3
- "version": "1.0.2",
4
- "builtAt": "2026-11-25T16:01:13.581Z"
3
+ "version": "1.0.4",
4
+ "builtAt": "2026-11-26T17:02:56.446Z"
5
5
  }
package/lib/chat.js CHANGED
@@ -2589,10 +2589,18 @@ async function startChat(opts = {}) {
2589
2589
  // The prompt says when autonomous mode is on, so it is never on unnoticed.
2590
2590
  const promptFor = () => `${autoMode(session) ? `${theme.warn('auto')} ` : ''}${theme.userPrompt('>')} `;
2591
2591
 
2592
+ // Looks for a new version in the background (interactive terminals only). It speaks only between turns, and files
2593
+ // are replaced only after the conversation has ended.
2594
+ const { Session: UpdateSession } = require('./update');
2595
+ const updates = new UpdateSession();
2596
+ updates.tick();
2597
+
2592
2598
  // The REPL: prompt -> answer -> prompt, until /exit, Ctrl+D or Ctrl+C twice.
2593
2599
  // Nothing that happens in a turn ends the session.
2594
2600
  for (;;) {
2595
2601
  notifications.manager().transition('idle');
2602
+ updates.notice();
2603
+ updates.tick();
2596
2604
  const input = await readPrompt({
2597
2605
  prompt: promptFor(),
2598
2606
  history: session.inputHistory,
@@ -2624,7 +2632,9 @@ async function startChat(opts = {}) {
2624
2632
  if (bg.length && interactive) ui.hint(`Stopping ${bg.length} background process${bg.length === 1 ? '' : 'es'}…`);
2625
2633
  if (bg.length) await session.tools.processes.stopAll();
2626
2634
  if (interactive) ui.hint('Goodbye!');
2627
- exit(EXIT.OK);
2635
+ session.close();
2636
+ await updates.finish(); // the last thing this process does: it may replace its own files
2637
+ process.exit(EXIT.OK);
2628
2638
  }
2629
2639
 
2630
2640
  /**
package/lib/settings.js CHANGED
@@ -22,8 +22,12 @@
22
22
  * "maxSuggestions": 8
23
23
  * }
24
24
  *
25
+ * "autoUpdate": true, install new versions automatically (lib/update.js)
26
+ * "updateCheckInterval": 60 minutes between checks for a new version
27
+ *
25
28
  * Environment overrides (win over the file, never written to it):
26
29
  * KORVENIQ_NOTIFICATIONS=0|1 KORVENIQ_AUTOCOMPLETE=0|1
30
+ * KORVENIQ_AUTO_UPDATE=0|1 KORVENIQ_UPDATE_CHECK=0 (never look for new versions)
27
31
  */
28
32
 
29
33
  const config = require('./config');
@@ -44,6 +48,10 @@ const DEFAULTS = Object.freeze({
44
48
  }),
45
49
  });
46
50
 
51
+ const DEFAULT_CHECK_MINUTES = 60;
52
+ const MIN_CHECK_MINUTES = 5;
53
+ const MAX_CHECK_MINUTES = 7 * 24 * 60;
54
+
47
55
  const NOTIFICATION_KEYS = ['onCompletion', 'onQuestion', 'onApproval', 'onError', 'onConnectionLoss'];
48
56
 
49
57
  /** "0", "false", "off", "no" -> false; "1", "true", "on", "yes" -> true; anything else -> undefined. */
@@ -93,6 +101,32 @@ function autocomplete() {
93
101
  return s;
94
102
  }
95
103
 
104
+ /**
105
+ * The effective update settings. A settings file that cannot be read may say "autoUpdate": false, so then nothing is
106
+ * installed automatically.
107
+ */
108
+ function updates() {
109
+ let saved;
110
+ let readable = true;
111
+ try {
112
+ saved = config.load();
113
+ } catch {
114
+ saved = {};
115
+ readable = false;
116
+ }
117
+ let auto = readable && saved.autoUpdate !== false;
118
+ const env = envFlag('KORVENIQ_AUTO_UPDATE');
119
+ if (env !== undefined) auto = env;
120
+ const n = saved.updateCheckInterval;
121
+ const checkIntervalMinutes = Number.isInteger(n) ? Math.min(MAX_CHECK_MINUTES, Math.max(MIN_CHECK_MINUTES, n)) : DEFAULT_CHECK_MINUTES;
122
+ return { auto, check: envFlag('KORVENIQ_UPDATE_CHECK') !== false, checkIntervalMinutes };
123
+ }
124
+
125
+ /** Save one top-level setting (the caller validates it); everything else in config.json is kept. */
126
+ function set(key, value) {
127
+ config.update({ [key]: value });
128
+ }
129
+
96
130
  /**
97
131
  * Change some notification settings and save them. Only the given keys are
98
132
  * written; the rest of config.json (token, other sections) is untouched.
@@ -105,4 +139,4 @@ function updateNotifications(patch) {
105
139
  return notifications();
106
140
  }
107
141
 
108
- module.exports = { DEFAULTS, NOTIFICATION_KEYS, notifications, autocomplete, updateNotifications, envFlag };
142
+ module.exports = { DEFAULTS, NOTIFICATION_KEYS, MIN_CHECK_MINUTES, MAX_CHECK_MINUTES, notifications, autocomplete, updates, set, updateNotifications, envFlag };
@@ -490,7 +490,8 @@ function extractToolCalls({ text = '', message = null, nonces = null, markerHint
490
490
  /* not a call: just prose that mentions the tag */
491
491
  }
492
492
  }
493
- if (well) calls.push({ name: null, misplaced: true, error: MISPLACED_HINT });
493
+ // `raw` tells two different refused blocks apart (the loop guard counts the SAME failing call, not every refusal).
494
+ if (well) calls.push({ name: null, misplaced: true, error: MISPLACED_HINT, raw: text.slice(r.bodyStart, r.bodyEnd) });
494
495
  } else if (r.kind === 'xml') {
495
496
  const { open } = r;
496
497
  const body = text.slice(r.bodyStart, r.bodyEnd);
@@ -0,0 +1,125 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * lib/update-commands.js: `korveniq update [--check]` and `korveniq config`.
5
+ * A manual update goes through exactly the same verification and installation as an automatic one.
6
+ */
7
+
8
+ const updater = require('./update');
9
+ const installer = require('./update-install');
10
+ const state = require('./update-state');
11
+ const view = require('./update-view');
12
+ const settings = require('./settings');
13
+ const ui = require('./ui');
14
+ const { CliError, EXIT } = require('./errors');
15
+ const pkg = require('../package.json');
16
+
17
+ async function update({ check: checkOnly = false } = {}, { install = state.detect(), current = pkg.version, cacheFile = updater.CACHE_FILE } = {}) {
18
+ const controller = new AbortController();
19
+ const stopSignals = require('./shutdown').add(() => controller.abort());
20
+ try {
21
+ const spinner = ui.spinner('Checking for updates…').start();
22
+ const result = await updater.check({ force: true, signal: controller.signal, retries: 1, timeoutMs: 10_000, cacheFile }).finally(() => spinner.stop());
23
+ if (!result.manifest && result.error.code === 'KEY_UNKNOWN') {
24
+ throw new CliError('New releases cannot be verified automatically', { cause: `${result.error.message}.`, action: 'Nothing was installed. Upgrade once by hand:', commands: [install.command] });
25
+ }
26
+ if (!result.manifest) {
27
+ const action = result.error.code === 'UNTRUSTED' ? 'Nothing was installed. Your current version is unchanged.' : 'Check your connection and try again. Your current version is unchanged.';
28
+ throw new CliError('Could not check for updates', { cause: `${result.error.message}.`, action });
29
+ }
30
+ const manifest = result.manifest;
31
+ const onDisk = install.supported ? installer.installedVersion(install) : current;
32
+ if (!updater.isOffer(manifest, onDisk)) {
33
+ ui.success(`Korveniq v${onDisk} is up to date.`);
34
+ return;
35
+ }
36
+ if (checkOnly) {
37
+ view.print([`Update available: v${onDisk} ${ui.symbols.arrow} v${manifest.version}`]);
38
+ if (install.supported) ui.commands(['korveniq update']);
39
+ else {
40
+ ui.hint(install.message);
41
+ ui.commands([install.command]);
42
+ }
43
+ return;
44
+ }
45
+ if (!install.supported) {
46
+ throw new CliError(`v${manifest.version} is available, but this installation cannot be updated automatically`, { cause: install.message, action: 'Update it with:', commands: [install.command] });
47
+ }
48
+
49
+ const failure = (err) =>
50
+ new CliError('The update could not be completed', {
51
+ cause: `${err.message}.`.replace(/\.\.$/, '.'),
52
+ action: err.broken ? 'Reinstall:' : 'Your current version remains available. Try again, or update by hand:',
53
+ commands: [install.command],
54
+ exitCode: err.code === 'ABORTED' ? EXIT.INTERRUPTED : EXIT.ERROR,
55
+ error: err,
56
+ });
57
+
58
+ ui.info(`Update available: v${onDisk} ${ui.symbols.arrow} v${manifest.version}`);
59
+ const reporter = view.downloadReporter();
60
+ let outcome;
61
+ try {
62
+ if ((await updater.stage(install, manifest, { signal: controller.signal, onProgress: reporter.update, manual: true })) === 'busy') {
63
+ throw new CliError('Another update is being downloaded', { action: 'Wait a moment and run `korveniq update` again.' });
64
+ }
65
+ reporter.done();
66
+ ui.success('Downloaded and verified.');
67
+ outcome = installer.apply(install);
68
+ } catch (err) {
69
+ reporter.done();
70
+ throw err instanceof updater.UpdateError ? failure(err) : err;
71
+ }
72
+ if (outcome.status === 'installed') view.print(view.installed(outcome.version));
73
+ else if (outcome.status === 'busy') {
74
+ throw new CliError(`v${manifest.version} is downloaded but not installed yet`, {
75
+ cause: { npm: 'npm is changing this installation right now.', changed: 'The installation was changed by another program.' }[outcome.reason] || 'Another Korveniq process is running from this installation.',
76
+ action: 'Close it and run `korveniq update` again. An interactive session also installs it when it exits alone.',
77
+ });
78
+ } else ui.success(`Korveniq v${installer.installedVersion(install)} is already installed.`);
79
+ } finally {
80
+ stopSignals();
81
+ }
82
+ }
83
+
84
+ // ---------------------------------------------------------------------------
85
+ // korveniq config: only the keys listed here; credentials are never readable or writable through it
86
+ // ---------------------------------------------------------------------------
87
+
88
+ const KEYS = {
89
+ autoUpdate: {
90
+ parse: (v) => (/^(true|on|1|yes)$/i.test(v) ? true : /^(false|off|0|no)$/i.test(v) ? false : undefined),
91
+ expected: 'true or false',
92
+ read: () => settings.updates().auto,
93
+ },
94
+ updateCheckInterval: {
95
+ parse: (v) => (/^\d+$/.test(v) && Number(v) >= settings.MIN_CHECK_MINUTES && Number(v) <= settings.MAX_CHECK_MINUTES ? Number(v) : undefined),
96
+ expected: `a number of minutes from ${settings.MIN_CHECK_MINUTES} to ${settings.MAX_CHECK_MINUTES}`,
97
+ read: () => settings.updates().checkIntervalMinutes,
98
+ },
99
+ };
100
+
101
+ function known(key) {
102
+ if (!Object.prototype.hasOwnProperty.call(KEYS, key)) {
103
+ throw new CliError('Unknown setting', { action: `Available settings: ${Object.keys(KEYS).join(', ')}.`, exitCode: EXIT.USAGE });
104
+ }
105
+ return KEYS[key];
106
+ }
107
+
108
+ function configSet(key, value) {
109
+ const spec = known(key);
110
+ const parsed = spec.parse(String(value).trim());
111
+ if (parsed === undefined) throw new CliError(`Invalid value for ${key}`, { action: `Use ${spec.expected}.`, exitCode: EXIT.USAGE });
112
+ settings.set(key, parsed);
113
+ ui.success(`${key} = ${parsed}`);
114
+ if (key === 'autoUpdate' && settings.envFlag('KORVENIQ_AUTO_UPDATE') !== undefined) ui.hint('KORVENIQ_AUTO_UPDATE is set and overrides this setting.');
115
+ }
116
+
117
+ function configGet(key) {
118
+ process.stdout.write(`${known(key).read()}\n`);
119
+ }
120
+
121
+ function configList() {
122
+ for (const [key, spec] of Object.entries(KEYS)) process.stdout.write(`${key}=${spec.read()}\n`);
123
+ }
124
+
125
+ module.exports = { update, configSet, configGet, configList, KEYS };
@@ -0,0 +1,287 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * lib/update-install.js
5
+ * -----------------------------------------------------------------------------
6
+ * Put a staged package in place of the installed one, as a transaction. npm is not run and no script of the package
7
+ * or of its dependencies is executed during installation (the official package bundles its dependencies, so
8
+ * unpacking it is the whole installation).
9
+ *
10
+ * 1 take apply.lock; repair anything an interrupted installation left; stop if another CLI or npm is active
11
+ * 2 read the staged file once; verify signature and checksum on exactly those bytes
12
+ * 3 unpack into a new folder; check the package; run it with --version
13
+ * 4 write the journal; point the `korveniq` command at the recovery launcher (outside the package)
14
+ * 5 rename installed -> previous, new -> installed; run it with --version
15
+ * 6 mark the journal committed; point the command back; clean up
16
+ *
17
+ * Any failure, and any interruption (kill, crash, power loss), is settled by lib/update-recover.js: until step 6 the
18
+ * previous version is restored, from step 6 the new one stays. At every instant the command resolves to a program.
19
+ * Everything here is synchronous on purpose: no signal handler runs in the middle.
20
+ *
21
+ * All modules are loaded up front: after step 5 the files of this very program belong to another version.
22
+ */
23
+
24
+ const fs = require('fs');
25
+ const path = require('path');
26
+ const crypto = require('crypto');
27
+ const { spawnSync } = require('child_process');
28
+ const semver = require('./update-semver');
29
+ const source = require('./update-source');
30
+ const tar = require('./update-tar');
31
+ const state = require('./update-state');
32
+ const recovery = require('./update-recover');
33
+
34
+ const { UpdateError, PACKAGE } = source;
35
+ const VERIFY_TIMEOUT_MS = 20_000;
36
+
37
+ const refuse = (why) => new UpdateError('PACKAGE', `The new package was refused: ${why}`);
38
+
39
+ function readPackage(dir) {
40
+ const json = state.readJson(path.join(dir, 'package.json'));
41
+ if (!json) throw refuse('a package.json is missing or damaged');
42
+ return json;
43
+ }
44
+
45
+ const installedVersion = (install) => readPackage(install.root).version;
46
+
47
+ /** Does this Node satisfy ">=a[.b[.c]]"? Any other form is refused: it cannot be judged. */
48
+ function nodeSatisfies(range, version = process.versions.node) {
49
+ if (range === undefined) return true;
50
+ const m = /^>=\s*(\d+)(?:\.(\d+))?(?:\.(\d+))?$/.exec(String(range).trim());
51
+ if (!m) return false;
52
+ return semver.compare(version, `${m[1]}.${m[2] || 0}.${m[3] || 0}`) >= 0;
53
+ }
54
+
55
+ /** No package may need an install step, and every dependency must already be inside the package. */
56
+ function checkDependencies(top) {
57
+ const queue = [top];
58
+ const done = new Set();
59
+ while (queue.length) {
60
+ const dir = queue.pop();
61
+ if (done.has(dir)) continue;
62
+ done.add(dir);
63
+ const pkg = readPackage(dir);
64
+ const hooks = ['preinstall', 'install', 'postinstall'].filter((s) => pkg.scripts && pkg.scripts[s]);
65
+ if (hooks.length) throw refuse(`it needs install scripts (${hooks[0]})`);
66
+ if (fs.existsSync(path.join(dir, 'binding.gyp'))) throw refuse('it needs native compilation');
67
+ for (const name of Object.keys(pkg.dependencies || {})) {
68
+ if (!/^(@[a-z0-9~-][a-z0-9._~-]*\/)?[a-z0-9~-][a-z0-9._~-]*$/i.test(name)) throw refuse('a dependency has an invalid name');
69
+ let from = dir;
70
+ let found = null;
71
+ while (!found) {
72
+ const candidate = path.join(from, 'node_modules', name);
73
+ if (fs.existsSync(path.join(candidate, 'package.json'))) found = candidate;
74
+ else if (from === top) throw refuse(`the dependency "${name}" is not included`);
75
+ else from = path.dirname(from);
76
+ }
77
+ queue.push(found);
78
+ }
79
+ }
80
+ }
81
+
82
+ /** Is the unpacked folder the release we expect, and no weaker than the installed one? */
83
+ function checkPackage(dir, version, currentRoot) {
84
+ const pkg = readPackage(dir);
85
+ if (pkg.name !== PACKAGE) throw refuse('it is a different package');
86
+ if (pkg.version !== version) throw refuse('its version is not the one announced');
87
+ const bin = pkg.bin;
88
+ if (!bin || Object.keys(bin).join() !== PACKAGE || bin[PACKAGE] !== 'bin/index.js') throw refuse('it installs a different command');
89
+ if (!nodeSatisfies(pkg.engines && pkg.engines.node)) throw refuse(`it needs another Node.js version (${pkg.engines.node})`);
90
+ const entry = path.join(dir, 'bin', 'index.js');
91
+ if (!fs.existsSync(entry) || !fs.readFileSync(entry, 'utf8').startsWith('#!/usr/bin/env node')) throw refuse('its command file is missing');
92
+ // A restricted build (sandbox on, fail closed: lib/build-profile.js) is never replaced by an unrestricted one.
93
+ if (fs.existsSync(path.join(currentRoot, 'lib', 'build-profile.json'))) {
94
+ const profile = state.readJson(path.join(dir, 'lib', 'build-profile.json'));
95
+ if (!profile || profile.profile !== 'beta') throw refuse('it does not carry the security restrictions of the installed version');
96
+ }
97
+ checkDependencies(dir);
98
+ fs.chmodSync(entry, 0o755);
99
+ }
100
+
101
+ /** Run `<entry> --version` and require exactly the expected answer. */
102
+ function runVersion(entry, version) {
103
+ const env = { ...process.env };
104
+ for (const key of Object.keys(env)) if (/^(NODE_OPTIONS|KORVENIQ_TOKEN|KORVENIQ_DEBUG|FORCE_COLOR|NODE_PATH)$/i.test(key)) delete env[key];
105
+ const r = spawnSync(process.execPath, [entry, '--version'], { env, encoding: 'utf8', timeout: VERIFY_TIMEOUT_MS, killSignal: 'SIGKILL', maxBuffer: 64 * 1024 });
106
+ return r.status === 0 && r.stdout.trim() === version;
107
+ }
108
+
109
+ // ---------------------------------------------------------------------------
110
+ // Staging
111
+ // ---------------------------------------------------------------------------
112
+
113
+ const stagedFile = (install, version) => path.join(install.stateDir, `staged-${version}.tgz`);
114
+ const stagedJson = (install) => path.join(install.stateDir, 'staged.json');
115
+
116
+ /** The package waiting to be installed: { version, integrity, signatures, tarball, manual } or null. */
117
+ function readStaged(install) {
118
+ const meta = state.readJson(stagedJson(install));
119
+ if (!meta || !semver.isStable(meta.version) || !fs.existsSync(stagedFile(install, meta.version))) return null;
120
+ return meta;
121
+ }
122
+
123
+ function clearStaged(install) {
124
+ for (const name of fs.readdirSync(install.stateDir)) {
125
+ if (name === 'staged.json' || /^staged-.*\.tgz$/.test(name)) fs.rmSync(path.join(install.stateDir, name), { force: true });
126
+ }
127
+ }
128
+
129
+ /** Save verified bytes for a later installation (caller holds stage.lock). */
130
+ function writeStaged(install, manifest, bytes, { manual = false } = {}) {
131
+ source.verifySignature(manifest);
132
+ source.verifyBytes(bytes, manifest);
133
+ const part = path.join(install.stateDir, `${crypto.randomBytes(8).toString('hex')}.part`);
134
+ try {
135
+ fs.writeFileSync(part, bytes, { flag: 'wx', mode: 0o600 });
136
+ fs.renameSync(part, stagedFile(install, manifest.version));
137
+ } finally {
138
+ fs.rmSync(part, { force: true });
139
+ }
140
+ const { name, version, integrity, signatures, tarball } = manifest;
141
+ state.writeJson(stagedJson(install), { name, version, integrity, signatures, tarball, manual });
142
+ for (const old of fs.readdirSync(install.stateDir)) {
143
+ if (/^staged-.*\.tgz$/.test(old) && old !== `staged-${version}.tgz`) fs.rmSync(path.join(install.stateDir, old), { force: true });
144
+ }
145
+ }
146
+
147
+ const failedJson = (install) => path.join(install.stateDir, 'failed.json');
148
+ const readFailure = (install) => state.readJson(failedJson(install));
149
+
150
+ // ---------------------------------------------------------------------------
151
+ // Installation
152
+ // ---------------------------------------------------------------------------
153
+
154
+ /**
155
+ * Install the staged package.
156
+ * @param {{ rename?: Function, step?: Function }} [hooks] for tests: replace the swap's renames, observe each step
157
+ * @returns {{ status: 'installed'|'none'|'busy', version?: string, from?: string, reason?: 'sessions'|'npm'|'changed'|'lock' }}
158
+ * busy: someone else is using or changing the installation; the staged package stays for later.
159
+ * @throws {UpdateError} the installed version is unchanged (or was put back)
160
+ */
161
+ function apply(install, { rename = fs.renameSync, step = () => {} } = {}) {
162
+ state.ensureStateDir(install);
163
+ const lock = state.acquire(path.join(install.stateDir, 'apply.lock'));
164
+ if (!lock) return { status: 'busy', reason: 'lock' };
165
+ const paths = recovery.layout(install.stateDir);
166
+ const work = path.join(install.stateDir, `work-${crypto.randomBytes(8).toString('hex')}`);
167
+ let version = null;
168
+ let journalled = false;
169
+ let ids = null;
170
+ const busy = (reason) => ({ status: 'busy', version, reason });
171
+ try {
172
+ step('locked');
173
+ if (state.npmBusy(install.modulesDir)) return busy('npm');
174
+ // An earlier installation that was interrupted comes first.
175
+ const earlier = fs.existsSync(paths.journal) ? recovery.settle(paths).outcome : null;
176
+ if (earlier === 'busy') return busy('npm');
177
+ if (earlier === 'broken') {
178
+ throw new UpdateError('INSTALL', `An earlier update was interrupted and cannot be repaired. Reinstall with: ${install.command}`, { broken: true });
179
+ }
180
+ // With no journal, work folders are only leftovers of an installation that was killed.
181
+ for (const name of fs.readdirSync(install.stateDir)) {
182
+ if (name.startsWith('work-')) fs.rmSync(path.join(install.stateDir, name), { recursive: true, force: true });
183
+ }
184
+ const meta = readStaged(install);
185
+ if (!meta) return { status: 'none' };
186
+ version = meta.version;
187
+ const oldId = recovery.identity(install.root);
188
+ const from = installedVersion(install);
189
+ // Someone else installed this or something newer meanwhile: never go backwards.
190
+ if (!semver.isUpgrade(version, from)) {
191
+ clearStaged(install);
192
+ return { status: 'none' };
193
+ }
194
+ if (state.otherSessions(install).length) return busy('sessions');
195
+
196
+ const manifest = { ...meta, name: PACKAGE };
197
+ source.verifySignature(manifest);
198
+ const file = stagedFile(install, version);
199
+ if (!fs.lstatSync(file).isFile()) throw new UpdateError('INTEGRITY', 'The staged package is not a regular file');
200
+ const bytes = fs.readFileSync(file);
201
+ source.verifyBytes(bytes, manifest);
202
+ step('verified');
203
+
204
+ fs.mkdirSync(work, { mode: 0o700 });
205
+ const fresh = path.join(work, 'new');
206
+ const previous = path.join(work, 'previous');
207
+ tar.extract(bytes, fresh, { sync: true });
208
+ step('extracted');
209
+ checkPackage(fresh, version, install.root);
210
+ if (!runVersion(path.join(fresh, 'bin', 'index.js'), version)) throw refuse('it does not start');
211
+ step('checked');
212
+
213
+ // Last look before anything is touched.
214
+ if (!lock.owned()) return busy('lock');
215
+ if (state.otherSessions(install).length) return busy('sessions');
216
+ if (state.npmBusy(install.modulesDir)) return busy('npm');
217
+ if (recovery.identity(install.root) !== oldId || installedVersion(install) !== from) return busy('changed');
218
+ if (path.resolve(path.dirname(paths.link), fs.readlinkSync(paths.link)) !== paths.entry) return busy('changed');
219
+
220
+ recovery.installLauncher(paths);
221
+ ids = [oldId, recovery.identity(fresh)];
222
+ const journal = { work: path.basename(work), from, to: version, oldId, newId: ids[1], committed: false };
223
+ recovery.writeJournal(paths, journal);
224
+ journalled = true;
225
+ step('journalled');
226
+ recovery.setLink(paths.link, path.relative(path.dirname(paths.link), paths.launcher));
227
+ step('diverted');
228
+
229
+ // Again, with nothing between this and the rename: npm takes no lock of ours.
230
+ if (state.npmBusy(install.modulesDir) || recovery.identity(install.root) !== oldId) throw new UpdateError('BUSY', 'The installation is being changed by another program');
231
+ rename(install.root, previous);
232
+ step('moved-old');
233
+ if (recovery.identity(previous) !== oldId) throw new UpdateError('BUSY', 'The installation was changed by another program during the update');
234
+ rename(fresh, install.root);
235
+ step('moved-new');
236
+ recovery.syncPath(install.modulesDir);
237
+ if (installedVersion(install) !== version || !runVersion(paths.entry, version)) {
238
+ throw new UpdateError('INSTALL', 'The installed new version did not pass its check');
239
+ }
240
+ step('verified-new');
241
+ recovery.writeJournal(paths, { ...journal, committed: true });
242
+ step('committed');
243
+
244
+ // The new version is installed. What follows is tidying; if it fails, the next start finishes it.
245
+ try {
246
+ recovery.settle(paths, { step });
247
+ clearStaged(install);
248
+ fs.rmSync(failedJson(install), { force: true });
249
+ } catch {
250
+ /* repaired later */
251
+ }
252
+ return { status: 'installed', version, from };
253
+ } catch (err) {
254
+ let wrapped = err instanceof UpdateError ? err : new UpdateError('INSTALL', `The update could not be installed (${err.code || err.message})`);
255
+ // Did somebody else get in the way? (Judged before our own rollback changes the picture.)
256
+ const current = journalled ? recovery.identity(install.root) : null;
257
+ const outside = journalled && (wrapped.code === 'BUSY' || state.npmBusy(install.modulesDir) || (current !== null && !ids.includes(current)));
258
+ if (journalled) {
259
+ let outcome = 'broken';
260
+ try {
261
+ outcome = recovery.settle(paths).outcome;
262
+ } catch {
263
+ /* the launcher stays in place and tries again */
264
+ }
265
+ if (outside && outcome !== 'broken') return busy(state.npmBusy(install.modulesDir) ? 'npm' : 'changed');
266
+ if (outcome === 'broken') wrapped = new UpdateError('INSTALL', `The update failed and the previous version could not be put back yet. Run korveniq again, or reinstall with: ${install.command}`, { broken: true });
267
+ }
268
+ if (version) {
269
+ try {
270
+ state.writeJson(failedJson(install), { version, at: Date.now(), code: wrapped.code, message: wrapped.message });
271
+ clearStaged(install);
272
+ } catch {
273
+ /* the original error matters more */
274
+ }
275
+ }
276
+ throw wrapped;
277
+ } finally {
278
+ try {
279
+ // While a journal exists, the work folder may hold the only copy of the old version.
280
+ if (!fs.existsSync(paths.journal)) fs.rmSync(work, { recursive: true, force: true });
281
+ } finally {
282
+ lock.release();
283
+ }
284
+ }
285
+ }
286
+
287
+ module.exports = { apply, readStaged, writeStaged, clearStaged, readFailure, installedVersion, checkPackage, nodeSatisfies };