@indigoai-us/hq-cli 5.345.248 → 5.345.250

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 (79) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/contracts/host-canary-release.json +3 -3
  3. package/dist/command-catalog.generated.d.ts +93 -8
  4. package/dist/command-catalog.generated.js +114 -8
  5. package/dist/commands/core-job-run-native.js +4 -0
  6. package/dist/commands/core-knowledge-prefs.d.ts +1 -1
  7. package/dist/commands/core-knowledge-prefs.js +1 -16
  8. package/dist/commands/core.js +0 -2
  9. package/dist/commands/daemon.js +21 -0
  10. package/dist/commands/ontology-graph.d.ts +2 -1
  11. package/dist/commands/ontology-graph.js +41 -10
  12. package/dist/commands/sync-core.js +6 -0
  13. package/dist/fast-scaffold.js +1 -3
  14. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +281 -256
  15. package/dist/hq-cloud-sync-runner/package.json +1 -1
  16. package/dist/index.d.ts +8 -0
  17. package/dist/index.js +47 -0
  18. package/dist/lib/daemon/installed-cli-restart.d.ts +57 -0
  19. package/dist/lib/daemon/installed-cli-restart.js +114 -0
  20. package/dist/lib/daemon/legacy-journal-gate.d.ts +32 -0
  21. package/dist/lib/daemon/legacy-journal-gate.js +102 -0
  22. package/dist/lib/daemon/machine-checks.d.ts +7 -0
  23. package/dist/lib/daemon/machine-checks.js +10 -0
  24. package/dist/lib/daemon/run.d.ts +3 -1
  25. package/dist/lib/daemon/run.js +48 -5
  26. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  27. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  28. package/dist/lib/hook-engine/coverage.d.ts +82 -13
  29. package/dist/lib/hook-engine/coverage.js +214 -18
  30. package/dist/lib/hook-engine/registration-identity.d.ts +5 -0
  31. package/dist/lib/hook-engine/registration-identity.js +1 -1
  32. package/dist/lib/hook-engine/resolve.d.ts +23 -0
  33. package/dist/lib/hook-engine/resolve.js +48 -1
  34. package/dist/lib/hook-engine/stable-heal.d.ts +87 -0
  35. package/dist/lib/hook-engine/stable-heal.js +214 -0
  36. package/dist/lib/hot-channels/graph-context.js +4 -1
  37. package/dist/lib/ontology-graph/model/step.d.ts +2 -0
  38. package/dist/lib/ontology-graph/model/step.js +3 -0
  39. package/dist/lib/ontology-graph/org/derive.d.ts +2 -0
  40. package/dist/lib/ontology-graph/org/derive.js +9 -2
  41. package/dist/lib/ontology-graph/org/index.d.ts +35 -6
  42. package/dist/lib/ontology-graph/org/index.js +136 -19
  43. package/dist/lib/ontology-graph/org/text.d.ts +2 -0
  44. package/dist/lib/ontology-graph/org/text.js +6 -0
  45. package/dist/lib/ontology-graph/org/types.d.ts +5 -0
  46. package/dist/lib/ontology-graph/pages/render.d.ts +2 -0
  47. package/dist/lib/ontology-graph/pages/render.js +10 -4
  48. package/dist/lib/ontology-graph/read/brief.js +4 -1
  49. package/dist/lib/ontology-graph/read/index.js +13 -2
  50. package/dist/lib/ontology-graph/read/names.d.ts +6 -1
  51. package/dist/lib/ontology-graph/read/names.js +8 -3
  52. package/dist/lib/ontology-graph/replay/engine.d.ts +47 -1
  53. package/dist/lib/ontology-graph/replay/engine.js +68 -2
  54. package/dist/lib/ontology-graph/replay/index.d.ts +2 -1
  55. package/dist/lib/ontology-graph/replay/index.js +1 -1
  56. package/dist/lib/ontology-graph/schema/authority.d.ts +34 -0
  57. package/dist/lib/ontology-graph/schema/authority.js +29 -0
  58. package/dist/lib/ontology-graph/schema/index.d.ts +1 -1
  59. package/dist/lib/ontology-graph/schema/index.js +1 -1
  60. package/dist/lib/ontology-graph/types.d.ts +7 -0
  61. package/dist/lib/sync-core/engine-holds.d.ts +1 -1
  62. package/dist/lib/sync-core/engine-holds.js +12 -2
  63. package/dist/lib/sync-core/hand-back.d.ts +2 -1
  64. package/dist/lib/sync-core/hand-back.js +16 -2
  65. package/dist/lib/sync-core/legacy-journal-export-child.d.ts +2 -0
  66. package/dist/lib/sync-core/legacy-journal-export-child.js +24 -0
  67. package/dist/lib/sync-core/legacy-journal-export.d.ts +39 -0
  68. package/dist/lib/sync-core/legacy-journal-export.js +241 -0
  69. package/dist/lib/sync-core/legacy-journal-reader.d.ts +15 -0
  70. package/dist/lib/sync-core/legacy-journal-reader.js +56 -0
  71. package/dist/lib/sync-core/reconcile.d.ts +3 -0
  72. package/dist/lib/sync-core/reconcile.js +43 -3
  73. package/dist/utils/cli-telemetry.d.ts +1 -0
  74. package/dist/utils/cli-telemetry.js +6 -3
  75. package/dist/utils/hook-engine-rollup.d.ts +96 -0
  76. package/dist/utils/hook-engine-rollup.js +725 -0
  77. package/package.json +8 -8
  78. package/scripts/install-hook-engine.mjs +4 -0
  79. package/assets/scaffold/core/scripts/knowledge-prefs.sh +0 -55
