@indigoai-us/hq-cli 5.345.244 → 5.345.246

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 (116) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/dist/command-catalog.generated.d.ts +93 -6
  3. package/dist/command-catalog.generated.js +114 -6
  4. package/dist/commands/bot.js +1 -1
  5. package/dist/commands/core-checkpoint-native.d.ts +5 -1
  6. package/dist/commands/core-checkpoint-native.js +13 -5
  7. package/dist/commands/deploy-comments.js +139 -0
  8. package/dist/commands/deploy-list.d.ts +5 -0
  9. package/dist/commands/deploy-list.js +8 -0
  10. package/dist/commands/dm.d.ts +4 -1
  11. package/dist/commands/dm.js +11 -2
  12. package/dist/commands/files.d.ts +11 -2
  13. package/dist/commands/files.js +48 -3
  14. package/dist/commands/lanes-loop.js +4 -1
  15. package/dist/commands/lanes.js +16 -5
  16. package/dist/commands/mesh.d.ts +2 -0
  17. package/dist/commands/mesh.js +26 -6
  18. package/dist/commands/reindex.js +2 -1
  19. package/dist/commands/rescue.d.ts +22 -1
  20. package/dist/commands/rescue.js +56 -9
  21. package/dist/commands/sources.d.ts +1 -1
  22. package/dist/commands/sources.js +1 -1
  23. package/dist/commands/storage.d.ts +15 -2
  24. package/dist/commands/storage.js +74 -7
  25. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +2033 -1829
  26. package/dist/hq-cloud-sync-runner/package.json +1 -1
  27. package/dist/lib/agent-kit/mcp/tools.js +22 -0
  28. package/dist/lib/bot/jobs/hot-signal-sync.js +4 -1
  29. package/dist/lib/daemon/fleet-members-cache.d.ts +55 -0
  30. package/dist/lib/daemon/fleet-members-cache.js +266 -0
  31. package/dist/lib/daemon/handoff.d.ts +4 -0
  32. package/dist/lib/daemon/handoff.js +2 -1
  33. package/dist/lib/daemon/hook-requests.d.ts +2 -1
  34. package/dist/lib/daemon/hook-requests.js +19 -2
  35. package/dist/lib/daemon/install.d.ts +9 -1
  36. package/dist/lib/daemon/install.js +11 -2
  37. package/dist/lib/daemon/ops/policy.d.ts +23 -3
  38. package/dist/lib/daemon/ops/policy.js +62 -15
  39. package/dist/lib/daemon/run.js +12 -0
  40. package/dist/lib/daemon/server.d.ts +5 -0
  41. package/dist/lib/daemon/server.js +1 -1
  42. package/dist/lib/daemon/supervisor.d.ts +6 -0
  43. package/dist/lib/daemon/supervisor.js +31 -2
  44. package/dist/lib/doctor/checks/sync-runtime.js +8 -1
  45. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  46. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  47. package/dist/lib/hook-engine/coverage.d.ts +68 -0
  48. package/dist/lib/hook-engine/coverage.js +163 -0
  49. package/dist/lib/hook-engine/native-precompact-compatibility.json +1 -0
  50. package/dist/lib/hot-channels/signals-pass.d.ts +52 -2
  51. package/dist/lib/hot-channels/signals-pass.js +65 -3
  52. package/dist/lib/install/claude-targets.d.ts +6 -0
  53. package/dist/lib/install/claude-targets.js +9 -1
  54. package/dist/lib/lanes/reconcile-result.d.ts +1 -1
  55. package/dist/lib/lanes/reconcile.js +19 -4
  56. package/dist/lib/lanes/remote-control-lane.d.ts +6 -0
  57. package/dist/lib/lanes/remote-control-lane.js +10 -1
  58. package/dist/lib/lanes/spawn.d.ts +2 -0
  59. package/dist/lib/lanes/spawn.js +19 -3
  60. package/dist/lib/lanes/worker-env-scrub.d.ts +48 -0
  61. package/dist/lib/lanes/worker-env-scrub.js +146 -0
  62. package/dist/lib/lanes/worker-process.js +4 -1
  63. package/dist/lib/mesh/client.js +5 -1
  64. package/dist/lib/mesh/live/daemon/doctor.d.ts +9 -0
  65. package/dist/lib/mesh/live/daemon/doctor.js +51 -6
  66. package/dist/lib/mesh/live/daemon/install.d.ts +39 -0
  67. package/dist/lib/mesh/live/daemon/install.js +70 -0
  68. package/dist/lib/mesh/live/daemon/outbox-company.d.ts +47 -0
  69. package/dist/lib/mesh/live/daemon/outbox-company.js +77 -0
  70. package/dist/lib/mesh/live/daemon/run.d.ts +2 -0
  71. package/dist/lib/mesh/live/daemon/run.js +48 -3
  72. package/dist/lib/mesh/live/daemon/state.d.ts +5 -0
  73. package/dist/lib/mesh/live/daemon/system-unit.d.ts +21 -0
  74. package/dist/lib/mesh/live/daemon/system-unit.js +80 -0
  75. package/dist/lib/mesh/live/daemon/transcript-watch.d.ts +4 -1
  76. package/dist/lib/mesh/live/daemon/transcript-watch.js +42 -38
  77. package/dist/lib/mesh/live/direct-drain.js +3 -1
  78. package/dist/lib/mesh/live/emit.js +4 -2
  79. package/dist/lib/mesh/live/flush.d.ts +61 -0
  80. package/dist/lib/mesh/live/flush.js +434 -114
  81. package/dist/lib/mesh/live/paths.d.ts +10 -0
  82. package/dist/lib/mesh/live/paths.js +14 -0
  83. package/dist/lib/mesh/live/reporting-privacy.d.ts +41 -1
  84. package/dist/lib/mesh/live/reporting-privacy.js +81 -7
  85. package/dist/lib/mesh/live/spool.d.ts +171 -17
  86. package/dist/lib/mesh/live/spool.js +777 -62
  87. package/dist/lib/signals/engine.d.ts +82 -2
  88. package/dist/lib/signals/engine.js +389 -53
  89. package/dist/lib/signals/steps/extract.js +5 -0
  90. package/dist/lib/sync-core/engine-holds.d.ts +17 -1
  91. package/dist/lib/sync-core/engine-holds.js +73 -3
  92. package/dist/lib/sync-core/reconcile.js +10 -2
  93. package/dist/lib/work-context/organize.d.ts +22 -4
  94. package/dist/lib/work-context/organize.js +50 -21
  95. package/dist/lib/work-context/paths.d.ts +6 -0
  96. package/dist/lib/work-context/paths.js +9 -0
  97. package/dist/lib/work-context/reconcile.d.ts +1 -1
  98. package/dist/lib/work-context/reconcile.js +1 -1
  99. package/dist/startup-registration.d.ts +14 -0
  100. package/dist/startup-registration.js +26 -0
  101. package/dist/utils/cli-telemetry.d.ts +6 -0
  102. package/dist/utils/cli-telemetry.js +154 -9
  103. package/dist/utils/github-tag-fallback.d.ts +7 -2
  104. package/dist/utils/github-tag-fallback.js +17 -8
  105. package/dist/utils/hq-core-source.d.ts +31 -0
  106. package/dist/utils/hq-core-source.js +144 -0
  107. package/dist/utils/interactive-caller.d.ts +6 -0
  108. package/dist/utils/interactive-caller.js +8 -0
  109. package/dist/utils/shipped-codex-hooks.d.ts +6 -4
  110. package/dist/utils/shipped-codex-hooks.js +22 -10
  111. package/dist/utils/vault-api.js +1 -0
  112. package/dist/utils/version-report.d.ts +3 -1
  113. package/dist/utils/version-report.js +13 -5
  114. package/docs/anywhere-runtime.md +2 -2
  115. package/package.json +8 -8
  116. package/scripts/check-function-manifest.mjs +99 -18
