@moondeck/station 1.0.4 → 1.0.5

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/lib/skills.ts CHANGED
@@ -258,19 +258,19 @@ const SKILL_EXEC_TIMEOUT_MS = 180_000; // clones / npx installs can be slow
258
258
  * In-container git-skill installer. Shallow-clones a repo, then works out where
259
259
  * the actual skill(s) live and copies each into `~/.claude/skills/<name>/`:
260
260
  *
261
- * - `$2` (subpath) given → that folder is the skill.
261
+ * - `$3` (subpath) given → that folder is the skill.
262
262
  * - else repo root has a SKILL.md → the whole repo is the skill.
263
263
  * - else search the clone for SKILL.md files → install every skill folder it
264
264
  * finds (a "collection" repo), each under its own folder name.
265
265
  * - else exit 3 → the repo isn't a ready skill (needs a build; use cli mode).
266
266
  *
267
- * Params are positional argv ($1=url, $2=subpath, $3=name) — never interpolated
267
+ * Params are positional argv ($1=url, $2=name, $3=optional subpath) — never interpolated
268
268
  * into this text — so a repo URL / subpath can't shell-inject. `.git` is
269
269
  * stripped and the temp clone removed; existing skill dirs are left untouched.
270
270
  */
271
271
  const GIT_INSTALL_SCRIPT = `
272
272
  set -eu
273
- url="$1"; sub="$2"; name="$3"
273
+ url="$1"; name="$2"; sub="\${3:-}"
274
274
  skills="$HOME/.claude/skills"
275
275
  mkdir -p "$skills"
276
276
  tmp="$(mktemp -d)"
@@ -317,7 +317,9 @@ export function collectPackageSkills(agents: RosterAgent[]): RosterSkill[] {
317
317
  for (const a of agents) {
318
318
  if (a.kind !== "claude") continue;
319
319
  for (const s of a.skills ?? []) {
320
- if (s.type !== "package" || !s.value) continue;
320
+ // Draft entries must not claim a slug ahead of another agent's valid
321
+ // skill, or warn on every resume while their install details are unset.
322
+ if (s.type !== "package" || !s.value.trim() || s.source == null) continue;
321
323
  const key = skillSlug(s.name);
322
324
  if (seen.has(key)) continue;
323
325
  seen.add(key);
@@ -425,7 +427,28 @@ export async function installPackageSkills(
425
427
  for (const s of pkgs) {
426
428
  const slug = skillSlug(s.name);
427
429
  try {
430
+ // Validate author-supplied fields before invoking the provider so errors
431
+ // name the skill and field instead of surfacing a generic argv failure.
432
+ for (const [field, value] of [["name", s.name], ["value", s.value]] as const) {
433
+ if (!value.trim() || value.includes("\0")) {
434
+ throw new Error(`${field} must be a nonempty NUL-free string`);
435
+ }
436
+ }
437
+ if (s.source !== "git" && s.source !== "cli") {
438
+ throw new Error("source must be git or cli");
439
+ }
440
+ if (s.source === "git" && s.subpath?.includes("\0")) {
441
+ throw new Error("subpath must be NUL-free");
442
+ }
428
443
  if (s.source === "git") {
444
+ // subpath is de-fanged against traversal; url/subpath/name reach the
445
+ // installer as positional argv (never interpolated) — no shell inject.
446
+ const sub = (s.subpath ?? "").replace(/^[/.]+/, "").replace(/\.\.+/g, "");
447
+ // Single-dot/slash spellings mean the repo root. Only traversal that
448
+ // erases the whole path is an error, even if a done marker exists.
449
+ if (!sub && s.subpath?.includes("..")) {
450
+ throw new Error("subpath must name a folder after removing traversal");
451
+ }
429
452
  // Idempotent across ensureSessions re-runs: a marker records that the
430
453
  // clone+install already ran, so reconnects don't re-clone.
431
454
  const marker = `/home/node/.claude/skills/.uai-git-${slug}.done`;
@@ -433,17 +456,16 @@ export async function installPackageSkills(
433
456
  done.push(installedSkillPath(s));
434
457
  continue;
435
458
  }
436
- // subpath is de-fanged against traversal; url/subpath/name reach the
437
- // installer as positional argv (never interpolated) — no shell inject.
438
- const sub = (s.subpath ?? "").replace(/^[/.]+/, "").replace(/\.\.+/g, "");
439
459
  const r = await exec(container, [
440
460
  "bash",
441
461
  "-lc",
442
462
  GIT_INSTALL_SCRIPT,
443
463
  "uai-skill", // $0
444
464
  s.value, // $1 url
445
- sub, // $2 subpath
446
- slug, // $3 name
465
+ slug, // $2 name
466
+ // Environment exec forbids empty argv entries. Omit the optional
467
+ // subpath; the installer defaults it to empty inside the shell.
468
+ ...(sub ? [sub] : []), // $3 subpath
447
469
  ]);
448
470
  if (r.status !== 0) {
449
471
  const why =
@@ -0,0 +1,53 @@
1
+ /**
2
+ * The owned-host hourly standard-image maintenance schedule.
3
+ *
4
+ * A pass is Docker (or Apple container) work end to end; against an
5
+ * unavailable runtime every call waits out its own timeout (live 2026-11-06:
6
+ * a 1.0.4 station reported "no runtime" for 14 h while each hourly pass spent
7
+ * 15 min timing out against a hung OrbStack). So the schedule only runs a
8
+ * pass while the runtime is operational (the public state is `ready`), and
9
+ * otherwise skips with one log line. A detected-but-fenced runtime counts as
10
+ * not ready: activation has not yet proved the persisted environments'
11
+ * identity or quarantined writable containers (Codex review, 2026-11-06).
12
+ * Readiness brings its own maintenance: activation runs a pass on every ready
13
+ * edge, so a skipped hour is not lost.
14
+ */
15
+
16
+ export interface StandardImageScheduleDeps {
17
+ intervalMs: number;
18
+ /** The PUBLIC runtime status (containerRuntimeCapabilityState): `checking`
19
+ * while a detected runtime is still fenced. Activation's own pass does not
20
+ * go through this schedule. */
21
+ runtimeStatus: () => string;
22
+ run: () => Promise<unknown>;
23
+ log?: (line: string) => void;
24
+ }
25
+
26
+ /** One scheduled tick: run the pass, or skip it while the runtime is not ready. */
27
+ export async function runScheduledStandardImageMaintenance(
28
+ deps: Omit<StandardImageScheduleDeps, "intervalMs">,
29
+ ): Promise<"ran" | "skipped"> {
30
+ const status = deps.runtimeStatus();
31
+ if (status !== "ready") {
32
+ (deps.log ?? ((line: string) => console.log(line)))(
33
+ `[host-agent] standard-image maintenance skipped: container runtime is ${status}`,
34
+ );
35
+ return "skipped";
36
+ }
37
+ try {
38
+ await deps.run();
39
+ } catch {
40
+ // ensureStandardImage reports its own failures; a schedule tick never throws.
41
+ }
42
+ return "ran";
43
+ }
44
+
45
+ export function startStandardImageMaintenanceSchedule(
46
+ deps: StandardImageScheduleDeps,
47
+ ): () => void {
48
+ const timer = setInterval(() => {
49
+ void runScheduledStandardImageMaintenance(deps);
50
+ }, deps.intervalMs);
51
+ timer.unref?.();
52
+ return () => clearInterval(timer);
53
+ }
@@ -15,6 +15,7 @@ import {
15
15
  forgetCredentialCleanupRestop,
16
16
  listCredentialCleanupRecoveryTasks,
17
17
  listCredentialCleanupPaths,
18
+ listCredentialCleanupPending,
18
19
  listCredentialCleanupRestops,
19
20
  rememberCredentialCleanupPending,
20
21
  rememberCredentialCleanupRestop,
@@ -274,6 +275,10 @@ async function reconstructCleanupRuntime(
274
275
  * - `absent`, exactly: the runtime, its writable layer with it, is gone, and
275
276
  * so is every path in it. Any other answer, `unknown` above all, is no
276
277
  * proof (a failed call never proves absence, 2026-10-20).
278
+ * - `stopped` with no instance (the container gone, its worktree not) is
279
+ * no proof: a project's Dockerfile `VOLUME` under /home/node leaves an
280
+ * anonymous volume behind a container removed without `-v`, and nothing
281
+ * recorded names the image it was made from (2026-11-09 review).
277
282
  * - `stopped`, inside the boot sweep only: `docker exec` cannot reach a
278
283
  * stopped container, and after a reboot every one is, so the sweep failed
279
284
  * for good and the runner stayed in `checking` (2026-10-30). The runtime
@@ -400,6 +405,9 @@ export class TaskCredentialCleanupCoordinator {
400
405
  Promise<{ failedEpoch: number; clearThroughEpoch: number }>
401
406
  >();
402
407
  readonly #deps: TaskCredentialCleanupDeps;
408
+ /** Tasks whose boot cleanup failed and was isolated (`recoverAll`), until
409
+ * a full cleanup of them succeeds. */
410
+ readonly #isolated = new Set<string>();
403
411
 
404
412
  constructor(deps: TaskCredentialCleanupDeps) {
405
413
  this.#deps = deps;
@@ -485,6 +493,7 @@ export class TaskCredentialCleanupCoordinator {
485
493
  this.#tails.get(request.taskId) === tail &&
486
494
  result.state.failedEpoch === 0
487
495
  ) {
496
+ this.#isolated.delete(request.taskId);
488
497
  forgetCredentialCleanupPending(
489
498
  request.taskId,
490
499
  result.state.clearThroughEpoch,
@@ -691,6 +700,23 @@ export class TaskCredentialCleanupCoordinator {
691
700
  this.#deps.hooks.dropMemory(request);
692
701
  }
693
702
 
703
+ /** Whether this process's boot sweep isolated the task's failed cleanup
704
+ * (`recoverAll`) and it still has durable cleanup left (a pending
705
+ * witness, a path row of any run, an owed re-stop): a start of it must
706
+ * run its full cleanup, and prove it, before its gate may open (the
707
+ * registry's startup fence). Only an isolated task: any other task with
708
+ * rows held the sweep, or got them in this process, and starts as before.
709
+ * Each process's sweep isolates afresh. */
710
+ isolatedCleanupOwed(taskId: string): boolean {
711
+ if (!this.#isolated.has(taskId)) return false;
712
+ const owed =
713
+ listCredentialCleanupPending(this.#deps.db).some((row) => row.taskId === taskId) ||
714
+ listCredentialCleanupPaths(taskId, this.#deps.db).length > 0 ||
715
+ listCredentialCleanupRestops(taskId, this.#deps.db).length > 0;
716
+ if (!owed) this.#isolated.delete(taskId);
717
+ return owed;
718
+ }
719
+
694
720
  /** Every re-stop the task is owed, tried; each proven retired. Only proof
695
721
  * that the exact container is stopped or gone retires one: a removed
696
722
  * credential path never does. */
@@ -729,9 +755,18 @@ export class TaskCredentialCleanupCoordinator {
729
755
  }
730
756
 
731
757
  /** Boot recovery sweeps every durable task before any grant may be asked.
732
- * Every task is attempted, one failing never leaving the next unswept;
733
- * then any failure, all of them, fails the sweep. */
734
- async recoverAll(runEpochForTask: (taskId: string) => number): Promise<void> {
758
+ * Every task is attempted, one failing never leaving the next unswept.
759
+ * A failure is that task's alone when `isolatable` says the task has no
760
+ * run left (decisions.md "One bad task never blocks the fleet"): its
761
+ * rows, pending witness and closed gate stay, host.log names it, and the
762
+ * next sweep tries it again; the sweep goes on. Any other failure fails
763
+ * the sweep, all of them listed: a task that may still run would have
764
+ * its surviving agents reattached, or a start's gate opened, before its
765
+ * credential paths were proven gone. Absent `isolatable`, none is. */
766
+ async recoverAll(
767
+ runEpochForTask: (taskId: string) => number,
768
+ isolatable: (taskId: string) => boolean = () => false,
769
+ ): Promise<void> {
735
770
  const tasks = listCredentialCleanupRecoveryTasks(this.#deps.db);
736
771
  const failures: unknown[] = [];
737
772
  for (const task of tasks) {
@@ -742,11 +777,33 @@ export class TaskCredentialCleanupCoordinator {
742
777
  reason: "restart",
743
778
  }, true);
744
779
  } catch (error) {
745
- failures.push(error);
780
+ let isolated = false;
781
+ try {
782
+ isolated = isolatable(task.taskId);
783
+ } catch {
784
+ // Unknown is not isolated: the failure holds the sweep.
785
+ }
786
+ if (!isolated) {
787
+ failures.push(error);
788
+ continue;
789
+ }
790
+ this.#isolated.add(task.taskId);
791
+ console.warn(
792
+ `[credentials] boot recovery: task ${task.taskId} has no run left and its credential cleanup failed; ` +
793
+ `its rows and gate stay closed, the next sweep tries it again, and the station proceeds: ${
794
+ (error instanceof Error ? error.message : String(error)).slice(0, 500)
795
+ }`,
796
+ );
746
797
  }
747
798
  }
748
799
  if (failures.length > 0) {
749
- throw new AggregateError(failures, `credential recovery failed for ${String(failures.length)} task(s)`);
800
+ const detail = failures
801
+ .map((error) => (error instanceof Error ? error.message : String(error)).slice(0, 300))
802
+ .join("; ");
803
+ throw new AggregateError(
804
+ failures,
805
+ `credential recovery failed for ${String(failures.length)} task(s): ${detail}`.slice(0, 2_000),
806
+ );
750
807
  }
751
808
  }
752
809
  }
@@ -23,6 +23,7 @@ import type {
23
23
  MachineProvider,
24
24
  } from "../machine-provider";
25
25
  import { machineEnvironmentSshArgs } from "../machine-exec";
26
+ import { STATION_MACHINE_PAYLOAD_MARKER } from "../machine-payload-image";
26
27
  import { applyProjectEnvProfile } from "../runtime-authority";
27
28
  import { rootAnchoredRequest } from "./anchor";
28
29
  import {
@@ -217,6 +218,16 @@ class MachineTaskEnvironmentHandle implements TaskEnvironmentHandle {
217
218
  MachineTaskEnvironmentDeps;
218
219
  /** The machine's own /etc/environment, read once (see #anchoredBaseline). */
219
220
  #machineWide: Promise<Record<string, string>> | null = null;
221
+ /** Station payload validation (plan §1 item 3), enforced IN the handle so
222
+ * that every path to this machine runs the same rule first: provision,
223
+ * recovery, and any reconstructed handle's exec/spawn/session/copy/file
224
+ * op/gateway tunnel (all dial through #target) plus route inspection. An
225
+ * AWS machine still tagged `pending` is probed for the marker before
226
+ * anything else reaches it. A pass is remembered PER PHYSICAL INSTANCE
227
+ * (the EC2 instance id): a replacement under the same logical id is a
228
+ * different machine and the rule applies to it afresh. */
229
+ #validatedInstance: string | null = null;
230
+ #payloadProbe: { instanceId: string; done: Promise<void> } | null = null;
220
231
 
221
232
  constructor(
222
233
  locator: TaskEnvironmentLocator,
@@ -242,7 +253,7 @@ class MachineTaskEnvironmentHandle implements TaskEnvironmentHandle {
242
253
  /** Resolve the CURRENT dial target. Cloud machines change address across
243
254
  * stop/start, so the locator never stores one — describe is the only
244
255
  * source of truth, and a non-running machine has no target at all. */
245
- async #target(): Promise<{
256
+ async #target(options: { validate?: boolean } = {}): Promise<{
246
257
  address: string;
247
258
  keyPath: string;
248
259
  port?: number;
@@ -253,6 +264,17 @@ class MachineTaskEnvironmentHandle implements TaskEnvironmentHandle {
253
264
  `machine ${this.#value.machineId} is not reachable (${info.state})`,
254
265
  );
