@indigoai-us/hq-cli 5.345.225 → 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 (164) hide show
  1. package/CHANGELOG.md +174 -0
  2. package/dist/command-catalog.generated.d.ts +215 -0
  3. package/dist/command-catalog.generated.js +261 -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 +3 -3
  18. package/dist/commands/deploy-domains.js +38 -2
  19. package/dist/commands/index-cmd.d.ts +3 -1
  20. package/dist/commands/index-cmd.js +12 -0
  21. package/dist/commands/lanes-accounts.d.ts +14 -0
  22. package/dist/commands/lanes-accounts.js +119 -0
  23. package/dist/commands/lanes-checks.js +1 -1
  24. package/dist/commands/lanes-move.js +10 -0
  25. package/dist/commands/lanes-session-start.d.ts +1 -2
  26. package/dist/commands/lanes-session-start.js +9 -145
  27. package/dist/commands/lanes-shared.d.ts +3 -0
  28. package/dist/commands/lanes-shared.js +9 -0
  29. package/dist/commands/lanes.d.ts +3 -0
  30. package/dist/commands/lanes.js +231 -39
  31. package/dist/commands/link.d.ts +8 -3
  32. package/dist/commands/link.js +14 -17
  33. package/dist/commands/mcp-registration.d.ts +65 -7
  34. package/dist/commands/mcp-registration.js +289 -51
  35. package/dist/commands/mesh.d.ts +12 -0
  36. package/dist/commands/mesh.js +92 -10
  37. package/dist/commands/reindex.js +6 -0
  38. package/dist/commands/repo.d.ts +13 -0
  39. package/dist/commands/repo.js +39 -1
  40. package/dist/commands/sync-held.d.ts +22 -0
  41. package/dist/commands/sync-held.js +167 -18
  42. package/dist/commands/sync-mode.d.ts +3 -1
  43. package/dist/commands/sync-mode.js +11 -1
  44. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +4845 -2524
  45. package/dist/hq-cloud-sync-runner/package.json +1 -1
  46. package/dist/lazy-commands.js +3 -4
  47. package/dist/lib/capacity/accounts.d.ts +4 -0
  48. package/dist/lib/capacity/accounts.js +4 -0
  49. package/dist/lib/capacity/route.js +14 -0
  50. package/dist/lib/capacity/sign-in.d.ts +18 -0
  51. package/dist/lib/capacity/sign-in.js +34 -1
  52. package/dist/lib/checkpoint-ontology/entity-file.js +4 -4
  53. package/dist/lib/checkpoint-ontology/merge-copies.js +7 -11
  54. package/dist/lib/checkpoint-ontology/plan.js +2 -1
  55. package/dist/lib/core-utils/archive-old-threads.js +5 -2
  56. package/dist/lib/core-utils/session-company.d.ts +13 -1
  57. package/dist/lib/core-utils/session-company.js +75 -4
  58. package/dist/lib/core-utils/worktree-resume.d.ts +6 -0
  59. package/dist/lib/core-utils/worktree-resume.js +8 -4
  60. package/dist/lib/daemon/background-qos.d.ts +7 -0
  61. package/dist/lib/daemon/background-qos.js +13 -0
  62. package/dist/lib/daemon/catalog.d.ts +10 -0
  63. package/dist/lib/daemon/catalog.js +9 -2
  64. package/dist/lib/daemon/hook-requests-acl-suggest.d.ts +18 -0
  65. package/dist/lib/daemon/hook-requests-acl-suggest.js +245 -0
  66. package/dist/lib/daemon/hook-requests-fleet-session-start.d.ts +32 -0
  67. package/dist/lib/daemon/hook-requests-fleet-session-start.js +214 -0
  68. package/dist/lib/daemon/hook-requests-mesh-tool-writes.d.ts +44 -0
  69. package/dist/lib/daemon/hook-requests-mesh-tool-writes.js +292 -0
  70. package/dist/lib/daemon/hook-requests-mesh.d.ts +54 -0
  71. package/dist/lib/daemon/hook-requests-mesh.js +559 -0
  72. package/dist/lib/daemon/hook-requests.d.ts +417 -0
  73. package/dist/lib/daemon/hook-requests.js +1747 -0
  74. package/dist/lib/daemon/lanes-reconcile-status.d.ts +35 -0
  75. package/dist/lib/daemon/lanes-reconcile-status.js +86 -0
  76. package/dist/lib/daemon/machine-checks.d.ts +12 -2
  77. package/dist/lib/daemon/machine-checks.js +27 -10
  78. package/dist/lib/daemon/merge-sections.d.ts +24 -2
  79. package/dist/lib/daemon/merge-sections.js +58 -16
  80. package/dist/lib/daemon/ops/policy.d.ts +1 -1
  81. package/dist/lib/daemon/ops/policy.js +47 -6
  82. package/dist/lib/daemon/resolver.js +9 -2
  83. package/dist/lib/daemon/run.d.ts +11 -7
  84. package/dist/lib/daemon/run.js +195 -18
  85. package/dist/lib/daemon/search-index-worker-v1.d.ts +2 -0
  86. package/dist/lib/daemon/search-index-worker-v1.js +25 -0
  87. package/dist/lib/daemon/server.js +6 -1
  88. package/dist/lib/daemon/session-registry.d.ts +0 -1
  89. package/dist/lib/daemon/session-registry.js +0 -3
  90. package/dist/lib/daemon/supervisor.d.ts +5 -1
  91. package/dist/lib/daemon/supervisor.js +1 -1
  92. package/dist/lib/daemon/tcc-eperm.d.ts +59 -4
  93. package/dist/lib/daemon/tcc-eperm.js +110 -8
  94. package/dist/lib/doctor/fix/process-identity.d.ts +20 -2
  95. package/dist/lib/doctor/fix/process-identity.js +48 -5
  96. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  97. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  98. package/dist/lib/hook-engine/canary-gate.js +1 -0
  99. package/dist/lib/hook-engine/native-stop-compatibility.json +2 -1
  100. package/dist/lib/hot-channels/adapters/attio.js +2 -1
  101. package/dist/lib/hot-channels/adapters/meetings.js +2 -1
  102. package/dist/lib/lanes/account-company.d.ts +7 -1
  103. package/dist/lib/lanes/account-company.js +22 -4
  104. package/dist/lib/lanes/account-ownership.d.ts +65 -0
  105. package/dist/lib/lanes/account-ownership.js +134 -0
  106. package/dist/lib/lanes/accounts.js +9 -2
  107. package/dist/lib/lanes/claude-balance.js +9 -3
  108. package/dist/lib/lanes/company-outposts.d.ts +37 -0
  109. package/dist/lib/lanes/company-outposts.js +164 -0
  110. package/dist/lib/lanes/config.js +17 -0
  111. package/dist/lib/lanes/host-capacity.d.ts +19 -0
  112. package/dist/lib/lanes/host-capacity.js +37 -0
  113. package/dist/lib/lanes/liveness.d.ts +6 -0
  114. package/dist/lib/lanes/liveness.js +49 -8
  115. package/dist/lib/lanes/orphan-report.d.ts +15 -0
  116. package/dist/lib/lanes/orphan-report.js +223 -0
  117. package/dist/lib/lanes/orphan-sweep.d.ts +26 -0
  118. package/dist/lib/lanes/orphan-sweep.js +152 -0
  119. package/dist/lib/lanes/reaper.d.ts +2 -0
  120. package/dist/lib/lanes/reaper.js +11 -8
  121. package/dist/lib/lanes/reconcile.d.ts +8 -7
  122. package/dist/lib/lanes/reconcile.js +83 -3
  123. package/dist/lib/lanes/spawn.d.ts +0 -10
  124. package/dist/lib/lanes/spawn.js +51 -1
  125. package/dist/lib/lanes/types.d.ts +12 -0
  126. package/dist/lib/mesh/live/backfill-held.d.ts +13 -0
  127. package/dist/lib/mesh/live/backfill-held.js +23 -0
  128. package/dist/lib/mesh/live/daemon/mode.d.ts +8 -4
  129. package/dist/lib/mesh/live/daemon/mode.js +8 -4
  130. package/dist/lib/mesh/live/daemon/run.d.ts +14 -3
  131. package/dist/lib/mesh/live/daemon/run.js +116 -7
  132. package/dist/lib/mesh/live/direct-drain.d.ts +123 -0
  133. package/dist/lib/mesh/live/direct-drain.js +315 -0
  134. package/dist/lib/mesh/live/emit-replay.d.ts +10 -0
  135. package/dist/lib/mesh/live/emit-replay.js +10 -0
  136. package/dist/lib/mesh/live/flush.d.ts +15 -0
  137. package/dist/lib/mesh/live/flush.js +27 -0
  138. package/dist/lib/mesh/live/liveness-carry.d.ts +45 -0
  139. package/dist/lib/mesh/live/liveness-carry.js +141 -0
  140. package/dist/lib/mesh/live/spool.d.ts +19 -0
  141. package/dist/lib/mesh/live/spool.js +80 -0
  142. package/dist/lib/safe-store.d.ts +2 -0
  143. package/dist/lib/safe-store.js +8 -6
  144. package/dist/lib/search-index/index.d.ts +9 -3
  145. package/dist/lib/search-index/index.js +35 -10
  146. package/dist/lib/search-index/worker-process.d.ts +9 -0
  147. package/dist/lib/search-index/worker-process.js +171 -0
  148. package/dist/lib/session-company-lock.d.ts +3 -1
  149. package/dist/lib/session-company-lock.js +3 -2
  150. package/dist/utils/delegate-command-supervisor.d.ts +3 -0
  151. package/dist/utils/delegate-command-supervisor.js +44 -0
  152. package/dist/utils/delegate-lock.d.ts +12 -0
  153. package/dist/utils/delegate-lock.js +88 -0
  154. package/dist/utils/frontmatter.d.ts +27 -0
  155. package/dist/utils/frontmatter.js +33 -0
  156. package/dist/utils/hook-trust.d.ts +1 -0
  157. package/dist/utils/hook-trust.js +18 -2
  158. package/dist/utils/host-registration.d.ts +13 -1
  159. package/dist/utils/host-registration.js +98 -5
  160. package/dist/utils/package-use-lease.d.ts +1 -1
  161. package/dist/utils/package-use-lease.js +15 -7
  162. package/docs/anywhere-runtime.md +17 -0
  163. package/package.json +9 -8
  164. package/scripts/check-function-manifest.mjs +17 -3
