@crvouga/homelab 0.23.14 → 0.24.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.
Files changed (175) hide show
  1. package/.mise/locks/npm-vercel/{68.0.0 → 68.2.0}/aube-lock.yaml +73 -297
  2. package/.mise/locks/npm-vercel/{68.0.0 → 68.2.0}/package.json +1 -1
  3. package/.mise/locks/npm-wrangler/{4.169.0 → 4.170.0}/aube-lock.yaml +42 -42
  4. package/.mise/locks/npm-wrangler/{4.169.0 → 4.170.0}/package.json +1 -1
  5. package/README.md +54 -76
  6. package/ansible/ubuntu/agent-tool.py +106 -1
  7. package/ansible/ubuntu/heavy.py +142 -0
  8. package/ansible/ubuntu/idle-reboot.py +125 -0
  9. package/ansible/ubuntu/policy.json +51 -3
  10. package/ansible/ubuntu/t3-desktop.yml +7 -0
  11. package/ansible/ubuntu/t3-hang-snapshot.sh +75 -0
  12. package/ansible/ubuntu/t3-headless.yml +7 -0
  13. package/ansible/ubuntu/t3-health.sh +71 -3
  14. package/ansible/ubuntu/t3-policy.yml +14 -5
  15. package/ansible/ubuntu/tasks/packages.yml +2 -0
  16. package/ansible/ubuntu/tasks/recovery.yml +5 -1
  17. package/ansible/ubuntu/tasks/resources.yml +25 -2
  18. package/ansible/ubuntu/tasks/unattended-upgrades.yml +24 -6
  19. package/ansible/ubuntu/tasks/updates.yml +59 -0
  20. package/bootstrap/doctor.ts +0 -4
  21. package/bootstrap/project-action.sh +4 -5
  22. package/bootstrap/shell-path.ts +17 -19
  23. package/cliproxy/README.md +5 -6
  24. package/cliproxy/config.template.yaml +1 -15
  25. package/cliproxy/docs/health-workflow.example.yml +6 -6
  26. package/cliproxy/docs/model-health.md +8 -8
  27. package/cliproxy/scripts/accounts.py +3 -4
  28. package/cliproxy/scripts/fleet_sync.py +2 -13
  29. package/cliproxy/scripts/ops +3 -21
  30. package/docs/authentication.md +21 -26
  31. package/docs/convergence.md +28 -32
  32. package/docs/declared.md +30 -31
  33. package/docs/github.md +0 -9
  34. package/docs/machine-setup.md +16 -17
  35. package/docs/manager-recovery.md +0 -2
  36. package/docs/operations.md +12 -11
  37. package/docs/releasing.md +18 -21
  38. package/docs/runbooks.md +22 -78
  39. package/docs/support-matrix.md +1 -1
  40. package/docs/ubuntu-sync.md +71 -65
  41. package/docs/worker-contract.md +112 -15
  42. package/examples/fleet.json +0 -1
  43. package/llms.txt +0 -2
  44. package/mise.lock +206 -780
  45. package/mise.toml +12 -27
  46. package/package.json +5 -6
  47. package/schema/check-ids.json +41 -482
  48. package/schema/fleet.schema.json +6 -57
  49. package/schema/roster.schema.json +0 -2
  50. package/src/agent-session-limit.ts +2 -7
  51. package/src/auth-checks.ts +1 -3
  52. package/src/check-owners.ts +0 -13
  53. package/src/check-registry.ts +13 -72
  54. package/src/cli/agent-guide.ts +3 -16
  55. package/src/cli/command-index.ts +0 -12
  56. package/src/cli/fleet-sync-manager.ts +4 -146
  57. package/src/cli/fleet-sync-output.ts +1 -4
  58. package/src/cli/fleet-sync-plan.ts +1 -24
  59. package/src/cli/fleet-sync-remote.ts +2 -1
  60. package/src/cli/fleet-sync-vault.ts +1 -2
  61. package/src/cli/fleet-sync.ts +8 -44
  62. package/src/cli/fleet.ts +1 -2
  63. package/src/cli/program.ts +3 -14
  64. package/src/cli/register-fleet.ts +1 -55
  65. package/src/cli/registry.ts +1 -43
  66. package/src/config.ts +0 -2
  67. package/src/definition.ts +8 -83
  68. package/src/fleet-config.ts +1 -1
  69. package/src/ide/definition.ts +2 -29
  70. package/src/ide/super.ts +4 -35
  71. package/src/ide/t3.ts +9 -38
  72. package/src/manager-sync.ts +1 -1
  73. package/src/node-converge-linux.ts +4 -47
  74. package/src/node-converge-shared.ts +1 -22
  75. package/src/{agents/toolchain.ts → pinned-path.ts} +0 -17
  76. package/src/platform/agent-oom-check.ts +104 -0
  77. package/src/platform/t3-policy.ts +23 -36
  78. package/src/platform/t3-service.ts +117 -0
  79. package/src/platform/wip-guard-check.ts +65 -0
  80. package/src/remote-entry.ts +2 -41
  81. package/src/repair-catalog.ts +0 -30
  82. package/src/schedule-check.ts +17 -4
  83. package/src/service-auth.ts +0 -50
  84. package/src/state/litestream.ts +1 -1
  85. package/src/t3/retire-providers.ts +79 -0
  86. package/src/t3/version.ts +1 -1
  87. package/src/transport.ts +2 -6
  88. package/src/types.ts +0 -2
  89. package/src/version-parity.ts +0 -8
  90. package/src/worker-access-checks.ts +0 -75
  91. package/src/worker-host-checks.ts +78 -1
  92. package/src/worker-policy.ts +0 -2
  93. package/src/worker-readiness.ts +2 -0
  94. package/src/worker-sizing.ts +25 -0
  95. package/.mise/locks/azure-cli/2.93.0~a837e014/pyproject.toml +0 -5
  96. package/.mise/locks/azure-cli/2.93.0~a837e014/uv.lock +0 -2841
  97. package/.mise/locks/gemini/0.71.1~84aac8e6/aube-lock.yaml +0 -124
  98. package/.mise/locks/gemini/0.71.1~84aac8e6/package.json +0 -12
  99. package/agents/antigravity-proxy.ts +0 -3
  100. package/agents/audit.md +0 -88
  101. package/agents/bin/agy +0 -10
  102. package/agents/bin/antigravity +0 -10
  103. package/agents/bin/claude +0 -10
  104. package/agents/bin/codex +0 -10
  105. package/agents/bin/grok +0 -10
  106. package/agents/bin/opencode +0 -10
  107. package/agents/claude-proxy +0 -5
  108. package/agents/claude-proxy.ts +0 -3
  109. package/agents/codex-proxy.ts +0 -3
  110. package/agents/grok-proxy.ts +0 -3
  111. package/agents/managed-proxy.ts +0 -109
  112. package/agents/opencode-proxy.ts +0 -3
  113. package/agents/registry.json +0 -209
  114. package/agents/registry.schema.json +0 -149
  115. package/agents/setup.md +0 -158
  116. package/agents/t3.json +0 -40
  117. package/ansible/agents/agents.yml +0 -135
  118. package/ansible/agents/commands.yml +0 -32
  119. package/ansible/agents/receipts.yml +0 -19
  120. package/ansible/agents/templates/antigravity.settings.json.j2 +0 -3
  121. package/ansible/agents/templates/claude.settings.json.j2 +0 -3
  122. package/ansible/agents/templates/codex.config.toml.j2 +0 -11
  123. package/ansible/agents/templates/gemini.settings.json.j2 +0 -14
  124. package/ansible/agents/templates/grok.config.toml.j2 +0 -25
  125. package/ansible/agents/templates/opencode.json.j2 +0 -24
  126. package/ansible/agents/templates/receipt.json.j2 +0 -10
  127. package/ansible/t3/provider-keys.yml +0 -24
  128. package/docs/accounts.md +0 -256
  129. package/src/accounts/checks.ts +0 -226
  130. package/src/accounts/context.ts +0 -77
  131. package/src/accounts/propagate.ts +0 -62
  132. package/src/accounts/roster.ts +0 -112
  133. package/src/accounts/selection.ts +0 -67
  134. package/src/accounts/sessions.ts +0 -354
  135. package/src/agents/account-relay.ts +0 -279
  136. package/src/agents/accounts.ts +0 -94
  137. package/src/agents/admission.ts +0 -65
  138. package/src/agents/audit.ts +0 -77
  139. package/src/agents/cli.ts +0 -13
  140. package/src/agents/command.ts +0 -257
  141. package/src/agents/commands.ts +0 -127
  142. package/src/agents/converge.ts +0 -339
  143. package/src/agents/doctor.ts +0 -107
  144. package/src/agents/errors.ts +0 -2
  145. package/src/agents/files.ts +0 -43
  146. package/src/agents/fleet-verify.ts +0 -195
  147. package/src/agents/launch.ts +0 -361
  148. package/src/agents/native-verify.ts +0 -738
  149. package/src/agents/provider-errors.ts +0 -57
  150. package/src/agents/registry.ts +0 -61
  151. package/src/agents/render.ts +0 -121
  152. package/src/agents/round-trip.ts +0 -192
  153. package/src/agents/secrets.ts +0 -48
  154. package/src/agents/verify-cache.ts +0 -164
  155. package/src/agents/verify.ts +0 -129
  156. package/src/cli/fleet-accounts.ts +0 -294
  157. package/src/cli/fleet-sync-accounts.ts +0 -62
  158. package/src/cli/node-deployment.ts +0 -34
  159. package/src/cli/node-sync.ts +0 -121
  160. package/src/cli/node-t3.ts +0 -35
  161. package/src/cli/t3/command.ts +0 -91
  162. package/src/cli/t3/register.ts +0 -56
  163. package/src/configure.ts +0 -271
  164. package/src/github/copilot.ts +0 -54
  165. package/src/t3/accounts.ts +0 -90
  166. package/src/t3/antigravity.ts +0 -93
  167. package/src/t3/desired.ts +0 -174
  168. package/src/t3/diagnostics.ts +0 -42
  169. package/src/t3/models.ts +0 -354
  170. package/src/t3/names-check.ts +0 -53
  171. package/src/t3/names.ts +0 -155
  172. package/src/t3/plan.ts +0 -106
  173. package/src/t3/provider-keys.ts +0 -49
  174. package/src/t3/providers.ts +0 -102
  175. package/src/t3/reconcile.ts +0 -133
