@indigoai-us/hq-cli 5.345.222 → 5.345.225

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 (128) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/assets/bot-workers/setup/context/quick-reference.md +2 -2
  3. package/assets/mesh-daemon/README.md +11 -12
  4. package/dist/command-catalog.generated.d.ts +79 -5
  5. package/dist/command-catalog.generated.js +95 -5
  6. package/dist/commands/bot.d.ts +1 -1
  7. package/dist/commands/bot.js +34 -33
  8. package/dist/commands/cloud-provision.d.ts +4 -1
  9. package/dist/commands/cloud-provision.js +7 -3
  10. package/dist/commands/cloud-retire.js +1 -1
  11. package/dist/commands/core-delegate-w1b.js +210 -188
  12. package/dist/commands/core-delegate.d.ts +5 -0
  13. package/dist/commands/core-dm-bind-native.d.ts +5 -1
  14. package/dist/commands/core-dm-bind-native.js +4 -0
  15. package/dist/commands/core-job-notify-native.d.ts +5 -1
  16. package/dist/commands/core-job-notify-native.js +8 -2
  17. package/dist/commands/core-jobs-native.d.ts +27 -1
  18. package/dist/commands/core-jobs-native.js +49 -28
  19. package/dist/commands/core-pipeline-conductor-native.js +7 -7
  20. package/dist/commands/core-pipeline-driver-native.js +5 -5
  21. package/dist/commands/core-refresh-vault-access-native.d.ts +5 -0
  22. package/dist/commands/core-refresh-vault-access-native.js +3 -1
  23. package/dist/commands/core-work-mesh-bind-trusted-native.js +1 -1
  24. package/dist/commands/daemon.d.ts +2 -0
  25. package/dist/commands/daemon.js +67 -1
  26. package/dist/commands/lanes-hold.d.ts +2 -27
  27. package/dist/commands/lanes-hold.js +3 -75
  28. package/dist/commands/lanes-loop.js +1 -1
  29. package/dist/commands/lanes-session-start.js +2 -2
  30. package/dist/commands/mesh.d.ts +12 -0
  31. package/dist/commands/mesh.js +13 -4
  32. package/dist/commands/monitor.js +1 -1
  33. package/dist/commands/packs.js +14 -3
  34. package/dist/commands/sync-core.js +31 -12
  35. package/dist/commands/whoami.d.ts +10 -17
  36. package/dist/commands/whoami.js +7 -79
  37. package/dist/data/command-states.json +13 -0
  38. package/dist/index.js +1 -1
  39. package/dist/lib/bot/fleet-cron.d.ts +26 -3
  40. package/dist/lib/bot/fleet-cron.js +44 -4
  41. package/dist/lib/bot/run.d.ts +4 -4
  42. package/dist/lib/bot/run.js +5 -3
  43. package/dist/lib/bot/signals-engine-flag.d.ts +53 -13
  44. package/dist/lib/bot/signals-engine-flag.js +202 -9
  45. package/dist/lib/daemon/catalog.d.ts +8 -5
  46. package/dist/lib/daemon/catalog.js +13 -7
  47. package/dist/lib/daemon/config.d.ts +5 -0
  48. package/dist/lib/daemon/config.js +6 -0
  49. package/dist/lib/daemon/lanes-monitor-state.d.ts +55 -0
  50. package/dist/lib/daemon/lanes-monitor-state.js +129 -0
  51. package/dist/lib/daemon/lanes-reconcile-loader.d.ts +7 -0
  52. package/dist/lib/daemon/lanes-reconcile-loader.js +13 -0
  53. package/dist/lib/daemon/machine-checks.d.ts +45 -0
  54. package/dist/lib/daemon/machine-checks.js +95 -11
  55. package/dist/lib/daemon/merge-sections.d.ts +165 -0
  56. package/dist/lib/daemon/merge-sections.js +556 -0
  57. package/dist/lib/daemon/native-notice-ledger.d.ts +9 -0
  58. package/dist/lib/daemon/native-notice-ledger.js +43 -0
  59. package/dist/lib/daemon/ops/policy.d.ts +1 -1
  60. package/dist/lib/daemon/ops/policy.js +1 -1
  61. package/dist/lib/daemon/protocol.d.ts +1 -1
  62. package/dist/lib/daemon/protocol.js +0 -6
  63. package/dist/lib/daemon/run.js +76 -3
  64. package/dist/lib/daemon/selfcheck.js +2 -2
  65. package/dist/lib/daemon/server.d.ts +2 -4
  66. package/dist/lib/daemon/server.js +5 -48
  67. package/dist/lib/daemon/state-file.d.ts +74 -4
  68. package/dist/lib/daemon/state-file.js +159 -19
  69. package/dist/lib/daemon/supervisor.d.ts +11 -1
  70. package/dist/lib/daemon/supervisor.js +86 -0
  71. package/dist/lib/daemon/updater.d.ts +2 -6
  72. package/dist/lib/daemon/updater.js +4 -11
  73. package/dist/lib/daemon/whoami-cache.d.ts +96 -0
  74. package/dist/lib/daemon/whoami-cache.js +244 -0
  75. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  76. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  77. package/dist/lib/flag-registry-worker.js +33 -3
  78. package/dist/lib/flag-registry.js +13 -0
  79. package/dist/lib/hook-engine/coverage.d.ts +2 -0
  80. package/dist/lib/hook-engine/coverage.js +71 -0
  81. package/dist/lib/hook-engine/native-precompact-compatibility.json +449 -0
  82. package/dist/lib/hook-engine/reconcile.js +14 -8
  83. package/dist/lib/install/hook-target.d.ts +13 -3
  84. package/dist/lib/install/hook-target.js +14 -11
  85. package/dist/lib/lanes/envelope-repair-dispatch.js +1 -1
  86. package/dist/lib/lanes/monitor.d.ts +2 -0
  87. package/dist/lib/lanes/monitor.js +2 -1
  88. package/dist/lib/lanes/registry-flag.d.ts +6 -0
  89. package/dist/lib/lanes/registry-flag.js +3 -2
  90. package/dist/lib/lanes/repo-merge-hold.d.ts +39 -0
  91. package/dist/lib/lanes/repo-merge-hold.js +90 -0
  92. package/dist/lib/lanes/watcher-main.js +3 -3
  93. package/dist/lib/mesh/live/daemon/doctor.js +1 -1
  94. package/dist/lib/mesh/live/daemon/install.js +2 -2
  95. package/dist/lib/scan-packages/index.js +8 -9
  96. package/dist/lib/signals/engine.d.ts +8 -0
  97. package/dist/lib/signals/engine.js +15 -5
  98. package/dist/lib/sync-core/flag.d.ts +18 -0
  99. package/dist/lib/sync-core/flag.js +66 -0
  100. package/dist/lib/sync-core/reconcile.d.ts +6 -0
  101. package/dist/lib/sync-core/reconcile.js +15 -0
  102. package/dist/lib/sync-core/rollout-state.d.ts +2 -0
  103. package/dist/lib/sync-core/rollout-state.js +7 -0
  104. package/dist/lib/sync-core/vault-settings.d.ts +12 -1
  105. package/dist/lib/sync-core/vault-settings.js +23 -7
  106. package/dist/lib/windows/install-followup.js +1 -1
  107. package/dist/utils/client-health-contract.d.ts +1 -0
  108. package/dist/utils/client-health-contract.js +5 -0
  109. package/dist/utils/client-health.d.ts +2 -0
  110. package/dist/utils/client-health.js +40 -0
  111. package/dist/utils/cognito-session.d.ts +2 -14
  112. package/dist/utils/cognito-session.js +2 -40
  113. package/dist/utils/daemon-cli-version.d.ts +13 -0
  114. package/dist/utils/daemon-cli-version.js +47 -0
  115. package/dist/utils/duplicate-command-usage.js +1 -1
  116. package/dist/utils/machine-token-cache.d.ts +21 -0
  117. package/dist/utils/machine-token-cache.js +49 -0
  118. package/dist/utils/pack-contributions.d.ts +14 -2
  119. package/dist/utils/pack-contributions.js +31 -5
  120. package/dist/utils/resident-package-preload.js +4 -0
  121. package/dist/utils/whoami-identity.d.ts +54 -0
  122. package/dist/utils/whoami-identity.js +108 -0
  123. package/package.json +7 -7
  124. package/scripts/bench-core.mjs +34 -3
  125. package/dist/lib/daemon/ops/memory.d.ts +0 -18
  126. package/dist/lib/daemon/ops/memory.js +0 -65
  127. package/dist/lib/daemon/ops/mesh.d.ts +0 -38
  128. package/dist/lib/daemon/ops/mesh.js +0 -70
