@crvouga/homelab 0.26.1 → 0.27.1

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.
@@ -144,6 +144,13 @@ are preserved by the hub's backups. Set them once, as the fleet account:
144
144
  alerts to 85% used to match the worker warning on disks up to 1706 GiB;
145
145
  on larger disks use the 256 GiB free warning floor from the worker policy. Do not add a
146
146
  notification destination until one you are allowed to use exists.
147
+ - **T3 restart counts.** The pinned Beszel agent reads
148
+ a fixed set of metrics and has no input for custom ones, so the restarts
149
+ of T3 per 24 hours are not shown next to CPU, memory and pressure there.
150
+ `homelab check` shows them for each worker (`t3Restarts24h`, and `health:
151
+ degraded` above what `worker:t3-stability` allows), and the check fails
152
+ on the worker. The exact count in the hub is tracked in [#528](https://github.com/crvouga/homelab/issues/528)
153
+ and depends on [Beszel custom metrics](https://github.com/henrygd/beszel/issues/2562).
147
154
  - **Service alerts are not promised.** Alerting on a failed systemd service has
148
155
  not been verified against the pinned release; the agent watches only the
149
156
  services in `SERVICE_PATTERNS`, and none of them is relied on for alerting.
@@ -70,20 +70,8 @@
70
70
  - name: Inspect existing service ownership
71
71
  ansible.builtin.service_facts:
72
72
  tasks:
73
- - name: Inspect the retired coding-agent launcher link
74
- ansible.builtin.stat:
75
- path: '{{ development_home }}/.local/share/personal/fleet/agent-commands'
76
- follow: false
77
- register: retired_agent_commands
78
-
79
- - name: Remove the fleet-owned coding-agent launcher link
80
- ansible.builtin.file:
81
- path: '{{ development_home }}/.local/share/personal/fleet/agent-commands'
82
- state: absent
83
- when:
84
- - retired_agent_commands.stat.islnk | default(false)
85
- - retired_agent_commands.stat.lnk_target == 'current/agents/bin'
86
-
73
+ - name: Retire the fleet-owned coding-agent launcher
74
+ ansible.builtin.import_tasks: tasks/retire-agent-launchers.yml
87
75
  - name: Install the pinned packages
88
76
  ansible.builtin.import_tasks: tasks/packages.yml
89
77
  - name: Configure Docker
@@ -1,5 +1,5 @@
1
1
  ---
2
- - name: Enable recovery for an already verified T3 desktop app
2
+ - name: Enable recovery for an already verified worker T3 service
3
3
  hosts: localhost
4
4
  connection: local
5
5
  become: true
@@ -30,6 +30,8 @@
30
30
  - libxtst6
31
31
  - xdg-utils
32
32
  tasks:
33
+ - name: Require the former upstream server to be retired
34
+ ansible.builtin.import_tasks: tasks/check-legacy-t3.yml
33
35
  - name: Create the desktop application scope policy directory
34
36
  ansible.builtin.file:
35
37
  path: /etc/systemd/user/app-com.t3tools.T3Code-.scope.d
@@ -266,19 +268,6 @@
266
268
  ansible.builtin.file:
267
269
  path: '{{ development_home }}/.config/systemd/user/t3code-headless.service'
268
270
  state: absent
269
- # One T3 process per worker: the desktop app. The former headless server
270
- # (`t3 service install`) is retired; absent on machines that never had it.
271
- - name: Retire the former headless T3 server
272
- become: true
273
- become_user: '{{ development_user }}'
274
- environment:
275
- XDG_RUNTIME_DIR: '/run/user/{{ development_uid }}'
276
- ansible.builtin.systemd_service:
277
- scope: user
278
- name: t3code.service
279
- state: stopped
280
- enabled: false
281
- failed_when: false
282
271
  # Starting needs the auto-login graphical session, which a machine has only
283
272
  # after its first reboot; the running state is measured after this play.
284
273
  - name: Reconcile the desktop listener with the recovery timer
@@ -18,6 +18,8 @@
18
18
  vars_files:
19
19
  - policy.json
20
20
  tasks:
21
+ - name: Require the former upstream server to be retired
22
+ ansible.builtin.import_tasks: tasks/check-legacy-t3.yml
21
23
  - name: Require the pinned server from the worker's toolchain
22
24
  ansible.builtin.stat:
23
25
  path: '{{ t3_server_path }}'
@@ -5,12 +5,8 @@
5
5
  # minute by personal-worker-recovery.timer (managed by converge,
6
6
  # tasks/recovery.yml), from the stable copy the role installs beside
7
7
  # t3-idle.py.
8
- # - The former upstream server unit (t3code.service) is stopped and
9
- # disabled: one T3 per worker.
10
- # - Desktop only. No graphical session: T3_NO_GRAPHICAL_SESSION; after three
11
- # checks in a row the display manager is restarted so auto-login starts
12
- # one, three times at most until a session is seen again. A headless
13
- # worker has no session to wait for.
8
+ # - Report a conflicting server or a missing desktop session without
9
+ # operating either the foreign service or the display manager.
14
10
  # - Stopped or failed: reset its start limit and start it.
15
11
  # - Running but its local API has not answered for three checks in a row:
16
12
  # restart it, since a hung server serves no turns. The first failed check
@@ -32,8 +28,6 @@ fi
32
28
  url=http://127.0.0.1:3773/.well-known/t3/environment
33
29
  runtime="${XDG_RUNTIME_DIR:?}"
34
30
  failures="$runtime/personal-t3-health-failures"
35
- no_session="$runtime/personal-t3-no-session"
36
- display_restarts="$runtime/personal-t3-display-restarts"
37
31
  pending="$runtime/personal-t3-restart-pending"
38
32
  handoff="$runtime/personal-t3-desktop-handoff"
39
33
  restarted="$runtime/personal-t3-restarted-for"
@@ -109,34 +103,16 @@ count() {
109
103
 
110
104
  if systemctl --user is-active --quiet t3code.service ||
111
105
  systemctl --user is-enabled --quiet t3code.service; then
112
- echo "Retiring the former headless T3 server."
113
- if ! systemctl --user disable --now t3code.service; then
114
- echo "T3_LEGACY_SERVER_RUNNING"
115
- exit 1
116
- fi
106
+ echo "T3_LEGACY_SERVER_RUNNING: retire the former upstream unit after its turns finish."
107
+ exit 1
117
108
  fi
118
109
 
119
110
  if [ -z "$headless" ] && ! systemctl --user is-active --quiet graphical-session.target; then
120
111
  rm -f "$failures"
121
- if [ "${1:-}" = --apply ]; then
122
- echo "T3_NO_GRAPHICAL_SESSION"
123
- exit 0
124
- fi
125
- seen=$(count "$no_session")
126
- echo "T3_NO_GRAPHICAL_SESSION ($seen/$limit)."
127
- if [ "$seen" -ge "$limit" ]; then
128
- rm -f "$no_session"
129
- restarts=$(count "$display_restarts")
130
- if [ "$restarts" -le "$limit" ]; then
131
- echo "Restarting the display manager so auto-login starts a session ($restarts/$limit)."
132
- sudo -n systemctl restart display-manager.service
133
- else
134
- echo "The display manager was restarted $limit times; a person must log in."
135
- fi
136
- fi
112
+ echo "T3_NO_GRAPHICAL_SESSION"
113
+ [ "${1:-}" = --apply ] && exit 0
137
114
  exit 1
138
115
  fi
139
- rm -f "$no_session" "$display_restarts"
140
116
 
141
117
  if [ -z "$headless" ]; then
142
118
  owner=$(python3 -I -B "$here/t3-listener.py") || exit 1
@@ -166,8 +142,9 @@ if [ -z "$headless" ]; then
166
142
  ;;
167
143
  exposed) record_pending ;;
168
144
  app-com.t3tools.T3Code-*.scope)
169
- if [ "$(cat "$handoff" 2>/dev/null)" != "$owner" ]; then
170
- printf '%s\n' "$owner" > "$handoff" || exit 1
145
+ if [ "${1:-}" != --apply ]; then
146
+ echo "T3_DESKTOP_UNMANAGED: converge to adopt the desktop after its turns finish."
147
+ exit 1
171
148
  fi
172
149
  if [ "$force" != --force ] && ! python3 -I -B "$here/t3-idle.py" --state "${T3CODE_HOME:-$HOME/.t3}/userdata/statev2.sqlite"; then
173
150
  record_pending
@@ -177,15 +154,11 @@ if [ -z "$headless" ]; then
177
154
  # Remeasure after the idle probe. An interrupted handoff resumes from
178
155
  # the listener that actually exists on the next invocation.
179
156
  [ "$(python3 -I -B "$here/t3-listener.py")" = "$owner" ] || exit 1
180
- echo "T3_HANDOFF: stopping the idle desktop scope."
157
+ printf '%s\n' "$owner" > "$handoff" || exit 1
158
+ echo "T3_HANDOFF: stopping the desktop scope for explicit adoption."
181
159
  record_pending
182
- if [ "${1:-}" = --apply ]; then
183
- systemctl --user stop "$owner" || exit 1
184
- else
185
- systemctl --user stop --no-block "$owner" || exit 1
186
- fi
187
- # The application may spend its full stop timeout flushing state.
188
- # Leave the stop job in systemd and resume on the next observation.
160
+ systemctl --user stop "$owner" || exit 1
161
+ # Confirm the port is free before starting the managed service.
189
162
  [ "$(python3 -I -B "$here/t3-listener.py")" = free ] || exit 0
190
163
  state=$(systemctl --user show "$owner" -p ActiveState --value)
191
164
  case "$state" in active | activating | deactivating) exit 0 ;; esac
