@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
@@ -0,0 +1,39 @@
1
+ export interface LegacyJournalSource {
2
+ files: Record<string, unknown>;
3
+ }
4
+ export type LegacyJournalReader = (slug: string, stateDir: string) => LegacyJournalSource;
5
+ export interface LegacyJournalExportVault {
6
+ uid: string;
7
+ kind: "personal" | "company";
8
+ slug?: string;
9
+ }
10
+ export type LegacyJournalExportResult = {
11
+ status: "written";
12
+ entries: number;
13
+ file: string;
14
+ replaced: boolean;
15
+ } | {
16
+ status: "present" | "consumed" | "not-company" | "no-journal";
17
+ };
18
+ export type LegacyJournalExportState = "present" | "unusable" | "consumed" | "missing" | "not-company";
19
+ export declare const LEGACY_JOURNAL_EXPORT_MAX_BYTES: number;
20
+ export declare const LEGACY_JOURNAL_EXPORT_MAX_AHEAD_MS: number;
21
+ export declare function legacyJournalExportPath(home: string, uid: string, slug: string): string;
22
+ export declare function legacyJournalConsumedPath(home: string, uid: string, slug: string): string;
23
+ export declare function legacyJournalUnprovenPath(home: string, uid: string, slug: string): string;
24
+ export declare function legacyJournalExportState(home: string, vault: LegacyJournalExportVault, now?: number): LegacyJournalExportState;
25
+ export declare function legacyStateDir(home: string, env: NodeJS.ProcessEnv): string;
26
+ export declare function legacyStateDirs(home: string, env: NodeJS.ProcessEnv): string[];
27
+ export declare function legacyJournalDirs(home: string, env: NodeJS.ProcessEnv, slug: string): string[];
28
+ export declare function removeLegacyJournalTemps(home: string, vault: LegacyJournalExportVault): void;
29
+ export interface WriteLegacyJournalExportOptions {
30
+ home: string;
31
+ vault: LegacyJournalExportVault;
32
+ readJournal: LegacyJournalReader;
33
+ env?: NodeJS.ProcessEnv;
34
+ now?: () => number;
35
+ offSince?: number;
36
+ }
37
+ export declare function writeLegacyJournalExport(opts: WriteLegacyJournalExportOptions): LegacyJournalExportResult;
38
+ export declare function removeLegacyJournalExport(home: string, vault: LegacyJournalExportVault): void;
39
+ //# sourceMappingURL=legacy-journal-export.d.ts.map
@@ -0,0 +1,241 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { machineTokenStateDir } from "../../utils/machine-token-cache.js";
4
+ import { syncCoreEngineHome } from "./engine-home.js";
5
+ export const LEGACY_JOURNAL_EXPORT_MAX_BYTES = 256 * 1024 * 1024;
6
+ export const LEGACY_JOURNAL_EXPORT_MAX_AHEAD_MS = 5 * 60 * 1000;
7
+ const ENTRY_FIELDS = ["hash", "size", "kind", "syncedAt", "localDiverges", "removedAt", "localDeleteIntent"];
8
+ const SLUG = /^[A-Za-z0-9_-]+$/;
9
+ const CHUNK_ENTRIES = 512;
10
+ const HEAD_BYTES = 256;
11
+ function exportDir(home, uid) {
12
+ return path.join(syncCoreEngineHome(home, uid), ".hq", "sync-core", "legacy-journal");
13
+ }
14
+ export function legacyJournalExportPath(home, uid, slug) {
15
+ return path.join(exportDir(home, uid), `${slug}.json`);
16
+ }
17
+ export function legacyJournalConsumedPath(home, uid, slug) {
18
+ return `${legacyJournalExportPath(home, uid, slug)}.consumed`;
19
+ }
20
+ export function legacyJournalUnprovenPath(home, uid, slug) {
21
+ return `${legacyJournalExportPath(home, uid, slug)}.unproven`;
22
+ }
23
+ function exportable(vault) {
24
+ return vault.kind === "company" && vault.uid.startsWith("cmp_") && typeof vault.slug === "string" && SLUG.test(vault.slug);
25
+ }
26
+ function exists(file) {
27
+ try {
28
+ fs.lstatSync(file);
29
+ return true;
30
+ }
31
+ catch (error) {
32
+ if (error.code === "ENOENT")
33
+ return false;
34
+ throw error;
35
+ }
36
+ }
37
+ function usableExport(file, now) {
38
+ const stat = fs.lstatSync(file);
39
+ if (!stat.isFile() || stat.size > LEGACY_JOURNAL_EXPORT_MAX_BYTES)
40
+ return false;
41
+ const fd = fs.openSync(file, "r");
42
+ let head;
43
+ try {
44
+ const buffer = Buffer.alloc(HEAD_BYTES);
45
+ head = buffer.subarray(0, fs.readSync(fd, buffer, 0, HEAD_BYTES, 0)).toString("utf8");
46
+ }
47
+ finally {
48
+ fs.closeSync(fd);
49
+ }
50
+ const match = /^\{"version":"2","exportedAt":(\d{1,16}),"files":\{/.exec(head);
51
+ if (!match)
52
+ return false;
53
+ const exportedAt = Number(match[1]);
54
+ return Number.isSafeInteger(exportedAt) && exportedAt - now <= LEGACY_JOURNAL_EXPORT_MAX_AHEAD_MS;
55
+ }
56
+ export function legacyJournalExportState(home, vault, now = Date.now()) {
57
+ if (!exportable(vault))
58
+ return "not-company";
59
+ if (exists(legacyJournalConsumedPath(home, vault.uid, vault.slug)))
60
+ return "consumed";
61
+ const file = legacyJournalExportPath(home, vault.uid, vault.slug);
62
+ if (!exists(file))
63
+ return "missing";
64
+ return usableExport(file, now) ? "present" : "unusable";
65
+ }
66
+ export function legacyStateDir(home, env) {
67
+ return env.HQ_STATE_DIR ?? path.join(home, ".hq");
68
+ }
69
+ export function legacyStateDirs(home, env) {
70
+ return [...new Set([legacyStateDir(home, env), path.join(home, ".hq"), machineTokenStateDir(home, env)])];
71
+ }
72
+ export function legacyJournalDirs(home, env, slug) {
73
+ return legacyStateDirs(home, env).filter((dir) => fs.existsSync(path.join(dir, `sync-journal.${slug}.json`)));
74
+ }
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
+ }
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;
91
+ }
92
+ function entrySyncedAt(entry) {
93
+ return entry && typeof entry === "object" ? syncedAtMs(entry.syncedAt) : 0;
94
+ }
95
+ function entryHash(entry) {
96
+ return entry && typeof entry === "object" ? entry.hash : undefined;
97
+ }
98
+ function lastSyncedEntries(slug, dirs, readJournal, offSince) {
99
+ 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);
105
+ if (read.length === 0)
106
+ 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
+ }
112
+ const merged = Object.create(null);
113
+ 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;
119
+ continue;
120
+ }
121
+ const kept = merged[key];
122
+ const at = entrySyncedAt(entry);
123
+ const keptAt = entrySyncedAt(kept);
124
+ if (at > keptAt) {
125
+ merged[key] = entry;
126
+ disputed.delete(key);
127
+ }
128
+ else if (at === keptAt && entryHash(entry) !== entryHash(kept)) {
129
+ disputed.add(key);
130
+ }
131
+ }
132
+ }
133
+ for (const key of disputed)
134
+ delete merged[key];
135
+ return merged;
136
+ }
137
+ export function removeLegacyJournalTemps(home, vault) {
138
+ if (!exportable(vault))
139
+ return;
140
+ const dir = exportDir(home, vault.uid);
141
+ let names;
142
+ try {
143
+ names = fs.readdirSync(dir);
144
+ }
145
+ catch (error) {
146
+ if (error.code === "ENOENT")
147
+ return;
148
+ throw error;
149
+ }
150
+ const prefix = `${vault.slug}.json.`;
151
+ for (const name of names) {
152
+ if (name.startsWith(prefix) && name.endsWith(".tmp"))
153
+ fs.rmSync(path.join(dir, name), { recursive: true, force: true });
154
+ }
155
+ }
156
+ function exportedEntry(value) {
157
+ if (!value || typeof value !== "object" || Array.isArray(value))
158
+ return undefined;
159
+ const entry = value;
160
+ const out = {};
161
+ for (const field of ENTRY_FIELDS) {
162
+ if (entry[field] !== undefined)
163
+ out[field] = entry[field];
164
+ }
165
+ return out;
166
+ }
167
+ export function writeLegacyJournalExport(opts) {
168
+ const { home, vault } = opts;
169
+ const now = opts.now ?? Date.now;
170
+ const state = legacyJournalExportState(home, vault, now());
171
+ if (state !== "missing" && state !== "unusable")
172
+ return { status: state };
173
+ const slug = vault.slug;
174
+ const dirs = legacyJournalDirs(home, opts.env ?? process.env, slug);
175
+ if (dirs.length === 0)
176
+ return { status: "no-journal" };
177
+ const files = lastSyncedEntries(slug, dirs, opts.readJournal, opts.offSince);
178
+ const keys = Object.keys(files);
179
+ const file = legacyJournalExportPath(home, vault.uid, slug);
180
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
181
+ removeLegacyJournalTemps(home, vault);
182
+ const tmp = `${file}.${process.pid}.tmp`;
183
+ const fd = fs.openSync(tmp, "wx", 0o600);
184
+ let entries = 0;
185
+ let closed = false;
186
+ try {
187
+ fs.writeSync(fd, `{"version":"2","exportedAt":${now()},"files":{`);
188
+ let chunk = [];
189
+ for (const key of keys) {
190
+ const entry = exportedEntry(files[key]);
191
+ if (!entry)
192
+ continue;
193
+ chunk.push(`${entries > 0 ? "," : ""}${JSON.stringify(key)}:${JSON.stringify(entry)}`);
194
+ entries += 1;
195
+ if (chunk.length >= CHUNK_ENTRIES) {
196
+ fs.writeSync(fd, chunk.join(""));
197
+ chunk = [];
198
+ }
199
+ }
200
+ 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
+ if (fs.fstatSync(fd).size > LEGACY_JOURNAL_EXPORT_MAX_BYTES) {
204
+ 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
+ }
206
+ fs.fsyncSync(fd);
207
+ closed = true;
208
+ fs.closeSync(fd);
209
+ }
210
+ catch (error) {
211
+ if (!closed)
212
+ fs.closeSync(fd);
213
+ fs.rmSync(tmp, { force: true });
214
+ throw error;
215
+ }
216
+ try {
217
+ const settled = legacyJournalExportState(home, vault, now());
218
+ if (settled !== "missing" && settled !== "unusable") {
219
+ fs.rmSync(tmp, { force: true });
220
+ return { status: settled };
221
+ }
222
+ if (settled === "unusable" && !fs.lstatSync(file).isFile())
223
+ fs.rmSync(file, { recursive: true, force: true });
224
+ fs.renameSync(tmp, file);
225
+ return { status: "written", entries, file, replaced: settled === "unusable" };
226
+ }
227
+ catch (error) {
228
+ fs.rmSync(tmp, { force: true });
229
+ throw error;
230
+ }
231
+ }
232
+ export function removeLegacyJournalExport(home, vault) {
233
+ if (!exportable(vault))
234
+ return;
235
+ const file = legacyJournalExportPath(home, vault.uid, vault.slug);
236
+ for (const target of [file, `${file}.consumed`, `${file}.unproven`, `${file}.unproven.bad`]) {
237
+ fs.rmSync(target, { recursive: true, force: true });
238
+ }
239
+ removeLegacyJournalTemps(home, vault);
240
+ }
241
+ //# sourceMappingURL=legacy-journal-export.js.map
@@ -0,0 +1,15 @@
1
+ import type { LegacyJournalReader } from "./legacy-journal-export.js";
2
+ export declare const LEGACY_JOURNAL_READ_API = "readJournalWithoutWrites";
3
+ export interface LegacyJournalReaderSource {
4
+ root: string;
5
+ version: string;
6
+ }
7
+ export type LoadedLegacyJournalReader = {
8
+ reader: LegacyJournalReader;
9
+ source: LegacyJournalReaderSource;
10
+ } | {
11
+ reader?: undefined;
12
+ reason: string;
13
+ };
14
+ export declare function loadLegacyJournalReader(copies: readonly (LegacyJournalReaderSource | null | undefined)[], importModule?: (url: string) => Promise<Record<string, unknown>>): Promise<LoadedLegacyJournalReader>;
15
+ //# sourceMappingURL=legacy-journal-reader.d.ts.map
@@ -0,0 +1,56 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ export const LEGACY_JOURNAL_READ_API = "readJournalWithoutWrites";
5
+ function entryFile(root) {
6
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"));
7
+ return path.join(root, typeof pkg.main === "string" ? pkg.main : "dist/index.js");
8
+ }
9
+ function readerFrom(module) {
10
+ const read = module[LEGACY_JOURNAL_READ_API];
11
+ if (typeof read !== "function")
12
+ return undefined;
13
+ return (slug, stateDir) => {
14
+ const before = process.env.HQ_STATE_DIR;
15
+ process.env.HQ_STATE_DIR = stateDir;
16
+ let result;
17
+ try {
18
+ result = read(slug);
19
+ }
20
+ finally {
21
+ if (before === undefined)
22
+ delete process.env.HQ_STATE_DIR;
23
+ else
24
+ process.env.HQ_STATE_DIR = before;
25
+ }
26
+ if (!result || typeof result !== "object")
27
+ throw new Error(`${LEGACY_JOURNAL_READ_API} returned no result for ${slug}`);
28
+ if (result.status === "empty")
29
+ return { files: {} };
30
+ if (result.status !== "ok" || !result.files || typeof result.files !== "object") {
31
+ const why = typeof result.errorClass === "string" ? ` (${result.errorClass})` : "";
32
+ throw new Error(`the current sync's journal for ${slug} in ${stateDir} could not be read${why}`);
33
+ }
34
+ return { files: result.files };
35
+ };
36
+ }
37
+ export async function loadLegacyJournalReader(copies, importModule = (url) => import(url)) {
38
+ const seen = new Set();
39
+ const reasons = [];
40
+ for (const copy of copies) {
41
+ if (!copy || seen.has(copy.root))
42
+ continue;
43
+ seen.add(copy.root);
44
+ try {
45
+ const reader = readerFrom(await importModule(pathToFileURL(entryFile(copy.root)).href));
46
+ if (reader)
47
+ return { reader, source: copy };
48
+ reasons.push(`hq-cloud ${copy.version} cannot read a journal without writing to it`);
49
+ }
50
+ catch (error) {
51
+ reasons.push(`hq-cloud ${copy.version} at ${copy.root} could not be loaded: ${error instanceof Error ? error.message : String(error)}`);
52
+ }
53
+ }
54
+ return { reason: reasons.length > 0 ? reasons.join("; ") : "no hq-cloud copy was found" };
55
+ }
56
+ //# sourceMappingURL=legacy-journal-reader.js.map
@@ -2,6 +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
6
  import { type SyncCoreRolloutState } from "./rollout-state.js";
