@indigoai-us/hq-cli 5.345.226 → 5.345.228

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/CHANGELOG.md +142 -0
  2. package/dist/command-catalog.generated.d.ts +137 -0
  3. package/dist/command-catalog.generated.js +164 -0
  4. package/dist/commands/auth.d.ts +2 -2
  5. package/dist/commands/auth.js +3 -3
  6. package/dist/commands/core-delegate-w1b.js +92 -69
  7. package/dist/commands/core-delegate.d.ts +19 -1
  8. package/dist/commands/core-delegate.js +411 -6
  9. package/dist/commands/core-dm-bind-native.js +2 -1
  10. package/dist/commands/core-handoff.d.ts +5 -0
  11. package/dist/commands/core-handoff.js +1008 -14
  12. package/dist/commands/core-pin-native.d.ts +1 -0
  13. package/dist/commands/core-pin-native.js +3 -15
  14. package/dist/commands/core-register-project-native.d.ts +6 -0
  15. package/dist/commands/core-register-project-native.js +182 -52
  16. package/dist/commands/core-work-mesh-bind-trusted-native.js +4 -9
  17. package/dist/commands/daemon.js +2 -2
  18. package/dist/commands/index-cmd.d.ts +3 -1
  19. package/dist/commands/index-cmd.js +12 -0
  20. package/dist/commands/lanes-checks.js +1 -1
  21. package/dist/commands/lanes-session-start.d.ts +1 -2
  22. package/dist/commands/lanes-session-start.js +9 -145
  23. package/dist/commands/lanes-shared.d.ts +3 -0
  24. package/dist/commands/lanes.d.ts +3 -0
  25. package/dist/commands/lanes.js +94 -27
  26. package/dist/commands/link.d.ts +8 -3
  27. package/dist/commands/link.js +14 -17
  28. package/dist/commands/mcp-registration.d.ts +65 -7
  29. package/dist/commands/mcp-registration.js +289 -51
  30. package/dist/commands/mesh.d.ts +12 -0
  31. package/dist/commands/mesh.js +92 -10
  32. package/dist/commands/reindex.js +6 -0
  33. package/dist/commands/repo.d.ts +13 -0
  34. package/dist/commands/repo.js +39 -1
  35. package/dist/commands/sync-mode.d.ts +3 -1
  36. package/dist/commands/sync-mode.js +11 -1
  37. package/dist/lazy-commands.js +3 -4
  38. package/dist/lib/checkpoint-ontology/entity-file.js +4 -4
  39. package/dist/lib/checkpoint-ontology/merge-copies.js +7 -11
  40. package/dist/lib/checkpoint-ontology/plan.js +2 -1
  41. package/dist/lib/core-utils/archive-old-threads.js +5 -2
  42. package/dist/lib/core-utils/session-company.d.ts +13 -1
  43. package/dist/lib/core-utils/session-company.js +75 -4
  44. package/dist/lib/core-utils/worktree-resume.d.ts +6 -0
  45. package/dist/lib/core-utils/worktree-resume.js +8 -4
  46. package/dist/lib/daemon/background-qos.d.ts +7 -0
  47. package/dist/lib/daemon/background-qos.js +13 -0
  48. package/dist/lib/daemon/catalog.d.ts +9 -0
  49. package/dist/lib/daemon/catalog.js +8 -1
  50. package/dist/lib/daemon/hook-requests-acl-suggest.d.ts +18 -0
  51. package/dist/lib/daemon/hook-requests-acl-suggest.js +245 -0
  52. package/dist/lib/daemon/hook-requests-fleet-session-start.d.ts +32 -0
  53. package/dist/lib/daemon/hook-requests-fleet-session-start.js +214 -0
  54. package/dist/lib/daemon/hook-requests-mesh-tool-writes.d.ts +44 -0
  55. package/dist/lib/daemon/hook-requests-mesh-tool-writes.js +292 -0
  56. package/dist/lib/daemon/hook-requests-mesh.d.ts +54 -0
  57. package/dist/lib/daemon/hook-requests-mesh.js +559 -0
  58. package/dist/lib/daemon/hook-requests.d.ts +349 -8
  59. package/dist/lib/daemon/hook-requests.js +1312 -46
  60. package/dist/lib/daemon/machine-checks.d.ts +12 -2
  61. package/dist/lib/daemon/machine-checks.js +27 -10
  62. package/dist/lib/daemon/merge-sections.d.ts +24 -2
  63. package/dist/lib/daemon/merge-sections.js +58 -16
  64. package/dist/lib/daemon/ops/policy.js +4 -2
  65. package/dist/lib/daemon/resolver.js +9 -2
  66. package/dist/lib/daemon/run.d.ts +11 -7
  67. package/dist/lib/daemon/run.js +168 -24
  68. package/dist/lib/daemon/search-index-worker-v1.d.ts +2 -0
  69. package/dist/lib/daemon/search-index-worker-v1.js +25 -0
  70. package/dist/lib/daemon/session-registry.d.ts +0 -1
  71. package/dist/lib/daemon/session-registry.js +0 -3
  72. package/dist/lib/daemon/supervisor.d.ts +3 -1
  73. package/dist/lib/daemon/supervisor.js +1 -1
  74. package/dist/lib/daemon/tcc-eperm.d.ts +59 -4
  75. package/dist/lib/daemon/tcc-eperm.js +110 -8
  76. package/dist/lib/doctor/fix/process-identity.d.ts +20 -2
  77. package/dist/lib/doctor/fix/process-identity.js +48 -5
  78. package/dist/lib/hook-engine/canary-gate.js +1 -0
  79. package/dist/lib/hook-engine/native-stop-compatibility.json +2 -1
  80. package/dist/lib/hot-channels/adapters/attio.js +2 -1
  81. package/dist/lib/hot-channels/adapters/meetings.js +2 -1
  82. package/dist/lib/lanes/company-outposts.d.ts +37 -0
  83. package/dist/lib/lanes/company-outposts.js +164 -0
  84. package/dist/lib/lanes/liveness.d.ts +6 -0
  85. package/dist/lib/lanes/liveness.js +49 -8
  86. package/dist/lib/lanes/orphan-report.d.ts +15 -0
  87. package/dist/lib/lanes/orphan-report.js +223 -0
  88. package/dist/lib/lanes/orphan-sweep.d.ts +26 -0
  89. package/dist/lib/lanes/orphan-sweep.js +152 -0
  90. package/dist/lib/lanes/reaper.d.ts +2 -0
  91. package/dist/lib/lanes/reaper.js +11 -8
  92. package/dist/lib/lanes/reconcile.d.ts +8 -7
  93. package/dist/lib/lanes/reconcile.js +39 -0
  94. package/dist/lib/mesh/live/backfill-held.d.ts +13 -0
  95. package/dist/lib/mesh/live/backfill-held.js +23 -0
  96. package/dist/lib/mesh/live/daemon/mode.d.ts +8 -4
  97. package/dist/lib/mesh/live/daemon/mode.js +8 -4
  98. package/dist/lib/mesh/live/daemon/run.d.ts +14 -3
  99. package/dist/lib/mesh/live/daemon/run.js +116 -7
  100. package/dist/lib/mesh/live/direct-drain.d.ts +123 -0
  101. package/dist/lib/mesh/live/direct-drain.js +315 -0
  102. package/dist/lib/mesh/live/emit-replay.d.ts +10 -0
  103. package/dist/lib/mesh/live/emit-replay.js +10 -0
  104. package/dist/lib/mesh/live/flush.d.ts +15 -0
  105. package/dist/lib/mesh/live/flush.js +27 -0
  106. package/dist/lib/mesh/live/liveness-carry.d.ts +45 -0
  107. package/dist/lib/mesh/live/liveness-carry.js +141 -0
  108. package/dist/lib/mesh/live/spool.d.ts +19 -0
  109. package/dist/lib/mesh/live/spool.js +80 -0
  110. package/dist/lib/safe-store.d.ts +2 -0
  111. package/dist/lib/safe-store.js +8 -6
  112. package/dist/lib/search-index/index.d.ts +9 -3
  113. package/dist/lib/search-index/index.js +35 -10
  114. package/dist/lib/search-index/worker-process.d.ts +9 -0
  115. package/dist/lib/search-index/worker-process.js +171 -0
  116. package/dist/lib/session-company-lock.d.ts +3 -1
  117. package/dist/lib/session-company-lock.js +3 -2
  118. package/dist/utils/delegate-command-supervisor.d.ts +3 -0
  119. package/dist/utils/delegate-command-supervisor.js +44 -0
  120. package/dist/utils/delegate-lock.d.ts +12 -0
  121. package/dist/utils/delegate-lock.js +88 -0
  122. package/dist/utils/frontmatter.d.ts +27 -0
  123. package/dist/utils/frontmatter.js +33 -0
  124. package/dist/utils/hook-trust.d.ts +1 -0
  125. package/dist/utils/hook-trust.js +18 -2
  126. package/dist/utils/host-registration.d.ts +13 -1
  127. package/dist/utils/host-registration.js +98 -5
  128. package/dist/utils/package-use-lease.d.ts +1 -1
  129. package/dist/utils/package-use-lease.js +15 -7
  130. package/docs/anywhere-runtime.md +17 -0
  131. package/package.json +8 -7
  132. package/scripts/check-function-manifest.mjs +17 -3
