@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
@@ -0,0 +1,365 @@
1
+ /**
2
+ * Binding receipts: a dated record, written by `hq`, of each time a session's
3
+ * company lock set was changed with `hq-session set company_slug`,
4
+ * `add company` or `remove company`.
5
+ *
6
+ * A session's meta.yaml holds its current company only, with no time and a
7
+ * `company_source` line anyone can write. The receipt adds what meta cannot
8
+ * say: when the change happened, that it went through `hq` and not a hook,
9
+ * and the source of the change itself. Bound-session attribution (plan:
10
+ * companies/indigo/projects/telemetry-required-for-company-work) will count a
11
+ * bind as company work only when a receipt covers the moment of the work and
12
+ * its source is on {@link CHOSEN_SOURCES}. Nothing reads the receipt to decide
13
+ * reporting yet; this module only writes and reads it.
14
+ *
15
+ * One append-only file per session, `<work mesh root>/bindings/<sid>.jsonl`.
16
+ * Each line is the session's lock set after one change:
17
+ *
18
+ * {"v":2,"at":"<ISO time>","action":"bind","companies":["acme"],
19
+ * "source":"explicit","root":"<16 hex>","writer":"hq-cli"}
20
+ *
21
+ * Version 2 made `root` required. A version 1 line (written by unreleased
22
+ * builds before `root` existed) reads like any other unusable line: the whole
23
+ * file is no receipt.
24
+ *
25
+ * `root` names the HQ tree whose meta.yaml the change was read from (the
26
+ * first 16 hex digits of the sha256 of its real path). The file is per user,
27
+ * not per tree, so a reader matches `root` against the tree it judges: a bind
28
+ * made in a second HQ is never credited to the first. A reader that names no
29
+ * tree matches no line. `actor`, when present, is the caller's own session
30
+ * when the change named another session with `--session-id` (a parent
31
+ * binding a child, for example); it does not change whether the line counts.
32
+ *
33
+ * A file that is not a plain file, is over the size limit, has a line that
34
+ * does not parse, or has times that go backwards is read as no receipt at
35
+ * all. The file is not tamper-evident: a well-formed line written by any
36
+ * process running as the member reads like one `hq` wrote.
37
+ */
38
+ import { createHash } from "node:crypto";
39
+ import * as fs from "node:fs";
40
+ import * as os from "node:os";
41
+ import * as path from "node:path";
42
+ import { workMeshRoot } from "./paths.js";
43
+ export const BINDINGS_DIRNAME = "bindings";
44
+ /** The receipt line schema. 2: `root` is required. */
45
+ export const BINDING_RECEIPT_VERSION = 2;
46
+ const MAX_BYTES = 256 * 1024;
47
+ const MAX_COMPANIES = 64;
48
+ /** How many parents a `parent` bind is followed up. */
49
+ export const BINDING_PARENT_WALK_MAX = 8;
50
+ const SESSION_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$/;
51
+ const SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
52
+ const SOURCE_RE = /^[a-z][a-z0-9_]{0,63}$/;
53
+ const ROOT_RE = /^[0-9a-f]{16}$/;
54
+ const CALL_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
55
+ const ACTIONS = ["bind", "unbind", "add", "remove", "source"];
56
+ /**
57
+ * The allowlist: sources a person, an agent or a dispatching parent chose.
58
+ * Everything else is a default or a guess and never counts:
59
+ * `device_default`, `manifest_single_company`, `session`, `prompt_mention`,
60
+ * `scheduled_task`, a missing source, and any word not on this list.
61
+ * `parent` counts only through {@link bindingSourceCounts}.
62
+ */
63
+ export const CHOSEN_SOURCES = new Set(["explicit", "spawn_intent", "spawn"]);
64
+ export const PARENT_SOURCE = "parent";
65
+ /** The tree key a receipt line carries: sha256 of the tree's real path, first 16 hex digits. */
66
+ export function treeKeyOf(hqRoot) {
67
+ let real;
68
+ try {
69
+ real = fs.realpathSync.native(hqRoot);
70
+ }
71
+ catch {
72
+ real = path.resolve(hqRoot);
73
+ }
74
+ return createHash("sha256").update(real).digest("hex").slice(0, 16);
75
+ }
76
+ function bindingsDir(options) {
77
+ const env = options.env ?? process.env;
78
+ const root = options.workMeshRoot ?? workMeshRoot(options.home ?? (env.HOME?.trim() || os.homedir()), env);
79
+ return path.join(root, BINDINGS_DIRNAME);
80
+ }
81
+ export function bindingReceiptPath(sessionId, options = {}) {
82
+ if (!SESSION_RE.test(sessionId))
83
+ return null;
84
+ return path.join(bindingsDir(options), `${sessionId}.jsonl`);
85
+ }
86
+ function sameSlug(a, b) {
87
+ return a.toLowerCase() === b.toLowerCase();
88
+ }
89
+ function parseLine(raw) {
90
+ let value;
91
+ try {
92
+ value = JSON.parse(raw);
93
+ }
94
+ catch {
95
+ return null;
96
+ }
97
+ if (!value || typeof value !== "object" || Array.isArray(value))
98
+ return null;
99
+ const rec = value;
100
+ if (rec.v !== BINDING_RECEIPT_VERSION || rec.writer !== "hq-cli")
101
+ return null;
102
+ if (typeof rec.at !== "string" || !Number.isFinite(Date.parse(rec.at)))
103
+ return null;
104
+ if (typeof rec.action !== "string" || !ACTIONS.includes(rec.action))
105
+ return null;
106
+ if (!Array.isArray(rec.companies) || rec.companies.length > MAX_COMPANIES)
107
+ return null;
108
+ const companies = [];
109
+ for (const company of rec.companies) {
110
+ if (typeof company !== "string" || !SLUG_RE.test(company) || company.toLowerCase() === "personal")
111
+ return null;
112
+ companies.push(company);
113
+ }
114
+ if (typeof rec.source !== "string" || (rec.source !== "" && !SOURCE_RE.test(rec.source)))
115
+ return null;
116
+ if (rec.parent !== undefined && (typeof rec.parent !== "string" || !SESSION_RE.test(rec.parent)))
117
+ return null;
118
+ if (typeof rec.root !== "string" || !ROOT_RE.test(rec.root))
119
+ return null;
120
+ if (rec.actor !== undefined && (typeof rec.actor !== "string" || !SESSION_RE.test(rec.actor)))
121
+ return null;
122
+ if (rec.confirmed !== undefined && rec.confirmed !== "hook")
123
+ return null;
124
+ if (rec.call !== undefined && (typeof rec.call !== "string" || !CALL_RE.test(rec.call)))
125
+ return null;
126
+ if ((rec.confirmed === undefined) !== (rec.call === undefined))
127
+ return null;
128
+ return {
129
+ v: BINDING_RECEIPT_VERSION, at: rec.at, action: rec.action, companies, source: rec.source,
130
+ ...(typeof rec.parent === "string" ? { parent: rec.parent } : {}),
131
+ root: rec.root,
132
+ ...(typeof rec.actor === "string" ? { actor: rec.actor } : {}),
133
+ ...(rec.confirmed === "hook" && typeof rec.call === "string" ? { confirmed: "hook", call: rec.call } : {}),
134
+ writer: "hq-cli",
135
+ };
136
+ }
137
+ /**
138
+ * Every line of a session's receipt, oldest first. Null when there is no
139
+ * usable receipt: no file, a link or a folder at its path, a file over the
140
+ * size limit, a line that does not parse, or times that go backwards.
141
+ */
142
+ export function readBindingReceipt(sessionId, options = {}) {
143
+ const file = bindingReceiptPath(sessionId, options);
144
+ if (!file)
145
+ return null;
146
+ try {
147
+ const stat = fs.lstatSync(file);
148
+ if (!stat.isFile() || stat.size > MAX_BYTES)
149
+ return null;
150
+ const lines = [];
151
+ let last = Number.NEGATIVE_INFINITY;
152
+ for (const raw of fs.readFileSync(file, "utf8").split("\n")) {
153
+ if (raw === "")
154
+ continue;
155
+ const line = parseLine(raw);
156
+ if (!line)
157
+ return null;
158
+ const at = Date.parse(line.at);
159
+ if (at < last)
160
+ return null;
161
+ last = at;
162
+ lines.push(line);
163
+ }
164
+ return lines.length > 0 ? lines : null;
165
+ }
166
+ catch {
167
+ return null;
168
+ }
169
+ }
170
+ /** Append one line. Never throws: a receipt that cannot be written is no receipt. */
171
+ export function appendBindingReceipt(sessionId, entry, options = {}) {
172
+ const file = bindingReceiptPath(sessionId, options);
173
+ // The tree the change was made in: the entry's, else the one the paths name.
174
+ const tree = entry.hqRoot ?? options.hqRoot;
175
+ if (!file || !tree)
176
+ return null;
177
+ try {
178
+ const companies = [];
179
+ for (const company of entry.companies) {
180
+ if (!SLUG_RE.test(company) || company.toLowerCase() === "personal")
181
+ continue;
182
+ if (!companies.some((known) => sameSlug(known, company)))
183
+ companies.push(company);
184
+ }
185
+ const line = {
186
+ v: BINDING_RECEIPT_VERSION,
187
+ at: (options.now?.() ?? new Date()).toISOString(),
188
+ action: entry.action,
189
+ companies: companies.slice(0, MAX_COMPANIES),
190
+ source: SOURCE_RE.test(entry.source) ? entry.source : "",
191
+ ...(entry.parent && SESSION_RE.test(entry.parent) ? { parent: entry.parent } : {}),
192
+ root: treeKeyOf(tree),
193
+ ...(entry.actor && entry.actor !== sessionId && SESSION_RE.test(entry.actor) ? { actor: entry.actor } : {}),
194
+ ...(entry.confirmedCall && CALL_RE.test(entry.confirmedCall) ? { confirmed: "hook", call: entry.confirmedCall } : {}),
195
+ writer: "hq-cli",
196
+ };
197
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
198
+ // Never write through a link or onto a folder someone put at the path.
199
+ try {
200
+ if (!fs.lstatSync(file).isFile())
201
+ return null;
202
+ }
203
+ catch (error) {
204
+ if (error?.code !== "ENOENT")
205
+ return null;
206
+ }
207
+ // A line timed before the last one (the clock moved back) is still
208
+ // appended. The file then reads as no receipt, so the session counts as
209
+ // not bound from then on: an unbind is never lost, and nothing is
210
+ // attributed by a receipt whose order is in doubt.
211
+ fs.appendFileSync(file, `${JSON.stringify(line)}\n`, { mode: 0o600 });
212
+ return line;
213
+ }
214
+ catch {
215
+ return null;
216
+ }
217
+ }
218
+ /**
219
+ * The receipt's lines for the tree `options.hqRoot` names, oldest first.
220
+ * None when no tree is named.
221
+ */
222
+ function treeLines(sessionId, options) {
223
+ if (!options.hqRoot)
224
+ return null;
225
+ const lines = readBindingReceipt(sessionId, options);
226
+ if (!lines)
227
+ return null;
228
+ const key = treeKeyOf(options.hqRoot);
229
+ const mine = lines.filter((line) => line.root === key);
230
+ return mine.length > 0 ? mine : null;
231
+ }
232
+ /**
233
+ * The session's lock set and source at `at` in the tree `options.hqRoot`
234
+ * names: the last change on or before it.
235
+ */
236
+ export function bindingAt(sessionId, at, options = {}) {
237
+ const lines = treeLines(sessionId, options);
238
+ if (!lines)
239
+ return null;
240
+ const moment = at.getTime();
241
+ if (!Number.isFinite(moment))
242
+ return null;
243
+ let found = null;
244
+ for (const line of lines) {
245
+ if (Date.parse(line.at) <= moment)
246
+ found = line;
247
+ else
248
+ break;
249
+ }
250
+ return found;
251
+ }
252
+ /**
253
+ * Does the session's bind to `company` at `at` come from a choice? True for
254
+ * the sources on {@link CHOSEN_SOURCES}. A `parent` bind counts only when the
255
+ * parent's own receipt, at that moment, binds the same company and counts by
256
+ * the same rule, at most {@link BINDING_PARENT_WALK_MAX} parents up.
257
+ */
258
+ export function bindingSourceCounts(sessionId, company, at, options = {}) {
259
+ let current = sessionId;
260
+ const seen = new Set();
261
+ for (let depth = 0; depth <= BINDING_PARENT_WALK_MAX; depth += 1) {
262
+ if (seen.has(current))
263
+ return false;
264
+ seen.add(current);
265
+ const line = bindingAt(current, at, options);
266
+ if (!line || !line.companies.some((bound) => sameSlug(bound, company)))
267
+ return false;
268
+ if (CHOSEN_SOURCES.has(line.source))
269
+ return true;
270
+ if (line.source !== PARENT_SOURCE || !line.parent)
271
+ return false;
272
+ current = line.parent;
273
+ }
274
+ return false;
275
+ }
276
+ /**
277
+ * Since when has the session held `company` without a break, as of `at`?
278
+ * The time of the first line of the unbroken run of lines, ending at the one
279
+ * in force at `at`, whose lock set includes the company. Null when the
280
+ * session does not hold it at `at`.
281
+ */
282
+ export function bindingBoundSince(sessionId, company, at, options = {}) {
283
+ const lines = treeLines(sessionId, options);
284
+ const moment = at.getTime();
285
+ if (!lines || !Number.isFinite(moment))
286
+ return null;
287
+ let since = null;
288
+ for (const line of lines) {
289
+ const time = Date.parse(line.at);
290
+ if (time > moment)
291
+ break;
292
+ if (line.companies.some((bound) => sameSlug(bound, company)))
293
+ since ??= time;
294
+ else
295
+ since = null;
296
+ }
297
+ return since === null ? null : new Date(since);
298
+ }
299
+ /** An unattended run: the job runner and the Outpost export this before they start anything. */
300
+ export function unattendedRun(env = process.env) {
301
+ return ["1", "true", "TRUE", "yes", "YES", "on", "ON"].includes(env.HQ_SYNC_UNATTENDED?.trim() ?? "");
302
+ }
303
+ /**
304
+ * What the member is told when a session is bound to a company that requires
305
+ * reporting. It names the session by its first 12 characters, and says whether it is the caller's own
306
+ * (`own`), another session the caller bound (`other`), or unknown because the
307
+ * caller's environment names no session (`unknown`).
308
+ */
309
+ export function sessionReportingRequiredNotice(company, sessionId, relation) {
310
+ const which = relation === "own" ? " (this session)" : relation === "other" ? " (not this session)" : "";
311
+ return `Activity in session ${sessionId.slice(0, 12)}${which} is reported to ${company}. Required by the company.`;
312
+ }
313
+ /** Forget every receipt: the person signed out. */
314
+ export function clearBindingReceipts(options = {}) {
315
+ try {
316
+ fs.rmSync(bindingsDir(options), { recursive: true, force: true });
317
+ }
318
+ catch {
319
+ // Nothing to forget.
320
+ }
321
+ }
322
+ /**
323
+ * The company lines of `<HQ root>/workspace/sessions/<sid>/meta.yaml`, read
324
+ * line by line as the session scripts write them. Null when the file is
325
+ * missing, is not a plain file, cannot be read, or names a company that is
326
+ * not a plain slug.
327
+ */
328
+ export function readSessionMeta(hqRoot, sessionId) {
329
+ if (!hqRoot || !SESSION_RE.test(sessionId))
330
+ return null;
331
+ const file = path.join(hqRoot, "workspace", "sessions", sessionId, "meta.yaml");
332
+ let text;
333
+ try {
334
+ const stat = fs.lstatSync(file);
335
+ if (!stat.isFile() || stat.size > MAX_BYTES)
336
+ return null;
337
+ text = fs.readFileSync(file, "utf8");
338
+ }
339
+ catch {
340
+ return null;
341
+ }
342
+ const value = (key) => {
343
+ for (const line of text.split(/\r?\n/)) {
344
+ const match = new RegExp(`^\\s*${key}\\s*:\\s*(.*?)\\s*$`).exec(line);
345
+ if (match)
346
+ return (match[1] ?? "").replace(/^["']|["']$/g, "");
347
+ }
348
+ return "";
349
+ };
350
+ const companySlug = value("company_slug");
351
+ const listed = value("company_slugs").replace(/^\[|\]$/g, "").split(",")
352
+ .map((entry) => entry.trim().replace(/^["']|["']$/g, "")).filter(Boolean);
353
+ const companies = [];
354
+ for (const slug of [companySlug, ...listed]) {
355
+ if (!slug || slug.toLowerCase() === "personal")
356
+ continue;
357
+ // A name that is not a plain slug makes the whole set unusable.
358
+ if (!SLUG_RE.test(slug))
359
+ return null;
360
+ if (!companies.some((known) => sameSlug(known, slug)))
361
+ companies.push(slug);
362
+ }
363
+ return { companySlug, companies, companySource: value("company_source"), foreignCwd: value("foreign_cwd") };
364
+ }
365
+ //# sourceMappingURL=binding-receipt.js.map
@@ -21,7 +21,7 @@
21
21
  */
22
22
  import * as fs from "node:fs";
23
23
  import * as path from "node:path";
24
- import { createFlagClient } from "@indigoai-us/hq-flags-client";
24
+ import { createHqFlagClient as createFlagClient } from "../../flag-client-headers.js";
25
25
  import { resolveFlagRegistryEndpoint } from "../../flag-registry-endpoint.js";
26
26
  import { readFlagSnapshotFile, writeFlagSnapshotFile } from "../../flag-snapshot-file.js";
27
27
  import { isNonCloudCompanySlug } from "../../work-context/company-rebind.js";
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Daemon doctor telemetry: the metadata-only report hq-pro stores per company
3
+ * and actor (POST /v1/work-mesh/live/doctor-telemetry). The Board roster's
4
+ * "daemon last seen" column reads only these rows, so without this report
5
+ * every member shows "never" while their daemon runs.
6
+ *
7
+ * Counts only: held, spool and dead-letter line counts. Never prompts,
8
+ * tokens or event bodies.
9
+ */
10
+ export declare const DOCTOR_TELEMETRY_PATH = "/v1/work-mesh/live/doctor-telemetry";
11
+ /** How often a running daemon reports each online company. */
12
+ export declare const DOCTOR_TELEMETRY_INTERVAL_MS: number;
13
+ export interface DoctorTelemetryCounts {
14
+ heldCount: number;
15
+ spoolDepth: number;
16
+ deadLetterCount: number;
17
+ }
18
+ export type DoctorTelemetryBody = DoctorTelemetryCounts & {
19
+ companyUid: string;
20
+ reportedAt: string;
21
+ };
22
+ export interface DoctorTelemetryReporterOptions {
23
+ /** POST one company's report. Rejections are swallowed and retried next interval. */
24
+ post: (body: DoctorTelemetryBody) => Promise<void>;
25
+ counts: () => DoctorTelemetryCounts;
26
+ now: () => number;
27
+ intervalMs?: number;
28
+ onError?: (companyUid: string, err: unknown) => void;
29
+ }
30
+ export interface DoctorTelemetryReporter {
31
+ /**
32
+ * Report each company whose last successful report is older than half
33
+ * the interval. Presence reconnects call this often; the throttle keeps
34
+ * them from repeating the report.
35
+ */
36
+ report(companyUids: readonly string[]): Promise<number>;
37
+ }
38
+ export declare function createDoctorTelemetryReporter(options: DoctorTelemetryReporterOptions): DoctorTelemetryReporter;
39
+ //# sourceMappingURL=doctor-telemetry.d.ts.map
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Daemon doctor telemetry: the metadata-only report hq-pro stores per company
3
+ * and actor (POST /v1/work-mesh/live/doctor-telemetry). The Board roster's
4
+ * "daemon last seen" column reads only these rows, so without this report
5
+ * every member shows "never" while their daemon runs.
6
+ *
7
+ * Counts only: held, spool and dead-letter line counts. Never prompts,
8
+ * tokens or event bodies.
9
+ */
10
+ export const DOCTOR_TELEMETRY_PATH = "/v1/work-mesh/live/doctor-telemetry";
11
+ /** How often a running daemon reports each online company. */
12
+ export const DOCTOR_TELEMETRY_INTERVAL_MS = 5 * 60_000;
13
+ export function createDoctorTelemetryReporter(options) {
14
+ const intervalMs = options.intervalMs ?? DOCTOR_TELEMETRY_INTERVAL_MS;
15
+ // The periodic tick fires every intervalMs. A throttle of the full interval
16
+ // would skip every other tick when the first report came from a presence
17
+ // reconnect a few seconds after start, so allow a report after half of it.
18
+ const minGapMs = intervalMs / 2;
19
+ const lastSent = new Map();
20
+ const inFlight = new Set();
21
+ return {
22
+ async report(companyUids) {
23
+ const due = [...new Set(companyUids)].filter((uid) => {
24
+ if (typeof uid !== "string" || !uid.trim() || inFlight.has(uid))
25
+ return false;
26
+ const last = lastSent.get(uid);
27
+ return last === undefined || options.now() - last >= minGapMs;
28
+ });
29
+ if (due.length === 0)
30
+ return 0;
31
+ let counts;
32
+ try {
33
+ counts = options.counts();
34
+ }
35
+ catch {
36
+ counts = { heldCount: 0, spoolDepth: 0, deadLetterCount: 0 };
37
+ }
38
+ const reportedAt = new Date(options.now()).toISOString();
39
+ let sent = 0;
40
+ await Promise.all(due.map(async (companyUid) => {
41
+ inFlight.add(companyUid);
42
+ try {
43
+ await options.post({ companyUid, reportedAt, ...counts });
44
+ lastSent.set(companyUid, options.now());
45
+ sent += 1;
46
+ }
47
+ catch (err) {
48
+ options.onError?.(companyUid, err);
49
+ }
50
+ finally {
51
+ inFlight.delete(companyUid);
52
+ }
53
+ }));
54
+ return sent;
55
+ },
56
+ };
57
+ }
58
+ //# sourceMappingURL=doctor-telemetry.js.map
@@ -28,6 +28,7 @@ import { activateLaunchd, defaultRunCommand, discoverLaunchdIdentity, installLau
28
28
  import { activateSystemd, systemdIsActive } from "../../../service-manager/systemd.js";
29
29
  import { SYSTEMD_SYSTEM_UNIT_DIR, describeSystemUnitState, meshSystemUnitPath, meshSystemUnitPresent, readMeshSystemUnitState, } from "./system-unit.js";
30
30
  import { nodeBinaryProblem, preferStableNodeBinary } from "../../../node-binary.js";
31
+ import { isSignalablePid } from "../../../../utils/pid.js";
31
32
  /**
32
33
  * `schtasks /End` terminates the task's root process only. The daemon is
33
34
  * launched through `conhost.exe --headless`, so ending the task kills conhost
@@ -40,7 +41,7 @@ export function stopWindowsDaemonProcess(dir, deps = {}) {
40
41
  readFileSync: deps.readFileSync,
41
42
  existsSync: deps.existsSync,
42
43
  });
43
- if (!record || record.pid === (deps.selfPid ?? process.pid))
44
+ if (!record || !isSignalablePid(record.pid) || record.pid === (deps.selfPid ?? process.pid))
44
45
  return null;
45
46
  try {
46
47
  (deps.kill ?? ((pid) => process.kill(pid)))(record.pid);
@@ -273,6 +273,15 @@ export class PresenceClient {
273
273
  catch {
274
274
  /* best-effort */
275
275
  }
276
+ // mqtt.js can still emit "error" after end(), for example its CONNACK
277
+ // timeout on a connection that never finished. An EventEmitter "error"
278
+ // with no listener throws and kills the mesh daemon, so keep one.
279
+ try {
280
+ client.on("error", () => undefined);
281
+ }
282
+ catch {
283
+ /* best-effort */
284
+ }
276
285
  try {
277
286
  if (force) {
278
287
  client.end(true);
@@ -10,6 +10,7 @@ import { PresenceClient, type MqttConnectFn } from "./presence.js";
10
10
  import { TranscriptWatcher, type TranscriptFs } from "./transcript-watch.js";
11
11
  import { type MeshEmitMode } from "./mode.js";
12
12
  import { type CommandRunner, type LegacyListenPlatform } from "./legacy-listen.js";
13
+ import { type DoctorTelemetryBody } from "./doctor-telemetry.js";
13
14
  import { type CompanyFlagClient } from "../company-flag-refresh.js";
14
15
  import type { FlagClientOptions } from "@indigoai-us/hq-flags-client";
15
16
  import { type StartCapacitySchedulerOptions } from "../../../capacity/scheduler.js";
@@ -112,6 +113,8 @@ export interface DaemonRunDeps {
112
113
  exit?: (code: number) => void;
113
114
  /** Token provider (tests). */
114
115
  getToken?: () => Promise<string>;
116
+ /** Doctor telemetry POST seam (tests). Defaults to meshJson with the daemon token. */
117
+ postDoctorTelemetry?: (body: DoctorTelemetryBody) => Promise<void>;
115
118
  /** Low-level tenant I/O seams used by authorization regression tests. */
116
119
  poster?: SessionEventsPoster;
117
120
  deliver?: DeliverFn;
@@ -33,7 +33,7 @@ import { acquirePidLock, defaultPidLockDeps, releasePidLock, } from "./pid-lock.
33
33
  import { daemonDir } from "./paths.js";
34
34
  import { PresenceClient, defaultMqttConnect, } from "./presence.js";
35
35
  import { defaultDaemonState, patchDaemonState, readDaemonState, writeDaemonState, } from "./state.js";
36
- import { workMeshHeldPath } from "../paths.js";
36
+ import { workMeshDeadLetterPath, workMeshHeldPath } from "../paths.js";
37
37
  import { compactDeadLetter, countJsonlLines } from "../spool.js";
38
38
  import { createOutboxCompanyUidFiller, requeueCompanyUidQuarantines } from "./outbox-company.js";
39
39
  import { defaultTranscriptFs, noteHookSessionsFromSpoolFile, TRANSCRIPT_WATCH_INTERVAL_MS, TranscriptWatcher, } from "./transcript-watch.js";
@@ -43,6 +43,7 @@ import { resolveRunningCliEntry } from "./install.js";
43
43
  import { readDaemonConfig } from "./config.js";
44
44
  import { retireLegacyListen } from "./legacy-listen.js";
45
45
  import { runDirectDrainCycle } from "../direct-drain.js";
46
+ import { DOCTOR_TELEMETRY_INTERVAL_MS, DOCTOR_TELEMETRY_PATH, createDoctorTelemetryReporter } from "./doctor-telemetry.js";
46
47
  import { COMPANY_FLAG_REFRESH_INTERVAL_MS, refreshCompanyFlagSnapshots, } from "../company-flag-refresh.js";
47
48
  import { startWorkCacheSubscriber } from "./work-subscribe.js";
48
49
  import { createOwnerChannelScope } from "./owner-inbox-push.js";
@@ -625,6 +626,24 @@ export async function runMeshDaemon(deps = {}) {
625
626
  }
626
627
  };
627
628
  let presence = null;
629
+ // The roster's "daemon last seen" reads only these reports (hq-pro
630
+ // doctor-telemetry rows); without them every member shows "never".
631
+ const doctorTelemetry = createDoctorTelemetryReporter({
632
+ post: deps.postDoctorTelemetry ?? (async (body) => {
633
+ await meshJson(await getToken(), DOCTOR_TELEMETRY_PATH, { method: "POST", body: { ...body } });
634
+ }),
635
+ counts: () => ({
636
+ heldCount: countJsonlLines(workMeshHeldPath(meshRoot)),
637
+ spoolDepth: countJsonlLines(workMeshSpoolPath(meshRoot)),
638
+ deadLetterCount: countJsonlLines(workMeshDeadLetterPath(meshRoot)),
639
+ }),
640
+ now: () => timers.now(),
641
+ onError: (companyUid, err) => {
642
+ const msg = err instanceof Error ? err.message : String(err);
643
+ log(dir, `doctor telemetry ${companyUid} failed: ${msg.slice(0, 160)}`);
644
+ },
645
+ });
646
+ let doctorTelemetryHandle = null;
628
647
  let workCache = null;
629
648
  if (deps.enablePresence !== false) {
630
649
  const fetchCredentialsRaw = deps.fetchCredentials ??
@@ -660,6 +679,7 @@ export async function runMeshDaemon(deps = {}) {
660
679
  presenceRefusal: null,
661
680
  }, now);
662
681
  log(dir, `presence online companies=${companies.length}`);
682
+ void doctorTelemetry.report(companies);
663
683
  },
664
684
  readPreferredCompanyUids: () => readPreferredCompanyUids({ workContextRoot: ctxRoot }),
665
685
  onRefusal: (refusal) => {
@@ -1035,6 +1055,16 @@ export async function runMeshDaemon(deps = {}) {
1035
1055
  };
1036
1056
  if (!emitPath)
1037
1057
  scheduleDirectDrain(DIRECT_DRAIN_START_DELAY_MS);
1058
+ doctorTelemetryHandle = timers.setTimeout(function doctorTelemetryTick() {
1059
+ if (stopped)
1060
+ return;
1061
+ const companies = presence?.getBundle()?.companies.map((c) => c.companyUid) ?? [];
1062
+ void doctorTelemetry.report(companies).finally(() => {
1063
+ if (stopped)
1064
+ return;
1065
+ doctorTelemetryHandle = timers.setTimeout(doctorTelemetryTick, DOCTOR_TELEMETRY_INTERVAL_MS);
1066
+ });
1067
+ }, DOCTOR_TELEMETRY_INTERVAL_MS);
1038
1068
  boardIntervalHandle = timers.setTimeout(function boardTick() {
1039
1069
  if (stopped)
1040
1070
  return;
@@ -1156,6 +1186,8 @@ export async function runMeshDaemon(deps = {}) {
1156
1186
  timers.clearTimeout(versionIntervalHandle);
1157
1187
  if (boardIntervalHandle !== null)
1158
1188
  timers.clearTimeout(boardIntervalHandle);
1189
+ if (doctorTelemetryHandle !== null)
1190
+ timers.clearTimeout(doctorTelemetryHandle);
1159
1191
  if (transcriptIntervalHandle !== null) {
1160
1192
  timers.clearTimeout(transcriptIntervalHandle);
1161
1193
  }