@indigoai-us/hq-cli 5.345.250 → 5.345.252

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 (186) hide show
  1. package/CHANGELOG.md +214 -0
  2. package/assets/scaffold/core/scripts/hq-session.sh +9 -0
  3. package/contracts/host-canary-release.json +9 -3
  4. package/dist/command-catalog.generated.d.ts +316 -2
  5. package/dist/command-catalog.generated.js +389 -2
  6. package/dist/commands/bot.js +12 -3
  7. package/dist/commands/core-bucket-c-work-mesh-offer-native.js +1 -1
  8. package/dist/commands/core-hq-session-binding.d.ts +140 -0
  9. package/dist/commands/core-hq-session-binding.js +363 -0
  10. package/dist/commands/core-hq-session-native.d.ts +23 -0
  11. package/dist/commands/core-hq-session-native.js +59 -9
  12. package/dist/commands/core-stop-autosave.js +1 -1
  13. package/dist/commands/core.js +10 -0
  14. package/dist/commands/doctor.d.ts +5 -1
  15. package/dist/commands/doctor.js +42 -5
  16. package/dist/commands/files.js +1 -1
  17. package/dist/commands/install-global.js +4 -2
  18. package/dist/commands/lanes.d.ts +2 -0
  19. package/dist/commands/lanes.js +9 -4
  20. package/dist/commands/logout.js +4 -0
  21. package/dist/commands/ontology-graph.d.ts +11 -2
  22. package/dist/commands/ontology-graph.js +130 -4
  23. package/dist/commands/report.js +35 -2
  24. package/dist/commands/sources.js +26 -8
  25. package/dist/commands/storage-gate.js +1 -1
  26. package/dist/commands/vault-retention-flag.js +2 -1
  27. package/dist/commands/whoami.js +1 -1
  28. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +238 -221
  29. package/dist/hq-cloud-sync-runner/package.json +1 -1
  30. package/dist/index.js +3 -1
  31. package/dist/lib/agent-kit/inbox-poll-backoff-flag.js +1 -1
  32. package/dist/lib/agent-kit/mcp/tools.js +48 -0
  33. package/dist/lib/bot/fleet-bots-update-pass.js +1 -1
  34. package/dist/lib/bot/fleet-cron.d.ts +37 -0
  35. package/dist/lib/bot/fleet-cron.js +59 -12
  36. package/dist/lib/bot/fleet-local.d.ts +18 -0
  37. package/dist/lib/bot/fleet-local.js +51 -5
  38. package/dist/lib/bot/inbox-poll-backoff-flag.js +1 -1
  39. package/dist/lib/bot/signals-engine-flag.d.ts +1 -1
  40. package/dist/lib/bot/signals-engine-flag.js +1 -1
  41. package/dist/lib/cli-invite-nudge.js +1 -1
  42. package/dist/lib/client-version.d.ts +2 -0
  43. package/dist/lib/client-version.js +24 -0
  44. package/dist/lib/company-flag-gate.d.ts +30 -0
  45. package/dist/lib/company-flag-gate.js +104 -0
  46. package/dist/lib/core-utils/hook-timeout-debug-context-flag.js +1 -1
  47. package/dist/lib/daemon/flag.js +2 -1
  48. package/dist/lib/daemon/legacy-journal-gate.js +3 -1
  49. package/dist/lib/daemon/shared-flag-reads.js +1 -1
  50. package/dist/lib/doctor/checks/host-core.js +22 -4
  51. package/dist/lib/doctor/checks/jq.d.ts +27 -6
  52. package/dist/lib/doctor/checks/jq.js +46 -8
  53. package/dist/lib/doctor/client-health-reason-codes-flag.js +1 -1
  54. package/dist/lib/doctor/fix/refresh-sync-handoff.d.ts +1 -1
  55. package/dist/lib/doctor/fix/refresh-sync-handoff.js +1 -1
  56. package/dist/lib/flag-client-gate-headers.d.ts +38 -0
  57. package/dist/lib/flag-client-gate-headers.js +62 -0
  58. package/dist/lib/flag-client-headers.d.ts +15 -0
  59. package/dist/lib/flag-client-headers.js +25 -0
  60. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  61. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  62. package/dist/lib/flag-registry-worker.js +35 -0
  63. package/dist/lib/flag-registry.d.ts +1 -20
  64. package/dist/lib/flag-registry.js +5 -81
  65. package/dist/lib/hook-engine/adapter-core-pin.d.ts +29 -0
  66. package/dist/lib/hook-engine/adapter-core-pin.js +29 -0
  67. package/dist/lib/hook-engine/coverage.d.ts +68 -8
  68. package/dist/lib/hook-engine/coverage.js +167 -25
  69. package/dist/lib/hook-engine/native-stop-compatibility.json +9 -4
  70. package/dist/lib/hook-engine/reconcile.js +3 -2
  71. package/dist/lib/hot-channels/graph-context.d.ts +26 -1
  72. package/dist/lib/hot-channels/graph-context.js +76 -9
  73. package/dist/lib/hot-channels/prompts/signals-pass.md +20 -0
  74. package/dist/lib/hot-channels/run.d.ts +1 -0
  75. package/dist/lib/hot-channels/signal-changes.d.ts +228 -0
  76. package/dist/lib/hot-channels/signal-changes.js +683 -0
  77. package/dist/lib/hot-channels/signals-pass.d.ts +24 -0
  78. package/dist/lib/hot-channels/signals-pass.js +240 -15
  79. package/dist/lib/lanes/outpost-worktree-pruner-flag.d.ts +1 -1
  80. package/dist/lib/lanes/outpost-worktree-pruner-flag.js +1 -1
  81. package/dist/lib/lanes/registry-flag.js +2 -1
  82. package/dist/lib/lanes/spawn.js +11 -1
  83. package/dist/lib/mesh/live/binding-intent.d.ts +61 -0
  84. package/dist/lib/mesh/live/binding-intent.js +201 -0
  85. package/dist/lib/mesh/live/binding-receipt.d.ts +157 -0
  86. package/dist/lib/mesh/live/binding-receipt.js +365 -0
  87. package/dist/lib/mesh/live/company-flag-refresh.js +1 -1
  88. package/dist/lib/mesh/live/daemon/doctor-telemetry.d.ts +39 -0
  89. package/dist/lib/mesh/live/daemon/doctor-telemetry.js +58 -0
  90. package/dist/lib/mesh/live/daemon/install.js +2 -1
  91. package/dist/lib/mesh/live/daemon/presence.js +9 -0
  92. package/dist/lib/mesh/live/daemon/run.d.ts +3 -0
  93. package/dist/lib/mesh/live/daemon/run.js +33 -1
  94. package/dist/lib/ontology-graph/lineage/index.d.ts +401 -0
  95. package/dist/lib/ontology-graph/lineage/index.js +1027 -0
  96. package/dist/lib/ontology-graph/model/files.d.ts +4 -0
  97. package/dist/lib/ontology-graph/model/files.js +23 -0
  98. package/dist/lib/ontology-graph/model/index.d.ts +65 -1
  99. package/dist/lib/ontology-graph/model/index.js +154 -18
  100. package/dist/lib/ontology-graph/model/pass-tasks.d.ts +84 -1
  101. package/dist/lib/ontology-graph/model/pass-tasks.js +173 -4
  102. package/dist/lib/ontology-graph/model/pass.d.ts +11 -0
  103. package/dist/lib/ontology-graph/model/pass.js +17 -10
  104. package/dist/lib/ontology-graph/model/pending-items.d.ts +39 -0
  105. package/dist/lib/ontology-graph/model/pending-items.js +136 -0
  106. package/dist/lib/ontology-graph/model/step.d.ts +47 -2
  107. package/dist/lib/ontology-graph/model/step.js +202 -36
  108. package/dist/lib/ontology-graph/model/tasks.d.ts +28 -4
  109. package/dist/lib/ontology-graph/model/tasks.js +48 -15
  110. package/dist/lib/ontology-graph/pages/render.d.ts +1 -1
  111. package/dist/lib/ontology-graph/pages/render.js +4 -3
  112. package/dist/lib/ontology-graph/read/brief.d.ts +13 -3
  113. package/dist/lib/ontology-graph/read/brief.js +349 -67
  114. package/dist/lib/ontology-graph/read/index.d.ts +5 -1
  115. package/dist/lib/ontology-graph/read/index.js +174 -30
  116. package/dist/lib/ontology-graph/read/lineage.d.ts +101 -0
  117. package/dist/lib/ontology-graph/read/lineage.js +262 -0
  118. package/dist/lib/ontology-graph/read/reader-setting.d.ts +2 -0
  119. package/dist/lib/ontology-graph/read/reader-setting.js +4 -1
  120. package/dist/lib/ontology-graph/remodel/index.d.ts +174 -0
  121. package/dist/lib/ontology-graph/remodel/index.js +450 -0
  122. package/dist/lib/ontology-graph/replay/buffered-store.js +17 -0
  123. package/dist/lib/ontology-graph/replay/engine.d.ts +32 -1
  124. package/dist/lib/ontology-graph/replay/engine.js +213 -8
  125. package/dist/lib/ontology-graph/replay/extractors.d.ts +26 -0
  126. package/dist/lib/ontology-graph/replay/extractors.js +25 -1
  127. package/dist/lib/ontology-graph/replay/index.d.ts +2 -0
  128. package/dist/lib/ontology-graph/replay/index.js +120 -8
  129. package/dist/lib/ontology-graph/replay/signal-changes.d.ts +118 -0
  130. package/dist/lib/ontology-graph/replay/signal-changes.js +687 -0
  131. package/dist/lib/ontology-graph/schema/authority.d.ts +14 -5
  132. package/dist/lib/ontology-graph/schema/authority.js +13 -3
  133. package/dist/lib/ontology-graph/schema/decision-status.d.ts +18 -0
  134. package/dist/lib/ontology-graph/schema/decision-status.js +20 -0
  135. package/dist/lib/ontology-graph/schema/index.d.ts +2 -1
  136. package/dist/lib/ontology-graph/schema/index.js +2 -1
  137. package/dist/lib/ontology-graph/setup/index.d.ts +88 -0
  138. package/dist/lib/ontology-graph/setup/index.js +499 -0
  139. package/dist/lib/ontology-graph/types.d.ts +21 -0
  140. package/dist/lib/ontology-graph/types.js +5 -0
  141. package/dist/lib/search-index/index.d.ts +33 -1
  142. package/dist/lib/search-index/index.js +180 -25
  143. package/dist/lib/search-index/qmd-exit-diagnostics.d.ts +7 -0
  144. package/dist/lib/search-index/qmd-exit-diagnostics.js +25 -1
  145. package/dist/lib/signals/adapters-catalog.js +1 -1
  146. package/dist/lib/signals/failure-alert.js +4 -5
  147. package/dist/lib/signals/steps/adapters.js +3 -0
  148. package/dist/lib/sync-core/engine-holds.d.ts +1 -0
  149. package/dist/lib/sync-core/engine-holds.js +26 -0
  150. package/dist/lib/sync-core/engine-home.d.ts +3 -0
  151. package/dist/lib/sync-core/engine-home.js +41 -1
  152. package/dist/lib/sync-core/flag.js +2 -1
  153. package/dist/lib/sync-core/legacy-journal-export-child.js +5 -3
  154. package/dist/lib/sync-core/legacy-journal-export.d.ts +23 -4
  155. package/dist/lib/sync-core/legacy-journal-export.js +120 -55
  156. package/dist/lib/sync-core/reconcile.d.ts +2 -1
  157. package/dist/lib/sync-core/reconcile.js +30 -5
  158. package/dist/lib/sync-invalid-entity-warning.js +2 -1
  159. package/dist/lib/windows/install-followup.d.ts +41 -0
  160. package/dist/lib/windows/install-followup.js +87 -0
  161. package/dist/lib/windows/jq.d.ts +59 -0
  162. package/dist/lib/windows/jq.js +154 -3
  163. package/dist/lib/windows/user-path.d.ts +5 -0
  164. package/dist/lib/windows/user-path.js +1 -1
  165. package/dist/lib/work-context/auto-bind.d.ts +12 -0
  166. package/dist/lib/work-context/auto-bind.js +49 -3
  167. package/dist/lib/work-context/organize.d.ts +4 -2
  168. package/dist/lib/work-context/organize.js +18 -8
  169. package/dist/lib/work-context/reconcile.js +16 -1
  170. package/dist/main.js +12 -1
  171. package/dist/utils/client-health-contract.d.ts +30 -0
  172. package/dist/utils/client-health-contract.js +111 -0
  173. package/dist/utils/client-health.d.ts +5 -2
  174. package/dist/utils/client-health.js +74 -5
  175. package/dist/utils/exclusive-lock.d.ts +5 -1
  176. package/dist/utils/exclusive-lock.js +9 -2
  177. package/dist/utils/host-registration.d.ts +7 -0
  178. package/dist/utils/host-registration.js +10 -1
  179. package/dist/utils/pid.d.ts +31 -0
  180. package/dist/utils/pid.js +65 -0
  181. package/dist/utils/resident-package-preload.js +12 -4
  182. package/dist/utils/sentry-fingerprint.js +3 -0
  183. package/dist/utils/sync-person.d.ts +15 -0
  184. package/dist/utils/sync-person.js +74 -0
  185. package/package.json +8 -8
  186. package/scripts/install-hook-engine.mjs +5 -3
