@indigoai-us/hq-cli 5.345.203 → 5.345.205

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 (95) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/dist/command-catalog.generated.d.ts +51 -1
  3. package/dist/command-catalog.generated.js +63 -1
  4. package/dist/commands/bot.d.ts +67 -0
  5. package/dist/commands/bot.js +308 -41
  6. package/dist/commands/cloud-off-gate.d.ts +9 -2
  7. package/dist/commands/cloud-off-gate.js +49 -13
  8. package/dist/commands/cloud.d.ts +14 -2
  9. package/dist/commands/cloud.js +25 -16
  10. package/dist/commands/feedback.d.ts +26 -0
  11. package/dist/commands/feedback.js +91 -5
  12. package/dist/commands/install-global.d.ts +3 -1
  13. package/dist/commands/install-global.js +15 -4
  14. package/dist/commands/lanes.d.ts +2 -0
  15. package/dist/commands/lanes.js +9 -3
  16. package/dist/commands/mcp-serve.d.ts +5 -2
  17. package/dist/commands/mcp-serve.js +45 -3
  18. package/dist/commands/mcp-status.d.ts +3 -1
  19. package/dist/commands/mcp-status.js +24 -14
  20. package/dist/commands/secrets.js +11 -1
  21. package/dist/commands/sources.js +10 -15
  22. package/dist/commands/sync-core.js +2 -0
  23. package/dist/index.js +7 -2
  24. package/dist/lib/bot/claude-login.d.ts +7 -1
  25. package/dist/lib/bot/claude-login.js +56 -16
  26. package/dist/lib/bot/executive-settings.d.ts +13 -0
  27. package/dist/lib/bot/executive-settings.js +20 -17
  28. package/dist/lib/bot/executive-sync.d.ts +12 -0
  29. package/dist/lib/bot/executive-sync.js +36 -0
  30. package/dist/lib/bot/executive.d.ts +51 -0
  31. package/dist/lib/bot/executive.js +144 -0
  32. package/dist/lib/bot/fleet-cron.d.ts +7 -0
  33. package/dist/lib/bot/fleet-cron.js +2 -1
  34. package/dist/lib/bot/jobs/executive-handover.d.ts +6 -0
  35. package/dist/lib/bot/jobs/executive-handover.js +33 -0
  36. package/dist/lib/bot/jobs/hot-signal-sync.d.ts +22 -0
  37. package/dist/lib/bot/jobs/hot-signal-sync.js +47 -0
  38. package/dist/lib/bot/listed-running.d.ts +16 -0
  39. package/dist/lib/bot/listed-running.js +16 -0
  40. package/dist/lib/bot/pending-switch.d.ts +51 -0
  41. package/dist/lib/bot/pending-switch.js +103 -0
  42. package/dist/lib/bot/run.js +27 -3
  43. package/dist/lib/bot/runtime-failure.js +19 -3
  44. package/dist/lib/bot/status.d.ts +20 -0
  45. package/dist/lib/capacity/collectors/claude-oauth.d.ts +53 -5
  46. package/dist/lib/capacity/collectors/claude-oauth.js +251 -71
  47. package/dist/lib/company-skill-wrapper.js +29 -0
  48. package/dist/lib/daemon/catalog.js +2 -2
  49. package/dist/lib/daemon/hq-child-bootstrap.mjs +197 -2
  50. package/dist/lib/daemon/resolver.d.ts +14 -0
  51. package/dist/lib/daemon/resolver.js +96 -0
  52. package/dist/lib/daemon/run.d.ts +11 -0
  53. package/dist/lib/daemon/run.js +60 -8
  54. package/dist/lib/daemon/server.d.ts +2 -9
  55. package/dist/lib/daemon/server.js +3 -89
  56. package/dist/lib/doctor/checks/claude-wiring.js +41 -0
  57. package/dist/lib/doctor/checks/sync-health.d.ts +8 -0
  58. package/dist/lib/doctor/checks/sync-health.js +34 -2
  59. package/dist/lib/doctor/duplicate-hook-registrations.d.ts +34 -0
  60. package/dist/lib/doctor/duplicate-hook-registrations.js +130 -0
  61. package/dist/lib/doctor/fix/apply.js +79 -3
  62. package/dist/lib/doctor/fix/remediation.d.ts +1 -1
  63. package/dist/lib/doctor/fix/remediation.js +15 -0
  64. package/dist/lib/doctor/types.d.ts +1 -1
  65. package/dist/lib/doctor/types.js +1 -0
  66. package/dist/lib/lanes/config.js +13 -0
  67. package/dist/lib/lanes/throttle.d.ts +12 -1
  68. package/dist/lib/lanes/throttle.js +27 -8
  69. package/dist/lib/lanes/types.d.ts +5 -0
  70. package/dist/lib/mcp/local-native-tools.d.ts +40 -0
  71. package/dist/lib/mcp/local-native-tools.js +111 -0
  72. package/dist/lib/mcp/tools.d.ts +2 -0
  73. package/dist/lib/mcp/tools.js +2 -0
  74. package/dist/lib/signals/steps/extract.d.ts +111 -5
  75. package/dist/lib/signals/steps/extract.js +524 -55
  76. package/dist/lib/sync-core/engine-home.d.ts +2 -1
  77. package/dist/lib/sync-core/engine-home.js +25 -8
  78. package/dist/lib/sync-core/reconcile.d.ts +3 -1
  79. package/dist/lib/sync-core/reconcile.js +21 -8
  80. package/dist/lib/sync-core/release.d.ts +14 -5
  81. package/dist/lib/sync-core/release.js +58 -14
  82. package/dist/sentry-init.js +6 -0
  83. package/dist/utils/cli-network-lifecycle.d.ts +11 -1
  84. package/dist/utils/cli-network-lifecycle.js +36 -2
  85. package/dist/utils/daemon-helper-lifetime.d.ts +39 -0
  86. package/dist/utils/daemon-helper-lifetime.js +209 -0
  87. package/dist/utils/daemon-helper-markers.d.ts +24 -0
  88. package/dist/utils/daemon-helper-markers.js +53 -0
  89. package/dist/utils/mcp-launcher.d.ts +28 -0
  90. package/dist/utils/mcp-launcher.js +117 -0
  91. package/dist/utils/package-use-lease.d.ts +10 -0
  92. package/dist/utils/package-use-lease.js +31 -0
  93. package/dist/utils/resident-package-preload.js +4 -1
  94. package/docs/anywhere-runtime.md +7 -0
  95. package/package.json +7 -7
