@indigoai-us/hq-cli 5.345.210 → 5.345.211

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 CHANGED
@@ -2,6 +2,14 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [5.345.211] — 2026-11-10
6
+ - `hq integrations connect` now cleans a pasted API key before sending it: it trims the ends and joins a key wrapped across lines. A key with a smart quote or another character that can't be sent stops with a plain message instead of failing on the server.
7
+ - On computers using the new sync engine, its vaults no longer stop and restart every 15 to 60 seconds while another sync runner, such as the HQ desktop app's, holds the sync lock. The engine now runs a vault only when that runner was started after the vault's old-sync switch was turned off and 10 minutes have passed since the switch. If the runner was started before the switch, or the daemon cannot read when it started, the engine waits and says why.
8
+ - A malformed `~/.hq/sync-core/skip.json` no longer puts every skipped vault back on the new sync engine. The daemon keeps the vaults it skipped on its previous run and reports the file error. A missing file still means no vault is skipped.
9
+ - `hq daemon` no longer restarts the sync engine or the sync runner just because the computer was asleep. Time spent asleep used to count toward the heartbeat timeout, so the watchdog fired within seconds of waking, before the engine could report in. After a wake the unit now gets a fresh full window; a unit that stays silent for the timeout while the machine is awake is still restarted as before.
10
+ - The policy hook's fact helper no longer slows to minutes on large tool output. The bundled `trigger-fact-text.awk` it runs on Bash output was quadratic in the output size, so a command that printed 1 MB or more kept the PostToolUse policy hook busy past its 20 s cap and no policy reminder was added; a 5 MB output took minutes. It now runs in linear time: the awk takes about a second for 1 MB and the whole fact helper a few seconds. The native `hq core derive-trigger-facts` tokenizer also stays linear on long runs of file-name characters, on text with many "pull request #N" lines and on text with many private-key header openings, and no longer fails with "Maximum call stack size exceeded" when a large text yields more than about 100,000 facts. Facts, their order and exit codes are unchanged.
11
+ - `hq core work-mesh-bind-trusted` writes its Work Mesh observation file under the HQ root's `workspace/tmp/work-mesh/obs/` instead of the system temp folder, and removes it once the detached `hq mesh context reconcile` that reads it exits (or at once when no `hq` CLI is on PATH). On Windows the old location was the user's Temp folder, where these files piled up. This matches the hq-core change to `core/scripts/work-mesh-live-bind-trusted.sh`.
12
+
5
13
  ## [5.345.210] — 2026-11-09
6
14
 
7
15
  - On a Mac that runs `hq daemon`, HQ Fleet bots no longer get a login item of their own. The daemon starts each bot's gateway as a `fleet-bots:<name>` unit (visible in `hq daemon status`), restarts it after a crash, and keeps a bot stopped with `hq bot stop` until `hq bot start`. Creating or starting a bot no longer makes macOS report that "python" can run in the background. The daemon unloads and deletes the `ai.hq-fleet.gateway-*` LaunchAgents earlier releases installed, so Login Items shows HQ alone; `hq doctor` warns while one is still there. Linux, Windows, and a Mac without `hq daemon` keep the runtime's own service.
@@ -5,9 +5,74 @@ function hq_is_shared_branch(t) {
5
5
  return t ~ /(^|[^a-z0-9_])(main|master|staging|production)([^a-z0-9_]|$)/ || t ~ /release\//
6
6
  }
7
7
 
