@indigoai-us/hq-cli 5.345.221 → 5.345.223

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 (87) hide show
  1. package/CHANGELOG.md +70 -1
  2. package/dist/command-catalog.generated.d.ts +31 -0
  3. package/dist/command-catalog.generated.js +38 -0
  4. package/dist/commands/auth.js +2 -1
  5. package/dist/commands/bot.d.ts +1 -1
  6. package/dist/commands/bot.js +34 -33
  7. package/dist/commands/core-delegate-w1b.js +216 -190
  8. package/dist/commands/daemon.d.ts +1 -0
  9. package/dist/commands/daemon.js +15 -1
  10. package/dist/commands/link.d.ts +2 -0
  11. package/dist/commands/link.js +14 -2
  12. package/dist/commands/mesh.js +23 -3
  13. package/dist/commands/packs.js +13 -2
  14. package/dist/commands/sync-core.d.ts +6 -0
  15. package/dist/commands/sync-core.js +75 -1
  16. package/dist/data/command-states.json +3 -0
  17. package/dist/lib/bot/fleet-cron.d.ts +26 -3
  18. package/dist/lib/bot/fleet-cron.js +44 -4
  19. package/dist/lib/bot/run.d.ts +4 -4
  20. package/dist/lib/bot/run.js +5 -3
  21. package/dist/lib/bot/signals-engine-flag.d.ts +53 -13
  22. package/dist/lib/bot/signals-engine-flag.js +202 -9
  23. package/dist/lib/daemon/catalog.js +2 -0
  24. package/dist/lib/daemon/install.d.ts +2 -1
  25. package/dist/lib/daemon/install.js +9 -0
  26. package/dist/lib/daemon/legacy.d.ts +1 -0
  27. package/dist/lib/daemon/legacy.js +5 -2
  28. package/dist/lib/daemon/machine-check-owner.d.ts +2 -0
  29. package/dist/lib/daemon/machine-check-owner.js +6 -1
  30. package/dist/lib/daemon/machine-checks.d.ts +52 -1
  31. package/dist/lib/daemon/machine-checks.js +104 -11
  32. package/dist/lib/daemon/mesh-owner.d.ts +45 -0
  33. package/dist/lib/daemon/mesh-owner.js +166 -0
  34. package/dist/lib/daemon/native-notice-ledger.d.ts +36 -0
  35. package/dist/lib/daemon/native-notice-ledger.js +156 -0
  36. package/dist/lib/daemon/run.d.ts +15 -0
  37. package/dist/lib/daemon/run.js +72 -3
  38. package/dist/lib/daemon/selfcheck.d.ts +35 -2
  39. package/dist/lib/daemon/selfcheck.js +118 -9
  40. package/dist/lib/daemon/supervisor.d.ts +10 -0
  41. package/dist/lib/daemon/supervisor.js +86 -0
  42. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  43. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  44. package/dist/lib/flag-registry-worker.js +33 -3
  45. package/dist/lib/flag-registry.js +13 -0
  46. package/dist/lib/hook-engine/coverage.d.ts +9 -0
  47. package/dist/lib/hook-engine/coverage.js +56 -0
  48. package/dist/lib/hook-engine/native-stop-compatibility.json +56 -5
  49. package/dist/lib/mesh/live/daemon/config.d.ts +8 -1
  50. package/dist/lib/mesh/live/daemon/config.js +16 -0
  51. package/dist/lib/mesh/live/daemon/install.d.ts +31 -2
  52. package/dist/lib/mesh/live/daemon/install.js +142 -1
  53. package/dist/lib/mesh/live/daemon/login-home.d.ts +5 -0
  54. package/dist/lib/mesh/live/daemon/login-home.js +27 -0
  55. package/dist/lib/mesh/live/daemon/unit-home.d.ts +49 -0
  56. package/dist/lib/mesh/live/daemon/unit-home.js +134 -0
  57. package/dist/lib/registry/registry.d.ts +35 -7
  58. package/dist/lib/registry/registry.js +88 -13
  59. package/dist/lib/scan-packages/index.js +23 -2
  60. package/dist/lib/search-index/max-doc-bytes.js +2 -1
  61. package/dist/lib/service-manager/startup-migration.d.ts +1 -0
  62. package/dist/lib/service-manager/startup-migration.js +3 -0
  63. package/dist/lib/signals/engine.d.ts +8 -0
  64. package/dist/lib/signals/engine.js +15 -5
  65. package/dist/lib/sync-core/engine-holds.d.ts +14 -0
  66. package/dist/lib/sync-core/engine-holds.js +60 -0
  67. package/dist/lib/sync-core/engine-home.d.ts +2 -0
  68. package/dist/lib/sync-core/flag.d.ts +18 -0
  69. package/dist/lib/sync-core/flag.js +66 -0
  70. package/dist/lib/sync-core/reconcile.d.ts +6 -0
  71. package/dist/lib/sync-core/reconcile.js +23 -0
  72. package/dist/lib/sync-core/rollout-state.d.ts +2 -0
  73. package/dist/lib/sync-core/rollout-state.js +7 -0
  74. package/dist/lib/sync-core/vault-settings.d.ts +32 -0
  75. package/dist/lib/sync-core/vault-settings.js +147 -0
  76. package/dist/lib/windows/install-followup.d.ts +2 -0
  77. package/dist/lib/windows/install-followup.js +4 -1
  78. package/dist/utils/host-registration.js +3 -1
  79. package/dist/utils/pack-contributions.d.ts +16 -1
  80. package/dist/utils/pack-contributions.js +139 -26
  81. package/dist/utils/self-update.d.ts +3 -1
  82. package/dist/utils/self-update.js +56 -11
  83. package/dist/utils/update-lock.d.ts +151 -14
  84. package/dist/utils/update-lock.js +782 -46
  85. package/dist/utils/version-gate.js +12 -2
  86. package/package.json +7 -7
  87. package/scripts/bench-core.mjs +34 -3