@@ -26,6 +26,7 @@ import * as path from "node:path";
26
26
  import { GATE_PROFILES, activeGateProfile, gateMembership, parseHookGateProfiles, requiredMissingProfiles, } from "../hook-gate-profiles.js";
27
27
  import { modeIsExecutable } from "../shared.js";
28
28
  import { countStrayGateEntries } from "../stray-gate-entries.js";
29
+ import { findDuplicateHookRegistrations } from "../duplicate-hook-registrations.js";
29
30
  /** Common id prefix for every result this check family emits. */
30
31
  export const CLAUDE_WIRING_PREFIX = "hooks.claude";
31
32
  /**
@@ -88,6 +89,46 @@ export function checkClaudeWiring(context) {
88
89
  message: `.claude/${file} has no stray matcher-less hook-gate registrations.`,
89
90
  });
90
91
  }
92
+ // --- Doubled hooks: the same registration in both settings files ------------
93
+ // Claude Code runs every registered command, so a hook present in
94
+ // settings.json and again in settings.local.json (or twice in one file) runs
95
+ // twice per event (feedback a73db922). Local copies are auto-fixable; a repeat
96
+ // inside the release-owned settings.json is reported only.
97
+ if (base.present && !base.invalid) {
98
+ const localValue = local.present && !local.invalid ? local.value : {};
99
+ const dupes = findDuplicateHookRegistrations(base.value, localValue);
100
+ const baseTarget = path.join(claudeDir, "settings.json");
101
+ const localTarget = path.join(claudeDir, "settings.local.json");
102
+ if (dupes.localDuplicates > 0) {
103
+ const n = dupes.localDuplicates;
104
+ results.push({
105
+ status: "WARN",
106
+ checkId: `${CLAUDE_WIRING_PREFIX}.duplicate-registration`,
107
+ target: localTarget,
108
+ message: `.claude/settings.local.json registers ${n} hook command${n === 1 ? "" : "s"} that settings.json (or an earlier line of the same file) already registers for the same event, ` +
109
+ `so ${n === 1 ? "it runs" : "they run"} twice. Doubled hooks enqueue every Work Mesh event twice and start extra background sessions.`,
110
+ remediation: "Run `hq doctor --fix` to remove only the repeated entries from .claude/settings.local.json (settings.json is not touched and the file is backed up first).",
111
+ });
112
+ }
113
+ if (dupes.baseInternalDuplicates > 0) {
114
+ const n = dupes.baseInternalDuplicates;
115
+ results.push({
116
+ status: "WARN",
117
+ checkId: `${CLAUDE_WIRING_PREFIX}.duplicate-registration`,
118
+ target: baseTarget,
119
+ message: `.claude/settings.json registers ${n} hook command${n === 1 ? "" : "s"} more than once for the same event, so ${n === 1 ? "it runs" : "they run"} twice.`,
120
+ remediation: "settings.json is release-owned: run /update-hq to restore it instead of editing it by hand.",
121
+ });
122
+ }
123
+ if (dupes.localDuplicates === 0 && dupes.baseInternalDuplicates === 0 && local.present && !local.invalid) {
124
+ results.push({
125
+ status: "PASS",
126
+ checkId: `${CLAUDE_WIRING_PREFIX}.duplicate-registration`,
127
+ target: localTarget,
128
+ message: "No hook command is registered twice for the same event across settings.json and settings.local.json.",
129
+ });
130
+ }
131
+ }
91
132
  const scans = registrations.map((reg) => ({
92
133
  reg,
93
134
  scan: scanHookCommand(reg.command),
@@ -23,6 +23,7 @@
23
23
  * Every dependency is injectable so the family is unit-testable without an HQ
24
24
  * tree, a state dir, or the wall clock.
25
25
  */
26
+ import { type VaultSyncSwitches } from "../../vault-sync-switches.js";
26
27
  import type { CheckContext, CheckFamily, CheckResult } from "../types.js";
27
28
  /** The id of the versions/sync family. */
28
29
  export declare const SYNC_FAMILY_ID = "sync";
