@indigoai-us/hq-cli 5.345.236 → 5.345.237

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 (91) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/dist/command-catalog.generated.d.ts +1 -1
  3. package/dist/command-catalog.generated.js +1 -1
  4. package/dist/commands/bot.js +9 -0
  5. package/dist/commands/daemon.d.ts +1 -0
  6. package/dist/commands/daemon.js +70 -6
  7. package/dist/commands/deploy-app-db.js +4 -19
  8. package/dist/commands/deploy-app-upload.js +66 -40
  9. package/dist/commands/deploy-mutations.js +24 -16
  10. package/dist/commands/deploy-runtime-bindings.js +7 -26
  11. package/dist/commands/deploy-ssr.js +5 -24
  12. package/dist/commands/mesh.js +6 -2
  13. package/dist/commands/signals-run.d.ts +43 -2
  14. package/dist/commands/signals-run.js +85 -7
  15. package/dist/commands/sync-core.d.ts +7 -0
  16. package/dist/commands/sync-core.js +52 -3
  17. package/dist/lib/bot/continuity.d.ts +21 -2
  18. package/dist/lib/bot/continuity.js +48 -19
  19. package/dist/lib/bot/fleet-cron.js +6 -0
  20. package/dist/lib/bot/fleet-local.d.ts +11 -1
  21. package/dist/lib/bot/fleet-local.js +21 -1
  22. package/dist/lib/bot/fleet-state.d.ts +129 -0
  23. package/dist/lib/bot/fleet-state.js +669 -0
  24. package/dist/lib/bot/promote.d.ts +9 -3
  25. package/dist/lib/bot/promote.js +115 -16
  26. package/dist/lib/daemon/catalog.d.ts +13 -0
  27. package/dist/lib/daemon/catalog.js +32 -6
  28. package/dist/lib/daemon/lanes-reconcile-status.d.ts +0 -4
  29. package/dist/lib/daemon/lanes-reconcile-status.js +2 -12
  30. package/dist/lib/daemon/lanes-reconcile-watcher.d.ts +1 -1
  31. package/dist/lib/daemon/lanes-reconcile-watcher.js +2 -1
  32. package/dist/lib/daemon/legacy-handover.d.ts +38 -0
  33. package/dist/lib/daemon/legacy-handover.js +117 -0
  34. package/dist/lib/daemon/mesh-owner.js +2 -1
  35. package/dist/lib/daemon/run.d.ts +18 -1
  36. package/dist/lib/daemon/run.js +85 -12
  37. package/dist/lib/daemon/selfcheck.d.ts +28 -0
  38. package/dist/lib/daemon/selfcheck.js +86 -15
  39. package/dist/lib/deploy-api.d.ts +1 -1
  40. package/dist/lib/deploy-api.js +2 -1
  41. package/dist/lib/deploy-identity.d.ts +18 -0
  42. package/dist/lib/deploy-identity.js +179 -0
  43. package/dist/lib/hot-channels/alert.js +13 -6
  44. package/dist/lib/hot-channels/fleet-complete.d.ts +89 -0
  45. package/dist/lib/hot-channels/fleet-complete.js +157 -0
  46. package/dist/lib/hot-channels/run.js +2 -1
  47. package/dist/lib/hot-channels/signals-claude-login.d.ts +3 -2
  48. package/dist/lib/hot-channels/signals-claude-login.js +6 -1
  49. package/dist/lib/hot-channels/signals-pass-failure.d.ts +29 -0
  50. package/dist/lib/hot-channels/signals-pass-failure.js +36 -0
  51. package/dist/lib/hot-channels/signals-pass.d.ts +49 -2
  52. package/dist/lib/hot-channels/signals-pass.js +188 -12
  53. package/dist/lib/hot-channels/signals-runtime.d.ts +6 -3
  54. package/dist/lib/hot-channels/signals-runtime.js +11 -2
  55. package/dist/lib/lanes/reconcile-result.d.ts +5 -0
  56. package/dist/lib/lanes/reconcile-result.js +20 -2
  57. package/dist/lib/lanes/reconcile.js +12 -3
  58. package/dist/lib/mesh/live/emit.js +25 -6
  59. package/dist/lib/mesh/live/flush.js +119 -15
  60. package/dist/lib/mesh/live/reporting-privacy.d.ts +41 -0
  61. package/dist/lib/mesh/live/reporting-privacy.js +147 -1
  62. package/dist/lib/mesh/live/spool.d.ts +16 -0
  63. package/dist/lib/mesh/live/spool.js +45 -0
  64. package/dist/lib/signals/engine.d.ts +17 -3
  65. package/dist/lib/signals/engine.js +28 -9
  66. package/dist/lib/signals/failure-alert.d.ts +33 -1
  67. package/dist/lib/signals/failure-alert.js +72 -5
  68. package/dist/lib/signals/owner-notice.d.ts +94 -0
  69. package/dist/lib/signals/owner-notice.js +233 -0
  70. package/dist/lib/signals/reply.d.ts +7 -0
  71. package/dist/lib/signals/reply.js +23 -3
  72. package/dist/lib/signals/steps/adapters.d.ts +51 -2
  73. package/dist/lib/signals/steps/adapters.js +213 -7
  74. package/dist/lib/signals/steps/extract.js +18 -4
  75. package/dist/lib/signals/steps/types.d.ts +63 -1
  76. package/dist/lib/signals/steps/types.js +32 -0
  77. package/dist/lib/sync-core/engine-auth.d.ts +35 -0
  78. package/dist/lib/sync-core/engine-auth.js +96 -0
  79. package/dist/lib/sync-core/engine-home.d.ts +6 -0
  80. package/dist/lib/sync-core/engine-home.js +12 -0
  81. package/dist/lib/sync-core/rollout-state.d.ts +1 -0
  82. package/dist/lib/sync-core/rollout-state.js +3 -0
  83. package/dist/lib/vault-sync-switches.d.ts +7 -0
  84. package/dist/lib/vault-sync-switches.js +56 -0
  85. package/dist/lib/work-context/errors.d.ts +12 -0
  86. package/dist/lib/work-context/errors.js +15 -0
  87. package/dist/lib/work-context/organize.js +6 -1
  88. package/dist/lib/work-context/reconcile.js +20 -1
  89. package/dist/utils/resident-package-preload.js +34 -4
  90. package/docs/anywhere-runtime.md +6 -0
  91. package/package.json +7 -7
