@indigoai-us/hq-cli 5.345.222 → 5.345.225

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 (128) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/assets/bot-workers/setup/context/quick-reference.md +2 -2
  3. package/assets/mesh-daemon/README.md +11 -12
  4. package/dist/command-catalog.generated.d.ts +79 -5
  5. package/dist/command-catalog.generated.js +95 -5
  6. package/dist/commands/bot.d.ts +1 -1
  7. package/dist/commands/bot.js +34 -33
  8. package/dist/commands/cloud-provision.d.ts +4 -1
  9. package/dist/commands/cloud-provision.js +7 -3
  10. package/dist/commands/cloud-retire.js +1 -1
  11. package/dist/commands/core-delegate-w1b.js +210 -188
  12. package/dist/commands/core-delegate.d.ts +5 -0
  13. package/dist/commands/core-dm-bind-native.d.ts +5 -1
  14. package/dist/commands/core-dm-bind-native.js +4 -0
  15. package/dist/commands/core-job-notify-native.d.ts +5 -1
  16. package/dist/commands/core-job-notify-native.js +8 -2
  17. package/dist/commands/core-jobs-native.d.ts +27 -1
  18. package/dist/commands/core-jobs-native.js +49 -28
  19. package/dist/commands/core-pipeline-conductor-native.js +7 -7
  20. package/dist/commands/core-pipeline-driver-native.js +5 -5
  21. package/dist/commands/core-refresh-vault-access-native.d.ts +5 -0
  22. package/dist/commands/core-refresh-vault-access-native.js +3 -1
  23. package/dist/commands/core-work-mesh-bind-trusted-native.js +1 -1
  24. package/dist/commands/daemon.d.ts +2 -0
  25. package/dist/commands/daemon.js +67 -1
  26. package/dist/commands/lanes-hold.d.ts +2 -27
  27. package/dist/commands/lanes-hold.js +3 -75
  28. package/dist/commands/lanes-loop.js +1 -1
  29. package/dist/commands/lanes-session-start.js +2 -2
  30. package/dist/commands/mesh.d.ts +12 -0
  31. package/dist/commands/mesh.js +13 -4
  32. package/dist/commands/monitor.js +1 -1
  33. package/dist/commands/packs.js +14 -3
  34. package/dist/commands/sync-core.js +31 -12
  35. package/dist/commands/whoami.d.ts +10 -17
  36. package/dist/commands/whoami.js +7 -79
  37. package/dist/data/command-states.json +13 -0
  38. package/dist/index.js +1 -1
  39. package/dist/lib/bot/fleet-cron.d.ts +26 -3
  40. package/dist/lib/bot/fleet-cron.js +44 -4
  41. package/dist/lib/bot/run.d.ts +4 -4
  42. package/dist/lib/bot/run.js +5 -3
  43. package/dist/lib/bot/signals-engine-flag.d.ts +53 -13
  44. package/dist/lib/bot/signals-engine-flag.js +202 -9
  45. package/dist/lib/daemon/catalog.d.ts +8 -5
  46. package/dist/lib/daemon/catalog.js +13 -7
  47. package/dist/lib/daemon/config.d.ts +5 -0
  48. package/dist/lib/daemon/config.js +6 -0
  49. package/dist/lib/daemon/lanes-monitor-state.d.ts +55 -0
  50. package/dist/lib/daemon/lanes-monitor-state.js +129 -0
  51. package/dist/lib/daemon/lanes-reconcile-loader.d.ts +7 -0
  52. package/dist/lib/daemon/lanes-reconcile-loader.js +13 -0
  53. package/dist/lib/daemon/machine-checks.d.ts +45 -0
  54. package/dist/lib/daemon/machine-checks.js +95 -11
  55. package/dist/lib/daemon/merge-sections.d.ts +165 -0
  56. package/dist/lib/daemon/merge-sections.js +556 -0
  57. package/dist/lib/daemon/native-notice-ledger.d.ts +9 -0
  58. package/dist/lib/daemon/native-notice-ledger.js +43 -0
  59. package/dist/lib/daemon/ops/policy.d.ts +1 -1
  60. package/dist/lib/daemon/ops/policy.js +1 -1
  61. package/dist/lib/daemon/protocol.d.ts +1 -1
  62. package/dist/lib/daemon/protocol.js +0 -6
  63. package/dist/lib/daemon/run.js +76 -3
  64. package/dist/lib/daemon/selfcheck.js +2 -2
  65. package/dist/lib/daemon/server.d.ts +2 -4
  66. package/dist/lib/daemon/server.js +5 -48
  67. package/dist/lib/daemon/state-file.d.ts +74 -4
  68. package/dist/lib/daemon/state-file.js +159 -19
  69. package/dist/lib/daemon/supervisor.d.ts +11 -1
  70. package/dist/lib/daemon/supervisor.js +86 -0
  71. package/dist/lib/daemon/updater.d.ts +2 -6
  72. package/dist/lib/daemon/updater.js +4 -11
  73. package/dist/lib/daemon/whoami-cache.d.ts +96 -0
  74. package/dist/lib/daemon/whoami-cache.js +244 -0
  75. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  76. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  77. package/dist/lib/flag-registry-worker.js +33 -3
  78. package/dist/lib/flag-registry.js +13 -0
  79. package/dist/lib/hook-engine/coverage.d.ts +2 -0
  80. package/dist/lib/hook-engine/coverage.js +71 -0
  81. package/dist/lib/hook-engine/native-precompact-compatibility.json +449 -0
  82. package/dist/lib/hook-engine/reconcile.js +14 -8
  83. package/dist/lib/install/hook-target.d.ts +13 -3
  84. package/dist/lib/install/hook-target.js +14 -11
  85. package/dist/lib/lanes/envelope-repair-dispatch.js +1 -1
  86. package/dist/lib/lanes/monitor.d.ts +2 -0
  87. package/dist/lib/lanes/monitor.js +2 -1
  88. package/dist/lib/lanes/registry-flag.d.ts +6 -0
  89. package/dist/lib/lanes/registry-flag.js +3 -2
  90. package/dist/lib/lanes/repo-merge-hold.d.ts +39 -0
  91. package/dist/lib/lanes/repo-merge-hold.js +90 -0
  92. package/dist/lib/lanes/watcher-main.js +3 -3
  93. package/dist/lib/mesh/live/daemon/doctor.js +1 -1
  94. package/dist/lib/mesh/live/daemon/install.js +2 -2
  95. package/dist/lib/scan-packages/index.js +8 -9
  96. package/dist/lib/signals/engine.d.ts +8 -0
  97. package/dist/lib/signals/engine.js +15 -5
  98. package/dist/lib/sync-core/flag.d.ts +18 -0
  99. package/dist/lib/sync-core/flag.js +66 -0
  100. package/dist/lib/sync-core/reconcile.d.ts +6 -0
  101. package/dist/lib/sync-core/reconcile.js +15 -0
  102. package/dist/lib/sync-core/rollout-state.d.ts +2 -0
  103. package/dist/lib/sync-core/rollout-state.js +7 -0
  104. package/dist/lib/sync-core/vault-settings.d.ts +12 -1
  105. package/dist/lib/sync-core/vault-settings.js +23 -7
  106. package/dist/lib/windows/install-followup.js +1 -1
  107. package/dist/utils/client-health-contract.d.ts +1 -0
  108. package/dist/utils/client-health-contract.js +5 -0
  109. package/dist/utils/client-health.d.ts +2 -0
  110. package/dist/utils/client-health.js +40 -0
  111. package/dist/utils/cognito-session.d.ts +2 -14
  112. package/dist/utils/cognito-session.js +2 -40
  113. package/dist/utils/daemon-cli-version.d.ts +13 -0
  114. package/dist/utils/daemon-cli-version.js +47 -0
  115. package/dist/utils/duplicate-command-usage.js +1 -1
  116. package/dist/utils/machine-token-cache.d.ts +21 -0
  117. package/dist/utils/machine-token-cache.js +49 -0
  118. package/dist/utils/pack-contributions.d.ts +14 -2
  119. package/dist/utils/pack-contributions.js +31 -5
  120. package/dist/utils/resident-package-preload.js +4 -0
  121. package/dist/utils/whoami-identity.d.ts +54 -0
  122. package/dist/utils/whoami-identity.js +108 -0
  123. package/package.json +7 -7
  124. package/scripts/bench-core.mjs +34 -3
  125. package/dist/lib/daemon/ops/memory.d.ts +0 -18
  126. package/dist/lib/daemon/ops/memory.js +0 -65
  127. package/dist/lib/daemon/ops/mesh.d.ts +0 -38
  128. package/dist/lib/daemon/ops/mesh.js +0 -70
