@indigoai-us/hq-cli 5.345.211 → 5.345.212

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 (90) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/dist/command-catalog.generated.d.ts +28 -0
  3. package/dist/command-catalog.generated.js +34 -0
  4. package/dist/command-registration-plan.d.ts +15 -0
  5. package/dist/command-registration-plan.js +20 -1
  6. package/dist/commands/agents.js +6 -1
  7. package/dist/commands/billing.js +17 -4
  8. package/dist/commands/bot-runtime.d.ts +21 -2
  9. package/dist/commands/bot-runtime.js +54 -9
  10. package/dist/commands/bot.d.ts +13 -0
  11. package/dist/commands/bot.js +142 -12
  12. package/dist/commands/daemon.js +60 -5
  13. package/dist/commands/files.js +2 -2
  14. package/dist/commands/integrations-api.d.ts +11 -0
  15. package/dist/commands/integrations-connect.d.ts +2 -0
  16. package/dist/commands/integrations-connect.js +17 -5
  17. package/dist/commands/integrations-core.d.ts +1 -1
  18. package/dist/commands/integrations-core.js +18 -10
  19. package/dist/commands/integrations.js +1 -1
  20. package/dist/commands/lanes.js +34 -16
  21. package/dist/commands/whoami.js +7 -6
  22. package/dist/lazy-commands.js +4 -1
  23. package/dist/lib/billing/usage-only.d.ts +4 -1
  24. package/dist/lib/billing/usage-only.js +7 -2
  25. package/dist/lib/bot/api.d.ts +1 -1
  26. package/dist/lib/bot/config.js +2 -1
  27. package/dist/lib/bot/fleet-daemon.d.ts +4 -0
  28. package/dist/lib/bot/fleet-daemon.js +12 -1
  29. package/dist/lib/bot/fleet-download.d.ts +6 -0
  30. package/dist/lib/bot/fleet-download.js +128 -3
  31. package/dist/lib/bot/fleet-local.d.ts +38 -1
  32. package/dist/lib/bot/fleet-local.js +239 -26
  33. package/dist/lib/bot/install-progress.d.ts +28 -0
  34. package/dist/lib/bot/install-progress.js +185 -0
  35. package/dist/lib/bot/legacy-provider-login.d.ts +22 -1
  36. package/dist/lib/bot/legacy-provider-login.js +67 -9
  37. package/dist/lib/bot/prompt.d.ts +1 -0
  38. package/dist/lib/bot/prompt.js +3 -2
  39. package/dist/lib/bot/readiness.d.ts +68 -0
  40. package/dist/lib/bot/readiness.js +145 -0
  41. package/dist/lib/bot/run.d.ts +2 -0
  42. package/dist/lib/bot/run.js +6 -3
  43. package/dist/lib/bot/scaffold.d.ts +6 -3
  44. package/dist/lib/bot/scaffold.js +18 -12
  45. package/dist/lib/capacity/ledger.d.ts +7 -0
  46. package/dist/lib/capacity/ledger.js +31 -1
  47. package/dist/lib/capacity/project.d.ts +1 -1
  48. package/dist/lib/capacity/project.js +13 -4
  49. package/dist/lib/capacity/route.d.ts +10 -0
  50. package/dist/lib/capacity/route.js +16 -0
  51. package/dist/lib/daemon/install.d.ts +15 -0
  52. package/dist/lib/daemon/install.js +31 -0
  53. package/dist/lib/daemon/migrate.js +29 -4
  54. package/dist/lib/daemon/run.d.ts +1 -0
  55. package/dist/lib/daemon/run.js +6 -1
  56. package/dist/lib/daemon/supervisor.d.ts +1 -0
  57. package/dist/lib/daemon/supervisor.js +5 -3
  58. package/dist/lib/doctor/__testing__/run-doctor.js +4 -0
  59. package/dist/lib/doctor/checks/jq.d.ts +27 -0
  60. package/dist/lib/doctor/checks/jq.js +82 -0
  61. package/dist/lib/doctor/registry.js +4 -0
  62. package/dist/lib/flag-snapshot-file.js +36 -8
  63. package/dist/lib/install/codex-targets.d.ts +52 -1
  64. package/dist/lib/install/codex-targets.js +77 -2
  65. package/dist/lib/lanes/monitor.d.ts +4 -1
  66. package/dist/lib/lanes/monitor.js +47 -10
  67. package/dist/lib/lanes/spawn.js +8 -1
  68. package/dist/lib/lanes/watch.js +31 -0
  69. package/dist/lib/onboarding/checkpoint.d.ts +6 -0
  70. package/dist/lib/onboarding/checkpoint.js +6 -0
  71. package/dist/lib/onboarding/orchestrator.d.ts +3 -1
  72. package/dist/lib/onboarding/orchestrator.js +62 -9
  73. package/dist/lib/onboarding/types.d.ts +8 -0
  74. package/dist/lib/work-context/organize.d.ts +23 -1
  75. package/dist/lib/work-context/organize.js +25 -3
  76. package/dist/lib/work-context/reconcile.js +3 -2
  77. package/dist/secrets-env-action.js +7 -5
  78. package/dist/startup-registration.js +7 -2
  79. package/dist/utils/billing-gate.d.ts +12 -16
  80. package/dist/utils/billing-gate.js +17 -18
  81. package/dist/utils/install-tree-torn.d.ts +22 -4
  82. package/dist/utils/install-tree-torn.js +24 -0
  83. package/dist/utils/registration-plan-error.d.ts +22 -0
  84. package/dist/utils/registration-plan-error.js +27 -0
  85. package/dist/utils/sentry-fingerprint.js +3 -0
  86. package/dist/utils/unauthorized-error.d.ts +36 -0
  87. package/dist/utils/unauthorized-error.js +105 -0
  88. package/dist/utils/vault-api.js +7 -5
  89. package/package.json +7 -7
  90. package/scripts/install-hook-engine.mjs +17 -0
