@indigoai-us/hq-cli 5.345.226 → 5.345.228

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 (132) hide show
  1. package/CHANGELOG.md +142 -0
  2. package/dist/command-catalog.generated.d.ts +137 -0
  3. package/dist/command-catalog.generated.js +164 -0
  4. package/dist/commands/auth.d.ts +2 -2
  5. package/dist/commands/auth.js +3 -3
  6. package/dist/commands/core-delegate-w1b.js +92 -69
  7. package/dist/commands/core-delegate.d.ts +19 -1
  8. package/dist/commands/core-delegate.js +411 -6
  9. package/dist/commands/core-dm-bind-native.js +2 -1
  10. package/dist/commands/core-handoff.d.ts +5 -0
  11. package/dist/commands/core-handoff.js +1008 -14
  12. package/dist/commands/core-pin-native.d.ts +1 -0
  13. package/dist/commands/core-pin-native.js +3 -15
  14. package/dist/commands/core-register-project-native.d.ts +6 -0
  15. package/dist/commands/core-register-project-native.js +182 -52
  16. package/dist/commands/core-work-mesh-bind-trusted-native.js +4 -9
  17. package/dist/commands/daemon.js +2 -2
  18. package/dist/commands/index-cmd.d.ts +3 -1
  19. package/dist/commands/index-cmd.js +12 -0
  20. package/dist/commands/lanes-checks.js +1 -1
  21. package/dist/commands/lanes-session-start.d.ts +1 -2
  22. package/dist/commands/lanes-session-start.js +9 -145
  23. package/dist/commands/lanes-shared.d.ts +3 -0
  24. package/dist/commands/lanes.d.ts +3 -0
  25. package/dist/commands/lanes.js +94 -27
  26. package/dist/commands/link.d.ts +8 -3
  27. package/dist/commands/link.js +14 -17
  28. package/dist/commands/mcp-registration.d.ts +65 -7
  29. package/dist/commands/mcp-registration.js +289 -51
  30. package/dist/commands/mesh.d.ts +12 -0
  31. package/dist/commands/mesh.js +92 -10
  32. package/dist/commands/reindex.js +6 -0
  33. package/dist/commands/repo.d.ts +13 -0
  34. package/dist/commands/repo.js +39 -1
  35. package/dist/commands/sync-mode.d.ts +3 -1
  36. package/dist/commands/sync-mode.js +11 -1
  37. package/dist/lazy-commands.js +3 -4
  38. package/dist/lib/checkpoint-ontology/entity-file.js +4 -4
  39. package/dist/lib/checkpoint-ontology/merge-copies.js +7 -11
  40. package/dist/lib/checkpoint-ontology/plan.js +2 -1
  41. package/dist/lib/core-utils/archive-old-threads.js +5 -2
  42. package/dist/lib/core-utils/session-company.d.ts +13 -1
  43. package/dist/lib/core-utils/session-company.js +75 -4
  44. package/dist/lib/core-utils/worktree-resume.d.ts +6 -0
  45. package/dist/lib/core-utils/worktree-resume.js +8 -4
  46. package/dist/lib/daemon/background-qos.d.ts +7 -0
  47. package/dist/lib/daemon/background-qos.js +13 -0
  48. package/dist/lib/daemon/catalog.d.ts +9 -0
  49. package/dist/lib/daemon/catalog.js +8 -1
  50. package/dist/lib/daemon/hook-requests-acl-suggest.d.ts +18 -0
  51. package/dist/lib/daemon/hook-requests-acl-suggest.js +245 -0
  52. package/dist/lib/daemon/hook-requests-fleet-session-start.d.ts +32 -0
  53. package/dist/lib/daemon/hook-requests-fleet-session-start.js +214 -0
  54. package/dist/lib/daemon/hook-requests-mesh-tool-writes.d.ts +44 -0
  55. package/dist/lib/daemon/hook-requests-mesh-tool-writes.js +292 -0
  56. package/dist/lib/daemon/hook-requests-mesh.d.ts +54 -0
  57. package/dist/lib/daemon/hook-requests-mesh.js +559 -0
  58. package/dist/lib/daemon/hook-requests.d.ts +349 -8
  59. package/dist/lib/daemon/hook-requests.js +1312 -46
  60. package/dist/lib/daemon/machine-checks.d.ts +12 -2
  61. package/dist/lib/daemon/machine-checks.js +27 -10
  62. package/dist/lib/daemon/merge-sections.d.ts +24 -2
  63. package/dist/lib/daemon/merge-sections.js +58 -16
  64. package/dist/lib/daemon/ops/policy.js +4 -2
  65. package/dist/lib/daemon/resolver.js +9 -2
  66. package/dist/lib/daemon/run.d.ts +11 -7
  67. package/dist/lib/daemon/run.js +168 -24
  68. package/dist/lib/daemon/search-index-worker-v1.d.ts +2 -0
  69. package/dist/lib/daemon/search-index-worker-v1.js +25 -0
  70. package/dist/lib/daemon/session-registry.d.ts +0 -1
  71. package/dist/lib/daemon/session-registry.js +0 -3
  72. package/dist/lib/daemon/supervisor.d.ts +3 -1
  73. package/dist/lib/daemon/supervisor.js +1 -1
  74. package/dist/lib/daemon/tcc-eperm.d.ts +59 -4
  75. package/dist/lib/daemon/tcc-eperm.js +110 -8
  76. package/dist/lib/doctor/fix/process-identity.d.ts +20 -2
  77. package/dist/lib/doctor/fix/process-identity.js +48 -5
  78. package/dist/lib/hook-engine/canary-gate.js +1 -0
  79. package/dist/lib/hook-engine/native-stop-compatibility.json +2 -1
  80. package/dist/lib/hot-channels/adapters/attio.js +2 -1
  81. package/dist/lib/hot-channels/adapters/meetings.js +2 -1
  82. package/dist/lib/lanes/company-outposts.d.ts +37 -0
  83. package/dist/lib/lanes/company-outposts.js +164 -0
  84. package/dist/lib/lanes/liveness.d.ts +6 -0
  85. package/dist/lib/lanes/liveness.js +49 -8
  86. package/dist/lib/lanes/orphan-report.d.ts +15 -0
  87. package/dist/lib/lanes/orphan-report.js +223 -0
  88. package/dist/lib/lanes/orphan-sweep.d.ts +26 -0
  89. package/dist/lib/lanes/orphan-sweep.js +152 -0
  90. package/dist/lib/lanes/reaper.d.ts +2 -0
  91. package/dist/lib/lanes/reaper.js +11 -8
  92. package/dist/lib/lanes/reconcile.d.ts +8 -7
  93. package/dist/lib/lanes/reconcile.js +39 -0
  94. package/dist/lib/mesh/live/backfill-held.d.ts +13 -0
  95. package/dist/lib/mesh/live/backfill-held.js +23 -0
  96. package/dist/lib/mesh/live/daemon/mode.d.ts +8 -4
  97. package/dist/lib/mesh/live/daemon/mode.js +8 -4
  98. package/dist/lib/mesh/live/daemon/run.d.ts +14 -3
  99. package/dist/lib/mesh/live/daemon/run.js +116 -7
  100. package/dist/lib/mesh/live/direct-drain.d.ts +123 -0
  101. package/dist/lib/mesh/live/direct-drain.js +315 -0
  102. package/dist/lib/mesh/live/emit-replay.d.ts +10 -0
  103. package/dist/lib/mesh/live/emit-replay.js +10 -0
  104. package/dist/lib/mesh/live/flush.d.ts +15 -0
  105. package/dist/lib/mesh/live/flush.js +27 -0
  106. package/dist/lib/mesh/live/liveness-carry.d.ts +45 -0
  107. package/dist/lib/mesh/live/liveness-carry.js +141 -0
  108. package/dist/lib/mesh/live/spool.d.ts +19 -0
  109. package/dist/lib/mesh/live/spool.js +80 -0
  110. package/dist/lib/safe-store.d.ts +2 -0
  111. package/dist/lib/safe-store.js +8 -6
  112. package/dist/lib/search-index/index.d.ts +9 -3
  113. package/dist/lib/search-index/index.js +35 -10
  114. package/dist/lib/search-index/worker-process.d.ts +9 -0
  115. package/dist/lib/search-index/worker-process.js +171 -0
  116. package/dist/lib/session-company-lock.d.ts +3 -1
  117. package/dist/lib/session-company-lock.js +3 -2
  118. package/dist/utils/delegate-command-supervisor.d.ts +3 -0
  119. package/dist/utils/delegate-command-supervisor.js +44 -0
  120. package/dist/utils/delegate-lock.d.ts +12 -0
  121. package/dist/utils/delegate-lock.js +88 -0
  122. package/dist/utils/frontmatter.d.ts +27 -0
  123. package/dist/utils/frontmatter.js +33 -0
  124. package/dist/utils/hook-trust.d.ts +1 -0
  125. package/dist/utils/hook-trust.js +18 -2
  126. package/dist/utils/host-registration.d.ts +13 -1
  127. package/dist/utils/host-registration.js +98 -5
  128. package/dist/utils/package-use-lease.d.ts +1 -1
  129. package/dist/utils/package-use-lease.js +15 -7
  130. package/docs/anywhere-runtime.md +17 -0
  131. package/package.json +8 -7
  132. package/scripts/check-function-manifest.mjs +17 -3
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Session liveness that outlives the spool.
3
+ *
4
+ * `hq lanes` reads the last event of each session from spool.jsonl. Once the
5
+ * direct-mode drain delivers spool lines and removes them, that record would
6
+ * be gone, so the drain first copies the last event per session here: kind,
7
+ * time and sequence number only, never the event body. Lanes merges this file
8
+ * with whatever is still in the spool (the newer event wins).
9
+ *
10
+ * One writer (the mesh daemon). Entries older than the retention are pruned on
11
+ * every write, so the file is bounded by the sessions seen in that window.
12
+ */
13
+ import * as fs from "node:fs";
14
+ import * as path from "node:path";
15
+ import { ensureOwnerDir } from "../../work-context/atomic.js";
16
+ import { workMeshRoot } from "./paths.js";
17
+ export const LIVENESS_CARRY_BASENAME = "liveness-carry.json";
18
+ /** Well past the lanes "lost" window (12 h by default). */
19
+ export const LIVENESS_CARRY_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
20
+ export function livenessCarryPath(root) {
21
+ return path.join(root ?? workMeshRoot(), LIVENESS_CARRY_BASENAME);
22
+ }
23
+ function record(value) {
24
+ return value && typeof value === "object" && !Array.isArray(value)
25
+ ? value
26
+ : null;
27
+ }
28
+ /** Parse the carry file's text. Null when it is not a carry file. */
29
+ export function parseLivenessCarry(raw) {
30
+ let parsed;
31
+ try {
32
+ parsed = record(JSON.parse(raw));
33
+ }
34
+ catch {
35
+ return null;
36
+ }
37
+ const sessionsIn = parsed ? record(parsed.sessions) : null;
38
+ if (!parsed || parsed.v !== 1 || !sessionsIn)
39
+ return null;
40
+ const sessions = {};
41
+ for (const [sessionId, value] of Object.entries(sessionsIn)) {
42
+ const entry = record(value);
43
+ if (!entry)
44
+ continue;
45
+ const { lastKind, lastAt, lastSeq } = entry;
46
+ if (typeof lastKind !== "string" || typeof lastAt !== "string")
47
+ continue;
48
+ if (!Number.isFinite(Date.parse(lastAt)))
49
+ continue;
50
+ sessions[sessionId] = {
51
+ sessionId,
52
+ lastKind,
53
+ lastAt,
54
+ ...(typeof lastSeq === "number" ? { lastSeq } : {}),
55
+ };
56
+ }
57
+ return {
58
+ v: 1,
59
+ updatedAt: typeof parsed.updatedAt === "string" ? parsed.updatedAt : "",
60
+ sessions,
61
+ };
62
+ }
63
+ export function readLivenessCarry(root) {
64
+ try {
65
+ return parseLivenessCarry(fs.readFileSync(livenessCarryPath(root), "utf8"));
66
+ }
67
+ catch {
68
+ return null;
69
+ }
70
+ }
71
+ /**
72
+ * True when `next` replaces `prior` as a session's last event: a later time,
73
+ * or the same time without a lower sequence number. Same rule lanes applies
74
+ * to spool lines.
75
+ */
76
+ export function supersedesLivenessEntry(prior, next) {
77
+ if (!prior)
78
+ return true;
79
+ const priorAt = Date.parse(prior.lastAt);
80
+ const nextAt = Date.parse(next.lastAt);
81
+ if (nextAt < priorAt)
82
+ return false;
83
+ if (nextAt === priorAt &&
84
+ next.lastSeq !== undefined &&
85
+ prior.lastSeq !== undefined &&
86
+ next.lastSeq < prior.lastSeq) {
87
+ return false;
88
+ }
89
+ return true;
90
+ }
91
+ /** Fold one spool line (raw event or held envelope) into `sessions`. */
92
+ export function ingestLivenessLine(line, sessions) {
93
+ if (!line.trim())
94
+ return;
95
+ let outer;
96
+ try {
97
+ outer = record(JSON.parse(line));
98
+ }
99
+ catch {
100
+ return;
101
+ }
102
+ if (!outer)
103
+ return;
104
+ const event = record(outer.event) ?? outer;
105
+ const { sessionId, kind, at, seq } = event;
106
+ if (typeof sessionId !== "string" || !sessionId)
107
+ return;
108
+ if (typeof kind !== "string" || !kind)
109
+ return;
110
+ if (typeof at !== "string" || !Number.isFinite(Date.parse(at)))
111
+ return;
112
+ const next = {
113
+ sessionId,
114
+ lastKind: kind,
115
+ lastAt: at,
116
+ ...(typeof seq === "number" ? { lastSeq: seq } : {}),
117
+ };
118
+ if (supersedesLivenessEntry(sessions[sessionId], next))
119
+ sessions[sessionId] = next;
120
+ }
121
+ /**
122
+ * Fold lines into the carry file. `feed` is handed an `ingest` function and
123
+ * calls it once per line, so a caller can stream a large file. Prunes entries
124
+ * past the retention and writes with a rename. Returns the session count kept.
125
+ */
126
+ export function updateLivenessCarry(root, feed, now = () => new Date()) {
127
+ const sessions = readLivenessCarry(root)?.sessions ?? {};
128
+ feed((line) => ingestLivenessLine(line, sessions));
129
+ const cutoff = now().getTime() - LIVENESS_CARRY_RETENTION_MS;
130
+ for (const [sessionId, entry] of Object.entries(sessions)) {
131
+ if (Date.parse(entry.lastAt) < cutoff)
132
+ delete sessions[sessionId];
133
+ }
134
+ const file = { v: 1, updatedAt: now().toISOString(), sessions };
135
+ const target = livenessCarryPath(ensureOwnerDir(root));
136
+ const tmp = `${target}.${process.pid}.${Date.now()}.tmp`;
137
+ fs.writeFileSync(tmp, `${JSON.stringify(file)}\n`, { mode: 0o600 });
138
+ fs.renameSync(tmp, target);
139
+ return Object.keys(sessions).length;
140
+ }
141
+ //# sourceMappingURL=liveness-carry.js.map
@@ -22,6 +22,19 @@ export declare function appendHeldLine(line: string, root?: string): string;
22
22
  /** Append a deduplicated held batch under one file lock and one write. */
