@indigoai-us/hq-cli 5.345.237 → 5.345.241

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 (115) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/assets/scaffold/core/scripts/hq-delegate-repo.sh +7 -1
  3. package/assets/scaffold/core/scripts/hq-delegate-secrets.sh +95 -20
  4. package/assets/scaffold/core/scripts/hq-delegate-transfer.sh +57 -9
  5. package/dist/command-catalog.generated.d.ts +185 -3
  6. package/dist/command-catalog.generated.js +228 -3
  7. package/dist/command-registration-plan.d.ts +6 -0
  8. package/dist/command-registration-plan.js +1 -0
  9. package/dist/commands/bot.d.ts +2 -0
  10. package/dist/commands/bot.js +23 -0
  11. package/dist/commands/cloud-off-gate.d.ts +2 -1
  12. package/dist/commands/cloud-off-gate.js +17 -4
  13. package/dist/commands/cloud.d.ts +17 -2
  14. package/dist/commands/cloud.js +126 -24
  15. package/dist/commands/core-delegate-w1b.js +35 -10
  16. package/dist/commands/core-delegate.d.ts +2 -1
  17. package/dist/commands/core-delegate.js +207 -48
  18. package/dist/commands/deploy-comments.js +8 -2
  19. package/dist/commands/deploy-events.d.ts +40 -0
  20. package/dist/commands/deploy-events.js +300 -0
  21. package/dist/commands/doctor.d.ts +4 -4
  22. package/dist/commands/doctor.js +2 -2
  23. package/dist/commands/feedback.js +2 -3
  24. package/dist/commands/keyed-sync-pull.d.ts +12 -0
  25. package/dist/commands/keyed-sync-pull.js +151 -0
  26. package/dist/commands/library-add.d.ts +5 -2
  27. package/dist/commands/library-add.js +22 -9
  28. package/dist/commands/mcp-registration.d.ts +4 -18
  29. package/dist/commands/mcp-registration.js +9 -29
  30. package/dist/commands/mesh.d.ts +4 -0
  31. package/dist/commands/mesh.js +25 -5
  32. package/dist/commands/pack-install.d.ts +2 -3
  33. package/dist/commands/pack-install.js +6 -8
  34. package/dist/commands/secrets.d.ts +3 -4
  35. package/dist/commands/secrets.js +3 -20
  36. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +307 -232
  37. package/dist/hq-cloud-sync-runner/package.json +1 -1
  38. package/dist/lib/agent-kit/inbox-state.d.ts +2 -1
  39. package/dist/lib/agent-kit/inbox-state.js +27 -3
  40. package/dist/lib/bot/api.d.ts +2 -1
  41. package/dist/lib/bot/api.js +2 -15
  42. package/dist/lib/bot/promote.d.ts +23 -0
  43. package/dist/lib/bot/promote.js +73 -0
  44. package/dist/lib/bot/promotion-hold-reconcile.d.ts +56 -0
  45. package/dist/lib/bot/promotion-hold-reconcile.js +155 -0
  46. package/dist/lib/capacity/collectors/claude-oauth.d.ts +0 -2
  47. package/dist/lib/capacity/collectors/claude-oauth.js +0 -5
  48. package/dist/lib/core-utils/delegate-helper-paths.d.ts +26 -0
  49. package/dist/lib/core-utils/delegate-helper-paths.js +33 -0
  50. package/dist/lib/daemon/jq-provision.d.ts +63 -0
  51. package/dist/lib/daemon/jq-provision.js +155 -0
  52. package/dist/lib/daemon/lanes-reconcile-guard.d.ts +4 -3
  53. package/dist/lib/daemon/lanes-reconcile-guard.js +4 -4
  54. package/dist/lib/daemon/mesh-owner.d.ts +4 -0
  55. package/dist/lib/daemon/mesh-owner.js +20 -0
  56. package/dist/lib/daemon/ops/policy.d.ts +3 -0
  57. package/dist/lib/daemon/ops/policy.js +32 -4
  58. package/dist/lib/daemon/run.d.ts +17 -1
  59. package/dist/lib/daemon/run.js +24 -3
  60. package/dist/lib/daemon/server.d.ts +6 -0
  61. package/dist/lib/daemon/server.js +5 -0
  62. package/dist/lib/daemon/verified-jq.d.ts +96 -0
  63. package/dist/lib/daemon/verified-jq.js +337 -0
  64. package/dist/lib/doctor/checks/jq.js +16 -0
  65. package/dist/lib/doctor/deep/executor.d.ts +7 -0
  66. package/dist/lib/doctor/deep/executor.js +1 -1
  67. package/dist/lib/doctor/deep/parity.js +1 -27
  68. package/dist/lib/doctor/deep/sandbox.d.ts +2 -2
  69. package/dist/lib/doctor/deep/sandbox.js +3 -19
  70. package/dist/lib/doctor/fix/refresh-sync-handoff.js +52 -21
  71. package/dist/lib/doctor/fixtures/discover.d.ts +2 -0
  72. package/dist/lib/doctor/fixtures/discover.js +1 -1
  73. package/dist/lib/doctor/json-output.d.ts +1 -1
  74. package/dist/lib/doctor/registry.d.ts +6 -7
  75. package/dist/lib/doctor/registry.js +6 -7
  76. package/dist/lib/doctor/report.d.ts +9 -10
  77. package/dist/lib/doctor/report.js +4 -4
  78. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  79. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  80. package/dist/lib/jq/install.d.ts +27 -0
  81. package/dist/lib/jq/install.js +156 -0
  82. package/dist/lib/lanes/outpost-dispatch.d.ts +1 -1
  83. package/dist/lib/lanes/outpost-dispatch.js +13 -13
  84. package/dist/lib/lanes/outpost-pruner-install.js +1 -1
  85. package/dist/lib/mesh/live/daemon/doctor.js +7 -1
  86. package/dist/lib/mesh/live/daemon/install.d.ts +4 -0
  87. package/dist/lib/mesh/live/daemon/install.js +10 -0
  88. package/dist/lib/mesh/live/daemon/run.js +17 -0
  89. package/dist/lib/mesh/live/emit-retry.d.ts +20 -2
  90. package/dist/lib/mesh/live/emit-retry.js +57 -4
  91. package/dist/lib/mesh/live/emit.js +25 -4
  92. package/dist/lib/mesh/live/flush.d.ts +2 -0
  93. package/dist/lib/mesh/live/flush.js +21 -8
  94. package/dist/lib/mesh/live/spool.d.ts +9 -1
  95. package/dist/lib/mesh/live/spool.js +41 -29
  96. package/dist/lib/sync-core/rollout-state.d.ts +9 -1
  97. package/dist/lib/sync-core/rollout-state.js +34 -4
  98. package/dist/lib/windows/jq.d.ts +4 -0
  99. package/dist/lib/windows/jq.js +10 -39
  100. package/dist/lib/workers-registry/index.js +7 -11
  101. package/dist/utils/callback-port-busy.d.ts +2 -2
  102. package/dist/utils/callback-port-busy.js +2 -2
  103. package/dist/utils/cli-network-lifecycle.js +1 -0
  104. package/dist/utils/client-health-contract.d.ts +2 -0
  105. package/dist/utils/client-health-contract.js +1 -1
  106. package/dist/utils/client-health.js +1 -9
  107. package/dist/utils/cognito-config.js +5 -0
  108. package/dist/utils/cognito-session.d.ts +4 -6
  109. package/dist/utils/cognito-session.js +4 -24
  110. package/dist/utils/incomplete-install-error.js +1 -11
  111. package/dist/utils/install-tree-torn.d.ts +11 -0
  112. package/dist/utils/install-tree-torn.js +1 -1
  113. package/dist/utils/resident-package-preload.js +2 -1
  114. package/docs/anywhere-runtime.md +8 -0
  115. package/package.json +9 -9
