@crvouga/homelab 0.23.13 → 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 (177) 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 +58 -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 +16 -2
  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/ansible/ubuntu/wip-guard.py +141 -14
  21. package/bootstrap/doctor.ts +0 -4
  22. package/bootstrap/project-action.sh +4 -5
  23. package/bootstrap/shell-path.ts +17 -19
  24. package/cliproxy/README.md +5 -6
  25. package/cliproxy/config.template.yaml +1 -15
  26. package/cliproxy/docs/health-workflow.example.yml +6 -6
  27. package/cliproxy/docs/model-health.md +8 -8
  28. package/cliproxy/scripts/accounts.py +3 -4
  29. package/cliproxy/scripts/fleet_sync.py +2 -13
  30. package/cliproxy/scripts/ops +3 -21
  31. package/docs/authentication.md +21 -26
  32. package/docs/convergence.md +28 -32
  33. package/docs/declared.md +30 -31
  34. package/docs/durability.md +9 -0
  35. package/docs/github.md +0 -9
  36. package/docs/machine-setup.md +16 -17
  37. package/docs/manager-recovery.md +0 -2
  38. package/docs/operations.md +12 -11
  39. package/docs/releasing.md +18 -21
  40. package/docs/runbooks.md +22 -78
  41. package/docs/support-matrix.md +1 -1
  42. package/docs/ubuntu-sync.md +71 -65
  43. package/docs/worker-contract.md +112 -15
  44. package/examples/fleet.json +0 -1
  45. package/llms.txt +0 -2
  46. package/mise.lock +206 -780
  47. package/mise.toml +12 -27
  48. package/package.json +5 -6
  49. package/schema/check-ids.json +41 -482
  50. package/schema/fleet.schema.json +6 -57
  51. package/schema/roster.schema.json +0 -2
  52. package/src/agent-session-limit.ts +2 -7
  53. package/src/auth-checks.ts +1 -3
  54. package/src/check-owners.ts +0 -13
  55. package/src/check-registry.ts +13 -72
  56. package/src/cli/agent-guide.ts +3 -16
  57. package/src/cli/command-index.ts +0 -12
  58. package/src/cli/fleet-sync-manager.ts +4 -146
  59. package/src/cli/fleet-sync-output.ts +1 -4
  60. package/src/cli/fleet-sync-plan.ts +1 -24
  61. package/src/cli/fleet-sync-remote.ts +2 -1
  62. package/src/cli/fleet-sync-vault.ts +1 -2
  63. package/src/cli/fleet-sync.ts +8 -44
  64. package/src/cli/fleet.ts +1 -2
  65. package/src/cli/program.ts +3 -14
  66. package/src/cli/register-fleet.ts +1 -55
  67. package/src/cli/registry.ts +1 -43
  68. package/src/config.ts +0 -2
  69. package/src/definition.ts +8 -83
  70. package/src/fleet-config.ts +1 -1
  71. package/src/ide/definition.ts +2 -29
  72. package/src/ide/super.ts +4 -35
  73. package/src/ide/t3.ts +9 -38
  74. package/src/manager-sync.ts +1 -1
  75. package/src/node-converge-linux.ts +4 -47
  76. package/src/node-converge-shared.ts +1 -22
  77. package/src/{agents/toolchain.ts → pinned-path.ts} +0 -17
  78. package/src/platform/agent-oom-check.ts +104 -0
  79. package/src/platform/t3-policy.ts +23 -36
  80. package/src/platform/t3-service.ts +117 -0
  81. package/src/platform/wip-guard-check.ts +65 -0
  82. package/src/remote-entry.ts +2 -41
  83. package/src/repair-catalog.ts +0 -30
  84. package/src/schedule-check.ts +17 -4
  85. package/src/service-auth.ts +0 -50
  86. package/src/state/litestream.ts +1 -1
  87. package/src/t3/retire-providers.ts +79 -0
  88. package/src/t3/version.ts +1 -1
  89. package/src/transport.ts +2 -6
  90. package/src/types.ts +0 -2
  91. package/src/version-parity.ts +0 -8
  92. package/src/worker-access-checks.ts +0 -75
  93. package/src/worker-host-checks.ts +78 -1
  94. package/src/worker-policy.ts +0 -2
  95. package/src/worker-readiness.ts +2 -0
  96. package/src/worker-sizing.ts +25 -0
  97. package/.mise/locks/azure-cli/2.93.0~a837e014/pyproject.toml +0 -5
  98. package/.mise/locks/azure-cli/2.93.0~a837e014/uv.lock +0 -2841
  99. package/.mise/locks/gemini/0.71.1~84aac8e6/aube-lock.yaml +0 -124
  100. package/.mise/locks/gemini/0.71.1~84aac8e6/package.json +0 -12
  101. package/agents/antigravity-proxy.ts +0 -3
  102. package/agents/audit.md +0 -88
  103. package/agents/bin/agy +0 -10
  104. package/agents/bin/antigravity +0 -10
  105. package/agents/bin/claude +0 -10
  106. package/agents/bin/codex +0 -10
  107. package/agents/bin/grok +0 -10
  108. package/agents/bin/opencode +0 -10
  109. package/agents/claude-proxy +0 -5
  110. package/agents/claude-proxy.ts +0 -3
  111. package/agents/codex-proxy.ts +0 -3
  112. package/agents/grok-proxy.ts +0 -3
  113. package/agents/managed-proxy.ts +0 -109
  114. package/agents/opencode-proxy.ts +0 -3
  115. package/agents/registry.json +0 -209
  116. package/agents/registry.schema.json +0 -149
  117. package/agents/setup.md +0 -158
  118. package/agents/t3.json +0 -40
  119. package/ansible/agents/agents.yml +0 -135
  120. package/ansible/agents/commands.yml +0 -32
  121. package/ansible/agents/receipts.yml +0 -19
  122. package/ansible/agents/templates/antigravity.settings.json.j2 +0 -3
  123. package/ansible/agents/templates/claude.settings.json.j2 +0 -3
  124. package/ansible/agents/templates/codex.config.toml.j2 +0 -11
  125. package/ansible/agents/templates/gemini.settings.json.j2 +0 -14
  126. package/ansible/agents/templates/grok.config.toml.j2 +0 -25
  127. package/ansible/agents/templates/opencode.json.j2 +0 -24
  128. package/ansible/agents/templates/receipt.json.j2 +0 -10
  129. package/ansible/t3/provider-keys.yml +0 -24
  130. package/docs/accounts.md +0 -256
  131. package/src/accounts/checks.ts +0 -226
  132. package/src/accounts/context.ts +0 -77
  133. package/src/accounts/propagate.ts +0 -62
  134. package/src/accounts/roster.ts +0 -112
  135. package/src/accounts/selection.ts +0 -67
  136. package/src/accounts/sessions.ts +0 -354
  137. package/src/agents/account-relay.ts +0 -279
  138. package/src/agents/accounts.ts +0 -94
  139. package/src/agents/admission.ts +0 -65
  140. package/src/agents/audit.ts +0 -77
  141. package/src/agents/cli.ts +0 -13
  142. package/src/agents/command.ts +0 -257
  143. package/src/agents/commands.ts +0 -127
  144. package/src/agents/converge.ts +0 -339
  145. package/src/agents/doctor.ts +0 -107
  146. package/src/agents/errors.ts +0 -2
  147. package/src/agents/files.ts +0 -43
  148. package/src/agents/fleet-verify.ts +0 -195
  149. package/src/agents/launch.ts +0 -361
  150. package/src/agents/native-verify.ts +0 -738
  151. package/src/agents/provider-errors.ts +0 -57
  152. package/src/agents/registry.ts +0 -61
  153. package/src/agents/render.ts +0 -121
  154. package/src/agents/round-trip.ts +0 -192
  155. package/src/agents/secrets.ts +0 -48
  156. package/src/agents/verify-cache.ts +0 -164
  157. package/src/agents/verify.ts +0 -129
  158. package/src/cli/fleet-accounts.ts +0 -294
  159. package/src/cli/fleet-sync-accounts.ts +0 -62
  160. package/src/cli/node-deployment.ts +0 -34
  161. package/src/cli/node-sync.ts +0 -121
  162. package/src/cli/node-t3.ts +0 -35
  163. package/src/cli/t3/command.ts +0 -91
  164. package/src/cli/t3/register.ts +0 -56
  165. package/src/configure.ts +0 -271
  166. package/src/github/copilot.ts +0 -54
  167. package/src/t3/accounts.ts +0 -90
  168. package/src/t3/antigravity.ts +0 -93
  169. package/src/t3/desired.ts +0 -174
  170. package/src/t3/diagnostics.ts +0 -42
  171. package/src/t3/models.ts +0 -354
  172. package/src/t3/names-check.ts +0 -53
  173. package/src/t3/names.ts +0 -155
  174. package/src/t3/plan.ts +0 -106
  175. package/src/t3/provider-keys.ts +0 -49
  176. package/src/t3/providers.ts +0 -102
  177. package/src/t3/reconcile.ts +0 -133
