@indigoai-us/hq-cli 5.345.226 → 5.345.230

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 (138) hide show
  1. package/CHANGELOG.md +156 -0
  2. package/dist/command-catalog.generated.d.ts +376 -11
  3. package/dist/command-catalog.generated.js +451 -11
  4. package/dist/commands/auth.d.ts +2 -2
  5. package/dist/commands/auth.js +3 -3
  6. package/dist/commands/core-delegate-w1b.js +92 -69
  7. package/dist/commands/core-delegate.d.ts +19 -1
  8. package/dist/commands/core-delegate.js +411 -6
  9. package/dist/commands/core-dm-bind-native.js +2 -1
  10. package/dist/commands/core-handoff.d.ts +5 -0
  11. package/dist/commands/core-handoff.js +1008 -14
  12. package/dist/commands/core-pin-native.d.ts +1 -0
  13. package/dist/commands/core-pin-native.js +3 -15
  14. package/dist/commands/core-register-project-native.d.ts +6 -0
  15. package/dist/commands/core-register-project-native.js +182 -52
  16. package/dist/commands/core-work-mesh-bind-trusted-native.js +4 -9
  17. package/dist/commands/daemon.js +2 -2
  18. package/dist/commands/index-cmd.d.ts +3 -1
  19. package/dist/commands/index-cmd.js +12 -0
  20. package/dist/commands/lanes-checks.js +1 -1
  21. package/dist/commands/lanes-session-start.d.ts +1 -2
  22. package/dist/commands/lanes-session-start.js +9 -145
  23. package/dist/commands/lanes-shared.d.ts +3 -0
  24. package/dist/commands/lanes.d.ts +3 -0
  25. package/dist/commands/lanes.js +94 -27
  26. package/dist/commands/link.d.ts +8 -3
  27. package/dist/commands/link.js +14 -17
  28. package/dist/commands/mcp-registration.d.ts +65 -7
  29. package/dist/commands/mcp-registration.js +289 -51
  30. package/dist/commands/mesh.d.ts +12 -0
  31. package/dist/commands/mesh.js +92 -10
  32. package/dist/commands/reindex.js +6 -0
  33. package/dist/commands/repo.d.ts +13 -0
  34. package/dist/commands/repo.js +39 -1
  35. package/dist/commands/sync-mode.d.ts +3 -1
  36. package/dist/commands/sync-mode.js +11 -1
  37. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +1473 -1043
  38. package/dist/hq-cloud-sync-runner/package.json +1 -1
  39. package/dist/lazy-commands.js +3 -4
  40. package/dist/lib/checkpoint-ontology/entity-file.js +4 -4
  41. package/dist/lib/checkpoint-ontology/merge-copies.js +7 -11
  42. package/dist/lib/checkpoint-ontology/plan.js +2 -1
  43. package/dist/lib/core-utils/archive-old-threads.js +5 -2
  44. package/dist/lib/core-utils/session-company.d.ts +13 -1
  45. package/dist/lib/core-utils/session-company.js +75 -4
  46. package/dist/lib/core-utils/worktree-resume.d.ts +6 -0
  47. package/dist/lib/core-utils/worktree-resume.js +8 -4
  48. package/dist/lib/daemon/background-qos.d.ts +7 -0
  49. package/dist/lib/daemon/background-qos.js +13 -0
  50. package/dist/lib/daemon/catalog.d.ts +9 -0
  51. package/dist/lib/daemon/catalog.js +8 -1
  52. package/dist/lib/daemon/hook-requests-acl-suggest.d.ts +18 -0
  53. package/dist/lib/daemon/hook-requests-acl-suggest.js +245 -0
  54. package/dist/lib/daemon/hook-requests-conduct-link.d.ts +20 -0
  55. package/dist/lib/daemon/hook-requests-conduct-link.js +105 -0
  56. package/dist/lib/daemon/hook-requests-fleet-session-start.d.ts +32 -0
  57. package/dist/lib/daemon/hook-requests-fleet-session-start.js +214 -0
  58. package/dist/lib/daemon/hook-requests-mesh-tool-writes.d.ts +44 -0
  59. package/dist/lib/daemon/hook-requests-mesh-tool-writes.js +292 -0
  60. package/dist/lib/daemon/hook-requests-mesh.d.ts +54 -0
  61. package/dist/lib/daemon/hook-requests-mesh.js +559 -0
  62. package/dist/lib/daemon/hook-requests.d.ts +354 -8
  63. package/dist/lib/daemon/hook-requests.js +1330 -46
  64. package/dist/lib/daemon/machine-checks.d.ts +12 -2
  65. package/dist/lib/daemon/machine-checks.js +27 -10
  66. package/dist/lib/daemon/merge-sections.d.ts +24 -2
  67. package/dist/lib/daemon/merge-sections.js +58 -16
  68. package/dist/lib/daemon/ops/policy.js +4 -2
  69. package/dist/lib/daemon/resolver.js +9 -2
  70. package/dist/lib/daemon/run.d.ts +11 -7
  71. package/dist/lib/daemon/run.js +168 -24
  72. package/dist/lib/daemon/search-index-worker-v1.d.ts +2 -0
  73. package/dist/lib/daemon/search-index-worker-v1.js +25 -0
  74. package/dist/lib/daemon/session-registry.d.ts +0 -1
  75. package/dist/lib/daemon/session-registry.js +0 -3
  76. package/dist/lib/daemon/supervisor.d.ts +3 -1
  77. package/dist/lib/daemon/supervisor.js +1 -1
  78. package/dist/lib/daemon/tcc-eperm.d.ts +59 -4
  79. package/dist/lib/daemon/tcc-eperm.js +110 -8
  80. package/dist/lib/doctor/fix/process-identity.d.ts +20 -2
  81. package/dist/lib/doctor/fix/process-identity.js +48 -5
  82. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  83. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  84. package/dist/lib/hook-engine/canary-gate.js +1 -0
  85. package/dist/lib/hook-engine/native-stop-compatibility.json +2 -1
  86. package/dist/lib/hot-channels/adapters/attio.js +2 -1
  87. package/dist/lib/hot-channels/adapters/meetings.js +2 -1
  88. package/dist/lib/lanes/company-outposts.d.ts +37 -0
  89. package/dist/lib/lanes/company-outposts.js +164 -0
  90. package/dist/lib/lanes/liveness.d.ts +6 -0
  91. package/dist/lib/lanes/liveness.js +49 -8
  92. package/dist/lib/lanes/orphan-report.d.ts +15 -0
  93. package/dist/lib/lanes/orphan-report.js +223 -0
  94. package/dist/lib/lanes/orphan-sweep.d.ts +26 -0
  95. package/dist/lib/lanes/orphan-sweep.js +152 -0
  96. package/dist/lib/lanes/reaper.d.ts +2 -0
  97. package/dist/lib/lanes/reaper.js +11 -8
  98. package/dist/lib/lanes/reconcile.d.ts +8 -7
  99. package/dist/lib/lanes/reconcile.js +39 -0
  100. package/dist/lib/mesh/live/backfill-held.d.ts +13 -0
  101. package/dist/lib/mesh/live/backfill-held.js +23 -0
  102. package/dist/lib/mesh/live/daemon/mode.d.ts +8 -4
  103. package/dist/lib/mesh/live/daemon/mode.js +8 -4
  104. package/dist/lib/mesh/live/daemon/run.d.ts +14 -3
  105. package/dist/lib/mesh/live/daemon/run.js +116 -7
  106. package/dist/lib/mesh/live/direct-drain.d.ts +123 -0
  107. package/dist/lib/mesh/live/direct-drain.js +315 -0
  108. package/dist/lib/mesh/live/emit-replay.d.ts +10 -0
  109. package/dist/lib/mesh/live/emit-replay.js +10 -0
  110. package/dist/lib/mesh/live/flush.d.ts +15 -0
  111. package/dist/lib/mesh/live/flush.js +27 -0
  112. package/dist/lib/mesh/live/liveness-carry.d.ts +45 -0
  113. package/dist/lib/mesh/live/liveness-carry.js +141 -0
  114. package/dist/lib/mesh/live/spool.d.ts +19 -0
  115. package/dist/lib/mesh/live/spool.js +80 -0
  116. package/dist/lib/safe-store.d.ts +2 -0
  117. package/dist/lib/safe-store.js +8 -6
  118. package/dist/lib/search-index/index.d.ts +9 -3
  119. package/dist/lib/search-index/index.js +35 -10
  120. package/dist/lib/search-index/worker-process.d.ts +9 -0
  121. package/dist/lib/search-index/worker-process.js +171 -0
  122. package/dist/lib/session-company-lock.d.ts +3 -1
  123. package/dist/lib/session-company-lock.js +3 -2
  124. package/dist/utils/delegate-command-supervisor.d.ts +3 -0
  125. package/dist/utils/delegate-command-supervisor.js +44 -0
  126. package/dist/utils/delegate-lock.d.ts +12 -0
  127. package/dist/utils/delegate-lock.js +88 -0
  128. package/dist/utils/frontmatter.d.ts +27 -0
  129. package/dist/utils/frontmatter.js +33 -0
  130. package/dist/utils/hook-trust.d.ts +1 -0
  131. package/dist/utils/hook-trust.js +18 -2
  132. package/dist/utils/host-registration.d.ts +13 -1
  133. package/dist/utils/host-registration.js +98 -5
  134. package/dist/utils/package-use-lease.d.ts +1 -1
  135. package/dist/utils/package-use-lease.js +15 -7
  136. package/docs/anywhere-runtime.md +17 -0
  137. package/package.json +9 -8
  138. package/scripts/check-function-manifest.mjs +17 -3
