@crouton-kit/crouter 0.3.38 → 0.3.39

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 (30) hide show
  1. package/dist/core/hearth/provider.d.ts +8 -0
  2. package/dist/core/hearth/providers/__tests__/sweep-and-release.test.d.ts +1 -0
  3. package/dist/core/hearth/providers/__tests__/sweep-and-release.test.js +254 -0
  4. package/dist/core/hearth/providers/blaxel-home.d.ts +39 -0
  5. package/dist/core/hearth/providers/blaxel-home.js +271 -21
  6. package/dist/core/hearth/providers/blaxel.d.ts +5 -0
  7. package/dist/core/hearth/providers/blaxel.js +86 -4
  8. package/dist/core/hearth/providers/types.d.ts +16 -0
  9. package/dist/hearth/control-plane/__tests__/error-serialization.test.d.ts +1 -0
  10. package/dist/hearth/control-plane/__tests__/error-serialization.test.js +29 -0
  11. package/dist/hearth/control-plane/__tests__/oauth-serving-marker.test.d.ts +1 -0
  12. package/dist/hearth/control-plane/__tests__/oauth-serving-marker.test.js +44 -0
  13. package/dist/hearth/control-plane/__tests__/wake-roll.test.d.ts +1 -0
  14. package/dist/hearth/control-plane/__tests__/wake-roll.test.js +230 -0
  15. package/dist/hearth/control-plane/db.js +27 -0
  16. package/dist/hearth/control-plane/hearth-target.d.ts +23 -0
  17. package/dist/hearth/control-plane/hearth-target.js +68 -0
  18. package/dist/hearth/control-plane/registry.d.ts +6 -1
  19. package/dist/hearth/control-plane/registry.js +7 -0
  20. package/dist/hearth/control-plane/relay.d.ts +4 -0
  21. package/dist/hearth/control-plane/relay.js +72 -3
  22. package/dist/hearth/control-plane/secrets.d.ts +14 -0
  23. package/dist/hearth/control-plane/secrets.js +21 -0
  24. package/dist/hearth/control-plane/server.js +140 -4
  25. package/dist/hearth/control-plane/serving.d.ts +15 -0
  26. package/dist/hearth/control-plane/serving.js +106 -0
  27. package/dist/hearth/control-plane/types.d.ts +20 -0
  28. package/dist/hearth/control-plane/wake.d.ts +8 -2
  29. package/dist/hearth/control-plane/wake.js +241 -3
  30. package/package.json +1 -1
@@ -31,10 +31,12 @@
31
31
  import { setTimeout as delay } from 'node:timers/promises';
32
32
  import { WebSocket } from 'ws';
33
33
  import { general } from '../../core/errors.js';
34
- import { loadM0Config } from '../../core/hearth/config.js';
34
+ import { hearthHomeImageRefForVersion, loadM0Config } from '../../core/hearth/config.js';
35
35
  import { getHomeBackend } from '../../core/hearth/provider.js';
36
36
  import { loadControlPlaneConfig } from './config.js';
37
- import { getHomeById, refreshProviderPointers, setHomeStatus, touchReady, touchWake } from './registry.js';
37
+ import { getHearthTarget, recordBadTarget } from './hearth-target.js';
38
+ import { getHomeById, refreshProviderPointers, setHealthVerdict, setHomeStatus, touchReady, touchWake } from './registry.js';
39
+ import { isHomeServing as isHomeServingNow } from './serving.js';
38
40
  import { resolveSecret } from './secrets.js';
39
41
  // Individual probe attempt timeout — bounded short so a dead route fails
40
42
  // fast and the retry loop gets multiple attempts inside the overall window,
