@indigoai-us/hq-cli 5.345.236 → 5.345.238

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 (96) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/dist/command-catalog.generated.d.ts +1 -1
  3. package/dist/command-catalog.generated.js +1 -1
  4. package/dist/commands/bot.d.ts +2 -0
  5. package/dist/commands/bot.js +32 -0
  6. package/dist/commands/daemon.d.ts +1 -0
  7. package/dist/commands/daemon.js +70 -6
  8. package/dist/commands/deploy-app-db.js +4 -19
  9. package/dist/commands/deploy-app-upload.js +66 -40
  10. package/dist/commands/deploy-mutations.js +24 -16
  11. package/dist/commands/deploy-runtime-bindings.js +7 -26
  12. package/dist/commands/deploy-ssr.js +5 -24
  13. package/dist/commands/mesh.js +6 -2
  14. package/dist/commands/signals-run.d.ts +43 -2
  15. package/dist/commands/signals-run.js +85 -7
  16. package/dist/commands/sync-core.d.ts +7 -0
  17. package/dist/commands/sync-core.js +52 -3
  18. package/dist/lib/agent-kit/inbox-state.d.ts +2 -1
  19. package/dist/lib/agent-kit/inbox-state.js +27 -3
  20. package/dist/lib/bot/continuity.d.ts +21 -2
  21. package/dist/lib/bot/continuity.js +48 -19
  22. package/dist/lib/bot/fleet-cron.js +6 -0
  23. package/dist/lib/bot/fleet-local.d.ts +11 -1
  24. package/dist/lib/bot/fleet-local.js +21 -1
  25. package/dist/lib/bot/fleet-state.d.ts +129 -0
  26. package/dist/lib/bot/fleet-state.js +669 -0
  27. package/dist/lib/bot/promote.d.ts +32 -3
  28. package/dist/lib/bot/promote.js +188 -16
  29. package/dist/lib/bot/promotion-hold-reconcile.d.ts +56 -0
  30. package/dist/lib/bot/promotion-hold-reconcile.js +155 -0
  31. package/dist/lib/daemon/catalog.d.ts +13 -0
  32. package/dist/lib/daemon/catalog.js +32 -6
  33. package/dist/lib/daemon/lanes-reconcile-status.d.ts +0 -4
  34. package/dist/lib/daemon/lanes-reconcile-status.js +2 -12
  35. package/dist/lib/daemon/lanes-reconcile-watcher.d.ts +1 -1
  36. package/dist/lib/daemon/lanes-reconcile-watcher.js +2 -1
  37. package/dist/lib/daemon/legacy-handover.d.ts +38 -0
  38. package/dist/lib/daemon/legacy-handover.js +117 -0
  39. package/dist/lib/daemon/mesh-owner.js +2 -1
  40. package/dist/lib/daemon/run.d.ts +35 -2
  41. package/dist/lib/daemon/run.js +108 -15
  42. package/dist/lib/daemon/selfcheck.d.ts +28 -0
  43. package/dist/lib/daemon/selfcheck.js +86 -15
  44. package/dist/lib/deploy-api.d.ts +1 -1
  45. package/dist/lib/deploy-api.js +2 -1
  46. package/dist/lib/deploy-identity.d.ts +18 -0
  47. package/dist/lib/deploy-identity.js +179 -0
  48. package/dist/lib/hot-channels/alert.js +13 -6
  49. package/dist/lib/hot-channels/fleet-complete.d.ts +89 -0
  50. package/dist/lib/hot-channels/fleet-complete.js +157 -0
  51. package/dist/lib/hot-channels/run.js +2 -1
  52. package/dist/lib/hot-channels/signals-claude-login.d.ts +3 -2
  53. package/dist/lib/hot-channels/signals-claude-login.js +6 -1
  54. package/dist/lib/hot-channels/signals-pass-failure.d.ts +29 -0
  55. package/dist/lib/hot-channels/signals-pass-failure.js +36 -0
  56. package/dist/lib/hot-channels/signals-pass.d.ts +49 -2
  57. package/dist/lib/hot-channels/signals-pass.js +188 -12
  58. package/dist/lib/hot-channels/signals-runtime.d.ts +6 -3
  59. package/dist/lib/hot-channels/signals-runtime.js +11 -2
  60. package/dist/lib/lanes/reconcile-result.d.ts +5 -0
  61. package/dist/lib/lanes/reconcile-result.js +20 -2
  62. package/dist/lib/lanes/reconcile.js +12 -3
  63. package/dist/lib/mesh/live/emit.js +25 -6
  64. package/dist/lib/mesh/live/flush.js +119 -15
  65. package/dist/lib/mesh/live/reporting-privacy.d.ts +41 -0
  66. package/dist/lib/mesh/live/reporting-privacy.js +147 -1
  67. package/dist/lib/mesh/live/spool.d.ts +16 -0
  68. package/dist/lib/mesh/live/spool.js +45 -0
  69. package/dist/lib/signals/engine.d.ts +17 -3
  70. package/dist/lib/signals/engine.js +28 -9
  71. package/dist/lib/signals/failure-alert.d.ts +33 -1
  72. package/dist/lib/signals/failure-alert.js +72 -5
  73. package/dist/lib/signals/owner-notice.d.ts +94 -0
  74. package/dist/lib/signals/owner-notice.js +233 -0
  75. package/dist/lib/signals/reply.d.ts +7 -0
  76. package/dist/lib/signals/reply.js +23 -3
  77. package/dist/lib/signals/steps/adapters.d.ts +51 -2
  78. package/dist/lib/signals/steps/adapters.js +213 -7
  79. package/dist/lib/signals/steps/extract.js +18 -4
  80. package/dist/lib/signals/steps/types.d.ts +63 -1
  81. package/dist/lib/signals/steps/types.js +32 -0
  82. package/dist/lib/sync-core/engine-auth.d.ts +35 -0
  83. package/dist/lib/sync-core/engine-auth.js +96 -0
  84. package/dist/lib/sync-core/engine-home.d.ts +6 -0
  85. package/dist/lib/sync-core/engine-home.js +12 -0
  86. package/dist/lib/sync-core/rollout-state.d.ts +1 -0
  87. package/dist/lib/sync-core/rollout-state.js +3 -0
  88. package/dist/lib/vault-sync-switches.d.ts +7 -0
  89. package/dist/lib/vault-sync-switches.js +56 -0
  90. package/dist/lib/work-context/errors.d.ts +12 -0
  91. package/dist/lib/work-context/errors.js +15 -0
  92. package/dist/lib/work-context/organize.js +6 -1
  93. package/dist/lib/work-context/reconcile.js +20 -1
  94. package/dist/utils/resident-package-preload.js +34 -4
  95. package/docs/anywhere-runtime.md +6 -0
  96. package/package.json +7 -7