@@ -0,0 +1,152 @@
1
+ /** In-process PID marker maintenance. Never starts or stops a process. */
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { laneRunsOnHost } from "./admission.js";
5
+ import { laneRunDir, parsePidRecord, parseProcStat, readPidRecord } from "./spawn.js";
6
+ import { isSubagentLane } from "./types.js";
7
+ export function orphanProcessAlive(pid) {
8
+ process.kill(pid, 0);
9
+ return true;
10
+ }
11
+ export function orphanProcessStarttime(pid) {
12
+ // Darwin's existing starttime reader starts ps. Leave identity uncertain
13
+ // there rather than starting a helper from the daemon sweep.
14
+ if (process.platform !== "linux")
15
+ return null;
16
+ return parseProcStat(fs.readFileSync(path.join("/proc", String(pid), "stat"), "utf8")).starttime ?? null;
17
+ }
18
+ function classify(record, deps) {
19
+ try {
20
+ if (!(deps.isAlive ?? orphanProcessAlive)(record.pid))
21
+ return { status: "stale", reason: "process_gone" };
22
+ }
23
+ catch (error) {
24
+ return error.code === "ESRCH"
25
+ ? { status: "stale", reason: "process_gone" }
26
+ : { status: "uncertain", reason: "process_probe_unavailable" };
27
+ }
28
+ if (record.starttime == null)
29
+ return { status: "uncertain", reason: "recorded_identity_missing" };
30
+ try {
31
+ const current = (deps.readStarttime ?? orphanProcessStarttime)(record.pid);
32
+ if (current === null)
33
+ return { status: "uncertain", reason: "process_identity_unavailable" };
34
+ return current === record.starttime
35
+ ? { status: "live", reason: "process_identity_matches" }
36
+ : { status: "stale", reason: "pid_reused" };
37
+ }
38
+ catch {
39
+ return { status: "uncertain", reason: "process_identity_unavailable" };
40
+ }
41
+ }
42
+ /** Shared with manual reap: recheck both marker contents and staleness. */
43
+ export function clearStalePidMarker(root, file, expected, isStale) {
44
+ if (!withinRoot(root, file))
45
+ return false;
46
+ const before = fs.lstatSync(file);
47
+ if (!before.isFile())
48
+ return false;
49
+ const current = readPidRecord(file);
50
+ if (!current || current.pid !== expected.pid || current.starttime !== expected.starttime || !isStale(current))
51
+ return false;
52
+ const after = fs.lstatSync(file);
53
+ if (!after.isFile() || before.ino !== after.ino || before.dev !== after.dev || before.mtimeMs !== after.mtimeMs || before.size !== after.size)
54
+ return false;
55
+ const latest = readPidRecord(file);
56
+ if (!latest || latest.pid !== expected.pid || latest.starttime !== expected.starttime)
57
+ return false;
58
+ fs.unlinkSync(file);
59
+ return true;
60
+ }
61
+ function withinRoot(root, file) {
62
+ const relative = path.relative(fs.realpathSync(root), fs.realpathSync(path.dirname(file)));
63
+ return relative === "" || (!path.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${path.sep}`));
64
+ }
65
+ /** Keep cleanup from removing markers created or replaced during reconciliation. */
66
+ export function snapshotOrphanMarkers(root, lanes, host) {
67
+ const snapshot = new Map();
68
+ for (const lane of lanes) {
69
+ if (isSubagentLane(lane) || !laneRunsOnHost(lane, host))
70
+ continue;
71
+ for (const marker of ["worker.pid", "watcher.pid"]) {
72
+ const file = path.join(laneRunDir(root, lane.lane_id), marker);
73
+ try {
74
+ snapshot.set(file, withinRoot(root, file) && fs.lstatSync(file).isFile() ? fs.readFileSync(file, "utf8") : null);
75
+ }
76
+ catch (error) {
77
+ if (error.code !== "ENOENT")
78
+ snapshot.set(file, null);
79
+ }
80
+ }
81
+ }
82
+ return snapshot;
83
+ }
84
+ export function sweepOrphanMarkers(root, lanes, host, dryRun, deps = {}, snapshot) {
85
+ const findings = [];
86
+ for (const lane of lanes) {
87
+ if (isSubagentLane(lane) || !laneRunsOnHost(lane, host))
88
+ continue;
89
+ for (const marker of ["worker.pid", "watcher.pid"]) {
90
+ const file = path.join(laneRunDir(root, lane.lane_id), marker);
91
+ if (snapshot && !snapshot.has(file))
92
+ continue;
93
+ const finding = { lane_id: lane.lane_id, marker, status: "uncertain", reason: "marker_unreadable", cleared: false };
94
+ try {
95
+ if (!withinRoot(root, file)) {
96
+ finding.reason = "marker_parent_outside_root";
97
+ }
98
+ else if (!fs.lstatSync(file).isFile()) {
99
+ finding.reason = "marker_not_regular_file";
100
+ }
101
+ else {
102
+ const text = fs.readFileSync(file, "utf8");
103
+ const record = parsePidRecord(text);
104
+ if (snapshot && snapshot.get(file) !== text)
105
+ finding.reason = "marker_changed_during_reconcile";
106
+ else if (!record)
107
+ finding.reason = "marker_malformed";
108
+ else {
109
+ Object.assign(finding, classify(record, deps));
110
+ if (finding.status === "stale" && !dryRun) {
111
+ finding.cleared = clearStalePidMarker(root, file, record, (current) => classify(current, deps).status === "stale");
112
+ if (!finding.cleared) {
113
+ finding.status = "uncertain";
114
+ finding.reason = "marker_or_process_changed";
115
+ }
116
+ }
117
+ }
118
+ }
119
+ }
120
+ catch (error) {
121
+ if (error.code === "ENOENT")
122
+ continue;
123
+ finding.status = "uncertain";
124
+ finding.reason = "marker_read_or_clear_failed";
125
+ }
126
+ findings.push(finding);
127
+ }
128
+ }
129
+ return findings;
130
+ }
131
+ // Each root/host keeps only its current markers. Bound root/host entries too.
132
+ const reportedMarkerStates = new Map();
133
+ export function changedOrphanMarkers(root, host, findings, snapshot) {
134
+ const scope = JSON.stringify([fs.realpathSync(root), host.hostname, host.outpostId]);
135
+ const previous = reportedMarkerStates.get(scope);
136
+ const current = new Map();
137
+ const changed = [];
138
+ for (const finding of findings) {
139
+ const key = `${finding.lane_id}/${finding.marker}`;
140
+ const bytes = snapshot.get(path.join(laneRunDir(root, finding.lane_id), finding.marker));
141
+ const state = JSON.stringify([finding.status, finding.reason, finding.cleared, bytes]);
142
+ current.set(key, state);
143
+ if (previous?.get(key) !== state)
144
+ changed.push(finding);
145
+ }
146
+ reportedMarkerStates.delete(scope);
147
+ reportedMarkerStates.set(scope, current);
148
+ while (reportedMarkerStates.size > 64)
149
+ reportedMarkerStates.delete(reportedMarkerStates.keys().next().value);
150
+ return changed;
151
+ }
152
+ //# sourceMappingURL=orphan-sweep.js.map
@@ -28,6 +28,8 @@ export interface ReapDeps {
28
28
  now?: () => Date;
29
29
  hostname?: () => string;
30
30
  processes?: () => ReapProcess[];
31
+ /** In-process ancestry reader, used by daemon reporting without a full ps. */
32
+ processAncestry?: (pid: number) => ReapProcess[];
31
33
  isAlive?: (pid: number) => boolean;
32
34
  readStarttime?: (pid: number) => number | null;
33
35
  sessionState?: (root: string, sessionId: string, now: Date) => string | null;
@@ -1,3 +1,4 @@
1
+ import { clearStalePidMarker } from "./orphan-sweep.js";
1
2
  /** Session-start orphan lane sweep. Every destructive action is opt-in and gated. */
2
3
  import * as fs from "node:fs";
3
4
  import { createHash } from "node:crypto";
@@ -211,7 +212,8 @@ function localRun(lane, hostname) {
211
212
  }
212
213
  export async function classifyLocalLanes(root, now, minAgeMinutes, deps = {}) {
213
214
  const hostname = deps.hostname?.() ?? os.hostname();
214
- const processes = (deps.processes ?? readProcesses)();
215
+ let processes;
216
+ const ancestry = (pid) => deps.processAncestry?.(pid) ?? (processes ??= (deps.processes ?? readProcesses)());
215
217
  const alive = deps.isAlive ?? isProcessRunning;
216
218
  const readStart = deps.readStarttime ?? readProcStarttime;
217
219
  const result = [];
@@ -281,7 +283,7 @@ export async function classifyLocalLanes(root, now, minAgeMinutes, deps = {}) {
281
283
  finding.reason = "worker_process_gone_or_pid_reused";
282
284
  finding.stale_state = staleState;
283
285
  }
284
- else if (ancestryReachesSession(worker.pid, processes))
286
+ else if (ancestryReachesSession(worker.pid, ancestry(worker.pid)))
285
287
  finding.reason = "process_has_live_session_ancestor";
286
288
  else {
287
289
  finding.orphaned = true;
@@ -356,12 +358,13 @@ export async function reapLocalLanes(root, options, deps = {}) {
356
358
  if (!expected)
357
359
  return;
358
360
  const markerPath = path.join(laneRunDir(root, finding.lane_id), marker);
359
- const current = readPidRecord(markerPath);
360
- if (!current || current.pid !== expected.pid || current.starttime !== expected.starttime)
361
- return;
362
- if (isPidRecordAlive(current, isAlive, readStart))
363
- return;
364
- fs.rmSync(markerPath, { force: true });
361
+ try {
362
+ clearStalePidMarker(root, markerPath, expected, (current) => !isPidRecordAlive(current, isAlive, readStart));
363
+ }
364
+ catch (error) {
365
+ if (error.code !== "ENOENT")
366
+ throw error;
367
+ }
365
368
  };
366
369
  let stopEnabled = false;
367
370
  for (const finding of findings) {
@@ -1,10 +1,5 @@
1
- /**
2
- * Periodic reconcile pass (spec §5.7, §6.8, §9).
3
- *
4
- * Owned by the machine, not by any lane. Reads never mutate; every write is a
5
- * compare-and-set. The per-lane watcher owns progress/terminal/silence of a
6
- * live process — this pass owns the transitions no single lane can own.
7
- */
1
+ import { type DaemonOrphanDeps } from "./orphan-report.js";
2
+ import { type OrphanMarkerDeps, type OrphanMarkerFinding } from "./orphan-sweep.js";
8
3
  import { type LivenessDeps } from "./liveness.js";
9
4
  import { type EnvelopeRepairSpawnInput, type SpawnLaneDeps } from "./spawn.js";
10
5
  import { type ThrottleDeps, type CpuBusyObservation } from "./throttle.js";
@@ -67,6 +62,9 @@ export interface ReconcileSummary {
67
62
  heartbeats: string[];
68
63
  skipped: ReconcileSkip[];
69
64
  notes?: string[];
65
+ orphan_markers?: OrphanMarkerFinding[];
66
+ uncertain_markers?: number;
67
+ orphan_count?: number;
70
68
  keep_alive_blocked: Array<{
71
69
  id: string;
72
70
  reason: KeepAliveBlockedReason;
@@ -93,6 +91,9 @@ export interface ReconcileHost {
93
91
  aliases?: readonly string[];
94
92
  }
95
93
  export interface ReconcileDeps {
94
+ /** Child-free process identity probes for stale marker maintenance. */
95
+ orphanMarkerDeps?: OrphanMarkerDeps;
96
+ orphanReportDeps?: DaemonOrphanDeps;
96
97
  now: () => Date;
97
98
  host: ReconcileHost;
98
99
  dryRun: boolean;
@@ -1,3 +1,6 @@
1
+ import { classifyDaemonOrphans, writeOrphanReport } from "./orphan-report.js";
2
+ import { LANE_ORPHAN_SWEEP_WAITING_FLAG } from "./flag-keys.js";
3
+ import { changedOrphanMarkers, snapshotOrphanMarkers, sweepOrphanMarkers } from "./orphan-sweep.js";
1
4
  /**
2
5
  * Periodic reconcile pass (spec §5.7, §6.8, §9).
3
6
  *
@@ -1180,6 +1183,7 @@ export async function runPassBody(hqRoot, deps) {
1180
1183
  if (deps.terminalKeepAliveCandidate) {
1181
1184
  return runTerminalKeepAliveCandidatePass(hqRoot, lanes, summary, deps, now, deps.terminalKeepAliveCandidate);
1182
1185
  }
1186
+ const orphanMarkerSnapshot = snapshotOrphanMarkers(hqRoot, lanes, deps.host);
1183
1187
  await reconcileBlockedEscalations(hqRoot, lanes, summary, deps, now);
1184
1188
  await resumeDueQuotaHeldLanes(hqRoot, lanes, summary, deps, now);
1185
1189
  let presenceConnected;
@@ -1298,6 +1302,29 @@ export async function runPassBody(hqRoot, deps) {
1298
1302
  sessionStateCache.set(sessionId, state);
1299
1303
  return state;
1300
1304
  };
1305
+ try {
1306
+ const orphans = await classifyDaemonOrphans(hqRoot, now, {
1307
+ hostname: () => deps.host.hostname,
1308
+ onProcessReadFailure: (note) => {
1309
+ summary.notes ??= [];
1310
+ summary.notes.push(note);
1311
+ process.stderr.write(`${note}\n`);
1312
+ },
1313
+ isAlive: deps.isAlive,
1314
+ sessionState: (_root, id) => sessionState(id),
1315
+ waitingSeniorEnabled: () => (deps.readRegistryFlag ?? readLanesRegistryFlagFailOpen)(LANE_ORPHAN_SWEEP_WAITING_FLAG, { env: deps.env, defaultValue: true }),
1316
+ ...deps.orphanReportDeps,
1317
+ });
1318
+ summary.orphan_count = orphans.filter((lane) => lane.orphaned).length;
1319
+ if (!deps.dryRun)
1320
+ writeOrphanReport(hqRoot, deps.host.hostname, now, orphans);
1321
+ }
1322
+ catch (error) {
1323
+ const note = `Orphan report unavailable: ${error instanceof Error ? error.message : String(error)}`;
1324
+ summary.notes ??= [];
1325
+ summary.notes.push(note);
1326
+ process.stderr.write(`${note}\n`);
1327
+ }
1301
1328
  const questionAgeWindowMs = (audience) => audience.kind === "session"
1302
1329
  ? config.session_question_timeout_secs * 1000
1303
1330
  : QUESTION_AGE_MS;
@@ -1562,6 +1589,18 @@ export async function runPassBody(hqRoot, deps) {
1562
1589
  writeThrottleState(throttleStatePath(hqRoot), recordCpuBusyObservation(currentThrottleState, cpuObservation), admissionThrottleDeps);
1563
1590
  }
1564
1591
  }
1592
+ const markerFindings = sweepOrphanMarkers(hqRoot, lanes, deps.host, deps.dryRun, {
1593
+ isAlive: deps.isAlive,
1594
+ ...deps.orphanMarkerDeps,
1595
+ }, orphanMarkerSnapshot);
1596
+ summary.uncertain_markers = markerFindings.filter((marker) => marker.status === "uncertain").length;
1597
+ summary.orphan_markers = deps.dryRun ? markerFindings : changedOrphanMarkers(hqRoot, deps.host, markerFindings, orphanMarkerSnapshot);
1598
+ for (const marker of summary.orphan_markers) {
1599
+ const note = `hq runners marker ${marker.lane_id}/${marker.marker}: ${marker.reason}${marker.cleared ? "; cleared" : "; preserved"}`;
1600
+ summary.notes ??= [];
1601
+ summary.notes.push(note);
1602
+ process.stderr.write(`${note}\n`);
1603
+ }
1565
1604
  if (!deps.dryRun && summary.errors.length === 0) {
1566
1605
  try {
1567
1606
  writeHeartbeatFile(hqRoot, summary, nowIso);
@@ -167,6 +167,19 @@ export declare function hasCurrentAcknowledgedRegistration(ref: HeldSessionRef,
167
167
  * their disposition; this backfill never mutates or deletes held lines).
168
168
  */
169
169
  export declare function readHeldSessions(workMeshRoot: string): HeldSessionRef[];
170
+ /** A real held backfill was asked for on a machine in emit mode "direct". */
171
+ export declare class HeldBackfillRefusedError extends Error {
172
+ readonly code: "HELD_BACKFILL_REFUSED_DIRECT_MODE";
173
+ constructor();
174
+ }
175
+ /**
176
+ * backfillHeldSessions behind the emit mode. In direct mode a real run is
177
+ * refused before anything is read, written or delivered (the direct-mode
178
+ * drain trusts session state, so this command must not write a company the
179
+ * session's own state never named). A dry run writes and delivers nothing and
180
+ * is allowed. Legacy mode is unchanged.
181
+ */
182
+ export declare function backfillHeldSessionsForMode(mode: "legacy" | "direct", deps: BackfillHeldDeps): Promise<BackfillHeldResult>;
170
183
  /**
171
184
  * Reconcile ended sessions whose held events lack a company. Idempotent:
172
185
  * re-running skips sessions that already carry a companyUid.
@@ -583,6 +583,29 @@ export function readHeldSessions(workMeshRoot) {
583
583
  }
584
584
  return [...seen.values()];
585
585
  }
586
+ /** A real held backfill was asked for on a machine in emit mode "direct". */
587
+ export class HeldBackfillRefusedError extends Error {
588
+ code = "HELD_BACKFILL_REFUSED_DIRECT_MODE";
589
+ constructor() {
590
+ super("hq mesh context backfill-held does not run in emit mode direct. It gives a held session a company from " +
591
+ "its working folder, the slug on its events or the device default, and the daemon would then send that " +
592
+ "session's events to that company. In direct mode a session is sent only to the company its own state " +
593
+ "names. Nothing was changed. --dry-run still works.");
594
+ this.name = "HeldBackfillRefusedError";
595
+ }
596
+ }
597
+ /**
598
+ * backfillHeldSessions behind the emit mode. In direct mode a real run is
599
+ * refused before anything is read, written or delivered (the direct-mode
600
+ * drain trusts session state, so this command must not write a company the
601
+ * session's own state never named). A dry run writes and delivers nothing and
602
+ * is allowed. Legacy mode is unchanged.
603
+ */
604
+ export async function backfillHeldSessionsForMode(mode, deps) {
605
+ if (mode === "direct" && !deps.dryRun)
606
+ throw new HeldBackfillRefusedError();
607
+ return backfillHeldSessions(deps);
608
+ }
586
609
  /**
587
610
  * Reconcile ended sessions whose held events lack a company. Idempotent:
588
611
  * re-running skips sessions that already carry a companyUid.
@@ -7,10 +7,14 @@
7
7
  * - "legacy" — the daemon runs the EMIT path (spool watch + flush + held +
8
8
  * outbox replay + transcript-watch fallback) AND the receive
9
9
  * subscriber. This is the default until the server route is live.
10
- * - "direct" — sessions POST events directly (see `hq mesh session`/`emit`);
11
- * the daemon runs RECEIVE-ONLY: the presence subscriber on
12
- * hq/{personUid}/mesh keeps the cache the desktop app reads warm.
13
- * No spool/held/outbox/flush/transcript-watch on this box.
10
+ * - "direct" — CLI commands POST their events directly (see `hq mesh
11
+ * session`/`emit`) and the daemon keeps the presence subscriber
12
+ * on hq/{personUid}/mesh, which keeps the cache the desktop app
13
+ * reads warm. The hooks still append session and turn events
14
+ * to the spool, so the daemon also delivers the spool on a
15
+ * timer (../direct-drain.ts; US-038, owner decision 70). No
16
+ * outbox replay, held backfill, directory watcher, shutdown
17
+ * flush or transcript-watch on this box.
14
18
  *
15
19
  * The flag is resolved from (highest first): env HQ_MESH_MODE, the work-mesh
16
20
  * config file (~/.hq/work-mesh/config.json `emitMode`), else "legacy".
@@ -7,10 +7,14 @@
7
7
  * - "legacy" — the daemon runs the EMIT path (spool watch + flush + held +
8
8
  * outbox replay + transcript-watch fallback) AND the receive
9
9
  * subscriber. This is the default until the server route is live.
10
- * - "direct" — sessions POST events directly (see `hq mesh session`/`emit`);
11
- * the daemon runs RECEIVE-ONLY: the presence subscriber on
12
- * hq/{personUid}/mesh keeps the cache the desktop app reads warm.
13
- * No spool/held/outbox/flush/transcript-watch on this box.
10
+ * - "direct" — CLI commands POST their events directly (see `hq mesh
11
+ * session`/`emit`) and the daemon keeps the presence subscriber
12
+ * on hq/{personUid}/mesh, which keeps the cache the desktop app
13
+ * reads warm. The hooks still append session and turn events
14
+ * to the spool, so the daemon also delivers the spool on a
15
+ * timer (../direct-drain.ts; US-038, owner decision 70). No
16
+ * outbox replay, held backfill, directory watcher, shutdown
17
+ * flush or transcript-watch on this box.
14
18
  *
15
19
  * The flag is resolved from (highest first): env HQ_MESH_MODE, the work-mesh
16
20
  * config file (~/.hq/work-mesh/config.json `emitMode`), else "legacy".
@@ -11,6 +11,8 @@ import { type MeshEmitMode } from "./mode.js";
11
11
  import { type CommandRunner, type LegacyListenPlatform } from "./legacy-listen.js";
12
12
  import { type StartCapacitySchedulerOptions } from "../../../capacity/scheduler.js";
13
13
  export declare const SPOOL_DEBOUNCE_MS = 2000;
14
+ /** Direct mode: wait after daemon start before the first spool drain cycle. */
15
+ export declare const DIRECT_DRAIN_START_DELAY_MS = 1000;
14
16
  export declare const FLUSH_INTERVAL_MS = 10000;
15
17
  /** Keep startup recovery bounded: the next daemon start continues the backlog. */
16
18
  export declare const HELD_BACKFILL_STARTUP_BATCH_SIZE = 100;
@@ -24,6 +26,14 @@ export declare const DEVICE_DEFAULT_MEMBERSHIP_TIMEOUT_MS = 2000;
24
26
  /** Skip further membership probes after a transport failure so a network drop
25
27
  * cannot fan out one hanging lookup per held session. */
26
28
  export declare const DEVICE_DEFAULT_MEMBERSHIP_UNAVAILABLE_COOLDOWN_MS = 30000;
29
+ /** Direct mode: longest wait between drain cycles after repeated failures. */
30
+ export declare const DIRECT_DRAIN_MAX_DELAY_MS: number;
31
+ /**
32
+ * Wait before the next direct-mode drain cycle. FLUSH_INTERVAL_MS while cycles
33
+ * succeed; doubled for each cycle in a row that failed or delivered nothing
34
+ * it tried to send, up to DIRECT_DRAIN_MAX_DELAY_MS.
35
+ */
36
+ export declare function directDrainDelayMs(consecutiveFailures: number): number;
27
37
  /** Three sequential async shutdown steps must finish within six seconds. */
28
38
  export declare const SHUTDOWN_STEP_TIMEOUT_MS = 2000;
29
39
  /** Non-zero exit reserved for CLI version drift so legacy Restart=on-failure units restart. */
@@ -74,9 +84,10 @@ export interface DaemonRunDeps {
74
84
  enableTranscriptWatch?: boolean;
75
85
  /**
76
86
  * Emit mode. "legacy" runs the spool/flush/held/outbox/transcript-watch emit
77
- * path; "direct" runs receive-only (subscriber + cache) because sessions POST
78
- * events directly. Default resolves from HQ_MESH_MODE / work-mesh config, else
79
- * "legacy" (contract direct-emit-v1 §6.3).
87
+ * path. "direct" keeps the subscriber and cache, and delivers the spool the
88
+ * hooks still write on a timer (runDirectDrainCycle), with no outbox replay,
89
+ * held backfill or transcript-watch. Default resolves from HQ_MESH_MODE /
90
+ * work-mesh config, else "legacy" (contract direct-emit-v1 §6.3).
80
91
  */
81
92
  mode?: MeshEmitMode;
82
93
  /** Injectable transcript fs (tests). */
@@ -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
  }