@indigoai-us/hq-cli 5.345.212-beta.0 → 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 (59) hide show
  1. package/CHANGELOG.md +20 -1
  2. package/dist/command-registration-plan.d.ts +15 -0
  3. package/dist/command-registration-plan.js +20 -1
  4. package/dist/commands/agents.js +6 -1
  5. package/dist/commands/billing.js +17 -4
  6. package/dist/commands/daemon.js +57 -5
  7. package/dist/commands/files.js +2 -2
  8. package/dist/commands/integrations-api.d.ts +11 -0
  9. package/dist/commands/integrations-connect.d.ts +2 -0
  10. package/dist/commands/integrations-connect.js +17 -5
  11. package/dist/commands/integrations-core.d.ts +1 -1
  12. package/dist/commands/integrations-core.js +18 -10
  13. package/dist/commands/integrations.js +1 -1
  14. package/dist/commands/lanes.js +34 -16
  15. package/dist/lazy-commands.js +4 -1
  16. package/dist/lib/billing/usage-only.d.ts +4 -1
  17. package/dist/lib/billing/usage-only.js +7 -2
  18. package/dist/lib/capacity/ledger.d.ts +7 -0
  19. package/dist/lib/capacity/ledger.js +31 -1
  20. package/dist/lib/capacity/project.d.ts +1 -1
  21. package/dist/lib/capacity/project.js +13 -4
  22. package/dist/lib/capacity/route.d.ts +10 -0
  23. package/dist/lib/capacity/route.js +16 -0
  24. package/dist/lib/daemon/install.d.ts +15 -0
  25. package/dist/lib/daemon/install.js +31 -0
  26. package/dist/lib/daemon/migrate.js +29 -4
  27. package/dist/lib/doctor/__testing__/run-doctor.js +4 -0
  28. package/dist/lib/doctor/checks/jq.d.ts +27 -0
  29. package/dist/lib/doctor/checks/jq.js +82 -0
  30. package/dist/lib/doctor/registry.js +4 -0
  31. package/dist/lib/flag-snapshot-file.js +36 -8
  32. package/dist/lib/install/codex-targets.d.ts +52 -1
  33. package/dist/lib/install/codex-targets.js +77 -2
  34. package/dist/lib/lanes/monitor.d.ts +4 -1
  35. package/dist/lib/lanes/monitor.js +47 -10
  36. package/dist/lib/lanes/spawn.js +8 -1
  37. package/dist/lib/lanes/watch.js +31 -0
  38. package/dist/lib/onboarding/checkpoint.d.ts +6 -0
  39. package/dist/lib/onboarding/checkpoint.js +6 -0
  40. package/dist/lib/onboarding/orchestrator.d.ts +3 -1
  41. package/dist/lib/onboarding/orchestrator.js +62 -9
  42. package/dist/lib/onboarding/types.d.ts +8 -0
  43. package/dist/lib/work-context/organize.d.ts +23 -1
  44. package/dist/lib/work-context/organize.js +25 -3
  45. package/dist/lib/work-context/reconcile.js +3 -2
  46. package/dist/secrets-env-action.js +7 -5
  47. package/dist/startup-registration.js +7 -2
  48. package/dist/utils/billing-gate.d.ts +12 -16
  49. package/dist/utils/billing-gate.js +17 -18
  50. package/dist/utils/install-tree-torn.d.ts +22 -4
  51. package/dist/utils/install-tree-torn.js +24 -0
  52. package/dist/utils/registration-plan-error.d.ts +22 -0
  53. package/dist/utils/registration-plan-error.js +27 -0
  54. package/dist/utils/sentry-fingerprint.js +3 -0
  55. package/dist/utils/unauthorized-error.d.ts +36 -0
  56. package/dist/utils/unauthorized-error.js +105 -0
  57. package/dist/utils/vault-api.js +7 -5
  58. package/package.json +7 -7
  59. package/scripts/install-hook-engine.mjs +17 -0
@@ -331,9 +331,14 @@ export function usageOnlyPlanLine(card = BUNDLED_USAGE_CARD) {
331
331
  return (`Plan: usage pricing — ${formatCardUsd(card.includedUsd)} of usage included each month. ` +
332
332
  "See `hq billing usage`.");
333
333
  }
334
- /** Agent boxes on usage pricing, priced by size from the card. */
334
+ /**
335
+ * Agent boxes on usage pricing, priced by size from the card, plus the
336
+ * agent-run meter when the card lists one.
337
+ */
335
338
  export function usageOnlyBoxSentence(card = BUNDLED_USAGE_CARD) {
336
- return `Agent boxes on usage pricing are billed by size: ${formatBoxQuotes(card)}.`;
339
+ const run = card.meters.find((m) => m.id === "agent-run");
340
+ const perRun = run ? `, plus ${formatCardUsd(run.unitUsd)} per agent run` : "";
341
+ return `Agent boxes on usage pricing are billed by size: ${formatBoxQuotes(card)}${perRun}.`;
337
342
  }
