@indigoai-us/hq-cli 5.345.208 → 5.345.211

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 (133) hide show
  1. package/CHANGELOG.md +106 -0
  2. package/assets/scaffold/core/scripts/derive-trigger-facts.sh +22 -3
  3. package/assets/scaffold/core/scripts/lib/trigger-fact-text.awk +152 -41
  4. package/dist/command-catalog.generated.d.ts +33 -8
  5. package/dist/command-catalog.generated.js +40 -8
  6. package/dist/command-registration-plan.d.ts +2 -2
  7. package/dist/command-registration-plan.js +1 -1
  8. package/dist/commands/access.js +11 -5
  9. package/dist/commands/agents.d.ts +8 -0
  10. package/dist/commands/agents.js +5 -0
  11. package/dist/commands/bot.d.ts +8 -0
  12. package/dist/commands/bot.js +67 -7
  13. package/dist/commands/channels.js +4 -0
  14. package/dist/commands/cloud.d.ts +83 -2
  15. package/dist/commands/cloud.js +161 -31
  16. package/dist/commands/company.d.ts +9 -0
  17. package/dist/commands/company.js +44 -14
  18. package/dist/commands/core-checkpoint-native.js +21 -0
  19. package/dist/commands/core-derive-trigger-facts-native.d.ts +1 -0
  20. package/dist/commands/core-derive-trigger-facts-native.js +75 -14
  21. package/dist/commands/core-generate-workers-registry-fast.d.ts +1 -1
  22. package/dist/commands/core-generate-workers-registry-fast.js +7 -1
  23. package/dist/commands/core-job-run-native.d.ts +8 -0
  24. package/dist/commands/core-job-run-native.js +11 -3
  25. package/dist/commands/core-jobs-native.js +1 -1
  26. package/dist/commands/core-register-project-native.js +31 -1
  27. package/dist/commands/core-scan-packages-fast.d.ts +1 -1
  28. package/dist/commands/core-scan-packages-fast.js +8 -1
  29. package/dist/commands/core-work-mesh-bind-trusted-native.d.ts +14 -2
  30. package/dist/commands/core-work-mesh-bind-trusted-native.js +62 -8
  31. package/dist/commands/core.js +12 -3
  32. package/dist/commands/dm-attach.d.ts +10 -0
  33. package/dist/commands/dm-attach.js +33 -5
  34. package/dist/commands/integrations-connect.d.ts +16 -0
  35. package/dist/commands/integrations-connect.js +70 -6
  36. package/dist/commands/lanes-session-start.d.ts +17 -0
  37. package/dist/commands/lanes-session-start.js +281 -13
  38. package/dist/commands/lanes-watch.js +11 -3
  39. package/dist/commands/lanes.d.ts +4 -0
  40. package/dist/commands/lanes.js +95 -22
  41. package/dist/commands/library.d.ts +10 -0
  42. package/dist/commands/library.js +30 -3
  43. package/dist/commands/meetings.d.ts +42 -0
  44. package/dist/commands/meetings.js +157 -12
  45. package/dist/commands/mesh.js +3 -0
  46. package/dist/commands/monitor.d.ts +6 -0
  47. package/dist/commands/monitor.js +29 -19
  48. package/dist/commands/onboard.js +8 -1
  49. package/dist/commands/sources.js +7 -3
  50. package/dist/index.js +9 -0
  51. package/dist/lanes-monitor-check-argv.d.ts +1 -1
  52. package/dist/lanes-monitor-check-argv.js +2 -2
  53. package/dist/lanes-session-start-argv.d.ts +4 -1
  54. package/dist/lanes-session-start-argv.js +5 -2
  55. package/dist/lib/bot/fleet-daemon.d.ts +101 -0
  56. package/dist/lib/bot/fleet-daemon.js +227 -0
  57. package/dist/lib/bot/fleet-local.d.ts +26 -0
  58. package/dist/lib/bot/fleet-local.js +51 -2
  59. package/dist/lib/bot/index.d.ts +1 -0
  60. package/dist/lib/bot/index.js +1 -0
  61. package/dist/lib/bot/jobs/hot-signal-sync.d.ts +4 -0
  62. package/dist/lib/bot/jobs/hot-signal-sync.js +8 -1
  63. package/dist/lib/bot/log.js +3 -1
  64. package/dist/lib/bot/probe.js +2 -0
  65. package/dist/lib/bot/run.js +28 -3
  66. package/dist/lib/bot/runtime-failure.d.ts +4 -2
  67. package/dist/lib/bot/runtime-failure.js +9 -1
  68. package/dist/lib/bot/status.d.ts +17 -0
  69. package/dist/lib/bot/status.js +53 -2
  70. package/dist/lib/capacity/collectors/claude-oauth.d.ts +5 -5
  71. package/dist/lib/capacity/collectors/claude-oauth.js +6 -6
  72. package/dist/lib/core-utils/native-scaffold-help.d.ts +16 -0
  73. package/dist/lib/core-utils/native-scaffold-help.js +26 -0
  74. package/dist/lib/core-utils/session-company.d.ts +25 -8
  75. package/dist/lib/core-utils/session-company.js +59 -17
  76. package/dist/lib/daemon/catalog.d.ts +34 -1
  77. package/dist/lib/daemon/catalog.js +42 -3
  78. package/dist/lib/daemon/run.d.ts +5 -4
  79. package/dist/lib/daemon/run.js +40 -16
  80. package/dist/lib/daemon/server.js +26 -7
  81. package/dist/lib/daemon/supervisor.d.ts +2 -0
  82. package/dist/lib/daemon/supervisor.js +60 -1
  83. package/dist/lib/daemon/tools.js +17 -1
  84. package/dist/lib/db/sqlite-binding.js +2 -1
  85. package/dist/lib/doctor/checks/bots.d.ts +2 -0
  86. package/dist/lib/doctor/checks/bots.js +11 -0
  87. package/dist/lib/doctor/checks/runtime-health.js +3 -2
  88. package/dist/lib/doctor/checks/work-context.js +5 -2
  89. package/dist/lib/hook-engine/resolve.d.ts +1 -1
  90. package/dist/lib/hook-engine/resolve.js +4 -1
  91. package/dist/lib/hot-channels/adapters/meeting-providers.d.ts +2 -0
  92. package/dist/lib/hot-channels/adapters/meeting-providers.js +13 -2
  93. package/dist/lib/lanes/index.d.ts +1 -1
  94. package/dist/lib/lanes/index.js +1 -1
  95. package/dist/lib/lanes/monitor.d.ts +14 -0
  96. package/dist/lib/lanes/monitor.js +51 -10
  97. package/dist/lib/lanes/outpost-dispatch.d.ts +3 -0
  98. package/dist/lib/lanes/outpost-dispatch.js +1 -0
  99. package/dist/lib/lanes/store.d.ts +1 -1
  100. package/dist/lib/lanes/store.js +2 -1
  101. package/dist/lib/mesh/client.js +7 -1
  102. package/dist/lib/mesh/live/backfill-held.d.ts +3 -0
  103. package/dist/lib/mesh/live/backfill-held.js +167 -7
  104. package/dist/lib/mesh/live/flush.d.ts +7 -0
  105. package/dist/lib/mesh/live/flush.js +10 -1
  106. package/dist/lib/monitor.d.ts +9 -0
  107. package/dist/lib/monitor.js +33 -7
  108. package/dist/lib/onboarding/orchestrator.js +269 -132
  109. package/dist/lib/onboarding/types.d.ts +2 -0
  110. package/dist/lib/scaffold-cli-floor.js +2 -1
  111. package/dist/lib/signals/failure-alert.js +3 -1
  112. package/dist/lib/sync-core/reconcile.js +15 -11
  113. package/dist/lib/work-context/organize.d.ts +6 -0
  114. package/dist/lib/work-context/organize.js +28 -0
  115. package/dist/lib/work-context/paths.d.ts +9 -0
  116. package/dist/lib/work-context/paths.js +15 -0
  117. package/dist/lib/work-context/prd-sync.js +2 -1
  118. package/dist/runners-alias.d.ts +54 -0
  119. package/dist/runners-alias.js +86 -0
  120. package/dist/utils/install-tree-torn.js +5 -3
  121. package/dist/utils/npm-install-flags.d.ts +27 -0
  122. package/dist/utils/npm-install-flags.js +68 -0
  123. package/dist/utils/package-use-lease.js +1 -1
  124. package/dist/utils/qmd-native-binding-error.js +2 -1
  125. package/dist/utils/self-update.js +2 -1
  126. package/dist/utils/staged-install.js +2 -1
  127. package/dist/utils/staged-npm-install.js +2 -1
  128. package/dist/utils/upload-author.d.ts +2 -1
  129. package/dist/utils/upload-author.js +9 -5
  130. package/dist/utils/version-check.js +2 -1
  131. package/dist/utils/version-gate.js +7 -6
  132. package/package.json +7 -7
  133. package/scripts/install-hook-engine.mjs +7 -3
