@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.
@@ -378,6 +378,34 @@ export interface TaskEnvironmentProvisioned<TResult, TTeardownResult = void> {
378
378
  * stopped machine, whose disk holds the task's work — rather than creating
379
379
  * it. A failed start stops such an environment; it never destroys it. */
380
380
  reused?: boolean;
381
+ /** F6: the task had an environment before, it is gone (a terminated
382
+ * machine and its disk), and this provision created a fresh one. Work
383
+ * that lived only on the old one is lost; the start says so. */
384
+ replacedLostEnvironment?: boolean;
385
+ /** The proof behind replacedLostEnvironment, until the user is told. */
386
+ /** One per lost environment not yet told, oldest first (review #4ndq0w). */
387
+ lossNotices?: EnvironmentLossNotice[];
388
+ }
389
+
390
+ /**
391
+ * A lost environment the user has not yet been told about (F6, reviews
392
+ * #tgxadc, #2cp6r4). The Station delivers a task's notices one at a time,
393
+ * oldest first: markAttempted (persisted, never undone) before the first
394
+ * publish, the same id and text on every retry, and acknowledge only once the
395
+ * cloud has the note. The next notice is attempted only after that.
396
+ */
397
+ export interface EnvironmentLossNotice {
398
+ readonly id: string;
399
+ /** Handed to a publisher before: resend exactly this. */
400
+ readonly attempted: boolean;
401
+ /** How many lost environments this notice speaks for: 1, or more for a
402
+ * summary folded from an overflowing queue (review #d0p42f). */
403
+ readonly lostEnvironments?: number;
404
+ /** Before publishing: mark the notice attempted (persisted; from then on it
405
+ * is immutable) and return how many lost environments it carries, or
406
+ * null when it is already gone. */
407
+ markAttempted(): number | null;
408
+ acknowledge(): void;
381
409
  }
382
410
 
383
411
  export interface TaskEnvironmentProvider<
@@ -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.6",
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>",
@@ -38,41 +38,48 @@ UAI_TTYD_BIND="${UAI_TTYD_BIND:-127.0.0.1}"
38
38
  UAI_LOG_DIR="${UAI_LOG_DIR:-$UAI_DATA_DIR/logs}"
39
39
  mkdir -p "$UAI_LOG_DIR"
40
40
 