338
343
  /**
339
344
  * A refusal that a legacy account answers by upgrading its plan. On usage
@@ -170,6 +170,11 @@ export interface NowAccount {
170
170
  * been able to refresh them since.
171
171
  */
172
172
  usageStale?: boolean;
173
+ /**
174
+ * Newest failure for this account that is not a sign-in problem (parse
175
+ * drift, HTTP error), absent once a later reading from the account lands.
176
+ */
177
+ lastError?: string;
173
178
  limits: NowLimit[];
174
179
  }
175
180
  export interface NowProvider {
@@ -402,4 +407,6 @@ export declare function readLedgerEvents(options?: LedgerOptions): LedgerEvent[]
402
407
  export declare function readCollectorMark(options?: LedgerOptions): CollectorMark | null;
403
408
  export declare function setCollectorEnabled(enabled: boolean, options?: LedgerOptions): CollectorMark;
404
409
  export declare function rebuildNow(options?: LedgerOptions): NowView;
410
+ /** Newest uncleared parse or HTTP error among these accounts. */
411
+ export declare function newestAccountError(accounts: readonly NowAccount[]): string | null;
405
412
  //# sourceMappingURL=ledger.d.ts.map
@@ -881,7 +881,10 @@ function materialize(events, ctx) {
881
881
  }
882
882
  if (failed)
883
883
  state = "unknown";
884
- if (limits.length === 0 && failed)
884
+ // No mapped limit is never "ok". A labelled account's parse drift or HTTP
885
+ // error is account-scoped, so `failed` misses it; without this the
886
+ // provider read "ok" with an empty table (feedback_601a961f).
887
+ if (limits.length === 0)
885
888
  state = "unknown";
886
889
  const unknownLimit = limits.find((limit) => limit.state === "unknown" && limit.lastError);
887
890
  const lastError = failed
@@ -894,6 +897,10 @@ function materialize(events, ctx) {
894
897
  }
895
898
  const unscopedFailure = bucket.failure !== null && bucket.failure.at >= bucket.latestReadingAt;
896
899
  attachAccounts(entry, events, unscopedFailure);
900
+ // With no limits, show the newest account error (parse drift, HTTP error)
901
+ // that no later reading from that account has cleared.
902
+ if (limits.length === 0 && entry.lastError === null)
903
+ entry.lastError = newestAccountError(entry.accounts ?? []);
897
904
  if (provider === "codex" && !failed && entry.accounts?.length) {
898
905
  for (const account of entry.accounts) {
899
906
  if (account.authState === "ok" && account.state === "exhausted"
@@ -972,6 +979,7 @@ function clusterAccounts(provider, events) {
972
979
  organization: cleanOrganization(event.organization),
973
980
  at,
974
981
  problem: problemFor(event.error),
982
+ failure: problemFor(event.error) ? null : event.error,
975
983
  });
976
984
  continue;
977
985
  }
@@ -985,6 +993,7 @@ function clusterAccounts(provider, events) {
985
993
  organization: cleanOrganization(reading.organization),
986
994
  at,
987
995
  problem: null,
996
+ failure: null,
988
997
  });
989
998
  }
990
999
  if (seeds.length === 0)
@@ -1035,6 +1044,8 @@ function clusterAccounts(provider, events) {
1035
1044
  let problem = null;
1036
1045
  let latestReadingAt = Number.NEGATIVE_INFINITY;
1037
1046
  let latestAt = Number.NEGATIVE_INFINITY;
1047
+ let latestDataAt = Number.NEGATIVE_INFINITY;
1048
+ let failure = null;
1038
1049
  for (const seed of members) {
1039
1050
  for (const label of seed.labels) {
1040
1051
  if (!labels.includes(label))
@@ -1051,7 +1062,13 @@ function clusterAccounts(provider, events) {
1051
1062
  latestReadingAt = seed.at;
1052
1063
  if (seed.at > latestAt)
1053
1064
  latestAt = seed.at;
1065
+ if (seed.failure !== null && (!failure || seed.at >= failure.at))
1066
+ failure = { error: seed.failure, at: seed.at };
1067
+ if (seed.problem === null && seed.failure === null && seed.at > latestDataAt)
1068
+ latestDataAt = seed.at;
1054
1069
  }
1070
+ // The account's newest parse or HTTP error, until a later reading clears it.
1071
+ const accountError = failure && failure.at >= latestDataAt ? failure.error : null;
1055
1072
  const ordered = orderLabels(labels);
1056
1073
  const primary = ordered.find((label) => label !== "default") ?? ordered[0] ?? "default";
1057
1074
  const limitedIds = ids.filter((id) => provider.limits.some((limit) => limit.accountId === id));
@@ -1099,12 +1116,25 @@ function clusterAccounts(provider, events) {
1099
1116
  : capacityLoginCommand(provider.provider, primary))
1100
1117
  : null,
1101
1118
  usageStale: usageStale ? true : undefined,
1119
+ lastError: accountError ?? undefined,
1102
1120
  limits,
1103
1121
  });
1104
1122
  }