@@ -1,5 +1,6 @@
1
1
  import * as fs from "node:fs";
2
2
  import { enabledServices } from "./catalog.js";
3
+ import { engineVaultCount } from "../sync-core/rollout-state.js";
3
4
  import { readDaemonConfig } from "./config.js";
4
5
  import { hostedDaemonRunning, recentlyHostedDaemon } from "./handoff.js";
5
6
  import { clearHealPending, healPending, homeIsLoginSafe, isLoginHome, jobLoadedFromHome, meshUnitFromOtherHome, removeMeshUnitFromOtherHome } from "../mesh/live/daemon/unit-home.js";
@@ -27,7 +28,7 @@ export function meshOwnerHere(home, env, deps = {}) {
27
28
  existsSync: fs.existsSync,
28
29
  readFileSync: (p) => fs.readFileSync(p, "utf8"),
29
30
  }).type;
30
- return enabledServices(machineType, config).includes("mesh") ? "hq-daemon" : "hq-daemon-mesh-off";
31
+ return enabledServices(machineType, config, { engineVaults: engineVaultCount(home) }).includes("mesh") ? "hq-daemon" : "hq-daemon-mesh-off";
31
32
  }
32
33
  function daemonRunsElsewhere(home, env) {
33
34
  const paths = daemonPaths(home, env);
@@ -7,9 +7,11 @@
7
7
  */
8
8
  import { acquirePackageUseLease } from "../../utils/package-use-lease.js";
9
9
  import { type LegacySyncHolder, type PlanContext, type ServiceName, type UnitPlan } from "./catalog.js";
10
+ import { type LegacyHandover } from "./legacy-handover.js";
10
11
  import { type SyncCoreVaultPlan } from "../sync-core/engine-home.js";
11
12
  import { type DaemonFlagRegistryRead, type DaemonFlagSnapshotSource } from "./flag.js";
12
13
  import { type LegacyUnit, type WindowsTaskOwner } from "./legacy.js";
14
+ import { type VaultSwitchOnTimes, type VaultSyncSwitches } from "../vault-sync-switches.js";
13
15
  import { type DaemonLockResult } from "./lock.js";
14
16
  import { removeMeshUnitFromOtherHome, type LaunchctlRunner } from "../mesh/live/daemon/unit-home.js";
15
17
  import { type MeshUnitRepairResult } from "../mesh/live/daemon/install.js";
@@ -21,7 +23,21 @@ export declare const LOG_ROTATE_BYTES: number;
21
23
  /** Exit code for "restart me": non-zero so every service manager relaunches (Windows tasks only restart on failure). */
22
24
  export declare const RESTART_EXIT_CODE = 75;
23
25
  export declare function syncCoreVaultPlans(home: string, hqRoot: string | undefined, platform: NodeJS.Platform): SyncCoreVaultPlan[];
24
- export declare function planUnitsWithSyncCoreInterlock(services: readonly ServiceName[], context: PlanContext, supervisor: Pick<Supervisor, "runningPlanKey" | "state"> | null | undefined, readOwnerStatus: () => WatchRunnerOwnerStatus | null): UnitPlan[];
26
+ export declare function planUnitsWithSyncCoreInterlock(services: readonly ServiceName[], context: PlanContext, supervisor: Pick<Supervisor, "runningPlanKey" | "state"> | null | undefined, readOwnerStatus: () => WatchRunnerOwnerStatus | null, handover?: LegacyHandover, readSwitchOnTimes?: () => VaultSwitchOnTimes): UnitPlan[];
27
+ export interface LegacyRestoreWait {
28
+ what: string;
29
+ /** When HQ turned the vault's old-sync switch back on. */
30
+ since: number;
31
+ }
32
+ /**
33
+ * Vaults whose old-sync switch HQ turned back on (a rollback, or a held engine)
34
+ * after the running old sync started: that runner still skips them until it
35
+ * restarts, so they have no sync at all until then.
36
+ */
37
+ export declare function legacyRestoreWaits(vaultSync: VaultSyncSwitches | undefined, onTimes: VaultSwitchOnTimes, holder: LegacySyncHolder | undefined, engineStillRunning?: {
38
+ personal: boolean;
39
+ companies: ReadonlySet<string>;
40
+ }): LegacyRestoreWait[];
25
41
  export declare function legacySyncHeldByOtherOwner(units: DaemonState["units"], readOwnerStatus: () => WatchRunnerOwnerStatus | null): LegacySyncHolder | undefined;
26
42
  /** A bounded shutdown deadline that can account for sync push persistence. */
27
43
  export declare function createShutdownCap(): {
@@ -63,6 +79,7 @@ export declare function hqdListenerRuntimeAllowed(env: NodeJS.ProcessEnv, readSe
63
79
  /** Route an updater request through the daemon's existing graceful handoff. */
64
80
  export declare function handoffForPackageUpdateRequest(requested: boolean, restartDaemon: () => void): void;
65
81
  export interface RunDaemonOptions {
82
+ legacyHandover?: LegacyHandover;
66
83
  removeMeshUnitFromOtherHome?: typeof removeMeshUnitFromOtherHome;
67
84
  isLoginHome?: (home: string) => boolean;
68
85
  foreground?: boolean;
@@ -24,13 +24,14 @@ import { agentKitPaths } from "../agent-kit/paths.js";
24
24
  import { HQ_FLEET_RUNTIME_ENGINE_ID, readBotConfig } from "../bot/config.js";
25
25
  import { clearStaleReadyBeforeGatewayStart, planFleetBots } from "../bot/fleet-daemon.js";
26
26
  import { botsRoot } from "../bot/paths.js";
27
- import { CLAUDE_RUNNER_SCRIPT, CODEX_RUNNER_SCRIPT, enabledServices, planUnits, SEARCH_INDEX_WORKER_UNAVAILABLE } from "./catalog.js";
27
+ import { CLAUDE_RUNNER_SCRIPT, CODEX_RUNNER_SCRIPT, enabledServices, planUnits, SEARCH_INDEX_WORKER_UNAVAILABLE, isLegacyRestartWait } from "./catalog.js";
28
+ import { createLegacyHandover, LEGACY_HANDOVER_STUCK_FILE, writeLegacyHandoverStuck } from "./legacy-handover.js";
28
29
  import { effectiveSyncOwner, readDaemonConfig } from "./config.js";
29
30
  import { backgroundQosCommand } from "./background-qos.js";
30
31
  import { serveQmdWorker } from "../search-index/worker-process.js";
31
32
  import { inspectEngineHome } from "../sync-core/engine-home.js";
32
33
  import { fullModeHold } from "../sync-core/reconcile.js";
33
- import { readSyncCoreRolloutState } from "../sync-core/rollout-state.js";
34
+ import { engineVaultCount, readSyncCoreRolloutState } from "../sync-core/rollout-state.js";
34
35
  import { effectiveEngineSettings, readSyncCoreVaultSettings } from "../sync-core/vault-settings.js";
35
36
  import { assertPersonalServiceSessionCapability, readRemoteControlPoolsConfig, remoteControlPoolSecretsEnv, } from "./remote-control-pools.js";
36
37
  import { loadLanesConfig } from "../lanes/config.js";
@@ -46,7 +47,7 @@ import { createLanesReconcileWatcher } from "./lanes-reconcile-watcher.js";
46
47
  import { createLanesReconcileStatus, withLanesReconcileUnit } from "./lanes-reconcile-status.js";
47
48
  import { findLegacyUnits, legacyMeshUnitsToRetire, legacyOwnerLookup, } from "./legacy.js";
48
49
  import { readLegacySyncEnv } from "./legacy-sync-env.js";
49
- import { readVaultSyncSwitches, unreadableSwitchesWarning, writeVaultSyncSwitches } from "../vault-sync-switches.js";
50
+ import { readVaultSwitchOnTimes, readVaultSyncSwitches, unreadableSwitchesWarning, writeVaultSyncSwitches } from "../vault-sync-switches.js";
50
51
  import { scheduleDaemonPlistRefresh } from "./plist-refresh.js";
51
52
  import { acquireDaemonLock, isProcessAlive, processCommandLine, releaseDaemonLock } from "./lock.js";
52
53
  import { retireLegacyMeshUnits } from "./migrate.js";
@@ -113,7 +114,7 @@ export function syncCoreVaultPlans(home, hqRoot, platform) {
113
114
  });
114
115
  }
115
116
  const rememberedSyncCoreVaults = new Map();
116
- export function planUnitsWithSyncCoreInterlock(services, context, supervisor, readOwnerStatus) {
117
+ export function planUnitsWithSyncCoreInterlock(services, context, supervisor, readOwnerStatus, handover, readSwitchOnTimes = () => ({ companies: {} })) {
117
118
  const companies = new Set();
118
119
  const runningVaults = new Set();
119
120
  let personal = false;
@@ -180,18 +181,74 @@ export function planUnitsWithSyncCoreInterlock(services, context, supervisor, re
180
181
  waiting = planUnits(services, transitionContext);
181
182
  legacy = waiting.find((unit) => unit.id === "sync");
182
183
  }
183
- const holder = context.syncCoreVaults?.some((vault) => vault.phase === "full")
184
+ let onTimes;
185
+ try {
186
+ onTimes = readSwitchOnTimes();
187
+ }
188
+ catch {
189
+ onTimes = { companies: {} };
190
+ }
191
+ const anyTurnedOn = onTimes.personal !== undefined || Object.keys(onTimes.companies).length > 0;
192
+ const holder = context.syncCoreVaults?.some((vault) => vault.phase === "full") || anyTurnedOn
184
193
  ? legacySyncHeldByOtherOwner(supervisor?.state().units ?? [], readOwnerStatus)
185
194
  : undefined;
186
195
  const legacySyncReadyForCore = legacy !== undefined
187
196
  && (legacy.blocked !== undefined
188
197
  || holder !== undefined
189
198
  || supervisor?.runningPlanKey("sync") === planKey(legacy, CLI_VERSION));
190
- return planUnits(services, {
199
+ const planned = {
191
200
  ...transitionContext,
192
201
  legacySyncReadyForCore,
193
202
  ...(holder !== undefined ? { legacySyncHolder: holder } : {}),
194
- });
203
+ };
204
+ let plans = planUnits(services, planned);
205
+ if (!handover)
206
+ return plans;
207
+ const vaultName = (uid) => {
208
+ const vault = context.syncCoreVaults?.find((v) => v.uid === uid);
209
+ return vault?.kind === "personal" ? "the personal vault" : `the ${vault?.slug ?? uid} vault`;
210
+ };
211
+ const toEngine = plans
212
+ .filter((unit) => unit.id.startsWith("sync-core:") && isLegacyRestartWait(unit.blocked))
213
+ .map((unit) => vaultName(unit.id.slice("sync-core:".length)));
214
+ const engineStillRunning = { personal: false, companies: new Set() };
215
+ for (const uid of runningVaults) {
216
+ const vault = rememberedSyncCoreVaults.get(uid);
217
+ if (vault?.kind === "personal")
218
+ engineStillRunning.personal = true;
219
+ else if (vault?.slug)
220
+ engineStillRunning.companies.add(vault.slug);
221
+ }
222
+ const restores = legacyRestoreWaits(transitionContext.vaultSync, onTimes, holder, engineStillRunning);
223
+ if (holder?.status === "started" && (toEngine.length > 0 || restores.length > 0)) {
224
+ handover.request(holder, [...toEngine, ...restores.map((wait) => wait.what)]);
225
+ }
226
+ handover.reportRestoreWaits(holder, restores);
227
+ const stopRequestedAt = handover.requestedAt(holder);
228
+ if (stopRequestedAt !== undefined && toEngine.length > 0) {
229
+ plans = planUnits(services, { ...planned, legacyHandoverStopRequestedAt: stopRequestedAt });
230
+ }
231
+ return plans;
232
+ }
233
+ /**
234
+ * Vaults whose old-sync switch HQ turned back on (a rollback, or a held engine)
235
+ * after the running old sync started: that runner still skips them until it
236
+ * restarts, so they have no sync at all until then.
237
+ */
238
+ export function legacyRestoreWaits(vaultSync, onTimes, holder, engineStillRunning = { personal: false, companies: new Set() }) {
239
+ if (holder?.status !== "started" || vaultSync?.allOff === true)
240
+ return [];
241
+ const waits = [];
242
+ const add = (what, at, off) => {
243
+ const since = at ? Date.parse(at) : Number.NaN;
244
+ if (!off && Number.isFinite(since) && holder.startedAt < since)
245
+ waits.push({ what, since });
246
+ };
247
+ add("the personal vault", onTimes.personal, vaultSync?.personalOff === true || engineStillRunning.personal);
248
+ for (const [slug, at] of Object.entries(onTimes.companies).sort(([a], [b]) => a.localeCompare(b))) {
249
+ add(`the ${slug} vault`, at, vaultSync?.offCompanies.has(slug) === true || engineStillRunning.companies.has(slug));
250
+ }
251
+ return waits;
195
252
  }
196
253
  export function legacySyncHeldByOtherOwner(units, readOwnerStatus) {
197
254
  const sync = units.find((unit) => unit.id === "sync");
@@ -212,7 +269,7 @@ export function legacySyncHeldByOtherOwner(units, readOwnerStatus) {
212
269
  if (retrying && sync.pid !== undefined && owner.pid === sync.pid)
213
270
  return undefined;
214
271
  const startedAt = Date.parse(owner.startedAt);
215
- return Number.isFinite(startedAt) ? { status: "started", startedAt } : { status: "unreadable" };
272
+ return Number.isFinite(startedAt) ? { status: "started", startedAt, pid: owner.pid, owner: owner.owner } : { status: "unreadable" };
216
273
  }
217
274
  /** A bounded shutdown deadline that can account for sync push persistence. */
218
275
  export function createShutdownCap() {
@@ -961,7 +1018,7 @@ export async function runDaemon(opts) {
961
1018
  }
962
1019
  return legacyCache.units;
963
1020
  };
964
- const meshEnabled = enabledServices(machineType, initial).includes("mesh");
1021
+ const meshEnabled = enabledServices(machineType, initial, { engineVaults: engineVaultCount(home) }).includes("mesh");
965
1022
  const launchctl = (command, args) => {
966
1023
  const r = spawnSync(command, args, { encoding: "utf8", windowsHide: true, timeout: 15_000 });
967
1024
  return { status: r.status, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
@@ -998,7 +1055,7 @@ export async function runDaemon(opts) {
998
1055
  platform,
999
1056
  managed: opts.managed === true,
1000
1057
  hosted: opts.host !== undefined,
1001
- meshEnabled: enabledServices(machineType, initial).includes("mesh"),
1058
+ meshEnabled,
1002
1059
  }, {
1003
1060
  run: (command, args) => {
1004
1061
  const r = spawnSync(command, args, { encoding: "utf8", windowsHide: true, timeout: 15_000 });
@@ -1018,6 +1075,22 @@ export async function runDaemon(opts) {
1018
1075
  }
1019
1076
  legacyCache = null;
1020
1077
  }
1078
+ const legacyHandover = opts.legacyHandover ?? createLegacyHandover({
1079
+ now: Date.now,
1080
+ selfPid: process.pid,
1081
+ isAlive: (pid) => isProcessAlive(pid),
1082
+ commandLine: (pid) => processCommandLine(pid, {
1083
+ platform,
1084
+ run: (file, args) => {
1085
+ const r = spawnSync(file, args, { encoding: "utf8", windowsHide: true, timeout: 15_000 });
1086
+ return { status: r.status, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
1087
+ },
1088
+ }),
1089
+ signal: (pid, sig) => process.kill(pid, sig),
1090
+ platform,
1091
+ writeRestoreStuck: (stuck) => writeLegacyHandoverStuck(path.join(paths.root, LEGACY_HANDOVER_STUCK_FILE), stuck),
1092
+ log: (level, message) => log(level, message),
1093
+ });
1021
1094
  const meshOwnerReason = () => {
1022
1095
  const lockPath = meshDaemonPidPath(meshDaemonDir(undefined, home, env));
1023
1096
  const owner = readPidLock(lockPath);
@@ -1463,7 +1536,7 @@ export async function runDaemon(opts) {
1463
1536
  }
1464
1537
  const packageRunners = hqCloud ? hqCloudRunners(hqCloud.root) : { syncRunner: null, heartbeat: null, sessionHost: null };
1465
1538
  const runners = { ...packageRunners, syncRunner: syncSource.runnerPath };
1466
- const services = enabledServices(machineType, config);
1539
+ const services = enabledServices(machineType, config, { engineVaults: engineVaultCount(home) });
1467
1540
  const isSignedIn = signedIn(env, home, log);
1468
1541
  lastPlanSignedIn = isSignedIn;
1469
1542
  lastPlanServices = services;
@@ -1564,7 +1637,7 @@ export async function runDaemon(opts) {
1564
1637
  };
1565
1638
  const plans = planUnitsWithSyncCoreInterlock(services, context, supervisor, () => hqRoot
1566
1639
  ? readWatchRunnerOwnerStatus(watchRunnerOwnerStatusPath(hqRoot, home, env))
1567
- : null);
1640
+ : null, legacyHandover, () => readVaultSwitchOnTimes(home));
1568
1641
  if (startupPlanOpen) {
1569
1642
  const replaceablePackageRoots = cliPackageRoot ? [cliPackageRoot] : [];
1570
1643
  if (hqCloud?.source === "bundled")
@@ -20,6 +20,8 @@ export interface EngineUnitProblem {
20
20
  since: number;
21
21
  /** One line for the DM. */
22
22
  what: string;
23
+ /** Already past its own bound when it first shows (a stuck handover), so it is reported without the 30-minute wait. */
24
+ urgent?: boolean;
23
25
  }
24
26
  /** Engine units held, or failing without a heartbeat, for more than ATTENTION_AFTER_MS at `now`. */
25
27
  export declare function engineUnitsNeedingAttention(state: DaemonState | null, holds: PersistedHolds, now: number,
@@ -38,6 +40,8 @@ export interface WakeProblem {
38
40
  export interface WakeWatch {
39
41
  notLiveSince: number;
40
42
  checkedAt: number;
43
+ /** When the self-check last restarted or took over Work Mesh while the marker was not live. */
44
+ repairedAt?: number;
41
45
  }
42
46
  export declare const WAKE_WATCH_GAP_MS: number;
43
47
  export declare function readWakeWatch(file: string): WakeWatch | null;
@@ -92,6 +96,11 @@ vaultName?: (vaultUid: string) => string | undefined, wake?: WakeProblem | null)
92
96
  body: string;
93
97
  details: string;
94
98
  };
99
+ export interface EngineAuthRefusalProblem {
100
+ unitId: string;
101
+ since: number;
102
+ what: string;
103
+ }
95
104
  export interface SelfCheckDeps {
96
105
  statePath: string;
97
106
  holdsPath: string;
@@ -119,8 +128,27 @@ export interface SelfCheckDeps {
119
128
  markerPath: string;
120
129
  watchPath: string;
121
130
  meshWanted: () => boolean;
131
+ /** Restart Work Mesh or take it over from an older unit; resolves to what was done, or null when nothing could be. */
132
+ repairMesh?: () => Promise<string | null>;
133
+ /** Where the last repair time is kept, so repairs stay at most one per MESH_REPAIR_MIN_INTERVAL_MS. */
134
+ repairPath?: string;
122
135
  };
136
+ /** Vaults switched back to the current sync that the running old sync has skipped for over the bound. */
137
+ readRestoreStuck?: () => readonly {
138
+ what: string;
139
+ since: number;
140
+ reason: string;
141
+ }[];
142
+ /**
143
+ * Engine units whose cycles the sync service keeps refusing (HTTP 401). The
144
+ * unit runs and heartbeats, so the unit checks above see it as healthy.
145
+ */
146
+ readAuthRefusals?: () => readonly EngineAuthRefusalProblem[] | Promise<readonly EngineAuthRefusalProblem[]>;
123
147
  }
148
+ export declare const MESH_REPAIR_MIN_INTERVAL_MS: number;
149
+ export declare const MESH_HELD_BY_OLDER_UNIT = "already run by ";
150
+ /** What the self-check does about Work Mesh when change notifications are not live. */
151
+ export declare function meshRepairAction(state: DaemonState | null): "take-over" | "restart" | null;
124
152
  export type SelfCheckOutcome = "healthy" | "reported" | "already-reported" | "no-owner";
125
153
  export declare function runSelfCheck(deps: SelfCheckDeps): Promise<SelfCheckOutcome>;
126
154
  //# sourceMappingURL=selfcheck.d.ts.map
@@ -11,6 +11,7 @@
11
11
  import * as fs from "node:fs";
12
12
  import * as path from "node:path";
13
13
  import { syncCoreUnitId } from "../sync-core/engine-home.js";
14
+ import { LEGACY_HANDOVER_STUCK_PREFIX } from "./catalog.js";
14
15
  import { ensurePrivateDir, readStoreFile, writeStoreFile } from "./paths.js";
15
16
  /** An engine unit that has been held or failing this long needs a person. */
16
17
  export const ATTENTION_AFTER_MS = 30 * 60_000;
@@ -31,7 +32,7 @@ wanted = () => true) {
31
32
  continue;
32
33
  seen.add(unit.id);
33
34
  const problem = unitProblem(unit, holds[unit.id], state, now);
34
- if (problem && now - problem.since > ATTENTION_AFTER_MS)
35
+ if (problem && (problem.urgent === true || now - problem.since > ATTENTION_AFTER_MS))
35
36
  problems.push(problem);
36
37
  }
37
38
  // With no daemon state, the persisted holds are all there is to go on. With
@@ -59,7 +60,9 @@ function unitProblem(unit, hold, state, now) {
59
60
  const detail = unit.hold?.detail ?? hold?.detail ?? unit.reason ?? "held";
60
61
  return { unitId: unit.id, since, what: `held since ${iso(since)}: ${detail}` };
61
62
  }
62
- // Paused on purpose (sync paused, waiting for the legacy sync to hand over) is not failing.
63
+ if (unit.status === "waiting" && unit.reason?.startsWith(LEGACY_HANDOVER_STUCK_PREFIX)) {
64
+ return { unitId: unit.id, since: now, what: unit.reason, urgent: true };
65
+ }
63
66
  if (unit.status !== "backoff" && unit.status !== "exited" && unit.status !== "running")
64
67
  return null;
65
68
  const last = unit.lastHeartbeatAt ? Date.parse(unit.lastHeartbeatAt) : Number.NaN;
@@ -117,7 +120,7 @@ export function readWakeWatch(file) {
117
120
  const parsed = JSON.parse(text);
118
121
  const ok = (v) => typeof v === "number" && Number.isFinite(v);
119
122
  return ok(parsed?.notLiveSince) && ok(parsed.checkedAt)
120
- ? { notLiveSince: parsed.notLiveSince, checkedAt: parsed.checkedAt }
123
+ ? { notLiveSince: parsed.notLiveSince, checkedAt: parsed.checkedAt, ...(ok(parsed.repairedAt) ? { repairedAt: parsed.repairedAt } : {}) }
121
124
  : null;
122
125
  }
123
126
  catch (error) {
@@ -223,48 +226,116 @@ export function selfCheckMessage(problems, machine,
223
226
  /** A name for a vault (company slug, "personal"), when known. */
224
227
  vaultName = () => undefined, wake = null) {
225
228
  const named = (p) => {
229
+ if (!p.unitId.startsWith(ENGINE_UNIT_PREFIX))
230
+ return "the old sync";
226
231
  const uid = p.unitId.slice(ENGINE_UNIT_PREFIX.length);
227
232
  const name = vaultName(uid);
228
233
  return name ? `${name} (${uid})` : uid;
229
234
  };
230
- const names = problems.map(named).join(", ");
231
- const body = problems.length > 0
235
+ const engineProblems = problems.filter((p) => p.unitId.startsWith(ENGINE_UNIT_PREFIX));
236
+ const names = engineProblems.map(named).join(", ");
237
+ const body = engineProblems.length > 0
232
238
  ? `HQ sync on ${machine}: the sync engine for ${names} has not synced for over ${ATTENTION_AFTER_MS / 60_000} minutes. ` +
233
239
  "Run `hq daemon status` on that machine."
234
- : `HQ sync on ${machine}: the sync engine is running without change notifications, so it only polls and other machines' changes can arrive up to 30 minutes late. ` +
235
- "Run `hq daemon status` and `hq daemon doctor` on that machine.";
236
- const lines = problems.map((p) => `- ${named(p)}: ${p.what}. Retry with: hq daemon restart ${p.unitId}`);
240
+ : problems.length > 0
241
+ ? `HQ sync on ${machine}: a vault switched back to the current sync is not syncing, because the running sync started before the switch. ` +
242
+ "Run `hq sync-core status` on that machine."
243
+ : `HQ sync on ${machine}: the sync engine is running without change notifications, so it only polls and other machines' changes can arrive up to 30 minutes late. ` +
244
+ "Run `hq daemon status` and `hq daemon doctor` on that machine.";
245
+ const lines = problems.map((p) => p.urgent
246
+ ? `- ${named(p)}: ${p.what}.`
247
+ : `- ${named(p)}: ${p.what}. Retry with: hq daemon restart ${p.unitId}`);
237
248
  if (wake)
238
249
  lines.push(`- change notifications: ${wake.what}. Check with: hq daemon status and hq daemon doctor`);
239
250
  lines.push("", "Logs: hq daemon logs <unit>. This check runs in hq daemon and sends at most one DM a day from this machine.");
240
251
  return { body, details: lines.join("\n") };
241
252
  }
242
- function checkWake(deps, state, now) {
253
+ export const MESH_REPAIR_MIN_INTERVAL_MS = 3 * 60 * 60_000;
254
+ function readLastRepair(file) {
255
+ if (!file)
256
+ return undefined;
257
+ try {
258
+ const at = JSON.parse(fs.readFileSync(file, "utf8")).at;
259
+ return typeof at === "number" && Number.isFinite(at) ? at : undefined;
260
+ }
261
+ catch {
262
+ return undefined;
263
+ }
264
+ }
265
+ async function checkWake(deps, state, now) {
243
266
  if (!deps.wake)
244
267
  return null;
245
268
  try {
269
+ const watch = readWakeWatch(deps.wake.watchPath);
246
270
  const assessment = assessWake({
247
271
  engineRunning: deps.wake.meshWanted() && engineIsRunning(state, deps.wanted),
248
272
  marker: readWakeMarker(deps.wake.markerPath),
249
- watch: readWakeWatch(deps.wake.watchPath),
273
+ watch,
250
274
  now,
251
275
  });
252
- if (assessment.live)
276
+ if (assessment.live) {
253
277
  fs.rmSync(deps.wake.watchPath, { force: true });
254
- else
255
- writeSelfCheckRecordFile(deps.wake.watchPath, { notLiveSince: assessment.notLiveSince ?? now, checkedAt: now });
256
- return assessment.problem;
278
+ return null;
279
+ }
280
+ const earlierRepair = watch?.repairedAt;
281
+ let repaired = null;
282
+ const lastRepair = readLastRepair(deps.wake.repairPath);
283
+ const repairDue = lastRepair === undefined || now - lastRepair >= MESH_REPAIR_MIN_INTERVAL_MS;
284
+ if (deps.wake.repairMesh && repairDue) {
285
+ try {
286
+ repaired = await deps.wake.repairMesh();
287
+ }
288
+ catch (error) {
289
+ deps.log(`sync engine self-check: could not repair Work Mesh (${error.message})`);
290
+ }
291
+ if (repaired && deps.wake.repairPath)
292
+ writeSelfCheckRecordFile(deps.wake.repairPath, { at: now });
293
+ }
294
+ else if (deps.wake.repairMesh) {
295
+ deps.log(`sync engine self-check: Work Mesh was last repaired at ${iso(lastRepair)}; not repairing again before ${iso(lastRepair + MESH_REPAIR_MIN_INTERVAL_MS)}`);
296
+ }
297
+ if (repaired)
298
+ deps.log(`sync engine self-check: change notifications are not live; ${repaired}`);
299
+ const repairedAt = repaired ? now : earlierRepair;
300
+ writeSelfCheckRecordFile(deps.wake.watchPath, {
301
+ notLiveSince: assessment.notLiveSince ?? now,
302
+ checkedAt: now,
303
+ ...(repairedAt !== undefined ? { repairedAt } : {}),
304
+ });
305
+ // The first repair gets one check to work before the owner hears about it.
306
+ return repaired && earlierRepair === undefined ? null : assessment.problem;
257
307
  }
258
308
  catch (error) {
259
309
  deps.log(`sync engine self-check: could not check change notifications (${error.code ?? error.message})`);
260
310
  return null;
261
311
  }
262
312
  }
313
+ export const MESH_HELD_BY_OLDER_UNIT = "already run by ";
314
+ /** What the self-check does about Work Mesh when change notifications are not live. */
315
+ export function meshRepairAction(state) {
316
+ const mesh = state?.units.find((unit) => unit.id === "mesh");
317
+ if (!mesh)
318
+ return null;
319
+ if (mesh.status === "waiting" && mesh.reason?.startsWith(MESH_HELD_BY_OLDER_UNIT))
320
+ return "take-over";
321
+ if (mesh.status === "running" || mesh.status === "backoff" || mesh.status === "exited")
322
+ return "restart";
323
+ return null;
324
+ }
263
325
  export async function runSelfCheck(deps) {
264
326
  const now = deps.now();
265
327
  const state = deps.readState();
266
328
  const problems = engineUnitsNeedingAttention(state, deps.readHolds(), now, deps.wanted);
267
- const wake = checkWake(deps, state, now);
329
+ const flagged = new Set(problems.map((p) => p.unitId));
330
+ for (const refused of (await deps.readAuthRefusals?.()) ?? []) {
331
+ if (flagged.has(refused.unitId))
332
+ continue;
333
+ problems.push({ unitId: refused.unitId, since: refused.since, what: refused.what, urgent: true });
334
+ }
335
+ for (const stuck of deps.readRestoreStuck?.() ?? []) {
336
+ problems.push({ unitId: "sync", since: stuck.since, what: stuck.reason, urgent: true });
337
+ }
338
+ const wake = await checkWake(deps, state, now);
268
339
  if (deps.resultPath) {
269
340
  try {
270
341
  writeSelfCheckResult(deps.resultPath, { checkedAt: now, problems: problems.length });
@@ -3,5 +3,5 @@ export declare const DEPLOY_API_URL: string;
3
3
  export declare function deployHeaders(token: string, json?: boolean, extra?: Record<string, string>): Record<string, string>;
4
4
  export declare function deployApiRequest(token: string, route: string, method: string, body?: unknown, extraHeaders?: Record<string, string>, options?: Pick<RequestInit, "redirect">): Promise<Response>;
5
5
  /** Submit an app archive on the authenticated multipart route. Fetch owns the boundary. */
6
- export declare function deployApiFormRequest(token: string, route: string, body: FormData, extraHeaders: Record<string, string>): Promise<Response>;
6
+ export declare function deployApiFormRequest(token: string, route: string, body: FormData, extraHeaders: Record<string, string>, signal?: AbortSignal): Promise<Response>;
7
7
  //# sourceMappingURL=deploy-api.d.ts.map
@@ -22,12 +22,13 @@ export async function deployApiRequest(token, route, method, body, extraHeaders
22
22
  });
23
23
  }
24
24
  /** Submit an app archive on the authenticated multipart route. Fetch owns the boundary. */
25
- export function deployApiFormRequest(token, route, body, extraHeaders) {
25
+ export function deployApiFormRequest(token, route, body, extraHeaders, signal) {
26
26
  return fetch(deployApiUrl(route), {
27
27
  method: "POST",
28
28
  headers: deployHeaders(token, false, extraHeaders),
29
29
  body,
30
30
  redirect: "error",
31
+ ...(signal ? { signal } : {}),
31
32
  });
32
33
  }
33
34
  //# sourceMappingURL=deploy-api.js.map
@@ -0,0 +1,18 @@
1
+ export declare class DeployIdentityError extends Error {
2
+ }
3
+ interface DeployScope {
4
+ company?: string;
5
+ personal?: boolean;
6
+ }
7
+ interface IdentityOptions {
8
+ personOnly?: boolean;
9
+ companion?: boolean;
10
+ }
11
+ type SendDeployRequest = (bearer: string, headers: Record<string, string>) => Promise<Response>;
12
+ type ScopedRequest = (send: SendDeployRequest, options?: {
13
+ recoverUnauthorized?: boolean;
14
+ }) => Promise<Response>;
15
+ /** Pin the selected principal and scope for the lifetime of a deploy command. */
16
+ export declare function openDeployIdentity(scope: DeployScope, options?: IdentityOptions): Promise<ScopedRequest>;
17
+ export {};
18
+ //# sourceMappingURL=deploy-identity.d.ts.map