@@ -199,8 +201,11 @@ async function probeNodeReady(previewEndpoint, target, relayToken, windowMs) {
199
201
  * never reassigns these; only ad hoc verification scripts do. */
200
202
  export const wakeInternals = {
201
203
  getHomeById,
204
+ getHearthTarget,
205
+ recordBadTarget,
202
206
  refreshProviderPointers,
203
207
  setHomeStatus,
208
+ setHealthVerdict,
204
209
  touchWake,
205
210
  touchReady,
206
211
  resolveSecret,
@@ -237,6 +242,223 @@ export function resetWakeCacheForTests() {
237
242
  warmVerdicts.clear();
238
243
  inflightWakes.clear();
239
244
  }
245
+ /** Is this home currently serving, so a destructive roll would interrupt it?
246
+ * Delegates entirely to `serving.ts`'s independent live-session counters,
247
+ * bumped at the relay's HTTP/WS lifecycle seams and the CP's OAuth
248
+ * start/finish dispatch — never derived from any TTL/cache. `home.status` is
249
+ * intentionally NOT consulted: a suspended home has no live counters anyway
250
+ * (nothing to bump them), so this stays a single source of truth. */
251
+ function homeIsServing(home) {
252
+ return isHomeServingNow(home.home_id);
253
+ }
254
+ /** Is this home due to roll onto the registered target? Stale = it isn't
255
+ * already on the target version AND the target is not a known-bad release.
256
+ * The bad-target clause is the ONLY brake in the zero-touch loop (roadmap
257
+ * decision 1: never auto-advance onto a release that already failed a roll):
258
+ * once `recordBadTarget` poisons the current target, no home rolls onto it
259
+ * until a NEW release advances the target past it.
260
+ *
261
+ * NOTE (design divergence, flagged): design §3's literal snippet compared
262
+ * `home.template_version !== last_bad_target_version`, which would THRASH —
263
+ * after a failed roll a home sits on the PRIOR version, so that clause stays
264
+ * true and it would re-roll onto the same broken target forever. The roadmap's
265
+ * plain-English brake and design §5's own comment both mean `target !==
266
+ * last_bad`; that is what is implemented here. */
267
+ function isHomeStale(home, target) {
268
+ if (home.template_version === null)
269
+ return false;
270
+ if (home.template_version === target.target_template_version)
271
+ return false;
272
+ if (target.last_bad_target_version !== null && target.target_template_version === target.last_bad_target_version)
273
+ return false;
274
+ return true;
275
+ }
276
+ // Baked crtr path (deploy/hearth-blaxel/Dockerfile symlink) — target it
277
+ // directly for the in-guest version assert rather than a bare PATH lookup,
278
+ // exactly as blaxel-bootstrap.ts does, so a stale legacy binary earlier on
279
+ // PATH can't answer instead.
280
+ const BAKED_CRTR_PATH = '/usr/local/bin/crtr';
281
+ /** Assert what crtr the recreated guest is ACTUALLY running (design §4 step 7)
282
+ * by reading `crtr --json sys version` in-guest — stronger than trusting the
283
+ * provider's config version, since it proves the booted binary. Parses the
284
+ * `.version` field from `{ "version": "X.Y.Z" }`. The same drift-guard env
285
+ * vars the bootstrap uses keep this a pure read (no bootstrap/auto-init/
286
+ * auto-update side effects). */
287
+ async function assertGuestVersion(backend, sandboxName) {
288
+ const result = await backend.exec(sandboxName, {
289
+ command: `CRTR_NO_BOOTSTRAP=1 CRTR_NO_AUTO_INIT=1 CRTR_NO_AUTO_UPDATE=1 ${BAKED_CRTR_PATH} --json sys version`,
290
+ timeoutMs: 20_000,
291
+ });
292
+ // A parseable stdout is not proof the command itself succeeded — require a
293
+ // clean exit before trusting anything it printed.
294
+ if (result.exitCode !== 0 || result.timedOut === true) {
295
+ throw general(`in-guest crtr sys version did not exit cleanly (exitCode ${result.exitCode}, timedOut ${result.timedOut})`, {
296
+ sandboxName,
297
+ exitCode: result.exitCode,
298
+ timedOut: result.timedOut,
299
+ stdout: result.stdout.slice(0, 200),
300
+ stderr: result.stderr.slice(0, 200),
301
+ });
302
+ }
303
+ const stdout = result.stdout.trim();
304
+ try {
305
+ const parsed = JSON.parse(stdout);
306
+ if (typeof parsed.version === 'string' && parsed.version.trim() !== '')
307
+ return parsed.version.trim();
308
+ }
309
+ catch {
310
+ /* fall through to a tolerant field extraction below */
311
+ }
312
+ const match = /"version"\s*:\s*"([^"]+)"/.exec(stdout);
313
+ if (match !== null && match[1].trim() !== '')
314
+ return match[1].trim();
315
+ throw general(`in-guest crtr sys version returned no parseable .version (exit ${result.exitCode})`, {
316
+ sandboxName,
317
+ stdout: stdout.slice(0, 200),
318
+ });
319
+ }
320
+ /** Structured HIGH-SEVERITY alert lines. The CP is a standalone Fly process
321
+ * and cannot `crtr push`; alerting is a distinct `level: 'error'` stderr line
322
+ * with an `alert` marker that ops log-alerting keys on. (Wiring these to a
323
+ * real notification channel is future work — the marker is the seam.) */
324
+ function alertRollRolledBack(home, target, restoredVersion) {
325
+ process.stderr.write(`${JSON.stringify({
326
+ level: 'error',
327
+ alert: 'hearth.roll.rolled_back',
328
+ message: `Hearth auto-upgrade roll FAILED and was rolled back — release ${target.target_template_version} is broken`,
329
+ home_id: home.home_id,
330
+ bad_target_version: target.target_template_version,
331
+ restored_version: restoredVersion,
332
+ })}\n`);
333
+ }
334
+ export function serializeError(error) {
335
+ if (error instanceof Error)
336
+ return error.message;
337
+ try {
338
+ // `JSON.stringify` returns `undefined` (does not throw) for `undefined`, a function, or a
339
+ // symbol — falling through to that would OMIT the `error` field from the incident alert's
340
+ // JSON line entirely, which is worse than the "[object Object]" bug this rider fixes.
341
+ const json = JSON.stringify(error);
342
+ return json === undefined ? String(error) : json;
343
+ }
344
+ catch {
345
+ return String(error);
346
+ }
347
+ }
348
+ function alertRollIncident(home, target, priorVersion, error) {
349
+ process.stderr.write(`${JSON.stringify({
350
+ level: 'error',
351
+ alert: 'hearth.roll.incident',
352
+ message: `Hearth auto-upgrade roll AND rollback both failed — home ${home.home_id} is DEGRADED, manual recovery needed`,
353
+ home_id: home.home_id,
354
+ bad_target_version: target.target_template_version,
355
+ prior_version: priorVersion,
356
+ error: serializeError(error),
357
+ })}\n`);
358
+ }
359
+ /** Fall back onto the PRIOR pinned image after a failed roll (design §5). The
360
+ * volume was never touched by the roll, so this is deterministic: recreate on
361
+ * the prior image name (still in the registry — images are never pruned),
362
+ * revive, ready-probe, assert `crtr sys version === priorVersion`. On success,
363
+ * ALERT (the release is broken) — the bad target is already poisoned by
364
+ * `rollHome`'s catch (the roll's own failure is what poisons the target, not
365
+ * rollback's success, so the brake is set even when rollback ALSO fails).
366
+ * On rollback also failing: mark the home
367
+ * `unknown`/`degraded` and alert — a genuine incident (the volume is intact,
368
+ * so manual recovery is always possible). */
369
+ async function rollbackHome(args) {
370
+ const { home, target, descriptor, priorImageRef, priorVersion, relayToken, backend, readyTimeoutMs } = args;
371
+ try {
372
+ const refresh = await backend.recreateOnImage(descriptor, priorImageRef, priorVersion);
373
+ const previewEndpoint = requireHomeField(refresh.previewEndpoint ?? null, 'preview_endpoint', home.home_id);
374
+ const ready = await wakeInternals.probeNodeReady(previewEndpoint, descriptor.homeAgentTarget, relayToken, readyTimeoutMs);
375
+ if (!ready)
376
+ throw general(`rollback ready-probe timed out for ${home.home_id}`, { home_id: home.home_id });
377
+ // Assert against the sandbox the recreate actually reports, not a stale name captured at
378
+ // entry — under generation naming (recreate-race-fix.md §3.5) the pre-recreate sandbox is
379
+ // destroyed, so exec-ing into anything else would target a gone/wrong generation.
380
+ const asserted = await assertGuestVersion(backend, refresh.providerSandboxId);
381
+ if (asserted !== priorVersion) {
382
+ throw general(`rollback version mismatch: expected ${priorVersion}, got ${asserted}`, { home_id: home.home_id, expected: priorVersion, asserted });
383
+ }
384
+ wakeInternals.refreshProviderPointers(home.home_id, {
385
+ provider_sandbox_id: refresh.providerSandboxId,
386
+ preview_endpoint: previewEndpoint,
387
+ template_version: priorVersion,
388
+ status: 'running',
389
+ });
390
+ wakeInternals.setHealthVerdict(home.home_id, 'healthy');
391
+ alertRollRolledBack(home, target, priorVersion);
392
+ return { preview_endpoint: previewEndpoint, relayToken };
393
+ }
394
+ catch (rollbackError) {
395
+ wakeInternals.setHomeStatus(home.home_id, 'unknown');
396
+ wakeInternals.setHealthVerdict(home.home_id, 'degraded');
397
+ alertRollIncident(home, target, priorVersion, rollbackError);
398
+ throw general(`hearth roll AND rollback both failed for ${home.home_id}`, {
399
+ home_id: home.home_id,
400
+ target: target.target_template_version,
401
+ priorVersion,
402
+ });
403
+ }
404
+ }
405
+ /** CP-driven destroy→recreate of a stale home onto the registered target
406
+ * image, reattaching the same durable volume (design §4). Captures rollback
407
+ * anchors first, marks the home `restoring` (so a concurrent wake coalesces
408
+ * rather than races), then recreates on the target image, ready-probes, and
409
+ * ASSERTS the in-guest `crtr sys version` equals the target before committing
410
+ * pointers + `health_verdict = healthy`. A roll never writes
411
+ * `home_agent_target` (canvas.db is reattached byte-identical;
412
+ * `refreshProviderPointers` has no such field). Any of recreate/probe/assert
413
+ * failing falls back to the prior image (§5). Returns the route so the
414
+ * triggering wake serves the just-upgraded home in the same call. */
415
+ async function rollHome(home, target, relayToken, descriptor) {
416
+ const priorVersion = requireHomeField(home.template_version, 'template_version', home.home_id);
417
+ const priorImageRef = hearthHomeImageRefForVersion(priorVersion);
418
+ const m0 = wakeInternals.loadM0Config();
419
+ const backend = wakeInternals.getHomeBackend(m0);
420
+ const cpConfig = wakeInternals.loadControlPlaneConfig();
421
+ wakeInternals.setHomeStatus(home.home_id, 'restoring');
422
+ invalidateWarmVerdict(home.home_id);
423
+ const startedAt = wakeInternals.now();
424
+ try {
425
+ const refresh = await backend.recreateOnImage(descriptor, target.target_image_ref, target.target_template_version);
426
+ const previewEndpoint = requireHomeField(refresh.previewEndpoint ?? null, 'preview_endpoint', home.home_id);
427
+ const ready = await wakeInternals.probeNodeReady(previewEndpoint, descriptor.homeAgentTarget, relayToken, cpConfig.readyTimeoutMs);
428
+ if (!ready)
429
+ throw general(`roll ready-probe timed out for ${home.home_id}`, { home_id: home.home_id });
430
+ // Assert against the sandbox the recreate actually reports (recreate-race-fix.md §3.5) —
431
+ // never the row's pre-recreate `provider_sandbox_id`, which under generation naming is
432
+ // already destroyed by the time this runs.
433
+ const asserted = await assertGuestVersion(backend, refresh.providerSandboxId);
434
+ if (asserted !== target.target_template_version) {
435
+ throw general(`roll version mismatch: expected ${target.target_template_version}, got ${asserted}`, {
436
+ home_id: home.home_id,
437
+ expected: target.target_template_version,
438
+ asserted,
439
+ });
440
+ }
441
+ wakeInternals.refreshProviderPointers(home.home_id, {
442
+ provider_sandbox_id: refresh.providerSandboxId,
443
+ preview_endpoint: previewEndpoint,
444
+ template_version: asserted,
445
+ status: 'running',
446
+ });
447
+ wakeInternals.setHealthVerdict(home.home_id, 'healthy');
448
+ wakeInternals.touchWake(home.home_id, { at: new Date(startedAt).toISOString(), latency_ms: wakeInternals.now() - startedAt });
449
+ wakeInternals.touchReady(home.home_id);
450
+ return { preview_endpoint: previewEndpoint, relayToken };
451
+ }
452
+ catch {
453
+ // The target is known-bad the INSTANT its own roll fails, independent of
454
+ // whether rollback then recovers — poison it here, before delegating to
455
+ // rollbackHome, so a roll-fails+rollback-also-fails home doesn't leave the
456
+ // brake unset (which would let a later wake, of this home or any other,
457
+ // re-roll onto the same broken target).
458
+ wakeInternals.recordBadTarget(target.target_template_version);
459
+ return rollbackHome({ home, target, descriptor, priorImageRef, priorVersion, relayToken, backend, readyTimeoutMs: cpConfig.readyTimeoutMs });
460
+ }
461
+ }
240
462
  async function runEnsureAwake(home_id) {
241
463
  const home = wakeInternals.getHomeById(home_id);
242
464
  if (home === null)
@@ -245,6 +467,16 @@ async function runEnsureAwake(home_id) {
245
467
  const relayToken = wakeInternals.resolveSecret(relayAuthRef);
246
468
  const target = requireHomeField(home.home_agent_target, 'home_agent_target', home_id);
247
469
  const descriptor = buildDescriptor(home, relayToken);
470
+ // Auto-upgrade lazy roll (design §3/§4): if a newer image target is
471
+ // registered, this home is stale, and it is NOT currently serving, roll it
472
+ // onto the target image now instead of the normal wake. At wake-entry an
473
+ // idle home is definitionally safe to tear down; a serving home doesn't roll
474
+ // this pass (it rolls on its next cold wake). This is the ONLY new branch —
475
+ // the normal wake path below is unchanged.
476
+ const hearthTarget = wakeInternals.getHearthTarget();
477
+ if (hearthTarget !== null && isHomeStale(home, hearthTarget) && !homeIsServing(home)) {
478
+ return rollHome(home, hearthTarget, relayToken, descriptor);
479
+ }
248
480
  const startedAt = wakeInternals.now();
249
481
  const m0 = wakeInternals.loadM0Config();
250
482
  const refresh = await wakeInternals.getHomeBackend(m0).wake(descriptor);
@@ -277,12 +509,18 @@ async function runEnsureAwake(home_id) {
277
509
  const readyAt = new Date().toISOString();
278
510
  wakeInternals.touchWake(home_id, { at: new Date(startedAt).toISOString(), latency_ms: wakeInternals.now() - startedAt });
279
511
  wakeInternals.touchReady(home_id, readyAt);
512
+ // A successful ready-probe means the home is healthy right now, regardless of what the
513
+ // verdict was before this wake (e.g. left `degraded` by an earlier failed rollback) —
514
+ // clear it here the same way rollHome/rollbackHome clear it on their own success, or a
515
+ // stale degraded/unknown verdict never heals on the normal wake path.
516
+ wakeInternals.setHealthVerdict(home_id, 'healthy');
280
517
  return { preview_endpoint: resolvedPreviewEndpoint, relayToken };
281
518
  }
282
519
  /** Bring a home up and ready, returning the route to relay to once it is.
283
520
  * Reads the registry, resolves the relay token, calls the provider
284
521
  * wake/resume seam, ready-probes `/node/<home_agent_target>`, refreshes
285
- * provider pointers on a recreate, records wake/ready timing, and returns
522
+ * provider pointers on a recreate, records wake/ready timing, clears the
523
+ * health verdict to `healthy` on success, and returns
286
524
  * `{ preview_endpoint, relayToken }`. Throws on a ready-probe timeout
287
525
  * (wake-failure UX is deferred — gap note 2 — a throw is the accepted
288
526
  * cutover behavior).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crouton-kit/crouter",
3
- "version": "0.3.38",
3
+ "version": "0.3.39",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",