6
7
  export interface SyncCoreMembership {
7
8
  companyUid: string;
@@ -27,6 +28,8 @@ export interface SyncCoreReconcileDeps {
27
28
  * can adopt it without a pass of the current sync. Omitted: nothing is set up.
28
29
  */
29
30
  resolveCompany?: (companyUid: string) => Promise<SyncCoreCompanyEntity | null>;
31
+ readLegacyJournal?: LegacyJournalReader;
32
+ legacyJournalUnavailable?: string;
30
33
  /** Only desktop and self-hosted machines set up a joined company. */
31
34
  machineType?: MachineType;
32
35
  ensureBinary: (release: string) => Promise<SyncCoreBinaryInstall>;
@@ -8,6 +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
12
  import { SYNC_RUST_ENGINE_ROLLOUT_FLAG } from "./flag.js";
12
13
  import { readSyncCoreRolloutState, syncCoreRolloutStatePath, writeSyncCoreRolloutState, } from "./rollout-state.js";
13
14
  function message(error) {
@@ -151,6 +152,14 @@ async function setUpJoinedCompanies(deps, memberships, ctx) {
151
152
  }
152
153
  }
153
154
  }
155
+ function dropLegacyJournalExport(home, vault, warnings) {
156
+ try {
157
+ removeLegacyJournalExport(home, vault);
158
+ }
159
+ catch (error) {
160
+ warnings.push(`could not remove the old copy of the current sync's record of ${vault.slug ?? vault.uid}: ${message(error)}`);
161
+ }
162
+ }
154
163
  export async function reconcileSyncCore(deps) {
155
164
  const now = deps.now ?? (() => new Date());
156
165
  const log = deps.log ?? (() => { });
@@ -272,6 +281,8 @@ export async function reconcileSyncCore(deps) {
272
281
  const engineHome = syncCoreEngineHome(deps.home, vault.uid);
273
282
  if (!before)
274
283
  clearEngineStatus(deps.home, vault.uid);
284
+ if (!before && !pending)
285
+ dropLegacyJournalExport(deps.home, vault, warnings);
275
286
  writeEngineHome({ home: deps.home, hqRoot: deps.hqRoot, vault, phase: "full", tokenFile: deps.tokenFile, platform, release: engineRelease });
276
287
  const wasFull = before?.phase === "full";
277
288
  const alreadyOff = vault.kind === "personal"
@@ -312,6 +323,31 @@ export async function reconcileSyncCore(deps) {
312
323
  ...(firstCycle ? { firstCycle } : {}),
313
324
  ...(downloadStreams !== undefined ? { downloadStreams } : {}),
314
325
  });
326
+ if (vault.kind === "company" && wasFull && !alreadyOff && switchesBefore.unreadable === undefined) {
327
+ dropLegacyJournalExport(deps.home, vault, warnings);
328
+ }
329
+ const cycledSinceOff = vault.kind === "company" && wasFull && alreadyOff
330
+ ? engineFirstCycle(engineHome, vault.uid, legacyOffSince)
331
+ : null;
332
+ if (cycledSinceOff && Date.parse(cycledSinceOff.at) > Date.parse(legacyOffSince)) {
333
+ try {
334
+ if (deps.readLegacyJournal) {
335
+ const exported = writeLegacyJournalExport({ home: deps.home, vault, readJournal: deps.readLegacyJournal, env, now: () => now().getTime(), offSince: Date.parse(legacyOffSince) });
336
+ if (exported.status === "written") {
337
+ log(`${vault.uid}: ${exported.replaced ? "replaced an unusable copy of" : "wrote"} what the current sync last synced for ${exported.entries} files ${exported.replaced ? "at" : "to"} ${exported.file}, so the new sync engine can tell an old copy from an edit that was never uploaded`);
338
+ }
339
+ }
340
+ else if (deps.legacyJournalUnavailable) {
341
+ const state = legacyJournalExportState(deps.home, vault, now().getTime());
342
+ if ((state === "missing" || state === "unusable") && legacyJournalDirs(deps.home, env, vault.slug ?? "").length > 0) {
343
+ log(`${vault.uid}: not copying the current sync's record of ${vault.slug ?? vault.uid} for the new sync engine: ${deps.legacyJournalUnavailable}`);
344
+ }
345
+ }
346
+ }
347
+ catch (error) {
348
+ warnings.push(`could not copy the current sync's record of ${vault.slug ?? vault.uid} for the new sync engine: ${message(error)}; the engine keeps treating files that differ from the vault as conflicts`);
349
+ }
350
+ }
315
351
  if (firstCycle && firstCycle !== recorded && (!recorded || firstCycle.planned > 0))
316
352
  log(`${vault.uid}: first full cycle ${firstCycle.at}: ${firstCycle.planned} planned, ${firstCycle.completed} completed, ${firstCycle.held} held`);
317
353
  if (vault.kind === "company" && vault.slug)
@@ -335,7 +371,7 @@ export async function reconcileSyncCore(deps) {
335
371
  if (vault.phase !== "full")
336
372
  continue;
337
373
  const engineHome = syncCoreEngineHome(deps.home, vault.uid);
338
- const heldDeletes = readEngineHeldDeletes(engineHome, vault.uid);
374
+ const heldDeletes = readEngineHeldDeletes(engineHome, vault.uid, (line) => warnings.push(line));
339
375
  if (heldDeletes && heldDeletes !== "unreadable") {
340
376
  try {
341
377
  writeHandbackKeep(deps.home, vault, heldDeletes, at);
@@ -368,8 +404,12 @@ export async function reconcileSyncCore(deps) {
368
404
  };
369
405
  writeSyncCoreRolloutState(deps.home, state);
370
406
  for (const uid of stopped) {
371
- if (!handedBack.some((vault) => vault.uid === uid))
372
- removeEngineOwnership(deps.home, uid);
407
+ if (handedBack.some((vault) => vault.uid === uid))
408
+ continue;
409
+ removeEngineOwnership(deps.home, uid);
410
+ const vault = previousByUid.get(uid);
411
+ if (vault)
412
+ dropLegacyJournalExport(deps.home, vault, warnings);
373
413
  }
374
414
  const patch = {
375
415
  ...(personalOff ? { personal: false } : {}),
@@ -87,6 +87,7 @@ export declare const CLI_TELEMETRY_CONSENT_TTL_MS: number;
87
87
  * throws. Only `true` allows a send.
88
88
  */
89
89
  export declare function hasCliTelemetryConsent(token: string, machineIdentity: boolean, signal: AbortSignal): Promise<boolean>;
90
+ export declare function readCliTelemetryConsent(token: string, machineIdentity: boolean, signal: AbortSignal): Promise<boolean | null>;
90
91
  export declare function telemetryDisclosureMarkerPath(): string;
91
92
  /**
92
93
  * Print the one-line disclosure at most once per machine. Returns whether
@@ -362,13 +362,16 @@ async function fetchCliTelemetryConsent(token, signal) {
362
362
  * throws. Only `true` allows a send.
363
363
  */
364
364
  export async function hasCliTelemetryConsent(token, machineIdentity, signal) {
365
+ return (await readCliTelemetryConsent(token, machineIdentity, signal)) === true;
366
+ }
367
+ export async function readCliTelemetryConsent(token, machineIdentity, signal) {
365
368
  try {
366
369
  // Agents and machine identities are always collected; the server answers
367
370
  // `agent-required` for them, so no request is needed.
368
371
  if (machineIdentity)
369
372
  return true;
370
373
  if (signal.aborted)
371
- return false;
374
+ return null;
372
375
  const subject = consentSubjectKey(token);
373
376
  if (subject) {
374
377
  const cached = readCachedConsent(subject, Date.now());
@@ -389,10 +392,10 @@ export async function hasCliTelemetryConsent(token, machineIdentity, signal) {
389
392
  });
390
393
  pendingConsentReads.set(key, pending);
391
394
  }
392
- return (await pending) === true;
395
+ return await pending;
393
396
  }
394
397
  catch {
395
- return false;
398
+ return null;
396
399
  }
397
400
  }
398
401
  /**
@@ -0,0 +1,96 @@
1
+ export declare const HOOK_ENGINE_ROLLUP_EVENT = "hook_engine_failure_rollup";
2
+ export declare const HOOK_ENGINE_LOG_RELATIVE: string;
3
+ export declare const HOOK_ENGINE_ROLLUP_STATE_FILE = "hook-engine-rollup.json";
4
+ export declare const HOOK_ENGINE_ROLLUP_LOOKBACK_DAYS = 7;
5
+ export declare const HOOK_ENGINE_ROLLUP_MAX_READ_BYTES: number;
6
+ export declare const HOOK_ENGINE_ROLLUP_MAX_GROUPS = 500;
7
+ export declare const HOOK_ENGINE_ROLLUP_BATCH_SIZE = 50;
8
+ export declare const HOOK_ENGINE_ROLLUP_POST_TIMEOUT_MS = 15000;
9
+ export declare const HOOK_ENGINE_ROLLUP_MAX_CONFIRM_GAP_MS: number;
10
+ export declare const HOOK_ENGINE_SHIPPED_HOOK_IDS: ReadonlySet<string>;
11
+ export type HookEngineFailureKind = "bridge" | "dispatch-failure" | "run-deny" | "run-fault";
12
+ export type HookEngineFailureReason = "budget" | "died" | "unreadable" | "spawn" | "other" | "none";
13
+ export interface HookEngineFailureProperties {
14
+ kind: HookEngineFailureKind;
15
+ hook: string;
16
+ hookEvent: string;
17
+ bridgeStatus: string;
18
+ reason: HookEngineFailureReason;
19
+ code?: number;
20
+ timedOut?: boolean;
21
+ host: string;
22
+ engine: string;
23
+ release?: string;
24
+ count: number;
25
+ medianMs?: number;
26
+ p95Ms?: number;
27
+ }
28
+ export interface HookEngineRollupEvent {
29
+ eventName: typeof HOOK_ENGINE_ROLLUP_EVENT;
30
+ app: "hq-cli";
31
+ source: "cli";
32
+ occurredAt: string;
33
+ consentBasis: HookEngineRollupConsentBasis;
34
+ schemaVersion: 1;
35
+ idempotencyKey: string;
36
+ properties: HookEngineFailureProperties;
37
+ }
38
+ export type HookEngineRollupConsentBasis = "opted-in" | "agent-required";
39
+ export type HookEngineRollupConsent = "yes" | "no" | "unknown";
40
+ export type HookEngineRollupPostResult = "ok" | "retry" | "rejected";
41
+ export interface HookEngineRollupClient {
42
+ subject: string;
43
+ consentBasis?: HookEngineRollupConsentBasis;
44
+ consent(): Promise<HookEngineRollupConsent>;
45
+ post(events: readonly HookEngineRollupEvent[]): Promise<HookEngineRollupPostResult>;
46
+ }
47
+ export interface HookEngineRollupOptions {
48
+ home: string;
49
+ stateFile: string;
50
+ env?: NodeJS.ProcessEnv;
51
+ now?: () => number;
52
+ maxConfirmGapMs?: number;
53
+ client?: () => HookEngineRollupClient | null;
54
+ newRunId?: () => string;
55
+ }
56
+ export type HookEngineRollupResult = {
57
+ status: "disabled" | "up-to-date" | "no-identity" | "not-consented" | "consent-unknown" | "started" | "nothing-to-send";
58
+ } | {
59
+ status: "sent";
60
+ events: number;
61
+ rejected: number;
62
+ droppedGroups: number;
63
+ } | {
64
+ status: "send-failed";
65
+ };
66
+ interface Classified {
67
+ day: string;
68
+ properties: Omit<HookEngineFailureProperties, "count" | "medianMs" | "p95Ms">;
69
+ ms?: number;
70
+ }
71
+ export declare function isSafeHookEngineRollupProperties(value: unknown): value is HookEngineFailureProperties;
72
+ export declare function engineVersion(value: unknown): {
73
+ engine: string;
74
+ release?: string;
75
+ };
76
+ export declare function runReason(kind: "run-deny" | "run-fault", value: unknown): HookEngineFailureReason;
77
+ export declare function classifyHookEngineRow(row: Record<string, unknown>): Omit<Classified, "day"> | null;
78
+ export declare function aggregateHookEngineFailures(rows: readonly Classified[], maxGroups?: number): {
79
+ groups: Array<{
80
+ day: string;
81
+ properties: HookEngineFailureProperties;
82
+ }>;
83
+ dropped: number;
84
+ };
85
+ export declare function buildHookEngineRollupEvents(groups: ReadonlyArray<{
86
+ day: string;
87
+ properties: HookEngineFailureProperties;
88
+ }>, runId: string, consentBasis?: HookEngineRollupConsentBasis): HookEngineRollupEvent[];
89
+ export declare function defaultHookEngineRollupClient(): HookEngineRollupClient | null;
90
+ export declare function hookEngineRollupLogLine(result: HookEngineRollupResult, previous: HookEngineRollupResult["status"] | undefined): {
91
+ level: "info" | "warn";
92
+ message: string;
93
+ } | null;
94
+ export declare function runHookEngineRollup(options: HookEngineRollupOptions): Promise<HookEngineRollupResult>;
95
+ export {};
96
+ //# sourceMappingURL=hook-engine-rollup.d.ts.map