8
+ # Linear-time tokenizing. A loop of the form
9
+ # while (match(x, re)) { ...; x = substr(x, RSTART + RLENGTH) }
10
+ # copies the rest of x on every match, so it is quadratic in the length of x.
11
+ # Hooks feed this file whole tool outputs as one line (JSON, or text with LF
12
+ # flattened), and a 1 MB line took seconds; 5 MB took minutes. The loops below
13
+ # run on short segments instead. Segments come only from single-character
14
+ # split() calls, which are linear in every awk; regex split() and gsub() are
15
+ # quadratic on long strings in the BWK awk that macOS ships.
16
+
17
+ # hq_segments(s, S): split s into segments that each hold every
18
+ # [a-z0-9_./-] run whole, so a token or file-reference match never crosses a
19
+ # segment boundary. Whitespace-mode split first; then a segment longer than
20
+ # the limit is split on the first separator in the list, and any piece still
21
+ # too long on the next one, and so on. Only long pieces are re-split, so short
22
+ # segments are copied once. No token or file-reference byte is in the list.
23
+ # LF and tab are left out: the whitespace split already removed them, and BWK
24
+ # single-character split() also breaks on LF. hq_segment_limit (-v) only
25
+ # exists so tests can force every re-split level with a tiny limit.
26
+ function hq_segments(s, S, i, m, n, W) {
27
+ hq_seg_lim = hq_segment_limit > 0 ? hq_segment_limit + 0 : 4096
28
+ if (!hq_seg_ns) hq_seg_ns = split("\" \\ , : ; = { } ( ) [ ] < > ' + * & ? ! @ # $ % ^ ~ ` | \r \v \f \036", hq_seg_seps, " ")
29
+ m = split(s, W, " ")
30
+ n = 0
31
+ for (i = 1; i <= m; i++) n = hq_segment_add(W[i], 1, S, n)
32
+ return n
33
+ }
34
+
35
+ # hq_segment_add(p, level, S, n): append p to S[n+1...], split on the
36
+ # separator at this level and deeper while a piece is over the limit.
37
+ function hq_segment_add(p, level, S, n, B, j, k) {
38
+ if (length(p) <= hq_seg_lim || level > hq_seg_ns) {
39
+ S[++n] = p
40
+ return n
41
+ }
42
+ k = split(p, B, hq_seg_seps[level])
43
+ for (j = 1; j <= k; j++) n = hq_segment_add(B[j], level + 1, S, n)
44
+ return n
45
+ }
46
+
47
+ # hq_join(A, n, sep): join A[1..n] with sep, consuming A. Appending one piece
48
+ # at a time copies the whole string once per piece, which is quadratic for
49
+ # many pieces; joining neighbours in pairs copies it once per halving, so the
50
+ # cost is size * log2(n).
51
+ function hq_join(A, n, sep, i, k) {
52
+ if (n == 0) return ""
53
+ while (n > 1) {
54
+ k = 0
55
+ for (i = 1; i <= n; i += 2) {
56
+ if (i < n) A[++k] = A[i] sep A[i + 1]
57
+ else A[++k] = A[i]
58
+ }
59
+ for (i = k + 1; i <= n; i++) delete A[i]
60
+ n = k
61
+ }
62
+ return A[1]
63
+ }
64
+
65
+ function hq_emit_fact(f) {
66
+ if (policy_vocab_cache != "") {
67
+ if (f in vocab) matched = 1
68
+ } else {
69
+ print f
70
+ }
71
+ }
72
+
8
73
  function hq_emit_derived_text_facts(t) {
9
- if (t ~ /(^|[^a-z0-9_])aws_profile/ || t ~ /op:\/\/|\.env([^a-z0-9]|$)/) print "secret"
10
- if (hq_is_shared_branch(t)) print "shared_branch"
74
+ if (t ~ /(^|[^a-z0-9_])aws_profile/ || t ~ /op:\/\/|\.env([^a-z0-9]|$)/) hq_emit_fact("secret")
75
+ if (hq_is_shared_branch(t)) hq_emit_fact("shared_branch")
11
76
  if (t ~ /(^|[^a-z0-9])sk-[a-z0-9]/ \
12
77
  || t ~ /(^|[^a-z0-9])(gh[opsur]_|github_pat_)[a-z0-9_]/ \
13
78
  || t ~ /(^|[^a-z0-9])akia[a-z0-9][a-z0-9]/ \
@@ -15,72 +80,118 @@ function hq_emit_derived_text_facts(t) {
15
80
  || t ~ /(^|[^a-z0-9])glpat-[a-z0-9]/ \
16
81
  || t ~ /-----begin[a-z -]*private key/ \
17
82
  || t ~ /(^|[^a-z0-9])bearer[ ][a-z0-9._-][a-z0-9._-][a-z0-9._-]/) {
18
- print "apikey"
19
- print "secret"
83
+ hq_emit_fact("apikey")
84
+ hq_emit_fact("secret")
20
85
  }
21
86
  if (t ~ /successfully (merged|deployed|pushed|published|created)/ \
22
87
  || t ~ /(deployment|deploy|build|release) (complete|completed|succeeded|ready)/ \
23
88
  || t ~ /merged pull request/ \
24
- || t ~ /pull request #?[0-9]+ .* merged/) print "completed"
89
+ || t ~ /pull request #?[0-9]+ .* merged/) hq_emit_fact("completed")
90
+ }
91
+
92
+ BEGIN {
93
+ if (policy_vocab_cache != "") {
94
+ while ((cache_status = getline cache_line < policy_vocab_cache) > 0) {
95
+ if (index(cache_line, "token=") == 1) vocab[substr(cache_line, 7)] = 1
96
+ }
97
+ close(policy_vocab_cache)
98
+ if (cache_status < 0) cache_error = 1
99
+ }
25
100
  }
26
101
 
27
102
  {
28
- if (NR > 1) text = text "\n"
29
- text = text $0
103
+ hq_lines[++hq_nlines] = $0
30
104
  }
31
105
 
32
106
  END {
107
+ text = hq_join(hq_lines, hq_nlines, "\n")
33
108
  t = tolower(text)
34
109
  if (mode == "derived") {
35
110
  hq_emit_derived_text_facts(t)
36
- if (hq_is_shared_branch(tolower(branch))) print "shared_branch"
111
+ if (hq_is_shared_branch(tolower(branch))) hq_emit_fact("shared_branch")
37
112
  exit
38
113
  }
39
114
  if (mode == "normalize") {
40
- rest = t
41
- while (match(rest, /[^[:space:]]+/)) {
42
- fact = substr(rest, RSTART, RLENGTH)
43
- rest = substr(rest, RSTART + RLENGTH)
44
- if (!seen[fact]++) {
45
- if (out != "") out = out " "
46
- out = out fact
115
+ # Whitespace-mode split removes space, tab and LF; the match loop still
116
+ # runs on each word for any other [:space:] byte (CR, VT, FF).
117
+ nw = split(t, W, " ")
118
+ for (wi = 1; wi <= nw; wi++) {
119
+ rest = W[wi]
120
+ while (match(rest, /[^[:space:]]+/)) {
121
+ fact = substr(rest, RSTART, RLENGTH)
122
+ rest = substr(rest, RSTART + RLENGTH)
123
+ if (!seen[fact]++) OUT[++nout] = fact
47
124
  }
48
125
  }
49
- if (hq_is_shared_branch(tolower(branch)) && !seen["shared_branch"]++) {
50
- if (out != "") out = out " "
51
- out = out "shared_branch"
52
- }
53
- printf "%s", out
126
+ if (hq_is_shared_branch(tolower(branch)) && !seen["shared_branch"]++) OUT[++nout] = "shared_branch"
127
+ printf "%s", hq_join(OUT, nout, " ")
54
128
  exit
55
129
  }
56
130
 
57
131
  # Open tokenization: every word token in the text becomes a fact. Tokens are
58
132
  # letter-led and length >= 2; underscores and internal hyphens are retained.
59
- tw = t
60
- while (match(tw, /[a-z][a-z0-9_-]+/)) {
61
- print substr(tw, RSTART, RLENGTH)
62
- tw = substr(tw, RSTART + RLENGTH)
133
+ nseg = hq_segments(t, SEG)
134
+ for (si = 1; si <= nseg; si++) {
135
+ # A token holds no "." or "/", so split on them too: each piece then holds
136
+ # at most one token, because a token runs to the end of its piece.
137
+ np = split(SEG[si], P, ".")
138
+ for (pi = 1; pi <= np; pi++) {
139
+ nq = split(P[pi], Q, "/")
140
+ for (qi = 1; qi <= nq; qi++) {
141
+ tw = Q[qi]
142
+ while (match(tw, /[a-z][a-z0-9_-]+/)) {
143
+ hq_emit_fact(substr(tw, RSTART, RLENGTH))
144
+ tw = substr(tw, RSTART + RLENGTH)
145
+ }
146
+ }
147
+ }
63
148
  }
149
+ # Prefilter mode only needs to know whether any fact is in the vocabulary.
150
+ # The final exit below returns the same status for this case.
151
+ if (policy_vocab_cache != "" && matched && !cache_error) exit 0
64
152
  hq_emit_derived_text_facts(t)
65
153
 
66
- # File references emit their basename and extension as facts.
67
- tmp = t
68
- while (match(tmp, "\\.?[a-z0-9_][a-z0-9_./-]*\\.[a-z][a-z0-9]+")) {
69
- fn = substr(tmp, RSTART, RLENGTH)
70
- tmp = substr(tmp, RSTART + RLENGTH)
71
- bn = fn
72
- sub(/.*\//, "", bn)
73
- ext = bn
74
- sub(/.*\./, "", ext)
75
- print "." ext
76
- print bn
154
+ # File references emit their basename and extension as facts. A reference
155
+ # ends in "." then a letter then [a-z0-9], so the cheap literal check stops
156
+ # the loop once the rest of a segment cannot hold one (a failed match of
157
+ # the full pattern costs the square of a long run in BWK awk). The basename
158
+ # is the last "/" piece and the extension the last "." piece: the same
159
+ # strings sub(/.*\//) and sub(/.*\./) leave, without their quadratic cost.
160
+ for (si = 1; si <= nseg; si++) {
161
+ tmp = SEG[si]
162
+ while (match(tmp, /\.[a-z][a-z0-9]/) \
163
+ && match(tmp, "\\.?[a-z0-9_][a-z0-9_./-]*\\.[a-z][a-z0-9]+")) {
164
+ fn = substr(tmp, RSTART, RLENGTH)
165
+ tmp = substr(tmp, RSTART + RLENGTH)
166
+ nb = split(fn, FB, "/")
167
+ bn = FB[nb]
168
+ ne = split(bn, FE, ".")
169
+ ext = FE[ne]
170
+ hq_emit_fact("." ext)
171
+ hq_emit_fact(bn)
172
+ }
77
173
  }
78
174
 
79
- # Slash-command mentions emit /command facts; paths such as repos/public do not.
80
- tmp2 = " " t
81
- while (match(tmp2, " /[a-z][a-z0-9-]*")) {
82
- sc = substr(tmp2, RSTART + 1, RLENGTH - 1)
83
- tmp2 = substr(tmp2, RSTART + RLENGTH)
84
- print sc
175
+ # Slash-command mentions emit /command facts; paths such as repos/public do
176
+ # not. A fact is " /" then [a-z][a-z0-9-]*, where the space is a real space
177
+ # (not LF or tab), and line 1 counts as preceded by one. Per line (BWK
178
+ # single-character split() also breaks on LF), split on "/": every piece
179
+ # after the first follows a slash, and the previous piece's last byte says
180
+ # whether a space came before that slash.
181
+ nl = split(t, L, "\n")
182
+ for (li = 1; li <= nl; li++) {
183
+ np = split((li == 1 ? " " : "") L[li], P, "/")
184
+ for (pi = 2; pi <= np; pi++) {
185
+ if (substr(P[pi - 1], length(P[pi - 1])) != " ") continue
186
+ # Match on a bounded head so a long piece costs little; re-match the
187
+ # whole piece only when the name fills the head.
188
+ head = substr(P[pi], 1, 256)
189
+ if (match(head, /^[a-z][a-z0-9-]*/)) {
190
+ if (RLENGTH == 256) match(P[pi], /^[a-z][a-z0-9-]*/)
191
+ hq_emit_fact("/" substr(P[pi], 1, RLENGTH))
192
+ }
193
+ }
85
194
  }
195
+ if (hq_is_shared_branch(tolower(branch))) hq_emit_fact("shared_branch")
196
+ if (policy_vocab_cache != "") exit cache_error ? 2 : (matched ? 0 : 1)
86
197
  }
@@ -17,6 +17,7 @@ export type DeriveTriggerRunResult = {
17
17
  };
18
18
  export declare function resolveWindowsFilesystemPath(candidate: string, cwd: string, resolveRealpath?: (value: string) => string, isDirectory?: (value: string) => boolean): string | undefined;
19
19
  export declare function commandOnPath(command: string, env: Record<string, string | undefined>, platform?: NodeJS.Platform): boolean;
20
+ export declare function matchTextFacts(rawText: string, env: Record<string, string | undefined>): string[];
20
21
  /** Run the native handler contract, retaining exact bytes for differential tests. */
21
22
  export declare function runDeriveTriggerFacts(options: DeriveTriggerRunOptions): DeriveTriggerRunResult;
22
23
  export declare function runDeriveTriggerFactsFast(argv: readonly string[], stdin: string, cwd: string, hqRoot: string | undefined): number;
@@ -271,7 +271,52 @@ function emptyPayload() {
271
271
  cwd: "", sessionId: "", transcriptPath: "",
272
272
  };
273
273
  }
274
- function matchTextFacts(rawText, env) {
274
+ // `pull request #?[0-9]+ [\s\S]* merged`, without the backtracking regex: V8
275
+ // retries `[\s\S]*` to the end of the text from every "pull request <n> ", so
276
+ // an output with many of them cost size times count. The earliest prefix
277
+ // leaves the most text for " merged", so it alone decides the match.
278
+ function pullRequestMerged(text) {
279
+ const prefix = /pull request #?[0-9]+ /.exec(text);
280
+ return prefix !== null && text.includes(" merged", prefix.index + prefix[0].length);
281
+ }
282
+ // `-----begin[a-z -]*private key`, without the backtracking regex: V8 rescans
283
+ // the [a-z -] run after every "-----begin" in it. Every "-----begin" in one
284
+ // run can reach the same bytes, so only the first in each run is checked.
285
+ function pemPrivateKeyHeader(text) {
286
+ const outsideRun = /[^a-z -]/g;
287
+ let from = 0;
288
+ for (;;) {
289
+ const start = text.indexOf("-----begin", from);
290
+ if (start < 0)
291
+ return false;
292
+ const body = start + "-----begin".length;
293
+ outsideRun.lastIndex = body;
294
+ const end = outsideRun.exec(text)?.index ?? text.length;
295
+ if (text.slice(body, end).includes("private key"))
296
+ return true;
297
+ from = end;
298
+ }
299
+ }
300
+ // File references, as `text.matchAll(/\.?[a-z0-9_][a-z0-9_./-]*\.[a-z][a-z0-9]+/g)`
301
+ // would find them. A reference holds only [a-z0-9_./-] bytes, so each run of
302
+ // those bytes is scanned on its own, and only up to the end of its last
303
+ // `.<letter><alnum>` extension: no match can end later. Without that cut, V8
304
+ // retries the pattern from every start in a long run with no extension (a hex
305
+ // blob, say) to the end of the run, which is quadratic in the run's length.
306
+ function fileReferences(text) {
307
+ const references = [];
308
+ for (const run of text.matchAll(/[a-z0-9_./-]+/g)) {
309
+ let end = 0;
310
+ for (const extension of run[0].matchAll(/\.[a-z][a-z0-9]+/g))
311
+ end = extension.index + extension[0].length;
312
+ if (end === 0)
313
+ continue;
314
+ for (const match of run[0].slice(0, end).matchAll(/\.?[a-z0-9_][a-z0-9_./-]*\.[a-z][a-z0-9]+/g))
315
+ references.push(match[0]);
316
+ }
317
+ return references;
318
+ }
319
+ export function matchTextFacts(rawText, env) {
275
320
  const text = localeLower(rawText, env);
276
321
  const facts = [];
277
322
  const words = /[a-z][a-z0-9_-]+/g;
@@ -288,19 +333,18 @@ function matchTextFacts(rawText, env) {
288
333
  /(^|[^a-z0-9])akia[a-z0-9][a-z0-9]/.test(text) ||
289
334
  /(^|[^a-z0-9])xox[bpsa]-[a-z0-9]/.test(text) ||
290
335
  /(^|[^a-z0-9])glpat-[a-z0-9]/.test(text) ||
291
- /-----begin[a-z -]*private key/.test(text) ||
336
+ pemPrivateKeyHeader(text) ||
292
337
  /(^|[^a-z0-9])bearer [a-z0-9._-][a-z0-9._-][a-z0-9._-]/.test(text)) {
293
338
  facts.push("apikey", "secret");
294
339
  }
295
340
  if (/successfully (merged|deployed|pushed|published|created)/.test(text) ||
296
341
  /(deployment|deploy|build|release) (complete|completed|succeeded|ready)/.test(text) ||
297
342
  /merged pull request/.test(text) ||
298
- /pull request #?[0-9]+ [\s\S]* merged/.test(text)) {
343
+ pullRequestMerged(text)) {
299
344
  facts.push("completed");
300
345
  }
301
- const filenames = /\.?[a-z0-9_][a-z0-9_./-]*\.[a-z][a-z0-9]+/g;
302
- for (const match of text.matchAll(filenames)) {
303
- const filename = match[0].slice(match[0].lastIndexOf("/") + 1);
346
+ for (const reference of fileReferences(text)) {
347
+ const filename = reference.slice(reference.lastIndexOf("/") + 1);
304
348
  const dot = filename.lastIndexOf(".");
305
349
  facts.push(`.${filename.slice(dot + 1)}`, filename);
306
350
  }
@@ -310,6 +354,12 @@ function matchTextFacts(rawText, env) {
310
354
  }
311
355
  return facts;
312
356
  }
357
+ // Appends one by one: `facts.push(...list)` passes every fact as an argument
358
+ // and overflows the call stack once a large text yields ~100k facts.
359
+ function pushTextFacts(facts, text, env) {
360
+ for (const fact of matchTextFacts(text, env))
361
+ facts.push(fact);
362
+ }
313
363
  function isSharedBranch(branch, env) {
314
364
  const value = localeLower(branch, env);
315
365
  return /(^|[^a-z0-9_])(main|master|staging|production)([^a-z0-9_]|$)/.test(value) || /release\//.test(value);
@@ -481,22 +531,22 @@ function computeOutput(options) {
481
531
  if (kind === "PreToolUse" || kind === "PostToolUse") {
482
532
  if (payload.tool === "Bash") {
483
533
  if (kind === "PreToolUse") {
484
- facts.push(...matchTextFacts(payload.command, env));
534
+ pushTextFacts(facts, payload.command, env);
485
535
  if (payload.runInBackground === "true")
486
536
  facts.push("run_in_background");
487
537
  }
488
538
  else
489
- facts.push(...matchTextFacts(payload.toolResponse, env));
539
+ pushTextFacts(facts, payload.toolResponse, env);
490
540
  }
491
541
  else if (payload.tool !== "") {
492
542
  if (kind === "PreToolUse")
493
543
  facts.push(localeLower(payload.tool, env));
494
544
  else
495
- facts.push(...matchTextFacts(payload.toolResponse, env));
545
+ pushTextFacts(facts, payload.toolResponse, env);
496
546
  }
497
547
  }
498
548
  else if (kind === "UserPromptSubmit") {
499
- facts.push(...matchTextFacts(payload.prompt, env));
549
+ pushTextFacts(facts, payload.prompt, env);
500
550
  }
501
551
  if (company)
502
552
  facts.push("company");
@@ -506,7 +556,7 @@ function computeOutput(options) {
506
556
  if (fs.statSync(payload.transcriptPath).isFile()) {
507
557
  const lookback = transcriptAssistantText(payload.transcriptPath);
508
558
  if (lookback)
509
- facts.push(...matchTextFacts(lookback, env));
559
+ pushTextFacts(facts, lookback, env);
510
560
  }
511
561
  }
512
562
  catch (error) {
@@ -21,9 +21,9 @@ export type WorkMeshBindDeps = {
21
21
  stdout: string;
22
22
  stderr: string;
23
23
  };
24
- spawnHq: (args: string[], env: NodeJS.ProcessEnv) => void;
24
+ /** Starts `hq <args>` detached; removes `removeAfterExit` once that process exits. */
25
+ spawnHq: (args: string[], env: NodeJS.ProcessEnv, removeAfterExit?: string) => void;
25
26
  pid: number;
26
- tmpDir: string;
27
27
  ulid: (now: Date) => string;
28
28
  };
29
29
  export declare const createWorkMeshBindDeps: (root: string, cwd: string, env: NodeJS.ProcessEnv, now: () => Date, daemonWarningEnabled?: boolean) => WorkMeshBindDeps;
@@ -33,6 +33,10 @@ type DetachedSpawnOptions = {
33
33
  env: NodeJS.ProcessEnv;
34
34
  platform?: NodeJS.Platform;
35
35
  existsSync?: (candidate: string) => boolean;
36
+ /** File to delete after the hq process exits (the observation it reads). */
37
+ removeAfterExit?: string;
38
+ /** Node binary for the wait-then-remove wrapper; defaults to process.execPath. */
39
+ execPath?: string;
36
40
  spawnProcess?: (command: string, args: string[], options: {
37
41
  cwd: string;
38
42
  env: NodeJS.ProcessEnv;
@@ -40,10 +44,18 @@ type DetachedSpawnOptions = {
40
44
  stdio: "ignore";
41
45
  shell: boolean;
42
46
  windowsVerbatimArguments?: boolean;
47
+ windowsHide?: boolean;
43
48
  }) => {
44
49
  unref: () => void;
50
+ on?: (event: "error", listener: () => void) => unknown;
45
51
  };
46
52
  };
53
+ /**
54
+ * Detached wrapper: runs the planned hq command, waits for it to exit, then
55
+ * removes the observation file it read. Mirrors the shell script's
56
+ * `nohup bash -c '"$1" mesh context reconcile ...; rm -f -- "$2"'`.
57
+ */
58
+ export declare const WORK_MESH_RECONCILE_REMOVE_WRAPPER: string;
47
59
  export declare function spawnWorkMeshHqDetached(args: string[], options: DetachedSpawnOptions): void;
48
60
  /**
49
61
  * Resolve the bind session. Only a session id the caller owns (the process env)
@@ -19,7 +19,7 @@ ROOT="\${HQ_ROOT:-\${CLAUDE_PROJECT_DIR:-}}"
19
19
  if [ -z "$ROOT" ]; then
20
20
  `;
21
21
  export const createWorkMeshBindDeps = (root, cwd, env, now, daemonWarningEnabled = false) => ({
22
- root, cwd, env, now, fs, pid: process.pid, tmpDir: env.TMPDIR || "/tmp", ulid: (date) => generateUlid(date.getTime()),
22
+ root, cwd, env, now, fs, pid: process.pid, ulid: (date) => generateUlid(date.getTime()),
23
23
  daemonWarningEnabled: daemonWarningEnabled
24
24
  && Boolean(env.HQ_FLAGS_API_URL?.trim())
25
25
  && /^cmp_[A-Za-z0-9]{3,128}$/.test(env.HQ_COMPANY_UID?.trim() ?? ""),
@@ -50,12 +50,26 @@ export const createWorkMeshBindDeps = (root, cwd, env, now, daemonWarningEnabled
50
50
  const result = spawnSync("bash", [path.join(scriptRoot, "core/scripts/hq-session.sh"), ...args], { cwd, env: childEnv, encoding: "utf8" });
51
51
  return { code: result.status ?? 127, stdout: result.stdout ?? "", stderr: result.stderr ?? (result.error ? `${result.error.message}\n` : "") };
52
52
  },
53
- spawnHq: (args, childEnv) => spawnWorkMeshHqDetached(args, {
53
+ spawnHq: (args, childEnv, removeAfterExit) => spawnWorkMeshHqDetached(args, {
54
54
  cwd,
55
55
  root,
56
56
  env: childEnv,
57
+ ...(removeAfterExit ? { removeAfterExit } : {}),
57
58
  }),
58
59
  });
60
+ /**
61
+ * Detached wrapper: runs the planned hq command, waits for it to exit, then
62
+ * removes the observation file it read. Mirrors the shell script's
63
+ * `nohup bash -c '"$1" mesh context reconcile ...; rm -f -- "$2"'`.
64
+ */
65
+ export const WORK_MESH_RECONCILE_REMOVE_WRAPPER = [
66
+ "const cp=require('node:child_process'),fs=require('node:fs');",
67
+ "const [spec,file]=process.argv.slice(1);",
68
+ "let done=false;const remove=()=>{if(done)return;done=true;try{fs.rmSync(file,{force:true})}catch{}};",
69
+ "try{const p=JSON.parse(spec);",
70
+ "const child=cp.spawn(p.cmd,p.args,{cwd:p.cwd,env:process.env,stdio:'ignore',shell:p.shell,windowsHide:true,windowsVerbatimArguments:p.windowsVerbatimArguments===true});",
71
+ "child.on('error',remove);child.on('exit',remove)}catch{remove()}",
72
+ ].join("");
59
73
  export function spawnWorkMeshHqDetached(args, options) {
60
74
  const platform = options.platform ?? process.platform;
61
75
  const childEnv = { ...options.env, HQ_ROOT: options.root };
@@ -63,6 +77,28 @@ export function spawnWorkMeshHqDetached(args, options) {
63
77
  ? resolveWindowsExecutable("hq", childEnv, options.existsSync ?? fs.existsSync, options.cwd) ?? "hq"
64
78
  : "hq";
65
79
  const plan = planResolvedCommandSpawn(executable, args, childEnv, platform);
80
+ if (options.removeAfterExit) {
81
+ const spec = JSON.stringify({
82
+ cmd: plan.cmd,
83
+ args: plan.args,
84
+ cwd: options.cwd,
85
+ shell: plan.shell,
86
+ windowsVerbatimArguments: plan.windowsVerbatimArguments === true,
87
+ });
88
+ const wrapper = (options.spawnProcess ?? spawn)(options.execPath ?? process.execPath, ["--input-type=commonjs", "-e", WORK_MESH_RECONCILE_REMOVE_WRAPPER, spec, options.removeAfterExit], {
89
+ cwd: options.cwd,
90
+ env: childEnv,
91
+ detached: true,
92
+ stdio: "ignore",
93
+ shell: false,
94
+ windowsHide: true,
95
+ });
96
+ // A failed wrapper start must not throw in this process; the SessionStart
97
+ // hook's age sweep removes the observation it leaves.
98
+ wrapper.on?.("error", () => { });
99
+ wrapper.unref();
100
+ return;
101
+ }
66
102
  const child = (options.spawnProcess ?? spawn)(plan.cmd, plan.args, {
67
103
  cwd: options.cwd,
68
104
  env: childEnv,
@@ -216,12 +252,21 @@ export function runWorkMeshBindTrusted(args, deps) {
216
252
  trusted.authority = "trusted";
217
253
  observation.trustedContext = trusted;
218
254
  }
219
- const directory = path.join(deps.tmpDir, "hq-work-mesh-obs");
255
+ // Observations live under the HQ root's workspace/, not the system temp
256
+ // folder (on Windows that is the user's Temp, which nothing cleans). The
257
+ // SessionStart hook's age sweep removes any that a crashed run leaves.
258
+ const scratchRoot = path.join(root, "workspace", "tmp", "work-mesh");
259
+ const directory = path.join(scratchRoot, "obs");
220
260
  try {
221
- deps.fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
222
- deps.fs.chmodSync(directory, 0o700);
261
+ deps.fs.mkdirSync(directory, { recursive: true });
262
+ }
263
+ catch { /* legacy mkdir -p is best effort */ }
264
+ for (const folder of [scratchRoot, directory]) {
265
+ try {
266
+ deps.fs.chmodSync(folder, 0o700);
267
+ }
268
+ catch { /* legacy chmod is best effort */ }
223
269
  }
224
- catch { /* legacy mkdir/chmod are best effort */ }
225
270
  const observationFile = path.join(directory, `${sid}.bind.${deps.pid}.json`);
226
271
  try {
227
272
  deps.fs.writeFileSync(observationFile, `${workMeshObservationJson(observation)}\n`);
@@ -250,8 +295,17 @@ export function runWorkMeshBindTrusted(args, deps) {
250
295
  catch { /* the shell's jq test fails quiet on invalid status JSON */ }
251
296
  }
252
297
  }
253
- if (hasExecutable(deps, "hq") && deps.fs.existsSync(observationFile)) {
254
- deps.spawnHq(["mesh", "context", "reconcile", "--observation-file", observationFile, "--machine"], childEnv);
298
+ if (!hasExecutable(deps, "hq")) {
299
+ // No reader: the observation would never be consumed.
300
+ try {
301
+ deps.fs.rmSync(observationFile, { force: true });
302
+ }
303
+ catch { /* legacy rm -f is best effort */ }
304
+ stderr += "Work Mesh reconcile skipped: hq CLI not found on PATH.\n";
305
+ return { code: 0, stdout: output.join(""), stderr };
306
+ }
307
+ if (deps.fs.existsSync(observationFile)) {
308
+ deps.spawnHq(["mesh", "context", "reconcile", "--observation-file", observationFile, "--machine"], childEnv, observationFile);
255
309
  }
256
310
  return { code: 0, stdout: output.join(""), stderr };
257
311
  }
@@ -69,6 +69,22 @@ export declare function assertAuthMode(value: string | undefined): void;
69
69
  export declare function assertAuthHeader(value: string | undefined): void;
70
70
  /** Single-quote a value for a copy-pasteable shell command. */
71
71
  export declare function shellQuote(value: string): string;
72
+ /**
73
+ * Resolve the API key for a key-authenticated app, in descending order of how
74
+ * safe the source is: piped stdin, a hidden prompt, then the explicit
75
+ * `--token` flag. Refuses rather than connecting credential-less when there is
76
+ * nobody to ask.
77
+ */
78
+ /**
79
+ * HQ-PRO-5QF: a key pasted from a doc or chat often arrives wrapped across
80
+ * lines or with a tab, and sometimes with smart quotes. hq-pro sends the key
81
+ * in an HTTP header, which can't carry those characters. Trim the ends, drop
82
+ * inner line breaks and tabs, and refuse anything else outside visible ASCII
83
+ * (an inner space is left for hq-pro to judge, since HTTP Basic allows it).
84
+ * The message never echoes the key.
85
+ */
86
+ export declare const API_KEY_UNSENDABLE_MESSAGE = "The key contains a character that can't be sent. Copy it again and paste only the key.";
87
+ export declare function normalizePastedApiKey(raw: string): string;
72
88
  /** Everything the connect verbs need to name one app to hq-pro. */
73
89
  interface ConnectTarget {
74
90
  /** Install/OAuth identity fields, exactly as hq-pro expects them. */
@@ -308,9 +308,25 @@ function promptForKey(label) {
308
308
  * `--token` flag. Refuses rather than connecting credential-less when there is
309
309
  * nobody to ask.
310
310
  */
311
+ /**
312
+ * HQ-PRO-5QF: a key pasted from a doc or chat often arrives wrapped across
313
+ * lines or with a tab, and sometimes with smart quotes. hq-pro sends the key
314
+ * in an HTTP header, which can't carry those characters. Trim the ends, drop
315
+ * inner line breaks and tabs, and refuse anything else outside visible ASCII
316
+ * (an inner space is left for hq-pro to judge, since HTTP Basic allows it).
317
+ * The message never echoes the key.
318
+ */
319
+ export const API_KEY_UNSENDABLE_MESSAGE = "The key contains a character that can't be sent. Copy it again and paste only the key.";
320
+ export function normalizePastedApiKey(raw) {
321
+ const cleaned = raw.trim().replace(/[\r\n\t]+/g, "");
322
+ if (!/^[\x20-\x7e]*$/.test(cleaned)) {
323
+ throw new IntegrationsCliError(API_KEY_UNSENDABLE_MESSAGE, { expected: true });
324
+ }
325
+ return cleaned;
326
+ }
311
327
  async function resolveKey(opts, appLabel) {
312
328
  if (opts.tokenStdin) {
313
- const piped = (await readStdin()).trim();
329
+ const piped = normalizePastedApiKey(await readStdin());
314
330
  if (!piped) {
315
331
  throw new IntegrationsCliError("--token-stdin was set but stdin was empty.", {
316
332
  expected: true,
@@ -318,10 +334,13 @@ async function resolveKey(opts, appLabel) {
318
334
  }
319
335
  return piped;
320
336
  }
321
- if (opts.token)
322
- return opts.token;
337
+ if (opts.token) {
338
+ const flagged = normalizePastedApiKey(opts.token);
339
+ if (flagged)
340
+ return flagged;
341
+ }
323
342
  if (process.stdin.isTTY) {
324
- const value = (await promptForKey(`API key for ${appLabel}`)).trim();
343
+ const value = normalizePastedApiKey(await promptForKey(`API key for ${appLabel}`));
325
344
  if (!value) {
326
345
  throw new IntegrationsCliError("No API key entered — nothing was connected.", {
327
346
  expected: true,
@@ -127,6 +127,14 @@ export declare const SYNC_CORE_SELFCHECK_UNIT = "sync-core-selfcheck";
127
127
  export declare const SYNC_CORE_SELFCHECK_INTERVAL_SEC = 3600;
128
128
  export declare const SYNC_CORE_MANIFEST_INTERVAL_SEC: number;
129
129
  export declare const SYNC_CORE_LEGACY_SETTLE_MS: number;
130
+ export type LegacySyncHolder = {
131
+ status: "started";
132
+ startedAt: number;
133
+ } | {
134
+ status: "missing";
135
+ } | {
136
+ status: "unreadable";
137
+ };
130
138
  export interface PlanContext {
131
139
  machineType: MachineType;
132
140
  platform: NodeJS.Platform;
@@ -157,6 +165,7 @@ export interface PlanContext {
157
165
  syncCoreVaults?: readonly SyncCoreVaultPlan[];
158
166
  syncCoreRunning?: SyncCoreRunning;
159
167
  legacySyncReadyForCore?: boolean;
168
+ legacySyncHolder?: LegacySyncHolder;
160
169
  now?: number;
161
170
  /** A legacy desktop app or sync unit is still managing sync. */
162
171
  desktopAppManagesSync: boolean;
@@ -241,9 +241,20 @@ function planService(service, ctx) {
241
241
  : ctx.vaultSync?.offCompanies.has(vault.slug ?? "") === true;
242
242
  const offSince = vault.legacyOffSince ? Date.parse(vault.legacyOffSince) : Number.NaN;
243
243
  const settled = Number.isFinite(offSince) && now - offSince >= SYNC_CORE_LEGACY_SETTLE_MS;
244
- const settleNeeded = ctx.desktopAppManagesSync && !daemonAloneRunsLegacySync(ctx);
244
+ const settleNeeded = ctx.legacySyncHolder !== undefined
245
+ || (ctx.desktopAppManagesSync && !daemonAloneRunsLegacySync(ctx));
245
246
  const legacyReady = ctx.legacySyncReadyForCore === true && (!settleNeeded || settled);
246
247
  const what = vault.kind === "personal" ? "the personal vault" : `the ${vault.slug} vault`;
248
+ const holder = ctx.legacySyncHolder;
249
+ const holderBlock = holder === undefined
250
+ ? undefined
251
+ : holder.status === "missing"
252
+ ? "waiting for the current sync to take the sync lock again (the runner that held it has exited)"
253
+ : holder.status === "unreadable"
254
+ ? "waiting to learn when the sync that holds the sync lock started (its owner status could not be read)"
255
+ : !Number.isFinite(offSince) || holder.startedAt < offSince
256
+ ? `waiting for the running sync (started before the switch was turned off for ${what}) to restart`
257
+ : undefined;
247
258
  return base(service, {
248
259
  id: syncCoreUnitId(vault.uid),
249
260
  description: full
@@ -266,6 +277,7 @@ function planService(service, ctx) {
266
277
  [!ctx.signedIn, NOT_SIGNED_IN],
267
278
  [!!vault.blockedReason, vault.blockedReason ?? ""],
268
279
  [full && !legacyOff, `waiting for the current sync to be turned off for ${what}`],
280
+ [full && !!holderBlock, holderBlock ?? ""],
269
281
  [full && !legacyReady, ctx.legacySyncReadyForCore !== true
270
282
  ? "waiting for the current sync to run its plan without this vault"
271
283
  : "waiting for the desktop app's sync to pick up the off-switch"],
@@ -5,18 +5,20 @@
5
5
  * legacy units, the desktop app), so enabling a service, creating a bot, or
6
6
  * signing in takes effect without restarting the daemon.
7
7
  */
8
- import { type PlanContext, type ServiceName, type UnitPlan } from "./catalog.js";
8
+ import { type LegacySyncHolder, type PlanContext, type ServiceName, type UnitPlan } from "./catalog.js";
9
9
  import { type SyncCoreVaultPlan } from "../sync-core/engine-home.js";
10
10
  import { type LegacyUnit, type WindowsTaskOwner } from "./legacy.js";
11
11
  import { type DaemonLockResult } from "./lock.js";
12
12
  import { type MachineType } from "./machine-type.js";
13
13
  import { type PickedHqCloud } from "./hq-cloud.js";
14
- import { type HostApp, type Supervisor } from "./supervisor.js";
14
+ import { type WatchRunnerOwnerStatus } from "./sync-runner.js";
15
+ import { type DaemonState, type HostApp, type Supervisor } from "./supervisor.js";
15
16
  export declare const LOG_ROTATE_BYTES: number;
16
17
  /** Exit code for "restart me": non-zero so every service manager relaunches (Windows tasks only restart on failure). */
17
18
  export declare const RESTART_EXIT_CODE = 75;
18
19
  export declare function syncCoreVaultPlans(home: string, hqRoot: string | undefined, platform: NodeJS.Platform): SyncCoreVaultPlan[];
19
- export declare function planUnitsWithSyncCoreInterlock(services: readonly ServiceName[], context: PlanContext, supervisor: Pick<Supervisor, "runningPlanKey" | "state"> | null | undefined): UnitPlan[];
20
+ export declare function planUnitsWithSyncCoreInterlock(services: readonly ServiceName[], context: PlanContext, supervisor: Pick<Supervisor, "runningPlanKey" | "state"> | null | undefined, readOwnerStatus: () => WatchRunnerOwnerStatus | null): UnitPlan[];
21
+ export declare function legacySyncHeldByOtherOwner(units: DaemonState["units"], readOwnerStatus: () => WatchRunnerOwnerStatus | null): LegacySyncHolder | undefined;
20
22
  /** A bounded shutdown deadline that can account for sync push persistence. */
21
23
  export declare function createShutdownCap(): {
22
24
  promise: Promise<"timeout">;
@@ -58,7 +58,7 @@ import { stageSyncRunnerBundle } from "./sync-runner-bundle.js";
58
58
  import { stageHqChildBootstrap } from "./hq-child-bootstrap-stage.js";
59
59
  import { runnerSessionName } from "./remote-control.js";
60
60
  import { adoptChild, createChildTracker, finishSuccession, handoffEligible, readProcStart, stopOrphans, successionPaths, systemdKillMode, takeSuccession, writeHandoff, } from "./succession.js";
61
- import { listSyncRunnerProcesses, readWatchRunnerOwnerStatus, syncHeartbeatTimeoutMs, syncRunnerNodeOptions, watchRunnerOwnerStatusPath, } from "./sync-runner.js";
61
+ import { listSyncRunnerProcesses, readWatchRunnerOwnerStatus, SYNC_RUNNER_LEASE_CONFLICT_EXIT, syncHeartbeatTimeoutMs, syncRunnerNodeOptions, watchRunnerOwnerStatusPath, } from "./sync-runner.js";
62
62
  import { STOP_ESCALATION_MS, SYNC_RUNNER_PERSIST_GRACE_MS, createSupervisor, planKey, } from "./supervisor.js";
63
63
  import { userToolDirs } from "./tools.js";
64
64
  import { logOffset, readLogSince, readUnitHolds, writeUnitHolds } from "./unit-holds.js";
@@ -88,7 +88,7 @@ export function syncCoreVaultPlans(home, hqRoot, platform) {
88
88
  });
89
89
  }
90
90
  const rememberedSyncCoreVaults = new Map();
91
- export function planUnitsWithSyncCoreInterlock(services, context, supervisor) {
91
+ export function planUnitsWithSyncCoreInterlock(services, context, supervisor, readOwnerStatus) {
92
92
  const companies = new Set();
93
93
  const runningVaults = new Set();
94
94
  let personal = false;
@@ -155,9 +155,39 @@ export function planUnitsWithSyncCoreInterlock(services, context, supervisor) {
155
155
  waiting = planUnits(services, transitionContext);
156
156
  legacy = waiting.find((unit) => unit.id === "sync");
157
157
  }
158
+ const holder = context.syncCoreVaults?.some((vault) => vault.phase === "full")
159
+ ? legacySyncHeldByOtherOwner(supervisor?.state().units ?? [], readOwnerStatus)
160
+ : undefined;
158
161
  const legacySyncReadyForCore = legacy !== undefined
159
- && (legacy.blocked !== undefined || supervisor?.runningPlanKey("sync") === planKey(legacy, CLI_VERSION));
160
- return planUnits(services, { ...transitionContext, legacySyncReadyForCore });
162
+ && (legacy.blocked !== undefined
163
+ || holder !== undefined
164
+ || supervisor?.runningPlanKey("sync") === planKey(legacy, CLI_VERSION));
165
+ return planUnits(services, {
166
+ ...transitionContext,
167
+ legacySyncReadyForCore,
168
+ ...(holder !== undefined ? { legacySyncHolder: holder } : {}),
169
+ });
170
+ }
171
+ export function legacySyncHeldByOtherOwner(units, readOwnerStatus) {
172
+ const sync = units.find((unit) => unit.id === "sync");
173
+ if (sync?.lastExit?.code !== SYNC_RUNNER_LEASE_CONFLICT_EXIT)
174
+ return undefined;
175
+ const retrying = sync.status === "running" && sync.startedAt !== undefined && sync.startedAt >= sync.lastExit.at;
176
+ if (sync.status !== "waiting" && !retrying)
177
+ return undefined;
178
+ let owner;
179
+ try {
180
+ owner = readOwnerStatus();
181
+ }
182
+ catch {
183
+ return { status: "unreadable" };
184
+ }
185
+ if (!owner)
186
+ return { status: "missing" };
187
+ if (retrying && sync.pid !== undefined && owner.pid === sync.pid)
188
+ return undefined;
189
+ const startedAt = Date.parse(owner.startedAt);
190
+ return Number.isFinite(startedAt) ? { status: "started", startedAt } : { status: "unreadable" };
161
191
  }
162
192
  /** A bounded shutdown deadline that can account for sync push persistence. */
163
193
  export function createShutdownCap() {
@@ -1163,7 +1193,9 @@ export async function runDaemon(opts) {
1163
1193
  availablePoolFrontends,
1164
1194
  unverifiablePoolFrontends,
1165
1195
  };
1166
- const plans = planUnitsWithSyncCoreInterlock(services, context, supervisor);
1196
+ const plans = planUnitsWithSyncCoreInterlock(services, context, supervisor, () => hqRoot
1197
+ ? readWatchRunnerOwnerStatus(watchRunnerOwnerStatusPath(hqRoot, home, env))
1198
+ : null);
1167
1199
  if (startupPlanOpen) {
1168
1200
  const replaceablePackageRoots = cliPackageRoot ? [cliPackageRoot] : [];
1169
1201
  if (hqCloud?.source === "bundled")
@@ -57,6 +57,8 @@ export declare const SYNC_CORE_LOCK_HELD_EXIT = 17;
57
57
  export declare const SYNC_CORE_PROGRESS_EXEMPT_MAX = 6;
58
58
  /** How often a unit held for exit 17 checks whether the lock holder is still alive. */
59
59
  export declare const LOCK_HOLDER_POLL_MS = 5000;
60
+ export declare const WAKE_TICK_MS = 5000;
61
+ export declare const WAKE_GAP_MS = 30000;
60
62
  /**
61
63
  * The pid hq-syncd names when it exits 17: "local sync engine is already
62
64
  * running (pid N)" or "HQ operation lock for ... is held by "cmd" (pid N)".
@@ -62,6 +62,8 @@ export const SYNC_CORE_LOCK_HELD_EXIT = 17;
62
62
  export const SYNC_CORE_PROGRESS_EXEMPT_MAX = 6;
63
63
  /** How often a unit held for exit 17 checks whether the lock holder is still alive. */
64
64
  export const LOCK_HOLDER_POLL_MS = 5_000;
65
+ export const WAKE_TICK_MS = 5_000;
66
+ export const WAKE_GAP_MS = 30_000;
65
67
  /**
66
68
  * The pid hq-syncd names when it exits 17: "local sync engine is already
67
69
  * running (pid N)" or "HQ operation lock for ... is held by "cmd" (pid N)".
@@ -238,6 +240,55 @@ export function createSupervisor(deps) {
238
240
  clearT(slot.heartbeatTimer);
239
241
  slot.heartbeatTimer = undefined;
240
242
  };
243
+ let wakeTickTimer;
244
+ let lastWakeTickAt;
245
+ let resumedAt;
246
+ const noteWakeGap = () => {
247
+ if (lastWakeTickAt === undefined)
248
+ return;
249
+ const at = now();
250
+ if (at - lastWakeTickAt > WAKE_GAP_MS)
251
+ resumedAt = at;
252
+ lastWakeTickAt = at;
253
+ };
254
+ const stopWakeTicker = () => {
255
+ if (wakeTickTimer !== undefined)
256
+ clearT(wakeTickTimer);
257
+ wakeTickTimer = undefined;
258
+ lastWakeTickAt = undefined;
259
+ };
260
+ const scheduleWakeTick = () => {
261
+ const handle = setT(() => {
262
+ wakeTickTimer = undefined;
263
+ noteWakeGap();
264
+ if (stopped || ![...slots.values()].some((s) => s.heartbeatTimer !== undefined)) {
265
+ lastWakeTickAt = undefined;
266
+ return;
267
+ }
268
+ scheduleWakeTick();
269
+ }, WAKE_TICK_MS);
270
+ if (typeof handle === "object" && handle !== null && "unref" in handle && typeof handle.unref === "function") {
271
+ handle.unref();
272
+ }
273
+ wakeTickTimer = handle;
274
+ };
275
+ const ensureWakeTicker = () => {
276
+ if (wakeTickTimer !== undefined)
277
+ return;
278
+ lastWakeTickAt = now();
279
+ scheduleWakeTick();
280
+ };
281
+ const resumedWithin = (windowMs) => {
282
+ noteWakeGap();
283
+ if (resumedAt === undefined)
284
+ return false;
285
+ const sinceResume = now() - resumedAt;
286
+ if (sinceResume < 0) {
287
+ resumedAt = undefined;
288
+ return false;
289
+ }
290
+ return sinceResume < windowMs;
291
+ };
241
292
  const clearDeferredCliRestart = () => {
242
293
  deferredCliRestart = false;
243
294
  if (deferredCliRestartTimer !== undefined)
@@ -587,10 +638,16 @@ export function createSupervisor(deps) {
587
638
  if (!timeoutMs)
588
639
  return;
589
640
  clearHeartbeatTimer(slot);
641
+ ensureWakeTicker();
590
642
  slot.heartbeatTimer = setT(() => {
591
643
  slot.heartbeatTimer = undefined;
592
644
  if (stopped || slot.child !== child || slot.expectingExit)
593
645
  return;
646
+ if (resumedWithin(timeoutMs)) {
647
+ deps.log("info", `${slot.plan.id} emitted no sync protocol heartbeat for ${timeoutMs}ms, but this machine resumed from sleep ${now() - (resumedAt ?? now())}ms ago; waiting another ${timeoutMs}ms before restarting it`);
648
+ armHeartbeatWatchdog();
649
+ return;
650
+ }
594
651
  // An engine that reported bytes moving during this run is slow, not
595
652
  // hung: restart it, but do not count it toward the exhausted hold.
596
653
  // Bounded per episode: past SYNC_CORE_PROGRESS_EXEMPT_MAX these count again.
@@ -1451,6 +1508,7 @@ export function createSupervisor(deps) {
1451
1508
  clearT(handoffTimer);
1452
1509
  clearDeferredCliRestart();
1453
1510
  clearPendingSyncCommandRestart();
1511
+ stopWakeTicker();
1454
1512
  const childOwners = new Map(liveOwners);
1455
1513
  for (const slot of slots.values()) {
1456
1514
  clearTimer(slot);
@@ -1546,6 +1604,7 @@ export function createSupervisor(deps) {
1546
1604
  if (handoffTimer !== undefined)
1547
1605
  clearT(handoffTimer);
1548
1606
  clearDeferredCliRestart();
1607
+ stopWakeTicker();
1549
1608
  for (const slot of slots.values()) {
1550
1609
  clearTimer(slot);
1551
1610
  if (slot.killTimer !== undefined)
@@ -107,19 +107,23 @@ export async function reconcileSyncCore(deps) {
107
107
  if (personUid)
108
108
  desired.push({ uid: personUid, kind: "personal" });
109
109
  }
110
- const skipped = [];
110
+ let skips;
111
111
  try {
112
- const skips = readSyncCoreSkips(deps.home);
113
- for (let i = desired.length - 1; i >= 0; i -= 1) {
114
- const skip = skips.find((entry) => entry.uid === desired[i]?.uid);
115
- if (!skip)
116
- continue;
117
- skipped.unshift(skip);
118
- desired.splice(i, 1);
119
- }
112
+ skips = readSyncCoreSkips(deps.home);
120
113
  }
121
114
  catch (error) {
122
- warnings.push(message(error));
115
+ skips = previous?.skipped ?? [];
116
+ warnings.push(`${message(error)}; ${skips.length > 0
117
+ ? `keeping last run's skips (${skips.map((skip) => skip.uid).join(", ")})`
118
+ : "no vault was skipped last run, so none is skipped now"}`);
119
+ }
120
+ const skipped = [];
121
+ for (let i = desired.length - 1; i >= 0; i -= 1) {
122
+ const skip = skips.find((entry) => entry.uid === desired[i]?.uid);
123
+ if (!skip)
124
+ continue;
125
+ skipped.unshift(skip);
126
+ desired.splice(i, 1);
123
127
  }
124
128
  let binaryPath = syncCoreBinaryPath(deps.home, platform);
125
129
  let installedRelease = installedSyncCoreRelease(deps.home, platform);
@@ -181,7 +185,7 @@ export async function reconcileSyncCore(deps) {
181
185
  ? switchesBefore.personalOff
182
186
  : switchesBefore.offCompanies.has(vault.slug ?? "");
183
187
  const legacyAlreadyOff = wasFull ? before.legacyAlreadyOff === true : alreadyOff;
184
- const legacyOffSince = (wasFull ? before.legacyOffSince : undefined) ?? at;
188
+ const legacyOffSince = (wasFull && alreadyOff ? before.legacyOffSince : undefined) ?? at;
185
189
  const recorded = wasFull ? before.firstCycle : undefined;
186
190
  const firstCycle = recorded && recorded.planned > 0
187
191
  ? recorded
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@indigoai-us/hq-cli",
3
- "version": "5.345.210",
3
+ "version": "5.345.211",
4
4
  "description": "HQ by Indigo management CLI — modules and cloud sync",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -117,11 +117,11 @@
117
117
  "*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}": "eslint --cache --no-error-on-unmatched-pattern"
118
118
  },
119
119
  "optionalDependencies": {
120
- "@indigoai-us/hq-hook-win32-x64": "5.345.210",
121
- "@indigoai-us/hq-hook-win32-arm64": "5.345.210",
122
- "@indigoai-us/hq-hook-darwin-x64": "5.345.210",
123
- "@indigoai-us/hq-hook-darwin-arm64": "5.345.210",
124
- "@indigoai-us/hq-hook-linux-x64": "5.345.210",
125
- "@indigoai-us/hq-hook-linux-arm64": "5.345.210"
120
+ "@indigoai-us/hq-hook-win32-x64": "5.345.211",
121
+ "@indigoai-us/hq-hook-win32-arm64": "5.345.211",
122
+ "@indigoai-us/hq-hook-darwin-x64": "5.345.211",
123
+ "@indigoai-us/hq-hook-darwin-arm64": "5.345.211",
124
+ "@indigoai-us/hq-hook-linux-x64": "5.345.211",
125
+ "@indigoai-us/hq-hook-linux-arm64": "5.345.211"
126
126
  }
127
127
  }