@crvouga/homelab 0.25.0 → 0.26.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.
package/src/ide/t3.ts CHANGED
@@ -3,8 +3,6 @@ import { homedir } from 'node:os';
3
3
  import { join, resolve } from 'node:path';
4
4
  import type { Check, FleetNode } from '../types';
5
5
  import type { Ide, MachineContext, WorkerContext } from './ide';
6
- import { fleet } from '../fleet-config';
7
- import { profileCheck } from '../t3/profile';
8
6
  import { retireManagedProviders } from '../t3/retire-providers';
9
7
  import { MACOS_POLICY, updatesCheck, workerVersion } from '../t3/version';
10
8
  import { verifyT3Endpoint } from '../t3-endpoint';
@@ -19,7 +17,6 @@ const t3Home = (): string =>
19
17
  /** What the T3 checks read besides the machine: injected by scenarios. */
20
18
  export interface T3Inputs {
21
19
  t3Home?: string;
22
- profile?: Record<string, unknown>;
23
20
  policyPath?: string;
24
21
  }
25
22
 
@@ -31,11 +28,6 @@ export function t3Ide(inputs: T3Inputs = {}): Ide {
31
28
  const home = () => inputs.t3Home ?? t3Home();
32
29
  const settings = async (context: MachineContext): Promise<Check[]> => [
33
30
  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
31
  ];
40
32
  return {
41
33
  id: 't3',
@@ -281,9 +281,20 @@ async function applyNodes(
281
281
  ? chooseCanary(workers, input.canary, input.nodes)
282
282
  : undefined;
283
283
  if (canary) report.canary = canary.node;
284
+ // A T3 restart is scheduled after converge exits, so a manager (or a
285
+ // canary) whose T3 still runs an older version never gates a rollout.
286
+ // A version that has not been measured yet is not a failure either, and
287
+ // neither is `rollout`: that marker only means this revision has not been
288
+ // applied, which is what the rollout is about to do. Only a version check
289
+ // that ran and failed holds the other workers back.
284
290
  const unverified = (node: ManagerNode) =>
285
291
  input.definition.softwarePolicy &&
286
- pendingVersions(input.definition, node, input.revision).length > 0;
292
+ pendingVersions(input.definition, node, input.revision).some(
293
+ (pending) =>
294
+ pending !== 'rollout' &&
295
+ !pending.startsWith('t3') &&
296
+ node.checks.some((check) => check.id === pending && blocking(check))
297
+ );
287
298
  let blocked =
288
299
  report.checks.some(blocking) ||
289
300
  report.nodes.some((node) => node.role === 'manager' && unverified(node));
@@ -120,44 +120,74 @@ export function decodeRelease(
120
120
  export const RELEASE_ENV = 'HOMELAB_RELEASE';
121
121
 
122
122
  /** The release this process runs: what it was told, else its own package.
123
- * A checkout has no stamped commit, so the date is read from Git.
123
+ * A checkout's manifest stays at the development version and names no
124
+ * commit, so the commit and its date come from Git, and the version is the
125
+ * nearest tag that checkout can see. A hand-off that only knows the
126
+ * development version has not told this process anything.
124
127
  */
125
128
  export function releaseIdentity(cwd = PACKAGE_ROOT): ReleaseIdentity {
126
129
  const told = decodeRelease(process.env[RELEASE_ENV]);
127
- if (told) return told;
130
+ if (told?.revision) return told;
128
131
  const info = packageInfo(cwd);
132
+ const revision = info.revision ?? headCommit(cwd);
133
+ const version =
134
+ info.version === DEVELOPMENT_VERSION
135
+ ? (nearestRelease(cwd) ?? info.version)
136
+ : info.version;
129
137
  return {
130
- version: info.version,
131
- revision: info.revision,
138
+ version,
139
+ revision,
132
140
  committedAt:
133
- info.committedAt ??
134
- (info.revision ? commitDate(info.revision, cwd) : null),
141
+ info.committedAt ?? (revision ? commitDate(revision, cwd) : null),
135
142
  };
136
143
  }
137
144
 
138
- /** `homelab 0.23.14 (952dd2ba7785, 2026-12-01)`. */
139
- export function releaseLine(release: ReleaseIdentity): string {
140
- return `homelab ${release.version} (${(release.revision ?? 'unknown').slice(0, 12)}, ${release.committedAt ?? 'unknown'})`;
145
+ const DEVELOPMENT_VERSION = '0.0.0-development';
146
+
147
+ /** `HEAD` when this directory is a checkout of a commit, else null. */
148
+ function headCommit(cwd: string): string | null {
149
+ const revision = git(cwd, ['rev-parse', 'HEAD']);
150
+ return revision && /^[a-f0-9]{40}$/.test(revision) ? revision : null;
141
151
  }
142
152
 
143
- /** The calendar date of a commit this checkout can see, `YYYY-MM-DD`, or
144
- * null. A published package already carries the date; a checkout asks Git.
153
+ /** The version named by the nearest tag at or before `HEAD`, else null.
154
+ * `v1.4.0` is `1.4.0`. A checkout fetched without tags has none.
145
155
  */
146
- export function commitDate(
147
- revision: string,
148
- cwd = PACKAGE_ROOT
149
- ): string | null {
150
- if (!/^[a-f0-9]{40}$/.test(revision)) return null;
156
+ function nearestRelease(cwd: string): string | null {
157
+ const tag = git(cwd, ['describe', '--tags', '--abbrev=0']);
158
+ if (!tag) return null;
159
+ const version = tag.startsWith('v') ? tag.slice(1) : tag;
160
+ return /^\d+\.\d+\.\d+/.test(version) ? version : null;
161
+ }
162
+
163
+ function git(cwd: string, args: string[]): string | null {
151
164
  try {
152
- const date = execFileSync('git', ['log', '-1', '--format=%cs', revision], {
165
+ const text = execFileSync('git', args, {
153
166
  cwd,
154
167
  stdio: ['ignore', 'pipe', 'ignore'],
155
168
  timeout: 5_000,
156
169
  })
157
170
  .toString()
158
171
  .trim();
159
- return calendarDate(date) ? date : null;
172
+ return text || null;
160
173
  } catch {
161
174
  return null;
162
175
  }
163
176
  }
177
+
178
+ /** `homelab 0.23.14 (952dd2ba7785, 2026-12-01)`. */
179
+ export function releaseLine(release: ReleaseIdentity): string {
180
+ return `homelab ${release.version} (${(release.revision ?? 'unknown').slice(0, 12)}, ${release.committedAt ?? 'unknown'})`;
181
+ }
182
+
183
+ /** The calendar date of a commit this checkout can see, `YYYY-MM-DD`, or
184
+ * null. A published package already carries the date; a checkout asks Git.
185
+ */
186
+ export function commitDate(
187
+ revision: string,
188
+ cwd = PACKAGE_ROOT
189
+ ): string | null {
190
+ if (!/^[a-f0-9]{40}$/.test(revision)) return null;
191
+ const date = git(cwd, ['log', '-1', '--format=%cs', revision]);
192
+ return date && calendarDate(date) ? date : null;
193
+ }
@@ -204,7 +204,7 @@ async function recoveryChecks(
204
204
  : 'The T3 desktop app runs as an enabled session service with automatic crash recovery.'
205
205
  )
206
206
  );
207
- checks.push(await t3HealthCheck(run));
207
+ checks.push(await t3HealthCheck(run, features.session));
208
208
  checks.push(await wipGuardCheck(run));
209
209
  checks.push(await t3StabilityCheck(run, userInfo().homedir));
210
210
  checks.push(
@@ -269,8 +269,32 @@ export async function serviceRecoveryCheck(run: Runner): Promise<Check> {
269
269
  );
270
270
  }
271
271
 
272
- /** The server answers its local API now, not merely that a process exists. */
273
- async function t3HealthCheck(run: Runner): Promise<Check> {
272
+ /** Seconds from this boot until T3's unit became active, or null when the
273
+ * clock cannot be read. The unit's monotonic start is measured from boot. */
274
+ export async function bootToServingSeconds(
275
+ run: Runner,
276
+ session: 'desktop' | 'headless' = 'desktop'
277
+ ): Promise<number | null> {
278
+ const started = await run([
279
+ 'systemctl',
280
+ '--user',
281
+ 'show',
282
+ '--property=ActiveEnterTimestampMonotonic',
283
+ '--value',
284
+ t3Unit(session),
285
+ ]);
286
+ const entered = Number(started.stdout.trim());
287
+ if (!started.ok || !Number.isSafeInteger(entered) || entered <= 0)
288
+ return null;
289
+ return entered / 1_000_000;
290
+ }
291
+
292
+ /** The server answers its local API now, not merely that a process exists,
293
+ * with unit activation checked against the boot-serving limit. */
294
+ export async function t3HealthCheck(
295
+ run: Runner,
296
+ session: 'desktop' | 'headless' = 'desktop'
297
+ ): Promise<Check> {
274
298
  const probe = await run(
275
299
  [
276
300
  'curl',
@@ -282,21 +306,59 @@ async function t3HealthCheck(run: Runner): Promise<Check> {
282
306
  ],
283
307
  { timeoutMs: 15_000 }
284
308
  );
285
- let identified = false;
309
+ const answers = probe.ok && hasEnvironmentIdentity(probe.stdout);
310
+ const boot = answers
311
+ ? await bootServing(run, session)
312
+ : { late: false, summary: '' };
313
+ const ok = answers && !boot.late;
314
+ return {
315
+ id: 'worker:t3-health',
316
+ status: ok ? 'pass' : 'fail',
317
+ summary: boot.late
318
+ ? boot.summary
319
+ : `${answers ? 'T3 local API answers with its environment identity within 10 seconds.' : 'T3 local API did not answer with its environment identity within 10 seconds.'}${boot.summary}${await hangEvidence(run, userInfo().homedir)}`,
320
+ ...(!ok
321
+ ? {
322
+ remedy: {
323
+ action: boot.late
324
+ ? 'The T3 unit activated later than t3Service.bootServingSeconds in ansible/ubuntu/policy.json. Read the journal of the T3 unit and of personal-worker-recovery for what delayed the start after boot.'
325
+ : 'Apply the approved converge revision over verified SSH, then rerun check --workers. No password prompt or state reset is attempted by health.',
326
+ },
327
+ }
328
+ : {}),
329
+ };
330
+ }
331
+
332
+ function hasEnvironmentIdentity(response: string): boolean {
286
333
  try {
287
- const value: unknown = JSON.parse(probe.stdout);
288
- identified =
334
+ const value: unknown = JSON.parse(response);
335
+ return (
289
336
  typeof value === 'object' &&
290
337
  value !== null &&
291
- typeof (value as Record<string, unknown>)['environmentId'] === 'string';
338
+ typeof (value as Record<string, unknown>)['environmentId'] === 'string'
339
+ );
292
340
  } catch {
293
- /* Raw responses are never reported. */
341
+ return false;
294
342
  }
295
- return check(
296
- 'worker:t3-health',
297
- probe.ok && identified,
298
- `T3 local API answers with its environment identity within 10 seconds.${await hangEvidence(run, userInfo().homedir)}`
299
- );
343
+ }
344
+
345
+ /** Compare the unit activation time with the boot-serving deadline. */
346
+ async function bootServing(
347
+ run: Runner,
348
+ session: 'desktop' | 'headless'
349
+ ): Promise<{ late: boolean; summary: string }> {
350
+ const limit = policy.t3Service.bootServingSeconds;
351
+ const serving = await bootToServingSeconds(run, session);
352
+ if (serving === null) return { late: false, summary: '' };
353
+ if (serving > limit)
354
+ return {
355
+ late: true,
356
+ summary: `T3_BOOT_SERVING_LATE: The T3 unit activated ${serving} seconds after boot, past the ${limit} seconds a worker is given to serve after a power loss.`,
357
+ };
358
+ return {
359
+ late: false,
360
+ summary: ` The T3 unit activated ${serving} seconds after boot (at most ${limit}).`,
361
+ };
300
362
  }
301
363
 
302
364
  const DAY_SECONDS = 86_400;
package/src/t3/profile.ts DELETED
@@ -1,204 +0,0 @@
1
- import { dirname, join } from 'node:path';
2
- import type { Check } from '../types';
3
- import { canonical, object, read, write } from './files';
4
- import { fleetJson } from '../fleet-config';
5
-
6
- /** What happens to one declared setting. `release` stops managing a key the
7
- * fleet no longer declares and leaves its value to the machine.
8
- */
9
- export type ProfileAction =
10
- 'create' | 'update' | 'delete' | 'release' | 'unchanged' | 'conflict';
11
- export type ProfileChange = { key: string; action: ProfileAction };
12
-
13
- /** The values the fleet last wrote, kept beside T3's settings: the base of
14
- * the three-way merge between what is declared, what T3 holds and what was
15
- * applied before.
16
- */
17
- export const profileRecord = (settings: string): string =>
18
- join(dirname(settings), 'personal-profile.json');
19
-
20
- const same = (a: unknown, b: unknown): boolean => canonical(a) === canonical(b);
21
-
22
- /** Managed keys converge, keys nobody declared are left alone, and a key
23
- * changed on the machine since the fleet last wrote it (or that existed
24
- * before the fleet declared it) is a conflict, never overwritten.
25
- */
26
- export function planProfile(
27
- settings: Record<string, unknown>,
28
- applied: Record<string, unknown>,
29
- declared: Record<string, unknown>
30
- ) {
31
- const next = { ...settings };
32
- const record = { ...applied };
33
- const changes: ProfileChange[] = [];
34
- const keys = [
35
- ...new Set([...Object.keys(declared), ...Object.keys(applied)]),
36
- ].sort();
37
- for (const key of keys) {
38
- const present = Object.hasOwn(settings, key);
39
- const managed = Object.hasOwn(applied, key);
40
- const action = actionFor(key, declared, {
41
- present,
42
- managed,
43
- current: settings[key],
44
- base: applied[key],
45
- });
46
- changes.push({ key, action });
47
- if (action === 'create' || action === 'update') {
48
- next[key] = declared[key];
49
- record[key] = declared[key];
50
- } else if (action === 'unchanged') record[key] = declared[key];
51
- else if (action === 'delete') {
52
- delete next[key];
53
- delete record[key];
54
- } else if (action === 'release') delete record[key];
55
- }
56
- return {
57
- settings: next,
58
- record,
59
- changes,
60
- settingsChanged: !same(next, settings),
61
- recordChanged: !same(record, applied),
62
- };
63
- }
64
-
65
- function actionFor(
66
- key: string,
67
- declared: Record<string, unknown>,
68
- {
69
- present,
70
- managed,
71
- current,
72
- base,
73
- }: { present: boolean; managed: boolean; current: unknown; base: unknown }
74
- ): ProfileAction {
75
- if (!Object.hasOwn(declared, key)) {
76
- if (present && same(current, base)) return 'delete';
77
- return 'release';
78
- }
79
- const wanted = declared[key];
80
- if (present && same(current, wanted)) return 'unchanged';
81
- if (!present) return managed ? 'conflict' : 'create';
82
- return managed && same(current, base) ? 'update' : 'conflict';
83
- }
84
-
85
- export interface ProfileOptions {
86
- apply: boolean;
87
- /** Tries before a settings file T3 keeps rewriting is reported busy. */
88
- attempts?: number;
89
- pause?: () => Promise<void>;
90
- /** Runs between the read and the write: where T3 may write too. */
91
- beforeWrite?: () => Promise<void>;
92
- }
93
-
94
- /** Plans, and with `apply` writes, the declared profile. T3 writes the same
95
- * file and offers no compare-and-swap, so a write happens only when the file
96
- * is still what was read; otherwise the merge is planned again, a bounded
97
- * number of times.
98
- */
99
- export async function reconcileProfile(
100
- settingsPath: string,
101
- declared: Record<string, unknown>,
102
- options: ProfileOptions
103
- ) {
104
- const recordPath = profileRecord(settingsPath);
105
- const attempts = options.attempts ?? 3;
106
- const pause =
107
- options.pause ?? (() => new Promise((done) => setTimeout(done, 500)));
108
- for (let attempt = 1; ; attempt++) {
109
- const raw = await read(settingsPath);
110
- const recordRaw = await read(recordPath);
111
- const plan = planProfile(
112
- object(raw),
113
- readRecord(recordRaw, settingsPath),
114
- declared
115
- );
116
- if (!options.apply || (!plan.settingsChanged && !plan.recordChanged))
117
- return { ...plan, applied: false };
118
- await options.beforeWrite?.();
119
- if (!plan.settingsChanged || (await read(settingsPath)) === raw) {
120
- if (plan.settingsChanged)
121
- await write(
122
- settingsPath,
123
- JSON.stringify(plan.settings, null, 2) + '\n'
124
- );
125
- await write(
126
- recordPath,
127
- canonical({ version: 1, target: settingsPath, settings: plan.record }) +
128
- '\n'
129
- );
130
- return { ...plan, applied: true };
131
- }
132
- if (attempt >= attempts) throw new Error('T3_SETTINGS_BUSY');
133
- await pause();
134
- }
135
- }
136
-
137
- function readRecord(
138
- raw: string | null,
139
- target: string
140
- ): Record<string, unknown> {
141
- if (raw === null) return {};
142
- const record = object(raw);
143
- if (record['version'] !== 1 || record['target'] !== target)
144
- throw new Error('T3_PROFILE_RECORD_INVALID');
145
- return object(JSON.stringify(record['settings'] ?? {}));
146
- }
147
-
148
- /** `t3:profile`: the declared settings on this machine. A report names the
149
- * keys and what happens to them, never a value: a tool server's settings may
150
- * carry a credential.
151
- */
152
- export async function profileCheck(
153
- settingsPath: string,
154
- declared: Record<string, unknown>,
155
- options: ProfileOptions
156
- ): Promise<Check> {
157
- const remedy = (action: string) => ({ remedy: { action } });
158
- try {
159
- const result = await reconcileProfile(settingsPath, declared, options);
160
- const conflicts = result.changes.filter(
161
- (change) => change.action === 'conflict'
162
- );
163
- if (conflicts.length)
164
- return {
165
- id: 't3:profile',
166
- status: 'warn',
167
- summary: 'T3_PROFILE_CONFLICT',
168
- ...remedy(
169
- `These T3 settings were changed on this machine since homelab last wrote them, or existed before they were declared, and were left as they are: ${conflicts.map((change) => change.key).join(', ')}. Put the value every machine should hold under t3.profile in ${fleetJson()}, or remove the setting on this machine, then run converge.`
170
- ),
171
- };
172
- const pending = result.changes.filter(
173
- (change) => !['unchanged', 'conflict'].includes(change.action)
174
- );
175
- if (!options.apply && pending.length)
176
- return {
177
- id: 't3:profile',
178
- status: 'warn',
179
- summary: 'T3_PROFILE_PENDING',
180
- ...remedy(
181
- `converge would change these T3 settings: ${pending.map((change) => `${change.key} (${change.action})`).join(', ')}.`
182
- ),
183
- };
184
- return {
185
- id: 't3:profile',
186
- status: 'pass',
187
- summary: Object.keys(declared).length
188
- ? 'T3 on this machine holds every setting of the declared profile; settings nobody declared are its own.'
189
- : 'No T3 profile is declared; every setting stays local.',
190
- };
191
- } catch (error) {
192
- const busy = error instanceof Error && error.message === 'T3_SETTINGS_BUSY';
193
- return {
194
- id: 't3:profile',
195
- status: 'fail',
196
- summary: busy ? 'T3_SETTINGS_BUSY' : 'T3_PROFILE_UNVERIFIED',
197
- ...remedy(
198
- busy
199
- ? 'T3 kept rewriting its settings while homelab merged the profile. Run converge again; nothing was overwritten.'
200
- : 'Repair T3’s settings.json (or restore personal-profile.json from a backup) on this machine, then run converge.'
201
- ),
202
- };
203
- }
204
- }