clavarium 0.2.485-next.1 → 0.2.487-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -89,6 +89,11 @@ const ASK_EVERY_MS = 6 * 3600_000;
89
89
  had it): nothing of it ran here, so it is tried again by itself, this long after, this many times at most. */
90
90
  export const FETCH_AGAIN_MS = 30 * 60_000;
91
91
  export const FETCH_TRIES = 3;
92
+ /* NOT RACING THE REGISTRY (17-11: 0.2.228-beta.1 asked of npm the minute it was tagged, refused; the same
93
+ install worked 20 minutes later): a version is installed by itself only once it has been out this long --
94
+ since its time in the registry (`time`), or since this updater first saw it when the registry says none.
95
+ Asked by the owner (Update, Try again): at once. */
96
+ export const RELEASE_SETTLE_MS = 10 * 60_000;
92
97
  /* Between "Switching" said in state.json and the server stopped: the pages ask the server every
93
98
  10 seconds at most (app.js), and the server says it in each answer (updates.mjs, notice): each
94
99
  gives way to the maintenance page before the server goes. */
@@ -96,6 +101,8 @@ export const NOTICE_MS = 15_000;
96
101
  const PROVENANCE = 'https://slsa.dev/provenance/v1';
97
102
  /* What the log of a failure keeps, at most (history entry `log`, shown behind "See the log"). */
98
103
  const LOG_MAX = 12_000;
104
+ /* Of npm's own debug log (in its cache, which goes with the attempt): the last lines kept in the history. */
105
+ const NPM_LOG_LINES = 40;
99
106
  /* Set beside the server's unit by the updater (root): a crash loop never locks the service out, so a
100
107
  restart asked later (an update, the watchdog) still starts it. */
101
108
  export const DROP_IN = '/etc/systemd/system/clavarium.service.d/restart.conf';
@@ -263,6 +270,37 @@ export async function ensureMaintenance({ caddyfile = CADDYFILE, caddy = CADDY,
263
270
  }
264
271
 
265
272
  export class Refused extends Error {}
273
+ /* NOTHING OF THE VERSION RAN: npm could not install it, or the registry did not answer about it (not there
274
+ yet, a mirror behind, the network). Said in the history as `fetch: true`, tried again by itself later.
275
+ `log`: what npm said, for "See the log". */
276
+ export class FetchFailed extends Error {
277
+ constructor(message, { log } = {}) { super(message); this.log = log; }
278
+ }
279
+
280
+ /* WHAT A LOG MUST NEVER SHOW: npm's debug log can carry the registry's credentials (an .npmrc token, an
281
+ Authorization header, a URL with a password). Each is put as ***. */
282
+ export function redact(text) {
283
+ return String(text ?? '')
284
+ .replace(/\b(proxy-authorization|authorization)(["']?\s*[:=]\s*["']?)(?:(bearer|basic|token)\s+)?[^\s"',;}]+/gi, (_, k, sep, scheme) => `${k}${sep}${scheme ? `${scheme} ` : ''}***`)
285
+ .replace(/\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]{6,}/gi, '$1 ***')
286
+ .replace(/((?:_authToken|_auth|_password|authToken|token|password|passwd|secret|otp)["']?\s*[=:]\s*["']?)[^\s"',;}]+/gi, '$1***')
287
+ .replace(/\bnpm_[A-Za-z0-9]{16,}\b/g, 'npm_***')
288
+ .replace(/\bgh[opsur]_[A-Za-z0-9]{16,}\b/g, 'gh*_***')
289
+ .replace(/(\/\/)[^\s/@:]+:[^\s/@]+@/g, '$1***@');
290
+ }
291
+
292
+ /* The end of npm's own debug log, from the cache it was given: the last lines that say something (its
293
+ `silly` lines, its call stack and its pointer to itself left out), each bounded, credentials taken out. '' when there is none. */
294
+ export function npmLogTail(cache, lines = NPM_LOG_LINES) {
295
+ const dir = join(cache, '_logs');
296
+ let name;
297
+ try { name = readdirSync(dir).filter((f) => f.endsWith('.log')).sort().pop(); } catch { return ''; }
298
+ if (!name) return '';
299
+ let text = '';
300
+ try { text = readFileSync(join(dir, name), 'utf8'); } catch { return ''; }
301
+ const kept = text.split('\n').filter((l) => l.trim() && !/^\d+\s+silly\b|^\d+\s+verbose stack\s+at |A complete log of this run can be found in/.test(l)).slice(-lines).map((l) => (l.length > 500 ? `${l.slice(0, 500)}...` : l));
302
+ return redact(kept.join('\n'));
303
+ }
266
304
 
267
305
  /* SEMANTIC VERSIONS, compared as npm does: a pre-release comes before its release. */
268
306
  export function compareVersions(a, b) {
@@ -328,7 +366,19 @@ export function runCommand(argv, { cwd, env = process.env, timeoutMs = 900_000 }
328
366
  });
329
367
  }
330
368
 
