@indigoai-us/hq-cli 5.345.264 → 5.345.267

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 (31) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/assets/scaffold/core/scripts/hq-delegate-grant.sh +4 -48
  3. package/assets/scaffold/core/scripts/hq-delegate-secrets.sh +16 -10
  4. package/assets/scaffold/core/scripts/hq-delegate-send.sh +17 -1
  5. package/contracts/host-canary-release.json +7 -7
  6. package/dist/command-catalog.generated.d.ts +30 -1
  7. package/dist/command-catalog.generated.js +37 -1
  8. package/dist/commands/core-delegate-w1b.js +21 -40
  9. package/dist/commands/core-delegate.js +11 -8
  10. package/dist/commands/files-browse.d.ts +83 -4
  11. package/dist/commands/files-browse.js +404 -54
  12. package/dist/commands/groups.js +2 -2
  13. package/dist/commands/skill.js +15 -0
  14. package/dist/lib/agent-kit/mcp/tools.js +2 -2
  15. package/dist/lib/agent-kit/skills.js +12 -6
  16. package/dist/lib/daemon/merge-sections.d.ts +44 -9
  17. package/dist/lib/daemon/merge-sections.js +234 -37
  18. package/dist/lib/daemon/run.js +1 -0
  19. package/dist/lib/doctor/checks/antigravity-wiring.js +20 -4
  20. package/dist/lib/doctor/checks/host-core.js +9 -4
  21. package/dist/lib/doctor/fix/process-identity.d.ts +2 -0
  22. package/dist/lib/doctor/fix/process-identity.js +5 -2
  23. package/dist/lib/hook-engine/coverage.js +13 -1
  24. package/dist/lib/hook-engine/native-precompact-compatibility.json +1 -0
  25. package/dist/lib/hook-engine/reconcile.js +13 -3
  26. package/dist/lib/signals/reply.js +25 -5
  27. package/dist/lib/signals/steps/extract.d.ts +28 -4
  28. package/dist/lib/signals/steps/extract.js +124 -10
  29. package/dist/lib/sync-core/release.d.ts +1 -1
  30. package/dist/lib/sync-core/release.js +2 -2
  31. package/package.json +7 -7
@@ -4,16 +4,27 @@
4
4
  * - merge_holds: every repository merge hold record under
5
5
  * <hqRoot>/workspace/lanes/holds, grouped by the company that owns it, with
6
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.
7
+ * - merge_approvals: per session id, the conduct link whose decision queue
8
+ * gates the session's merges and whether that queue could be read (closed
9
+ * links and stale conductor pointers omitted), the session's company, and
10
+ * whether the `lanes.review-before-merge` gate applies to it, with the lane
11
+ * review records.
12
+ *
13
+ * `decisions` is always written as an empty array. The native owner-approval
14
+ * gate (crates/hq-hook/src/rules/conduct_files.rs) reads the conduct link and
15
+ * its decision queue from disk when the merge is called, so unanswered,
16
+ * withdrawn and superseded decisions are decided there; no reader decides from
17
+ * this section's copy. Copying the queue once per session made the section
18
+ * grow with sessions x queue length (4.5 MB on one machine). The key stays,
19
+ * as an empty array, because released hook binaries require it when
20
+ * queue_status is "present".
11
21
  *
12
22
  * The native merge check in crates/hq-hook reads only these two sections and
13
23
  * 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:
24
+ * missing or wrongly typed field, exceeds MAX_SECTION_BYTES (256 KiB), or its
25
+ * `refreshed_at` is older than min(max_age_seconds, 60) seconds, so whenever a
26
+ * decision cannot be made here the section (or the session) is written so the
27
+ * check refuses:
17
28
  *
18
29
  * - a hold file `hq runners hold` would refuse, an unreadable holds folder, or
19
30
  * an unreadable `lanes.repo-merge-hold` flag omits merge_holds;
@@ -22,7 +33,12 @@
22
33
  * whose company cannot be resolved is written with queue_status
23
34
  * "unreadable";
24
35
  * - an unreadable `lanes.review-before-merge` flag writes review_required
25
- * true with no reviews.
36
+ * true with no reviews;
37
+ * - if merge_approvals would still exceed MERGE_APPROVALS_MAX_SECTION_BYTES
38
+ * (a backstop: with no decisions copied it is not expected), the largest
39
+ * sessions lose their review records while keeping review_required, so
40
+ * only those sessions refuse, rather than letting the whole section exceed
41
+ * the reader's cap and refuse every session.
26
42
  *
27
43
  * Files are read through src/lib/safe-store.ts (a regular single-link file of
28
44
  * this user in a folder no other user can write), except lane records and
@@ -33,6 +49,12 @@ import { type RepoMergeHold } from "../lanes/repo-merge-hold.js";
33
49
  import { type LaneCompanyRef } from "../lanes/types.js";
34
50
  export declare const MERGE_HOLDS_SCHEMA = "merge-holds.v1";
35
51
  export declare const MERGE_APPROVALS_SCHEMA = "merge-approvals.v1";