@@ -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
@@ -3,14 +3,14 @@
3
3
  * default list for each machine type, and the concrete unit each service
4
4
  * becomes on this host.
5
5
  *
6
- * Services run today's existing entrypoints (`hq mesh daemon run`,
6
+ * Services run today's existing entrypoints (`hq daemon service mesh`,
7
7
  * `hq bot run <name>`, `hq-sync-runner --watch`, ...) as child processes, so
8
8
  * moving a service under the daemon does not change what it does. Services
9
9
  * with no entrypoint yet stay in the catalog as `unavailable` so status shows
10
10
  * them instead of silently dropping them.
11
11
  */
12
12
  import type { MachineType } from "./machine-type.js";
13
- import type { SyncOwner } from "./config.js";
13
+ import type { SyncOwner, DaemonConfig } from "./config.js";
14
14
  import { type SyncCoreVaultPlan } from "../sync-core/engine-home.js";
15
15
  import type { RemoteControlPoolsConfig } from "./remote-control-pools.js";
16
16
  import { type SyncRunnerProcess } from "./sync-runner.js";
@@ -41,11 +41,13 @@ type UnitCommand = {
41
41
  args: string[];
42
42
  } | {
43
43
  type: "internal";
44
- task: "rotate-logs";
44
+ task: InternalTask;
45
45
  };