@@ -1,6 +1,10 @@
1
+ import * as fs from "node:fs";
1
2
  import { homedir } from "node:os";
2
- import { join } from "node:path";
3
- import { installPinnedJq } from "../jq/install.js";
3
+ import { dirname, join } from "node:path";
4
+ import { findExecutableOnPath } from "../../utils/resolve-executable.js";
5
+ import { installPinnedJq, matchesPinnedJq } from "../jq/install.js";
6
+ import { homeIsLoginSafe } from "../mesh/live/daemon/login-home.js";
7
+ import { READ_PATHS_SCRIPT, USER_PATH_TEST_KEY_ENV, defaultPowerShell, expandWindowsEnv, npmShimDir, parseReadPathsOutput, pathFixCommand, powershellUserPathStore, } from "./user-path.js";
4
8
  const version = "1.8.2";
5
9
  const release = `https://github.com/jqlang/jq/releases/download/jq-${version}`;
6
10
  export const WINDOWS_JQ_REPAIR = "hq doctor --fix-jq";
@@ -24,7 +28,9 @@ export function windowsJqAsset(arch) {
24
28
  return asset ? { url: `${release}/${asset.name}`, sha256: asset.sha256 } : null;
25
29
  }
26
30
  export function windowsJqPath(home = homedir()) {
27
- // hq-core-staging #2047 adds this directory to hook PATH when it holds jq.exe.
31
+ // hq-core-staging #2047 (first released in hq-core 16.0.51) adds this
32
+ // directory to hook PATH when it holds jq.exe. Older hooks search only the
33
+ // inherited PATH, so ensureWindowsJq also puts the directory on the user PATH.
28
34
  return join(home, ".local", "bin", "jq.exe");
29
35
  }