52
+ export declare const MERGE_APPROVALS_SECTION_NAME = "merge_approvals";
53
+ /**
54
+ * Per-section cap enforced by `crates/hq-hook/src/state.rs` (`MAX_SECTION_BYTES`):
55
+ * the section name (`"merge_approvals"`) plus compact UTF-8 JSON bytes.
56
+ */
57
+ export declare const MERGE_APPROVALS_MAX_SECTION_BYTES: number;
36
58
  /** Written as each section's max_age_seconds; the native check caps it at 60 anyway. */
37
59
  export declare const MERGE_SECTION_MAX_AGE_SECONDS = 60;
38
60
  /**
@@ -79,7 +101,8 @@ export interface MergeApprovalSession {
79
101
  company_slug: string;
80
102
  link_id: string;
81
103
  queue_status: MergeQueueStatus;
82
- decisions: MergeDecision[];
104
+ /** Always empty: the owner-approval gate reads the queue file itself. */
105
+ decisions: [];
83
106
  review_required: boolean;
84
107
  reviews: MergeReview[];
85
108
  }
@@ -109,11 +132,16 @@ export interface MergeSections {
109
132
  }
110
133
  /** A lanes flag for one company: its value, or null when it could not be read. */
111
134
  export type MergeFlagReader = (flag: string, company: LaneCompanyRef) => Promise<boolean | null>;
135
+ export type MergeSectionLog = (level: "info" | "warn" | "error", message: string) => void;
112
136
  export interface MergeSectionInput {
113
137
  hqRoot: string;
114
138
  /** Written as refreshed_at; take it before any file is read. */
115
139
  now: Date;
116
140
  readFlag: MergeFlagReader;
141
+ /** Optional log sink for size-guard warnings. */
142
+ log?: MergeSectionLog;
143
+ /** Test seam: override MERGE_APPROVALS_MAX_SECTION_BYTES. */
144
+ maxApprovalsSectionBytes?: number;
117
145
  }
118
146
  /**
119
147
  * Every hold record, or null when any of them is one `hq runners hold list`
@@ -134,6 +162,11 @@ export interface FoldedQueue {
134
162
  * lines (a torn last line among them) and rows without an id are skipped.
135
163
  */
136
164
  export declare function foldDecisionQueue(text: string): FoldedQueue;
165
+ /**
166
+ * Exact byte size `crates/hq-hook/src/state.rs` measures against
167
+ * `MAX_SECTION_BYTES`: section name plus compact UTF-8 JSON bytes.
168
+ */
169
+ export declare function mergeApprovalsSectionBytes(section: MergeApprovalsSection): number;
137
170
  /** The merge_approvals section, or null to leave it out of the state file. */
138
171
  export declare function buildMergeApprovalsSection(input: MergeSectionInput): Promise<MergeApprovalsSection | null>;
139
172
  /** Both sections, read at `input.now`. A builder that throws leaves its section out. */
@@ -174,6 +207,8 @@ export interface MergeSectionRefresherOptions {
174
207
  readFlag: MergeFlagReader;
175
208
  /** Called after each refresh, to rewrite the state file. */
176
209
  onRefresh?: () => void;
210
+ /** Optional log sink for size-guard warnings (deduplicated across identical ticks). */
211
+ log?: MergeSectionLog;
177
212
  intervalMs?: number;
178
213
  wallClock?: () => Date;
179
214
  /** Start the timer (default true). */
@@ -4,16 +4,27 @@
4
4
  * - merge_holds: every repository merge hold record under
5
5
  * <hqRoot>/workspace/lanes/holds, grouped by the company that owns it, with
6
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.
7
+ * - merge_approvals: per session id, the conduct link whose decision queue
8
+ * gates the session's merges and whether that queue could be read (closed
9
+ * links and stale conductor pointers omitted), the session's company, and
10
+ * whether the `lanes.review-before-merge` gate applies to it, with the lane
11
+ * review records.
12
+ *
13
+ * `decisions` is always written as an empty array. The native owner-approval
14
+ * gate (crates/hq-hook/src/rules/conduct_files.rs) reads the conduct link and
15
+ * its decision queue from disk when the merge is called, so unanswered,
16
+ * withdrawn and superseded decisions are decided there; no reader decides from
17
+ * this section's copy. Copying the queue once per session made the section
18
+ * grow with sessions x queue length (4.5 MB on one machine). The key stays,
19
+ * as an empty array, because released hook binaries require it when
20
+ * queue_status is "present".
11
21
  *
12
22
  * The native merge check in crates/hq-hook reads only these two sections and
13
23
  * 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:
24
+ * missing or wrongly typed field, exceeds MAX_SECTION_BYTES (256 KiB), or its
25
+ * `refreshed_at` is older than min(max_age_seconds, 60) seconds, so whenever a
26
+ * decision cannot be made here the section (or the session) is written so the
27
+ * check refuses:
17
28
  *
18
29
  * - a hold file `hq runners hold` would refuse, an unreadable holds folder, or
19
30
  * an unreadable `lanes.repo-merge-hold` flag omits merge_holds;
@@ -22,7 +33,12 @@
22
33
  * whose company cannot be resolved is written with queue_status