@@ -155,6 +156,13 @@ export interface SyncHealthDeps {
155
156
  * than stale (feedback cd56a501).
156
157
  */
157
158
  refreshInProgress?: (fixTarget: string) => number | null;
159
+ /**
160
+ * The HQ app's Settings > Sync switches on this computer. A stale journal
161
+ * for a vault the user switched off is "off by choice" (NA), not a WARN with
162
+ * a `hq sync pull` fix the sync gate would refuse (feedback a73db922).
163
+ * Defaults to reading `~/.hq/menubar.json`.
164
+ */
165
+ vaultSyncSwitches?: () => VaultSyncSwitches;
158
166
  }
159
167
  /**
160
168
  * True when `slug` is a filesystem-safe company folder name. Rejects empty
@@ -36,6 +36,7 @@ import * as hqCloud from "@indigoai-us/hq-cloud";
36
36
  import { loadManifestExports, MANIFEST_UNAVAILABLE_REASON, } from "../../hq-cloud-manifest.js";
37
37
  import { readCompaniesManifestMap } from "../../work-context/repo-remote.js";
38
38
  import { companyRecordedNotResolved } from "../company-resolution-state.js";
39
+ import { readVaultSyncSwitches } from "../../vault-sync-switches.js";
39
40
  import { MANIFEST_DISABLED_ENV, manifestUploadsDisabled, } from "../../manifest-disabled.js";
40
41
  import { CLI_VERSION } from "../../../cli-version.js";
41
42
  import { readSyncVersion } from "../../../utils/feedback-versions.js";
@@ -104,6 +105,7 @@ function withDefaults(deps, hqRoot) {
104
105
  companySyncResolvable: deps.companySyncResolvable ??
105
106
  ((slug, lastSync) => !companyRecordedNotResolved(hqRoot, slug, deps.now().getTime(), lastSync)),
106
107
  manifestUploadsDisabled: deps.manifestUploadsDisabled ?? (() => manifestUploadsDisabled()),
108
+ vaultSyncSwitches: deps.vaultSyncSwitches ?? (() => readVaultSyncSwitches()),
107
109
  refreshInProgress: deps.refreshInProgress ??
108
110
  ((fixTarget) => refreshHandoffStartedAt(hqRoot, fixTarget, deps.now().getTime())),
109
111
  };
@@ -602,7 +604,7 @@ function journalResults(deps, journals) {
602
604
  if (entry.slug === PERSONAL_SCOPE_SLUG) {
603
605
  results.push(leftoverPersonalJournalResult(entry));
604
606
  if (!hasPersonalVaultJournal) {
605
- results.push(withRefreshInProgress(deps, journalFreshnessResult(entry, PERSONAL_VAULT_SCOPE_SLUG, nowMs), "personal"));
607
+ results.push(withRefreshInProgress(deps, withSyncOffByChoice(deps, journalFreshnessResult(entry, PERSONAL_VAULT_SCOPE_SLUG, nowMs), { personal: true }), "personal"));
606
608
  }
607
609
  continue;
608
610
  }
@@ -632,7 +634,7 @@ function journalResults(deps, journals) {
632
634
  continue;
633
635
  }
634
636
  }
635
- const freshness = journalFreshnessResult(entry, entry.slug, nowMs);
637
+ const freshness = withSyncOffByChoice(deps, journalFreshnessResult(entry, entry.slug, nowMs), isPersonalJournalSlug(entry.slug) ? { personal: true } : { company: entry.slug });
636
638
  // A stale company journal whose company the sync service could not
637
639
  // resolve on the last pull would send `--fix` into the same failure, and
638
640
  // the health hook would then report it every day (feedback 9b4a5016).
@@ -648,6 +650,36 @@ function journalResults(deps, journals) {
648
650
  }
649
651
  return results;
650
652
  }
653
+ /**
654
+ * A stale or never-synced journal for a vault the user turned off in Settings >
655
+ * Sync is "off by choice": NA with no remediation, because `hq sync pull`
656
+ * would be refused by the sync gate. Fresh or unreadable journals are untouched.
657
+ */
658
+ function withSyncOffByChoice(deps, result, scope) {
659
+ if (result.status !== "WARN")
660
+ return result;
661
+ if (result.reasonCode !== "stale-threshold" && result.reasonCode !== "never-synced")
662
+ return result;
663
+ let switches;
664
+ try {
665
+ switches = deps.vaultSyncSwitches();
666
+ }
667
+ catch {
668
+ return result;
669
+ }
670
+ const off = switches.allOff ||
671
+ ("personal" in scope ? switches.personalOff : switches.offCompanies.has(scope.company.toLowerCase()));
672
+ if (!off)
673
+ return result;
674
+ const name = "personal" in scope ? "personal vault" : `'${scope.company}' vault`;
675
+ return {
676
+ status: "NA",
677
+ checkId: result.checkId,
678
+ reasonCode: "sync-off-by-choice",
679
+ ...(result.target ? { target: result.target } : {}),
680
+ message: `Sync for the ${name} is off by choice on this computer (Settings > Sync), so its journal is not refreshed. ${result.message}`,
681
+ };
682
+ }
651
683
  /**
652
684
  * A stale or never-synced journal whose `hq doctor --fix` pull is still
653
685
  * running in the background is UNTESTED "refresh in progress", not WARN.
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Hook commands registered twice for the same event.
3
+ *
4
+ * Claude Code merges `.claude/settings.local.json` over `.claude/settings.json`
5
+ * and runs every registered command, so a hook that appears in both files (or
6
+ * twice in one) runs twice per event. The known cause is a `hq rescue`
7
+ * relocate that copied every master-hook.sh registration into
8
+ * settings.local.json as a "user customization" (feedback a73db922): every
9
+ * Work Mesh event was enqueued twice and the Stop hook started two checkpoint
10
+ * sessions per turn.
11
+ *
12
+ * A registration is identified by (event, matcher, full hook object). The same
13
+ * command under a different event or matcher, or with a different `if`,
14
+ * `timeout`, `async` or `shell`, is a different registration and is left
15
+ * alone. The repair only ever edits the local file: settings.json is the
16
+ * release-owned copy and is never touched.
17
+ */
18
+ export interface DuplicateHookReport {
19
+ /** Registrations in settings.json beyond the first copy of the same one. */
20
+ baseInternalDuplicates: number;
21
+ /** Local registrations that repeat settings.json or an earlier local one. */
22
+ localDuplicates: number;
23
+ }
24
+ export declare function findDuplicateHookRegistrations(base: unknown, local: unknown): DuplicateHookReport;
25
+ /**
26
+ * Copy of `local` without the registrations that repeat `base` or an earlier
27
+ * local one. An entry whose hooks all go is dropped, then an emptied event
28
+ * array, then an emptied `hooks` map; everything else is preserved.
29
+ */
30
+ export declare function removeDuplicateHookRegistrations(base: unknown, local: unknown): {
31
+ settings: unknown;
32
+ removed: number;
33
+ };
34
+ //# sourceMappingURL=duplicate-hook-registrations.d.ts.map
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Hook commands registered twice for the same event.
3
+ *
4
+ * Claude Code merges `.claude/settings.local.json` over `.claude/settings.json`
5
+ * and runs every registered command, so a hook that appears in both files (or
6
+ * twice in one) runs twice per event. The known cause is a `hq rescue`
7
+ * relocate that copied every master-hook.sh registration into
8
+ * settings.local.json as a "user customization" (feedback a73db922): every
9
+ * Work Mesh event was enqueued twice and the Stop hook started two checkpoint
10
+ * sessions per turn.
11
+ *
12
+ * A registration is identified by (event, matcher, full hook object). The same
13
+ * command under a different event or matcher, or with a different `if`,
14
+ * `timeout`, `async` or `shell`, is a different registration and is left
15
+ * alone. The repair only ever edits the local file: settings.json is the
16
+ * release-owned copy and is never touched.
17
+ */
18
+ function isObject(v) {
19
+ return !!v && typeof v === "object" && !Array.isArray(v);
20
+ }
21
+ /** JSON with object keys sorted, so field order never changes the identity. */
22
+ function stable(v) {
23
+ if (Array.isArray(v))
24
+ return `[${v.map(stable).join(",")}]`;
25
+ if (isObject(v)) {
26
+ return `{${Object.keys(v)
27
+ .sort()
28
+ .map((k) => `${JSON.stringify(k)}:${stable(v[k])}`)
29
+ .join(",")}}`;
30
+ }
31
+ return JSON.stringify(v) ?? "null";
32
+ }
33
+ function key(event, entry, hook) {
34
+ const matcher = typeof entry.matcher === "string" ? entry.matcher : "";
35
+ return stable([event, matcher, hook]);
36
+ }
37
+ function commandOf(hook) {
38
+ if (!isObject(hook) || hook.type !== "command")
39
+ return null;
40
+ return typeof hook.command === "string" && hook.command.length > 0 ? hook.command : null;
41
+ }
42
+ /** Keys of every command registration in `settings`, in order (repeats included). */
43
+ function registrationKeys(settings) {
44
+ const out = [];
45
+ const hooks = isObject(settings) ? settings.hooks : undefined;
46
+ if (!isObject(hooks))
47
+ return out;
48
+ for (const [event, entries] of Object.entries(hooks)) {
49
+ if (!Array.isArray(entries))
50
+ continue;
51
+ for (const entry of entries) {
52
+ if (!isObject(entry) || !Array.isArray(entry.hooks))
53
+ continue;
54
+ for (const hook of entry.hooks) {
55
+ if (commandOf(hook) !== null)
56
+ out.push(key(event, entry, hook));
57
+ }
58
+ }
59
+ }
60
+ return out;
61
+ }
62
+ export function findDuplicateHookRegistrations(base, local) {
63
+ const seen = new Set();
64
+ let baseInternalDuplicates = 0;
65
+ for (const k of registrationKeys(base)) {
66
+ if (seen.has(k))
67
+ baseInternalDuplicates += 1;
68
+ else
69
+ seen.add(k);
70
+ }
71
+ let localDuplicates = 0;
72
+ for (const k of registrationKeys(local)) {
73
+ if (seen.has(k))
74
+ localDuplicates += 1;
75
+ else
76
+ seen.add(k);
77
+ }
78
+ return { baseInternalDuplicates, localDuplicates };
79
+ }
80
+ /**
81
+ * Copy of `local` without the registrations that repeat `base` or an earlier
82
+ * local one. An entry whose hooks all go is dropped, then an emptied event
83
+ * array, then an emptied `hooks` map; everything else is preserved.
84
+ */
85
+ export function removeDuplicateHookRegistrations(base, local) {
86
+ if (!isObject(local) || !isObject(local.hooks))
87
+ return { settings: local, removed: 0 };
88
+ const seen = new Set(registrationKeys(base));
89
+ let removed = 0;
90
+ const nextHooks = {};
91
+ for (const [event, entries] of Object.entries(local.hooks)) {
92
+ if (!Array.isArray(entries)) {
93
+ nextHooks[event] = entries;
94
+ continue;
95
+ }
96
+ const keptEntries = [];
97
+ for (const entry of entries) {
98
+ if (!isObject(entry) || !Array.isArray(entry.hooks)) {
99
+ keptEntries.push(entry);
100
+ continue;
101
+ }
102
+ const keptHooks = entry.hooks.filter((hook) => {
103
+ if (commandOf(hook) === null)
104
+ return true;
105
+ const k = key(event, entry, hook);
106
+ if (seen.has(k)) {
107
+ removed += 1;
108
+ return false;
109
+ }
110
+ seen.add(k);
111
+ return true;
112
+ });
113
+ if (keptHooks.length === entry.hooks.length)
114
+ keptEntries.push(entry);
115
+ else if (keptHooks.length > 0)
116
+ keptEntries.push({ ...entry, hooks: keptHooks });
117
+ }
118
+ if (keptEntries.length > 0 || entries.length === 0)
119
+ nextHooks[event] = keptEntries;
120
+ }
121
+ if (removed === 0)
122
+ return { settings: local, removed: 0 };
123
+ const next = { ...local };
124
+ if (Object.keys(nextHooks).length > 0)
125
+ next.hooks = nextHooks;
126
+ else
127
+ delete next.hooks;
128
+ return { settings: next, removed };
129
+ }
130
+ //# sourceMappingURL=duplicate-hook-registrations.js.map
@@ -48,6 +48,7 @@ import { repairDanglingReleaseLinks } from "../checks/release-links.js";
48
48
  import { parseHookGateProfiles, requiredMissingProfiles, } from "../hook-gate-profiles.js";
