@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
@@ -40,12 +40,15 @@ import { hasCliVersionDrift, readInstalledCliVersion } from "./version-drift.js"
40
40
  import { resolveRunningCliEntry } from "./install.js";
41
41
  import { readDaemonConfig } from "./config.js";
42
42
  import { retireLegacyListen } from "./legacy-listen.js";
43
+ import { runDirectDrainCycle } from "../direct-drain.js";
43
44
  import { startWorkCacheSubscriber } from "./work-subscribe.js";
44
45
  import { createOwnerChannelScope } from "./owner-inbox-push.js";
45
46
  import { vaultApiFetch } from "../../../../utils/vault-api.js";
46
47
  import { capacityRoot } from "../../../capacity/ledger.js";
47
48
  import { startCapacityScheduler, } from "../../../capacity/scheduler.js";
48
49
  export const SPOOL_DEBOUNCE_MS = 2_000;
50
+ /** Direct mode: wait after daemon start before the first spool drain cycle. */
51
+ export const DIRECT_DRAIN_START_DELAY_MS = 1_000;
49
52
  export const FLUSH_INTERVAL_MS = 10_000;
50
53
  /** Keep startup recovery bounded: the next daemon start continues the backlog. */
51
54
  export const HELD_BACKFILL_STARTUP_BATCH_SIZE = 100;
@@ -59,6 +62,17 @@ export const DEVICE_DEFAULT_MEMBERSHIP_TIMEOUT_MS = 2_000;
59
62
  /** Skip further membership probes after a transport failure so a network drop
60
63
  * cannot fan out one hanging lookup per held session. */
61
64
  export const DEVICE_DEFAULT_MEMBERSHIP_UNAVAILABLE_COOLDOWN_MS = 30_000;
65
+ /** Direct mode: longest wait between drain cycles after repeated failures. */
66
+ export const DIRECT_DRAIN_MAX_DELAY_MS = 5 * 60 * 1_000;
67
+ /**
68
+ * Wait before the next direct-mode drain cycle. FLUSH_INTERVAL_MS while cycles
69
+ * succeed; doubled for each cycle in a row that failed or delivered nothing
70
+ * it tried to send, up to DIRECT_DRAIN_MAX_DELAY_MS.
71
+ */
72
+ export function directDrainDelayMs(consecutiveFailures) {
73
+ const doublings = Math.min(Math.max(consecutiveFailures, 0), 10);
74
+ return Math.min(FLUSH_INTERVAL_MS * 2 ** doublings, DIRECT_DRAIN_MAX_DELAY_MS);
75
+ }
62
76
  /** Three sequential async shutdown steps must finish within six seconds. */
63
77
  export const SHUTDOWN_STEP_TIMEOUT_MS = 2_000;
64
78
  /** Non-zero exit reserved for CLI version drift so legacy Restart=on-failure units restart. */
@@ -376,6 +390,34 @@ export async function runMeshDaemon(deps = {}) {
376
390
  // One gate for the daemon's lifetime: the person setting is read from the
377
391
  // server once and on change, not on every flush.
378
392
  const reportingAllowed = deps.reportingAllowed ?? createReportingGate(machineIdentity, env, { home });
393
+ // Held sessions whose local evidence only names a slug need the membership
394
+ // slug -> uid lookup, or they stay NEEDS_COMPANY forever.
395
+ const resolveCompanyUid = async (slug) => {
396
+ const authorization = await tenantGate.authorize({ companySlug: slug, deviceDefault: false });
397
+ return authorization.status === "authorized" ? authorization.uid : null;
398
+ };
399
+ /**
400
+ * Flush deps for the direct-mode drain. No device-default authorization is
401
+ * passed, and runDirectDrainCycle narrows company evidence further.
402
+ */
403
+ const directFlushDeps = async () => {
404
+ const t = await getToken();
405
+ return {
406
+ env,
407
+ reportingAllowed,
408
+ workMeshRoot: meshRoot,
409
+ workContextRoot: ctxRoot,
410
+ poster: deps.poster ?? createSessionEventsPoster({ token: t, baseUrl: resolveVaultApiBase(env) }),
411
+ signal: shutdownController.signal,
412
+ heldRetryIntervalMs: HELD_RETRY_INTERVAL_MS,
413
+ lastHeldRetryAtMs,
414
+ onHeldClaimed: (atMs) => {
415
+ lastHeldRetryAtMs = atMs;
416
+ },
417
+ log: (message) => log(dir, message),
418
+ resolveCompanyUid,
419
+ };
420
+ };
379
421
  const flushFn = deps.flush ??
380
422
  (async (signal) => {
381
423
  const t = await getToken();
@@ -407,12 +449,7 @@ export async function runMeshDaemon(deps = {}) {
407
449
  return "unavailable";
408
450
  return authorization.status === "authorized";
409
451
  },
410
- // Held sessions whose local evidence only names a slug need the
411
- // membership slug -> uid lookup, or they stay NEEDS_COMPANY forever.
412
- resolveCompanyUid: async (slug) => {
413
- const authorization = await tenantGate.authorize({ companySlug: slug, deviceDefault: false });
414
- return authorization.status === "authorized" ? authorization.uid : null;
415
- },
452
+ resolveCompanyUid,
416
453
  });
417
454
  });
