@indigoai-us/hq-cli 5.345.245 → 5.345.247
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.
- package/CHANGELOG.md +91 -0
- package/dist/command-catalog.generated.d.ts +96 -9
- package/dist/command-catalog.generated.js +117 -9
- package/dist/commands/bot.js +1 -1
- package/dist/commands/core-checkpoint-native.d.ts +5 -1
- package/dist/commands/core-checkpoint-native.js +13 -5
- package/dist/commands/deploy-comments.js +139 -0
- package/dist/commands/deploy-list.d.ts +5 -0
- package/dist/commands/deploy-list.js +8 -0
- package/dist/commands/dm.d.ts +4 -1
- package/dist/commands/dm.js +11 -2
- package/dist/commands/files.d.ts +11 -2
- package/dist/commands/files.js +48 -3
- package/dist/commands/install-global.d.ts +15 -0
- package/dist/commands/install-global.js +98 -4
- package/dist/commands/lanes-loop.js +4 -1
- package/dist/commands/lanes.js +16 -5
- package/dist/commands/mcp-registration.d.ts +17 -0
- package/dist/commands/mcp-registration.js +119 -0
- package/dist/commands/mesh.d.ts +2 -0
- package/dist/commands/mesh.js +26 -6
- package/dist/commands/pkg-install.js +1 -1
- package/dist/commands/reindex.js +3 -2
- package/dist/commands/rescue.d.ts +22 -1
- package/dist/commands/rescue.js +56 -9
- package/dist/commands/sources.d.ts +1 -1
- package/dist/commands/sources.js +1 -1
- package/dist/commands/storage.d.ts +15 -2
- package/dist/commands/storage.js +74 -7
- package/dist/hq-cloud-sync-runner/bin/sync-runner.js +232 -225
- package/dist/hq-cloud-sync-runner/package.json +1 -1
- package/dist/lib/agent-kit/mcp/tools.js +22 -0
- package/dist/lib/bot/jobs/hot-signal-sync.js +4 -1
- package/dist/lib/daemon/fleet-members-cache.d.ts +55 -0
- package/dist/lib/daemon/fleet-members-cache.js +266 -0
- package/dist/lib/daemon/handoff.d.ts +4 -0
- package/dist/lib/daemon/handoff.js +2 -1
- package/dist/lib/daemon/hook-requests.d.ts +2 -1
- package/dist/lib/daemon/hook-requests.js +19 -2
- package/dist/lib/daemon/install.d.ts +9 -1
- package/dist/lib/daemon/install.js +11 -2
- package/dist/lib/daemon/ops/policy.d.ts +23 -3
- package/dist/lib/daemon/ops/policy.js +62 -15
- package/dist/lib/daemon/run.js +12 -0
- package/dist/lib/daemon/server.d.ts +5 -0
- package/dist/lib/daemon/server.js +1 -1
- package/dist/lib/daemon/supervisor.d.ts +6 -0
- package/dist/lib/daemon/supervisor.js +31 -2
- package/dist/lib/doctor/checks/antigravity-wiring.d.ts +21 -0
- package/dist/lib/doctor/checks/antigravity-wiring.js +75 -0
- package/dist/lib/doctor/checks/anywhere.js +30 -0
- package/dist/lib/doctor/checks/runtime-probe.js +13 -0
- package/dist/lib/doctor/checks/sync-runtime.js +8 -1
- package/dist/lib/doctor/platform.d.ts +1 -1
- package/dist/lib/doctor/platform.js +5 -0
- package/dist/lib/doctor/registry.js +3 -0
- package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
- package/dist/lib/flag-registry-worker-source.generated.js +1 -1
- package/dist/lib/hook-engine/coverage.d.ts +159 -0
- package/dist/lib/hook-engine/coverage.js +347 -0
- package/dist/lib/hook-engine/native-precompact-compatibility.json +1 -0
- package/dist/lib/hot-channels/signals-pass.d.ts +52 -2
- package/dist/lib/hot-channels/signals-pass.js +65 -3
- package/dist/lib/install/antigravity-targets.d.ts +39 -0
- package/dist/lib/install/antigravity-targets.js +122 -0
- package/dist/lib/install/claude-targets.d.ts +6 -0
- package/dist/lib/install/claude-targets.js +9 -1
- package/dist/lib/lanes/reconcile-result.d.ts +1 -1
- package/dist/lib/lanes/reconcile.js +19 -4
- package/dist/lib/lanes/remote-control-lane.d.ts +6 -0
- package/dist/lib/lanes/remote-control-lane.js +10 -1
- package/dist/lib/lanes/spawn.d.ts +2 -0
- package/dist/lib/lanes/spawn.js +19 -3
- package/dist/lib/lanes/worker-env-scrub.d.ts +48 -0
- package/dist/lib/lanes/worker-env-scrub.js +146 -0
- package/dist/lib/lanes/worker-process.js +4 -1
- package/dist/lib/mesh/client.js +5 -1
- package/dist/lib/mesh/live/daemon/doctor.d.ts +9 -0
- package/dist/lib/mesh/live/daemon/doctor.js +51 -6
- package/dist/lib/mesh/live/daemon/install.d.ts +39 -0
- package/dist/lib/mesh/live/daemon/install.js +70 -0
- package/dist/lib/mesh/live/daemon/outbox-company.d.ts +47 -0
- package/dist/lib/mesh/live/daemon/outbox-company.js +77 -0
- package/dist/lib/mesh/live/daemon/run.d.ts +2 -0
- package/dist/lib/mesh/live/daemon/run.js +48 -3
- package/dist/lib/mesh/live/daemon/state.d.ts +5 -0
- package/dist/lib/mesh/live/daemon/system-unit.d.ts +21 -0
- package/dist/lib/mesh/live/daemon/system-unit.js +80 -0
- package/dist/lib/mesh/live/daemon/transcript-watch.d.ts +4 -1
- package/dist/lib/mesh/live/daemon/transcript-watch.js +42 -38
- package/dist/lib/mesh/live/direct-drain.js +3 -1
- package/dist/lib/mesh/live/emit.js +4 -2
- package/dist/lib/mesh/live/flush.d.ts +61 -0
- package/dist/lib/mesh/live/flush.js +434 -114
- package/dist/lib/mesh/live/paths.d.ts +10 -0
- package/dist/lib/mesh/live/paths.js +14 -0
- package/dist/lib/mesh/live/reporting-privacy.d.ts +41 -1
- package/dist/lib/mesh/live/reporting-privacy.js +81 -7
- package/dist/lib/mesh/live/spool.d.ts +171 -17
- package/dist/lib/mesh/live/spool.js +777 -62
- package/dist/lib/signals/engine.d.ts +82 -2
- package/dist/lib/signals/engine.js +389 -53
- package/dist/lib/signals/steps/extract.js +5 -0
- package/dist/lib/work-context/organize.d.ts +22 -4
- package/dist/lib/work-context/organize.js +50 -21
- package/dist/lib/work-context/paths.d.ts +6 -0
- package/dist/lib/work-context/paths.js +9 -0
- package/dist/lib/work-context/reconcile.d.ts +1 -1
- package/dist/lib/work-context/reconcile.js +1 -1
- package/dist/startup-registration.d.ts +14 -0
- package/dist/startup-registration.js +26 -0
- package/dist/utils/cli-telemetry.d.ts +6 -0
- package/dist/utils/cli-telemetry.js +154 -9
- package/dist/utils/github-tag-fallback.d.ts +7 -2
- package/dist/utils/github-tag-fallback.js +17 -8
- package/dist/utils/hq-core-source.d.ts +31 -0
- package/dist/utils/hq-core-source.js +144 -0
- package/dist/utils/interactive-caller.d.ts +6 -0
- package/dist/utils/interactive-caller.js +8 -0
- package/dist/utils/shipped-codex-hooks.d.ts +6 -4
- package/dist/utils/shipped-codex-hooks.js +22 -10
- package/dist/utils/vault-api.js +1 -0
- package/dist/utils/version-report.d.ts +3 -1
- package/dist/utils/version-report.js +13 -5
- package/docs/anywhere-runtime.md +2 -2
- package/package.json +8 -8
- package/scripts/check-function-manifest.mjs +99 -18
|
@@ -25,7 +25,8 @@ import { LOCAL_ONLY_FIELDS, stripLocalOnlyFields } from "./format-spool-line.js"
|
|
|
25
25
|
import { enrichSessionEndEvent } from "./report-summary.js";
|
|
26
26
|
import { createWorkLocationResolver, withWorkLocation, } from "./work-location.js";
|
|
27
27
|
import { SESSION_EVENTS_BATCH_MAX, WRITABLE_CONTEXT_STATUSES, isSessionOwnerMismatch, parseSessionEventsBatchAck, SESSION_OWNER_MISMATCH, } from "./session-events-client.js";
|
|
28
|
-
import { appendDeadLetterLine,
|
|
28
|
+
import { appendDeadLetterLine, appendDroppedReceipt, appendHeldLinesIfAbsent, appendSpoolLine, claimHeld, claimHeldPath, claimSpoolPath, countDistinctHeldEvents, countJsonlLines, createParkedAppender, createStagedAppender, forEachJsonlLine, forEachJsonlLineYielding, hasPendingFlushWork, JsonlAppender, listOrphanClaims, listOrphanSpoolClaims, removeClaimFile, removeStaleStagingFiles, reofferParkedLines, appendDroppedReceiptOnce, parkedTimesRange, verifiedParkedClaimTimes, segmentsRange, } from "./spool.js";
|
|
29
|
+
import { createHash } from "node:crypto";
|
|
29
30
|
import { workMeshHeldPath, workMeshRoot, workMeshSpoolPath } from "./paths.js";
|
|
30
31
|
/** Bound a replayed session backlog so one flush cannot burst hundreds of events. */
|
|
31
32
|
const SESSION_EVENTS_MAX_PER_SESSION_PER_FLUSH = 25;
|
|
@@ -41,7 +42,100 @@ export const HELD_MAX_LINES = 20_000;
|
|
|
41
42
|
* The catalog itself is also cached inside bind-best.
|
|
42
43
|
*/
|
|
43
44
|
export const PROJECT_REBIND_INTERVAL_MS = 60_000;
|
|
45
|
+
/**
|
|
46
|
+
* Most claimed events one flush keeps in memory to act on. Lines past it go
|
|
47
|
+
* back on the spool as they were, for a later flush, so a claim of any size is
|
|
48
|
+
* read with bounded memory. Far above a normal spool, so ordinary flushes are
|
|
49
|
+
* unchanged.
|
|
50
|
+
*/
|
|
51
|
+
export const FLUSH_MAX_EVENTS_IN_MEMORY = 200_000;
|
|
52
|
+
/**
|
|
53
|
+
* Most bytes of claimed lines one flush keeps in memory to act on, next to
|
|
54
|
+
* the event count: a few very large events reach the heap limit long before
|
|
55
|
+
* 200,000 of them. Lines past it go back on the spool like lines past the
|
|
56
|
+
* count. The first event is always kept, so one oversized line cannot stall
|
|
57
|
+
* the queue.
|
|
58
|
+
*/
|
|
59
|
+
export const FLUSH_MAX_BYTES_IN_MEMORY = 128 * 1024 * 1024;
|
|
60
|
+
/**
|
|
61
|
+
* A line in the parked file (see workMeshParkedPath) is dropped once it was
|
|
62
|
+
* parked longer ago than this, with a dropped receipt and a log line, so the
|
|
63
|
+
* parked file does not grow for ever on a machine that stays off. The age is
|
|
64
|
+
* the time since the line was parked, never the event's own time, and only
|
|
65
|
+
* lines read back from the parked file are dropped: a line read from the
|
|
66
|
+
* spool or a spool claim is parked, never dropped, however old its event.
|
|
67
|
+
*/
|
|
68
|
+
export const PARKED_LINE_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
|
|
69
|
+
/**
|
|
70
|
+
* How far a recorded parked-at time may be ahead of the clock before the
|
|
71
|
+
* clock is taken to be wrong (behind the time lines were parked), in which
|
|
72
|
+
* case nothing is dropped.
|
|
73
|
+
*/
|
|
74
|
+
export const PARKED_CLOCK_SKEW_MS = 5 * 60 * 1000;
|
|
75
|
+
/**
|
|
76
|
+
* Mesh roots that already had their first bound-only flush in this process.
|
|
77
|
+
* That flush parks a backlog of lines that may not be sent even when the spool
|
|
78
|
+
* holds no bound session's event, and re-reads the parked file when its oldest
|
|
79
|
+
* line is past PARKED_LINE_MAX_AGE_MS. Later flushes do neither.
|
|
80
|
+
*/
|
|
81
|
+
const firstBoundOnlyFlushDone = new Set();
|
|
82
|
+
/**
|
|
83
|
+
* The smallest spool the first bound-only flush parks with no bound session's
|
|
84
|
+
* event in it. Below one read chunk, scanning the spool costs little, and the
|
|
85
|
+
* flush leaves it exactly as it is (the usual rule with HQ Anywhere off).
|
|
86
|
+
*/
|
|
87
|
+
export const PARK_BACKLOG_MIN_BYTES = 1024 * 1024;
|
|
88
|
+
/** Test hook: forget which roots had their first bound-only flush. */
|
|
89
|
+
export function resetFirstBoundOnlyFlushes() {
|
|
90
|
+
firstBoundOnlyFlushDone.clear();
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Most distinct eventIds one flush remembers to collapse repeated lines of the
|
|
94
|
+
* same event. Past it, ids already remembered are still collapsed.
|
|
95
|
+
*/
|
|
96
|
+
export const FLUSH_DEDUPE_MAX_IDS = 1_000_000;
|
|
97
|
+
/** onSpoolLinesClaimed receives claimed lines in batches of at most this many. */
|
|
98
|
+
const OBSERVER_BATCH_LINES = 5_000;
|
|
44
99
|
const lastProjectRebindAtMs = new Map();
|
|
100
|
+
function fileSize(file) {
|
|
101
|
+
try {
|
|
102
|
+
return fs.statSync(file).size;
|
|
103
|
+
}
|
|
104
|
+
catch (err) {
|
|
105
|
+
if (err.code === "ENOENT")
|
|
106
|
+
return 0;
|
|
107
|
+
throw err;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* True when the parked file holds a line parked longer ago than
|
|
112
|
+
* PARKED_LINE_MAX_AGE_MS and the clock is not behind any recorded parked-at
|
|
113
|
+
* time. Reads the parked index only.
|
|
114
|
+
*/
|
|
115
|
+
function oldestParkedLineExpired(root, nowMs) {
|
|
116
|
+
const range = parkedTimesRange(root);
|
|
117
|
+
if (!range)
|
|
118
|
+
return false;
|
|
119
|
+
if (range.newestMs > nowMs + PARKED_CLOCK_SKEW_MS)
|
|
120
|
+
return false;
|
|
121
|
+
return nowMs - range.oldestMs > PARKED_LINE_MAX_AGE_MS;
|
|
122
|
+
}
|
|
123
|
+
/** The parked-at time of each non-empty line of a parked claim, in order (null: not known). */
|
|
124
|
+
function parkedAtCursor(segments) {
|
|
125
|
+
let index = 0;
|
|
126
|
+
let used = 0;
|
|
127
|
+
return () => {
|
|
128
|
+
while (segments && index < segments.length && used >= segments[index].lines) {
|
|
129
|
+
index += 1;
|
|
130
|
+
used = 0;
|
|
131
|
+
}
|
|
132
|
+
if (!segments || index >= segments.length)
|
|
133
|
+
return null;
|
|
134
|
+
used += 1;
|
|
135
|
+
return segments[index].parkedAt;
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
const isParkedClaim = (claimPath) => path.basename(claimPath).endsWith(".parked.claimed");
|
|
45
139
|
function parseLine(line) {
|
|
46
140
|
try {
|
|
47
141
|
const v = JSON.parse(line);
|
|
@@ -58,6 +152,29 @@ function sessionIdOf(obj) {
|
|
|
58
152
|
? obj.sessionId.trim()
|
|
59
153
|
: null;
|
|
60
154
|
}
|
|
155
|
+
/** The binding a parked session is recorded with; a change re-offers its lines. */
|
|
156
|
+
function parkedBinding(state, env, root) {
|
|
157
|
+
return hasWorkMeshCompanyBinding(state, env, root) ? `bound:${state.companySlug ?? ""}` : "unbound";
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Orphan claims this flush can open. One it cannot open (other than one that
|
|
161
|
+
* vanished) is logged and left on disk for the next flush.
|
|
162
|
+
*/
|
|
163
|
+
function readableClaims(claimPaths, log) {
|
|
164
|
+
const out = [];
|
|
165
|
+
for (const claimPath of claimPaths) {
|
|
166
|
+
try {
|
|
167
|
+
fs.closeSync(fs.openSync(claimPath, "r"));
|
|
168
|
+
out.push(claimPath);
|
|
169
|
+
}
|
|
170
|
+
catch (err) {
|
|
171
|
+
if (err.code === "ENOENT")
|
|
172
|
+
continue;
|
|
173
|
+
log?.(`work-mesh: kept unreadable claim ${path.basename(claimPath)} for the next flush: ${(err instanceof Error ? err.message : String(err)).slice(0, 120)}`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return out;
|
|
177
|
+
}
|
|
61
178
|
function eventIdOf(obj) {
|
|
62
179
|
return typeof obj.eventId === "string" && obj.eventId.trim()
|
|
63
180
|
? obj.eventId.trim()
|
|
@@ -195,14 +312,11 @@ export async function flushSessionEvents(inputDeps) {
|
|
|
195
312
|
}
|
|
196
313
|
// Events stored before this machine first saw HQ Anywhere off were held
|
|
197
314
|
// back by the member's opt-out. While it stays off they are not sent.
|
|
198
|
-
|
|
315
|
+
let offSinceMs;
|
|
199
316
|
// A recorded time ahead of the clock (a wrong clock when it was written, or
|
|
200
317
|
// an edited file) stops every bound session's events. It is not moved back:
|
|
201
318
|
// that would release what was stored before it whenever a clock is set
|
|
202
319
|
// back. It is said in the log instead, once per process.
|
|
203
|
-
if (boundOnly) {
|
|
204
|
-
logAnywhereOffSinceAhead(inputDeps.workMeshRoot, offSinceMs, (inputDeps.now ?? (() => new Date()))().getTime(), inputDeps.log);
|
|
205
|
-
}
|
|
206
320
|
const bindings = new Map();
|
|
207
321
|
/**
|
|
208
322
|
* The event belongs to a session whose own state holds a verified company
|
|
@@ -210,8 +324,6 @@ export async function flushSessionEvents(inputDeps) {
|
|
|
210
324
|
* seen off.
|
|
211
325
|
*/
|
|
212
326
|
const eventOfBoundSession = (event) => {
|
|
213
|
-
if (boundOnly && !eventDatedSince(event, offSinceMs))
|
|
214
|
-
return false;
|
|
215
327
|
const sessionId = typeof event.sessionId === "string" ? event.sessionId : "";
|
|
216
328
|
if (!sessionId)
|
|
217
329
|
return false;
|
|
@@ -220,25 +332,63 @@ export async function flushSessionEvents(inputDeps) {
|
|
|
220
332
|
state = readSessionState(sessionId, inputDeps.workContextRoot);
|
|
221
333
|
bindings.set(sessionId, state);
|
|
222
334
|
}
|
|
223
|
-
|
|
335
|
+
if (!hasWorkMeshCompanyBinding(state, env, inputDeps.workContextRoot) || !eventMatchesWorkMeshCompany(event, state.companySlug))
|
|
336
|
+
return false;
|
|
337
|
+
if (boundOnly) {
|
|
338
|
+
// Do not create an enforcement marker until the scoped flag confirms on.
|
|
339
|
+
offSinceMs ??= anywhereOffSince(inputDeps.workMeshRoot, inputDeps.now ?? (() => new Date()));
|
|
340
|
+
logAnywhereOffSinceAhead(inputDeps.workMeshRoot, offSinceMs, (inputDeps.now ?? (() => new Date()))().getTime(), inputDeps.log);
|
|
341
|
+
if (!eventDatedSince(event, offSinceMs))
|
|
342
|
+
return false;
|
|
343
|
+
}
|
|
344
|
+
return true;
|
|
224
345
|
};
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
346
|
+
const bindingOf = (sessionId) => {
|
|
347
|
+
let state = bindings.get(sessionId);
|
|
348
|
+
if (state === undefined) {
|
|
349
|
+
state = readSessionState(sessionId, inputDeps.workContextRoot);
|
|
350
|
+
bindings.set(sessionId, state);
|
|
351
|
+
}
|
|
352
|
+
return parkedBinding(state, env, inputDeps.workContextRoot);
|
|
353
|
+
};
|
|
354
|
+
// Parked lines (see workMeshParkedPath) come back as a spool claim: always
|
|
355
|
+
// with HQ Anywhere on, and with it off only when a parked session's company
|
|
356
|
+
// binding is no longer the one recorded when it was parked.
|
|
357
|
+
const parkingAllowed = boundOnly && inputDeps.parkUnbound !== false;
|
|
358
|
+
// The first bound-only flush in this process also offers the parked lines
|
|
359
|
+
// again when the oldest is past PARKED_LINE_MAX_AGE_MS, so expired lines are
|
|
360
|
+
// dropped (see below) even for sessions whose binding never changes.
|
|
361
|
+
const firstBoundOnly = parkingAllowed && !firstBoundOnlyFlushDone.has(inputDeps.workMeshRoot);
|
|
362
|
+
if (parkingAllowed)
|
|
363
|
+
firstBoundOnlyFlushDone.add(inputDeps.workMeshRoot);
|
|
364
|
+
const flushStartMs = (inputDeps.now ?? (() => new Date()))().getTime();
|
|
365
|
+
const expireParked = firstBoundOnly && oldestParkedLineExpired(inputDeps.workMeshRoot, flushStartMs);
|
|
366
|
+
const reoffered = reofferParkedLines(inputDeps.workMeshRoot, `${flushStartMs}`, boundOnly && !expireParked
|
|
367
|
+
? (index) => Object.entries(index.sessions).some(([sessionId, recorded]) => bindingOf(sessionId) !== recorded)
|
|
368
|
+
: null);
|
|
369
|
+
if (reoffered) {
|
|
370
|
+
inputDeps.log?.(`work-mesh: offered parked lines to this flush again (${path.basename(reoffered)})`);
|
|
371
|
+
}
|
|
372
|
+
// Look before claiming. With no bound session's event in the spool and no
|
|
373
|
+
// claim file waiting, nothing is touched at all. A waiting claim (a crashed
|
|
374
|
+
// flush's, or parked lines offered again) is always read, so its lines are
|
|
375
|
+
// sent or parked rather than scanned again by every later flush.
|
|
376
|
+
// The first bound-only flush in this process claims a spool of at least
|
|
377
|
+
// PARK_BACKLOG_MIN_BYTES even when none of its lines can be sent, so a
|
|
378
|
+
// backlog left from before parking is parked once instead of staying on the
|
|
379
|
+
// spool for every later flush to scan.
|
|
380
|
+
if (boundOnly && listOrphanSpoolClaims(inputDeps.workMeshRoot).length === 0) {
|
|
228
381
|
let any = false;
|
|
229
|
-
const
|
|
230
|
-
if (any)
|
|
231
|
-
return;
|
|
382
|
+
const looked = forEachJsonlLineYielding(workMeshSpoolPath(inputDeps.workMeshRoot), (line) => {
|
|
232
383
|
const parsed = parseLine(line);
|
|
233
384
|
if (parsed && eventOfBoundSession(parsed))
|
|
234
385
|
any = true;
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
if (
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
if (!any)
|
|
386
|
+
return !any;
|
|
387
|
+
});
|
|
388
|
+
if (typeof looked !== "boolean")
|
|
389
|
+
await looked;
|
|
390
|
+
const parkBacklog = firstBoundOnly && fileSize(workMeshSpoolPath(inputDeps.workMeshRoot)) >= PARK_BACKLOG_MIN_BYTES;
|
|
391
|
+
if (!any && !parkBacklog)
|
|
242
392
|
return nothingDone("anywhere_off_no_company_session_event");
|
|
243
393
|
}
|
|
244
394
|
// One resolver per flush: git lookups are cached per cwd for this flush only.
|
|
@@ -255,41 +405,32 @@ export async function flushSessionEvents(inputDeps) {
|
|
|
255
405
|
const heldMaxLines = deps.heldMaxLines ?? HELD_MAX_LINES;
|
|
256
406
|
const nowMs = now().getTime();
|
|
257
407
|
const ts = `${nowMs}`;
|
|
408
|
+
const maxEventsInMemory = Math.max(1, deps.maxEventsInMemory ?? FLUSH_MAX_EVENTS_IN_MEMORY);
|
|
409
|
+
const dedupeMaxIds = Math.max(0, deps.dedupeMaxIds ?? FLUSH_DEDUPE_MAX_IDS);
|
|
410
|
+
const maxBytesInMemory = Math.max(1, deps.maxBytesInMemory ?? FLUSH_MAX_BYTES_IN_MEMORY);
|
|
411
|
+
const parkUnbound = parkingAllowed;
|
|
258
412
|
// Bound-only: the live spool and orphaned spool claims are read. Held lines
|
|
259
413
|
// and orphaned held claims wait, as they did, until HQ Anywhere is back on.
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
deps.log?.(`work-mesh: kept unreadable claim ${path.basename(claim.claimPath)} for the next flush: ${claim.error.slice(0, 120)}`);
|
|
265
|
-
}
|
|
266
|
-
const spoolClaim = claimSpool(deps.workMeshRoot, ts);
|
|
414
|
+
// Claims are listed and renamed here, and streamed line by line below: a
|
|
415
|
+
// claim can be far larger than one string or than memory.
|
|
416
|
+
const orphanPaths = readableClaims(boundOnly ? listOrphanSpoolClaims(deps.workMeshRoot) : listOrphanClaims(deps.workMeshRoot), deps.log);
|
|
417
|
+
const spoolClaimPath = claimSpoolPath(deps.workMeshRoot, ts);
|
|
267
418
|
// Throttle held re-attempts; spool (fresh) events still flush every cycle.
|
|
268
419
|
const lastHeldRetryAtMs = deps.lastHeldRetryAtMs ?? 0;
|
|
269
420
|
const shouldClaimHeld = !boundOnly && (heldRetryIntervalMs <= 0 ||
|
|
270
421
|
nowMs - lastHeldRetryAtMs >= heldRetryIntervalMs);
|
|
271
|
-
const
|
|
272
|
-
? claimHeld(deps.workMeshRoot, `${ts}.held`)
|
|
273
|
-
: { claimPath: null, lines: [] };
|
|
422
|
+
const heldClaimPath = shouldClaimHeld ? claimHeldPath(deps.workMeshRoot, `${ts}.held`) : null;
|
|
274
423
|
if (shouldClaimHeld) {
|
|
275
424
|
deps.onHeldClaimed?.(nowMs);
|
|
276
425
|
}
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
deps.log?.(`spool claim observer failed: ${(err instanceof Error ? err.message : String(err)).slice(0, 120)}`);
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
const claimPaths = [
|
|
289
|
-
...orphans.claimPaths,
|
|
290
|
-
spoolClaim.claimPath,
|
|
291
|
-
heldClaim.claimPath,
|
|
292
|
-
].filter((p) => Boolean(p));
|
|
426
|
+
/** Orphans first, then the spool, then held: the order the flush always used. */
|
|
427
|
+
const sources = [
|
|
428
|
+
...orphanPaths.map((claimPath) => ({ claimPath, observe: true })),
|
|
429
|
+
...(spoolClaimPath ? [{ claimPath: spoolClaimPath, observe: true }] : []),
|
|
430
|
+
...(heldClaimPath ? [{ claimPath: heldClaimPath, observe: false }] : []),
|
|
431
|
+
];
|
|
432
|
+
/** Claim files read to the end; only these are removed after the flush. */
|
|
433
|
+
const claimPaths = [];
|
|
293
434
|
const summary = {
|
|
294
435
|
claimed: 0,
|
|
295
436
|
posted: 0,
|
|
@@ -301,58 +442,232 @@ export async function flushSessionEvents(inputDeps) {
|
|
|
301
442
|
heldClaimed: shouldClaimHeld,
|
|
302
443
|
heldOverflow: 0,
|
|
303
444
|
};
|
|
445
|
+
const spoolPath = workMeshSpoolPath(deps.workMeshRoot);
|
|
446
|
+
removeStaleStagingFiles(deps.workMeshRoot, nowMs);
|
|
447
|
+
/**
|
|
448
|
+
* Lines that go back on the spool byte for byte: past the in-memory budget
|
|
449
|
+
* (not acted on this flush), and, bound-only without parking, lines this
|
|
450
|
+
* flush may not act on. Staged while the claims are read and appended to the
|
|
451
|
+
* spool only once every claim was read to the end: a flush that fails
|
|
452
|
+
* partway through the read writes nothing back, so a failure that repeats
|
|
453
|
+
* on every flush cannot grow the queue.
|
|
454
|
+
*/
|
|
455
|
+
const spoolStage = createStagedAppender(deps.workMeshRoot, spoolPath);
|
|
304
456
|
/**
|
|
305
457
|
* Bound-only: claimed lines this flush may not act on (another session's,
|
|
306
458
|
* dated before HQ Anywhere was first seen off, not an event at all). They
|
|
307
|
-
*
|
|
459
|
+
* are parked byte for byte (see workMeshParkedPath), so later flushes do not
|
|
460
|
+
* claim and re-read them, until HQ Anywhere is on or the session's binding
|
|
461
|
+
* changes.
|
|
308
462
|
*/
|
|
309
|
-
const
|
|
463
|
+
const parkedOut = parkUnbound ? createParkedAppender(deps.workMeshRoot, bindingOf) : null;
|
|
464
|
+
/**
|
|
465
|
+
* Parked lines dropped past PARKED_LINE_MAX_AGE_MS, per session ("" for
|
|
466
|
+
* none): how many, and the first and last event ids, so a drop can be
|
|
467
|
+
* traced. `ids` hashes every dropped id in read order for the receipt id.
|
|
468
|
+
*/
|
|
469
|
+
const expiredBySession = new Map();
|
|
470
|
+
const expiredIds = createHash("sha256");
|
|
471
|
+
let expiredOldestParkedMs = Infinity;
|
|
472
|
+
let expiredNewestParkedMs = -Infinity;
|
|
473
|
+
const flushNowIso = now().toISOString();
|
|
474
|
+
const recordExpired = (parsed, eventId, parkedAtMs) => {
|
|
475
|
+
const sessionId = (parsed ? sessionIdOf(unwrapHeld(parsed).event) : null) ?? "";
|
|
476
|
+
const entry = expiredBySession.get(sessionId) ?? { count: 0, firstEventId: null, lastEventId: null, withoutEventId: 0 };
|
|
477
|
+
entry.count += 1;
|
|
478
|
+
if (eventId) {
|
|
479
|
+
entry.firstEventId ??= eventId;
|
|
480
|
+
entry.lastEventId = eventId;
|
|
481
|
+
}
|
|
482
|
+
else {
|
|
483
|
+
entry.withoutEventId += 1;
|
|
484
|
+
}
|
|
485
|
+
expiredBySession.set(sessionId, entry);
|
|
486
|
+
expiredIds.update(`${sessionId}\u0000${eventId ?? ""}\n`);
|
|
487
|
+
expiredOldestParkedMs = Math.min(expiredOldestParkedMs, parkedAtMs);
|
|
488
|
+
expiredNewestParkedMs = Math.max(expiredNewestParkedMs, parkedAtMs);
|
|
489
|
+
};
|
|
490
|
+
/** eventIds seen this flush: a repeated line of the same event is collapsed. */
|
|
491
|
+
const seenEventIds = new Set();
|
|
492
|
+
/** True once every claim was read to the end without a throw. */
|
|
493
|
+
let streamed = false;
|
|
494
|
+
let observed = [];
|
|
495
|
+
const flushObserved = () => {
|
|
496
|
+
if (observed.length === 0 || !deps.onSpoolLinesClaimed)
|
|
497
|
+
return;
|
|
498
|
+
const batch = observed;
|
|
499
|
+
observed = [];
|
|
500
|
+
try {
|
|
501
|
+
deps.onSpoolLinesClaimed(batch);
|
|
502
|
+
}
|
|
503
|
+
catch (err) {
|
|
504
|
+
deps.log?.(`spool claim observer failed: ${(err instanceof Error ? err.message : String(err)).slice(0, 120)}`);
|
|
505
|
+
}
|
|
506
|
+
};
|
|
310
507
|
/** Original events still awaiting disposition (restored on throw). O(1) delete. */
|
|
311
508
|
const pendingRestore = new Set();
|
|
312
509
|
const collected = [];
|
|
510
|
+
/** Bytes of the lines in `collected` (see FLUSH_MAX_BYTES_IN_MEMORY). */
|
|
511
|
+
let collectedBytes = 0;
|
|
512
|
+
const handleClaimedLine = (line, parsed) => {
|
|
513
|
+
summary.claimed += 1;
|
|
514
|
+
if (!parsed) {
|
|
515
|
+
appendDeadLetterLine(deadLetterEnvelope({ raw: line.slice(0, 200) }, "SCHEMA_REJECTED", "parse_error", now().toISOString()), deps.workMeshRoot);
|
|
516
|
+
summary.deadLettered += 1;
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
const { event, heldAt } = unwrapHeld(parsed);
|
|
520
|
+
if (!sessionIdOf(event)) {
|
|
521
|
+
appendDeadLetterLine(deadLetterEnvelope(event, "SCHEMA_REJECTED", "missing_sessionId", now().toISOString()), deps.workMeshRoot);
|
|
522
|
+
summary.deadLettered += 1;
|
|
523
|
+
return;
|
|
524
|
+
}
|
|
525
|
+
// Expire held lines older than 7 days only when local recovery cannot
|
|
526
|
+
// still resolve the session. The daemon backfill runs before startup
|
|
527
|
+
// flush, so retaining these lines gives that deterministic repair a
|
|
528
|
+
// chance rather than silently losing attributable work.
|
|
529
|
+
if (heldAt) {
|
|
530
|
+
const age = now().getTime() - Date.parse(heldAt);
|
|
531
|
+
const state = readSessionState(sessionIdOf(event), deps.workContextRoot);
|
|
532
|
+
if (Number.isFinite(age) &&
|
|
533
|
+
age > HELD_TTL_MS &&
|
|
534
|
+
!isLocallyReconcilableHeldEvent(event, state, deps.workContextRoot)) {
|
|
535
|
+
appendDeadLetterLine(deadLetterEnvelope(event, "HELD_EXPIRED", "held_ttl", now().toISOString()), deps.workMeshRoot);
|
|
536
|
+
summary.deadLettered += 1;
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
// Past the in-memory budget the line is not acted on this flush: it
|
|
541
|
+
// goes back on the spool as it was, for a later flush.
|
|
542
|
+
// What the parsed event keeps in memory: the line without the whitespace
|
|
543
|
+
// around it (a padded line costs no more than its JSON).
|
|
544
|
+
const lineBytes = line.trim().length;
|
|
545
|
+
if (collected.length >= maxEventsInMemory ||
|
|
546
|
+
(collected.length > 0 && collectedBytes + lineBytes > maxBytesInMemory)) {
|
|
547
|
+
spoolStage.push(line);
|
|
548
|
+
summary.restored += 1;
|
|
549
|
+
return;
|
|
550
|
+
}
|
|
551
|
+
collectedBytes += lineBytes;
|
|
552
|
+
pendingRestore.add(event);
|
|
553
|
+
collected.push({ event, heldAt });
|
|
554
|
+
};
|
|
313
555
|
try {
|
|
314
|
-
//
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
556
|
+
// Stream each claim: memory holds at most maxEventsInMemory events plus
|
|
557
|
+
// one read chunk and one write chunk, whatever the size of the claim.
|
|
558
|
+
// A claim over one read chunk is read with the event loop yielding
|
|
559
|
+
// between chunks, so MQTT keepalives and timers keep running.
|
|
560
|
+
for (const source of sources) {
|
|
561
|
+
// Lines read back from the parked file carry the time they were parked
|
|
562
|
+
// (from the claim's sidecar). Only they may be dropped for age, and not
|
|
563
|
+
// when the clock is behind a recorded parked-at time.
|
|
564
|
+
const parkedSource = parkedOut !== null && isParkedClaim(source.claimPath);
|
|
565
|
+
// Only times that still describe the claim (same size, same line
|
|
566
|
+
// count) are used; otherwise every line is of unknown age and kept.
|
|
567
|
+
const segments = parkedSource ? verifiedParkedClaimTimes(source.claimPath) : null;
|
|
568
|
+
const range = segments ? segmentsRange(segments) : null;
|
|
569
|
+
const clockBehind = range !== null && range.newestMs > nowMs + PARKED_CLOCK_SKEW_MS;
|
|
570
|
+
if (clockBehind) {
|
|
571
|
+
deps.log?.(`work-mesh: parked lines were parked at ${new Date(range.newestMs).toISOString()}, after this clock's ${now().toISOString()}; none are dropped for age this flush`);
|
|
572
|
+
}
|
|
573
|
+
const nextParkedAt = parkedAtCursor(segments);
|
|
574
|
+
let parkedAt = null;
|
|
575
|
+
let mayDrop = false;
|
|
576
|
+
const reading = forEachJsonlLineYielding(source.claimPath, (line) => {
|
|
577
|
+
if (!line.trim())
|
|
578
|
+
return;
|
|
579
|
+
parkedAt = nextParkedAt();
|
|
580
|
+
mayDrop = parkedSource && !clockBehind && parkedAt !== null;
|
|
581
|
+
if (source.observe && deps.onSpoolLinesClaimed) {
|
|
582
|
+
observed.push(line);
|
|
583
|
+
if (observed.length >= OBSERVER_BATCH_LINES)
|
|
584
|
+
flushObserved();
|
|
323
585
|
}
|
|
324
|
-
summary.claimed += 1;
|
|
325
586
|
const parsed = parseLine(line);
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
587
|
+
const eventId = parsed ? eventIdOf(unwrapHeld(parsed).event) : null;
|
|
588
|
+
if (eventId) {
|
|
589
|
+
// The same event repeated (a restore that ran twice after a crash):
|
|
590
|
+
// keep the first line only. The server deduplicates by eventId too.
|
|
591
|
+
if (seenEventIds.has(eventId)) {
|
|
592
|
+
summary.duplicates = (summary.duplicates ?? 0) + 1;
|
|
593
|
+
return;
|
|
594
|
+
}
|
|
595
|
+
if (seenEventIds.size < dedupeMaxIds)
|
|
596
|
+
seenEventIds.add(eventId);
|
|
336
597
|
}
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
summary.
|
|
349
|
-
continue;
|
|
598
|
+
if (boundOnly && (!parsed || !eventOfBoundSession(parsed))) {
|
|
599
|
+
const parkedAtMs = parkedAt === null ? Number.NaN : Date.parse(parkedAt);
|
|
600
|
+
if (mayDrop && nowMs - parkedAtMs > PARKED_LINE_MAX_AGE_MS) {
|
|
601
|
+
// Read back from the parked file and parked longer ago than the
|
|
602
|
+
// limit: dropped, with a receipt after the read.
|
|
603
|
+
summary.parkedExpired = (summary.parkedExpired ?? 0) + 1;
|
|
604
|
+
recordExpired(parsed, eventId, parkedAtMs);
|
|
605
|
+
return;
|
|
606
|
+
}
|
|
607
|
+
if (parkedOut) {
|
|
608
|
+
parkedOut.push(line, parsed ? sessionIdOf(parsed) : null, parkedAt ?? flushNowIso);
|
|
609
|
+
summary.parked = (summary.parked ?? 0) + 1;
|
|
350
610
|
}
|
|
611
|
+
else {
|
|
612
|
+
spoolStage.push(line);
|
|
613
|
+
}
|
|
614
|
+
return;
|
|
351
615
|
}
|
|
352
|
-
|
|
353
|
-
|
|
616
|
+
handleClaimedLine(line, parsed);
|
|
617
|
+
});
|
|
618
|
+
const read = typeof reading === "boolean" ? reading : await reading;
|
|
619
|
+
if (read)
|
|
620
|
+
claimPaths.push(source.claimPath);
|
|
621
|
+
else if (fs.existsSync(source.claimPath)) {
|
|
622
|
+
deps.log?.(`work-mesh: kept unreadable claim ${path.basename(source.claimPath)} for the next flush`);
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
flushObserved();
|
|
626
|
+
// Every claim was read. Write the staged lines: the spool's first, then
|
|
627
|
+
// the parked ones. If parking fails, those lines go back on the spool
|
|
628
|
+
// instead (as before parking existed), so nothing stays only in claims
|
|
629
|
+
// that later flushes would read and stage again.
|
|
630
|
+
spoolStage.commit();
|
|
631
|
+
if (parkedOut) {
|
|
632
|
+
try {
|
|
633
|
+
parkedOut.commit();
|
|
634
|
+
}
|
|
635
|
+
catch (err) {
|
|
636
|
+
deps.log?.(`work-mesh: could not park ${parkedOut.count} lines; put them back on the spool: ${(err instanceof Error ? err.message : String(err)).slice(0, 120)}`);
|
|
637
|
+
parkedOut.commitTo(spoolPath);
|
|
638
|
+
summary.parked = 0;
|
|
354
639
|
}
|
|
355
640
|
}
|
|
641
|
+
streamed = true;
|
|
642
|
+
if (expiredBySession.size > 0) {
|
|
643
|
+
const dropped = summary.parkedExpired ?? 0;
|
|
644
|
+
// The same claim read again after a crash drops the same lines and
|
|
645
|
+
// gives the same receipt id, so the receipt is written once.
|
|
646
|
+
const claims = sources.map((source) => path.basename(source.claimPath)).filter((name) => name.endsWith(".parked.claimed")).sort();
|
|
647
|
+
expiredIds.update(claims.join("\n"));
|
|
648
|
+
const receiptId = `parked_max_age_${expiredIds.digest("hex").slice(0, 24)}`;
|
|
649
|
+
const written = appendDroppedReceiptOnce({
|
|
650
|
+
v: 1,
|
|
651
|
+
receiptId,
|
|
652
|
+
dropped,
|
|
653
|
+
reason: "parked_max_age",
|
|
654
|
+
maxAgeDays: Math.round(PARKED_LINE_MAX_AGE_MS / 86_400_000),
|
|
655
|
+
oldestParkedAt: new Date(expiredOldestParkedMs).toISOString(),
|
|
656
|
+
newestParkedAt: new Date(expiredNewestParkedMs).toISOString(),
|
|
657
|
+
claims,
|
|
658
|
+
sessions: [...expiredBySession].map(([sessionId, entry]) => ({
|
|
659
|
+
sessionId: sessionId || null,
|
|
660
|
+
dropped: entry.count,
|
|
661
|
+
firstEventId: entry.firstEventId,
|
|
662
|
+
lastEventId: entry.lastEventId,
|
|
663
|
+
withoutEventId: entry.withoutEventId,
|
|
664
|
+
})),
|
|
665
|
+
at: now().toISOString(),
|
|
666
|
+
}, deps.workMeshRoot);
|
|
667
|
+
deps.log?.(written
|
|
668
|
+
? `work-mesh: dropped ${dropped} parked lines parked more than ${Math.round(PARKED_LINE_MAX_AGE_MS / 86_400_000)} days ago from ${expiredBySession.size} sessions (receipt ${receiptId} in dropped-receipts.jsonl)`
|
|
669
|
+
: `work-mesh: dropped ${dropped} parked lines again after an interrupted flush (receipt ${receiptId} already written)`);
|
|
670
|
+
}
|
|
356
671
|
const bySession = groupBySession(collected);
|
|
357
672
|
const meshDisabled = workMeshSwitchDisabled(env);
|
|
358
673
|
// Older clients acknowledged register operations without copying the
|
|
@@ -362,7 +677,7 @@ export async function flushSessionEvents(inputDeps) {
|
|
|
362
677
|
// Mesh switch is set, or HQ Anywhere is off), the repair is for those
|
|
363
678
|
// sessions alone: it must not write a binding into another session's state.
|
|
364
679
|
const repairFor = boundOnly || meshDisabled
|
|
365
|
-
? [...bySession.keys()].filter(sessionId => hasWorkMeshCompanyBinding(readSessionState(sessionId, deps.workContextRoot)))
|
|
680
|
+
? [...bySession.keys()].filter(sessionId => hasWorkMeshCompanyBinding(readSessionState(sessionId, deps.workContextRoot), env, deps.workContextRoot))
|
|
366
681
|
: [...bySession.keys()];
|
|
367
682
|
repairAckedRegisterStates(deps.workContextRoot, new Set(repairFor), now);
|
|
368
683
|
const markDisposed = (event) => {
|
|
@@ -377,13 +692,13 @@ export async function flushSessionEvents(inputDeps) {
|
|
|
377
692
|
// Bound-only: a session without a verified company binding is not
|
|
378
693
|
// touched. Its events are not sent, held or dropped and its state is
|
|
379
694
|
// not rebound; they go back to the spool (finally block).
|
|
380
|
-
if (boundOnly && !hasWorkMeshCompanyBinding(state))
|
|
695
|
+
if (boundOnly && !hasWorkMeshCompanyBinding(state, env, deps.workContextRoot))
|
|
381
696
|
continue;
|
|
382
697
|
state = applySessionMetaCompanyRebind(sessionId, sessionItems, state, deps, now);
|
|
383
698
|
let items = sessionItems;
|
|
384
699
|
if (boundOnly) {
|
|
385
700
|
const binding = state;
|
|
386
|
-
if (!hasWorkMeshCompanyBinding(binding))
|
|
701
|
+
if (!hasWorkMeshCompanyBinding(binding, env, deps.workContextRoot))
|
|
387
702
|
continue;
|
|
388
703
|
items = sessionItems.filter(item => eventMatchesWorkMeshCompany(item.event, binding.companySlug));
|
|
389
704
|
if (items.length === 0)
|
|
@@ -392,7 +707,7 @@ export async function flushSessionEvents(inputDeps) {
|
|
|
392
707
|
else if (meshDisabled) {
|
|
393
708
|
const binding = state;
|
|
394
709
|
items = sessionItems.filter(item => {
|
|
395
|
-
if (hasWorkMeshCompanyBinding(binding) && eventMatchesWorkMeshCompany(item.event, binding.companySlug))
|
|
710
|
+
if (hasWorkMeshCompanyBinding(binding, env, deps.workContextRoot) && eventMatchesWorkMeshCompany(item.event, binding.companySlug))
|
|
396
711
|
return true;
|
|
397
712
|
summary.dropped += 1;
|
|
398
713
|
markDisposed(item.event);
|
|
@@ -582,35 +897,39 @@ export async function flushSessionEvents(inputDeps) {
|
|
|
582
897
|
}
|
|
583
898
|
}
|
|
584
899
|
finally {
|
|
585
|
-
//
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
900
|
+
// A claim not read to the end still holds every line this flush took from
|
|
901
|
+
// it, so nothing is restored, the staged lines are discarded, and every
|
|
902
|
+
// claim file is kept for the next flush.
|
|
903
|
+
let gaveBack = streamed;
|
|
904
|
+
if (!streamed) {
|
|
589
905
|
try {
|
|
590
|
-
|
|
591
|
-
|
|
906
|
+
spoolStage.discard();
|
|
907
|
+
parkedOut?.discard();
|
|
908
|
+
}
|
|
909
|
+
catch {
|
|
910
|
+
// A staging file left behind is removed by a later flush once stale.
|
|
911
|
+
}
|
|
912
|
+
deps.log?.("work-mesh: a claim could not be read to the end; kept claim files for the next flush");
|
|
913
|
+
}
|
|
914
|
+
else {
|
|
915
|
+
// Crash / throw mid-flush: put unprocessed events back on the spool.
|
|
916
|
+
const restoring = pendingRestore.size;
|
|
917
|
+
try {
|
|
918
|
+
const restoreOut = new JsonlAppender(spoolPath);
|
|
919
|
+
for (const event of pendingRestore) {
|
|
920
|
+
restoreOut.push(JSON.stringify(canonicalizeForRestore(event)));
|
|
921
|
+
}
|
|
922
|
+
restoreOut.flush();
|
|
923
|
+
summary.restored += restoring;
|
|
592
924
|
}
|
|
593
925
|
catch (err) {
|
|
594
|
-
// The claim files still hold
|
|
595
|
-
// orphan claim scan retries
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
restoreError = err instanceof Error ? err.message : String(err);
|
|
926
|
+
// The claim files still hold these events; they are kept below so the
|
|
927
|
+
// orphan claim scan retries them next flush.
|
|
928
|
+
gaveBack = false;
|
|
929
|
+
deps.log?.(`work-mesh: could not put ${restoring} events back on the spool; kept claim files for the next flush: ${(err instanceof Error ? err.message : String(err)).slice(0, 120)}`);
|
|
599
930
|
}
|
|
600
931
|
}
|
|
601
932
|
pendingRestore.clear();
|
|
602
|
-
let gaveBack = restoreFailed === 0;
|
|
603
|
-
if (restoreFailed > 0) {
|
|
604
|
-
deps.log?.(`work-mesh: could not put ${restoreFailed} events back on the spool; kept claim files for the next flush: ${restoreError.slice(0, 120)}`);
|
|
605
|
-
}
|
|
606
|
-
try {
|
|
607
|
-
appendRawSpoolLines(giveBack, deps.workMeshRoot);
|
|
608
|
-
}
|
|
609
|
-
catch (err) {
|
|
610
|
-
// The claim files still hold these lines; the next flush recovers them.
|
|
611
|
-
gaveBack = false;
|
|
612
|
-
deps.log?.(`work-mesh: could not give ${giveBack.length} lines back to the spool; kept claim files for the next flush: ${(err instanceof Error ? err.message : String(err)).slice(0, 120)}`);
|
|
613
|
-
}
|
|
614
933
|
if (gaveBack) {
|
|
615
934
|
for (const p of claimPaths) {
|
|
616
935
|
removeClaimFile(p);
|
|
@@ -726,13 +1045,14 @@ function readHeldEventIds(filePath) {
|
|
|
726
1045
|
if (!fs.existsSync(filePath))
|
|
727
1046
|
return new Set();
|
|
728
1047
|
const ids = new Set();
|
|
729
|
-
|
|
1048
|
+
// Streamed: never one string for the whole file.
|
|
1049
|
+
forEachJsonlLine(filePath, (line) => {
|
|
730
1050
|
if (!line.trim())
|
|
731
|
-
|
|
1051
|
+
return;
|
|
732
1052
|
const id = heldEventIdOfLine(line);
|
|
733
1053
|
if (id)
|
|
734
1054
|
ids.add(id);
|
|
735
|
-
}
|
|
1055
|
+
});
|
|
736
1056
|
return ids;
|
|
737
1057
|
}
|
|
738
1058
|
/**
|