@indigoai-us/hq-cli 5.345.245 → 5.345.246

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 (113) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/dist/command-catalog.generated.d.ts +93 -6
  3. package/dist/command-catalog.generated.js +114 -6
  4. package/dist/commands/bot.js +1 -1
  5. package/dist/commands/core-checkpoint-native.d.ts +5 -1
  6. package/dist/commands/core-checkpoint-native.js +13 -5
  7. package/dist/commands/deploy-comments.js +139 -0
  8. package/dist/commands/deploy-list.d.ts +5 -0
  9. package/dist/commands/deploy-list.js +8 -0
  10. package/dist/commands/dm.d.ts +4 -1
  11. package/dist/commands/dm.js +11 -2
  12. package/dist/commands/files.d.ts +11 -2
  13. package/dist/commands/files.js +48 -3
  14. package/dist/commands/lanes-loop.js +4 -1
  15. package/dist/commands/lanes.js +16 -5
  16. package/dist/commands/mesh.d.ts +2 -0
  17. package/dist/commands/mesh.js +26 -6
  18. package/dist/commands/reindex.js +2 -1
  19. package/dist/commands/rescue.d.ts +22 -1
  20. package/dist/commands/rescue.js +56 -9
  21. package/dist/commands/sources.d.ts +1 -1
  22. package/dist/commands/sources.js +1 -1
  23. package/dist/commands/storage.d.ts +15 -2
  24. package/dist/commands/storage.js +74 -7
  25. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +232 -225
  26. package/dist/hq-cloud-sync-runner/package.json +1 -1
  27. package/dist/lib/agent-kit/mcp/tools.js +22 -0
  28. package/dist/lib/bot/jobs/hot-signal-sync.js +4 -1
  29. package/dist/lib/daemon/fleet-members-cache.d.ts +55 -0
  30. package/dist/lib/daemon/fleet-members-cache.js +266 -0
  31. package/dist/lib/daemon/handoff.d.ts +4 -0
  32. package/dist/lib/daemon/handoff.js +2 -1
  33. package/dist/lib/daemon/hook-requests.d.ts +2 -1
  34. package/dist/lib/daemon/hook-requests.js +19 -2
  35. package/dist/lib/daemon/install.d.ts +9 -1
  36. package/dist/lib/daemon/install.js +11 -2
  37. package/dist/lib/daemon/ops/policy.d.ts +23 -3
  38. package/dist/lib/daemon/ops/policy.js +62 -15
  39. package/dist/lib/daemon/run.js +12 -0
  40. package/dist/lib/daemon/server.d.ts +5 -0
  41. package/dist/lib/daemon/server.js +1 -1
  42. package/dist/lib/daemon/supervisor.d.ts +6 -0
  43. package/dist/lib/daemon/supervisor.js +31 -2
  44. package/dist/lib/doctor/checks/sync-runtime.js +8 -1
  45. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  46. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  47. package/dist/lib/hook-engine/coverage.d.ts +68 -0
  48. package/dist/lib/hook-engine/coverage.js +163 -0
  49. package/dist/lib/hook-engine/native-precompact-compatibility.json +1 -0
  50. package/dist/lib/hot-channels/signals-pass.d.ts +52 -2
  51. package/dist/lib/hot-channels/signals-pass.js +65 -3
  52. package/dist/lib/install/claude-targets.d.ts +6 -0
  53. package/dist/lib/install/claude-targets.js +9 -1
  54. package/dist/lib/lanes/reconcile-result.d.ts +1 -1
  55. package/dist/lib/lanes/reconcile.js +19 -4
  56. package/dist/lib/lanes/remote-control-lane.d.ts +6 -0
  57. package/dist/lib/lanes/remote-control-lane.js +10 -1
  58. package/dist/lib/lanes/spawn.d.ts +2 -0
  59. package/dist/lib/lanes/spawn.js +19 -3
  60. package/dist/lib/lanes/worker-env-scrub.d.ts +48 -0
  61. package/dist/lib/lanes/worker-env-scrub.js +146 -0
  62. package/dist/lib/lanes/worker-process.js +4 -1
  63. package/dist/lib/mesh/client.js +5 -1
  64. package/dist/lib/mesh/live/daemon/doctor.d.ts +9 -0
  65. package/dist/lib/mesh/live/daemon/doctor.js +51 -6
  66. package/dist/lib/mesh/live/daemon/install.d.ts +39 -0
  67. package/dist/lib/mesh/live/daemon/install.js +70 -0
  68. package/dist/lib/mesh/live/daemon/outbox-company.d.ts +47 -0
  69. package/dist/lib/mesh/live/daemon/outbox-company.js +77 -0
  70. package/dist/lib/mesh/live/daemon/run.d.ts +2 -0
  71. package/dist/lib/mesh/live/daemon/run.js +48 -3
  72. package/dist/lib/mesh/live/daemon/state.d.ts +5 -0
  73. package/dist/lib/mesh/live/daemon/system-unit.d.ts +21 -0
  74. package/dist/lib/mesh/live/daemon/system-unit.js +80 -0
  75. package/dist/lib/mesh/live/daemon/transcript-watch.d.ts +4 -1
  76. package/dist/lib/mesh/live/daemon/transcript-watch.js +42 -38
  77. package/dist/lib/mesh/live/direct-drain.js +3 -1
  78. package/dist/lib/mesh/live/emit.js +4 -2
  79. package/dist/lib/mesh/live/flush.d.ts +61 -0
  80. package/dist/lib/mesh/live/flush.js +434 -114
  81. package/dist/lib/mesh/live/paths.d.ts +10 -0
  82. package/dist/lib/mesh/live/paths.js +14 -0
  83. package/dist/lib/mesh/live/reporting-privacy.d.ts +41 -1
  84. package/dist/lib/mesh/live/reporting-privacy.js +81 -7
  85. package/dist/lib/mesh/live/spool.d.ts +171 -17
  86. package/dist/lib/mesh/live/spool.js +777 -62
  87. package/dist/lib/signals/engine.d.ts +82 -2
  88. package/dist/lib/signals/engine.js +389 -53
  89. package/dist/lib/signals/steps/extract.js +5 -0
  90. package/dist/lib/work-context/organize.d.ts +22 -4
  91. package/dist/lib/work-context/organize.js +50 -21
  92. package/dist/lib/work-context/paths.d.ts +6 -0
  93. package/dist/lib/work-context/paths.js +9 -0
  94. package/dist/lib/work-context/reconcile.d.ts +1 -1
  95. package/dist/lib/work-context/reconcile.js +1 -1
  96. package/dist/startup-registration.d.ts +14 -0
  97. package/dist/startup-registration.js +26 -0
  98. package/dist/utils/cli-telemetry.d.ts +6 -0
  99. package/dist/utils/cli-telemetry.js +154 -9
  100. package/dist/utils/github-tag-fallback.d.ts +7 -2
  101. package/dist/utils/github-tag-fallback.js +17 -8
  102. package/dist/utils/hq-core-source.d.ts +31 -0
  103. package/dist/utils/hq-core-source.js +144 -0
  104. package/dist/utils/interactive-caller.d.ts +6 -0
  105. package/dist/utils/interactive-caller.js +8 -0
  106. package/dist/utils/shipped-codex-hooks.d.ts +6 -4
  107. package/dist/utils/shipped-codex-hooks.js +22 -10
  108. package/dist/utils/vault-api.js +1 -0
  109. package/dist/utils/version-report.d.ts +3 -1
  110. package/dist/utils/version-report.js +13 -5
  111. package/docs/anywhere-runtime.md +2 -2
  112. package/package.json +8 -8
  113. package/scripts/check-function-manifest.mjs +99 -18