@@ -0,0 +1,17 @@
1
+ ---
2
+ - name: Inspect the former upstream T3 server
3
+ become: true
4
+ become_user: '{{ development_user }}'
5
+ environment:
6
+ XDG_RUNTIME_DIR: '/run/user/{{ development_uid }}'
7
+ ansible.builtin.command:
8
+ argv: [systemctl, --user, '{{ item }}', --quiet, t3code.service]
9
+ loop: [is-active, is-enabled]
10
+ register: legacy_t3
11
+ changed_when: false
12
+ check_mode: false
13
+ failed_when: legacy_t3.rc not in [0, 1, 3, 4]
14
+ - name: Preserve the former server and its active turns
15
+ ansible.builtin.assert:
16
+ that: legacy_t3.results | selectattr('rc', 'equalto', 0) | list | length == 0
17
+ fail_msg: T3_LEGACY_SERVER_RUNNING. After its turns finish, stop and disable the former upstream t3code.service and rerun converge.
@@ -51,7 +51,7 @@
51
51
  name: personal-t3-boot-readiness.service
52
52
  daemon_reload: true
53
53
  enabled: true
54
- - name: Declare bounded recovery of the worker T3 desktop app
54
+ - name: Declare bounded recovery of the managed worker T3 service
55
55
  ansible.builtin.copy:
56
56
  dest: '{{ development_home }}/.config/systemd/user/personal-worker-recovery.service'
57
57
  owner: '{{ development_user }}'
@@ -59,7 +59,7 @@
59
59
  content: |
60
60
  # Managed by personal converge: ansible/ubuntu/t3-health.sh
61
61
  [Unit]
62
- Description=Keep the worker T3 desktop app running and responsive
62
+ Description=Keep the managed worker T3 service running and responsive
63
63
  [Service]
64
64
  Type=oneshot
65
65
  Environment=T3_RENDERER_HIGH_MIB={{ resourceSafety.rendererHighMiB }} T3_RENDERER_MAX_MIB={{ resourceSafety.rendererMaxMiB }}
@@ -76,7 +76,7 @@
76
76
  mode: '0600'
77
77
  content: |
78
78
  [Unit]
79
- Description=Check the worker T3 desktop app every minute
79
+ Description=Check the managed worker T3 service every minute
80
80
  [Timer]
81
81
  OnBootSec=1min
82
82
  OnUnitActiveSec=1min
@@ -0,0 +1,14 @@
1
+ ---
2
+ - name: Inspect the retired coding-agent launcher link
3
+ ansible.builtin.stat:
4
+ path: '{{ development_home }}/.local/share/personal/fleet/agent-commands'
5
+ follow: false
6
+ register: retired_agent_commands
7
+
8
+ - name: Remove the fleet-owned coding-agent launcher link
9
+ ansible.builtin.file:
10
+ path: '{{ development_home }}/.local/share/personal/fleet/agent-commands'
11
+ state: absent
12
+ when:
13
+ - retired_agent_commands.stat.islnk | default(false)
14
+ - retired_agent_commands.stat.lnk_target == 'current/agents/bin'
@@ -25,7 +25,7 @@ export function miseDataDir(
25
25
 
26
26
  function persistWindowsPath(bin: string, shims: string): void {
27
27
  const script =
28
- "$paths = @($env:WORKSPACE_TOOL_SHIMS, $env:WORKSPACE_TOOL_BIN); $old = [Environment]::GetEnvironmentVariable('Path', 'User'); $new = (($paths + ($old -split ';') | Where-Object { $_ } | Select-Object -Unique) -join ';'); [Environment]::SetEnvironmentVariable('Path', $new, 'User')";
28
+ "$paths = @($env:WORKSPACE_TOOL_BIN, $env:WORKSPACE_TOOL_SHIMS); $old = [Environment]::GetEnvironmentVariable('Path', 'User'); $new = (($paths + ($old -split ';') | Where-Object { $_ } | Select-Object -Unique) -join ';'); [Environment]::SetEnvironmentVariable('Path', $new, 'User')";
29
29
  const result = spawnSync(
30
30
  'powershell.exe',
31
31
  ['-NoProfile', '-Command', script],
@@ -50,20 +50,9 @@ export function configurePosixShellPath(
50
50
  home = homedir(),
51
51
  zdotdir = process.env['ZDOTDIR'] || home
52
52
  ): void {
53
- // Earlier releases put a worker's agent launchers before the shims; what
54
- // they wrote is removed wherever it stands.
55
- const agents = join(
56
- home,
57
- '.local',
58
- 'share',
59
- 'personal',
60
- 'fleet',
61
- 'agent-commands'
62
- );
63
53
  const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
64
- const paths = quote(`${shims}:${bin}`);
65
- const legacy = `# homelab toolchain\nexport PATH=${paths}:"$PATH"`;
66
- const block = `# homelab toolchain\ncase ":$PATH:" in\n *${quote(`:${shims}:${bin}:`)}*) ;;\n *) export PATH=${paths}:"$PATH" ;;\nesac`;
54
+ const paths = quote(`${bin}:${shims}`);
55
+ const block = `# homelab toolchain\ncase ":$PATH:" in\n *${quote(`:${bin}:${shims}:`)}*) ;;\n *) export PATH=${paths}:"$PATH" ;;\nesac`;
67
56
  const targets = new Set([
68
57
  join(home, '.profile'),
69
58
  ...['.bash_profile', '.bash_login']
@@ -73,41 +62,27 @@ export function configurePosixShellPath(
73
62
  join(zdotdir, '.zshenv'),
74
63
  join(zdotdir, '.zshrc'),
75
64
  ]);
76
- // Version managers and vendor installers (nvm, a native Claude installer's
77
- // ~/.local/bin) prepend their own directories later in these files; the
78
- // last line puts the pinned shims back in front, so every shell and the
79
- // apps that inherit its PATH (T3) run the locked tool versions.
80
- // Guarded like the block above so nested shells do not grow PATH.
81
- const unguarded = `${TAIL_MARKER}\nexport PATH=${quote(shims)}:"$PATH"\n`;
82
- const agentsFirst = (marker: string) =>
83
- `${marker}\nif [ -d ${quote(agents)} ]; then\n case "$PATH" in\n ${quote(agents)}:*) ;;\n *) export PATH=${quote(agents)}:"$PATH" ;;\n esac\nfi\n`;
84
- const earlierHead = `${block}\n${agentsFirst(AGENTS_MARKER)}`;
85
- const shimsOnly = `${TAIL_MARKER}\ncase "$PATH" in\n ${quote(shims)}:*) ;;\n *) export PATH=${quote(shims)}:"$PATH" ;;\nesac\n`;
86
- const earlierTail = `${TAIL_MARKER}\ncase "$PATH" in\n ${quote(shims)}:*|${quote(agents)}:${quote(shims)}:*) ;;\n *) export PATH=${quote(shims)}:"$PATH" ;;\nesac\n${agentsFirst(AGENTS_TAIL_MARKER)}`;
87
- const head = block;
88
- const tail = shimsOnly;
89
65
  for (const path of targets) {
90
66
  const current = existsSync(path) ? readFileSync(path, 'utf8') : '';
91
- // What this and every earlier release wrote, wherever it stands.
92
- const body = [
93
- earlierHead,
94
- earlierTail,
95
- `${block}\n`,
96
- legacy,
97
- shimsOnly,
98
- unguarded,
99
- ].reduce((text, earlier) => text.split(earlier).join(''), current);
100
- const next = `${head}\n${body.replace(/\n*$/, '\n')}${tail}`;
67
+ const body = removeManagedPathBlocks(current);
68
+ // User/vendor PATH edits later in the file keep their precedence. Never
69
+ // force retired harness shims in front of an externally installed CLI.
70
+ const next = `${block}\n${body.replace(/\n*$/, '\n')}`;
101
71
  if (next === current) continue;
102
72
  mkdirSync(dirname(path), { recursive: true });
103
73
  writeFileSync(path, next);
104
74
  }
105
75
  }
106
76
 
107
- const TAIL_MARKER = '# pinned tool shims first (homelab, keep this last)';
108
- const AGENTS_MARKER = "# a worker's agent commands (homelab)";
109
- const AGENTS_TAIL_MARKER =
110
- "# a worker's agent commands before them (homelab, keep this last)";
77
+ /** Remove complete blocks written by this toolchain and its earlier names,
78
+ * including old launcher precedence. Leave unmarked user configuration alone.
79
+ */
80
+ function removeManagedPathBlocks(text: string): string {
81
+ return text.replace(
82
+ /^# (?:homelab toolchain|dev-fleet toolchain|crvouga\/workspace toolchain|pinned tool shims first \((?:homelab|dev-fleet|crvouga\/workspace), keep this last\)|a worker's agent commands(?: before them)? \((?:homelab|dev-fleet)(?:, keep this last)?\))\n(?:export PATH=[^\n]*\n?|case [\s\S]*?^esac\n?|if [\s\S]*?^fi\n?)/gm,
83
+ ''
84
+ );
85
+ }
111
86
 
112
87
  export function configureShellPath(): void {
113
88
  const bin = join(homedir(), '.local', 'bin');
@@ -119,8 +94,17 @@ export function configureShellPath(): void {
119
94
  configurePosixShellPath(bin, shims);
120
95
  const fishQuote = (value: string) =>
121
96
  `'${value.replaceAll('\\', '\\\\').replaceAll("'", "\\'")}'`;
97
+ const fish = join(homedir(), '.config/fish/config.fish');
98
+ if (existsSync(fish)) {
99
+ const current = readFileSync(fish, 'utf8');
100
+ const next = current.replace(
101
+ /^# (?:homelab|dev-fleet|crvouga\/workspace) toolchain\nfish_add_path --prepend [^\n]*\n?/gm,
102
+ ''
103
+ );
104
+ if (next !== current) writeFileSync(fish, next);
105
+ }
122
106
  appendOnce(
123
- join(homedir(), '.config/fish/config.fish'),
124
- `# homelab toolchain\nfish_add_path --prepend ${fishQuote(shims)} ${fishQuote(bin)}`
107
+ fish,
108
+ `# homelab toolchain\nfish_add_path --prepend ${fishQuote(bin)} ${fishQuote(shims)}`
125
109
  );
126
110
  }
@@ -483,3 +483,14 @@ cannot bind one address is held to the tailnet with `tailnetOnlyPorts`. See
483
483
  The source-owned `worker-auth.ts` timer renews the worker's existing Vault token
484
484
  and can restore the declared GitHub account from its authorized Vault service
485
485
  credential, without copying another machine's login directory.
486
+
487
+ ## Handing agent commands to their external owner
488
+
489
+ Shell setup removes historical homelab, dev-fleet and workspace PATH blocks,
490
+ places the user bin directory ahead of mise shims, and preserves later vendor
491
+ PATH additions. Coding-agent executables and credentials belong to T3 Code or
492
+ the chosen meta-harness. A removed mise pin does not install a replacement:
493
+ verify the external owner's command from home and a project before removing
494
+ the old installation. Restart login shells after migrating PATH; restart a
495
+ background app only after its active turns have drained. Run setup on the
496
+ manager and every worker to migrate their shell files.
package/docs/runbooks.md CHANGED
@@ -14,7 +14,7 @@ It reads a code by where it stands, never by the word it ends with. The CLI
14
14
  proxy documents the codes of its own commands in
15
15
  [its README](../cliproxy/README.md); the ones converge reports are here.
16
16
 
17
- There are 458 codes; 106 need a person.
17
+ There are 463 codes; 107 need a person.
18
18
 
19
19
  ## Bootstrap of a new or returning worker
20
20
 
@@ -371,14 +371,19 @@ runaway, write `1` to that agent scope’s `cgroup.kill`.
371
371
  - `T3_UPDATES_UNMANAGED`: a failure of `t3:updates`: the administrator policy of T3 on the manager does not turn its own updater off, so T3 may update itself away from the pinned release. Stage the fleet's policy once, as an administrator, with the command the remedy prints. **Needs a person.**
372
372
  - `T3_RUNNING_VERSION_UNKNOWN`: `t3:running-version` could not read the version of the running server from its local API, or the release installed on the worker. Read `worker:t3-health`, then run `homelab converge`, which reinstalls the pinned T3.
373
373
  - `T3_RUNNING_VERSION_MISMATCH`: logged by `personal-worker-recovery` on the worker: T3 was restarted once for the installed release and still reports another version. It is not restarted again for that release and the run fails (`WORKER_RECOVERY_LAST_RUN_FAILED`). Run `homelab converge`, which reinstalls the pinned T3.
374
- - `T3_LEGACY_SERVER_RUNNING`: logged by `personal-worker-recovery`: the former server unit `t3code.service` is active or enabled and could not be stopped and disabled, so the run fails before it looks at T3. On the worker read `systemctl --user status t3code.service` and disable the unit by hand: one T3 runs per worker. **Needs a person.**
375
- - `T3_NO_GRAPHICAL_SESSION`: logged by `personal-worker-recovery` on a desktop worker with a count: no graphical session is running, so the desktop app cannot run and the run fails. After three checks in a row the display manager is restarted so that auto-login starts a session, three times at most; after that the log says a person must log in at the worker.
374
+ - `T3_LEGACY_SERVER_RUNNING`: the former upstream `t3code.service` is active or enabled. Let its turns finish, then stop and disable it before running `converge`. **Needs a person.**
375
+ - `T3_NO_GRAPHICAL_SESSION`: the desktop worker cannot serve T3 until its graphical session starts. Inspect the display manager and restore auto-login. **Needs a person.**
376
+ - `T3_DESKTOP_UNMANAGED`: a standalone T3 desktop owns the listener. Run `converge` when its turns finish to adopt it.
376
377
  - `T3_RESTART_DEADLINE`: not a failure. `personal-worker-recovery` logs it when a restart of T3 has waited `t3RestartMaxDeferralHours` (`ansible/ubuntu/policy.json`) and is applied although agent turns run: they end. `worker:t3-deadline-restarts` counts these of the last 24 hours as a warning. Nothing is left to repair: send the threads whose turn ended their next message.
377
378
  - `WIP_GUARD_HEAVY`: a warning of `worker:wip-guard`: a run of the work-in-progress guard in the last 24 hours took longer than `resourceSafety.wipGuard.slowRunSeconds` or used more than `peakWarnMiB` (`ansible/ubuntu/policy.json`). Each run ends with a JSON `run` line in `journalctl --user -u personal-worker-wip-guard.service`. The cost is a worktree with a large tree of files Git does not ignore: ignore its build output or remove the worktree.
378
379
  - `T3_BOOT_SERVING_LATE`: a failure of `worker:t3-health`: T3 answers now, but its first successful loopback probe was later than `t3Service.bootServingSeconds` (`ansible/ubuntu/policy.json`) after this boot. A worker that lost power is given that long to serve on loopback with no one at the machine. Read the journal of the T3 unit and of `personal-worker-recovery` for what delayed the start.
379
380
  - `T3_HANG_SNAPSHOT`: not a failure. `personal-worker-recovery` logs it on the first failed check of the T3 local API with the directory it wrote under `~/.local/state/personal/t3-hangs` (the newest ten are kept): each thread of T3 with the kernel call it waits in (`wchan`), the pressure, the busiest processes and the journal of the unit. Read it before the third failed check restarts T3 and destroys the evidence. `worker:t3-health` names the newest one after a restart.
380
381
  - `T3_RESTART_BACKOFF`: not a failure. `personal-worker-recovery` logs it when T3 is unresponsive again soon after the watchdog restarted it: each restart for unresponsiveness within the hour makes the next one wait twice as long (`t3Service.restartBackoffBaseSeconds`, at most `restartBackoffMaxSeconds` in `ansible/ubuntu/policy.json`), so a persistent fault does not restart T3 every few minutes. Find the cause in the snapshots (`T3_HANG_SNAPSHOT`).
381
382
  - `T3_RESTARTS_FREQUENT`: a failure of `worker:t3-stability`: the watchdog restarted T3 for being unresponsive more than `t3Stability.maxRestarts24h` times in the last 24 hours. Each restart leaves a server that answers, so no other check reports it. The remedy names the newest snapshots of why T3 hung; look for agents or recovery jobs running heavy work at that time.
383
+ - `T3_LINK_TAILSCALE_DOWN`: the first explanation of a failing `t3:paired-access` whose link exists but is not reachable: Tailscale is not running on the manager, the worker is offline on the tailnet, or the worker does not answer over SSH although the tailnet lists it online. Run `homelab tailnet`, then bring Tailscale or the worker back.
384
+ - `T3_LINK_T3_RESTARTING`: the worker's T3 is starting or was restarted in the last three minutes, by the watchdog or a sync, and the manager's link has not reconnected. Check again in a few minutes; a worker that keeps doing this fails `worker:t3-stability`.
385
+ - `T3_LINK_T3_NOT_ANSWERING`: the worker answers over SSH but its T3 does not answer its local API. See `worker:t3-health`, `worker:t3-stability` and the hang snapshots on the worker.
386
+ - `T3_LINK_RELAY_DOWN`: T3 answers on the worker but the manager's link does not reach it. Check `t3:private-route` and the link in T3 Connections on the manager.
382
387
  - `T3_API_SLOW`: a failure of `worker:t3-stability`: more than `t3Stability.slowProbeFraction` of the watchdog's probes of the T3 local API in the last 24 hours took longer than `t3Stability.slowProbeMs`. T3 answers but the worker is overloaded or T3 stalls; check `worker:pressure-events` and the load of the worker.
383
388
  - `AGENT_OOM_KILLS`: a warning of `worker:agent-oom`: the kernel killed processes inside agent scopes in the last 24 hours although the worker as a whole had memory left; the summary names the programs (never their arguments). Agent scopes and shell tool scopes are slowed by reclaim at `memory.high` before they are killed at `memory.max`. Run fewer builds at once (`homelab-heavy` queues them), lower their parallelism (`TURBO_CONCURRENCY`, `gradle --max-workers`) or move the work to a larger worker.
384
389
  - `T3_IDLE_UNKNOWN`: not a failure of its own. The idle check of `personal-worker-recovery` could not read the runs T3 records in its state database, and what it cannot read counts as busy: a pending restart keeps waiting (`T3_RESTART_PENDING`) until its deadline. Read `worker:t3-health` when it repeats.
@@ -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
@@ -355,6 +355,19 @@ API to answer within that limit. The optional desktop VM run also checks
355
355
  this limit and verifies RDP control while the login keyring is locked.
356
356
  Tunnel registration after a power cut requires separate verification.
357
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.
370
+
358
371
  A package run cut off by a power loss is finished by the next sync: the
359
372
  baseline waits for the APT lock, runs `dpkg --configure -a` once (bounded to
360
373
  ten minutes) and audits again; only a database still inconsistent stops with
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crvouga/homelab",
3
- "version": "0.26.1",
3
+ "version": "0.27.1",
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": "debd78cddc6e71eff3b3d6eecf5b86187687d603",
76
+ "gitHead": "14c34c8ca19a7151da17ad834da001074df8951c",
77
77
  "gitCommittedAt": "2026-12-03"
78
78
  }
@@ -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)}`,