@@ -100,6 +100,80 @@ export function isAdapterEntry(entry, hqRoot) {
100
100
  cmd.includes(JSON.stringify(shimPath(hqRoot))) ||
101
101
  cmd.includes(JSON.stringify(path.join(hqRoot, 'core', 'packages', 'hq-anywhere', 'hooks', 'codex.sh')))));
102
102
  }
103
+ /**
104
+ * Where Codex hook runs claim an event, under `$HOME` (feedback_bf4df70e,
105
+ * feedback_d69d01c0). Shared with the hq-core Codex hook adapter
106
+ * (`.codex/hooks/hq-codex-hook-adapter.sh`), which claims the same way, so the
107
+ * two must agree on this directory, the key and the window.
108
+ */
109
+ export const CODEX_HOOK_CLAIM_DIR = '.hq/state/codex-hook-claims';
110
+ /** A claim younger than this many seconds makes a second run of the same event a no-op. */
111
+ export const CODEX_HOOK_CLAIM_WINDOW_SECONDS = 10;
112
+ /** Claim markers older than this many minutes are pruned on every successful claim. */
113
+ export const CODEX_HOOK_CLAIM_PRUNE_MINUTES = 2;
114
+ /** Set on the hook a wrapper claimed for, so the adapter it runs does not claim again. */
115
+ export const CODEX_HOOK_CLAIM_ENV = 'HQ_CODEX_HOOK_CLAIM';
116
+ /** The file a user-scope entry runs: the adapter, the hqd shim, or the native engine. */
117
+ function codexHookTargetPath(hqRoot, target) {
118
+ if (target === 'shim')
119
+ return shimPath(hqRoot);
120
+ if (typeof target === 'object')
121
+ return target.engine;
122
+ return codexAdapterPath(hqRoot);
123
+ }
124
+ /**
125
+ * Wrap a user-scope (~/.codex/hooks.json) command so one Codex event runs the
126
+ * HQ hooks once (feedback_bf4df70e, feedback_d69d01c0).
127
+ *
128
+ * Inside an HQ root, Codex runs this entry and the root's own
129
+ * `.codex/config.toml` hook for the same event, at the same time, with no
130
+ * dedupe. Predicting from a shell whether Codex will load and trust the project
131
+ * hook proved unreliable (project-root rules, per-hook trust by hash, path
132
+ * spellings), so both registrations stay and the second run of an event is a
133
+ * no-op at runtime instead. Each run claims the event once:
134
+ *
135
+ * - The key is `cksum` of the real HQ root, the Codex process (`$PPID`) and
136
+ * the exact stdin payload. Codex sends both hooks of one event the same
137
+ * payload from the same process; different events differ in their payload
138
+ * (event name, tool call, turn), and other Codex sessions differ in `$PPID`.
139
+ * - The claim is an atomic `mkdir` of `$HOME/.hq/state/codex-hook-claims/<key>`
140
+ * holding the claim time. The first run to create it does the full work. A
141
+ * run that finds a claim younger than {@link CODEX_HOOK_CLAIM_WINDOW_SECONDS}
142
+ * exits 0 with no output; an older claim is taken over, so two identical
143
+ * events further apart both run. Markers older than
144
+ * {@link CODEX_HOOK_CLAIM_PRUNE_MINUTES} minutes are pruned.
145
+ * - The claiming run passes {@link CODEX_HOOK_CLAIM_ENV} to the command it
146
+ * runs, so the HQ adapter does not claim a second time.
147
+ * - When anything needed is missing (`HOME`, the HQ root, the target file, a
148
+ * writable claim directory, `cksum`), the entry runs without claiming. Any
149
+ * failure therefore leads to the hook running twice, never to no hook.
150
+ *
151
+ * Until the hq-core adapter claims too, the project hook never claims, this
152
+ * entry always wins, and both still run, as before. `commandWindows` is not
153
+ * wrapped, so Windows keeps running both.
154
+ */
155
+ export function codexUserHookClaimed(hqRoot, target, command) {
156
+ const root = quotePosix(hqRoot);
157
+ const file = quotePosix(codexHookTargetPath(hqRoot, target));
158
+ return (`p=$(cat); c=; d=\${HOME:+$HOME/${CODEX_HOOK_CLAIM_DIR}}; r=$(cd ${root} 2>/dev/null && pwd -P); ` +
159
+ `if [ -n "$d" ] && [ -n "$r" ] && [ -f ${file} ] && mkdir -p "$d" 2>/dev/null; then ` +
160
+ `k=$({ printf '%s\\n%s\\n' "$r" "$PPID"; printf '%s' "$p"; } | cksum 2>/dev/null); set -- $k; ` +
161
+ `if [ -n "$2" ] && n=$(date +%s 2>/dev/null) && case "$n" in ''|*[!0-9]*) false ;; esac; then c="$1-$2"; ` +
162
+ `if mkdir "$d/$c" 2>/dev/null; then printf '%s\\n' "$n" > "$d/$c/t"; ` +
163
+ `else t=$(cat "$d/$c/t" 2>/dev/null); case "$t" in '') t=$n ;; *[!0-9]*) t=0 ;; esac; ` +
164
+ `if [ $((n - t)) -lt ${CODEX_HOOK_CLAIM_WINDOW_SECONDS} ]; then exit 0; fi; ` +
165
+ `rm -rf "$d/$c"; if mkdir "$d/$c" 2>/dev/null; then printf '%s\\n' "$n" > "$d/$c/t"; else exit 0; fi; fi; ` +
166
+ `find "$d" -mindepth 1 -maxdepth 1 -mmin +${CODEX_HOOK_CLAIM_PRUNE_MINUTES} -exec rm -rf {} + 2>/dev/null; fi; fi; ` +
167
+ `printf '%s\\n' "$p" | ${CODEX_HOOK_CLAIM_ENV}="$c" ${command}`);
168
+ }
169
+ /**
170
+ * The user-scope hooks.json entry: {@link codexHookEntry} behind
171
+ * {@link codexUserHookClaimed}. `commandWindows` is unchanged.
172
+ */
173
+ export function codexUserHookEntry(hqRoot, event, target = 'master') {
174
+ const entry = codexHookEntry(hqRoot, event, target);
175
+ return { ...entry, command: codexUserHookClaimed(hqRoot, target, entry.command) };
176
+ }
103
177
  /** The HQ hooks.json entry for one event and target. */