@@ -0,0 +1,556 @@
1
+ /**
2
+ * The two merge sections of the daemon's state file (state-file.ts):
3
+ *
4
+ * - merge_holds: every repository merge hold record under
5
+ * <hqRoot>/workspace/lanes/holds, grouped by the company that owns it, with
6
+ * that company's `lanes.repo-merge-hold` flag;
7
+ * - merge_approvals: per session id, the conduct-link decision queue that
8
+ * gates the session's merges, the session's company, and whether the
9
+ * `lanes.review-before-merge` gate applies to it, with the lane review
10
+ * records.
11
+ *
12
+ * The native merge check in crates/hq-hook reads only these two sections and
13
+ * starts no process. It refuses every merge while a section is missing, has a
14
+ * missing or wrongly typed field, or its `refreshed_at` is older than
15
+ * min(max_age_seconds, 60) seconds, so whenever a decision cannot be made here
16
+ * the section (or the session) is written so the check refuses:
17
+ *
18
+ * - a hold file `hq lanes hold` would refuse, an unreadable holds folder, or
19
+ * an unreadable `lanes.repo-merge-hold` flag omits merge_holds;
20
+ * - an unreadable link folder omits merge_approvals;
21
+ * - a session the conduct gate covers (a link pointer and a decision queue)
22
+ * whose company cannot be resolved is written with queue_status
23
+ * "unreadable";
24
+ * - an unreadable `lanes.review-before-merge` flag writes review_required
25
+ * true with no reviews.
26
+ *
27
+ * Files are read through src/lib/safe-store.ts (a regular single-link file of
28
+ * this user in a folder no other user can write), except lane records and
29
+ * review records, which are read with their stores' own validating readers.
30
+ * Nothing here starts a process; the flags are read from the flag registry.
31
+ */
32
+ import * as fs from "node:fs";
33
+ import * as path from "node:path";
34
+ import { openStoreDir } from "../safe-store.js";
35
+ import { holdFilePath, LANES_REPO_MERGE_HOLD_FLAG, LANES_REVIEW_BEFORE_MERGE_FLAG, parseHold, REPO_MERGE_HOLDS_REL, } from "../lanes/repo-merge-hold.js";
36
+ import { listLaneIds, readLane } from "../lanes/store.js";
37
+ import { resolveLaneCompany } from "../lanes/lane-company.js";
38
+ import { listLaneReviews } from "../lanes/reviews.js";
39
+ import { readLanesRegistryFlagResult } from "../lanes/registry-flag.js";
40
+ import { readCompaniesManifestMap } from "../work-context/repo-remote.js";
41
+ import { TERMINAL_LANE_STATES } from "../lanes/types.js";
42
+ import { findSecretText } from "../lanes/text-scan.js";
43
+ export const MERGE_HOLDS_SCHEMA = "merge-holds.v1";
44
+ export const MERGE_APPROVALS_SCHEMA = "merge-approvals.v1";
45
+ /** Written as each section's max_age_seconds; the native check caps it at 60 anyway. */
46
+ export const MERGE_SECTION_MAX_AGE_SECONDS = 60;
47
+ /**
48
+ * How long after one refresh finishes the next starts. A section is refused
49
+ * past 60 s, so this plus two refresh durations (each bounded by
50
+ * MERGE_FLAG_READ_TIMEOUT_MS) stays under it.
51
+ */
52
+ export const MERGE_SECTION_REFRESH_INTERVAL_MS = 15_000;
53
+ /** A flag value is asked of the registry again after this long. */
54
+ export const MERGE_FLAG_TTL_MS = 30_000;
55
+ /** A flag read that takes longer than this counts as unreadable. */
56
+ export const MERGE_FLAG_READ_TIMEOUT_MS = 12_000;
57
+ const LINK_ID_RE = /^[A-Za-z0-9._-]{1,200}$/;
58
+ const REPO_RE = /^[a-z0-9_.-]+\/[a-z0-9_.-]+$/;
59
+ const HEAD_SHA_RE = /^[0-9a-f]{40}$/;
60
+ const COMPANY_UID_RE = /^cmp_[A-Za-z0-9]{3,128}$/;
61
+ const COMPANY_SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
62
+ const MAX_HOLD_BYTES = 1024 * 1024;
63
+ const MAX_POINTER_BYTES = 4096;
64
+ const MAX_QUEUE_BYTES = 4 * 1024 * 1024;
65
+ const MAX_SESSION_META_BYTES = 256 * 1024;
66
+ const LINKS_BY_SESSION_REL = path.join("workspace", "lanes-links", "by-session");
67
+ const CONDUCT_REPORTS_REL = path.join("workspace", "reports", "conduct");
68
+ const TERMINAL_STATES = new Set(TERMINAL_LANE_STATES);
69
+ /** A folder through safe-store: the store, "missing", or "refused". */
70
+ function openFolder(dir) {
71
+ const opened = openStoreDir(dir);
72
+ if (opened.ok)
73
+ return opened.value;
74
+ return opened.code === "folder-missing" ? "missing" : "refused";
75
+ }
76
+ function readIn(store, name, maxBytes) {
77
+ const read = store.read(name, { maxBytes });
78
+ if (read.ok)
79
+ return { kind: "text", text: read.value.toString("utf8") };
80
+ return read.code === "missing" ? { kind: "missing" } : { kind: "refused" };
81
+ }
82
+ function readOne(file, maxBytes) {
83
+ const folder = openFolder(path.dirname(file));
84
+ if (folder === "missing")
85
+ return { kind: "missing" };
86
+ if (folder === "refused")
87
+ return { kind: "refused" };
88
+ try {
89
+ return readIn(folder, path.basename(file), maxBytes);
90
+ }
91
+ finally {
92
+ folder.close();
93
+ }
94
+ }
95
+ function isRecord(value) {
96
+ return typeof value === "object" && value !== null && !Array.isArray(value);
97
+ }
98
+ /**
99
+ * Every hold record, or null when any of them is one `hq lanes hold list`
100
+ * would refuse (unreadable, not JSON, invalid fields, or a file name that
101
+ * does not match its repository), or when the folder cannot be read.
102
+ */
103
+ export function readMergeHoldRecords(hqRoot) {
104
+ const directory = path.join(hqRoot, REPO_MERGE_HOLDS_REL);
105
+ const folder = openFolder(directory);
106
+ if (folder === "missing")
107
+ return [];
108
+ if (folder === "refused")
109
+ return null;
110
+ try {
111
+ const listed = folder.list();
112
+ if (!listed.ok)
113
+ return null;
114
+ const holds = [];
115
+ for (const name of listed.value.filter((entry) => entry.endsWith(".json")).sort()) {
116
+ const file = path.join(directory, name);
117
+ const read = readIn(folder, name, MAX_HOLD_BYTES);
118
+ // A file removed between the listing and the read was released by `hq lanes hold`.
119
+ if (read.kind === "missing")
120
+ continue;
121
+ if (read.kind === "refused")
122
+ return null;
123
+ let hold;
124
+ try {
125
+ hold = parseHold(JSON.parse(read.text), file);
126
+ }
127
+ catch {
128
+ return null;
129
+ }
130
+ if (holdFilePath(hqRoot, hold.repo) !== file)
131
+ return null;
132
+ holds.push(hold);
133
+ }
134
+ return holds;
135
+ }
136
+ finally {
137
+ folder.close();
138
+ }
139
+ }
140
+ /** The merge_holds section, or null to leave it out of the state file. */
141
+ export async function buildMergeHoldsSection(input) {
142
+ const holds = readMergeHoldRecords(input.hqRoot);
143
+ if (!holds)
144
+ return null;
145
+ const grouped = new Map();
146
+ for (const hold of holds) {
147
+ if (!REPO_RE.test(hold.repo))
148
+ return null;
149
+ const uid = hold.company.uid;
150
+ const existing = grouped.get(uid);
151
+ // One uid under two slugs cannot be matched to a session's company.
152
+ if (existing && existing.company.slug !== hold.company.slug)
153
+ return null;
154
+ const entry = {
155
+ repo: hold.repo,
156
+ reason: hold.reason,
157
+ set_at: hold.set_at,
158
+ until: hold.until,
159
+ released_at: hold.released_at ?? null,
160
+ };
161
+ if (existing)
162
+ existing.holds.push(entry);
163
+ else
164
+ grouped.set(uid, { company: { uid, slug: hold.company.slug }, holds: [entry] });
165
+ }
166
+ const uids = [...grouped.keys()].sort();
167
+ // One read per company, all at once, so a slow registry costs one timeout.
168
+ const flags = await Promise.all(uids.map((uid) => input.readFlag(LANES_REPO_MERGE_HOLD_FLAG, grouped.get(uid).company)));
169
+ const companies = {};
170
+ for (const [index, uid] of uids.entries()) {
171
+ const enabled = flags[index];
172
+ // Never `enabled: false` for a flag that could not be read.
173
+ if (enabled === null)
174
+ return null;
175
+ companies[uid] = { slug: grouped.get(uid).company.slug, enabled, holds: grouped.get(uid).holds };
176
+ }
177
+ return {
178
+ schema: MERGE_HOLDS_SCHEMA,
179
+ refreshed_at: input.now.toISOString(),
180
+ max_age_seconds: MERGE_SECTION_MAX_AGE_SECONDS,
181
+ companies,
182
+ };
183
+ }
184
+ /**
185
+ * A conduct decision queue folded to the latest state of each row id, in
186
+ * first-seen order: later rows override earlier fields. Blank and unparseable
187
+ * lines (a torn last line among them) and rows without an id are skipped.
188
+ */
189
+ export function foldDecisionQueue(text) {
190
+ const rows = new Map();
191
+ for (const line of text.split("\n")) {
192
+ if (!line.trim())
193
+ continue;
194
+ let row;
195
+ try {
196
+ row = JSON.parse(line);
197
+ }
198
+ catch {
199
+ continue;
200
+ }
201
+ if (!isRecord(row))
202
+ continue;
203
+ const id = row.id;
204
+ if (typeof id !== "string" && typeof id !== "number")
205
+ continue;
206
+ const key = `${typeof id}:${String(id)}`;
207
+ rows.set(key, { ...(rows.get(key) ?? {}), ...row });
208
+ }
209
+ const decisions = [];
210
+ let skipped = 0;
211
+ for (const row of rows.values()) {
212
+ if (typeof row.status !== "string" || typeof row.ref !== "string" || typeof row.answer !== "string") {
213
+ skipped += 1;
214
+ continue;
215
+ }
216
+ decisions.push({ status: row.status, ref: row.ref, answer: row.answer });
217
+ }
218
+ return { decisions, skipped };
219
+ }
220
+ /**
221
+ * The conduct gate for one session: null when the gate does not cover it (no
222
+ * link pointer, or a pointer without a valid link id), else its link and
223
+ * queue. A pointer that exists but cannot be read gives an unreadable queue.
224
+ */
225
+ function readLinkQueue(byFolder, conduct, sid) {
226
+ const pointer = readIn(byFolder, sid, MAX_POINTER_BYTES);
227
+ if (pointer.kind === "missing")
228
+ return null;
229
+ if (pointer.kind === "refused")
230
+ return { link_id: "", queue_status: "unreadable", decisions: [] };
231
+ const link = pointer.text.trim().split(/\s+/)[1] ?? "";
232
+ if (!LINK_ID_RE.test(link))
233
+ return null;
234
+ if (conduct === "missing")
235
+ return { link_id: link, queue_status: "absent", decisions: [] };
236
+ if (conduct === "refused")
237
+ return { link_id: link, queue_status: "unreadable", decisions: [] };
238
+ const queue = readIn(conduct, `${link}-decisions.jsonl`, MAX_QUEUE_BYTES);
239
+ if (queue.kind === "missing")
240
+ return { link_id: link, queue_status: "absent", decisions: [] };
241
+ if (queue.kind === "refused")
242
+ return { link_id: link, queue_status: "unreadable", decisions: [] };
243
+ const decisions = foldDecisionQueue(queue.text).decisions;
244
+ // Queue answers are free text. Never copy credentials into hq-state.json;
245
+ // an unreadable queue preserves refusal rather than granting approval.
246
+ if (decisions.some((decision) => Object.values(decision).some((text) => findSecretText(text)))) {
247
+ return { link_id: link, queue_status: "unreadable", decisions: [] };
248
+ }
249
+ return { link_id: link, queue_status: "present", decisions };
250
+ }
251
+ /** `companies/<slug>/.company-uid` when it exists, else the slug's cloud_uid in companies/manifest.yaml. */
252
+ function companyUidForSlug(hqRoot, slug) {
253
+ if (!COMPANY_SLUG_RE.test(slug))
254
+ return null;
255
+ let uid;
256
+ const marker = readOne(path.join(hqRoot, "companies", slug, ".company-uid"), 4096);
257
+ if (marker.kind === "refused")
258
+ return null;
259
+ if (marker.kind === "text")
260
+ uid = marker.text.trim();
261
+ else
262
+ uid = readCompaniesManifestMap(hqRoot)?.[slug]?.cloud_uid;
263
+ return typeof uid === "string" && COMPANY_UID_RE.test(uid) ? uid : null;
264
+ }
265
+ /** The company a session's meta.yaml names (`company_slug`), the way `hq lanes link join` reads it. */
266
+ function sessionMetaCompany(hqRoot, sid) {
267
+ const meta = readOne(path.join(hqRoot, "workspace", "sessions", sid, "meta.yaml"), MAX_SESSION_META_BYTES);
268
+ if (meta.kind !== "text")
269
+ return null;
270
+ const slug = /^\s*company_slug:\s*["']?([^\s"'#]+)["']?\s*$/m.exec(meta.text)?.[1] ?? "";
271
+ const uid = slug ? companyUidForSlug(hqRoot, slug) : null;
272
+ return uid ? { slug, uid } : null;
273
+ }
274
+ function laneSessionIds(lane) {
275
+ const ids = [lane.provider_session_id, lane.last_resume?.session_id];
276
+ return ids.filter((id) => typeof id === "string" && LINK_ID_RE.test(id));
277
+ }
278
+ /**
279
+ * The review context `hq lanes hold check` builds for a caller lane, for every
280
+ * live lane whose provider session id is known: the lane's company, and
281
+ * whether the review-before-merge flag is on for it and the lane is a senior
282
+ * of another lane.
283
+ */
284
+ async function laneSessions(hqRoot, readFlag) {
285
+ const out = new Map();
286
+ let ids;
287
+ try {
288
+ ids = listLaneIds(hqRoot);
289
+ }
290
+ catch {
291
+ return null;
292
+ }
293
+ const lanes = [];
294
+ for (const id of ids) {
295
+ try {
296
+ lanes.push(readLane(hqRoot, id));
297
+ }
298
+ catch {
299
+ // This may be the caller or a junior that makes the caller a senior.
300
+ // `hq lanes hold check` refuses here too; an empty session map allows.
301
+ return null;
302
+ }
303
+ }
304
+ const seniors = new Set();
305
+ for (const lane of lanes)
306
+ if (lane.senior.kind === "lane" && lane.senior.id)
307
+ seniors.add(lane.senior.id);
308
+ const live = [];
309
+ for (const lane of lanes) {
310
+ if (TERMINAL_STATES.has(lane.state))
311
+ continue;
312
+ const sessions = laneSessionIds(lane);
313
+ if (sessions.length === 0)
314
+ continue;
315
+ let company;
316
+ try {
317
+ company = resolveLaneCompany(hqRoot, lane).company;
318
+ }
319
+ catch {
320
+ company = null;
321
+ }
322
+ live.push({ lane, sessions, company });
323
+ }
324
+ // One read per company, all at once, so a slow registry costs one timeout.
325
+ const companyKey = (company) => JSON.stringify([company.uid, company.slug]);
326
+ const byKey = new Map();
327
+ for (const { company } of live)
328
+ if (company)
329
+ byKey.set(companyKey(company), company);
330
+ const keys = [...byKey.keys()];
331
+ const values = await Promise.all(keys.map((key) => readFlag(LANES_REVIEW_BEFORE_MERGE_FLAG, byKey.get(key))));
332
+ const flags = new Map(keys.map((key, index) => [key, values[index]]));
333
+ for (const { lane, sessions, company } of live) {
334
+ let review = "off";
335
+ if (company) {
336
+ const enabled = flags.get(companyKey(company));
337
+ if (enabled === null)
338
+ review = "unreadable";
339
+ else if (enabled && seniors.has(lane.lane_id))
340
+ review = "required";
341
+ }
342
+ for (const sid of sessions) {
343
+ const previous = out.get(sid);
344
+ // Two lanes naming one session: the stricter answer wins.
345
+ if (!previous || (previous.review === "off" && review !== "off") || (previous.review === "required" && review === "unreadable")) {
346
+ out.set(sid, { company: company ?? previous?.company ?? null, review });
347
+ }
348
+ }
349
+ }
350
+ return out;
351
+ }
352
+ /** The merge_approvals section, or null to leave it out of the state file. */
353
+ export async function buildMergeApprovalsSection(input) {
354
+ const { hqRoot } = input;
355
+ const byFolder = openFolder(path.join(hqRoot, LINKS_BY_SESSION_REL));
356
+ if (byFolder === "refused")
357
+ return null;
358
+ const conduct = openFolder(path.join(hqRoot, CONDUCT_REPORTS_REL));
359
+ try {
360
+ const links = new Map();
361
+ if (byFolder !== "missing") {
362
+ const listed = byFolder.list();
363
+ if (!listed.ok)
364
+ return null;
365
+ for (const sid of listed.value.sort()) {
366
+ if (!LINK_ID_RE.test(sid))
367
+ continue;
368
+ const queue = readLinkQueue(byFolder, conduct, sid);
369
+ if (queue)
370
+ links.set(sid, queue);
371
+ }
372
+ }
373
+ const lanes = await laneSessions(hqRoot, input.readFlag);
374
+ if (!lanes)
375
+ return null;
376
+ let reviews;
377
+ const allReviews = () => {
378
+ reviews ??= listLaneReviews(hqRoot).reviews
379
+ .filter((review) => REPO_RE.test(review.repo) && Number.isSafeInteger(review.pr) && review.pr > 0 && HEAD_SHA_RE.test(review.head_sha))
380
+ .map((review) => ({ repo: review.repo, pr: review.pr, head_sha: review.head_sha }));
381
+ return reviews;
382
+ };
383
+ const sessions = {};
384
+ for (const sid of [...new Set([...links.keys(), ...lanes.keys()])].sort()) {
385
+ const link = links.get(sid);
386
+ const lane = lanes.get(sid);
387
+ // Without a queue and without the review gate, a listed session is the
388
+ // same as an unlisted one; leaving it out keeps the section small.
389
+ const gated = link !== undefined && link.queue_status !== "absent";
390
+ if (!gated && (!lane || lane.review === "off"))
391
+ continue;
392
+ const company = lane?.company ?? sessionMetaCompany(hqRoot, sid);
393
+ if (!company) {
394
+ // The conduct gate covers this session but its company is unknown:
395
+ // the native check is told the queue is unreadable, so it refuses.
396
+ if (gated) {
397
+ sessions[sid] = {
398
+ company_uid: "",
399
+ company_slug: "",
400
+ link_id: link.link_id,
401
+ queue_status: "unreadable",
402
+ decisions: [],
403
+ review_required: false,
404
+ reviews: [],
405
+ };
406
+ }
407
+ continue;
408
+ }
409
+ const review = lane?.review ?? "off";
410
+ sessions[sid] = {
411
+ company_uid: company.uid,
412
+ company_slug: company.slug,
413
+ link_id: link?.link_id ?? "",
414
+ queue_status: link?.queue_status ?? "absent",
415
+ decisions: link?.decisions ?? [],
416
+ review_required: review !== "off",
417
+ reviews: review === "required" ? allReviews() : [],
418
+ };
419
+ }
420
+ return {
421
+ schema: MERGE_APPROVALS_SCHEMA,
422
+ refreshed_at: input.now.toISOString(),
423
+ max_age_seconds: MERGE_SECTION_MAX_AGE_SECONDS,
424
+ sessions,
425
+ };
426
+ }
427
+ finally {
428
+ if (typeof byFolder === "object")
429
+ byFolder.close();
430
+ if (typeof conduct === "object")
431
+ conduct.close();
432
+ }
433
+ }
434
+ /** Both sections, read at `input.now`. A builder that throws leaves its section out. */
435
+ export async function buildMergeSections(input) {
436
+ const [holds, approvals] = await Promise.all([
437
+ buildMergeHoldsSection(input).catch(() => null),
438
+ buildMergeApprovalsSection(input).catch(() => null),
439
+ ]);
440
+ return { merge_holds: holds, merge_approvals: approvals };
441
+ }
442
+ async function registryRead(flag, company, env) {
443
+ const result = await readLanesRegistryFlagResult(flag, {
444
+ company,
445
+ env,
446
+ shareProcessRead: false,
447
+ reportFailure: () => { },
448
+ });
449
+ return result.state === "resolved" ? result.value : null;
450
+ }
451
+ /**
452
+ * Lanes flags as `hq lanes hold check` reads them (readLanesRegistryFlag: local
453
+ * override, then the registry, then its last-known-good cache on a transient
454
+ * failure), asked again after `ttlMs`. A read that fails, throws or takes
455
+ * longer than `timeoutMs` is null and is not kept.
456
+ */
457
+ export function createRegistryMergeFlagReader(options) {
458
+ const ttlMs = options.ttlMs ?? MERGE_FLAG_TTL_MS;
459
+ const timeoutMs = options.timeoutMs ?? MERGE_FLAG_READ_TIMEOUT_MS;
460
+ const now = options.now ?? (() => performance.now());
461
+ const read = options.read ?? registryRead;
462
+ const held = new Map();
463
+ return async (flag, company) => {
464
+ const key = JSON.stringify([flag, company.uid, company.slug]);
465
+ const kept = held.get(key);
466
+ if (kept && now() - kept.at < ttlMs)
467
+ return kept.value;
468
+ const startedAt = now();
469
+ let timer;
470
+ const timeout = new Promise((resolve) => {
471
+ timer = setTimeout(() => resolve(null), timeoutMs);
472
+ timer.unref?.();
473
+ });
474
+ let value;
475
+ try {
476
+ value = await Promise.race([read(flag, company, options.env), timeout]);
477
+ }
478
+ catch {
479
+ value = null;
480
+ }
481
+ finally {
482
+ clearTimeout(timer);
483
+ }
484
+ if (value === null)
485
+ held.delete(key);
486
+ else
487
+ held.set(key, { at: startedAt, value });
488
+ return value;
489
+ };
490
+ }
491
+ /**
492
+ * Rebuild both sections now and then every `intervalMs` after the previous
493
+ * build finished, and hand each result to `onRefresh`. Builds never overlap.
494
+ */
495
+ export function startMergeSectionRefresh(options) {
496
+ const intervalMs = options.intervalMs ?? MERGE_SECTION_REFRESH_INTERVAL_MS;
497
+ const wallClock = options.wallClock ?? (() => new Date());
498
+ let current = { merge_holds: null, merge_approvals: null };
499
+ let closed = false;
500
+ let timer;
501
+ let running;
502
+ const fresh = (section) => {
503
+ if (!section)
504
+ return null;
505
+ const age = wallClock().getTime() - Date.parse(section.refreshed_at);
506
+ return age <= Math.min(section.max_age_seconds, MERGE_SECTION_MAX_AGE_SECONDS) * 1000 ? section : null;
507
+ };
508
+ const build = async () => {
509
+ const now = wallClock();
510
+ let hqRoot;
511
+ try {
512
+ const configured = options.hqRoot();
513
+ hqRoot = configured && fs.existsSync(configured) ? configured : undefined;
514
+ }
515
+ catch {
516
+ hqRoot = undefined;
517
+ }
518
+ current = hqRoot
519
+ ? await buildMergeSections({ hqRoot, now, readFlag: options.readFlag })
520
+ : { merge_holds: null, merge_approvals: null };
521
+ if (closed)
522
+ return;
523
+ try {
524
+ options.onRefresh?.();
525
+ }
526
+ catch {
527
+ // the state file writer reports its own problems
528
+ }
529
+ };
530
+ const refresh = () => {
531
+ running ??= build().catch(() => { }).finally(() => { running = undefined; });
532
+ return running;
533
+ };
534
+ const loop = () => {
535
+ if (closed)
536
+ return;
537
+ void refresh().then(() => {
538
+ if (closed)
539
+ return;
540
+ timer = setTimeout(loop, intervalMs);
541
+ timer.unref?.();
542
+ });
543
+ };
544
+ if (options.start !== false)
545
+ loop();
546
+ return {
547
+ latest: () => ({ merge_holds: fresh(current.merge_holds), merge_approvals: fresh(current.merge_approvals) }),
548
+ refresh,
549
+ close() {
550
+ closed = true;
551
+ if (timer)
552
+ clearTimeout(timer);
553
+ },
554
+ };
555
+ }
556
+ //# sourceMappingURL=merge-sections.js.map
@@ -24,4 +24,13 @@ export declare const NATIVE_NOTICE_LEDGER_REFUSED = "the native notice cannot us
24
24
  * shared. Reading is by lstat, a handful of calls, no process.