23
23
  export declare function appendHeldLinesIfAbsent(lines: string[], root?: string): number;
24
24
  export declare function appendDeadLetterLine(line: string, root?: string): string;
25
+ /**
26
+ * Keep dead-letter.jsonl bounded for the direct-mode drain. Only lines
27
+ * dead-lettered at or after `protectBefore` count against `maxLines`; older
28
+ * lines (and lines with no readable `at`) are never removed, so a backlog
29
+ * that predates the drain stays as it was. When the newer lines exceed the
30
+ * cap, the oldest of them are removed down to three quarters of it. Runs under
31
+ * the same lock every dead-letter append takes, and replaces the file with a
32
+ * rename. Returns the number of lines removed.
33
+ */
34
+ export declare function trimDeadLetter(root: string, opts: {
35
+ maxLines: number;
36
+ protectBefore: string;
37
+ }): number;
25
38
  export declare function appendDroppedReceipt(receipt: Record<string, unknown>, root?: string): string;
26
39
  export interface ClaimResult {
27
40
  claimPath: string | null;
@@ -41,6 +54,12 @@ export declare function claimHeld(root: string, ts?: string): ClaimResult;
41
54
  * Any doubt answers true.
42
55
  */
43
56
  export declare function hasPendingFlushWork(root: string): boolean;
57
+ /**
58
+ * Like hasPendingFlushWork, without the held file: true when the spool has
59
+ * bytes or an orphan claim is waiting. The direct-mode drain uses it so a held
60
+ * file alone does not start a flush on every cycle.
61
+ */
62
+ export declare function hasPendingSpoolWork(root: string): boolean;
44
63
  /**
45
64
  * Recover orphaned claim files: read their lines and return paths to unlink
46
65
  * after the flush dispositions them.
@@ -222,6 +222,71 @@ export function appendDeadLetterLine(line, root) {
222
222
  });
223
223
  return dl;
224
224
  }
225
+ /**
226
+ * Keep dead-letter.jsonl bounded for the direct-mode drain. Only lines
227
+ * dead-lettered at or after `protectBefore` count against `maxLines`; older
228
+ * lines (and lines with no readable `at`) are never removed, so a backlog
229
+ * that predates the drain stays as it was. When the newer lines exceed the
230
+ * cap, the oldest of them are removed down to three quarters of it. Runs under
231
+ * the same lock every dead-letter append takes, and replaces the file with a
232
+ * rename. Returns the number of lines removed.
233
+ */
234
+ export function trimDeadLetter(root, opts) {
235
+ const dl = workMeshDeadLetterPath(root);
236
+ if (opts.maxLines <= 0 || !fs.existsSync(dl))
237
+ return 0;
238
+ const protectBeforeMs = Date.parse(opts.protectBefore);
239
+ if (!Number.isFinite(protectBeforeMs))
240
+ return 0;
241
+ const countsAgainstCap = (line) => {
242
+ try {
243
+ const parsed = JSON.parse(line);
244
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
245
+ return false;
246
+ const at = parsed.at;
247
+ const atMs = typeof at === "string" ? Date.parse(at) : Number.NaN;
248
+ return Number.isFinite(atMs) && atMs >= protectBeforeMs;
249
+ }
250
+ catch {
251
+ return false;
252
+ }
253
+ };
254
+ return withJsonlLock(dl, () => {
255
+ let newer = 0;
256
+ if (!forEachJsonlLine(dl, (line) => {
257
+ if (line.trim() && countsAgainstCap(line))
258
+ newer += 1;
259
+ }))
260
+ return 0;
261
+ if (newer <= opts.maxLines)
262
+ return 0;
263
+ const remove = newer - Math.floor(opts.maxLines * 0.75);
264
+ const tmp = `${dl}.${process.pid}.${Date.now()}.tmp`;
265
+ const fd = fs.openSync(tmp, "wx", 0o600);
266
+ let removed = 0;
267
+ try {
268
+ forEachJsonlLine(dl, (line) => {
269
+ if (!line.trim())
270
+ return;
271
+ if (removed < remove && countsAgainstCap(line)) {
272
+ removed += 1;
273
+ return;
274
+ }
275
+ fs.writeSync(fd, `${line}\n`);
276
+ });
277
+ fs.fsyncSync(fd);
278
+ }
279
+ catch (err) {
280
+ fs.closeSync(fd);
281
+ fs.rmSync(tmp, { force: true });
282
+ throw err;
283
+ }
284
+ fs.closeSync(fd);
285
+ fs.renameSync(tmp, dl);
286
+ chmodOwnerFile(dl);
287
+ return removed;
288
+ });
289
+ }
225
290
  export function appendDroppedReceipt(receipt, root) {
226
291
  const dest = workMeshDroppedReceiptPath(root ?? workMeshRoot());
227
292
  appendJsonlLine(dest, JSON.stringify(receipt));
@@ -303,6 +368,21 @@ export function hasPendingFlushWork(root) {
303
368
  }
304
369
  return jsonlHasBytes(workMeshSpoolPath(root)) || jsonlHasBytes(workMeshHeldPath(root));
305
370
  }
371
+ /**
372
+ * Like hasPendingFlushWork, without the held file: true when the spool has
373
+ * bytes or an orphan claim is waiting. The direct-mode drain uses it so a held
374
+ * file alone does not start a flush on every cycle.
375
+ */
376
+ export function hasPendingSpoolWork(root) {
377
+ try {
378
+ if (listOrphanClaimFiles(root).length > 0)
379
+ return true;
380
+ }
381
+ catch {
382
+ return true;
383
+ }
384
+ return jsonlHasBytes(workMeshSpoolPath(root));
385
+ }
306
386
  function readClaimFileLines(claimPath) {
307
387
  if (!fs.existsSync(claimPath))
308
388
  return [];
@@ -151,6 +151,8 @@ export interface OpenStoreDirOptions {
151
151
  platform?: NodeJS.Platform;
152
152
  /** Where the parent check stops when the store is inside it. Defaults to os.homedir(). */
153
153
  home?: string;
154
+ /** Replaces fs.fsyncSync for file and folder syncs (tests: a real disk sync can stall for seconds on a busy runner). */
155
+ fsync?: (fd: number) => void;
154
156
  }
155
157
  export interface ReadOptions {
156
158
  /** Refuse a file larger than this. Default 1 MiB. */
@@ -224,7 +224,7 @@ export function openStoreDir(dir, options = {}) {
224
224
  return refusal("folder-link", "the store folder is a symlink or junction");
225
225
  if (!held.isDirectory())
226
226
  return refusal("not-a-folder", "the store path is not a folder");
227
- return { ok: true, value: new HeldStore(directory, undefined, held, undefined, platform, options.at) };
227
+ return { ok: true, value: new HeldStore(directory, undefined, held, undefined, platform, options.at, options.fsync) };
228
228
  }
229
229
  let folderFd;
230
230
  try {
@@ -286,7 +286,7 @@ export function openStoreDir(dir, options = {}) {
286
286
  return fail(parents);
287
287
  }
288
288
  const bound = platform === "linux" && fs.existsSync(`/proc/self/fd/${folderFd}`) ? `/proc/self/fd/${folderFd}` : undefined;
289
- return { ok: true, value: new HeldStore(directory, folderFd, held, uid, platform, options.at, bound) };
289
+ return { ok: true, value: new HeldStore(directory, folderFd, held, uid, platform, options.at, options.fsync, bound) };
290
290
  }
291
291
  catch (error) {
292
292
  return fail(ioError("checking the store folder", error));
@@ -298,16 +298,18 @@ class HeldStore {
298
298
  held;
299
299
  uid;
300
300
  at;
301
+ sync;
301
302
  /** Prefix for file paths: /proc/self/fd/<n> on Linux, else the folder path. */
302
303
  base;
303
304
  noFollow;
304
305
  closed = false;
305
- constructor(directory, folderFd, held, uid, platform, at, bound) {
306
+ constructor(directory, folderFd, held, uid, platform, at, sync, bound) {
306
307
  this.path = directory;
307
308
  this.folderFd = folderFd;
308
309
  this.held = held;
309
310
  this.uid = uid;
310
311
  this.at = at ?? (() => { });
312
+ this.sync = sync ?? fs.fsyncSync;
311
313
  this.base = bound ?? directory;
312
314
  this.noFollow = platform === "win32" ? 0 : (fs.constants.O_NOFOLLOW ?? 0);
313
315
  }
@@ -425,7 +427,7 @@ class HeldStore {
425
427
  if (this.folderFd === undefined)
426
428
  return;
427
429
  try {
428
- fs.fsyncSync(this.folderFd);
430
+ this.sync(this.folderFd);
429
431
  }
430
432
  catch {
431
433
  // not supported for folders on every filesystem
@@ -558,7 +560,7 @@ class HeldStore {
558
560
  if (afterOpen)
559
561
  return afterOpen;
560
562
  this.writeAll(fd, data);
561
- fs.fsyncSync(fd);
563
+ this.sync(fd);
562
564
  fs.closeSync(fd);
563
565
  fd = undefined;
564
566
  this.at("before-rename", "writeAtomic");
@@ -663,7 +665,7 @@ class HeldStore {
663
665
  return afterOpen;
664
666
  if (data !== undefined) {
665
667
  this.writeAll(fd, data);
666
- fs.fsyncSync(fd);
668
+ this.sync(fd);
667
669
  }
668
670
  created = undefined;
669
671
  return { ok: true, value: true };
@@ -63,6 +63,7 @@ export type QmdSpawn = (cmd: string, args: string[], options: {
63
63
  cwd?: string;
64
64
  env?: NodeJS.ProcessEnv;
65
65
  encoding: 'utf8';
66
+ maxBuffer: number;
66
67
  timeout?: number;
67
68
  /** Signal sent when `timeout` elapses (spawnSync default: SIGTERM). */
68
69
  killSignal?: NodeJS.Signals;
@@ -145,8 +146,9 @@ export declare class QmdCollectionExistsError extends QmdExitError {
145
146
  * qmd's `collection add` exited non-zero because ANOTHER collection already
146
147
  * covers exactly this path and pattern (qmd 2.5.3 prints "A collection already
147
148
  * exists for this path and pattern:" and then `Name: <other> (qmd://<other>/)`).
148
- * For unmanaged names, reconciliation skips its own add, prints a notice and
149
- * carries on. HQ-managed name collisions remain fatal and captured. Before
149
+ * For names HQ does not manage in this HQ root (the user's own collections),
150
+ * reconciliation skips its own add, prints a notice and carries on. A
151
+ * collision with a collection HQ manages here remains fatal and captured. Before
150
152
  * this, the duplicate aborted the whole `hq index sync`, so no collection was
151
153
  * ever updated again on that machine (HQ-CLI-GJ).
152
154
  */
@@ -622,6 +624,7 @@ export declare function deriveCollections(hqRoot: string): SearchCollection[];
622
624
  export type ReconcileCollectionsOptions = {
623
625
  bin?: string;
624
626
  runner?: QmdProcessRunner;
627
+ spawn?: QmdSpawn;
625
628
  /** Test seam for the default-off collection-path repair rollout. */
626
629
  repairPathDrift?: boolean;
627
630
  /** Where reconciliation notices go (default: process.stderr). */
@@ -649,7 +652,10 @@ export type ReconcileCollectionsOptions = {
649
652
  * An unmanaged path+pattern duplicate is not fatal: the files are indexed under
650
653
  * that name, but scoped search misses them. Print a notice, skip this add and
651
654
  * its `context add`, and continue. It used to abort the whole sync, so
652
- * `qmd update` never ran again on that machine (HQ-CLI-GJ).
655
+ * `qmd update` never ran again on that machine (HQ-CLI-GJ). "Unmanaged" means
656
+ * any name outside the collections derived for this HQ root, including plain
657
+ * names such as `personal` (HQ-CLI-HF, HQ-CLI-HP). A duplicate held by a
658
+ * collection HQ manages here still propagates.
653
659
  *
654
660
  * Every other qmd failure still propagates: a same-name duplicate that named a
655
661
  * different collection, a missing collection, a `context add` failure, a
@@ -113,8 +113,9 @@ export class QmdCollectionExistsError extends QmdExitError {
113
113
  * qmd's `collection add` exited non-zero because ANOTHER collection already
114
114
  * covers exactly this path and pattern (qmd 2.5.3 prints "A collection already
115
115
  * exists for this path and pattern:" and then `Name: <other> (qmd://<other>/)`).
116
- * For unmanaged names, reconciliation skips its own add, prints a notice and
117
- * carries on. HQ-managed name collisions remain fatal and captured. Before
116
+ * For names HQ does not manage in this HQ root (the user's own collections),
117
+ * reconciliation skips its own add, prints a notice and carries on. A
118
+ * collision with a collection HQ manages here remains fatal and captured. Before
118
119
  * this, the duplicate aborted the whole `hq index sync`, so no collection was
119
120
  * ever updated again on that machine (HQ-CLI-GJ).
120
121
  */
@@ -729,7 +730,7 @@ const defaultSpawn = (cmd, args, options) => {
729
730
  timeout: options.timeout,
730
731
  killSignal: options.killSignal,
731
732
  shell: options.shell,
732
- maxBuffer: QMD_SPAWN_MAX_BUFFER,
733
+ maxBuffer: options.maxBuffer,
733
734
  });
734
735
  return {
735
736
  status: result.status,
@@ -759,6 +760,7 @@ function spawnQmd(invocation, args, options = {}) {
759
760
  cwd: options.cwd,
760
761
  env,
761
762
  encoding: 'utf8',
763
+ maxBuffer: QMD_SPAWN_MAX_BUFFER,
762
764
  timeout: options.timeout,
763
765
  ...(options.killSignal ? { killSignal: options.killSignal } : {}),
764
766
  shell: plan.shell,
@@ -1130,7 +1132,22 @@ export function resolveQmdInvocation(options = {}) {
1130
1132
  if (isUsable(bundled))
1131
1133
  return bundled;
1132
1134
  if (repairEnabled(env)) {
1133
- const repair = options.repair ?? repairQmdNativeBindings;
1135
+ const launch = options.spawn;
1136
+ const repair = options.repair ?? (launch
1137
+ ? (bin) => repairQmdNativeBindings(bin, {
1138
+ env,
1139
+ platform,
1140
+ spawn: (command, args, repairOptions) => {
1141
+ const plan = planCommandSpawn(command, args, platform);
1142
+ return launch(plan.cmd, plan.args, {
1143
+ ...repairOptions,
1144
+ encoding: 'utf8',
1145
+ maxBuffer: QMD_SPAWN_MAX_BUFFER,
1146
+ shell: plan.shell,
1147
+ });
1148
+ },
1149
+ })
1150
+ : repairQmdNativeBindings);
1134
1151
  if (repair(bundledBin)) {
1135
1152
  usableQmdCache.delete(invocationKey(bundled));
1136
1153
  if (isUsable(bundled))
@@ -1737,14 +1754,17 @@ function isPreviousHqManagedPath(hqRoot, collection, configuredPath) {
1737
1754
  * An unmanaged path+pattern duplicate is not fatal: the files are indexed under
1738
1755
  * that name, but scoped search misses them. Print a notice, skip this add and
1739
1756
  * its `context add`, and continue. It used to abort the whole sync, so
1740
- * `qmd update` never ran again on that machine (HQ-CLI-GJ).
1757
+ * `qmd update` never ran again on that machine (HQ-CLI-GJ). "Unmanaged" means
1758
+ * any name outside the collections derived for this HQ root, including plain
1759
+ * names such as `personal` (HQ-CLI-HF, HQ-CLI-HP). A duplicate held by a
1760
+ * collection HQ manages here still propagates.
1741
1761
  *
1742
1762
  * Every other qmd failure still propagates: a same-name duplicate that named a
1743
1763
  * different collection, a missing collection, a `context add` failure, a
1744
1764
  * missing/unbuilt qmd binary. HQ-CLI-Q (Sentry 7670823899).
1745
1765
  */
1746
1766
  export function reconcileCollections(hqRoot, options = {}) {
1747
- const runOptions = { bin: options.bin, runner: options.runner, cwd: hqRoot };
1767
+ const runOptions = { bin: options.bin, runner: options.runner, spawn: options.spawn, cwd: hqRoot };
1748
1768
  const registered = listRegisteredCollections(hqRoot, runOptions);
1749
1769
  const expected = deriveCollections(hqRoot);
1750
1770
  const managedNames = new Set(expected.map((collection) => collection.name));
@@ -1774,10 +1794,15 @@ export function reconcileCollections(hqRoot, options = {}) {
1774
1794
  }
1775
1795
  catch (error) {
1776
1796
  if (error instanceof QmdCollectionPathTakenError) {
1777
- // Reserve the company-slug namespace, including -projects/-assets and
1778
- // personal-knowledge, even when that company's folders are absent here.
1779
- // A collision can otherwise expose one company's files under another.
1780
- if (managedNames.has(error.existingName) || isSafeQmdCollectionName(error.existingName))
1797
+ // Only a collection HQ itself manages in this HQ root stays fatal: one
1798
+ // HQ collection covering another HQ folder can expose one company's
1799
+ // files under another, and HQ owns both sides of that collision.
1800
+ // Any other name is the user's own collection, however ordinary the
1801
+ // name looks ('personal', 'drake-knowledge'). HQ does not take it over
1802
+ // or remove it; it skips this folder and syncs the rest. Treating every
1803
+ // plain name as reserved aborted the whole sync on those machines
1804
+ // (HQ-CLI-HF, HQ-CLI-HP).
1805
+ if (managedNames.has(error.existingName))
1781
1806
  throw error;
1782
1807
  // Shown once per folder and covering collection, so background syncs do
1783
1808
  // not repeat it on every run.
@@ -0,0 +1,9 @@
1
+ import { type MessagePort } from "node:worker_threads";
2
+ import type { QmdSpawn } from "./index.js";
3
+ /** The worker retains the synchronous index API without owning an unobservable child. */
4
+ export declare function qmdWorkerSpawn(port: MessagePort): QmdSpawn;
5
+ /** Keep a cancellable QMD process tree on the daemon thread until it has exited. */
6
+ export declare function serveQmdWorker(port: MessagePort, signal?: AbortSignal): {
7
+ close: () => Promise<void>;
8
+ };
9
+ //# sourceMappingURL=worker-process.d.ts.map
@@ -0,0 +1,171 @@
1
+ import { execFile, spawn } from "node:child_process";
2
+ import path from "node:path";
3
+ import { receiveMessageOnPort } from "node:worker_threads";
4
+ const CANCELLED = {
5
+ status: null,
6
+ error: { code: "ABORT_ERR", message: "The scheduled search index was stopped" },
7
+ };
8
+ /** The worker retains the synchronous index API without owning an unobservable child. */
9
+ export function qmdWorkerSpawn(port) {
10
+ return (command, args, options) => {
11
+ const ready = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT);
12
+ const signal = new Int32Array(ready);
13
+ const request = { command, args, options, ready };
14
+ port.postMessage(request);
15
+ Atomics.wait(signal, 0, 0);
16
+ const response = receiveMessageOnPort(port)?.message;
17
+ if (!response)
18
+ throw new Error("Search-index worker received no process result");
19
+ const { error, ...result } = response;
20
+ return error ? { ...result, error: Object.assign(new Error(error.message), error) } : result;
21
+ };
22
+ }
23
+ function launchQmd(request) {
24
+ const { command, args, options } = request;
25
+ const windows = process.platform === "win32";
26
+ const child = spawn(command, args, {
27
+ cwd: options.cwd,
28
+ env: options.env,
29
+ shell: options.shell,
30
+ detached: !windows,
31
+ stdio: ["ignore", "pipe", "pipe"],
32
+ windowsHide: true,
33
+ });
34
+ let escalation;
35
+ let timeout;
36
+ let stopped = false;
37
+ let failure;
38
+ let killingWindowsTree;
39
+ const kill = (signal) => {
40
+ if (child.pid === undefined)
41
+ return;
42
+ const pid = child.pid;
43
+ if (windows) {
44
+ killingWindowsTree ??= new Promise((resolve) => {
45
+ const systemRoot = process.env.SystemRoot ?? process.env.WINDIR ?? "C:\\Windows";
46
+ const taskkill = path.join(systemRoot, "System32", "taskkill.exe");
47
+ execFile(taskkill, ["/PID", String(pid), "/T", "/F"], { windowsHide: true, timeout: 1_000 }, (error) => {
48
+ if (error)
49
+ child.kill(signal);
50
+ resolve();
51
+ });
52
+ });
53
+ return;
54
+ }
55
+ try {
56
+ process.kill(-pid, signal);
57
+ }
58
+ catch (error) {
59
+ if (error.code !== "ESRCH")
60
+ child.kill(signal);
61
+ }
62
+ };
63
+ const stop = () => {
64
+ if (stopped)
65
+ return;
66
+ stopped = true;
67
+ kill("SIGTERM");
68
+ if (!windows) {
69
+ escalation = setTimeout(() => kill("SIGKILL"), 1_000);
70
+ escalation.unref();
71
+ }
72
+ };
73
+ const output = { stdout: [], stderr: [] };
74
+ let remaining = options.maxBuffer;
75
+ const collect = (stream) => (chunk) => {
76
+ if (failure)
77
+ return;
78
+ if (chunk.length > remaining) {
79
+ output[stream].push(chunk.subarray(0, remaining));
80
+ failure = { code: "ENOBUFS", message: "qmd exceeded its captured output limit" };
81
+ stop();
82
+ return;
83
+ }
84
+ output[stream].push(chunk);
85
+ remaining -= chunk.length;
86
+ };
87
+ child.stdout.on("data", collect("stdout"));
88
+ child.stderr.on("data", collect("stderr"));
89
+ child.on("error", (error) => {
90
+ failure ??= { message: error.message, code: error.code, syscall: error.syscall, path: error.path };
91
+ });
92
+ if (options.timeout && options.timeout > 0) {
93
+ timeout = setTimeout(() => {
94
+ failure ??= { code: "ETIMEDOUT", message: "qmd process timed out" };
95
+ stopped = true;
96
+ kill(options.killSignal ?? "SIGTERM");
97
+ if (!windows && !escalation) {
98
+ escalation = setTimeout(() => kill("SIGKILL"), 1_000);
99
+ escalation.unref();
100
+ }
101
+ }, options.timeout);
102
+ timeout.unref();
103
+ }
104
+ const result = new Promise((resolve) => {
105
+ child.once("close", (status, signal) => {
106
+ if (timeout)
107
+ clearTimeout(timeout);
108
+ if (escalation)
109
+ clearTimeout(escalation);
110
+ if (stopped && !windows)
111
+ kill("SIGKILL");
112
+ const timedOut = failure?.code === "ETIMEDOUT";
113
+ void Promise.resolve(killingWindowsTree).then(() => resolve({
114
+ status: timedOut ? null : status,
115
+ signal: timedOut ? options.killSignal ?? "SIGTERM" : signal,
116
+ stdout: Buffer.concat(output.stdout).toString(options.encoding),
117
+ stderr: Buffer.concat(output.stderr).toString(options.encoding),
118
+ ...(failure ? { error: failure } : {}),
119
+ }));
120
+ });
121
+ });
122
+ return { stop, result };
123
+ }
124
+ /** Keep a cancellable QMD process tree on the daemon thread until it has exited. */
125
+ export function serveQmdWorker(port, signal) {
126
+ let closing = signal?.aborted === true;
127
+ let running;
128
+ const stop = () => {
129
+ if (closing)
130
+ return;
131
+ closing = true;
132
+ running?.stop();
133
+ };
134
+ const respond = (request, response) => {
135
+ port.postMessage(response);
136
+ const ready = new Int32Array(request.ready);
137
+ Atomics.store(ready, 0, 1);
138
+ Atomics.notify(ready, 0);
139
+ };
140
+ port.on("message", (request) => {
141
+ if (closing) {
142
+ respond(request, CANCELLED);
143
+ return;
144
+ }
145
+ try {
146
+ const task = launchQmd(request);
147
+ running = task;
148
+ void task.result.then((result) => {
149
+ running = undefined;
150
+ respond(request, closing ? CANCELLED : result);
151
+ });
152
+ }
153
+ catch (error) {
154
+ const failure = error;
155
+ respond(request, {
156
+ status: null,
157
+ error: { message: failure.message, code: failure.code, syscall: failure.syscall, path: failure.path },
158
+ });
159
+ }
160
+ });
161
+ signal?.addEventListener("abort", stop, { once: true });
162
+ return {
163
+ async close() {
164
+ stop();
165
+ await running?.result;
166
+ signal?.removeEventListener("abort", stop);
167
+ port.close();
168
+ },
169
+ };
170
+ }
171
+ //# sourceMappingURL=worker-process.js.map
@@ -3,5 +3,7 @@ export type SessionCompanyLock = {
3
3
  companies: string[];
4
4
  } | undefined;
5
5
  /** Read the session's validated company scope capability or legacy metadata. */
6
- export declare function readSessionCompanyLock(env?: NodeJS.ProcessEnv): SessionCompanyLock;
6
+ export declare function readSessionCompanyLock(env?: NodeJS.ProcessEnv, { requireAllCompanies }?: {
7
+ requireAllCompanies?: boolean | undefined;
8
+ }): SessionCompanyLock;
7
9
  //# sourceMappingURL=session-company-lock.d.ts.map