@moondeck/station 1.0.4 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -43,6 +43,49 @@ export interface MachineSpec {
43
43
  * host-routable there, so SSH must ride a loopback-published port. The
44
44
  * Linux guinea pig and cloud backends dial the address directly. */
45
45
  publishSsh?: boolean;
46
+ /** F3: where the task's launch intent is kept (its control dir), so a
47
+ * retry after a restart replays the subnet an earlier attempt used before
48
+ * trying any other. Backends without placement choices ignore it. */
49
+ launchIntent?: MachineLaunchIntentStore;
50
+ /** Which launch of this task's machine this is (F6). A cloud backend's
51
+ * launch idempotency is keyed on it: 0 (or absent) is the task's first
52
+ * machine, with the token every earlier release used. The caller bumps it
53
+ * only after the backend proved the previous generation's machine
54
+ * terminated (MachineLaunchTokenSpentError), so a retry of a launch still
55
+ * in flight keeps its token and can never mint a second machine. */
56
+ launchGeneration?: number;
57
+ }
58
+
59
+ /** The subnet a launch is attempting or launched in; `attempting` means its
60
+ * outcome is not yet known. */
61
+ export interface MachineLaunchIntent {
62
+ subnetId: string;
63
+ state: "attempting" | "launched";
64
+ }
65
+
66
+ export interface MachineLaunchIntentStore {
67
+ read(): MachineLaunchIntent | null;
68
+ /** Atomic and durable before it returns; throws rather than pretend. */
69
+ write(intent: MachineLaunchIntent): void;
70
+ }
71
+
72
+ /**
73
+ * The backend's launch idempotency resolved to a machine that is already
74
+ * terminated (F6, test 6.3): EC2 remembers a client token for a while past
75
+ * termination and answers a repeat with the old, gone instance. Proof that
76
+ * this launch generation is spent; the caller may launch the next one.
77
+ */
78
+ export class MachineLaunchTokenSpentError extends Error {
79
+ override readonly name = "MachineLaunchTokenSpentError";
80
+ constructor(
81
+ readonly machineId: string,
82
+ readonly instanceId: string,
83
+ readonly instanceState: string,
84
+ ) {
85
+ super(
86
+ `machine ${machineId}: its launch token resolved to instance ${instanceId}, which is ${instanceState}`,
87
+ );
88
+ }
46
89
  }
47
90
 