23
34
  * "unreadable";
24
35
  * - an unreadable `lanes.review-before-merge` flag writes review_required
25
- * true with no reviews.
36
+ * true with no reviews;
37
+ * - if merge_approvals would still exceed MERGE_APPROVALS_MAX_SECTION_BYTES
38
+ * (a backstop: with no decisions copied it is not expected), the largest
39
+ * sessions lose their review records while keeping review_required, so
40
+ * only those sessions refuse, rather than letting the whole section exceed
41
+ * the reader's cap and refuse every session.
26
42
  *
27
43
  * Files are read through src/lib/safe-store.ts (a regular single-link file of
28
44
  * this user in a folder no other user can write), except lane records and
@@ -43,6 +59,12 @@ import { TERMINAL_LANE_STATES } from "../lanes/types.js";
43
59
  import { findSecretText } from "../lanes/text-scan.js";
44
60
  export const MERGE_HOLDS_SCHEMA = "merge-holds.v1";
45
61
  export const MERGE_APPROVALS_SCHEMA = "merge-approvals.v1";
62
+ export const MERGE_APPROVALS_SECTION_NAME = "merge_approvals";
63
+ /**
64
+ * Per-section cap enforced by `crates/hq-hook/src/state.rs` (`MAX_SECTION_BYTES`):
65
+ * the section name (`"merge_approvals"`) plus compact UTF-8 JSON bytes.
66
+ */
67
+ export const MERGE_APPROVALS_MAX_SECTION_BYTES = 256 * 1024;
46
68
  /** Written as each section's max_age_seconds; the native check caps it at 60 anyway. */
47
69
  export const MERGE_SECTION_MAX_AGE_SECONDS = 60;
48
70
  /**
@@ -62,9 +84,11 @@ const COMPANY_UID_RE = /^cmp_[A-Za-z0-9]{3,128}$/;
62
84
  const COMPANY_SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
63
85
  const MAX_HOLD_BYTES = 1024 * 1024;
64
86
  const MAX_POINTER_BYTES = 4096;
87
+ const MAX_LINK_META_BYTES = 64 * 1024;
65
88
  const MAX_QUEUE_BYTES = 4 * 1024 * 1024;
66
89
  const MAX_SESSION_META_BYTES = 256 * 1024;
67
- const LINKS_BY_SESSION_REL = path.join("workspace", "lanes-links", "by-session");
90
+ const LINKS_REL = path.join("workspace", "lanes-links");
91
+ const LINKS_BY_SESSION_REL = path.join(LINKS_REL, "by-session");
68
92
  const CONDUCT_REPORTS_REL = path.join("workspace", "reports", "conduct");
69
93
  const TERMINAL_STATES = new Set(TERMINAL_LANE_STATES);
70
94
  /** A folder through safe-store: the store, "missing", or "refused". */
