@indigoai-us/hq-cli 5.345.251 → 5.345.252

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 (160) hide show
  1. package/CHANGELOG.md +112 -0
  2. package/assets/scaffold/core/scripts/hq-session.sh +9 -0
  3. package/contracts/host-canary-release.json +9 -3
  4. package/dist/command-catalog.generated.d.ts +121 -1
  5. package/dist/command-catalog.generated.js +148 -1
  6. package/dist/commands/bot.js +7 -2
  7. package/dist/commands/core-bucket-c-work-mesh-offer-native.js +1 -1
  8. package/dist/commands/core-hq-session-binding.d.ts +140 -0
  9. package/dist/commands/core-hq-session-binding.js +363 -0
  10. package/dist/commands/core-hq-session-native.d.ts +23 -0
  11. package/dist/commands/core-hq-session-native.js +59 -9
  12. package/dist/commands/core-stop-autosave.js +1 -1
  13. package/dist/commands/core.js +10 -0
  14. package/dist/commands/doctor.d.ts +5 -1
  15. package/dist/commands/doctor.js +42 -5
  16. package/dist/commands/files.js +1 -1
  17. package/dist/commands/install-global.js +4 -2
  18. package/dist/commands/logout.js +4 -0
  19. package/dist/commands/ontology-graph.d.ts +2 -0
  20. package/dist/commands/ontology-graph.js +33 -0
  21. package/dist/commands/report.js +35 -2
  22. package/dist/commands/storage-gate.js +1 -1
  23. package/dist/commands/vault-retention-flag.js +2 -1
  24. package/dist/commands/whoami.js +1 -1
  25. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +238 -221
  26. package/dist/hq-cloud-sync-runner/package.json +1 -1
  27. package/dist/index.js +3 -1
  28. package/dist/lib/agent-kit/inbox-poll-backoff-flag.js +1 -1
  29. package/dist/lib/agent-kit/mcp/tools.js +48 -0
  30. package/dist/lib/bot/fleet-bots-update-pass.js +1 -1
  31. package/dist/lib/bot/fleet-cron.d.ts +35 -0
  32. package/dist/lib/bot/fleet-cron.js +54 -12
  33. package/dist/lib/bot/fleet-local.d.ts +18 -0
  34. package/dist/lib/bot/fleet-local.js +51 -5
  35. package/dist/lib/bot/inbox-poll-backoff-flag.js +1 -1
  36. package/dist/lib/bot/signals-engine-flag.d.ts +1 -1
  37. package/dist/lib/bot/signals-engine-flag.js +1 -1
  38. package/dist/lib/cli-invite-nudge.js +1 -1
  39. package/dist/lib/client-version.d.ts +2 -0
  40. package/dist/lib/client-version.js +24 -0
  41. package/dist/lib/company-flag-gate.d.ts +30 -0
  42. package/dist/lib/company-flag-gate.js +104 -0
  43. package/dist/lib/core-utils/hook-timeout-debug-context-flag.js +1 -1
  44. package/dist/lib/daemon/flag.js +2 -1
  45. package/dist/lib/daemon/legacy-journal-gate.js +3 -1
  46. package/dist/lib/daemon/shared-flag-reads.js +1 -1
  47. package/dist/lib/doctor/checks/host-core.js +22 -4
  48. package/dist/lib/doctor/checks/jq.d.ts +27 -6
  49. package/dist/lib/doctor/checks/jq.js +46 -8
  50. package/dist/lib/doctor/client-health-reason-codes-flag.js +1 -1
  51. package/dist/lib/doctor/fix/refresh-sync-handoff.d.ts +1 -1
  52. package/dist/lib/doctor/fix/refresh-sync-handoff.js +1 -1
  53. package/dist/lib/flag-client-gate-headers.d.ts +38 -0
  54. package/dist/lib/flag-client-gate-headers.js +62 -0
  55. package/dist/lib/flag-client-headers.d.ts +15 -0
  56. package/dist/lib/flag-client-headers.js +25 -0
  57. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  58. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  59. package/dist/lib/flag-registry-worker.js +35 -0
  60. package/dist/lib/flag-registry.d.ts +1 -20
  61. package/dist/lib/flag-registry.js +5 -81
  62. package/dist/lib/hook-engine/adapter-core-pin.d.ts +29 -0
  63. package/dist/lib/hook-engine/adapter-core-pin.js +29 -0
  64. package/dist/lib/hook-engine/coverage.d.ts +50 -1
  65. package/dist/lib/hook-engine/coverage.js +111 -7
  66. package/dist/lib/hook-engine/reconcile.js +3 -2
  67. package/dist/lib/hot-channels/prompts/signals-pass.md +20 -0
  68. package/dist/lib/hot-channels/signal-changes.d.ts +228 -0
  69. package/dist/lib/hot-channels/signal-changes.js +683 -0
  70. package/dist/lib/hot-channels/signals-pass.d.ts +24 -0
  71. package/dist/lib/hot-channels/signals-pass.js +232 -12
  72. package/dist/lib/lanes/outpost-worktree-pruner-flag.d.ts +1 -1
  73. package/dist/lib/lanes/outpost-worktree-pruner-flag.js +1 -1
  74. package/dist/lib/lanes/registry-flag.js +2 -1
  75. package/dist/lib/lanes/spawn.js +11 -1
  76. package/dist/lib/mesh/live/binding-intent.d.ts +61 -0
  77. package/dist/lib/mesh/live/binding-intent.js +201 -0
  78. package/dist/lib/mesh/live/binding-receipt.d.ts +157 -0
  79. package/dist/lib/mesh/live/binding-receipt.js +365 -0
  80. package/dist/lib/mesh/live/company-flag-refresh.js +1 -1
  81. package/dist/lib/mesh/live/daemon/doctor-telemetry.d.ts +39 -0
  82. package/dist/lib/mesh/live/daemon/doctor-telemetry.js +58 -0
  83. package/dist/lib/mesh/live/daemon/install.js +2 -1
  84. package/dist/lib/mesh/live/daemon/presence.js +9 -0
  85. package/dist/lib/mesh/live/daemon/run.d.ts +3 -0
  86. package/dist/lib/mesh/live/daemon/run.js +33 -1
  87. package/dist/lib/ontology-graph/lineage/index.d.ts +401 -0
  88. package/dist/lib/ontology-graph/lineage/index.js +1027 -0
  89. package/dist/lib/ontology-graph/model/index.d.ts +54 -0
  90. package/dist/lib/ontology-graph/model/index.js +112 -0
  91. package/dist/lib/ontology-graph/model/pass-tasks.d.ts +75 -0
  92. package/dist/lib/ontology-graph/model/pass-tasks.js +166 -0
  93. package/dist/lib/ontology-graph/model/pass.d.ts +6 -0
  94. package/dist/lib/ontology-graph/model/pass.js +9 -2
  95. package/dist/lib/ontology-graph/model/pending-items.d.ts +8 -0
  96. package/dist/lib/ontology-graph/model/pending-items.js +24 -1
  97. package/dist/lib/ontology-graph/model/step.d.ts +1 -1
  98. package/dist/lib/ontology-graph/model/tasks.d.ts +11 -3
  99. package/dist/lib/ontology-graph/model/tasks.js +20 -7
  100. package/dist/lib/ontology-graph/read/brief.js +41 -6
  101. package/dist/lib/ontology-graph/read/index.d.ts +4 -0
  102. package/dist/lib/ontology-graph/read/index.js +173 -29
  103. package/dist/lib/ontology-graph/read/lineage.d.ts +101 -0
  104. package/dist/lib/ontology-graph/read/lineage.js +262 -0
  105. package/dist/lib/ontology-graph/replay/buffered-store.js +17 -0
  106. package/dist/lib/ontology-graph/replay/engine.d.ts +32 -1
  107. package/dist/lib/ontology-graph/replay/engine.js +213 -8
  108. package/dist/lib/ontology-graph/replay/extractors.d.ts +26 -0
  109. package/dist/lib/ontology-graph/replay/extractors.js +25 -1
  110. package/dist/lib/ontology-graph/replay/index.d.ts +2 -0
  111. package/dist/lib/ontology-graph/replay/index.js +9 -3
  112. package/dist/lib/ontology-graph/replay/signal-changes.d.ts +118 -0
  113. package/dist/lib/ontology-graph/replay/signal-changes.js +687 -0
  114. package/dist/lib/ontology-graph/schema/decision-status.d.ts +18 -0
  115. package/dist/lib/ontology-graph/schema/decision-status.js +20 -0
  116. package/dist/lib/ontology-graph/schema/index.d.ts +1 -0
  117. package/dist/lib/ontology-graph/schema/index.js +1 -0
  118. package/dist/lib/ontology-graph/setup/index.js +13 -3
  119. package/dist/lib/search-index/index.d.ts +33 -1
  120. package/dist/lib/search-index/index.js +180 -25
  121. package/dist/lib/search-index/qmd-exit-diagnostics.d.ts +7 -0
  122. package/dist/lib/search-index/qmd-exit-diagnostics.js +25 -1
  123. package/dist/lib/signals/adapters-catalog.js +1 -1
  124. package/dist/lib/sync-core/engine-holds.d.ts +1 -0
  125. package/dist/lib/sync-core/engine-holds.js +26 -0
  126. package/dist/lib/sync-core/engine-home.d.ts +3 -0
  127. package/dist/lib/sync-core/engine-home.js +41 -1
  128. package/dist/lib/sync-core/flag.js +2 -1
  129. package/dist/lib/sync-core/legacy-journal-export-child.js +5 -3
  130. package/dist/lib/sync-core/legacy-journal-export.d.ts +23 -4
  131. package/dist/lib/sync-core/legacy-journal-export.js +120 -55
  132. package/dist/lib/sync-core/reconcile.d.ts +2 -1
  133. package/dist/lib/sync-core/reconcile.js +30 -5
  134. package/dist/lib/sync-invalid-entity-warning.js +2 -1
  135. package/dist/lib/windows/install-followup.d.ts +41 -0
  136. package/dist/lib/windows/install-followup.js +87 -0
  137. package/dist/lib/windows/jq.d.ts +59 -0
  138. package/dist/lib/windows/jq.js +154 -3
  139. package/dist/lib/windows/user-path.d.ts +5 -0
  140. package/dist/lib/windows/user-path.js +1 -1
  141. package/dist/lib/work-context/auto-bind.d.ts +12 -0
  142. package/dist/lib/work-context/auto-bind.js +49 -3
  143. package/dist/lib/work-context/organize.d.ts +4 -2
  144. package/dist/lib/work-context/organize.js +18 -8
  145. package/dist/lib/work-context/reconcile.js +16 -1
  146. package/dist/main.js +12 -1
  147. package/dist/utils/client-health-contract.d.ts +30 -0
  148. package/dist/utils/client-health-contract.js +111 -0
  149. package/dist/utils/client-health.d.ts +5 -2
  150. package/dist/utils/client-health.js +74 -5
  151. package/dist/utils/exclusive-lock.d.ts +5 -1
  152. package/dist/utils/exclusive-lock.js +9 -2
  153. package/dist/utils/host-registration.d.ts +7 -0
  154. package/dist/utils/host-registration.js +10 -1
  155. package/dist/utils/pid.d.ts +31 -0
  156. package/dist/utils/pid.js +65 -0
  157. package/dist/utils/resident-package-preload.js +12 -4
  158. package/dist/utils/sentry-fingerprint.js +3 -0
  159. package/package.json +8 -8
  160. package/scripts/install-hook-engine.mjs +5 -3
