@indigoai-us/hq-cli 5.345.270 → 5.345.273

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 (54) hide show
  1. package/CHANGELOG.md +64 -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/merge-sections.d.ts +24 -1
  19. package/dist/lib/daemon/merge-sections.js +59 -11
  20. package/dist/lib/daemon/run.d.ts +1 -1
  21. package/dist/lib/daemon/run.js +67 -53
  22. package/dist/lib/daemon/supervisor.js +0 -2
  23. package/dist/lib/hook-engine/coverage.d.ts +21 -0
  24. package/dist/lib/hook-engine/coverage.js +98 -5
  25. package/dist/lib/hook-engine/native-precompact-compatibility.json +1 -0
  26. package/dist/lib/hook-engine/native-stop-compatibility.json +2 -1
  27. package/dist/lib/hot-channels/signals-pass.d.ts +10 -2
  28. package/dist/lib/hot-channels/signals-pass.js +13 -3
  29. package/dist/lib/signals/engine.d.ts +0 -2
  30. package/dist/lib/signals/engine.js +12 -7
  31. package/dist/lib/signals/reply.js +35 -82
  32. package/dist/lib/signals/run-lock.d.ts +8 -0
  33. package/dist/lib/signals/run-lock.js +42 -7
  34. package/dist/lib/signals/run-record.js +2 -1
  35. package/dist/lib/signals/settings.d.ts +9 -4
  36. package/dist/lib/signals/settings.js +7 -5
  37. package/dist/lib/signals/steps/extract.d.ts +37 -10
  38. package/dist/lib/signals/steps/extract.js +88 -111
  39. package/dist/lib/signals/steps/types.d.ts +3 -2
  40. package/dist/lib/sync-core/reconcile.d.ts +7 -1
  41. package/dist/lib/sync-core/reconcile.js +105 -18
  42. package/dist/lib/sync-core/release.d.ts +52 -2
  43. package/dist/lib/sync-core/release.js +172 -11
  44. package/dist/lib/sync-core/rollout-state.d.ts +11 -0
  45. package/dist/lib/sync-core/rollout-state.js +16 -0
  46. package/dist/utils/client-health-contract.d.ts +32 -0
  47. package/dist/utils/client-health-contract.js +35 -0
  48. package/dist/utils/client-health.d.ts +43 -0
  49. package/dist/utils/client-health.js +106 -3
  50. package/dist/utils/login-browser.d.ts +1 -0
  51. package/dist/utils/login-browser.js +31 -6
  52. package/dist/utils/spawn-detached-hidden.d.ts +66 -0
  53. package/dist/utils/spawn-detached-hidden.js +222 -0
  54. package/package.json +7 -7
@@ -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
  }
@@ -33,6 +33,7 @@
33
33
  import { isExpiring, loadCachedTokens } from "./cognito-session.js";
34
34
  import { type VersionInfo } from "./feedback-versions.js";
35
35
  import { type ClientHealthArch, type ClientHealthFailureReason, type ClientHealthHeartbeat, type ClientHealthLocalFilesOverview, type ClientHealthPlatform, type ClientHealthSyncEngineVault } from "./client-health-contract.js";
36
+ import { type SyncCoreBinaryOutcome } from "../lib/sync-core/rollout-state.js";
36
37
  import { type DaemonPaths } from "../lib/daemon/paths.js";
37
38
  export declare const CLIENT_HEALTH_STATE_FILE = "cli-client-health.json";
38
39
  /**
@@ -182,12 +183,48 @@ export interface BuildCliHeartbeatInput {
182
183
  localFilesOverview?: ClientHealthLocalFilesOverview | null;
183
184
  syncEngine?: CliSyncEngine | null;
184
185
  daemonCliVersion?: string | null;
186
+ /** The live daemon's state file facts; null with no live daemon. */
187
+ daemon?: CliDaemonFacts | null;
188
+ /** True when this process was started by the daemon (a daemon unit): `versions.cli` is then what its units run. */
189
+ daemonUnit?: boolean;
185
190
  }
186
191
  export interface CliSyncEngine {
187
192
  release: string;
188
193
  vaults: number;
189
194
  byVault?: ClientHealthSyncEngineVault[];
195
+ pinned?: string;
196
+ pinSource?: "server" | "built-in" | "last-good";
197
+ reconcileAt?: string;
198
+ reconcileOutcome?: SyncCoreBinaryOutcome;
199
+ reconcileWarnings?: number;
190
200
  }
