@indigoai-us/hq-cli 5.345.220 → 5.345.222

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 (184) hide show
  1. package/CHANGELOG.md +164 -0
  2. package/dist/command-catalog.generated.d.ts +175 -2
  3. package/dist/command-catalog.generated.js +213 -2
  4. package/dist/commands/auth.js +6 -2
  5. package/dist/commands/bot-runtime.d.ts +18 -5
  6. package/dist/commands/bot-runtime.js +29 -12
  7. package/dist/commands/bot.d.ts +39 -2
  8. package/dist/commands/bot.js +140 -11
  9. package/dist/commands/core-delegate-w1b.js +9 -3
  10. package/dist/commands/core-stop-autosave.d.ts +21 -0
  11. package/dist/commands/core-stop-autosave.js +300 -0
  12. package/dist/commands/core.js +2 -0
  13. package/dist/commands/daemon.d.ts +6 -0
  14. package/dist/commands/daemon.js +46 -8
  15. package/dist/commands/doctor-usage.d.ts +5 -0
  16. package/dist/commands/doctor-usage.js +25 -0
  17. package/dist/commands/env.d.ts +49 -4
  18. package/dist/commands/env.js +355 -5
  19. package/dist/commands/lanes-shared.d.ts +3 -0
  20. package/dist/commands/lanes.d.ts +3 -0
  21. package/dist/commands/lanes.js +87 -3
  22. package/dist/commands/link.d.ts +2 -0
  23. package/dist/commands/link.js +14 -2
  24. package/dist/commands/mesh.js +23 -3
  25. package/dist/commands/sources.js +3 -3
  26. package/dist/commands/sync-core.d.ts +7 -0
  27. package/dist/commands/sync-core.js +132 -3
  28. package/dist/commands/whoami.js +96 -80
  29. package/dist/data/command-states.json +3 -0
  30. package/dist/lib/bot/config.d.ts +17 -0
  31. package/dist/lib/bot/config.js +13 -0
  32. package/dist/lib/bot/fleet-cron.js +24 -2
  33. package/dist/lib/bot/fleet-local.d.ts +30 -2
  34. package/dist/lib/bot/fleet-local.js +60 -1
  35. package/dist/lib/bot/grok-login-scope.d.ts +36 -0
  36. package/dist/lib/bot/grok-login-scope.js +93 -0
  37. package/dist/lib/bot/legacy-provider-login.d.ts +32 -9
  38. package/dist/lib/bot/legacy-provider-login.js +28 -22
  39. package/dist/lib/bot/runtime-sign-in-check.js +6 -1
  40. package/dist/lib/bot/runtime-sign-in.d.ts +2 -0
  41. package/dist/lib/core-utils/sentry-report.js +2 -0
  42. package/dist/lib/daemon/catalog.js +2 -0
  43. package/dist/lib/daemon/install.d.ts +2 -1
  44. package/dist/lib/daemon/install.js +9 -0
  45. package/dist/lib/daemon/legacy.d.ts +1 -0
  46. package/dist/lib/daemon/legacy.js +5 -2
  47. package/dist/lib/daemon/machine-check-owner.d.ts +2 -0
  48. package/dist/lib/daemon/machine-check-owner.js +6 -1
  49. package/dist/lib/daemon/machine-checks.d.ts +29 -2
  50. package/dist/lib/daemon/machine-checks.js +64 -13
  51. package/dist/lib/daemon/mesh-owner.d.ts +45 -0
  52. package/dist/lib/daemon/mesh-owner.js +166 -0
  53. package/dist/lib/daemon/native-notice-ledger.d.ts +27 -0
  54. package/dist/lib/daemon/native-notice-ledger.js +113 -0
  55. package/dist/lib/daemon/run.d.ts +15 -0
  56. package/dist/lib/daemon/run.js +137 -11
  57. package/dist/lib/daemon/selfcheck.d.ts +35 -2
  58. package/dist/lib/daemon/selfcheck.js +118 -9
  59. package/dist/lib/daemon/stop-autosave-lock.d.ts +19 -0
  60. package/dist/lib/daemon/stop-autosave-lock.js +166 -0
  61. package/dist/lib/daemon/stop-autosave.d.ts +28 -0
  62. package/dist/lib/daemon/stop-autosave.js +111 -0
  63. package/dist/lib/daemon/stop-diagnostics.d.ts +11 -0
  64. package/dist/lib/daemon/stop-diagnostics.js +136 -0
  65. package/dist/lib/daemon/stop-job-executor.d.ts +19 -0
  66. package/dist/lib/daemon/stop-job-executor.js +126 -0
  67. package/dist/lib/daemon/stop-jobs.d.ts +93 -0
  68. package/dist/lib/daemon/stop-jobs.js +599 -0
  69. package/dist/lib/doctor/checks/fleet-hook-core.js +1 -1
  70. package/dist/lib/doctor/checks/host-core.js +1 -1
  71. package/dist/lib/environment/access-probes.d.ts +234 -0
  72. package/dist/lib/environment/access-probes.js +918 -0
  73. package/dist/lib/environment/profile.d.ts +15 -2
  74. package/dist/lib/environment/profile.js +55 -20
  75. package/dist/lib/environment/rfc3339.d.ts +8 -0
  76. package/dist/lib/environment/rfc3339.js +26 -0
  77. package/dist/lib/environment/work-requirements.d.ts +169 -0
  78. package/dist/lib/environment/work-requirements.js +389 -0
  79. package/dist/lib/hook-engine/coverage.d.ts +146 -7
  80. package/dist/lib/hook-engine/coverage.js +1480 -4
  81. package/dist/lib/hook-engine/fleet-registration.js +2 -2
  82. package/dist/lib/hook-engine/git-stop-config.json +513 -0
  83. package/dist/lib/hook-engine/native-stop-compatibility.json +362 -0
  84. package/dist/lib/hook-engine/reconcile.js +2 -2
  85. package/dist/lib/hot-channels/alert.d.ts +2 -2
  86. package/dist/lib/hot-channels/alert.js +8 -5
  87. package/dist/lib/hot-channels/signals-pass.d.ts +126 -17
  88. package/dist/lib/hot-channels/signals-pass.js +296 -17
  89. package/dist/lib/hot-channels/signals-runtime.d.ts +30 -0
  90. package/dist/lib/hot-channels/signals-runtime.js +82 -0
  91. package/dist/lib/install/hook-target.js +1 -1
  92. package/dist/lib/lanes/host-capacity.d.ts +26 -2
  93. package/dist/lib/lanes/host-capacity.js +17 -2
  94. package/dist/lib/lanes/host-compute.d.ts +90 -0
  95. package/dist/lib/lanes/host-compute.js +185 -0
  96. package/dist/lib/lanes/index.d.ts +2 -0
  97. package/dist/lib/lanes/index.js +1 -0
  98. package/dist/lib/lanes/reconcile.js +22 -1
  99. package/dist/lib/lanes/resource-usage.d.ts +155 -0
  100. package/dist/lib/lanes/resource-usage.js +589 -0
  101. package/dist/lib/lanes/run-size.d.ts +46 -0
  102. package/dist/lib/lanes/run-size.js +197 -0
  103. package/dist/lib/lanes/store.js +27 -0
  104. package/dist/lib/lanes/throttle.d.ts +36 -1
  105. package/dist/lib/lanes/throttle.js +47 -10
  106. package/dist/lib/lanes/types.d.ts +40 -0
  107. package/dist/lib/lanes/types.js +2 -2
  108. package/dist/lib/lanes/watcher.js +13 -4
  109. package/dist/lib/lanes/worker-process.d.ts +25 -2
  110. package/dist/lib/lanes/worker-process.js +71 -19
  111. package/dist/lib/mesh/live/daemon/config.d.ts +8 -1
  112. package/dist/lib/mesh/live/daemon/config.js +16 -0
  113. package/dist/lib/mesh/live/daemon/install.d.ts +31 -2
  114. package/dist/lib/mesh/live/daemon/install.js +142 -1
  115. package/dist/lib/mesh/live/daemon/login-home.d.ts +5 -0
  116. package/dist/lib/mesh/live/daemon/login-home.js +27 -0
  117. package/dist/lib/mesh/live/daemon/unit-home.d.ts +49 -0
  118. package/dist/lib/mesh/live/daemon/unit-home.js +134 -0
  119. package/dist/lib/placement/match.d.ts +192 -0
  120. package/dist/lib/placement/match.js +667 -0
  121. package/dist/lib/registry/registry.d.ts +35 -7
  122. package/dist/lib/registry/registry.js +88 -13
  123. package/dist/lib/safe-store.d.ts +14 -0
  124. package/dist/lib/safe-store.js +77 -4
  125. package/dist/lib/scan-packages/index.js +24 -2
  126. package/dist/lib/search-index/index.d.ts +88 -4
  127. package/dist/lib/search-index/index.js +288 -24
  128. package/dist/lib/search-index/max-doc-bytes.d.ts +17 -6
  129. package/dist/lib/search-index/max-doc-bytes.js +49 -23
  130. package/dist/lib/service-manager/startup-migration.d.ts +1 -0
  131. package/dist/lib/service-manager/startup-migration.js +3 -0
  132. package/dist/lib/signals/codex-lockdown.d.ts +79 -0
  133. package/dist/lib/signals/codex-lockdown.js +271 -0
  134. package/dist/lib/signals/codex-login.d.ts +37 -0
  135. package/dist/lib/signals/codex-login.js +83 -0
  136. package/dist/lib/signals/engine.d.ts +27 -0
  137. package/dist/lib/signals/engine.js +70 -0
  138. package/dist/lib/signals/reply.js +22 -1
  139. package/dist/lib/signals/run-record.js +6 -1
  140. package/dist/lib/signals/settings.d.ts +5 -0
  141. package/dist/lib/signals/settings.js +2 -0
  142. package/dist/lib/signals/steps/extract.d.ts +85 -9
  143. package/dist/lib/signals/steps/extract.js +317 -68
  144. package/dist/lib/signals/steps/types.d.ts +2 -0
  145. package/dist/lib/sync-core/engine-holds.d.ts +14 -0
  146. package/dist/lib/sync-core/engine-holds.js +60 -0
  147. package/dist/lib/sync-core/engine-home.d.ts +37 -1
  148. package/dist/lib/sync-core/engine-home.js +119 -16
  149. package/dist/lib/sync-core/reconcile.js +8 -0
  150. package/dist/lib/sync-core/rollout-state.d.ts +2 -1
  151. package/dist/lib/sync-core/rollout-state.js +5 -2
  152. package/dist/lib/sync-core/vault-settings.d.ts +21 -0
  153. package/dist/lib/sync-core/vault-settings.js +131 -0
  154. package/dist/lib/sync-core/vault-uid.d.ts +2 -0
  155. package/dist/lib/sync-core/vault-uid.js +4 -0
  156. package/dist/lib/windows/install-followup.d.ts +2 -0
  157. package/dist/lib/windows/install-followup.js +4 -1
  158. package/dist/schemas/hq-work-requirements.v1.schema.json +145 -0
  159. package/dist/utils/auth-session-check.d.ts +16 -0
  160. package/dist/utils/auth-session-check.js +16 -0
  161. package/dist/utils/client-health-contract.d.ts +6 -0
  162. package/dist/utils/client-health-contract.js +13 -0
  163. package/dist/utils/client-health.d.ts +7 -0
  164. package/dist/utils/client-health.js +22 -1
  165. package/dist/utils/command-usage.d.ts +40 -0
  166. package/dist/utils/command-usage.js +61 -0
  167. package/dist/utils/duplicate-command-usage.d.ts +72 -0
  168. package/dist/utils/duplicate-command-usage.js +125 -0
  169. package/dist/utils/host-registration.js +5 -2
  170. package/dist/utils/pack-contributions.d.ts +3 -0
  171. package/dist/utils/pack-contributions.js +110 -23
  172. package/dist/utils/resident-package-preload.js +4 -0
  173. package/dist/utils/self-update.d.ts +3 -1
  174. package/dist/utils/self-update.js +56 -11
  175. package/dist/utils/sentry-fingerprint.js +9 -0
  176. package/dist/utils/update-lock.d.ts +151 -14
  177. package/dist/utils/update-lock.js +782 -46
  178. package/dist/utils/version-gate.js +12 -2
  179. package/dist/utils/windows-bash.d.ts +2 -0
  180. package/dist/utils/windows-bash.js +2 -1
  181. package/package.json +9 -8
  182. package/scripts/bench-core-compare.mjs +313 -0
  183. package/scripts/bench-core.mjs +399 -12
  184. package/scripts/check-function-manifest.mjs +116 -3