@@ -211,6 +211,17 @@ export async function flushSessionEvents(inputDeps) {
211
211
  if (shouldClaimHeld) {
212
212
  deps.onHeldClaimed?.(nowMs);
213
213
  }
214
+ if (deps.onSpoolLinesClaimed) {
215
+ try {
216
+ if (orphans.lines.length > 0)
217
+ deps.onSpoolLinesClaimed(orphans.lines);
218
+ if (spoolClaim.lines.length > 0)
219
+ deps.onSpoolLinesClaimed(spoolClaim.lines);
220
+ }
221
+ catch (err) {
222
+ deps.log?.(`spool claim observer failed: ${(err instanceof Error ? err.message : String(err)).slice(0, 120)}`);
223
+ }
224
+ }
214
225
  const claimPaths = [
215
226
  ...orphans.claimPaths,
216
227
  spoolClaim.claimPath,
@@ -688,6 +699,10 @@ const SESSION_EVENT_HARNESSES = new Set([
688
699
  function resolveHeldCompany(sessionId, items, state, deps) {
689
700
  if (state?.companyUid)
690
701
  return null;
702
+ if (deps.companyEvidence === "own_session") {
703
+ const slug = ownSessionCompanySlug(state);
704
+ return slug ? { slug, source: "trusted_explicit" } : null;
705
+ }
691
706
  const sample = items[0]?.event;
692
707
  if (!sample)
693
708
  return null;
@@ -722,6 +737,18 @@ function resolveHeldCompany(sessionId, items, state, deps) {
722
737
  }
723
738
  return resolution.company;
724
739
  }
740
+ /**
741
+ * The only company evidence the direct-mode drain accepts for a session whose
742
+ * state has no companyUid: the slug in that session's own state file. A slug
743
+ * on a spool line is not used, not even on the session's own session_start
744
+ * line: what a hook or the CLI writes there can come from a machine binding.
745
+ * No slug in the state means no answer, and the session is held.
746
+ */
747
+ function ownSessionCompanySlug(state) {
748
+ if (state?.companyConfidence === "device_default")
749
+ return null;
750
+ return state?.companySlug?.trim().toLowerCase() || null;
751
+ }
725
752
  function writeHeldCompanyBinding(sessionId, state, company, deps, now) {
726
753
  const { uid, slug } = company;
727
754
  const nowIso = now().toISOString();
@@ -0,0 +1,45 @@
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
+ export declare const LIVENESS_CARRY_BASENAME = "liveness-carry.json";
14
+ /** Well past the lanes "lost" window (12 h by default). */
15
+ export declare const LIVENESS_CARRY_RETENTION_MS: number;
16
+ export interface LivenessCarryEntry {
17
+ sessionId: string;
18
+ lastKind: string;
19
+ lastAt: string;
20
+ lastSeq?: number;
21
+ }
22
+ export interface LivenessCarryFile {
23
+ v: 1;
24
+ updatedAt: string;
25
+ sessions: Record<string, LivenessCarryEntry>;
26
+ }
27
+ export declare function livenessCarryPath(root?: string): string;
28
+ /** Parse the carry file's text. Null when it is not a carry file. */
29
+ export declare function parseLivenessCarry(raw: string): LivenessCarryFile | null;
30
+ export declare function readLivenessCarry(root?: string): LivenessCarryFile | null;
31
+ /**
32
+ * True when `next` replaces `prior` as a session's last event: a later time,
33
+ * or the same time without a lower sequence number. Same rule lanes applies
34
+ * to spool lines.
35
+ */
36
+ export declare function supersedesLivenessEntry(prior: Pick<LivenessCarryEntry, "lastAt" | "lastSeq"> | undefined, next: Pick<LivenessCarryEntry, "lastAt" | "lastSeq">): boolean;
37
+ /** Fold one spool line (raw event or held envelope) into `sessions`. */
38
+ export declare function ingestLivenessLine(line: string, sessions: Record<string, LivenessCarryEntry>): void;
39
+ /**
40
+ * Fold lines into the carry file. `feed` is handed an `ingest` function and
41
+ * calls it once per line, so a caller can stream a large file. Prunes entries
42
+ * past the retention and writes with a rename. Returns the session count kept.
43
+ */
44
+ export declare function updateLivenessCarry(root: string, feed: (ingest: (line: string) => void) => void, now?: () => Date): number;
45
+ //# sourceMappingURL=liveness-carry.d.ts.map
@@ -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