@@ -96,6 +120,9 @@ function readOne(file, maxBytes) {
96
120
  function isRecord(value) {
97
121
  return typeof value === "object" && value !== null && !Array.isArray(value);
98
122
  }
123
+ function isSafeLinkId(value) {
124
+ return value !== "." && value !== ".." && LINK_ID_RE.test(value);
125
+ }
99
126
  /**
100
127
  * Every hold record, or null when any of them is one `hq runners hold list`
101
128
  * would refuse (unreadable, not JSON, invalid fields, or a file name that
@@ -218,36 +245,108 @@ export function foldDecisionQueue(text) {
218
245
  }
219
246
  return { decisions, skipped };
220
247
  }
248
+ /**
249
+ * Read `workspace/lanes-links/<link>/meta.json` through safe-store. Returns
250
+ * null when the file is missing, refused, or not a JSON object so callers
251
+ * never drop a session without positive proof its link is closed or stale.
252
+ */
253
+ function readLinkMeta(hqRoot, link, cache) {
254
+ if (cache.has(link))
255
+ return cache.get(link);
256
+ const read = readOne(path.join(hqRoot, LINKS_REL, link, "meta.json"), MAX_LINK_META_BYTES);
257
+ if (read.kind !== "text") {
258
+ cache.set(link, null);
259
+ return null;
260
+ }
261
+ let parsed;
262
+ try {
263
+ parsed = JSON.parse(read.text);
264
+ }
265
+ catch {
266
+ cache.set(link, null);
267
+ return null;
268
+ }
269
+ if (!isRecord(parsed)) {
270
+ cache.set(link, null);
271
+ return null;
272
+ }
273
+ const meta = {
274
+ closed: Boolean(parsed.closed),
275
+ conductorSession: typeof parsed.conductor_session === "string" ? parsed.conductor_session : null,
276
+ };
277
+ cache.set(link, meta);
278
+ return meta;
279
+ }
280
+ /**
281
+ * Same staleness rule as `dropStalePointer` in `src/lib/lanes/links.ts`:
282
+ * a pointer is stale when its link's meta.json marks the link closed, or when
283
+ * a conductor pointer no longer names the link's conductor_session.
284
+ */
285
+ function isStaleLinkPointer(hqRoot, sid, role, link, metaCache) {
286
+ const meta = readLinkMeta(hqRoot, link, metaCache);
287
+ if (!meta)
288
+ return false;
289
+ if (meta.closed)
290
+ return true;
291
+ if (role === "conductor" && meta.conductorSession !== null && meta.conductorSession !== sid)
292
+ return true;
293
+ return false;
294
+ }
295
+ /**
296
+ * Whether a link's decision queue exists and can be read, once per link per
297
+ * build. Its rows are not copied: the native owner-approval gate reads the
298
+ * queue file itself when the merge is called.
299
+ */
300
+ function readQueueStatus(conduct, link, queueCache) {
301
+ const cached = queueCache.get(link);
302
+ if (cached)
303
+ return cached;
304
+ let status;
305
+ if (conduct === "missing") {
306
+ status = "absent";
307
+ }
308
+ else if (conduct === "refused") {
309
+ status = "unreadable";
310
+ }
311
+ else {
312
+ const queue = readIn(conduct, `${link}-decisions.jsonl`, MAX_QUEUE_BYTES);
313
+ if (queue.kind === "missing") {
314
+ status = "absent";
315
+ }
316
+ else if (queue.kind === "refused") {
317
+ status = "unreadable";
318
+ }
319
+ else {
320
+ // Unchanged from when rows were copied: a queue holding sensitive text
321
+ // is written as unreadable, so no change here can turn it into a go.
322
+ const { decisions } = foldDecisionQueue(queue.text);
323
+ const sensitive = decisions.some((decision) => Object.values(decision).some((text) => findSecretText(text)));
324
+ status = sensitive ? "unreadable" : "present";
325
+ }
326
+ }
327
+ queueCache.set(link, status);
328
+ return status;
329
+ }
221
330
  /**
222
331
  * The conduct gate for one session: null when the gate does not cover it (no
223
- * link pointer, or a pointer without a valid link id), else its link and
224
- * queue. A pointer that exists but cannot be read gives an unreadable queue.
332
+ * link pointer, a pointer without a valid link id, or a pointer to a closed
333
+ * link / superseded conductor), else its link and whether its queue could be
334
+ * read. A pointer that exists but cannot be read gives an unreadable queue.
225
335
  */
226
- function readLinkQueue(byFolder, conduct, sid) {
336
+ function readLinkQueue(hqRoot, byFolder, conduct, sid, metaCache, queueCache) {
227
337
  const pointer = readIn(byFolder, sid, MAX_POINTER_BYTES);
228
338
  if (pointer.kind === "missing")
229
339
  return null;
230
340
  if (pointer.kind === "refused")
231
- return { link_id: "", queue_status: "unreadable", decisions: [] };
232
- const link = pointer.text.trim().split(/\s+/)[1] ?? "";
233
- if (!LINK_ID_RE.test(link))
341
+ return { link_id: "", queue_status: "unreadable" };
342
+ const words = pointer.text.trim().split(/\s+/);
343
+ const role = words[0] ?? "";
344
+ const link = words[1] ?? "";
345
+ if (!isSafeLinkId(link))
234
346
  return null;
235
- if (conduct === "missing")
236
- return { link_id: link, queue_status: "absent", decisions: [] };
237
- if (conduct === "refused")
238
- return { link_id: link, queue_status: "unreadable", decisions: [] };
239
- const queue = readIn(conduct, `${link}-decisions.jsonl`, MAX_QUEUE_BYTES);
240
- if (queue.kind === "missing")
241
- return { link_id: link, queue_status: "absent", decisions: [] };
242
- if (queue.kind === "refused")
243
- return { link_id: link, queue_status: "unreadable", decisions: [] };
244
- const decisions = foldDecisionQueue(queue.text).decisions;
245
- // Queue answers are free text. Never copy credentials into hq-state.json;
246
- // an unreadable queue preserves refusal rather than granting approval.
247
- if (decisions.some((decision) => Object.values(decision).some((text) => findSecretText(text)))) {
248
- return { link_id: link, queue_status: "unreadable", decisions: [] };
249
- }
250
- return { link_id: link, queue_status: "present", decisions };
347
+ if (isStaleLinkPointer(hqRoot, sid, role, link, metaCache))
348
+ return null;
349
+ return { link_id: link, queue_status: readQueueStatus(conduct, link, queueCache) };
251
350
  }
252
351
  /** `companies/<slug>/.company-uid` when it exists, else the slug's cloud_uid in companies/manifest.yaml. */
253
352
  function companyUidForSlug(hqRoot, slug) {
@@ -274,7 +373,7 @@ function sessionMetaCompany(hqRoot, sid) {
274
373
  }
275
374
  function laneSessionIds(lane) {
276
375
  const ids = [lane.provider_session_id, lane.last_resume?.session_id];
277
- return ids.filter((id) => typeof id === "string" && LINK_ID_RE.test(id));
376
+ return ids.filter((id) => typeof id === "string" && isSafeLinkId(id));
278
377
  }
279
378
  /**
280
379
  * The review context `hq runners hold check` builds for a caller lane, for every
@@ -367,6 +466,86 @@ async function laneSessions(hqRoot, readFlag) {
367
466
  }
368
467
  return { sessions: out, reviewFlags };
369
468
  }
469
+ /**
470
+ * Exact byte size `crates/hq-hook/src/state.rs` measures against
471
+ * `MAX_SECTION_BYTES`: section name plus compact UTF-8 JSON bytes.
472
+ */
473
+ export function mergeApprovalsSectionBytes(section) {
474
+ return Buffer.byteLength(MERGE_APPROVALS_SECTION_NAME, "utf8")
475
+ + Buffer.byteLength(JSON.stringify(section), "utf8");
476
+ }
477
+ function sessionEntryBytes(sid, entry) {
478
+ return Buffer.byteLength(`${JSON.stringify(sid)}:${JSON.stringify(entry)}`, "utf8");
479
+ }
480
+ /**
481
+ * Keep `merge_approvals` within the native reader's per-section byte cap so an
482
+ * oversized section never refuses every session. A backstop: with no decision
483
+ * rows copied, a section holds about 200 bytes per session plus review records.
484
+ * Largest sessions are reduced first:
485
+ * 1. largest byte reductions first: `reviews` emptied while keeping
486
+ * `review_required: true`, so only the affected senior sessions refuse;
487
+ * 2. if even empty-payload shells exceed the cap, non-review conduct sessions
488
+ * are omitted (their owner-approval gate is still enforced from disk by
489
+ * `conduct_files`);
490
+ * 3. if the remaining section still cannot fit, return null (fail-closed).
491
+ * Logs at most one line whenever the guard intervenes.
492
+ */
493
+ function fitMergeApprovalsSection(section, maxBytes, log) {
494
+ const initialBytes = mergeApprovalsSectionBytes(section);
495
+ if (initialBytes <= maxBytes)
496
+ return section;
497
+ let currentBytes = initialBytes;
498
+ const sessions = section.sessions;
499
+ const sids = Object.keys(sessions);
500
+ const totalSessions = sids.length;
501
+ const degraded = new Set();
502
+ const candidates = [];
503
+ for (const sid of sids) {
504
+ const entry = sessions[sid];
505
+ if (entry.reviews.length > 0) {
506
+ const saved = sessionEntryBytes(sid, entry) - sessionEntryBytes(sid, { ...entry, reviews: [] });
507
+ if (saved > 0)
508
+ candidates.push({ sid, saved });
509
+ }
510
+ }
511
+ candidates.sort((a, b) => b.saved - a.saved || (a.sid < b.sid ? -1 : a.sid > b.sid ? 1 : 0));
512
+ for (const candidate of candidates) {
513
+ if (currentBytes <= maxBytes)
514
+ break;
515
+ sessions[candidate.sid] = { ...sessions[candidate.sid], reviews: [] };
516
+ currentBytes -= candidate.saved;
517
+ degraded.add(candidate.sid);
518
+ }
519
+ let omitted = 0;
520
+ let remaining = totalSessions;
521
+ if (currentBytes > maxBytes) {
522
+ const dropCandidates = Object.keys(sessions)
523
+ .filter((sid) => !sessions[sid].review_required)
524
+ .map((sid) => ({ sid, bytes: sessionEntryBytes(sid, sessions[sid]) }))
525
+ .sort((a, b) => b.bytes - a.bytes || (a.sid < b.sid ? -1 : a.sid > b.sid ? 1 : 0));
526
+ for (const candidate of dropCandidates) {
527
+ if (currentBytes <= maxBytes)
528
+ break;
529
+ delete sessions[candidate.sid];
530
+ degraded.delete(candidate.sid);
531
+ currentBytes -= candidate.bytes + (remaining > 1 ? 1 : 0);
532
+ remaining -= 1;
533
+ omitted += 1;
534
+ }
535
+ }
536
+ const finalBytes = mergeApprovalsSectionBytes(section);
537
+ if (finalBytes > maxBytes) {
538
+ log?.("warn", `merge_approvals: omitted section (${initialBytes} bytes; still ${finalBytes} bytes after trimming ${totalSessions} session(s), exceeds ${maxBytes}-byte cap)`);
539
+ return null;
540
+ }
541
+ const actions = [];
542
+ if (degraded.size > 0)
543
+ actions.push(`trimmed ${degraded.size} of ${totalSessions} session(s)`);
544
+ if (omitted > 0)
545
+ actions.push(`omitted ${omitted} conduct-only session(s)`);
546
+ log?.("warn", `merge_approvals: ${actions.join(" and ")} to stay within ${maxBytes}-byte cap (${initialBytes} -> ${finalBytes} bytes)`);
547
+ return section;
548
+ }
370
549
  /** The merge_approvals section, or null to leave it out of the state file. */
371
550
  export async function buildMergeApprovalsSection(input) {
372
551
  const { hqRoot } = input;
@@ -376,14 +555,16 @@ export async function buildMergeApprovalsSection(input) {
376
555
  const conduct = openFolder(path.join(hqRoot, CONDUCT_REPORTS_REL));
377
556
  try {
378
557
  const links = new Map();
558
+ const metaCache = new Map();
559
+ const queueCache = new Map();
379
560
  if (byFolder !== "missing") {
380
561
  const listed = byFolder.list();
381
562
  if (!listed.ok)
382
563
  return null;
383
564
  for (const sid of listed.value.sort()) {
384
- if (!LINK_ID_RE.test(sid))
565
+ if (!isSafeLinkId(sid))
385
566
  continue;
386
- const queue = readLinkQueue(byFolder, conduct, sid);
567
+ const queue = readLinkQueue(hqRoot, byFolder, conduct, sid, metaCache, queueCache);
387
568
  if (queue)
388
569
  links.set(sid, queue);
389
570
  }
@@ -431,18 +612,19 @@ export async function buildMergeApprovalsSection(input) {
431
612
  company_slug: company.slug,
432
613
  link_id: link?.link_id ?? "",
433
614
  queue_status: link?.queue_status ?? "absent",
434
- decisions: link?.decisions ?? [],
615
+ decisions: [],
435
616
  review_required: review !== "off",
436
617
  reviews: review === "required" ? allReviews() : [],
437
618
  };
438
619
  }
439
- return {
620
+ const section = {
440
621
  schema: MERGE_APPROVALS_SCHEMA,
441
622
  refreshed_at: input.now.toISOString(),
442
623
  max_age_seconds: MERGE_SECTION_MAX_AGE_SECONDS,
443
624
  review_flags: laneFacts.reviewFlags,
444
625
  sessions,
445
626
  };
627
+ return fitMergeApprovalsSection(section, input.maxApprovalsSectionBytes ?? MERGE_APPROVALS_MAX_SECTION_BYTES, input.log);
446
628
  }
447
629
  finally {
448
630
  if (typeof byFolder === "object")
@@ -541,6 +723,7 @@ export function startMergeSectionRefresh(options) {
541
723
  let closed = false;
542
724
  let timer;
543
725
  let running;
726
+ let lastWarning;
544
727
  const fresh = (section) => {
545
728
  if (!section)
546
729
  return null;
@@ -557,9 +740,23 @@ export function startMergeSectionRefresh(options) {
557
740
  catch {
558
741
  hqRoot = undefined;
559
742
  }
743
+ let warned = false;
744
+ const buildLog = options.log
745
+ ? (level, message) => {
746
+ if (level === "warn") {
747
+ warned = true;
748
+ if (message === lastWarning)
749
+ return;
750
+ lastWarning = message;
751
+ }
752
+ options.log?.(level, message);
753
+ }
754
+ : undefined;
560
755
  current = hqRoot
561
- ? await buildMergeSections({ hqRoot, now, readFlag: options.readFlag })
756
+ ? await buildMergeSections({ hqRoot, now, readFlag: options.readFlag, log: buildLog })
562
757
  : { merge_holds: null, merge_approvals: null };
758
+ if (!warned)
759
+ lastWarning = undefined;
563
760
  if (closed)
564
761
  return;
565
762
  try {
@@ -1242,6 +1242,7 @@ export async function runDaemon(opts) {
1242
1242
  hqRoot: () => readDaemonConfig(paths.configPath).hqRoot ?? (env.HQ_ROOT?.trim() || undefined),
1243
1243
  readFlag: createRegistryMergeFlagReader({ env }),
1244
1244
  onRefresh: () => stateWriter.refresh(),
1245
+ log,
1245
1246
  });
1246
1247
  // The cached `hq whoami` answer CLI commands read instead of starting
1247
1248
  // `hq whoami` (whoami-cache.ts). The token caches it describes live under
@@ -14,6 +14,7 @@ import * as fs from "node:fs";
14
14
  import * as os from "node:os";
15
15
  import { ANTIGRAVITY_HOOK_EVENTS, antigravityEventEntries, antigravityTargets, detectAntigravity, isHqAntigravityRule, } from "../../install/antigravity-targets.js";
16
16
  import { CORE_NEXT_LINK, isCoreNextEntry } from "../../hook-engine/registration-identity.js";
17
+ import { stopCompatibilityHold } from "../../hook-engine/coverage.js";
17
18
  import { HQ_MCP_SERVER_NAME } from "../../install/claude-targets.js";
18
19
  export const ANTIGRAVITY_INSTALL_REMEDIATION = "hq install --global --runtime antigravity";
19
20
  export const ANTIGRAVITY_HOOKS_REMEDIATION = "hq reindex";
@@ -32,7 +33,7 @@ export function checkAntigravityWiring(context, options = {}) {
32
33
  return [
33
34
  checkRule(t.ruleFile),
34
35
  checkMcp(t.mcpConfig),
35
- checkHooks(t.hooksFile, context.hqRoot),
36
+ checkHooks(t.hooksFile, context.hqRoot, options.env),
36
37
  ];
37
38
  }
38
39
  function readOrNull(file) {
@@ -74,7 +75,7 @@ function checkMcp(mcpConfig) {
74
75
  }
75
76
  return { status: "PASS", checkId: "antigravity.mcp", target: mcpConfig, message: `Antigravity MCP server "${HQ_MCP_SERVER_NAME}" is registered.` };
76
77
  }
77
- function checkHooks(hooksFile, hqRoot) {
78
+ function checkHooks(hooksFile, hqRoot, env = process.env) {
78
79
  const raw = readOrNull(hooksFile);
79
80
  if (raw === null) {
80
81
  return {
@@ -111,7 +112,20 @@ function checkHooks(hooksFile, hqRoot) {
111
112
  remediation: ANTIGRAVITY_HOOKS_REMEDIATION,
112
113
  };
113
114
  }
114
- const missing = ANTIGRAVITY_HOOK_EVENTS.filter((event) => !present.includes(event));
115
+ const stopHold = fs.existsSync(hqRoot) ? stopCompatibilityHold(hqRoot, env) : null;
116
+ if (stopHold !== null && present.includes("Stop")) {
117
+ return {
118
+ status: "WARN",
119
+ checkId: "antigravity.hooks",
120
+ target: hooksFile,
121
+ message: `Antigravity hooks.json registers Stop while native Stop compatibility holds (${stopHold}); run ${ANTIGRAVITY_HOOKS_REMEDIATION} to remove it.`,
122
+ remediation: ANTIGRAVITY_HOOKS_REMEDIATION,
123
+ };
124
+ }
125
+ const expected = stopHold !== null
126
+ ? ANTIGRAVITY_HOOK_EVENTS.filter((event) => event !== "Stop")
127
+ : [...ANTIGRAVITY_HOOK_EVENTS];
128
+ const missing = expected.filter((event) => !present.includes(event));
115
129
  if (missing.length > 0) {
116
130
  return {
117
131
  status: "WARN",
@@ -125,7 +139,9 @@ function checkHooks(hooksFile, hqRoot) {
125
139
  status: "PASS",
126
140
  checkId: "antigravity.hooks",
127
141
  target: hooksFile,
128
- message: `Antigravity hooks are registered through the native hook engine (${ANTIGRAVITY_HOOK_EVENTS.join(", ")}).`,
142
+ message: stopHold !== null
143
+ ? `Antigravity hooks are registered through the native hook engine (${expected.join(", ")}; Stop omitted while native Stop compatibility holds: ${stopHold}).`
144
+ : `Antigravity hooks are registered through the native hook engine (${ANTIGRAVITY_HOOK_EVENTS.join(", ")}).`,
129
145
  };
130
146
  }
131
147
  //# sourceMappingURL=antigravity-wiring.js.map
@@ -14,7 +14,7 @@ import { jsonFormat } from '../../../commands/mcp-registration.js';
14
14
  import { CORE_NEXT_LINK, isCoreNextEntry, isNativeEntry } from '../../hook-engine/registration.js';
15
15
  import { isAdapterEntry } from '../../install/codex-targets.js';
16
16
  import { antigravityEventEntries, antigravityTargets } from '../../install/antigravity-targets.js';
17
- import { claudeProjectAdapterHold, uncoveredHooks } from '../../hook-engine/coverage.js';
17
+ import { claudeProjectAdapterHold, stopCompatibilityHold, uncoveredHooks } from '../../hook-engine/coverage.js';
18
18
  import { masterHookPath, shimPath } from '../../install/claude-targets.js';
19
19
  import { CORE_NEXT_FLAG, CORE_NEXT_KILL_ENV, CORE_NEXT_KILL_FILE, ENGINE_KILL_ENV, ENGINE_KILL_FILE, REQUIRED_EVALUATORS, STABLE_LINK_NAME, coreNextEnabled, coreNextKillReason, coreNextTargetFor, missingEvaluators, probeEngine, } from '../../../utils/host-registration.js';
20
20
  import { fleetHookCoreResults } from './fleet-hook-core.js';
@@ -144,7 +144,9 @@ export function hostCoreResults(root, options = {}) {
144
144
  return { status: 'PASS', reason: `the new core has ${REQUIRED_EVALUATORS[event].join(', ')}` };
145
145
  };
146
146
  /** Old-dispatcher hooks for `event` on `host` that the engine's report does not cover. */
147
- const uncovered = (caps, host, event) => host === 'antigravity' ? [] : uncoveredHooks(root, host, event, caps.covers, env);
147
+ const uncovered = (caps, host, event) => host === 'antigravity'
148
+ ? (event === 'Stop' ? (() => { const hold = stopCompatibilityHold(root, env); return hold ? [`(native Stop compatibility: ${hold})`] : []; })() : [])
149
+ : uncoveredHooks(root, host, event, caps.covers, env);
148
150
  const listed = (hooks) => (hooks.length > 6 ? `${hooks.slice(0, 6).join(', ')} and ${hooks.length - 6} more` : hooks.join(', '));
149
151
  /**
150
152
  * Why an event of `<root>/.claude/settings.json` stays on master-hook.sh for
@@ -251,8 +253,11 @@ export function hostCoreResults(root, options = {}) {
251
253
  verdict = newCore(event, engine);
252
254
  const caps = verdict.status === 'PASS' && engine ? capabilities(engine) : undefined;
253
255
  const left = caps && !(caps instanceof Error) ? uncovered(caps, target.host, event) : [];
254
- if (left.length > 0)
255
- verdict = { status: 'FAIL', reason: `the new core does not cover ${listed(left)}, so they do not run; run hq reindex to put this event back on the old dispatcher` };
256
+ if (left.length > 0) {
257
+ verdict = target.host === 'antigravity'
258
+ ? { status: 'FAIL', reason: `the new core does not cover ${listed(left)}, so Stop refuses every turn; run hq reindex to remove the Stop registration` }
259
+ : { status: 'FAIL', reason: `the new core does not cover ${listed(left)}, so they do not run; run hq reindex to put this event back on the old dispatcher` };
260
+ }
256
261
  const held = verdict.status === 'PASS' && caps && !(caps instanceof Error) && target.host === 'claude' && target.scope === 'project' ? adapterHold(caps, event) : null;
257
262
  if (held)
258
263
  verdict = { status: 'FAIL', reason: `registered to the new core while ${held}, so that adapter finds no master record for it; run hq reindex to put this event back on master-hook.sh` };
@@ -24,6 +24,8 @@ export declare function lastProcessStartFailure(): ProcessStartFailure | null;
24
24
  export declare function resetProcessStartTimeCache(): void;
25
25
  /** The fixed POSIX locations of `ps`, tried in order. */
26
26
  export declare const POSIX_PS_PATHS: readonly string[];
27
+ /** Timeout for the Windows PowerShell process-start-time probe (cold CLR start can exceed 10s under load). */
28
+ export declare const WINDOWS_PROCESS_START_TIMEOUT_MS = 30000;
27
29
  /**
28
30
  * The absolute path of the system tool that reads a process start time, found
29
31
  * at a fixed location and never through PATH, so the answer is the same on
@@ -18,6 +18,8 @@ export function resetProcessStartTimeCache() {
18
18
  }
19
19
  /** The fixed POSIX locations of `ps`, tried in order. */
20
20
  export const POSIX_PS_PATHS = ["/bin/ps", "/usr/bin/ps"];
21
+ /** Timeout for the Windows PowerShell process-start-time probe (cold CLR start can exceed 10s under load). */
22
+ export const WINDOWS_PROCESS_START_TIMEOUT_MS = 30_000;
21
23
  function defaultIsExecutable(platform) {
22
24
  return (file) => {
23
25
  try {
@@ -85,11 +87,12 @@ export function processStartTime(pid, probe = {}) {
85
87
  try {
86
88
  const result = platform === "win32"
87
89
  ? runSpawn(tool, [
90
+ "-NoLogo",
88
91
  "-NoProfile",
89
92
  "-NonInteractive",
90
93
  "-Command",
91
- `(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToUniversalTime().ToString('o')`,
92
- ], { encoding: "utf8", timeout: 10_000, windowsHide: true })
94
+ `[System.Diagnostics.Process]::GetProcessById(${pid}).StartTime.ToUniversalTime().ToString('o')`,
95
+ ], { encoding: "utf8", timeout: WINDOWS_PROCESS_START_TIMEOUT_MS, windowsHide: true })
93
96
  : runSpawn(tool, ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", timeout: 5_000 });
94
97
  const text = (result.stdout ?? "").trim();
95
98
  if (result.status === 0 && text) {
@@ -28,13 +28,25 @@ import * as fs from 'node:fs';
28
28
  import * as path from 'node:path';
29
29
  import { isCoreNextEntry } from './registration.js';
30
30
  import { CLASSIFYING_ADAPTER_CORE_SHA256, RELEASED_CLASSIFYING_ADAPTER_CORE_SHA256 } from './adapter-core-pin.js';
31
+ const CRATE_POLICY_FALLBACKS = {
32
+ 'native-precompact-compatibility.json': '../../../crates/hq-hook/src/stop/precompact/native-precompact-compatibility.json',
33
+ };
31
34
  /**
32
35
  * Read a policy file that ships beside this module (src/ and dist/ alike; scripts/copy-schemas.mjs copies
33
36
  * them to dist/). Not a JSON import: import attributes need Node 20.10, and `engines` allows Node 20.0, where
34
37
  * the attribute syntax is a SyntaxError that stops the whole CLI from loading (Sentry HQ-CLI-HZ).
35
38
  */
36
39
  function readPolicy(name) {
37
- return JSON.parse(fs.readFileSync(new URL(`./${name}`, import.meta.url), 'utf8'));
40
+ const local = new URL(`./${name}`, import.meta.url);
41
+ if (fs.existsSync(local))
42
+ return JSON.parse(fs.readFileSync(local, 'utf8'));
43
+ const fallback = CRATE_POLICY_FALLBACKS[name];
44
+ if (fallback) {
45
+ const crateCopy = new URL(fallback, import.meta.url);
46
+ if (fs.existsSync(crateCopy))
47
+ return JSON.parse(fs.readFileSync(crateCopy, 'utf8'));
48
+ }
49
+ return JSON.parse(fs.readFileSync(local, 'utf8'));
38
50
  }
39
51
  const stopCompatibility = readPolicy('native-stop-compatibility.json');
40
52
  const gitStopConfig = readPolicy('git-stop-config.json');