@@ -0,0 +1,142 @@
1
+ #!/usr/bin/python3
2
+ """Run one heavy tool behind a worker-wide queue of slots.
3
+
4
+ Managed by personal converge (tasks/resources.yml): installed beside
5
+ agent-tool.py and reached as `homelab-heavy`. Several agents on one worker may
6
+ each start a build, a type check or an Ansible run at the same time; together
7
+ they drove the load average of a 32-core worker to 208. Each heavy tool
8
+ takes a slot first, and the number of slots follows the cores of the worker
9
+ (`heavy.coresPerSlot` in the Ubuntu policy). A tool that finds no slot waits in
10
+ a queue instead of failing, and says so: `HEAVY_QUEUED`, then
11
+ `HEAVY_WAITING` with how long it has waited. New heavy jobs are also held
12
+ while the CPU or I/O pressure of the worker is above `heavy.pressureThreshold`
13
+ percent, so a worker that is already struggling does not admit more. No wait
14
+ is longer than `heavy.maxWaitSeconds`: after it the tool runs
15
+ (`HEAVY_QUEUE_TIMEOUT`), because a queue that never ends is a silent hang.
16
+
17
+ A slot is a lock held by this process only, never by the tool or the daemons it
18
+ starts, so it is released when the tool ends however it ends.
19
+
20
+ Usage: homelab-heavy COMMAND [ARGUMENT ...]
21
+ """
22
+ import fcntl
23
+ import json
24
+ import os
25
+ from pathlib import Path
26
+ import shutil
27
+ import signal
28
+ import subprocess
29
+ import sys
30
+ import time
31
+
32
+
33
+ def slot_count(policy, cpus):
34
+ return max(1, cpus // max(1, policy['coresPerSlot']))
35
+
36
+
37
+ def pressure(proc, kinds=('cpu', 'io')):
38
+ """The highest 10-second `some` pressure of the given resources, in percent."""
39
+ highest = 0.0
40
+ for kind in kinds:
41
+ try:
42
+ for line in (proc / 'pressure' / kind).read_text().splitlines():
43
+ if line.startswith('some '):
44
+ fields = dict(part.split('=') for part in line.split()[1:])
45
+ highest = max(highest, float(fields['avg10']))
46
+ except (OSError, KeyError, ValueError):
47
+ pass
48
+ return highest
49
+
50
+
51
+ def take(directory, count):
52
+ """The open lock file of a free slot, or None when every slot is taken."""
53
+ directory.mkdir(parents=True, exist_ok=True)
54
+ for number in range(count):
55
+ handle = open(directory / ('slot-%d.lock' % number), 'a')
56
+ try:
57
+ fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
58
+ return handle
59
+ except OSError:
60
+ handle.close()
61
+ return None
62
+
63
+
64
+ def busy(directory, count):
65
+ """How many slots are held right now."""
66
+ held = 0
67
+ for number in range(count):
68
+ try:
69
+ with open(directory / ('slot-%d.lock' % number), 'a') as handle:
70
+ try:
71
+ fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
72
+ except OSError:
73
+ held += 1
74
+ except OSError:
75
+ pass
76
+ return held
77
+
78
+
79
+ def queue(policy, directory, proc, cpus, name, say, clock=time.monotonic, sleep=time.sleep):
80
+ """Wait for a free slot while the worker is not under pressure. Returns the
81
+ lock to hold, or None after the longest wait."""
82
+ count = slot_count(policy, cpus)
83
+ started = clock()
84
+ announced = None
85
+ while True:
86
+ waited = clock() - started
87
+ calm = pressure(proc) <= policy['pressureThreshold']
88
+ if calm:
89
+ handle = take(directory, count)
90
+ if handle:
91
+ return handle, waited
92
+ if waited >= policy['maxWaitSeconds']:
93
+ say('HEAVY_QUEUE_TIMEOUT: %s waited %d seconds for one of %d slots; running it now.'
94
+ % (name, waited, count))
95
+ return None, waited
96
+ if announced is None:
97
+ say('HEAVY_QUEUED: %s waits for one of %d slots (%d busy)%s.'
98
+ % (name, count, busy(directory, count),
99
+ '' if calm else '; the worker is under pressure'))
100
+ announced = waited
101
+ elif waited - announced >= policy['reportEverySeconds']:
102
+ say('HEAVY_WAITING: %s has waited %d seconds (%d of %d slots busy).'
103
+ % (name, waited, busy(directory, count), count))
104
+ announced = waited
105
+ sleep(1)
106
+
107
+
108
+ def main(argv):
109
+ if not argv:
110
+ sys.stderr.write('Usage: homelab-heavy COMMAND [ARGUMENT ...]\n')
111
+ return 64
112
+ policy = json.loads(Path(__file__).with_name('agent-tool-policy.json').read_text())['heavy']
113
+ cpus = len(os.sched_getaffinity(0))
114
+ runtime = Path(os.environ.get('XDG_RUNTIME_DIR') or '/tmp')
115
+ executable = shutil.which(argv[0])
116
+ if not executable:
117
+ sys.stderr.write('homelab-heavy: %s: command not found\n' % argv[0])
118
+ return 127
119
+
120
+ def say(text):
121
+ sys.stderr.write(text + '\n')
122
+ sys.stderr.flush()
123
+
124
+ handle, waited = queue(policy, runtime / 'homelab-heavy', Path('/proc'), cpus, os.path.basename(argv[0]), say)
125
+ if waited >= 1:
126
+ say('HEAVY_ADMITTED: %s waited %d seconds in the queue.' % (os.path.basename(argv[0]), waited))
127
+ # close_fds: the tool and the daemons it starts never hold the slot.
128
+ child = subprocess.Popen([executable, *argv[1:]], close_fds=True)
129
+
130
+ def forward(signum, _frame):
131
+ child.send_signal(signum)
132
+
133
+ for number in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
134
+ signal.signal(number, forward)
135
+ code = child.wait()
136
+ if handle:
137
+ handle.close()
138
+ return 128 - code if code < 0 else code
139
+
140
+
141
+ if __name__ == '__main__':
142
+ sys.exit(main(sys.argv[1:]))
@@ -0,0 +1,125 @@
1
+ #!/usr/bin/python3
2
+ """Reboot the worker to finish updates, but only while it is idle.
3
+
4
+ Managed by homelab converge: ansible/ubuntu/tasks/updates.yml installs it as
5
+ personal-fleet-idle-reboot.service, started by personal-fleet-idle-reboot.timer.
6
+ Updates install themselves (unattended-upgrades) and kernel and library
7
+ updates apply after a reboot. A worker is cattle: nobody should have to reboot
8
+ it. A reboot ends every running agent turn, so this reboots only when all of
9
+ these hold, and otherwise leaves the worker as it is until the next run:
10
+
11
+ * Ubuntu says a reboot is required (/var/run/reboot-required);
12
+ * the worker has been up for --min-uptime-minutes, so a worker that keeps
13
+ asking for a reboot is never rebooted in a loop;
14
+ * no apt or dpkg process holds the package lock, so an upgrade is not cut off;
15
+ * T3 runs no agent turn and none ended in the last --idle-minutes
16
+ (ansible/ubuntu/t3-idle.py). A worker that cannot tell counts as busy.
17
+
18
+ A worker that never ran T3 has no turn to end.
19
+
20
+ Usage: idle-reboot.py --t3-idle PATH --state DB --idle-minutes N
21
+ --min-uptime-minutes N
22
+ The remaining options name the files it reads and the command it runs, so a
23
+ scenario can use stand-ins (features/machines/worker-updates.feature).
24
+ """
25
+ import argparse
26
+ import fcntl
27
+ import json
28
+ import os
29
+ import subprocess
30
+ import sys
31
+ from datetime import datetime, timezone
32
+
33
+ REBOOT_REQUIRED = '/var/run/reboot-required'
34
+ UPTIME = '/proc/uptime'
35
+ DPKG_LOCK = '/var/lib/dpkg/lock-frontend'
36
+
37
+
38
+ def say(message):
39
+ print(message, flush=True)
40
+
41
+
42
+ def uptime_minutes(path):
43
+ with open(path) as handle:
44
+ return float(handle.read().split()[0]) / 60
45
+
46
+
47
+ def package_manager_busy(path):
48
+ """True while something holds the dpkg lock, or when it cannot be tried."""
49
+ try:
50
+ descriptor = os.open(path, os.O_RDWR | os.O_CREAT, 0o640)
51
+ except OSError:
52
+ return True
53
+ try:
54
+ fcntl.lockf(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
55
+ except OSError:
56
+ return True
57
+ finally:
58
+ os.close(descriptor)
59
+ return False
60
+
61
+
62
+ def agent_turns(arguments):
63
+ """None when the worker is idle, otherwise why it is not."""
64
+ if not os.path.exists(arguments.state):
65
+ return None
66
+ base = [sys.executable, '-I', '-B', arguments.t3_idle, '--state', arguments.state]
67
+ try:
68
+ verdict = subprocess.run(base, capture_output=True, timeout=60).returncode
69
+ except (OSError, subprocess.SubprocessError):
70
+ return 'T3 could not be asked whether an agent turn runs'
71
+ if verdict == 1:
72
+ return 'an agent turn is running'
73
+ if verdict != 0:
74
+ return 'T3 could not say whether an agent turn runs'
75
+ try:
76
+ reply = subprocess.run(base + ['--activity'], capture_output=True, timeout=60, text=True)
77
+ last = json.loads(reply.stdout.strip().splitlines()[-1])['lastActivity']
78
+ except (OSError, subprocess.SubprocessError, ValueError, KeyError, IndexError):
79
+ return 'the last agent turn could not be read'
80
+ if last is None:
81
+ return None
82
+ try:
83
+ when = datetime.fromisoformat(str(last).replace('Z', '+00:00'))
84
+ except ValueError:
85
+ return 'the last agent turn has an unreadable time'
86
+ if when.tzinfo is None:
87
+ when = when.replace(tzinfo=timezone.utc)
88
+ quiet = (datetime.now(timezone.utc) - when).total_seconds() / 60
89
+ if quiet < arguments.idle_minutes:
90
+ return f'an agent turn was active {int(quiet)} minutes ago'
91
+ return None
92
+
93
+
94
+ def main():
95
+ parser = argparse.ArgumentParser()
96
+ parser.add_argument('--t3-idle', required=True)
97
+ parser.add_argument('--state', required=True)
98
+ parser.add_argument('--idle-minutes', type=float, required=True)
99
+ parser.add_argument('--min-uptime-minutes', type=float, required=True)
100
+ parser.add_argument('--reboot-required', default=REBOOT_REQUIRED)
101
+ parser.add_argument('--uptime', default=UPTIME)
102
+ parser.add_argument('--dpkg-lock', default=DPKG_LOCK)
103
+ parser.add_argument('--reboot-command', nargs='+', default=['/usr/bin/systemctl', 'reboot'])
104
+ arguments = parser.parse_args()
105
+
106
+ if not os.path.exists(arguments.reboot_required):
107
+ say('No reboot is pending.')
108
+ return 0
109
+ up = uptime_minutes(arguments.uptime)
110
+ if up < arguments.min_uptime_minutes:
111
+ say(f'Reboot pending; up {int(up)} minutes, waiting for {int(arguments.min_uptime_minutes)}.')
112
+ return 0
113
+ if package_manager_busy(arguments.dpkg_lock):
114
+ say('Reboot pending; the package manager is busy.')
115
+ return 0
116
+ reason = agent_turns(arguments)
117
+ if reason:
118
+ say(f'Reboot pending; waiting: {reason}.')
119
+ return 0
120
+ say('Reboot pending and the worker is idle: rebooting.')
121
+ return subprocess.run(arguments.reboot_command).returncode
122
+
123
+
124
+ if __name__ == '__main__':
125
+ sys.exit(main())
@@ -25,7 +25,7 @@
25
25
  "build-essential": "12.10ubuntu1",
26
26
  "ca-certificates": "20261130ubuntu0.24.04.1",
27
27
  "curl": "8.5.0-2ubuntu10.16",
28
- "git": "1:2.43.0-1ubuntu7.4",
28
+ "git": "1:2.43.0-1ubuntu7.5",
29
29
  "python3": "3.12.3-0ubuntu2.1",
30
30
  "unzip": "6.0-28ubuntu4.1",
31
31
  "xz-utils": "5.6.1+really5.4.5-1ubuntu0.4",
@@ -66,7 +66,7 @@
66
66
  }
67
67
  }