@@ -2,6 +2,7 @@ import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { parse as parseToml } from "smol-toml";
4
4
  import { compareSyncCoreReleases } from "./release-compare.js";
5
+ import { CLIENT_HEALTH_MAX_SYNC_ENGINE_COUNT, } from "../../utils/client-health-contract.js";
5
6
  export const SYNC_CORE_REQUESTS_PER_DAY = 20_000;
6
7
  // The first engine release with no daily request count; it ignores `requests_per_day`.
7
8
  export const SYNC_CORE_REQUEST_COUNT_REMOVED_IN = "v0.1.29";
@@ -94,9 +95,14 @@ export const SYNC_CORE_STATUS_WORK_LIMIT = 20;
94
95
  function count(value) {
95
96
  return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
96
97
  }
98
+ export const SYNC_CORE_STATUS_FILE_MAX_BYTES = 1024 * 1024;
97
99
  function readStatusFile(engineHome) {
98
100
  try {
99
- return record(JSON.parse(fs.readFileSync(path.join(engineHome, ".hq", "sync-core", "status.json"), "utf8")));
101
+ const file = path.join(engineHome, ".hq", "sync-core", "status.json");
102
+ const stat = fs.lstatSync(file);
103
+ if (!stat.isFile() || stat.size > SYNC_CORE_STATUS_FILE_MAX_BYTES)
104
+ return undefined;
105
+ return record(JSON.parse(fs.readFileSync(file, "utf8")));
100
106
  }
101
107
  catch {
102
108
  return undefined;
@@ -204,6 +210,38 @@ function vaultWakeChannel(value, vaultUid) {
204
210
  const since = isoTime(channel.since_ms);
205
211
  return { connected: channel.connected, ...(since ? { since } : {}) };
206
212
  }
213
+ const SAFETY_COUNTER_NAMES = [
214
+ ["vault_deletes", "vaultDeletes"],
215
+ ["local_deletes", "localDeletes"],
216
+ ["download_trashed", "downloadTrashed"],
217
+ ["conflict_backups", "conflictBackups"],
218
+ ["local_replaced", "localReplaced"],
219
+ ["uploads_over", "uploadsOver"],
220
+ ["refused_deletes", "refusedDeletes"],
221
+ ["refused_uploads", "refusedUploads"],
222
+ ["adoptions", "adoptions"],
223
+ ];
224
+ function vaultSafety(value, vaultUid) {
225
+ if (!Array.isArray(value))
226
+ return undefined;
227
+ const counters = record(value.map(record).find((item) => item?.vault === vaultUid)?.counters);
228
+ if (!counters)
229
+ return undefined;
230
+ const safety = {};
231
+ for (const [engineName, name] of SAFETY_COUNTER_NAMES) {
232
+ const counter = record(counters[engineName]);
233
+ const total = Math.min(wholeCount(counter?.total), CLIENT_HEALTH_MAX_SYNC_ENGINE_COUNT);
234
+ if (!counter || total === 0)
235
+ continue;
236
+ const lastAtMs = Math.floor(timestampMs(counter.last_at_ms) ?? 0);
237
+ safety[name] = {
238
+ total,
239
+ last24h: Math.min(wholeCount(counter.last_24h), CLIENT_HEALTH_MAX_SYNC_ENGINE_COUNT),
240
+ ...(lastAtMs > 0 ? { lastAtMs } : {}),
241
+ };
242
+ }
243
+ return safety;
244
+ }
207
245
  export function readEngineStatus(engineHome, vaultUid, now = new Date()) {
208
246
  const status = readStatusFile(engineHome);
209
247
  if (!status)
@@ -218,6 +256,7 @@ export function readEngineStatus(engineHome, vaultUid, now = new Date()) {
218
256
  const transfersQueued = cycle ? wholeCount(cycle.transfers_queued) : 0;
219
257
  const running = runningCycle(status.cycle, vaultUid, now);
220
258
  const wakeChannel = vaultWakeChannel(status.wakes, vaultUid);
259
+ const safety = vaultSafety(status.safety, vaultUid);
221
260
  return {
222
261
  ...(typeof status.engine_version === "string" && status.engine_version ? { engineVersion: status.engine_version } : {}),
223
262
  ...(startedAt ? { startedAt } : {}),
@@ -226,6 +265,7 @@ export function readEngineStatus(engineHome, vaultUid, now = new Date()) {
226
265
  : {}),
227
266
  ...(running ? { cycle: running } : {}),
228
267
  ...(wakeChannel ? { wakeChannel } : {}),
268
+ ...(safety ? { safety } : {}),
229
269
  ...(cycle && atMs !== undefined
230
270
  ? {
231
271
  lastCycle: {
@@ -1,4 +1,5 @@
1
- import { createFlagClient, readLocalOverride } from "@indigoai-us/hq-flags-client";
1
+ import { readLocalOverride } from "@indigoai-us/hq-flags-client";
2
+ import { createHqFlagClient as createFlagClient } from "../flag-client-headers.js";
2
3
  import { resolveFlagRegistryEndpoint } from "../flag-registry-endpoint.js";
3
4
  export const SYNC_RUST_ENGINE_ROLLOUT_FLAG = "sync.rust-engine-rollout-v3";
4
5
  const READ_TIMEOUT_MS = 5_000;
@@ -4,8 +4,10 @@ import { writeLegacyJournalExport } from "./legacy-journal-export.js";
4
4
  import { loadLegacyJournalReader } from "./legacy-journal-reader.js";
5
5
  const [home, uid, slug, offSince] = process.argv.slice(2);
6
6
  try {
7
- if (!home || !uid || !slug)
8
- throw new Error("usage: legacy-journal-export-child <home> <vault uid> <slug>");
7
+ const cutoff = offSince ? Date.parse(offSince) : Number.NaN;
8
+ if (!home || !uid || !slug || !Number.isFinite(cutoff)) {
9
+ throw new Error("usage: legacy-journal-export-child <home> <vault uid> <slug> <time the current sync's switch was turned off>");
10
+ }
9
11
  const loaded = await loadLegacyJournalReader([currentHqCloud(daemonPaths(home, process.env).root), bundledHqCloud()]);
10
12
  if (!loaded.reader)
11
13
  throw new Error(loaded.reason);
@@ -13,7 +15,7 @@ try {
13
15
  home,
14
16
  vault: { uid, kind: "company", slug },
15
17
  readJournal: loaded.reader,
16
- ...(offSince && Number.isFinite(Date.parse(offSince)) ? { offSince: Date.parse(offSince) } : {}),
18
+ offSince: cutoff,
17
19
  });
18
20
  process.exit(0);
19
21
  }
@@ -13,18 +13,30 @@ export type LegacyJournalExportResult = {
13
13
  file: string;
14
14
  replaced: boolean;
15
15
  } | {
16
- status: "present" | "consumed" | "not-company" | "no-journal";
16
+ status: "present" | "consumed" | "stale" | "not-company" | "no-journal" | "no-cutoff" | "nothing-to-export";
17
+ };
18
+ export type LegacyJournalExportState = "present" | "unusable" | "consumed" | "stale" | "missing" | "not-company";
19
+ export type StaleLegacyJournalDrop = {
20
+ status: "none" | "removed";
21
+ } | {
22
+ status: "failed";
23
+ reason: string;
17
24
  };
18
- export type LegacyJournalExportState = "present" | "unusable" | "consumed" | "missing" | "not-company";
19
25
  export declare const LEGACY_JOURNAL_EXPORT_MAX_BYTES: number;
20
26
  export declare const LEGACY_JOURNAL_EXPORT_MAX_AHEAD_MS: number;
21
27
  export declare function legacyJournalExportPath(home: string, uid: string, slug: string): string;
22
28
  export declare function legacyJournalConsumedPath(home: string, uid: string, slug: string): string;
23
29
  export declare function legacyJournalUnprovenPath(home: string, uid: string, slug: string): string;
30
+ export declare function legacyJournalStalePath(home: string, uid: string, slug: string): string;
24
31
  export declare function legacyJournalExportState(home: string, vault: LegacyJournalExportVault, now?: number): LegacyJournalExportState;
25
- export declare function legacyStateDir(home: string, env: NodeJS.ProcessEnv): string;
26
32
  export declare function legacyStateDirs(home: string, env: NodeJS.ProcessEnv): string[];
27
33
  export declare function legacyJournalDirs(home: string, env: NodeJS.ProcessEnv, slug: string): string[];
34
+ export interface MergeLegacyJournalOptions {
35
+ offSince: number | undefined;
36
+ now: number;
37
+ platform?: NodeJS.Platform;
38
+ }
39
+ export declare function mergeLegacyJournalFiles(journals: readonly Record<string, unknown>[], opts: MergeLegacyJournalOptions): Record<string, unknown>;
28
40
  export declare function removeLegacyJournalTemps(home: string, vault: LegacyJournalExportVault): void;
29
41
  export interface WriteLegacyJournalExportOptions {
30
42
  home: string;
@@ -33,7 +45,14 @@ export interface WriteLegacyJournalExportOptions {
33
45
  env?: NodeJS.ProcessEnv;
34
46
  now?: () => number;
35
47
  offSince?: number;
48
+ platform?: NodeJS.Platform;
36
49
  }
37
50
  export declare function writeLegacyJournalExport(opts: WriteLegacyJournalExportOptions): LegacyJournalExportResult;
38
- export declare function removeLegacyJournalExport(home: string, vault: LegacyJournalExportVault): void;
51
+ export declare function removeLegacyJournalExport(home: string, vault: LegacyJournalExportVault, removeFiles?: (home: string, vault: LegacyJournalExportVault & {
52
+ slug: string;
53
+ }) => void): void;
54
+ export declare function markLegacyJournalExportStale(home: string, vault: LegacyJournalExportVault): void;
55
+ export declare function dropStaleLegacyJournalExport(home: string, vault: LegacyJournalExportVault, removeFiles?: (home: string, vault: LegacyJournalExportVault & {
56
+ slug: string;
57
+ }) => void): StaleLegacyJournalDrop;
39
58
  //# sourceMappingURL=legacy-journal-export.d.ts.map
@@ -20,6 +20,9 @@ export function legacyJournalConsumedPath(home, uid, slug) {
20
20
  export function legacyJournalUnprovenPath(home, uid, slug) {
21
21
  return `${legacyJournalExportPath(home, uid, slug)}.unproven`;
22
22
  }
23
+ export function legacyJournalStalePath(home, uid, slug) {
24
+ return `${legacyJournalExportPath(home, uid, slug)}.stale`;
25
+ }
23
26
  function exportable(vault) {
24
27
  return vault.kind === "company" && vault.uid.startsWith("cmp_") && typeof vault.slug === "string" && SLUG.test(vault.slug);
25
28
  }
@@ -29,7 +32,8 @@ function exists(file) {
29
32
  return true;
30
33
  }
31
34
  catch (error) {
32
- if (error.code === "ENOENT")
35
+ const code = error.code;
36
+ if (code === "ENOENT" || code === "ENOTDIR")
33
37
  return false;
34
38
  throw error;
35
39
  }
@@ -56,6 +60,8 @@ function usableExport(file, now) {
56
60
  export function legacyJournalExportState(home, vault, now = Date.now()) {
57
61
  if (!exportable(vault))
58
62
  return "not-company";
63
+ if (exists(legacyJournalStalePath(home, vault.uid, vault.slug)))
64
+ return "stale";
59
65
  if (exists(legacyJournalConsumedPath(home, vault.uid, vault.slug)))
60
66
  return "consumed";
61
67
  const file = legacyJournalExportPath(home, vault.uid, vault.slug);
@@ -63,76 +69,104 @@ export function legacyJournalExportState(home, vault, now = Date.now()) {
63
69
  return "missing";
64
70
  return usableExport(file, now) ? "present" : "unusable";
65
71
  }
66
- export function legacyStateDir(home, env) {
67
- return env.HQ_STATE_DIR ?? path.join(home, ".hq");
68
- }
69
72
  export function legacyStateDirs(home, env) {
70
- return [...new Set([legacyStateDir(home, env), path.join(home, ".hq"), machineTokenStateDir(home, env)])];
73
+ const machine = machineTokenStateDir(home, env);
74
+ const set = env.HQ_STATE_DIR;
75
+ if (set && path.resolve(set) !== path.resolve(machine))
76
+ return [set];
77
+ return [path.join(home, ".hq"), machine];
71
78
  }
72
79
  export function legacyJournalDirs(home, env, slug) {
73
80
  return legacyStateDirs(home, env).filter((dir) => fs.existsSync(path.join(dir, `sync-journal.${slug}.json`)));
74
81
  }
75
- function syncedAtMs(value) {
76
- if (typeof value === "number")
77
- return Number.isFinite(value) ? value : 0;
78
- if (typeof value !== "string")
79
- return 0;
80
- const ms = Date.parse(value);
81
- return Number.isFinite(ms) ? ms : 0;
82
+ const ISO_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/;
83
+ function timeMs(value, now) {
84
+ if (typeof value !== "string" || !ISO_TIME.test(value))
85
+ return Number.NaN;
86
+ const at = Date.parse(value);
87
+ return at <= now ? at : Number.NaN;
82
88
  }
83
- function newestSyncedAt(files) {
84
- let newest = 0;
85
- for (const key of Object.keys(files)) {
86
- const at = entrySyncedAt(files[key]);
87
- if (at > newest)
88
- newest = at;
89
- }
90
- return newest;
89
+ function rankMs(entry, now) {
90
+ const synced = timeMs(entry.syncedAt, now);
91
+ if (!Number.isFinite(synced))
92
+ return Number.NaN;
93
+ if (entry.removedAt === undefined || entry.removedAt === null)
94
+ return synced;
95
+ const removed = timeMs(entry.removedAt, now);
96
+ return Number.isFinite(removed) ? Math.max(synced, removed) : Number.NaN;
91
97
  }
92
- function entrySyncedAt(entry) {
93
- return entry && typeof entry === "object" ? syncedAtMs(entry.syncedAt) : 0;
98
+ function sameValue(a, b) {
99
+ return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
94
100
  }
95
- function entryHash(entry) {
96
- return entry && typeof entry === "object" ? entry.hash : undefined;
101
+ function foldedPath(key) {
102
+ return key.normalize("NFC").toLowerCase();
97
103
  }
98
- function lastSyncedEntries(slug, dirs, readJournal, offSince) {
104
+ function lastSyncedEntries(slug, dirs, readJournal, opts) {
99
105
  const read = dirs
100
- .map((dir) => {
101
- const files = readJournal(slug, dir).files;
102
- return { dir, files, count: files && typeof files === "object" ? Object.keys(files).length : 0 };
103
- })
104
- .filter((journal) => journal.count > 0);
106
+ .map((dir) => readJournal(slug, dir).files)
107
+ .filter((files) => files && typeof files === "object" && Object.keys(files).length > 0);
105
108
  if (read.length === 0)
106
109
  throw new Error(`the current sync has a journal for ${slug} but it read as empty`);
107
- if (read.length === 1)
108
- return read[0].files;
109
- if (offSince !== undefined && Number.isFinite(offSince) && read.some((journal) => newestSyncedAt(journal.files) > offSince)) {
110
- throw new Error(`the current sync has journals for ${slug} in ${read.map((journal) => journal.dir).join(" and ")}, and one was written after its switch was turned off, so it is not clear what it last synced`);
111
- }
110
+ return mergeLegacyJournalFiles(read, opts);
111
+ }
112
+ export function mergeLegacyJournalFiles(journals, opts) {
113
+ const out = Object.create(null);
114
+ const cutoff = opts.offSince;
115
+ if (cutoff === undefined || !Number.isFinite(cutoff))
116
+ return out;
117
+ const platform = opts.platform ?? process.platform;
118
+ const folds = platform === "darwin" || platform === "win32";
112
119
  const merged = Object.create(null);
120
+ const leftOut = new Set();
113
121
  const disputed = new Set();
114
- for (const journal of read) {
115
- for (const key of Object.keys(journal.files)) {
116
- const entry = journal.files[key];
117
- if (!(key in merged)) {
118
- merged[key] = entry;
122
+ const spelled = new Map();
123
+ const collided = new Set();
124
+ for (const files of journals) {
125
+ for (const key of Object.keys(files)) {
126
+ if (folds) {
127
+ const folded = foldedPath(key);
128
+ const first = spelled.get(folded);
129
+ if (first === undefined)
130
+ spelled.set(folded, key);
131
+ else if (first !== key)
132
+ collided.add(folded);
133
+ }
134
+ const value = files[key];
135
+ if (!value || typeof value !== "object" || Array.isArray(value))
136
+ continue;
137
+ const entry = value;
138
+ const at = rankMs(entry, opts.now);
139
+ if (!Number.isFinite(at)) {
140
+ leftOut.add(key);
119
141
  continue;
120
142
  }
121
143
  const kept = merged[key];
122
- const at = entrySyncedAt(entry);
123
- const keptAt = entrySyncedAt(kept);
124
- if (at > keptAt) {
125
- merged[key] = entry;
144
+ if (!kept || at > kept.at) {
145
+ merged[key] = { entry, at };
126
146
  disputed.delete(key);
127
147
  }
128
- else if (at === keptAt && entryHash(entry) !== entryHash(kept)) {
129
- disputed.add(key);
148
+ else if (at === kept.at) {
149
+ if (entry.hash === kept.entry.hash
150
+ && sameValue(entry.removedAt, kept.entry.removedAt)
151
+ && sameValue(entry.localDeleteIntent, kept.entry.localDeleteIntent)) {
152
+ if (entry.localDiverges === true && kept.entry.localDiverges !== true)
153
+ merged[key] = { entry: { ...kept.entry, localDiverges: true }, at };
154
+ }
155
+ else {
156
+ disputed.add(key);
157
+ }
130
158
  }
131
159
  }
132
160
  }
133
- for (const key of disputed)
134
- delete merged[key];
135
- return merged;
161
+ for (const key of Object.keys(merged)) {
162
+ const { entry, at } = merged[key];
163
+ if (leftOut.has(key) || disputed.has(key) || at > cutoff)
164
+ continue;
165
+ if (folds && collided.has(foldedPath(key)))
166
+ continue;
167
+ out[key] = entry;
168
+ }
169
+ return out;
136
170
  }
137
171
  export function removeLegacyJournalTemps(home, vault) {
138
172
  if (!exportable(vault))
@@ -170,12 +204,16 @@ export function writeLegacyJournalExport(opts) {
170
204
  const state = legacyJournalExportState(home, vault, now());
171
205
  if (state !== "missing" && state !== "unusable")
172
206
  return { status: state };
207
+ if (opts.offSince === undefined || !Number.isFinite(opts.offSince))
208
+ return { status: "no-cutoff" };
173
209
  const slug = vault.slug;
174
210
  const dirs = legacyJournalDirs(home, opts.env ?? process.env, slug);
175
211
  if (dirs.length === 0)
176
212
  return { status: "no-journal" };
177
- const files = lastSyncedEntries(slug, dirs, opts.readJournal, opts.offSince);
213
+ const files = lastSyncedEntries(slug, dirs, opts.readJournal, { offSince: opts.offSince, now: now(), platform: opts.platform });
178
214
  const keys = Object.keys(files);
215
+ if (keys.length === 0)
216
+ return { status: "nothing-to-export" };
179
217
  const file = legacyJournalExportPath(home, vault.uid, slug);
180
218
  fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
181
219
  removeLegacyJournalTemps(home, vault);
@@ -198,8 +236,6 @@ export function writeLegacyJournalExport(opts) {
198
236
  }
199
237
  }
200
238
  fs.writeSync(fd, `${chunk.join("")}}}\n`);
201
- if (entries === 0)
202
- throw new Error(`the current sync's journal for ${slug} has no usable entries`);
203
239
  if (fs.fstatSync(fd).size > LEGACY_JOURNAL_EXPORT_MAX_BYTES) {
204
240
  throw new Error(`the copy of the current sync's journal for ${slug} is over ${LEGACY_JOURNAL_EXPORT_MAX_BYTES / (1024 * 1024)} MB, more than the new sync engine reads`);
205
241
  }
@@ -229,13 +265,42 @@ export function writeLegacyJournalExport(opts) {
229
265
  throw error;
230
266
  }
231
267
  }
232
- export function removeLegacyJournalExport(home, vault) {
233
- if (!exportable(vault))
234
- return;
268
+ function removeExportFiles(home, vault) {
235
269
  const file = legacyJournalExportPath(home, vault.uid, vault.slug);
236
270
  for (const target of [file, `${file}.consumed`, `${file}.unproven`, `${file}.unproven.bad`]) {
237
271
  fs.rmSync(target, { recursive: true, force: true });
238
272
  }
239
273
  removeLegacyJournalTemps(home, vault);
240
274
  }
275
+ export function removeLegacyJournalExport(home, vault, removeFiles = removeExportFiles) {
276
+ if (!exportable(vault))
277
+ return;
278
+ markLegacyJournalExportStale(home, vault);
279
+ removeFiles(home, vault);
280
+ fs.rmSync(legacyJournalStalePath(home, vault.uid, vault.slug), { force: true });
281
+ }
282
+ export function markLegacyJournalExportStale(home, vault) {
283
+ if (!exportable(vault))
284
+ return;
285
+ const file = legacyJournalExportPath(home, vault.uid, vault.slug);
286
+ const marker = legacyJournalStalePath(home, vault.uid, vault.slug);
287
+ if (exists(marker) || ![file, `${file}.consumed`, `${file}.unproven`].some(exists))
288
+ return;
289
+ fs.writeFileSync(marker, "{}\n", { mode: 0o600 });
290
+ }
291
+ export function dropStaleLegacyJournalExport(home, vault, removeFiles = removeExportFiles) {
292
+ if (!exportable(vault))
293
+ return { status: "none" };
294
+ const marker = legacyJournalStalePath(home, vault.uid, vault.slug);
295
+ if (!exists(marker))
296
+ return { status: "none" };
297
+ try {
298
+ removeFiles(home, vault);
299
+ }
300
+ catch (error) {
301
+ return { status: "failed", reason: error instanceof Error ? error.message : String(error) };
302
+ }
303
+ fs.rmSync(marker, { force: true });
304
+ return { status: "removed" };
305
+ }
241
306
  //# sourceMappingURL=legacy-journal-export.js.map
@@ -2,7 +2,7 @@ import { type SyncCoreVault } from "./engine-home.js";
2
2
  import { type SyncCoreBinaryInstall, type SyncCorePin } from "./release.js";
3
3
  import type { MachineType } from "../daemon/machine-type.js";
4
4
  import { type SyncCoreCompanyEntity } from "./company-adoption.js";
5
- import { type LegacyJournalReader } from "./legacy-journal-export.js";
5
+ import { dropStaleLegacyJournalExport, type LegacyJournalReader } from "./legacy-journal-export.js";
6
6
  import { type SyncCoreRolloutState } from "./rollout-state.js";
7
7
  export interface SyncCoreMembership {
8
8
  companyUid: string;
@@ -30,6 +30,7 @@ export interface SyncCoreReconcileDeps {
30
30
  resolveCompany?: (companyUid: string) => Promise<SyncCoreCompanyEntity | null>;
31
31
  readLegacyJournal?: LegacyJournalReader;
32
32
  legacyJournalUnavailable?: string;
33
+ removeStaleLegacyJournalFiles?: Parameters<typeof dropStaleLegacyJournalExport>[2];
33
34
  /** Only desktop and self-hosted machines set up a joined company. */
34
35
  machineType?: MachineType;
35
36
  ensureBinary: (release: string) => Promise<SyncCoreBinaryInstall>;
@@ -8,7 +8,7 @@ import { SYNC_CORE_FULL_RELEASE, SYNC_CORE_RELEASE, compareSyncCoreReleases, ful
8
8
  import { readSyncCoreSkips } from "./skip.js";
9
9
  import { isLiveCompanyEntity, joinedCompanySlug, setUpJoinedCompany } from "./company-adoption.js";
10
10
  import { heldDeletesHandoverLine, readEngineHeldDeletes, writeHandbackKeep } from "./engine-holds.js";
11
- import { legacyJournalDirs, legacyJournalExportState, removeLegacyJournalExport, writeLegacyJournalExport, } from "./legacy-journal-export.js";
11
+ import { dropStaleLegacyJournalExport, legacyJournalDirs, legacyJournalExportState, markLegacyJournalExportStale, removeLegacyJournalExport, writeLegacyJournalExport, } from "./legacy-journal-export.js";
12
12
  import { SYNC_RUST_ENGINE_ROLLOUT_FLAG } from "./flag.js";
13
13
  import { readSyncCoreRolloutState, syncCoreRolloutStatePath, writeSyncCoreRolloutState, } from "./rollout-state.js";
14
14
  function message(error) {
@@ -155,6 +155,19 @@ async function setUpJoinedCompanies(deps, memberships, ctx) {
155
155
  function dropLegacyJournalExport(home, vault, warnings) {
156
156
  try {
157
157
  removeLegacyJournalExport(home, vault);
158
+ return true;
159
+ }
160
+ catch (error) {
161
+ warnings.push(`could not remove the old copy of the current sync's record of ${vault.slug ?? vault.uid}: ${message(error)}`);
162
+ return false;
163
+ }
164
+ }
165
+ function retryStaleLegacyJournalExport(deps, vault, warnings) {
166
+ try {
167
+ const dropped = dropStaleLegacyJournalExport(deps.home, vault, deps.removeStaleLegacyJournalFiles);
168
+ if (dropped.status === "failed") {
169
+ warnings.push(`could not remove the old copy of the current sync's record of ${vault.slug ?? vault.uid}, which is out of date: ${dropped.reason}; trying again on the next reconcile, and no new copy is written until it is gone`);
170
+ }
158
171
  }
159
172
  catch (error) {
160
173
  warnings.push(`could not remove the old copy of the current sync's record of ${vault.slug ?? vault.uid}: ${message(error)}`);
@@ -176,7 +189,8 @@ export async function reconcileSyncCore(deps) {
176
189
  await setUpJoinedCompanies(deps, memberships, { platform, env, previousByUid, flagReads, warnings, log });
177
190
  const desired = [];
178
191
  let anyCompanyOn = false;
179
- for (const company of localCompanies(deps.hqRoot, memberships)) {
192
+ const companiesHere = localCompanies(deps.hqRoot, memberships);
193
+ for (const company of companiesHere) {
180
194
  let on;
181
195
  try {
182
196
  on = flagReads.get(company.uid) ?? await deps.readRolloutFlag(company.uid);
@@ -281,8 +295,7 @@ export async function reconcileSyncCore(deps) {
281
295
  const engineHome = syncCoreEngineHome(deps.home, vault.uid);
282
296
  if (!before)
283
297
  clearEngineStatus(deps.home, vault.uid);
284
- if (!before && !pending)
285
- dropLegacyJournalExport(deps.home, vault, warnings);
298
+ const dropFailed = !before && !pending && !dropLegacyJournalExport(deps.home, vault, warnings);
286
299
  writeEngineHome({ home: deps.home, hqRoot: deps.hqRoot, vault, phase: "full", tokenFile: deps.tokenFile, platform, release: engineRelease });
287
300
  const wasFull = before?.phase === "full";
288
301
  const alreadyOff = vault.kind === "personal"
@@ -324,8 +337,15 @@ export async function reconcileSyncCore(deps) {
324
337
  ...(downloadStreams !== undefined ? { downloadStreams } : {}),
325
338
  });
326
339
  if (vault.kind === "company" && wasFull && !alreadyOff && switchesBefore.unreadable === undefined) {
327
- dropLegacyJournalExport(deps.home, vault, warnings);
340
+ try {
341
+ markLegacyJournalExportStale(deps.home, vault);
342
+ }
343
+ catch (error) {
344
+ warnings.push(`could not mark the old copy of the current sync's record of ${vault.slug ?? vault.uid} as out of date: ${message(error)}`);
345
+ }
328
346
  }
347
+ if (vault.kind === "company" && !dropFailed)
348
+ retryStaleLegacyJournalExport(deps, vault, warnings);
329
349
  const cycledSinceOff = vault.kind === "company" && wasFull && alreadyOff
330
350
  ? engineFirstCycle(engineHome, vault.uid, legacyOffSince)
331
351
  : null;
@@ -390,6 +410,11 @@ export async function reconcileSyncCore(deps) {
390
410
  && !handedBack.some((back) => back.uid === vault.uid)
391
411
  && engineOwnsVault(deps.home, vault.uid)),
392
412
  ];
413
+ for (const company of companiesHere) {
414
+ if (desired.some((vault) => vault.uid === company.uid) || handingBack.some((vault) => vault.uid === company.uid))
415
+ continue;
416
+ retryStaleLegacyJournalExport(deps, company, warnings);
417
+ }
393
418
  const state = {
394
419
  version: 1,
395
420
  rolloutFlagKey: SYNC_RUST_ENGINE_ROLLOUT_FLAG,
@@ -1,4 +1,5 @@
1
- import { createFlagClient, readLocalOverride } from "@indigoai-us/hq-flags-client";
1
+ import { readLocalOverride } from "@indigoai-us/hq-flags-client";
2
+ import { createHqFlagClient as createFlagClient } from "./flag-client-headers.js";
2
3
  import { createHash } from "node:crypto";
3
4
  import * as fs from "node:fs";
4
5
  import * as path from "node:path";
@@ -15,6 +15,16 @@ export interface InstallFollowupMarker {
15
15
  };
16
16
  meshFailedVersion?: string;
17
17
  meshFailedAt?: number;
18
+ /**
19
+ * The CLI version whose jq step finished. `managed` is true when HQ's own
20
+ * jq.exe is the one in use, false when the machine already had jq on PATH.
21
+ */
22
+ jq?: {
23
+ version: string;
24
+ managed: boolean;
25
+ };
26
+ jqFailedVersion?: string;
27
+ jqFailedAt?: number;
18
28
  }
19
29
  /** A failed daemon install blocks for up to 30 s, so it is retried at most hourly. */
20
30
  export declare const MESH_RETRY_MS: number;
@@ -34,4 +44,35 @@ export interface InstallFollowupDeps {
34
44
  now?: () => number;
35
45
  }
36
46
  export declare function runWindowsInstallFollowup(deps: InstallFollowupDeps): void;
47
+ /** A failed jq download waits up to 20 s, so it is retried at most hourly. */
48
+ export declare const JQ_RETRY_MS: number;
49
+ export interface JqFollowupDeps {
50
+ argv: readonly string[];
51
+ env?: NodeJS.ProcessEnv;
52
+ platform?: NodeJS.Platform;
53
+ version?: string;
54
+ readMarker?: () => InstallFollowupMarker;
55
+ writeMarker?: (marker: InstallFollowupMarker) => void;
56
+ now?: () => number;
57
+ /** True when a jq.exe HQ did not install is on this process's PATH. */
58
+ otherJqOnPath?: () => boolean;
59
+ /** True when HQ's managed jq.exe exists. */
60
+ jqInstalled?: () => boolean;
61
+ /** Installs the verified jq and puts its folder on the user PATH. */
62
+ ensureJq?: () => Promise<{
63
+ onUserPath: boolean;
64
+ } | undefined>;
65
+ }
66
+ /** True when `file` is the jq.exe HQ installs: in the home's `.local\bin`, or beside hq.cmd. */
67
+ export declare function isHqManagedJq(file: string, home: string, shimDir: string | null): boolean;
68
+ /**
69
+ * Give a Windows machine the jq its HQ hooks need, with no step by hand
70
+ * (hq-cli #3716). Without jq, master-hook blocks every tool call, and npm 11
71
+ * skips the postinstall that would have installed it, so the first hq command
72
+ * after an install or update does it here. A machine that already has jq on
73
+ * PATH (one HQ did not install) is left alone. Runs once per CLI version; a settled machine pays one
74
+ * file check per command. A failure is retried after JQ_RETRY_MS and never
75
+ * fails the command the user asked for.
76
+ */
77
+ export declare function runWindowsJqFollowup(deps: JqFollowupDeps): Promise<void>;
37
78
  //# sourceMappingURL=install-followup.d.ts.map