@@ -1 +1 @@
1
- {"name":"hq-cli-daemon-sync-runner","type":"module","version":"6.18.121","bundleSha256":"93df1547b4ae2346bf65b1a16eba2410370625efaab1e29fd93ca0a4e627410d","formatVersion":1}
1
+ {"name":"hq-cli-daemon-sync-runner","type":"module","version":"6.18.122","bundleSha256":"b8fdfeffdf3169c9c27d4eaf2dd3ce730b2f1e20f5ada5aacaa0217ddeecc72e","formatVersion":1}
package/dist/index.d.ts CHANGED
@@ -12,6 +12,13 @@ import { isFastCoreRequest } from "./fast-scaffold.js";
12
12
  * install-followup.ts.
13
13
  */
14
14
  export declare function installFollowupWouldDoWork(argv: readonly string[], env: NodeJS.ProcessEnv, platform: NodeJS.Platform): boolean;
15
+ /**
16
+ * Whether this run should check the `stable` hook engine link after an update
17
+ * (lib/hook-engine/stable-heal.ts). Only full commands run from an install,
18
+ * never `hq reindex` itself, the reindex the heal starts, or the daemons; and
19
+ * only where the link exists, so a machine without core.next loads nothing.
20
+ */
21
+ export declare function stableHealWouldRun(argv: readonly string[], env: NodeJS.ProcessEnv, platform: NodeJS.Platform, home?: string): boolean;
15
22
  type PackageUseLeaseLoader = () => Promise<void>;
16
23
  type PackageUseUpdateProbe = () => Promise<boolean>;
17
24
  /** Resolves true once the command was re-run (exit code already set). */