49
49
  import { createBackup } from "./backup.js";
50
50
  import { removeStrayGateEntries } from "../stray-gate-entries.js";
51
+ import { removeDuplicateHookRegistrations } from "../duplicate-hook-registrations.js";
51
52
  import { deriveRemediation } from "./remediation.js";
52
53
  import { HQ_CLI_BINS, removeHqCliPs1Shims } from "../../windows/ps1-shims.js";
53
54
  import { botDir } from "../../bot/paths.js";
@@ -902,6 +903,8 @@ function planFix(hqRoot, result, rem, refreshSync, rewriteBotNodePath = defaultR
902
903
  return planGateProfile(hqRoot, result, rem);
903
904
  case "remove-stray-gate-entries":
904
905
  return planRemoveStrayGateEntries(hqRoot, result, rem);
906
+ case "remove-duplicate-hook-registrations":
907
+ return planRemoveDuplicateHookRegistrations(hqRoot, result, rem);
905
908
  case "refresh-sync":
906
909
  return planRefreshSync(hqRoot, result, rem, refreshSync);
907
910
  case "refresh-manifest":
@@ -1213,13 +1216,59 @@ function planRemoveStrayGateEntries(hqRoot, result, rem) {
1213
1216
  ` - ${removed} matcher-less hook-gate.sh registration${removed === 1 ? "" : "s"} (they fire on every tool call)`,
1214
1217
  summary: `remove ${removed} stray hook registration${removed === 1 ? "" : "s"} from ${relpath}`,
1215
1218
  apply: () => {
1216
- const latest = readJson(settingsPath) ?? {};
1217
- const cleaned = removeStrayGateEntries(latest).settings;
1218
- fs.writeFileSync(settingsPath, JSON.stringify(cleaned, null, 2) + "\n");
1219
+ // Unparseable now (Claude Code may be mid-write): leave it untouched.
1220
+ const latest = readJson(settingsPath);
1221
+ if (!latest) {
1222
+ process.stderr.write(`hq doctor --fix: skipped ${relpath}; it could not be read as JSON right now and was left unchanged.\n`);
1223
+ return;
1224
+ }
1225
+ const { settings: cleaned, removed: again } = removeStrayGateEntries(latest);
1226
+ if (again === 0)
1227
+ return;
1228
+ writeJsonAtomic(settingsPath, cleaned);
1219
1229
  },
1220
1230
  postStatus: (results) => statusForTarget(results, ".stray-gate-registration", settingsPath),
1221
1231
  };
1222
1232
  }
