@indigoai-us/hq-cli 5.345.236 → 5.345.237

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 (91) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/dist/command-catalog.generated.d.ts +1 -1
  3. package/dist/command-catalog.generated.js +1 -1
  4. package/dist/commands/bot.js +9 -0
  5. package/dist/commands/daemon.d.ts +1 -0
  6. package/dist/commands/daemon.js +70 -6
  7. package/dist/commands/deploy-app-db.js +4 -19
  8. package/dist/commands/deploy-app-upload.js +66 -40
  9. package/dist/commands/deploy-mutations.js +24 -16
  10. package/dist/commands/deploy-runtime-bindings.js +7 -26
  11. package/dist/commands/deploy-ssr.js +5 -24
  12. package/dist/commands/mesh.js +6 -2
  13. package/dist/commands/signals-run.d.ts +43 -2
  14. package/dist/commands/signals-run.js +85 -7
  15. package/dist/commands/sync-core.d.ts +7 -0
  16. package/dist/commands/sync-core.js +52 -3
  17. package/dist/lib/bot/continuity.d.ts +21 -2
  18. package/dist/lib/bot/continuity.js +48 -19
  19. package/dist/lib/bot/fleet-cron.js +6 -0
  20. package/dist/lib/bot/fleet-local.d.ts +11 -1
  21. package/dist/lib/bot/fleet-local.js +21 -1
  22. package/dist/lib/bot/fleet-state.d.ts +129 -0
  23. package/dist/lib/bot/fleet-state.js +669 -0
  24. package/dist/lib/bot/promote.d.ts +9 -3
  25. package/dist/lib/bot/promote.js +115 -16
  26. package/dist/lib/daemon/catalog.d.ts +13 -0
  27. package/dist/lib/daemon/catalog.js +32 -6
  28. package/dist/lib/daemon/lanes-reconcile-status.d.ts +0 -4
  29. package/dist/lib/daemon/lanes-reconcile-status.js +2 -12
  30. package/dist/lib/daemon/lanes-reconcile-watcher.d.ts +1 -1
  31. package/dist/lib/daemon/lanes-reconcile-watcher.js +2 -1
  32. package/dist/lib/daemon/legacy-handover.d.ts +38 -0
  33. package/dist/lib/daemon/legacy-handover.js +117 -0
  34. package/dist/lib/daemon/mesh-owner.js +2 -1
  35. package/dist/lib/daemon/run.d.ts +18 -1
  36. package/dist/lib/daemon/run.js +85 -12
  37. package/dist/lib/daemon/selfcheck.d.ts +28 -0
  38. package/dist/lib/daemon/selfcheck.js +86 -15
  39. package/dist/lib/deploy-api.d.ts +1 -1
  40. package/dist/lib/deploy-api.js +2 -1
  41. package/dist/lib/deploy-identity.d.ts +18 -0
  42. package/dist/lib/deploy-identity.js +179 -0
  43. package/dist/lib/hot-channels/alert.js +13 -6
  44. package/dist/lib/hot-channels/fleet-complete.d.ts +89 -0
  45. package/dist/lib/hot-channels/fleet-complete.js +157 -0
  46. package/dist/lib/hot-channels/run.js +2 -1
  47. package/dist/lib/hot-channels/signals-claude-login.d.ts +3 -2
  48. package/dist/lib/hot-channels/signals-claude-login.js +6 -1
  49. package/dist/lib/hot-channels/signals-pass-failure.d.ts +29 -0
  50. package/dist/lib/hot-channels/signals-pass-failure.js +36 -0
  51. package/dist/lib/hot-channels/signals-pass.d.ts +49 -2
  52. package/dist/lib/hot-channels/signals-pass.js +188 -12
  53. package/dist/lib/hot-channels/signals-runtime.d.ts +6 -3
  54. package/dist/lib/hot-channels/signals-runtime.js +11 -2
  55. package/dist/lib/lanes/reconcile-result.d.ts +5 -0
  56. package/dist/lib/lanes/reconcile-result.js +20 -2
  57. package/dist/lib/lanes/reconcile.js +12 -3
  58. package/dist/lib/mesh/live/emit.js +25 -6
  59. package/dist/lib/mesh/live/flush.js +119 -15
  60. package/dist/lib/mesh/live/reporting-privacy.d.ts +41 -0
  61. package/dist/lib/mesh/live/reporting-privacy.js +147 -1
  62. package/dist/lib/mesh/live/spool.d.ts +16 -0
  63. package/dist/lib/mesh/live/spool.js +45 -0
  64. package/dist/lib/signals/engine.d.ts +17 -3
  65. package/dist/lib/signals/engine.js +28 -9
  66. package/dist/lib/signals/failure-alert.d.ts +33 -1
  67. package/dist/lib/signals/failure-alert.js +72 -5
  68. package/dist/lib/signals/owner-notice.d.ts +94 -0
  69. package/dist/lib/signals/owner-notice.js +233 -0
  70. package/dist/lib/signals/reply.d.ts +7 -0
  71. package/dist/lib/signals/reply.js +23 -3
  72. package/dist/lib/signals/steps/adapters.d.ts +51 -2
  73. package/dist/lib/signals/steps/adapters.js +213 -7
  74. package/dist/lib/signals/steps/extract.js +18 -4
  75. package/dist/lib/signals/steps/types.d.ts +63 -1
  76. package/dist/lib/signals/steps/types.js +32 -0
  77. package/dist/lib/sync-core/engine-auth.d.ts +35 -0
  78. package/dist/lib/sync-core/engine-auth.js +96 -0
  79. package/dist/lib/sync-core/engine-home.d.ts +6 -0
  80. package/dist/lib/sync-core/engine-home.js +12 -0
  81. package/dist/lib/sync-core/rollout-state.d.ts +1 -0
  82. package/dist/lib/sync-core/rollout-state.js +3 -0
  83. package/dist/lib/vault-sync-switches.d.ts +7 -0
  84. package/dist/lib/vault-sync-switches.js +56 -0
  85. package/dist/lib/work-context/errors.d.ts +12 -0
  86. package/dist/lib/work-context/errors.js +15 -0
  87. package/dist/lib/work-context/organize.js +6 -1
  88. package/dist/lib/work-context/reconcile.js +20 -1
  89. package/dist/utils/resident-package-preload.js +34 -4
  90. package/docs/anywhere-runtime.md +6 -0
  91. package/package.json +7 -7
