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