41
- # Optional dependencies — fail fast with a structured error if missing.
42
- # docker is only a dependency of the docker runtime mode: the Apple runtime
43
- # path must work on a Docker-free Mac (ADR-106), and its own CLI is validated
44
- # by validate_task_runtime_selection instead.
45
- agent_required_bins="sqlite3 jq git"
46
- if [ "${UAI_TASK_RUNTIME:-docker}" != "apple-container" ]; then
47
- agent_required_bins="$agent_required_bins docker"
48
- fi
49
- # Collect EVERY missing tool before failing: reporting them one at a time
50
- # cost one full fix-and-Resume round trip per binary on a fresh Amazon
51
- # Linux box (sqlite3, then jq — live 2026-08-21). Bash 3.2: plain string
52
- # accumulation, no arrays.
53
- missing_bins=""
54
- for bin in $agent_required_bins; do
55
- if ! command -v "$bin" >/dev/null 2>&1; then
56
- missing_bins="$missing_bins $bin"
57
- fi
58
- done
41
+ # Required dependencies — fail fast with a structured error if missing. The
42
+ # list, and how it follows the runtime choice, live in _deps.sh, which
43
+ # check-deps.sh shares to report the same gaps on the host page.
44
+ # The directory holding the real file behind $1, following file symlinks
45
+ # (bash 3.2: macOS has no `readlink -f`, so loop on plain `readlink`).
46
+ _uai_real_dir() {
47
+ local path="$1" dir link hops=0
48
+ while [ -L "$path" ]; do
49
+ hops=$((hops + 1))
50
+ if [ "$hops" -gt 40 ]; then
51
+ printf 'too many levels of symbolic links: %s\n' "$1" >&2
52
+ return 1
53
+ fi
54
+ dir=$(cd -P "$(dirname "$path")" && pwd) || return 1
55
+ link=$(readlink "$path") || return 1
56
+ case "$link" in
57
+ /*) path=$link ;;
58
+ *) path="$dir/$link" ;;
59
+ esac
60
+ done
61
+ cd -P "$(dirname "$path")" && pwd
62
+ }
63
+ # _deps.sh sits beside the real _common.sh, which may be reached through a
64
+ # symlink (review #5r0tze).
65
+ _uai_agent_dir=$(_uai_real_dir "${BASH_SOURCE[0]}") || {
66
+ printf '{"ok":false,"error":{"code":"BAD_ARGS","message":"cannot locate the agent scripts beside %s"}}\n' "${BASH_SOURCE[0]}" >&2
67
+ exit 2
68
+ }
69
+ # shellcheck source=_deps.sh
70
+ . "$_uai_agent_dir/_deps.sh"
71
+ missing_bins=$(uai_missing_required_bins)
59
72
  if [ -n "$missing_bins" ]; then
60
- missing_bins="${missing_bins# }"
61
73
  printf '{"ok":false,"error":{"code":"MISSING_DEPENDENCY","message":"missing on PATH: %s — install with your package manager (dnf/apt/brew), then Resume"}}\n' "$missing_bins" >&2
62
74
  exit 127
63
75
  fi
64
76
 
65
-
66
- # The docker BINARY existing does not make `docker compose` work: the v2
67
- # compose plugin ships separately, and a bare-engine install (Amazon Linux
68
- # 2023's docker package) answers `docker compose` with the top-level help
69
- # text — the operator saw exactly that as their task error (live
70
- # 2026-08-21). Called LAZILY by the task scripts right before their first
71
- # compose use, never at source time: argument validation must precede any
72
- # docker invocation (the task-down/task-up tests enforce that ordering).
77
+ # Called LAZILY by the task scripts right before their first compose use,
78
+ # never at source time: argument validation must precede any docker
79
+ # invocation (the task-down/task-up tests enforce that ordering). A no-op on
80
+ # the Apple runtime (_deps.sh).
73
81
  uai_require_compose_plugin() {
74
- [ "${UAI_TASK_RUNTIME:-docker}" = "apple-container" ] && return 0
75
- if ! docker compose version >/dev/null 2>&1; then
82
+ if uai_compose_plugin_missing; then
76
83
  printf '{"ok":false,"error":{"code":"MISSING_DEPENDENCY","message":"missing on PATH: docker-compose-plugin — install the Docker Compose v2 plugin, then Resume"}}\n' >&2
77
84
  exit 127
78
85
  fi
@@ -0,0 +1,47 @@
1
+ # shellcheck shell=bash
2
+ # uai agent — the binaries the task scripts need, in one place.
3
+ #
4
+ # Sourced by _common.sh, which refuses to run a task script without them,
5
+ # and by check-deps.sh, which only reports them (the Station's
6
+ # `agentDependencies` capability). Side-effect free: no `set`, no output,
7
+ # no environment requirements. Bash 3.2 (CLAUDE.md).
8
+ #
9
+ # The runtime choice is the one the Station publishes to every agent
10
+ # script (lib/container-runtime.ts): UAI_TASK_RUNTIME=apple-container means
11
+ # the Apple runtime, whose own CLI validate_task_runtime_selection checks;
12
+ # anything else is Docker, which needs the docker CLI and the Compose v2
13
+ # plugin. The Apple runtime path must work on a Docker-free Mac (ADR-106).
14
+
15
+ agent_required_bins="sqlite3 jq git"
16
+ if [ "${UAI_TASK_RUNTIME:-docker}" != "apple-container" ]; then
17
+ agent_required_bins="$agent_required_bins docker"
18
+ fi
19
+
20
+ # Prints every missing required binary, space-separated; nothing when none.
21
+ # Collects them all: reporting them one at a time cost one full
22
+ # fix-and-Resume round trip per binary on a fresh Amazon Linux box
23
+ # (sqlite3, then jq — live 2026-08-21).
24
+ uai_missing_required_bins() {
25
+ local bin missing=""
26
+ for bin in $agent_required_bins; do
27
+ if ! command -v "$bin" >/dev/null 2>&1; then
28
+ missing="$missing $bin"
29
+ fi
30
+ done
31
+ printf '%s' "${missing# }"
32
+ }
33
+
34
+ # Succeeds when the Docker runtime applies and `docker compose` does not
35
+ # run. The docker BINARY existing does not make `docker compose` work: the
36
+ # v2 plugin ships separately, and a bare-engine install (Amazon Linux 2023's
37
+ # docker package) answers `docker compose` with the top-level help text
38
+ # (live 2026-08-21). `docker compose version` never dials the daemon.
39
+ uai_compose_plugin_missing() {
40
+ if [ "${UAI_TASK_RUNTIME:-docker}" = "apple-container" ]; then
41
+ return 1
42
+ fi
43
+ if docker compose version >/dev/null 2>&1; then
44
+ return 1
45
+ fi
46
+ return 0
47
+ }
@@ -0,0 +1,59 @@
1
+ #!/usr/bin/env bash
2
+ # uai agent — report the task scripts' missing dependencies.
3
+ #
4
+ # Usage: check-deps.sh
5
+ #
6
+ # stdout: {"ok":true,"data":{"missing":["sqlite3","docker-compose-plugin"]}}
7
+ #
8
+ # Reports, never refuses: exits 0 whenever the check ran, whatever is
9
+ # missing. The Station runs it at boot and on a timer and advertises the
10
+ # result as its `agentDependencies` capability; the task scripts keep their
11
+ # own refusal (_common.sh). Needs no database and no jq (jq may be one of the
12
+ # missing). Follows the same runtime choice as the task scripts (_deps.sh).
13
+ # Bash 3.2.
14
+
15
+ set -euo pipefail
16
+
17
+ # The directory holding the real file behind $1, following file symlinks
18
+ # (bash 3.2: macOS has no `readlink -f`, so loop on plain `readlink`).
19
+ _uai_real_dir() {
20
+ local path="$1" dir link hops=0
21
+ while [ -L "$path" ]; do
22
+ hops=$((hops + 1))
23
+ if [ "$hops" -gt 40 ]; then
24
+ printf 'too many levels of symbolic links: %s\n' "$1" >&2
25
+ return 1
26
+ fi
27
+ dir=$(cd -P "$(dirname "$path")" && pwd) || return 1
28
+ link=$(readlink "$path") || return 1
29
+ case "$link" in
30
+ /*) path=$link ;;
31
+ *) path="$dir/$link" ;;
32
+ esac
33
+ done
34
+ cd -P "$(dirname "$path")" && pwd
35
+ }
36
+ # _deps.sh sits beside the real script, which may be reached through a
37
+ # symlink (review #5r0tze).
38
+ SCRIPT_DIR=$(_uai_real_dir "${BASH_SOURCE[0]}")
39
+ # shellcheck source=_deps.sh
40
+ . "$SCRIPT_DIR/_deps.sh"
41
+
42
+ missing=$(uai_missing_required_bins)
43
+ # Whether the plugin is installed is unknowable without the docker CLI, so
44
+ # it is reported only once docker itself is on PATH.
45
+ case " $missing " in
46
+ *" docker "*) ;;
47
+ *)
48
+ if uai_compose_plugin_missing; then
49
+ missing="${missing:+$missing }docker-compose-plugin"
50
+ fi
51
+ ;;
52
+ esac
53
+
54
+ # Every name comes from the fixed lists above: no JSON escaping needed.
55
+ json=""
56
+ for name in $missing; do
57
+ json="$json${json:+,}\"$name\""
58
+ done
59
+ printf '{"ok":true,"data":{"missing":[%s]}}\n' "$json"
package/src/cli.ts CHANGED
@@ -646,7 +646,7 @@ async function boundedResponseJson(
646
646
 
647
647
  // --- aws setup (ADR-125 BYO-AWS: mint the host's scoped AWS identity) --------
648
648
 
649
- /** Mirrors scripts/machine-ami/byo-aws-quickcreate.yaml — keep in sync. */
649
+ /** Mirrors host-agent/scripts/machine-ami/byo-aws-quickcreate.yaml — keep in sync. */
650
650
  const AWS_MACHINE_POLICY = {
651
651
  Version: "2012-10-17",
652
652
  Statement: [
@@ -53,6 +53,49 @@ export class EventOutbox {
53
53
  private sentUpTo = 0;
54
54
  /** Entries dropped by overflow since the last drain — for one loud log. */
55
55
  private droppedSinceDrain = 0;
56
+ /** Highest seq the cloud has acknowledged. */
57
+ private ackedUpTo = 0;
58
+ /** Seqs dropped before transmission, as merged [from, to] ranges (drops
59
+ * are oldest-first runs, so this stays small). A later cumulative ack
60
+ * never makes a dropped entry delivered (review #mta79m). */
61
+ private droppedRanges: Array<[number, number]> = [];
62
+ /** Callers waiting to learn whether one entry reached the cloud. */
63
+ private ackWaiters = new Map<number, Array<(delivered: boolean) => void>>();
64
+
65
+ /**
66
+ * Whether the entry `seq` reached the cloud: true once a cumulative ack
67
+ * covers it, false if it is dropped (oversized, or overflow) first. Pending
68
+ * while neither has happened, e.g. across a disconnect; a process exit
69
+ * settles nothing, which callers treat as not delivered.
70
+ */
71
+ whenAcked(seq: number): Promise<boolean> {
72
+ if (this.wasDropped(seq)) return Promise.resolve(false);
73
+ if (seq <= this.ackedUpTo) return Promise.resolve(true);
74
+ if (!this.entries.some((entry) => entry.seq === seq)) return Promise.resolve(false);
75
+ return new Promise((resolve) => {
76
+ const waiting = this.ackWaiters.get(seq) ?? [];
77
+ waiting.push(resolve);
78
+ this.ackWaiters.set(seq, waiting);
79
+ });
80
+ }
81
+
82
+ private wasDropped(seq: number): boolean {
83
+ return this.droppedRanges.some(([from, to]) => seq >= from && seq <= to);
84
+ }
85
+
86
+ private noteDropped(seq: number): void {
87
+ const last = this.droppedRanges[this.droppedRanges.length - 1];
88
+ if (last && seq === last[1] + 1) last[1] = seq;
89
+ else this.droppedRanges.push([seq, seq]);
90
+ this.settle(seq, false);
91
+ }
92
+
93
+ private settle(seq: number, delivered: boolean): void {
94
+ const waiting = this.ackWaiters.get(seq);
95
+ if (!waiting) return;
96
+ this.ackWaiters.delete(seq);
97
+ for (const resolve of waiting) resolve(delivered);
98
+ }
56
99
 
57
100
  /** Serialize + append. Returns the entry's seq. */
58
101
  enqueue(event: HostEvent): number {
@@ -61,6 +104,7 @@ export class EventOutbox {
61
104
  const bytes = Buffer.byteLength(raw, "utf8");
62
105
  if (bytes > MAX_EVENT_FRAME_BYTES) {
63
106
  this.droppedSinceDrain += 1;
107
+ this.noteDropped(seq);
64
108
  return seq;
65
109
  }
66
110
  this.entries.push({ seq, raw, bytes });
@@ -72,6 +116,7 @@ export class EventOutbox {
72
116
  const dropped = this.entries.shift();
73
117
  if (!dropped) break;
74
118
  this.totalBytes -= dropped.bytes;
119
+ this.noteDropped(dropped.seq);
75
120
  // Only a NEVER-SENT entry is a real loss; an unacked-but-sent one most
76
121
  // likely landed and just lost its ack.
77
122
  if (dropped.seq > this.sentUpTo) this.droppedSinceDrain += 1;
@@ -87,8 +132,12 @@ export class EventOutbox {
87
132
  this.totalBytes -= entry.bytes;
88
133
  i += 1;
89
134
  }
90
- if (i > 0) this.entries.splice(0, i);
135
+ if (i > 0) {
136
+ for (const entry of this.entries.slice(0, i)) this.settle(entry.seq, true);
137
+ this.entries.splice(0, i);
138
+ }
91
139
  if (seq > this.sentUpTo) this.sentUpTo = seq;
140
+ if (seq > this.ackedUpTo) this.ackedUpTo = seq;
92
141
  }
93
142
 
94
143
  /**
package/src/index.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { requestAgentDependencyRecheck } from "../lib/agent-dependencies";
1
2
  import { assertShareablePath, normalizedWorkspacePath } from "./workspace-path-policy";
2
3
  import { hasPreviewUpstream, parsePreviewUpstream, tunnelPreviewUpstream } from "./preview-upstream";
3
4
  import { readBoundedFile } from "../lib/task-environment/workspace-files";
@@ -32,6 +33,7 @@ import { cloneRepo } from "../lib/repo-clone";
32
33
  import { handleFilesOp } from "../lib/shared-files";
33
34
  import type { SharedFilesMode } from "../lib/shared-files-s3";
34
35
  import {
36
+ abandonTaskRecovery,
35
37
  getOrchestrator,
36
38
  inspectTaskRuntimeContainer,
37
39
  proveAppleTaskRuntimeContract,
@@ -240,7 +242,7 @@ export type {
240
242
  PreviewPortDeclaration,
241
243
  PreviewPortRuntime,
242
244
  } from "../lib/preview-ports";
243
- import { isEnvironmentTransportProvider } from "../lib/task-environment/types";
245
+ import { isEnvironmentTransportProvider, type EnvironmentLossNotice } from "../lib/task-environment/types";
244
246
  import { awaitSidecarReady, sidecarMode } from "../lib/sidecar";
245
247
  import { guardSidecarMachine } from "../lib/sidecar-guard";
246
248
  import { projectEnvBindingCapability } from "../lib/project-env-feature";
@@ -1278,6 +1280,7 @@ async function taskUpOn(
1278
1280
  }
1279
1281
  recordHostEvent(input.task.id, "task.created");
1280
1282
  let environmentLocator: TaskEnvironmentLocator | undefined;
1283
+ let machineLossNotices: readonly EnvironmentLossNotice[] = [];
1281
1284
  // The locator of everything this start may create, recorded before any
1282
1285
  // of it exists: once set, the row must keep it.
1283
1286
  let runtimePrepared = false;
@@ -1404,6 +1407,7 @@ async function taskUpOn(
1404
1407
  recordPrepared,
1405
1408
  );
1406
1409
  environmentLocator = provisioned.handle.descriptor.locator;
1410
+ machineLossNotices = provisioned.lossNotices ?? [];
1407
1411
  // ADR-153 §4: the task's own schema observations, read from the
1408
1412
  // bases task-up recorded before its container started (a machine
1409
1413
  // captures its own). Stored once; a resume reuses them.
@@ -1514,6 +1518,13 @@ async function taskUpOn(
1514
1518
  }`,
1515
1519
  );
1516
1520
  }
1521
+ // F6: Resume found the task's machine terminated and launched a fresh
1522
+ // one from the task's branch. Say so before anyone looks for work that
1523
+ // was only on the old machine's disk.
1524
+ // One note per lost machine, oldest first, one at a time.
1525
+ if (machineLossNotices.length > 0) {
1526
+ void deliverMachineLossNotices(input.task.id, machineLossNotices);
1527
+ }
1517
1528
  // Degraded start (uai-init failed twice): the task is up, but say so
1518
1529
  // in the feed — a silent half-start reads as a broken product.
1519
1530
  if (result.value.initWarning) {
@@ -1704,6 +1715,16 @@ export const hostCommands: HostCommands = {
1704
1715
  async taskDown(ctx, input) {
1705
1716
  logCommand(ctx, "taskDown", input.taskId);
1706
1717
  const orphanGc = input.cleanup?.kind === "orphan-gc";
1718
+ // F4: deletion is terminal intent. Before queueing behind the task's
1719
+ // lifecycle slot, end what would otherwise keep running ahead of it: the
1720
+ // machine gateway tunnel's respawn loop, and the task's boot recovery
1721
+ // retries, whose barrier the slot waits on. Only for the run this
1722
+ // teardown names: a delayed teardown of an older run must leave the
1723
+ // newer one alone (the exact check repeats inside the slot).
1724
+ if (teardownNamesCurrentRun(input, orphanGc)) {
1725
+ stopMachineGatewayTunnel(input.taskId);
1726
+ abandonTaskRecovery(input.taskId);
1727
+ }
1707
1728
  // ADR-154: teardown ends its run's start (orphan GC: every start of the
1708
1729
  // task) before it queues behind it.
1709
1730
  const interrupting = activeCloudCredentials();
@@ -2493,6 +2514,119 @@ function taskEnvironmentStatusResult(status: TaskEnvironmentStatus) {
2493
2514
  };
2494
2515
  }
2495
2516
 
2517
+ /** Whether a teardown will pass its in-slot run check (taskDown below):
2518
+ * orphan GC always; otherwise exactly the current assignment's epoch, or a
2519
+ * v0 teardown of a task that has no v1 assignment. Read before the slot,
2520
+ * so only for releasing work that is safe to stop early. */
2521
+ function teardownNamesCurrentRun(input: TaskDownInput, orphanGc: boolean): boolean {
2522
+ if (orphanGc) return true;
2523
+ const runEpoch = input.task?.runEpoch;
2524
+ const state = readTaskRunEpochState(input.taskId);
2525
+ if (runEpoch === undefined) return state === null;
2526
+ return state !== null && state.highestRunEpoch === runEpoch;
2527
+ }
2528
+
2529
+ /** Resolves true only once the cloud holds the note; `noteId` lets a cloud
2530
+ * that stores notes durably keep at most one per (task, noteId). */
2531
+ type SystemNotePublisher = (taskId: string, text: string, noteId: string) => Promise<boolean>;
2532
+ let systemNotePublisher: SystemNotePublisher | null = null;
2533
+
2534
+ /** main.ts binds the outbox-acknowledged publisher. Without one (tests, other
2535
+ * entry points) a note is emitted and taken as published. */
2536
+ export function setSystemNotePublisher(publisher: SystemNotePublisher | null): void {
2537
+ systemNotePublisher = publisher;
2538
+ }
2539
+
2540
+ /** Loss notices the cloud confirmed in this process, by task and loss id:
2541
+ * if clearing one failed, the next start only retries the clearing. */
2542
+ const confirmedLossNotices = new Set<string>();
2543
+ /** The delivery under way per task. Each start's run queues behind it, so a
2544
+ * task never has two notices attempted at once (review #2cp6r4). */
2545
+ const lossNoticeDeliveries = new Map<string, Promise<void>>();
2546
+
2547
+ /**
2548
+ * F6 (reviews #tgxadc, #2cp6r4): tell the user their old machines are gone,
2549
+ * each exactly once. A task's notices go one at a time, oldest first, behind
2550
+ * any delivery already under way for the task. Each is marked attempted
2551
+ * (persisted, never undone) before its first publish and resent unchanged on
2552
+ * every retry. The next is attempted only once the current one is
2553
+ * acknowledged and cleared, so at most one notice per task is ever attempted
2554
+ * but unacknowledged. A crash, a refused publication or a lost ack stops the
2555
+ * run; the next start resumes from that same notice.
2556
+ */
2557
+ export function deliverMachineLossNotices(
2558
+ taskId: string,
2559
+ notices: readonly EnvironmentLossNotice[],
2560
+ ): Promise<void> {
2561
+ const previous = lossNoticeDeliveries.get(taskId) ?? Promise.resolve();
2562
+ const run = previous.then(async () => {
2563
+ for (const notice of notices) {
2564
+ if (!(await deliverOnce(taskId, notice))) return;
2565
+ }
2566
+ });
2567
+ const tracked = run.finally(() => {
2568
+ if (lossNoticeDeliveries.get(taskId) === tracked) lossNoticeDeliveries.delete(taskId);
2569
+ });
2570
+ lossNoticeDeliveries.set(taskId, tracked);
2571
+ return tracked;
2572
+ }
2573
+
2574
+ /** True once the notice is delivered and cleared (or already gone). */
2575
+ async function deliverOnce(taskId: string, notice: EnvironmentLossNotice): Promise<boolean> {
2576
+ const key = `${taskId}\u0000${notice.id}`;
2577
+ if (!confirmedLossNotices.has(key)) {
2578
+ // Persisted BEFORE the publish: from here on the entry is immutable, and
2579
+ // the text below is what it carries for good. A mark that cannot be
2580
+ // written sends nothing.
2581
+ let lostEnvironments: number | null;
2582
+ try {
2583
+ lostEnvironments = notice.markAttempted();
2584
+ } catch (error) {
2585
+ console.warn(`[machine] task ${taskId}: could not mark the machine-replaced note attempted; the next start sends it: ${error instanceof Error ? error.message : String(error)}`);
2586
+ return false;
2587
+ }
2588
+ // Cleared by an earlier run meanwhile.
2589
+ if (lostEnvironments === null) return true;
2590
+ const text = machineReplacedNote({ lostEnvironments });
2591
+ let published = false;
2592
+ try {
2593
+ published = systemNotePublisher
2594
+ ? await systemNotePublisher(taskId, text, `machine-loss:${notice.id}`)
2595
+ : (getOrchestrator().emitSystemNote(taskId, text), true);
2596
+ } catch (error) {
2597
+ console.warn(`[machine] task ${taskId}: posting the machine-replaced note failed: ${error instanceof Error ? error.message : String(error)}`);
2598
+ }
2599
+ if (!published) {
2600
+ console.warn(`[machine] task ${taskId}: the machine-replaced note was not confirmed; the next start resends it unchanged`);
2601
+ return false;
2602
+ }
2603
+ confirmedLossNotices.add(key);
2604
+ }
2605
+ try {
2606
+ notice.acknowledge();
2607
+ } catch (error) {
2608
+ // Still attempted on disk: the next notice must wait for this clearing.
2609
+ console.warn(`[machine] task ${taskId}: could not clear the machine-replaced notice: ${error instanceof Error ? error.message : String(error)}`);
2610
+ return false;
2611
+ }
2612
+ return true;
2613
+ }
2614
+
2615
+ /** The note for one loss, or for a summary of several (review #d0p42f). */
2616
+ export function machineReplacedNote(notice: Pick<EnvironmentLossNotice, "lostEnvironments">): string {
2617
+ const count = notice.lostEnvironments ?? 1;
2618
+ if (count <= 1) return MACHINE_REPLACED_NOTE;
2619
+ return (
2620
+ `${String(count)} of this task's machines had been terminated, so this start launched a new one and set the task up again from its branch. ` +
2621
+ "Anything on those machines that was not pushed (uncommitted or unpushed changes, local files) is gone."
2622
+ );
2623
+ }
2624
+
2625
+ /** F6: the feed note for a start that replaced a terminated machine. */
2626
+ export const MACHINE_REPLACED_NOTE =
2627
+ "This task's machine had been terminated, so this start launched a new one and set the task up again from its branch. " +
2628
+ "Anything on the old machine that was not pushed (uncommitted or unpushed changes, local files) is gone.";
2629
+
2496
2630
  function taskDownResultForInput(
2497
2631
  input: TaskDownInput,
2498
2632
  providerResult: TaskDownResult,
@@ -2821,6 +2955,9 @@ function failFromUnknown<T = never>(err: unknown): HostCommandResult<T> {
2821
2955
  };
2822
2956
  }
2823
2957
  if (AgentError.is(err)) {
2958
+ // The script's own text ("missing on PATH: sqlite3 — install …") is the
2959
+ // message the user reads; the host page catches up on the next check.
2960
+ if (err.code === "MISSING_DEPENDENCY") requestAgentDependencyRecheck();
2824
2961
  return {
2825
2962
  ok: false,
2826
2963
  code: mapAgentError(err.code),