@@ -0,0 +1,300 @@
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+ import { spawnSync } from "node:child_process";
5
+ import { createFlagClient } from "@indigoai-us/hq-flags-client";
6
+ import { loadCachedTokens } from "@indigoai-us/hq-cloud";
7
+ import { resolveFlagRegistryEndpoint } from "../lib/flag-registry-endpoint.js";
8
+ import { executeHqSession } from "./core-hq-session-native.js";
9
+ import { runStopSweep, sweepFileSize } from "../lib/daemon/stop-autosave.js";
10
+ import { openStoreDir } from "../lib/safe-store.js";
11
+ import { describeCoreCommand } from "./core-command-catalog.js";
12
+ import { acquireAutosaveLock, lockParentRefusal } from "../lib/daemon/stop-autosave-lock.js";
13
+ /** The private folder, inside the HQ root, that holds the autosave lock. */
14
+ export const AUTOSAVE_LOCK_FOLDER = "workspace/.autocommit-lock";
15
+ /** Fresh, explicit-company flag read. A missing row or any error stays off. */
16
+ async function sweepEnabled(root, env) {
17
+ let uid = env.HQ_COMPANY_UID?.trim();
18
+ let slug = env.HQ_COMPANY_SLUG?.trim();
19
+ if (!uid || !/^cmp_[A-Za-z0-9]{3,128}$/.test(uid)) {
20
+ const resolved = executeHqSession(["get", "company_slug"], { cwd: root, hqRoot: root }, { env });
21
+ if (resolved.code !== 0)
22
+ return false;
23
+ slug = resolved.stdout.trim();
24
+ if (!slug || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(slug))
25
+ return false;
26
+ try {
27
+ uid = JSON.parse(fs.readFileSync(path.join(root, "companies", slug, ".company.json"), "utf8")).cloud_uid;
28
+ }
29
+ catch {
30
+ return false;
31
+ }
32
+ }
33
+ if (!uid || !/^cmp_[A-Za-z0-9]{3,128}$/.test(uid))
34
+ return false;
35
+ const token = loadCachedTokens()?.idToken;
36
+ if (!token)
37
+ return false;
38
+ let failed = false;
39
+ const client = createFlagClient({ endpoint: resolveFlagRegistryEndpoint(undefined, env), companyUid: uid,
40
+ ...(slug ? { companyIdentifiers: [slug] } : {}), env: {}, getToken: () => token,
41
+ refreshIntervalMs: 0, requestTimeoutMs: 150, onError: () => { failed = true; } });
42
+ try {
43
+ await client.ready();
44
+ return !failed && client.snapshot()?.flags["hooks.hq-autocommit-bash-sweep"] === true;
45
+ }
46
+ catch {
47
+ return false;
48
+ }
49
+ finally {
50
+ client.close();
51
+ }
52
+ }
53
+ function indexLockHeld(file, env) {
54
+ // An arbitrary legacy probe cannot be reinterpreted as a native operation.
55
+ if (env.HQ_AUTOCOMMIT_LOCK_PROBE)
56
+ return undefined;
57
+ for (const command of ["/usr/sbin/lsof", "/usr/bin/lsof", "/usr/bin/fuser"]) {
58
+ if (!fs.existsSync(command))
59
+ continue;
60
+ const result = spawnSync(command, [file], { env, timeout: 1000, stdio: "ignore" });
61
+ if (result.error || result.signal)
62
+ return undefined;
63
+ return result.status === 0 ? true : result.status === 1 ? false : undefined;
64
+ }
65
+ return undefined;
66
+ }
67
+ export async function stopAutosave(root, session, env, deps = {}) {
68
+ root = fs.realpathSync(root);
69
+ const now = deps.now ?? Date.now;
70
+ const key = (session || `pid-${process.ppid}`).replace(/[^A-Za-z0-9._-]/g, "_");
71
+ const warnMessage = (marker, message) => {
72
+ const opened = openStoreDir(path.join(root, "workspace/.autocommit-warnings"), { create: true });
73
+ if (!opened.ok)
74
+ return;
75
+ try {
76
+ const name = `${key}.keys`;
77
+ const existing = opened.value.read(name);
78
+ if (existing.ok && existing.value.toString().split("\n").includes(marker))
79
+ return;
80
+ if (!opened.value.appendLine(name, marker).ok)
81
+ return;
82
+ process.stdout.write(message + "\n");
83
+ process.stderr.write(message + "\n");
84
+ }
85
+ finally {
86
+ opened.value.close();
87
+ }
88
+ };
89
+ const warn = (stage, code, relative) => warnMessage(`autocommit|${stage}|${code}`, `WARNING: HQ autosave failed — git ${stage} exited ${code} for '${relative}'. Local HQ edits are NOT being committed until this is resolved. Details: workspace/logs/hq-autocommit.log`);
90
+ const log = (message) => {
91
+ const opened = openStoreDir(path.join(root, "workspace/logs"), { create: true });
92
+ if (!opened.ok)
93
+ return;
94
+ try {
95
+ const configured = Number(env.HQ_AUTOCOMMIT_LOG_MAX_BYTES ?? 1_048_576);
96
+ const limit = Number.isSafeInteger(configured) && configured >= 0 ? configured : 1_048_576;
97
+ const facts = opened.value.stat("hq-autocommit.log");
98
+ if (facts.ok && facts.value.size > limit)
99
+ opened.value.rename("hq-autocommit.log", "hq-autocommit.log.1");
100
+ opened.value.appendLine("hq-autocommit.log", `[${new Date(now()).toISOString().slice(0, 19)}Z] ${message} session=${key}`);
101
+ }
102
+ finally {
103
+ opened.value.close();
104
+ }
105
+ };
106
+ const git = (args) => {
107
+ if (deps.git)
108
+ return deps.git(root, args);
109
+ const result = spawnSync("git", ["-C", root, ...args], {
110
+ env: { ...env, GIT_OPTIONAL_LOCKS: "0" }, encoding: "utf8", timeout: 30_000, maxBuffer: 8 * 1024 * 1024,
111
+ });
112
+ return { code: result.error ? 1 : result.status ?? 1, stdout: result.stdout ?? "", stderr: result.stderr ?? "" };
113
+ };
114
+ const failure = (stage, result, relative) => {
115
+ log(`FAIL stage=${stage} exit=${result.code} path=${relative}`);
116
+ const output = (result.stdout + result.stderr).replace(/\n+$/, "");
117
+ if (output) {
118
+ const opened = openStoreDir(path.join(root, "workspace/logs"), { create: true });
119
+ if (opened.ok) {
120
+ try {
121
+ opened.value.appendLine("hq-autocommit.log", output.split("\n").map(line => ` git: ${line}`).join("\n"));
122
+ }
123
+ finally {
124
+ opened.value.close();
125
+ }
126
+ }
127
+ }
128
+ warn(stage, result.code, relative);
129
+ return env.HQ_AUTOCOMMIT_STRICT === "1" ? 1 : 0;
130
+ };
131
+ const rawMinimum = Number(env.HQ_OFFLOAD_MIN_BYTES);
132
+ const minimum = Number.isSafeInteger(rawMinimum) && rawMinimum > 0 ? rawMinimum : 52_428_800;
133
+ return runStopSweep(root, minimum, {
134
+ git, enabled: deps.enabled ?? (() => sweepEnabled(root, env)), exists: fs.existsSync, size: sweepFileSize, log,
135
+ save: async (relative, hqTop) => {
136
+ if (env.HQ_AUTOCOMMIT === "0")
137
+ return 0;
138
+ const absolute = path.join(root, relative);
139
+ let parent;
140
+ try {
141
+ parent = fs.realpathSync(path.dirname(absolute));
142
+ }
143
+ catch {
144
+ return 0;
145
+ }
146
+ const relativeParent = path.relative(root, parent);
147
+ if (relativeParent === ".." || relativeParent.startsWith(`..${path.sep}`) || path.isAbsolute(relativeParent))
148
+ return 0;
149
+ const nested = deps.git ? deps.git(parent, ["rev-parse", "--show-toplevel"])
150
+ : (() => { const r = spawnSync("git", ["-C", parent, "rev-parse", "--show-toplevel"], { env, encoding: "utf8", timeout: 5000 }); return { code: r.status ?? 1, stdout: r.stdout ?? "" }; })();
151
+ // Two git outputs, as hq-autocommit.sh compares PATH_TOP with HQ_TOP:
152
+ // a git path is never compared with a Node path (they differ on Windows).
153
+ if (nested.code !== 0 || !nested.stdout.trim() || nested.stdout.trim() !== hqTop)
154
+ return 0;
155
+ const staged = git(["diff", "--cached", "--name-only"]);
156
+ if (staged.code !== 0)
157
+ return failure("diff-cached", staged, relative);
158
+ const warningStore = openStoreDir(path.join(root, "workspace/.autocommit-warnings"), { create: true });
159
+ if (staged.stdout.trim()) {
160
+ const count = staged.stdout.trim().split("\n").length;
161
+ log(`SKIP stage=prestaged staged=${count} path=${relative}`);
162
+ if (warningStore.ok) {
163
+ try {
164
+ const current = warningStore.value.read("prestaged-since", { maxBytes: 32 });
165
+ let since = current.ok ? Number(current.value.toString().trim()) : NaN;
166
+ if (!Number.isSafeInteger(since) || since < 0) {
167
+ since = Math.floor(now() / 1000);
168
+ warningStore.value.writeAtomic("prestaged-since", `${since}\n`);
169
+ }
170
+ const raw = env.HQ_AUTOCOMMIT_PRESTAGED_STALE_MINUTES ?? "10";
171
+ const minutes = /^\d+$/.test(raw) ? Number(raw) : 10;
172
+ if (Math.floor(now() / 1000) - since >= minutes * 60)
173
+ warnMessage("autocommit|prestaged", `WARNING: HQ autosave is skipping edits because the HQ git index already has ${count} staged path(s) that nobody has committed. Local HQ edits are NOT being committed until those paths are committed or unstaged (see: git diff --cached --name-only). Details: workspace/logs/hq-autocommit.log`);
174
+ }
175
+ finally {
176
+ warningStore.value.close();
177
+ }
178
+ }
179
+ return 0;
180
+ }
181
+ if (warningStore.ok) {
182
+ warningStore.value.remove("prestaged-since");
183
+ warningStore.value.close();
184
+ }
185
+ const rawStale = Number(env.HQ_AUTOCOMMIT_STALE_LOCK_MINUTES ?? 5);
186
+ const staleMinutes = Number.isFinite(rawStale) && rawStale >= 0 ? rawStale : 5;
187
+ // A refused lock folder is said where it is seen: the daemon runs this
188
+ // job with its output discarded, so the log is the durable record.
189
+ const refusedLock = (what) => {
190
+ log(`SKIP stage=lock reason=${JSON.stringify(what)} path=${relative}`);
191
+ process.stderr.write(`HQ autosave: ${what}\n`);
192
+ };
193
+ // The autosave lock lives in a private folder of this HQ root, never
194
+ // in a shared temporary folder that the store checks would refuse.
195
+ const lockFolder = openStoreDir(path.join(root, AUTOSAVE_LOCK_FOLDER), { create: true });
196
+ if (!lockFolder.ok) {
197
+ refusedLock(`autosave lock folder refused (${lockFolder.code}); local HQ edits are not being committed`);
198
+ return 0;
199
+ }
200
+ lockFolder.value.close();
201
+ const held = acquireAutosaveLock(path.join(root, AUTOSAVE_LOCK_FOLDER, "hq-autocommit.lock"), now(), staleMinutes);
202
+ if (!held)
203
+ return 0;
204
+ if (held.recovered)
205
+ log(`RECOVER stage=lock path=${relative}`);
206
+ // The shell autosave (hq-autocommit.sh) still takes
207
+ // ${TMPDIR:-/tmp}/hq-autocommit.lock; this job holds that lock too
208
+ // while it can, so the two never commit at once. A shared folder that
209
+ // cannot hold it safely is reported, and the private lock alone runs.
210
+ const sharedLock = path.join(env.TMPDIR || os.tmpdir(), "hq-autocommit.lock");
211
+ const sharedRefusal = lockParentRefusal(sharedLock);
212
+ let shared;
213
+ if (sharedRefusal)
214
+ refusedLock(`shared autosave ${sharedRefusal}; continuing with the private lock only`);
215
+ else {
216
+ shared = acquireAutosaveLock(sharedLock, now(), staleMinutes);
217
+ if (!shared) {
218
+ held.release();
219
+ return 0;
220
+ }
221
+ if (shared.recovered)
222
+ log(`RECOVER stage=lock path=${relative}`);
223
+ }
224
+ try {
225
+ const lockPath = git(["rev-parse", "--git-path", "index.lock"]);
226
+ if (lockPath.code === 0 && lockPath.stdout.trim()) {
227
+ const indexLock = path.resolve(root, lockPath.stdout.trim());
228
+ const within = path.relative(root, indexLock);
229
+ if (within !== ".." && !within.startsWith(`..${path.sep}`) && !path.isAbsolute(within)) {
230
+ const indexStore = openStoreDir(path.dirname(indexLock));
231
+ if (indexStore.ok) {
232
+ try {
233
+ const facts = indexStore.value.stat(path.basename(indexLock));
234
+ if (facts.ok && now() - facts.value.mtimeMs > (Number.isFinite(rawStale) && rawStale >= 0 ? rawStale : 5) * 60_000
235
+ && (deps.indexLockHeld ?? (file => indexLockHeld(file, env)))(indexLock) === false) {
236
+ const removed = indexStore.value.remove(path.basename(indexLock));
237
+ if (removed.ok && removed.value)
238
+ log(`RECOVER stage=index-lock path=${relative}`);
239
+ }
240
+ }
241
+ finally {
242
+ indexStore.value.close();
243
+ }
244
+ }
245
+ }
246
+ }
247
+ // Recheck after acquiring the shared autosave lock. A user's staged
248
+ // work must never be included in this commit.
249
+ const before = git(["diff", "--cached", "--name-only", "-z"]);
250
+ if (before.code !== 0 || before.stdout)
251
+ return 0;
252
+ let add = git(["add", "--", relative]);
253
+ for (let retry = 0; add.code !== 0 && retry < 3 && add.stderr.includes("index.lock") && add.stderr.includes("File exists"); retry++) {
254
+ await new Promise(resolve => setTimeout(resolve, 200));
255
+ add = git(["add", "--", relative]);
256
+ }
257
+ if (add.code !== 0)
258
+ return failure("add", add, relative);
259
+ const after = git(["diff", "--cached", "--name-only", "-z"]);
260
+ if (after.code !== 0)
261
+ return 0;
262
+ const paths = after.stdout.split("\0").filter(Boolean);
263
+ if (paths.some(name => name !== relative)) {
264
+ git(["reset", "-q", "--", relative]);
265
+ log(`SKIP stage=foreign-staged path=${relative}`);
266
+ return 0;
267
+ }
268
+ const mode = git(["ls-files", "--stage", "--", relative]);
269
+ if (mode.code !== 0 || /^160000 /m.test(mode.stdout)) {
270
+ git(["reset", "-q", "--", relative]);
271
+ return 0;
272
+ }
273
+ const changed = git(["diff", "--cached", "--quiet", "--", relative]);
274
+ if (changed.code !== 1)
275
+ return 0;
276
+ const display = relative.length > 72 ? relative.slice(0, 69) + "..." : relative;
277
+ const commit = git(["-c", "gc.auto=0", "-c", "maintenance.auto=false", "commit", "--no-verify", "-m", `autosave(hq): ${display}`]);
278
+ if (commit.code !== 0)
279
+ return failure("commit", commit, relative);
280
+ return 0;
281
+ }
282
+ finally {
283
+ shared?.release();
284
+ held.release();
285
+ }
286
+ },
287
+ });
288
+ }
289
+ export function registerCoreStopAutosave(core) {
290
+ const command = core.command("stop-autosave").description("Drain the typed Stop autosave job")
291
+ .requiredOption("--session-id <id>")
292
+ .action(async (options) => {
293
+ const root = core.opts().hqRoot || process.env.CLAUDE_PROJECT_DIR || process.env.HQ_ROOT;
294
+ if (!root)
295
+ throw new Error("Stop autosave requires an HQ root");
296
+ process.exitCode = await stopAutosave(root, options.sessionId, process.env);
297
+ });
298
+ describeCoreCommand(command, { execution: "native", root: "live" });
299
+ }
300
+ //# sourceMappingURL=core-stop-autosave.js.map
@@ -31,6 +31,7 @@
31
31
  import { Option } from "commander";