1105
1123
  accounts.sort((a, b) => (a.labels[0] ?? "").localeCompare(b.labels[0] ?? ""));
1106
1124
  return accounts;
1107
1125
  }
1126
+ /** Newest uncleared parse or HTTP error among these accounts. */
1127
+ export function newestAccountError(accounts) {
1128
+ let best = null;
1129
+ for (const account of accounts) {
1130
+ if (!account.lastError)
1131
+ continue;
1132
+ const at = account.observedAt ?? "";
1133
+ if (!best || at > best.at)
1134
+ best = { error: account.lastError, at };
1135
+ }
1136
+ return best?.error ?? null;
1137
+ }
1108
1138
  function problemFor(error) {
1109
1139
  if (isExpiredReason(error))
1110
1140
  return { kind: "expired", reason: EXPIRED_REASON };
@@ -1,5 +1,5 @@
1
1
  import type { CapacityAccount } from "./accounts.js";
2
- import type { NowView } from "./ledger.js";
2
+ import { type NowView } from "./ledger.js";
3
3
  export interface ProjectCapacityOptions {
4
4
  accounts: readonly CapacityAccount[];
5
5
  /**
@@ -10,6 +10,7 @@
10
10
  */
11
11
  import * as fs from "node:fs";
12
12
  import * as path from "node:path";
13
+ import { newestAccountError } from "./ledger.js";
13
14
  const STATE_RANK = {
14
15
  ok: 0,
15
16
  "reset-pending": 1,
@@ -131,9 +132,8 @@ function recomputeFromAccounts(provider, accounts) {
131
132
  }
132
133
  let state = "ok";
133
134
  if (limits.length === 0) {
134
- state = accounts.some((account) => account.authState === "expired" || account.authState === "signed_out" || account.signedOut)
135
- ? "unknown"
136
- : "ok";
135
+ // No limit rows is never "ok", signed in or not (feedback_601a961f).
136
+ state = "unknown";
137
137
  }
138
138
  else {
139
139
  for (const limit of limits) {
@@ -141,12 +141,20 @@ function recomputeFromAccounts(provider, accounts) {
141
141
  state = limit.state;
142
142
  }
143
143
  }
144
+ // The ledger fills an empty provider's lastError from an account's error. Show
145
+ // such an error only when its account is still in this projection; an account
146
+ // whose home left the registry is hidden, and so is its error.
147
+ const fromAccount = provider.lastError !== null
148
+ && (provider.accounts ?? []).some((account) => account.lastError === provider.lastError);
149
+ const providerError = fromAccount ? null : provider.lastError;
144
150
  return {
145
151
  ...provider,
146
152
  accounts,
147
153
  limits,
148
154
  state,
149
- lastError: state === "unknown" ? accounts.find((account) => account.reason)?.reason ?? provider.lastError : null,
155
+ lastError: state === "unknown"
156
+ ? accounts.find((account) => account.reason)?.reason ?? newestAccountError(accounts) ?? providerError
157
+ : null,
150
158
  };
151
159
  }
152
160
  function withoutAccounts(provider) {
@@ -223,6 +231,7 @@ function mergeGroup(group, homes, labels, provider) {
223
231
  reason: problem?.reason ?? null,
224
232
  fixCommand: problem?.fixCommand ?? null,
225
233
  usageStale: usageStale ? true : undefined,
234
+ lastError: newestAccountError(group.map((piece) => piece.account)) ?? undefined,
226
235
  limits,
227
236
  };
228
237
  }
@@ -168,6 +168,16 @@ export interface StaleReadingTarget {
168
168
  * reading cannot help.
169
169
  */
170
170
  export declare function staleReadingTargets(result: RouteResult): StaleReadingTarget[];
171
+ /**
172
+ * True when a refusal rests on no usage reading at all: nothing was ranked,
173
+ * and every skipped lane account was skipped only because the ledger has no
174
+ * reading for it yet (feedback_9e444a9f, feedback_86552798). On a fresh
175
+ * ledger that is the normal state until the first reading lands, so it says
176
+ * nothing about room. A skip for a used-up, signed-out, usage-only or
177
+ * day-old account is evidence and keeps the refusal. Skips with no lane
178
+ * account (a sign-in no lane uses) do not count either way.
179
+ */
180
+ export declare function refusalHasNoReadings(result: RouteResult): boolean;
171
181
  export declare class RouteUsageError extends Error {
172
182
  readonly code = "route_usage";
173
183
  constructor(message: string);
@@ -153,6 +153,22 @@ export function staleReadingTargets(result) {
153
153
  }
154
154
  return targets;
155
155
  }
156
+ /**
157
+ * True when a refusal rests on no usage reading at all: nothing was ranked,
158
+ * and every skipped lane account was skipped only because the ledger has no
159
+ * reading for it yet (feedback_9e444a9f, feedback_86552798). On a fresh
160
+ * ledger that is the normal state until the first reading lands, so it says
161
+ * nothing about room. A skip for a used-up, signed-out, usage-only or
162
+ * day-old account is evidence and keeps the refusal. Skips with no lane
163
+ * account (a sign-in no lane uses) do not count either way.
164
+ */
165
+ export function refusalHasNoReadings(result) {
166
+ if (result.ok && result.pick)
167
+ return false;
168
+ if (result.ranked.length > 0)
169
+ return false;
170
+ return result.skipped.every((entry) => !entry.account || entry.reason === SKIP_NO_READING);
171
+ }
156
172
  export class RouteUsageError extends Error {
157
173
  code = "route_usage";
158
174
  constructor(message) {
@@ -262,6 +262,21 @@ export declare function startDaemonUnit(host: DaemonHost, deps: InstallDeps & {
262
262
  daemonPid: () => number | null;
263
263
  waitMs?: number;
264
264
  }): StartDaemonResult;
265
+ /** How long `hq daemon install` waits for a live daemon before taking over the older mesh unit. */
266
+ export declare const DAEMON_ALIVE_WAIT_MS = 10000;
267
+ /**
268
+ * Wait up to `maxMs` for a running daemon to hold the lock (the same lock
269
+ * check the Windows path uses). launchd and systemd report a unit as loaded
270
+ * even when the daemon exits at once and crash-loops, so "installed and
271
+ * started" alone cannot gate a takeover (feedback_c85ad51b review).
272
+ *
273
+ * A daemon started after `previous` counts once the same live record is seen
274
+ * on two polls in a row, so a process that takes the lock and dies at startup
275
+ * does not count. The daemon from before the install counts only if it is
276
+ * still alive at the end of the wait (the service manager kept the previous
277
+ * definition running). Returns the live record, or null when none appeared.
278
+ */
279
+ export declare function waitForLiveDaemon(runningDaemon: () => PidLockRecord | null, previous: PidLockRecord | null, sleep?: SleepFn, maxMs?: number): PidLockRecord | null;
265
280
  /**
266
281
  * PowerShell script that lists Windows sessions as `id|state|DOMAIN\user`
267
282
  * lines through WTSEnumerateSessions and WTSQuerySessionInformation. State is
@@ -835,6 +835,37 @@ function waitForNewDaemon(runningDaemon, previous, sleep) {
835
835
  sleep(WINDOWS_START_POLL_MS);
836
836
  }
837
837
  }
838
+ /** How long `hq daemon install` waits for a live daemon before taking over the older mesh unit. */
839
+ export const DAEMON_ALIVE_WAIT_MS = 10_000;
840
+ /**
841
+ * Wait up to `maxMs` for a running daemon to hold the lock (the same lock
842
+ * check the Windows path uses). launchd and systemd report a unit as loaded
843
+ * even when the daemon exits at once and crash-loops, so "installed and
844
+ * started" alone cannot gate a takeover (feedback_c85ad51b review).
845
+ *
846
+ * A daemon started after `previous` counts once the same live record is seen
847
+ * on two polls in a row, so a process that takes the lock and dies at startup
848
+ * does not count. The daemon from before the install counts only if it is
849
+ * still alive at the end of the wait (the service manager kept the previous
850
+ * definition running). Returns the live record, or null when none appeared.
851
+ */
852
+ export function waitForLiveDaemon(runningDaemon, previous, sleep = blockingSleep, maxMs = DAEMON_ALIVE_WAIT_MS) {
853
+ let seen = null;
854
+ for (let waited = 0;; waited += WINDOWS_START_POLL_MS) {
855
+ const now = runningDaemon();
856
+ if (now && isNewDaemon(now, previous)) {
857
+ if (seen && seen.pid === now.pid && seen.ts === now.ts)
858
+ return now;
859
+ seen = now;
860
+ }
861
+ else {
862
+ seen = null;
863
+ }
864
+ if (waited >= maxMs)
865
+ return now && previous && !isNewDaemon(now, previous) ? now : null;
866
+ sleep(WINDOWS_START_POLL_MS);
867
+ }
868
+ }
838
869
  /**
839
870
  * PowerShell script that lists Windows sessions as `id|state|DOMAIN\user`
840
871
  * lines through WTSEnumerateSessions and WTSQuerySessionInformation. State is
@@ -84,12 +84,19 @@ function moveFile(from, to) {
84
84
  fs.rmSync(from);
85
85
  }
86
86
  }
87
+ function isFile(p) {
88
+ try {
89
+ return fs.lstatSync(p).isFile();
90
+ }
91
+ catch {
92
+ return false;
93
+ }
94
+ }
87
95
  /** schtasks /Create /XML reads UTF-16LE with a BOM, the format /Query /XML declares. */
88
96
  function encodeTaskXml(xml) {
89
97
  return Buffer.from(`\uFEFF${xml.replace(/^\uFEFF/, "")}`, "utf16le");
90
98
  }
91
- function adoptOne(unit, deps) {
92
- const to = path.join(storeFor(unit.kind, deps).dir, savedName(unit));
99
+ function adoptOne(unit, deps, to) {
93
100
  switch (unit.kind) {
94
101
  case "launchd": {
95
102
  if (!unit.path)
@@ -154,16 +161,34 @@ export function adoptLegacyUnits(units, deps) {
154
161
  continue;
155
162
  }
156
163
  const store = storeFor(unit.kind, deps);
164
+ // A unit taken over before can come back (a manual `hq mesh daemon
165
+ // install`), and `hq daemon install` now takes it over again. Keep the
166
+ // first saved definition and its record entry: the new definition goes to
167
+ // a timestamped file next to it, so the saved copy is never overwritten
168
+ // and the record never lists the unit twice (feedback_c85ad51b review).
169
+ const sameUnit = (r) => r.kind === unit.kind && r.name === unit.name;
170
+ const prior = recordOf(store).find((r) => sameUnit(r) && !r.definitionMissing && fs.existsSync(r.movedTo));
171
+ const savedTo = path.join(store.dir, savedName(unit));
172
+ const to = prior ? `${savedTo}.${now()}` : savedTo;
157
173
  let adoptedFields;
158
174
  try {
159
- adoptedFields = adoptOne(unit, deps);
175
+ // A stray saved file with no record entry is kept too, renamed aside, so
176
+ // the canonical name (which a system-unit restore checks) stays free.
177
+ if (!prior && isFile(savedTo))
178
+ moveFile(savedTo, `${savedTo}.${now()}`);
179
+ adoptedFields = adoptOne(unit, deps, to);
160
180
  }
161
181
  catch (err) {
162
182
  result.failed.push({ unit, error: err.message });
163
183
  continue;
164
184
  }
185
+ if (prior) {
186
+ // Stopped and moved aside; the existing record still restores the first copy.
187
+ result.adopted.push(prior);
188
+ continue;
189
+ }
165
190
  const adopted = { ...unit, ...adoptedFields, adoptedAt: now() };
166
- const next = [...recordOf(store), adopted];
191
+ const next = [...recordOf(store).filter((r) => !sameUnit(r)), adopted];
167
192
  try {
168
193
  // Record each unit as soon as it is moved, so a failure later in the
169
194
  // list never loses track of one already taken over.
@@ -3,6 +3,7 @@ import * as os from "node:os";
3
3
  import * as path from "node:path";
4
4
  import { runDoctor as runDoctorCommand, } from "../../../commands/doctor.js";
5
5
  import { createAnywhereFamily } from "../checks/anywhere.js";
6
+ import { createJqFamily } from "../checks/jq.js";
6
7
  import { createTempHomesFamily } from "../checks/temp-homes.js";
7
8
  import { createDefaultRegistry } from "../registry.js";
8
9
  /**
@@ -49,6 +50,9 @@ export async function runDoctorForTest(options = {}) {
49
50
  // The temp-homes family walks the machine's real temp folders; scan
50
51
  // none here. Its behaviour is covered with fake trees in its own tests.
51
52
  registry.register(createTempHomesFamily({ roots: [] }));
53
+ // The jq family reads the machine's real PATH; stub a present jq so
54
+ // full-doctor tests do not depend on jq being installed here.
55
+ registry.register(createJqFamily({ platform: process.platform, findJq: () => "/usr/bin/jq", readVersion: () => "jq-1.8.2" }));
52
56
  }
53
57
  return await runDoctorCommand({ ...options, registry, integrations: false });
54
58
  }
@@ -0,0 +1,27 @@
1
+ import type { CheckContext, CheckFamily, CheckResult } from "../types.js";
2
+ export declare const JQ_FAMILY_ID = "jq";
3
+ export declare const JQ_CHECK_ID = "jq.on-path";
4
+ /**
5
+ * Windows install hint for a missing jq. hq-core-staging PR 1882 makes
6
+ * master-hook block every tool call without jq. The npm postinstall
7
+ * (scripts/install-hook-engine.mjs) prints the same line; a test keeps them equal.
8
+ */
9
+ export declare const JQ_WINDOWS_INSTALL_HINT = "Install jq (Windows: winget install jqlang.jq) and open a new terminal; HQ hooks block tool calls until jq is on PATH.";
10
+ /** Per-platform install guidance for a missing jq. */
11
+ export declare function jqInstallHint(platform: NodeJS.Platform): string;
12
+ export interface JqCheckDeps {
13
+ platform: NodeJS.Platform;
14
+ /** Absolute path of the first `jq` on PATH, or undefined when there is none. */
15
+ findJq: () => string | undefined;
16
+ /** `jq --version` output for the binary at `file`; throws when it cannot run. */
17
+ readVersion: (file: string) => string;
18
+ }
19
+ /**
20
+ * HQ's master-hook needs jq to parse every hook payload. Since hq-core-staging
21
+ * PR 1882 it blocks every PreToolUse call when jq is missing, and no installer
22
+ * puts jq on PATH on Windows. This check only reads: it never installs jq.
23
+ */
24
+ export declare function createJqFamily(deps?: JqCheckDeps): CheckFamily;
25
+ export declare const jqFamily: CheckFamily;
26
+ export declare function checkJq(_context: CheckContext, deps?: JqCheckDeps): CheckResult[];
27
+ //# sourceMappingURL=jq.d.ts.map
@@ -0,0 +1,82 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { findExecutableOnPath } from "../../../utils/resolve-executable.js";
3
+ export const JQ_FAMILY_ID = "jq";
4
+ export const JQ_CHECK_ID = "jq.on-path";
5
+ /**
6
+ * Windows install hint for a missing jq. hq-core-staging PR 1882 makes
7
+ * master-hook block every tool call without jq. The npm postinstall
8
+ * (scripts/install-hook-engine.mjs) prints the same line; a test keeps them equal.
9
+ */
10
+ export const JQ_WINDOWS_INSTALL_HINT = "Install jq (Windows: winget install jqlang.jq) and open a new terminal; HQ hooks block tool calls until jq is on PATH.";
11
+ /** Per-platform install guidance for a missing jq. */
12
+ export function jqInstallHint(platform) {
13
+ if (platform === "win32")
14
+ return JQ_WINDOWS_INSTALL_HINT;
15
+ if (platform === "darwin") {
16
+ return "Install jq (macOS: brew install jq) and open a new terminal; HQ hooks block tool calls until jq is on PATH.";
17
+ }
18
+ return "Install jq (Debian/Ubuntu: sudo apt-get install jq; Fedora: sudo dnf install jq) and open a new terminal; HQ hooks block tool calls until jq is on PATH.";
19
+ }
20
+ const defaultDeps = {
21
+ platform: process.platform,
22
+ // Git Bash runs the hooks: it can run jq.exe but not a jq.cmd or jq.bat.
23
+ findJq: () => findExecutableOnPath("jq", process.env.PATH ?? "", process.platform, ".EXE"),
24
+ readVersion: (file) => execFileSync(file, ["--version"], {
25
+ encoding: "utf8",
26
+ timeout: 5_000,
27
+ stdio: ["ignore", "pipe", "pipe"],
28
+ windowsHide: true,
29
+ }),
30
+ };
31
+ /**
32
+ * HQ's master-hook needs jq to parse every hook payload. Since hq-core-staging
33
+ * PR 1882 it blocks every PreToolUse call when jq is missing, and no installer
34
+ * puts jq on PATH on Windows. This check only reads: it never installs jq.
35
+ */
36
+ export function createJqFamily(deps = defaultDeps) {
37
+ return {
38
+ id: JQ_FAMILY_ID,
39
+ title: "jq for HQ hooks",
40
+ run: (context) => Promise.resolve(checkJq(context, deps)),
41
+ };
42
+ }
43
+ export const jqFamily = createJqFamily();
44
+ export function checkJq(_context, deps = defaultDeps) {
45
+ const hint = jqInstallHint(deps.platform);
46
+ const file = deps.findJq();
47
+ if (!file) {
48
+ return [
49
+ {
50
+ status: "FAIL",
51
+ checkId: JQ_CHECK_ID,
52
+ message: "jq is not on PATH. HQ hooks block every tool call until it is.",
53
+ remediation: hint,
54
+ },
55
+ ];
56
+ }
57
+ let version;
58
+ try {
59
+ version = deps.readVersion(file).trim();
60
+ }
61
+ catch (error) {
62
+ return [
63
+ {
64
+ status: "FAIL",
65
+ checkId: JQ_CHECK_ID,
66
+ target: file,
67
+ message: `jq is on PATH at ${file} but \`jq --version\` failed: ${(error instanceof Error ? error.message : String(error)).split("\n")[0]}`,
68
+ remediation: hint,
69
+ },
70
+ ];
71
+ }
72
+ return [
73
+ {
74
+ status: "PASS",
75
+ checkId: JQ_CHECK_ID,
76
+ target: file,
77
+ message: `${version || "jq"} is on PATH at ${file}.`,
78
+ details: { version },
79
+ },
80
+ ];
81
+ }
82
+ //# sourceMappingURL=jq.js.map
@@ -15,6 +15,7 @@
15
15
  */
16
16
  import * as fs from "node:fs";
17
17
  import { hookEngineFamily } from './checks/hook-engine.js';
18
+ import { jqFamily } from './checks/jq.js';
18
19
  import * as path from "node:path";
19
20
  import { checkCodexWiring } from "./checks/codex-wiring.js";
20
21
  import { checkGrokWiring } from "./checks/grok-wiring.js";
@@ -245,6 +246,9 @@ export function createDefaultRegistry() {
245
246
  const registry = new DoctorRegistry();
246
247
  registry.register(hooksFamily);
247
248
  registry.register(hookEngineFamily);
249
+ // master-hook parses every payload with jq and blocks tool calls without it
250
+ // (hq-core-staging PR 1882). PATH scan plus `jq --version`; never installs.
251
+ registry.register(jqFamily);
248
252
  registry.register(scaffoldCliFloorFamily);
249
253
  // Fixture coverage (US-007): reports UNTESTED for every registered hook with
250
254
  // no fixture and prints the tested/total coverage line. A separate family so
@@ -146,8 +146,38 @@ export function personFlagSnapshotPath(env = process.env) {
146
146
  const cacheHome = env.XDG_CACHE_HOME?.trim() || path.join(os.homedir(), ".cache");
147
147
  return path.join(cacheHome, "hq", "flags", "snapshot-person.json");
148
148
  }
149
+ /**
150
+ * Per-hook engine bridge flags (`hook-engine-port-<hook-id>`) carry a mode,
151
+ * not only a boolean. The hq-hook engine (crates/hq-hook/src/flags.rs
152
+ * `mode_of`) maps `true` and `"on"` to on, `"shadow"` to shadow, and every
153
+ * other value to off, so these exact strings must survive the snapshot.
154
+ */
155
+ const HOOK_ENGINE_PORT_FLAG_PREFIX = "hook-engine-port-";
156
+ const HOOK_ENGINE_PORT_MODES = new Set(["off", "shadow", "on"]);
157
+ function isHookEnginePortMode(key, value) {
158
+ return key.startsWith(HOOK_ENGINE_PORT_FLAG_PREFIX)
159
+ && key.length > HOOK_ENGINE_PORT_FLAG_PREFIX.length
160
+ && HOOK_ENGINE_PORT_MODES.has(value);
161
+ }
162
+ function isPersistedFlagValue(key, value) {
163
+ return typeof value === "boolean" || isHookEnginePortMode(key, value);
164
+ }
149
165
  function normalizedFlagValues(flags) {
150
- return Object.fromEntries(Object.entries(flags).filter((entry) => Boolean(entry[0].trim()) && typeof entry[1] === "boolean"));
166
+ return Object.fromEntries(Object.entries(flags).filter((entry) => Boolean(entry[0].trim()) && isPersistedFlagValue(entry[0], entry[1])));
167
+ }
168
+ /**
169
+ * Validate every stored value, then return only the boolean decisions. CLI
170
+ * gates are boolean; the engine reads port mode strings from the file itself.
171
+ */
172
+ function booleanFlagsOf(flags) {
173
+ const booleans = {};
174
+ for (const [key, value] of Object.entries(flags)) {
175
+ if (!isPersistedFlagValue(key, value))
176
+ return null;
177
+ if (typeof value === "boolean")
178
+ booleans[key] = value;
179
+ }
180
+ return booleans;
151
181
  }
152
182
  function writeSnapshotAt(destination, snapshot, cacheRootKind) {
153
183
  const directory = path.dirname(destination);
@@ -259,8 +289,8 @@ export function readPersonFlagSnapshotFile(options = {}) {
259
289
  const age = (options.now ?? Date.now()) - fetchedAt;
260
290
  if (!Number.isFinite(fetchedAt) || age < 0 || age > (options.maxAgeMs ?? FLAG_SNAPSHOT_MAX_AGE_MS))
261
291
  continue;
262
- const flags = value.flags;
263
- if (!Object.values(flags).every((enabled) => typeof enabled === "boolean"))
292
+ const flags = booleanFlagsOf(value.flags);
293
+ if (!flags)
264
294
  continue;
265
295
  if (file === fallback && fallback)
266
296
  fallbackCacheUsed = true;
@@ -341,11 +371,9 @@ function parseSnapshotFile(companyUid, file, options) {
341
371
  if (!Number.isFinite(fetchedAt) || age < 0 || age > (options.maxAgeMs ?? FLAG_SNAPSHOT_MAX_AGE_MS)) {
342
372
  return null;
343
373
  }
344
- const flags = value.flags;
345
- for (const enabled of Object.values(flags)) {
346
- if (typeof enabled !== "boolean")
347
- return null;
348
- }
374
+ const flags = booleanFlagsOf(value.flags);
375
+ if (!flags)
376
+ return null;
349
377
  return {
350
378
  company_uid: companyUid,
351
379
  fetched_at: value.fetched_at,
@@ -24,11 +24,62 @@ export declare function addAgentsMdBlock(current: string | null, charter: string
24
24
  export declare function removeAgentsMdBlock(current: string): string;
25
25
  type Doc = Record<string, unknown>;
26
26
  export declare function isAdapterEntry(entry: unknown, hqRoot: string): boolean;
27
+ /**
28
+ * Where Codex hook runs claim an event, under `$HOME` (feedback_bf4df70e,
29
+ * feedback_d69d01c0). Shared with the hq-core Codex hook adapter
30
+ * (`.codex/hooks/hq-codex-hook-adapter.sh`), which claims the same way, so the
31
+ * two must agree on this directory, the key and the window.
32
+ */
33
+ export declare const CODEX_HOOK_CLAIM_DIR = ".hq/state/codex-hook-claims";
34
+ /** A claim younger than this many seconds makes a second run of the same event a no-op. */
35
+ export declare const CODEX_HOOK_CLAIM_WINDOW_SECONDS = 10;
36
+ /** Claim markers older than this many minutes are pruned on every successful claim. */
37
+ export declare const CODEX_HOOK_CLAIM_PRUNE_MINUTES = 2;
38
+ /** Set on the hook a wrapper claimed for, so the adapter it runs does not claim again. */
39
+ export declare const CODEX_HOOK_CLAIM_ENV = "HQ_CODEX_HOOK_CLAIM";
40
+ /**
41
+ * Wrap a user-scope (~/.codex/hooks.json) command so one Codex event runs the
42
+ * HQ hooks once (feedback_bf4df70e, feedback_d69d01c0).
43
+ *
44
+ * Inside an HQ root, Codex runs this entry and the root's own
45
+ * `.codex/config.toml` hook for the same event, at the same time, with no
46
+ * dedupe. Predicting from a shell whether Codex will load and trust the project
47
+ * hook proved unreliable (project-root rules, per-hook trust by hash, path
48
+ * spellings), so both registrations stay and the second run of an event is a
49
+ * no-op at runtime instead. Each run claims the event once:
50
+ *
51
+ * - The key is `cksum` of the real HQ root, the Codex process (`$PPID`) and
52
+ * the exact stdin payload. Codex sends both hooks of one event the same
53
+ * payload from the same process; different events differ in their payload
54
+ * (event name, tool call, turn), and other Codex sessions differ in `$PPID`.
55
+ * - The claim is an atomic `mkdir` of `$HOME/.hq/state/codex-hook-claims/<key>`
56
+ * holding the claim time. The first run to create it does the full work. A
57
+ * run that finds a claim younger than {@link CODEX_HOOK_CLAIM_WINDOW_SECONDS}
58
+ * exits 0 with no output; an older claim is taken over, so two identical
59
+ * events further apart both run. Markers older than
60
+ * {@link CODEX_HOOK_CLAIM_PRUNE_MINUTES} minutes are pruned.
61
+ * - The claiming run passes {@link CODEX_HOOK_CLAIM_ENV} to the command it
62
+ * runs, so the HQ adapter does not claim a second time.
63
+ * - When anything needed is missing (`HOME`, the HQ root, the target file, a
64
+ * writable claim directory, `cksum`), the entry runs without claiming. Any
65
+ * failure therefore leads to the hook running twice, never to no hook.
66
+ *
67
+ * Until the hq-core adapter claims too, the project hook never claims, this
68
+ * entry always wins, and both still run, as before. `commandWindows` is not
69
+ * wrapped, so Windows keeps running both.
70
+ */
71
+ export declare function codexUserHookClaimed(hqRoot: string, target: HookTarget, command: string): string;
72
+ /**
73
+ * The user-scope hooks.json entry: {@link codexHookEntry} behind
74
+ * {@link codexUserHookClaimed}. `commandWindows` is unchanged.
75
+ */
76
+ export declare function codexUserHookEntry(hqRoot: string, event: string, target?: HookTarget): Record<string, unknown>;
27
77
  /** The HQ hooks.json entry for one event and target. */
28
78
  export declare function codexHookEntry(hqRoot: string, event: string, target?: HookTarget): Record<string, unknown>;
29
79
  /**
30
80
  * Add one HQ hook group per event; idempotent. An HQ entry for the other
31
- * target (adapter vs the hqd shim) is swapped out. Foreign hooks are untouched.
81
+ * target (adapter vs the hqd shim) is swapped out, and so is an HQ entry
82
+ * written before the user-scope guard existed. Foreign hooks are untouched.
32
83
  */
33
84
  export declare function addCodexHooks(doc: Doc, hqRoot: string, target?: HookTarget): Doc;
34
85
  /** Remove only HQ adapter entries; drop containers this left empty. */