@@ -29,7 +29,7 @@ import { findHqRoot } from '../utils/manifest.js';
29
29
  import { resolveHqRoot as resolveDetectedHqRoot } from './doctor.js';
30
30
  import { anywhereRuntimeAllowed } from '../lib/anywhere-person-setting.js';
31
31
  import { classify, PINNED_HQ_ANYWHERE_SOURCE, resolveLatest, parseMarketplaceSource, resolveLatestMarketplace, runScanPackages, installPack, } from './pack-install.js';
32
- import { contributionLinks, linkStatus, listInstalledPacks, findDependentPacks, readPackManifest, unwirePack, unwirePackMcp, readHqVersion, readRecommendedPackages, packagesDir, } from '../utils/pack-contributions.js';
32
+ import { contributionLinks, linkStatus, listInstalledPacks, findDependentPacks, readPackManifest, unwirePack, unwireNamespacedSkills, unwirePackMcp, readHqVersion, readRecommendedPackages, packagesDir, } from '../utils/pack-contributions.js';
33
33
  import { readInstalledPackSetup } from '../lib/packages/setup-block.js';
34
34
  import { syncCodexPackHooks, syncCodexPackSkills } from '../lib/install/codex-pack-contributions.js';
35
35
  function resolveRoot(opts) {
@@ -275,7 +275,11 @@ export async function runUpdate(name, opts, deps = {}) {
275
275
  syncCodexPackSkills(pack.dir, pname, m.contributes?.skills ?? [], true);
276
276
  // Un-wire old contributions first so a contribution dropped by the new
277
277
  // version doesn't leave a dangling host symlink. installPack re-wires.
278
- unwirePack(hqRoot, pack.dir, m.contributes ?? {});
278
+ // The namespaced `<pack>:<skill>` hosts stay: the pack directory is
279
+ // replaced in place, so they keep resolving, and removing them would
280
+ // hide `/<pack>:<skill>` until the next reindex. Hosts of skills the new
281
+ // version dropped are removed after the install below.
282
+ unwirePack(hqRoot, pack.dir, m.contributes ?? {}, { keepNamespacedSkills: true });
279
283
  const prevCwd = process.cwd();
280
284
  if (opts.hqRoot)
281
285
  process.chdir(hqRoot); // installPack resolves via findHqRoot()
@@ -294,6 +298,13 @@ export async function runUpdate(name, opts, deps = {}) {
294
298
  if (opts.hqRoot)
295
299
  process.chdir(prevCwd);
296
300
  }
301
+ // An unreadable new manifest says nothing about which skills were
302
+ // dropped, so leave the namespaced hosts for reindex to reconcile.
303
+ const newManifest = readPackManifest(pack.dir).manifest;
304
+ if (newManifest) {
305
+ const newSkills = new Set(newManifest.contributes?.skills ?? []);
306
+ unwireNamespacedSkills(hqRoot, pack.dir, (m.contributes?.skills ?? []).filter((item) => !newSkills.has(item)));
307
+ }
297
308
  results.push({ ...base, applied: true });
298
309
  }
299
310
  catch (e) {
@@ -36,5 +36,11 @@ export declare function runSyncCoreManifest(opts: SyncCoreManifestCommandOptions
36
36
  export declare function runSyncCoreStatus(opts: {
37
37
  json?: boolean;
38
38
  }, d?: SyncCoreCommandDeps): void;
39
+ export declare function resolveSyncCoreVault(home: string, name: string, opts?: {
40
+ clearing?: boolean;
41
+ }): string;
42
+ export declare function runSyncCoreConfig(vault: string, key: string | undefined, value: string | undefined, opts: {
43
+ json?: boolean;
44
+ }, d?: SyncCoreCommandDeps): void;
39
45
  export declare function registerSyncCoreCommand(program: Command, over?: Partial<SyncCoreCommandDeps>): void;
40
46
  //# sourceMappingURL=sync-core.d.ts.map
@@ -3,11 +3,13 @@ import * as os from "node:os";
3
3
  import * as path from "node:path";
4
4
  import { ensureSyncCoreBinary, readSyncCorePin } from "../lib/sync-core/release.js";
5
5
  import { readEngineStatus } from "../lib/sync-core/engine-home.js";
6
- import { readCompanyRolloutFlag } from "../lib/sync-core/flag.js";
6
+ import { readCompanyDownloadStreams, readCompanyRolloutFlag } from "../lib/sync-core/flag.js";
7
7
  import { reconcileSyncCore } from "../lib/sync-core/reconcile.js";
8
8
  import { engineOwnedManifestScopes, manifestScopeArg } from "../lib/sync-core/manifest-scopes.js";
9
9
  import { readSyncCoreRolloutState, syncCoreRolloutStatePath } from "../lib/sync-core/rollout-state.js";
10
10
  import { readVaultSyncSwitches } from "../lib/vault-sync-switches.js";
11
+ import { isSyncCoreVaultUid } from "../lib/sync-core/vault-uid.js";
12
+ import { effectiveEngineSettings, readSyncCoreVaultSettings, setSyncCoreVaultSetting, SyncCoreVaultSettingError, } from "../lib/sync-core/vault-settings.js";
11
13
  function defaultDeps() {
12
14
  return {
13
15
  home: os.homedir(),
@@ -59,6 +61,7 @@ export async function runSyncCoreReconcile(opts, d = defaultDeps()) {
59
61
  getEntity: async () => null,
60
62
  }),
61
63
  readRolloutFlag: (companyUid) => readCompanyRolloutFlag(companyUid, token, { env: d.env }),
64
+ readDownloadStreams: (companyUid) => readCompanyDownloadStreams(companyUid, token, { env: d.env }),
62
65
  ensureBinary: (release) => ensureSyncCoreBinary({ home: d.home, platform: d.platform, arch: d.arch, release, env: d.env }),
63
66
  platform: d.platform,
64
67
  env: d.env,
@@ -213,6 +216,72 @@ export function runSyncCoreStatus(opts, d = defaultDeps()) {
213
216
  if (state.vaults.length === 0)
214
217
  d.out(" no vault is switched to the new sync engine");
215
218
  }
219
+ export function resolveSyncCoreVault(home, name, opts = {}) {
220
+ const wanted = name.trim();
221
+ const vaults = readSyncCoreRolloutState(home)?.vaults ?? [];
222
+ if (isSyncCoreVaultUid(wanted)) {
223
+ if (vaults.some((vault) => vault.uid === wanted))
224
+ return wanted;
225
+ if (opts.clearing && readSyncCoreVaultSettings(home).has(wanted))
226
+ return wanted;
227
+ }
228
+ const match = wanted === "personal"
229
+ ? vaults.filter((vault) => vault.kind === "personal")
230
+ : vaults.filter((vault) => vault.kind === "company" && vault.slug === wanted);
231
+ if (match.length === 1)
232
+ return match[0].uid;
233
+ throw new SyncCoreVaultSettingError(`No vault named ${JSON.stringify(wanted)} is on the new sync engine on this machine. Pass a company slug from hq sync-core status, personal, or a vault uid.`);
234
+ }
235
+ function describeSettings(settings, source) {
236
+ if (!settings?.parallelDownloads) {
237
+ return source === "computer" ? "parallel-downloads off (this computer)" : "parallel-downloads off (default)";
238
+ }
239
+ const text = `parallel-downloads on, download-streams ${settings.downloadStreams ?? "default"}`;
240
+ return source === "company" ? `${text} (company setting)` : text;
241
+ }
242
+ export function runSyncCoreConfig(vault, key, value, opts, d = defaultDeps()) {
243
+ try {
244
+ const clearing = key !== undefined && (value === "off" || value === "default");
245
+ const uid = resolveSyncCoreVault(d.home, vault, { clearing });
246
+ const onEngine = readSyncCoreRolloutState(d.home)?.vaults.find((entry) => entry.uid === uid);
247
+ let local;
248
+ if (key === undefined) {
249
+ local = readSyncCoreVaultSettings(d.home).get(uid);
250
+ }
251
+ else {
252
+ if (value === undefined)
253
+ throw new SyncCoreVaultSettingError(`Give a value for ${key}`);
254
+ // A vault no longer on the engine here has no company value to opt out
255
+ // of, so turning it off just removes the stale entry.
256
+ const stored = !onEngine && key === "parallel-downloads" && value === "off" ? "default" : value;
257
+ local = setSyncCoreVaultSetting(d.home, uid, key, stored);
258
+ }
259
+ const companyStreams = onEngine?.downloadStreams;
260
+ const settings = effectiveEngineSettings(local, companyStreams);
261
+ const source = local?.parallelDownloads !== undefined ? "computer" : settings ? "company" : "default";
262
+ if (opts.json) {
263
+ d.out(JSON.stringify({
264
+ vault: uid,
265
+ parallelDownloads: settings?.parallelDownloads === true,
266
+ downloadStreams: settings?.downloadStreams ?? null,
267
+ source,
268
+ companyDownloadStreams: companyStreams ?? null,
269
+ }));
270
+ return;
271
+ }
272
+ d.out(`${uid}: ${describeSettings(settings, source)}`);
273
+ if (source === "computer" && companyStreams !== undefined) {
274
+ d.out(`The company setting (${companyStreams} download streams) applies again after: hq sync-core config ${vault} parallel-downloads default`);
275
+ }
276
+ if (key !== undefined) {
277
+ d.out("Only this computer is changed. hq daemon restarts this vault's sync engine within about 15 seconds. Engine releases without parallel downloads ignore the setting.");
278
+ }
279
+ }
280
+ catch (error) {
281
+ d.err(error instanceof Error ? error.message : String(error));
282
+ process.exitCode = 1;
283
+ }
284
+ }
216
285
  export function registerSyncCoreCommand(program, over = {}) {
217
286
  const deps = () => ({ ...defaultDeps(), ...over });
218
287
  const syncCore = program
@@ -235,6 +304,11 @@ export function registerSyncCoreCommand(program, over = {}) {
235
304
  process.exitCode = 1;
236
305
  }
237
306
  });
307
+ syncCore
308
+ .command("config <vault> [key] [value]")
309
+ .description("Show or change this computer's new sync engine settings for one vault: parallel-downloads on|off|default (default follows the company setting), download-streams 1-32|default")
310
+ .option("--json", "Print JSON")
311
+ .action((vault, key, value, opts) => runSyncCoreConfig(vault, key, value, opts, deps()));
238
312
  syncCore
239
313
  .command("status")
240
314
  .description("Show which vaults are on the new sync engine on this machine")
@@ -1,8 +1,11 @@
1
1
  {
2
2
  "schema": 1,
3
3
  "commands": {
4
+ "auth login": { "state": "retiring", "replacedBy": "hq login" },
5
+ "auth logout": { "state": "retiring", "replacedBy": "hq logout" },
4
6
  "crm entity get": { "state": "retiring" },
5
7
  "crm entity list": { "state": "retiring" },
8
+ "packages install": { "state": "retiring", "replacedBy": "hq install" },
6
9
  "packages packs list": { "state": "retiring", "replacedBy": "hq packs list" },
7
10
  "packages packs uninstall": { "state": "retiring", "replacedBy": "hq packs uninstall" },
8
11
  "packages packs update": { "state": "retiring", "replacedBy": "hq packs update" },
@@ -108,10 +108,15 @@ export interface EnsureFleetHotSignalSyncInput {
108
108
  * cli.bot-signals-engine-job (default off). Every company still gets the
109
109
  * daily 06:30 hot-signal-sync job; the flag picks what its script runs: the
110
110
  * signals engine when true, the plain hot-channel sync when false. The script
111
- * is rewritten on every call, so flipping the flag takes effect on the next
112
- * bot start without re-registering the job.
111
+ * is rewritten on every call, so flipping the flag (or turning a capture
112
+ * setting on) takes effect on the next bot start without re-registering the
113
+ * job.
114
+ *
115
+ * The flag is a company flag, so pass a function to answer per company (a
116
+ * personal bot has one job per company and each can differ). A boolean is
117
+ * the same answer for every company.
113
118
  */
114
- signalsJobEnabled: boolean;
119
+ signalsJobEnabled: boolean | ((company: string) => boolean);
115
120
  /**
116
121
  * Whether this bot is the Executive bot (lib/bot/executive.ts). Other personal bots
117
122
  * hand over only companies with a confirmed replacement job. Default true.
@@ -132,5 +137,23 @@ export interface EnsureFleetHotSignalSyncResult {
132
137
  removed: string[];
133
138
  }
134
139
  export declare function fleetHotSignalSyncCompanies(config: EnsureFleetHotSignalSyncInput["config"], activeCompany: string | null, ownerCompanies?: readonly string[]): string[];
140
+ /**
141
+ * cli.bot-signals-engine-job, read for each company the bot has a
142
+ * hot-signal-sync job for: the answer for `signalsJobEnabled`. Only a company
143
+ * whose flag is on, and which the engine would not skip as prefs-off on this
144
+ * computer (signals_capture and ontology_capture both off), gets the engine
145
+ * script; the others keep the plain hot-channel sync. A company has one job
146
+ * and one script, so it is never run by both in a morning. Never throws: when
147
+ * the read itself throws, every company keeps the plain sync and `log` gets
148
+ * one line.
149
+ *
150
+ * The answer is taken when the script is written: each time `hq bot` syncs
151
+ * the bot's Fleet jobs (`hq bot start` and `restart` among them). A
152
+ * capture setting (or the flag) changed afterwards, in either direction,
153
+ * reaches the script the next time it is written. Until then a company whose
154
+ * capture was turned on keeps the plain sync, and a company whose capture was
155
+ * turned off keeps the engine script, which skips it as prefs-off.
156
+ */
157
+ export declare function fleetHotSignalSyncEngineCompanies(input: Pick<EnsureFleetHotSignalSyncInput, "config" | "activeCompany" | "ownerCompanies" | "executive" | "executiveCompanies">, read?: (companies: readonly string[]) => Promise<ReadonlySet<string>>, log?: (message: string) => void): Promise<(company: string) => boolean>;
135
158
  export declare function ensureFleetHotSignalSync(input: EnsureFleetHotSignalSyncInput): EnsureFleetHotSignalSyncResult;
136
159
  //# sourceMappingURL=fleet-cron.d.ts.map
@@ -5,6 +5,7 @@ import { effectiveBotCompanies, effectiveBotKind } from "./config.js";
5
5
  import { fleetLocalRuntimePython, stderrTail } from "./fleet-local.js";
6
6
  import { readLocalJobs, withJobsLock, writeLocalJobs } from "./local-jobs.js";
7
7
  import { signInCommand } from "./runtime-sign-in.js";
8
+ import { BOT_SIGNALS_ENGINE_JOB_FLAG, signalsEngineJobCompanies } from "./signals-engine-flag.js";
8
9
  import { SIGNALS_FAILURE_PREFIX } from "../hot-channels/alert.js";
9
10
  import { currentHotSignalSyncCompany, forgetHotSignalSyncRegistrationsExcept, hotSignalSyncJobCompany, fleetHotSignalSyncRegistered, markFleetHotSignalSyncRegistered, otherBotWithHotSignalSync, } from "./jobs/hot-signal-sync.js";
10
11
  const RESULT_MARKER = "@@HQ_FLEET_CRON@@";
@@ -584,9 +585,45 @@ export function fleetHotSignalSyncCompanies(config, activeCompany, ownerCompanie
584
585
  return owned;
585
586
  return single ? [single] : [];
586
587
  }
587
- export function ensureFleetHotSignalSync(input) {
588
- const companies = fleetHotSignalSyncCompanies(input.config, input.activeCompany, input.ownerCompanies)
588
+ /** The companies this bot keeps a hot-signal-sync job for: its own, less the ones the Executive bot runs. */
589
+ function fleetHotSignalSyncJobCompanies(input) {
590
+ return fleetHotSignalSyncCompanies(input.config, input.activeCompany, input.ownerCompanies)
589
591
  .filter((company) => input.executive !== false || !input.executiveCompanies?.includes(company));
592
+ }
593
+ /**
594
+ * cli.bot-signals-engine-job, read for each company the bot has a
595
+ * hot-signal-sync job for: the answer for `signalsJobEnabled`. Only a company
596
+ * whose flag is on, and which the engine would not skip as prefs-off on this
597
+ * computer (signals_capture and ontology_capture both off), gets the engine
598
+ * script; the others keep the plain hot-channel sync. A company has one job
599
+ * and one script, so it is never run by both in a morning. Never throws: when
600
+ * the read itself throws, every company keeps the plain sync and `log` gets
601
+ * one line.
602
+ *
603
+ * The answer is taken when the script is written: each time `hq bot` syncs
604
+ * the bot's Fleet jobs (`hq bot start` and `restart` among them). A
605
+ * capture setting (or the flag) changed afterwards, in either direction,
606
+ * reaches the script the next time it is written. Until then a company whose
607
+ * capture was turned on keeps the plain sync, and a company whose capture was
608
+ * turned off keeps the engine script, which skips it as prefs-off.
609
+ */
610
+ export async function fleetHotSignalSyncEngineCompanies(input, read, log) {
611
+ let engine = new Set();
612
+ try {
613
+ const companies = fleetHotSignalSyncJobCompanies(input);
614
+ if (companies.length > 0) {
615
+ engine = await (read ?? ((list) => signalsEngineJobCompanies(list, { hqRoot: input.config.hqRoot, ...(log ? { log } : {}) })))(companies);
616
+ }
617
+ }
618
+ catch (error) {
619
+ engine = new Set();
620
+ const errorClass = error instanceof Error ? error.name : "unknown";
621
+ (log ?? ((message) => console.warn(`hq: ${message}`)))(`Could not read ${BOT_SIGNALS_ENGINE_JOB_FLAG} (${errorClass}); every company's hot-signal-sync job runs the hot-channel sync only.`);
622
+ }
623
+ return (company) => engine.has(company);
624
+ }
625
+ export function ensureFleetHotSignalSync(input) {
626
+ const companies = fleetHotSignalSyncJobCompanies(input);
590
627
  const wanted = new Set(companies);
591
628
  const jobs = input.ops.list();
592
629
  const removed = [];
@@ -608,6 +645,9 @@ export function ensureFleetHotSignalSync(input) {
608
645
  }
609
646
  function ensureFleetHotSignalSyncFor(input, company, jobs) {
610
647
  const scriptName = fleetHotSignalSyncScript(company);
648
+ const signalsEngine = typeof input.signalsJobEnabled === "function"
649
+ ? input.signalsJobEnabled(company) === true
650
+ : input.signalsJobEnabled === true;
611
651
  const scriptsDir = path.join(input.profileDir, "scripts");
612
652
  fs.mkdirSync(scriptsDir, { recursive: true, mode: 0o700 });
613
653
  const logFile = path.join(input.dir, "logs", "hot-signal-sync.log");
@@ -620,7 +660,7 @@ function ensureFleetHotSignalSyncFor(input, company, jobs) {
620
660
  company,
621
661
  hqRoot: input.config.hqRoot,
622
662
  logFile,
623
- signalsEngine: input.signalsJobEnabled === true,
663
+ signalsEngine,
624
664
  }), { mode: 0o600 });
625
665
  fs.renameSync(temporary, scriptFile);
626
666
  const current = jobs.find((job) => companyOfHotSignalSyncJob(job) === company) ?? null;
@@ -635,7 +675,7 @@ function ensureFleetHotSignalSyncFor(input, company, jobs) {
635
675
  return { company, created: false, job: null, heldBy };
636
676
  const job = input.ops.create({
637
677
  name: FLEET_HOT_SIGNAL_SYNC_NAME,
638
- prompt: input.signalsJobEnabled === true
678
+ prompt: signalsEngine
639
679
  ? `Run the signals engine for ${company} and post to the owner only when it finds new signals.`
640
680
  : `Run the hot-channel sync for ${company}.`,
641
681
  schedule: FLEET_HOT_SIGNAL_SYNC_SCHEDULE,
@@ -142,13 +142,13 @@ export interface BotRunDeps {
142
142
  }) => Promise<SignalsJobResult>;
143
143
  /**
144
144
  * US-006 AC9: the member's "Try now" answer to a signals job reply.
145
- * Resolves cli.bot-signals-engine-job the same way a fired job does and
146
- * returns null when it is off (the message then goes to the model as
147
- * before); otherwise the runner for one `--trigger chat --force` run of the
145
+ * Resolves cli.bot-signals-engine-job and the capture settings the same way
146
+ * a fired job does and returns null when the engine is not chosen (the
147
+ * message then goes to the model as before); otherwise the runner for one `--trigger chat --force` run of the
148
148
  * signals engine through the job's own entry point, with its caps and lock.
149
149
  * Unset = "Try now" is never handled here.
150
150
  */
151
- signalsTryNow?: () => Promise<((input: SignalsTryNowInput) => Promise<SignalsJobResult>) | null>;
151
+ signalsTryNow?: (company: string) => Promise<((input: SignalsTryNowInput) => Promise<SignalsJobResult>) | null>;
152
152
  heartbeatIntervalMs?: number;
153
153
  readyComponents?: () => HeartbeatReadyComponents;
154
154
  /** Override the rendered system prompt (tests). */
@@ -2500,7 +2500,8 @@ export async function runBot(deps) {
2500
2500
  * holds the company lock starts nothing, gets the "already running" reply,
2501
2501
  * and leaves the offer as it was. Returns false (the normal model turn
2502
2502
  * answers) when the text is not "Try now", no offer is open, the company
2503
- * is no longer this bot's, or cli.bot-signals-engine-job is off.
2503
+ * is no longer this bot's, or the engine is not chosen for it
2504
+ * (cli.bot-signals-engine-job off, or capture off on this computer).
2504
2505
  */
2505
2506
  const runSignalsTryNow = async (item, text) => {
2506
2507
  const id = item.messageId;
@@ -2552,14 +2553,15 @@ export async function runBot(deps) {
2552
2553
  log("info", `"Try now" ${id}: the offer for ${company} is not this bot's company any more; cleared it, answering with a model turn`);
2553
2554
  return false;
2554
2555
  }
2555
- run = await deps.signalsTryNow();
2556
+ // cli.bot-signals-engine-job is a company flag: read for the offer's company.
2557
+ run = await deps.signalsTryNow(company);
2556
2558
  }
2557
2559
  catch (err) {
2558
2560
  log("warn", `"Try now" check failed (${err instanceof Error ? err.message : String(err)}); answering ${id} with a model turn`);
2559
2561
  return false;
2560
2562
  }
2561
2563
  if (!run) {
2562
- log("info", `"Try now" ${id}: ${BOT_SIGNALS_ENGINE_JOB_FLAG} is off; answering with a model turn`);
2564
+ log("info", `"Try now" ${id}: the signals engine does not run for ${company} (${BOT_SIGNALS_ENGINE_JOB_FLAG} is off for it, or its capture settings are off on this computer); answering with a model turn`);
2563
2565
  return false;
2564
2566
  }
2565
2567
  const target = { kind: "dm", peerUid: config.ownerUid };
@@ -1,18 +1,58 @@
1
+ import type { CompanyFlagGateDependencies } from "../flag-registry.js";
2
+ export declare const BOT_SIGNALS_ENGINE_JOB_FLAG = "cli.bot-signals-engine-job";
3
+ export interface SignalsEngineFlagSession {
4
+ token: string;
5
+ companyUid: string;
6
+ }
7
+ export interface SignalsEngineFlagDeps {
8
+ /**
9
+ * The signed-in person's token and the company's uid, or null when nobody is
10
+ * signed in. Defaults to the local HQ login, the same one the sync uses.
11
+ */
12
+ session?: (company: string) => Promise<SignalsEngineFlagSession | null>;
13
+ /** Test seam for the flag registry client. */
14
+ createClient?: CompanyFlagGateDependencies["createClient"];
15
+ /** Where a failed read is reported. Defaults to stderr. */
16
+ log?: (message: string) => void;
17
+ timeoutMs?: number;
18
+ }
19
+ /** Whether the signals engine is on for `company`'s hot-signal-sync job. Never throws. */
20
+ export declare function botSignalsEngineJobEnabled(company: string, deps?: SignalsEngineFlagDeps): Promise<boolean>;
1
21
  /**
2
- * Default-off rollout gate for the signals engine in the bot's built-in
3
- * hot-signal-sync job (hq-cli #2306, hot-signal-sync US-006).
4
- *
5
- * Off (the default): a fired job runs the hot-channel sync alone, as before
6
- * #2306. On: the job runs the full signals engine (`runSignals`) and replies in
7
- * the storyboarded format. Turn it on for a company in the flag registry, or on
8
- * one computer with `HQ_FLAG_CLI_BOT_SIGNALS_ENGINE_JOB=true` in the bot's
9
- * environment.
22
+ * The companies, out of `companies`, whose hot-signal-sync job runs the signals
23
+ * engine. Each company is read once and on its own: one company's failed read
24
+ * leaves the others' answers alone. Never throws.
10
25
  */
11
- export declare const BOT_SIGNALS_ENGINE_JOB_FLAG = "cli.bot-signals-engine-job";
12
- export declare function botSignalsEngineJobEnabled(): Promise<boolean>;
26
+ export declare function signalsEngineCompanies(companies: readonly string[], deps?: SignalsEngineFlagDeps): Promise<Set<string>>;
27
+ export interface SignalsEngineJobDeps extends SignalsEngineFlagDeps {
28
+ /** The HQ folder on this computer whose capture settings decide. */
29
+ hqRoot: string;
30
+ /** Test seam for the flag half. Defaults to `botSignalsEngineJobEnabled`. */
31
+ flagOn?: (company: string) => Promise<boolean>;
32
+ /**
33
+ * Test seam for the capture half: whether the engine would skip `company`
34
+ * as prefs-off. Defaults to the engine's own check. Throws when the
35
+ * settings cannot be read.
36
+ */
37
+ prefsOff?: (hqRoot: string, company: string) => boolean | Promise<boolean>;
38
+ }
39
+ /**
40
+ * Whether a hot-signal-sync job for `company` runs the signals engine: the
41
+ * flag is on for that company and the engine would not skip it as prefs-off on
42
+ * this computer. Otherwise the job runs the hot-channel sync. Never throws.
43
+ */
44
+ export declare function signalsEngineRunsJob(company: string, deps: SignalsEngineJobDeps): Promise<boolean>;
45
+ /**
46
+ * The companies, out of `companies`, whose hot-signal-sync job runs the signals
47
+ * engine: the flag is on for the company (`signalsEngineCompanies`) and the
48
+ * engine would not skip it as prefs-off on this computer. Each company is
49
+ * decided once and on its own. Never throws.
50
+ */
51
+ export declare function signalsEngineJobCompanies(companies: readonly string[], deps: SignalsEngineJobDeps): Promise<Set<string>>;
13
52
  /**
14
- * The engine a fired hot-signal-sync job gets: `engine` when the flag is on,
15
- * otherwise undefined, so `runHotSignalSyncJob` takes its sync-only path.
53
+ * The engine a fired hot-signal-sync job for `company` gets: `engine` when
54
+ * `signalsEngineRunsJob` says so, otherwise undefined, so `runHotSignalSyncJob`
55
+ * takes its sync-only path. "Try now" asks the same question.
16
56
  */
17
- export declare function signalsEngineForJob<T>(engine: T, enabled?: () => Promise<boolean>): Promise<T | undefined>;
57
+ export declare function signalsEngineForJob<T>(engine: T, company: string, deps: SignalsEngineJobDeps): Promise<T | undefined>;
18
58
  //# sourceMappingURL=signals-engine-flag.d.ts.map
@@ -7,24 +7,217 @@
7
7
  * the storyboarded format. Turn it on for a company in the flag registry, or on
8
8
  * one computer with `HQ_FLAG_CLI_BOT_SIGNALS_ENGINE_JOB=true` in the bot's
9
9
  * environment.
10
+ *
11
+ * The flag is read for the company the job is for, never for the bot's
12
+ * process. A personal bot runs the job for every company its owner belongs to
13
+ * and has no company of its own, so a read with no company can only return the
14
+ * row's default: a company override would never match. Both callers go through
15
+ * this file: the bot's own job (`signalsEngineForJob`) and the HQ Fleet Runtime
16
+ * job script (`signalsEngineJobCompanies`, lib/bot/fleet-cron.ts).
17
+ *
18
+ * A read that fails, times out or has no signed-in person answers off, with one
19
+ * logged line, so that company's job runs the hot-channel sync as before.
20
+ *
21
+ * The flag is half of the choice. The engine skips a company whose
22
+ * signals_capture and ontology_capture settings are both off on this computer
23
+ * (`prefs-off`), while the hot-channel sync writes meeting signals whatever
24
+ * those settings say. So a job gets the engine only when the flag is on for
25
+ * its company and the engine would not skip that company as prefs-off here;
26
+ * otherwise it keeps the hot-channel sync, with one logged line. The second
27
+ * half is the engine's own check (`capturePrefsOff`, lib/signals/engine.ts).
28
+ * `signalsEngineRunsJob`, `signalsEngineJobCompanies` and `signalsEngineForJob`
29
+ * make the whole choice; `botSignalsEngineJobEnabled` and
30
+ * `signalsEngineCompanies` answer the flag half alone. The computer-wide
31
+ * `HQ_FLAG_CLI_BOT_SIGNALS_ENGINE_JOB` switch sets the flag half only: capture
32
+ * must still be on for the engine to be chosen.
10
33
  */
34
+ import * as path from "node:path";
35
+ import { readLocalOverride } from "@indigoai-us/hq-flags-client";
36
+ import { capturePrefsOff, defaultSpawn } from "../signals/engine.js";
11
37
  export const BOT_SIGNALS_ENGINE_JOB_FLAG = "cli.bot-signals-engine-job";
12
- export async function botSignalsEngineJobEnabled() {
38
+ /** Each company's read (sign-in, company lookup, registry) is given this long. */
39
+ const FLAG_READ_TIMEOUT_MS = 5_000;
40
+ /**
41
+ * The local HQ login, resolved once and shared by every company read made
42
+ * through the returned function, so several companies never refresh the same
43
+ * login at the same time.
44
+ */
45
+ function signedInSessions() {
46
+ let login;
47
+ return async (company) => {
48
+ login ??= (async () => {
49
+ let token = process.env.HQ_ACCESS_TOKEN;
50
+ if (!token) {
51
+ try {
52
+ const { ensureCognitoIdToken } = await import("../../utils/cognito-session.js");
53
+ token = await ensureCognitoIdToken({ interactive: false });
54
+ }
55
+ catch {
56
+ // No usable login on this computer, as in the sync's own sign-in check.
57
+ return null;
58
+ }
59
+ }
60
+ const { getCompanyUid } = await import("../../utils/vault-api.js");
61
+ const idToken = token;
62
+ return { token: idToken, companyUid: (slug) => getCompanyUid(idToken, slug) };
63
+ })();
64
+ const signedIn = await login;
65
+ if (!signedIn)
66
+ return null;
67
+ return { token: signedIn.token, companyUid: await signedIn.companyUid(company) };
68
+ };
69
+ }
70
+ async function readForCompany(company, session, deps) {
71
+ const log = deps.log ?? ((message) => console.warn(`hq: ${message}`));
72
+ const keepSync = (reason) => {
73
+ try {
74
+ log(`Could not read ${BOT_SIGNALS_ENGINE_JOB_FLAG} for ${company} (${reason}); the bot's signals job for ${company} runs the hot-channel sync only.`);
75
+ }
76
+ catch {
77
+ // A logger that fails must not turn a safe "off" into a failed job.
78
+ }
79
+ return false;
80
+ };
81
+ let timer;
13
82
  try {
14
- const { resolveProcessFlagGate } = await import("../flag-registry.js");
15
- return resolveProcessFlagGate(BOT_SIGNALS_ENGINE_JOB_FLAG, { fallback: false }, () => false);
83
+ const read = (async () => {
84
+ const signedIn = await session(company);
85
+ if (!signedIn)
86
+ return "signed-out";
87
+ const { readCompanyFlag } = await import("../flag-registry.js");
88
+ return readCompanyFlag(signedIn.companyUid, signedIn.token, BOT_SIGNALS_ENGINE_JOB_FLAG, { fallback: false }, deps.createClient ? { createClient: deps.createClient } : {});
89
+ })();
90
+ // A read that loses the race below must not surface later as an unhandled rejection.
91
+ read.catch(() => { });
92
+ const timedOut = new Promise((resolve) => {
93
+ timer = setTimeout(() => resolve("timed-out"), Math.max(0, deps.timeoutMs ?? FLAG_READ_TIMEOUT_MS));
94
+ });
95
+ const result = await Promise.race([read, timedOut]);
96
+ if (result === "timed-out")
97
+ return keepSync("no answer in time");
98
+ if (result === "signed-out")
99
+ return keepSync("not signed in to HQ");
100
+ if (result === null)
101
+ return keepSync("the flag registry did not answer");
102
+ return result.value;
16
103
  }
17
104
  catch (error) {
18
- const errorClass = error instanceof Error ? error.name : "unknown";
19
- console.warn(`hq: Could not resolve ${BOT_SIGNALS_ENGINE_JOB_FLAG} (${errorClass}); the bot's signals job runs the sync only.`);
105
+ // The error class only: a message can carry a URL or a token.
106
+ return keepSync(error instanceof Error ? error.name : "unknown");
107
+ }
108
+ finally {
109
+ if (timer)
110
+ clearTimeout(timer);
111
+ }
112
+ }
113
+ /** Whether the signals engine is on for `company`'s hot-signal-sync job. Never throws. */
114
+ export async function botSignalsEngineJobEnabled(company, deps = {}) {
115
+ // The computer-wide switch decides for every company and needs no registry read.
116
+ const override = readLocalOverride(BOT_SIGNALS_ENGINE_JOB_FLAG, process.env);
117
+ if (override !== null)
118
+ return override;
119
+ return readForCompany(company, deps.session ?? signedInSessions(), deps);
120
+ }
121
+ /**
122
+ * The companies, out of `companies`, whose hot-signal-sync job runs the signals
123
+ * engine. Each company is read once and on its own: one company's failed read
124
+ * leaves the others' answers alone. Never throws.
125
+ */
126
+ export async function signalsEngineCompanies(companies, deps = {}) {
127
+ const unique = [...new Set(companies)];
128
+ const override = readLocalOverride(BOT_SIGNALS_ENGINE_JOB_FLAG, process.env);
129
+ if (override !== null)
130
+ return new Set(override ? unique : []);
131
+ const session = deps.session ?? signedInSessions();
132
+ const answers = await Promise.all(unique.map((company) => readForCompany(company, session, deps)));
133
+ return new Set(unique.filter((_, index) => answers[index] === true));
134
+ }
135
+ /** Each run of the capture settings script (two per company) is given this long. */
136
+ const CAPTURE_READ_TIMEOUT_MS = 5_000;
137
+ /**
138
+ * The engine's own prefs-off check, with a time limit on each settings read.
139
+ * The HQ folder is resolved as `runSignals` resolves it.
140
+ */
141
+ function enginePrefsOff(hqRoot, company) {
142
+ return capturePrefsOff(path.resolve(hqRoot), company, (cmd, args, opts) => defaultSpawn(cmd, args, { ...opts, timeoutMs: CAPTURE_READ_TIMEOUT_MS }));
143
+ }
144
+ /**
145
+ * The capture half, asked only for a company whose flag is on: true when the
146
+ * engine would run for `company` on this computer. Capture off, or settings
147
+ * that cannot be read, answer false with one logged line. Never throws.
148
+ */
149
+ async function captureOnFor(company, deps) {
150
+ const log = deps.log ?? ((message) => console.warn(`hq: ${message}`));
151
+ const keepSync = (message) => {
152
+ try {
153
+ log(`${message}; the bot's signals job for ${company} runs the hot-channel sync only.`);
154
+ }
155
+ catch {
156
+ // A logger that fails must not turn a safe "sync" into a failed job.
157
+ }
20
158
  return false;
159
+ };
160
+ let off;
161
+ try {
162
+ off = await (deps.prefsOff ?? enginePrefsOff)(deps.hqRoot, company);
163
+ }
164
+ catch (error) {
165
+ // The engine's own config error is written for the owner (it is the run
166
+ // record's failure reason). Any other error: the class only.
167
+ const reason = error instanceof Error ? (error.name === "SignalsConfigError" ? error.message : error.name) : "unknown";
168
+ return keepSync(`${BOT_SIGNALS_ENGINE_JOB_FLAG} is on for ${company}, but its capture settings could not be read (${reason})`);
169
+ }
170
+ if (off !== false) {
171
+ return keepSync(`${BOT_SIGNALS_ENGINE_JOB_FLAG} is on for ${company}, but signals_capture and ontology_capture are both off on this computer, so the signals engine would skip it`);
172
+ }
173
+ return true;
174
+ }
175
+ /**
176
+ * Whether a hot-signal-sync job for `company` runs the signals engine: the
177
+ * flag is on for that company and the engine would not skip it as prefs-off on
178
+ * this computer. Otherwise the job runs the hot-channel sync. Never throws.
179
+ */
180
+ export async function signalsEngineRunsJob(company, deps) {
181
+ let flag;
182
+ try {
183
+ flag = await (deps.flagOn ?? ((slug) => botSignalsEngineJobEnabled(slug, deps)))(company);
184
+ }
185
+ catch {
186
+ flag = false;
187
+ }
188
+ if (flag !== true)
189
+ return false;
190
+ return captureOnFor(company, deps);
191
+ }
192
+ /**
193
+ * The companies, out of `companies`, whose hot-signal-sync job runs the signals
194
+ * engine: the flag is on for the company (`signalsEngineCompanies`) and the
195
+ * engine would not skip it as prefs-off on this computer. Each company is
196
+ * decided once and on its own. Never throws.
197
+ */
198
+ export async function signalsEngineJobCompanies(companies, deps) {
199
+ const unique = [...new Set(companies)];
200
+ const engine = new Set();
201
+ if (deps.flagOn) {
202
+ for (const company of unique) {
203
+ if (await signalsEngineRunsJob(company, deps))
204
+ engine.add(company);
205
+ }
206
+ return engine;
207
+ }
208
+ const flagged = await signalsEngineCompanies(unique, deps);
209
+ for (const company of unique) {
210
+ if (flagged.has(company) && (await captureOnFor(company, deps)))
211
+ engine.add(company);
21
212
  }
213
+ return engine;
22
214
  }
23
215
  /**
24
- * The engine a fired hot-signal-sync job gets: `engine` when the flag is on,
25
- * otherwise undefined, so `runHotSignalSyncJob` takes its sync-only path.
216
+ * The engine a fired hot-signal-sync job for `company` gets: `engine` when
217
+ * `signalsEngineRunsJob` says so, otherwise undefined, so `runHotSignalSyncJob`
218
+ * takes its sync-only path. "Try now" asks the same question.
26
219
  */
27
- export async function signalsEngineForJob(engine, enabled = botSignalsEngineJobEnabled) {
28
- return (await enabled()) ? engine : undefined;
220
+ export async function signalsEngineForJob(engine, company, deps) {
221
+ return (await signalsEngineRunsJob(company, deps)) ? engine : undefined;
29
222
  }
30
223
  //# sourceMappingURL=signals-engine-flag.js.map