package/src/ide/t3.ts CHANGED
@@ -4,11 +4,8 @@ import { join, resolve } from 'node:path';
4
4
  import type { Check, FleetNode } from '../types';
5
5
  import type { Ide, MachineContext, WorkerContext } from './ide';
6
6
  import { fleet } from '../fleet-config';
7
- import { machineProviders } from '../t3/providers';
8
- import { providerNames } from '../t3/names-check';
9
7
  import { profileCheck } from '../t3/profile';
10
- import { modelsCheck } from '../t3/models';
11
- import { proxyAccounts, type Roster } from '../t3/accounts';
8
+ import { retireManagedProviders } from '../t3/retire-providers';
12
9
  import { MACOS_POLICY, updatesCheck, workerVersion } from '../t3/version';
13
10
  import { verifyT3Endpoint } from '../t3-endpoint';
14
11
  import { observedIdentity, verifyT3Linked } from '../t3-linked-check';
@@ -22,9 +19,7 @@ const t3Home = (): string =>
22
19
  /** What the T3 checks read besides the machine: injected by scenarios. */
23
20
  export interface T3Inputs {
24
21
  t3Home?: string;
25
- roster?: Roster;
26
22
  profile?: Record<string, unknown>;
27
- requiredModels?: Record<string, string[]>;
28
23
  policyPath?: string;
29
24
  }