104
178
  export function codexHookEntry(hqRoot, event, target = 'master') {
105
179
  const timeout = event === 'SessionEnd' ? 3 : 300;
@@ -110,13 +184,14 @@ export function codexHookEntry(hqRoot, event, target = 'master') {
110
184
  }
111
185
  /**
112
186
  * Add one HQ hook group per event; idempotent. An HQ entry for the other
113
- * target (adapter vs the hqd shim) is swapped out. Foreign hooks are untouched.
187
+ * target (adapter vs the hqd shim) is swapped out, and so is an HQ entry
188
+ * written before the user-scope guard existed. Foreign hooks are untouched.
114
189
  */
115
190
  export function addCodexHooks(doc, hqRoot, target = 'master') {
116
191
  const hooks = { ...(doc.hooks ?? {}) };
117
192
  let changed = false;
118
193
  for (const event of CODEX_HOOK_EVENTS) {
119
- const want = codexHookEntry(hqRoot, event, target);
194
+ const want = codexUserHookEntry(hqRoot, event, target);
120
195
  let groups = Array.isArray(hooks[event]) ? [...hooks[event]] : [];
121
196
  const present = groups.some((g) => Array.isArray(g?.hooks) && g.hooks.some((h) => h.command === want.command && h.commandWindows === ('commandWindows' in want ? want.commandWindows : undefined)));
122
197
  if (present)
@@ -38,7 +38,10 @@ export interface LiveMonitorEvidenceOptions {
38
38
  * torn final write cannot turn into positive liveness evidence.
39
39
  */
40
40
  export declare function parseMonitorTranscript(text: string): MonitorTaskEvidence[];
41
- /** Return argv only for the exact command form the gate arms. */
41
+ /**
42
+ * Return argv only for the exact command form the gate arms:
43
+ * `[HQ_ROOT=<path>] hq {lanes|runners} watch <lane-id>...`.
44
+ */
42
45
  export declare function parseCanonicalWatchCommand(command: string): string[] | null;
43
46
  /**
44
47
  * A Monitor covers its lanes only inside the 30-minute cap. `persistent` is
@@ -187,19 +187,55 @@ export function parseMonitorTranscript(text) {
187
187
  outputPath: item.outputPath,
188
188
  }));
189
189
  }
190
- /** Return argv only for the exact command form the gate arms. */
191
- export function parseCanonicalWatchCommand(command) {
192
- const tokens = command.trim().split(/\s+/u);
190
+ // One optional leading `HQ_ROOT=<path>` assignment. `hq lanes watch` reads
191
+ // $HQ_ROOT first, and a senior whose cwd is a repo outside the HQ tree has no
192
+ // other way to point the watch at the HQ root (feedback_b6b59676). The value
193
+ // is a bare word or a single- or double-quoted string; nothing else is
194
+ // accepted before the hq executable.
195
+ //
196
+ // The value may hold only path characters: letters, digits, `/ . _ - ~`, and
197
+ // spaces inside quotes. Anything the shell would act on (`$(...)`, `$VAR`,
198
+ // backticks, `\`, `;`, `|`, `&`, `<`, `>`, `#`) is rejected in every form, so
199
+ // a prefix can never redirect the watch's output, end the command before the
200
+ // watch, or run something else instead (review of hq-cli #2544).
201
+ // The hyphen is escaped so appending a space to the class can never form a range.
202
+ const HQ_ROOT_PATH_CHARS = "A-Za-z0-9/._~\\-";
203
+ const HQ_ROOT_ASSIGNMENT_PREFIX = new RegExp(`^HQ_ROOT=(?:'[${HQ_ROOT_PATH_CHARS} ]+'|"[${HQ_ROOT_PATH_CHARS} ]+"|[${HQ_ROOT_PATH_CHARS}]+)[ \\t]+`, "u");
204
+ /** The hq executable: a bare `hq` or a path to it, in path characters only. */
205
+ const HQ_EXECUTABLE_TOKEN = new RegExp(`^[${HQ_ROOT_PATH_CHARS}]+$`, "u");
206
+ function parseWatchCommand(command) {
207
+ // A shell splits words only on space, tab and newline. Unicode and control
208
+ // whitespace (NBSP, VT, FF, CR, ...) stays inside a word there, and a newline
209
+ // ends the command. So the gate accepts only printable ASCII and tab between
210
+ // the leading and trailing blanks, and splits on spaces and tabs alone
211
+ // (review of hq-cli #2544).
212
+ const trimmed = command.replace(/^[ \t\n]+|[ \t\n]+$/gu, "");
213
+ if (!/^[\x20-\x7e\t]*$/u.test(trimmed))
214
+ return null;
215
+ const body = trimmed.replace(HQ_ROOT_ASSIGNMENT_PREFIX, "");
216
+ const tokens = body.split(/[ \t]+/u);
193
217
  if (tokens.length < 4)
194
218
  return null;
219
+ // A prefix the assignment pattern refused stays in front of the executable;
220
+ // this keeps a token such as `HQ_ROOT=/x>/tmp/hq` from passing as `hq`.
221
+ if (!HQ_EXECUTABLE_TOKEN.test(tokens[0]))
222
+ return null;
195
223
  const executable = path.basename(tokens[0]);
196
- if (executable !== "hq" || (tokens[1] !== "runners" && tokens[1] !== "lanes") || tokens[2] !== "watch") {
224
+ const group = tokens[1];
225
+ if (executable !== "hq" || (group !== "runners" && group !== "lanes") || tokens[2] !== "watch") {
197
226
  return null;
198
227
  }
199
228
  const laneIds = tokens.slice(3);
200
229
  if (laneIds.some((laneId) => !LANE_ID_PATTERN.test(laneId)))
201
230
  return null;
202
- return laneIds;
231
+ return { group, laneIds };
232
+ }
233
+ /**
234
+ * Return argv only for the exact command form the gate arms:
235
+ * `[HQ_ROOT=<path>] hq {lanes|runners} watch <lane-id>...`.
236
+ */
237
+ export function parseCanonicalWatchCommand(command) {
238
+ return parseWatchCommand(command)?.laneIds ?? null;
203
239
  }
204
240
  function taskOutputIsTerminal(outputText) {
205
241
  return outputText ? TERMINAL_TASK_OUTPUT.test(outputText) : false;
@@ -423,13 +459,13 @@ function isHqInvocationPrefix(prefix) {
423
459
  isHqExecutablePath(prefix.slice(runtimeEnd + 1)));
424
460
  }
425
461
  function processHasExactCommand(processCommands, command) {
426
- const laneIds = parseCanonicalWatchCommand(command);
427
- if (!laneIds)
462
+ const parsed = parseWatchCommand(command);
463
+ if (!parsed)
428
464
  return false;
429
465
  // Match the group name the Monitor used: `hq runners watch` or the
430
- // `hq lanes watch` alias produce different process lines.
431
- const groupToken = command.trim().split(/\s+/u)[1];
432
- const expectedSuffix = ` ${groupToken} watch ${laneIds.join(" ")}`;
466
+ // `hq lanes watch` alias produce different process lines. A leading
467
+ // HQ_ROOT= assignment is environment, not argv, so it never shows in ps.
468
+ const expectedSuffix = ` ${parsed.group} watch ${parsed.laneIds.join(" ")}`;
433
469
  return processCommands.some((rawLine) => {
434
470
  const line = rawLine.trim().replace(/\s+/gu, " ");
435
471
  if (!line.endsWith(expectedSuffix))
@@ -489,6 +525,7 @@ export function monitorReminderText() {
489
525
  return [
490
526
  "For active Claude senior lanes, arm one live Claude Code Monitor task per uncovered lane:",
491
527
  'Monitor(command="hq lanes watch <lane-id>...", timeout_ms=1800000)',
528
+ "When the session's cwd is outside the HQ tree, prefix the command with HQ_ROOT=<hq root> (for example HQ_ROOT=/path/to/hq hq lanes watch <lane-id>...); the gate counts that form too.",
492
529
  "Claude Code stops every Monitor after 30 minutes, so a lane stays covered only while a Monitor armed in the last 30 minutes watches it. Re-arm the same call when `hq lanes monitor-check --session <id>` reports the lane as expired.",
493
530
  "The caller must pass `--engine codex` or `--engine grok` (or set HQ_LANE_ENGINE; deprecated alias HQ_CONDUCT_ENGINE) for sessions whose engine has no Claude Monitor tool; those engines are never required to provide one.",
494
531
  ].join("\n");
@@ -1358,7 +1358,14 @@ export const STANDING_AUTHORIZATION = "STANDING AUTHORIZATION. This brief author
1358
1358
  export const FOREGROUND_ONLY_RULE = "FOREGROUND ONLY. Run every command, test suite and check in the foreground and wait for it to finish. " +
1359
1359
  "Never background a process and end the turn while it is still running. " +
1360
1360
  "A turn that ends before the envelope is written is classified interrupted, " +
1361
- "and whatever the background process produces afterwards is not read.";
1361
+ "and whatever the background process produces afterwards is not read. " +
1362
+ // feedback_86552798: an /execute-task lane ended its turn while the
1363
+ // builder subagent it had started kept editing; the run left no envelope.
1364
+ "The same holds for a subagent or nested run you start (for example the builder an /execute-task phase spawns): " +
1365
+ "wait for it to finish before you write the envelope. " +
1366
+ "A Monitor or other wait tool stops after at most 30 minutes, so wait in windows shorter than that, " +
1367
+ "start the next wait when one ends, and print one line per window saying what is still running and for how long. " +
1368
+ "If a nested run cannot finish in this turn, stop it and write a blocked envelope that names it.";
1362
1369
  /**
1363
1370
  * Temp-home rule carried in every composed brief, for every provider. Lanes
1364
1371
  * that ran tests under a raw mktemp HOME re-downloaded the Rust toolchain and
@@ -110,6 +110,35 @@ export async function runLaneWatch(hqRoot, laneIds, deps = {}) {
110
110
  suppressed = true;
111
111
  }
112
112
  };
113
+ // feedback_86552798: a running lane whose worker waits on a long nested run
114
+ // printed nothing here between its start and its end, so a senior's Monitor
115
+ // on this watch saw silence for as long as the run took (and a Monitor ends
116
+ // after 30 minutes). Report the watcher's stall flag when it is set or
117
+ // cleared, and each progress event the watcher records, so a long run reads
118
+ // as progress or as a plain stall.
119
+ const previousStall = new Map();
120
+ const previousProgress = new Map();
121
+ const emitRunningActivity = (record) => {
122
+ const stallKey = record.stalled === true ? `stalled:${record.stalled_at ?? ""}` : "ok";
123
+ const priorStall = previousStall.get(record.lane_id);
124
+ if (priorStall !== stallKey) {
125
+ if (stallKey !== "ok") {
126
+ const since = record.stalled_at ? ` since ${record.stalled_at}` : "";
127
+ const reason = record.stalled_reason ? ` (${record.stalled_reason})` : "";
128
+ emit(`lane ${record.lane_id}: stalled${since}${reason}; still running, no envelope yet`);
129
+ }
130
+ else if (priorStall !== undefined) {
131
+ emit(`lane ${record.lane_id}: progressing again`);
132
+ }
133
+ previousStall.set(record.lane_id, stallKey);
134
+ }
135
+ const progressAt = record.last_progress_event_at ?? "";
136
+ const priorProgress = previousProgress.get(record.lane_id);
137
+ if (priorProgress !== undefined && progressAt !== "" && progressAt !== priorProgress) {
138
+ emit(`lane ${record.lane_id}: progress at ${progressAt}`);
139
+ }
140
+ previousProgress.set(record.lane_id, progressAt);
141
+ };
113
142
  const unreadable = (kind, id, err) => {
114
143
  const message = `${kind} ${id}: unreadable record (${readableError(err)})`;
115
144
  writeError(`lane watch: ${message}`);
@@ -158,6 +187,8 @@ export async function runLaneWatch(hqRoot, laneIds, deps = {}) {
158
187
  emit(`lane ${record.lane_id}: state=${record.state}${terminal ? " (terminal)" : ""}`);
159
188
  previousStates.set(laneId, stateKey);
160
189
  }
190
+ if (!terminal)
191
+ emitRunningActivity(record);
161
192
  }
162
193
  const keepAliveWaiting = new Set();
163
194
  if (deps.keepAliveEnabled !== undefined) {
@@ -5,6 +5,12 @@
5
5
  * If a flow fails partway, re-running picks up from the last checkpoint.
6
6
  */
7
7
  import type { OnboardingCheckpoint, OnboardingStep } from "./types.js";
8
+ /**
9
+ * Checkpoint format version. 2: a join's invite token is saved only together
10
+ * with `inviteTokenPersonUid`, so an unbound token in a version-2 checkpoint is
11
+ * never the caller's. A checkpoint with no `version` predates that rule.
12
+ */
13
+ export declare const CHECKPOINT_VERSION = 2;
8
14
  export declare function getCheckpointPath(hqRoot: string): string;
9
15
  export declare function readCheckpoint(hqRoot: string): Promise<OnboardingCheckpoint | null>;
10
16
  export declare function writeCheckpoint(hqRoot: string, checkpoint: OnboardingCheckpoint): Promise<void>;
@@ -7,6 +7,12 @@
7
7
  import { readFile, writeFile, mkdir } from "node:fs/promises";
8
8
  import { join, dirname } from "node:path";
9
9
  const CHECKPOINT_FILE = "onboarding-state.json";
10
+ /**
11
+ * Checkpoint format version. 2: a join's invite token is saved only together
12
+ * with `inviteTokenPersonUid`, so an unbound token in a version-2 checkpoint is
13
+ * never the caller's. A checkpoint with no `version` predates that rule.
14
+ */
15
+ export const CHECKPOINT_VERSION = 2;
10
16
  export function getCheckpointPath(hqRoot) {
11
17
  return join(hqRoot, ".hq", CHECKPOINT_FILE);
12
18
  }
@@ -35,7 +35,9 @@ export declare function createCompanyFlow(input: CreateCompanyInput, config: Onb
35
35
  * 5. First sync to pull initial vault contents
36
36
  * 6. Write .hq/config.json
37
37
  */
38
- export declare function joinCompanyFlow(input: JoinCompanyInput, config: OnboardingConfig, onProgress?: ProgressCallback): Promise<OnboardingResult>;
38
+ export declare function joinCompanyFlow(input: JoinCompanyInput, config: OnboardingConfig, onProgress?: ProgressCallback, { resumed }?: {
39
+ resumed?: boolean;
40
+ }): Promise<OnboardingResult>;
39
41
  /**
40
42
  * Resume an interrupted onboarding flow from checkpoint.
41
43
  */
@@ -15,7 +15,7 @@ import { writeFile, mkdir } from "node:fs/promises";
15
15
  import { join, dirname } from "node:path";
16
16
  import { VaultClient, VaultConflictError, VaultNotFoundError, resolveEntityContext, sync, parseToken, } from "@indigoai-us/hq-cloud";
17
17
  import { PersonCreationError, CompanyCreationError, ProvisioningError, MembershipBootstrapError, StsVerifyError, InviteAcceptError, FirstSyncError, } from "./errors.js";
18
- import { readCheckpoint, writeCheckpoint, isStepComplete, deleteCheckpoint, } from "./checkpoint.js";
18
+ import { readCheckpoint, writeCheckpoint, isStepComplete, deleteCheckpoint, CHECKPOINT_VERSION, } from "./checkpoint.js";
19
19
  // ---------------------------------------------------------------------------
20
20
  // Public API
21
21
  // ---------------------------------------------------------------------------
@@ -271,17 +271,58 @@ export async function createCompanyFlow(input, config, onProgress) {
271
271
  * 5. First sync to pull initial vault contents
272
272
  * 6. Write .hq/config.json
273
273
  */
274
- export async function joinCompanyFlow(input, config, onProgress) {
274
+ export async function joinCompanyFlow(input, config, onProgress, { resumed = false } = {}) {
275
275
  const client = new VaultClient(config.vaultConfig);
276
276
  const checkpoint = await readCheckpoint(config.hqRoot) ?? makeCheckpoint("join-company");
277
- // Step 1: Parse token
277
+ // Read before any write below stamps the current version on the checkpoint.
278
+ const legacyCheckpoint = (checkpoint.version ?? 1) < CHECKPOINT_VERSION;
279
+ // Step 1: Parse token. The token is not written to the checkpoint here: it is
280
+ // saved only together with the person it belongs to, after the person step.
281
+ // A run interrupted before that leaves the previous token and its binding as
282
+ // they were, so a later resume never finds this run's token unbound
283
+ // (review of hq-cli #2545).
278
284
  emit(onProgress, "parse-token", "running");
279
285
  const token = parseToken(input.inviteToken);
280
- checkpoint.inviteToken = token;
281
- await writeCheckpoint(config.hqRoot, checkpoint);
282
286
  emit(onProgress, "parse-token", "done");
283
287
  // Step 2: Create person (same caller-owned resolution as createCompanyFlow)
284
- await runPersonStep(client, checkpoint, input, config, onProgress);
288
+ const person = await runPersonStep(client, checkpoint, input, config, onProgress);
289
+ // Resume reads the invite token from the checkpoint, and the checkpoint may
290
+ // have been left by another sign-in on this machine. Accepting that token
291
+ // under the caller would give the caller an invite meant for someone else
292
+ // (review of hq-cli #2516, minor 1; feedback_a169f6dc). Resume only uses a
293
+ // token saved for the caller's own person; any other token is dropped and the
294
+ // caller is asked to run `hq onboard join` with their own invite. Only a
295
+ // checkpoint written before tokens were bound (no `version`) may hold an
296
+ // unbound token; it counts as the caller's only when its saved person is one
297
+ // the caller owns. An unbound token in a current checkpoint is never used.
298
+ if (resumed && !isStepComplete(checkpoint, "accept-invite")) {
299
+ // The person step drops the saved token when it replaces the saved person,
300
+ // so a token that is gone from the checkpoint is never used either.
301
+ const bound = Boolean(checkpoint.inviteToken) &&
302
+ checkpoint.inviteToken === token &&
303
+ (checkpoint.inviteTokenPersonUid
304
+ ? checkpoint.inviteTokenPersonUid === checkpoint.personUid
305
+ : legacyCheckpoint && person === "kept" && Boolean(checkpoint.personUid));
306
+ if (!bound) {
307
+ delete checkpoint.inviteToken;
308
+ delete checkpoint.inviteTokenPersonUid;
309
+ checkpoint.failedStep = "accept-invite";
310
+ checkpoint.error = "saved invite token was not saved under this sign-in";
311
+ await writeCheckpoint(config.hqRoot, checkpoint);
312
+ emit(onProgress, "accept-invite", "failed");
313
+ throw new InviteAcceptError("The invite saved on this machine was not started under your sign-in, so resume will not accept it for you. " +
314
+ "If the invite is yours, run `hq onboard join <token>` with it.");
315
+ }
316
+ }
317
+ // Save the token with the person it belongs to, in one write.
318
+ if (checkpoint.inviteToken !== token ||
319
+ checkpoint.inviteTokenPersonUid !== checkpoint.personUid ||
320
+ checkpoint.version !== CHECKPOINT_VERSION) {
321
+ checkpoint.inviteToken = token;
322
+ checkpoint.inviteTokenPersonUid = checkpoint.personUid;
323
+ checkpoint.version = CHECKPOINT_VERSION;
324
+ await writeCheckpoint(config.hqRoot, checkpoint);
325
+ }
285
326
  // Step 3: Accept invite
286
327
  if (!isStepComplete(checkpoint, "accept-invite")) {
287
328
  emit(onProgress, "accept-invite", "running");
@@ -443,7 +484,7 @@ export async function resumeOnboarding(config, onProgress) {
443
484
  personEmail: "",
444
485
  inviteToken: checkpoint.inviteToken ?? "",
445
486
  };
446
- return joinCompanyFlow(input, config, onProgress);
487
+ return joinCompanyFlow(input, config, onProgress, { resumed: true });
447
488
  }
448
489
  }
449
490
  /**
@@ -465,6 +506,7 @@ function makeCheckpoint(mode) {
465
506
  const now = new Date().toISOString();
466
507
  return {
467
508
  mode,
509
+ version: CHECKPOINT_VERSION,
468
510
  startedAt: now,
469
511
  updatedAt: now,
470
512
  completedSteps: [],
@@ -558,6 +600,10 @@ async function resolveCallerPerson(client, checkpoint, input) {
558
600
  * membership state is dropped with it. When the caller owns a person it is
559
601
  * used; when the caller owns none yet, create-person is dropped too and runs
560
602
  * again to create the caller's own person.
603
+ *
604
+ * Returns how it settled: `kept` the saved person the caller owns, `relinked`
605
+ * away from a saved person another sign-in owns, or `resolved` a person for a
606
+ * run that had none saved.
561
607
  */
562
608
  async function runPersonStep(client, checkpoint, input, config, onProgress) {
563
609
  let previous;
@@ -566,17 +612,23 @@ async function runPersonStep(client, checkpoint, input, config, onProgress) {
566
612
  const stale = owned !== null && !owned.some((p) => p.uid === checkpoint.personUid);
567
613
  if (!stale) {
568
614
  emit(onProgress, "create-person", "skipped", "Already complete");
569
- return;
615
+ return "kept";
570
616
  }
571
617
  previous = checkpoint.personUid;
572
618
  forgetMembershipState(checkpoint);
619
+ // A saved invite token belonged to the previous person. Drop it in the same
620
+ // write as the relink, so a run that stops before the join saves its own
621
+ // token cannot leave the old one for the new person's resume, even in a
622
+ // legacy checkpoint with no binding (review of hq-cli #2545).
623
+ delete checkpoint.inviteToken;
624
+ delete checkpoint.inviteTokenPersonUid;
573
625
  const relinked = pickOwnedPerson(owned, input.personEmail);
574
626
  if (relinked) {
575
627
  checkpoint.personUid = relinked.uid;
576
628
  await writeCheckpoint(config.hqRoot, checkpoint);
577
629
  emit(onProgress, "create-person", "done", `Using your sign-in's person record ${relinked.uid}; the saved record ${previous} belongs to another sign-in, ` +
578
630
  `so the company and membership steps run again under your sign-in`);
579
- return;
631
+ return "relinked";
580
632
  }
581
633
  // The caller owns no person yet: forget the other sign-in's person as well,
582
634
  // so the step below creates the caller's own.
@@ -593,6 +645,7 @@ async function runPersonStep(client, checkpoint, input, config, onProgress) {
593
645
  emit(onProgress, "create-person", "done", previous
594
646
  ? `${detail}; the saved record ${previous} belongs to another sign-in, so the company and membership steps run again under your sign-in`
595
647
  : detail);
648
+ return previous ? "relinked" : "resolved";
596
649
  }
597
650
  catch (err) {
598
651
  checkpoint.failedStep = "create-person";
@@ -44,6 +44,8 @@ export interface OnboardingResult {
44
44
  }
45
45
  export interface OnboardingCheckpoint {
46
46
  mode: "create-company" | "join-company";
47
+ /** Checkpoint format version (`CHECKPOINT_VERSION`); absent on checkpoints from older CLIs. */
48
+ version?: number;
47
49
  startedAt: string;
48
50
  updatedAt: string;
49
51
  personUid?: string;
@@ -54,6 +56,12 @@ export interface OnboardingCheckpoint {
54
56
  /** Role on the caller's membership row, recorded when the membership step finds or makes it. */
55
57
  role?: string;
56
58
  inviteToken?: string;
59
+ /**
60
+ * The person the invite token was saved for. Resume only accepts a token
61
+ * bound to the caller's own person, so it never accepts an invite another
62
+ * sign-in left on this machine.
63
+ */
64
+ inviteTokenPersonUid?: string;
57
65
  completedSteps: OnboardingStep[];
58
66
  failedStep?: OnboardingStep;
59
67
  error?: string;
@@ -74,11 +74,33 @@ export type PostOrganizeFn = (input: {
74
74
  expectedVersion: number;
75
75
  decisionExpiresAt?: string;
76
76
  }) => Promise<OrganizeReceipt>;
77
+ /**
78
+ * The projects a session's own context points at: its bound project, the
79
+ * project hint its folder or registry resolved, and the local project
80
+ * candidates. Only server candidates for these projects become bind options.
81
+ */
82
+ export interface DecisionScope {
83
+ projectIds: readonly string[];
84
+ }
85
+ export declare function sessionDecisionScope(fields: {
86
+ projectId?: string;
87
+ projectHint?: string;
88
+ projectCandidates?: ReadonlyArray<{
89
+ projectId: string;
90
+ }>;
91
+ }): DecisionScope;
77
92
  /**
78
93
  * Build a pending decision from server candidates. Soft evidence ranks on the
79
94
  * server; the CLI never auto-binds from this list.
95
+ *
96
+ * With a scope, only candidates for the session's own projects become
97
+ * `bind_existing` options. The server list is the company's most active
98
+ * projects and carries no repo or folder match, so without this filter a
99
+ * session with no project context was offered unrelated projects
100
+ * (feedback_f81b23c2). A session with an empty scope gets only
101
+ * "Create new project" and "Leave untracked".
80
102
  */
81
- export declare function decisionFromCandidates(sessionId: string, response: CandidatesResponse): SessionDecision;
103
+ export declare function decisionFromCandidates(sessionId: string, response: CandidatesResponse, scope?: DecisionScope): SessionDecision;
82
104
  /**
83
105
  * Evaluate work-signal threshold and, when crossed for the first time, attach
84
106
  * a one-time decision (optionally from server candidates). Never invents a
@@ -38,12 +38,34 @@ function stableOrganizeOperationId(sessionId, decision) {
38
38
  .slice(0, 32);
39
39
  return `op_${h}`;
40
40
  }
41
+ export function sessionDecisionScope(fields) {
42
+ const ids = new Set();
43
+ if (fields.projectId)
44
+ ids.add(fields.projectId);
45
+ if (fields.projectHint)
46
+ ids.add(fields.projectHint);
47
+ for (const c of fields.projectCandidates ?? []) {
48
+ if (c?.projectId)
49
+ ids.add(c.projectId);
50
+ }
51
+ return { projectIds: [...ids] };
52
+ }
41
53
  /**
42
54
  * Build a pending decision from server candidates. Soft evidence ranks on the
43
55
  * server; the CLI never auto-binds from this list.
56
+ *
57
+ * With a scope, only candidates for the session's own projects become
58
+ * `bind_existing` options. The server list is the company's most active
59
+ * projects and carries no repo or folder match, so without this filter a
60
+ * session with no project context was offered unrelated projects
61
+ * (feedback_f81b23c2). A session with an empty scope gets only
62
+ * "Create new project" and "Leave untracked".
44
63
  */
45
- export function decisionFromCandidates(sessionId, response) {
46
- const options = response.candidates.map((c) => ({
64
+ export function decisionFromCandidates(sessionId, response, scope) {
65
+ const inScope = scope
66
+ ? response.candidates.filter((c) => scope.projectIds.includes(c.projectId))
67
+ : response.candidates;
68
+ const options = inScope.map((c) => ({
47
69
  optionId: c.candidateId,
48
70
  label: c.taskId
49
71
  ? `${c.projectName} / ${c.title}`
@@ -183,7 +205,7 @@ export async function prepareOrganizeDecision(input) {
183
205
  sessionId: input.sessionId,
184
206
  companyUid: state.companyUid,
185
207
  });
186
- const decision = decisionFromCandidates(input.sessionId, response);
208
+ const decision = decisionFromCandidates(input.sessionId, response, sessionDecisionScope(state));
187
209
  const updatedAt = nowFn().toISOString();
188
210
  const next = mergeLocalSessionFields({
189
211
  ...state,
@@ -9,7 +9,7 @@ import { companyBindingChanged, isNonCloudCompanySlug, presenceLeaveFromState, r
9
9
  import { invalidateDefaultCompanyMemberships, } from "./config.js";
10
10
  import { WORK_CONTEXT_CONTRACT_VERSION, normalizeTaskId, } from "./contract.js";
11
11
  import { EXIT_INVALID_IDENTITY, EXIT_NOT_TRACKING, EXIT_OK, InvalidDecisionOriginError, NotTrackingError, } from "./errors.js";
12
- import { decisionFromCandidates, } from "./organize.js";
12
+ import { decisionFromCandidates, sessionDecisionScope, } from "./organize.js";
13
13
  import { refineProjectBinding } from "./bind-best.js";
14
14
  import { foreignSessionOwnsLane } from "./lane-bind.js";
15
15
  import { rebindNeedsProjectOnPrompt } from "./prompt-rebind.js";
@@ -693,7 +693,8 @@ export async function reconcileObservation(obs, deps) {
693
693
  sessionId,
694
694
  companyUid: resolvedCompany.uid,
695
695
  });
696
- decision = decisionFromCandidates(sessionId, candidates);
696
+ // Offer only the session's own projects (feedback_f81b23c2).
697
+ decision = decisionFromCandidates(sessionId, candidates, sessionDecisionScope({ projectId, projectHint, projectCandidates }));
697
698
  diagnostics.push(`askAfter prepared decisionId=${decision.decisionId} options=${decision.options.length}`);
698
699
  }
699
700
  catch (err) {
@@ -9,6 +9,7 @@ import { SECRET_NAME_PATTERN } from "./commands/_patterns.js";
9
9
  import { finishEnvExportsAndExit } from "./commands/secrets-env-exit.js";
10
10
  import { DELEGATED_MACHINE_SESSION_ENV, delegatedMachineSessionFilePath, loadDelegatedMachineSession, loadMachineCreds, } from "@indigoai-us/hq-cloud";
11
11
  import { AuthError, isAuthError } from "./utils/auth-error.js";
12
+ import { companyOutpostUnauthorizedMessage, unauthorizedServerCode } from "./utils/unauthorized-error.js";
12
13
  import { peekIdToken } from "./utils/id-token.js";
13
14
  import { wantsMachineCognitoTokens } from "./utils/machine-principal-state.js";
14
15
  import { getEntityUid, looksLikeCompanyUid, vaultApiFetch } from "./utils/vault-api.js";
@@ -305,7 +306,7 @@ export async function resolveCompanyOutpostSecretsCompany(token, outpost, scope)
305
306
  const body = (await res.json().catch(() => ({})));
306
307
  if (!res.ok) {
307
308
  if (res.status === 401)
308
- throw companyOutpostSessionRejected();
309
+ throw companyOutpostSessionRejected(outpost, body);
309
310
  const message = `Failed to resolve company '${ref}' for this Outpost: ${extractApiMessage(body, `HTTP ${res.status}`)}`;
310
311
  if (isUnavailableSecretLoadHttpStatus(res.status))
311
312
  throw new SecretLoadUnavailableError(message);
@@ -316,9 +317,10 @@ export async function resolveCompanyOutpostSecretsCompany(token, outpost, scope)
316
317
  }
317
318
  throw notBound();
318
319
  }
319
- function companyOutpostSessionRejected() {
320
- return new AuthError("HQ rejected this company Outpost session (HTTP 401). The job runner refreshes " +
321
- "HQ_MACHINE_SESSION_FILE; re-run the job, and if it persists check the Outpost's binding.");
320
+ // Same wording as every other company Outpost 401 (feedback_dfc0bb49), with
321
+ // the server's code and the Outpost uid from the token this read sent.
322
+ function companyOutpostSessionRejected(outpost, body) {
323
+ return new AuthError(companyOutpostUnauthorizedMessage({ kind: "company-outpost", entityUid: outpost.outpostUid }, unauthorizedServerCode(body)));
322
324
  }
323
325
  /**
324
326
  * The company uid a `secrets exec` / `env` / `get` call reads from. A company
@@ -414,7 +416,7 @@ async function loadRevealedSecretsForCompanyOutpost(token, outpost, companyUid,
414
416
  throw new Error(highSecuritySandboxOnlyMessage(name));
415
417
  }
416
418
  if (res.status === 401)
417
- throw companyOutpostSessionRejected();
419
+ throw companyOutpostSessionRejected(outpost, body);
418
420
  if (res.status === 404) {
419
421
  throw new Error(`Failed to fetch secret '${name}': Secret not found`);
420
422
  }
@@ -19,7 +19,7 @@
19
19
  import { spawnSync } from "node:child_process";
20
20
  import { stringDerivedPackageRoot } from "./utils/hq-roots.js";
21
21
  import { updateLockPath, UPDATE_LOCK_STALE_MS } from "./utils/update-lock.js";
22
- import { classifyEvalThrow, classifyModuleNotFound, installRewriteInProgress, InstallTreeTornError, waitForInstallTreeSettled, } from "./utils/install-tree-torn.js";
22
+ import { classifyEvalThrow, classifyMissingRegistrationPlan, classifyModuleNotFound, installRewriteInProgress, InstallTreeTornError, waitForInstallTreeSettled, } from "./utils/install-tree-torn.js";
23
23
  /**
24
24
  * Set on the re-exec'd child so it can NEVER wait or re-exec again — distinct
25
25
  * from self-update's HQ_RESCUE_SELF_UPDATED so the two recovery paths cannot
@@ -95,7 +95,12 @@ export async function registerCommandsWithRecovery(args) {
95
95
  // dialects (incl. HQ-CLI-1S resolve-enoent); classifyEvalThrow covers a
96
96
  // module-EVALUATION throw (HQ-CLI-1T). Anything unclassified is rethrown as the
97
97
  // SAME object to the existing boundary, preserving today's behaviour exactly.
98
- const classified = classifyModuleNotFound(err) ?? classifyEvalThrow(err, packageRoot);
98
+ // classifyMissingRegistrationPlan covers a startup catalog root that the
99
+ // lazily imported plan does not know (HQ-CLI-GM): the catalog and the plan
100
+ // came from different installs, so it takes the loader-race path (no gate).
101
+ const classified = classifyModuleNotFound(err) ??
102
+ classifyMissingRegistrationPlan(err) ??
103
+ classifyEvalThrow(err, packageRoot);
99
104
  if (!classified)
100
105
  throw err;
101
106
  const lockPath = (deps.lockPath ?? updateLockPath)();