@@ -9,7 +9,7 @@
9
9
  * 2xx responses are accounted per eventId (accepted / duplicates / rejected).
10
10
  */
11
11
  import * as fs from "node:fs";
12
- import { eventMatchesWorkMeshCompany, hasWorkMeshCompanyBinding, workMeshSwitchDisabled } from "./reporting-privacy.js";
12
+ import { anywhereOffSince, eventDatedSince, eventMatchesWorkMeshCompany, hasWorkMeshCompanyBinding, logAnywhereOffSinceAhead, operatorAllowsHqAnywhere, workMeshSwitchDisabled, } from "./reporting-privacy.js";
13
13
  import { hqAnywhereRuntimeLocallyDisabled } from "../../anywhere-runtime-flag-key.js";
14
14
  import * as path from "node:path";
15
15
  import { readMetaCompanySlug, resolveCompany } from "../../work-context/company.js";
@@ -25,8 +25,8 @@ import { LOCAL_ONLY_FIELDS, stripLocalOnlyFields } from "./format-spool-line.js"
25
25
  import { enrichSessionEndEvent } from "./report-summary.js";
26
26
  import { createWorkLocationResolver, withWorkLocation, } from "./work-location.js";
27
27
  import { SESSION_EVENTS_BATCH_MAX, WRITABLE_CONTEXT_STATUSES, isSessionOwnerMismatch, parseSessionEventsBatchAck, SESSION_OWNER_MISMATCH, } from "./session-events-client.js";
28
- import { appendDeadLetterLine, appendDroppedReceipt, appendHeldLinesIfAbsent, appendSpoolLine, claimHeld, claimSpool, countDistinctHeldEvents, countJsonlLines, hasPendingFlushWork, recoverOrphanClaims, removeClaimFile, } from "./spool.js";
29
- import { workMeshHeldPath, workMeshRoot } from "./paths.js";
28
+ import { appendDeadLetterLine, appendRawSpoolLines, appendDroppedReceipt, appendHeldLinesIfAbsent, appendSpoolLine, claimHeld, claimSpool, countDistinctHeldEvents, countJsonlLines, forEachJsonlLine, hasPendingFlushWork, listOrphanSpoolClaims, recoverOrphanClaims, recoverOrphanSpoolClaims, removeClaimFile, } from "./spool.js";
29
+ import { workMeshHeldPath, workMeshRoot, workMeshSpoolPath } from "./paths.js";
30
30
  /** Bound a replayed session backlog so one flush cannot burst hundreds of events. */
31
31
  const SESSION_EVENTS_MAX_PER_SESSION_PER_FLUSH = 25;
32
32
  /** Never keep a flush blocked on a Retry-After value for more than five minutes. */