@@ -1 +1 @@
1
- {"name":"hq-cli-daemon-sync-runner","type":"module","version":"6.18.120","bundleSha256":"69d850f48fdc6b6e1213b06d7b78b60f8a0c3a9b1fcc98520a59ba6919087cc3","formatVersion":1}
1
+ {"name":"hq-cli-daemon-sync-runner","type":"module","version":"6.18.121","bundleSha256":"93df1547b4ae2346bf65b1a16eba2410370625efaab1e29fd93ca0a4e627410d","formatVersion":1}
@@ -282,6 +282,12 @@ export function buildAgentMcpTools(clients) {
282
282
  if (res.status < 200 || res.status >= 300) {
283
283
  return errorResult(`DM send failed (${res.status}): ${describeError(res.body)}`);
284
284
  }
285
+ // hq-pro-core 1.178.0+: an agent-to-agent DM the bot loop breaker held
286
+ // is stored (200) but never reaches the recipient. Say so plainly
287
+ // instead of "sent", so the agent does not assume it was delivered.
288
+ const held = heldDeliveryNotice(res.body);
289
+ if (held)
290
+ return textResult(`WARNING: saved but NOT delivered to ${to}. ${held}`);
285
291
  return textResult(`sent to ${to}`);
286
292
  },
287
293
  },
@@ -449,6 +455,22 @@ export function buildAgentMcpTools(clients) {
449
455
  },
450
456
  ];
451
457
  }