68
68
  ],
69
- "snapshot": "20261201T000000Z",
69
+ "snapshot": "20261201T190000Z",
70
70
  "packages": {
71
71
  "sudo": "1.9.17p2-1ubuntu3.2",
72
72
  "openssh-server": "1:10.2p1-2ubuntu3.8",
@@ -77,7 +77,7 @@
77
77
  "build-essential": "12.12ubuntu2.26.04.2",
78
78
  "ca-certificates": "20261130ubuntu0.26.04.1",
79
79
  "curl": "8.18.0-1ubuntu2.8",
80
- "git": "1:2.53.0-1ubuntu1.1",
80
+ "git": "1:2.53.0-1ubuntu1.2",
81
81
  "python3": "3.14.3-0ubuntu2",
82
82
  "unzip": "6.0-29ubuntu1",
83
83
  "xz-utils": "5.8.3-1ubuntu0.1",
@@ -94,6 +94,20 @@
94
94
  "aptLockTimeoutSeconds": 120,
95
95
  "minimumFreeInodes": 10000,
96
96
  "t3RestartMaxDeferralHours": 24,
97
+ "t3Service": {
98
+ "stopTimeoutSeconds": 20,
99
+ "watchdogTimeoutSeconds": 180,
100
+ "restartBackoffBaseSeconds": 120,
101
+ "restartBackoffMaxSeconds": 1800,
102
+ "watchdogLogLines": 4000,
103
+ "hangSnapshotsKept": 10
104
+ },
105
+ "t3Stability": {
106
+ "maxRestarts24h": 3,
107
+ "slowProbeMs": 1000,
108
+ "slowProbeFraction": 0.05,
109
+ "minProbes": 60
110
+ },
97
111
  "alwaysOnServices": ["ssh", "tailscaled", "docker", "beszel-agent"],
98
112
  "powerLossRecovery": {
99
113
  "settings": [
@@ -193,6 +207,7 @@
193
207
  "rendererMaxMiB": 8192,
194
208
  "userMemoryMax": "90%",
195
209
  "agentMemoryMax": "30%",
210
+ "agentMemoryHigh": "22%",
196
211
  "agentSwapMax": "2G",
197
212
  "zram": {
198
213
  "memoryDivisor": 4,
@@ -280,9 +295,32 @@
280
295
  "memoryMaxMiB": 1024,
281
296
  "tasks": 64,
282
297
  "budgetSeconds": 240,
298
+ "slowRunSeconds": 300,
299
+ "peakWarnMiB": 512,
283
300
  "randomizedDelaySeconds": 120
284
301
  },
302
+ "agentCpu": {
303
+ "reservedCpus": 2,
304
+ "scopePercentOfCores": 50,
305
+ "minScopeCpus": 2,
306
+ "toolPercentOfCores": 25
307
+ },
308
+ "heavyTools": {
309
+ "coresPerSlot": 8,
310
+ "pressureThreshold": 60,
311
+ "maxWaitSeconds": 900,
312
+ "reportEverySeconds": 30,
313
+ "names": [
314
+ "gradle",
315
+ "turbo",
316
+ "tsc",
317
+ "biome",
318
+ "bun test",
319
+ "ansible-playbook"
320
+ ]
321
+ },
285
322
  "agentTool": {
323
+ "highPercent": 80,
286
324
  "memoryMiB": 4096,
287
325
  "minimumMemoryMiB": 256,
288
326
  "reserveMiB": 2048,
@@ -295,6 +333,16 @@
295
333
  "failOffsetSeconds": 30
296
334
  },
297
335
  "rebootPendingFailDays": 14,
336
+ "updates": {
337
+ "origins": ["security", "updates"],
338
+ "esm": true,
339
+ "pendingFailDays": 3,
340
+ "idleReboot": {
341
+ "idleMinutes": 30,
342
+ "minUptimeMinutes": 60,
343
+ "intervalMinutes": 15
344
+ }
345
+ },
298
346
  "exposure": {
299
347
  "tailnetInterface": "tailscale0",
300
348
  "tailscalePort": 41641,
@@ -214,6 +214,13 @@
214
214
  # XWayland works on every GNOME worker, so use it everywhere.
215
215
  ExecStart="{{ t3_desktop_dir }}/t3code" --ozone-platform=x11
216
216
  KillMode=mixed
217
+ # A server that hangs does not stop on SIGTERM: do not wait the 90 s
218
+ # default before it is killed. Agent scopes (t3code-*.scope) are
219
+ # transient scopes of app-t3code-agents.slice, outside this unit's
220
+ # cgroup, so stopping the unit does not touch them.
221
+ TimeoutStopSec={{ t3Service.stopTimeoutSeconds }}
222
+ TimeoutAbortSec={{ t3Service.stopTimeoutSeconds }}
223
+ SendSIGKILL=yes
217
224
  Restart=always
218
225
  RestartSec=5
219
226
  CPUWeight=1000
@@ -0,0 +1,75 @@
1
+ #!/bin/sh
2
+ # Leave a record of why T3 does not answer, before anything restarts it.
3
+ # Run by t3-health.sh on the first failed probe: a restart destroys the hung
4
+ # process, its blocked system call and the load around it, which is all that
5
+ # says what hung.
6
+ #
7
+ # Usage: t3-hang-snapshot.sh UNIT DIRECTORY [KEEP]
8
+ #
9
+ # Writes DIRECTORY/<timestamp>/ with one small file per question and prints
10
+ # its path. At most KEEP snapshots are kept (10). Every command is bounded in
11
+ # time and output so the snapshot is cheap on a machine that is already
12
+ # overloaded, and no step may fail the script: a partial record is better than
13
+ # none.
14
+ set -u
15
+ unit=${1:?unit}
16
+ base=${2:?directory}
17
+ keep=${3:-10}
18
+ limit=65536
19
+ dir="$base/$(date -u +%Y%m%dT%H%M%SZ)"
20
+ mkdir -p "$dir" || exit 1
21
+ chmod 700 "$base" "$dir" 2>/dev/null
22
+
23
+ # bounded NAME COMMAND...: the output of the command, at most 64 KiB, in NAME.
24
+ bounded() {
25
+ name=$1
26
+ shift
27
+ timeout 3 "$@" 2>&1 | head -c "$limit" > "$dir/$name"
28
+ }
29
+
30
+ pid=$(systemctl --user show "$unit" --property=MainPID --value 2>/dev/null)
31
+ case "$pid" in '' | *[!0-9]*) pid=0 ;; esac
32
+ {
33
+ echo "unit $unit"
34
+ echo "main_pid $pid"
35
+ echo "active $(systemctl --user show "$unit" --property=ActiveState,SubState --value 2>/dev/null | tr '\n' ' ')"
36
+ echo "loadavg $(cat /proc/loadavg 2>/dev/null)"
37
+ echo "nproc $(nproc 2>/dev/null)"
38
+ } > "$dir/summary"
39
+
40
+ if [ "$pid" -gt 0 ] && [ -d "/proc/$pid" ]; then
41
+ # Each thread: what it waits for (wchan) and its state. The kernel stack is
42
+ # readable only to root, and then it is the answer to a hang below
43
+ # JavaScript.
44
+ for task in /proc/"$pid"/task/*; do
45
+ tid=${task##*/}
46
+ printf '%s %s wchan=%s stack=%s\n' "$tid" \
47
+ "$(cat "$task/comm" 2>/dev/null)" \
48
+ "$(cat "$task/wchan" 2>/dev/null)" \
49
+ "$(head -n 3 "$task/stack" 2>/dev/null | tr '\n' ';')"
50
+ done 2>/dev/null | head -c "$limit" > "$dir/threads"
51
+ bounded status head -n 40 "/proc/$pid/status"
52
+ bounded sockets sh -c "ss -xpn 2>/dev/null | grep -F 'pid=$pid,' | head -n 200"
53
+ bounded descriptors sh -c "ls -l /proc/$pid/fd 2>/dev/null | awk '{print \$NF}' | sed 's/[0-9][0-9]*//g' | sort | uniq -c | sort -rn | head -n 20"
54
+ fi
55
+
56
+ bounded pressure sh -c 'for f in cpu io memory; do echo "$f: $(cat /proc/pressure/$f 2>/dev/null | tr "\n" " ")"; done'
57
+ bounded cgroups systemd-cgtop --batch --iterations=1 --depth=3 --order=cpu -n 1
58
+ bounded cpu ps -eo pid,ppid,pcpu,pmem,rss,stat,wchan:20,cgroup:60,args --sort=-pcpu --width 200
59
+ bounded memory ps -eo pid,ppid,pcpu,pmem,rss,stat,wchan:20,cgroup:60,args --sort=-rss --width 200
60
+ for list in cpu memory; do
61
+ head -n 16 "$dir/$list" > "$dir/$list.tmp" 2>/dev/null && mv "$dir/$list.tmp" "$dir/$list"
62
+ done
63
+ # The display stack, the recovery jobs and builds that may have starved or
64
+ # blocked T3.
65
+ bounded related sh -c "pgrep -af 'gnome-shell|Xwayland|Xorg|systemd-journald|wip-guard|disk-gc|ansible|gradle|tsc|turbo|biome|bun test' | cut -c1-200 | head -n 60"
66
+ bounded unit-journal journalctl --user --unit="$unit" --lines=200 --no-pager --output=short-iso
67
+ for log in "${T3CODE_HOME:-$HOME/.t3}"/userdata/logs/*trace*.ndjson; do
68
+ [ -f "$log" ] && tail -n 200 "$log" | tail -c "$limit" > "$dir/server-trace" && break
69
+ done
70
+
71
+ # Keep the newest KEEP snapshots.
72
+ ls -1d "$base"/*/ 2>/dev/null | sort -r | tail -n +"$((keep + 1))" | while read -r old; do
73
+ rm -rf -- "$old"
74
+ done
75
+ echo "$dir"
@@ -83,6 +83,13 @@
83
83
  Environment=NODE_OPTIONS=--max-old-space-size={{ sizing.agentBuildMiB }}
84
84
  ExecStart="{{ t3_server_path }}" serve --mode web --host 127.0.0.1 --port 3773 --base-dir %h/.t3 --no-browser
85
85
  KillMode=mixed
86
+ # A server that hangs does not stop on SIGTERM: do not wait the 90 s
87
+ # default before it is killed. Agent scopes (t3code-*.scope) are
88
+ # transient scopes of app-t3code-agents.slice, outside this unit's
89
+ # cgroup, so stopping the unit does not touch them.
90
+ TimeoutStopSec={{ t3Service.stopTimeoutSeconds }}
91
+ TimeoutAbortSec={{ t3Service.stopTimeoutSeconds }}
92
+ SendSIGKILL=yes
86
93
  Restart=always
87
94
  RestartSec=5
88
95
  CPUWeight=1000
@@ -13,7 +13,11 @@
13
13
  # worker has no session to wait for.
14
14
  # - Stopped or failed: reset its start limit and start it.
15
15
  # - Running but its local API has not answered for three checks in a row:
16
- # restart it, since a hung server serves no turns.
16
+ # restart it, since a hung server serves no turns. The first failed check
17
+ # leaves a snapshot of why (t3-hang-snapshot.sh) and every decision is a
18
+ # line of the watchdog log (T3_WATCHDOG_LOG), which worker:t3-stability
19
+ # reads. A restart after a restart waits longer each time within the hour
20
+ # (T3_RESTART_BACKOFF), so a persistent fault does not loop.
17
21
  # - Running another release than the installed one, or a restart a play
18
22
  # deferred: restart it once it runs no agent turn (T3_RESTART_PENDING). A
19
23
  # busy worker is never idle, so the wait is bounded: the restart is applied
@@ -36,6 +40,14 @@ restarted="$runtime/personal-t3-restarted-for"
36
40
  installed="${T3_DESKTOP_DIR:-/opt/T3 Code (Nightly)}/.personal-fleet-version"
37
41
  here=$(dirname "$0")
38
42
  limit=3
43
+ # What the watchdog leaves behind: its decisions, and a snapshot per hang.
44
+ state="${XDG_STATE_HOME:-$HOME/.local/state}/personal"
45
+ watchdog_log="$state/t3-watchdog.ndjson"
46
+ hangs="$state/t3-hangs"
47
+ backoff_base="${T3_RESTART_BACKOFF_BASE_SECONDS:-120}"
48
+ backoff_max="${T3_RESTART_BACKOFF_MAX_SECONDS:-1800}"
49
+ log_lines="${T3_WATCHDOG_LOG_LINES:-4000}"
50
+ hangs_kept="${T3_HANG_SNAPSHOTS_KEPT:-10}"
39
51
  # Both the installed timer and the play hold this lock through handoff/start.
40
52
  exec 9>"$runtime/personal-t3-recovery.lock"
41
53
  if [ "${1:-}" = --apply ]; then
@@ -56,6 +68,39 @@ record_pending() {
56
68
  [ -s "$pending" ] || date +%s > "$pending"
57
69
  }
58
70
 
71
+ # record EVENT FIELDS: one line of the watchdog log, bounded to log_lines.
72
+ # FIELDS is JSON members that start with a comma and hold no user input.
73
+ record() {
74
+ mkdir -p "$state" 2>/dev/null || return 0
75
+ printf '{"t":%s,"event":"%s"%s}\n' "$(date +%s)" "$1" "${2:-}" >> "$watchdog_log" 2>/dev/null || return 0
76
+ if [ "$(wc -l < "$watchdog_log")" -gt "$log_lines" ]; then
77
+ tail -n "$log_lines" "$watchdog_log" > "$watchdog_log.tmp" && mv "$watchdog_log.tmp" "$watchdog_log"
78
+ fi
79
+ }
80
+
81
+ # backoff_seconds: how much longer a restart of an unresponsive T3 must wait.
82
+ # After n restarts for unresponsiveness in the last hour, the next one waits
83
+ # base * 2^n seconds after the last, at most backoff_max.
84
+ backoff_seconds() {
85
+ now=$(date +%s)
86
+ seen=$(awk -v now="$now" '/"event":"restarted"/ && /"cause":"unresponsive"/ {
87
+ match($0, /"t":[0-9]+/); t = substr($0, RSTART + 4, RLENGTH - 4) + 0
88
+ if (now - t < 3600) { n++; if (t > last) last = t }
89
+ } END { print n + 0, last + 0 }' "$watchdog_log" 2>/dev/null)
90
+ set -- $seen
91
+ n=${1:-0}
92
+ last=${2:-0}
93
+ [ "$n" -gt 0 ] || { echo 0; return; }
94
+ wait=$backoff_base
95
+ while [ "$n" -gt 1 ] && [ "$wait" -lt "$backoff_max" ]; do
96
+ wait=$((wait * 2))
97
+ n=$((n - 1))
98
+ done
99
+ [ "$wait" -le "$backoff_max" ] || wait=$backoff_max
100
+ left=$((last + wait - now))
101
+ [ "$left" -gt 0 ] && echo "$left" || echo 0
102
+ }
103
+
59
104
  count() {
60
105
  n=$(($(cat "$1" 2>/dev/null || echo 0) + 1))
61
106
  echo "$n" > "$1"
@@ -169,19 +214,40 @@ if [ -z "$headless" ] && [ -n "${T3_RENDERER_HIGH_MIB:-}" ]; then
169
214
  python3 -I -B "$here/t3-renderers.py" --main-pid "$main_pid" "$group" "$T3_RENDERER_HIGH_MIB" "$T3_RENDERER_MAX_MIB" ||
170
215
  echo "T3 renderer limits could not be applied."
171
216
  fi
217
+ probe_started=$(date +%s%N)
172
218
  if ! environment=$(curl --fail --silent --max-time 10 "$url"); then
173
219
  # Only timed observations count toward the unresponsive threshold.
174
220
  [ "${1:-}" != --apply ] || exit 0
175
221
  failed=$(count "$failures")
176
222
  echo "T3 local API did not answer ($failed/$limit)."
223
+ record probe ",\"ok\":false,\"failures\":$failed"
224
+ if [ "$failed" -eq 1 ]; then
225
+ # The evidence is gone after a restart: take it on the first failure.
226
+ rm -f "$runtime/personal-t3-last-snapshot"
227
+ snapshot=$(sh "$here/t3-hang-snapshot.sh" "$unit" "$hangs" "$hangs_kept" 2>/dev/null | tail -n 1)
228
+ [ -z "$snapshot" ] || printf '%s\n' "$snapshot" > "$runtime/personal-t3-last-snapshot"
229
+ echo "T3_HANG_SNAPSHOT: ${snapshot:-not written}."
230
+ fi
177
231
  if [ "$failed" -ge "$limit" ]; then
232
+ wait=$(backoff_seconds)
233
+ if [ "$wait" -gt 0 ]; then
234
+ echo "T3_RESTART_BACKOFF: T3 was restarted for being unresponsive recently; the next restart waits $wait more seconds."
235
+ record backoff ",\"seconds\":$wait"
236
+ exit 0
237
+ fi
178
238
  rm -f "$failures" "$pending"
179
- echo "T3 is unresponsive; restarting it."
239
+ snapshot=$(cat "$runtime/personal-t3-last-snapshot" 2>/dev/null)
240
+ echo "T3 is unresponsive; restarting it (snapshot: ${snapshot:-none})."
180
241
  systemctl --user reset-failed "$unit" 2>/dev/null
181
- exec systemctl --user restart "$unit"
242
+ began=$(date +%s)
243
+ systemctl --user restart "$unit"
244
+ status=$?
245
+ record restarted ",\"cause\":\"unresponsive\",\"failures\":$failed,\"seconds\":$(($(date +%s) - began)),\"status\":$status,\"snapshot\":\"$snapshot\""
246
+ exit "$status"
182
247
  fi
183
248
  exit 0
184
249
  fi
250
+ record probe ",\"ok\":true,\"ms\":$((($(date +%s%N) - probe_started) / 1000000))"
185
251
  rm -f "$failures"
186
252
 
187
253
  running=$(printf '%s' "$environment" | sed -n 's/.*"serverVersion" *: *"\([^"]*\)".*/\1/p')
@@ -208,7 +274,9 @@ fi
208
274
  restart() {
209
275
  echo "$1"
210
276
  systemctl --user reset-failed "$unit" 2>/dev/null
277
+ began=$(date +%s)
211
278
  systemctl --user restart "$unit" || exit 1
279
+ record restarted ",\"cause\":\"planned\",\"seconds\":$(($(date +%s) - began))"
212
280
  rm -f "$pending"
213
281
  [ "$reason" != "release $release" ] || echo "$release" > "$restarted"
214
282
  exit 0
@@ -44,14 +44,23 @@
44
44
  # the staged policy is restarted so every node offers the same providers,
45
45
  # but only while it runs no agent turn (tasks/t3-restart.yml): a busy app
46
46
  # keeps its turns and loads the policy at the first idle check.
47
- - name: Check whether the desktop app is running
47
+ # t3_unit names the unit of the worker's session: the desktop app, or on a
48
+ # headless worker t3code-headless.service (t3-headless.yml).
49
+ - name: Check whether T3 is running
48
50
  become: true
49
51
  become_user: '{{ development_user }}'
50
52
  environment:
51
53
  XDG_RUNTIME_DIR: '/run/user/{{ development_uid }}'
52
54
  ansible.builtin.command:
53
- argv: [systemctl, --user, is-active, --quiet, t3code-desktop.service]
54
- register: t3_desktop_active
55
+ argv:
56
+ [
57
+ systemctl,
58
+ --user,
59
+ is-active,
60
+ --quiet,
61
+ "{{ t3_unit | default('t3code-desktop.service') }}",
62
+ ]
63
+ register: t3_active
55
64
  changed_when: false
56
65
  check_mode: false
57
66
  failed_when: false
@@ -64,7 +73,7 @@
64
73
  changed_when: false
65
74
  check_mode: false
66
75
  failed_when: false
67
- when: t3_desktop_active.rc == 0
76
+ when: t3_active.rc == 0
68
77
  - name: Restart T3 when it is idle
69
78
  become: true
70
79
  become_user: '{{ development_user }}'
@@ -79,5 +88,5 @@
79
88
  - "{{ '--force' if t3_restart_busy | default(false) | bool else '--keep-turns' }}"
80
89
  changed_when: true
81
90
  when:
82
- - t3_desktop_active.rc == 0
91
+ - t3_active.rc == 0
83
92
  - t3_policy_loaded.stdout is not search('loaded this policy\.\s*$')
@@ -5,3 +5,5 @@
5
5
  install_pins: '{{ packages }}'
6
6
  - name: Configure unattended upgrades
7
7
  ansible.builtin.import_tasks: unattended-upgrades.yml
8
+ - name: Reboot an idle worker to finish its updates
9
+ ansible.builtin.import_tasks: updates.yml
@@ -19,6 +19,7 @@
19
19
  mode: '0755'
20
20
  loop:
21
21
  - t3-health.sh
22
+ - t3-hang-snapshot.sh
22
23
  - t3-listener.py
23
24
  - t3-idle.py
24
25
  - t3-renderers.py
@@ -36,8 +37,11 @@
36
37
  Type=oneshot
37
38
  Environment=T3_RENDERER_HIGH_MIB={{ resourceSafety.rendererHighMiB }} T3_RENDERER_MAX_MIB={{ resourceSafety.rendererMaxMiB }}
38
39
  Environment=T3_RESTART_MAX_DEFERRAL_HOURS={{ t3RestartMaxDeferralHours }}
40
+ Environment=T3_RESTART_BACKOFF_BASE_SECONDS={{ t3Service.restartBackoffBaseSeconds }} T3_RESTART_BACKOFF_MAX_SECONDS={{ t3Service.restartBackoffMaxSeconds }}
41
+ Environment=T3_WATCHDOG_LOG_LINES={{ t3Service.watchdogLogLines }} T3_HANG_SNAPSHOTS_KEPT={{ t3Service.hangSnapshotsKept }}
39
42
  ExecStart=/bin/sh /usr/local/lib/personal-fleet/t3-health.sh
40
- TimeoutStartSec=90
43
+ # Longer than a restart: the stop timeout of the T3 unit plus its start.
44
+ TimeoutStartSec={{ t3Service.watchdogTimeoutSeconds }}
41
45
  - name: Declare persistent service recovery checks
42
46
  ansible.builtin.copy:
43
47
  dest: '{{ development_home }}/.config/systemd/user/personal-worker-recovery.timer'