@@ -70,6 +70,19 @@ function isAccessKeyRequiredError(err) {
70
70
  err.code === DIRECT_MCP_AUTH_REJECTED_CODE &&
71
71
  err.oauthProtected !== true);
72
72
  }
73
+ /** Caller forced a non-OAuth mode; do not auto-switch into the browser flow. */
74
+ function forcedNonOAuthAuth(opts) {
75
+ return opts.auth === "key" || opts.auth === "none" || Boolean(opts.authHeader);
76
+ }
77
+ function oauthDespiteForcedKey(target, opts, err) {
78
+ const forced = opts.auth === "none" ? "--auth none" : opts.auth === "key" ? "--auth key" : "--auth-header";
79
+ return new IntegrationsCliError(`${target.label} did not accept an API key (${err.message}). ${forced} was set, so HQ did not start a browser sign-in. Re-run without ${forced} to use OAuth, or use a key this endpoint accepts.`, {
80
+ expected: true,
81
+ code: err.code,
82
+ status: err.status,
83
+ oauthProtected: err.oauthProtected,
84
+ });
85
+ }
73
86
  /**
74
87
  * hq-pro will not take our loopback callback, for either of the two reasons it
75
88
  * can refuse one:
@@ -295,9 +308,25 @@ function promptForKey(label) {
295
308
  * `--token` flag. Refuses rather than connecting credential-less when there is
296
309
  * nobody to ask.
297
310
  */