@@ -177,15 +177,70 @@ export async function flushSessionEvents(inputDeps) {
177
177
  const env = inputDeps.env ?? process.env;
178
178
  const nothingDone = () => ({ claimed: 0, posted: 0, held: 0, dropped: 0, deadLettered: 0,
179
179
  restored: 0, batches: 0, heldClaimed: false, heldOverflow: 0 });
180
- if (hqAnywhereRuntimeLocallyDisabled(env))
181
- return nothingDone();
182
180
  // Idle machine: with nothing spooled, held or orphaned there is nothing to
183
181
  // report, so do not ask whether reporting is allowed. The gate still runs
184
182
  // before anything is claimed or sent whenever there is something.
185
183
  if (!hasPendingFlushWork(inputDeps.workMeshRoot))
186
184
  return nothingDone();
187
- if (inputDeps.reportingAllowed && !(await inputDeps.reportingAllowed()))
188
- return nothingDone();
185
+ // HQ Anywhere switched off by the member (the environment flag, or the
186
+ // personal setting behind the gate) does not stop a session with a verified
187
+ // company binding. `boundOnly` is that mode: only such a session's spool
188
+ // events are flushed, and every other line stays exactly where it is. The
189
+ // operator's switch, from the server's flag snapshot, stops everything.
190
+ let boundOnly = false;
191
+ if (hqAnywhereRuntimeLocallyDisabled(env) || (inputDeps.reportingAllowed && !(await inputDeps.reportingAllowed()))) {
192
+ if (!operatorAllowsHqAnywhere(env))
193
+ return nothingDone();
194
+ boundOnly = true;
195
+ }
196
+ // Events stored before this machine first saw HQ Anywhere off were held
197
+ // back by the member's opt-out. While it stays off they are not sent.
198
+ const offSinceMs = boundOnly ? anywhereOffSince(inputDeps.workMeshRoot, inputDeps.now ?? (() => new Date())) : 0;
199
+ // A recorded time ahead of the clock (a wrong clock when it was written, or
200
+ // an edited file) stops every bound session's events. It is not moved back:
201
+ // that would release what was stored before it whenever a clock is set
202
+ // back. It is said in the log instead, once per process.
203
+ if (boundOnly) {
204
+ logAnywhereOffSinceAhead(inputDeps.workMeshRoot, offSinceMs, (inputDeps.now ?? (() => new Date()))().getTime(), inputDeps.log);
205
+ }
206
+ const bindings = new Map();
207
+ /**
208
+ * The event belongs to a session whose own state holds a verified company
209
+ * binding and, with HQ Anywhere off, is dated from the time it was first
210
+ * seen off.
211
+ */
212
+ const eventOfBoundSession = (event) => {
213
+ if (boundOnly && !eventDatedSince(event, offSinceMs))
214
+ return false;
215
+ const sessionId = typeof event.sessionId === "string" ? event.sessionId : "";
216
+ if (!sessionId)
217
+ return false;
218
+ let state = bindings.get(sessionId);
219
+ if (state === undefined) {
220
+ state = readSessionState(sessionId, inputDeps.workContextRoot);
221
+ bindings.set(sessionId, state);
222
+ }
223
+ return hasWorkMeshCompanyBinding(state) && eventMatchesWorkMeshCompany(event, state.companySlug);
224
+ };
225
+ // Look before claiming. With no bound session's event in the spool or in a
226
+ // claim file a crashed flush left behind, nothing is touched at all.
227
+ if (boundOnly) {
228
+ let any = false;
229
+ const look = (line) => {
230
+ if (any)
231
+ return;
232
+ const parsed = parseLine(line);
233
+ if (parsed && eventOfBoundSession(parsed))
234
+ any = true;
235
+ };
236
+ forEachJsonlLine(workMeshSpoolPath(inputDeps.workMeshRoot), look);
237
+ if (!any) {
238
+ for (const claim of listOrphanSpoolClaims(inputDeps.workMeshRoot))
239
+ forEachJsonlLine(claim, look);
240
+ }
241
+ if (!any)
242
+ return nothingDone();
243
+ }
189
244
  // One resolver per flush: git lookups are cached per cwd for this flush only.
190
245
  const deps = {
191
246
  ...inputDeps,
@@ -200,12 +255,16 @@ export async function flushSessionEvents(inputDeps) {
200
255
  const heldMaxLines = deps.heldMaxLines ?? HELD_MAX_LINES;
201
256
  const nowMs = now().getTime();
202
257
  const ts = `${nowMs}`;
203
- const orphans = recoverOrphanClaims(deps.workMeshRoot);
258
+ // Bound-only: the live spool and orphaned spool claims are read. Held lines
259
+ // and orphaned held claims wait, as they did, until HQ Anywhere is back on.
260
+ const orphans = boundOnly
261
+ ? recoverOrphanSpoolClaims(deps.workMeshRoot)
262
+ : recoverOrphanClaims(deps.workMeshRoot);
204
263
  const spoolClaim = claimSpool(deps.workMeshRoot, ts);
205
264
  // Throttle held re-attempts; spool (fresh) events still flush every cycle.
206
265
  const lastHeldRetryAtMs = deps.lastHeldRetryAtMs ?? 0;
207
- const shouldClaimHeld = heldRetryIntervalMs <= 0 ||
208
- nowMs - lastHeldRetryAtMs >= heldRetryIntervalMs;
266
+ const shouldClaimHeld = !boundOnly && (heldRetryIntervalMs <= 0 ||
267
+ nowMs - lastHeldRetryAtMs >= heldRetryIntervalMs);
209
268
  const heldClaim = shouldClaimHeld
210
269
  ? claimHeld(deps.workMeshRoot, `${ts}.held`)
211
270
  : { claimPath: null, lines: [] };
@@ -239,6 +298,12 @@ export async function flushSessionEvents(inputDeps) {
239
298
  heldClaimed: shouldClaimHeld,
240
299
  heldOverflow: 0,
241
300
  };
301
+ /**
302
+ * Bound-only: claimed lines this flush may not act on (another session's,
303
+ * dated before HQ Anywhere was first seen off, not an event at all). They
304
+ * go back on the spool byte for byte before the claim files are removed.
305
+ */
306
+ const giveBack = [];
242
307
  /** Original events still awaiting disposition (restored on throw). O(1) delete. */
243
308
  const pendingRestore = new Set();
244
309
  const collected = [];
@@ -246,6 +311,13 @@ export async function flushSessionEvents(inputDeps) {
246
311
  // Iterate sources separately — avoid building one giant combined array.
247
312
  for (const source of [orphans.lines, spoolClaim.lines, heldClaim.lines]) {
248
313
  for (const line of source) {
314
+ if (boundOnly) {
315
+ const event = parseLine(line);
316
+ if (!event || !eventOfBoundSession(event)) {
317
+ giveBack.push(line);
318
+ continue;
319
+ }
320
+ }
249
321
  summary.claimed += 1;
250
322
  const parsed = parseLine(line);
251
323
  if (!parsed) {
@@ -279,23 +351,42 @@ export async function flushSessionEvents(inputDeps) {
279
351
  }
280
352
  }
281
353
  const bySession = groupBySession(collected);
354
+ const meshDisabled = workMeshSwitchDisabled(env);
282
355
  // Older clients acknowledged register operations without copying the
283
356
  // authoritative company into the session projection. Repair those files
284
357
  // before classification so a valid receipt cannot be held as NEEDS_COMPANY.
285
- repairAckedRegisterStates(deps.workContextRoot, new Set(bySession.keys()), now);
358
+ // Where only a session with a verified company binding may post (a Work
359
+ // Mesh switch is set, or HQ Anywhere is off), the repair is for those
360
+ // sessions alone: it must not write a binding into another session's state.
361
+ const repairFor = boundOnly || meshDisabled
362
+ ? [...bySession.keys()].filter(sessionId => hasWorkMeshCompanyBinding(readSessionState(sessionId, deps.workContextRoot)))
363
+ : [...bySession.keys()];
364
+ repairAckedRegisterStates(deps.workContextRoot, new Set(repairFor), now);
286
365
  const markDisposed = (event) => {
287
366
  pendingRestore.delete(event);
288
367
  };
289
368
  const loggedProject404 = new Set();
290
369
  const heldUidCache = new Map();
291
- const meshDisabled = workMeshSwitchDisabled(env);
292
370
  sessionLoop: for (const [sessionId, sessionItems] of bySession) {
293
371
  if (deps.signal?.aborted)
294
372
  break sessionLoop;
295
373
  let state = readSessionState(sessionId, deps.workContextRoot);
374
+ // Bound-only: a session without a verified company binding is not
375
+ // touched. Its events are not sent, held or dropped and its state is
376
+ // not rebound; they go back to the spool (finally block).
377
+ if (boundOnly && !hasWorkMeshCompanyBinding(state))
378
+ continue;
296
379
  state = applySessionMetaCompanyRebind(sessionId, sessionItems, state, deps, now);
297
380
  let items = sessionItems;
298
- if (meshDisabled) {
381
+ if (boundOnly) {
382
+ const binding = state;
383
+ if (!hasWorkMeshCompanyBinding(binding))
384
+ continue;
385
+ items = sessionItems.filter(item => eventMatchesWorkMeshCompany(item.event, binding.companySlug));
386
+ if (items.length === 0)
387
+ continue;
388
+ }
389
+ else if (meshDisabled) {
299
390
  const binding = state;
300
391
  items = sessionItems.filter(item => {
301
392
  if (hasWorkMeshCompanyBinding(binding) && eventMatchesWorkMeshCompany(item.event, binding.companySlug))
@@ -499,10 +590,23 @@ export async function flushSessionEvents(inputDeps) {
499
590
  }
500
591
  }
501
592
  pendingRestore.clear();
502
- for (const p of claimPaths) {
503
- removeClaimFile(p);
593
+ let gaveBack = true;
594
+ try {
595
+ appendRawSpoolLines(giveBack, deps.workMeshRoot);
596
+ }
597
+ catch {
598
+ // The claim files still hold these lines; the next flush recovers them.
599
+ gaveBack = false;
600
+ }
601
+ if (gaveBack) {
602
+ for (const p of claimPaths) {
603
+ removeClaimFile(p);
604
+ }
504
605
  }
505
606
  }
607
+ // Bound-only: the held file is not read, so it is not trimmed either.
608
+ if (boundOnly)
609
+ return summary;
506
610
  const overflowed = trimHeldOverflow(deps.workMeshRoot, heldMaxLines, now, summary);
507
611
  if (overflowed > 0) {
508
612
  deps.log?.(`held overflow: dead-lettered ${overflowed} oldest events (cap=${heldMaxLines})`);
@@ -4,8 +4,49 @@ export declare function workMeshSwitchDisabled(env?: NodeJS.ProcessEnv): boolean
4
4
  export declare function hasWorkMeshCompanyBinding(state: SessionStateFile | null): state is SessionStateFile & {
5
5
  companyUid: string;
6
6
  };
7
+ /**
8
+ * The operator's HQ Anywhere switch, read from the server's flag snapshot
9
+ * only. A flag override in the member's own environment (`HQ_FLAG_*`) is the
10
+ * member's switch and is not consulted here. When the operator has switched
11
+ * HQ Anywhere off, nothing is sent for any session.
12
+ */
13
+ export declare function operatorAllowsHqAnywhere(env?: NodeJS.ProcessEnv): boolean;
7
14
  export declare function eventMatchesWorkMeshCompany(event: Record<string, unknown>, companySlug: string | undefined): boolean;
8
15
  export declare function hasWorkMeshEventCompanyBinding(event: Record<string, unknown>, env: NodeJS.ProcessEnv): boolean;
16
+ /** The file, in the Work Mesh root, that holds when HQ Anywhere was first seen off on this machine. */
17
+ export declare const ANYWHERE_OFF_SINCE_BASENAME = "anywhere-off-since";
18
+ /**
19
+ * Says in the log, once per process for each Work Mesh root and recorded
20
+ * time, that the time HQ Anywhere was first seen off is ahead of the clock.
21
+ * While it is, no company session's event is sent. The daemon flushes every
22
+ * few seconds, so the line is not repeated on every flush.
23
+ */
24
+ export declare function logAnywhereOffSinceAhead(workMeshRootDir: string, offSinceMs: number, nowMs: number, log?: (message: string) => void): void;
25
+ export declare function anywhereOffSince(workMeshRootDir: string, now?: () => Date): number;
26
+ /** The event is dated at or after `sinceMs`. An event with no readable date is not. */
27
+ export declare function eventDatedSince(event: Record<string, unknown>, sinceMs: number): boolean;
28
+ /**
29
+ * The most `.json` files one check reads, sidecar files beside the session
30
+ * states included. Past it the check answers "no recent company session".
31
+ */
32
+ export declare const SESSION_BINDING_SCAN_MAX = 5000;
33
+ /** A company session counts for {@link anyRecentSessionHasWorkMeshCompanyBinding} this long after its last update. */
34
+ export declare const RECENT_COMPANY_SESSION_MS: number;
35
+ /**
36
+ * Does any session on this machine have a verified company binding that was
37
+ * updated in the last 24 hours? The time is the state's own `updatedAt`, or
38
+ * the file's modification time when the state carries none that can be read.
39
+ * A time in the future does not count as recent. Reads the session state
40
+ * files under the Work Context root the environment names and under the
41
+ * default one in the home folder, so naming an empty root does not hide a
42
+ * binding. Unreadable folders and files count as no binding, and so does
43
+ * everything past {@link SESSION_BINDING_SCAN_MAX} files. The state holds no
44
+ * person, so a session of an earlier sign-in on this account counts until it
45
+ * is 24 hours old.
46
+ */
47
+ export declare function anyRecentSessionHasWorkMeshCompanyBinding(home: string, env?: NodeJS.ProcessEnv, now?: () => Date): boolean;
48
+ /** What `hq daemon disable mesh` answers on a machine with company work. */
49
+ export declare const MESH_SERVICE_REQUIRED_NOTICE: string;
9
50
  /** Legacy emit must not let the server infer a company for conversation text. */
10
51
  export declare function mayEmitConversation(event: Record<string, unknown>, env?: NodeJS.ProcessEnv): boolean;
11
52
  /** Fleet identities have no person preference; operator and local controls still apply. */
@@ -8,7 +8,9 @@ import { hqAnywhereRuntimeLocallyDisabled } from "../../anywhere-runtime-flag-ke
8
8
  import { isNonCloudCompanySlug } from "../../work-context/company-rebind.js";
9
9
  import { readMetaCompanySlug, resolveCompany } from "../../work-context/company.js";
10
10
  import { deriveRemoteOwnerSlug, deriveRepoIdentityKey } from "../../work-context/repo-remote.js";
11
- import { workContextRoot } from "../../work-context/paths.js";
11
+ import * as path from "node:path";
12
+ import { workContextRoot, workContextSessionsDir } from "../../work-context/paths.js";
13
+ import { SESSION_COMPANY_CHANGE_COMMAND } from "../../work-context/errors.js";
12
14
  import { readSessionState } from "../../work-context/state.js";
13
15
  /** Match the off controls used by the hook and handoff command. */
14
16
  export function workMeshSwitchDisabled(env = process.env) {
@@ -24,6 +26,20 @@ export function hasWorkMeshCompanyBinding(state) {
24
26
  (state.companySlug === undefined || typeof state.companySlug === "string") &&
25
27
  !isNonCloudCompanySlug(state.companySlug);
26
28
  }
29
+ /**
30
+ * The operator's HQ Anywhere switch, read from the server's flag snapshot
31
+ * only. A flag override in the member's own environment (`HQ_FLAG_*`) is the
32
+ * member's switch and is not consulted here. When the operator has switched
33
+ * HQ Anywhere off, nothing is sent for any session.
34
+ */
35
+ export function operatorAllowsHqAnywhere(env = process.env) {
36
+ const withoutOverrides = {};
37
+ for (const [key, value] of Object.entries(env)) {
38
+ if (!key.startsWith("HQ_FLAG_"))
39
+ withoutOverrides[key] = value;
40
+ }
41
+ return anywhereRuntimeEnabledFromSnapshot(withoutOverrides);
42
+ }
27
43
  export function eventMatchesWorkMeshCompany(event, companySlug) {
28
44
  const evidence = event.evidence;
29
45
  return [event.companySlug, evidence?.companySlug].every(slug => typeof slug !== "string" || !slug.trim() ||
@@ -37,6 +53,136 @@ export function hasWorkMeshEventCompanyBinding(event, env) {
37
53
  const state = readSessionState(event.sessionId, workContextRoot(undefined, env));
38
54
  return hasWorkMeshCompanyBinding(state) && eventMatchesWorkMeshCompany(event, state.companySlug);
39
55
  }
56
+ /** The file, in the Work Mesh root, that holds when HQ Anywhere was first seen off on this machine. */
57
+ export const ANYWHERE_OFF_SINCE_BASENAME = "anywhere-off-since";
58
+ /**
59
+ * When this machine first saw HQ Anywhere switched off by the member, as
60
+ * milliseconds. Recorded the first time it is asked for and never moved
61
+ * earlier: an existing readable time is returned as it is, whatever the clock
62
+ * says now. While HQ Anywhere is off, a bound session's events dated before
63
+ * this time are not sent: they were stored while the member's opt-out still
64
+ * stopped them. A record that cannot be read is replaced by now. When the time
65
+ * cannot be stored, the answer is "now", so nothing older than this call goes.
66
+ */
67
+ const offSinceAheadLogged = new Set();
68
+ /**
69
+ * Says in the log, once per process for each Work Mesh root and recorded
70
+ * time, that the time HQ Anywhere was first seen off is ahead of the clock.
71
+ * While it is, no company session's event is sent. The daemon flushes every
72
+ * few seconds, so the line is not repeated on every flush.
73
+ */
74
+ export function logAnywhereOffSinceAhead(workMeshRootDir, offSinceMs, nowMs, log) {
75
+ if (!log || !(offSinceMs > nowMs))
76
+ return;
77
+ const key = workMeshRootDir + "\n" + offSinceMs;
78
+ if (offSinceAheadLogged.has(key))
79
+ return;
80
+ offSinceAheadLogged.add(key);
81
+ log("HQ Anywhere is off and the time it was first seen off (" + new Date(offSinceMs).toISOString() + ", in " + ANYWHERE_OFF_SINCE_BASENAME
82
+ + ") is ahead of this computer's clock: company sessions' events are not sent until the clock passes it.");
83
+ }
84
+ export function anywhereOffSince(workMeshRootDir, now = () => new Date()) {
85
+ const file = path.join(workMeshRootDir, ANYWHERE_OFF_SINCE_BASENAME);
86
+ const read = () => {
87
+ try {
88
+ const at = Date.parse(fs.readFileSync(file, "utf8").trim());
89
+ return Number.isFinite(at) ? at : null;
90
+ }
91
+ catch {
92
+ return null;
93
+ }
94
+ };
95
+ const recorded = read();
96
+ if (recorded !== null)
97
+ return recorded;
98
+ const at = now();
99
+ const text = `${at.toISOString()}\n`;
100
+ try {
101
+ fs.mkdirSync(workMeshRootDir, { recursive: true, mode: 0o700 });
102
+ try {
103
+ // Created once. Another process may have created it first: its time stands.
104
+ fs.writeFileSync(file, text, { flag: "wx", mode: 0o600 });
105
+ }
106
+ catch (error) {
107
+ if (error.code !== "EEXIST")
108
+ throw error;
109
+ const theirs = read();
110
+ if (theirs !== null)
111
+ return theirs;
112
+ // There, and not a time: replace it.
113
+ const tmp = `${file}.${process.pid}.tmp`;
114
+ fs.writeFileSync(tmp, text, { mode: 0o600 });
115
+ fs.renameSync(tmp, file);
116
+ }
117
+ }
118
+ catch {
119
+ // Not stored: nothing dated before this call is sent.
120
+ }
121
+ return at.getTime();
122
+ }
123
+ /** The event is dated at or after `sinceMs`. An event with no readable date is not. */
124
+ export function eventDatedSince(event, sinceMs) {
125
+ const at = typeof event.at === "string" ? Date.parse(event.at) : Number.NaN;
126
+ return Number.isFinite(at) && at >= sinceMs;
127
+ }
128
+ /**
129
+ * The most `.json` files one check reads, sidecar files beside the session
130
+ * states included. Past it the check answers "no recent company session".
131
+ */
132
+ export const SESSION_BINDING_SCAN_MAX = 5_000;
133
+ /** A company session counts for {@link anyRecentSessionHasWorkMeshCompanyBinding} this long after its last update. */
134
+ export const RECENT_COMPANY_SESSION_MS = 24 * 60 * 60 * 1000;
135
+ /**
136
+ * Does any session on this machine have a verified company binding that was
137
+ * updated in the last 24 hours? The time is the state's own `updatedAt`, or
138
+ * the file's modification time when the state carries none that can be read.
139
+ * A time in the future does not count as recent. Reads the session state
140
+ * files under the Work Context root the environment names and under the
141
+ * default one in the home folder, so naming an empty root does not hide a
142
+ * binding. Unreadable folders and files count as no binding, and so does
143
+ * everything past {@link SESSION_BINDING_SCAN_MAX} files. The state holds no
144
+ * person, so a session of an earlier sign-in on this account counts until it
145
+ * is 24 hours old.
146
+ */
147
+ export function anyRecentSessionHasWorkMeshCompanyBinding(home, env = process.env, now = () => new Date()) {
148
+ const nowMs = now().getTime();
149
+ const roots = [...new Set([workContextRoot(home, env), workContextRoot(home, {})])];
150
+ let read = 0;
151
+ for (const root of roots) {
152
+ let names;
153
+ try {
154
+ names = fs.readdirSync(workContextSessionsDir(root));
155
+ }
156
+ catch {
157
+ continue;
158
+ }
159
+ for (const name of names) {
160
+ if (!name.endsWith(".json"))
161
+ continue;
162
+ if ((read += 1) > SESSION_BINDING_SCAN_MAX)
163
+ return false;
164
+ const sessionId = path.basename(name, ".json");
165
+ try {
166
+ const state = readSessionState(sessionId, root);
167
+ if (state?.sessionId !== sessionId || !hasWorkMeshCompanyBinding(state))
168
+ continue;
169
+ let at = Date.parse(state.updatedAt);
170
+ if (!Number.isFinite(at))
171
+ at = fs.statSync(path.join(workContextSessionsDir(root), name)).mtimeMs;
172
+ if (at <= nowMs && nowMs - at <= RECENT_COMPANY_SESSION_MS)
173
+ return true;
174
+ }
175
+ catch {
176
+ // Not a session state file.
177
+ }
178
+ }
179
+ }
180
+ return false;
181
+ }
182
+ /** What `hq daemon disable mesh` answers on a machine with company work. */
183
+ export const MESH_SERVICE_REQUIRED_NOTICE = "Work Mesh reporting of company work is required and stays on. A company session record on this computer was updated in the last 24 hours, so `hq daemon disable mesh` is not available. " +
184
+ `If a session was bound to a company by mistake, change its company to the right one or to personal: \`${SESSION_COMPANY_CHANGE_COMMAND}\`. ` +
185
+ "The command works again once no company session record has been updated for 24 hours.";
40
186
  /** Legacy emit must not let the server infer a company for conversation text. */
41
187
  export function mayEmitConversation(event, env = process.env) {
42
188
  if (event.kind !== "session_end" && typeof event.summary !== "string")
@@ -17,6 +17,12 @@ export declare function ensureSpoolFile(filePath: string): void;
17
17
  * Append one JSON line (without newline in `line`) as a single write under O_APPEND.
18
18
  */
19
19
  export declare function appendJsonlLine(filePath: string, line: string): void;
20
+ /**
21
+ * Put lines back on the spool exactly as they were read: the same bytes, one
22
+ * write per line under O_APPEND, in the order given. Nothing is parsed or
23
+ * checked; a line a flush is not allowed to act on is not its to change.
24
+ */
25
+ export declare function appendRawSpoolLines(lines: readonly string[], root?: string): void;
20
26
  export declare function appendSpoolLine(line: string, root?: string): string;
21
27
  export declare function appendHeldLine(line: string, root?: string): string;
22
28
  /** Append a deduplicated held batch under one file lock and one write. */
@@ -70,6 +76,16 @@ export declare function recoverOrphanClaims(root: string): {
70
76
  lines: string[];
71
77
  claimPaths: string[];
72
78
  };
79
+ /** Orphaned claim files of the spool only (never held claims). */
80
+ export declare function listOrphanSpoolClaims(root: string): string[];
81
+ /**
82
+ * {@link recoverOrphanClaims} for spool claims only. Used when the member has
83
+ * HQ Anywhere switched off: held lines and held claims are left where they are.
84
+ */
85
+ export declare function recoverOrphanSpoolClaims(root: string): {
86
+ lines: string[];
87
+ claimPaths: string[];
88
+ };
73
89
  export declare function removeClaimFile(claimPath: string | null): void;
74
90
  export declare function deadLetterNonEmpty(root?: string): boolean;
75
91
  /**
@@ -60,6 +60,29 @@ export function appendJsonlLine(filePath, line) {
60
60
  }
61
61
  chmodOwnerFile(filePath);
62
62
  }
63
+ /**
64
+ * Put lines back on the spool exactly as they were read: the same bytes, one
65
+ * write per line under O_APPEND, in the order given. Nothing is parsed or
66
+ * checked; a line a flush is not allowed to act on is not its to change.
67
+ */
68
+ export function appendRawSpoolLines(lines, root) {
69
+ if (lines.length === 0)
70
+ return;
71
+ const spool = workMeshSpoolPath(root ?? workMeshRoot());
72
+ ensureSpoolFile(spool);
73
+ const fd = fs.openSync(spool, fs.constants.O_APPEND | fs.constants.O_CREAT | fs.constants.O_WRONLY, 0o600);
74
+ try {
75
+ for (const line of lines) {
76
+ const buf = Buffer.from(`${line}\n`, "utf8");
77
+ const written = fs.writeSync(fd, buf, 0, buf.length);
78
+ if (written !== buf.length)
79
+ throw new SpoolWriteError(`Short write to spool (${written} of ${buf.length} bytes)`);
80
+ }
81
+ }
82
+ finally {
83
+ fs.closeSync(fd);
84
+ }
85
+ }
63
86
  export function appendSpoolLine(line, root) {
64
87
  const spool = workMeshSpoolPath(root ?? workMeshRoot());
65
88
  appendJsonlLine(spool, line);
@@ -458,6 +481,28 @@ export function recoverOrphanClaims(root) {
458
481
  }
459
482
  return { lines, claimPaths };
460
483
  }
484
+ /** Orphaned claim files of the spool only (never held claims). */
485
+ export function listOrphanSpoolClaims(root) {
486
+ try {
487
+ return listOrphanClaimFiles(root).filter((p) => path.basename(p).startsWith("spool."));
488
+ }
489
+ catch {
490
+ return [];
491
+ }
492
+ }
493
+ /**
494
+ * {@link recoverOrphanClaims} for spool claims only. Used when the member has
495
+ * HQ Anywhere switched off: held lines and held claims are left where they are.
496
+ */
497
+ export function recoverOrphanSpoolClaims(root) {
498
+ const claimPaths = listOrphanSpoolClaims(root);
499
+ const lines = [];
500
+ for (const p of claimPaths) {
501
+ for (const line of readClaimFileLines(p))
502
+ lines.push(line);
503
+ }
504
+ return { lines, claimPaths };
505
+ }
461
506
  export function removeClaimFile(claimPath) {
462
507
  if (!claimPath)
463
508
  return;
@@ -4,7 +4,7 @@ import { type LockTakeover } from "./run-lock.js";
4
4
  import { type UploadDeps } from "./steps/upload.js";
5
5
  import { type SignalsRunAlertSenders } from "./failure-alert.js";
6
6
  import { type RaiseSignalsFailureAlertsResult } from "../hot-channels/alert.js";
7
- import type { ErrorKind, HotChannelSyncFn, SignalsStep, SpawnSyncFn, StepFailure, StepName, StepStatus } from "./steps/types.js";
7
+ import type { ErrorKind, HotChannelSyncFn, SignalsPassFactory, SignalsStep, SpawnSyncFn, StepFailure, StepName, StepStatus } from "./steps/types.js";
8
8
  import type { AdapterFlagReader } from "./adapters-catalog.js";
9
9
  export declare const SIGNALS_TRIGGERS: readonly ["job", "chat", "manual", "brief"];
10
10
  export type SignalsTrigger = (typeof SIGNALS_TRIGGERS)[number];
@@ -31,6 +31,8 @@ export interface StepRecord {
31
31
  tokenLevels?: Record<string, string>;
32
32
  adapterSkips?: Record<string, string>;
33
33
  adapterOutcomes?: Record<string, string>;
34
+ /** adapters step: signals the hot-channel signals pass wrote this run. */
35
+ signalsOut?: number;
34
36
  uploaded?: {
35
37
  count: number;
36
38
  bytes: number;
@@ -84,6 +86,11 @@ export interface RunRecord {
84
86
  * writes a fresh record with false.
85
87
  */
86
88
  alreadyRanToday: boolean;
89
+ /**
90
+ * sourcesIn: sources the adapters step landed. signalsOut: signals the run
91
+ * wrote, from the extract step plus the hot-channel signals pass the
92
+ * adapters step runs over what it landed.
93
+ */
87
94
  counts: {
88
95
  sourcesIn: number;
89
96
  signalsOut: number;
@@ -93,7 +100,9 @@ export interface RunRecord {
93
100
  * PS-011 placement facts, set on every finished record this CLI writes.
94
101
  * Absent on records written before PS-011. host_id is the machine's
95
102
  * canonical host id (the id lane placement uses); engine is the runtime the
96
- * extract step ran (claude, codex, grok), null when no model turn ran;
103
+ * extract step ran (claude, codex, grok), or, when extract ran no model
104
+ * turn, the runtime the adapters step's signals pass sent documents to
105
+ * (claude, codex); null when no model turn ran;
97
106
  * account is the login that runtime used ("default" for the user's own
98
107
  * Claude or Grok login, the CLAUDE_CONFIG_DIR folder name when set, or
99
108
  * "custom" when that name holds @, / or a backslash,
@@ -166,6 +175,8 @@ export interface RunSignalsOptions {
166
175
  now?: () => Date;
167
176
  spawn?: SpawnSyncFn;
168
177
  hotChannelSync?: HotChannelSyncFn;
178
+ /** The signals pass the adapters step gives the sync. Defaults to the pass `hq sources sync` uses. */
179
+ signalsPass?: SignalsPassFactory;
169
180
  /** Adapter ids the adapters step gates and syncs. Defaults to the builtin registry. */
170
181
  registeredAdapterIds?: readonly string[];
171
182
  uploadDeps?: Partial<UploadDeps>;
@@ -198,7 +209,10 @@ export interface SignalsPlacementDeps {
198
209
  hostId?: () => string | null;
199
210
  account?: (engine: string) => string | null;
200
211
  }
201
- /** The runtime the record's extract step ran, or null when no extract turn ran. */
212
+ /**
213
+ * The runtime the record's model turns ran on: the extract step's, else the
214
+ * runtime of the adapters step's signals pass; null when no model turn ran.
215
+ */
202
216
  export declare function signalsRunEngine(record: Pick<RunRecord, "steps">, incremental: boolean): string | null;
203
217
  /** The login an engine's extract turn uses, named without paths or e-mail addresses. */
204
218
  export declare function defaultSignalsAccount(engine: string, env?: NodeJS.ProcessEnv, resolveBotName?: () => string | null): string | null;
@@ -23,6 +23,7 @@ import { extractStep, redoItemChannel } from "./steps/extract.js";
23
23
  import { uploadStep } from "./steps/upload.js";
24
24
  import { SIGNALS_RUN_ALERT_ADAPTER, raiseSignalsRunAlerts, resolveSignedInAlertPerson, } from "./failure-alert.js";
25
25
  import { signalsAlertKey, signalsAlertStatePath } from "../hot-channels/alert.js";
26
+ import { readSignalsPassDetail } from "./steps/types.js";
26
27
  import { canonicalHostIdHere } from "../lanes/run-size.js";
27
28
  import { resolveExecutiveBot } from "../bot/executive.js";
28
29
  import { botsRoot } from "../bot/paths.js";
@@ -32,16 +33,32 @@ export const STEP_ORDER = ["garden", "adapters", "extract", "garden", "upload"];
32
33
  export const RUN_RECORD_SCHEMA_VERSION = 2;
33
34
  /** A failed run with a transient error is due for a retry this long after it finished. */
34
35
  export const RETRY_DELAY_MS = 15 * 60 * 1000;
35
- /** The runtime the record's extract step ran, or null when no extract turn ran. */
36
+ /** The runtime the adapters step's signals pass sent documents to, or null when it sent none. */
37
+ function signalsPassEngine(record) {
38
+ for (const step of record.steps) {
39
+ if (step.name !== "adapters")
40
+ continue;
41
+ const pass = readSignalsPassDetail(step);
42
+ if (pass && pass.documents > 0 && pass.runtime)
43
+ return pass.runtime;
44
+ }
45
+ return null;
46
+ }
47
+ /**
48
+ * The runtime the record's model turns ran on: the extract step's, else the
49
+ * runtime of the adapters step's signals pass; null when no model turn ran.
50
+ */
36
51
  export function signalsRunEngine(record, incremental) {
37
52
  const extract = [...record.steps].reverse().find((s) => s.name === "extract" && s.status !== "skipped");
38
- if (!extract)
39
- return null;
40
- const runtime = extract.detail?.runtime;
41
- if (typeof runtime === "string" && runtime.trim() !== "")
42
- return runtime;
43
- // The incremental (single growing source) extract always runs claude.
44
- return incremental ? "claude" : null;
53
+ if (extract) {
54
+ const runtime = extract.detail?.runtime;
55
+ if (typeof runtime === "string" && runtime.trim() !== "")
56
+ return runtime;
57
+ // The incremental (single growing source) extract always runs claude.
58
+ if (incremental)
59
+ return "claude";
60
+ }
61
+ return signalsPassEngine(record);
45
62
  }
46
63
  /** The login an engine's extract turn uses, named without paths or e-mail addresses. */
47
64
  export function defaultSignalsAccount(engine, env = process.env, resolveBotName = () => resolveExecutiveBot({ root: botsRoot() })?.name ?? null) {
@@ -270,7 +287,8 @@ export function finalizeRecord(record, input) {
270
287
  }
271
288
  record.counts = {
272
289
  sourcesIn: record.steps.filter((s) => s.name === "adapters").reduce((n, s) => n + s.itemsOut, 0),
273
- signalsOut: record.steps.filter((s) => s.name === "extract").reduce((n, s) => n + s.itemsOut, 0),
290
+ signalsOut: record.steps.filter((s) => s.name === "extract").reduce((n, s) => n + s.itemsOut, 0) +
291
+ record.steps.filter((s) => s.name === "adapters").reduce((n, s) => n + (s.signalsOut ?? 0), 0),
274
292
  };
275
293
  }
276
294
  function summaryEntry(r) {
@@ -515,6 +533,7 @@ export async function runSignals(opts) {
515
533
  spawn,
516
534
  write,
517
535
  ...(opts.hotChannelSync ? { hotChannelSync: opts.hotChannelSync } : {}),
536
+ ...(opts.signalsPass ? { signalsPass: opts.signalsPass } : {}),
518
537
  ...(opts.uploadDeps ? { uploadDeps: opts.uploadDeps } : {}),
519
538
  ...(opts.isFlagOn ? { isFlagOn: opts.isFlagOn } : {}),
520
539
  ...(opts.registeredAdapterIds ? { registeredAdapterIds: opts.registeredAdapterIds } : {}),