331
- const lastLine = (r) => String(r.stderr || r.stdout || '').trim().split('\n').filter((l) => l.trim() && !/^npm (notice|warn)/.test(l)).pop()?.slice(0, 300) ?? `exit ${r.code}`;
369
+ /* npm's lines that say nothing of why: its notices, its warnings, its pointer to a log that is gone with
370
+ its cache, its empty error lines. */
371
+ const NPM_NOISE = /^npm (notice|warn)|A complete log of this run can be found in|^npm (error|ERR!)\s*$/;
372
+ const lastLine = (r) => redact(String(r.stderr || r.stdout || '').trim().split('\n').filter((l) => l.trim() && !NPM_NOISE.test(l)).pop()?.slice(0, 300) ?? `exit ${r.code}`);
373
+ /* Why npm failed, in one line: its error code and its first words of explanation ("code ETARGET: notarget
374
+ No matching version found for ..."), else its last line that says something. */
375
+ function npmWhy(r) {
376
+ const errors = String(r.stderr || r.stdout || '').split('\n').map((l) => /^npm (?:error|ERR!) (.+)$/.exec(l.trim())?.[1]?.trim()).filter((l) => l && !NPM_NOISE.test(`npm error ${l}`));
377
+ const code = errors.find((l) => /^code \S+$/.test(l));
378
+ const said = errors.find((l) => !/^(code|errno|syscall|path|dest|signal|command|cwd) /.test(l));
379
+ if (!code && !said) return lastLine(r);
380
+ return redact([code, said].filter(Boolean).join(': ').slice(0, 300));
381
+ }
332
382
  const stamp = (d) => d.toISOString().replace(/[-:]/g, '').replace('T', '-').slice(0, 15);
333
383
  const toHex = (integrity) => Buffer.from(String(integrity).replace(/^sha512-/, ''), 'base64').toString('hex');
334
384
 