48
91
  export interface MachineInfo {
@@ -66,6 +109,17 @@ export interface MachineInfo {
66
109
  sshPort?: number;
67
110
  /** Present only alongside `unknown` — what the backend actually said. */
68
111
  detail?: string;
112
+ /** Station payload validation recorded ON the machine (aws: the
113
+ * `com.uai.payload-validation` tag, set to `pending` atomically at launch
114
+ * of an auto-selected image). `pending` = the payload marker has not been
115
+ * confirmed yet, so it is probed before any workspace prep; `ok` = it was;
116
+ * null/absent = never subject to the probe (pinned image, pre-1.0.5
117
+ * machine, or a backend without the concept). */
118
+ payloadValidation?: "pending" | "ok" | null;
119
+ /** The PHYSICAL instance behind the logical id (aws: the EC2 instance id).
120
+ * Payload validation is bound to it: a replacement under the same logical
121
+ * id is a different machine and is validated afresh. */
122
+ instanceId?: string;
69
123
  }
70
124
 
71
125
  export interface MachineProvider {
@@ -87,4 +141,15 @@ export interface MachineProvider {
87
141
  * rows reject the whole listing (they could hide exactly the labeled
88
142
  * machine a proof needs to see). */
89
143
  list(): Promise<MachineInfo[]>;
144
+ /** Record that the payload marker was confirmed ON exactly `instanceId`
145
+ * (the physical instance that was probed), never on whatever the logical
146
+ * id resolves to now. Backends without validation state omit it. Throws
147
+ * when the write fails; the instance then stays `pending`. */
148
+ markPayloadValidated?(id: string, instanceId: string): Promise<void>;
149
+ /** Terminate exactly ONE physical instance (the one a payload probe
150
+ * rejected), never re-resolving the logical id: a replacement under the
151
+ * same id is never touched. Resolves once that instance is proven
152
+ * shutting down or gone; throws otherwise. Ordinary teardown keeps using
153
+ * `terminate(id)`. */
154
+ terminateInstance?(id: string, instanceId: string): Promise<void>;
90
155
  }
@@ -37,6 +37,8 @@ import {
37
37
  BUNDLED_RUNTIME_ROOT,
38
38
  MANAGED_RUNTIME_CAPABILITY,
39
39
  MANAGED_RUNTIME_CREDENTIALS,
40
+ AGENT_FILES_SINCE_1_0_5,
41
+ agentFilesRequiredFor,
40
42
  MANAGED_RUNTIME_CREDENTIALS_VERSION,
41
43
  extractVerifiedRuntimeArchive,
42
44
  readVerifiedArtifactFile,
@@ -2165,6 +2167,29 @@ export async function validateInstalledRuntime(
2165
2167
  throw new Error(`managed runtime file escapes its version directory: ${relative}`);
2166
2168
  }
2167
2169
  }
2170
+ for (const [relative, executable] of AGENT_FILES_SINCE_1_0_5) {
2171
+ const absolute = path.join(root, ...relative.split("/"));
2172
+ const stat = await lstat(absolute).catch((error: NodeJS.ErrnoException) => {
2173
+ if (error.code === "ENOENT") return null;
2174
+ throw error;
2175
+ });
2176
+ // Absent in every generation before 1.0.5, a rollback target included;
2177
+ // required from 1.0.5 on.
2178
+ if (stat === null) {
2179
+ if (agentFilesRequiredFor(descriptor.hostVersion)) {
2180
+ throw new Error(`managed runtime is missing regular file ${relative}`);
2181
+ }
2182
+ continue;
2183
+ }
2184
+ if (!stat.isFile()) throw new Error(`managed runtime is missing regular file ${relative}`);
2185
+ if (executable && (stat.mode & 0o111) === 0) {
2186
+ throw new Error(`managed runtime file is not executable: ${relative}`);
2187
+ }
2188
+ const resolved = await realpath(absolute);
2189
+ if (!isInside(root, resolved)) {
2190
+ throw new Error(`managed runtime file escapes its version directory: ${relative}`);
2191
+ }
2192
+ }
2168
2193
  if (capabilities.capabilitySchemaVersion === 3) {
2169
2194
  await validateInstalledRuntimeAssets(root, capabilities);
2170
2195
  }
@@ -142,6 +142,7 @@ import {
142
142
  ensureMachineGatewayTunnel,
143
143
  ensureMachineGatewayTunnelReady,
144
144
  MACHINE_GATEWAY_TUNNEL_PORT,
145
+ stopMachineGatewayTunnel,
145
146
  } from "./machine-gateway-tunnel";
146
147
  import { ensureContainerTaskEnvForwarder } from "./task-env-forwarder";
147
148
  import { STATION_AGENT_CLI } from "../src/station-identity";
@@ -1665,6 +1666,14 @@ export class Orchestrator {
1665
1666
  ) {
1666
1667
  return false;
1667
1668
  }
1669
+ // A healthy initial start stays memoized, so binds and the start-loop tail
1670
+ // do not run on a re-attach ensure. Reassert the actual roster state to
1671
+ // heal a ready event lost by the cloud's former stage-write race. An ensure
1672
+ // acknowledgement alone is not readiness: every roster member must have
1673
+ // bound (including one-shot engines that have since exited).
1674
+ if (ready && this.rosterReady(channel)) {
1675
+ this.emitTaskStage(channel.taskId, "ready");
1676
+ }
1668
1677
  return ready;
1669
1678
  }
1670
1679
 
@@ -8238,6 +8247,27 @@ function finishAllTaskRecovery(): void {
8238
8247
  for (const taskId of [...taskRecoveryBarriers.keys()]) {
8239
8248
  finishTaskRecovery(taskId);
8240
8249
  }
8250
+ abandonedTaskRecoveries.clear();
8251
+ }
8252
+
8253
+ /** Boot-recovery attempts under way, by task: a barrier is never released
8254
+ * under one (the attempt may be starting the task's runtime). */
8255
+ const recoveringTaskIds = new Set<string>();
8256
+ /** Tasks whose boot recovery a terminal command ended (F4): never retried. */
8257
+ const abandonedTaskRecoveries = new Set<string>();
8258
+
8259
+ /**
8260
+ * Terminal intent (task deletion / teardown of the current run): end this
8261
+ * task's boot recovery. Its barrier opens now, or as soon as an attempt
8262
+ * under way returns, and no later pass retries it, so the teardown queued
8263
+ * behind the barrier runs instead of waiting out every retry (F4, test 6.2:
8264
+ * a deleted task whose machine was never launched kept recovery retrying
8265
+ * until the next restart). A no-op once the task's recovery is over.
8266
+ */
8267
+ export function abandonTaskRecovery(taskId: string): void {
8268
+ if (!taskRecoveryBarriers.has(taskId)) return;
8269
+ abandonedTaskRecoveries.add(taskId);
8270
+ if (!recoveringTaskIds.has(taskId)) finishTaskRecovery(taskId);
8241
8271
  }
8242
8272
 
8243
8273
  export function taskRecoveryComplete(taskId: string): Promise<void> {
@@ -9717,6 +9747,12 @@ async function recoveryPass(
9717
9747
  );
9718
9748
  for (const task of rows) {
9719
9749
  if (!isCurrent()) break;
9750
+ if (!lifecycle && abandonedTaskRecoveries.has(task.taskId)) {
9751
+ abandonedTaskRecoveries.delete(task.taskId);
9752
+ finishTaskRecovery(task.taskId);
9753
+ continue;
9754
+ }
9755
+ if (!lifecycle) recoveringTaskIds.add(task.taskId);
9720
9756
  try {
9721
9757
  const recovered = lifecycle
9722
9758
  ? await lifecycle.runTaskLifecycle(task.taskId, async () => {
@@ -9745,7 +9781,10 @@ async function recoveryPass(
9745
9781
  isCurrent,
9746
9782
  consumerLifecycle,
9747
9783
  );
9748
- if (recovered) {
9784
+ if (!lifecycle && abandonedTaskRecoveries.delete(task.taskId)) {
9785
+ // Ended by a terminal command while this attempt ran.
9786
+ finishTaskRecovery(task.taskId);
9787
+ } else if (recovered) {
9749
9788
  if (!lifecycle) finishTaskRecovery(task.taskId);
9750
9789
  } else {
9751
9790
  deferred.add(task.taskId);
@@ -9757,6 +9796,8 @@ async function recoveryPass(
9757
9796
  `[orchestrator] recovery: ${task.taskId} failed:`,
9758
9797
  err instanceof Error ? err.message : err,
9759
9798
  );
9799
+ } finally {
9800
+ if (!lifecycle) recoveringTaskIds.delete(task.taskId);
9760
9801
  }
9761
9802
  }
9762
9803
  } catch (err) {
@@ -10078,6 +10119,18 @@ async function recoverPersistedTaskEnvironment(
10078
10119
  : {}),
10079
10120
  });
10080
10121
  if (result.outcome === "recovered" && !consumersPrepared && isCurrent()) {
10122
+ const settled = result.status?.state;
10123
+ if (settled === "absent" || settled === "stopped") {
10124
+ // F4 (test 6.2): the provider proved nothing runs, so there is no
10125
+ // consumer to prepare. Preparing them anyway waited on a gateway
10126
+ // tunnel to a machine that does not exist, deferred recovery every
10127
+ // pass, and held Resume and deletion behind the task's barrier.
10128
+ // Settle the row as stopped instead, like Docker and Apple recovery:
10129
+ // Resume provisions it (starting a stopped machine, launching an
10130
+ // absent one), and deletion tears it down.
10131
+ settleRecoveredWithoutRuntime(task.taskId, settled);
10132
+ return true;
10133
+ }
10081
10134
  const current = getHostTask(task.taskId);
10082
10135
  if (current?.statusMirror && isActive(current.statusMirror)) {
10083
10136
  await prepareConsumers();
@@ -10093,6 +10146,22 @@ async function recoverPersistedTaskEnvironment(
10093
10146
  }
10094
10147
  }
10095
10148
 
10149
+ /** A recovered environment with nothing running: drop the gateway tunnel the
10150
+ * recovery armed, mark an active row stopped, and revoke its gateway token. */
10151
+ function settleRecoveredWithoutRuntime(
10152
+ taskId: string,
10153
+ state: "absent" | "stopped",
10154
+ ): void {
10155
+ stopMachineGatewayTunnel(taskId);
10156
+ const current = getHostTask(taskId);
10157
+ if (!current?.statusMirror || !isActive(current.statusMirror)) return;
10158
+ db_setStatus(taskId, "stopped", { codeServerPort: null, previewPorts: "[]" });
10159
+ clearTaskGatewayAcl(taskId);
10160
+ console.log(
10161
+ `[orchestrator] recovery: ${taskId} has no running environment (${state}); marked stopped until Resume`,
10162
+ );
10163
+ }
10164
+
10096
10165
  /** A durable row the provider can never reconcile with its locator. Retrying
10097
10166
  * cannot change the verdict, so the sweep must not treat it as an unknown
10098
10167
  * runtime state: that kept the whole runtime in checking, retrying every
@@ -459,6 +459,41 @@ function validateEntryGraph(
459
459
  }
460
460
  }
461
461
 
462
+
463
+ /**
464
+ * Agent scripts added in Station 1.0.5: the dependency list _common.sh
465
+ * sources, and the Station's report of it. The build requires them
466
+ * (scripts/host-runtime/archive.mjs). Validation here and of an installed
467
+ * generation (managed-runtime.ts) requires them for a generation at or above
468
+ * 1.0.5, and for an older one checks them only if present: both validators
469
+ * also judge OLDER generations (a rollback target, a pinned earlier
470
+ * release), which never had them, and refusing those would block every way
471
+ * back. Main is still 1.0.4 while these land; #790's bump to 1.0.5 is what
472
+ * makes them required, with no further change here.
473
+ */
474
+ export const AGENT_FILES_SINCE_1_0_5: ReadonlyArray<readonly [string, boolean]> = Object.freeze([
475
+ Object.freeze(["agent/scripts/agent/_deps.sh", false] as const),
476
+ Object.freeze(["agent/scripts/agent/check-deps.sh", true] as const),
477
+ ]);
478
+ const AGENT_FILES_REQUIRED_FROM = Object.freeze([1, 0, 5] as const);
479
+
480
+ /**
481
+ * Whether a generation of `version` must carry AGENT_FILES_SINCE_1_0_5.
482
+ * Compares the numeric major.minor.patch core, so 1.0.5 and every later
483
+ * release (1.0.10, 1.1.0, 2.0.0) require them, and a prerelease of 1.0.5 is
484
+ * built from code that has them. A version that does not parse is held to
485
+ * the stricter rule.
486
+ */
487
+ export function agentFilesRequiredFor(version: string): boolean {
488
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(version);
489
+ if (!match) return true;
490
+ const core = [Number(match[1]), Number(match[2]), Number(match[3])];
491
+ for (let i = 0; i < 3; i++) {
492
+ if (core[i]! !== AGENT_FILES_REQUIRED_FROM[i]) return core[i]! > AGENT_FILES_REQUIRED_FROM[i]!;
493
+ }
494
+ return true;
495
+ }
496
+
462
497
  function validateEntryLayout(
463
498
  entries: readonly ArchiveEntry[],
464
499
  byPath: ReadonlyMap<string, ArchiveEntry>,
@@ -555,6 +590,18 @@ function validateEntryLayout(
555
590
  throw new Error(`runtime archive executable mode is invalid: ${executable}`);
556
591
  }
557
592
  }
593
+ const agentFilesRequired = agentFilesRequiredFor(descriptor.hostVersion);
594
+ for (const [file, executable] of AGENT_FILES_SINCE_1_0_5) {
595
+ const entry = byPath.get(file);
596
+ if (entry === undefined) {
597
+ if (agentFilesRequired) throw new Error(`runtime archive is missing regular file ${file}`);
598
+ continue;
599
+ }
600
+ if (entry.type !== "0") throw new Error(`runtime archive is missing regular file ${file}`);
601
+ if (executable && entry.mode !== 0o755) {
602
+ throw new Error(`runtime archive executable mode is invalid: ${file}`);
603
+ }
604
+ }
558
605
  return {
559
606
  ...platformCapabilities,
560
607
  runtimeCapabilityVersion,
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
  }