25
25
  */
26
26
  export declare function nativeNoticeLedgerUsable(env: NodeJS.ProcessEnv, home: string): boolean;
27
+ /**
28
+ * The fingerprints (lowercase hex) the native SessionStart notice recorded as
29
+ * delivered, read from this environment's ledger (`HQ_HOOK_STATE_DIR`, or
30
+ * `<home>/.hq/state/hq-hook`). Read-only and without the notice's lock: a
31
+ * read that races a write can miss an entry, which only delays the commit to
32
+ * the next batch. Empty when the ledger is unusable (nativeNoticeLedgerUsable),
33
+ * missing, not a single-link regular file, or not the expected size and magic.
34
+ */
35
+ export declare function nativeNoticeShownFingerprints(env: NodeJS.ProcessEnv, home: string): Set<string>;
27
36
  //# sourceMappingURL=native-notice-ledger.d.ts.map
@@ -110,4 +110,47 @@ export function nativeNoticeLedgerUsable(env, home) {
110
110
  return stat.isFile() && stat.nlink === 1 && ownedOk(stat) && !looseBits(stat);
111
111
  }
112
112
  }
113
+ /** Ledger layout (`MAGIC`, `HEADER_BYTES`, `SLOT`, `SLOTS` in crates/hq-hook/src/session_start.rs). */
114
+ const LEDGER_MAGIC = Buffer.from("HQMCSN1\n", "latin1");
115
+ const LEDGER_HEADER_BYTES = 16;
116
+ const LEDGER_SLOT = 32;
117
+ const LEDGER_SLOTS = 256;
118
+ const LEDGER_SIZE = LEDGER_HEADER_BYTES + LEDGER_SLOT * LEDGER_SLOTS;
119
+ /**
120
+ * The fingerprints (lowercase hex) the native SessionStart notice recorded as
121
+ * delivered, read from this environment's ledger (`HQ_HOOK_STATE_DIR`, or
122
+ * `<home>/.hq/state/hq-hook`). Read-only and without the notice's lock: a
123
+ * read that races a write can miss an entry, which only delays the commit to
124
+ * the next batch. Empty when the ledger is unusable (nativeNoticeLedgerUsable),
125
+ * missing, not a single-link regular file, or not the expected size and magic.
126
+ */
127
+ export function nativeNoticeShownFingerprints(env, home) {
128
+ const shown = new Set();
129
+ if (!nativeNoticeLedgerUsable(env, home))
130
+ return shown;
131
+ const override = env.HQ_HOOK_STATE_DIR;
132
+ const folder = override ? override : `${home}/.hq/state/hq-hook`;
133
+ const file = path.posix.join(folder, NATIVE_NOTICE_LEDGER_FILE);
134
+ let bytes;
135
+ try {
136
+ const stat = fs.lstatSync(file);
137
+ if (!stat.isFile() || stat.nlink !== 1 || stat.size !== LEDGER_SIZE)
138
+ return shown;
139
+ bytes = fs.readFileSync(file);
140
+ }
141
+ catch {
142
+ return shown;
143
+ }
144
+ if (bytes.length !== LEDGER_SIZE || !bytes.subarray(0, LEDGER_MAGIC.length).equals(LEDGER_MAGIC))
145
+ return shown;
146
+ for (let index = 0; index < LEDGER_SLOTS; index += 1) {
147
+ const start = LEDGER_HEADER_BYTES + index * LEDGER_SLOT;
148
+ const slot = bytes.subarray(start, start + LEDGER_SLOT);
149
+ // An all-zero slot is empty (the notice never records an all-zero print).
150
+ if (slot.every((byte) => byte === 0))
151
+ continue;
152
+ shown.add(slot.toString("hex"));
153
+ }
154
+ return shown;
155
+ }
113
156
  //# sourceMappingURL=native-notice-ledger.js.map