255
266
  }
267
+ // Only readiness checks and the probe itself dial an unvalidated machine.
268
+ // The gate and the dial use the SAME describe answer, so the instance
269
+ // validated is the instance dialed.
270
+ if (options.validate !== false) await this.#gate(info);
271
+ return this.#dialTarget(info);
272
+ }
273
+
274
+ #dialTarget(info: MachineInfo): { address: string; keyPath: string; port?: number } {
275
+ if (info.state !== "running" || info.address === null) {
276
+ throw new Error(`machine ${this.#value.machineId} is not reachable (${info.state})`);
277
+ }
256
278
  return {
257
279
  address: info.address,
258
280
  keyPath: this.#value.privateKeyPath,
@@ -260,6 +282,146 @@ class MachineTaskEnvironmentHandle implements TaskEnvironmentHandle {
260
282
  };
261
283
  }
262
284
 
285
+ /** Validate before use. `validation` is what the caller knows (provision:
286
+ * what it launched or found); otherwise the machine's own tag is read. */
287
+ async ensurePayloadValidated(validation?: MachineInfo["payloadValidation"]): Promise<void> {
288
+ const info = await this.#describeOwn();
289
+ await this.#gate(validation === undefined ? info : { ...info, payloadValidation: validation });
290
+ }
291
+
292
+ async #gate(info: MachineInfo): Promise<void> {
293
+ if (this.#deps.machines.kind !== "aws") return;
294
+ const instanceId = info.instanceId ?? null;
295
+ // A different physical instance than the one validated: forget the pass
296
+ // and apply the rule to this one (pending → probe; ok/null → no probe).
297
+ if (this.#validatedInstance !== null && this.#validatedInstance !== instanceId) {
298
+ this.#validatedInstance = null;
299
+ }
300
+ if (info.payloadValidation !== "pending") return;
301
+ if (instanceId === null) {
302
+ throw new PayloadValidationError(
303
+ `machine ${this.#value.machineId} is pending payload validation but its instance id is unknown (left pending; the next attempt probes again)`,
304
+ true,
305
+ );
306
+ }
307
+ if (this.#validatedInstance === instanceId) return;
308
+ // Join an in-flight probe only when it is for THIS instance: one started
309
+ // for a replaced instance must never stand in for its successor.
310
+ let probe = this.#payloadProbe;
311
+ if (!probe || probe.instanceId !== instanceId) {
312
+ const started: { instanceId: string; done: Promise<void> } = {
313
+ instanceId,
314
+ done: this.#probePayloadMarker(info, instanceId).then(() => {
315
+ // Remember the instance that was PROBED, nothing else.
316
+ this.#validatedInstance = instanceId;
317
+ }),
318
+ };
319
+ started.done.catch(() => {
320
+ // A failed probe proves nothing: the next use probes again.
321
+ if (this.#payloadProbe === started) this.#payloadProbe = null;
322
+ });
323
+ this.#payloadProbe = started;
324
+ probe = started;
325
+ }
326
+ await probe.done;
327
+ // A replacement raced the probe: this caller's instance is no longer
328
+ // the one remembered, so the caller's answer is not validated.
329
+ if (this.#validatedInstance !== instanceId) {
330
+ throw new PayloadValidationError(
331
+ `machine ${this.#value.machineId} changed instance during payload validation (left pending; the next attempt probes again)`,
332
+ true,
333
+ );
334
+ }
335
+ }
336
+
337
+ /** One ssh round trip that bypasses the payload gate (readiness, probe).
338
+ * `info` pins the dial to one describe answer (the probe's instance). */
339
+ async #ungatedSsh(argv: readonly [string, ...string[]], timeoutMs: number, info?: MachineInfo): Promise<{ exitCode: number | null; stderr: string }> {
340
+ const target = info ? this.#dialTarget(info) : await this.#target({ validate: false });
341
+ const result = await capturedCliExec(
342
+ this.#deps.spawn,
343
+ "ssh",
344
+ machineEnvironmentSshArgs(target, this.#maintenanceRequest({ argv }), "interactive"),
345
+ { argv: [argv[0]], projectEnvProfile: "maintenance", timeoutMs, maxOutputBytes: 4 * 1024 },
346
+ );
347
+ return { exitCode: result.exitCode, stderr: Buffer.from(result.stderr).toString("utf8").trim() };
348
+ }
349
+
350
+ /** ssh readiness without the payload gate (provision's wait). */
351
+ async sshReady(): Promise<{ ready: boolean; detail: string }> {
352
+ try {
353
+ const probe = await this.#ungatedSsh(["/bin/true"], 10_000);
354
+ return { ready: probe.exitCode === 0, detail: probe.stderr || `probe exited ${probe.exitCode ?? "killed"}` };
355
+ } catch (error) {
356
+ return { ready: false, detail: error instanceof Error ? error.message : String(error) };
357
+ }
358
+ }
359
+
360
+ /** Marker present: record `ok` (a failed write throws, retryable; the
361
+ * machine stays `pending`). Marker DEFINITELY missing (exit 1): terminate,
362
+ * then throw (fatal); a failed terminate leaves it `pending`, so every
363
+ * later use probes and terminates again and nothing reaches it. Anything
364
+ * else (ssh error, timeout): throw, retryable, machine alive and `pending`
365
+ * — a slow boot is not evidence of a wrong image. */
366
+ async #probePayloadMarker(info: MachineInfo, instanceId: string): Promise<void> {
367
+ const machineId = this.#value.machineId;
368
+ const machines = this.#deps.machines;
369
+ let probe: { exitCode: number | null; stderr: string };
370
+ try {
371
+ probe = await this.#ungatedSsh(
372
+ ["/bin/sh", "-c", 'test -f "$1"', "payload-probe", STATION_MACHINE_PAYLOAD_MARKER],
373
+ 30_000,
374
+ info,
375
+ );
376
+ } catch (error) {
377
+ throw new PayloadValidationError(
378
+ `payload marker probe on ${machineId} could not run (left pending; the next attempt probes again): ${
379
+ error instanceof Error ? error.message : String(error)
380
+ }`,
381
+ true,
382
+ );
383
+ }
384
+ if (probe.exitCode === 0) {
385
+ if (!machines.markPayloadValidated) {
386
+ throw new PayloadValidationError(`machine backend ${machines.kind} cannot record payload validation`, false);
387
+ }
388
+ try {
389
+ await machines.markPayloadValidated(machineId, instanceId);
390
+ } catch (error) {
391
+ throw new PayloadValidationError(
392
+ `${error instanceof Error ? error.message : String(error)} (left pending; the next attempt probes again)`,
393
+ true,
394
+ );
395
+ }
396
+ return;
397
+ }
398
+ if (probe.exitCode === 1) {
399
+ try {
400
+ // Exactly the probed instance: never the logical id, which may
401
+ // already name a replacement that must not be touched.
402
+ if (!machines.terminateInstance) {
403
+ throw new Error(`machine backend ${machines.kind} cannot terminate one instance`);
404
+ }
405
+ await machines.terminateInstance(machineId, instanceId);
406
+ } catch (error) {
407
+ throw new PayloadValidationError(
408
+ `machine ${machineId} lacks the Station payload marker ${STATION_MACHINE_PAYLOAD_MARKER} and could not be terminated (left pending; the next attempt probes and terminates again): ${
409
+ error instanceof Error ? error.message : String(error)
410
+ }`,
411
+ false,
412
+ );
413
+ }
414
+ throw new PayloadValidationError(
415
+ `machine ${machineId} was launched from an image without the Station payload marker ${STATION_MACHINE_PAYLOAD_MARKER}; it was terminated. Set UAI_MACHINE_IMAGE to an approved Station AMI, or ask Moondeck to check this region's image`,
416
+ false,
417
+ );
418
+ }
419
+ throw new PayloadValidationError(
420
+ `payload marker probe on ${machineId} did not answer (exit ${probe.exitCode ?? "killed"}${probe.stderr ? `: ${probe.stderr}` : ""}); left pending, the next attempt probes again`,
421
+ true,
422
+ );
423
+ }
424
+
263
425
  /** Describe with the ownership check every mutation rides on: a machine
264
426
  * that does not carry OUR task label is a foreign occupant of the id and
265
427
  * is treated as unknown — never dialed, never stopped, never terminated. */