30
36
  /** The npm lifecycle, global hook setup and doctor use the same Windows installer. */
@@ -40,4 +46,149 @@ export async function installWindowsJq({ platform = process.platform, arch = pro
40
46
  fetch: download,
41
47
  });
42
48
  }
49
+ /**
50
+ * Put the verified jq.exe beside hq.cmd. A terminal or Claude Code session
51
+ * that is already open keeps the PATH it started with, so the user PATH entry
52
+ * does not reach it; the hq shim folder is already on that PATH. Returns the
53
+ * copy's path, or undefined when the folder is outside the home folder, holds
54
+ * a jq.exe HQ did not put there, or cannot be written.
55
+ */
56
+ function copyJqBesideHq(home, source, shimDir, sha256) {
57
+ try {
58
+ const dest = join(shimDir, "jq.exe");
59
+ const pinned = { url: "", sha256 };
60
+ // Also refuses a folder outside the home folder and any link on the way.
61
+ if (matchesPinnedJq(home, dest, pinned))
62
+ return dest;
63
+ if (fs.existsSync(dest))
64
+ return undefined;
65
+ const staged = fs.mkdtempSync(join(shimDir, ".hq-jq-"));
66
+ try {
67
+ const file = join(staged, "jq.exe");
68
+ fs.copyFileSync(source, file, fs.constants.COPYFILE_EXCL);
69
+ if (!matchesPinnedJq(home, file, pinned))
70
+ return undefined;
71
+ fs.renameSync(file, dest);
72
+ }
73
+ finally {
74
+ // A staging folder that cannot be removed must not undo a finished copy.
75
+ try {
76
+ fs.rmSync(staged, { recursive: true, force: true });
77
+ }
78
+ catch {
79
+ // Left behind: an empty `.hq-jq-*` folder, harmless on PATH.
80
+ }
81
+ }
82
+ return dest;
83
+ }
84
+ catch {
85
+ return undefined;
86
+ }
87
+ }
88
+ /**
89
+ * Install the verified jq and make hooks able to find it (hq-cli #3716).
90
+ *
91
+ * Installing alone is not enough: before hq-core 16.0.51 the hook gate
92
+ * searches only the inherited PATH, and `%USERPROFILE%\.local\bin` is not on
93
+ * it by default. Two things make hooks find jq:
94
+ *
95
+ * 1. The folder goes on the user PATH (HKCU only, through the same writer as
96
+ * the npm shim folder, which also tells Explorer the environment changed).
97
+ * Terminals and sessions opened afterwards find jq there.
98
+ * 2. A copy goes beside hq.cmd, a folder already on the PATH of sessions that
99
+ * are open now, so they are unblocked without a restart. A jq.exe already
100
+ * there that is not this pinned build is left alone, so when the pinned
101
+ * version changes the old copy stays until it is removed.
102
+ *
103
+ * This process's own PATH is left as it is: a doctor check in the same process
104
+ * must report what the open terminal sees. The npm postinstall, the first hq
105
+ * command after an install, `hq install-global` and `hq doctor --fix-jq` all
106
+ * call it. Undefined off Windows.
107
+ */
108
+ export async function ensureWindowsJq(options = {}) {
109
+ const { store, env = process.env, loginHome, shimDir, ...install } = options;
110
+ const target = await installWindowsJq(install);
111
+ if (!target)
112
+ return undefined;
113
+ const dir = dirname(target);
114
+ const home = install.home ?? homedir();
115
+ let path;
116
+ // Tests redirect the registry write to a scratch key; the writer below
117
+ // reads the same variable from the same environment.
118
+ const scratchKey = env[USER_PATH_TEST_KEY_ENV];
119
+ if (!scratchKey && !homeIsLoginSafe(home, loginHome)) {
120
+ // USERPROFILE names a scratch folder (a test, a temporary home). The
121
+ // registry is still the real account's, so its PATH is not touched.
122
+ path = "not-login-home";
123
+ }
124
+ else {
125
+ let applied;
126
+ try {
127
+ const writer = store ?? powershellUserPathStore(undefined, scratchKey ? { [USER_PATH_TEST_KEY_ENV]: scratchKey } : {});
128
+ applied = writer.appendUserPath(dir);
129
+ }
130
+ catch {
131
+ applied = { written: false, reason: "write-failed" };
132
+ }
133
+ path = applied.written ? "written" : applied.reason;
134
+ }
135
+ const result = { target, dir, path, onUserPath: path === "written" || path === "present" };
136
+ const beside = shimDir === undefined ? npmShimDir(process.argv[1], fs.existsSync) : shimDir;
137
+ const sha256 = (install.asset ?? assets[install.arch ?? process.arch])?.sha256;
138
+ if (beside && sha256) {
139
+ const sessionTarget = copyJqBesideHq(home, target, beside, sha256);
140
+ if (sessionTarget)
141
+ result.sessionTarget = sessionTarget;
142
+ }
143
+ return result;
144
+ }
145
+ /**
146
+ * The jq a terminal or Claude Code session opened from now on will find: the
147
+ * first jq.exe on the stored machine Path followed by the stored user Path,
148
+ * which is the order Windows builds a new process's PATH in. Undefined when
149
+ * there is none, and also when the registry cannot be read: this process's own
150
+ * PATH is not evidence of what a new session gets.
151
+ */
152
+ export function findJqOnPersistedPath(run = defaultPowerShell, env = process.env) {
153
+ let read;
154
+ try {
155
+ const result = run(READ_PATHS_SCRIPT, {});
156
+ if (result.status !== 0)
157
+ return undefined;
158
+ read = parseReadPathsOutput(result.stdout);
159
+ }
160
+ catch {
161
+ return undefined;
162
+ }
163
+ const stored = [read.machine, read.user].filter((value) => value !== null);
164
+ if (stored.length === 0)
165
+ return undefined;
166
+ // Git Bash runs the hooks: it can run jq.exe but not a jq.cmd or jq.bat.
167
+ return findExecutableOnPath("jq", stored.map((value) => expandWindowsEnv(value, env)).join(";"), "win32", ".exe");
168
+ }
169
+ /**
170
+ * The one step left when `hq doctor --fix-jq` installed jq but its closing
171
+ * check still fails. `check` is the failing jq.on-path result.
172
+ */
173
+ export function jqRemainingStep(ensured, check) {
174
+ if (!ensured.onUserPath) {
175
+ if (ensured.path === "not-login-home") {
176
+ return `${dirname(dirname(ensured.dir))} is not your Windows profile folder, so HQ left your user PATH alone. Run \`${WINDOWS_JQ_REPAIR}\` from a normal terminal, without USERPROFILE or HOME pointed somewhere else.`;
177
+ }
178
+ if (ensured.path === "too-long") {
179
+ return `Your user PATH is too long for HQ to add ${ensured.dir}. Remove an entry you no longer need (Windows Settings, "Edit environment variables for your account"), then run \`${WINDOWS_JQ_REPAIR}\` again.`;
180
+ }
181
+ return [
182
+ `HQ could not add ${ensured.dir} to your user PATH (${ensured.path}). Run this in PowerShell, then open a new terminal and restart Claude Code:`,
183
+ ` ${pathFixCommand(ensured.dir)}`,
184
+ ].join("\n");
185
+ }
186
+ if (check.target && check.target.toLowerCase() !== ensured.target.toLowerCase()) {
187
+ return `Another jq at ${check.target} comes first on PATH and does not work. Remove or rename it, then run \`${WINDOWS_JQ_REPAIR}\` again.`;
188
+ }
189
+ if (check.target) {
190
+ return `The jq HQ installed at ${check.target} does not run. Delete that file, then run \`${WINDOWS_JQ_REPAIR}\` again to download it afresh.`;
191
+ }
192
+ return `Open a new terminal and run \`hq doctor --only jq\`. If it still fails, report it with \`/hq-bug\` and include that output.`;
193
+ }
43
194
  //# sourceMappingURL=jq.js.map