@@ -0,0 +1,27 @@
1
+ export interface PinnedJqAsset {
2
+ url: string;
3
+ sha256: string;
4
+ }
5
+ export type JqDownload = (url: string, init: {
6
+ signal: AbortSignal;
7
+ redirect: "follow";
8
+ }) => Promise<Response>;
9
+ /** Carries the refused component so callers can exclude its entire subtree. */
10
+ export declare class UnsafeJqPathError extends Error {
11
+ readonly path: string;
12
+ constructor(path: string, message: string);
13
+ }
14
+ /** Validate/create a private directory without following links or shared parents. */
15
+ export declare function checkJqDirectory(home: string, directory: string, create?: boolean): void;
16
+ /** Read-only check for an existing system PATH directory, which may be root-owned. */
17
+ export declare function checkSystemJqDirectory(directory: string): void;
18
+ /** Never run an existing managed binary until its pinned digest is checked. */
19
+ export declare function matchesPinnedJq(home: string, target: string, asset: PinnedJqAsset): boolean;
20
+ export declare function installPinnedJq(options: {
21
+ home: string;
22
+ target: string;
23
+ asset: PinnedJqAsset;
24
+ fetch?: JqDownload;
25
+ verify?: (file: string) => Promise<void>;
26
+ }): Promise<string>;
27
+ //# sourceMappingURL=install.d.ts.map
@@ -0,0 +1,156 @@
1
+ /** Shared, pinned jq installer for daemon provisioning and Windows hook setup. */
2
+ import { createHash } from "node:crypto";
3
+ import * as fs from "node:fs";
4
+ import * as path from "node:path";
5
+ const MAX_DOWNLOAD_BYTES = 16 * 1024 * 1024;
6
+ function missing(error) {
7
+ return error.code === "ENOENT";
8
+ }
9
+ /** Carries the refused component so callers can exclude its entire subtree. */
10
+ export class UnsafeJqPathError extends Error {
11
+ path;
12
+ constructor(path, message) {
13
+ super(message);
14
+ this.path = path;
15
+ this.name = "UnsafeJqPathError";
16
+ }
17
+ }
18
+ function checkOwned(file, directory, allowRootOwner = false) {
19
+ let stat;
20
+ try {
21
+ stat = fs.lstatSync(file);
22
+ }
23
+ catch (error) {
24
+ if (missing(error))
25
+ return false;
26
+ throw new UnsafeJqPathError(file, `Could not inspect jq path ${file}: ${error.message}`);
27
+ }
28
+ if (stat.isSymbolicLink() || (directory ? !stat.isDirectory() : !stat.isFile())) {
29
+ throw new UnsafeJqPathError(file, `Refusing unsafe jq path: ${file}`);
30
+ }
31
+ // Windows permission bits do not describe ACLs; the user's profile is the
32
+ // trust boundary there. POSIX additionally requires ownership and no writers.
33
+ if (process.platform !== "win32" &&
34
+ ((stat.uid !== process.getuid?.() && !(allowRootOwner && stat.uid === 0)) || (stat.mode & 0o022) !== 0)) {
35
+ throw new UnsafeJqPathError(file, `Refusing jq path not exclusively writable by its owner: ${file}`);
36
+ }
37
+ return true;
38
+ }
39
+ /** Reject links at every component below the owned home, including the file. */
40
+ function checkPath(home, target, create = false, directory = false, allowRootOwner = false) {
41
+ if (!path.isAbsolute(home) || !path.isAbsolute(target))
42
+ throw new Error("jq needs an absolute home and target");
43
+ const relative = path.relative(home, target);
44
+ if ((!relative && !directory) || relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
45
+ throw new Error("jq target must be inside its home");
46
+ }
47
+ if (!checkOwned(home, true, allowRootOwner))
48
+ throw new UnsafeJqPathError(home, `jq home does not exist: ${home}`);
49
+ let dir = home;
50
+ const parts = relative ? relative.split(path.sep) : [];
51
+ for (const part of directory ? parts : parts.slice(0, -1)) {
52
+ dir = path.join(dir, part);
53
+ if (!checkOwned(dir, true, allowRootOwner) && create) {
54
+ try {
55
+ fs.mkdirSync(dir, { mode: 0o700 });
56
+ }
57
+ catch (error) {
58
+ if (error.code !== "EEXIST")
59
+ throw error;
60
+ }
61
+ checkOwned(dir, true, allowRootOwner);
62
+ }
63
+ }
64
+ if (!directory)
65
+ checkOwned(target, false, allowRootOwner);
66
+ }
67
+ /** Validate/create a private directory without following links or shared parents. */
68
+ export function checkJqDirectory(home, directory, create = false) {
69
+ checkPath(home, directory, create, true);
70
+ }
71
+ /** Read-only check for an existing system PATH directory, which may be root-owned. */
72
+ export function checkSystemJqDirectory(directory) {
73
+ checkPath(directory, directory, false, true, true);
74
+ }
75
+ function digest(bytes) {
76
+ return createHash("sha256").update(bytes).digest("hex");
77
+ }
78
+ /** Never run an existing managed binary until its pinned digest is checked. */
79
+ export function matchesPinnedJq(home, target, asset) {
80
+ checkPath(home, target);
81
+ let fd;
82
+ try {
83
+ fd = fs.openSync(target, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
84
+ }
85
+ catch (error) {
86
+ if (missing(error))
87
+ return false;
88
+ throw error;
89
+ }
90
+ try {
91
+ const stat = fs.fstatSync(fd);
92
+ if (!stat.isFile() || stat.size > MAX_DOWNLOAD_BYTES)
93
+ return false;
94
+ return digest(fs.readFileSync(fd)) === asset.sha256;
95
+ }
96
+ finally {
97
+ fs.closeSync(fd);
98
+ }
99
+ }
100
+ export async function installPinnedJq(options) {
101
+ const { home, target, asset } = options;
102
+ if (matchesPinnedJq(home, target, asset) &&
103
+ (process.platform === "win32" || (fs.statSync(target).mode & 0o111) !== 0))
104
+ return target;
105
+ const response = await (options.fetch ?? fetch)(asset.url, {
106
+ signal: AbortSignal.timeout(20_000), redirect: "follow",
107
+ });
108
+ if (!response.ok)
109
+ throw new Error(`jq download failed: HTTP ${response.status}`);
110
+ if (Number(response.headers.get("content-length") ?? 0) > MAX_DOWNLOAD_BYTES) {
111
+ await response.body?.cancel();
112
+ throw new Error("jq download is larger than any jq release");
113
+ }
114
+ const chunks = [];
115
+ let total = 0;
116
+ if (response.body) {
117
+ const reader = response.body.getReader();
118
+ try {
119
+ for (;;) {
120
+ const { done, value } = await reader.read();
121
+ if (done)
122
+ break;
123
+ total += value.byteLength;
124
+ if (total > MAX_DOWNLOAD_BYTES) {
125
+ await reader.cancel();
126
+ throw new Error("jq download is larger than any jq release");
127
+ }
128
+ chunks.push(Buffer.from(value));
129
+ }
130
+ }
131
+ finally {
132
+ reader.releaseLock();
133
+ }
134
+ }
135
+ const bytes = Buffer.concat(chunks);
136
+ if (digest(bytes) !== asset.sha256) {
137
+ throw new Error("jq download did not match the pinned release checksum");
138
+ }
139
+ checkPath(home, target, true);
140
+ const staged = fs.mkdtempSync(path.join(path.dirname(target), ".hq-jq-"));
141
+ try {
142
+ // Private staging and exclusive creation prevent pre-planted links.
143
+ // Verification precedes executable permission and the optional probe.
144
+ const file = path.join(staged, path.basename(target));
145
+ fs.writeFileSync(file, bytes, { flag: "wx", mode: 0o600 });
146
+ fs.chmodSync(file, 0o755);
147
+ await options.verify?.(file);
148
+ checkPath(home, target);
149
+ fs.renameSync(file, target);
150
+ }
151
+ finally {
152
+ fs.rmSync(staged, { recursive: true, force: true });
153
+ }
154
+ return target;
155
+ }
156
+ //# sourceMappingURL=install.js.map
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * The transport is the existing OutpostsClient submit/wait pair — the same
5
5
  * path as `hq outposts exec --async`. Create stages a payload, then runs
6
- * `hq lanes pickup --payload-url` on the box. A submit or wait failure is
6
+ * `hq runners pickup --payload-url` on the box. A submit or wait failure is
7
7
  * `outpost_dispatch_failed`, never a queued lane nobody will pick up.
8
8
  */
9
9
  import { OutpostsClient } from "@indigoai-us/hq-cloud/outposts";
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * The transport is the existing OutpostsClient submit/wait pair — the same
5
5
  * path as `hq outposts exec --async`. Create stages a payload, then runs
6
- * `hq lanes pickup --payload-url` on the box. A submit or wait failure is
6
+ * `hq runners pickup --payload-url` on the box. A submit or wait failure is
7
7
  * `outpost_dispatch_failed`, never a queued lane nobody will pick up.
8
8
  */
9
9
  import { OutpostsClient, joinCommandParts, withRemoteHqDir } from "@indigoai-us/hq-cloud/outposts";
@@ -13,7 +13,7 @@ export const PICKUP_WAIT_MS = PICKUP_EXEC_TIMEOUT_SECONDS * 1000;
13
13
  export function buildOutpostQuestionAnswerCommand(input) {
14
14
  const args = [
15
15
  input.hqBinary?.trim() || "hq",
16
- "lanes",
16
+ "runners",
17
17
  "questions",
18
18
  "answer",
19
19
  input.questionId,
@@ -59,11 +59,11 @@ export function parseOutpostPickupPayload(raw) {
59
59
  }
60
60
  /** Same wrapping `hq outposts exec` applies: run from the box's HQ folder. */
61
61
  export function buildOutpostPickupCommand(payloadUrl) {
62
- return withRemoteHqDir(joinCommandParts(["hq", "lanes", "pickup", "--payload-url", payloadUrl]));
62
+ return withRemoteHqDir(joinCommandParts(["hq", "runners", "pickup", "--payload-url", payloadUrl]));
63
63
  }
64
64
  /** Bounded, read-only capacity query executed by the target Outpost CLI. */
65
65
  export function buildOutpostCapacityCommand() {
66
- return withRemoteHqDir(joinCommandParts(["hq", "lanes", "capacity", "--json"]));
66
+ return withRemoteHqDir(joinCommandParts(["hq", "runners", "capacity", "--json"]));
67
67
  }
68
68
  /**
69
69
  * Marks a lane list that runs on an Outpost for another host. Such a list
@@ -79,7 +79,7 @@ export function buildOutpostLaneListCommand(input = {}) {
79
79
  "env",
80
80
  `${REMOTE_LANE_READ_ENV}=1`,
81
81
  input.hqBinary?.trim() || "hq",
82
- "lanes",
82
+ "runners",
83
83
  "list",
84
84
  "--json",
85
85
  ];
@@ -107,7 +107,7 @@ export function buildOutpostLegacyLaneUlidListCommand(input) {
107
107
  const hqBinary = input.hqBinary?.trim() || "hq";
108
108
  const script = [
109
109
  "const { spawnSync } = require('node:child_process');",
110
- `const result = spawnSync(${JSON.stringify(hqBinary)}, ['lanes', 'list', '--json'], { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024, env: { ...process.env, ${REMOTE_LANE_READ_ENV}: '1' } });`,
110
+ `const result = spawnSync(${JSON.stringify(hqBinary)}, ['runners', 'list', '--json'], { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024, env: { ...process.env, ${REMOTE_LANE_READ_ENV}: '1' } });`,
111
111
  "if (result.error || result.status !== 0) { console.error(JSON.stringify({ error: result.error?.message || 'legacy Outpost lane list failed', status: result.status, signal: result.signal, stderr_tail: String(result.stderr || '').slice(-4096), stdout_tail: String(result.stdout || '').slice(-4096) })); process.exit(result.status || 1); }",
112
112
  "try {",
113
113
  "const payload = JSON.parse(result.stdout);",
@@ -123,7 +123,7 @@ export function buildOutpostLegacyLaneUlidListCommand(input) {
123
123
  export function buildOutpostQuestionListCommand(input = {}) {
124
124
  const args = [
125
125
  ...(input.sessionId?.trim() ? ["env", `HQ_SESSION_ID=${input.sessionId.trim()}`] : []),
126
- "hq", "lanes", "questions", "list",
126
+ "hq", "runners", "questions", "list",
127
127
  ];
128
128
  const company = input.company?.trim();
129
129
  if (company)
@@ -144,7 +144,7 @@ export function buildOutpostQuestionListCommand(input = {}) {
144
144
  export function buildOutpostQuestionShowCommand(questionId) {
145
145
  return withRemoteHqDir(joinCommandParts([
146
146
  "hq",
147
- "lanes",
147
+ "runners",
148
148
  "questions",
149
149
  "show",
150
150
  questionId,
@@ -154,7 +154,7 @@ export function buildOutpostQuestionShowCommand(questionId) {
154
154
  export function buildOutpostQuestionCancelCommand(input) {
155
155
  return withRemoteHqDir(joinCommandParts([
156
156
  "hq",
157
- "lanes",
157
+ "runners",
158
158
  "questions",
159
159
  "cancel",
160
160
  input.questionId,
@@ -166,7 +166,7 @@ export function buildOutpostQuestionCancelCommand(input) {
166
166
  export function buildOutpostMoveTargetCommand(input) {
167
167
  return withRemoteHqDir(joinCommandParts([
168
168
  "hq",
169
- "lanes",
169
+ "runners",
170
170
  "move-target",
171
171
  input.laneId,
172
172
  "--host-kind",
@@ -181,7 +181,7 @@ export function buildOutpostMoveTargetCommand(input) {
181
181
  export function buildOutpostBalanceMoveCommand(input) {
182
182
  return withRemoteHqDir(joinCommandParts([
183
183
  "hq",
184
- "lanes",
184
+ "runners",
185
185
  "balance-move-target",
186
186
  input.laneId,
187
187
  "--account",
@@ -196,7 +196,7 @@ export function buildOutpostBalanceMoveCommand(input) {
196
196
  export function buildOutpostIdentityBackfillCommand(expectedId) {
197
197
  return withRemoteHqDir(joinCommandParts([
198
198
  "hq",
199
- "lanes",
199
+ "runners",
200
200
  "outpost-identity-backfill-target",
201
201
  "--expected-id",
202
202
  expectedId,
@@ -205,7 +205,7 @@ export function buildOutpostIdentityBackfillCommand(expectedId) {
205
205
  /** Build the same `hq outposts exec` remote command used by lane pickup. */
206
206
  export function buildOutpostLaneCommand(input) {
207
207
  const action = input.action === "blocked-escalation-target" ? "_enqueue-blocked-escalation" : input.action;
208
- const args = [input.hqBinary?.trim() || "hq", "lanes", action];
208
+ const args = [input.hqBinary?.trim() || "hq", "runners", action];
209
209
  if (input.action === "blocked-escalation-target")
210
210
  args.push(input.recipientKind ?? "lane", input.laneId);
211
211
  else
@@ -96,7 +96,7 @@ export function renderOutpostPrunerService(opts) {
96
96
  const command = [
97
97
  opts.nodeBinary,
98
98
  opts.hqBinary,
99
- "lanes",
99
+ "runners",
100
100
  "outpost-pruner",
101
101
  "run",
102
102
  "--trigger",
@@ -244,7 +244,13 @@ export function collectDaemonDoctor(deps = {}) {
244
244
  const whoamiSubject = formatCognitoSubject(whoamiTokens);
245
245
  const daemonSubject = formatCognitoSubject(daemonTokens);
246
246
  const emitState = readEmitState(meshRoot);
247
- const emitRetry = emitRetryDepth(meshRoot);
247
+ let emitRetry = 0;
248
+ try {
249
+ emitRetry = emitRetryDepth(meshRoot);
250
+ }
251
+ catch (err) {
252
+ unhealthyReasons.push(`direct-emit retry file unreadable: ${err?.code ?? "read error"}`);
253
+ }
248
254
  if (emitRetry > 0) {
249
255
  unhealthyReasons.push(`direct-emit retry depth=${emitRetry}`);
250
256
  }
@@ -397,6 +397,10 @@ export declare function daemonServiceStatus(opts: {
397
397
  /** Windows: liveness probe for the daemon pid lock (tests inject). */
398
398
  isProcessAlive?: (pid: number) => boolean;
399
399
  readFileSync?: typeof fs.readFileSync;
400
+ hqDaemonMesh?: {
401
+ daemonPid: number;
402
+ pid?: number;
403
+ } | null;
400
404
  }): InstallResult;
401
405
  /** Read baked template files from assets/ (optional; renderers are primary). */
402
406
  export declare function readAssetTemplate(name: "launchd.plist.template" | "systemd.user.service.template" | "systemd.system.service.template"): string | null;
@@ -1376,6 +1376,16 @@ export function daemonServiceStatus(opts) {
1376
1376
  const platform = opts.platform ?? detectPlatform();
1377
1377
  const paths = opts.paths ?? buildInstallPaths({});
1378
1378
  const existsSync = opts.existsSync ?? fs.existsSync;
1379
+ if (opts.hqDaemonMesh) {
1380
+ const { daemonPid, pid } = opts.hqDaemonMesh;
1381
+ return {
1382
+ platform,
1383
+ action: "status",
1384
+ paths,
1385
+ running: true,
1386
+ message: `hq daemon (pid ${daemonPid}): mesh service running${pid ? `, pid ${pid}` : ""}. Details: hq daemon status`,
1387
+ };
1388
+ }
1379
1389
  if (platform === "win32") {
1380
1390
  const schtasks = opts.schtasks ?? defaultSchtasks;
1381
1391
  // schtasks only tells us whether the task exists. Its Status column is
@@ -34,6 +34,7 @@ import { daemonDir } from "./paths.js";
34
34
  import { PresenceClient, defaultMqttConnect, } from "./presence.js";
35
35
  import { defaultDaemonState, patchDaemonState, readDaemonState, writeDaemonState, } from "./state.js";
36
36
  import { workMeshHeldPath } from "../paths.js";
37
+ import { countJsonlLines } from "../spool.js";
37
38
  import { defaultTranscriptFs, noteHookSessionsFromSpoolFile, TRANSCRIPT_WATCH_INTERVAL_MS, TranscriptWatcher, } from "./transcript-watch.js";
38
39
  import { resolveMeshEmitMode, runsEmitPath, } from "./mode.js";
39
40
  import { hasCliVersionDrift, readInstalledCliVersion } from "./version-drift.js";
@@ -64,6 +65,11 @@ export const DEVICE_DEFAULT_MEMBERSHIP_TIMEOUT_MS = 2_000;
64
65
  export const DEVICE_DEFAULT_MEMBERSHIP_UNAVAILABLE_COOLDOWN_MS = 30_000;
65
66
  /** Direct mode: longest wait between drain cycles after repeated failures. */
66
67
  export const DIRECT_DRAIN_MAX_DELAY_MS = 5 * 60 * 1_000;
68
+ const DIRECT_NO_CLAIM_REASON_TEXT = {
69
+ operator_switch_off: "HQ Anywhere is switched off by the operator",
70
+ anywhere_off_no_company_session_event: "HQ Anywhere reads as off for this person or this machine and no queued event is from a company-bound session dated since it was first seen off",
71
+ no_claimable_line: "the queue files held no line this cycle could claim",
72
+ };
67
73
  /**
68
74
  * Wait before the next direct-mode drain cycle. FLUSH_INTERVAL_MS while cycles
69
75
  * succeed; doubled for each cycle in a row that failed or delivered nothing
@@ -910,6 +916,7 @@ export async function runMeshDaemon(deps = {}) {
910
916
  let directDrainHandle = null;
911
917
  let directDrainInFlight = null;
912
918
  let directDrainFailures = 0;
919
+ let directNoClaimLogged = null;
913
920
  const runDirectDrain = async () => {
914
921
  try {
915
922
  const atMs = now().getTime();
@@ -929,6 +936,16 @@ export async function runMeshDaemon(deps = {}) {
929
936
  patchDaemonState(dir, { lastFlushAt: now().toISOString(), lastFlushResult: { ...summary, ok: true } }, now);
930
937
  if (summary.claimed > 0) {
931
938
  log(dir, `drain(direct): claimed=${summary.claimed} posted=${summary.posted} held=${summary.held} dropped=${summary.dropped} deadLettered=${summary.deadLettered} restored=${summary.restored}`);
939
+ directNoClaimLogged = null;
940
+ }
941
+ else {
942
+ const reason = summary.noClaimReason ?? "no_claimable_line";
943
+ if (directNoClaimLogged !== reason) {
944
+ directNoClaimLogged = reason;
945
+ const spool = countJsonlLines(workMeshSpoolPath(meshRoot));
946
+ const held = countJsonlLines(workMeshHeldPath(meshRoot));
947
+ log(dir, `drain(direct): claimed=0 pending=${spool + held} (spool=${spool} held=${held}) reason=${reason}: ${DIRECT_NO_CLAIM_REASON_TEXT[reason]}`);
948
+ }
932
949
  }
933
950
  // Lines went back on the spool and nothing was delivered: the server is
934
951
  // unreachable or refusing for now. Wait longer before the next cycle.
@@ -9,7 +9,12 @@
9
9
  /** Default cap on retained retry events (oldest dropped past this). */
10
10
  export declare const EMIT_RETRY_MAX = 5000;
11
11
  export declare function emitRetryPath(workMeshRoot: string): string;
12
- /** Read pending retry events (parseable objects only). Missing file → []. */
12
+ /**
13
+ * Read pending retry events (parseable objects only). Missing file → [].
14
+ * Any other read error throws: a caller that took it as "nothing pending" and
15
+ * rewrote the file would delete the events it holds. Use appendEmitRetry to
16
+ * keep new events when the read failed.
17
+ */
13
18
  export declare function readEmitRetry(workMeshRoot: string): Record<string, unknown>[];
14
19
  /**
15
20
  * Atomically replace the retry file with `events` (keeping the most recent
@@ -20,6 +25,19 @@ export declare function writeEmitRetry(workMeshRoot: string, events: Record<stri
20
25
  written: number;
21
26
  dropped: number;
22
27
  };
23
- /** Count of pending retry events (doctor retryDepth). */
28
+ /**
29
+ * Append `events` to the retry file without reading or replacing it. Used when
30
+ * the file could not be read, so its existing events are left as they are.
31
+ * Duplicates are removed by eventId on the next drain, and the cap applies on
32
+ * the next full write.
33
+ *
34
+ * readEmitRetry accepts a final record with no trailing newline, and this path
35
+ * cannot read the file to check its last byte. So when the file already has
36
+ * bytes, the batch starts with a newline: otherwise it would join that final
37
+ * record into one invalid line and the reader would drop both. The reader
38
+ * skips the blank line this leaves when the file did end in a newline.
39
+ */
40
+ export declare function appendEmitRetry(workMeshRoot: string, events: Record<string, unknown>[]): number;
41
+ /** Count of pending retry events (doctor retryDepth). Throws if the file cannot be read. */
24
42
  export declare function emitRetryDepth(workMeshRoot: string): number;
25
43
  //# sourceMappingURL=emit-retry.d.ts.map
@@ -16,15 +16,22 @@ export function emitRetryPath(workMeshRoot) {
16
16
  function ensureFileDir(filePath) {
17
17
  fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
18
18
  }
19
- /** Read pending retry events (parseable objects only). Missing file → []. */
19
+ /**
20
+ * Read pending retry events (parseable objects only). Missing file → [].
21
+ * Any other read error throws: a caller that took it as "nothing pending" and
22
+ * rewrote the file would delete the events it holds. Use appendEmitRetry to
23
+ * keep new events when the read failed.
24
+ */
20
25
  export function readEmitRetry(workMeshRoot) {
21
26
  const p = emitRetryPath(workMeshRoot);
22
27
  let raw;
23
28
  try {
24
29
  raw = fs.readFileSync(p, "utf8");
25
30
  }
26
- catch {
27
- return [];
31
+ catch (err) {
32
+ if (err?.code === "ENOENT")
33
+ return [];
34
+ throw err;
28
35
  }
29
36
  const out = [];
30
37
  for (const line of raw.split("\n")) {
@@ -72,7 +79,53 @@ export function writeEmitRetry(workMeshRoot, events, max = EMIT_RETRY_MAX) {
72
79
  fs.renameSync(tmp, p);
73
80
  return { written: keep.length, dropped };
74
81
  }
75
- /** Count of pending retry events (doctor retryDepth). */
82
+ /**
83
+ * Append `events` to the retry file without reading or replacing it. Used when
84
+ * the file could not be read, so its existing events are left as they are.
85
+ * Duplicates are removed by eventId on the next drain, and the cap applies on
86
+ * the next full write.
87
+ *
88
+ * readEmitRetry accepts a final record with no trailing newline, and this path
89
+ * cannot read the file to check its last byte. So when the file already has
90
+ * bytes, the batch starts with a newline: otherwise it would join that final
91
+ * record into one invalid line and the reader would drop both. The reader
92
+ * skips the blank line this leaves when the file did end in a newline.
93
+ */
94
+ export function appendEmitRetry(workMeshRoot, events) {
95
+ if (events.length === 0)
96
+ return 0;
97
+ const p = emitRetryPath(workMeshRoot);
98
+ ensureFileDir(p);
99
+ const body = events.map((e) => JSON.stringify(e)).join("\n") + "\n";
100
+ const fd = fs.openSync(p, "a", 0o600);
101
+ try {
102
+ // fstat needs no read permission, so it works on a file we cannot read.
103
+ const separator = fs.fstatSync(fd).size > 0 ? "\n" : "";
104
+ writeAll(fd, Buffer.from(separator + body, "utf8"));
105
+ }
106
+ finally {
107
+ fs.closeSync(fd);
108
+ }
109
+ return events.length;
110
+ }
111
+ /**
112
+ * Write every byte of `buf`. writeSync may write fewer bytes than asked (for
113
+ * example when the disk or quota is nearly full); stopping there would leave a
114
+ * truncated record that the reader drops while the caller counts it as kept.
115
+ * Errors propagate, and a write that makes no progress throws instead of
116
+ * looping forever.
117
+ */
118
+ function writeAll(fd, buf) {
119
+ let offset = 0;
120
+ while (offset < buf.length) {
121
+ const n = fs.writeSync(fd, buf, offset, buf.length - offset);
122
+ if (n <= 0) {
123
+ throw new Error(`emit retry append wrote ${offset} of ${buf.length} bytes`);
124
+ }
125
+ offset += n;
126
+ }
127
+ }
128
+ /** Count of pending retry events (doctor retryDepth). Throws if the file cannot be read. */
76
129
  export function emitRetryDepth(workMeshRoot) {
77
130
  return readEmitRetry(workMeshRoot).length;
78
131
  }
@@ -14,7 +14,7 @@ import { hqAnywhereRuntimeLocallyDisabled } from "../../anywhere-runtime-flag-ke
14
14
  import * as fs from "node:fs";
15
15
  import * as path from "node:path";
16
16
  import { MESH_EVENTS_BATCH_MAX, parseEmitResults, } from "./emit-client.js";
17
- import { EMIT_RETRY_MAX, readEmitRetry, writeEmitRetry, } from "./emit-retry.js";
17
+ import { EMIT_RETRY_MAX, appendEmitRetry, readEmitRetry, writeEmitRetry, } from "./emit-retry.js";
18
18
  import { defaultSleep, fullJitterDelayMs, } from "./backoff.js";
19
19
  export function emitStatePath(workMeshRoot) {
20
20
  return path.join(workMeshRoot, "emit-state.json");
@@ -68,7 +68,28 @@ export async function emitEvents(deps) {
68
68
  const maxAttempts = deps.maxAttempts ?? 3;
69
69
  const retryMax = deps.retryMax ?? EMIT_RETRY_MAX;
70
70
  // Combine pending retry + new events, deduped by eventId (first wins).
71
- const pending = readEmitRetry(deps.workMeshRoot);
71
+ // A retry file that exists but cannot be read is never rewritten: that would
72
+ // delete the events in it. New events that are not sent are appended instead.
73
+ let pending = [];
74
+ let retryUnreadable = false;
75
+ try {
76
+ pending = readEmitRetry(deps.workMeshRoot);
77
+ }
78
+ catch (err) {
79
+ retryUnreadable = true;
80
+ deps.log?.(`emit retry file unreadable; left in place: ${(err instanceof Error ? err.message : String(err)).slice(0, 120)}`);
81
+ }
82
+ const persistRetry = (events) => {
83
+ if (!retryUnreadable)
84
+ return writeEmitRetry(deps.workMeshRoot, events, retryMax);
85
+ try {
86
+ return { written: appendEmitRetry(deps.workMeshRoot, events), dropped: 0 };
87
+ }
88
+ catch (err) {
89
+ deps.log?.(`emit retry append failed; ${events.length} events not retained: ${(err instanceof Error ? err.message : String(err)).slice(0, 120)}`);
90
+ return { written: 0, dropped: events.length };
91
+ }
92
+ };
72
93
  const combined = [];
73
94
  const seen = new Set();
74
95
  for (const e of [...pending, ...(deps.newEvents ?? [])]) {
@@ -109,7 +130,7 @@ export async function emitEvents(deps) {
109
130
  bound = combined.filter(event => eventDatedSince(event, offSinceMs) && hasWorkMeshEventCompanyBinding(event, env));
110
131
  }
111
132
  if (bound.length === 0) {
112
- const written = writeEmitRetry(deps.workMeshRoot, combined, retryMax);
133
+ const written = persistRetry(combined);
113
134
  return { ...summary, attempted: 0, retained: written.written,
114
135
  retryDepth: written.written, droppedOverflow: written.dropped };
115
136
  }
@@ -193,7 +214,7 @@ export async function emitEvents(deps) {
193
214
  }
194
215
  }
195
216
  }
196
- const written = writeEmitRetry(deps.workMeshRoot, keep, retryMax);
217
+ const written = persistRetry(keep);
197
218
  summary.retained = written.written;
198
219
  summary.droppedOverflow = written.dropped;
199
220
  summary.retryDepth = written.written;
@@ -87,6 +87,7 @@ export interface FlushDeps {
87
87
  */
88
88
  onSpoolLinesClaimed?: (lines: string[]) => void;
89
89
  }
90
+ export type FlushNoClaimReason = "operator_switch_off" | "anywhere_off_no_company_session_event";
90
91
  export interface FlushSummary {
91
92
  claimed: number;
92
93
  posted: number;
@@ -99,6 +100,7 @@ export interface FlushSummary {
99
100
  heldClaimed?: boolean;
100
101
  /** Oldest held lines dead-lettered this flush due to HELD_MAX_LINES. */
101
102
  heldOverflow?: number;
103
+ noClaimReason?: FlushNoClaimReason;
102
104
  }
103
105
  /**
104
106
  * Flush spool + held. Safe to call concurrently with enqueue (claim-by-rename).