418
455
  const replayFn = deps.replayOutbox ??
@@ -866,6 +903,66 @@ export async function runMeshDaemon(deps = {}) {
866
903
  });
867
904
  }, FLUSH_INTERVAL_MS);
868
905
  }
906
+ // Direct mode: the hooks still append session and turn events to the spool,
907
+ // so deliver them on a timer (US-038, owner decision 70). No directory
908
+ // watcher: a failed post puts lines back on the spool, and a watcher would
909
+ // turn that into a retry every two seconds.
910
+ let directDrainHandle = null;
911
+ let directDrainInFlight = null;
912
+ let directDrainFailures = 0;
913
+ const runDirectDrain = async () => {
914
+ try {
915
+ const atMs = now().getTime();
916
+ const result = await runDirectDrainCycle({
917
+ workMeshRoot: meshRoot,
918
+ flushDeps: directFlushDeps,
919
+ flush: deps.flush ? () => deps.flush(shutdownController.signal) : undefined,
920
+ heldRetryDue: atMs - lastHeldRetryAtMs >= HELD_RETRY_INTERVAL_MS,
921
+ now,
922
+ log: (message) => log(dir, message),
923
+ });
924
+ const summary = result.summary;
925
+ if (!summary) {
926
+ directDrainFailures = 0;
927
+ return;
928
+ }
929
+ patchDaemonState(dir, { lastFlushAt: now().toISOString(), lastFlushResult: { ...summary, ok: true } }, now);
930
+ if (summary.claimed > 0) {
931
+ log(dir, `drain(direct): claimed=${summary.claimed} posted=${summary.posted} held=${summary.held} dropped=${summary.dropped} deadLettered=${summary.deadLettered} restored=${summary.restored}`);
932
+ }
933
+ // Lines went back on the spool and nothing was delivered: the server is
934
+ // unreachable or refusing for now. Wait longer before the next cycle.
935
+ directDrainFailures = summary.restored > 0 && summary.posted === 0
936
+ ? directDrainFailures + 1
937
+ : 0;
938
+ }
939
+ catch (err) {
940
+ directDrainFailures += 1;
941
+ const msg = err instanceof Error ? err.message : String(err);
942
+ try {
943
+ patchDaemonState(dir, { lastErrorCode: msg.slice(0, 120) }, now);
944
+ }
945
+ catch {
946
+ /* the log line below still records it */
947
+ }
948
+ log(dir, `drain(direct) error: ${msg.slice(0, 200)}`);
949
+ }
950
+ };
951
+ const scheduleDirectDrain = (delayMs) => {
952
+ directDrainHandle = timers.setTimeout(() => {
953
+ directDrainHandle = null;
954
+ if (stopped || restartRequested || directDrainInFlight)
955
+ return;
956
+ directDrainInFlight = runDirectDrain().finally(() => {
957
+ directDrainInFlight = null;
958
+ if (stopped || restartRequested)
959
+ return;
960
+ scheduleDirectDrain(directDrainDelayMs(directDrainFailures));
961
+ });
962
+ }, delayMs);
963
+ };
964
+ if (!emitPath)
965
+ scheduleDirectDrain(DIRECT_DRAIN_START_DELAY_MS);
869
966
  boardIntervalHandle = timers.setTimeout(function boardTick() {
870
967
  if (stopped)
871
968
  return;
@@ -958,6 +1055,8 @@ export async function runMeshDaemon(deps = {}) {
958
1055
  timers.clearTimeout(debounceHandle);
959
1056
  if (flushIntervalHandle !== null)
960
1057
  timers.clearTimeout(flushIntervalHandle);
1058
+ if (directDrainHandle !== null)
1059
+ timers.clearTimeout(directDrainHandle);
961
1060
  if (versionIntervalHandle !== null)
962
1061
  timers.clearTimeout(versionIntervalHandle);
963
1062
  if (boardIntervalHandle !== null)
@@ -996,7 +1095,17 @@ export async function runMeshDaemon(deps = {}) {
996
1095
  };
997
1096
  // Final flush, then clean MQTT DISCONNECT so the broker emits the
998
1097
  // lifecycle event; offline is published server-side only.
999
- await stopStep("shutdown flush", () => doFlushCycle("shutdown", { force: true }));
1098
+ // Legacy only. The shutdown flush runs with the shutdown signal already
1099
+ // aborted, so it can deliver nothing: it claims the whole spool and writes
1100
+ // every line back. In direct mode the drain timer delivers instead, and a
1101
+ // cycle that is mid-post gets the same bounded wait to put its lines back.
1102
+ if (emitPath) {
1103
+ await stopStep("shutdown flush", () => doFlushCycle("shutdown", { force: true }));
1104
+ }
1105
+ else if (directDrainInFlight) {
1106
+ const inFlight = directDrainInFlight;
1107
+ await stopStep("direct drain", () => inFlight);
1108
+ }
1000
1109
  if (workCache) {
1001
1110
  await stopStep("work cache stop", () => workCache.stop());
1002
1111
  }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Spool delivery for emit mode "direct" (US-038, owner decision 70).
3
+ *
4
+ * In direct mode the hooks still append session and turn events to
5
+ * spool.jsonl, and until this module nothing posted them. One cycle:
6
+ *
7
+ * 1. First run on this machine (no direct-drain.json): everything already
8
+ * queued (spool.jsonl, held.jsonl, leftover *.claimed files) is moved,
9
+ * unread by any poster and byte for byte, into pre-drain-backlog/<ms>/,
10
+ * then the marker is written. Nothing is posted in that cycle. The
11
+ * renames come first: if the process dies between them and the marker,
12
+ * the next start sets aside again instead of posting.
13
+ * 2. Cap the spool, so it stays bounded while the server cannot be reached.
14
+ * 3. Run the shared flush (claim by rename, post per session, remove what
15
+ * was delivered) with the direct-mode restrictions in directFlushDeps.
16
+ * 4. Cap the dead-letter lines written since the first run.
17
+ *
18
+ * Not done here on purpose: outbox replay and held backfill. Both would send
19
+ * work queued before the first run.
20
+ */
21
+ import type { MeshEmitMode } from "./daemon/mode.js";
22
+ import { type FlushDeps, type FlushSummary } from "./flush.js";
23
+ export declare const DIRECT_DRAIN_MARKER_BASENAME = "direct-drain.json";
24
+ export declare const PRE_DRAIN_BACKLOG_DIRNAME = "pre-drain-backlog";
25
+ /** Lines kept in spool.jsonl while nothing can be delivered. */
26
+ export declare const DIRECT_SPOOL_MAX_LINES = 20000;
27
+ /** Dead-letter lines written since the first run that are kept. */
28
+ export declare const DIRECT_DEAD_LETTER_MAX_LINES = 5000;
29
+ export interface DirectDrainMarker {
30
+ v: 1;
31
+ /** When the drain first ran here. Events queued before it are never posted. */
32
+ firstRunAt: string;
33
+ /** File names moved aside on the first run. */
34
+ setAside: string[];
35
+ /** Where they went; absent when nothing was queued. */
36
+ backlogDir?: string;
37
+ }
38
+ export declare function directDrainMarkerPath(root: string): string;
39
+ /** The marker, or null when it is absent or not a valid marker. */
40
+ export declare function readDirectDrainMarker(root: string): DirectDrainMarker | null;
41
+ export interface DirectDrainStart {
42
+ firstRun: boolean;
43
+ marker: DirectDrainMarker;
44
+ }
45
+ /**
46
+ * Establish the start point. With a valid marker this does nothing. Without
47
+ * one it moves every queued file aside and writes the marker. Throws when a
48
+ * file cannot be moved or the marker cannot be written; the caller must not
49
+ * flush in that case.
50
+ */
51
+ export declare function ensureDirectDrainStart(root: string, now?: () => Date, log?: (message: string) => void): DirectDrainStart;
52
+ /**
53
+ * Keep spool.jsonl bounded when lines cannot be delivered (offline, signed
54
+ * out, reporting off). Over `maxLines`, the spool is claimed by rename (the
55
+ * same claim the flush uses, so a hook appending meanwhile writes a fresh
56
+ * file and a crash leaves an orphan claim the next flush recovers), the newest
57
+ * three quarters are appended back, and the rest are discarded with one
58
+ * dropped receipt. Returns the number discarded.
59
+ */
60
+ export declare function capSpool(root: string, opts: {
61
+ maxLines: number;
62
+ now?: () => Date;
63
+ log?: (message: string) => void;
64
+ }): number;
65
+ /**
66
+ * The flush deps the direct-mode drain runs with, whatever the caller passed:
67
+ * - a company comes only from the session's own state file
68
+ * (companyEvidence "own_session");
69
+ * - a device-default company is never authorized, so such a session is held;
70
+ * - session liveness is copied before a claimed line can be removed.
71
+ */
72
+ export declare function directFlushDeps(base: FlushDeps, now?: () => Date): FlushDeps;
73
+ export interface DirectDrainDeps {
74
+ workMeshRoot: string;
75
+ /** Built only when there is something to flush (it may fetch a token). */
76
+ flushDeps: () => Promise<FlushDeps>;
77
+ /** Replaces flushSessionEvents (daemon tests). Still receives the restricted deps. */
78
+ flush?: (deps: FlushDeps) => Promise<FlushSummary>;
79
+ /** False while the held file was retried recently; held alone then starts no flush. */
80
+ heldRetryDue?: boolean;
81
+ now?: () => Date;
82
+ log?: (message: string) => void;
83
+ spoolMaxLines?: number;
84
+ deadLetterMaxLines?: number;
85
+ }
86
+ export interface DirectDrainResult {
87
+ /** True for the cycle that wrote the marker. That cycle posts nothing. */
88
+ firstRun: boolean;
89
+ /** File names moved aside in this cycle (first run only). */
90
+ setAside: string[];
91
+ /** Null when the cycle had nothing to flush. */
92
+ summary: FlushSummary | null;
93
+ spoolDiscarded: number;
94
+ deadLetterDiscarded: number;
95
+ }
96
+ export declare function runDirectDrainCycle(deps: DirectDrainDeps): Promise<DirectDrainResult>;
97
+ export interface ModeFlushResult {
98
+ summary: FlushSummary;
99
+ /** Direct mode only: this call was the machine's first run and posted nothing. */
100
+ firstRun: boolean;
101
+ /** Direct mode only: file names moved aside by this call. */
102
+ setAside: string[];
103
+ }
104
+ /**
105
+ * One flush for a caller outside the daemon (`hq mesh session flush`). Legacy
106
+ * mode runs the shared flush as before. Direct mode runs one drain cycle, so
107
+ * the manual command obeys the same first-run rule and the same company rule
108
+ * as the daemon: on a machine whose drain has not run yet it sets the queue
109
+ * aside and posts nothing.
110
+ */
111
+ export declare function flushForEmitMode(mode: MeshEmitMode, deps: FlushDeps): Promise<ModeFlushResult>;
112
+ /**
113
+ * For a manual command that reads the spool or the held file and can post
114
+ * from them. In direct mode it establishes the drain's start point first, so
115
+ * a queue that predates the first run is set aside before the command reads
116
+ * anything. Legacy mode: nothing happens. Throws when the queue cannot be set
117
+ * aside; the caller must not go on to read or post.
118
+ */
119
+ export declare function ensureDrainStartForMode(mode: MeshEmitMode, root: string, now?: () => Date): {
120
+ firstRun: boolean;
121
+ setAside: string[];
122
+ };
123
+ //# sourceMappingURL=direct-drain.d.ts.map
@@ -0,0 +1,315 @@
1
+ /**
2
+ * Spool delivery for emit mode "direct" (US-038, owner decision 70).
3
+ *
4
+ * In direct mode the hooks still append session and turn events to
5
+ * spool.jsonl, and until this module nothing posted them. One cycle:
6
+ *
7
+ * 1. First run on this machine (no direct-drain.json): everything already
8
+ * queued (spool.jsonl, held.jsonl, leftover *.claimed files) is moved,
9
+ * unread by any poster and byte for byte, into pre-drain-backlog/<ms>/,
10
+ * then the marker is written. Nothing is posted in that cycle. The
11
+ * renames come first: if the process dies between them and the marker,
12
+ * the next start sets aside again instead of posting.
13
+ * 2. Cap the spool, so it stays bounded while the server cannot be reached.
14
+ * 3. Run the shared flush (claim by rename, post per session, remove what
15
+ * was delivered) with the direct-mode restrictions in directFlushDeps.
16
+ * 4. Cap the dead-letter lines written since the first run.
17
+ *
18
+ * Not done here on purpose: outbox replay and held backfill. Both would send
19
+ * work queued before the first run.
20
+ */
21
+ import * as fs from "node:fs";
22
+ import * as path from "node:path";
23
+ import { ensureOwnerDir } from "../../work-context/atomic.js";
24
+ import { flushSessionEvents } from "./flush.js";
25
+ import { updateLivenessCarry } from "./liveness-carry.js";
26
+ import { workMeshClaimPath, workMeshSpoolPath } from "./paths.js";
27
+ import { appendDroppedReceipt, appendJsonlLine, forEachJsonlLine, hasPendingFlushWork, hasPendingSpoolWork, removeClaimFile, trimDeadLetter, } from "./spool.js";
28
+ export const DIRECT_DRAIN_MARKER_BASENAME = "direct-drain.json";
29
+ export const PRE_DRAIN_BACKLOG_DIRNAME = "pre-drain-backlog";
30
+ /** Lines kept in spool.jsonl while nothing can be delivered. */
31
+ export const DIRECT_SPOOL_MAX_LINES = 20_000;
32
+ /** Dead-letter lines written since the first run that are kept. */
33
+ export const DIRECT_DEAD_LETTER_MAX_LINES = 5_000;
34
+ /** A spool line is far longer than this, so a smaller file is under the cap. */
35
+ const MIN_SPOOL_LINE_BYTES = 64;
36
+ /** Queue files that exist before the first run: the live files and any claim. */
37
+ const PRE_EXISTING_QUEUE_RE = /^(spool\.jsonl|held\.jsonl|(spool|held)\..+\.claimed)$/;
38
+ export function directDrainMarkerPath(root) {
39
+ return path.join(root, DIRECT_DRAIN_MARKER_BASENAME);
40
+ }
41
+ /** The marker, or null when it is absent or not a valid marker. */
42
+ export function readDirectDrainMarker(root) {
43
+ try {
44
+ const parsed = JSON.parse(fs.readFileSync(directDrainMarkerPath(root), "utf8"));
45
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
46
+ return null;
47
+ const rec = parsed;
48
+ if (rec.v !== 1 || typeof rec.firstRunAt !== "string")
49
+ return null;
50
+ if (!Number.isFinite(Date.parse(rec.firstRunAt)))
51
+ return null;
52
+ return {
53
+ v: 1,
54
+ firstRunAt: rec.firstRunAt,
55
+ setAside: Array.isArray(rec.setAside)
56
+ ? rec.setAside.filter((name) => typeof name === "string")
57
+ : [],
58
+ ...(typeof rec.backlogDir === "string" ? { backlogDir: rec.backlogDir } : {}),
59
+ };
60
+ }
61
+ catch {
62
+ return null;
63
+ }
64
+ }
65
+ /**
66
+ * Establish the start point. With a valid marker this does nothing. Without
67
+ * one it moves every queued file aside and writes the marker. Throws when a
68
+ * file cannot be moved or the marker cannot be written; the caller must not
69
+ * flush in that case.
70
+ */
71
+ export function ensureDirectDrainStart(root, now = () => new Date(), log) {
72
+ const existing = readDirectDrainMarker(root);
73
+ if (existing)
74
+ return { firstRun: false, marker: existing };
75
+ const dir = ensureOwnerDir(root);
76
+ const at = now();
77
+ const queued = fs.readdirSync(dir)
78
+ .filter((name) => PRE_EXISTING_QUEUE_RE.test(name))
79
+ .filter((name) => {
80
+ try {
81
+ return fs.statSync(path.join(dir, name)).size > 0;
82
+ }
83
+ catch (err) {
84
+ if (err.code === "ENOENT")
85
+ return false;
86
+ throw err;
87
+ }
88
+ })
89
+ .sort();
90
+ const setAside = [];
91
+ let backlogDir;
92
+ if (queued.length > 0) {
93
+ // Read-only pass so `hq lanes` still knows each session's last event.
94
+ // Only kind, time and sequence number are copied; nothing is posted.
95
+ try {
96
+ updateLivenessCarry(dir, (ingest) => {
97
+ for (const name of queued)
98
+ forEachJsonlLine(path.join(dir, name), ingest);
99
+ }, now);
100
+ }
101
+ catch (err) {
102
+ log?.(`direct drain: liveness carry failed: ${(err instanceof Error ? err.message : String(err)).slice(0, 120)}`);
103
+ }
104
+ backlogDir = path.join(dir, PRE_DRAIN_BACKLOG_DIRNAME, `${at.getTime()}`);
105
+ fs.mkdirSync(backlogDir, { recursive: true, mode: 0o700 });
106
+ for (const name of queued) {
107
+ try {
108
+ fs.renameSync(path.join(dir, name), path.join(backlogDir, name));
109
+ setAside.push(name);
110
+ }
111
+ catch (err) {
112
+ if (err.code !== "ENOENT")
113
+ throw err;
114
+ }
115
+ }
116
+ }
117
+ const marker = {
118
+ v: 1,
119
+ firstRunAt: at.toISOString(),
120
+ setAside,
121
+ ...(backlogDir && setAside.length > 0 ? { backlogDir } : {}),
122
+ };
123
+ const target = directDrainMarkerPath(dir);
124
+ const tmp = `${target}.${process.pid}.${Date.now()}.tmp`;
125
+ fs.writeFileSync(tmp, `${JSON.stringify(marker, null, 2)}\n`, { mode: 0o600 });
126
+ fs.renameSync(tmp, target);
127
+ return { firstRun: true, marker };
128
+ }
129
+ /**
130
+ * Keep spool.jsonl bounded when lines cannot be delivered (offline, signed
131
+ * out, reporting off). Over `maxLines`, the spool is claimed by rename (the
132
+ * same claim the flush uses, so a hook appending meanwhile writes a fresh
133
+ * file and a crash leaves an orphan claim the next flush recovers), the newest
134
+ * three quarters are appended back, and the rest are discarded with one
135
+ * dropped receipt. Returns the number discarded.
136
+ */
137
+ export function capSpool(root, opts) {
138
+ const now = opts.now ?? (() => new Date());
139
+ const spool = workMeshSpoolPath(root);
140
+ if (opts.maxLines <= 0)
141
+ return 0;
142
+ try {
143
+ if (fs.statSync(spool).size < opts.maxLines * MIN_SPOOL_LINE_BYTES)
144
+ return 0;
145
+ }
146
+ catch {
147
+ return 0;
148
+ }
149
+ let total = 0;
150
+ forEachJsonlLine(spool, (line) => {
151
+ if (line.trim())
152
+ total += 1;
153
+ });
154
+ if (total <= opts.maxLines)
155
+ return 0;
156
+ const keep = Math.max(1, Math.floor(opts.maxLines * 0.75));
157
+ const claimPath = workMeshClaimPath("spool", `${now().getTime()}.cap`, root);
158
+ try {
159
+ fs.renameSync(spool, claimPath);
160
+ }
161
+ catch (err) {
162
+ if (err.code === "ENOENT")
163
+ return 0;
164
+ throw err;
165
+ }
166
+ const ring = [];
167
+ let seen = 0;
168
+ const scan = (ingest) => {
169
+ forEachJsonlLine(claimPath, (line) => {
170
+ if (!line.trim())
171
+ return;
172
+ ingest?.(line);
173
+ ring[seen % keep] = line;
174
+ seen += 1;
175
+ });
176
+ };
177
+ let scanned = false;
178
+ try {
179
+ updateLivenessCarry(root, (ingest) => {
180
+ scanned = true;
181
+ scan(ingest);
182
+ }, now);
183
+ }
184
+ catch (err) {
185
+ opts.log?.(`spool cap: liveness carry failed: ${(err instanceof Error ? err.message : String(err)).slice(0, 120)}`);
186
+ }
187
+ if (!scanned)
188
+ scan();
189
+ const newest = seen <= keep ? ring.slice(0, seen) : [...ring.slice(seen % keep), ...ring.slice(0, seen % keep)];
190
+ let kept = 0;
191
+ for (const line of newest) {
192
+ try {
193
+ appendJsonlLine(spool, line);
194
+ kept += 1;
195
+ }
196
+ catch (err) {
197
+ opts.log?.(`spool cap: line not kept: ${(err instanceof Error ? err.message : String(err)).slice(0, 120)}`);
198
+ }
199
+ }
200
+ removeClaimFile(claimPath);
201
+ const discarded = seen - kept;
202
+ if (discarded > 0) {
203
+ appendDroppedReceipt({ v: 1, dropped: discarded, reason: "spool_cap", cap: opts.maxLines, at: now().toISOString() }, root);
204
+ opts.log?.(`spool cap: discarded ${discarded} oldest undelivered line(s) of ${seen} (cap=${opts.maxLines})`);
205
+ }
206
+ return discarded;
207
+ }
208
+ /**
209
+ * The flush deps the direct-mode drain runs with, whatever the caller passed:
210
+ * - a company comes only from the session's own state file
211
+ * (companyEvidence "own_session");
212
+ * - a device-default company is never authorized, so such a session is held;
213
+ * - session liveness is copied before a claimed line can be removed.
214
+ */
215
+ export function directFlushDeps(base, now = () => new Date()) {
216
+ return {
217
+ ...base,
218
+ companyEvidence: "own_session",
219
+ authorizeDeviceDefaultTenant: undefined,
220
+ onSpoolLinesClaimed: (lines) => {
221
+ updateLivenessCarry(base.workMeshRoot, (ingest) => {
222
+ for (const line of lines)
223
+ ingest(line);
224
+ }, now);
225
+ },
226
+ };
227
+ }
228
+ export async function runDirectDrainCycle(deps) {
229
+ const root = deps.workMeshRoot;
230
+ const now = deps.now ?? (() => new Date());
231
+ const start = ensureDirectDrainStart(root, now, deps.log);
232
+ if (start.firstRun) {
233
+ deps.log?.(start.marker.setAside.length > 0
234
+ ? `direct drain first run: moved ${start.marker.setAside.length} queued file(s) to ${PRE_DRAIN_BACKLOG_DIRNAME}/; they are not posted`
235
+ : "direct drain first run: nothing was queued");
236
+ return {
237
+ firstRun: true,
238
+ setAside: start.marker.setAside,
239
+ summary: null,
240
+ spoolDiscarded: 0,
241
+ deadLetterDiscarded: 0,
242
+ };
243
+ }
244
+ const spoolDiscarded = capSpool(root, {
245
+ maxLines: deps.spoolMaxLines ?? DIRECT_SPOOL_MAX_LINES,
246
+ now,
247
+ log: deps.log,
248
+ });
249
+ const pending = deps.heldRetryDue === false
250
+ ? hasPendingSpoolWork(root)
251
+ : hasPendingFlushWork(root);
252
+ if (!pending) {
253
+ return { firstRun: false, setAside: [], summary: null, spoolDiscarded, deadLetterDiscarded: 0 };
254
+ }
255
+ const flushDeps = directFlushDeps(await deps.flushDeps(), now);
256
+ const summary = await (deps.flush ?? flushSessionEvents)(flushDeps);
257
+ let deadLetterDiscarded = 0;
258
+ if (summary.deadLettered > 0) {
259
+ deadLetterDiscarded = trimDeadLetter(root, {
260
+ maxLines: deps.deadLetterMaxLines ?? DIRECT_DEAD_LETTER_MAX_LINES,
261
+ protectBefore: start.marker.firstRunAt,
262
+ });
263
+ if (deadLetterDiscarded > 0) {
264
+ appendDroppedReceipt({
265
+ v: 1,
266
+ dropped: deadLetterDiscarded,
267
+ reason: "dead_letter_cap",
268
+ cap: deps.deadLetterMaxLines ?? DIRECT_DEAD_LETTER_MAX_LINES,
269
+ at: now().toISOString(),
270
+ }, root);
271
+ deps.log?.(`dead-letter cap: removed ${deadLetterDiscarded} oldest line(s) written since the drain's first run`);
272
+ }
273
+ }
274
+ return { firstRun: false, setAside: [], summary, spoolDiscarded, deadLetterDiscarded };
275
+ }
276
+ /**
277
+ * One flush for a caller outside the daemon (`hq mesh session flush`). Legacy
278
+ * mode runs the shared flush as before. Direct mode runs one drain cycle, so
279
+ * the manual command obeys the same first-run rule and the same company rule
280
+ * as the daemon: on a machine whose drain has not run yet it sets the queue
281
+ * aside and posts nothing.
282
+ */
283
+ export async function flushForEmitMode(mode, deps) {
284
+ if (mode !== "direct") {
285
+ return { summary: await flushSessionEvents(deps), firstRun: false, setAside: [] };
286
+ }
287
+ const result = await runDirectDrainCycle({
288
+ workMeshRoot: deps.workMeshRoot,
289
+ flushDeps: async () => deps,
290
+ now: deps.now,
291
+ log: deps.log,
292
+ });
293
+ return {
294
+ summary: result.summary ?? {
295
+ claimed: 0, posted: 0, held: 0, dropped: 0, deadLettered: 0,
296
+ restored: 0, batches: 0, heldClaimed: false, heldOverflow: 0,
297
+ },
298
+ firstRun: result.firstRun,
299
+ setAside: result.setAside,
300
+ };
301
+ }
302
+ /**
303
+ * For a manual command that reads the spool or the held file and can post
304
+ * from them. In direct mode it establishes the drain's start point first, so
305
+ * a queue that predates the first run is set aside before the command reads
306
+ * anything. Legacy mode: nothing happens. Throws when the queue cannot be set
307
+ * aside; the caller must not go on to read or post.
308
+ */
309
+ export function ensureDrainStartForMode(mode, root, now = () => new Date()) {
310
+ if (mode !== "direct")
311
+ return { firstRun: false, setAside: [] };
312
+ const start = ensureDirectDrainStart(root, now);
313
+ return { firstRun: start.firstRun, setAside: start.firstRun ? start.marker.setAside : [] };
314
+ }
315
+ //# sourceMappingURL=direct-drain.js.map
@@ -10,6 +10,7 @@
10
10
  * the retry file; this module never deletes spool/held (a follow-up removes the
11
11
  * legacy queue once replay is confirmed).
12
12
  */
13
+ import type { MeshEmitMode } from "./daemon/mode.js";
13
14
  import { type MeshEmitEvent } from "./emit-client.js";
14
15
  /** Convert one legacy spool/held event object into a MeshEmitEvent, or null. */
15
16
  export declare function legacyEventToEmit(raw: Record<string, unknown>): MeshEmitEvent | null;
@@ -23,4 +24,13 @@ export interface LegacyBacklog {
23
24
  * The daemon's held retry may duplicate a spool line; first occurrence wins.
24
25
  */
25
26
  export declare function readLegacyBacklog(workMeshRoot: string): LegacyBacklog;
27
+ /**
28
+ * readLegacyBacklog for `hq mesh emit --replay-legacy`. In direct mode the
29
+ * drain's first-run rule applies first: a spool or held file that predates the
30
+ * first run is set aside and is not part of the backlog returned here.
31
+ */
32
+ export declare function readLegacyBacklogForMode(mode: MeshEmitMode, workMeshRoot: string, now?: () => Date): LegacyBacklog & {
33
+ firstRun: boolean;
34
+ setAside: string[];
35
+ };
26
36
  //# sourceMappingURL=emit-replay.d.ts.map
@@ -12,6 +12,7 @@
12
12
  */
13
13
  import * as fs from "node:fs";
14
14
  import { workMeshSpoolPath, workMeshHeldPath } from "./paths.js";
15
+ import { ensureDrainStartForMode } from "./direct-drain.js";
15
16
  import { buildMeshEmitEvent } from "./emit-client.js";
16
17
  const KINDS = new Set([
17
18
  "session_start",
@@ -154,4 +155,13 @@ export function readLegacyBacklog(workMeshRoot) {
154
155
  }
155
156
  return { events, scanned: rows.length, skipped };
156
157
  }
158
+ /**
159
+ * readLegacyBacklog for `hq mesh emit --replay-legacy`. In direct mode the
160
+ * drain's first-run rule applies first: a spool or held file that predates the
161
+ * first run is set aside and is not part of the backlog returned here.
162
+ */
163
+ export function readLegacyBacklogForMode(mode, workMeshRoot, now = () => new Date()) {
164
+ const start = ensureDrainStartForMode(mode, workMeshRoot, now);
165
+ return { ...readLegacyBacklog(workMeshRoot), ...start };
166
+ }
157
167
  //# sourceMappingURL=emit-replay.js.map
@@ -71,6 +71,21 @@ export interface FlushDeps {
71
71
  * stay held and are retried). Called at most once per slug per flush.
72
72
  */
73
73
  resolveCompanyUid?: (slug: string) => Promise<string | null>;
74
+ /**
75
+ * Which evidence may give a session without a companyUid its company.
76
+ * "local" (default, legacy daemon) runs the full local resolver: cwd, git
77
+ * remote, repo map, session meta. "own_session" (the direct-mode drain)
78
+ * accepts only the slug in the session's own state file, and still needs
79
+ * resolveCompanyUid to confirm membership. Nothing is taken from a spool
80
+ * line, a device default, a folder, a repo map or another session.
81
+ */
82
+ companyEvidence?: "local" | "own_session";
83
+ /**
84
+ * Called once with the raw lines this flush took from the spool and from
85
+ * orphan claims, before any of them is posted or removed. The direct-mode
86
+ * drain records session liveness from them (lanes reads it).
87
+ */
88
+ onSpoolLinesClaimed?: (lines: string[]) => void;
74
89
  }
75
90
  export interface FlushSummary {
76
91
  claimed: number;