@@ -50,6 +50,11 @@ export declare function readPersistedPath(run: PowerShellRun, env: NodeJS.Proces
50
50
  source: "registry" | "process";
51
51
  };
52
52
  export declare function isDirOnPath(dir: string, pathValue: string): boolean;
53
+ /** Runs a script through Windows PowerShell. The script travels as -EncodedCommand (UTF-16LE), so quoting cannot change it. */
54
+ export declare function defaultPowerShell(script: string, extraEnv: NodeJS.ProcessEnv): {
55
+ status: number | null;
56
+ stdout: string;
57
+ };
53
58
  /** Null when not on Windows or when hq was not installed as an npm global shim. */
54
59
  export declare function checkShimOnPath(deps?: ShimPathDeps): ShimPathCheck | null;
55
60
  /** Dummy user variable set and cleared so Windows tells running programs that the environment changed. */
@@ -108,7 +108,7 @@ export function isDirOnPath(dir, pathValue) {
108
108
  return pathValue.split(";").some((entry) => normalizeDir(entry) === want);
109
109
  }
110
110
  /** Runs a script through Windows PowerShell. The script travels as -EncodedCommand (UTF-16LE), so quoting cannot change it. */
111
- function defaultPowerShell(script, extraEnv) {
111
+ export function defaultPowerShell(script, extraEnv) {
112
112
  const encoded = Buffer.from(script, "utf16le").toString("base64");
113
113
  const result = spawnSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], {
114
114
  encoding: "utf8",
@@ -47,11 +47,21 @@ export declare function findRepoPrdCandidates(input: {
47
47
  branch: string | null;
48
48
  }): AutoBindCandidate[];
49
49
  export declare function autoBindHistoryPath(workContextRoot: string): string;
50
+ /**
51
+ * Whether the Board for this project is archived or completed, read from the
52
+ * local work-mesh project cache (no network). A duplicate Board archived in
53
+ * favor of the canonical one must not keep receiving sessions.
54
+ */
55
+ export declare function projectRetiredInCache(companyUid: string | undefined, projectId: string, cacheRoot?: string): boolean;
56
+ /** Drop every remembered binding to a retired project. Best-effort; never throws. */
57
+ export declare function forgetRetiredPriorBindings(workContextRoot: string, projectId: string): number;
50
58
  export declare function lookupPriorBinding(input: {
51
59
  workContextRoot: string;
52
60
  companySlug: string;
53
61
  identities: string[];
54
62
  branch: string | null;
63
+ /** A remembered project that is retired is forgotten, and the lookup goes on. */
64
+ isRetired?: (projectId: string) => boolean;
55
65
  }): string | null;
56
66
  /** Remember a binding for this repo+branch. Best-effort; never throws. */
57
67
  export declare function recordPriorBinding(input: {
@@ -68,6 +78,8 @@ export declare function decideAutoBind(input: {
68
78
  hqRoot: string;
69
79
  workContextRoot: string;
70
80
  companySlug?: string;
81
+ /** Defaults to the local work-mesh cache's Board lifecycle. */
82
+ isRetired?: (projectId: string) => boolean;
71
83
  }): AutoBindDecision & {
72
84
  git?: GitLocation;
73
85
  identities?: string[];
@@ -11,6 +11,7 @@
11
11
  import * as fs from "node:fs";
12
12
  import * as path from "node:path";
13
13
  import { foreignSessionOwnsLane } from "./lane-bind.js";
14
+ import { isSafeCacheSegment, meshCacheRoot } from "../mesh/cache.js";
14
15
  function readText(file) {
15
16
  try {
16
17
  return fs.readFileSync(file, "utf8");
@@ -157,14 +158,57 @@ function readHistory(workContextRoot) {
157
158
  return {};
158
159
  }
159
160
  }
161
+ /**
162
+ * Whether the Board for this project is archived or completed, read from the
163
+ * local work-mesh project cache (no network). A duplicate Board archived in
164
+ * favor of the canonical one must not keep receiving sessions.
165
+ */
166
+ export function projectRetiredInCache(companyUid, projectId, cacheRoot = meshCacheRoot()) {
167
+ if (!companyUid || !isSafeCacheSegment(companyUid) || !isSafeCacheSegment(projectId))
168
+ return false;
169
+ const raw = readText(path.join(cacheRoot, "projects", companyUid, `${projectId}.json`));
170
+ if (!raw)
171
+ return false;
172
+ try {
173
+ const lifecycle = asRecord(asRecord(JSON.parse(raw))?.lifecycle);
174
+ return lifecycle?.status === "archived" || lifecycle?.status === "completed";
175
+ }
176
+ catch {
177
+ return false;
178
+ }
179
+ }
180
+ /** Drop every remembered binding to a retired project. Best-effort; never throws. */
181
+ export function forgetRetiredPriorBindings(workContextRoot, projectId) {
182
+ try {
183
+ const history = readHistory(workContextRoot);
184
+ const stale = Object.keys(history).filter((key) => history[key]?.projectId === projectId);
185
+ if (stale.length === 0)
186
+ return 0;
187
+ for (const key of stale)
188
+ delete history[key];
189
+ const file = autoBindHistoryPath(workContextRoot);
190
+ const tmp = `${file}.tmp.${process.pid}`;
191
+ fs.writeFileSync(tmp, `${JSON.stringify(history, null, 2)}\n`, { mode: 0o600 });
192
+ fs.renameSync(tmp, file);
193
+ return stale.length;
194
+ }
195
+ catch {
196
+ return 0;
197
+ }
198
+ }
160
199
  export function lookupPriorBinding(input) {
161
200
  if (!input.branch)
162
201
  return null;
163
202
  const history = readHistory(input.workContextRoot);
164
203
  for (const repo of input.identities) {
165
204
  const hit = history[historyKey(input.companySlug, repo, input.branch)];
166
- if (hit?.projectId)
167
- return hit.projectId;
205
+ if (!hit?.projectId)
206
+ continue;
207
+ if (input.isRetired?.(hit.projectId)) {
208
+ forgetRetiredPriorBindings(input.workContextRoot, hit.projectId);
209
+ continue;
210
+ }
211
+ return hit.projectId;
168
212
  }
169
213
  return null;
170
214
  }
@@ -212,18 +256,20 @@ export function decideAutoBind(input) {
212
256
  return { action: "skip", reason: "no_git", candidates: [] };
213
257
  const identities = repoIdentities(git, input.hqRoot);
214
258
  const extra = { git, identities };
259
+ const isRetired = input.isRetired ?? ((projectId) => projectRetiredInCache(state.companyUid, projectId));
215
260
  const prior = lookupPriorBinding({
216
261
  workContextRoot: input.workContextRoot,
217
262
  companySlug,
218
263
  identities,
219
264
  branch: git.branch,
265
+ isRetired,
220
266
  });
221
267
  const candidates = findRepoPrdCandidates({
222
268
  hqRoot: input.hqRoot,
223
269
  companySlug,
224
270
  identities,
225
271
  branch: git.branch,
226
- });
272
+ }).filter((c) => !isRetired(c.projectId));
227
273
  const ownedByOtherSession = (projectId) => foreignSessionOwnsLane({
228
274
  hqRoot: input.hqRoot,
229
275
  projectId,
@@ -100,9 +100,11 @@ export declare function sessionDecisionScope(fields: {
100
100
  * projects and carries no repo or folder match, so without this filter a
101
101
  * session with no project context was offered unrelated projects
102
102
  * (feedback_f81b23c2). A session with an empty scope gets only
103
- * "Create new project" and "Leave untracked".
103
+ * "Create new project" and, when untracked would be accepted, "Leave untracked".
104
104
  */
105
- export declare function decisionFromCandidates(sessionId: string, response: CandidatesResponse, scope?: DecisionScope): SessionDecision;
105
+ export declare function decisionFromCandidates(sessionId: string, response: CandidatesResponse, scope?: DecisionScope, opts?: {
106
+ omitUntracked?: boolean;
107
+ }): SessionDecision;
106
108
  /**
107
109
  * Evaluate work-signal threshold and, when crossed for the first time, attach
108
110
  * a one-time decision (optionally from server candidates). Never invents a
@@ -62,9 +62,9 @@ export function sessionDecisionScope(fields) {
62
62
  * projects and carries no repo or folder match, so without this filter a
63
63
  * session with no project context was offered unrelated projects
64
64
  * (feedback_f81b23c2). A session with an empty scope gets only
65
- * "Create new project" and "Leave untracked".
65
+ * "Create new project" and, when untracked would be accepted, "Leave untracked".
66
66
  */
67
- export function decisionFromCandidates(sessionId, response, scope) {
67
+ export function decisionFromCandidates(sessionId, response, scope, opts) {
68
68
  const inScope = scope
69
69
  ? response.candidates.filter((c) => scope.projectIds.includes(c.projectId))
70
70
  : response.candidates;
@@ -82,11 +82,15 @@ export function decisionFromCandidates(sessionId, response, scope) {
82
82
  label: "Create new project",
83
83
  kind: "create_project",
84
84
  });
85
- options.push({
86
- optionId: "opt_untracked",
87
- label: "Leave untracked (local only)",
88
- kind: "untracked",
89
- });
85
+ // Do not offer Leave untracked when submit would refuse it (company-bound
86
+ // session, feedback_0e0bd7b3 / feedback_27faa67c).
87
+ if (!opts?.omitUntracked) {
88
+ options.push({
89
+ optionId: "opt_untracked",
90
+ label: "Leave untracked (local only)",
91
+ kind: "untracked",
92
+ });
93
+ }
90
94
  return {
91
95
  decisionId: stableDecisionId(sessionId, response.decisionExpiresAt),
92
96
  options,
@@ -208,7 +212,13 @@ export async function prepareOrganizeDecision(input) {
208
212
  sessionId: input.sessionId,
209
213
  companyUid: state.companyUid,
210
214
  });
211
- const decision = decisionFromCandidates(input.sessionId, response, sessionDecisionScope(state));
215
+ // This path writes needs_project (or keeps needs_task) below. Judge the
216
+ // option list against that next status, or we offer Leave untracked and
217
+ // then refuse it on submit.
218
+ const nextStatus = state.contextStatus === "needs_task" ? "needs_task" : "needs_project";
219
+ const decision = decisionFromCandidates(input.sessionId, response, sessionDecisionScope(state), {
220
+ omitUntracked: hasWorkMeshCompanyBinding({ ...state, contextStatus: nextStatus }, undefined, input.root),
221
+ });
212
222
  const updatedAt = nowFn().toISOString();
213
223
  const next = mergeLocalSessionFields({
214
224
  ...state,
@@ -713,7 +713,22 @@ export async function reconcileObservation(obs, deps) {
713
713
  companyUid: resolvedCompany.uid,
714
714
  });
715
715
  // Offer only the session's own projects (feedback_f81b23c2).
716
- decision = decisionFromCandidates(sessionId, candidates, sessionDecisionScope({ projectId, projectHint, projectCandidates }));
716
+ // Judge omit against the status this ask will register as. Unresolved
717
+ // becomes needs_project below; that is company-bound, so Leave
718
+ // untracked would be refused on submit (feedback_0e0bd7b3).
719
+ const nextAskStatus = effectiveClassification === "needs_task" ? "needs_task" : "needs_project";
720
+ decision = decisionFromCandidates(sessionId, candidates, sessionDecisionScope({ projectId, projectHint, projectCandidates }), {
721
+ omitUntracked: hasWorkMeshCompanyBinding({
722
+ contractVersion: 1,
723
+ sessionId,
724
+ companyUid: resolvedCompany.uid,
725
+ companySlug: resolvedCompany.slug,
726
+ contextStatus: nextAskStatus,
727
+ companyConfidence: prior?.companyConfidence,
728
+ ownerMismatch: prior?.ownerMismatch,
729
+ updatedAt: nowFn().toISOString(),
730
+ }, env, deps.root),
731
+ });
717
732
  diagnostics.push(`askAfter prepared decisionId=${decision.decisionId} options=${decision.options.length}`);
718
733
  }
719
734
  catch (err) {
package/dist/main.js CHANGED
@@ -25,7 +25,7 @@ import { qmdStoreUnopenableMessage } from "./utils/qmd-store-unopenable-error.js
25
25
  import { qmdQueryDocumentMessage } from "./utils/qmd-query-document-error.js";
26
26
  import { qmdModelDownloadMessage } from "./utils/qmd-model-download-error.js";
27
27
  import { qmdWorkdirMissingMessage } from "./utils/qmd-workdir-missing-error.js";
28
- import { qmdExitCaptureContext } from "./lib/search-index/qmd-exit-diagnostics.js";
28
+ import { qmdExitCaptureContext, qmdUnusableCaptureContext } from "./lib/search-index/qmd-exit-diagnostics.js";
29
29
  import { hqStateWriteErrorMessage } from "./utils/hq-state-write-error.js";
30
30
  import { checkpointStampWriteCaptureContext, checkpointStampWriteMessage, } from "./utils/checkpoint-stamp-write-error.js";
31
31
  import { incompleteInstallMessage, incompleteInstallCaptureContext, } from "./utils/incomplete-install-error.js";
@@ -1035,6 +1035,7 @@ export async function handleTopLevelError(err, deps = defaultTopLevelErrorDepend
1035
1035
  // hypotheses can be separated without creating one issue per host path.
1036
1036
  const checkpointStampContext = checkpointStampWriteCaptureContext(err);
1037
1037
  const checkpointStampMessage = checkpointStampWriteMessage(err);
1038
+ const qmdUnusableContext = qmdUnusableCaptureContext(err);
1038
1039
  const fsContext = filesystemErrorCaptureContext(err);
1039
1040
  const fsMsg = fsContext ? filesystemErrorMessage(err) : null;
1040
1041
  if (qmdMsg) {
@@ -1082,6 +1083,16 @@ export async function handleTopLevelError(err, deps = defaultTopLevelErrorDepend
1082
1083
  else if (transportMsg) {
1083
1084
  deps.stderr.write(`hq: ${transportMsg}\n`);
1084
1085
  }
1086
+ else if (qmdUnusableContext) {
1087
+ // Neither the bundled nor the PATH qmd passed its probe (HQ-CLI-J4,
1088
+ // HQ-CLI-HH). The message is already the plain remedy; print it without
1089
+ // the class name and still capture, with the two bounded probe kinds.
1090
+ // The message holds only hq-built text and the two resolved qmd paths,
1091
+ // never qmd output, so it is printed whole (redaction would truncate
1092
+ // the repair command).
1093
+ deps.sentry.captureException(err, qmdUnusableContext);
1094
+ deps.stderr.write(`hq: ${err.message}\n`);
1095
+ }
1085
1096
  else if (checkpointStampContext && checkpointStampMessage) {
1086
1097
  deps.sentry.captureException(err, checkpointStampContext);
1087
1098
  deps.stderr.write(`hq: ${checkpointStampMessage}\n`);
@@ -60,6 +60,15 @@ export declare const CLIENT_HEALTH_DAEMON_HQ_CLOUD_UPDATE_OUTCOMES: readonly ["u
60
60
  export declare const CLIENT_HEALTH_SYNC_ENGINES: readonly ["hq-syncd"];
61
61
  export type ClientHealthSyncEngine = (typeof CLIENT_HEALTH_SYNC_ENGINES)[number];
62
62
  export declare const CLIENT_HEALTH_MAX_SYNC_ENGINE_VAULTS = 10000;
63
+ export declare const CLIENT_HEALTH_SYNC_ENGINE_OWNERS: readonly ["engine", "legacy"];
64
+ export type ClientHealthSyncEngineOwner = (typeof CLIENT_HEALTH_SYNC_ENGINE_OWNERS)[number];
65
+ export declare const CLIENT_HEALTH_SYNC_ENGINE_HOLD_KINDS: readonly ["delete_local", "delete_remote", "overwrite_local"];
66
+ export type ClientHealthSyncEngineHoldKind = (typeof CLIENT_HEALTH_SYNC_ENGINE_HOLD_KINDS)[number];
67
+ export declare const CLIENT_HEALTH_MAX_SYNC_ENGINE_VAULT_ENTRIES = 16;
68
+ export declare const CLIENT_HEALTH_MAX_SYNC_ENGINE_COUNT = 100000000;
69
+ export declare const CLIENT_HEALTH_SYNC_ENGINE_SAFETY_COUNTERS: readonly ["vaultDeletes", "localDeletes", "downloadTrashed", "conflictBackups", "localReplaced", "uploadsOver", "refusedDeletes", "refusedUploads", "adoptions"];
70
+ export type ClientHealthSyncEngineSafetyCounter = (typeof CLIENT_HEALTH_SYNC_ENGINE_SAFETY_COUNTERS)[number];
71
+ export declare const CLIENT_HEALTH_MAX_EPOCH_MS = 8640000000000000;
63
72
  export type ClientHealthDaemonHqCloudUpdateOutcome = (typeof CLIENT_HEALTH_DAEMON_HQ_CLOUD_UPDATE_OUTCOMES)[number];
64
73
  export declare const CLIENT_HEALTH_DAEMON_HQ_CLOUD_UPDATE_ERROR_CLASSES: readonly ["registry", "install", "convergence", "filesystem", "unknown"];
65
74
  export type ClientHealthDaemonHqCloudUpdateErrorClass = (typeof CLIENT_HEALTH_DAEMON_HQ_CLOUD_UPDATE_ERROR_CLASSES)[number];
@@ -120,6 +129,26 @@ export interface ClientHealthLocalFilesOverview {
120
129
  /** Capped at {@link CLIENT_HEALTH_MAX_ERROR_LINE_COUNT}. */
121
130
  recentErrorLineCount: number;
122
131
  }
132
+ export interface ClientHealthSyncEngineVault {
133
+ vaultUid: string;
134
+ owner: ClientHealthSyncEngineOwner;
135
+ unitRunning?: boolean;
136
+ lastCycleAt?: string;
137
+ lastCycleSuccess?: boolean;
138
+ held?: number;
139
+ holdKinds?: ClientHealthSyncEngineHoldKind[];
140
+ conflicts?: number;
141
+ transferFailures?: number;
142
+ truncated?: boolean;
143
+ requests24h?: number;
144
+ safety?: ClientHealthSyncEngineSafety;
145
+ }
146
+ export interface ClientHealthSyncEngineSafetyCount {
147
+ total: number;
148
+ last24h: number;
149
+ lastAtMs?: number;
150
+ }
151
+ export type ClientHealthSyncEngineSafety = Partial<Record<ClientHealthSyncEngineSafetyCounter, ClientHealthSyncEngineSafetyCount>>;
123
152
  export interface ClientHealthHeartbeat {
124
153
  contractVersion: number;
125
154
  /** Stable random installation identity — NOT a hardware fingerprint. */
@@ -153,6 +182,7 @@ export interface ClientHealthHeartbeat {
153
182
  syncRunnerSource?: ClientHealthSyncRunnerSource;
154
183
  syncEngine?: ClientHealthSyncEngine;
155
184
  syncEngineVaults?: number;
185
+ syncEngineByVault?: ClientHealthSyncEngineVault[];
156
186
  daemonHqCloudUpdateLastCheckAt?: string;
157
187
  daemonHqCloudUpdateOutcome?: ClientHealthDaemonHqCloudUpdateOutcome;
158
188
  daemonHqCloudUpdateTarget?: string;
@@ -81,6 +81,22 @@ export const CLIENT_HEALTH_DAEMON_HQ_CLOUD_UPDATE_OUTCOMES = [
81
81
  ];
82
82
  export const CLIENT_HEALTH_SYNC_ENGINES = ["hq-syncd"];
83
83
  export const CLIENT_HEALTH_MAX_SYNC_ENGINE_VAULTS = 10_000;
84
+ export const CLIENT_HEALTH_SYNC_ENGINE_OWNERS = ["engine", "legacy"];
85
+ export const CLIENT_HEALTH_SYNC_ENGINE_HOLD_KINDS = ["delete_local", "delete_remote", "overwrite_local"];
86
+ export const CLIENT_HEALTH_MAX_SYNC_ENGINE_VAULT_ENTRIES = 16;
87
+ export const CLIENT_HEALTH_MAX_SYNC_ENGINE_COUNT = 100_000_000;
88
+ export const CLIENT_HEALTH_SYNC_ENGINE_SAFETY_COUNTERS = [
89
+ "vaultDeletes",
90
+ "localDeletes",
91
+ "downloadTrashed",
92
+ "conflictBackups",
93
+ "localReplaced",
94
+ "uploadsOver",
95
+ "refusedDeletes",
96
+ "refusedUploads",
97
+ "adoptions",
98
+ ];
99
+ export const CLIENT_HEALTH_MAX_EPOCH_MS = 8_640_000_000_000_000;
84
100
  export const CLIENT_HEALTH_DAEMON_HQ_CLOUD_UPDATE_ERROR_CLASSES = [
85
101
  "registry",
86
102
  "install",
@@ -165,6 +181,7 @@ export class ClientHealthContractError extends Error {
165
181
  // ─── Value validators (fail closed) ──────────────────────────────────────────
166
182
  const INSTALLATION_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{7,63}$/;
167
183
  const COMMAND_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{7,63}$/;
184
+ const SYNC_ENGINE_VAULT_UID = /^(?:prs|cmp)_[A-Za-z0-9][A-Za-z0-9_-]{0,59}$/;
168
185
  /** Same shape sync-auth-middleware.ts enforces on x-hq-*-version headers. */
169
186
  export const SEMVER = /^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
170
187
  const ISO_UTC = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/;
@@ -316,6 +333,11 @@ export function parseClientHealthHeartbeat(input) {
316
333
  if (vaults !== undefined)
317
334
  heartbeat.syncEngineVaults = vaults;
318
335
  }
336
+ if (raw.syncEngineByVault !== undefined) {
337
+ const byVault = parseClientHealthSyncEngineByVault(raw.syncEngineByVault);
338
+ if (byVault !== undefined)
339
+ heartbeat.syncEngineByVault = byVault;
340
+ }
319
341
  if (raw.daemonHqCloudUpdateLastCheckAt !== undefined) {
320
342
  const lastCheckAt = copyValidOptionalDiagnostic("daemonHqCloudUpdateLastCheckAt", raw.daemonHqCloudUpdateLastCheckAt, assertIsoUtc);
321
343
  if (lastCheckAt !== undefined)
@@ -338,6 +360,95 @@ export function parseClientHealthHeartbeat(input) {
338
360
  }
339
361
  return heartbeat;
340
362
  }
363
+ function parseClientHealthSyncEngineByVault(input) {
364
+ if (!Array.isArray(input))
365
+ return undefined;
366
+ if (input.length === 0)
367
+ return [];
368
+ const seen = new Set();
369
+ const out = [];
370
+ const limit = Math.min(input.length, CLIENT_HEALTH_MAX_SYNC_ENGINE_VAULT_ENTRIES);
371
+ for (let index = 0; index < limit; index += 1) {
372
+ const entry = parseClientHealthSyncEngineVault(`syncEngineByVault[${index}]`, input[index]);
373
+ if (!entry || seen.has(entry.vaultUid))
374
+ continue;
375
+ seen.add(entry.vaultUid);
376
+ out.push(entry);
377
+ }
378
+ return out.length > 0 ? out : undefined;
379
+ }
380
+ function parseClientHealthSyncEngineVault(field, input) {
381
+ const raw = copyValidOptionalDiagnostic(field, input, asRecord);
382
+ if (!raw)
383
+ return undefined;
384
+ const vaultUid = copyValidOptionalDiagnostic(`${field}.vaultUid`, raw.vaultUid, (name, value) => {
385
+ const safe = assertSafeBoundedString(name, value);
386
+ if (!SYNC_ENGINE_VAULT_UID.test(safe))
387
+ throw new ClientHealthContractError("UNSAFE_VALUE", name);
388
+ return safe;
389
+ });
390
+ const owner = copyValidOptionalDiagnostic(`${field}.owner`, raw.owner, (name, value) => assertEnum(name, value, CLIENT_HEALTH_SYNC_ENGINE_OWNERS));
391
+ if (vaultUid === undefined || owner === undefined)
392
+ return undefined;
393
+ const entry = { vaultUid, owner };
394
+ const optional = (key, validate) => {
395
+ if (raw[key] === undefined)
396
+ return;
397
+ const parsed = copyValidOptionalDiagnostic(`${field}.${key}`, raw[key], validate);
398
+ if (parsed !== undefined)
399
+ entry[key] = parsed;
400
+ };
401
+ const count = (name, value) => assertBoundedInt(name, value, CLIENT_HEALTH_MAX_SYNC_ENGINE_COUNT);
402
+ optional("unitRunning", assertBoolean);
403
+ optional("lastCycleAt", assertIsoUtc);
404
+ optional("lastCycleSuccess", assertBoolean);
405
+ optional("held", count);
406
+ optional("holdKinds", (name, value) => {
407
+ if (!Array.isArray(value))
408
+ throw new ClientHealthContractError("INVALID_TYPE", name, "expected array");
409
+ const kinds = CLIENT_HEALTH_SYNC_ENGINE_HOLD_KINDS.filter((known) => value.includes(known));
410
+ if (kinds.length === 0)
411
+ throw new ClientHealthContractError("UNKNOWN_ENUM_VALUE", name);
412
+ return kinds;
413
+ });
414
+ optional("conflicts", count);
415
+ optional("transferFailures", count);
416
+ optional("truncated", assertBoolean);
417
+ optional("requests24h", count);
418
+ optional("safety", parseClientHealthSyncEngineSafety);
419
+ return entry;
420
+ }
421
+ function parseClientHealthSyncEngineSafety(field, input) {
422
+ const raw = asRecord(field, input);
423
+ const safety = {};
424
+ let malformed = false;
425
+ for (const name of CLIENT_HEALTH_SYNC_ENGINE_SAFETY_COUNTERS) {
426
+ if (raw[name] === undefined)
427
+ continue;
428
+ const parsed = copyValidOptionalDiagnostic(`${field}.${name}`, raw[name], parseClientHealthSyncEngineSafetyCount);
429
+ if (parsed === undefined)
430
+ malformed = true;
431
+ else
432
+ safety[name] = parsed;
433
+ }
434
+ if (malformed && Object.keys(safety).length === 0) {
435
+ throw new ClientHealthContractError("INVALID_TYPE", field, "no valid counter");
436
+ }
437
+ return safety;
438
+ }
439
+ function parseClientHealthSyncEngineSafetyCount(field, input) {
440
+ const raw = asRecord(field, input);
441
+ const count = {
442
+ total: assertBoundedInt(`${field}.total`, raw.total, CLIENT_HEALTH_MAX_SYNC_ENGINE_COUNT),
443
+ last24h: assertBoundedInt(`${field}.last24h`, raw.last24h, CLIENT_HEALTH_MAX_SYNC_ENGINE_COUNT),
444
+ };
445
+ if (raw.lastAtMs !== undefined) {
446
+ const lastAtMs = copyValidOptionalDiagnostic(`${field}.lastAtMs`, raw.lastAtMs, (name, value) => assertBoundedInt(name, value, CLIENT_HEALTH_MAX_EPOCH_MS));
447
+ if (lastAtMs !== undefined && lastAtMs > 0)
448
+ count.lastAtMs = lastAtMs;
449
+ }
450
+ return count;
451
+ }
341
452
  /**
342
453
  * Parse + validate a {@link ClientHealthLocalFilesOverview}. Every field is a
343
454
  * boolean or a bounded integer — there is no string field to be path- or
@@ -32,7 +32,8 @@
32
32
  */
33
33
  import { isExpiring, loadCachedTokens } from "./cognito-session.js";
34
34
  import { type VersionInfo } from "./feedback-versions.js";
35
- import { type ClientHealthArch, type ClientHealthFailureReason, type ClientHealthHeartbeat, type ClientHealthLocalFilesOverview, type ClientHealthPlatform } from "./client-health-contract.js";
35
+ import { type ClientHealthArch, type ClientHealthFailureReason, type ClientHealthHeartbeat, type ClientHealthLocalFilesOverview, type ClientHealthPlatform, type ClientHealthSyncEngineVault } from "./client-health-contract.js";
36
+ import { type DaemonPaths } from "../lib/daemon/paths.js";
36
37
  export declare const CLIENT_HEALTH_STATE_FILE = "cli-client-health.json";
37
38
  /**
38
39
  * Single-flight marker for the journal observation below. Held only for the
@@ -184,8 +185,9 @@ export interface BuildCliHeartbeatInput {
184
185
  export interface CliSyncEngine {
185
186
  release: string;
186
187
  vaults: number;
188
+ byVault?: ClientHealthSyncEngineVault[];
187
189
  }
188
- export declare function readCliSyncEngine(stateDir: string): CliSyncEngine | null;
190
+ export declare function readCliSyncEngine(stateDir: string, now?: Date, paths?: DaemonPaths, alive?: (pid: number) => boolean): CliSyncEngine | null;
189
191
  /** Classify sync failures using typed error identity/code fields only. */
190
192
  export declare function classifySyncFailure(err: unknown): ClientHealthFailureReason;
191
193
  /**
@@ -213,6 +215,7 @@ export interface ClientHealthDeps {
213
215
  /** US-016: overridable for tests; defaults to {@link collectLocalFilesOverview}. */
214
216
  localFilesOverview?: () => ClientHealthLocalFilesOverview;
215
217
  syncEngine?: () => CliSyncEngine | null;
218
+ daemonPaths?: DaemonPaths;
216
219
  daemonCliVersion?: () => Promise<string | null>;
217
220
  /** Override for {@link JOURNAL_OBSERVATION_TTL_MS}. */
218
221
  journalObservationTtlMs?: number;