30
25
 
@@ -34,38 +29,14 @@ export interface T3Inputs {
34
29
  */
35
30
  export function t3Ide(inputs: T3Inputs = {}): Ide {
36
31
  const home = () => inputs.t3Home ?? t3Home();
37
- const settings = async (context: MachineContext): Promise<Check[]> => {
38
- const required = inputs.requiredModels ?? fleet.t3?.requiredModels;
39
- const options = {
40
- t3Home: home(),
41
- ...(inputs.roster ? { roster: inputs.roster } : {}),
42
- };
43
- return [
44
- await machineProviders(
45
- context.id,
46
- context.workspace,
47
- context.apply,
48
- options
49
- ),
50
- await providerNames(
51
- context.id,
52
- context.workspace,
53
- context.apply,
54
- options
55
- ),
56
- await profileCheck(
57
- join(home(), 'userdata/settings.json'),
58
- inputs.profile ?? fleet.t3?.profile ?? {},
59
- { apply: context.apply }
60
- ),
61
- await modelsCheck({
62
- t3Home: home(),
63
- roster: inputs.roster ?? proxyAccounts,
64
- ...(required ? { required } : {}),
65
- apply: context.apply,
66
- }),
67
- ];
68
- };
32
+ const settings = async (context: MachineContext): Promise<Check[]> => [
33
+ await retireManagedProviders(home(), context.apply),
34
+ await profileCheck(
35
+ join(home(), 'userdata/settings.json'),
36
+ inputs.profile ?? fleet.t3?.profile ?? {},
37
+ { apply: context.apply }
38
+ ),
39
+ ];
69
40
  return {
70
41
  id: 't3',
71
42
  settings,
@@ -392,7 +392,7 @@ async function deployNode(
392
392
  }
393
393
 
394
394
  /** Inspection measures single resources. Convergence may measure one again.
395
- * Within convergence keep per-profile results sharing configuration:apply. */
395
+ * Within convergence keep results that share an ID. */
396
396
  export function reconcileObservations(
397
397
  result: ManagerNode,
398
398
  final: Check[]
@@ -16,16 +16,11 @@ import {
16
16
  import { verifyUbuntuBoot } from './platform/ubuntu-verify';
17
17
  import { verifyResourceSafety } from './platform/resource-verify';
18
18
  import { convergeT3Route, T3_ROUTE } from './platform/t3-route';
19
- import { convergeProxy } from './proxy-converge';
20
19
  import { IDES } from './ide';
21
20
  import { enabled, settingsChecks } from './ide/orchestrate';
22
21
  import { idesOf } from './ide/definition';
23
22
  import { fleet } from './fleet-config';
24
23
  import { disposableStorage } from './definition';
25
- import { quotaLimited, verifyFleetProviders } from './agents/fleet-verify';
26
- import { verifyNativeAgents } from './agents/native-verify';
27
- import { commandsPlay, linkAgentCommands } from './agents/commands';
28
- import { accountContext, nodeAccountChecks } from './accounts/context';
29
24
  import { managedT3, managedT3Desktop } from '../bootstrap/native-t3';
30
25
  import {
31
26
  convergeT3Service,
@@ -48,17 +43,13 @@ import { convergeGitIdentity } from './git-identity';
48
43
  import { workerSelection } from '../bootstrap/worker-tools';
49
44
  import { workerExposure } from './exposure';
50
45
  import { agentSessionLimit } from './agent-session-limit';
51
- import {
52
- applyAgentProfiles,
53
- attempt,
54
- configureWorkstation,
55
- } from './node-converge-shared';
46
+ import { attempt, configureWorkstation } from './node-converge-shared';
56
47
  import { loginServer } from './tailnet-control';
57
48
  import { tailscaleConfiguration } from './tailscale-configuration';
58
49
  import type { Check, Runner } from './types';
59
50
 
60
51
  /** Ubuntu worker convergence: Ansible owns OS policy, services and recovery; the
61
- * native T3, proxy and provider owners run only after the baseline passes.
52
+ * native T3 owner runs only after the baseline passes.
62
53
  */
63
54
  export async function convergeLinux(
64
55
  root: string,
@@ -70,7 +61,7 @@ export async function convergeLinux(
70
61
  },
71
62
  run: Runner
72
63
  ): Promise<Check[]> {
73
- const { node, revision } = target;
64
+ const { node } = target;
74
65
  const restartBusy = target.restartBusy === true;
75
66
  const audit = await auditUbuntu(run);
76
67
  if (!audit.supported || !audit.passwordlessSudo)
@@ -158,41 +149,6 @@ export async function convergeLinux(
158
149
  convergeGitIdentity(root, fleet.git, run)
159
150
  ))
160
151
  );
161
- checks.push(
162
- ...(await attempt('configuration:apply', () =>
163
- applyAgentProfiles(root, node, revision, run)
164
- ))
165
- );
166
- checks.push(
167
- ...(await attempt('agent:commands', async () => [
168
- await linkAgentCommands(root, commandsPlay(run)),
169
- ]))
170
- );
171
- checks.push(
172
- ...(await attempt('proxy:configuration', () =>
173
- convergeProxy(node, revision, run)
174
- ))
175
- );
176
- const providers = await attempt('provider:verification', () =>
177
- verifyFleetProviders(node)
178
- );
179
- checks.push(...providers);
180
- const accounts = await accountContext();
181
- checks.push(
182
- ...(await attempt('accounts:verification', () =>
183
- nodeAccountChecks(accounts)
184
- ))
185
- );
186
- checks.push(
187
- ...(await attempt('agent:verification', () =>
188
- verifyNativeAgents(node, root, run, {
189
- outOfQuota: quotaLimited(providers),
190
- // Where T3 starts them: the environment of its user service.
191
- t3Service: true,
192
- ...(accounts ? { accounts } : {}),
193
- })
194
- ))
195
- );
196
152
  checks.push(
197
153
  ...(await attempt('worker:readiness', () => workerReadiness(run, node)))
198
154
  );
@@ -393,6 +349,7 @@ async function convergeT3(
393
349
  const staged = await stageT3Policy(root, artifact.path, run, {
394
350
  node,
395
351
  restartBusy,
352
+ session,
396
353
  });
397
354
  return staged.status === 'pass' ? [] : [staged];
398
355
  },
@@ -1,8 +1,6 @@
1
1
  import { fingerprint, writeReceipt } from './fingerprint';
2
- import { configureWorkspace } from './configure';
3
2
  import { stableWorkspace } from './platform/t3-policy';
4
3
  import { convergeGithub } from './github/converge';
5
- import { T3DiagnosticError } from './t3/diagnostics';
6
4
  import { secretVia } from './fleet-config';
7
5
  import type { Check, Runner } from './types';
8
6
 
@@ -16,9 +14,7 @@ export async function attempt(
16
14
  const checks = await operation();
17
15
  const phaseDurationMs = Date.now() - started;
18
16
  return checks.map((check) => ({ ...check, phaseDurationMs }));
19
- } catch (error) {
20
- if (error instanceof T3DiagnosticError)
21
- return [{ ...error.check, phaseDurationMs: Date.now() - started }];
17
+ } catch {
22
18
  return [
23
19
  {
24
20
  id,
@@ -75,20 +71,3 @@ export async function configureWorkstation(
75
71
  }),
76
72
  ];
77
73
  }
78
-
79
- export function applyAgentProfiles(
80
- root: string,
81
- node: string,
82
- revision: string,
83
- run: Runner
84
- ): Promise<Check[]> {
85
- return configureWorkspace(
86
- root,
87
- { node, revision, tool: 'codex', profile: 'proxy' },
88
- run,
89
- {
90
- additionalTools: ['claude', 'gemini', 'opencode', 'grok', 'antigravity'],
91
- bootstrappedDeployment: true,
92
- }
93
- );
94
- }
@@ -1,6 +1,5 @@
1
1
  import { homedir } from 'node:os';
2
2
  import { delimiter, join } from 'node:path';
3
- import { spawnSync } from 'node:child_process';
4
3
 
5
4
  /** mise shims resolve every agent to the version pinned in the shared lock.
6
5
  * Putting them first keeps an unmanaged copy elsewhere on PATH (a vendor
@@ -16,19 +15,3 @@ export function pinnedPath(env: NodeJS.ProcessEnv = process.env): string {
16
15
  .filter((entry) => entry && entry !== shims);
17
16
  return [shims, ...rest].join(delimiter);
18
17
  }
19
-
20
- /** The real pinned executable behind a mise shim. Needed when a launch
21
- * changes HOME: a shim run under another HOME cannot find mise's trust state.
22
- */
23
- export function pinnedBinary(
24
- tool: string,
25
- env: NodeJS.ProcessEnv = process.env
26
- ): string {
27
- const result = spawnSync('mise', ['which', tool], {
28
- encoding: 'utf8',
29
- env: { ...env, PATH: pinnedPath(env) },
30
- timeout: 15_000,
31
- });
32
- const path = result.status === 0 ? result.stdout.trim() : '';
33
- return path.startsWith('/') ? path : tool;
34
- }
@@ -0,0 +1,104 @@
1
+ import type { Check, Runner } from '../types';
2
+
3
+ /** Where the shell tool wrapper (`ansible/ubuntu/agent-tool.py`) appends a
4
+ * line each time it tells an agent that a tool was killed. */
5
+ export const AGENT_OOM_LOG = '.local/state/personal/agent-oom.ndjson';
6
+
7
+ const SCOPE =
8
+ /oom_memcg=[^,\s]*\/(?:t3code-[^/,\s]*|homelab-tool-[^/,\s]*)\.scope\b/;
9
+
10
+ /** The programs the kernel killed inside agent scopes in the last 24 hours,
11
+ * from its OOM lines about a memory cgroup (`CONSTRAINT_MEMCG`): the machine
12
+ * as a whole had memory left, the scope did not. Only the program name of
13
+ * the victim is read, never its arguments. `undefined` when the journal
14
+ * cannot be read. */
15
+ export async function scopeOomKills(
16
+ run: Runner
17
+ ): Promise<string[] | undefined> {
18
+ const kernel = await run([
19
+ 'sudo',
20
+ '-n',
21
+ 'journalctl',
22
+ '--quiet',
23
+ '--dmesg',
24
+ '--since=24 hours ago',
25
+ '--output=cat',
26
+ '--grep=oom-kill:',
27
+ ]);
28
+ // journalctl exits 1 when --grep found nothing.
29
+ if (!kernel.ok && (kernel.stderr.trim() || kernel.reason !== 'exit'))
30
+ return undefined;
31
+ return kernel.stdout
32
+ .split('\n')
33
+ .filter((line) => /CONSTRAINT_MEMCG/.test(line) && SCOPE.test(line))
34
+ .map((line) => /\btask=([^,\s]+),/.exec(line)?.[1] ?? 'unknown');
35
+ }
36
+
37
+ /** How many tool runs the wrapper told an agent about, in the last 24 hours. */
38
+ async function reportedKills(
39
+ run: Runner,
40
+ home: string,
41
+ now: number
42
+ ): Promise<number> {
43
+ const logged = await run(['tail', '-n', '500', `${home}/${AGENT_OOM_LOG}`]);
44
+ if (!logged.ok) return 0;
45
+ const since = now / 1000 - 86_400;
46
+ let count = 0;
47
+ for (const line of logged.stdout.split('\n')) {
48
+ try {
49
+ const record = JSON.parse(line) as { t?: number };
50
+ if (typeof record.t === 'number' && record.t >= since) count++;
51
+ } catch {
52
+ /* A line cut by the bound of the log. */
53
+ }
54
+ }
55
+ return count;
56
+ }
57
+
58
+ const top = (names: string[]): string =>
59
+ Object.entries(
60
+ names.reduce<Record<string, number>>(
61
+ (all, name) => ({ ...all, [name]: (all[name] ?? 0) + 1 }),
62
+ {}
63
+ )
64
+ )
65
+ .sort((a, b) => b[1] - a[1])
66
+ .slice(0, 3)
67
+ .map(([name, count]) => `${name}: ${count}`)
68
+ .join(', ');
69
+
70
+ /** An agent whose tool is killed for memory sees a killed build and no
71
+ * reason, and may retry in a loop. The wrapper now says why when it can and
72
+ * logs it; this reports what the kernel killed inside agent scopes, which is
73
+ * the same event seen from the machine. */
74
+ export async function agentOomCheck(
75
+ run: Runner,
76
+ home: string,
77
+ now: number = Date.now()
78
+ ): Promise<Check> {
79
+ const id = 'worker:agent-oom';
80
+ const kills = await scopeOomKills(run);
81
+ if (!kills)
82
+ return {
83
+ id,
84
+ status: 'warn',
85
+ summary: 'Recent memory kills inside agent scopes could not be read.',
86
+ };
87
+ const reported = await reportedKills(run, home, now);
88
+ if (!kills.length && !reported)
89
+ return {
90
+ id,
91
+ status: 'pass',
92
+ summary:
93
+ 'The kernel killed no process inside an agent scope in the last 24 hours.',
94
+ };
95
+ return {
96
+ id,
97
+ status: 'warn',
98
+ summary: `AGENT_OOM_KILLS: the kernel killed ${kills.length} processes inside agent scopes in the last 24 hours${kills.length ? ` (${top(kills)})` : ''}; agents were told the reason for ${reported} killed tools.`,
99
+ remedy: {
100
+ action:
101
+ 'A scope reached its memory cap although the worker as a whole had memory left. Heavy tools are slowed at memory.high before they are killed at memory.max. Run fewer builds at once on this worker (homelab-heavy queues them), lower their parallelism (TURBO_CONCURRENCY, gradle --max-workers), or move the work to a larger worker.',
102
+ },
103
+ };
104
+ }
@@ -1,29 +1,29 @@
1
1
  import { runAnsible } from './ansible';
2
- import { desired } from '../t3/desired';
3
2
  import policy from '../../ansible/ubuntu/t3/policy.json';
4
- import { deferralRemedy, restartDeferral } from './t3-service';
3
+ import { deferralRemedy, restartDeferral, t3Unit } from './t3-service';
4
+ import type { Session } from '../../bootstrap/worker-features';
5
5
  import { basename, dirname, join, resolve } from 'node:path';
6
6
  import { readlink, rename, rm, symlink } from 'node:fs/promises';
7
7
  import { userInfo } from 'node:os';
8
8
  import type { Runner, Check } from '../types';
9
9
 
10
- /** The administrator policy a worker's T3 runs: the fleet's
11
- * (`ansible/ubuntu/t3/policy.json`, which keeps linked environments on so
12
- * the manager pairs with a replaced worker without a person) with the
13
- * worker's provider instances locked.
14
- */
15
- export function workerPolicy(instances: Record<string, unknown>) {
10
+ /** What `t3-policy.yml` is given. `t3_unit` is the unit of the worker's
11
+ * session, the one it asks whether T3 runs and restarts when T3 has not
12
+ * loaded the staged policy. */
13
+ export function policyPlayVariables(
14
+ executable: string,
15
+ document: object,
16
+ user: { username: string; uid: number; homedir: string },
17
+ target: { restartBusy?: boolean; session?: Session }
18
+ ) {
16
19
  return {
17
- ...policy,
18
- settings: {
19
- ...policy.settings,
20
- ...Object.fromEntries(
21
- Object.entries(instances).map(([id, value]) => [
22
- `providerInstances.${id}`,
23
- { value, locked: true },
24
- ])
25
- ),
26
- },
20
+ t3_executable: executable,
21
+ t3_policy_document: document,
22
+ development_user: user.username,
23
+ development_uid: user.uid,
24
+ development_home: user.homedir,
25
+ t3_restart_busy: target.restartBusy === true,
26
+ t3_unit: t3Unit(target.session),
27
27
  };
28
28
  }
29
29
 
@@ -31,26 +31,13 @@ export async function stageT3Policy(
31
31
  root: string,
32
32
  executable: string,
33
33
  run: Runner,
34
- target: { node: string; restartBusy?: boolean }
34
+ target: { node: string; restartBusy?: boolean; session?: Session }
35
35
  ): Promise<Check> {
36
- const { node } = target;
37
- const instances = await desired(
38
- resolve(root, 'agents/t3.json'),
39
- await stableWorkspace(root),
40
- node
41
- );
42
- const user = userInfo();
43
- const document = workerPolicy(instances);
44
36
  const result = await runAnsible(run, 't3-policy.yml', {
45
37
  cwd: resolve(root, 'ansible/ubuntu'),
46
- input: JSON.stringify({
47
- t3_executable: executable,
48
- t3_policy_document: document,
49
- development_user: user.username,
50
- development_uid: user.uid,
51
- development_home: user.homedir,
52
- t3_restart_busy: target.restartBusy === true,
53
- }),
38
+ input: JSON.stringify(
39
+ policyPlayVariables(executable, policy, userInfo(), target)
40
+ ),
54
41
  timeoutMs: 120_000,
55
42
  });
56
43
  return {
@@ -90,7 +77,7 @@ export async function verifyT3Policy(
90
77
  : 'T3_POLICY_RESTART_PENDING',
91
78
  remedy: {
92
79
  action:
93
- 'T3 did not load the installed policy after a restart. Inspect systemctl --user status t3code-desktop.service on the node, then rerun converge.',
80
+ 'T3 did not load the installed policy after a restart. Inspect systemctl --user status t3code-desktop.service (t3code-headless.service on a headless worker) on the node, then rerun converge.',
94
81
  },
95
82
  };
96
83
  }
@@ -308,6 +308,123 @@ export async function deadlineRestartsCheck(run: Runner): Promise<Check> {
308
308
  };
309
309
  }
310
310
 
311
+ /** Where the watchdog (`t3-health.sh`) appends one JSON line per decision. */
312
+ export const T3_WATCHDOG_LOG = '.local/state/personal/t3-watchdog.ndjson';
313
+
314
+ interface WatchdogRecord {
315
+ t: number;
316
+ event: string;
317
+ cause?: string;
318
+ ok?: boolean;
319
+ ms?: number;
320
+ snapshot?: string;
321
+ }
322
+
323
+ /** The last 24 hours of the watchdog's log. `undefined` when it cannot be
324
+ * read; an absent file is an empty log. */
325
+ export async function watchdogRecords(
326
+ run: Runner,
327
+ home: string,
328
+ now: number
329
+ ): Promise<WatchdogRecord[] | undefined> {
330
+ const logged = await run([
331
+ 'tail',
332
+ '-n',
333
+ String(policy.t3Service.watchdogLogLines),
334
+ `${home}/${T3_WATCHDOG_LOG}`,
335
+ ]);
336
+ if (!logged.ok) return /No such file/.test(logged.stderr) ? [] : undefined;
337
+ const since = now / 1000 - 86_400;
338
+ const records: WatchdogRecord[] = [];
339
+ for (const line of logged.stdout.split('\n')) {
340
+ try {
341
+ const value = JSON.parse(line) as WatchdogRecord;
342
+ if (typeof value.t === 'number' && value.t >= since && value.event)
343
+ records.push(value);
344
+ } catch {
345
+ /* A line cut by the bound of the log is not a record. */
346
+ }
347
+ }
348
+ return records;
349
+ }
350
+
351
+ const unresponsiveRestarts = (records: WatchdogRecord[]): WatchdogRecord[] =>
352
+ records.filter(
353
+ (record) => record.event === 'restarted' && record.cause === 'unresponsive'
354
+ );
355
+
356
+ /** What the health check adds when the watchdog restarted T3: how often, and
357
+ * where the newest snapshot of why is. Empty when it did not. */
358
+ export async function hangEvidence(
359
+ run: Runner,
360
+ home: string,
361
+ now: number = Date.now()
362
+ ): Promise<string> {
363
+ const restarts = unresponsiveRestarts(
364
+ (await watchdogRecords(run, home, now)) ?? []
365
+ );
366
+ if (!restarts.length) return '';
367
+ const snapshot = restarts.at(-1)?.snapshot;
368
+ return ` The watchdog restarted T3 ${restarts.length} ${restarts.length === 1 ? 'time' : 'times'} in the last 24 hours${snapshot ? `; the newest snapshot of why is ${snapshot}` : ''}.`;
369
+ }
370
+
371
+ /** A T3 that is restarted again and again passes every other check, because
372
+ * each restart leaves a server that answers. The watchdog logs what it did;
373
+ * this fails when it restarted T3 for being unresponsive too often in the
374
+ * last 24 hours, or when too many of its probes were slow. */
375
+ export async function t3StabilityCheck(
376
+ run: Runner,
377
+ home: string,
378
+ now: number = Date.now()
379
+ ): Promise<Check> {
380
+ const id = 'worker:t3-stability';
381
+ const records = await watchdogRecords(run, home, now);
382
+ if (!records)
383
+ return {
384
+ id,
385
+ status: 'warn',
386
+ summary: 'The watchdog log of T3 could not be read.',
387
+ };
388
+ const limits = policy.t3Stability;
389
+ const restarts = unresponsiveRestarts(records);
390
+ const probes = records.filter(
391
+ (record) => record.event === 'probe' && record.ok && record.ms !== undefined
392
+ );
393
+ const slow = probes.filter((record) => (record.ms ?? 0) > limits.slowProbeMs);
394
+ if (restarts.length > limits.maxRestarts24h) {
395
+ const snapshots = restarts
396
+ .map((record) => record.snapshot)
397
+ .filter(Boolean)
398
+ .slice(-3);
399
+ return {
400
+ id,
401
+ status: 'fail',
402
+ summary: `T3_RESTARTS_FREQUENT: the watchdog restarted T3 ${restarts.length} times in the last 24 hours because it did not answer (at most ${limits.maxRestarts24h} are expected).`,
403
+ remedy: {
404
+ action: `Read the snapshots of why T3 hung${snapshots.length ? ` (${snapshots.join(', ')})` : ' under ~/.local/state/personal/t3-hangs on the worker'}: the threads' wchan, the pressure and the busiest processes. Look for agents or recovery jobs running heavy work at the time (worker:pressure-events), then see docs/runbooks.md.`,
405
+ },
406
+ };
407
+ }
408
+ if (
409
+ probes.length >= limits.minProbes &&
410
+ slow.length / probes.length > limits.slowProbeFraction
411
+ )
412
+ return {
413
+ id,
414
+ status: 'fail',
415
+ summary: `T3_API_SLOW: ${slow.length} of the last ${probes.length} answers of the T3 local API took more than ${limits.slowProbeMs} ms.`,
416
+ remedy: {
417
+ action:
418
+ 'T3 answers but slowly: the worker is overloaded or T3 stalls. Check worker:pressure-events and the load of the worker before T3 starts failing its probes.',
419
+ },
420
+ };
421
+ return {
422
+ id,
423
+ status: 'pass',
424
+ summary: `The watchdog restarted T3 ${restarts.length} times in the last 24 hours and ${slow.length} of ${probes.length} probes were slow.`,
425
+ };
426
+ }
427
+
311
428
  /** The release installed for the session: the desktop package the app was
312
429
  * unpacked from, or the versioned directory the server unit runs. */
313
430
  async function installedRelease(
@@ -0,0 +1,65 @@
1
+ import policy from '../../ansible/ubuntu/policy.json';
2
+ import type { Check, Runner } from '../types';
3
+
4
+ interface Run {
5
+ seconds?: number;
6
+ peak_mib?: number;
7
+ deferred?: number;
8
+ }
9
+
10
+ /** The work-in-progress guard (`ansible/ubuntu/wip-guard.py`) ends each run
11
+ * with one JSON `run` line. A run that takes minutes or gigabytes competes
12
+ * with T3 and the agents on a busy worker, so this reads those of the last 24
13
+ * hours and warns when one ran too long or held too much memory. Only the
14
+ * numbers are read, never a worktree path. */
15
+ export async function wipGuardCheck(run: Runner): Promise<Check> {
16
+ const id = 'worker:wip-guard';
17
+ const limits = policy.resourceSafety.wipGuard;
18
+ const logged = await run([
19
+ 'journalctl',
20
+ '--user',
21
+ '--quiet',
22
+ '--unit=personal-worker-wip-guard.service',
23
+ '--since=24 hours ago',
24
+ '--output=cat',
25
+ '--grep="event": "run"',
26
+ '--lines=1000',
27
+ ]);
28
+ // journalctl exits 1 when --grep found nothing.
29
+ if (!logged.ok && (logged.stderr.trim() || logged.reason !== 'exit'))
30
+ return {
31
+ id,
32
+ status: 'warn',
33
+ summary: 'Recent runs of the work-in-progress guard could not be read.',
34
+ };
35
+ const runs: Run[] = [];
36
+ for (const line of logged.stdout.split('\n')) {
37
+ try {
38
+ const value = JSON.parse(line) as Run & { event?: string };
39
+ if (value.event === 'run') runs.push(value);
40
+ } catch {
41
+ /* Not a run summary. */
42
+ }
43
+ }
44
+ const slow = runs.filter(
45
+ (entry) => (entry.seconds ?? 0) > limits.slowRunSeconds
46
+ );
47
+ const heavy = runs.filter(
48
+ (entry) => (entry.peak_mib ?? 0) > limits.peakWarnMiB
49
+ );
50
+ if (!slow.length && !heavy.length)
51
+ return {
52
+ id,
53
+ status: 'pass',
54
+ summary: `${runs.length} runs of the work-in-progress guard in the last 24 hours stayed within ${limits.slowRunSeconds} seconds and ${limits.peakWarnMiB} MiB.`,
55
+ };
56
+ return {
57
+ id,
58
+ status: 'warn',
59
+ summary: `WIP_GUARD_HEAVY: of ${runs.length} runs of the work-in-progress guard in the last 24 hours, ${slow.length} took more than ${limits.slowRunSeconds} seconds and ${heavy.length} used more than ${limits.peakWarnMiB} MiB.`,
60
+ remedy: {
61
+ action:
62
+ 'Read the run lines of personal-worker-wip-guard.service (journalctl --user -u personal-worker-wip-guard.service): the worktree that was slow to read is the one with a large tree of files Git does not ignore. Ignore its build output or remove the worktree.',
63
+ },
64
+ };
65
+ }