32
32
  import { registerCoreHookRegistrationPlan } from "./core-hook-registration-plan.js";
33
33
  import { registerCoreCheckpointCommand } from "./core-checkpoint.js";
34
+ import { registerCoreStopAutosave } from "./core-stop-autosave.js";
34
35
  import { runHookEnginePath } from '../hook-engine-path.js';
35
36
  import { registerCoreDelegateCommand } from "./core-delegate.js";
36
37
  import { registerCoreDelegateW1b } from "./core-delegate-w1b.js";
@@ -451,6 +452,7 @@ export function registerCoreCommands(program) {
451
452
  });
452
453
  describeCoreCommand(machineCheckOwnerCommand, { execution: "native", root: "cwd" });
453
454
  registerCoreCheckpointCommand(core);
455
+ registerCoreStopAutosave(core);
454
456
  registerCoreHookRegistrationPlan(core);
455
457
  const hookEnginePath = core.command('hook-engine-path')
456
458
  .description('Print the offline, version-pinned native hook engine path')
@@ -27,6 +27,7 @@ export declare function loadDaemonRunner(release?: () => void, load?: () => Prom
27
27
  export interface DaemonCommandDeps {
28
28
  env: NodeJS.ProcessEnv;
29
29
  home: string;
30
+ loginHome?: string;
30
31
  platform: NodeJS.Platform;
31
32
  out: (line: string) => void;
32
33
  err: (line: string) => void;
@@ -57,6 +58,11 @@ export interface DaemonCommandDeps {
57
58
  runtimeAllowed?: () => boolean | Promise<boolean>;
58
59
  /** Test seam for the company sync-mode commands. */
59
60
  syncModeClient?: () => Promise<SyncModeVaultClient>;
61
+ /**
62
+ * Test seam for the deleted-company notice `hq daemon sync mode list`
63
+ * prints to stderr when there are no memberships (as `hq sync mode --show` does).
64
+ */
65
+ deletedCompanyNotices?: () => Promise<void>;
60
66
  /** Reads stdin for the one-shot daemon machine login; never reads env or argv credentials. */
61
67
  readStdin?: () => Promise<string>;
62
68
  windowsUser?: string;
@@ -17,6 +17,8 @@
17
17
  import * as fs from "node:fs";
18
18
  import * as os from "node:os";
19
19
  import * as path from "node:path";
20
+ import { SYNC_WAKE_STATE_BASENAME, workMeshRoot } from "../lib/mesh/live/paths.js";
21
+ import { homeIsLoginSafe, meshJobLoadedForHome } from "../lib/mesh/live/daemon/unit-home.js";
20
22
  import { randomBytes } from "node:crypto";
21
23
  import { spawn, spawnSync } from "node:child_process";
22
24
  import { once } from "node:events";
@@ -41,7 +43,7 @@ import { runDaemonCall } from "../lib/daemon/command-call.js";
41
43
  import { acknowledgeConflictNotice, conflictNoticeStateDir } from "../lib/daemon/conflict-notices.js";
42
44
  import { isSyncRunnerCommandLine, readWatchRunnerOwnerStatus, syncRunnerPathFromCommandLine, watchRunnerOwnerStatusPath } from "../lib/daemon/sync-runner.js";
43
45
  import { stagedSyncRunnerVersion, syncRunnerBundleStageRoot } from "../lib/daemon/sync-runner-bundle.js";
44
- import { getSyncModeForCompany, setSyncMode } from "./sync-mode.js";
46
+ import { formatShowTable, getSyncModeForCompany, parseCustomPaths, setSyncMode, showSyncModes, validateMode, } from "./sync-mode.js";
45
47
  import { assertSafeCompanySlug } from "../utils/people.js";
46
48
  import { anywhereRuntimeAllowed } from "../lib/anywhere-person-setting.js";
47
49
  import { hqdRequest, hqdSocketPath, HqdClientError } from "../lib/daemon/protocol.js";
@@ -110,6 +112,7 @@ async function loadDefaults(over) {
110
112
  return {
111
113
  env,
112
114
  home,
115
+ loginHome: over.loginHome,
113
116
  platform,
114
117
  out: over.out ?? ((l) => console.log(l)),
115
118
  err: over.err ?? ((l) => console.error(l)),
@@ -134,7 +137,8 @@ async function loadDefaults(over) {
134
137
  home: dir ?? home,
135
138
  existsSync: fs.existsSync,
136
139
  listDir: (dir) => fs.readdirSync(dir),
137
- launchdJobLoaded: (label) => run("launchctl", ["print", `gui/${process.getuid?.() ?? 0}/${label}`]).status === 0,
140
+ launchdJobLoaded: (label) => meshJobLoadedForHome(run("launchctl", ["print", `gui/${process.getuid?.() ?? 0}/${label}`]), dir ?? home),
141
+ homeIsLogin: platform === "darwin" ? homeIsLoginSafe(dir ?? home) : true,
138
142
  windowsTaskOwner: (task) => classifyWindowsTask(run, task, {
139
143
  windowsSid: over.windowsSid ?? readWindowsSid(run),
140
144
  windowsUser: over.windowsUser ?? mesh.resolveWindowsUser(env),
@@ -211,6 +215,7 @@ function hostFor(d, paths, pathEnv) {
211
215
  windowsHeadlessLauncher: d.windowsHeadlessLauncher,
212
216
  systemUnitDir: d.systemUnitDir ?? SYSTEM_UNIT_DIR,
213
217
  env,
218
+ loginHome: d.loginHome,
214
219
  };
215
220
  }
216
221
  /**
@@ -919,13 +924,28 @@ async function runDaemonSyncModeGet(d, companySlug, opts) {
919
924
  };
920
925
  d.out(opts.json ? JSON.stringify(value, null, 2) : `${value.companySlug}: ${value.mode}${value.isDefault ? " (default)" : ""}`);
921
926
  }
922
- async function runDaemonSyncModeSet(d, companySlug, mode, opts) {
923
- if (mode !== "all" && mode !== "shared") {
924
- throw new DaemonCommandError(`Invalid sync mode '${mode}'. Use all or shared.`);
925
- }
927
+ async function runDaemonSyncModeList(d, opts) {
928
+ // Same rows, columns and order as `hq sync mode --show`.
929
+ const rows = await showSyncModes({ vaultClient: await daemonSyncModeClient(d) });
930
+ d.out(opts.json ? JSON.stringify(rows, null, 2) : formatShowTable(rows));
931
+ // No memberships may mean the person's company was deleted (stderr only).
932
+ if (rows.length === 0)
933
+ await daemonDeletedCompanyNotices(d);
934
+ }
935
+ async function daemonDeletedCompanyNotices(d) {
936
+ if (d.deletedCompanyNotices)
937
+ return d.deletedCompanyNotices();
938
+ const { printDeletedCompanyNotices } = await import("../utils/deleted-company-notice.js");
939
+ await printDeletedCompanyNotices({ write: (line) => d.err(line) });
940
+ }
941
+ async function runDaemonSyncModeSet(d, companySlug, modeArg, opts) {
942
+ // Same validation and write as `hq sync mode <mode> --company <slug> [--paths <csv>]`.
943
+ const mode = validateMode(modeArg);
944
+ const customPaths = parseCustomPaths(opts.paths);
926
945
  const result = await setSyncMode({
927
946
  mode,
928
947
  companySlug,
948
+ customPaths,
929
949
  vaultClient: await daemonSyncModeClient(d),
930
950
  });
931
951
  const value = {
@@ -934,6 +954,9 @@ async function runDaemonSyncModeSet(d, companySlug, mode, opts) {
934
954
  previousMode: result.previousMode,
935
955
  mode: result.newMode,
936
956
  isDefault: result.newConfig.isDefault,
957
+ ...(result.newConfig.customPaths && result.newConfig.customPaths.length > 0
958
+ ? { customPaths: result.newConfig.customPaths }
959
+ : {}),
937
960
  ...(result.newConfig.updatedAt ? { updatedAt: result.newConfig.updatedAt } : {}),
938
961
  };
939
962
  d.out(opts.json ? JSON.stringify(value, null, 2) : `${value.companySlug}: ${value.previousMode} → ${value.mode}`);
@@ -1757,14 +1780,20 @@ export function registerDaemonCommand(program, over = {}) {
1757
1780
  .option("--json", "Print machine-readable JSON")
1758
1781
  .action(wrap((d, opts) => runDaemonSyncTakeOwnership(d, opts)));
1759
1782
  const mode = sync.command("mode").description("Read or change a company's sync footprint");
1783
+ mode
1784
+ .command("list")
1785
+ .description("List every membership's company and current sync mode (same table as `hq sync mode --show`)")
1786
+ .option("--json", "Print machine-readable JSON")
1787
+ .action(wrap((d, opts) => runDaemonSyncModeList(d, opts)));
1760
1788
  mode
1761
1789
  .command("get <company>")
1762
- .description("Read a company's current all/shared sync mode")
1790
+ .description("Read a company's current sync mode")
1763
1791
  .option("--json", "Print machine-readable JSON")
1764
1792
  .action(wrap((d, company, opts) => runDaemonSyncModeGet(d, company, opts)));
1765
1793
  mode
1766
1794
  .command("set <company> <mode>")
1767
- .description("Set a company's sync mode to all or shared")
1795
+ .description("Set a company's sync mode to shared, all or custom")
1796
+ .option("--paths <csv>", "Comma-separated allowed prefixes (required when mode is 'custom')")
1768
1797
  .option("--json", "Print machine-readable JSON")
1769
1798
  .action(wrap((d, company, mode, opts) => runDaemonSyncModeSet(d, company, mode, opts)));
1770
1799
  daemon
@@ -1910,6 +1939,15 @@ export function registerDaemonCommand(program, over = {}) {
1910
1939
  }
1911
1940
  },
1912
1941
  sendToOwner: (message) => sendDmToMachineOwner(message),
1942
+ wake: {
1943
+ markerPath: path.join(workMeshRoot(d.home, d.env), SYNC_WAKE_STATE_BASENAME),
1944
+ watchPath: path.join(paths.root, "selfcheck-wake.json"),
1945
+ meshWanted: () => {
1946
+ const config = readDaemonConfig(paths.configPath);
1947
+ const { detected } = currentHost(d);
1948
+ return enabledServices(detected.type, config).includes("mesh");
1949
+ },
1950
+ },
1913
1951
  ...(await selfCheckVaults(d.home)),
1914
1952
  log: (line) => d.out(line),
1915
1953
  });
@@ -2,6 +2,11 @@
2
2
  * `hq doctor usage` — counts per command for the last 30 days, read from the
3
3
  * local usage file (utils/command-usage.ts). It reads one small folder under
4
4
  * `~/.hq` and sends nothing.
5
+ *
6
+ * `hq doctor usage --duplicates [--since <window>]` lists the duplicate
7
+ * command paths (utils/duplicate-command-usage.ts) with their runs in the
8
+ * window. It exits 0 when none ran, 1 when one did, and 2 when the count
9
+ * cannot be read or the window is not valid.
5
10
  */
6
11
  import type { Command } from "commander";
7
12
  export declare function registerDoctorUsageCommand(doctor: Command): void;
@@ -2,17 +2,42 @@
2
2
  * `hq doctor usage` — counts per command for the last 30 days, read from the
3
3
  * local usage file (utils/command-usage.ts). It reads one small folder under
4
4
  * `~/.hq` and sends nothing.
5
+ *
6
+ * `hq doctor usage --duplicates [--since <window>]` lists the duplicate
7
+ * command paths (utils/duplicate-command-usage.ts) with their runs in the
8
+ * window. It exits 0 when none ran, 1 when one did, and 2 when the count
9
+ * cannot be read or the window is not valid.
5
10
  */
6
11
  import { COMMAND_USAGE_WINDOW_DAYS, readCommandUsage, renderCommandUsageText, } from "../utils/command-usage.js";
12
+ import { DEFAULT_SINCE, duplicateUsageExitCode, MAX_SINCE_HOURS, parseSince, readDuplicateUsage, renderDuplicateUsageText, } from "../utils/duplicate-command-usage.js";
7
13
  export function registerDoctorUsageCommand(doctor) {
8
14
  doctor
9
15
  .command("usage")
10
16
  .description(`Show how many times each command ran on this computer in the last ${COMMAND_USAGE_WINDOW_DAYS} days (a local file that is never sent).`)
11
17
  .option("--json", "Emit the counts as JSON.")
18
+ .option("--duplicates", "List only the duplicate commands and their runs in the window; exit 0 when none ran, 1 when one did, 2 when the count cannot be read.")
19
+ .option("--since <window>", `Window for --duplicates: Nh or Nd, at most ${MAX_SINCE_HOURS / 24}d (default ${DEFAULT_SINCE}). Counts are per UTC date, so whole dates are counted.`)
12
20
  .action((opts, command) => {
13
21
  // `hq doctor` declares --json too, and Commander stores the flag on
14
22
  // whichever of the two commands it reaches first. Read the merged set.
15
23
  const json = opts.json === true || command.optsWithGlobals().json === true;
24
+ if (opts.since !== undefined && opts.duplicates !== true) {
25
+ process.stderr.write("hq doctor usage: --since needs --duplicates\n");
26
+ process.exitCode = 2;
27
+ return;
28
+ }
29
+ if (opts.duplicates === true) {
30
+ const since = opts.since ?? DEFAULT_SINCE;
31
+ if (parseSince(since) === null) {
32
+ process.stderr.write(`hq doctor usage: --since must be Nh or Nd (N from 1), at most ${MAX_SINCE_HOURS / 24}d; got "${since}"\n`);
33
+ process.exitCode = 2;
34
+ return;
35
+ }
36
+ const report = readDuplicateUsage({ since });
37
+ process.stdout.write(json ? `${JSON.stringify(report, null, 2)}\n` : renderDuplicateUsageText(report));
38
+ process.exitCode = duplicateUsageExitCode(report);
39
+ return;
40
+ }
16
41
  const report = readCommandUsage();
17
42
  process.stdout.write(json ? `${JSON.stringify(report, null, 2)}\n` : renderCommandUsageText(report));
18
43
  });
@@ -1,18 +1,63 @@
1
1
  /**
2
2
  * `hq env`: environment profiles (hq-environment-profile.v1).
3
3
  *
4
- * This release has one subcommand, `hq env validate <file>`. It reads one
5
- * file and checks it against the schema. The command itself writes nothing,
6
- * calls no service and needs no sign-in; the CLI's usual start-up state files
7
- * are still written, as for every hq command.
4
+ * `hq env validate <file>` reads one file and checks it against the schema.
5
+ * It writes nothing, calls no service and needs no sign-in; the CLI's usual
6
+ * start-up state files are still written, as for every hq command.
7
+ *
8
+ * `hq env probe` runs access probes by name (vault grant, repo, secret,
9
+ * integration, local data, and optionally `hq agent probe`) and prints them
10
+ * as readings.access entries. A secret is resolved only inside a child of
11
+ * `hq secrets exec`, which checks its length and prints nothing; no value
12
+ * reaches this process. `--write-profile <file>` stores the readings in an
13
+ * existing profile after validating the result.
14
+ *
15
+ * `hq env match --requirements <file> --profiles <dir>` runs the matcher
16
+ * (src/lib/placement/match.ts): it filters the profiles for one piece of work
17
+ * and prints a first ranking, which the conductor engine reads. It is not a
18
+ * placement; the conductor makes and records the choice. It writes nothing,
19
+ * calls no service and needs no sign-in.
8
20
  */
9
21
  import type { Command } from "commander";
22
+ import type { AccessProbeDeps } from "../lib/environment/access-probes.js";
10
23
  /** A profile is a few kilobytes; nothing larger than this is read. */
11
24
  export declare const ENV_VALIDATE_MAX_BYTES: number;
12
25
  export interface EnvCommandDeps {
13
26
  print: (line: string) => void;
14
27
  printError: (line: string) => void;
15
28
  setExitCode: (code: number) => void;
29
+ /** Test seam for `hq env probe`; defaults to real child processes. */
30
+ probeDeps?: (hqRoot: string) => AccessProbeDeps;
31
+ /** Test seam for the HQ root `hq env probe` reads repos and data under. */
32
+ hqRoot?: () => string;
33
+ /** Test seam: the environment the session lock and agent kit are read from. */
34
+ env?: NodeJS.ProcessEnv;
35
+ /** Test seam: the company of this host's external agent kit, or null. */
36
+ agentCompany?: () => Promise<string | null>;
16
37
  }
17
38
  export declare function registerEnvCommand(program: Command, overrides?: Partial<EnvCommandDeps>): Command;
39
+ type EnvMatchFailureCode = "unreadable" | "too_large" | "invalid_requirements" | "invalid_profile" | "invalid_now";
40
+ export type EnvMatchRun = {
41
+ ok: true;
42
+ match: import("../lib/placement/match.js").MatchResult;
43
+ profilesRead: number;
44
+ } | {
45
+ ok: false;
46
+ code: EnvMatchFailureCode;
47
+ message: string;
48
+ issues: string[];
49
+ };
50
+ /**
51
+ * Load the requirements and every profile in the directory, then call the
52
+ * matcher library. All I/O for `hq env match` is here; match() itself reads
53
+ * nothing.
54
+ */
55
+ export declare function runEnvMatch(opts: {
56
+ requirements: string;
57
+ profiles: string;
58
+ now?: string;
59
+ }): Promise<EnvMatchRun>;
60
+ /** A profile file: *.json, not a dotfile (which covers AppleDouble "._*" files). */
61
+ export declare function isProfileFileName(name: string): boolean;
62
+ export {};
18
63
  //# sourceMappingURL=env.d.ts.map