@@ -76,6 +76,14 @@ export interface RunMachineChecksOptions {
76
76
  /** Write the results here (through the store rules) after the batch. */
77
77
  resultsFile?: string;
78
78
  resultsWrite?: StoreFileWriteOptions;
79
+ /**
80
+ * One check run for a daemon request note, not a batch. It answers from a
81
+ * batch already running, but it never takes the in-flight slot: a batch
82
+ * started meanwhile is not handed its answer, runs every check and writes
83
+ * its results file. The batch waits for it first, so scripts still run one
84
+ * at a time.
85
+ */
86
+ single?: boolean;
79
87
  /** Test seams. */
80
88
  checks?: readonly MachineCheckSpec[];
81
89
  killGraceMs?: number;
@@ -126,8 +134,10 @@ export declare const MACHINE_CHECK_COLLECT_ONLY_KEY = "machineCheckCollectOnly";
126
134
  export declare function machineCheckCollectOnlySupported(hqRoot: string): boolean;
127
135
  /**
128
136
  * Run every machine check once, one at a time. A call while a batch is
129
- * running returns that batch. Inside a machine check
130
- * (HQ_MACHINE_CHECKS_RUNNING=1) nothing runs and the answer is empty.
137
+ * running returns that batch. A single run does not take that slot; a run
138
+ * that starts while one is going waits for it, then runs its own checks.
139
+ * Inside a machine check (HQ_MACHINE_CHECKS_RUNNING=1) nothing runs and the
140
+ * answer is empty.
131
141
  */
132
142
  export declare function runMachineChecks(options: RunMachineChecksOptions): Promise<MachineCheckResult[]>;
133
143
  /** Written atomically through src/lib/safe-store.ts in the daemon's private folder. */
@@ -312,10 +312,14 @@ async function runOne(spec, options, env, disabled, shell) {
312
312
  return resultFromStdout(spec.id, run.stdout, at());
313
313
  }
314
314
  let inFlight;
315
+ /** The last single run (options.single) still going. It never answers a batch. */
316
+ let singleTail;
315
317
  /**
316
318
  * Run every machine check once, one at a time. A call while a batch is
317
- * running returns that batch. Inside a machine check
318
- * (HQ_MACHINE_CHECKS_RUNNING=1) nothing runs and the answer is empty.
319
+ * running returns that batch. A single run does not take that slot; a run
320
+ * that starts while one is going waits for it, then runs its own checks.
321
+ * Inside a machine check (HQ_MACHINE_CHECKS_RUNNING=1) nothing runs and the
322
+ * answer is empty.
319
323
  */
320
324
  export function runMachineChecks(options) {
321
325
  const env = options.env ?? process.env;
@@ -323,7 +327,10 @@ export function runMachineChecks(options) {
323
327
  return Promise.resolve([]);
324
328
  if (inFlight)
325
329
  return inFlight;
326
- const batch = (async () => {
330
+ const before = singleTail;
331
+ const run = (async () => {
332
+ if (before)
333
+ await before.then(() => undefined, () => undefined);
327
334
  const disabled = disabledIds(env);
328
335
  const shell = machineCheckShell(options.platform ?? process.platform, env, options.resolveBash);
329
336
  const results = [];
@@ -334,13 +341,23 @@ export function runMachineChecks(options) {
334
341
  writeMachineCheckResults(options.resultsFile, results, options.resultsWrite);
335
342
  return results;
336
343
  })();
337
- inFlight = batch;
338
- const clear = () => {
339
- if (inFlight === batch)
340
- inFlight = undefined;
341
- };
342
- batch.then(clear, clear);
343
- return batch;
344
+ if (options.single === true) {
345
+ singleTail = run;
346
+ const clear = () => {
347
+ if (singleTail === run)
348
+ singleTail = undefined;
349
+ };
350
+ run.then(clear, clear);
351
+ }
352
+ else {
353
+ inFlight = run;
354
+ const clear = () => {
355
+ if (inFlight === run)
356
+ inFlight = undefined;
357
+ };
358
+ run.then(clear, clear);
359
+ }
360
+ return run;
344
361
  }
345
362
  /** Written atomically through src/lib/safe-store.ts in the daemon's private folder. */
346
363
  export function writeMachineCheckResults(file, results, options = {}) {
@@ -83,10 +83,24 @@ export interface MergeApprovalSession {
83
83
  review_required: boolean;
84
84
  reviews: MergeReview[];
85
85
  }
86
+ /** `lanes.review-before-merge` for one company, as the registry holds it. */
87
+ export interface MergeReviewFlag {
88
+ slug: string;
89
+ enabled: boolean;
90
+ }
86
91
  export interface MergeApprovalsSection {
87
92
  schema: typeof MERGE_APPROVALS_SCHEMA;
88
93
  refreshed_at: string;
89
94
  max_age_seconds: number;
95
+ /**
96
+ * By company uid, for every company a lane record resolves to. The native
97
+ * review check reads the lane and review records itself and takes only
98
+ * this flag from here. A company whose flag could not be read, or whose
99
+ * uid appears under two slugs, has no entry, and the native check refuses.
100
+ * The value is read as review_required is, with the daemon's own
101
+ * HQ_FLAG_LANES_REVIEW_BEFORE_MERGE kept.
102
+ */
103
+ review_flags: Record<string, MergeReviewFlag>;
90
104
  sessions: Record<string, MergeApprovalSession>;
91
105
  }
92
106
  export interface MergeSections {
@@ -133,11 +147,19 @@ export interface RegistryMergeFlagReaderOptions {
133
147
  read?: (flag: string, company: LaneCompanyRef, env: NodeJS.ProcessEnv) => Promise<boolean | null>;
134
148
  }
135
149
  /**
136
- * Lanes flags as `hq lanes hold check` reads them (readLanesRegistryFlag: local
137
- * override, then the registry, then its last-known-good cache on a transient
150
+ * Lanes flags as the registry holds them (readLanesRegistryFlag without the
151
+ * local override: the registry, then its last-known-good cache on a transient
138
152
  * failure), asked again after `ttlMs`. A read that fails, throws or takes
139
153
  * longer than `timeoutMs` is null and is not kept.
140
154
  */
155
+ /**
156
+ * The environment the hold flag is read under: the daemon's own, without
157
+ * the flag's local override (`HQ_FLAG_<KEY>`). The sections are read by the
158
+ * native merge gates of every session; each session applies its own override
159
+ * in process, as its `hq lanes hold check` would. An override set only in the
160
+ * daemon's environment must not be written as every company's registry value.
161
+ */
162
+ export declare function withoutLocalOverride(flag: string, env: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
141
163
  export declare function createRegistryMergeFlagReader(options: RegistryMergeFlagReaderOptions): MergeFlagReader;
142
164
  export interface MergeSectionRefresher {
143
165
  /** The latest sections, each only while younger than its max age. */
@@ -29,6 +29,7 @@
29
29
  * review records, which are read with their stores' own validating readers.
30
30
  * Nothing here starts a process; the flags are read from the flag registry.
31
31
  */
32
+ import { localOverrideEnvVar } from "@indigoai-us/hq-flags-client";
32
33
  import * as fs from "node:fs";
33
34
  import * as path from "node:path";
34
35
  import { openStoreDir } from "../safe-store.js";
@@ -306,12 +307,9 @@ async function laneSessions(hqRoot, readFlag) {
306
307
  if (lane.senior.kind === "lane" && lane.senior.id)
307
308
  seniors.add(lane.senior.id);
308
309
  const live = [];
310
+ const companyKey = (company) => JSON.stringify([company.uid, company.slug]);
311
+ const byKey = new Map();
309
312
  for (const lane of lanes) {
310
- if (TERMINAL_STATES.has(lane.state))
311
- continue;
312
- const sessions = laneSessionIds(lane);
313
- if (sessions.length === 0)
314
- continue;
315
313
  let company;
316
314
  try {
317
315
  company = resolveLaneCompany(hqRoot, lane).company;
@@ -319,17 +317,37 @@ async function laneSessions(hqRoot, readFlag) {
319
317
  catch {
320
318
  company = null;
321
319
  }
320
+ // Every lane's company, whatever the lane's state: the native review
321
+ // check finds its caller by HQ_LANE_ID, not by a session listed here.
322
+ if (company)
323
+ byKey.set(companyKey(company), company);
324
+ if (TERMINAL_STATES.has(lane.state))
325
+ continue;
326
+ const sessions = laneSessionIds(lane);
327
+ if (sessions.length === 0)
328
+ continue;
322
329
  live.push({ lane, sessions, company });
323
330
  }
324
331
  // One read per company, all at once, so a slow registry costs one timeout.
325
- const companyKey = (company) => JSON.stringify([company.uid, company.slug]);
326
- const byKey = new Map();
327
- for (const { company } of live)
328
- if (company)
329
- byKey.set(companyKey(company), company);
330
332
  const keys = [...byKey.keys()];
331
333
  const values = await Promise.all(keys.map((key) => readFlag(LANES_REVIEW_BEFORE_MERGE_FLAG, byKey.get(key))));
332
334
  const flags = new Map(keys.map((key, index) => [key, values[index]]));
335
+ const reviewFlags = {};
336
+ const twoSlugs = new Set();
337
+ for (const key of keys.sort()) {
338
+ const company = byKey.get(key);
339
+ const enabled = flags.get(key);
340
+ const listed = reviewFlags[company.uid];
341
+ if (twoSlugs.has(company.uid) || (listed && listed.slug !== company.slug)) {
342
+ // One uid under two slugs cannot be matched to a lane's company.
343
+ twoSlugs.add(company.uid);
344
+ delete reviewFlags[company.uid];
345
+ continue;
346
+ }
347
+ // Never `enabled: false` for a flag that could not be read.
348
+ if (typeof enabled === "boolean")
349
+ reviewFlags[company.uid] = { slug: company.slug, enabled };
350
+ }
333
351
  for (const { lane, sessions, company } of live) {
334
352
  let review = "off";
335
353
  if (company) {
@@ -347,7 +365,7 @@ async function laneSessions(hqRoot, readFlag) {
347
365
  }
348
366
  }
349
367
  }
350
- return out;
368
+ return { sessions: out, reviewFlags };
351
369
  }
352
370
  /** The merge_approvals section, or null to leave it out of the state file. */
353
371
  export async function buildMergeApprovalsSection(input) {
@@ -370,9 +388,10 @@ export async function buildMergeApprovalsSection(input) {
370
388
  links.set(sid, queue);
371
389
  }
372
390
  }
373
- const lanes = await laneSessions(hqRoot, input.readFlag);
374
- if (!lanes)
391
+ const laneFacts = await laneSessions(hqRoot, input.readFlag);
392
+ if (!laneFacts)
375
393
  return null;
394
+ const lanes = laneFacts.sessions;
376
395
  let reviews;
377
396
  const allReviews = () => {
378
397
  reviews ??= listLaneReviews(hqRoot).reviews
@@ -421,6 +440,7 @@ export async function buildMergeApprovalsSection(input) {
421
440
  schema: MERGE_APPROVALS_SCHEMA,
422
441
  refreshed_at: input.now.toISOString(),
423
442
  max_age_seconds: MERGE_SECTION_MAX_AGE_SECONDS,
443
+ review_flags: laneFacts.reviewFlags,
424
444
  sessions,
425
445
  };
426
446
  }
@@ -449,11 +469,26 @@ async function registryRead(flag, company, env) {
449
469
  return result.state === "resolved" ? result.value : null;
450
470
  }
451
471
  /**
452
- * Lanes flags as `hq lanes hold check` reads them (readLanesRegistryFlag: local
453
- * override, then the registry, then its last-known-good cache on a transient
472
+ * Lanes flags as the registry holds them (readLanesRegistryFlag without the
473
+ * local override: the registry, then its last-known-good cache on a transient
454
474
  * failure), asked again after `ttlMs`. A read that fails, throws or takes
455
475
  * longer than `timeoutMs` is null and is not kept.
456
476
  */
477
+ /**
478
+ * The environment the hold flag is read under: the daemon's own, without
479
+ * the flag's local override (`HQ_FLAG_<KEY>`). The sections are read by the
480
+ * native merge gates of every session; each session applies its own override
481
+ * in process, as its `hq lanes hold check` would. An override set only in the
482
+ * daemon's environment must not be written as every company's registry value.
483
+ */
484
+ export function withoutLocalOverride(flag, env) {
485
+ const name = localOverrideEnvVar(flag);
486
+ if (!(name in env))
487
+ return env;
488
+ const rest = { ...env };
489
+ delete rest[name];
490
+ return rest;
491
+ }
457
492
  export function createRegistryMergeFlagReader(options) {
458
493
  const ttlMs = options.ttlMs ?? MERGE_FLAG_TTL_MS;
459
494
  const timeoutMs = options.timeoutMs ?? MERGE_FLAG_READ_TIMEOUT_MS;
@@ -473,7 +508,14 @@ export function createRegistryMergeFlagReader(options) {
473
508
  });
474
509
  let value;
475
510
  try {
476
- value = await Promise.race([read(flag, company, options.env), timeout]);
511
+ // Only the hold flag: the native hold check applies the session's own
512
+ // override in process. The review-before-merge flag keeps the daemon's
513
+ // override: the row-based review gate (review_required) is still
514
+ // decided from this section, and the record-file review gate, which
515
+ // runs beside it, reads the same value from review_flags. Dropping the
516
+ // override here would let the row gate allow merges it refuses today.
517
+ const readEnv = flag === LANES_REPO_MERGE_HOLD_FLAG ? withoutLocalOverride(flag, options.env) : options.env;
518
+ value = await Promise.race([read(flag, company, readEnv), timeout]);
477
519
  }
478
520
  catch {
479
521
  value = null;
@@ -20,7 +20,7 @@
20
20
  import { spawn } from "node:child_process";
21
21
  import * as fs from "node:fs";
22
22
  import * as path from "node:path";
23
- import { sessionMetaCompanies } from "../../core-utils/session-company.js";
23
+ import { isPendingManifestCompany, sessionMetaCompanies } from "../../core-utils/session-company.js";
24
24
  import { withoutHookEnv } from "../hook-env.js";
25
25
  export const SCOPE_AUTHORIZER = ".claude/hooks/mandatory-scope-authorizer.sh";
26
26
  export const POLICY_TRIGGER = ".claude/hooks/inject-policy-on-trigger.sh";
@@ -351,7 +351,9 @@ async function policyCheckUnmapped(args, deps) {
351
351
  const { hqRoot } = deps;
352
352
  if (args.company !== undefined && !SLUG_RE.test(args.company))
353
353
  throw new PolicyOpError("bad_args", "company must be a company slug");
354
- if (args.company !== undefined && !isDir(path.join(hqRoot, "companies", args.company))) {
354
+ if (args.company !== undefined
355
+ && !isDir(path.join(hqRoot, "companies", args.company))
356
+ && !isPendingManifestCompany(hqRoot, args.company)) {
355
357
  throw new PolicyOpError("unknown_company", `no companies/${args.company} under ${hqRoot}`);
356
358
  }
357
359
  const authorizer = path.join(hqRoot, SCOPE_AUTHORIZER);
@@ -4,7 +4,7 @@
4
4
  */
5
5
  import * as fs from "node:fs";
6
6
  import * as path from "node:path";
7
- import { canonicalDir, emptyRegistry, readRegistry, resolveCompanyForDir } from "../registry/registry.js";
7
+ import { canonicalDir, companyFromHqLayout, emptyRegistry, readRegistry, resolveCompanyForDir, } from "../registry/registry.js";
8
8
  import { readCompaniesManifestMap } from "../work-context/repo-remote.js";
9
9
  /** Resolve cwd → company through the registry, cached until registry.json changes. */
10
10
  export function createResolver(registryPath, options = {}) {
@@ -55,8 +55,15 @@ export function createResolver(registryPath, options = {}) {
55
55
  return { company: null, reason: "HQ registry is unavailable; using personal context." };
56
56
  }
57
57
  const key = canonicalDir(cwd);
58
- const result = cache.get(key) ?? resolveCompanyForDir(registry, key);
58
+ let result = cache.get(key) ?? resolveCompanyForDir(registry, key);
59
59
  cache.set(key, result);
60
+ // With no registry hit, HQ's own companies/<slug> layout answers (#2823).
61
+ // Only the caller's HQ root counts, and the manifest check below still
62
+ // applies. Not cached: the cache is keyed to registry.json alone, and a
63
+ // company folder or manifest row can change without it.
64
+ if (!result.company && options.hqRoot) {
65
+ result = companyFromHqLayout(key, options.hqRoot) ?? result;
66
+ }
60
67
  if (result.company && options.hqRoot) {
61
68
  const manifestPath = path.join(options.hqRoot, "companies", "manifest.yaml");
62
69
  let currentManifestStamp;
@@ -5,6 +5,7 @@
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 { acquirePackageUseLease } from "../../utils/package-use-lease.js";
8
9
  import { type LegacySyncHolder, type PlanContext, type ServiceName, type UnitPlan } from "./catalog.js";
9
10
  import { type SyncCoreVaultPlan } from "../sync-core/engine-home.js";
10
11
  import { type LegacyUnit, type WindowsTaskOwner } from "./legacy.js";
@@ -89,12 +90,16 @@ export declare function syncRunnerSourceForPlan(stagedRunnerPath: string | null,
89
90
  }, currentSyncRunnerSource?: SyncRunnerSource | null): SyncRunnerSource;
90
91
  /** Whether every executable in the first service plan remains usable after the CLI package is replaced. */
91
92
  export declare function daemonPlanCanReleasePackageUseLease(plans: readonly UnitPlan[], replaceablePackageRoots: readonly string[], stagingFailed: boolean, hqBootstrapReady?: boolean): boolean;
92
- /**
93
- * Prefix a unit's command with `taskpolicy -b` on macOS. taskpolicy execs the
94
- * command in place, so the pid the supervisor tracks is the unit itself, and
95
- * PRIO_DARWIN_BG is inherited by everything the unit spawns (qmd included).
96
- */
97
- export declare function backgroundQosCommand(command: [string, string[]], backgroundQos: boolean, platform?: NodeJS.Platform | string, exists?: (file: string) => boolean): [string, string[]];
93
+ /** Keep the installed search-index entry and its qmd files stable for one pass. */
94
+ export declare function withSearchIndexPackageLease(releasedPackagePrefix: string | null, run: () => Promise<boolean>, acquire?: typeof acquirePackageUseLease, stopOnExpiry?: () => void): Promise<boolean>;
95
+ export declare function runSearchIndexWorker(options: {
96
+ root: string;
97
+ backgroundQos: boolean;
98
+ env: NodeJS.ProcessEnv;
99
+ logPath: string;
100
+ signal?: AbortSignal;
101
+ }, entry?: import("url").URL): Promise<boolean>;
102
+ export { backgroundQosCommand } from "./background-qos.js";
98
103
  export declare function daemonHqChildCommand(nodeBinary: string, hqBinary: string, args: readonly string[], bootstrapPath: string | null, packagePrefix: string | null, handoffWatchEnabled?: boolean): [string, string[]];
99
104
  export declare function daemonSyncUnitIsPresent(units: readonly {
100
105
  id: string;
@@ -188,5 +193,4 @@ export declare function checkMeshUnitHome(opts: {
188
193
  repair: () => MeshUnitRepairResult;
189
194
  }): boolean;
190
195
  export declare function runDaemon(opts: RunDaemonOptions): Promise<number>;
191
- export {};
192
196
  //# sourceMappingURL=run.d.ts.map
@@ -6,24 +6,28 @@
6
6
  * signing in takes effect without restarting the daemon.
7
7
  */
8
8
  import { spawn, spawnSync } from "node:child_process";
9
+ import { EventEmitter } from "node:events";
9
10
  import * as fs from "node:fs";
10
11
  import { createRequire } from "node:module";
11
12
  import * as os from "node:os";
12
13
  import * as path from "node:path";
13
14
  import { fileURLToPath } from "node:url";
15
+ import { MessageChannel, Worker } from "node:worker_threads";
14
16
  import { loadCachedTokens } from "@indigoai-us/hq-cloud";
15
17
  import { CLI_VERSION } from "../../cli-version.js";
16
18
  import { anywhereRuntimeEnabled } from "../../commands/anywhere-runtime-flag.js";
17
19
  import { anywhereRuntimeAllowed, readHqAnywherePersonSetting, stickyPersonSettingReader } from "../anywhere-person-setting.js";
18
20
  import { watchRuntimeInputs } from "./runtime-notifications.js";
19
- import { currentPackageUseLeaseInstall, currentPackageUseUpdateRequested } from "../../utils/package-use-lease.js";
21
+ import { acquirePackageUseLease, currentPackageUseLeaseInstall, currentPackageUseUpdateRequested, PackageUseUpdatePendingError, } from "../../utils/package-use-lease.js";
20
22
  import { isLocalDependencyInstall, resolveRunningInstall } from "../../utils/version-gate.js";
21
23
  import { agentKitPaths } from "../agent-kit/paths.js";
22
24
  import { HQ_FLEET_RUNTIME_ENGINE_ID, readBotConfig } from "../bot/config.js";
23
25
  import { clearStaleReadyBeforeGatewayStart, planFleetBots } from "../bot/fleet-daemon.js";
24
26
  import { botsRoot } from "../bot/paths.js";
25
- import { CLAUDE_RUNNER_SCRIPT, CODEX_RUNNER_SCRIPT, enabledServices, planUnits } from "./catalog.js";
27
+ import { CLAUDE_RUNNER_SCRIPT, CODEX_RUNNER_SCRIPT, enabledServices, legacySearchIndexCommand, planUnits } from "./catalog.js";
26
28
  import { effectiveSyncOwner, readDaemonConfig } from "./config.js";
29
+ import { backgroundQosCommand } from "./background-qos.js";
30
+ import { serveQmdWorker } from "../search-index/worker-process.js";
27
31
  import { inspectEngineHome } from "../sync-core/engine-home.js";
28
32
  import { fullModeHold } from "../sync-core/reconcile.js";
29
33
  import { readSyncCoreRolloutState } from "../sync-core/rollout-state.js";
@@ -74,11 +78,11 @@ import { listSyncRunnerProcesses, readWatchRunnerOwnerStatus, SYNC_RUNNER_LEASE_
74
78
  import { STOP_ESCALATION_MS, SYNC_RUNNER_PERSIST_GRACE_MS, createSupervisor, planKey, } from "./supervisor.js";
75
79
  import { userToolDirs } from "./tools.js";
76
80
  import { logOffset, readLogSince, readUnitHolds, writeUnitHolds } from "./unit-holds.js";
77
- import { createTccEpermGuard, TCC_EPERM_SENTRY_FINGERPRINT } from "./tcc-eperm.js";
81
+ import { createTccEpermGuard, filesAccessLaunch, TCC_EPERM_SENTRY_FINGERPRINT } from "./tcc-eperm.js";
78
82
  import { daemonRunGuard } from "./lanes-reconcile-guard.js";
79
83
  import { startStopJobDrainer } from "./stop-jobs.js";
80
84
  import { executeStopJob, pruneStopJobResults, stopJobCompleted } from "./stop-job-executor.js";
81
- import { executeHookRequest, startHookRequestDrainer } from "./hook-requests.js";
85
+ import { executeHookRequest, executeSessionClose, startHookRequestDrainer } from "./hook-requests.js";
82
86
  import { closeStopDiagnosticCursor, drainStopDiagnostics } from "./stop-diagnostics.js";
83
87
  export const LOG_ROTATE_BYTES = 5 * 1024 * 1024;
84
88
  /** Exit code for "restart me": non-zero so every service manager relaunches (Windows tasks only restart on failure). */
@@ -352,23 +356,87 @@ export function daemonPlanCanReleasePackageUseLease(plans, replaceablePackageRoo
352
356
  return true;
353
357
  if (command.type === "hq")
354
358
  return hqBootstrapReady;
355
- if (command.type === "internal")
359
+ if (command.type === "internal" || command.type === "worker")
356
360
  return true;
357
361
  const executablePaths = command.type === "node" ? [command.script, ...command.args] : [command.file, ...command.args];
358
362
  return executablePaths.every((candidate) => replaceablePackageRoots.every((root) => !isPathWithin(root, candidate)));
359
363
  });
360
364
  }
361
- const DARWIN_TASKPOLICY = "/usr/sbin/taskpolicy";
362
- /**
363
- * Prefix a unit's command with `taskpolicy -b` on macOS. taskpolicy execs the
364
- * command in place, so the pid the supervisor tracks is the unit itself, and
365
- * PRIO_DARWIN_BG is inherited by everything the unit spawns (qmd included).
366
- */
367
- export function backgroundQosCommand(command, backgroundQos, platform = process.platform, exists = fs.existsSync) {
368
- if (!backgroundQos || platform !== "darwin" || !exists(DARWIN_TASKPOLICY))
369
- return command;
370
- return [DARWIN_TASKPOLICY, ["-b", command[0], ...command[1]]];
365
+ /** Keep the installed search-index entry and its qmd files stable for one pass. */
366
+ export async function withSearchIndexPackageLease(releasedPackagePrefix, run, acquire = acquirePackageUseLease, stopOnExpiry) {
367
+ if (!releasedPackagePrefix)
368
+ return run();
369
+ let lease;
370
+ try {
371
+ lease = acquire(releasedPackagePrefix, CLI_VERSION, undefined, "command", 0, stopOnExpiry);
372
+ }
373
+ catch (error) {
374
+ if (error instanceof PackageUseUpdatePendingError)
375
+ return true;
376
+ throw error;
377
+ }
378
+ try {
379
+ return await run();
380
+ }
381
+ finally {
382
+ lease.release();
383
+ }
371
384
  }
385
+ const searchIndexWorkerEntry = new URL("./search-index-worker-v1.js", import.meta.url);
386
+ export function runSearchIndexWorker(options, entry = searchIndexWorkerEntry) {
387
+ const { root, backgroundQos, env, logPath } = options;
388
+ fs.closeSync(openPrivateAppend(logPath));
389
+ return new Promise((resolve, reject) => {
390
+ // QMD's synchronous lock and work stay off the supervisor thread.
391
+ const channel = new MessageChannel();
392
+ const stop = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
393
+ const notifyStop = () => {
394
+ Atomics.store(stop, 0, 1);
395
+ Atomics.notify(stop, 0);
396
+ };
397
+ if (options.signal?.aborted)
398
+ notifyStop();
399
+ let worker;
400
+ try {
401
+ worker = new Worker(entry, {
402
+ workerData: { root, backgroundQos, qmdPort: channel.port2, stopBuffer: stop.buffer },
403
+ transferList: [channel.port2],
404
+ env,
405
+ stdout: true,
406
+ stderr: true,
407
+ });
408
+ }
409
+ catch (error) {
410
+ channel.port1.close();
411
+ channel.port2.close();
412
+ throw error;
413
+ }
414
+ const qmd = serveQmdWorker(channel.port1, options.signal);
415
+ options.signal?.addEventListener("abort", notifyStop, { once: true });
416
+ let failure;
417
+ const record = (chunk) => {
418
+ try {
419
+ appendPrivate(logPath, chunk);
420
+ }
421
+ catch (err) {
422
+ failure ??= err instanceof Error ? err : new Error(String(err));
423
+ }
424
+ };
425
+ worker.stdout.setEncoding("utf8").on("data", record);
426
+ worker.stderr.setEncoding("utf8").on("data", record);
427
+ worker.once("error", (err) => { failure ??= err; });
428
+ worker.once("exit", (code) => {
429
+ options.signal?.removeEventListener("abort", notifyStop);
430
+ void qmd.close().then(() => {
431
+ if (failure)
432
+ reject(failure);
433
+ else
434
+ resolve(code === 0);
435
+ }, reject);
436
+ });
437
+ });
438
+ }
439
+ export { backgroundQosCommand } from "./background-qos.js";
372
440
  export function daemonHqChildCommand(nodeBinary, hqBinary, args, bootstrapPath, packagePrefix, handoffWatchEnabled = true) {
373
441
  return bootstrapPath && packagePrefix
374
442
  ? [nodeBinary, [bootstrapPath, packagePrefix, CLI_VERSION, ...(handoffWatchEnabled ? [] : ["--handoff-watch=off"]), ...args]]
@@ -1157,27 +1225,40 @@ export async function runDaemon(opts) {
1157
1225
  }),
1158
1226
  log: message => log("warn", message),
1159
1227
  });
1160
- // Request notes hq-hook leaves on PostToolUse (hook-requests.ts): same lease, same stop signal, this daemon's HQ root only.
1228
+ /** The running hqd's session registry, for session-close request notes; undefined while hqd is stopped. */
1229
+ let hqdSessionsForRequests;
1230
+ // Request notes hq-hook leaves (hook-requests.ts): same lease, same stop signal, this daemon's HQ root only.
1231
+ // session-close is done in the running hqd's session registry (set in onServerChange below); nothing is started.
1161
1232
  const hookRequestDrainer = startHookRequestDrainer({
1162
1233
  home,
1163
1234
  root: () => readDaemonConfig(paths.configPath).hqRoot ?? env.HQ_ROOT,
1164
1235
  ownsQueue: ownsStopQueue,
1165
- execute: request => executeHookRequest(request, {
1166
- nodeBinary: opts.nodeBinary,
1167
- hqBinary: opts.hqBinary,
1168
- allowedRoot: readDaemonConfig(paths.configPath).hqRoot ?? env.HQ_ROOT,
1169
- env,
1170
- signal: stopJobAbort.signal,
1171
- }),
1236
+ execute: request => request.operation.kind === "session-close"
1237
+ ? executeSessionClose(request, {
1238
+ sessions: hqdSessionsForRequests,
1239
+ allowedRoot: readDaemonConfig(paths.configPath).hqRoot ?? env.HQ_ROOT,
1240
+ })
1241
+ : executeHookRequest(request, {
1242
+ nodeBinary: opts.nodeBinary,
1243
+ hqBinary: opts.hqBinary,
1244
+ allowedRoot: readDaemonConfig(paths.configPath).hqRoot ?? env.HQ_ROOT,
1245
+ env,
1246
+ home,
1247
+ signal: stopJobAbort.signal,
1248
+ log: message => log("warn", message),
1249
+ }),
1172
1250
  log: message => log("warn", message),
1173
1251
  });
1174
- /** Closes the watchers; the promise settles once the Stop job or hook request in progress (if any) has finished. */
1252
+ let activeIndexWorker;
1253
+ /** Close runtime work before releasing the daemon lock. */
1175
1254
  const closeRuntimeWatchers = () => {
1176
1255
  if (stopDiagnosticRoot)
1177
1256
  closeStopDiagnosticCursor(stopDiagnosticRoot);
1178
1257
  clearInterval(stopDiagnosticTimer);
1179
1258
  stopJobAbort.abort();
1259
+ activeIndexWorker?.stop();
1180
1260
  const stopJobsClosed = Promise.all([
1261
+ activeIndexWorker?.done,
1181
1262
  stopJobDrainer.close().catch((err) => log("warn", `Stop job drainer did not close cleanly: ${String(err)}`)),
1182
1263
  hookRequestDrainer.close().catch((err) => log("warn", `Hook request drainer did not close cleanly: ${String(err)}`)),
1183
1264
  ]).then(() => undefined);
@@ -1436,6 +1517,9 @@ export async function runDaemon(opts) {
1436
1517
  syncRunnerOwnerPid,
1437
1518
  daemonSyncRunnerPids,
1438
1519
  lanesReconcileInProcess: Boolean(laneReconcileWatcher && laneReconcileWatcherRoot === hqRoot),
1520
+ // The first plan runs under the daemon startup lease. If it cannot be
1521
+ // released, keep the old independent launcher on later reconciles.
1522
+ searchIndexWorkerAvailable: startupPlanOpen || !cliPackagePrefix || packageUseLeaseReleased,
1439
1523
  searchIndexOwnedBySyncRunner: searchIndexRunnerOwnsIndexFlag.status().enabled &&
1440
1524
  hqCloud !== null && !hqCloudVersionOlder(hqCloud.version, "6.18.75") &&
1441
1525
  syncOwner === "daemon" && services.includes("sync") && !config.syncPaused &&
@@ -1482,6 +1566,63 @@ export async function runDaemon(opts) {
1482
1566
  throw new Error(`${unit.id} has no process to start`);
1483
1567
  prepareUnitStart(unit, log);
1484
1568
  unitLogOffsets.set(unit.id, logOffset(paths.unitLogPath(unit.id)));
1569
+ if (command.type === "worker") {
1570
+ const root = unit.env.HQ_ROOT;
1571
+ if (!root)
1572
+ throw new Error("search index has no HQ folder");
1573
+ const events = new EventEmitter();
1574
+ if (activeIndexWorker) {
1575
+ log("info", "search-index is still stopping; skipping this pass");
1576
+ queueMicrotask(() => events.emit("exit", 0, null));
1577
+ return { skipped: true, on: events.on.bind(events), kill: () => false };
1578
+ }
1579
+ const controller = new AbortController();
1580
+ let fallback;
1581
+ const stop = (signal = "SIGTERM") => {
1582
+ controller.abort();
1583
+ return fallback?.kill(signal) ?? true;
1584
+ };
1585
+ let needsFallback = false;
1586
+ const done = withSearchIndexPackageLease(packageUseLeaseReleased ? cliPackagePrefix : null, () => {
1587
+ // A running daemon can survive a rollback to a package without v1.
1588
+ if (cliPackagePrefix && !fs.existsSync(searchIndexWorkerEntry)) {
1589
+ needsFallback = true;
1590
+ return Promise.resolve(true);
1591
+ }
1592
+ return runSearchIndexWorker({
1593
+ root,
1594
+ backgroundQos: unit.backgroundQos === true,
1595
+ env: unitProcessEnv(env, unit),
1596
+ logPath: paths.unitLogPath(unit.id),
1597
+ signal: controller.signal,
1598
+ });
1599
+ }, acquirePackageUseLease, stop).then((ok) => {
1600
+ if (!needsFallback || controller.signal.aborted)
1601
+ return ok;
1602
+ // The compatibility child acquires its own lease during bootstrap.
1603
+ return new Promise((resolve, reject) => {
1604
+ fallback = spawnUnit({ ...unit, command: legacySearchIndexCommand(root) });
1605
+ fallback.on("exit", (code) => resolve(code === 0));
1606
+ fallback.on("error", reject);
1607
+ });
1608
+ }).then((ok) => {
1609
+ if (activeIndexWorker?.stop === stop)
1610
+ activeIndexWorker = undefined;
1611
+ if (controller.signal.aborted)
1612
+ events.emit("exit", null, "SIGTERM");
1613
+ else
1614
+ events.emit("exit", ok ? 0 : 1, null);
1615
+ }, (error) => {
1616
+ if (activeIndexWorker?.stop === stop)
1617
+ activeIndexWorker = undefined;
1618
+ if (controller.signal.aborted)
1619
+ events.emit("exit", null, "SIGTERM");
1620
+ else
1621
+ events.emit("error", error);
1622
+ });
1623
+ activeIndexWorker = { stop, done };
1624
+ return { on: events.on.bind(events), kill: stop };
1625
+ }
1485
1626
  let [file, args] = command.type === "hq"
1486
1627
  ? daemonHqChildCommand(opts.nodeBinary, opts.hqBinary, command.args, stagedHqChildBootstrap?.bootstrapPath ?? null, cliPackagePrefix, childBootstrapHandoffWatchFlag.status().enabled)
1487
1628
  : command.type === "node"
@@ -1715,6 +1856,8 @@ export async function runDaemon(opts) {
1715
1856
  platform,
1716
1857
  daemonDir: paths.root,
1717
1858
  restartable: restartsAfterTccEpermExit(opts),
1859
+ // Which program macOS checks, so the access message names the right one.
1860
+ launch: filesAccessLaunch({ managed: opts.managed, host: opts.host, ppid: process.ppid }),
1718
1861
  isStopping: () => daemonStopping,
1719
1862
  log,
1720
1863
  report: reportTccEperm,
@@ -1745,6 +1888,7 @@ export async function runDaemon(opts) {
1745
1888
  });
1746
1889
  },
1747
1890
  onServerChange: (server) => {
1891
+ hqdSessionsForRequests = server?.sessions;
1748
1892
  stopHeartbeat();
1749
1893
  stopHeartbeat = () => { };
1750
1894
  if (!server)
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=search-index-worker-v1.d.ts.map