@crvouga/homelab 0.26.0 → 0.27.0

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.
@@ -182,20 +182,20 @@ independently. Bespoke TypeScript remains only where a native CLI or API has no
182
182
  declarative owner: T3 service lifecycle, Beszel enrollment tokens, provider
183
183
  verification and the CLIProxy singleton.
184
184
 
185
- | Policy | Workers (Ubuntu 26.04 or 24.04, stateless) | Manager (macOS, singleton) |
186
- | --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
187
- | Never sleep | systemd sleep targets masked; logind lid/idle policy; GNOME power plugin set to `nothing` | never sleeps on AC power (`pmset -c sleep 0`, `macos/manager.yml`, verified as `manager:power`); battery sleep is left to the human |
188
- | No automatic logout or lock | GNOME `lock-enabled false`, `idle-delay 0`; designated-user lingering | not managed (the human uses it) |
189
- | Always-on services | drop-ins `Restart=always`, `StartLimitIntervalSec=0` for ssh, tailscaled, docker, beszel-agent | singleton services under launchd and Docker Desktop (see the last row) |
190
- | T3 health and connection | `sync` and `status --workers` require `worker:t3-health` (local API answers), `t3:manager-endpoint` (manager HTTPS over Tailscale) and `t3:paired-access` (manager T3 link reachable) | the human's T3 desktop holds the links to every worker (`t3:paired-access`) |
191
- | Memory safety | `systemd-oomd` (swap 90%; no aggregate agent PSI kills); `user.slice` `MemoryMax=90%`; T3 reserves memory and CPU/I/O weight in its service and the desktop application scope that hosts the listener; each `t3code-*.scope` agent `MemoryMax=30%`, `OOMPolicy=continue`, `IOAccounting=yes` (the pressure guard reads its `io.stat` and `cpu.stat`); zram at priority 100 (25% of memory up to 8 GiB), with disk swap retained for overflow; the agent pressure guard sheds one agent on sustained CPU, memory or I/O pressure | not managed |
192
- | Disk safety | `personal-fleet-disk-guard` kills only the top user-cgroup writer below 3 GiB free, never deletes files; hourly (every 15 minutes with `storage.disposable`) `personal-fleet-disk-gc.timer` deletes git-ignored build output (`node_modules`, `.cache`, `dist`, ...) in checkouts idle 7d (12h under 15 GiB free) with no process inside, plus unused Docker images and build cache, never source, worktrees or volumes; journal 1G; `/tmp` 25% of RAM, aged 2d hourly, a measured write probe (`TMP_QUOTA_EXHAUSTED`), and T3 agents use disk-backed `/var/tmp` (`TMPDIR`, aged 14d); Docker log rotation | not managed |
193
- | Tailscale | pinned APT package, `tailscaled` enabled, native login required | Tailscale app, human login |
194
- | Dashboard agent | pinned native binary, hardened `beszel-agent` systemd unit as user `beszel` | not installed |
195
- | Credential renewal | user timer `personal-worker-auth` renews the node's own Vault token every 10min; `personal-worker-github` signs it in to GitHub from the stored token ([GitHub](github.md)) | the human's own Vault and GitHub sessions |
196
- | Noninteractive sudo | validated `/etc/sudoers.d/personal-fleet-USER` | only `pmset -c`, granted once by `manager-privilege.yml` (`-K`) |
197
- | T3 worker app | pinned desktop `.deb` is the only T3 process (UI plus embedded server) on a desktop worker, and the pinned server as the lingering user unit `t3code-headless.service` on a headless one (`features.session`; no session is waited for); GDM auto-login, user unit `t3code-desktop.service` bound to the graphical session with `Restart=always`; `personal-worker-recovery` runs a copy of `t3-health.sh` installed in `/usr/local/lib/personal-fleet` every minute: it stops and disables a still-running headless `t3code.service`, reports `T3_NO_GRAPHICAL_SESSION` and restarts the display manager (three times at most) when there is no session, starts a stopped app after `reset-failed`, restarts one whose local API missed three checks, and restarts one on another release than the installed one or with a deferred policy restart once it runs no agent turn; administrator policy | not a worker |
198
- | Singleton services | never; clients of the manager's services only | every singleton runs here: CLI proxy (`cliproxy`), Beszel hub (`workstation/monitoring`) |
185
+ | Policy | Workers (Ubuntu 26.04 or 24.04, stateless) | Manager (macOS, singleton) |
186
+ | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
187
+ | Never sleep | systemd sleep targets masked; logind lid/idle policy; GNOME power plugin set to `nothing` | never sleeps on AC power (`pmset -c sleep 0`, `macos/manager.yml`, verified as `manager:power`); battery sleep is left to the human |
188
+ | No automatic logout or lock | GNOME `lock-enabled false`, `idle-delay 0`; designated-user lingering | not managed (the human uses it) |
189
+ | Always-on services | drop-ins `Restart=always`, `StartLimitIntervalSec=0` for ssh, tailscaled, docker, beszel-agent | singleton services under launchd and Docker Desktop (see the last row) |
190
+ | T3 health and connection | `sync` and `status --workers` require `worker:t3-health` (local API answers), `t3:manager-endpoint` (manager HTTPS over Tailscale) and `t3:paired-access` (manager T3 link reachable) | the human's T3 desktop holds the links to every worker (`t3:paired-access`) |
191
+ | Memory safety | `systemd-oomd` (swap 90%; no aggregate agent PSI kills); `user.slice` `MemoryMax=90%`; T3 reserves memory and CPU/I/O weight in its service and the desktop application scope that hosts the listener; each `t3code-*.scope` agent `MemoryMax=30%`, `OOMPolicy=continue`, `IOAccounting=yes` (the pressure guard reads its `io.stat` and `cpu.stat`); zram at priority 100 (25% of memory up to 8 GiB), with disk swap retained for overflow; the agent pressure guard sheds one agent on sustained CPU, memory or I/O pressure | not managed |
192
+ | Disk safety | `personal-fleet-disk-guard` kills only the top user-cgroup writer below 3 GiB free, never deletes files; hourly (every 15 minutes with `storage.disposable`) `personal-fleet-disk-gc.timer` deletes git-ignored build output (`node_modules`, `.cache`, `dist`, ...) in checkouts idle 7d (12h under 15 GiB free) with no process inside, plus unused Docker images and build cache, never source, worktrees or volumes; journal 1G; `/tmp` 25% of RAM, aged 2d hourly, a measured write probe (`TMP_QUOTA_EXHAUSTED`), and T3 agents use disk-backed `/var/tmp` (`TMPDIR`, aged 14d); Docker log rotation | not managed |
193
+ | Tailscale | pinned APT package, `tailscaled` enabled, native login required | Tailscale app, human login |
194
+ | Dashboard agent | pinned native binary, hardened `beszel-agent` systemd unit as user `beszel` | not installed |
195
+ | Credential renewal | user timer `personal-worker-auth` renews the node's own Vault token every 10min; `personal-worker-github` signs it in to GitHub from the stored token ([GitHub](github.md)) | the human's own Vault and GitHub sessions |
196
+ | Noninteractive sudo | validated `/etc/sudoers.d/personal-fleet-USER` | only `pmset -c`, granted once by `manager-privilege.yml` (`-K`) |
197
+ | T3 worker app | pinned desktop `.deb` is the only T3 process (UI plus embedded server) on a desktop worker, and the pinned server as the lingering user unit `t3code-headless.service` on a headless one (`features.session`; no session is waited for); GDM auto-login, user unit `t3code-desktop.service` bound to the graphical session with `Restart=always`; `personal-worker-recovery` runs a copy of `t3-health.sh` installed in `/usr/local/lib/personal-fleet` every minute: it reports a conflicting upstream `t3code.service` or a missing desktop session, starts a stopped managed service after `reset-failed`, restarts a managed service whose local API missed three checks, and restarts one on another release than the installed one or with a deferred policy restart once it runs no agent turn; administrator policy | not a worker |
198
+ | Singleton services | never; clients of the manager's services only | every singleton runs here: CLI proxy (`cliproxy`), Beszel hub (`workstation/monitoring`) |
199
199
 