@@ -1,10 +1,9 @@
1
1
  import { deployApiRequest } from "../lib/deploy-api.js";
2
- import { cognitoSubjectFromToken, ensureCognitoIdToken, ensureCognitoToken, resolveCognitoTokenSource, } from "../utils/cognito-session.js";
2
+ import { DeployIdentityError, openDeployIdentity } from "../lib/deploy-identity.js";
3
3
  class BindingError extends Error {
4
4
  }
5
5
  const REFERENCE_PATH = /^[A-Z][A-Z0-9_]*(\/[A-Z][A-Z0-9_]+)*$/;
6
6
  const ALIAS = /^[A-Za-z_][A-Za-z0-9_]*$/;
7
- const PERSON_SESSION = { tokenSource: "person", interactive: false };
8
7
  const CONFIRM_STATE = "List the current bindings before trying again.";
9
8
  function projectReference(entry) {
10
9
  if (typeof entry !== "object" || entry === null)
@@ -48,34 +47,16 @@ async function scopedRequest(appId, company, update) {
48
47
  if (!company || !/^[a-z0-9][a-z0-9-]{0,62}$/.test(company)) {
49
48
  throw new BindingError("Provide an explicit --company slug.");
50
49
  }
51
- if (resolveCognitoTokenSource() === "machine") {
52
- throw new BindingError("Managing runtime bindings requires a person identity.");
53
- }
54
- const token = await ensureCognitoToken(PERSON_SESSION).catch(() => {
55
- throw new BindingError("Could not get an HQ person sign-in. Run hq login and try again.");
56
- });
57
- const headers = { "X-Org-Slug": company };
58
- if (update) {
59
- const companion = await ensureCognitoIdToken(PERSON_SESSION).catch(() => {
60
- throw new BindingError("Could not get the HQ Pro companion sign-in. Run hq login and try again.");
61
- });
62
- const accessIdentity = cognitoSubjectFromToken(token);
63
- const companionIdentity = cognitoSubjectFromToken(companion);
64
- if (!accessIdentity.sub || accessIdentity.sub !== companionIdentity.sub
65
- || (accessIdentity.entityUid && companionIdentity.entityUid && accessIdentity.entityUid !== companionIdentity.entityUid)) {
66
- throw new BindingError("Deploy and HQ Pro sign-ins must belong to the same person. Run hq login and try again.");
67
- }
68
- headers["X-HQ-Pro-Authorization"] = `Bearer ${companion}`;
69
- }
70
- const response = await deployApiRequest(token, `/api/apps/${encodeURIComponent(appId)}/secret-bindings`, update ? "PUT" : "GET", update, headers, { redirect: "error" }).catch(() => {
50
+ const request = await openDeployIdentity({ company }, { personOnly: true, companion: update !== undefined });
51
+ const response = await request((token, headers) => deployApiRequest(token, "/api/apps/" + encodeURIComponent(appId) + "/secret-bindings", update ? "PUT" : "GET", update, headers, { redirect: "error" })).catch((error) => {
52
+ if (error instanceof DeployIdentityError)
53
+ throw error;
71
54
  throw new BindingError(update
72
- ? `Could not confirm the binding replacement. ${CONFIRM_STATE}`
55
+ ? "Could not confirm the binding replacement. " + CONFIRM_STATE
73
56
  : "Could not read runtime bindings. Check your connection and try again.");
74
57
  });
75
58
  if (response.status === 200)
76
59
  return response;
77
- if (response.status === 401)
78
- throw new BindingError("Run hq login and try again.");
79
60
  if (response.status === 403 || response.status === 404) {
80
61
  throw new BindingError("Could not access runtime bindings. Check the app ID, company and your permissions.");
81
62
  }
@@ -112,7 +93,7 @@ async function report(action) {
112
93
  await action();
113
94
  }
114
95
  catch (error) {
115
- console.error(error instanceof BindingError ? error.message : "Could not confirm the runtime binding operation.");
96
+ console.error(error instanceof BindingError || error instanceof DeployIdentityError ? error.message : "Could not confirm the runtime binding operation.");
116
97
  process.exitCode = 1;
117
98
  }
118
99
  }
@@ -1,39 +1,20 @@
1
1
  import { deployApiRequest } from "../lib/deploy-api.js";
2
- import { ensureCognitoToken } from "../utils/cognito-session.js";
2
+ import { DeployIdentityError, openDeployIdentity } from "../lib/deploy-identity.js";
3
3
  class RegisterSsrError extends Error {
4
4
  }
5
- function scopeHeaders(options) {
6
- if (Boolean(options.company) === Boolean(options.personal)) {
7
- throw new RegisterSsrError("Choose exactly one of --company <slug> or --personal.");
8
- }
9
- if (!options.company)
10
- return { "X-HQ-Deploy-Scope": "personal" };
11
- if (!/^[a-z0-9][a-z0-9-]{0,62}$/.test(options.company)) {
12
- throw new RegisterSsrError("Invalid company slug.");
13
- }
14
- return { "X-Org-Slug": options.company };
15
- }
16
5
  async function register(appId, imageTag, options) {
17
- const headers = scopeHeaders(options);
18
6
  if (!/^(?:[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}|app_[A-Za-z0-9_-]+)$/i.test(appId)) {
19
7
  throw new RegisterSsrError("Use the app ID shown by hq deploy list.");
20
8
  }
21
9
  if (!/^(?:[a-z0-9][a-z0-9._-]*\/)*[a-z0-9][a-z0-9._-]*:[A-Za-z0-9_][A-Za-z0-9_.:-]*$/.test(imageTag)) {
22
10
  throw new RegisterSsrError("Give the existing ECR image in repository:tag form.");
23
11
  }
24
- const token = await ensureCognitoToken().catch(() => {
25
- throw new RegisterSsrError("Could not get an HQ sign-in for hq-deploy. Run hq login and try again.");
26
- });
27
- const appRoute = `/api/apps/${encodeURIComponent(appId)}`;
28
- const response = await deployApiRequest(token, `${appRoute}/deploy`, "POST", { type: "ssr", image_tag: imageTag }, headers)
29
- .catch(() => {
30
- throw new RegisterSsrError("Could not confirm SSR registration. Check deployment history before trying again.");
31
- });
12
+ const request = await openDeployIdentity(options);
13
+ const appRoute = "/api/apps/" + encodeURIComponent(appId);
14
+ const response = await request((token, headers) => deployApiRequest(token, appRoute + "/deploy", "POST", { type: "ssr", image_tag: imageTag }, headers, { redirect: "error" }));
32
15
  if (response.status !== 202) {
33
16
  const prefix = `hq-deploy did not confirm SSR registration (HTTP ${response.status}).`;
34
17
  switch (response.status) {
35
- case 401:
36
- throw new RegisterSsrError(`${prefix} Run hq login and try again.`);
37
18
  case 403:
38
19
  throw new RegisterSsrError(`${prefix} Check your app scope or ask the app owner or an org admin.`);
39
20
  case 404:
@@ -64,7 +45,7 @@ export function registerDeploySsrCommand(deploy) {
64
45
  await register(appId, imageTag, options);
65
46
  }
66
47
  catch (error) {
67
- console.error(error instanceof RegisterSsrError
48
+ console.error(error instanceof RegisterSsrError || error instanceof DeployIdentityError
68
49
  ? error.message
69
50
  : "Could not confirm SSR registration. Check deployment history before trying again.");
70
51
  process.exitCode = 1;
@@ -1150,8 +1150,12 @@ async function runPrdSync(opts) {
1150
1150
  evidence: { ...evidenceBase, task: event.taskId },
1151
1151
  }));
1152
1152
  const poster = createEmitPoster({ token, baseUrl: resolveVaultApiBase(process.env) });
1153
+ // Asked once. With HQ Anywhere off the events of a session with a verified
1154
+ // company binding are still sent (emitEvents); the story claim below is a
1155
+ // Board write on the person's behalf and stays off.
1156
+ const reportingOn = await reportingRuntimeAllowed(isMachineIdentity());
1153
1157
  const emitted = await emitEvents({
1154
- reportingAllowed: () => reportingRuntimeAllowed(isMachineIdentity()),
1158
+ reportingAllowed: async () => reportingOn,
1155
1159
  workMeshRoot: meshRoot,
1156
1160
  poster,
1157
1161
  newEvents: events,
@@ -1169,7 +1173,7 @@ async function runPrdSync(opts) {
1169
1173
  }
1170
1174
  const advanced = events.flatMap((event) => (event.eventId && event.taskId && !blocked.has(event.eventId) ? [event.taskId] : []));
1171
1175
  plan.commit([...alreadyOnBoard, ...advanced]);
1172
- const claimed = bound?.companyUid && bound.projectId
1176
+ const claimed = reportingOn && bound?.companyUid && bound.projectId
1173
1177
  ? await claimUnassignedInProgress({
1174
1178
  token,
1175
1179
  companyUid: bound.companyUid,
@@ -9,7 +9,8 @@
9
9
  */
10
10
  import { Command } from "commander";
11
11
  import { type RunSignalsResult, type SignalsStepChoice, type SignalsTrigger } from "../lib/signals/engine.js";
12
- import type { SignalsRunAlertSenders } from "../lib/signals/failure-alert.js";
12
+ import { type SignalsRunAlertSenders } from "../lib/signals/failure-alert.js";
13
+ import { type SignalsNoticeBot } from "../lib/signals/owner-notice.js";
13
14
  interface RunCliOptions {
14
15
  source?: string;
15
16
  incremental?: boolean;
@@ -27,7 +28,47 @@ interface RunCliOptions {
27
28
  hqRoot: string;
28
29
  }
29
30
  export declare function formatRunResult(result: RunSignalsResult, dryRun: boolean): string;
30
- export declare function foundSignalsReply(result: RunSignalsResult, company: string | undefined, timeZone: string): string | null;
31
+ /**
32
+ * The owner's reply for `--report-found`, or null when there is nothing to
33
+ * say. The HQ Fleet Runtime job sends this command's stdout to the owner and
34
+ * its stderr to a log, so this is the only line the owner gets from that job.
35
+ * It is printed when the run found signals, from the extract step or from the
36
+ * hot-channel signals pass the adapters step runs, and when that pass did not
37
+ * finish in a way the signals-failure alert counts (`signalsPassRunFailure`:
38
+ * the tool signed out, a failure after a landing, the document cap spent
39
+ * before a landing was read). The alert itself goes to stderr here.
40
+ */
41
+ export declare function foundSignalsReply(result: RunSignalsResult, company: string | undefined, timeZone: string, bot?: SignalsNoticeBot): string | null;
42
+ /**
43
+ * The Executive bot whose Fleet job runs `--report-found` (fleet-cron.ts is its
44
+ * only caller), so a signed-out notice names that bot's own sign-in. Never
45
+ * throws: an unreadable bot list gives the "your bot" wording.
46
+ */
47
+ export declare function reportFoundBot(): SignalsNoticeBot;
48
+ /**
49
+ * Everything `--report-found` prints, which HQ Fleet sends to the owner as an
50
+ * HQ DM. A run that could not do its work (`signalsNoticeProblem`: the tool
51
+ * the signals pass runs on is signed out, the pass failed, the document cap
52
+ * left landed documents unread, or the run failed) prints the owner's plain
53
+ * notice with its fix, once per company per day per cause, in place of the run
54
+ * reply. A clean run after a told problem prints the "running again" notice
55
+ * once, before the found-signals reply. Otherwise the found-signals reply, as
56
+ * before. The notice state is saved only after `write` returned.
57
+ */
58
+ export declare function reportFoundOutput(result: RunSignalsResult, opts: {
59
+ company: string | undefined;
60
+ timeZone: string;
61
+ hqRoot: string;
62
+ now: Date;
63
+ write: (text: string) => void;
64
+ log?: (message: string) => void;
65
+ /**
66
+ * The bot whose job this is. `--report-found` is printed only by the Fleet
67
+ * Executive bot's job, so a signed-out notice always names the bot's own
68
+ * sign-in, never a Claude Code sign-in. Default: "your bot".
69
+ */
70
+ bot?: SignalsNoticeBot;
71
+ }): Promise<void>;
31
72
  /**
32
73
  * The terminal alert sender for `hq signals run` (US-018). The CLI has no
33
74
  * owner-DM sender, so the terminal is the primary alert, as in
@@ -12,6 +12,9 @@ import chalk from "chalk";
12
12
  import { DEFAULT_HQ_ROOT } from "../utils/cognito-session.js";
13
13
  import { Sentry } from "../sentry.js";
14
14
  import { runSignals, signalsExitCode, SignalsUsageError, SIGNALS_STEP_CHOICES, SIGNALS_TRIGGERS, } from "../lib/signals/engine.js";
15
+ import { signalsPassRunFailure } from "../lib/signals/failure-alert.js";
16
+ import { deliverSignalsNotice, signalsNoticeProblem, UNKNOWN_SIGNALS_NOTICE_BOT } from "../lib/signals/owner-notice.js";
17
+ import { resolveExecutiveBot } from "../lib/bot/executive.js";
15
18
  import { formatRunReply } from "../lib/signals/reply.js";
16
19
  function parsePositiveInt(v) {
17
20
  const n = Number(v);
@@ -67,14 +70,83 @@ export function formatRunResult(result, dryRun) {
67
70
  }
68
71
  return `${lines.join("\n")}\n`;
69
72
  }
70
- export function foundSignalsReply(result, company, timeZone) {
73
+ /**
74
+ * The owner's reply for `--report-found`, or null when there is nothing to
75
+ * say. The HQ Fleet Runtime job sends this command's stdout to the owner and
76
+ * its stderr to a log, so this is the only line the owner gets from that job.
77
+ * It is printed when the run found signals, from the extract step or from the
78
+ * hot-channel signals pass the adapters step runs, and when that pass did not
79
+ * finish in a way the signals-failure alert counts (`signalsPassRunFailure`:
80
+ * the tool signed out, a failure after a landing, the document cap spent
81
+ * before a landing was read). The alert itself goes to stderr here.
82
+ */
83
+ export function foundSignalsReply(result, company, timeZone, bot = UNKNOWN_SIGNALS_NOTICE_BOT) {
71
84
  const record = result.records.find((r) => !company || r.company === company);
72
85
  if (!record || record.alreadyRanToday || (record.status !== "complete" && record.status !== "partial"))
73
86
  return null;
74
87
  const extract = record.steps.find((s) => s.name === "extract" && s.status !== "skipped");
75
- if (!extract || extract.itemsOut <= 0)
88
+ const passSignals = record.steps.filter((s) => s.name === "adapters").reduce((n, s) => n + (s.signalsOut ?? 0), 0);
89
+ const found = (extract?.itemsOut ?? 0) + passSignals;
90
+ if (found <= 0 && signalsPassRunFailure(record) === null)
76
91
  return null;
77
- return formatRunReply(record, result.summary, { timeZone }).text;
92
+ return formatRunReply(record, result.summary, { timeZone, bot }).text;
93
+ }
94
+ /**
95
+ * The Executive bot whose Fleet job runs `--report-found` (fleet-cron.ts is its
96
+ * only caller), so a signed-out notice names that bot's own sign-in. Never
97
+ * throws: an unreadable bot list gives the "your bot" wording.
98
+ */
99
+ export function reportFoundBot() {
100
+ try {
101
+ const bot = resolveExecutiveBot();
102
+ return bot ? { name: bot.name, runtime: typeof bot.config.runtime === "string" ? bot.config.runtime : null } : UNKNOWN_SIGNALS_NOTICE_BOT;
103
+ }
104
+ catch {
105
+ return UNKNOWN_SIGNALS_NOTICE_BOT;
106
+ }
107
+ }
108
+ /**
109
+ * Everything `--report-found` prints, which HQ Fleet sends to the owner as an
110
+ * HQ DM. A run that could not do its work (`signalsNoticeProblem`: the tool
111
+ * the signals pass runs on is signed out, the pass failed, the document cap
112
+ * left landed documents unread, or the run failed) prints the owner's plain
113
+ * notice with its fix, once per company per day per cause, in place of the run
114
+ * reply. A clean run after a told problem prints the "running again" notice
115
+ * once, before the found-signals reply. Otherwise the found-signals reply, as
116
+ * before. The notice state is saved only after `write` returned.
117
+ */
118
+ export async function reportFoundOutput(result, opts) {
119
+ const bot = opts.bot ?? UNKNOWN_SIGNALS_NOTICE_BOT;
120
+ const record = result.records.find((r) => !opts.company || r.company === opts.company);
121
+ if (!record)
122
+ return;
123
+ const problem = signalsNoticeProblem(record);
124
+ const reply = foundSignalsReply(result, opts.company, opts.timeZone, bot);
125
+ // Signals the run did find are news even on a day with a problem: the run
126
+ // reply then carries them and the notice's words and link together.
127
+ const withFound = problem !== null && signalsFoundIn(record) > 0 && reply !== null ? reply : null;
128
+ const told = await deliverSignalsNotice({
129
+ hqRoot: opts.hqRoot,
130
+ record,
131
+ now: opts.now,
132
+ send: (text) => opts.write(`${withFound ?? text}\n`),
133
+ bot,
134
+ ...(opts.log ? { log: opts.log } : {}),
135
+ });
136
+ if (problem === null) {
137
+ if (reply)
138
+ opts.write(`${reply}\n`);
139
+ }
140
+ else if (withFound && told.kind === null) {
141
+ // The cause was already told today; the signals found this run still go out.
142
+ opts.write(`${withFound}\n`);
143
+ }
144
+ }
145
+ /** Signals this run wrote: the extract step's plus the adapters step's signals pass. */
146
+ function signalsFoundIn(record) {
147
+ const extract = record.steps.find((s) => s.name === "extract" && s.status !== "skipped");
148
+ const passSignals = record.steps.filter((s) => s.name === "adapters").reduce((n, s) => n + (s.signalsOut ?? 0), 0);
149
+ return (extract?.itemsOut ?? 0) + passSignals;
78
150
  }
79
151
  function localTimeZone() {
80
152
  try {
@@ -123,9 +195,15 @@ export async function runSignalsCli(options, overrides = {}) {
123
195
  });
124
196
  const code = signalsExitCode(result);
125
197
  if (options.reportFound) {
126
- const reply = foundSignalsReply(result, options.company, localTimeZone());
127
- if (reply)
128
- process.stdout.write(`${reply}\n`);
198
+ await reportFoundOutput(result, {
199
+ company: options.company,
200
+ timeZone: localTimeZone(),
201
+ hqRoot: options.hqRoot,
202
+ now: new Date(),
203
+ write: (text) => void process.stdout.write(text),
204
+ bot: reportFoundBot(),
205
+ log: (message) => void process.stderr.write(chalk.yellow(`${message}\n`)),
206
+ });
129
207
  if (code !== 0)
130
208
  process.exitCode = code;
131
209
  return;
@@ -163,7 +241,7 @@ export function registerSignalsRunSubcommand(signals) {
163
241
  .option("--max-turns <n>", "Model turn cap for the extract step (default from core/settings/signals.yaml, else 40)", parsePositiveInt)
164
242
  .option("--max-budget-usd <x>", "Spend cap in USD for the extract step (default from core/settings/signals.yaml, else 2.00)", parseNonNegative)
165
243
  .option("--json", "Print the run record as JSON")
166
- .option("--report-found", "Print the owner's run reply only when the run found new signals; print nothing otherwise")
244
+ .option("--report-found", "Print the owner's run reply only when the run found new signals or its hot-channel signals pass did not finish; print nothing otherwise")
167
245
  .option("--redo <file>", "Process a source item again (sources/<channel>/<file>.md; repeatable; needs --company): the extract step re-queues it in the ontology worklist before listing", collectRedo)
168
246
  .option("--hq-root <path>", `HQ root (default: ${DEFAULT_HQ_ROOT})`, DEFAULT_HQ_ROOT)
169
247
  .action(async (options) => {
@@ -8,7 +8,14 @@ export interface SyncCoreReconcileCommandOptions {
8
8
  tokenFile?: string;
9
9
  json?: boolean;
10
10
  }
11
+ export interface DaemonUnitSummary {
12
+ id: string;
13
+ status: string;
14
+ reason?: string;
15
+ }
11
16
  export interface SyncCoreCommandDeps {
17
+ /** The daemon's units from its state file; null when the daemon has not written one. */
18
+ readDaemonUnits?: () => DaemonUnitSummary[] | null;
12
19
  home: string;
13
20
  env: NodeJS.ProcessEnv;
14
21
  platform: NodeJS.Platform;
@@ -2,7 +2,10 @@ import * as fs from "node:fs";
2
2
  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
- import { readEngineStatus } from "../lib/sync-core/engine-home.js";
5
+ import { readEngineStatus, syncCoreUnitId } from "../lib/sync-core/engine-home.js";
6
+ import { daemonPaths } from "../lib/daemon/paths.js";
7
+ import { describeAuthRefusal, readEngineAuthRefusal } from "../lib/sync-core/engine-auth.js";
8
+ import { LEGACY_HANDOVER_STUCK_FILE, readLegacyHandoverStuck } from "../lib/daemon/legacy-handover.js";
6
9
  import { readCompanyDownloadStreams, readCompanyRolloutFlag } from "../lib/sync-core/flag.js";
7
10
  import { reconcileSyncCore } from "../lib/sync-core/reconcile.js";
8
11
  import { engineOwnedManifestScopes, manifestScopeArg } from "../lib/sync-core/manifest-scopes.js";
@@ -177,15 +180,52 @@ function engineStatusLines(engine, full, now) {
177
180
  lines.push(` ${running.join(", ")}`);
178
181
  return lines;
179
182
  }
183
+ function readDaemonUnitsFromState(home, env) {
184
+ let parsed;
185
+ try {
186
+ parsed = JSON.parse(fs.readFileSync(daemonPaths(home, env).statePath, "utf8"));
187
+ }
188
+ catch {
189
+ return null;
190
+ }
191
+ const units = parsed?.units;
192
+ if (!Array.isArray(units))
193
+ return null;
194
+ return units.flatMap((unit) => {
195
+ const u = unit;
196
+ return u && typeof u.id === "string" && typeof u.status === "string"
197
+ ? [{ id: u.id, status: u.status, ...(typeof u.reason === "string" ? { reason: u.reason } : {}) }]
198
+ : [];
199
+ });
200
+ }
201
+ function engineUnitLine(units, vaultUid) {
202
+ if (units === null)
203
+ return "engine: unknown (hq daemon has not written its state; run `hq daemon status`)";
204
+ const unit = units.find((u) => u.id === syncCoreUnitId(vaultUid));
205
+ if (!unit)
206
+ return "engine: not planned by hq daemon yet";
207
+ if (unit.status === "running")
208
+ return "engine: running";
209
+ return `engine: ${unit.status}${unit.reason ? ` (${unit.reason})` : ""}`;
210
+ }
211
+ function pushChannelLine(engine) {
212
+ const channel = engine?.wakeChannel;
213
+ if (!channel)
214
+ return "push channel: not reported by the engine";
215
+ return `push channel: ${channel.connected ? "connected" : "not connected (the engine polls instead)"}${channel.since ? ` since ${channel.since}` : ""}`;
216
+ }
180
217
  export function runSyncCoreStatus(opts, d = defaultDeps()) {
181
218
  const state = readSyncCoreRolloutState(d.home);
182
219
  if (opts.json) {
183
220
  const jsonNow = (d.now ?? (() => new Date()))();
221
+ const jsonUnits = (d.readDaemonUnits ?? (() => readDaemonUnitsFromState(d.home, d.env)))();
184
222
  d.out(JSON.stringify(state && {
185
223
  ...state,
186
224
  vaults: state.vaults.map((vault) => {
187
225
  const engine = readEngineStatus(vault.engineHome, vault.uid, jsonNow);
188
- return engine ? { ...vault, engine } : vault;
226
+ const unit = jsonUnits?.find((u) => u.id === syncCoreUnitId(vault.uid));
227
+ const authRefused = readEngineAuthRefusal(daemonPaths(d.home, d.env).unitLogPath(syncCoreUnitId(vault.uid)), vault.engineHome, vault.uid);
228
+ return { ...vault, ...(engine ? { engine } : {}), ...(unit ? { unit } : {}), ...(authRefused ? { authRefused } : {}) };
189
229
  }),
190
230
  }, null, 2));
191
231
  return;
@@ -196,13 +236,19 @@ export function runSyncCoreStatus(opts, d = defaultDeps()) {
196
236
  }
197
237
  const switches = readVaultSyncSwitches(d.home);
198
238
  const now = (d.now ?? (() => new Date()))();
239
+ const daemonUnits = (d.readDaemonUnits ?? (() => readDaemonUnitsFromState(d.home, d.env)))();
199
240
  d.out(`engine ${state.release} at ${state.binaryPath}, last read ${state.readAt}`);
200
241
  if (state.error)
201
242
  d.out(`warning: ${state.error}`);
202
243
  for (const vault of state.vaults) {
203
244
  const legacyOff = vault.kind === "personal" ? switches.personalOff : switches.offCompanies.has(vault.slug ?? "");
204
245
  d.out(` ${vault.uid} ${vault.kind}${vault.slug ? ` ${vault.slug}` : ""} ${vault.phase === "full" ? "full" : "read-only"} legacy sync ${legacyOff ? "off" : "still on"} home ${vault.engineHome}`);
205
- for (const line of engineStatusLines(readEngineStatus(vault.engineHome, vault.uid, now), vault.phase === "full", now))
246
+ const engine = readEngineStatus(vault.engineHome, vault.uid, now);
247
+ d.out(` ${engineUnitLine(daemonUnits, vault.uid)}; ${pushChannelLine(engine)}`);
248
+ const refused = readEngineAuthRefusal(daemonPaths(d.home, d.env).unitLogPath(syncCoreUnitId(vault.uid)), vault.engineHome, vault.uid);
249
+ if (refused)
250
+ d.out(` ${describeAuthRefusal(refused)}`);
251
+ for (const line of engineStatusLines(engine, vault.phase === "full", now))
206
252
  d.out(line);
207
253
  if (vault.firstCycle) {
208
254
  const c = vault.firstCycle;
@@ -215,6 +261,9 @@ export function runSyncCoreStatus(opts, d = defaultDeps()) {
215
261
  d.out(` ${hold.uid} held: ${hold.reason}`);
216
262
  if (state.vaults.length === 0)
217
263
  d.out(" no vault is switched to the new sync engine");
264
+ for (const stuck of readLegacyHandoverStuck(path.join(daemonPaths(d.home, d.env).root, LEGACY_HANDOVER_STUCK_FILE))) {
265
+ d.out(` back on the current sync, ${stuck.reason}`);
266
+ }
218
267
  }
219
268
  export function resolveSyncCoreVault(home, name, opts = {}) {
220
269
  const wanted = name.trim();
@@ -1,4 +1,12 @@
1
+ /** Portable, identity-bound context for the local -> Fleet provisioning bridge.
2
+ * This module does not provision compute, copy credentials, or enable a consumer.
3
+ */
4
+ import * as fs from "node:fs";
1
5
  import type { BotConfig } from "./config.js";
6
+ declare const MAX_FILES = 2000;
7
+ declare const MAX_BYTES: number;
8
+ export { MAX_FILES as MAX_TRANSFER_FILES, MAX_BYTES as MAX_TRANSFER_BYTES };
9
+ export declare const PRIVATE_NAME: RegExp;
2
10
  interface ContinuityFile {
3
11
  area: "worker" | "memory";
4
12
  path: string;
@@ -21,8 +29,20 @@ export interface BotContinuityBundle {
21
29
  files: ContinuityFile[];
22
30
  digest: string;
23
31
  }
32
+ /** No link is followed, and a file that changes while it is read is refused. */
33
+ export declare function readStableFile(absolute: string, label: string, st?: fs.Stats): {
34
+ bytes: Buffer;
35
+ executable: boolean;
36
+ };
37
+ /** Reserved folder in area `memory` for state carried out of the HQ Fleet Runtime profile. */
38
+ export declare const FLEET_STATE_DIR = "fleet-state";
39
+ export interface ContinuityExtraFile {
40
+ path: string;
41
+ bytes: Buffer;
42
+ executable: boolean;
43
+ }
24
44
  /** Capture original bytes, including supporting scripts and Mac-only memory. */
25
- export declare function snapshotBotContinuity(config: BotConfig, stateDir: string): BotContinuityBundle;
45
+ export declare function snapshotBotContinuity(config: BotConfig, stateDir: string, fleetState?: readonly ContinuityExtraFile[]): BotContinuityBundle;
26
46
  /** Validate all bytes and ownership before planning any destination write. */
27
47
  export declare function validateBotContinuity(bundle: BotContinuityBundle, identity: {
28
48
  agentUid: string;
@@ -63,5 +83,4 @@ export declare function planFleetContinuity(bundle: BotContinuityBundle, target:
63
83
  sha256: string;
64
84
  };
65
85
  };
66
- export {};
67
86
  //# sourceMappingURL=continuity.d.ts.map
@@ -10,7 +10,8 @@ import { resolveBotMemoryDir } from "./config.js";
10
10
  import { packageRoot } from "../../utils/hq-roots.js";
11
11
  const MAX_FILES = 2000;
12
12
  const MAX_BYTES = 32 * 1024 * 1024;
13
- const PRIVATE_NAME = /^(?:\.env(?:\..*)?|\.ssh|\.aws|\.gnupg|\.netrc|\.git|node_modules|machine-creds\.json|bot\.json|auth\.json|credentials(?:\..*)?|id_rsa|id_ed25519)$/i;
13
+ export { MAX_FILES as MAX_TRANSFER_FILES, MAX_BYTES as MAX_TRANSFER_BYTES };
14
+ export const PRIVATE_NAME = /^(?:\.env(?:\..*)?|\.ssh|\.aws|\.gnupg|\.netrc|\.git|node_modules|machine-creds\.json|bot\.json|auth\.json|credentials(?:\..*)?|id_rsa|id_ed25519)$/i;
14
15
  const BUNDLED_SETUP_WORKER_DIR = "assets/bot-workers/setup";
15
16
  const BUNDLED_SETUP_CONTEXT = new Set([
16
17
  "skills/",
@@ -46,8 +47,33 @@ function plainDirectory(absolute, allowPrivateComponents = false) {
46
47
  }
47
48
  return resolved;
48
49
  }
50
+ /** No link is followed, and a file that changes while it is read is refused. */
51
+ export function readStableFile(absolute, label, st = fs.lstatSync(absolute)) {
52
+ if (st.isSymbolicLink())
53
+ reject(`symlink in context: ${label}`);
54
+ if (!st.isFile())
55
+ reject(`not a regular file: ${label}`);
56
+ if (st.size > MAX_BYTES)
57
+ reject(`file exceeds the transfer limit: ${label}`);
58
+ const fd = fs.openSync(absolute, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
59
+ try {
60
+ const current = fs.fstatSync(fd);
61
+ if (!current.isFile() || current.ino !== st.ino || current.dev !== st.dev)
62
+ reject(`file changed while reading: ${label}`);
63
+ const bytes = fs.readFileSync(fd);
64
+ const after = fs.fstatSync(fd);
65
+ if (after.size !== current.size || after.mtimeMs !== current.mtimeMs || bytes.length !== current.size)
66
+ reject(`file changed while reading: ${label}`);
67
+ return { bytes, executable: Boolean(st.mode & 0o111) };
68
+ }
69
+ finally {
70
+ fs.closeSync(fd);
71
+ }
72
+ }
73
+ /** Reserved folder in area `memory` for state carried out of the HQ Fleet Runtime profile. */
74
+ export const FLEET_STATE_DIR = "fleet-state";
49
75
  /** Capture original bytes, including supporting scripts and Mac-only memory. */
50
- export function snapshotBotContinuity(config, stateDir) {
76
+ export function snapshotBotContinuity(config, stateDir, fleetState = []) {
51
77
  assertIdentity(config.agentUid, config.ownerUid);
52
78
  const configuredWorkerRoot = path.resolve(config.hqRoot, config.workerDir);
53
79
  const bundledSetupRoot = path.resolve(packageRoot(), BUNDLED_SETUP_WORKER_DIR);
@@ -90,27 +116,30 @@ export function snapshotBotContinuity(config, stateDir) {
90
116
  reject(`not a regular file: ${child}`);
91
117
  if (files.length >= MAX_FILES || total + st.size > MAX_BYTES)
92
118
  reject("context exceeds transfer limit; nothing was truncated");
93
- const fd = fs.openSync(absolute, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
94
- try {
95
- const current = fs.fstatSync(fd);
96
- if (!current.isFile() || current.ino !== st.ino || current.dev !== st.dev)
97
- reject(`file changed while reading: ${child}`);
98
- const bytes = fs.readFileSync(fd);
99
- const after = fs.fstatSync(fd);
100
- if (after.size !== current.size || after.mtimeMs !== current.mtimeMs || bytes.length !== current.size)
101
- reject(`file changed while reading: ${child}`);
102
- total += bytes.length;
103
- if (total > MAX_BYTES)
104
- reject("context exceeds transfer limit");
105
- files.push({ area, path: child, bytes: bytes.length, sha256: sha(bytes), executable: Boolean(st.mode & 0o111), base64: bytes.toString("base64") });
106
- }
107
- finally {
108
- fs.closeSync(fd);
109
- }
119
+ const read = readStableFile(absolute, child, st);
120
+ total += read.bytes.length;
121
+ if (total > MAX_BYTES)
122
+ reject("context exceeds transfer limit");
123
+ files.push({ area, path: child, bytes: read.bytes.length, sha256: sha(read.bytes), executable: read.executable, base64: read.bytes.toString("base64") });
110
124
  }
111
125
  };
112
126
  walk(workerRoot, "worker");
113
127
  walk(memoryRoot, "memory");
128
+ if (fleetState.length) {
129
+ if (fs.lstatSync(path.join(memoryRoot, FLEET_STATE_DIR), { throwIfNoEntry: false }))
130
+ reject(`the memory folder already has an entry named ${FLEET_STATE_DIR}; rename it, then retry`);
131
+ for (const extra of fleetState) {
132
+ if (!extra.path.startsWith(`${FLEET_STATE_DIR}/`))
133
+ reject(`carried bot state must stay under ${FLEET_STATE_DIR}/`);
134
+ relativeFile(extra.path);
135
+ if (files.length >= MAX_FILES)
136
+ reject(`the bot's learned skills and scheduled jobs exceed the ${MAX_FILES}-file transfer limit; nothing was truncated`);
137
+ total += extra.bytes.length;
138
+ if (total > MAX_BYTES)
139
+ reject(`the bot's learned skills and scheduled jobs exceed the ${MAX_BYTES / (1024 * 1024)} MiB transfer limit; nothing was truncated`);
140
+ files.push({ area: "memory", path: extra.path, bytes: extra.bytes.length, sha256: sha(extra.bytes), executable: extra.executable, base64: extra.bytes.toString("base64") });
141
+ }
142
+ }
114
143
  if (!files.some((f) => f.area === "worker" && f.path === "worker.yaml"))
115
144
  reject("worker.yaml is missing");
116
145
  const payload = {
@@ -342,6 +342,10 @@ def classify(out, err, code):
342
342
  text = ANSI.sub('', (err or '') + '\n' + (out or ''))
343
343
  if re.search(r"HQ session has expired|not signed in to HQ|Sign in to HQ first|run .hq login", text, re.I):
344
344
  return 'you are signed out of HQ', FIXES['hq_signed_out']
345
+ if re.search(r'bot-api-key-login', text, re.I):
346
+ return "the Executive bot uses an API key", FIXES['bot_api_key']
347
+ if re.search(r'bot-logged-out', text, re.I):
348
+ return "the Executive bot's own login needs renewing", FIXES['bot_signed_out']
345
349
  # Before the plain claude checks: a Codex main bot whose signals still run
346
350
  # on Claude Code is pointed at running them on its own Codex.
347
351
  if re.search(r'claude-logged-out-codex-bot', text, re.I):
@@ -458,6 +462,8 @@ export function renderFleetHotSignalSyncScript(input) {
458
462
  const syncCommand = `hq sources sync --company ${input.company}`;
459
463
  const claudeSignInFix = `open HQ, go to Settings → AI tools, and use the Claude Code button there (Connect Claude, or Install Claude if it is not installed yet). Or run \`${signInCommand("claude")}\` in a terminal on this computer.`;
460
464
  const fixes = {
465
+ bot_signed_out: "open the Executive bot's profile in HQ, go to Brain, and reconnect its subscription login.",
466
+ bot_api_key: "open the Executive bot's profile in HQ, go to Brain, and connect its Claude or ChatGPT subscription instead of an API key.",
461
467
  hq_signed_out: "run `hq login`.",
462
468
  // The desktop app first (Settings → AI tools lists Claude Code with a
463
469
  // "Connect Claude" or "Install Claude" button), the terminal as the fallback.
@@ -322,6 +322,15 @@ export declare const FLEET_LOCAL_DISTRIBUTION_LOCK_STALE_MS: number;
322
322
  /** Whether the pinned release is installed on this machine (no download needed). */
323
323
  export declare function fleetLocalDistributionInstalled(release?: FleetLocalReleasePin, root?: string): boolean;
324
324
  export declare function installPinnedFleetLocalDistribution(deps?: FleetLocalInstallDeps): Promise<FleetLocalInstallation>;
325
+ /**
326
+ * The installed `hq-fleet-local` helper and the profile folder of an HQ Fleet
327
+ * bot, or null when the profile, the runtime or the helper is not installed.
328
+ * Never throws. Says nothing about which commands that helper release has.
329
+ */
330
+ export declare function fleetLocalHelper(agentUid: string, deps?: Pick<FleetLocalControlDeps, "fleetHome" | "platform">): {
331
+ profileDir: string;
332
+ helper: string;
333
+ } | null;
325
334
  /** The process id the bot's gateway recorded, when its file reads; the caller checks whether it is alive. */
326
335
  export declare function fleetLocalGatewayPid(agentUid: string, deps?: Pick<FleetLocalControlDeps, "fleetHome">): number | null;
327
336
  /**
@@ -369,7 +378,8 @@ export declare function fleetLocalPromotionRuntime(agentUid: string, deps?: Flee
369
378
  export declare function fleetLocalProfileProvider(agentUid: string, deps?: Pick<FleetLocalControlDeps, "fleetHome">): Partial<FleetLocalProfile["provider"]> | null;
370
379
  /**
371
380
  * The model brain a Fleet profile provider runs, or null when it names none
372
- * this hq knows. Any Anthropic sign of the provider means Claude.
381
+ * this hq knows. Any Anthropic sign of the provider, or a Claude model, means
382
+ * Claude; a Grok model means Grok.
373
383
  */
374
384
  export declare function fleetProviderBrainRuntime(provider: Partial<FleetLocalProfile["provider"]>): BotRuntimeId | null;
375
385
  export declare function removeFleetLocalBot(agentUid: string, deps?: FleetLocalControlDeps): FleetLocalRemovalResult;