201
+ export interface CliDaemonFacts {
202
+ startedAt?: string;
203
+ hosted: boolean;
204
+ }
205
+ /**
206
+ * How long the daemon's state file may go without a rewrite before HQ stops
207
+ * trusting it. A running daemon rewrites state.json on every reconcile pass
208
+ * (15 s), so a state this old belongs to a daemon that is no longer running,
209
+ * even when its pid now names another live process.
210
+ */
211
+ export declare const DAEMON_STATE_FRESH_MS: number;
212
+ /**
213
+ * The live daemon's start time and whether an app hosts it, read only from
214
+ * its lock and state files; null when none runs. The state counts only when
215
+ * it was written by the daemon instance that holds the lock (same pid, and
216
+ * started no earlier than the lock was taken) and was rewritten within
217
+ * {@link DAEMON_STATE_FRESH_MS}.
218
+ */
219
+ export declare function readCliDaemonFacts(paths?: DaemonPaths, alive?: (pid: number) => boolean, now?: () => number): CliDaemonFacts | null;
220
+ /**
221
+ * True for the hq process a daemon (or its staged launcher) started for a
222
+ * unit. A daemon running this release records the unit's parent in
223
+ * HQ_DAEMON_UNIT_PARENT_PID, and a bot or session below the unit inherits it
224
+ * with a different parent, so it does not count. An older daemon sets no
225
+ * marker; its units are recognised by HQ_DAEMON_CLI_VERSION alone, as before.
226
+ */
227
+ export declare function isDirectDaemonUnit(env: NodeJS.ProcessEnv, parentPid?: number): boolean;
191
228
  export declare function readCliSyncEngine(stateDir: string, now?: Date, paths?: DaemonPaths, alive?: (pid: number) => boolean): CliSyncEngine | null;
192
229
  /** Classify sync failures using typed error identity/code fields only. */
193
230
  export declare function classifySyncFailure(err: unknown): ClientHealthFailureReason;
@@ -218,6 +255,12 @@ export interface ClientHealthDeps {
218
255
  syncEngine?: () => CliSyncEngine | null;
219
256
  daemonPaths?: DaemonPaths;
220
257
  daemonCliVersion?: () => Promise<string | null>;
258
+ daemonFacts?: () => CliDaemonFacts | null;
259
+ daemonAlive?: (pid: number) => boolean;
260
+ /** This process's environment, read for HQ_DAEMON_CLI_VERSION and HQ_DAEMON_UNIT_PARENT_PID. */
261
+ env?: NodeJS.ProcessEnv;
262
+ /** This process's parent pid at startup; see {@link isDirectDaemonUnit}. */
263
+ parentPid?: number;
221
264
  /** Override for {@link JOURNAL_OBSERVATION_TTL_MS}. */
222
265
  journalObservationTtlMs?: number;
223
266
  /** Override for {@link JOURNAL_OBSERVATION_LOCK_STALE_MS}. */
@@ -42,12 +42,13 @@ import { vaultApiFetch } from "./vault-api.js";
42
42
  import { collectVersions } from "./feedback-versions.js";
43
43
  import { resolveDaemonCliVersion } from "./daemon-cli-version.js";
44
44
  import { isAuthError } from "./auth-error.js";
45
- import { CLIENT_HEALTH_CONTRACT_VERSION, CLIENT_HEALTH_MAX_SYNC_ENGINE_VAULTS, CLIENT_HEALTH_MAX_SYNC_ENGINE_VAULT_ENTRIES, CLIENT_HEALTH_SYNC_ENGINE_HOLD_KINDS, parseClientHealthHeartbeat, SEMVER, } from "./client-health-contract.js";
45
+ import { CLIENT_HEALTH_CONTRACT_VERSION, CLIENT_HEALTH_MAX_SYNC_ENGINE_VAULTS, CLIENT_HEALTH_MAX_RECONCILE_WARNINGS, CLIENT_HEALTH_MAX_SYNC_ENGINE_VAULT_ENTRIES, CLIENT_HEALTH_SYNC_ENGINE_HOLD_KINDS, parseClientHealthHeartbeat, SEMVER, } from "./client-health-contract.js";
46
46
  import { collectLocalFilesOverview } from "./local-files-overview.js";
47
47
  import { readSyncCoreRolloutStateFile } from "../lib/sync-core/rollout-state.js";
48
+ const ISO_UTC_MS = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/;
48
49
  import { readEngineStatus, SYNC_CORE_STATUS_WORK_LIMIT, syncCoreUnitId } from "../lib/sync-core/engine-home.js";
49
50
  import { daemonPaths } from "../lib/daemon/paths.js";
50
- import { isProcessAlive, runningDaemonPid } from "../lib/daemon/lock.js";
51
+ import { isProcessAlive, liveDaemonLock, runningDaemonPid } from "../lib/daemon/lock.js";
51
52
  import { readEngineHoldKinds } from "../lib/sync-core/engine-holds.js";
52
53
  /** Same bound as CLI telemetry: a heartbeat may never stall a command. */
53
54
  const CLIENT_HEALTH_TIMEOUT_MS = 1_200;
@@ -430,6 +431,62 @@ function acquireJournalObservationLock(stateDir, nowMs, staleMs) {
430
431
  }
431
432
  };