1233
+ /** Remove hook registrations from settings.local.json that settings.json already has. */
1234
+ function planRemoveDuplicateHookRegistrations(hqRoot, result, rem) {
1235
+ const localPath = rem.fixTarget;
1236
+ if (!localPath)
1237
+ return null;
1238
+ // The shipped file is only read, never written.
1239
+ const basePath = path.join(path.dirname(localPath), "settings.json");
1240
+ const base = readJson(basePath);
1241
+ const current = readJson(localPath);
1242
+ if (!base || !current)
1243
+ return null;
1244
+ const { removed } = removeDuplicateHookRegistrations(base, current);
1245
+ if (removed === 0)
1246
+ return null;
1247
+ const relpath = toRelpath(hqRoot, localPath);
1248
+ return {
1249
+ checkId: result.checkId,
1250
+ fixClass: "remove-duplicate-hook-registrations",
1251
+ target: localPath,
1252
+ relpath,
1253
+ preview: ` ${relpath}\n` +
1254
+ ` - ${removed} hook registration${removed === 1 ? "" : "s"} that settings.json already registers (they run twice)`,
1255
+ summary: `remove ${removed} duplicate hook registration${removed === 1 ? "" : "s"} from ${relpath}`,
1256
+ apply: () => {
1257
+ // Either file unparseable now (Claude Code may be mid-write): leave both untouched.
1258
+ const latestBase = readJson(basePath);
1259
+ const latest = readJson(localPath);
1260
+ if (!latestBase || !latest) {
1261
+ process.stderr.write(`hq doctor --fix: skipped ${relpath}; it or settings.json could not be read as JSON right now and was left unchanged.\n`);
1262
+ return;
1263
+ }
1264
+ const { settings: cleaned, removed: again } = removeDuplicateHookRegistrations(latestBase, latest);
1265
+ if (again === 0)
1266
+ return;
1267
+ writeJsonAtomic(localPath, cleaned);
1268
+ },
1269
+ postStatus: (results) => statusForTarget(results, ".duplicate-registration", localPath),
1270
+ };
1271
+ }
1223
1272
  // --- Shell / JSON edit primitives ---------------------------------------------
