@indigoai-us/hq-cli 5.345.269 → 5.345.272

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 (61) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/contracts/host-canary-release.json +7 -7
  3. package/dist/command-catalog.generated.d.ts +2 -2
  4. package/dist/command-catalog.generated.js +2 -2
  5. package/dist/commands/core-checkpoint-stop-gate-native.js +2 -13
  6. package/dist/commands/core-session-journal-native.js +20 -4
  7. package/dist/commands/signals-run.d.ts +4 -1
  8. package/dist/commands/signals-run.js +6 -8
  9. package/dist/commands/sync-core.js +2 -1
  10. package/dist/lib/daemon/daemon-restart.d.ts +70 -0
  11. package/dist/lib/daemon/daemon-restart.js +114 -0
  12. package/dist/lib/daemon/hook-requests-work-mesh-shims.d.ts +41 -0
  13. package/dist/lib/daemon/hook-requests-work-mesh-shims.js +237 -0
  14. package/dist/lib/daemon/hook-requests.d.ts +4 -1
  15. package/dist/lib/daemon/hook-requests.js +23 -1
  16. package/dist/lib/daemon/hq-child-bootstrap.mjs +1 -0
  17. package/dist/lib/daemon/installed-cli-restart.js +14 -4
  18. package/dist/lib/daemon/run.d.ts +1 -1
  19. package/dist/lib/daemon/run.js +65 -51
  20. package/dist/lib/daemon/supervisor.js +0 -2
  21. package/dist/lib/hook-engine/coverage.d.ts +21 -0
  22. package/dist/lib/hook-engine/coverage.js +98 -5
  23. package/dist/lib/hook-engine/native-precompact-compatibility.json +1 -0
  24. package/dist/lib/hook-engine/native-stop-compatibility.json +4 -2
  25. package/dist/lib/hook-engine/reconcile.js +8 -0
  26. package/dist/lib/hook-engine/stable-heal.d.ts +17 -1
  27. package/dist/lib/hook-engine/stable-heal.js +42 -5
  28. package/dist/lib/hook-engine/stable-link.d.ts +70 -0
  29. package/dist/lib/hook-engine/stable-link.js +300 -0
  30. package/dist/lib/hot-channels/signals-pass.d.ts +10 -2
  31. package/dist/lib/hot-channels/signals-pass.js +13 -3
  32. package/dist/lib/install/hook-target.js +4 -1
  33. package/dist/lib/signals/engine.d.ts +0 -2
  34. package/dist/lib/signals/engine.js +12 -7
  35. package/dist/lib/signals/reply.js +35 -82
  36. package/dist/lib/signals/run-lock.d.ts +8 -0
  37. package/dist/lib/signals/run-lock.js +42 -7
  38. package/dist/lib/signals/run-record.js +2 -1
  39. package/dist/lib/signals/settings.d.ts +9 -4
  40. package/dist/lib/signals/settings.js +7 -5
  41. package/dist/lib/signals/steps/extract.d.ts +64 -17
  42. package/dist/lib/signals/steps/extract.js +175 -197
  43. package/dist/lib/signals/steps/types.d.ts +3 -2
  44. package/dist/lib/sync-core/reconcile.d.ts +7 -1
  45. package/dist/lib/sync-core/reconcile.js +105 -18
  46. package/dist/lib/sync-core/release.d.ts +52 -2
  47. package/dist/lib/sync-core/release.js +172 -11
  48. package/dist/lib/sync-core/rollout-state.d.ts +11 -0
  49. package/dist/lib/sync-core/rollout-state.js +16 -0
  50. package/dist/utils/client-health-contract.d.ts +32 -0
  51. package/dist/utils/client-health-contract.js +35 -0
  52. package/dist/utils/client-health.d.ts +43 -0
  53. package/dist/utils/client-health.js +106 -3
  54. package/dist/utils/hook-trust.js +7 -1
  55. package/dist/utils/host-registration.d.ts +12 -35
  56. package/dist/utils/host-registration.js +47 -177
  57. package/dist/utils/login-browser.d.ts +1 -0
  58. package/dist/utils/login-browser.js +31 -6
  59. package/dist/utils/spawn-detached-hidden.d.ts +66 -0
  60. package/dist/utils/spawn-detached-hidden.js +222 -0
  61. package/package.json +7 -7