@@ -336,8 +386,8 @@ export class Updater {
336
386
  #o; #run; #fetch;
337
387
  constructor({ code = PATHS.code, conf = PATHS.conf, stateDir = PATHS.stateDir, data = PATHS.data, hostTarget = PATHS.host, gitReadTarget = PATHS.gitRead, tunnelTarget = PATHS.tunnel, registry = REGISTRY, run = runCommand, fetcher = fetch, now = () => new Date(), log = (line) => console.log(line),
338
388
  verifySignatures, restart, health, backup, restoreData, installPrivileged, ensureNode, serviceState, answers, restarts, mainPid, pidCwd, diagnose, dropIn = DROP_IN,
339
- clock = () => Date.now(), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), minFreeMb = 1024, healthMs = 60_000, watchMs = 120_000, settleMs = 10_000, noticeMs = NOTICE_MS } = {}) {
340
- this.#o = { code, conf, stateDir, data, hostTarget, gitReadTarget, tunnelTarget, registry: registry.replace(/\/$/, ''), now, log, minFreeMb, healthMs, watchMs, settleMs, noticeMs, clock, sleep, dropIn };
389
+ clock = () => Date.now(), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), minFreeMb = 1024, healthMs = 60_000, watchMs = 120_000, settleMs = 10_000, noticeMs = NOTICE_MS, releaseSettleMs = RELEASE_SETTLE_MS } = {}) {
390
+ this.#o = { code, conf, stateDir, data, hostTarget, gitReadTarget, tunnelTarget, registry: registry.replace(/\/$/, ''), now, log, minFreeMb, healthMs, watchMs, settleMs, noticeMs, releaseSettleMs, clock, sleep, dropIn };
341
391
  this.#run = run; this.#fetch = fetcher;
342
392
  this.verifySignatures = verifySignatures ?? ((dir) => this.#npm(['audit', 'signatures'], { cwd: dir, timeoutMs: 300_000 }));
343
393
  this.restart = restart ?? (() => this.#restart());
@@ -403,10 +453,12 @@ export class Updater {
403
453
 
404
454
  set(key, value) { writeConf(this.#o.conf, key, value); return this.about(); }
405
455
 
456
+ /* The registry not answering, or not with what was asked: a fetch failure (FetchFailed), not the release's fault. */
406
457
  async #json(url) {
407
- const answer = await this.#fetch(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(60_000) });
408
- if (!answer.ok) throw new Error(`the registry answered ${answer.status} for ${url}`);
409
- return answer.json();
458
+ let answer;
459
+ try { answer = await this.#fetch(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(60_000) }); } catch (error) { throw new FetchFailed(`the registry could not be reached for ${url}: ${error.cause?.code ?? error.message}`); }
460
+ if (!answer.ok) throw new FetchFailed(`the registry answered ${answer.status} for ${url}`);
461
+ try { return await answer.json(); } catch (error) { throw new FetchFailed(`the registry's answer for ${url} was cut: ${error.message}`); }
410
462
  }
411
463
  #packument(name) { return this.#json(`${this.#o.registry}/${name}`); }
412
464
 
@@ -424,7 +476,11 @@ export class Updater {
424
476
  if (conf.CHANNEL === 'beta' && tags.beta && (!candidate || compareVersions(tags.beta, candidate) > 0)) candidate = tags.beta;
425
477
  if (candidate && (!VERSION.test(candidate) || !p.versions?.[candidate])) candidate = undefined;
426
478
  const available = candidate && (!current || compareVersions(candidate, current.version) > 0) ? candidate : null;
427
- this.#save({ checkedAt: this.#o.now().toISOString(), available, checkError: null });
479
+ /* Since when it is out (RELEASE_SETTLE_MS): the registry's time for it, and when it was first seen here. */
480
+ const was = this.#state().outSince;
481
+ const published = Date.parse(p.time?.[available] ?? '');
482
+ const outSince = available ? { version: available, seenAt: was?.version === available && was.seenAt ? was.seenAt : this.#o.now().toISOString(), publishedAt: Number.isFinite(published) ? new Date(published).toISOString() : null } : null;
483
+ this.#save({ checkedAt: this.#o.now().toISOString(), available, checkError: null, outSince });
428
484
  return available;
429
485
  } catch (error) {
430
486
  this.#save({ checkedAt: this.#o.now().toISOString(), checkError: `The registry could not be asked: ${error.message}` });
@@ -442,6 +498,12 @@ export class Updater {
442
498
  }
443
499
 
444
500
  #npmEnv(nodeDir) { return { ...process.env, PATH: `${nodeDir ? `${nodeDir}/bin:` : ''}${dirname(process.execPath)}:${process.env.PATH ?? '/usr/bin:/bin'}`, npm_config_update_notifier: 'false', npm_config_fund: 'false', npm_config_audit: 'false' }; }
501
+ /* What npm said when it failed, for "See the log": its own words, then the end of its debug log. */
502
+ #npmFailure(r, what) {
503
+ const said = redact(String(r.stderr || r.stdout || '').trim().split('\n').filter((l) => !/A complete log of this run can be found in/.test(l)).slice(-20).join('\n'));
504
+ const tail = npmLogTail(join(this.#o.stateDir, 'npm-cache'));
505
+ return [`== ${this.#o.now().toISOString()} ${what} failed (exit ${r.code})`, `-- what npm said\n${said || '(nothing)'}`, ...(tail ? [`-- the end of npm's debug log\n${tail}`] : [])].join('\n').slice(-LOG_MAX);
506
+ }
445
507
  #npm(args, { cwd, nodeDir, timeoutMs = 900_000 } = {}) {
446
508
  const npm = nodeDir ? join(nodeDir, 'bin', 'npm') : join(dirname(process.execPath), 'npm');
447
509
  return this.#run([npm, ...args, '--registry', `${this.#o.registry}/`, '--cache', join(this.#o.stateDir, 'npm-cache'), '--loglevel=error'], { cwd, env: this.#npmEnv(nodeDir), timeoutMs });
@@ -465,9 +527,12 @@ export class Updater {
465
527
  this.#step(action, id, 'Fetching');
466
528
  writeFileSync(join(tmp, 'package.json'), `${JSON.stringify({ name: 'clavarium-release', private: true, dependencies: { [NAME]: version } }, null, 2)}\n`);
467
529
  const got = await this.#npm(['install', '--ignore-scripts', '--no-audit', '--no-fund', '--save-exact'], { cwd: tmp });
468
- if (got.code !== 0) throw new Error(`npm could not install ${NAME}@${version}: ${lastLine(got)}`);
530
+ /* Whatever made it fail (not there yet, a mirror behind, the network, a cut archive), nothing of it ran:
531
+ a fetch failure, with what npm said kept (its debug log goes with its cache, below). */
532
+ if (got.code !== 0) throw new FetchFailed(`npm could not install ${NAME}@${version}: ${npmWhy(got)}`, { log: this.#npmFailure(got, `npm install ${NAME}@${version}`) });
469
533
  app = join(tmp, 'node_modules', NAME);
470
- const manifest = JSON.parse(readFileSync(join(app, 'package.json'), 'utf8'));
534
+ let manifest;
535
+ try { manifest = JSON.parse(readFileSync(join(app, 'package.json'), 'utf8')); } catch (error) { throw new FetchFailed(`npm could not install ${NAME}@${version}: it left no package (${error.code ?? error.message})`, { log: this.#npmFailure(got, `npm install ${NAME}@${version}`) }); }
471
536
  if (manifest.name !== NAME || manifest.version !== version) throw new Error(`npm installed ${manifest.name}@${manifest.version}, not ${NAME}@${version}`);
472
537
  this.#step(action, id, 'Checking');
473
538
  await this.verify(tmp, version);
@@ -514,6 +579,8 @@ export class Updater {
514
579
  const own = entry(NAME);
515
580
  const p = await this.#packument(NAME);
516
581
  const dist = p.versions?.[version]?.dist;
582
+ /* Installed, but not listed by the registry that was asked next (a mirror behind): fetched again later. */
583
+ if (own && !dist) throw new FetchFailed(`the registry does not list ${NAME}@${version} yet`);
517
584
  if (!own || !dist || own.version !== version || own.integrity !== dist.integrity) throw new Error(`${NAME}@${version} as installed is not the archive the registry lists`);
518
585
  for (const name of Object.keys(REPOS)) {
519
586
  const e = name === NAME ? own : entry(name);
@@ -606,7 +673,11 @@ export class Updater {
606
673
  const unlock = this.#lock();
607
674
  try {
608
675
  let release;
609
- try { release = await this.prepare({ version }); } catch (error) { this.#history({ action: 'update', from: from?.version ?? null, to: version, result: 'failed', why: error.message, ...(/^npm could not install /.test(error.message) ? { fetch: true } : {}) }); throw error; }
676
+ try { release = await this.prepare({ version }); } catch (error) {
677
+ const fetched = error instanceof FetchFailed || /^npm could not install /.test(error.message);
678
+ this.#history({ action: 'update', from: from?.version ?? null, to: version, result: 'failed', why: error.message, ...(fetched ? { fetch: true } : {}), ...(typeof error.log === 'string' && error.log ? { log: error.log.slice(-LOG_MAX) } : {}) });
679
+ throw error;
680
+ }
610
681
  const before = this.#dataFormat();
611
682
  let archive;
612
683
  try {
@@ -725,6 +796,10 @@ export class Updater {
725
796
  if (failed.length >= FETCH_TRIES) return `${available} could not be fetched ${failed.length} times: not tried again by itself`;
726
797
  const lastAt = Math.max(...failed.map((h) => new Date(h.at ?? 0).getTime()), -Infinity);
727
798
  if (failed.length && now - lastAt < FETCH_AGAIN_MS) return `${available} could not be fetched: tried again later`;
799
+ /* Just out: every mirror given time to have it (RELEASE_SETTLE_MS). */
800
+ const out = this.#state().outSince;
801
+ const outAt = Math.min(...[out?.version === available ? out.seenAt : null, out?.version === available ? out.publishedAt : null].map((t) => Date.parse(t ?? '')).filter(Number.isFinite), now.getTime());
802
+ if (now - outAt < this.#o.releaseSettleMs) return `${available} is just out: installed by itself from ${new Date(outAt + this.#o.releaseSettleMs).toISOString()}`;
728
803
  const why = await this.busy(); if (why) return why;
729
804
  await this.apply(available);
730
805
  /* What the history says, not what was hoped: a version that did not start was undone. */
@@ -869,11 +944,19 @@ export class Updater {
869
944
  const port = readConf(this.#o.conf).PORT;
870
945
  const part = async (title, argv) => { const r = await this.#run(argv, { timeoutMs: 20_000 }); return `-- ${title}\n${String(r.stdout || r.stderr || `exit ${r.code}`).trim()}`; };
871
946
  const left = await this.#leftovers().catch(() => []);
947
+ /* WHAT THE SERVER ITSELF SAID (17-11): the unit's journal is mostly the sudo lines of the host program it
948
+ runs (a hundred a minute), its own words lost among them -- the owner saw only those, and no reason.
949
+ Read further back, the sudo and PAM lines left out, the last of the rest kept. */
950
+ const serverSaid = async () => {
951
+ const r = await this.#run(['journalctl', '-u', 'clavarium.service', '-n', '4000', '--no-pager', '-o', 'short-iso'], { timeoutMs: 20_000 });
952
+ const lines = String(r.stdout || '').split('\n').filter((l) => l.trim() && !/ (sudo|pkexec)\[\d+\]: | pam_unix\(/.test(l));
953
+ return `-- what the server said (journalctl -u clavarium, sudo lines left out)\n${lines.slice(-80).join('\n').trim() || String(r.stderr || `exit ${r.code}`).trim()}`;
954
+ };
872
955
  return [
873
956
  await part('systemctl status clavarium', ['systemctl', 'status', 'clavarium.service', '--no-pager', '-n', '0']),
874
957
  await part(`who listens on ${port}`, ['ss', '-Hltnp', `sport = :${port}`]),
875
958
  `-- processes of the server's unit or on its port\n${left.map((p) => `pid ${p.pid} state ${p.state}${p.port ? ' (holds the port)' : ''}`).join('\n') || 'none'}`,
876
- await part('journalctl -u clavarium -n 80', ['journalctl', '-u', 'clavarium.service', '-n', '80', '--no-pager', '-o', 'short-iso']),
959
+ await serverSaid(),
877
960
  ].join('\n');
878
961
  }
879
962
 
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.485-next.1",
3
+ "version": "0.2.487-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.485-next.1",
9
+ "version": "0.2.487-next.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.485-next.1",
3
+ "version": "0.2.487-next.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "A conversation is a VM with a terminal in it. Everything else is a folder.",
@@ -40,7 +40,6 @@ import { appendFileSync, readFileSync, writeFileSync, mkdirSync, statSync, rmSyn
40
40
  import { createHash } from 'node:crypto';
41
41
  import { Refusal, SESSION } from './conversations.mjs';
42
42
  import { SOCKET } from './tmux.mjs';
43
- import { TerminalType } from './terminaltype.mjs';
44
43
  import { isConversationName } from './names.mjs';
45
44
 
46
45
  export const TICK_MS = 8000;
@@ -180,14 +179,12 @@ const PANE = `=${SESSION}:`;
180
179
  const fingerprint = (screen) => createHash('sha256').update(screen).digest('hex');
181
180
 
182
181
  export class Answerer {
183
- #store; #vms; #config; #fetcher; #dir; #conversations; #seen = new Map(); #busy = new Set(); #turn = 0; #now; #onNeeds; #typer;
182
+ #store; #vms; #config; #fetcher; #dir; #conversations; #seen = new Map(); #busy = new Set(); #turn = 0; #now; #onNeeds;
184
183
 
185
184
  /* `conversations`: asked which conversations exist and are awake. */
186
185
  /* `onNeeds(name, why)`: it stopped and waits for its owner, who must be told. */
187
- constructor({ store, vms, config, conversations, dataDir, fetcher = fetch, now = () => new Date(), onNeeds = () => {}, typer = null }) {
186
+ constructor({ store, vms, config, conversations, dataDir, fetcher = fetch, now = () => new Date(), onNeeds = () => {} }) {
188
187
  this.#onNeeds = onNeeds;
189
- /* `typer`: the server's one TerminalType (main.mjs), or one of its own. */
190
- this.#typer = typer ?? new TerminalType({ vms, log: () => {} });
191
188
  this.#store = store; this.#vms = vms; this.#config = config; this.#conversations = conversations; this.#fetcher = fetcher; this.#now = now;
192
189
  this.#dir = `${dataDir}/answerer`;
193
190
  mkdirSync(this.#dir, { recursive: true, mode: 0o700 });
@@ -252,12 +249,16 @@ export class Answerer {
252
249
  return lines.slice(-SCREEN_LINES).join('\n').slice(-SCREEN_MAX);
253
250
  }
254
251
 
255
- /* Typed as every line of this server is (terminaltype.mjs): copy mode left first. Never while
256
- somebody types there (`hold` 0): the answer is for the screen read, not one changed meanwhile. */
257
252
  async #type(name, answer) {
258
- if (answer.action === 'text') return this.#typer.typeLine(name, answer.text, { why: 'answerer', what: 'its answer', hold: 0 });
253
+ const to = ['-t', PANE];
254
+ const tmux = ['tmux', '-L', SOCKET];
255
+ if (answer.action === 'text') {
256
+ const typed = await this.#vms.exec(name, [...tmux, 'send-keys', ...to, '-l', '--', answer.text], { timeoutMs: 30_000 });
257
+ if (typed.code !== 0) return false;
258
+ return (await this.#vms.exec(name, [...tmux, 'send-keys', ...to, 'Enter'], { timeoutMs: 30_000 })).code === 0;
259
+ }
259
260
  for (const key of answer.keys) {
260
- if (!(await this.#typer.sendKey(name, KEYS.get(key), { why: 'answerer' }))) return false;
261
+ if ((await this.#vms.exec(name, [...tmux, 'send-keys', ...to, KEYS.get(key)], { timeoutMs: 30_000 })).code !== 0) return false;
261
262
  }
262
263
  return true;
263
264
  }
@@ -9,7 +9,7 @@
9
9
  import { isConversationName, identifierFrom, titleProblem, groupProblem } from './names.mjs';
10
10
  import { JsonFile } from './store.mjs';
11
11
  import { attachCommand, SOCKET } from './tmux.mjs';
12
- import { WORK, VM_USER, SHARING_STEP, stepLine, vmName } from './vm.mjs';
12
+ import { WORK, VM_USER, SHARING_STEP, stepLine, vmName, WAIT_FRESH_MS } from './vm.mjs';
13
13
  import { resumeOrFresh } from './tools.mjs';
14
14
  import { TOOLS_PATH, LAUNCH } from './toolbox.mjs';
15
15
  import { homeExcludes, wholeStream, readManifest, workEmpty, unpackHere, restoreWork, CARRY } from './carry.mjs';
@@ -254,7 +254,7 @@ export class Conversations {
254
254
  while (!done) {
255
255
  await new Promise((r) => { setTimeout(r, this.#pollMs).unref?.(); });
256
256
  if (done) return;
257
- const state = await this.#vms.state(name).catch(() => undefined);
257
+ const state = await this.#vms.state(name, { within: WAIT_FRESH_MS }).catch(() => undefined);
258
258
  if (done) return;
259
259
  if (how === 'stop' && (state === 'Stopping' || state === 'Suspending')) this.#reach(name, 'stopping');
260
260
  if (how === 'start' && state === 'Running') this.#reach(name, 'answering');
@@ -899,7 +899,7 @@ export class Conversations {
899
899
  async #until(name, done, ms) {
900
900
  const end = Date.now() + ms;
901
901
  for (;;) {
902
- const state = await this.#vms.state(name).catch(() => 'Unknown');
902
+ const state = await this.#vms.state(name, { within: WAIT_FRESH_MS }).catch(() => 'Unknown');
903
903
  if (done(state) || Date.now() >= end) return state;
904
904
  await new Promise((r) => setTimeout(r, this.#pollMs));
905
905
  }
@@ -8,9 +8,8 @@
8
8
  * Where the chat is off, a wake-up types its line as before.
9
9
  *
10
10
  * NOTHING IS LOST: an event not acknowledged is told again, when the tool is
11
- * idle (its pulse, Parley's, says it is not in a turn), AGAIN_MS apart, then
12
- * further apart (AGAIN_STEPS_MS), never given up -- as the chat's own line is
13
- * (talk.mjs, RENUDGE_MS); told TOLD_MAX times, its chat says it is not handled.
11
+ * idle (its pulse, Parley's, says it is not in a turn), every AGAIN_MS, at
12
+ * most TOLD_MAX times; then its chat says it was not handled.
14
13
  *
15
14
  * THE TOOL'S OWN REMINDERS (docket remind --at/--in/--cron) are turned into
16
15
  * events here (tick), and told the same way. Its owner sees them in the
@@ -50,11 +49,7 @@ export function copyPlans(fromWork, toWork, now = Date.now()) {
50
49
  export const TICK_MS = 5000;
51
50
  /* An event not acknowledged is told again after this long, the tool idle... */
52
51
  export const AGAIN_MS = 30 * 60_000;
53
- /* ...then these long after the last time, the last of them for ever after (17-11: told three times at
54
- most, it was then silent for good -- one line lost, and the event waited unseen). */
55
- export const AGAIN_STEPS_MS = Object.freeze([AGAIN_MS, 60 * 60_000, 120 * 60_000]);
56
- const againAfter = (count) => AGAIN_STEPS_MS[Math.min(Math.max(count, 1), AGAIN_STEPS_MS.length) - 1];
57
- /* Told this many times (the first included): its chat says it is not handled, once; it is still told. */
52
+ /* ...this many times at most (the first included); then its chat says so. */
58
53
  export const TOLD_MAX = 3;
59
54
 
60
55
  /* AN ANSWER NEVER SHOWN (15-11, #362): the note of a sign-in a companion did for another conversation is
@@ -173,12 +168,12 @@ export class Dockets {
173
168
  const told = Object.fromEntries(Object.entries(record.told ?? {}).filter(([id]) => waiting.some((e) => e.id === id)));
174
169
  const due = waiting.filter((e) => {
175
170
  const t = told[e.id];
176
- return !t || now - t.at >= againAfter(t.count);
171
+ return !t || (t.count < TOLD_MAX && now - t.at >= AGAIN_MS);
177
172
  });
178
173
  /* Told again only while it is not in a turn: a busy tool reads its docket when its turn ends. */
179
174
  const fresh = due.filter((e) => !told[e.id]);
180
175
  if (due.length && (fresh.length || this.#idle(name))) {
181
- if (await this.#say(name, WAKE).catch(() => false)) for (const e of due) told[e.id] = { ...told[e.id], count: (told[e.id]?.count ?? 0) + 1, at: now };
176
+ if (await this.#say(name, WAKE).catch(() => false)) for (const e of due) told[e.id] = { count: (told[e.id]?.count ?? 0) + 1, at: now };
182
177
  }
183
178
  for (const e of waiting) {
184
179
  const t = told[e.id];
@@ -65,6 +65,16 @@ import { GitFailure, waiversProblem } from './gitrunner.mjs';
65
65
  import { SECONDS_MIN, SECONDS_MAX, COMMAND_MAX } from './gitchecks.mjs';
66
66
 
67
67
  export const TICK_MS = 30_000;
68
+ /* Each repository's refresh comes up to this much after its period, the same for a
69
+ repository every time (from its name): fifteen repositories do not all reach their
70
+ remote, and then every machine, at the same tick. */
71
+ export const SPREAD_MS = 60_000;
72
+ export function spread(name, within = SPREAD_MS) {
73
+ if (!(within > 0)) return 0;
74
+ let h = 0;
75
+ for (const ch of String(name)) h = (h * 31 + ch.charCodeAt(0)) >>> 0;
76
+ return h % within;
77
+ }
68
78
  /* A read waits this long after the last change of the marks. */
69
79
  export const READ_DELAY_MS = 5_000;
70
80
  /* And happens at least this often while a machine uses the repository. */
@@ -221,6 +231,13 @@ export const SENDING_KEEP_MS = 60_000;
221
231
 
222
232
  export class GitKeeper {
223
233
  #store; #review; #resources; #checks; #alerts; #now; #tellAgent; #thread; #last; #held = new Map(); #results = new Map(); #running = new Set(); #telling = new Map(); #inFlight = new Map(); #sending = new Map();
234
+ /* The reference's branches after its last refresh that worked (its `mark`), by repository; and,
235
+ by "conversation repository", the mark its machine was last fetched at (see #fetchInMachines). */
236
+ #marks = new Map(); #fetchedAt = new Map();
237
+ /* Set by start: no refresh before this (the keeper's clock), each repository a little after it (spread). */
238
+ #since = 0;
239
+ /* Set by start: how far the refreshes are spread (two ticks at most; none before a start). */
240
+ #spreadMs = 0;
224
241
 
225
242
  /* `review`: GitReview (reads, the reference, Send). `checks`: GitChecks.
226
243
  `alerts`: what tells the owner's phone. `tellAgent(repository, line,
@@ -444,6 +461,7 @@ export class GitKeeper {
444
461
  const record = this.#record(name);
445
462
  const failures = result.ok ? 0 : (record.refreshFailures ?? 0) + 1;
446
463
  this.#patch(name, { mirror: { at, ok: result.ok, message: result.ok ? 'Up to date with the origin.' : result.message }, refreshFailures: failures });
464
+ if (result.ok && typeof result.mark === 'string') this.#marks.set(name, result.mark);
447
465
  if (!result.ok && failures === 3) this.#tell(`${name}: the remote does not answer`, result.message);
448
466
  if (result.stale?.length) this.#log(name, { ok: false, what: `A refresh was stopped by its time limit; stale lock files removed: ${result.stale.join(', ')}.` });
449
467
  for (const w of result.rewritten ?? []) {
@@ -787,7 +805,7 @@ export class GitKeeper {
787
805
  if (!await this.#inUse(r.name)) return;
788
806
  /* The reference, when due; its upkeep once a day. */
789
807
  const last = this.#record(r.name).mirror?.at;
790
- if (s.refreshMinutes > 0 && (!last || now - new Date(last).getTime() >= s.refreshMinutes * 60_000)) {
808
+ if (s.refreshMinutes > 0 && now >= this.#since + spread(r.name, this.#spreadMs) && (!last || now - new Date(last).getTime() >= s.refreshMinutes * 60_000 + spread(r.name, this.#spreadMs))) {
791
809
  await this.#review.refresh(r.name).catch(() => {});
792
810
  await this.#fetchInMachines(r.name, s).catch(() => {});
793
811
  const upkeep = this.#record(r.name).upkeepAt;
@@ -811,11 +829,19 @@ export class GitKeeper {
811
829
  /* THE AGENTS' OWN COPIES, after each refresh of the reference: brought up to date in each machine
812
830
  that runs with the repository attached for writing (gitchecks.mjs, fetchIn), origin/* only.
813
831
  A branch it follows that moved is said to its agent, once per move, unless the owner turned
814
- that line off (tellMoves). */
832
+ that line off (tellMoves).
833
+ Only when there is something new for it: a machine already fetched at the reference's
834
+ current branches (its mark) is not asked again -- each fetch is a command to the host,
835
+ for every machine, every few minutes. Unknown (no refresh has worked since the server
836
+ started), or a machine that stopped since: fetched, as before. */
815
837
  async #fetchInMachines(name, s) {
838
+ const mark = this.#marks.get(name);
816
839
  for (const c of this.#writers(name)) {
817
- if (!await this.#runs(c, name)) continue;
840
+ const key = `${c} ${name}`;
841
+ if (!await this.#runs(c, name)) { this.#fetchedAt.delete(key); continue; }
842
+ if (mark !== undefined && this.#fetchedAt.get(key) === mark) continue;
818
843
  const got = await this.#checks.fetchIn?.(c, name).catch(() => undefined);
844
+ if (got?.ok && mark !== undefined) this.#fetchedAt.set(key, mark); else this.#fetchedAt.delete(key);
819
845
  if (!got?.ok || !s.tellMoves || got.moved.length === 0) continue;
820
846
  const said = got.moved.slice(0, 3).map((m) => `${plain(m.upstream)} moved (${m.from.slice(0, 7)} -> ${m.to.slice(0, 7)}), your branch ${plain(m.branch)} follows it`).join('; ');
821
847
  this.#toAgent(name, `${said}; fetched for you into origin/*, nothing of yours changed`, c);
@@ -833,7 +859,10 @@ export class GitKeeper {
833
859
  return removed;
834
860
  }
835
861
 
836
- start(everyMs = TICK_MS) {
862
+ /* `quietMs`: how long after a start of the server nothing is looked at (main.mjs, quietStartMs):
863
+ the machines starting again come first. The refreshes then come one repository after
864
+ another over SPREAD_MS, not all at the first tick. */
865
+ start(everyMs = TICK_MS, { quietMs = 0 } = {}) {
837
866
  /* A read the server gave up on when it stopped is stopped on the host;
838
867
  a fetch it killed may have left lock files in the reference, which
839
868
  would refuse every later refresh. No git of ours runs there yet:
@@ -842,10 +871,13 @@ export class GitKeeper {
842
871
  void this.#review.runner?.stopReads(r.name);
843
872
  void this.#staleLocks(r.name).catch(() => {});
844
873
  }
845
- const timer = setInterval(() => { void this.tick(); }, everyMs);
874
+ this.#since = this.#now().getTime() + quietMs;
875
+ this.#spreadMs = Math.min(SPREAD_MS, everyMs * 2);
876
+ const quietUntil = Date.now() + quietMs;
877
+ const timer = setInterval(() => { if (Date.now() >= quietUntil) void this.tick(); }, everyMs);
846
878
  timer.unref?.();
847
- /* Looked at soon after a start, not a whole period later. */
848
- setTimeout(() => { void this.tick(); }, Math.min(everyMs, 5000)).unref?.();
879
+ /* Looked at soon after a start (once it is quiet no more), not a whole period later. */
880
+ setTimeout(() => { void this.tick(); }, Math.max(quietMs, Math.min(everyMs, 5000))).unref?.();
849
881
  return timer;
850
882
  }
851
883
  }
@@ -207,7 +207,7 @@ export class GitReview {
207
207
 
208
208
  /* Fetches the remote's branches into the reference, making it the first
209
209
  time. Under the reference's lock. Resolves { ok, message, rewritten,
210
- made, brought }; `rewritten`: branches whose tip before is not an
210
+ made, brought, mark }; `rewritten`: branches whose tip before is not an
211
211
  ancestor of their tip now, or that are gone; `brought`: branches that
212
212
  came with commits the reference did not have, { branch, commits }.
213
213
  The only writer of the reference. */
@@ -289,7 +289,10 @@ export class GitReview {
289
289
  await this.#learnDefault(r, remote).catch(() => {});
290
290
  /* When the reference was last brought up to date: the list shown at once says "as of" it. */
291
291
  this.#store.put({ ...this.#record(r.name), name: r.name, fetchedAt: this.#now().toISOString() });
292
- return said({ ok: true, message: 'Up to date with the remote.', rewritten, made, brought });
292
+ /* `mark`: the reference's branches as they are now, so that a caller can tell a
293
+ refresh that changed nothing (gitkeeper.mjs: no fetch into the machines then). */
294
+ const mark = [...after].map(([b, id]) => `${b} ${id}`).sort().join('\n');
295
+ return said({ ok: true, message: 'Up to date with the remote.', rewritten, made, brought, mark });
293
296
  }
294
297
 
295
298
  /* Is `tip` of the agent's branch `b` something the remote lacks? Not
package/server/health.mjs CHANGED
@@ -27,6 +27,7 @@ import { SHARING_STEP } from './vm.mjs';
27
27
  import { WHY } from './linkguard.mjs';
28
28
  import { SOCKET } from './tmux.mjs';
29
29
  import { SESSION } from './conversations.mjs';
30
+ import { SECRETS_DIR } from './secrets.mjs';
30
31
 
31
32
  /* A FILE OUTSIDE /work where its tool may ask to be restarted when /work itself is dead (16-11): the
32
33
  one in its chat's folder (talk.mjs, RESTART_ASKED) cannot be written then. Read by the probe. */
@@ -42,6 +43,8 @@ export const STUCK_MOUNT = /already mounted|terminate SSHFS mount process/i;
42
43
 
43
44
  /* How long installing the shared-folder helper in a machine may take (it comes from the snap store). */
44
45
  export const SHARING_MS = 180_000;
46
+ /* At most this many names of its secrets are listed by the probe (their number always is). */
47
+ export const SECRETS_LISTED = 64;
45
48
  export const PROBE = [
46
49
  'awk \'/^MemTotal:/{t=$2} /^MemAvailable:/{a=$2} END{print "memory", t+0, a+0}\' /proc/meminfo',
47
50
  'awk \'$1=="oom_kill"{n=$2} END{print "oom", n+0}\' /proc/vmstat',
@@ -67,10 +70,17 @@ export const PROBE = [
67
70
  `for p in $(pgrep -f '${TOOLS_HOST_PATTERN}' 2>/dev/null); do [ -d "/proc/$p/cwd/." ] || { echo "stale $p"; break; }; done`,
68
71
  `tmux -L ${SOCKET} capture-pane -p -t '=${SESSION}:' 2>/dev/null | grep -c -i -E '${LOOSE_WORDS}' | awk '{print "screen", $1+0}'`,
69
72
  `if [ -f ${RESTART_OUTSIDE} ]; then echo "restart asked"; fi`,
73
+ /* THE NAMES IN ITS /run/secrets, for the secrets' guard (main.mjs, secrets.mjs reconcile): read
74
+ here, in the look made anyway, not by a command of their own. How many, then the first of them. */
75
+ `echo "secrets $(ls -1 ${SECRETS_DIR} 2>/dev/null | wc -l)"`,
76
+ `ls -1 ${SECRETS_DIR} 2>/dev/null | head -n ${SECRETS_LISTED} | sed 's/^/secret /'`,
70
77
  ].join('\n');
71
78
  export const PROBE_NAME = 'clavarium-health';
72
79
 
73
80
  export const EVERY_MS = 120_000;
81
+ /* The looks of one tick start this far apart, one machine after another (at most a tick shared out
82
+ between them): a burst of probes lines up at the VM manager in front of every other command. */
83
+ export const STAGGER_MS = 5_000;
74
84
  const PROBE_MS = 15_000;
75
85
  /* What the clock waits for one conversation's look before it goes on. */
76
86
  const LOOK_MS = 60_000;
@@ -105,6 +115,10 @@ export function readProbe(text, paths = []) {
105
115
  if (parts[0] === 'stale' && parts.length === 2 && a !== undefined) facts.stale = true;
106
116
  if (parts[0] === 'screen' && parts.length === 2 && a !== undefined) facts.screenLoose = a;
107
117
  if (line.trim() === 'restart asked') facts.restartAsked = true;
118
+ /* A name that is not a plain one (the agent may put anything there) is kept as '?': it
119
+ matches nothing that is given, so the guard writes the folder again, as it would have. */
120
+ if (parts[0] === 'secrets' && parts.length === 2 && a !== undefined) facts.secrets = { count: a, names: [] };
121
+ if (parts[0] === 'secret' && facts.secrets && facts.secrets.names.length < SECRETS_LISTED) facts.secrets.names.push(parts.length === 2 && /^[A-Za-z0-9_.-]{1,64}$/.test(parts[1]) ? parts[1] : '?');
108
122
  }
109
123
  return facts;
110
124
  }
@@ -171,6 +185,9 @@ export class Health {
171
185
  judged = () => {};
172
186
  /* Set by the server: told a conversation is forgotten (what else is kept of its machine goes too). */
173
187
  forgotten = () => {};
188
+ /* Set by the server: told what a probe that answered found (`facts`: readProbe's), not waited for.
189
+ The secrets' guard reads its names of /run/secrets there (main.mjs). */
190
+ probed = () => {};
174
191
 
175
192
  /* `settleMs`: how long a missing folder is given before it is mounted
176
193
  again (a machine that has just started may still be mounting it).
@@ -228,6 +245,7 @@ export class Health {
228
245
  return this.#keep(name, { at, state, answering: false });
229
246
  }
230
247
  this.#quiet.delete(name);
248
+ try { void Promise.resolve(this.probed(name, facts)).catch(() => {}); } catch { /* told, nothing more */ }
231
249
  const loose = () => paths.filter((p) => facts.mounts[p] !== 'ok');
232
250
  const remounted = []; const failed = [];
233
251
  if (loose().length > 0 && repair && this.#resources) {
@@ -316,18 +334,23 @@ export class Health {
316
334
 
317
335
  /* Every so often, each conversation whose machine should run. A machine
318
336
  that does not run is not touched (its state alone is asked). */
319
- start(everyMs = EVERY_MS) {
337
+ /* `quietMs`: no look by the clock that soon after a start of the server (main.mjs, quietStartMs). */
338
+ start(everyMs = EVERY_MS, { quietMs = 0 } = {}) {
320
339
  if (!everyMs) return () => {};
321
340
  let going = false;
341
+ const quietUntil = Date.now() + quietMs;
322
342
  const timer = setInterval(async () => {
323
- if (going) return;
343
+ if (going || Date.now() < quietUntil) return;
324
344
  going = true;
325
345
  /* All at once, each within its own time: one machine slow to
326
346
  answer (or a mount that hangs) does not hold up the others.
327
347
  A look still going when its time is up goes on; the next tick
328
348
  joins it rather than starting another (check). */
329
349
  try {
330
- await Promise.all(this.#conversations.awake().map((name) => {
350
+ const names = this.#conversations.awake();
351
+ const apart = Math.min(STAGGER_MS, Math.floor(everyMs / Math.max(1, names.length)));
352
+ await Promise.all(names.map(async (name, i) => {
353
+ if (i > 0 && apart > 0) await new Promise((resolve) => { setTimeout(resolve, i * apart).unref?.(); });
331
354
  let timer;
332
355
  const bound = new Promise((resolve) => { timer = setTimeout(resolve, this.#lookMs); timer.unref?.(); });
333
356
  return Promise.race([this.check(name).catch(() => {}), bound]).finally(() => clearTimeout(timer));