200
200
  Under sustained host memory pressure the guard selects the leaf agent scope
201
201
  using the most RAM plus swap. Under CPU pressure (80% full PSI) it selects
@@ -163,10 +163,9 @@ removes the desktop unit, installs `t3code-headless.service` from the pinned
163
163
  server archive the toolchain already holds, keeps `~/.t3` (environment
164
164
  identity, pairing, history), repoints recovery to the new unit and starts it;
165
165
  `converge --dry-run` lists what the worker loses. Back to `desktop` is the same
166
- edit and also keeps `~/.t3`. This repository changes no fleet's
167
- `fleet.json`: moving the MS-A2 workers is that consumer's change.
166
+ edit and also keeps `~/.t3`. Apply this change in the consumer project.
168
167
 
169
- Canary, before more workers follow: converge one MS-A2 worker, confirm
168
+ Canary, before more workers follow: converge one unattended worker, confirm
170
169
  `worker:t3-recovery`, `worker:t3-health`, `worker:t3-protection` and the
171
170
  resource checks pass and the manager's link reconnects; open T3's preview
172
171
  browser on a thread of that worker; and compare the restarts and slow probes
@@ -343,15 +342,31 @@ one:
343
342
  After an unclean power loss a worker reaches "T3 answers on loopback" with
344
343
  no one at the machine. `t3Service.bootServingSeconds` (`ansible/ubuntu/policy.json`,
345
344
  180 seconds from the boot) is that limit, and `worker:t3-health` fails with