1224
1273
  /**
1225
1274
  * Insert a new `case` arm allowlisting `hookId` (leading to `return 0`) at the
@@ -1299,6 +1348,33 @@ function readJson(file) {
1299
1348
  return null;
1300
1349
  }
1301
1350
  }
1351
+ /**
1352
+ * Write JSON via a temp file next to the real target, then rename over it.
1353
+ * A symlinked target is resolved first so the link stays and its target is
1354
+ * updated. The temp is fsynced and given the original mode exactly (the mode
1355
+ * passed to openSync is masked by umask) before the rename.
1356
+ */
1357
+ function writeJsonAtomic(file, value) {
1358
+ const real = fs.realpathSync(file);
1359
+ const tmp = `${real}.${process.pid}.tmp`;
1360
+ try {
1361
+ const mode = fs.statSync(real).mode & 0o7777;
1362
+ const fd = fs.openSync(tmp, "w", mode);
1363
+ try {
1364
+ fs.writeSync(fd, JSON.stringify(value, null, 2) + "\n");
1365
+ fs.fsyncSync(fd);
1366
+ }
1367
+ finally {
1368
+ fs.closeSync(fd);
1369
+ }
1370
+ fs.chmodSync(tmp, mode);
1371
+ fs.renameSync(tmp, real);
1372
+ }
1373
+ catch (err) {
1374
+ fs.rmSync(tmp, { force: true });
1375
+ throw err;
1376
+ }
1377
+ }
1302
1378
  function toRelpath(hqRoot, abs) {
1303
1379
  const rel = path.relative(hqRoot, abs);
1304
1380
  return rel === "" ? abs : rel;
@@ -61,7 +61,7 @@
61
61
  */
62
62
  import type { CheckResult } from "../types.js";
63
63
  /** The allowlisted safe repair classes `--fix` is permitted to apply. */
64
- export type FixClass = "executable-bit" | "gate-profile" | "remove-stray-gate-entries" | "refresh-sync" | "refresh-manifest" | "bot-node-path" | "bot-hq-binary" | "remove-ps1-shims" | "repair-release-link";
64
+ export type FixClass = "executable-bit" | "gate-profile" | "remove-stray-gate-entries" | "remove-duplicate-hook-registrations" | "refresh-sync" | "refresh-manifest" | "bot-node-path" | "bot-hq-binary" | "remove-ps1-shims" | "repair-release-link";
65
65
  /**
66
66
  * A finding's structured remediation. `autoFixable`, `action`, and `command`
67
67
  * are the `--json` surface (AC1); `fixTarget`/`fixClass` are the internal handle
@@ -131,6 +131,21 @@ export function deriveRemediation(result) {
131
131
  command: remediation ?? `Remove the matcher-less hook-gate.sh entries from ${target}.`,
132
132
  };
133
133
  }
134
+ // remove-duplicate-hook-registrations — hooks registered in settings.local.json
135
+ // that settings.json already registers, so each runs twice. Only the local
136
+ // overlay is repaired; a repeat inside settings.json stays manual.
137
+ if (checkId.endsWith(".duplicate-registration") &&
138
+ result.status === "WARN" &&
139
+ target &&
140
+ path.basename(target) === "settings.local.json") {
141
+ return {
142
+ autoFixable: true,
143
+ fixClass: "remove-duplicate-hook-registrations",
144
+ fixTarget: target,
145
+ action: `Remove hook registrations from ${target} that settings.json already registers (settings.json is not changed).`,
146
+ command: remediation ?? `Remove the repeated hook entries from ${target}.`,
147
+ };
148
+ }
134
149
  // bot-node-path — a bot LaunchAgent that names node by a versioned path
135
150
  // (…/Cellar/node/<v>/bin/node) that an upgrade removed or will remove.
136
151
  // The repair rewrites only the plist file; it never reloads launchd, so it
@@ -19,7 +19,7 @@ export declare const DOCTOR_STATUSES: readonly ["PASS", "FAIL", "WARN", "UNTESTE
19
19
  */
20
20
  export type DoctorStatus = (typeof DOCTOR_STATUSES)[number];
21
21
  /** Stable, privacy-safe diagnostics emitted by the sync health family. */
22
- export declare const SYNC_REASON_CODES: readonly ["core-version-unavailable", "core-update-available", "no-local-tree", "company-not-resolved", "legacy-personal-journal", "never-synced", "invalid-last-sync", "stale-threshold", "refresh-in-progress", "refresh-lock-held", "manifest-unavailable", "manifest-state-unavailable", "no-manifest-scopes", "never-uploaded", "invalid-upload-time", "manifest-upload-rejected", "unresolved-company-uid", "realtime-lag-stuck", "receiver-permission-denied", "pull-access-denied", "runner-restart-loop", "device-limit-backoff", "repeated-conflicts"];
22
+ export declare const SYNC_REASON_CODES: readonly ["core-version-unavailable", "core-update-available", "no-local-tree", "company-not-resolved", "legacy-personal-journal", "never-synced", "invalid-last-sync", "stale-threshold", "sync-off-by-choice", "refresh-in-progress", "refresh-lock-held", "manifest-unavailable", "manifest-state-unavailable", "no-manifest-scopes", "never-uploaded", "invalid-upload-time", "manifest-upload-rejected", "unresolved-company-uid", "realtime-lag-stuck", "receiver-permission-denied", "pull-access-denied", "runner-restart-loop", "device-limit-backoff", "repeated-conflicts"];
23
23
  export type SyncReasonCode = (typeof SYNC_REASON_CODES)[number];
24
24
  /** Runtime type guard: true only for a member of the fixed vocabulary. */
25
25
  export declare function isDoctorStatus(value: unknown): value is DoctorStatus;
@@ -31,6 +31,7 @@ export const SYNC_REASON_CODES = [
31
31
  "never-synced",
32
32
  "invalid-last-sync",
33
33
  "stale-threshold",
34
+ "sync-off-by-choice",
34
35
  "refresh-in-progress",
35
36
  "refresh-lock-held",
36
37
  "manifest-unavailable",
@@ -172,6 +172,14 @@ function optionalUnitInterval(value, field) {
172
172
  }
173
173
  return value;
174
174
  }
175
+ function optionalPercent(value, field) {
176
+ if (value === undefined)
177
+ return undefined;
178
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 100) {
179
+ throw new LanesConfigError("invalid_config", `${field} must be a number in [0, 100]`, { field, value });
180
+ }
181
+ return value;
182
+ }
175
183
  function parseAccount(provider, id, raw, deps) {
176
184
  if (!isPlainObject(raw)) {
177
185
  throw new LanesConfigError("invalid_config", `providers.${provider}.accounts.${id} must be an object`, { provider, account: id });
@@ -407,6 +415,11 @@ function parseThrottle(raw) {
407
415
  }
408
416
  result.min_available_mem_mb = obj.min_available_mem_mb;
409
417
  }
418
+ // darwin: a warn pressure level holds only at or below this free
419
+ // percentage. Unset means DEFAULT_MEMORY_WARN_MIN_FREE_PERCENT (20).
420
+ const warnMinFree = optionalPercent(obj.memory_warn_min_free_percent, "throttle.memory_warn_min_free_percent");
421
+ if (warnMinFree !== undefined)
422
+ result.memory_warn_min_free_percent = warnMinFree;
410
423
  return result;
411
424
  }