@@ -70,6 +70,8 @@ export interface DaemonRunDeps {
70
70
  backfillHeld?: () => Promise<BackfillHeldResult>;
71
71
  /** Maximum distinct held sessions reconciled during one daemon startup. */
72
72
  heldBackfillBatchSize?: number;
73
+ /** Dead-letter size that triggers compaction at start. Default DEAD_LETTER_COMPACT_MIN_BYTES (tests pass 0). */
74
+ deadLetterCompactMinBytes?: number;
73
75
  /** Minimum gap between periodic held backfills. Default HELD_BACKFILL_INTERVAL_MS. */
74
76
  heldBackfillIntervalMs?: number;
75
77
  /** Injected board refresh (tests). */
@@ -34,7 +34,8 @@ import { daemonDir } from "./paths.js";
34
34
  import { PresenceClient, defaultMqttConnect, } from "./presence.js";
35
35
  import { defaultDaemonState, patchDaemonState, readDaemonState, writeDaemonState, } from "./state.js";
36
36
  import { workMeshHeldPath } from "../paths.js";
37
- import { countJsonlLines } from "../spool.js";
37
+ import { compactDeadLetter, countJsonlLines } from "../spool.js";
38
+ import { createOutboxCompanyUidFiller, requeueCompanyUidQuarantines } from "./outbox-company.js";
38
39
  import { defaultTranscriptFs, noteHookSessionsFromSpoolFile, TRANSCRIPT_WATCH_INTERVAL_MS, TranscriptWatcher, } from "./transcript-watch.js";
39
40
  import { resolveMeshEmitMode, runsEmitPath, } from "./mode.js";
40
41
  import { hasCliVersionDrift, readInstalledCliVersion } from "./version-drift.js";
@@ -462,7 +463,14 @@ export async function runMeshDaemon(deps = {}) {
462
463
  (async () => {
463
464
  const t = await getToken();
464
465
  const deliver = deps.deliver ?? createWorkSessionDeliverer({ token: t });
466
+ // A registration queued with a company slug and no uid gets its uid
467
+ // here, from the membership-checked lookup only (never from local
468
+ // evidence). Not confirmed: it stays quarantined, with a logged reason.
469
+ const fillCompanyUid = createOutboxCompanyUidFiller((companySlug) => tenantGate.authorize({ companySlug, deviceDefault: false }), (message) => log(dir, message), ctxRoot);
465
470
  return replayOutbox(ctxRoot, async (op) => {
471
+ const refusal = await fillCompanyUid(op);
472
+ if (refusal)
473
+ return refusal;
466
474
  const state = readSessionState(op.sessionId, ctxRoot);
467
475
  // Provenance must survive session-state loss. For pre-upgrade outbox
468
476
  // entries without provenance, absent state is unknown and therefore
@@ -775,6 +783,8 @@ export async function runMeshDaemon(deps = {}) {
775
783
  return;
776
784
  }
777
785
  flushInFlight = (async () => {
786
+ // Doctor shows a flush that has started and not ended, instead of "never".
787
+ patchDaemonState(dir, { flushStartedAt: now().toISOString() }, now);
778
788
  try {
779
789
  // A held session has already ended, so no later hook will naturally
780
790
  // revisit its context. Repair a bounded batch before the first flush;
@@ -819,12 +829,21 @@ export async function runMeshDaemon(deps = {}) {
819
829
  patchDaemonState(dir, {
820
830
  lastFlushAt: now().toISOString(),
821
831
  lastFlushResult: { ...summary, ok: true },
832
+ flushStartedAt: null,
833
+ lastFlushError: null,
834
+ lastFlushErrorAt: null,
822
835
  }, now);
836
+ const duplicates = summary.duplicates ?? 0;
837
+ const parked = summary.parked ?? 0;
823
838
  if (summary.claimed > 0 ||
824
839
  summary.posted > 0 ||
825
840
  summary.held > 0 ||
826
- (summary.heldOverflow ?? 0) > 0) {
827
- log(dir, `flush(${reason}): claimed=${summary.claimed} posted=${summary.posted} held=${summary.held}`);
841
+ (summary.heldOverflow ?? 0) > 0 ||
842
+ duplicates > 0 ||
843
+ parked > 0) {
844
+ log(dir, `flush(${reason}): claimed=${summary.claimed} posted=${summary.posted} held=${summary.held}` +
845
+ (duplicates > 0 ? ` duplicates=${duplicates}` : "") +
846
+ (parked > 0 ? ` parked=${parked}` : ""));
828
847
  }
829
848
  }
830
849
  catch (err) {
@@ -842,6 +861,9 @@ export async function runMeshDaemon(deps = {}) {
842
861
  batches: 0,
843
862
  },
844
863
  lastErrorCode: msg.slice(0, 120),
864
+ flushStartedAt: null,
865
+ lastFlushError: `flush(${reason}): ${msg.slice(0, 200)}`,
866
+ lastFlushErrorAt: now().toISOString(),
845
867
  }, now);
846
868
  log(dir, `flush(${reason}) error: ${msg.slice(0, 200)}`);
847
869
  }
@@ -1042,6 +1064,29 @@ export async function runMeshDaemon(deps = {}) {
1042
1064
  });
1043
1065
  }, TRANSCRIPT_WATCH_INTERVAL_MS);
1044
1066
  }
1067
+ // Once per start: heal queues an older version left behind. Registrations
1068
+ // quarantined for a missing company uid go back in the queue (the replay
1069
+ // looks the uid up through the membership check), and a large dead-letter
1070
+ // file is compacted to one line per event, with the event loop yielding.
1071
+ if (emitPath) {
1072
+ try {
1073
+ const requeued = requeueCompanyUidQuarantines(ctxRoot, now);
1074
+ if (requeued > 0)
1075
+ log(dir, `outbox: re-queued ${requeued} registrations quarantined for a missing company uid`);
1076
+ }
1077
+ catch (err) {
1078
+ log(dir, `outbox re-queue failed: ${(err instanceof Error ? err.message : String(err)).slice(0, 160)}`);
1079
+ }
1080
+ void compactDeadLetter(meshRoot, { minBytes: deps.deadLetterCompactMinBytes })
1081
+ .then((result) => {
1082
+ if (result.compacted) {
1083
+ log(dir, `dead-letter compacted: lines ${result.linesBefore} -> ${result.linesAfter}, bytes ${result.bytesBefore} -> ${result.bytesAfter}`);
1084
+ }
1085
+ })
1086
+ .catch((err) => {
1087
+ log(dir, `dead-letter compaction failed: ${(err instanceof Error ? err.message : String(err)).slice(0, 160)}`);
1088
+ });
1089
+ }
1045
1090
  // Initial pass. Board refresh runs in both modes; the flush + transcript
1046
1091
  // scan are legacy emit-path only.
1047
1092
  if (!requestRestartForVersionDrift() && emitPath) {
@@ -23,6 +23,11 @@ export interface DaemonStateFile {
23
23
  lastFlushResult?: FlushSummary & {
24
24
  ok: boolean;
25
25
  };
26
+ /** Set when a flush starts and cleared when it ends, so doctor can tell "running" from "never". */
27
+ flushStartedAt?: string | null;
28
+ /** The last flush's error message (bounded) and when it happened; cleared by a flush that succeeds. */
29
+ lastFlushError?: string | null;
30
+ lastFlushErrorAt?: string | null;
26
31
  lastErrorCode?: string;
27
32
  /** Set while credential vend is refused (FEATURE_DISABLED / unsupported / 403). */
28
33
  presenceRefusal?: PresenceRefusalState | null;
@@ -0,0 +1,21 @@
1
+ import type { RunCommand } from "../../../service-manager/launchd.js";
2
+ export declare const SYSTEMD_SYSTEM_UNIT_DIR = "/etc/systemd/system";
3
+ export declare function meshSystemUnitPath(systemUnitDir?: string): string;
4
+ export declare function meshSystemUnitPresent(systemUnitDir?: string, existsSync?: (file: string) => boolean): boolean;
5
+ /** The properties `systemctl show` reports for the system unit. Empty strings when unknown. */
6
+ export interface SystemUnitState {
7
+ loadState: string;
8
+ activeState: string;
9
+ subState: string;
10
+ unitFileState: string;
11
+ }
12
+ /** Parse `systemctl show -p LoadState -p ActiveState -p SubState -p UnitFileState` output. */
13
+ export declare function parseSystemctlShow(stdout: string): SystemUnitState;
14
+ /**
15
+ * Read the system unit's state from the system manager. Reading needs no root.
16
+ * Returns null when systemctl cannot answer (no systemd, no bus).
17
+ */
18
+ export declare function readMeshSystemUnitState(run: RunCommand): SystemUnitState | null;
19
+ /** One plain phrase for the state, for example "active (running), enabled". */
20
+ export declare function describeSystemUnitState(state: SystemUnitState | null): string;
21
+ //# sourceMappingURL=system-unit.d.ts.map
@@ -0,0 +1,80 @@
1
+ /**
2
+ * The box-level Work Mesh unit at /etc/systemd/system/hq-mesh-daemon.service.
3
+ *
4
+ * Hosted agent boxes run the daemon from this system unit (installed by the
5
+ * box's own tooling with `hq mesh daemon install --system-user ...`). A
6
+ * per-user unit next to it starts a second daemon that cannot take the pid
7
+ * lock and restarts every few seconds, so install, status and the daemon's
8
+ * start path all need to see the system unit.
9
+ */
10
+ import * as fs from "node:fs";
11
+ import * as path from "node:path";
12
+ import { SYSTEMD_UNIT_NAME } from "./paths.js";
13
+ export const SYSTEMD_SYSTEM_UNIT_DIR = "/etc/systemd/system";
14
+ export function meshSystemUnitPath(systemUnitDir = SYSTEMD_SYSTEM_UNIT_DIR) {
15
+ return path.join(systemUnitDir, SYSTEMD_UNIT_NAME);
16
+ }
17
+ export function meshSystemUnitPresent(systemUnitDir = SYSTEMD_SYSTEM_UNIT_DIR, existsSync = fs.existsSync) {
18
+ return existsSync(meshSystemUnitPath(systemUnitDir));
19
+ }
20
+ /** Parse `systemctl show -p LoadState -p ActiveState -p SubState -p UnitFileState` output. */
21
+ export function parseSystemctlShow(stdout) {
22
+ const values = new Map();
23
+ for (const line of stdout.split(/\r?\n/)) {
24
+ const eq = line.indexOf("=");
25
+ if (eq <= 0)
26
+ continue;
27
+ values.set(line.slice(0, eq).trim(), line.slice(eq + 1).trim());
28
+ }
29
+ return {
30
+ loadState: values.get("LoadState") ?? "",
31
+ activeState: values.get("ActiveState") ?? "",
32
+ subState: values.get("SubState") ?? "",
33
+ unitFileState: values.get("UnitFileState") ?? "",
34
+ };
35
+ }
36
+ /**
37
+ * Read the system unit's state from the system manager. Reading needs no root.
38
+ * Returns null when systemctl cannot answer (no systemd, no bus).
39
+ */
40
+ export function readMeshSystemUnitState(run) {
41
+ let result;
42
+ try {
43
+ result = run("systemctl", [
44
+ "show",
45
+ "-p",
46
+ "LoadState",
47
+ "-p",
48
+ "ActiveState",
49
+ "-p",
50
+ "SubState",
51
+ "-p",
52
+ "UnitFileState",
53
+ SYSTEMD_UNIT_NAME,
54
+ ]);
55
+ }
56
+ catch {
57
+ return null;
58
+ }
59
+ if (result.status !== 0)
60
+ return null;
61
+ const state = parseSystemctlShow(result.stdout);
62
+ if (!state.loadState && !state.activeState)
63
+ return null;
64
+ return state;
65
+ }
66
+ /** One plain phrase for the state, for example "active (running), enabled". */
67
+ export function describeSystemUnitState(state) {
68
+ if (!state)
69
+ return "state unknown (systemctl did not answer)";
70
+ const active = state.subState && state.subState !== state.activeState
71
+ ? `${state.activeState} (${state.subState})`
72
+ : state.activeState || "unknown";
73
+ const parts = [active];
74
+ if (state.loadState && state.loadState !== "loaded")
75
+ parts.push(state.loadState);
76
+ if (state.unitFileState)
77
+ parts.push(state.unitFileState);
78
+ return parts.join(", ");
79
+ }
80
+ //# sourceMappingURL=system-unit.js.map
@@ -253,9 +253,12 @@ export declare function resolveTranscriptRegistration(input: {
253
253
  }): SessionStateFile;
254
254
  /**
255
255
  * Scan a spool/held jsonl for hook-emitted session ids (not transcript-watch).
256
- * Reads spool metadata only — never a transcript file.
256
+ * Reads spool metadata only — never a transcript file. The file is streamed
257
+ * line by line: a spool past V8's ~512 MB string limit cannot be read whole.
258
+ * Returns each noted session id once.
257
259
  */
258
260
  export declare function noteHookSessionsFromSpoolFile(spoolPath: string, lastHookEventAt: Map<string, number>, atMs: number, tfs?: Pick<TranscriptFs, "existsSync"> & {
261
+ /** Unused: kept so existing callers still type-check. The file is streamed. */
259
262
  readFileSync?: (p: string, enc: "utf8") => string;
260
263
  }, lastHookTurnEndAt?: Map<string, number>): string[];
261
264
  export declare class TranscriptWatcher {
@@ -50,6 +50,7 @@ import { isHookWrittenSessionState, readSessionState, writeSessionState, } from
50
50
  import { enqueueSessionEvent } from "../enqueue.js";
51
51
  import { isValidSessionId } from "../session-identity.js";
52
52
  import { reserveSessionSeq } from "../session-seq.js";
53
+ import { forEachJsonlLine } from "../spool.js";
53
54
  export const TRANSCRIPT_WATCH_INTERVAL_MS = 30_000;
54
55
  /** Ceiling for adaptive backoff after heavy ticks. */
55
56
  export const TRANSCRIPT_WATCH_INTERVAL_MAX_MS = 120_000;
@@ -516,55 +517,58 @@ export function resolveTranscriptRegistration(input) {
516
517
  }
517
518
  /**
518
519
  * Scan a spool/held jsonl for hook-emitted session ids (not transcript-watch).
519
- * Reads spool metadata only — never a transcript file.
520
+ * Reads spool metadata only — never a transcript file. The file is streamed
521
+ * line by line: a spool past V8's ~512 MB string limit cannot be read whole.
522
+ * Returns each noted session id once.
520
523
  */
521
524
  export function noteHookSessionsFromSpoolFile(spoolPath, lastHookEventAt, atMs, tfs = defaultTranscriptFs, lastHookTurnEndAt) {
522
525
  if (!tfs.existsSync(spoolPath))
523
526
  return [];
524
- const readFile = tfs.readFileSync ?? ((p, enc) => fs.readFileSync(p, enc));
525
- let text;
527
+ const noted = new Set();
526
528
  try {
527
- text = readFile(spoolPath, "utf8");
529
+ forEachJsonlLine(spoolPath, (rawLine) => {
530
+ const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
531
+ noteHookSessionLine(line, lastHookEventAt, atMs, noted, lastHookTurnEndAt);
532
+ });
528
533
  }
529
534
  catch {
530
- return [];
535
+ // A read error mid-file: keep what was noted.
531
536
  }
532
- const noted = [];
533
- for (const line of text.split(/\r?\n/)) {
534
- if (!line.trim())
535
- continue;
536
- try {
537
- const raw = JSON.parse(line);
538
- const ev = raw.event && typeof raw.event === "object" ? raw.event : raw;
539
- if (typeof ev.sessionId !== "string" || !ev.sessionId)
540
- continue;
541
- // Synthesized transcript events carry source=transcript — not hooks.
542
- if (ev.source === TRANSCRIPT_EVENT_SOURCE)
543
- continue;
544
- let eventAt = atMs;
545
- const atRaw = typeof ev.at === "string" ? ev.at : undefined;
546
- if (atRaw) {
547
- const parsed = Date.parse(atRaw);
548
- if (Number.isFinite(parsed))
549
- eventAt = parsed;
550
- }
551
- const prev = lastHookEventAt.get(ev.sessionId);
552
- if (prev === undefined || eventAt > prev) {
553
- lastHookEventAt.set(ev.sessionId, eventAt);
554
- }
555
- if (ev.kind === "turn_end" && lastHookTurnEndAt) {
556
- const prevEnd = lastHookTurnEndAt.get(ev.sessionId);
557
- if (prevEnd === undefined || eventAt > prevEnd) {
558
- lastHookTurnEndAt.set(ev.sessionId, eventAt);
559
- }
560
- }
561
- noted.push(ev.sessionId);
537
+ return [...noted];
538
+ }
539
+ function noteHookSessionLine(line, lastHookEventAt, atMs, noted, lastHookTurnEndAt) {
540
+ if (!line.trim())
541
+ return;
542
+ try {
543
+ const raw = JSON.parse(line);
544
+ const ev = raw.event && typeof raw.event === "object" ? raw.event : raw;
545
+ if (typeof ev.sessionId !== "string" || !ev.sessionId)
546
+ return;
547
+ // Synthesized transcript events carry source=transcript — not hooks.
548
+ if (ev.source === TRANSCRIPT_EVENT_SOURCE)
549
+ return;
550
+ let eventAt = atMs;
551
+ const atRaw = typeof ev.at === "string" ? ev.at : undefined;
552
+ if (atRaw) {
553
+ const parsed = Date.parse(atRaw);
554
+ if (Number.isFinite(parsed))
555
+ eventAt = parsed;
562
556
  }
563
- catch {
564
- /* ignore malformed */
557
+ const prev = lastHookEventAt.get(ev.sessionId);
558
+ if (prev === undefined || eventAt > prev) {
559
+ lastHookEventAt.set(ev.sessionId, eventAt);
560
+ }
561
+ if (ev.kind === "turn_end" && lastHookTurnEndAt) {
562
+ const prevEnd = lastHookTurnEndAt.get(ev.sessionId);
563
+ if (prevEnd === undefined || eventAt > prevEnd) {
564
+ lastHookTurnEndAt.set(ev.sessionId, eventAt);
565
+ }
565
566
  }
567
+ noted.add(ev.sessionId);
568
+ }
569
+ catch {
570
+ /* ignore malformed */
566
571
  }
567
- return noted;
568
572
  }
569
573
  export class TranscriptWatcher {
570
574
  tracked = new Map();
@@ -34,7 +34,7 @@ export const DIRECT_DEAD_LETTER_MAX_LINES = 5_000;
34
34
  /** A spool line is far longer than this, so a smaller file is under the cap. */
35
35
  const MIN_SPOOL_LINE_BYTES = 64;
36
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)$/;
37
+ const PRE_EXISTING_QUEUE_RE = /^(spool\.jsonl|held\.jsonl|spool\.parked\.jsonl|(spool|held)\..+\.claimed)$/;
38
38
  export function directDrainMarkerPath(root) {
39
39
  return path.join(root, DIRECT_DRAIN_MARKER_BASENAME);
40
40
  }
@@ -217,6 +217,8 @@ export function directFlushDeps(base, now = () => new Date()) {
217
217
  ...base,
218
218
  companyEvidence: "own_session",
219
219
  authorizeDeviceDefaultTenant: undefined,
220
+ // Lines a flush may not act on stay on the spool, under capSpool's bound.
221
+ parkUnbound: false,
220
222
  onSpoolLinesClaimed: (lines) => {
221
223
  updateLivenessCarry(base.workMeshRoot, (ingest) => {
222
224
  for (const line of lines)
@@ -124,10 +124,12 @@ export async function emitEvents(deps) {
124
124
  // Events stored before this machine first saw HQ Anywhere off were held
125
125
  // back by the member's opt-out; while it stays off they wait.
126
126
  let bound = [];
127
- if (operatorAllowsHqAnywhere(env)) {
127
+ const confirmed = operatorAllowsHqAnywhere(env)
128
+ ? combined.filter(event => hasWorkMeshEventCompanyBinding(event, env)) : [];
129
+ if (confirmed.length > 0) {
128
130
  const offSinceMs = anywhereOffSince(deps.workMeshRoot, now);
129
131
  logAnywhereOffSinceAhead(deps.workMeshRoot, offSinceMs, now().getTime(), deps.log);
130
- bound = combined.filter(event => eventDatedSince(event, offSinceMs) && hasWorkMeshEventCompanyBinding(event, env));
132
+ bound = confirmed.filter(event => eventDatedSince(event, offSinceMs));
131
133
  }
132
134
  if (bound.length === 0) {
133
135
  const written = persistRetry(combined);
@@ -22,6 +22,49 @@ export declare const HELD_MAX_LINES = 20000;
22
22
  * The catalog itself is also cached inside bind-best.
23
23
  */
24
24
  export declare const PROJECT_REBIND_INTERVAL_MS = 60000;
25
+ /**
26
+ * Most claimed events one flush keeps in memory to act on. Lines past it go
27
+ * back on the spool as they were, for a later flush, so a claim of any size is
28
+ * read with bounded memory. Far above a normal spool, so ordinary flushes are
29
+ * unchanged.
30
+ */
31
+ export declare const FLUSH_MAX_EVENTS_IN_MEMORY = 200000;
32
+ /**
33
+ * Most bytes of claimed lines one flush keeps in memory to act on, next to
34
+ * the event count: a few very large events reach the heap limit long before
35
+ * 200,000 of them. Lines past it go back on the spool like lines past the
36
+ * count. The first event is always kept, so one oversized line cannot stall
37
+ * the queue.
38
+ */
39
+ export declare const FLUSH_MAX_BYTES_IN_MEMORY: number;
40
+ /**
41
+ * A line in the parked file (see workMeshParkedPath) is dropped once it was
42
+ * parked longer ago than this, with a dropped receipt and a log line, so the
43
+ * parked file does not grow for ever on a machine that stays off. The age is
44
+ * the time since the line was parked, never the event's own time, and only
45
+ * lines read back from the parked file are dropped: a line read from the
46
+ * spool or a spool claim is parked, never dropped, however old its event.
47
+ */
48
+ export declare const PARKED_LINE_MAX_AGE_MS: number;
49
+ /**
50
+ * How far a recorded parked-at time may be ahead of the clock before the
51
+ * clock is taken to be wrong (behind the time lines were parked), in which
52
+ * case nothing is dropped.
53
+ */
54
+ export declare const PARKED_CLOCK_SKEW_MS: number;
55
+ /**
56
+ * The smallest spool the first bound-only flush parks with no bound session's
57
+ * event in it. Below one read chunk, scanning the spool costs little, and the
58
+ * flush leaves it exactly as it is (the usual rule with HQ Anywhere off).
59
+ */
60
+ export declare const PARK_BACKLOG_MIN_BYTES: number;
61
+ /** Test hook: forget which roots had their first bound-only flush. */
62
+ export declare function resetFirstBoundOnlyFlushes(): void;
63
+ /**
64
+ * Most distinct eventIds one flush remembers to collapse repeated lines of the
65
+ * same event. Past it, ids already remembered are still collapsed.
66
+ */
67
+ export declare const FLUSH_DEDUPE_MAX_IDS = 1000000;
25
68
  export type HeldReason = "STATE_ABSENT" | "NEEDS_COMPANY" | "COMPANY_CONFLICT" | "NEEDS_PROJECT" | "HELD_EXPIRED" | "HELD_OVERFLOW";
26
69
  export interface FlushDeps {
27
70
  /**
@@ -86,6 +129,18 @@ export interface FlushDeps {
86
129
  * drain records session liveness from them (lanes reads it).
87
130
  */
88
131
  onSpoolLinesClaimed?: (lines: string[]) => void;
132
+ /** Default FLUSH_MAX_EVENTS_IN_MEMORY (tests pass a small value). */
133
+ maxEventsInMemory?: number;
134
+ /** Default FLUSH_DEDUPE_MAX_IDS. */
135
+ dedupeMaxIds?: number;
136
+ /** Default FLUSH_MAX_BYTES_IN_MEMORY (tests pass a small value). */
137
+ maxBytesInMemory?: number;
138
+ /**
139
+ * With HQ Anywhere off, park the lines this flush may not act on instead of
140
+ * putting them back on the spool. Default true. The direct-mode drain passes
141
+ * false: its spool cap must keep bounding those lines.
142
+ */
143
+ parkUnbound?: boolean;
89
144
  }
90
145
  export type FlushNoClaimReason = "operator_switch_off" | "anywhere_off_no_company_session_event";
91
146
  export interface FlushSummary {
@@ -101,6 +156,12 @@ export interface FlushSummary {
101
156
  /** Oldest held lines dead-lettered this flush due to HELD_MAX_LINES. */
102
157
  heldOverflow?: number;
103
158
  noClaimReason?: FlushNoClaimReason;
159
+ /** Repeated lines of an event already read this flush, collapsed to one. */
160
+ duplicates?: number;
161
+ /** Lines parked with HQ Anywhere off (see workMeshParkedPath). */
162
+ parked?: number;
163
+ /** Lines read from the parked file and dropped: parked longer ago than PARKED_LINE_MAX_AGE_MS. */
164
+ parkedExpired?: number;
104
165
  }
105
166
  /**
106
167
  * Flush spool + held. Safe to call concurrently with enqueue (claim-by-rename).