346
- `T3_BOOT_SERVING_LATE` when this boot's T3 unit became active later than
347
- that. The tunnel registers once the server answers; the check measures the
345
+ `T3_BOOT_SERVING_LATE` when the first successful loopback probe exceeds that limit.
346
+ The boot-time probe keeps its first observation in the worker's runtime
347
+ directory across T3 restarts. Measurement begins on the first boot after
348
+ installation. The tunnel registers once the server answers. The check measures the
348
349
  loopback API, which is what the watchdog and the route both need. A desktop
349
350
  worker's unit stores Chromium passwords in a file under `T3CODE_HOME`
350
351
  (`--password-store=basic`), so a locked login keyring never blocks the T3
351
352
  path; the RDP credential stays in the volatile session keyring. The VM test
352
- power-cycles the guest without a clean shutdown and requires the headless
353
- server to answer within that limit, and the desktop path within the longer
354
- time a graphical auto-login takes.
353
+ power-cycles the guest without a clean shutdown and requires the loopback
354
+ API to answer within that limit. The optional desktop VM run also checks
355
+ this limit and verifies RDP control while the login keyring is locked.
356
+ Tunnel registration after a power cut requires separate verification.
357
+
358
+ The recovery timer keeps its unit name and watchdog log across upgrades.
359
+ It operates the managed T3 service. A missing desktop session still reports
360
+ `T3_NO_GRAPHICAL_SESSION`. If graphical auto-login fails, restore the
361
+ graphical session before the desktop worker can serve T3 again. The
362
+ headless worker can recover without a display or login.
363
+
364
+ A manually started desktop keeps its listener and turns until an explicit
365
+ `converge` adopts it while idle. If convergence found it busy, rerun
366
+ `converge` when its turns finish. Workers still running or enabling the former
367
+ upstream `t3code.service` must finish their turns and stop and disable that
368
+ unit before converging. Convergence removes the fleet's old coding-agent
369
+ launcher link and leaves agent credentials in place.
355
370
 
356
371
  A package run cut off by a power loss is finished by the next sync: the
357
372
  baseline waits for the APT lock, runs `dpkg --configure -a` once (bounded to
package/mise.lock CHANGED
@@ -1619,10 +1619,10 @@ backend = "npm:vercel"
1619
1619
  specifiers = ["68.5.0"]
1620
1620
 
1621
1621
  [[tools."npm:wrangler"]]
1622
- version = "4.170.0"
1623
- aube = { path = ".mise/locks/npm-wrangler/4.170.0", digest = "sha256:9746e062ee1a18e850f3d3f99e23c913fe1ec41502efb4bf4792e1fb48129458" }
1622
+ version = "4.171.0"
1623
+ aube = { path = ".mise/locks/npm-wrangler/4.171.0", digest = "sha256:fcb2d440403de048e88881e422829f885c4bed4f4a4a4c2ca7a35a2f2957df36" }
1624
1624
  backend = "npm:wrangler"
1625
- specifiers = ["4.170.0"]
1625
+ specifiers = ["4.171.0"]
1626
1626
 
1627
1627
  [[tools.opentofu]]
1628
1628
  version = "1.13.11"
package/mise.toml CHANGED
@@ -44,7 +44,7 @@ delta = "0.23.0"
44
44
  git-lfs = "3.8.1"
45
45
  docker-cli = "29.10.1"
46
46
  "npm:vercel" = "68.5.0"
47
- "npm:wrangler" = "4.170.0"
47
+ "npm:wrangler" = "4.171.0"
48
48
  railway = "5.77.1"
49
49
  vault = "2.2.2"
50
50
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crvouga/homelab",
3
- "version": "0.26.0",
3
+ "version": "0.27.0",
4
4
  "description": "Keeps a set of development machines in sync: one manager and many workers",
5
5
  "license": "MIT",
6
6
  "repository": "github:crvouga/homelab",
@@ -73,6 +73,6 @@
73
73
  "engines": {
74
74
  "node": ">=22"
75
75
  },
76
- "gitHead": "60fd0791e43ea7febf8b1ff6d2233881b8bde31f",
76
+ "gitHead": "1302be50d81e10bbf57b563a9331e600921a232d",
77
77
  "gitCommittedAt": "2026-12-03"
78
78
  }