412
425
  function parseLiveness(raw) {
@@ -25,6 +25,17 @@ export declare const SYSCTL_BIN = "/usr/sbin/sysctl";
25
25
  * hw.memsize turns the percentage into MiB for min_available_mem_mb.
26
26
  */
27
27
  export declare const MEMORY_PRESSURE_SYSCTLS: readonly ["kern.memorystatus_level", "kern.memorystatus_vm_pressure_level", "hw.memsize"];
28
+ /**
29
+ * Default for throttle.memory_warn_min_free_percent. On darwin a warn pressure
30
+ * level holds admission only while the free percentage is at or below this.
31
+ */
32
+ export declare const DEFAULT_MEMORY_WARN_MIN_FREE_PERCENT = 20;
33
+ /**
34
+ * Whether a darwin memory_pressure level holds admission on its own. Critical
35
+ * always holds. Warn holds only at or below warnMinFreePercent free, or when
36
+ * the free percentage is unknown.
37
+ */
38
+ export declare function pressureLevelHolds(signal: MemorySignal, warnMinFreePercent?: number): boolean;
28
39
  export declare const LANES_CPU_BUSY_OVERRIDE = "HQ_LANES_CPU_BUSY_OVERRIDE";
29
40
  export declare const LANES_CPU_CHECK = "HQ_LANES_CPU_CHECK";
30
41
  export interface CpuTimes {
@@ -129,7 +140,7 @@ export declare function readMemorySignal(deps?: ThrottleDeps): MemorySignal | nu
129
140
  /** Available memory in MiB from readMemorySignal; null skips the memory gate. */
130
141
  export declare function readAvailableMemMb(deps?: ThrottleDeps): number | null;
131
142
  /** Plain explanation of a memory hold: which signal, its value, and the threshold. */
132
- export declare function formatMemoryHoldMessage(signal: MemorySignal, thresholdMb: number): string;
143
+ export declare function formatMemoryHoldMessage(signal: MemorySignal, thresholdMb: number, warnMinFreePercent?: number): string;
133
144
  export interface ThrottleState {
134
145
  consecutiveDeferrals: number;
135
146
  lastAdmissionAt: string | null;
@@ -34,6 +34,23 @@ export const MEMORY_PRESSURE_SYSCTLS = [
34
34
  "kern.memorystatus_vm_pressure_level",
35
35
  "hw.memsize",
36
36
  ];
37
+ /**
38
+ * Default for throttle.memory_warn_min_free_percent. On darwin a warn pressure
39
+ * level holds admission only while the free percentage is at or below this.
40
+ */
41
+ export const DEFAULT_MEMORY_WARN_MIN_FREE_PERCENT = 20;
42
+ /**
43
+ * Whether a darwin memory_pressure level holds admission on its own. Critical
44
+ * always holds. Warn holds only at or below warnMinFreePercent free, or when
45
+ * the free percentage is unknown.
46
+ */
47
+ export function pressureLevelHolds(signal, warnMinFreePercent = DEFAULT_MEMORY_WARN_MIN_FREE_PERCENT) {
48
+ if (signal.pressure_level === "critical")
49
+ return true;
50
+ if (signal.pressure_level !== "warn")
51
+ return false;
52
+ return signal.free_percent === undefined || signal.free_percent <= warnMinFreePercent;
53
+ }
37
54
  export const LANES_CPU_BUSY_OVERRIDE = "HQ_LANES_CPU_BUSY_OVERRIDE";
38
55
  export const LANES_CPU_CHECK = "HQ_LANES_CPU_CHECK";
39
56
  function defaultSleep(ms) {
@@ -340,11 +357,11 @@ function formatMb(mb) {
340
357
  return `${Math.round(mb)} MB`;
341
358
  }
342
359
  /** Plain explanation of a memory hold: which signal, its value, and the threshold. */
343
- export function formatMemoryHoldMessage(signal, thresholdMb) {
360
+ export function formatMemoryHoldMessage(signal, thresholdMb, warnMinFreePercent = DEFAULT_MEMORY_WARN_MIN_FREE_PERCENT) {
344
361
  if (signal.source === "memory_pressure") {
345
362
  const reading = `memory_pressure reports ${signal.free_percent}% free (about ${formatMb(signal.available_mb)}), pressure level ${signal.pressure_level}`;
346
- if (signal.pressure_level !== "normal") {
347
- return `Holding new lanes: ${reading}. Lanes wait while the level is warn or critical (throttle.min_available_mem_mb is ${thresholdMb}).`;
363
+ if (pressureLevelHolds(signal, warnMinFreePercent)) {
364
+ return `Holding new lanes: ${reading}. Lanes wait while the level is critical, or warn with ${warnMinFreePercent}% free or less (throttle.memory_warn_min_free_percent; throttle.min_available_mem_mb is ${thresholdMb}).`;
348
365
  }
349
366
  return `Holding new lanes: ${reading}, below throttle.min_available_mem_mb ${thresholdMb}.`;
350
367
  }
@@ -379,6 +396,8 @@ export function evaluateThrottle(input) {
379
396
  const pause = input.throttle.cpu_busy_pause;
380
397
  const resume = input.throttle.cpu_busy_resume;
381
398
  const minMem = input.throttle.min_available_mem_mb;
399
+ const warnMinFree = input.throttle.memory_warn_min_free_percent ??
400
+ DEFAULT_MEMORY_WARN_MIN_FREE_PERCENT;
382
401
  // Each gate is opt-in: an unset threshold never blocks admission.
383
402
  let cpuBlocks = false;
384
403
  if (pause !== undefined && input.cpuCheckEnabled && input.busy !== null) {
@@ -389,8 +408,9 @@ export function evaluateThrottle(input) {
389
408
  cpuBlocks = input.busy >= pause;
390
409
  }
391
410
  }
392
- // On darwin the signal is memory_pressure's: a warn or critical level holds
393
- // even above the threshold, and a normal level holds only below it.
411
+ // On darwin the signal is memory_pressure's: a critical level holds even
412
+ // above the threshold, a warn level holds only at or below
413
+ // memory_warn_min_free_percent free, and otherwise only below the threshold.
394
414
  let memBlocks = false;
395
415
  let memorySignal;
396
416
  if (minMem !== undefined && input.availableMemMb !== null) {
@@ -398,8 +418,7 @@ export function evaluateThrottle(input) {
398
418
  ? input.memory
399
419
  : { source: "meminfo", available_mb: input.availableMemMb };
400
420
  memBlocks = input.availableMemMb < minMem ||
401
- memorySignal.pressure_level === "warn" ||
402
- memorySignal.pressure_level === "critical";
421
+ pressureLevelHolds(memorySignal, warnMinFree);
403
422
  }
404
423
  if (!cpuBlocks && !memBlocks) {
405
424
  return {
@@ -420,7 +439,7 @@ export function evaluateThrottle(input) {
420
439
  memory_hold: {
421
440
  ...memorySignal,
422
441
  threshold_mb: minMem,
423
- message: formatMemoryHoldMessage(memorySignal, minMem),
442
+ message: formatMemoryHoldMessage(memorySignal, minMem, warnMinFree),
424
443
  },
425
444
  };
426
445
  }
@@ -1226,6 +1226,11 @@ export interface ThrottleConfig {
1226
1226
  cpu_busy_pause?: number;
1227
1227
  cpu_busy_resume?: number;
1228
1228
  min_available_mem_mb?: number;
1229
+ /**
1230
+ * darwin only: a warn memory_pressure level holds admission only at or
1231
+ * below this free percentage (0-100). Unset means 20. Critical always holds.
1232
+ */
1233
+ memory_warn_min_free_percent?: number;
1229
1234
  }
1230
1235
  /** Session liveness windows from spec §9. Missing keys keep these documented defaults. */
1231
1236
  export interface LivenessWindows {