@@ -1,5 +1,5 @@
1
1
  /**
2
- * policy.check and policy.index ops (hq-anywhere US-009).
2
+ * policy.check op (hq-anywhere US-009) and the policy index it counts from.
3
3
  *
4
4
  * Verdicts come from the hq-core hook scripts under HQ_ROOT, run as child
5
5
  * processes with a synthesized hook payload, so hookless hosts and sub-agents
@@ -1,5 +1,5 @@
1
1
  /**
2
- * policy.check and policy.index ops (hq-anywhere US-009).
2
+ * policy.check op (hq-anywhere US-009) and the policy index it counts from.
3
3
  *
4
4
  * Verdicts come from the hq-core hook scripts under HQ_ROOT, run as child
5
5
  * processes with a synthesized hook payload, so hookless hosts and sub-agents
@@ -7,7 +7,7 @@
7
7
  * out of order, so clients match them by `id`.
8
8
  */
9
9
  export declare const HQD_SOCKET_NAME = "hqd.sock";
10
- export declare const HQD_OPS: readonly ["ping", "health", "resolve", "session.open", "session.get", "session.close", "policy.check", "policy.index", "journal.append", "memory.get", "memory.put", "mesh.presence", "mcp.call", "auth.login", "auth.status", "shutdown"];
10
+ export declare const HQD_OPS: readonly ["ping", "health", "resolve", "session.open", "session.close", "policy.check", "journal.append", "mcp.call", "auth.login", "auth.status"];
11
11
  export type HqdOp = (typeof HQD_OPS)[number];
12
12
  export type HqdHealthFallbackReason = "registry_unavailable" | "manifest_missing_or_malformed" | "company_not_in_manifest" | "no_match";
13
13
  export interface HqdHealthResult {
@@ -16,18 +16,12 @@ export const HQD_OPS = [
16
16
  "health",
17
17
  "resolve",
18
18
  "session.open",
19
- "session.get",
20
19
  "session.close",
21
20
  "policy.check",
22
- "policy.index",
23
21
  "journal.append",
24
- "memory.get",
25
- "memory.put",
26
- "mesh.presence",
27
22
  "mcp.call",
28
23
  "auth.login",
29
24
  "auth.status",
30
- "shutdown",
31
25
  ];
32
26
  /** A request line larger than this is rejected and the connection closed. */
33
27
  export const HQD_MAX_LINE_BYTES = 1024 * 1024;