@@ -2208,7 +2208,7 @@
2208
2208
  },
2209
2209
  {
2210
2210
  "id": "worker:t3-health",
2211
- "meaning": "T3 local API answers with its environment identity within 10 seconds, and the unit activation time is checked against the boot-serving limit.",
2211
+ "meaning": "T3 local API answers with its environment identity within 10 seconds, and any recorded first successful loopback probe falls within the boot-serving limit.",
2212
2212
  "severity": "required",
2213
2213
  "repair": {
2214
2214
  "manual": "Re-converge the worker with converge: it applies the whole worker policy at the approved revision."
@@ -514,7 +514,7 @@ export const CHECK_MEANINGS: Record<string, string> = {
514
514
  'worker:service-recovery': 'Worker services recover after failure.',
515
515
  'worker:sudo': 'Designated worker user has noninteractive sudo.',
516
516
  'worker:t3-health':
517
- 'T3 local API answers with its environment identity within 10 seconds, and the unit activation time is checked against the boot-serving limit.',
517
+ 'T3 local API answers with its environment identity within 10 seconds, and any recorded first successful loopback probe falls within the boot-serving limit.',
518
518
  'worker:convergence':
519
519
  'The worker last applied the approved revision and its last apply succeeded.',
520
520
  'worker:pressure-events':
@@ -334,9 +334,14 @@ export async function watchdogRecords(
334
334
  `${home}/${T3_WATCHDOG_LOG}`,
335
335
  ]);
336
336
  if (!logged.ok) return /No such file/.test(logged.stderr) ? [] : undefined;
337
+ return parseWatchdog(logged.stdout, now);
338
+ }
339
+
340
+ /** The records of the last 24 hours in a watchdog log's lines. */
341
+ export function parseWatchdog(log: string, now: number): WatchdogRecord[] {
337
342
  const since = now / 1000 - 86_400;
338
343
  const records: WatchdogRecord[] = [];
339
- for (const line of logged.stdout.split('\n')) {
344
+ for (const line of log.split('\n')) {
340
345
  try {
341
346
  const value = JSON.parse(line) as WatchdogRecord;
342
347
  if (typeof value.t === 'number' && value.t >= since && value.event)
@@ -348,6 +353,12 @@ export async function watchdogRecords(
348
353
  return records;
349
354
  }
350
355
 
356
+ /** How often the watchdog restarted T3 for being unresponsive in the last 24
357
+ * hours, from the lines of its log. */
358
+ export function restartsIn24Hours(log: string, now: number): number {
359
+ return unresponsiveRestarts(parseWatchdog(log, now)).length;
360
+ }
361
+
351
362
  const unresponsiveRestarts = (records: WatchdogRecord[]): WatchdogRecord[] =>
352
363
  records.filter(
353
364
  (record) => record.event === 'restarted' && record.cause === 'unresponsive'
@@ -1,5 +1,8 @@
1
1
  import { sshArgs } from './ssh';
2
2
  import { record } from './config';
3
+ import { discoverTailnet } from './tailscale';
4
+ import { T3_WATCHDOG_LOG } from './platform/t3-service';
5
+ import policy from '../ansible/ubuntu/policy.json';
3
6
  import type { Check, FleetNode, Runner } from './types';
4
7
 
5
8
  /** Correlate a live SSH-verified server identity with the native manager's authenticated link. */
@@ -15,14 +18,24 @@ export async function verifyT3Linked(
15
18
  ): Promise<Check> {
16
19
  const now = options.now ?? Date.now;
17
20
  const deadline = now() + (options.reconnectMs ?? 0);
18
- let check = await linkedOnce(node, run, now());
19
- while (check.status === 'fail' && now() < deadline) {
21
+ let once = await linkedOnce(node, run, now());
22
+ while (once.check.status === 'fail' && now() < deadline) {
20
23
  await (
21
24
  options.pause ?? (() => new Promise((done) => setTimeout(done, 10_000)))
22
25
  )();
23
- check = await linkedOnce(node, run, now());
26
+ once = await linkedOnce(node, run, now());
24
27
  }
25
- return check.status === 'fail' ? explained(node, run, check) : check;
28
+ return once.check.status === 'fail'
29
+ ? explained(node, run, once, now())
30
+ : once.check;
31
+ }
32
+
33
+ /** What `linkedOnce` measured: the check, and whether the manager's T3 holds
34
+ * a link to the environment that is not reachable. A link that does not
35
+ * exist is a missing pairing, not an unreachable worker. */
36
+ interface Linked {
37
+ check: Check;
38
+ listedUnreachable: boolean;
26
39
  }
27
40
 
28
41
  /** A worker enrolled with one T3 environment that now runs another lost
@@ -32,11 +45,14 @@ export async function verifyT3Linked(
32
45
  async function explained(
33
46
  node: FleetNode,
34
47
  run: Runner,
35
- check: Check
48
+ { check, listedUnreachable }: Linked,
49
+ now: number
36
50
  ): Promise<Check> {
37
- if (!node.t3EnvironmentId) return check;
38
- const observed = await observedIdentity(node, run).catch(() => undefined);
39
- if (!observed || observed === node.t3EnvironmentId) return check;
51
+ const observed = node.t3EnvironmentId
52
+ ? await observedIdentity(node, run).catch(() => undefined)
53
+ : undefined;
54
+ if (!(observed && observed !== node.t3EnvironmentId))
55
+ return listedUnreachable ? withCause(node, run, check, now) : check;
40
56
  return {
41
57
  ...check,
42
58
  summary: 'T3_ENVIRONMENT_IDENTITY_CHANGED',
@@ -51,7 +67,7 @@ async function linkedOnce(
51
67
  node: FleetNode,
52
68
  run: Runner,
53
69
  now: number
54
- ): Promise<Check> {
70
+ ): Promise<Linked> {
55
71
  const unavailable: Check = {
56
72
  id: 't3:paired-access',
57
73
  status: 'fail',
@@ -61,18 +77,29 @@ async function linkedOnce(
61
77
  'For first pairing, enable t3.pairOnEnrollment in fleet.json and sync, or link this exact worker in T3 Connections. Existing pairing identities are preserved; passwords and pairing tokens are never copied by Fleet.',
62
78
  },
63
79
  };
80
+ const missing = { check: unavailable, listedUnreachable: false };
64
81
  try {
65
82
  const identity =
66
83
  node.t3EnvironmentId ?? (await observedIdentity(node, run));
67
- if (!identity) return unavailable;
84
+ if (!identity) return missing;
68
85
  const result = await run(['t3', 'environment', 'list', '--json'], {
69
86
  timeoutMs: 30_000,
70
87
  });
71
88
  const links: unknown = JSON.parse(result.stdout);
72
- if (!result.ok || !Array.isArray(links)) return unavailable;
73
- return linkedEvidence(links, identity, unavailable, now);
89
+ if (!result.ok || !Array.isArray(links)) return missing;
90
+ const check = linkedEvidence(links, identity, unavailable, now);
91
+ const link = links.find(
92
+ (value) => record(value) && value['environmentId'] === identity
93
+ );
94
+ return {
95
+ check,
96
+ listedUnreachable:
97
+ check.status === 'fail' &&
98
+ record(link) &&
99
+ link['status'] !== 'reachable',
100
+ };
74
101
  } catch {
75
- return unavailable;
102
+ return missing;
76
103
  }
77
104
  }
78
105
 
@@ -121,3 +148,116 @@ export async function observedIdentity(
121
148
  ? identity['environmentId']
122
149
  : undefined;
123
150
  }
151
+
152
+ /** The restart that a worker's T3 is still recovering from: its link needs
153
+ * about this long to reconnect (`reconnectMs` of a sync that restarted it). */
154
+ const RECOVERING_MS = 180_000;
155
+
156
+ /** One session to the worker: does its T3 answer locally, what state is its
157
+ * unit in, and when did the watchdog last restart it? The unit is the
158
+ * headless one when that is enabled, else the desktop one (`t3-health.sh`).
159
+ */
160
+ const WORKER_PROBE = [
161
+ 'if curl --fail --silent --max-time 5 -o /dev/null http://127.0.0.1:3773/.well-known/t3/environment; then echo answers; else echo silent; fi',
162
+ 'state=; for u in t3code-headless.service t3code-desktop.service; do if systemctl --user is-enabled --quiet "$u" 2>/dev/null; then state=$(systemctl --user show --property=ActiveState --value "$u" 2>/dev/null); break; fi; done; printf "%s\\n" "$state"',
163
+ `tail -n ${policy.t3Service.watchdogLogLines} "$HOME/${T3_WATCHDOG_LOG}" 2>/dev/null | grep '"event":"restarted"' | tail -n 1 || true`,
164
+ ].join('; ');
165
+
166
+ /** The first cause that explains a link that is listed but not reachable,
167
+ * from the manager outwards: its own Tailscale, the worker on the tailnet,
168
+ * the worker's T3 (restarting, or not answering) and last the relay: T3
169
+ * answers on the worker but the manager's link does not reach it. Each word
170
+ * is a code a runbook entry explains; nothing but these fixed words and the
171
+ * worker's id leaves the probes.
172
+ */
173
+ async function withCause(
174
+ node: FleetNode,
175
+ run: Runner,
176
+ check: Check,
177
+ now: number
178
+ ): Promise<Check> {
179
+ const [code, action] = await cause(node, run, now);
180
+ return {
181
+ ...check,
182
+ summary: `${code}: ${CAUSES[code]} (${check.summary})`,
183
+ remedy: { action },
184
+ };
185
+ }
186
+
187
+ const CAUSES = {
188
+ T3_LINK_TAILSCALE_DOWN:
189
+ 'the manager cannot reach the worker over the tailnet, so its link to T3 cannot connect',
190
+ T3_LINK_T3_RESTARTING:
191
+ 'the worker is restarting T3 and the manager’s link has not reconnected yet',
192
+ T3_LINK_T3_NOT_ANSWERING:
193
+ 'the worker is reachable but its T3 does not answer its local API',
194
+ T3_LINK_RELAY_DOWN:
195
+ 'the worker’s T3 answers on the worker, but the manager’s link does not reach it',
196
+ } as const;
197
+
198
+ type Cause = [keyof typeof CAUSES, string];
199
+
200
+ async function cause(
201
+ node: FleetNode,
202
+ run: Runner,
203
+ now: number
204
+ ): Promise<Cause> {
205
+ return (await tailnetCause(node, run)) ?? (await workerCause(node, run, now));
206
+ }
207
+
208
+ /** Tailscale on the manager, or the worker on the tailnet. */
209
+ async function tailnetCause(
210
+ node: FleetNode,
211
+ run: Runner
212
+ ): Promise<Cause | undefined> {
213
+ const tailnet = await discoverTailnet(run);
214
+ const self = tailnet.computers.find((computer) => computer.self);
215
+ const peer = node.tailscaleId
216
+ ? tailnet.computers.find((computer) => computer.id === node.tailscaleId)
217
+ : undefined;
218
+ if (!self?.online)
219
+ return [
220
+ 'T3_LINK_TAILSCALE_DOWN',
221
+ 'Tailscale on the manager is not running or signed in. Run tailscale status on the manager, bring it up, then run check again.',
222
+ ];
223
+ if (peer && !peer.online)
224
+ return [
225
+ 'T3_LINK_TAILSCALE_DOWN',
226
+ `The worker ${node.id} is offline on the tailnet. Check that it is powered on and that tailscaled runs on it (homelab tailnet lists what Tailscale sees).`,
227
+ ];
228
+ return undefined;
229
+ }
230
+
231
+ /** What one session to the worker says about its T3. */
232
+ async function workerCause(
233
+ node: FleetNode,
234
+ run: Runner,
235
+ now: number
236
+ ): Promise<Cause> {
237
+ const probed = await run([...sshArgs(node), WORKER_PROBE], {
238
+ timeoutMs: 20_000,
239
+ });
240
+ const [answer, state, restart] = probed.stdout.split('\n');
241
+ if (!probed.ok || (answer !== 'answers' && answer !== 'silent'))
242
+ return [
243
+ 'T3_LINK_TAILSCALE_DOWN',
244
+ `The worker ${node.id} did not answer over SSH although the tailnet lists it online. Check tailscaled and sshd on it, then run check again.`,
245
+ ];
246
+ const restartedAt = Number(/"t":(\d+)/.exec(restart ?? '')?.[1]) * 1000;
247
+ const recently =
248
+ Number.isFinite(restartedAt) && now - restartedAt < RECOVERING_MS;
249
+ if (/^(activating|deactivating|reloading)$/.test(state ?? '') || recently)
250
+ return [
251
+ 'T3_LINK_T3_RESTARTING',
252
+ 'T3 was restarted a moment ago, by the watchdog or a sync. Run check again in a few minutes; if it keeps restarting, see worker:t3-stability.',
253
+ ];
254
+ if (answer === 'silent')
255
+ return [
256
+ 'T3_LINK_T3_NOT_ANSWERING',
257
+ 'T3 does not answer on the worker. See worker:t3-health and worker:t3-stability, and the hang snapshots under ~/.local/state/personal/t3-hangs on the worker.',
258
+ ];
259
+ return [
260
+ 'T3_LINK_RELAY_DOWN',
261
+ 'T3 runs and answers on the worker, so the path from the manager is at fault. Check the private route to the worker’s T3 (t3:private-route) and the link in T3 Connections on the manager.',
262
+ ];
263
+ }
@@ -1,6 +1,8 @@
1
1
  import { record } from './config';
2
2
  import type { FleetDefinition, MachineDefinition } from './definition';
3
3
  import { sshArgs } from './ssh';
4
+ import policy from '../ansible/ubuntu/policy.json';
5
+ import { T3_WATCHDOG_LOG, restartsIn24Hours } from './platform/t3-service';
4
6
  import type { Check, FleetNode, Runner } from './types';
5
7
 
6
8
  /** How long a worker has been up and what its agents are doing, as T3
@@ -11,6 +13,9 @@ export interface WorkerActivity {
11
13
  uptimeSeconds: number | null;
12
14
  runningSessions: number | null;
13
15
  lastActivityAt: string | null;
16
+ /** Restarts of T3 for being unresponsive in the last 24 hours, from the
17
+ * watchdog's log; null when the log could not be read. */
18
+ t3Restarts24h: number | null;
14
19
  }
15
20
 
16
21
  /** One worker in check: active or parked, what it does, and what it
@@ -21,6 +26,9 @@ export interface WorkerUsage extends Partial<WorkerActivity> {
21
26
  state: 'active' | 'parked';
22
27
  parkedAt?: string;
23
28
  reachable?: boolean;
29
+ /** `degraded` when the worker answers but its T3 is restarted more often
30
+ * than `t3Stability.maxRestarts24h` allows (`worker:t3-stability`). */
31
+ health?: 'reachable' | 'degraded' | 'unreachable';
24
32
  /** Seconds since the last agent activity, or since boot without any. */
25
33
  idleSeconds?: number;
26
34
  idle?: boolean;
@@ -32,21 +40,27 @@ export interface WorkerUsage extends Partial<WorkerActivity> {
32
40
  /** The installed copy converge keeps outside every revision
33
41
  * (ansible/ubuntu/tasks/recovery.yml).
34
42
  */
35
- export const ACTIVITY_PROBE =
36
- 'cut -d" " -f1 /proc/uptime; python3 -I -B /usr/local/lib/personal-fleet/t3-idle.py --state "${T3CODE_HOME:-$HOME/.t3}/userdata/statev2.sqlite" --activity';
43
+ export const ACTIVITY_PROBE = [
44
+ 'cut -d" " -f1 /proc/uptime',
45
+ 'python3 -I -B /usr/local/lib/personal-fleet/t3-idle.py --state "${T3CODE_HOME:-$HOME/.t3}/userdata/statev2.sqlite" --activity',
46
+ // The watchdog's restarts, when its log is readable (t3-health.sh).
47
+ `if [ -r "$HOME/${T3_WATCHDOG_LOG}" ]; then echo watchdog; tail -n ${policy.t3Service.watchdogLogLines} "$HOME/${T3_WATCHDOG_LOG}" | grep '"event":"restarted"'; fi`,
48
+ 'true',
49
+ ].join('; ');
37
50
 
38
51
  /** Reads a worker's uptime and agent activity over SSH; null when the
39
52
  * worker did not answer.
40
53
  */
41
54
  export async function workerActivity(
42
55
  node: FleetNode,
43
- run: Runner
56
+ run: Runner,
57
+ now: number = Date.now()
44
58
  ): Promise<WorkerActivity | null> {
45
59
  const result = await run([...sshArgs(node), ACTIVITY_PROBE], {
46
60
  timeoutMs: 20_000,
47
61
  });
48
62
  if (!result.ok && !result.stdout) return null;
49
- return parseActivity(result.stdout);
63
+ return parseActivity(result.stdout, now);
50
64
  }
51
65
 
52
66
  /** The JSON line of t3-idle.py --activity, or nothing known. */
@@ -65,8 +79,11 @@ function activityLine(line: string | undefined): Record<string, unknown> {
65
79
  /** What the probe printed: the uptime, then the one JSON line of
66
80
  * t3-idle.py --activity. Anything unreadable is unknown, never zero.
67
81
  */
68
- export function parseActivity(stdout: string): WorkerActivity {
69
- const [uptime, line] = stdout.split('\n');
82
+ export function parseActivity(
83
+ stdout: string,
84
+ now: number = Date.now()
85
+ ): WorkerActivity {
86
+ const [uptime, line, ...log] = stdout.split('\n');
70
87
  const seconds = Number(uptime);
71
88
  const known = activityLine(line);
72
89
  const running = known['running'];
@@ -84,6 +101,8 @@ export function parseActivity(stdout: string): WorkerActivity {
84
101
  typeof last === 'string' && !Number.isNaN(Date.parse(last))
85
102
  ? new Date(last).toISOString()
86
103
  : null,
104
+ t3Restarts24h:
105
+ log[0] === 'watchdog' ? restartsIn24Hours(log.join('\n'), now) : null,
87
106
  };
88
107
  }
89
108
 
@@ -164,6 +183,16 @@ export function idleCheck(
164
183
  };
165
184
  }
166
185
 
186
+ /** A worker whose T3 the watchdog restarted for being unresponsive more
187
+ * often in 24 hours than `worker:t3-stability` allows answers, but is not
188
+ * well. */
189
+ function flapping(activity: WorkerActivity): boolean {
190
+ return (
191
+ activity.t3Restarts24h !== null &&
192
+ activity.t3Restarts24h > policy.t3Stability.maxRestarts24h
193
+ );
194
+ }
195
+
167
196
  function billing(worker: MachineDefinition | undefined) {
168
197
  return worker?.billing
169
198
  ? {
@@ -205,12 +234,15 @@ export async function fleetUsage(
205
234
  ...billing(worker),
206
235
  };
207
236
  const node = nodes.find((entry) => entry.id === worker.id);
208
- const activity = node ? await workerActivity(node, run) : null;
237
+ const activity = node
238
+ ? await workerActivity(node, run, now.getTime())
239
+ : null;
209
240
  if (!activity)
210
241
  return {
211
242
  id: worker.id,
212
243
  state: 'active',
213
244
  reachable: false,
245
+ health: 'unreachable',
214
246
  ...billing(worker),
215
247
  };
216
248
  const judged = idleCheck(
@@ -224,6 +256,7 @@ export async function fleetUsage(
224
256
  id: worker.id,
225
257
  state: 'active',
226
258
  reachable: true,
259
+ health: flapping(activity) ? 'degraded' : 'reachable',
227
260
  ...activity,
228
261
  ...(judged.idleSeconds === undefined
229
262
  ? {}
@@ -268,6 +301,9 @@ export function usageText(workers: WorkerUsage[], now: Date): string {
268
301
  return ` ${worker.id}: parked for ${duration(Math.max(0, (now.getTime() - Date.parse(worker.parkedAt!)) / 1000))}`;
269
302
  if (!worker.reachable) return ` ${worker.id}: not reached`;
270
303
  const parts = [
304
+ worker.health === 'degraded'
305
+ ? `degraded: T3 restarted ${worker.t3Restarts24h} times in 24h`
306
+ : 'reachable',
271
307
  worker.uptimeSeconds == null
272
308
  ? 'uptime unknown'
273
309
  : `up ${duration(worker.uptimeSeconds)}`,