432
433
  }
434
+ /**
435
+ * How long the daemon's state file may go without a rewrite before HQ stops
436
+ * trusting it. A running daemon rewrites state.json on every reconcile pass
437
+ * (15 s), so a state this old belongs to a daemon that is no longer running,
438
+ * even when its pid now names another live process.
439
+ */
440
+ export const DAEMON_STATE_FRESH_MS = 2 * 60_000;
441
+ /** How far the state's start may precede its lock's ts (whole-second rounding and clock skew). */
442
+ const DAEMON_LOCK_TS_SLACK_MS = 2_000;
443
+ /**
444
+ * The live daemon's start time and whether an app hosts it, read only from
445
+ * its lock and state files; null when none runs. The state counts only when
446
+ * it was written by the daemon instance that holds the lock (same pid, and
447
+ * started no earlier than the lock was taken) and was rewritten within
448
+ * {@link DAEMON_STATE_FRESH_MS}.
449
+ */
450
+ export function readCliDaemonFacts(paths = daemonPaths(), alive = isProcessAlive, now = Date.now) {
451
+ try {
452
+ const lock = liveDaemonLock(paths.lockPath, alive);
453
+ if (lock === null)
454
+ return null;
455
+ const state = JSON.parse(fs.readFileSync(paths.statePath, "utf8"));
456
+ if (!state || state.pid !== lock.pid)
457
+ return null;
458
+ const updatedAt = typeof state.updatedAt === "number" && Number.isFinite(state.updatedAt) ? state.updatedAt : undefined;
459
+ if (updatedAt === undefined || now() - updatedAt > DAEMON_STATE_FRESH_MS)
460
+ return null;
461
+ const hosted = typeof state.host === "string" && state.host.length > 0;
462
+ const startedAtMs = typeof state.startedAt === "number" && Number.isFinite(state.startedAt) && state.startedAt > 0 ? state.startedAt : undefined;
463
+ if (startedAtMs === undefined)
464
+ return { hosted };
465
+ if (startedAtMs + DAEMON_LOCK_TS_SLACK_MS < lock.ts * 1000)
466
+ return null;
467
+ return { startedAt: new Date(startedAtMs).toISOString(), hosted };
468
+ }
469
+ catch {
470
+ return null;
471
+ }
472
+ }
473
+ const startupParentPid = process.ppid;
474
+ /**
475
+ * True for the hq process a daemon (or its staged launcher) started for a
476
+ * unit. A daemon running this release records the unit's parent in
477
+ * HQ_DAEMON_UNIT_PARENT_PID, and a bot or session below the unit inherits it
478
+ * with a different parent, so it does not count. An older daemon sets no
479
+ * marker; its units are recognised by HQ_DAEMON_CLI_VERSION alone, as before.
480
+ */
481
+ export function isDirectDaemonUnit(env, parentPid = startupParentPid) {
482
+ if (!env.HQ_DAEMON_CLI_VERSION?.trim())
483
+ return false;
484
+ const marker = env.HQ_DAEMON_UNIT_PARENT_PID?.trim();
485
+ if (!marker)
486
+ return true;
487
+ const spawner = Number(marker);
488
+ return Number.isInteger(spawner) && spawner > 1 && spawner === parentPid;
489
+ }
433
490
  function readDaemonUnitStatuses(paths, alive) {
434
491
  try {
435
492
  const daemonPid = runningDaemonPid(paths.lockPath, alive);
@@ -495,7 +552,19 @@ export function readCliSyncEngine(stateDir, now = new Date(), paths = daemonPath
495
552
  add(vault.uid, () => syncEngineVaultFacts(vault, "legacy", units, now));
496
553
  for (const { uid } of [...(state.skipped ?? []), ...(state.held ?? [])])
497
554
  add(uid, () => ({ vaultUid: uid, owner: "legacy" }));
498
- return { release: state.release, vaults, byVault };
555
+ return {
556
+ release: state.release,
557
+ vaults,
558
+ byVault,
559
+ ...(state.binaryOutcome
560
+ ? {
561
+ ...(state.pin ? { pinned: state.pin.release, pinSource: state.pin.source } : {}),
562
+ reconcileAt: state.readAt,
563
+ reconcileOutcome: state.binaryOutcome,
564
+ reconcileWarnings: state.warnings ?? 0,
565
+ }
566
+ : {}),
567
+ };
499
568
  }
500
569
  /** Classify sync failures using typed error identity/code fields only. */
501
570
  export function classifySyncFailure(err) {
@@ -616,6 +685,28 @@ export function buildCliHeartbeat(input) {
616
685
  if (input.daemonCliVersion && SEMVER.test(input.daemonCliVersion)) {
617
686
  heartbeat.daemonCliVersion = input.daemonCliVersion;
618
687
  }
688
+ if (input.daemon) {
689
+ if (input.daemon.startedAt && ISO_UTC_MS.test(input.daemon.startedAt))
690
+ heartbeat.daemonStartedAt = input.daemon.startedAt;
691
+ heartbeat.daemonHosted = input.daemon.hosted;
692
+ }
693
+ if (input.daemonUnit && versions.cli)
694
+ heartbeat.daemonUnitCliVersion = versions.cli;
695
+ const engine = input.syncEngine;
696
+ if (engine) {
697
+ const pinned = engine.pinned?.replace(/^v/, "");
698
+ if (pinned && SEMVER.test(pinned))
699
+ heartbeat.syncEnginePinned = pinned;
700
+ if (engine.pinSource)
701
+ heartbeat.syncEnginePinSource = engine.pinSource;
702
+ if (engine.reconcileAt && ISO_UTC_MS.test(engine.reconcileAt))
703
+ heartbeat.syncEngineReconcileAt = engine.reconcileAt;
704
+ if (engine.reconcileOutcome)
705
+ heartbeat.syncEngineReconcileOutcome = engine.reconcileOutcome;
706
+ if (engine.reconcileWarnings !== undefined) {
707
+ heartbeat.syncEngineReconcileWarnings = Math.min(engine.reconcileWarnings, CLIENT_HEALTH_MAX_RECONCILE_WARNINGS);
708
+ }
709
+ }
619
710
  return heartbeat;
620
711
  }
621
712
  const defaultPoster = (heartbeat, token, signal) => vaultApiFetch({
@@ -792,6 +883,16 @@ async function contributeClientHealthUnbounded(kind, deps, failureReason) {
792
883
  catch {
793
884
  daemonCliVersion = null;
794
885
  }
886
+ let daemon = null;
887
+ try {
888
+ daemon = deps.daemonFacts
889
+ ? deps.daemonFacts()
890
+ : readCliDaemonFacts(deps.daemonPaths ?? daemonPaths(), deps.daemonAlive ?? isProcessAlive, () => now.getTime());
891
+ }
892
+ catch {
893
+ daemon = null;
894
+ }
895
+ const daemonUnit = isDirectDaemonUnit(deps.env ?? process.env, deps.parentPid ?? startupParentPid);
795
896
  const heartbeat = buildCliHeartbeat({
796
897
  kind,
797
898
  state,
@@ -803,6 +904,8 @@ async function contributeClientHealthUnbounded(kind, deps, failureReason) {
803
904
  failureReason,
804
905
  syncEngine,
805
906
  daemonCliVersion,
907
+ daemon,
908
+ daemonUnit,
806
909
  });
807
910
  if (!heartbeat)
808
911
  return;