458
+ /**
459
+ * The server's explanation when a DM was stored but held back from the
460
+ * recipient (`delivery: "held"`), or undefined for a delivered DM.
461
+ */
462
+ function heldDeliveryNotice(body) {
463
+ if (!body || typeof body !== "object")
464
+ return undefined;
465
+ const b = body;
466
+ if (b.delivery !== "held")
467
+ return undefined;
468
+ const detail = typeof b.heldDetail === "string" && b.heldDetail.trim()
469
+ ? b.heldDetail.trim()
470
+ : "The server held this DM; the recipient was not given it.";
471
+ const reason = typeof b.heldReason === "string" && b.heldReason ? ` (${b.heldReason})` : "";
472
+ return `${detail}${reason}`;
473
+ }
452
474
  function describeError(body) {
453
475
  if (body && typeof body === "object") {
454
476
  const b = body;
@@ -446,9 +446,12 @@ async function runSignalsEngineJob(input) {
446
446
  // Check it before this run replaces the record; one alert per stopped run.
447
447
  // Yesterday's record is checked too: a hung morning run usually has no
448
448
  // later fire that day, so the next morning's fire is the first to see it.
449
+ // Today goes first. The owner gets one alert an hour, and the run below
450
+ // replaces today's record, so this fire is the only one that can report a
451
+ // run that died today; yesterday's records stay on disk for a later fire.
449
452
  if (input.sendAlert) {
450
453
  const senders = { sendOwnerDm: input.sendAlert, ...(input.log ? { log: input.log } : {}) };
451
- for (const daysAgo of [1, 0]) {
454
+ for (const daysAgo of [0, 1]) {
452
455
  await raiseStoppedRunAlert({ hqRoot: input.hqRoot, company: input.company, now: input.now, senders, daysAgo });
453
456
  }
454
457
  }
@@ -0,0 +1,55 @@
1
+ export declare const FLEET_MEMBERS_TTL_SECONDS = 600;
2
+ export declare const FLEET_MEMBERS_MARGIN_SECONDS = 150;
3
+ export declare const FLEET_MEMBERS_INTERVAL_MS = 60000;
4
+ export declare const FLEET_MEMBERS_RETRY_MS: number;
5
+ export declare const FLEET_MEMBERS_KILL_MS = 60000;
6
+ export type FleetMembersRefreshOperation = {
7
+ kind: "fleet-members-refresh";
8
+ companies: string[];
9
+ cacheDir: string;
10
+ };
11
+ export declare function ownerSlug(slug: unknown): slug is string;
12
+ export declare function parseFleetMembersRefresh(kind: unknown, args: Record<string, unknown>): FleetMembersRefreshOperation | undefined;
13
+ export declare function fleetMembersCacheDir(home: string, env: NodeJS.ProcessEnv): string;
14
+ export declare function fleetMembersTtlSeconds(env: NodeJS.ProcessEnv): number;
15
+ export declare function memberIdsFromList(stdout: string): unknown[] | undefined;
16
+ export declare function cacheAgeSeconds(file: string, now: number): number | undefined;
17
+ export declare function needsRefresh(file: string, ttlSeconds: number, now: number): boolean;
18
+ export declare function writeMemberCache(dir: string, slug: string, ids: unknown[], now: number): boolean;
19
+ export interface MembersListOptions {
20
+ nodeBinary: string;
21
+ hqBinary: string;
22
+ env?: NodeJS.ProcessEnv;
23
+ signal?: AbortSignal;
24
+ timeoutMs?: number;
25
+ killGraceMs?: number;
26
+ }
27
+ export type MembersList = (slug: string) => Promise<string | undefined>;
28
+ export declare function hqMembersList(options: MembersListOptions): MembersList;
29
+ export declare function refreshMemberCache(dir: string, slug: string, list: MembersList, now?: () => number): Promise<boolean>;
30
+ export declare function runFleetMembersRefresh(operation: FleetMembersRefreshOperation, list: MembersList, options: {
31
+ home: string;
32
+ env: NodeJS.ProcessEnv;
33
+ now?: () => number;
34
+ companies?: () => string[];
35
+ }): Promise<{
36
+ code: number;
37
+ }>;
38
+ export declare function fleetLocalOwnerCompanies(home: string, env: NodeJS.ProcessEnv): string[];
39
+ export interface FleetMembersWarmerOptions {
40
+ home: string;
41
+ env: NodeJS.ProcessEnv;
42
+ log: (level: "info" | "warn" | "error", message: string) => void;
43
+ list: MembersList;
44
+ abort?: AbortController;
45
+ companies?: () => string[];
46
+ intervalMs?: number;
47
+ now?: () => number;
48
+ schedule?: (callback: () => void, delayMs: number) => () => void;
49
+ }
50
+ export interface FleetMembersWarmer {
51
+ tick(): Promise<void>;
52
+ close(): void;
53
+ }
54
+ export declare function startFleetMembersWarmer(options: FleetMembersWarmerOptions): FleetMembersWarmer;
55
+ //# sourceMappingURL=fleet-members-cache.d.ts.map
@@ -0,0 +1,266 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { listFleetBots } from "../bot/fleet-daemon.js";
5
+ import { fleetHome, fleetLocalProfileDir } from "../bot/fleet-local.js";
6
+ import { botsRoot } from "../bot/paths.js";
7
+ import { spawnRequestProgram } from "./hook-requests.js";
8
+ export const FLEET_MEMBERS_TTL_SECONDS = 600;
9
+ export const FLEET_MEMBERS_MARGIN_SECONDS = 150;
10
+ export const FLEET_MEMBERS_INTERVAL_MS = 60_000;
11
+ export const FLEET_MEMBERS_RETRY_MS = 5 * 60_000;
12
+ export const FLEET_MEMBERS_KILL_MS = 60_000;
13
+ const MAX_COMPANIES = 64;
14
+ const PATH_MAX_BYTES = 1024;
15
+ const STDOUT_MAX_BYTES = 4 * 1024 * 1024;
16
+ const SLUG = /^[a-z0-9][a-z0-9_-]*$/;
17
+ export function ownerSlug(slug) {
18
+ return typeof slug === "string" && SLUG.test(slug) && slug !== "personal";
19
+ }
20
+ export function parseFleetMembersRefresh(kind, args) {
21
+ if (kind !== "fleet-members-refresh")
22
+ return undefined;
23
+ if (Object.keys(args).sort().join(",") !== "cacheDir,companies")
24
+ return undefined;
25
+ const { companies, cacheDir } = args;
26
+ if (typeof cacheDir !== "string" || cacheDir.includes("\0") || !path.isAbsolute(cacheDir)
27
+ || Buffer.byteLength(cacheDir) > PATH_MAX_BYTES)
28
+ return undefined;
29
+ if (!Array.isArray(companies) || companies.length === 0 || companies.length > MAX_COMPANIES || !companies.every(ownerSlug))
30
+ return undefined;
31
+ return { kind, companies: [...new Set(companies)], cacheDir };
32
+ }
33
+ export function fleetMembersCacheDir(home, env) {
34
+ const explicit = env.HQ_FLEET_LOCAL_MEMBERS_CACHE;
35
+ if (explicit && path.isAbsolute(explicit))
36
+ return explicit;
37
+ return path.join(home || "/tmp", ".hq-fleet", "cache", "company-members");
38
+ }
39
+ export function fleetMembersTtlSeconds(env) {
40
+ const value = env.HQ_FLEET_LOCAL_MEMBERS_TTL;
41
+ if (value === undefined || value === "")
42
+ return FLEET_MEMBERS_TTL_SECONDS;
43
+ return /^[0-9]{1,9}$/.test(value) ? Number(value) : FLEET_MEMBERS_TTL_SECONDS;
44
+ }
45
+ export function memberIdsFromList(stdout) {
46
+ let top;
47
+ try {
48
+ top = JSON.parse(stdout);
49
+ }
50
+ catch {
51
+ return undefined;
52
+ }
53
+ let list = top;
54
+ if (top && typeof top === "object" && !Array.isArray(top)) {
55
+ const members = top.members;
56
+ if (members !== undefined && members !== null && members !== false)
57
+ list = members;
58
+ }
59
+ let items;
60
+ if (Array.isArray(list))
61
+ items = list;
62
+ else if (list && typeof list === "object")
63
+ items = Object.values(list);
64
+ else
65
+ return undefined;
66
+ const out = [];
67
+ for (const item of items) {
68
+ if (item === null)
69
+ continue;
70
+ if (typeof item !== "object" || Array.isArray(item))
71
+ return undefined;
72
+ const entry = item;
73
+ const status = entry.status === undefined || entry.status === null || entry.status === false ? "active" : entry.status;
74
+ if (status !== "active")
75
+ continue;
76
+ const id = entry.person_id;
77
+ if (id === undefined || id === null || id === false)
78
+ continue;
79
+ out.push(id);
80
+ }
81
+ return out;
82
+ }
83
+ export function cacheAgeSeconds(file, now) {
84
+ try {
85
+ const stat = fs.statSync(file);
86
+ if (!stat.isFile())
87
+ return undefined;
88
+ return Math.floor(now / 1000) - Math.floor(stat.mtimeMs / 1000);
89
+ }
90
+ catch {
91
+ return undefined;
92
+ }
93
+ }
94
+ export function needsRefresh(file, ttlSeconds, now) {
95
+ const age = cacheAgeSeconds(file, now);
96
+ return age === undefined || age >= Math.max(0, ttlSeconds - FLEET_MEMBERS_MARGIN_SECONDS);
97
+ }
98
+ export function writeMemberCache(dir, slug, ids, now) {
99
+ const target = path.join(dir, `${slug}.json`);
100
+ const text = `${JSON.stringify(ids)}\n`;
101
+ try {
102
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
103
+ let same = false;
104
+ try {
105
+ same = fs.readFileSync(target, "utf8") === text;
106
+ }
107
+ catch {
108
+ same = false;
109
+ }
110
+ if (same) {
111
+ const at = new Date(now);
112
+ fs.utimesSync(target, at, at);
113
+ return true;
114
+ }
115
+ const stage = `${target}.${process.pid}.${randomUUID()}`;
116
+ try {
117
+ fs.writeFileSync(stage, text, { mode: 0o600 });
118
+ fs.chmodSync(stage, 0o600);
119
+ fs.renameSync(stage, target);
120
+ }
121
+ finally {
122
+ fs.rmSync(stage, { force: true });
123
+ }
124
+ return true;
125
+ }
126
+ catch {
127
+ return false;
128
+ }
129
+ }
130
+ export function hqMembersList(options) {
131
+ return slug => new Promise(resolve => {
132
+ if (options.signal?.aborted) {
133
+ resolve(undefined);
134
+ return;
135
+ }
136
+ const env = { ...(options.env ?? process.env), HQ_MACHINE_CREDS_FILE: "", HQ_NO_UPDATE_CHECK: "1" };
137
+ const { child, settle } = spawnRequestProgram(options.nodeBinary, [options.hqBinary, "members", "list", "--company", slug, "--json"], {
138
+ env, windowsHide: true, stdio: ["ignore", "pipe", "ignore"],
139
+ }, { timeoutMs: options.timeoutMs ?? FLEET_MEMBERS_KILL_MS, killGraceMs: options.killGraceMs, signal: options.signal });
140
+ let out = "";
141
+ child.stdout?.setEncoding("utf8");
142
+ child.stdout?.on("data", (text) => { if (out.length < STDOUT_MAX_BYTES)
143
+ out += text; });
144
+ child.stdout?.on("error", () => undefined);
145
+ let settled = false;
146
+ const done = (code) => {
147
+ if (settled)
148
+ return;
149
+ settled = true;
150
+ const ended = settle();
151
+ resolve(!ended && code === 0 ? out : undefined);
152
+ };
153
+ child.once("error", () => done(1));
154
+ child.once("close", code => done(code ?? 1));
155
+ });
156
+ }
157
+ export async function refreshMemberCache(dir, slug, list, now = Date.now) {
158
+ const stdout = await list(slug);
159
+ if (stdout === undefined)
160
+ return false;
161
+ const ids = memberIdsFromList(stdout);
162
+ if (!ids)
163
+ return false;
164
+ return writeMemberCache(dir, slug, ids, now());
165
+ }
166
+ function samePath(a, b) {
167
+ const real = (p) => { try {
168
+ return fs.realpathSync(p);
169
+ }
170
+ catch {
171
+ return path.resolve(p);
172
+ } };
173
+ return real(a) === real(b);
174
+ }
175
+ export async function runFleetMembersRefresh(operation, list, options) {
176
+ const now = options.now ?? Date.now;
177
+ if (!samePath(operation.cacheDir, fleetMembersCacheDir(options.home, options.env)))
178
+ return { code: 0 };
179
+ const owned = (options.companies ?? (() => fleetLocalOwnerCompanies(options.home, options.env)))();
180
+ for (const slug of operation.companies) {
181
+ if (!owned.includes(slug))
182
+ continue;
183
+ await refreshMemberCache(operation.cacheDir, slug, list, now);
184
+ }
185
+ return { code: 0 };
186
+ }
187
+ export function fleetLocalOwnerCompanies(home, env) {
188
+ const out = [];
189
+ const root = fleetHome(home, env);
190
+ for (const bot of listFleetBots(botsRoot(home, env))) {
191
+ let raw;
192
+ try {
193
+ raw = JSON.parse(fs.readFileSync(path.join(fleetLocalProfileDir(bot.config.agentUid, { fleetHome: root }), "profile.json"), "utf8"));
194
+ }
195
+ catch {
196
+ continue;
197
+ }
198
+ if (!raw || typeof raw !== "object")
199
+ continue;
200
+ const { ownerCompanies, hqRoot } = raw;
201
+ if (!Array.isArray(ownerCompanies) || typeof hqRoot !== "string" || !path.isAbsolute(hqRoot))
202
+ continue;
203
+ for (const slug of ownerCompanies) {
204
+ if (!ownerSlug(slug) || out.includes(slug))
205
+ continue;
206
+ const folder = path.join(hqRoot, "companies", slug);
207
+ const facts = fs.lstatSync(folder, { throwIfNoEntry: false });
208
+ if (facts?.isDirectory() !== true)
209
+ continue;
210
+ out.push(slug);
211
+ }
212
+ }
213
+ return out;
214
+ }
215
+ export function startFleetMembersWarmer(options) {
216
+ const now = options.now ?? Date.now;
217
+ const companies = options.companies ?? (() => fleetLocalOwnerCompanies(options.home, options.env));
218
+ const dir = fleetMembersCacheDir(options.home, options.env);
219
+ const ttl = fleetMembersTtlSeconds(options.env);
220
+ const failedAt = new Map();
221
+ const schedule = options.schedule ?? ((callback, delayMs) => {
222
+ const timer = setInterval(callback, delayMs);
223
+ timer.unref();
224
+ return () => clearInterval(timer);
225
+ });
226
+ let closed = false;
227
+ let inFlight = null;
228
+ const tick = () => {
229
+ if (closed)
230
+ return Promise.resolve();
231
+ if (inFlight)
232
+ return inFlight;
233
+ inFlight = (async () => {
234
+ let slugs;
235
+ try {
236
+ slugs = companies();
237
+ }
238
+ catch {
239
+ slugs = [];
240
+ }
241
+ for (const slug of slugs) {
242
+ if (closed)
243
+ return;
244
+ if (!needsRefresh(path.join(dir, `${slug}.json`), ttl, now()))
245
+ continue;
246
+ const failed = failedAt.get(slug);
247
+ if (failed !== undefined && now() - failed < FLEET_MEMBERS_RETRY_MS)
248
+ continue;
249
+ if (await refreshMemberCache(dir, slug, options.list, now))
250
+ failedAt.delete(slug);
251
+ else {
252
+ failedAt.set(slug, now());
253
+ options.log("warn", `fleet member cache for ${slug} could not be refreshed`);
254
+ }
255
+ }
256
+ })().finally(() => { inFlight = null; });
257
+ return inFlight;
258
+ };
259
+ const cancel = schedule(() => { void tick(); }, options.intervalMs ?? FLEET_MEMBERS_INTERVAL_MS);
260
+ void tick();
261
+ return {
262
+ tick,
263
+ close: () => { closed = true; cancel(); options.abort?.abort(); },
264
+ };
265
+ }
266
+ //# sourceMappingURL=fleet-members-cache.js.map
@@ -60,5 +60,9 @@ export declare function handOffInstall(opts: {
60
60
  export declare function handOffInstallHere(services: readonly ServiceName[], env?: NodeJS.ProcessEnv, opts?: {
61
61
  hqRoot?: string;
62
62
  ifStale?: boolean;
63
+ /** Home folder to look for the hq daemon unit in (tests pass a fake one). */
64
+ home?: string;
65
+ /** Directory holding system units on Linux (tests pass a fake root). */
66
+ systemUnitDir?: string;
63
67
  }): string | null;
64
68
  //# sourceMappingURL=handoff.d.ts.map
@@ -144,7 +144,7 @@ export function handOffInstall(opts) {
144
144
  }
145
145
  /** handOffInstall for this machine and user, for the older install commands. */
146
146
  export function handOffInstallHere(services, env = process.env, opts = {}) {
147
- const home = os.homedir();
147
+ const home = opts.home ?? os.homedir();
148
148
  const paths = daemonPaths(home, env);
149
149
  const config = readDaemonConfig(paths.configPath);
150
150
  if (opts.ifStale && services.every((service) => config.disable.includes(service))) {
@@ -154,6 +154,7 @@ export function handOffInstallHere(services, env = process.env, opts = {}) {
154
154
  const installed = daemonUnitInstalled({
155
155
  platform: process.platform,
156
156
  home,
157
+ systemUnitDir: opts.systemUnitDir,
157
158
  windowsTaskName: identity ? windowsTaskName(identity) : "",
158
159
  windowsLegacyTaskIsMine: () => identity !== undefined && legacyWindowsTask(defaultRunCommand, identity).state === "mine",
159
160
  windowsTaskExists: (task) => spawnSync("schtasks.exe", ["/Query", "/TN", task], { encoding: "utf8", windowsHide: true }).status === 0,
@@ -56,6 +56,7 @@ import { type MeshToolWritesOperation } from "./hook-requests-mesh-tool-writes.j
56
56
  import { type FleetLocalPromptOperation, type FleetSessionStartOperation } from "./hook-requests-fleet-session-start.js";
57
57
  import { type ConductLinkOperation } from "./hook-requests-conduct-link.js";
58
58
  import { type CodexSettingsOperation } from "./hook-requests-codex-settings.js";
59
+ import { type FleetMembersRefreshOperation } from "./fleet-members-cache.js";
59
60
  /** What the daemon is asked to do. A closed list, the same as `Kind` in daemon_req.rs. */
60
61
  export type HookOperation = {
61
62
  kind: "reindex";
@@ -108,7 +109,7 @@ export type HookOperation = {
108
109
  disabled?: MeshSessionBindSwitch;
109
110
  }
110
111
  /** One machine check run by the daemon for a SessionStart where the hooks own the checks (the machine-check notes at the end of this file). */
111
- | MachineCheckOperation | MeshOperation | MeshToolWritesOperation | CodexSettingsOperation | FleetSessionStartOperation | FleetLocalPromptOperation
112
+ | MachineCheckOperation | MeshOperation | MeshToolWritesOperation | CodexSettingsOperation | FleetSessionStartOperation | FleetLocalPromptOperation | FleetMembersRefreshOperation
112
113
  /** The Codex adapter's SubagentStop runs of the root's conduct-link hooks (hook-requests-conduct-link.ts). */
113
114
  | ConductLinkOperation;
114
115
  /**
@@ -65,6 +65,7 @@ import { parseMeshToolWrites, runMeshToolWrites } from "./hook-requests-mesh-too
65
65
  import { parseFleetLocalPrompt, parseFleetSessionStart, runFleetLocalPrompt, runFleetSessionStart } from "./hook-requests-fleet-session-start.js";
66
66
  import { isConductLinkKind, parseConductLink, runConductLink } from "./hook-requests-conduct-link.js";
67
67
  import { parseCodexSettings, runCodexSettings } from "./hook-requests-codex-settings.js";
68
+ import { hqMembersList, parseFleetMembersRefresh, runFleetMembersRefresh } from "./fleet-members-cache.js";
68
69
  /** The longest note the Rust writer leaves (`NOTE_MAX_BYTES`). */
69
70
  export const HOOK_REQUEST_MAX_BYTES = 4096;
70
71
  /** The longest `.body` file the Rust writer leaves (`BODY_MAX_BYTES`). */
@@ -324,6 +325,12 @@ export function parseHookRequest(text, stem) {
324
325
  return undefined;
325
326
  operation = codex;
326
327
  }
328
+ else if (value.kind === "fleet-members-refresh") {
329
+ const members = parseFleetMembersRefresh(value.kind, args);
330
+ if (!members)
331
+ return undefined;
332
+ operation = members;
333
+ }
327
334
  else if (isMachineCheckRequestKind(value.kind)) {
328
335
  const check = parseMachineCheckOperation(value.kind, args);
329
336
  if (!check)
@@ -432,7 +439,8 @@ export function hookRequestArguments(request) {
432
439
  // Not a CLI request: the Codex settings commands are started one by one (hook-requests-codex-settings.ts).
433
440
  case "codex-settings": return [];
434
441
  case "fleet-session-start":
435
- case "fleet-local-prompt": return [];
442
+ case "fleet-local-prompt":
443
+ case "fleet-members-refresh": return [];
436
444
  // Not a CLI request: the root's own conduct-link hook script is run (`runConductLink`).
437
445
  case "conduct-lanes-link-deliver":
438
446
  case "conduct-link-inherit": return [];
@@ -1449,7 +1457,7 @@ async function runMeshSessionBind(request, operation, base, options) {
1449
1457
  const contextRoot = workContextRoot(base.HOME, base);
1450
1458
  const state = readSessionState(operation.sessionId, contextRoot);
1451
1459
  const metaCompany = readMetaCompanySlug(operation.sessionId, request.root);
1452
- const bound = hasWorkMeshCompanyBinding(state) &&
1460
+ const bound = hasWorkMeshCompanyBinding(state, base, contextRoot) &&
1453
1461
  (metaCompany === undefined || metaCompany === state.companySlug) &&
1454
1462
  (operation.kind === "mesh-session-register" || operation.company === state.companySlug);
1455
1463
  if (!bound) {
@@ -1635,6 +1643,15 @@ export function executeHookRequest(request, options) {
1635
1643
  return runFleetSessionStart(request, operation, options);
1636
1644
  if (operation.kind === "fleet-local-prompt")
1637
1645
  return runFleetLocalPrompt(request, operation, options);
1646
+ if (operation.kind === "fleet-members-refresh") {
1647
+ const list = hqMembersList({
1648
+ nodeBinary: options.nodeBinary, hqBinary: options.hqBinary, ...(options.env ? { env: options.env } : {}),
1649
+ ...(options.signal ? { signal: options.signal } : {}), timeoutMs: options.timeoutMs ?? HOOK_REQUEST_KILL_MS,
1650
+ killGraceMs: options.killGraceMs ?? HOOK_REQUEST_KILL_GRACE_MS,
1651
+ });
1652
+ const env = options.env ?? process.env;
1653
+ return runFleetMembersRefresh(operation, list, { home: options.home ?? env.HOME ?? os.homedir(), env }).catch(() => ({ code: 0 }));
1654
+ }
1638
1655
  if (operation.kind === "codex-settings")
1639
1656
  return runCodexSettings(request, operation, { ...options, timeoutMs: options.timeoutMs ?? HOOK_REQUEST_KILL_MS, killGraceMs: options.killGraceMs ?? HOOK_REQUEST_KILL_GRACE_MS }).catch(() => ({ code: 1 }));
1640
1657
  const cliArgs = hookRequestArguments(request);
@@ -37,7 +37,15 @@ export declare function daemonWindowsTaskName(who: {
37
37
  sid?: string;
38
38
  user: string;
39
39
  }): string;
40
- /** The current Windows user's SID from `whoami /user`, or undefined when it cannot be read. */
40
+ /**
41
+ * The current Windows user's SID from `whoami /user`, or undefined when it
42
+ * cannot be read.
43
+ *
44
+ * Call System32's whoami.exe, not PATH. Git Bash/MSYS put a coreutils
45
+ * `whoami.exe` first; that binary rejects `/user`, so the SID looks unread
46
+ * and install registers the name-based task while the desktop app registered
47
+ * the SID task (feedback_9fa243e0).
48
+ */
41
49
  export declare function readWindowsSid(run: RunCommand): string | undefined;
42
50
  /** The per-user task name for the user running this process. */
43
51
  export declare function currentDaemonWindowsTaskName(run: RunCommand, user: string): string;
@@ -27,6 +27,7 @@ import { userToolDirs } from "./tools.js";
27
27
  import { liveDaemonLock, verifyDaemonForKill } from "./lock.js";
28
28
  import { daemonPaths } from "./paths.js";
29
29
  import { assertLoginHome, homeIsLoginSafe } from "../mesh/live/daemon/unit-home.js";
30
+ import { system32Tool } from "../work-context/windows-acl.js";
30
31
  export const DAEMON_LAUNCHD_LABEL = "ai.getindigo.hq-daemon";
31
32
  export const DAEMON_SYSTEMD_UNIT = "hq-daemon.service";
32
33
  /**
@@ -49,9 +50,17 @@ export function daemonWindowsTaskName(who) {
49
50
  const user = who.user.trim().replace(/[^A-Za-z0-9_.-]/g, "_");
50
51
  return `${LEGACY_DAEMON_WINDOWS_TASK}-${user || "user"}`;
51
52
  }
52
- /** The current Windows user's SID from `whoami /user`, or undefined when it cannot be read. */
53
+ /**
54
+ * The current Windows user's SID from `whoami /user`, or undefined when it
55
+ * cannot be read.
56
+ *
57
+ * Call System32's whoami.exe, not PATH. Git Bash/MSYS put a coreutils
58
+ * `whoami.exe` first; that binary rejects `/user`, so the SID looks unread
59
+ * and install registers the name-based task while the desktop app registered
60
+ * the SID task (feedback_9fa243e0).
61
+ */
53
62
  export function readWindowsSid(run) {
54
- const r = run("whoami.exe", ["/user", "/FO", "CSV", "/NH"]);
63
+ const r = run(system32Tool("whoami.exe"), ["/user", "/FO", "CSV", "/NH"]);
55
64
  if (r.status !== 0)
56
65
  return undefined;
57
66
  return /S-1-\d+(?:-\d+)+/.exec(r.stdout)?.[0];
@@ -16,6 +16,14 @@
16
16
  * a watcher can miss a change: on macOS fs.watch is backed by an FSEvents
17
17
  * stream that starts asynchronously, so a change made right after a rebuild
18
18
  * re-arms the watchers is never reported.
19
+ *
20
+ * A stamp alone can also miss a change. Linux sets a directory's mtime from
21
+ * the coarse kernel clock (one tick, about 1-10 ms), so a change made in the
22
+ * same tick as the rebuild's stat leaves dev:ino:mtime unchanged. This is git's
23
+ * "racy index" problem and gets git's answer: a directory whose mtime is within
24
+ * RACY_WINDOW_MS of the rebuild is racy, its names are kept, and list()
25
+ * re-reads it and compares names until its mtime is older than the window.
26
+ * Directories outside the window cost one stat per list(), as before.
19
27
  */
20
28
  import { type ResolveJqDeps, type VerifiedJq } from "../verified-jq.js";
21
29
  export declare const SCOPE_AUTHORIZER = ".claude/hooks/mandatory-scope-authorizer.sh";
@@ -30,18 +38,30 @@ export interface PolicyEntry {
30
38
  scope: "core" | "personal" | "company";
31
39
  company?: string;
32
40
  }
41
+ /**
42
+ * How close to a rebuild a directory's mtime may be before a later change could
43
+ * leave it unchanged. It must exceed the filesystem's mtime granularity: one
44
+ * kernel tick on Linux (up to 10 ms), nanoseconds on APFS, and 2 s on FAT and
45
+ * exFAT volumes, which set the bound. A wider window only means a recently
46
+ * changed directory is re-read (one readdir) on each list() for that long.
47
+ */
48
+ export declare const RACY_WINDOW_MS = 2000;
33
49
  /** Cached list of policy files under HQ_ROOT, invalidated by fs.watch. */
34
50
  export declare class PolicyIndex {
35
51
  readonly hqRoot: string;
36
52
  private readonly log;
53
+ /** Wall clock in ms, compared with directory mtimes. Injectable for tests. */
54
+ private readonly now;
37
55
  private entries;
38
- /** Directory stat stamps taken while building `entries` (dir -> stamp). */
39
- private stamps;
56
+ /** Directory state taken while building `entries` (dir -> stamp, plus names while racy). */
57
+ private dirStates;
40
58
  private watchers;
41
59
  private closed;
42
60
  /** Bumped on every invalidation; lets callers see that the cache was rebuilt. */
43
61
  version: number;
44
- constructor(hqRoot: string, log?: (level: "info" | "warn" | "error", message: string) => void);
62
+ constructor(hqRoot: string, log?: (level: "info" | "warn" | "error", message: string) => void,
63
+ /** Wall clock in ms, compared with directory mtimes. Injectable for tests. */
64
+ now?: () => number);
45
65
  /** Policies visible to `company`: core, personal, and that company only. */
46
66
  list(company?: string): PolicyEntry[];
47
67
  invalidate(): void;