@@ -57,8 +57,9 @@ export interface StepContext {
57
57
  trigger: string;
58
58
  catchUp: boolean;
59
59
  maxTurns: number;
60
- maxBudgetUsd: number;
61
- /** What a source counts as against the budget when the runtime reports no cost (core/settings/signals.yaml). */
60
+ /** Refreshes the run's company lock. A step calls it only on progress: when an item starts or finishes. Absent on a dry run. */
61
+ heartbeat?: () => void;
62
+ /** What a source adds to the estimated spend when the runtime reports no cost (core/settings/signals.yaml). */
62
63
  unpricedSourceEstimateUsd?: number;
63
64
  now: () => Date;
64
65
  spawn: SpawnSyncFn;
@@ -38,7 +38,8 @@ export interface SyncCoreReconcileDeps {
38
38
  removeStaleLegacyJournalFiles?: Parameters<typeof dropStaleLegacyJournalExport>[2];
39
39
  /** Only desktop and self-hosted machines set up a joined company. */
40
40
  machineType?: MachineType;
41
- ensureBinary: (release: string) => Promise<SyncCoreBinaryInstall>;
41
+ /** `revoked`: withdrawn releases from the server pin; an installed one is replaced even with an older release. */
42
+ ensureBinary: (release: string, revoked?: readonly string[]) => Promise<SyncCoreBinaryInstall>;
42
43
  /** A fixed release (tests). Otherwise readPin decides, then SYNC_CORE_RELEASE. */
43
44
  release?: string;
44
45
  platform?: NodeJS.Platform;
@@ -47,6 +48,11 @@ export interface SyncCoreReconcileDeps {
47
48
  readPin?: () => Promise<SyncCorePin>;
48
49
  now?: () => Date;
49
50
  log?: (line: string) => void;
51
+ /**
52
+ * Log a set of warnings identical to the last reconcile's as one pointer line. For the
53
+ * scheduled daemon run; a person running reconcile by hand sees every warning.
54
+ */
55
+ quietRepeatedWarnings?: boolean;
50
56
  }
51
57
  export interface SyncCoreReconcileResult {
52
58
  state: SyncCoreRolloutState;
@@ -4,7 +4,7 @@ import { readCompaniesManifestMap } from "../work-context/repo-remote.js";
4
4
  import { readVaultSyncSwitches, writeVaultSyncSwitches } from "../vault-sync-switches.js";
5
5
  import { engineOwnsVault } from "./hand-back.js";
6
6
  import { clearEngineStatus, engineFirstCycle, isSyncCoreVaultUid, removeEngineOwnership, syncCoreEngineHome, writeEngineHome, } from "./engine-home.js";
7
- import { SYNC_CORE_FULL_RELEASE, SYNC_CORE_RELEASE, compareSyncCoreReleases, fullModeAllowed, installedSyncCoreRelease, syncCoreBinaryPath, windowsFullRelease, } from "./release.js";
7
+ import { SYNC_CORE_FULL_RELEASE, SYNC_CORE_RELEASE, compareSyncCoreReleases, fullModeAllowed, installedSyncCoreRelease, isRevokedSyncCoreRelease, mergeRevokedSyncCoreReleases, readLastGoodSyncCorePin, syncCoreBinaryPath, windowsFullRelease, writeLastGoodSyncCorePin, } from "./release.js";
8
8
  import { readSyncCoreSkips } from "./skip.js";
9
9
  import { isPersonUid } from "./vault-uid.js";
10
10
  import { isLiveCompanyEntity, joinedCompanySlug, setUpJoinedCompany } from "./company-adoption.js";
@@ -15,6 +15,44 @@ import { readSyncCoreRolloutState, syncCoreRolloutStatePath, writeSyncCoreRollou
15
15
  function message(error) {
16
16
  return error instanceof Error ? error.message : String(error);
17
17
  }
18
+ /**
19
+ * Applies the last pin read successfully on this computer. A good server pin is stored. When
20
+ * pin.json cannot be read, the stored pin decides the release and its revoked list still
21
+ * applies; with no stored pin nothing is installed or upgraded. A revoked list is never lost
22
+ * to a failed read, so a revoked built-in release is not installed during an outage.
23
+ */
24
+ function resolvePin(deps, served, warnings) {
25
+ if (served.warning)
26
+ warnings.push(served.warning);
27
+ if (served.source === "server") {
28
+ let pin = served;
29
+ if (served.unknownKeys?.length) {
30
+ // The served release always wins: a release the operator pins is never kept revoked.
31
+ const stored = readLastGoodSyncCorePin(deps.home, (line) => warnings.push(line), served.base);
32
+ const revoked = mergeRevokedSyncCoreReleases(served.revoked, stored?.revoked)
33
+ .filter((entry) => !isRevokedSyncCoreRelease(served.release, [entry]));
34
+ pin = { ...served, ...(revoked.length > 0 ? { revoked } : {}) };
35
+ }
36
+ try {
37
+ writeLastGoodSyncCorePin(deps.home, pin);
38
+ }
39
+ catch (error) {
40
+ warnings.push(`could not store the engine pin on this computer: ${message(error)}`);
41
+ }
42
+ return pin;
43
+ }
44
+ const last = readLastGoodSyncCorePin(deps.home, (line) => warnings.push(line), served.base);
45
+ const revoked = mergeRevokedSyncCoreReleases(last?.revoked, served.revoked);
46
+ const withRevoked = revoked.length > 0 ? { revoked } : {};
47
+ if (!served.unreadable)
48
+ return { ...served, ...withRevoked };
49
+ if (last) {
50
+ warnings.push(`using the engine pin last read on this computer (${last.release})`);
51
+ return { release: last.release, source: "last-good", ...withRevoked };
52
+ }
53
+ warnings.push("no engine pin has been read on this computer yet, so no engine is installed or upgraded until it can be read");
54
+ return { ...served, ...withRevoked, noInstall: true };
55
+ }
18
56
  /** The old sync reads a `.hqinclude` allowlist at the HQ root; the engine does not, so it would upload everything in scope. */
19
57
  const HQINCLUDE_HOLD = "hqinclude-unsupported: this HQ folder has a .hqinclude allowlist, which the new sync engine does not support yet; staying on the current sync";
20
58
  export function fullModeHold(vault, release, platform = process.platform, env = process.env) {
@@ -260,29 +298,66 @@ export async function reconcileSyncCore(deps) {
260
298
  held.push({ uid: vault.uid, reason: HQINCLUDE_HOLD });
261
299
  desired.length = 0;
262
300
  }
301
+ let pin;
302
+ let binaryOutcome = "not_needed";
263
303
  if (desired.length > 0) {
304
+ let revoked;
305
+ let installAllowed = true;
306
+ if (deps.release === undefined)
307
+ pin = { release, source: "built-in" };
264
308
  if (deps.release === undefined && deps.readPin) {
265
- const pin = await deps.readPin();
266
- release = pin.release;
267
- if (pin.warning)
268
- warnings.push(pin.warning);
269
- if (pin.source === "server" && installedRelease && compareSyncCoreReleases(pin.release, installedRelease) < 0) {
309
+ const resolved = resolvePin(deps, await deps.readPin(), warnings);
310
+ pin = { release: resolved.release, source: resolved.source };
311
+ release = resolved.release;
312
+ revoked = resolved.revoked;
313
+ installAllowed = !resolved.noInstall;
314
+ if (!installAllowed) {
315
+ // Nothing is installed or upgraded without a pin that has been read, so a
316
+ // revoked built-in release is never installed during a pin outage.
317
+ }
318
+ else if (isRevokedSyncCoreRelease(installedRelease, revoked)) {
319
+ log(`the server revoked the installed hq-syncd ${installedRelease}; installing ${resolved.release} to replace it`);
320
+ }
321
+ else if (resolved.source !== "built-in" && installedRelease && compareSyncCoreReleases(resolved.release, installedRelease) < 0) {
270
322
  // The no-downgrade guard in ensureSyncCoreBinary keeps the newer engine.
271
- log(`the server pins hq-syncd ${pin.release}, older than the installed ${installedRelease}; keeping ${installedRelease}`);
323
+ log(`the server pins hq-syncd ${resolved.release}, older than the installed ${installedRelease}; keeping ${installedRelease}`);
272
324
  }
273
325
  }
274
- try {
275
- const install = await deps.ensureBinary(release);
276
- binaryPath = install.binaryPath;
277
- installedRelease = install.release;
278
- if (install.installed)
279
- log(`installed hq-syncd ${install.release} at ${install.binaryPath}`);
326
+ const keptRevoked = isRevokedSyncCoreRelease(installedRelease, revoked);
327
+ const keeping = installedRelease
328
+ ? `keeping ${keptRevoked ? "the revoked " : ""}hq-syncd ${installedRelease}${keptRevoked ? " until its replacement installs" : ""}`
329
+ : null;
330
+ if (!installAllowed) {
331
+ binaryOutcome = "pin_unreadable";
332
+ if (keptRevoked && keeping)
333
+ warnings.push(keeping);
334
+ if (!installedRelease)
335
+ desired.length = 0;
280
336
  }
281
- catch (error) {
282
- warnings.push(`${message(error)}; ${installedRelease ? `keeping hq-syncd ${installedRelease}` : "no vault moves until the engine download succeeds"}`);
337
+ else if (isRevokedSyncCoreRelease(release, revoked)) {
338
+ binaryOutcome = "revoked_refused";
339
+ warnings.push(`hq-syncd ${release} is revoked, so it is not installed; ${keeping ?? "no vault moves until a release that is not revoked is pinned"}`);
283
340
  if (!installedRelease)
284
341
  desired.length = 0;
285
342
  }
343
+ else {
344
+ try {
345
+ const install = await deps.ensureBinary(release, revoked);
346
+ binaryPath = install.binaryPath;
347
+ installedRelease = install.release;
348
+ binaryOutcome = install.installed
349
+ ? "installed"
350
+ : compareSyncCoreReleases(install.release, release) > 0 ? "kept_newer" : "current";
351
+ if (install.installed)
352
+ log(`installed hq-syncd ${install.release} at ${install.binaryPath}`);
353
+ }
354
+ catch (error) {
355
+ binaryOutcome = "install_failed";
356
+ warnings.push(`${message(error)}; ${keeping ?? "no vault moves until the engine download succeeds"}`);
357
+ if (!installedRelease)
358
+ desired.length = 0;
359
+ }
360
+ }
286
361
  }
287
362
  const engineRelease = installedRelease ?? release;
288
363
  for (let i = desired.length - 1; i >= 0; i -= 1) {
@@ -453,9 +528,12 @@ export async function reconcileSyncCore(deps) {
453
528
  ...(handingBack.length > 0 ? { handingBack } : {}),
454
529
  ...(skipped.length > 0 ? { skipped } : {}),
455
530
  ...(held.length > 0 ? { held } : {}),
456
- ...(warnings.length > 0 ? { error: warnings.join("; ") } : {}),
531
+ ...(warnings.length > 0 ? { error: warnings.join("; "), warnings: warnings.length } : {}),
532
+ ...(pin ? { pin } : {}),
533
+ binaryOutcome,
457
534
  };
458
535
  writeSyncCoreRolloutState(deps.home, state);
536
+ const warningsWritten = warnings.length;
459
537
  for (const uid of stopped) {
460
538
  if (handedBack.some((vault) => vault.uid === uid))
461
539
  continue;
@@ -474,7 +552,10 @@ export async function reconcileSyncCore(deps) {
474
552
  }
475
553
  catch (error) {
476
554
  warnings.push(`could not update the sync switches: ${message(error)}`);
555
+ }
556
+ if (warnings.length !== warningsWritten) {
477
557
  state.error = warnings.join("; ");
558
+ state.warnings = warnings.length;
478
559
  writeSyncCoreRolloutState(deps.home, state);
479
560
  }
480
561
  for (const uid of started)
@@ -492,8 +573,14 @@ export async function reconcileSyncCore(deps) {
492
573
  log(`${skip.uid}: skipped on this machine: ${skip.reason}`);
493
574
  for (const hold of held)
494
575
  log(`${hold.uid}: ${hold.reason}`);
495
- for (const warning of warnings)
496
- log(`warning: ${warning}`);
576
+ // The rollout state carries every warning on each run; the log repeats them only when they change.
577
+ if (deps.quietRepeatedWarnings && warnings.length > 0 && state.error !== undefined && state.error === previous?.error) {
578
+ log(`warning: the same ${warnings.length === 1 ? "warning" : `${warnings.length} warnings`} as the last reconcile; see ${syncCoreRolloutStatePath(deps.home)}`);
579
+ }
580
+ else {
581
+ for (const warning of warnings)
582
+ log(`warning: ${warning}`);
583
+ }
497
584
  return { state, started, promoted, stopped, kept, warnings };
498
585
  }
499
586
  //# sourceMappingURL=reconcile.js.map
@@ -18,11 +18,59 @@ export declare const SYNC_CORE_PIN_FILE = "pin.json";
18
18
  export interface SyncCorePin {
19
19
  /** The engine release machines should run. */
20
20
  release: string;
21
- /** "server": read from pin.json; "built-in": SYNC_CORE_RELEASE, because no server pin could be used. */
22
- source: "server" | "built-in";
21
+ /**
22
+ * "server": read from pin.json now. "last-good": the pin read successfully last time on this
23
+ * computer, used because pin.json could not be read now. "built-in": SYNC_CORE_RELEASE.
24
+ */
25
+ source: "server" | "built-in" | "last-good";
23
26
  /** Why the server pin was not used, when it exists but could not be read. A missing pin.json sets none. */
24
27
  warning?: string;
28
+ /**
29
+ * Withdrawn engine releases (`"revoked": ["v0.1.42"]` in pin.json). An installed
30
+ * one is replaced with `release` even when `release` is older.
31
+ */
32
+ revoked?: string[];
33
+ /**
34
+ * pin.json exists but could not be used: network error, HTTP error, not JSON, no valid
35
+ * release, a `revoked` that is not a list, or a release it also revokes. The caller
36
+ * falls back to the last good pin and never installs past it. On the default download base
37
+ * a missing pin.json (403/404) counts as unreadable too: the pin is published there, so its
38
+ * absence is an outage, not "no pin".
39
+ */
40
+ unreadable?: boolean;
41
+ /** The download base the pin was read from; the stored last good pin is kept per base. */
42
+ base?: string;
43
+ /**
44
+ * pin.json had keys other than "release" and "revoked" (for example a misspelled "revoke").
45
+ * The stored revoked list is then kept, so a typo cannot drop a revocation.
46
+ */
47
+ unknownKeys?: string[];
25
48
  }
49
+ /** Whether `base` is the production download base: https only, ignoring host case and trailing slashes. */
50
+ export declare function isProductionSyncCoreBase(base: string): boolean;
51
+ /** "v0.1.42" or "0.1.42" as "v0.1.42"; null for anything else. */
52
+ export declare function normalizeSyncCoreRelease(release: string): string | null;
53
+ export declare function isRevokedSyncCoreRelease(release: string | null | undefined, revoked: readonly string[] | undefined): boolean;
54
+ export declare function mergeRevokedSyncCoreReleases(...lists: (readonly string[] | undefined)[]): string[];
55
+ /**
56
+ * The last pin read successfully on this computer from `base`, kept for when pin.json cannot be
57
+ * read. Each download base has its own file, so a test mirror never overwrites the production pin.
58
+ */
59
+ export declare function syncCoreLastGoodPinPath(home?: string, base?: string): string;
60
+ export interface LastGoodSyncCorePin {
61
+ release: string;
62
+ revoked: string[];
63
+ /** The download base it was read from; absent in a file written before bases were recorded. */
64
+ base?: string;
65
+ }
66
+ /** The pin stored for `base` (the production base when omitted), or null with a warning when unusable. */
67
+ export declare function readLastGoodSyncCorePin(home: string, warn?: (line: string) => void, base?: string): LastGoodSyncCorePin | null;
68
+ /** Stores `pin` for its base. A release is never stored as revoked by its own pin. */
69
+ export declare function writeLastGoodSyncCorePin(home: string, pin: {
70
+ release: string;
71
+ revoked?: readonly string[];
72
+ base?: string;
73
+ }): void;
26
74
  /**
27
75
  * The engine release to install, read from `<download base>/pin.json`
28
76
  * (`{"release":"v0.1.24"}`), so an engine release reaches machines without an
@@ -49,6 +97,8 @@ export interface EnsureSyncCoreBinaryOptions {
49
97
  platform: NodeJS.Platform;
50
98
  arch: string;
51
99
  release?: string;
100
+ /** Withdrawn releases: an installed one is replaced with `release` even when `release` is older. */
101
+ revoked?: readonly string[];
52
102
  baseUrl?: string;
53
103
  env?: NodeJS.ProcessEnv;
54
104
  fetch?: typeof fetch;
@@ -33,6 +33,105 @@ const DOWNLOAD_TIMEOUT_MS = 600_000;
33
33
  export const SYNC_CORE_PIN_FILE = "pin.json";
34
34
  const PIN_TIMEOUT_MS = 10_000;
35
35
  const RELEASE_PATTERN = /^v\d+\.\d+\.\d+$/;
36
+ const PIN_KEYS = new Set(["release", "revoked"]);
37
+ /**
38
+ * Keys an operator may add for people (a note, a timestamp, a schema link) without changing how
39
+ * the pin is read. Any other unknown key, such as a misspelled "revoke", makes the client keep its
40
+ * stored revoked list.
41
+ */
42
+ const IGNORED_PIN_KEY = /^(?:_.*|\$schema|notes?|comments?|description|reason|updated(?:_?at)?|updatedAt|author)$/i;
43
+ /** A key that looks like a revoked list (for example "_revoked" or "revoke") is never ignored. */
44
+ function ignoredPinKey(key) {
45
+ return IGNORED_PIN_KEY.test(key) && !/revok/i.test(key);
46
+ }
47
+ function comparableBase(base) {
48
+ try {
49
+ const url = new URL(base);
50
+ return `${url.host.toLowerCase()}${url.pathname.replace(/\/+$/, "")}`;
51
+ }
52
+ catch {
53
+ return base.trim().replace(/\/+$/, "").toLowerCase();
54
+ }
55
+ }
56
+ /** Whether `base` is the production download base: https only, ignoring host case and trailing slashes. */
57
+ export function isProductionSyncCoreBase(base) {
58
+ try {
59
+ if (new URL(base).protocol !== "https:")
60
+ return false;
61
+ }
62
+ catch {
63
+ return false;
64
+ }
65
+ return comparableBase(base) === comparableBase(SYNC_CORE_DOWNLOAD_BASE);
66
+ }
67
+ const LOOSE_RELEASE_PATTERN = /^v?(\d+\.\d+\.\d+)$/;
68
+ /** "v0.1.42" or "0.1.42" as "v0.1.42"; null for anything else. */
69
+ export function normalizeSyncCoreRelease(release) {
70
+ const match = LOOSE_RELEASE_PATTERN.exec(release.trim());
71
+ return match ? `v${match[1]}` : null;
72
+ }
73
+ export function isRevokedSyncCoreRelease(release, revoked) {
74
+ if (!release || !revoked?.length)
75
+ return false;
76
+ const exact = normalizeSyncCoreRelease(release);
77
+ return exact !== null && revoked.some((entry) => normalizeSyncCoreRelease(entry) === exact);
78
+ }
79
+ export function mergeRevokedSyncCoreReleases(...lists) {
80
+ return [...new Set(lists.flatMap((list) => list ?? []))];
81
+ }
82
+ /**
83
+ * The last pin read successfully on this computer from `base`, kept for when pin.json cannot be
84
+ * read. Each download base has its own file, so a test mirror never overwrites the production pin.
85
+ */
86
+ export function syncCoreLastGoodPinPath(home = os.homedir(), base = SYNC_CORE_DOWNLOAD_BASE) {
87
+ const dir = path.join(home, ".hq", "sync-core");
88
+ if (isProductionSyncCoreBase(base))
89
+ return path.join(dir, "pin-last-good.json");
90
+ const key = crypto.createHash("sha256").update(comparableBase(base)).digest("hex").slice(0, 16);
91
+ return path.join(dir, `pin-last-good-${key}.json`);
92
+ }
93
+ /** The pin stored for `base` (the production base when omitted), or null with a warning when unusable. */
94
+ export function readLastGoodSyncCorePin(home, warn = () => { }, base = SYNC_CORE_DOWNLOAD_BASE) {
95
+ const file = syncCoreLastGoodPinPath(home, base);
96
+ if (!fs.existsSync(file))
97
+ return null;
98
+ try {
99
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
100
+ const release = typeof parsed.release === "string" ? normalizeSyncCoreRelease(parsed.release) : null;
101
+ if (!release) {
102
+ warn(`the last good engine pin ${file} has no valid release; ignoring it`);
103
+ return null;
104
+ }
105
+ const storedBase = typeof parsed.base === "string" ? parsed.base : SYNC_CORE_DOWNLOAD_BASE;
106
+ if (comparableBase(storedBase) !== comparableBase(base)) {
107
+ warn(`the last good engine pin ${file} was read from ${storedBase}, not ${base}; ignoring it`);
108
+ return null;
109
+ }
110
+ const revoked = Array.isArray(parsed.revoked)
111
+ ? parsed.revoked.flatMap((entry) => (typeof entry === "string" ? [normalizeSyncCoreRelease(entry)].filter((value) => value !== null) : []))
112
+ : [];
113
+ return { release, revoked: revoked.filter((entry) => entry !== release), base: storedBase };
114
+ }
115
+ catch (error) {
116
+ warn(`could not read the last good engine pin ${file}: ${error instanceof Error ? error.message : String(error)}; ignoring it`);
117
+ return null;
118
+ }
119
+ }
120
+ /** Stores `pin` for its base. A release is never stored as revoked by its own pin. */
121
+ export function writeLastGoodSyncCorePin(home, pin) {
122
+ const base = pin.base ?? SYNC_CORE_DOWNLOAD_BASE;
123
+ const file = syncCoreLastGoodPinPath(home, base);
124
+ fs.mkdirSync(path.dirname(file), { recursive: true });
125
+ const tmp = `${file}.${process.pid}.tmp`;
126
+ const revoked = [...(pin.revoked ?? [])].filter((entry) => !isRevokedSyncCoreRelease(pin.release, [entry]));
127
+ try {
128
+ fs.writeFileSync(tmp, `${JSON.stringify({ release: pin.release, revoked, base })}\n`, { mode: 0o600 });
129
+ fs.renameSync(tmp, file);
130
+ }
131
+ finally {
132
+ fs.rmSync(tmp, { force: true });
133
+ }
134
+ }
36
135
  /**
37
136
  * The engine release to install, read from `<download base>/pin.json`
38
137
  * (`{"release":"v0.1.24"}`), so an engine release reaches machines without an
@@ -41,32 +140,88 @@ const RELEASE_PATTERN = /^v\d+\.\d+\.\d+$/;
41
140
  * Windows the release gate (fullModeAllowed) still decides whether it installs.
42
141
  */
43
142
  export async function readSyncCorePin(opts = {}) {
44
- const builtIn = (warning) => ({ release: SYNC_CORE_RELEASE, source: "built-in", ...(warning ? { warning } : {}) });
45
- const url = `${opts.baseUrl?.replace(/\/+$/, "") ?? syncCoreDownloadBase(opts.env)}/${SYNC_CORE_PIN_FILE}`;
143
+ const base = opts.baseUrl?.replace(/\/+$/, "") ?? syncCoreDownloadBase(opts.env);
144
+ const unreadable = (warning, revoked = []) => ({
145
+ release: SYNC_CORE_RELEASE,
146
+ source: "built-in",
147
+ warning,
148
+ unreadable: true,
149
+ base,
150
+ ...(revoked.length > 0 ? { revoked } : {}),
151
+ });
152
+ const url = `${base}/${SYNC_CORE_PIN_FILE}`;
46
153
  let response;
47
154
  try {
48
155
  response = await (opts.fetch ?? fetch)(url, { signal: AbortSignal.timeout(opts.timeoutMs ?? PIN_TIMEOUT_MS) });
49
156
  }
50
157
  catch (error) {
51
- return builtIn(`could not read the engine pin ${url}: ${error instanceof Error ? error.message : String(error)}; using built-in ${SYNC_CORE_RELEASE}`);
158
+ return unreadable(`could not read the engine pin ${url}: ${error instanceof Error ? error.message : String(error)}`);
52
159
  }
53
160
  // S3 answers 403 for a missing key on a bucket without public listing.
54
- if (response.status === 404 || response.status === 403)
55
- return builtIn();
161
+ if (response.status === 404 || response.status === 403) {
162
+ // The production base publishes a pin, so a missing one there is an outage. Another base
163
+ // (a test mirror) may have none, and then the built-in release is used.
164
+ if (isProductionSyncCoreBase(base))
165
+ return unreadable(`the engine pin ${url} is missing (HTTP ${response.status})`);
166
+ return { release: SYNC_CORE_RELEASE, source: "built-in", base };
167
+ }
56
168
  if (!response.ok)
57
- return builtIn(`could not read the engine pin ${url}: HTTP ${response.status}; using built-in ${SYNC_CORE_RELEASE}`);
169
+ return unreadable(`could not read the engine pin ${url}: HTTP ${response.status}`);
58
170
  let parsed;
59
171
  try {
60
172
  parsed = JSON.parse(await response.text());
61
173
  }
62
174
  catch {
63
- return builtIn(`the engine pin ${url} is not JSON; using built-in ${SYNC_CORE_RELEASE}`);
175
+ return unreadable(`the engine pin ${url} is not JSON`);
64
176
  }
65
- const release = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed.release : undefined;
177
+ const body = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : undefined;
178
+ const unknownKeys = body ? Object.keys(body).filter((key) => !PIN_KEYS.has(key) && !ignoredPinKey(key)) : [];
179
+ const rawRevoked = body?.revoked;
180
+ if (rawRevoked !== undefined && !Array.isArray(rawRevoked)) {
181
+ return unreadable(`the engine pin ${url} has a "revoked" that is not a list of releases`);
182
+ }
183
+ const revoked = [];
184
+ const invalid = [];
185
+ for (const entry of rawRevoked ?? []) {
186
+ const normalized = typeof entry === "string" ? normalizeSyncCoreRelease(entry) : null;
187
+ if (normalized) {
188
+ if (!revoked.includes(normalized))
189
+ revoked.push(normalized);
190
+ }
191
+ else {
192
+ invalid.push(JSON.stringify(entry));
193
+ }
194
+ }
195
+ const release = body?.release;
66
196
  if (typeof release !== "string" || !RELEASE_PATTERN.test(release)) {
67
- return builtIn(`the engine pin ${url} has no valid "release" (want vX.Y.Z); using built-in ${SYNC_CORE_RELEASE}`);
197
+ return unreadable(`the engine pin ${url} has no valid "release" (want vX.Y.Z)`, revoked);
198
+ }
199
+ if (isRevokedSyncCoreRelease(release, revoked)) {
200
+ return unreadable(`the engine pin ${url} pins ${release}, which it also lists as revoked`, revoked);
68
201
  }
69
- return { release, source: "server" };
202
+ const revokingKey = unknownKeys.find((key) => {
203
+ const value = body?.[key];
204
+ return /revok/i.test(key)
205
+ && Array.isArray(value)
206
+ && value.some((entry) => typeof entry === "string" && isRevokedSyncCoreRelease(release, [entry]));
207
+ });
208
+ if (revokingKey !== undefined) {
209
+ return unreadable(`the engine pin ${url} pins ${release}, which its key ${JSON.stringify(revokingKey)} also lists`, revoked);
210
+ }
211
+ const problems = [
212
+ ...(invalid.length > 0 ? [`lists revoked entries that are not releases (want vX.Y.Z), ignored: ${invalid.join(", ")}`] : []),
213
+ ...(unknownKeys.length > 0
214
+ ? [`has keys it does not know (${unknownKeys.map((key) => JSON.stringify(key)).join(", ")}; want "release" and "revoked"), so the revoked list stored on this computer is kept`]
215
+ : []),
216
+ ];
217
+ return {
218
+ release,
219
+ source: "server",
220
+ base,
221
+ ...(revoked.length > 0 ? { revoked } : {}),
222
+ ...(unknownKeys.length > 0 ? { unknownKeys } : {}),
223
+ ...(problems.length > 0 ? { warning: `the engine pin ${url} ${problems.join("; and ")}` } : {}),
224
+ };
70
225
  }
71
226
  export function syncCoreBinaryName(platform = process.platform) {
72
227
  return platform === "win32" ? "hq-syncd.exe" : "hq-syncd";
@@ -179,7 +334,13 @@ export async function ensureSyncCoreBinary(opts) {
179
334
  const release = opts.release ?? SYNC_CORE_RELEASE;
180
335
  const binaryPath = syncCoreBinaryPath(opts.home, opts.platform);
181
336
  const installedRelease = installedSyncCoreRelease(opts.home, opts.platform);
182
- if (installedRelease && compareSyncCoreReleases(installedRelease, release) >= 0 && fs.existsSync(binaryPath)) {
337
+ if (isRevokedSyncCoreRelease(release, opts.revoked)) {
338
+ throw new SyncCoreReleaseError(`the sync engine ${release} is revoked; not installing it`);
339
+ }
340
+ if (installedRelease
341
+ && !isRevokedSyncCoreRelease(installedRelease, opts.revoked)
342
+ && compareSyncCoreReleases(installedRelease, release) >= 0
343
+ && fs.existsSync(binaryPath)) {
183
344
  const marker = syncCoreReleaseMarkerPath(opts.home);
184
345
  let current = "";
185
346
  try {
@@ -29,7 +29,18 @@ export interface SyncCoreRolloutState {
29
29
  reason: string;
30
30
  }[];
31
31
  error?: string;
32
+ /** The engine release this reconcile asked for, and where that came from. */
33
+ pin?: {
34
+ release: string;
35
+ source: "server" | "built-in" | "last-good";
36
+ };
37
+ /** What this reconcile did with the engine binary (see SyncCoreBinaryOutcome). */
38
+ binaryOutcome?: SyncCoreBinaryOutcome;
39
+ /** How many warnings this reconcile recorded in `error`. */
40
+ warnings?: number;
32
41
  }
42
+ export declare const SYNC_CORE_BINARY_OUTCOMES: readonly ["current", "installed", "kept_newer", "install_failed", "pin_unreadable", "revoked_refused", "not_needed"];
43
+ export type SyncCoreBinaryOutcome = (typeof SYNC_CORE_BINARY_OUTCOMES)[number];
33
44
  export declare function syncCoreRolloutStatePath(home: string): string;
34
45
  type RolloutStateFailure = "is unreadable" | "contains invalid JSON" | "has an invalid format" | "has an unsupported version";
35
46
  export declare class SyncCoreRolloutStateError extends Error {
@@ -26,6 +26,17 @@ function firstCycle(value) {
26
26
  const counts = Object.fromEntries(FIRST_CYCLE_COUNTS.map((key) => [key, c[key]]));
27
27
  return { at: c.at, ...counts, truncated: c.truncated };
28
28
  }
29
+ export const SYNC_CORE_BINARY_OUTCOMES = ["current", "installed", "kept_newer", "install_failed", "pin_unreadable", "revoked_refused", "not_needed"];
30
+ function pinEntry(value) {
31
+ if (!value || typeof value !== "object" || Array.isArray(value))
32
+ return undefined;
33
+ const v = value;
34
+ if (typeof v.release !== "string" || !/^v\d+\.\d+\.\d+$/.test(v.release))
35
+ return undefined;
36
+ if (v.source !== "server" && v.source !== "built-in" && v.source !== "last-good")
37
+ return undefined;
38
+ return { release: v.release, source: v.source };
39
+ }
29
40
  function skippedEntries(value) {
30
41
  if (value === undefined)
31
42
  return [];
@@ -157,6 +168,11 @@ function parseRolloutState(raw) {
157
168
  ...(skipped.length > 0 ? { skipped } : {}),
158
169
  ...(held.length > 0 ? { held } : {}),
159
170
  ...(typeof obj.error === "string" ? { error: obj.error } : {}),
171
+ ...(pinEntry(obj.pin) ? { pin: pinEntry(obj.pin) } : {}),
172
+ ...(SYNC_CORE_BINARY_OUTCOMES.includes(obj.binaryOutcome)
173
+ ? { binaryOutcome: obj.binaryOutcome }
174
+ : {}),
175
+ ...(typeof obj.warnings === "number" && Number.isSafeInteger(obj.warnings) && obj.warnings >= 0 ? { warnings: obj.warnings } : {}),
160
176
  };
161
177
  }
162
178
  export function writeSyncCoreRolloutState(home, state) {
@@ -59,6 +59,20 @@ export type ClientHealthSyncRunnerSource = (typeof CLIENT_HEALTH_SYNC_RUNNER_SOU
59
59
  export declare const CLIENT_HEALTH_DAEMON_HQ_CLOUD_UPDATE_OUTCOMES: readonly ["updated", "up_to_date", "pinned", "failed"];
60
60
  export declare const CLIENT_HEALTH_SYNC_ENGINES: readonly ["hq-syncd"];
61
61
  export type ClientHealthSyncEngine = (typeof CLIENT_HEALTH_SYNC_ENGINES)[number];
62
+ export declare const CLIENT_HEALTH_SYNC_ENGINE_PIN_SOURCES: readonly ["server", "built-in", "last-good"];
63
+ export type ClientHealthSyncEnginePinSource = (typeof CLIENT_HEALTH_SYNC_ENGINE_PIN_SOURCES)[number];
64
+ /**
65
+ * What the last sync-core reconcile did with the engine binary. `current`: the
66
+ * installed engine is the pinned one. `installed`: it installed the pinned one.
67
+ * `kept_newer`: it kept an installed engine newer than the pin. `install_failed`:
68
+ * it could not install the pinned engine. `pin_unreadable`: pin.json could not be read and
69
+ * no pin was stored, so nothing was installed. `revoked_refused`: the release it would
70
+ * install is revoked, so it installed nothing. `not_needed`: no vault was on the
71
+ * engine, so it did not look.
72
+ */
73
+ export declare const CLIENT_HEALTH_SYNC_ENGINE_RECONCILE_OUTCOMES: readonly ["current", "installed", "kept_newer", "install_failed", "pin_unreadable", "revoked_refused", "not_needed"];
74
+ export type ClientHealthSyncEngineReconcileOutcome = (typeof CLIENT_HEALTH_SYNC_ENGINE_RECONCILE_OUTCOMES)[number];
75
+ export declare const CLIENT_HEALTH_MAX_RECONCILE_WARNINGS = 100;
62
76
  export declare const CLIENT_HEALTH_MAX_SYNC_ENGINE_VAULTS = 10000;
63
77
  export declare const CLIENT_HEALTH_SYNC_ENGINE_OWNERS: readonly ["engine", "legacy"];
64
78
  export type ClientHealthSyncEngineOwner = (typeof CLIENT_HEALTH_SYNC_ENGINE_OWNERS)[number];
@@ -188,6 +202,24 @@ export interface ClientHealthHeartbeat {
188
202
  daemonHqCloudUpdateTarget?: string;
189
203
  daemonHqCloudUpdateErrorClass?: ClientHealthDaemonHqCloudUpdateErrorClass;
190
204
  daemonCliVersion?: string;
205
+ /** When the running daemon process started (its state file); absent with no live daemon. */
206
+ daemonStartedAt?: string;
207
+ /** True when an app (the desktop app) runs the daemon as its child rather than the OS service manager. */
208
+ daemonHosted?: boolean;
209
+ /**
210
+ * The hq-cli version of a process the daemon started (a daemon unit), sent only
211
+ * by such a process. Newer than `daemonCliVersion` means the daemon runs older
212
+ * code than the CLI its units load.
213
+ */
214
+ daemonUnitCliVersion?: string;
215
+ /** The engine release the last reconcile asked for (server pin or built-in fallback). */
216
+ syncEnginePinned?: string;
217
+ syncEnginePinSource?: ClientHealthSyncEnginePinSource;
218
+ /** When the last sync-core reconcile wrote its state. */
219
+ syncEngineReconcileAt?: string;
220
+ syncEngineReconcileOutcome?: ClientHealthSyncEngineReconcileOutcome;
221
+ /** How many warnings the last reconcile recorded (their text stays on the machine). */
222
+ syncEngineReconcileWarnings?: number;
191
223
  /** Absent on older clients / non-sync-outcome events. See {@link ClientHealthLocalFilesOverview}. */
192
224
  localFilesOverview?: ClientHealthLocalFilesOverview;
193
225
  }
@@ -80,6 +80,26 @@ export const CLIENT_HEALTH_DAEMON_HQ_CLOUD_UPDATE_OUTCOMES = [
80
80
  "failed",
81
81
  ];
82
82
  export const CLIENT_HEALTH_SYNC_ENGINES = ["hq-syncd"];
83
+ export const CLIENT_HEALTH_SYNC_ENGINE_PIN_SOURCES = ["server", "built-in", "last-good"];
84
+ /**
85
+ * What the last sync-core reconcile did with the engine binary. `current`: the
86
+ * installed engine is the pinned one. `installed`: it installed the pinned one.
87
+ * `kept_newer`: it kept an installed engine newer than the pin. `install_failed`:
88
+ * it could not install the pinned engine. `pin_unreadable`: pin.json could not be read and
89
+ * no pin was stored, so nothing was installed. `revoked_refused`: the release it would
90
+ * install is revoked, so it installed nothing. `not_needed`: no vault was on the
91
+ * engine, so it did not look.
92
+ */
93
+ export const CLIENT_HEALTH_SYNC_ENGINE_RECONCILE_OUTCOMES = [
94
+ "current",
95
+ "installed",
96
+ "kept_newer",
97
+ "install_failed",
98
+ "pin_unreadable",
99
+ "revoked_refused",
100
+ "not_needed",
101
+ ];
102
+ export const CLIENT_HEALTH_MAX_RECONCILE_WARNINGS = 100;
83
103
  export const CLIENT_HEALTH_MAX_SYNC_ENGINE_VAULTS = 10_000;
84
104
  export const CLIENT_HEALTH_SYNC_ENGINE_OWNERS = ["engine", "legacy"];
85
105
  export const CLIENT_HEALTH_SYNC_ENGINE_HOLD_KINDS = ["delete_local", "delete_remote", "overwrite_local"];
@@ -355,6 +375,21 @@ export function parseClientHealthHeartbeat(input) {
355
375
  if (daemonCliVersion !== undefined)
356
376
  heartbeat.daemonCliVersion = daemonCliVersion;
357
377
  }
378
+ const optionalDiagnostic = (field, validate) => {
379
+ if (raw[field] === undefined)
380
+ return;
381
+ const value = copyValidOptionalDiagnostic(field, raw[field], validate);
382
+ if (value !== undefined)
383
+ heartbeat[field] = value;
384
+ };
385
+ optionalDiagnostic("daemonStartedAt", assertIsoUtc);
386
+ optionalDiagnostic("daemonHosted", assertBoolean);
387
+ optionalDiagnostic("daemonUnitCliVersion", assertVersion);
388
+ optionalDiagnostic("syncEnginePinned", assertVersion);
389
+ copyKnownOptionalEnum(heartbeat, "syncEnginePinSource", raw.syncEnginePinSource, CLIENT_HEALTH_SYNC_ENGINE_PIN_SOURCES);
390
+ optionalDiagnostic("syncEngineReconcileAt", assertIsoUtc);
391
+ copyKnownOptionalEnum(heartbeat, "syncEngineReconcileOutcome", raw.syncEngineReconcileOutcome, CLIENT_HEALTH_SYNC_ENGINE_RECONCILE_OUTCOMES);
392
+ optionalDiagnostic("syncEngineReconcileWarnings", (name, value) => assertBoundedInt(name, value, CLIENT_HEALTH_MAX_RECONCILE_WARNINGS));
358
393
  if (raw.localFilesOverview !== undefined) {
359
394
  heartbeat.localFilesOverview = parseClientHealthLocalFilesOverview("localFilesOverview", raw.localFilesOverview);
360
395
  }