@@ -28,6 +35,7 @@ export declare const __test__: {
28
35
  isVersionRequest: typeof isVersionRequest;
29
36
  isFastCoreRequest: typeof isFastCoreRequest;
30
37
  installFollowupWouldDoWork: typeof installFollowupWouldDoWork;
38
+ stableHealWouldRun: typeof stableHealWouldRun;
31
39
  dispatchWithPackageUseLease: typeof dispatchWithPackageUseLease;
32
40
  waitForUpdateThenReexec: typeof waitForUpdateThenReexec;
33
41
  runCliEntry: typeof runCliEntry;
package/dist/index.js CHANGED
@@ -19,6 +19,9 @@ import { parseMonitorCheckFastRequest } from "./lanes-monitor-check-argv.js";
19
19
  import { isLaneSessionStartFastRequest } from "./lanes-session-start-argv.js";
20
20
  import { writeLanesAliasDeprecationForArgv } from "./runners-alias.js";
21
21
  import { createRequire } from "node:module";
22
+ import { lstatSync } from "node:fs";
23
+ import { homedir } from "node:os";
24
+ import { join } from "node:path";
22
25
  import { hookEnginePathArgs, runHookEnginePath } from "./hook-engine-path.js";
23
26
  // Builtins only: the local command count and the retiring gate run on every
24
27
  // route, including the hook fast routes. The gate ships switched off
@@ -293,6 +296,49 @@ function dispatchCliRoutes() {
293
296
  // daemon work, so they never start PowerShell or reg.exe. The module stays
294
297
  // unloaded when there is nothing to do, so a Linux fast route does not
295
298
  // import it.
299
+ if (!versionRequest && !helpRequest && !monitorRequest && !parsedFastCore && !secretsRequest && !mcpRequest
300
+ && stableHealWouldRun(process.argv, process.env, process.platform)) {
301
+ void import("./lib/hook-engine/stable-heal.js").then(({ healStableEngine, recordStableHealFailure }) => {
302
+ try {
303
+ healStableEngine();
304
+ }
305
+ catch (error) {
306
+ // The heal must not turn into a failed command; its log says what went wrong.
307
+ recordStableHealFailure(error);
308
+ }
309
+ }).catch(() => undefined).then(() => {
310
+ dispatchInstallFollowupThenCommand(versionRequest, helpRequest, parsedFastCore, monitorRequest, secretsRequest, mcpRequest);
311
+ });
312
+ return;
313
+ }
314
+ dispatchInstallFollowupThenCommand(versionRequest, helpRequest, parsedFastCore, monitorRequest, secretsRequest, mcpRequest);
315
+ }
316
+ /**
317
+ * Whether this run should check the `stable` hook engine link after an update
318
+ * (lib/hook-engine/stable-heal.ts). Only full commands run from an install,
319
+ * never `hq reindex` itself, the reindex the heal starts, or the daemons; and
320
+ * only where the link exists, so a machine without core.next loads nothing.
321
+ */
322
+ export function stableHealWouldRun(argv, env, platform, home = homedir()) {
323
+ if (platform === "win32" || env.HQ_STABLE_HEAL === "1" || env.HQ_STAGED_INSTALL === "1")
324
+ return false;
325
+ const args = argv.slice(2).filter((arg) => arg !== "--verbose");
326
+ if (args[0] === "reindex" || args[0] === "master-sync")
327
+ return false;
328
+ if (args[0] === "mesh" && args[1] === "daemon")
329
+ return false;
330
+ if (args[0] === "daemon")
331
+ return false;
332
+ if (!/node_modules[/\\]@indigoai-us[/\\]hq-cli[/\\]/i.test(argv[1] ?? ""))
333
+ return false;
334
+ try {
335
+ return lstatSync(join(home, ".hq", "bin", "hq-hook", "stable")).isSymbolicLink();
336
+ }
337
+ catch {
338
+ return false;
339
+ }
340
+ }
341
+ function dispatchInstallFollowupThenCommand(versionRequest, helpRequest, parsedFastCore, monitorRequest, secretsRequest, mcpRequest) {
296
342
  if (!versionRequest && !monitorRequest && !parsedFastCore && !secretsRequest && !mcpRequest
297
343
  && installFollowupWouldDoWork(process.argv, process.env, process.platform)) {
298
344
  void import("./lib/windows/install-followup.js").then(({ runWindowsInstallFollowup }) => {
@@ -536,6 +582,7 @@ export const __test__ = {
536
582
  isVersionRequest,
537
583
  isFastCoreRequest,
538
584
  installFollowupWouldDoWork,
585
+ stableHealWouldRun,
539
586
  dispatchWithPackageUseLease,
540
587
  waitForUpdateThenReexec,
541
588
  runCliEntry,
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Restart a daemon that is older than the hq CLI installed on disk.
3
+ *
4
+ * The desktop app, `hq update` or `npm install -g` can replace the CLI while
5
+ * the daemon keeps running. Units the daemon starts load the new files, but
6
+ * work the daemon does in its own process (the in-process lanes reconcile,
7
+ * the supervisor itself) keeps running the release it started from. The
8
+ * `updater` unit restarts an older daemon, but a machine can turn that unit
9
+ * off (`hq daemon disable updater`), and then nothing restarted the daemon:
10
+ * on 2026-11-22 a desktop daemon still ran 5.345.236 with 5.345.247
11
+ * installed, so the lanes reconcile kept failing with a bug 5.345.246 fixed.
12
+ *
13
+ * Restarting onto an installed release is not an update, so this runs from
14
+ * the hourly housekeeping unit on every machine type, whether or not the
15
+ * updater is on. Only a strictly older, parseable daemon version asks, and
16
+ * it asks once per (running, installed) pair, recorded on disk, so a dev build
17
+ * or a restart that comes back on the same old release never loops.
18
+ */
19
+ /** The version in the hq-cli package.json under `packageRoot`, read from disk now; null when unknown. */
20
+ export declare function installedCliVersionOnDisk(packageRoot: string | null, read?: (file: string) => string): string | null;
21
+ export interface OlderParentDaemonDeps {
22
+ /** HQ_DAEMON_CLI_VERSION: the release of the daemon that started this unit (set by every daemon since before 5.345.236). */
23
+ parentVersion: string | undefined;
24
+ /** This process's own CLI_VERSION: the CLI installed on disk, since units start from it. */
25
+ cliVersion: string;
26
+ /** Records the last pair asked for, so units started by the same daemon ask once. */
27
+ markerPath: string;
28
+ /** Ask the running daemon to restart once sync is idle. */
29
+ requestRestart: () => void;
30
+ }
31
+ /**
32
+ * Heal a daemon that is already stuck on an older release, which has no
33
+ * housekeeping check of its own: a unit it starts runs the CLI on disk and can
34
+ * see that its parent is older. Asks once per (daemon, installed) pair; returns
35
+ * whether it asked. Never throws: the unit must start either way.
36
+ */
37
+ export declare function requestRestartOfOlderParentDaemon(deps: OlderParentDaemonDeps): boolean;
38
+ export interface InstalledCliRestartDeps {
39
+ /** The release this daemon process was started from (its CLI_VERSION). */
40
+ runningVersion: string;
41
+ /** The release installed on disk now, or null when it cannot be read. */
42
+ readInstalledVersion: () => string | null;
43
+ /** Ask the running daemon to restart once sync is idle. */
44
+ requestRestart: () => void;
45
+ log: (level: "info" | "warn", line: string) => void;
46
+ /**
47
+ * Records the last (running, installed) pair asked for, so a daemon that comes
48
+ * back on the same old release after a restart does not ask again every hour.
49
+ */
50
+ markerPath?: string;
51
+ }
52
+ /**
53
+ * One check per call. Returns the installed version it asked to restart onto,
54
+ * or null when it did not ask. Never throws: housekeeping must keep running.
55
+ */
56
+ export declare function createInstalledCliRestartCheck(deps: InstalledCliRestartDeps): () => string | null;
57
+ //# sourceMappingURL=installed-cli-restart.d.ts.map
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Restart a daemon that is older than the hq CLI installed on disk.
3
+ *
4
+ * The desktop app, `hq update` or `npm install -g` can replace the CLI while
5
+ * the daemon keeps running. Units the daemon starts load the new files, but
6
+ * work the daemon does in its own process (the in-process lanes reconcile,
7
+ * the supervisor itself) keeps running the release it started from. The
8
+ * `updater` unit restarts an older daemon, but a machine can turn that unit
9
+ * off (`hq daemon disable updater`), and then nothing restarted the daemon:
10
+ * on 2026-11-22 a desktop daemon still ran 5.345.236 with 5.345.247
11
+ * installed, so the lanes reconcile kept failing with a bug 5.345.246 fixed.
12
+ *
13
+ * Restarting onto an installed release is not an update, so this runs from
14
+ * the hourly housekeeping unit on every machine type, whether or not the
15
+ * updater is on. Only a strictly older, parseable daemon version asks, and
16
+ * it asks once per (running, installed) pair, recorded on disk, so a dev build
17
+ * or a restart that comes back on the same old release never loops.
18
+ */
19
+ import * as fs from "node:fs";
20
+ import * as path from "node:path";
21
+ import semver from "semver";
22
+ /** The version in the hq-cli package.json under `packageRoot`, read from disk now; null when unknown. */
23
+ export function installedCliVersionOnDisk(packageRoot, read = (file) => fs.readFileSync(file, "utf8")) {
24
+ if (!packageRoot)
25
+ return null;
26
+ try {
27
+ const pkg = JSON.parse(read(path.join(packageRoot, "package.json")));
28
+ if (pkg.name !== "@indigoai-us/hq-cli" || typeof pkg.version !== "string")
29
+ return null;
30
+ return semver.valid(pkg.version);
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ }
36
+ /**
37
+ * Heal a daemon that is already stuck on an older release, which has no
38
+ * housekeeping check of its own: a unit it starts runs the CLI on disk and can
39
+ * see that its parent is older. Asks once per (daemon, installed) pair; returns
40
+ * whether it asked. Never throws: the unit must start either way.
41
+ */
42
+ export function requestRestartOfOlderParentDaemon(deps) {
43
+ try {
44
+ const parent = semver.valid(deps.parentVersion?.trim() ?? "");
45
+ const installed = semver.valid(deps.cliVersion);
46
+ if (!parent || !installed || !semver.lt(parent, installed))
47
+ return false;
48
+ const pair = `${parent}->${installed}`;
49
+ try {
50
+ if (JSON.parse(fs.readFileSync(deps.markerPath, "utf8")).pair === pair)
51
+ return false;
52
+ }
53
+ catch {
54
+ // no marker yet, or unreadable: ask
55
+ }
56
+ fs.mkdirSync(path.dirname(deps.markerPath), { recursive: true, mode: 0o700 });
57
+ fs.writeFileSync(deps.markerPath, `${JSON.stringify({ pair })}\n`, { mode: 0o600 });
58
+ deps.requestRestart();
59
+ return true;
60
+ }
61
+ catch {
62
+ return false;
63
+ }
64
+ }
65
+ function readRequestedPair(markerPath) {
66
+ if (!markerPath)
67
+ return null;
68
+ try {
69
+ return JSON.parse(fs.readFileSync(markerPath, "utf8"));
70
+ }
71
+ catch {
72
+ return null;
73
+ }
74
+ }
75
+ /**
76
+ * One check per call. Returns the installed version it asked to restart onto,
77
+ * or null when it did not ask. Never throws: housekeeping must keep running.
78
+ */
79
+ export function createInstalledCliRestartCheck(deps) {
80
+ let requestedFor = null;
81
+ return () => {
82
+ try {
83
+ const running = semver.valid(deps.runningVersion);
84
+ const installed = deps.readInstalledVersion();
85
+ if (!running || !installed || !semver.lt(running, installed))
86
+ return null;
87
+ if (requestedFor === installed)
88
+ return null;
89
+ const earlier = readRequestedPair(deps.markerPath);
90
+ if (earlier?.running === running && earlier.installed === installed) {
91
+ requestedFor = installed;
92
+ return null;
93
+ }
94
+ requestedFor = installed;
95
+ if (deps.markerPath) {
96
+ try {
97
+ fs.mkdirSync(path.dirname(deps.markerPath), { recursive: true, mode: 0o700 });
98
+ fs.writeFileSync(deps.markerPath, `${JSON.stringify({ running, installed })}\n`, { mode: 0o600 });
99
+ }
100
+ catch {
101
+ // Without the marker this process still asks only once; ask now.
102
+ }
103
+ }
104
+ deps.log("info", `this daemon runs hq-cli ${running}, older than the installed ${installed}; restarting onto it once sync is idle`);
105
+ deps.requestRestart();
106
+ return installed;
107
+ }
108
+ catch (error) {
109
+ deps.log("warn", `could not compare this daemon with the installed hq-cli (${error instanceof Error ? error.message : String(error)})`);
110
+ return null;
111
+ }
112
+ };
113
+ }
114
+ //# sourceMappingURL=installed-cli-restart.js.map
@@ -0,0 +1,32 @@
1
+ export declare const LEGACY_JOURNAL_EXPORT_TIMEOUT_MS = 120000;
2
+ export declare const LEGACY_JOURNAL_EXPORT_WAIT_PREFIX = "copying what the current sync last synced for ";
3
+ export interface LegacyJournalGateVault {
4
+ uid: string;
5
+ kind: "personal" | "company";
6
+ slug?: string;
7
+ phase: "warming" | "full";
8
+ legacyOffSince?: string;
9
+ }
10
+ export interface LegacyJournalGate {
11
+ pending(vault: LegacyJournalGateVault): boolean;
12
+ }
13
+ export type LegacyJournalExportRun = (vault: {
14
+ uid: string;
15
+ slug: string;
16
+ legacyOffSince?: string;
17
+ }, done: (failure?: string) => void) => {
18
+ cancel: () => void;
19
+ };
20
+ export interface LegacyJournalGateDeps {
21
+ home: string;
22
+ env: NodeJS.ProcessEnv;
23
+ now: () => number;
24
+ run: LegacyJournalExportRun;
25
+ timeoutMs?: number;
26
+ log: (level: "info" | "warn", message: string) => void;
27
+ }
28
+ export declare function legacyJournalExportWaitReason(what: string): string;
29
+ export declare function createLegacyJournalGate(deps: LegacyJournalGateDeps): LegacyJournalGate;
30
+ export declare function legacyJournalExportChildPath(): string;
31
+ export declare function runLegacyJournalExportChild(home: string, env: NodeJS.ProcessEnv, nodeBinary?: string, childPath?: string): LegacyJournalExportRun;
32
+ //# sourceMappingURL=legacy-journal-gate.d.ts.map
@@ -0,0 +1,102 @@
1
+ import { spawn } from "node:child_process";
2
+ import { fileURLToPath } from "node:url";
3
+ import { legacyJournalDirs, legacyJournalExportState, removeLegacyJournalTemps } from "../sync-core/legacy-journal-export.js";
4
+ export const LEGACY_JOURNAL_EXPORT_TIMEOUT_MS = 120_000;
5
+ export const LEGACY_JOURNAL_EXPORT_WAIT_PREFIX = "copying what the current sync last synced for ";
6
+ export function legacyJournalExportWaitReason(what) {
7
+ return `${LEGACY_JOURNAL_EXPORT_WAIT_PREFIX}${what}, so the new sync engine can tell an old copy from an edit that was never uploaded`;
8
+ }
9
+ export function createLegacyJournalGate(deps) {
10
+ const seen = new Map();
11
+ const timeoutMs = deps.timeoutMs ?? LEGACY_JOURNAL_EXPORT_TIMEOUT_MS;
12
+ const dropTemps = (vault) => {
13
+ try {
14
+ removeLegacyJournalTemps(deps.home, vault);
15
+ }
16
+ catch (error) {
17
+ deps.log("warn", `${vault.uid}: could not remove an unfinished copy of the current sync's record: ${error instanceof Error ? error.message : String(error)}`);
18
+ }
19
+ };
20
+ return {
21
+ pending(vault) {
22
+ if (vault.kind !== "company" || vault.phase !== "full" || !vault.slug)
23
+ return false;
24
+ const slug = vault.slug;
25
+ const key = vault.legacyOffSince ?? "";
26
+ const entry = seen.get(vault.uid);
27
+ if (entry && entry.key === key) {
28
+ if (entry.done)
29
+ return false;
30
+ if (deps.now() - entry.startedAt < timeoutMs)
31
+ return true;
32
+ entry.done = true;
33
+ entry.cancel?.();
34
+ dropTemps(vault);
35
+ deps.log("warn", `${vault.uid}: copying the current sync's record of ${slug} took over ${Math.round(timeoutMs / 1000)} seconds; starting the new sync engine without it`);
36
+ return false;
37
+ }
38
+ const started = { key, startedAt: deps.now(), done: false };
39
+ seen.set(vault.uid, started);
40
+ let needed;
41
+ try {
42
+ const state = legacyJournalExportState(deps.home, vault, deps.now());
43
+ needed = (state === "missing" || state === "unusable") && legacyJournalDirs(deps.home, deps.env, slug).length > 0;
44
+ }
45
+ catch (error) {
46
+ deps.log("warn", `${vault.uid}: could not check for the current sync's record of ${slug}: ${error instanceof Error ? error.message : String(error)}; starting the new sync engine without it`);
47
+ needed = false;
48
+ }
49
+ if (!needed) {
50
+ started.done = true;
51
+ return false;
52
+ }
53
+ try {
54
+ started.cancel = deps.run({ uid: vault.uid, slug, ...(vault.legacyOffSince ? { legacyOffSince: vault.legacyOffSince } : {}) }, (failure) => {
55
+ if (failure)
56
+ dropTemps(vault);
57
+ if (started.done)
58
+ return;
59
+ started.done = true;
60
+ if (failure)
61
+ deps.log("warn", `${vault.uid}: could not copy the current sync's record of ${slug} for the new sync engine: ${failure}; starting the engine without it`);
62
+ else
63
+ deps.log("info", `${vault.uid}: copied the current sync's record of ${slug} for the new sync engine`);
64
+ }).cancel;
65
+ }
66
+ catch (error) {
67
+ started.done = true;
68
+ deps.log("warn", `${vault.uid}: could not copy the current sync's record of ${slug} for the new sync engine: ${error instanceof Error ? error.message : String(error)}; starting the engine without it`);
69
+ }
70
+ return !started.done;
71
+ },
72
+ };
73
+ }
74
+ export function legacyJournalExportChildPath() {
75
+ return fileURLToPath(new URL("../sync-core/legacy-journal-export-child.js", import.meta.url));
76
+ }
77
+ export function runLegacyJournalExportChild(home, env, nodeBinary = process.execPath, childPath = legacyJournalExportChildPath()) {
78
+ return (vault, done) => {
79
+ const child = spawn(nodeBinary, [childPath, home, vault.uid, vault.slug, ...(vault.legacyOffSince ? [vault.legacyOffSince] : [])], {
80
+ env: { ...env, HQ_NO_UPDATE_CHECK: "1" },
81
+ stdio: ["ignore", "ignore", "pipe"],
82
+ windowsHide: true,
83
+ });
84
+ let stderr = "";
85
+ child.stderr?.setEncoding("utf8");
86
+ child.stderr?.on("data", (text) => {
87
+ if (stderr.length < 2000)
88
+ stderr += text;
89
+ });
90
+ child.on("error", (error) => done(error.message));
91
+ child.on("exit", (code, signal) => {
92
+ if (code === 0)
93
+ done();
94
+ else {
95
+ const lines = stderr.split("\n").map((line) => line.trim()).filter(Boolean);
96
+ done(lines.find((line) => /\bError\b/.test(line)) ?? lines.pop() ?? `the copy step ended with ${signal ?? `exit code ${String(code)}`}`);
97
+ }
98
+ });
99
+ return { cancel: () => void child.kill() };
100
+ };
101
+ }
102
+ //# sourceMappingURL=legacy-journal-gate.js.map
@@ -190,6 +190,13 @@ export interface MachineCheckScheduleOptions {
190
190
  collectOnlySupported?: (hqRoot: string) => boolean;
191
191
  /** Test seam: the fingerprints the native notice delivered. Default nativeNoticeShownFingerprints. */
192
192
  shownFingerprints?: (env: NodeJS.ProcessEnv, home: string) => ReadonlySet<string>;
193
+ /**
194
+ * Work that rides every tick while the schedule's gate is on (the daily
195
+ * hook-engine failure upload). It needs no HQ root and does not wait for the
196
+ * batch interval. Its own failure logs the error's name only and never stops
197
+ * the batch.
198
+ */
199
+ rollup?: () => Promise<void>;
193
200
  }
194
201
  /**
195
202
  * The checks to commit in this batch: each whose last result (the results
@@ -490,6 +490,16 @@ export function startMachineCheckSchedule(options) {
490
490
  /** Check id to the fingerprint last committed for it (in memory; a restart may commit once more, which is harmless). */
491
491
  const committed = new Map();
492
492
  const tick = async () => {
493
+ if (closed)
494
+ return;
495
+ if (options.rollup && enabled(options.env, options.home)) {
496
+ try {
497
+ await options.rollup();
498
+ }
499
+ catch (error) {
500
+ options.log("warn", `hook-engine rollup failed (${error instanceof Error ? error.name : "UnknownError"})`);
501
+ }
502
+ }
493
503
  try {
494
504
  if (closed)
495
505
  return;
@@ -9,6 +9,7 @@ import { acquirePackageUseLease } from "../../utils/package-use-lease.js";
9
9
  import { type PlanFleetBotsDeps } from "../bot/fleet-daemon.js";
10
10
  import { type FleetBotPlan, type LegacySyncHolder, type PlanContext, type ServiceName, type UnitPlan } from "./catalog.js";
11
11
  import { type LegacyHandover } from "./legacy-handover.js";
12
+ import { type LegacyJournalGate } from "./legacy-journal-gate.js";
12
13
  import { type SyncCoreVaultPlan } from "../sync-core/engine-home.js";
13
14
  import { type DaemonFlagRegistryRead, type DaemonFlagSnapshotSource } from "./flag.js";
14
15
  import { type LegacyUnit, type WindowsTaskOwner } from "./legacy.js";
@@ -24,7 +25,7 @@ export declare const LOG_ROTATE_BYTES: number;
24
25
  /** Exit code for "restart me": non-zero so every service manager relaunches (Windows tasks only restart on failure). */
25
26
  export declare const RESTART_EXIT_CODE = 75;
26
27
  export declare function syncCoreVaultPlans(home: string, hqRoot: string | undefined, platform: NodeJS.Platform): SyncCoreVaultPlan[];
27
- export declare function planUnitsWithSyncCoreInterlock(services: readonly ServiceName[], context: PlanContext, supervisor: Pick<Supervisor, "runningPlanKey" | "state"> | null | undefined, readOwnerStatus: () => WatchRunnerOwnerStatus | null, handover?: LegacyHandover, readSwitchOnTimes?: () => VaultSwitchOnTimes): UnitPlan[];
28
+ export declare function planUnitsWithSyncCoreInterlock(services: readonly ServiceName[], context: PlanContext, supervisor: Pick<Supervisor, "runningPlanKey" | "state"> | null | undefined, readOwnerStatus: () => WatchRunnerOwnerStatus | null, handover?: LegacyHandover, readSwitchOnTimes?: () => VaultSwitchOnTimes, journalGate?: LegacyJournalGate): UnitPlan[];
28
29
  export interface LegacyRestoreWait {
29
30
  what: string;
30
31
  /** When HQ turned the vault's old-sync switch back on. */
@@ -81,6 +82,7 @@ export declare function hqdListenerRuntimeAllowed(env: NodeJS.ProcessEnv, readSe
81
82
  export declare function handoffForPackageUpdateRequest(requested: boolean, restartDaemon: () => void): void;
82
83
  export interface RunDaemonOptions {
83
84
  legacyHandover?: LegacyHandover;
85
+ legacyJournalGate?: LegacyJournalGate;
84
86
  removeMeshUnitFromOtherHome?: typeof removeMeshUnitFromOtherHome;
85
87
  isLoginHome?: (home: string) => boolean;
86
88
  foreground?: boolean;
@@ -27,6 +27,7 @@ import { createHeldBotReconciler, heldBotThrottleDir } from "../bot/promotion-ho
27
27
  import { botsRoot } from "../bot/paths.js";
28
28
  import { CLAUDE_RUNNER_SCRIPT, CODEX_RUNNER_SCRIPT, enabledServices, planUnits, SEARCH_INDEX_WORKER_UNAVAILABLE, isLegacyRestartWait } from "./catalog.js";
29
29
  import { createLegacyHandover, LEGACY_HANDOVER_STUCK_FILE, writeLegacyHandoverStuck } from "./legacy-handover.js";
30
+ import { createLegacyJournalGate, legacyJournalExportWaitReason, runLegacyJournalExportChild } from "./legacy-journal-gate.js";
30
31
  import { effectiveSyncOwner, readDaemonConfig } from "./config.js";
31
32
  import { backgroundQosCommand } from "./background-qos.js";
32
33
  import { serveQmdWorker } from "../search-index/worker-process.js";
@@ -45,7 +46,8 @@ import { hqMembersList, startFleetMembersWarmer } from "./fleet-members-cache.js
45
46
  import { SUPERVISOR_HANDOFF_FLAG, readDaemonFlag } from "./flag.js";
46
47
  import { createDaemonSharedFlagReads, hqdListenerFlagGate } from "./shared-flag-reads.js";
47
48
  import { createDaemonKillSwitchMonitors } from "./timed-flag-monitors.js";
48
- import { MACHINE_CHECKS_RESULT_FILE, readMachineCheckResults, startMachineCheckSchedule } from "./machine-checks.js";
49
+ import { MACHINE_CHECKS_INTERVAL_MS, MACHINE_CHECKS_MIN_INTERVAL_MS, MACHINE_CHECKS_RESULT_FILE, readMachineCheckResults, startMachineCheckSchedule, } from "./machine-checks.js";
50
+ import { HOOK_ENGINE_ROLLUP_STATE_FILE, hookEngineRollupLogLine, runHookEngineRollup, } from "../../utils/hook-engine-rollup.js";
49
51
  import { createLanesReconcileWatcher } from "./lanes-reconcile-watcher.js";
50
52
  import { createLanesReconcileStatus, withLanesReconcileUnit } from "./lanes-reconcile-status.js";
51
53
  import { findLegacyUnits, legacyMeshUnitsToRetire, legacyOwnerLookup, } from "./legacy.js";
@@ -74,6 +76,7 @@ import { heartbeatFile, startHeartbeat } from "./heartbeat.js";
74
76
  import { daemonStartEnv } from "./hook-env.js";
75
77
  import { createProtocolTail, ensureProtocolFifo, openProtocolWriter } from "./protocol-tail.js";
76
78
  import { takeControlRequests, writeControlRequest } from "./requests.js";
79
+ import { createInstalledCliRestartCheck, installedCliVersionOnDisk } from "./installed-cli-restart.js";
77
80
  import { currentHqCloud, currentHqCloudAfterLeaseRelease, hqCloudRunners, hqCloudVersionOlder } from "./hq-cloud.js";
78
81
  import { stageSyncRunnerBundle } from "./sync-runner-bundle.js";
79
82
  import { stageHqChildBootstrap } from "./hq-child-bootstrap-stage.js";
@@ -118,7 +121,7 @@ export function syncCoreVaultPlans(home, hqRoot, platform) {
118
121
  });
119
122
  }
120
123
  const rememberedSyncCoreVaults = new Map();
121
- export function planUnitsWithSyncCoreInterlock(services, context, supervisor, readOwnerStatus, handover, readSwitchOnTimes = () => ({ companies: {} })) {
124
+ export function planUnitsWithSyncCoreInterlock(services, context, supervisor, readOwnerStatus, handover, readSwitchOnTimes = () => ({ companies: {} }), journalGate) {
122
125
  const companies = new Set();
123
126
  const runningVaults = new Set();
124
127
  let personal = false;
@@ -196,9 +199,20 @@ export function planUnitsWithSyncCoreInterlock(services, context, supervisor, re
196
199
  legacySyncReadyForCore,
197
200
  ...(holder !== undefined ? { legacySyncHolder: holder } : {}),
198
201
  };
202
+ const holdForJournal = (units) => journalGate
203
+ ? units.map((unit) => {
204
+ if (!unit.id.startsWith("sync-core:") || unit.blocked !== undefined)
205
+ return unit;
206
+ const uid = unit.id.slice("sync-core:".length);
207
+ const vault = context.syncCoreVaults?.find((v) => v.uid === uid);
208
+ if (!vault || runningVaults.has(uid) || !journalGate.pending(vault))
209
+ return unit;
210
+ return { ...unit, blocked: { state: "waiting", reason: legacyJournalExportWaitReason(`the ${vault.slug ?? uid} vault`) } };
211
+ })
212
+ : units;
199
213
  let plans = planUnits(services, planned);
200
214
  if (!handover)
201
- return plans;
215
+ return holdForJournal(plans);
202
216
  const vaultName = (uid) => {
203
217
  const vault = context.syncCoreVaults?.find((v) => v.uid === uid);
204
218
  return vault?.kind === "personal" ? "the personal vault" : `the ${vault?.slug ?? uid} vault`;
@@ -223,7 +237,7 @@ export function planUnitsWithSyncCoreInterlock(services, context, supervisor, re
223
237
  if (stopRequestedAt !== undefined && toEngine.length > 0) {
224
238
  plans = planUnits(services, { ...planned, legacyHandoverStopRequestedAt: stopRequestedAt });
225
239
  }
226
- return plans;
240
+ return holdForJournal(plans);
227
241
  }
228
242
  /**
229
243
  * Vaults whose old-sync switch HQ turned back on (a rollback, or a held engine)
@@ -878,6 +892,14 @@ export async function runDaemon(opts) {
878
892
  const cliPackagePrefix = opts.cliPackagePrefix === undefined
879
893
  ? currentPackageUseLeaseInstall()?.prefix ?? null
880
894
  : opts.cliPackagePrefix;
895
+ // A daemon older than the CLI on disk restarts onto it, even with the updater unit off.
896
+ const checkInstalledCli = createInstalledCliRestartCheck({
897
+ runningVersion: CLI_VERSION,
898
+ readInstalledVersion: () => installedCliVersionOnDisk(cliPackageRoot),
899
+ requestRestart: () => { writeControlRequest(paths.requestsDir, { action: "restart-daemon", deferUntilSyncIdle: true }); },
900
+ log,
901
+ markerPath: path.join(paths.root, "installed-cli-restart.json"),
902
+ });
881
903
  let stagedSyncBundle = null;
882
904
  let bundleStageChecked = false;
883
905
  let bundleStageFailed = false;
@@ -1101,6 +1123,13 @@ export async function runDaemon(opts) {
1101
1123
  writeRestoreStuck: (stuck) => writeLegacyHandoverStuck(path.join(paths.root, LEGACY_HANDOVER_STUCK_FILE), stuck),
1102
1124
  log: (level, message) => log(level, message),
1103
1125
  });
1126
+ const legacyJournalGate = opts.legacyJournalGate ?? createLegacyJournalGate({
1127
+ home,
1128
+ env,
1129
+ now: Date.now,
1130
+ run: runLegacyJournalExportChild(home, env, opts.nodeBinary),
1131
+ log: (level, message) => log(level, message),
1132
+ });
1104
1133
  const meshOwnerReason = () => {
1105
1134
  const lockPath = meshDaemonPidPath(meshDaemonDir(undefined, home, env));
1106
1135
  const owner = readPidLock(lockPath);
@@ -1251,6 +1280,7 @@ export async function runDaemon(opts) {
1251
1280
  const lanesReconcileFileWatchFlag = killSwitches.lanesReconcileFileWatch;
1252
1281
  const searchIndexRunnerOwnsIndexFlag = killSwitches.searchIndexRunnerOwnsIndex;
1253
1282
  const syncProcessScanOnMissingFlag = killSwitches.syncProcessScanOnMissing;
1283
+ let lastRollupStatus;
1254
1284
  const machineChecks = startMachineCheckSchedule({
1255
1285
  env,
1256
1286
  home,
@@ -1260,6 +1290,18 @@ export async function runDaemon(opts) {
1260
1290
  return configured && fs.existsSync(configured) ? configured : undefined;
1261
1291
  },
1262
1292
  resultsFile: path.join(paths.root, MACHINE_CHECKS_RESULT_FILE),
1293
+ rollup: async () => {
1294
+ const result = await runHookEngineRollup({
1295
+ home,
1296
+ env,
1297
+ stateFile: path.join(paths.root, HOOK_ENGINE_ROLLUP_STATE_FILE),
1298
+ maxConfirmGapMs: 2 * MACHINE_CHECKS_INTERVAL_MS + MACHINE_CHECKS_MIN_INTERVAL_MS,
1299
+ });
1300
+ const line = hookEngineRollupLogLine(result, lastRollupStatus);
1301
+ lastRollupStatus = result.status;
1302
+ if (line)
1303
+ log(line.level, line.message);
1304
+ },
1263
1305
  });
1264
1306
  let laneReconcileWatcher = null;
1265
1307
  let laneReconcileWatcherRoot = null;
@@ -1663,7 +1705,7 @@ export async function runDaemon(opts) {
1663
1705
  };
1664
1706
  const plans = planUnitsWithSyncCoreInterlock(services, context, supervisor, () => hqRoot
1665
1707
  ? readWatchRunnerOwnerStatus(watchRunnerOwnerStatusPath(hqRoot, home, env))
1666
- : null, legacyHandover, () => readVaultSwitchOnTimes(home));
1708
+ : null, legacyHandover, () => readVaultSwitchOnTimes(home), legacyJournalGate);
1667
1709
  if (startupPlanOpen) {
1668
1710
  const replaceablePackageRoots = cliPackageRoot ? [cliPackageRoot] : [];
1669
1711
  if (hqCloud?.source === "bundled")
@@ -1873,6 +1915,7 @@ export async function runDaemon(opts) {
1873
1915
  const n = rotateLogs(paths.logsDir);
1874
1916
  if (n > 0)
1875
1917
  log("info", `rotated ${n} log file(s)`);
1918
+ checkInstalledCli();
1876
1919
  return true;
1877
1920
  },
1878
1921
  takeRequests: () => {