311
+ /**
312
+ * HQ-PRO-5QF: a key pasted from a doc or chat often arrives wrapped across
313
+ * lines or with a tab, and sometimes with smart quotes. hq-pro sends the key
314
+ * in an HTTP header, which can't carry those characters. Trim the ends, drop
315
+ * inner line breaks and tabs, and refuse anything else outside visible ASCII
316
+ * (an inner space is left for hq-pro to judge, since HTTP Basic allows it).
317
+ * The message never echoes the key.
318
+ */
319
+ export const API_KEY_UNSENDABLE_MESSAGE = "The key contains a character that can't be sent. Copy it again and paste only the key.";
320
+ export function normalizePastedApiKey(raw) {
321
+ const cleaned = raw.trim().replace(/[\r\n\t]+/g, "");
322
+ if (!/^[\x20-\x7e]*$/.test(cleaned)) {
323
+ throw new IntegrationsCliError(API_KEY_UNSENDABLE_MESSAGE, { expected: true });
324
+ }
325
+ return cleaned;
326
+ }
298
327
  async function resolveKey(opts, appLabel) {
299
328
  if (opts.tokenStdin) {
300
- const piped = (await readStdin()).trim();
329
+ const piped = normalizePastedApiKey(await readStdin());
301
330
  if (!piped) {
302
331
  throw new IntegrationsCliError("--token-stdin was set but stdin was empty.", {
303
332
  expected: true,
@@ -305,10 +334,13 @@ async function resolveKey(opts, appLabel) {
305
334
  }
306
335
  return piped;
307
336
  }
308
- if (opts.token)
309
- return opts.token;
337
+ if (opts.token) {
338
+ const flagged = normalizePastedApiKey(opts.token);
339
+ if (flagged)
340
+ return flagged;
341
+ }
310
342
  if (process.stdin.isTTY) {
311
- const value = (await promptForKey(`API key for ${appLabel}`)).trim();
343
+ const value = normalizePastedApiKey(await promptForKey(`API key for ${appLabel}`));
312
344
  if (!value) {
313
345
  throw new IntegrationsCliError("No API key entered — nothing was connected.", {
314
346
  expected: true,
@@ -1200,8 +1232,14 @@ async function connectApp(token, companyUid, app, opts, expectedRevivedConnectio
1200
1232
  }
1201
1233
  // Server-authoritative detection: the endpoint turned out to be
1202
1234
  // OAuth-protected, so run the browser flow instead of making the
1203
- // caller re-issue the command with --auth oauth.
1235
+ // caller re-issue the command with --auth oauth. An explicit --auth
1236
+ // key/none or --auth-header must not be silently overridden: the
1237
+ // Brandsearch connect (feedback_0bdcfff1) printed an OAuth URL after
1238
+ // --auth key --token-stdin, so the key path never finished.
1204
1239
  if (isOAuthRequiredError(err)) {
1240
+ if (forcedNonOAuthAuth(opts)) {
1241
+ throw oauthDespiteForcedKey(target, opts, err);
1242
+ }
1205
1243
  try {
1206
1244
  const result = await connectViaOAuth(token, companyUid, target, opts);
1207
1245
  if (result)
@@ -1542,6 +1580,7 @@ export function registerConnectCommands(integrations) {
1542
1580
  .option("--connect", "For a revoked row, run `connect <domain>` to re-add and revive it")
1543
1581
  .option("--personal", "With --connect: re-add it as your own personal connection")
1544
1582
  .option("--company-owned", "With --connect: re-add it as a connection the whole company owns")
1583
+ .option("--mcp-url <url>", "MCP endpoint for a custom app whose install never finished (no saved endpoint)")
1545
1584
  .option("--json", "Machine-readable output")
1546
1585
  .action(async (app, opts) => {
1547
1586
  // Same validation as `connect`. Without it a typo like `--auth oauth2`
@@ -1576,8 +1615,30 @@ export function registerConnectCommands(integrations) {
1576
1615
  await connectApp(token, companyUid, connectionDomain(connection), opts, connection.id);
1577
1616
  return;
1578
1617
  }
1579
- const url = connection.installation?.surface?.url;
1618
+ // A custom MCP connection (factory:<slug>) whose install failed keeps no
1619
+ // installation, so it has no saved endpoint. Refusing it outright left
1620
+ // the broken row with no CLI repair (feedback_558830a4). Re-installing
1621
+ // the same provider slug with the endpoint the caller supplies reuses
1622
+ // that row, the same way a saved endpoint does below.
1623
+ const savedUrl = connection.installation?.surface?.url;
1624
+ const factoryConnection = connection.provider.startsWith("factory:");
1625
+ if (opts.mcpUrl && savedUrl && opts.mcpUrl !== savedUrl) {
1626
+ throw new IntegrationsCliError(`${bareProvider(connection.provider)} already has a saved endpoint, so --mcp-url does not apply. ` +
1627
+ "Run the reconnect again without --mcp-url.", { expected: true });
1628
+ }
1629
+ if (opts.mcpUrl && !savedUrl && !factoryConnection) {
1630
+ throw new IntegrationsCliError(`${bareProvider(connection.provider)} is not a custom MCP connection, so --mcp-url does not apply.`, { expected: true });
1631
+ }
1632
+ const url = savedUrl ?? opts.mcpUrl;
1580
1633
  if (!url) {
1634
+ if (factoryConnection) {
1635
+ const arg = (value) => (/^[A-Za-z0-9_.:-]+$/.test(value) ? value : shellQuote(value));
1636
+ const selector = opts.connection
1637
+ ? `--connection ${arg(opts.connection)}`
1638
+ : `--provider ${arg(bareProvider(connection.provider))}`;
1639
+ throw new IntegrationsCliError(`${bareProvider(connection.provider)} has no saved MCP endpoint because its install never finished. ` +
1640
+ `Reconnect it with: hq integrations reconnect ${selector} --mcp-url <endpoint>`, { expected: true });
1641
+ }
1581
1642
  throw new IntegrationsCliError(`${bareProvider(connection.provider)} was not installed through the app catalog, so it cannot be reconnected from here.`, { expected: true });
1582
1643
  }
1583
1644
  // Re-installing the same endpoint is the reconnect: hq-pro serializes it
@@ -1623,6 +1684,9 @@ export function registerConnectCommands(integrations) {
1623
1684
  }
1624
1685
  catch (err) {
1625
1686
  if (isOAuthRequiredError(err)) {
1687
+ if (forcedNonOAuthAuth(opts)) {
1688
+ throw oauthDespiteForcedKey(target, opts, err);
1689
+ }
1626
1690
  const result = await connectViaOAuth(token, companyUid, target, opts);
1627
1691
  if (result)
1628
1692
  reportInstall(result, opts);
@@ -13,6 +13,23 @@ export interface SessionStartOptions {
13
13
  }
14
14
  /** Offline flag values older than this trigger one background registry read. */
15
15
  export declare const SESSION_START_FLAG_REFRESH_AFTER_MS: number;
16
+ /** How conduct runs lanes: in-session subagents, or detached CLI runners. */
17
+ export type ConductRunner = "subagent" | "runner";
18
+ /**
19
+ * Resolve `conduct.runner` from settings, personal then core per key. A missing
20
+ * file, a missing key, or an unknown value resolves to `subagent`.
21
+ */
22
+ export declare function conductRunnerFromSettings(root: string): ConductRunner;
23
+ /** True when the installed hq-core reads `conduct_runner: subagent|runner`. */
24
+ export declare function hqCoreReadsRunnerPin(root: string): boolean;
25
+ /** Logged once when conduct.runner is runner and the conduct-runners skill is not installed. */
26
+ export declare const CONDUCT_RUNNERS_CORE_MISSING_LINE = "hq runners session-start: conduct.runner is runner but .claude/skills/conduct-runners/conductor-core.md is missing; using .claude/skills/conduct/conductor-core.md";
27
+ /**
28
+ * Upper bound on one run of hq-core's conduct-runner-resolve.sh. hq-core's
29
+ * SessionStart hook gives the whole CLI 2 s, so the resolver gets a fraction of
30
+ * that: a stalled resolver costs the pin, and the inject block still prints.
31
+ */
32
+ export declare const CONDUCT_RUNNER_RESOLVE_TIMEOUT_MS = 500;
16
33
  /** Starts the CL-4 read-only orphan report once per host, without holding SessionStart open. */
17
34
  export declare function startSessionStartOrphanSweep(root: string, env?: NodeJS.ProcessEnv, spawnDetached?: typeof spawn, rootScoped?: boolean): void;
18
35
  /**
@@ -1,5 +1,5 @@
1
1
  import fs from "node:fs";
2
- import { spawn } from "node:child_process";
2
+ import { spawn, spawnSync } from "node:child_process";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { createHash, randomUUID } from "node:crypto";
@@ -26,8 +26,8 @@ function readSessionMetaValue(text, key) {
26
26
  function writeCodexSessionDefaults(root, env, payload, debug) {
27
27
  if (env.HQ_HARNESS !== "codex")
28
28
  return;
29
- const sessionId = payload.session_id ?? payload.sessionId;
30
- if (!sessionId || !/^[A-Za-z0-9._-]+$/.test(sessionId) || sessionId === "." || sessionId === "..")
29
+ const sessionId = validPayloadSessionId(payload);
30
+ if (!sessionId)
31
31
  return;
32
32
  let model = typeof payload.model === "string" ? payload.model : "";
33
33
  if (/\s/.test(model))
@@ -83,15 +83,278 @@ function writeCodexSessionDefaults(root, env, payload, debug) {
83
83
  debug(`hq lanes session-start: Codex metadata bootstrap failed (${kind})`);
84
84
  }
85
85
  }
86
+ const PERSONAL_SETTINGS = path.join("personal", "settings", "orchestrator.yaml");
87
+ const CORE_SETTINGS = path.join("core", "settings", "orchestrator.yaml");
88
+ /** Shell `[ -f file ]`: a regular file, following symlinks. */
89
+ function isRegularFile(file) {
90
+ try {
91
+ return fs.statSync(file).isFile();
92
+ }
93
+ catch {
94
+ return false;
95
+ }
96
+ }
97
+ /**
98
+ * Lines inside the top-level `conduct:` map, with the block rules of hq-core's
99
+ * `yaml_runner` awk (core/scripts/conduct-runner-resolve.sh): the block starts
100
+ * after a `conduct:` line and ends at the next column-0 line that is not a
101
+ * comment. Blank lines and column-0 comments stay inside it.
102
+ */
103
+ function conductBlockLines(text) {
104
+ const lines = [];
105
+ let inBlock = false;
106
+ for (const line of text.split("\n")) {
107
+ if (/^conduct:/.test(line)) {
108
+ inBlock = true;
109
+ continue;
110
+ }
111
+ if (inBlock && /^[^ #]/.test(line))
112
+ inBlock = false;
113
+ if (inBlock)
114
+ lines.push(line);
115
+ }
116
+ return lines;
117
+ }
118
+ /**
119
+ * `default_enabled` from personal/settings/orchestrator.yaml when that file
120
+ * exists, otherwise core/settings/orchestrator.yaml. False when neither exists.
121
+ */
86
122
  function enabledFromSettings(root) {
87
- const personal = path.join(root, "personal", "settings", "orchestrator.yaml");
88
- const settings = fs.existsSync(personal) ? personal : path.join(root, "core", "settings", "orchestrator.yaml");
123
+ const personal = path.join(root, PERSONAL_SETTINGS);
124
+ const settings = fs.existsSync(personal) ? personal : path.join(root, CORE_SETTINGS);
89
125
  if (!fs.existsSync(settings))
90
126
  return false;
91
- const text = fs.readFileSync(settings, "utf8");
92
- const block = /^conduct:\s*(?:#.*)?\r?\n((?:[ \t]+.*\r?\n?)*)/m.exec(text)?.[1] ?? "";
93
- const value = /^\s+default_enabled:\s*["']?(true|false|yes|no|on|off|1|0)["']?\s*(?:#.*)?$/mi.exec(block)?.[1]?.toLowerCase();
94
- return value === "true" || value === "yes" || value === "on" || value === "1";
127
+ for (const line of conductBlockLines(fs.readFileSync(settings, "utf8"))) {
128
+ const value = /^\s+default_enabled:\s*["']?(true|false|yes|no|on|off|1|0)["']?\s*(?:#.*)?$/i.exec(line)?.[1]?.toLowerCase();
129
+ if (value !== undefined)
130
+ return value === "true" || value === "yes" || value === "on" || value === "1";
131
+ }
132
+ return false;
133
+ }
134
+ /** Maps a `conduct.runner` value to a runner. Legacy `mixed` and `lane` read as `runner`. */
135
+ function normalizeConductRunner(value) {
136
+ switch (value?.trim().toLowerCase()) {
137
+ case "subagent": return "subagent";
138
+ case "runner":
139
+ case "mixed":
140
+ case "lane": return "runner";
141
+ default: return null;
142
+ }
143
+ }
144
+ /**
145
+ * hq-core's `yaml_runner` for one file: the first ` runner:` line (exactly two
146
+ * spaces) inside the `conduct:` block, its first word with quotes removed.
147
+ * Null when the file is not a regular file or has no value. Throws when the
148
+ * file exists but cannot be read.
149
+ */
150
+ function yamlRunner(file) {
151
+ if (!isRegularFile(file))
152
+ return null;
153
+ for (const line of conductBlockLines(fs.readFileSync(file, "utf8"))) {
154
+ if (!/^ {2}runner:/.test(line))
155
+ continue;
156
+ // The second field, split on runs of spaces and tabs as awk splits $2.
157
+ const value = (line.replace(/^[ \t]+/, "").split(/[ \t]+/)[1] ?? "").replace(/["']/g, "");
158
+ return value || null;
159
+ }
160
+ return null;
161
+ }
162
+ /**
163
+ * `conduct.runner` with hq-core's per-key fallback: the personal file's value,
164
+ * then the core file's. A personal file that has other `conduct:` keys but no
165
+ * `runner:` still falls through to core. An unreadable file is skipped and
166
+ * reported, so the caller can decline to write a pin from it.
167
+ */
168
+ function conductRunnerSetting(root) {
169
+ let readFailed = false;
170
+ for (const settings of [PERSONAL_SETTINGS, CORE_SETTINGS]) {
171
+ try {
172
+ const value = yamlRunner(path.join(root, settings));
173
+ if (value !== null)
174
+ return { value, readFailed };
175
+ }
176
+ catch {
177
+ readFailed = true;
178
+ }
179
+ }
180
+ return { value: null, readFailed };
181
+ }
182
+ /**
183
+ * Resolve `conduct.runner` from settings, personal then core per key. A missing
184
+ * file, a missing key, or an unknown value resolves to `subagent`.
185
+ */
186
+ export function conductRunnerFromSettings(root) {
187
+ return normalizeConductRunner(conductRunnerSetting(root).value ?? undefined) ?? "subagent";
188
+ }
189
+ /**
190
+ * hq-core ships this resolver in the same release that teaches
191
+ * conduct-standing.sh the `subagent | runner` values. Older hq-core reads the
192
+ * `conduct_runner` pin and exits on any value other than `mixed`, `subagent` or
193
+ * `lane`, so its presence decides which values are safe to write.
194
+ */
195
+ const CONDUCT_RUNNER_RESOLVER = path.join("core", "scripts", "conduct-runner-resolve.sh");
196
+ /** True when the installed hq-core reads `conduct_runner: subagent|runner`. */
197
+ export function hqCoreReadsRunnerPin(root) {
198
+ try {
199
+ return fs.statSync(path.join(root, CONDUCT_RUNNER_RESOLVER)).isFile();
200
+ }
201
+ catch {
202
+ return false;
203
+ }
204
+ }
205
+ /** The values older hq-core's resolve_runner accepts, compared exactly as it does. */
206
+ const LEGACY_CONDUCT_RUNNER_PINS = new Set(["mixed", "subagent", "lane"]);
207
+ /**
208
+ * The value to record for older hq-core: the setting's own value when it is one
209
+ * that hq-core reads (so `mixed` keeps its routing), `runner` as `lane`, and
210
+ * nothing when the setting is missing or unknown (hq-core then applies its own
211
+ * default, as it did before).
212
+ */
213
+ function legacyConductRunnerPin(settingValue) {
214
+ if (settingValue === null)
215
+ return null;
216
+ if (LEGACY_CONDUCT_RUNNER_PINS.has(settingValue))
217
+ return settingValue;
218
+ return normalizeConductRunner(settingValue) === "runner" ? "lane" : null;
219
+ }
220
+ /** Logged once when conduct.runner is runner and the conduct-runners skill is not installed. */
221
+ export const CONDUCT_RUNNERS_CORE_MISSING_LINE = "hq runners session-start: conduct.runner is runner but .claude/skills/conduct-runners/conductor-core.md is missing; using .claude/skills/conduct/conductor-core.md";
222
+ const CONDUCT_SKILL_DIRS = {
223
+ subagent: "conduct",
224
+ runner: "conduct-runners",
225
+ };
226
+ function conductorCorePath(root, runner) {
227
+ return path.join(root, ".claude", "skills", CONDUCT_SKILL_DIRS[runner], "conductor-core.md");
228
+ }
229
+ function validPayloadSessionId(payload) {
230
+ const sessionId = payload.session_id ?? payload.sessionId;
231
+ if (!sessionId || !/^[A-Za-z0-9._-]+$/.test(sessionId) || sessionId === "." || sessionId === "..")
232
+ return null;
233
+ return sessionId;
234
+ }
235
+ /**
236
+ * Upper bound on one run of hq-core's conduct-runner-resolve.sh. hq-core's
237
+ * SessionStart hook gives the whole CLI 2 s, so the resolver gets a fraction of
238
+ * that: a stalled resolver costs the pin, and the inject block still prints.
239
+ */
240
+ export const CONDUCT_RUNNER_RESOLVE_TIMEOUT_MS = 500;
241
+ /**
242
+ * Ask the installed hq-core which runner this session uses, by running its
243
+ * conduct-runner-resolve.sh from the HQ root. Returns null, so that no pin is
244
+ * written, when the resolver fails, times out, or prints anything other than
245
+ * `subagent` or `runner`. The resolver's stderr is never forwarded.
246
+ */
247
+ function resolveRunnerWithHqCore(root, sessionId, env, debug) {
248
+ const result = spawnSync("/bin/sh", [path.join(root, CONDUCT_RUNNER_RESOLVER), "--session-id", sessionId, "--root", root], {
249
+ cwd: root,
250
+ env,
251
+ encoding: "utf8",
252
+ timeout: CONDUCT_RUNNER_RESOLVE_TIMEOUT_MS,
253
+ killSignal: "SIGKILL",
254
+ stdio: ["ignore", "pipe", "pipe"],
255
+ maxBuffer: 64 * 1024,
256
+ });
257
+ if (result.error || result.status !== 0) {
258
+ debug("hq runners session-start: conduct-runner-resolve.sh failed; no conduct_runner pin written");
259
+ return null;
260
+ }
261
+ const value = result.stdout.trim();
262
+ if (value === "subagent" || value === "runner")
263
+ return value;
264
+ debug("hq runners session-start: conduct-runner-resolve.sh printed an unknown runner; no conduct_runner pin written");
265
+ return null;
266
+ }
267
+ /**
268
+ * Resolve the runner for this session and record it as `conduct_runner` in the
269
+ * session's meta.yaml. The file is only updated when it already exists; the HQ
270
+ * master hook creates it before this command runs.
271
+ *
272
+ * When the installed hq-core ships conduct-runner-resolve.sh, the pin is the
273
+ * value that script prints, so the CLI and /conduct cannot disagree. If the
274
+ * script fails, nothing is written. Older hq-core gets its own vocabulary from
275
+ * the settings reader, and a pin it already reads is left alone.
276
+ */
277
+ function resolveSessionConductRunner(root, payload, env, debug) {
278
+ const setting = conductRunnerSetting(root);
279
+ const fromSettings = normalizeConductRunner(setting.value ?? undefined) ?? "subagent";
280
+ const sessionId = validPayloadSessionId(payload);
281
+ if (!sessionId)
282
+ return fromSettings;
283
+ const sessionDir = path.join(root, "workspace", "sessions", sessionId);
284
+ const metaPath = path.join(sessionDir, "meta.yaml");
285
+ let text;
286
+ try {
287
+ text = fs.readFileSync(metaPath, "utf8");
288
+ }
289
+ catch {
290
+ return fromSettings;
291
+ }
292
+ const pinned = readSessionMetaValue(text, "conduct_runner").trim();
293
+ let resolved = normalizeConductRunner(pinned) ?? fromSettings;
294
+ let target;
295
+ if (hqCoreReadsRunnerPin(root)) {
296
+ const fromCore = resolveRunnerWithHqCore(root, sessionId, env, debug);
297
+ if (fromCore === null)
298
+ return resolved;
299
+ resolved = fromCore;
300
+ target = fromCore;
301
+ }
302
+ else {
303
+ // Older hq-core's /conduct exits on `runner`, so never write it there.
304
+ if (LEGACY_CONDUCT_RUNNER_PINS.has(pinned))
305
+ return resolved;
306
+ target = normalizeConductRunner(pinned) === "runner"
307
+ ? "lane"
308
+ : setting.readFailed ? null : legacyConductRunnerPin(setting.value);
309
+ }
310
+ if (target === null || pinned === target)
311
+ return resolved;
312
+ const line = `conduct_runner: ${target}\n`;
313
+ const matcher = /^[ \t]*conduct_runner:.*(?:\r?\n|$)/m;
314
+ // Other SessionStart hooks can rewrite meta.yaml at the same time (the master
315
+ // hook runs them in parallel), so never write back a stale copy of the file.
316
+ if (!matcher.test(text)) {
317
+ // A new key is appended in place: whatever another hook wrote stays.
318
+ // No O_CREAT, so a file removed since the read is not recreated.
319
+ let fd;
320
+ try {
321
+ fd = fs.openSync(metaPath, fs.constants.O_WRONLY | fs.constants.O_APPEND | (fs.constants.O_NOFOLLOW ?? 0));
322
+ fs.writeSync(fd, `${text.endsWith("\n") || !text ? "" : "\n"}${line}`);
323
+ }
324
+ catch (error) {
325
+ const kind = error instanceof Error ? error.name : "Error";
326
+ debug(`hq runners session-start: conduct_runner metadata write failed (${kind})`);
327
+ }
328
+ finally {
329
+ if (fd !== undefined)
330
+ fs.closeSync(fd);
331
+ }
332
+ return resolved;
333
+ }
334
+ // A legacy or unknown value is replaced, unless meta.yaml changed since it
335
+ // was read; then the other hook's change is kept and the session still runs
336
+ // with the resolved value.
337
+ const tempPath = path.join(sessionDir, `.meta-${process.pid}-${randomUUID()}.tmp`);
338
+ try {
339
+ fs.writeFileSync(tempPath, text.replace(matcher, line), { mode: 0o600 });
340
+ if (fs.readFileSync(metaPath, "utf8") !== text) {
341
+ debug("hq runners session-start: meta.yaml changed during conduct_runner update; kept the other change");
342
+ }
343
+ else {
344
+ fs.renameSync(tempPath, metaPath);
345
+ }
346
+ }
347
+ catch (error) {
348
+ const kind = error instanceof Error ? error.name : "Error";
349
+ debug(`hq runners session-start: conduct_runner metadata write failed (${kind})`);
350
+ }
351
+ finally {
352
+ try {
353
+ fs.rmSync(tempPath, { force: true });
354
+ }
355
+ catch { /* best-effort temp cleanup */ }
356
+ }
357
+ return resolved;
95
358
  }
96
359
  function isUnattended(env) {
97
360
  const flags = `${env.HQ_UNATTENDED ?? ""}${env.HQ_SESSION_UNATTENDED ?? ""}${env.CLAUDE_HEADLESS ?? ""}`;
@@ -379,13 +642,18 @@ export async function runLaneSessionStart(options = {}) {
379
642
  return;
380
643
  if (!forceOn && isUnattended(env))
381
644
  return;
382
- let enabled = enabledFromSettings(root);
383
- if (forceOn)
384
- enabled = true;
645
+ // HQ_AUTO_CONDUCT=1 turns conduct on without reading the settings file.
646
+ const enabled = forceOn || enabledFromSettings(root);
385
647
  if (!enabled)
386
648
  return;
387
649
  writeCodexSessionDefaults(root, env, payload, debug);
388
- const core = path.join(root, ".claude", "skills", "conduct", "conductor-core.md");
650
+ const runner = resolveSessionConductRunner(root, payload, env, debug);
651
+ let core = conductorCorePath(root, runner);
652
+ if (runner === "runner" && !fs.existsSync(core)) {
653
+ // Older hq-core has no conduct-runners skill; its default block still applies.
654
+ core = conductorCorePath(root, "subagent");
655
+ stderr.write(`${CONDUCT_RUNNERS_CORE_MISSING_LINE}\n`);
656
+ }
389
657
  if (!fs.existsSync(core))
390
658
  return;
391
659
  const block = extractConductorBlock(fs.readFileSync(core, "utf8"));
@@ -1,4 +1,4 @@
1
- import { accountStatus, coveredLaneIds, loadLanesConfig, MAX_WATCHED_LANES, MONITOR_ENGINES, MONITOR_MAX_TIMEOUT_MS, MONITOR_UNCOVERED_EXIT_CODE, monitorReminderText, runLaneWatch, } from "../lib/lanes/index.js";
1
+ import { accountStatus, coveredLaneIds, expiredLaneIds, loadLanesConfig, MAX_WATCHED_LANES, MONITOR_ENGINES, MONITOR_MAX_TIMEOUT_MS, MONITOR_UNCOVERED_EXIT_CODE, monitorReminderText, runLaneWatch, } from "../lib/lanes/index.js";
2
2
  import { LEAD_LANE_KEEP_ALIVE_FLAG } from "../lib/lanes/keep-alive.js";
3
3
  import { resolveLaneCompany } from "../lib/lanes/lane-company.js";
4
4
  import { readLanesRegistryFlag } from "../lib/lanes/registry-flag.js";
@@ -27,7 +27,7 @@ function monitorCallsForLaneIds(laneIds) {
27
27
  calls.push({
28
28
  command: `hq lanes watch ${chunk.join(" ")}`,
29
29
  timeout_ms: MONITOR_MAX_TIMEOUT_MS,
30
- persistent: true,
30
+ persistent: false,
31
31
  });
32
32
  }
33
33
  return calls;
@@ -166,6 +166,8 @@ export function createLaneWatchHandlers(deps) {
166
166
  const covered = coveredLaneIds(evidence, ctx.now());
167
167
  const activeIds = activeLanes.map((lane) => lane.lane_id);
168
168
  const uncovered = activeIds.filter((laneId) => !covered.has(laneId));
169
+ const expired = expiredLaneIds(evidence, ctx.now());
170
+ const expiredUncovered = uncovered.filter((laneId) => expired.has(laneId));
169
171
  const monitorCalls = monitorCallsForLaneIds(uncovered);
170
172
  if (opts.json) {
171
173
  printJson({
@@ -176,6 +178,9 @@ export function createLaneWatchHandlers(deps) {
176
178
  active_lane_ids: activeIds,
177
179
  covered_lane_ids: activeIds.filter((laneId) => covered.has(laneId)),
178
180
  uncovered_lane_ids: uncovered,
181
+ // Uncovered because this session's Monitor for the lane reached the
182
+ // 30-minute cap (or ended), so the fix is to re-arm it.
183
+ expired_lane_ids: expiredUncovered,
179
184
  monitor_call: monitorCalls.length === 1 ? monitorCalls[0] : null,
180
185
  monitor_calls: monitorCalls,
181
186
  });
@@ -183,8 +188,11 @@ export function createLaneWatchHandlers(deps) {
183
188
  else if (uncovered.length > 0) {
184
189
  for (const laneId of uncovered)
185
190
  console.log(`uncovered lane: ${laneId}`);
191
+ if (expiredUncovered.length > 0) {
192
+ console.log(`Monitor ended (Claude Code stops every Monitor after 30 minutes), re-arm it: ${expiredUncovered.join(" ")}`);
193
+ }
186
194
  for (const monitorCall of monitorCalls) {
187
- console.log(`Monitor(command=${JSON.stringify(monitorCall.command)}, timeout_ms=${monitorCall.timeout_ms}, persistent=true)`);
195
+ console.log(`Monitor(command=${JSON.stringify(monitorCall.command)}, timeout_ms=${monitorCall.timeout_ms})`);
188
196
  }
189
197
  }
190
198
  return uncovered.length > 0 ? MONITOR_UNCOVERED_EXIT_CODE : 0;
@@ -189,5 +189,9 @@ export declare function applyResumeProfileAndEffort(hqRoot: string, current: Lan
189
189
  }): void;
190
190
  export declare function stopCommittedState(state: LaneRecord["state"]): "cancelled" | "killed";
191
191
  export declare function readLaneReapStopEnabled(hqRoot: string, lane: LaneRecord, env: NodeJS.ProcessEnv): Promise<boolean>;
192
+ /** Group help: a runner is the detached CLI machinery behind an advanced-mode conduct lane. */
193
+ export declare const RUNNERS_GROUP_DESCRIPTION = "Detached CLI machinery that runs a conduct lane in advanced mode";
194
+ export declare function registerRunnersCommand(parent: Command, deps?: LanesCommandDeps): Command;
195
+ /** Compatibility export for in-process callers during the lanes transition. */
192
196
  export declare function registerLanesCommand(parent: Command, deps?: LanesCommandDeps): Command;
193
197
  //# sourceMappingURL=lanes.d.ts.map