@@ -621,6 +783,12 @@ class MachineTaskEnvironmentHandle implements TaskEnvironmentHandle {
621
783
  > {
622
784
  const info = await this.#describeOwn();
623
785
  if (info.state === "running" && info.address !== null) {
786
+ // The editor and previews dial the machine directly: same gate.
787
+ try {
788
+ await this.#gate(info);
789
+ } catch (error) {
790
+ return { kind: "unknown", detail: error instanceof Error ? error.message : String(error) };
791
+ }
624
792
  return { kind: "running", ipv4Address: info.address };
625
793
  }
626
794
  if (info.state === "stopped" || info.state === "absent") {
@@ -752,6 +920,21 @@ class MachineTaskEnvironmentHandle implements TaskEnvironmentHandle {
752
920
  if (!context.isCurrent()) {
753
921
  return { outcome: "deferred", detail: "runtime generation superseded" };
754
922
  }
923
+ // A Station that died between launch and probe left the machine
924
+ // `pending`: probe it before any consumer is prepared or admitted. A
925
+ // retryable failure defers (the machine stays pending); a missing
926
+ // marker terminated it, which throws like provision does.
927
+ try {
928
+ await this.#gate(info);
929
+ } catch (error) {
930
+ if (error instanceof PayloadValidationError && error.retryable) {
931
+ return { outcome: "deferred", detail: error.message };
932
+ }
933
+ throw error;
934
+ }
935
+ if (!context.isCurrent()) {
936
+ return { outcome: "deferred", detail: "runtime generation superseded" };
937
+ }
755
938
  await context.prepareConsumers?.();
756
939
  context.allowConsumers?.();
757
940
  await context.ensureConsumersStarted?.();
@@ -764,7 +947,7 @@ class MachineTaskEnvironmentHandle implements TaskEnvironmentHandle {
764
947
 
765
948
  async #sshAnswers(): Promise<boolean> {
766
949
  try {
767
- const target = await this.#target();
950
+ const target = await this.#target({ validate: false });
768
951
  const result = await capturedCliExec(
769
952
  this.#deps.spawn,
770
953
  "ssh",
@@ -863,6 +1046,10 @@ export function createMachineTaskEnvironmentProvider(
863
1046
  );
864
1047
  }
865
1048
  const reused = existing.state !== "absent";
1049
+ // Validation state lives ON the machine (set at launch), so a retry
1050
+ // or a restarted Station sees the same answer: an unconfirmed machine
1051
+ // is probed whether it is fresh or reused.
1052
+ let payloadValidation = existing.payloadValidation ?? null;
866
1053
  if (existing.state === "absent") {
867
1054
  const launched = await deps.machines.launch({
868
1055
  taskId,
@@ -881,6 +1068,7 @@ export function createMachineTaskEnvironmentProvider(
881
1068
  `machine backend named ${launched.id}, locator promised ${machineId}`,
882
1069
  );
883
1070
  }
1071
+ payloadValidation = launched.payloadValidation ?? null;
884
1072
  } else if (existing.state === "stopped") {
885
1073
  await deps.machines.start(machineId);
886
1074
  }
@@ -893,6 +1081,13 @@ export function createMachineTaskEnvironmentProvider(
893
1081
  );
894
1082
  await waitForSsh(handle, deps.readyTimeoutMs ?? 120_000);
895
1083
 
1084
+ // Before ANY workspace prep, clone or credential delivery: an AWS
1085
+ // machine launched from an auto-selected image must carry the Station
1086
+ // payload marker. `ok` / null (validated before, pre-1.0.5, or pinned)
1087
+ // is preserved and never terminated from here. (The handle enforces
1088
+ // the same rule on every later dial.)
1089
+ await handle.ensurePayloadValidated(payloadValidation);
1090
+
896
1091
  // Workspace + optional in-env clone (ADR-121: the clone happens in the
897
1092
  // task's world; the host never materializes task code).
898
1093
  // As root: the workspace root is typically directly under a
@@ -948,6 +1143,16 @@ export function createMachineTaskEnvironmentProvider(
948
1143
  };
949
1144
  }
950
1145
 
1146
+ /** A payload validation failure. `retryable`: the machine is alive and
1147
+ * still `pending`, and a later attempt probes again. Otherwise the image is
1148
+ * wrong (marker missing; terminated, or termination itself failed). */
1149
+ export class PayloadValidationError extends Error {
1150
+ override name = "PayloadValidationError";
1151
+ constructor(message: string, readonly retryable: boolean) {
1152
+ super(message);
1153
+ }
1154
+ }
1155
+
951
1156
  async function waitForSsh(
952
1157
  handle: MachineTaskEnvironmentHandle,
953
1158
  budgetMs: number,
@@ -955,19 +1160,10 @@ async function waitForSsh(
955
1160
  const deadline = Date.now() + budgetMs;
956
1161
  let lastDetail = "ssh never answered";
957
1162
  while (Date.now() < deadline) {
958
- try {
959
- const probe = await handle.exec({
960
- argv: ["/bin/true"],
961
- projectEnvProfile: "maintenance",
962
- timeoutMs: 10_000,
963
- maxOutputBytes: 4 * 1024,
964
- });
965
- if (probe.exitCode === 0) return;
966
- lastDetail = Buffer.from(probe.stderr).toString("utf8").trim() ||
967
- `probe exited ${probe.exitCode ?? "killed"}`;
968
- } catch (error) {
969
- lastDetail = error instanceof Error ? error.message : String(error);
970
- }
1163
+ // Readiness only: the payload gate runs after it, not inside it.
1164
+ const probe = await handle.sshReady();
1165
+ if (probe.ready) return;
1166
+ lastDetail = probe.detail;
971
1167
  await new Promise<void>((resolve) => setTimeout(resolve, 2_000));
972
1168
  }
973
1169
  throw new Error(`machine never became reachable over ssh: ${lastDetail}`);
@@ -42,6 +42,15 @@ const WARN_THRESHOLD = 0.8;
42
42
  * requires the vnode ratio AND genuine file-table pressure together.
43
43
  */
44
44
  const FILE_TABLE_CORROBORATION_THRESHOLD = 0.5;
45
+ /**
46
+ * The warn band needs the same corroboration, scaled to the warn band. A
47
+ * vnode ratio alone warned at every boot on a normal Mac (MacBook Air,
48
+ * 2026-11-06: `vnodes 263168/263168 (100%)`): macOS caches vnodes until the
49
+ * table reaches kern.maxvnodes, so a full table is the steady state there,
50
+ * not pressure. The sysctls are the right ones; the band was wrong.
51
+ */
52
+ const FILE_TABLE_WARN_CORROBORATION_THRESHOLD =
53
+ FILE_TABLE_CORROBORATION_THRESHOLD * WARN_THRESHOLD;
45
54
  const CACHE_MS = 15_000;
46
55
 
47
56
  export interface VnodePressure {
@@ -112,19 +121,33 @@ export async function vnodeAdmissionProblem(): Promise<string | null> {
112
121
 
113
122
  let lastLoggedBand: "ok" | "warn" | "critical" = "ok";
114
123
 
124
+ /** The log band for one reading: a full vnode table counts only when the
125
+ * file table corroborates it (see FILE_TABLE_WARN_CORROBORATION_THRESHOLD). */
126
+ export function vnodePressureBand(
127
+ pressure: VnodePressure,
128
+ ): "ok" | "warn" | "critical" {
129
+ if (
130
+ pressure.ratio >= ADMISSION_THRESHOLD &&
131
+ pressure.filesRatio >= FILE_TABLE_CORROBORATION_THRESHOLD
132
+ ) {
133
+ return "critical";
134
+ }
135
+ if (pressure.filesRatio >= WARN_THRESHOLD) return "warn";
136
+ if (
137
+ pressure.ratio >= WARN_THRESHOLD &&
138
+ pressure.filesRatio >= FILE_TABLE_WARN_CORROBORATION_THRESHOLD
139
+ ) {
140
+ return "warn";
141
+ }
142
+ return "ok";
143
+ }
144
+
115
145
  /** Log on band TRANSITIONS only, so a host sitting near the ceiling does not
116
146
  * spam its own log every interval. */
117
147
  export async function logVnodePressure(): Promise<void> {
118
148
  const pressure = await readVnodePressure();
119
149
  if (!pressure) return;
120
- const refusing =
121
- pressure.ratio >= ADMISSION_THRESHOLD &&
122
- pressure.filesRatio >= FILE_TABLE_CORROBORATION_THRESHOLD;
123
- const band = refusing
124
- ? "critical"
125
- : pressure.filesRatio >= WARN_THRESHOLD || pressure.ratio >= WARN_THRESHOLD
126
- ? "warn"
127
- : "ok";
150
+ const band = vnodePressureBand(pressure);
128
151
  if (band === lastLoggedBand) return;
129
152
  lastLoggedBand = band;
130
153
  const detail =
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moondeck/station",
3
- "version": "1.0.4",
3
+ "version": "1.0.5",
4
4
  "description": "Moondeck Station: runs Moondeck tasks in containers on a machine you control.",
5
5
  "license": "MIT",
6
6
  "author": "Moondeck <team@moondeck.io>",