46
+ /** Work the daemon does in its own process on a schedule, without starting a child. */
47
+ export type InternalTask = "rotate-logs" | "lanes-reconcile";
46
48
  interface UnitBlock {
47
- /** `waiting` clears on its own once the requirement appears; `unavailable` needs a newer CLI. */
48
- state: "waiting" | "unavailable";
49
+ /** `waiting` clears when requirements appear; `unavailable` needs a newer CLI; `paused` needs an explicit resume. */
50
+ state: "waiting" | "unavailable" | "paused";
49
51
  reason: string;
50
52
  /** A failed availability probe must not stop an already running service. */
51
53
  keepRunning?: true;
@@ -154,6 +156,7 @@ export interface PlanContext {
154
156
  instantSyncEnabled?: boolean;
155
157
  /** Keep the local sync runner stopped until the operator resumes it. */
156
158
  syncPaused: boolean;
159
+ syncCorePause?: DaemonConfig['syncCorePause'];
157
160
  /**
158
161
  * The desktop app's Settings > Sync switches on this computer (US-016).
159
162
  * Off vaults are skipped by the runner; all off keeps the unit stopped.
@@ -3,7 +3,7 @@
3
3
  * default list for each machine type, and the concrete unit each service
4
4
  * becomes on this host.
5
5
  *
6
- * Services run today's existing entrypoints (`hq mesh daemon run`,
6
+ * Services run today's existing entrypoints (`hq daemon service mesh`,
7
7
  * `hq bot run <name>`, `hq-sync-runner --watch`, ...) as child processes, so
8
8
  * moving a service under the daemon does not change what it does. Services
9
9
  * with no entrypoint yet stay in the catalog as `unavailable` so status shows
@@ -320,7 +320,7 @@ function planService(service, ctx) {
320
320
  return [reconcile, ...engines, manifest, ...selfcheck];
321
321
  }
322
322
  case "mesh": {
323
- const args = ["mesh", "daemon", "run", ...(ctx.hqRoot ? ["--hq-root", ctx.hqRoot] : [])];
323
+ const args = ["daemon", "service", "mesh", ...(ctx.hqRoot ? ["--hq-root", ctx.hqRoot] : [])];
324
324
  return [
325
325
  base(service, {
326
326
  command: { type: "hq", args },
@@ -436,12 +436,15 @@ function planService(service, ctx) {
436
436
  base(service, {
437
437
  kind: "scheduled",
438
438
  // Polls every 15 s so local keep-alive resumes are admitted on time (#1396).
439
- // Each pass is a fresh `hq` node process (~1.8 s CPU, ~200 MB RSS), so
440
- // desktops reconcile in-process on lane-store changes with a bounded
441
- // timer for due keep-alive work, avoiding a fresh CLI process per poll.
439
+ // The daemon's lane-store watcher owns reconcile while it runs (the
440
+ // plan above returns no unit then). This timed unit covers the time
441
+ // before the watcher starts, a watch failure and the watch kill
442
+ // switch. It reconciles in the daemon's own process: it used to start
443
+ // a fresh `hq` node process every 15 s (~1.8 s CPU, ~200 MB RSS),
444
+ // and no longer starts any (hq-core-rust US-036).
442
445
  intervalSec: 15,
443
446
  initialDelaySec: 30,
444
- command: { type: "hq", args: ["runners", "reconcile"] },
447
+ command: { type: "internal", task: "lanes-reconcile" },
445
448
  env: ctx.hqRoot ? { HQ_ROOT: ctx.hqRoot } : {},
446
449
  ...(ctx.machineType === "desktop"
447
450
  ? { runGuard: { name: "lanes-reconcile", idleIntervalSec: 60 } }
@@ -557,8 +560,11 @@ export function planUnits(services, ctx) {
557
560
  const units = [];
558
561
  for (const service of services) {
559
562
  for (const unit of planService(service, ctx)) {
563
+ if (service === "sync-core" && ctx.syncCorePause) {
564
+ unit.blocked = { state: "paused", reason: `paused at ${ctx.syncCorePause.at} by ${ctx.syncCorePause.by}; run hq daemon resume sync-core` };
565
+ }
560
566
  const owner = unit.command ? ctx.legacyOwner(unit.id) : null;
561
- if (owner && unit.blocked?.state !== "unavailable") {
567
+ if (owner && unit.blocked?.state !== "unavailable" && unit.blocked?.state !== "paused") {
562
568
  unit.blocked = {
563
569
  state: "waiting",
564
570
  reason: `already run by ${owner}; \`hq daemon migrate\` will take it over`,
@@ -14,6 +14,11 @@ export interface DaemonConfig {
14
14
  hqCloudVersion?: string;
15
15
  /** Persisted machine-local sync pause. */
16
16
  syncPaused?: boolean;
17
+ /** Separate operator pause for the Rust sync engines only. */
18
+ syncCorePause?: {
19
+ at: string;
20
+ by: string;
21
+ };
17
22
  /** Desktop Instant Sync preference, applied when the sync unit is planned. */
18
23
  instantSyncEnabled?: boolean;
19
24
  /** Explicit desktop handoff; absent values preserve the legacy per-machine owner. */
@@ -47,6 +47,10 @@ export function readDaemonConfig(file) {
47
47
  };
48
48
  if (typeof obj.instantSyncEnabled === "boolean")
49
49
  config.instantSyncEnabled = obj.instantSyncEnabled;
50
+ const pause = obj.syncCorePause;
51
+ if (pause && typeof pause.at === 'string' && Number.isFinite(Date.parse(pause.at)) && typeof pause.by === 'string') {
52
+ config.syncCorePause = { at: pause.at, by: pause.by };
53
+ }
50
54
  if (isMachineType(obj.machineType))
51
55
  config.machineType = obj.machineType;
52
56
  if (obj.syncOwner === "daemon" || obj.syncOwner === "desktop-app")
@@ -69,6 +73,8 @@ export function writeDaemonConfig(file, config) {
69
73
  if (config.hqCloudVersion)
70
74
  ordered.hqCloudVersion = config.hqCloudVersion;
71
75
  ordered.syncPaused = config.syncPaused === true;
76
+ if (config.syncCorePause)
77
+ ordered.syncCorePause = config.syncCorePause;
72
78
  if (typeof config.instantSyncEnabled === "boolean")
73
79
  ordered.instantSyncEnabled = config.instantSyncEnabled;
74
80
  if (config.syncOwner)
@@ -0,0 +1,55 @@
1
+ /**
2
+ * The lanes_monitor section of the daemon state file (state-file.ts): for each
3
+ * Claude senior session of an active lane, what `hq lanes monitor-check
4
+ * --session <id> --engine claude --json` would answer, plus the
5
+ * `--reminder` text. The UserPromptSubmit hook (crates/hq-hook) reads it
6
+ * instead of starting `hq`, so a prompt never waits on a program. A missing or
7
+ * stale section means no reminder.
8
+ *
9
+ * The rules match runMonitorCheck in src/commands/lanes-watch.ts: a lane is
10
+ * active in the states below, and a lane is covered while a live Claude Code
11
+ * Monitor of that session watches it (coveredLaneIds). Only Claude has a
12
+ * Monitor tool, so every entry's engine is "claude"; the hook ignores an entry
13
+ * whose engine is not the session's.
14
+ */
15
+ import { type MonitorEvidence } from "../lanes/monitor.js";
16
+ import type { LaneRecord } from "../lanes/types.js";
17
+ /**
18
+ * MAX_WATCHED_LANES in src/lib/lanes/watch.ts (a test checks they match).
19
+ * Not imported: watch.ts reaches spawn.ts and worker-process.ts, whose
20
+ * entry-point block runs when the daemon bundle is the started script and
21
+ * exits the daemon with code 2.
22
+ */
23
+ export declare const LANES_MONITOR_MAX_WATCHED_LANES = 64;
24
+ import { type DaemonStateLanesMonitor, type DaemonStateMonitorCall } from "./state-file.js";
25
+ /** The states `hq lanes monitor-check` counts as active (MONITOR_ACTIVE_LANE_STATES in lanes-watch.ts). */
26
+ export declare const LANES_MONITOR_ACTIVE_STATES: ReadonlySet<string>;
27
+ export interface ComputeLanesMonitorSectionOptions {
28
+ hqRoot: string;
29
+ now: Date;
30
+ /** Default: readAllLanes from the lanes store. A throw means the store cannot be read (no section). */
31
+ loadLanes?: (hqRoot: string) => readonly Pick<LaneRecord, "lane_id" | "state" | "senior">[];
32
+ /** Home and env the default evidence reader looks for Claude transcripts under. Default: the process's. */
33
+ homedir?: () => string;
34
+ env?: NodeJS.ProcessEnv;
35
+ /** Default: readLiveMonitorEvidence. A throw omits that session. */
36
+ readEvidence?: (sessionId: string, options: {
37
+ now: Date;
38
+ readProcessCommands: () => readonly string[];
39
+ }) => MonitorEvidence;
40
+ /** Default: `ps -eww -o args=`. Read at most once per computation, and only when a session needs evidence. */
41
+ readProcessCommands?: () => readonly string[];
42
+ /** Told about each session left out because its evidence could not be read. */
43
+ onSessionError?: (sessionId: string, error: unknown) => void;
44
+ }
45
+ /** The Monitor calls that cover `laneIds`, chunked like monitorCallsForLaneIds in lanes-watch.ts. */
46
+ export declare function lanesMonitorCalls(laneIds: readonly string[]): DaemonStateMonitorCall[];
47
+ /**
48
+ * The lanes_monitor section, or null when the lane store cannot be read. One
49
+ * entry per valid session id that is the session senior of at least one
50
+ * active lane, in session id order, at most LANES_MONITOR_MAX_SESSIONS and at
51
+ * most LANES_MONITOR_MAX_BYTES serialized; sessions past either cap are left
52
+ * out. No qualifying session gives an empty `sessions` object.
53
+ */
54
+ export declare function computeLanesMonitorSection(options: ComputeLanesMonitorSectionOptions): DaemonStateLanesMonitor | null;
55
+ //# sourceMappingURL=lanes-monitor-state.d.ts.map
@@ -0,0 +1,129 @@
1
+ /**
2
+ * The lanes_monitor section of the daemon state file (state-file.ts): for each
3
+ * Claude senior session of an active lane, what `hq lanes monitor-check
4
+ * --session <id> --engine claude --json` would answer, plus the
5
+ * `--reminder` text. The UserPromptSubmit hook (crates/hq-hook) reads it
6
+ * instead of starting `hq`, so a prompt never waits on a program. A missing or
7
+ * stale section means no reminder.
8
+ *
9
+ * The rules match runMonitorCheck in src/commands/lanes-watch.ts: a lane is
10
+ * active in the states below, and a lane is covered while a live Claude Code
11
+ * Monitor of that session watches it (coveredLaneIds). Only Claude has a
12
+ * Monitor tool, so every entry's engine is "claude"; the hook ignores an entry
13
+ * whose engine is not the session's.
14
+ */
15
+ import { coveredLaneIds, defaultProcessCommands, MONITOR_MAX_TIMEOUT_MS, monitorReminderText, readLiveMonitorEvidence, } from "../lanes/monitor.js";
16
+ import { readAllLanes } from "../lanes/store.js";
17
+ /**
18
+ * MAX_WATCHED_LANES in src/lib/lanes/watch.ts (a test checks they match).
19
+ * Not imported: watch.ts reaches spawn.ts and worker-process.ts, whose
20
+ * entry-point block runs when the daemon bundle is the started script and
21
+ * exits the daemon with code 2.
22
+ */
23
+ export const LANES_MONITOR_MAX_WATCHED_LANES = 64;
24
+ const MAX_WATCHED_LANES = LANES_MONITOR_MAX_WATCHED_LANES;
25
+ import { LANES_MONITOR_MAX_BYTES, LANES_MONITOR_MAX_SESSIONS, LANES_MONITOR_SESSION_ID_RE, } from "./state-file.js";
26
+ /** The states `hq lanes monitor-check` counts as active (MONITOR_ACTIVE_LANE_STATES in lanes-watch.ts). */
27
+ export const LANES_MONITOR_ACTIVE_STATES = new Set([
28
+ "running",
29
+ "queued",
30
+ "awaiting_input",
31
+ "blocked",
32
+ ]);
33
+ /** The Monitor calls that cover `laneIds`, chunked like monitorCallsForLaneIds in lanes-watch.ts. */
34
+ export function lanesMonitorCalls(laneIds) {
35
+ const calls = [];
36
+ for (let offset = 0; offset < laneIds.length; offset += MAX_WATCHED_LANES) {
37
+ const chunk = laneIds.slice(offset, offset + MAX_WATCHED_LANES);
38
+ calls.push({
39
+ command: `hq runners watch ${chunk.join(" ")}`,
40
+ timeout_ms: MONITOR_MAX_TIMEOUT_MS,
41
+ persistent: false,
42
+ });
43
+ }
44
+ return calls;
45
+ }
46
+ /**
47
+ * The lanes_monitor section, or null when the lane store cannot be read. One
48
+ * entry per valid session id that is the session senior of at least one
49
+ * active lane, in session id order, at most LANES_MONITOR_MAX_SESSIONS and at
50
+ * most LANES_MONITOR_MAX_BYTES serialized; sessions past either cap are left
51
+ * out. No qualifying session gives an empty `sessions` object.
52
+ */
53
+ export function computeLanesMonitorSection(options) {
54
+ const { hqRoot, now } = options;
55
+ const checkedAt = now.toISOString();
56
+ let lanes;
57
+ try {
58
+ lanes = (options.loadLanes ?? ((root) => readAllLanes(root)))(hqRoot);
59
+ }
60
+ catch {
61
+ return null;
62
+ }
63
+ // Lane order is the store's (creation time, then id), the order the command prints.
64
+ const activeBySession = new Map();
65
+ for (const lane of lanes) {
66
+ if (lane.senior?.kind !== "session" || typeof lane.senior.id !== "string")
67
+ continue;
68
+ if (!LANES_MONITOR_SESSION_ID_RE.test(lane.senior.id))
69
+ continue;
70
+ if (!LANES_MONITOR_ACTIVE_STATES.has(lane.state))
71
+ continue;
72
+ if (typeof lane.lane_id !== "string" || !lane.lane_id)
73
+ continue;
74
+ const ids = activeBySession.get(lane.senior.id) ?? [];
75
+ ids.push(lane.lane_id);
76
+ activeBySession.set(lane.senior.id, ids);
77
+ }
78
+ const readCommands = options.readProcessCommands ?? defaultProcessCommands;
79
+ let processCommands;
80
+ const sharedProcessCommands = () => {
81
+ processCommands ??= readCommands();
82
+ return processCommands;
83
+ };
84
+ const readEvidence = options.readEvidence ??
85
+ ((sessionId, evidenceOptions) => readLiveMonitorEvidence(sessionId, {
86
+ ...(options.homedir ? { homedir: options.homedir } : {}),
87
+ ...(options.env ? { env: options.env } : {}),
88
+ now: () => evidenceOptions.now,
89
+ readProcessCommands: evidenceOptions.readProcessCommands,
90
+ }));
91
+ const sessions = {};
92
+ let count = 0;
93
+ let bytes = Buffer.byteLength(JSON.stringify({ checked_at: checkedAt, sessions: {} }), "utf8");
94
+ for (const sessionId of [...activeBySession.keys()].sort()) {
95
+ if (count >= LANES_MONITOR_MAX_SESSIONS)
96
+ break;
97
+ const active = activeBySession.get(sessionId);
98
+ let entry;
99
+ try {
100
+ const evidence = readEvidence(sessionId, { now, readProcessCommands: sharedProcessCommands });
101
+ if (evidence.sessionId !== sessionId) {
102
+ throw new Error(`monitor evidence was for another session`);
103
+ }
104
+ const covered = coveredLaneIds(evidence, now);
105
+ const uncovered = active.filter((laneId) => !covered.has(laneId));
106
+ entry = {
107
+ engine: "claude",
108
+ checked_at: checkedAt,
109
+ active_lane_ids: [...active],
110
+ uncovered_lane_ids: uncovered,
111
+ monitor_calls: lanesMonitorCalls(uncovered),
112
+ reminder: monitorReminderText(),
113
+ };
114
+ }
115
+ catch (error) {
116
+ options.onSessionError?.(sessionId, error);
117
+ continue;
118
+ }
119
+ // `,"<id>":<entry>`: a comma is counted for every entry, which only overstates.
120
+ const added = Buffer.byteLength(`,${JSON.stringify(sessionId)}:${JSON.stringify(entry)}`, "utf8");
121
+ if (bytes + added > LANES_MONITOR_MAX_BYTES)
122
+ break;
123
+ bytes += added;
124
+ sessions[sessionId] = entry;
125
+ count += 1;
126
+ }
127
+ return { checked_at: checkedAt, sessions };
128
+ }
129
+ //# sourceMappingURL=lanes-monitor-state.js.map
@@ -4,4 +4,11 @@ export interface DaemonLanesReconcileRegistrationOptions {
4
4
  }
5
5
  /** Load the lazy lanes command root only when the daemon needs its reconciler. */
6
6
  export declare function ensureDaemonLanesReconcileHandler(options: DaemonLanesReconcileRegistrationOptions): Promise<void>;
7
+ /**
8
+ * One lane reconcile pass in this process: the daemon's timed
9
+ * `lanes-reconcile` unit when its lane-store watcher is not running. Loads the
10
+ * reconciler on first use. A load failure throws, so the supervisor records
11
+ * the run as failed and tries again on the next tick.
12
+ */
13
+ export declare function runDaemonLanesReconcileInProcess(options: DaemonLanesReconcileRegistrationOptions, load?: (options: DaemonLanesReconcileRegistrationOptions) => Promise<void>): Promise<void>;
7
14
  //# sourceMappingURL=lanes-reconcile-loader.d.ts.map
@@ -21,4 +21,17 @@ export async function ensureDaemonLanesReconcileHandler(options) {
21
21
  throw new Error("lanes command did not register its daemon reconcile handler");
22
22
  }
23
23
  }
24
+ /**
25
+ * One lane reconcile pass in this process: the daemon's timed
26
+ * `lanes-reconcile` unit when its lane-store watcher is not running. Loads the
27
+ * reconciler on first use. A load failure throws, so the supervisor records
28
+ * the run as failed and tries again on the next tick.
29
+ */
30
+ export async function runDaemonLanesReconcileInProcess(options, load = ensureDaemonLanesReconcileHandler) {
31
+ await load(options);
32
+ const handler = daemonLanesReconcileHandler();
33
+ if (!handler)
34
+ throw new Error("the in-process lanes reconciler is not registered");
35
+ await handler();
36
+ }
24
37
  //# sourceMappingURL=lanes-reconcile-loader.js.map