@indigoai-us/hq-cli 5.345.270 → 5.345.273

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 (54) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/contracts/host-canary-release.json +7 -7
  3. package/dist/command-catalog.generated.d.ts +2 -2
  4. package/dist/command-catalog.generated.js +2 -2
  5. package/dist/commands/core-checkpoint-stop-gate-native.js +2 -13
  6. package/dist/commands/core-session-journal-native.js +20 -4
  7. package/dist/commands/signals-run.d.ts +4 -1
  8. package/dist/commands/signals-run.js +6 -8
  9. package/dist/commands/sync-core.js +2 -1
  10. package/dist/lib/daemon/daemon-restart.d.ts +70 -0
  11. package/dist/lib/daemon/daemon-restart.js +114 -0
  12. package/dist/lib/daemon/hook-requests-work-mesh-shims.d.ts +41 -0
  13. package/dist/lib/daemon/hook-requests-work-mesh-shims.js +237 -0
  14. package/dist/lib/daemon/hook-requests.d.ts +4 -1
  15. package/dist/lib/daemon/hook-requests.js +23 -1
  16. package/dist/lib/daemon/hq-child-bootstrap.mjs +1 -0
  17. package/dist/lib/daemon/installed-cli-restart.js +14 -4
  18. package/dist/lib/daemon/merge-sections.d.ts +24 -1
  19. package/dist/lib/daemon/merge-sections.js +59 -11
  20. package/dist/lib/daemon/run.d.ts +1 -1
  21. package/dist/lib/daemon/run.js +67 -53
  22. package/dist/lib/daemon/supervisor.js +0 -2
  23. package/dist/lib/hook-engine/coverage.d.ts +21 -0
  24. package/dist/lib/hook-engine/coverage.js +98 -5
  25. package/dist/lib/hook-engine/native-precompact-compatibility.json +1 -0
  26. package/dist/lib/hook-engine/native-stop-compatibility.json +2 -1
  27. package/dist/lib/hot-channels/signals-pass.d.ts +10 -2
  28. package/dist/lib/hot-channels/signals-pass.js +13 -3
  29. package/dist/lib/signals/engine.d.ts +0 -2
  30. package/dist/lib/signals/engine.js +12 -7
  31. package/dist/lib/signals/reply.js +35 -82
  32. package/dist/lib/signals/run-lock.d.ts +8 -0
  33. package/dist/lib/signals/run-lock.js +42 -7
  34. package/dist/lib/signals/run-record.js +2 -1
  35. package/dist/lib/signals/settings.d.ts +9 -4
  36. package/dist/lib/signals/settings.js +7 -5
  37. package/dist/lib/signals/steps/extract.d.ts +37 -10
  38. package/dist/lib/signals/steps/extract.js +88 -111
  39. package/dist/lib/signals/steps/types.d.ts +3 -2
  40. package/dist/lib/sync-core/reconcile.d.ts +7 -1
  41. package/dist/lib/sync-core/reconcile.js +105 -18
  42. package/dist/lib/sync-core/release.d.ts +52 -2
  43. package/dist/lib/sync-core/release.js +172 -11
  44. package/dist/lib/sync-core/rollout-state.d.ts +11 -0
  45. package/dist/lib/sync-core/rollout-state.js +16 -0
  46. package/dist/utils/client-health-contract.d.ts +32 -0
  47. package/dist/utils/client-health-contract.js +35 -0
  48. package/dist/utils/client-health.d.ts +43 -0
  49. package/dist/utils/client-health.js +106 -3
  50. package/dist/utils/login-browser.d.ts +1 -0
  51. package/dist/utils/login-browser.js +31 -6
  52. package/dist/utils/spawn-detached-hidden.d.ts +66 -0
  53. package/dist/utils/spawn-detached-hidden.js +222 -0
  54. package/package.json +7 -7
@@ -0,0 +1,237 @@
1
+ /**
2
+ * Daemon-side handlers for the four request note kinds left by the native
3
+ * Work Mesh core-shims member (`crates/hq-hook/src/work_mesh_shims.rs`):
4
+ *
5
+ * - `work-mesh-register`: `bash <root>/core/hooks/work-mesh-register.sh __bg__`
6
+ * - `work-mesh-sweep`: `bash <root>/core/hooks/work-mesh-close.sh __sweep_bg__`
7
+ * - `work-mesh-ground`: `bash <root>/core/hooks/work-mesh-ground.sh <event>`
8
+ * (prompt in `.body`, passed on stdin as JSON)
9
+ * - `work-mesh-close`: `bash <root>/core/hooks/work-mesh-close.sh __close_bg__`
10
+ *
11
+ * Each note carries validated typed fields only (never an argv or environment
12
+ * dump). A root without the target body script is done (`code: 0`). Output
13
+ * goes to `<root>/workspace/logs/work-mesh-hook.log`, matching the detached
14
+ * shell jobs. A run that ends on its own is done (`code: 0`); a timeout,
15
+ * abort, spawn failure, or unreadable log file is a failed try (`code: 1`).
16
+ */
17
+ import * as fs from "node:fs";
18
+ import * as path from "node:path";
19
+ // A cycle with hook-requests.ts, which dispatches to this module: each side uses the other only inside functions.
20
+ import { spawnRequestProgram } from "./hook-requests.js";
21
+ export const WORK_MESH_SHIM_SCRIPTS = {
22
+ "work-mesh-register": "core/hooks/work-mesh-register.sh",
23
+ "work-mesh-sweep": "core/hooks/work-mesh-close.sh",
24
+ "work-mesh-ground": "core/hooks/work-mesh-ground.sh",
25
+ "work-mesh-close": "core/hooks/work-mesh-close.sh",
26
+ };
27
+ export const WORK_MESH_SHIM_LOG = "workspace/logs/work-mesh-hook.log";
28
+ const SAFE_SESSION = /^[A-Za-z0-9][A-Za-z0-9._-]{0,511}$/;
29
+ const SAFE_SLUG = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
30
+ const SAFE_UID = /^[A-Za-z0-9._-]{1,128}$/;
31
+ const SAFE_EVENT = /^[A-Za-z]{1,64}$/;
32
+ const plain = (s) => typeof s === "string" && !s.includes("\0");
33
+ const bounded = (s, maxBytes, nonEmpty = false) => plain(s) && (!nonEmpty || s.length > 0) && Buffer.byteLength(s) <= maxBytes;
34
+ const exactKeys = (args, expected) => {
35
+ const keys = Object.keys(args).sort();
36
+ return keys.length === expected.length && keys.every((key, i) => key === expected[i]);
37
+ };
38
+ export function isWorkMeshShimKind(kind) {
39
+ return kind === "work-mesh-register"
40
+ || kind === "work-mesh-sweep"
41
+ || kind === "work-mesh-ground"
42
+ || kind === "work-mesh-close";
43
+ }
44
+ export function parseWorkMeshShim(kind, args, session) {
45
+ switch (kind) {
46
+ case "work-mesh-register": {
47
+ if (!exactKeys(args, ["binding", "category", "harness", "intent", "project", "session_id", "slug", "uid"]))
48
+ return undefined;
49
+ const { session_id: sessionId, slug, uid, project, binding, category, intent, harness } = args;
50
+ if (!plain(sessionId) || !SAFE_SESSION.test(sessionId) || sessionId !== session)
51
+ return undefined;
52
+ if (!plain(slug) || !SAFE_SLUG.test(slug))
53
+ return undefined;
54
+ if (!plain(uid) || (uid !== "" && !SAFE_UID.test(uid)))
55
+ return undefined;
56
+ if (!bounded(project, 256))
57
+ return undefined;
58
+ if (binding !== "project" && binding !== "adhoc")
59
+ return undefined;
60
+ if (!bounded(category, 128, true))
61
+ return undefined;
62
+ if (!bounded(intent, 1120))
63
+ return undefined;
64
+ if (!bounded(harness, 128, true))
65
+ return undefined;
66
+ return { kind, sessionId, slug, uid, project, binding, category, intent, harness };
67
+ }
68
+ case "work-mesh-sweep": {
69
+ if (Object.keys(args).length !== 0)
70
+ return undefined;
71
+ return { kind };
72
+ }
73
+ case "work-mesh-ground": {
74
+ if (!exactKeys(args, ["company", "event", "project", "session_id"]))
75
+ return undefined;
76
+ const { event, session_id: sessionId, company, project } = args;
77
+ if (!plain(event) || !SAFE_EVENT.test(event))
78
+ return undefined;
79
+ if (!plain(sessionId) || (sessionId !== "" && !SAFE_SESSION.test(sessionId)) || sessionId !== session)
80
+ return undefined;
81
+ if (!plain(company) || (company !== "" && !SAFE_SLUG.test(company)))
82
+ return undefined;
83
+ if (!bounded(project, 256))
84
+ return undefined;
85
+ return { kind, event, sessionId, company, project };
86
+ }
87
+ case "work-mesh-close": {
88
+ if (!exactKeys(args, ["category", "harness", "hint", "intent", "project", "session_id", "summary"]))
89
+ return undefined;
90
+ const { session_id: sessionId, hint, project, category, intent, harness, summary } = args;
91
+ if (!plain(sessionId) || !SAFE_SESSION.test(sessionId) || sessionId !== session)
92
+ return undefined;
93
+ if (!bounded(hint, 3500))
94
+ return undefined;
95
+ if (!bounded(project, 256))
96
+ return undefined;
97
+ if (!bounded(category, 128, true))
98
+ return undefined;
99
+ if (!bounded(intent, 1120))
100
+ return undefined;
101
+ if (!bounded(harness, 128, true))
102
+ return undefined;
103
+ if (!bounded(summary, 1024))
104
+ return undefined;
105
+ return { kind, sessionId, hint, project, category, intent, harness, summary };
106
+ }
107
+ }
108
+ }
109
+ function decodeGroundPrompt(body) {
110
+ if (!body || body.includes(0))
111
+ return undefined;
112
+ try {
113
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(body);
114
+ }
115
+ catch {
116
+ return undefined;
117
+ }
118
+ }
119
+ export async function runWorkMeshShim(request, operation, base, options) {
120
+ const script = path.join(request.root, WORK_MESH_SHIM_SCRIPTS[operation.kind]);
121
+ try {
122
+ if (!fs.statSync(script).isFile())
123
+ return { code: 0 };
124
+ }
125
+ catch {
126
+ return { code: 0 };
127
+ }
128
+ let stdinPayload;
129
+ let argv;
130
+ const env = { ...base };
131
+ // Session kill switches were already evaluated by the native hook.
132
+ delete env.HQ_WORK_MESH_DISABLED;
133
+ delete env.HQ_DISABLED_HOOKS;
134
+ Object.assign(env, {
135
+ HQ_ROOT: request.root,
136
+ WM_ROOT: request.root,
137
+ HQ_HOOK_REQUEST_ID: request.id,
138
+ });
139
+ switch (operation.kind) {
140
+ case "work-mesh-register":
141
+ argv = [script, "__bg__"];
142
+ Object.assign(env, {
143
+ WM_SID: operation.sessionId,
144
+ WM_SLUG: operation.slug,
145
+ WM_UID: operation.uid,
146
+ WM_PROJECT: operation.project,
147
+ WM_BINDING: operation.binding,
148
+ WM_CATEGORY: operation.category,
149
+ WM_INTENT: operation.intent,
150
+ WM_HARNESS: operation.harness,
151
+ });
152
+ break;
153
+ case "work-mesh-sweep":
154
+ argv = [script, "__sweep_bg__"];
155
+ break;
156
+ case "work-mesh-close":
157
+ argv = [script, "__close_bg__"];
158
+ Object.assign(env, {
159
+ WM_SID: operation.sessionId,
160
+ WM_HINT: operation.hint,
161
+ WM_HARNESS: operation.harness,
162
+ WM_PROJECT: operation.project,
163
+ WM_CATEGORY: operation.category,
164
+ WM_INTENT: operation.intent,
165
+ WM_SUMMARY: operation.summary,
166
+ });
167
+ break;
168
+ case "work-mesh-ground": {
169
+ const prompt = decodeGroundPrompt(request.body);
170
+ if (prompt === undefined) {
171
+ options.log?.(`Hook request ${request.stem}: invalid work-mesh-ground prompt body; deleted, nothing was run`);
172
+ return { code: 0 };
173
+ }
174
+ argv = [script, operation.event];
175
+ env.CLAUDE_PROJECT_DIR = request.root;
176
+ if (operation.sessionId !== "") {
177
+ env.HQ_SESSION_ID = operation.sessionId;
178
+ }
179
+ else {
180
+ delete env.HQ_SESSION_ID;
181
+ }
182
+ stdinPayload = JSON.stringify({
183
+ prompt,
184
+ hook_event_name: operation.event,
185
+ ...(operation.sessionId !== "" ? { session_id: operation.sessionId } : {}),
186
+ });
187
+ break;
188
+ }
189
+ }
190
+ const logFile = path.join(request.root, WORK_MESH_SHIM_LOG);
191
+ let output;
192
+ try {
193
+ fs.mkdirSync(path.dirname(logFile), { recursive: true });
194
+ output = fs.openSync(logFile, "a");
195
+ }
196
+ catch (error) {
197
+ options.log?.(`${operation.kind}: ${WORK_MESH_SHIM_LOG} under ${request.root} could not be opened (${String(error)})`);
198
+ return { code: 1 };
199
+ }
200
+ try {
201
+ if (options.signal?.aborted)
202
+ return { code: 1 };
203
+ const stdio = operation.kind === "work-mesh-ground"
204
+ ? ["pipe", "ignore", output]
205
+ : ["ignore", output, output];
206
+ const { child, settle } = spawnRequestProgram("bash", argv, {
207
+ cwd: request.root,
208
+ env,
209
+ windowsHide: true,
210
+ stdio,
211
+ }, {
212
+ timeoutMs: options.timeoutMs,
213
+ killGraceMs: options.killGraceMs,
214
+ ...(options.signal ? { signal: options.signal } : {}),
215
+ });
216
+ if (stdinPayload !== undefined) {
217
+ child.stdin?.on("error", () => undefined);
218
+ child.stdin?.end(stdinPayload);
219
+ }
220
+ return await new Promise(resolve => {
221
+ let settled = false;
222
+ const done = (exited) => {
223
+ if (settled)
224
+ return;
225
+ settled = true;
226
+ const ended = settle();
227
+ resolve({ code: !ended && exited ? 0 : 1 });
228
+ };
229
+ child.once("error", () => done(false));
230
+ child.once("close", (code, signal) => done(code !== null && signal === null));
231
+ });
232
+ }
233
+ finally {
234
+ fs.closeSync(output);
235
+ }
236
+ }
237
+ //# sourceMappingURL=hook-requests-work-mesh-shims.js.map
@@ -55,6 +55,7 @@ import { type MachineCheckResult, type RunMachineChecksOptions } from "./machine
55
55
  import { type MeshToolWritesOperation } from "./hook-requests-mesh-tool-writes.js";
56
56
  import { type FleetLocalPromptOperation, type FleetSessionStartOperation } from "./hook-requests-fleet-session-start.js";
57
57
  import { type ConductLinkOperation } from "./hook-requests-conduct-link.js";
58
+ import { type WorkMeshShimOperation } from "./hook-requests-work-mesh-shims.js";
58
59
  import { type CodexSettingsOperation } from "./hook-requests-codex-settings.js";
59
60
  import { type FleetMembersRefreshOperation } from "./fleet-members-cache.js";
60
61
  /** What the daemon is asked to do. A closed list, the same as `Kind` in daemon_req.rs. */
@@ -111,7 +112,9 @@ export type HookOperation = {
111
112
  /** One machine check run by the daemon for a SessionStart where the hooks own the checks (the machine-check notes at the end of this file). */
112
113
  | MachineCheckOperation | MeshOperation | MeshToolWritesOperation | CodexSettingsOperation | FleetSessionStartOperation | FleetLocalPromptOperation | FleetMembersRefreshOperation
113
114
  /** The Codex adapter's SubagentStop runs of the root's conduct-link hooks (hook-requests-conduct-link.ts). */
114
- | ConductLinkOperation;
115
+ | ConductLinkOperation
116
+ /** The background runs of the five legacy core Work Mesh shims (hook-requests-work-mesh-shims.ts). */
117
+ | WorkMeshShimOperation;
115
118
  /**
116
119
  * One command of a `fleet-local-settings` note, a record of the adapter's `hqad_iter_settings`. Typed fields only: the
117
120
  * daemon builds the program and its arguments (`fleetLocalSettingsProgram`).
@@ -64,6 +64,7 @@ import { MACHINE_CHECKS, machineCheckCollectOnlySupported, runMachineChecks } fr
64
64
  import { parseMeshToolWrites, runMeshToolWrites } from "./hook-requests-mesh-tool-writes.js";
65
65
  import { parseFleetLocalPrompt, parseFleetSessionStart, runFleetLocalPrompt, runFleetSessionStart } from "./hook-requests-fleet-session-start.js";
66
66
  import { isConductLinkKind, parseConductLink, runConductLink } from "./hook-requests-conduct-link.js";
67
+ import { isWorkMeshShimKind, parseWorkMeshShim, runWorkMeshShim } from "./hook-requests-work-mesh-shims.js";
67
68
  import { parseCodexSettings, runCodexSettings } from "./hook-requests-codex-settings.js";
68
69
  import { hqMembersList, parseFleetMembersRefresh, runFleetMembersRefresh } from "./fleet-members-cache.js";
69
70
  /** The longest note the Rust writer leaves (`NOTE_MAX_BYTES`). */
@@ -319,6 +320,12 @@ export function parseHookRequest(text, stem) {
319
320
  return undefined;
320
321
  operation = conduct;
321
322
  }
323
+ else if (isWorkMeshShimKind(value.kind)) {
324
+ const shim = parseWorkMeshShim(value.kind, args, value.session);
325
+ if (!shim)
326
+ return undefined;
327
+ operation = shim;
328
+ }
322
329
  else if (value.kind === "codex-settings") {
323
330
  const codex = parseCodexSettings(value.kind, args);
324
331
  if (!codex)
@@ -403,7 +410,8 @@ export function hookRequestHasBody(operation) {
403
410
  || operation.kind === "fleet-local-settings"
404
411
  || operation.kind === "codex-settings"
405
412
  || operation.kind === "fleet-session-start"
406
- || operation.kind === "fleet-local-prompt";
413
+ || operation.kind === "fleet-local-prompt"
414
+ || operation.kind === "work-mesh-ground";
407
415
  }
408
416
  /** The helper a plan-sync request runs, inside the HQ root. */
409
417
  export const PLAN_SYNC_HELPER = "core/scripts/session-project.sh";
@@ -444,6 +452,11 @@ export function hookRequestArguments(request) {
444
452
  // Not a CLI request: the root's own conduct-link hook script is run (`runConductLink`).
445
453
  case "conduct-lanes-link-deliver":
446
454
  case "conduct-link-inherit": return [];
455
+ // Not a CLI request: the root's own work-mesh-*.sh script is run (`runWorkMeshShim`).
456
+ case "work-mesh-register":
457
+ case "work-mesh-sweep":
458
+ case "work-mesh-ground":
459
+ case "work-mesh-close": return [];
447
460
  }
448
461
  }
449
462
  /**
@@ -1675,6 +1688,15 @@ export function executeHookRequest(request, options) {
1675
1688
  timeoutMs: options.timeoutMs ?? HOOK_REQUEST_KILL_MS,
1676
1689
  }).catch(() => ({ code: 1 }));
1677
1690
  }
1691
+ if (request.operation.kind === "work-mesh-register"
1692
+ || request.operation.kind === "work-mesh-sweep"
1693
+ || request.operation.kind === "work-mesh-ground"
1694
+ || request.operation.kind === "work-mesh-close") {
1695
+ return runWorkMeshShim(request, request.operation, base, {
1696
+ ...(options.signal ? { signal: options.signal } : {}), killGraceMs,
1697
+ timeoutMs: options.timeoutMs ?? HOOK_REQUEST_KILL_MS, ...(options.log ? { log: options.log } : {}),
1698
+ }).catch(() => ({ code: 1 }));
1699
+ }
1678
1700
  if (request.operation.kind === "startwork-prefetch") {
1679
1701
  return runStartworkPrefetch(request, request.operation, base, {
1680
1702
  ...(options.signal ? { signal: options.signal } : {}), killGraceMs,
@@ -366,6 +366,7 @@ async function run() {
366
366
  // must not inherit them: it would exit when its own launcher exited.
367
367
  HQ_DAEMON_BOOTSTRAP_CHILD: "1",
368
368
  HQ_DAEMON_OWNER_CONTROL_FD: "3",
369
+ HQ_DAEMON_UNIT_PARENT_PID: String(process.pid),
369
370
  },
370
371
  // fd 3 is a pipe this process holds. When we exit, including by SIGKILL,
371
372
  // the command sees EOF and leaves. stdin stays the parent's stdin.
@@ -33,6 +33,18 @@ export function installedCliVersionOnDisk(packageRoot, read = (file) => fs.readF
33
33
  return null;
34
34
  }
35
35
  }
36
+ function writeMarker(markerPath, marker) {
37
+ fs.mkdirSync(path.dirname(markerPath), { recursive: true, mode: 0o700 });
38
+ const tmp = `${markerPath}.${process.pid}.tmp`;
39
+ try {
40
+ fs.writeFileSync(tmp, `${JSON.stringify(marker)}\n`, { mode: 0o600 });
41
+ fs.renameSync(tmp, markerPath);
42
+ }
43
+ catch (error) {
44
+ fs.rmSync(tmp, { force: true });
45
+ throw error;
46
+ }
47
+ }
36
48
  /**
37
49
  * Heal a daemon that is already stuck on an older release, which has no
38
50
  * housekeeping check of its own: a unit it starts runs the CLI on disk and can
@@ -53,8 +65,7 @@ export function requestRestartOfOlderParentDaemon(deps) {
53
65
  catch {
54
66
  // no marker yet, or unreadable: ask
55
67
  }
56
- fs.mkdirSync(path.dirname(deps.markerPath), { recursive: true, mode: 0o700 });
57
- fs.writeFileSync(deps.markerPath, `${JSON.stringify({ pair })}\n`, { mode: 0o600 });
68
+ writeMarker(deps.markerPath, { pair });
58
69
  deps.requestRestart();
59
70
  return true;
60
71
  }
@@ -94,8 +105,7 @@ export function createInstalledCliRestartCheck(deps) {
94
105
  requestedFor = installed;
95
106
  if (deps.markerPath) {
96
107
  try {
97
- fs.mkdirSync(path.dirname(deps.markerPath), { recursive: true, mode: 0o700 });
98
- fs.writeFileSync(deps.markerPath, `${JSON.stringify({ running, installed })}\n`, { mode: 0o600 });
108
+ writeMarker(deps.markerPath, { running, installed });
99
109
  }
100
110
  catch {
101
111
  // Without the marker this process still asks only once; ask now.
@@ -65,8 +65,18 @@ export declare const MERGE_SECTION_MAX_AGE_SECONDS = 60;
65
65
  export declare const MERGE_SECTION_REFRESH_INTERVAL_MS = 15000;
66
66
  /** A flag value is asked of the registry again after this long. */
67
67
  export declare const MERGE_FLAG_TTL_MS = 30000;
68
+ /**
69
+ * The daemon's reader re-reads a kept flag value in the background once it is
70
+ * this old, and keeps answering with it until MERGE_FLAG_TTL_MS, so a build
71
+ * does not wait on the registry while a value is kept. On 2026-11-30 the
72
+ * state file was written 4 to 52 s after the build that stamped its sections
73
+ * started, and the native merge gate refuses a section past 60 s.
74
+ */
75
+ export declare const MERGE_FLAG_REFRESH_AHEAD_MS = 15000;
68
76
  /** A flag read that takes longer than this counts as unreadable. */
69
77
  export declare const MERGE_FLAG_READ_TIMEOUT_MS = 12000;
78
+ /** A section build that takes longer than this is logged with its time. */
79
+ export declare const MERGE_SECTION_SLOW_BUILD_MS = 5000;
70
80
  export interface MergeHoldEntry {
71
81
  repo: string;
72
82
  reason: string;
@@ -169,11 +179,24 @@ export declare function foldDecisionQueue(text: string): FoldedQueue;
169
179
  export declare function mergeApprovalsSectionBytes(section: MergeApprovalsSection): number;
170
180
  /** The merge_approvals section, or null to leave it out of the state file. */
171
181
  export declare function buildMergeApprovalsSection(input: MergeSectionInput): Promise<MergeApprovalsSection | null>;
172
- /** Both sections, read at `input.now`. A builder that throws leaves its section out. */
182
+ /**
183
+ * Both sections, read at `input.now`. A builder that throws leaves its section
184
+ * out. A builder slower than MERGE_SECTION_SLOW_BUILD_MS is logged with its
185
+ * time: its section's refreshed_at is the build's start, so that time comes
186
+ * off the section's 60 s life before the state file is even written.
187
+ */
173
188
  export declare function buildMergeSections(input: MergeSectionInput): Promise<MergeSections>;
174
189
  export interface RegistryMergeFlagReaderOptions {
175
190
  env: NodeJS.ProcessEnv;
176
191
  ttlMs?: number;
192
+ /**
193
+ * When set, a kept value at least this old (and younger than `ttlMs`) is
194
+ * answered at once and read again in the background, one read per flag and
195
+ * company at a time. A background read that fails leaves the kept value to
196
+ * expire at `ttlMs`, as it would have without the read. Unset: a kept value
197
+ * is answered until `ttlMs` and never read early.
198
+ */
199
+ refreshAheadMs?: number;
177
200
  timeoutMs?: number;
178
201
  now?: () => number;
179
202
  /** Test seam: one registry read; null when it could not be read. */
@@ -75,8 +75,18 @@ export const MERGE_SECTION_MAX_AGE_SECONDS = 60;
75
75
  export const MERGE_SECTION_REFRESH_INTERVAL_MS = 15_000;
76
76
  /** A flag value is asked of the registry again after this long. */
77
77
  export const MERGE_FLAG_TTL_MS = 30_000;
78
+ /**
79
+ * The daemon's reader re-reads a kept flag value in the background once it is
80
+ * this old, and keeps answering with it until MERGE_FLAG_TTL_MS, so a build
81
+ * does not wait on the registry while a value is kept. On 2026-11-30 the
82
+ * state file was written 4 to 52 s after the build that stamped its sections
83
+ * started, and the native merge gate refuses a section past 60 s.
84
+ */
85
+ export const MERGE_FLAG_REFRESH_AHEAD_MS = 15_000;
78
86
  /** A flag read that takes longer than this counts as unreadable. */
79
87
  export const MERGE_FLAG_READ_TIMEOUT_MS = 12_000;
88
+ /** A section build that takes longer than this is logged with its time. */
89
+ export const MERGE_SECTION_SLOW_BUILD_MS = 5_000;
80
90
  const LINK_ID_RE = /^[A-Za-z0-9._-]{1,200}$/;
81
91
  const REPO_RE = /^[a-z0-9_.-]+\/[a-z0-9_.-]+$/;
82
92
  const HEAD_SHA_RE = /^[0-9a-f]{40}$/;
@@ -633,11 +643,28 @@ export async function buildMergeApprovalsSection(input) {
633
643
  conduct.close();
634
644
  }
635
645
  }
636
- /** Both sections, read at `input.now`. A builder that throws leaves its section out. */
646
+ /**
647
+ * Both sections, read at `input.now`. A builder that throws leaves its section
648
+ * out. A builder slower than MERGE_SECTION_SLOW_BUILD_MS is logged with its
649
+ * time: its section's refreshed_at is the build's start, so that time comes
650
+ * off the section's 60 s life before the state file is even written.
651
+ */
637
652
  export async function buildMergeSections(input) {
653
+ const timed = async (name, build) => {
654
+ const started = performance.now();
655
+ try {
656
+ return await build().catch(() => null);
657
+ }
658
+ finally {
659
+ const ms = Math.round(performance.now() - started);
660
+ if (ms > MERGE_SECTION_SLOW_BUILD_MS) {
661
+ input.log?.("info", `merge section ${name} took ${ms} ms to build; its refreshed_at is the build's start`);
662
+ }
663
+ }
664
+ };
638
665
  const [holds, approvals] = await Promise.all([
639
- buildMergeHoldsSection(input).catch(() => null),
640
- buildMergeApprovalsSection(input).catch(() => null),
666
+ timed("merge_holds", () => buildMergeHoldsSection(input)),
667
+ timed("merge_approvals", () => buildMergeApprovalsSection(input)),
641
668
  ]);
642
669
  return { merge_holds: holds, merge_approvals: approvals };
643
670
  }
@@ -676,12 +703,10 @@ export function createRegistryMergeFlagReader(options) {
676
703
  const timeoutMs = options.timeoutMs ?? MERGE_FLAG_READ_TIMEOUT_MS;
677
704
  const now = options.now ?? (() => performance.now());
678
705
  const read = options.read ?? registryRead;
706
+ const refreshAheadMs = options.refreshAheadMs;
679
707
  const held = new Map();
680
- return async (flag, company) => {
681
- const key = JSON.stringify([flag, company.uid, company.slug]);
682
- const kept = held.get(key);
683
- if (kept && now() - kept.at < ttlMs)
684
- return kept.value;
708
+ const reading = new Map();
709
+ const readNow = async (flag, company) => {
685
710
  const startedAt = now();
686
711
  let timer;
687
712
  const timeout = new Promise((resolve) => {
@@ -705,12 +730,35 @@ export function createRegistryMergeFlagReader(options) {
705
730
  finally {
706
731
  clearTimeout(timer);
707
732
  }
708
- if (value === null)
709
- held.delete(key);
710
- else
733
+ const key = JSON.stringify([flag, company.uid, company.slug]);
734
+ if (value !== null)
711
735
  held.set(key, { at: startedAt, value });
736
+ // A failed read is never kept. A kept value it would replace expires at
737
+ // ttlMs as before: drop it only once it has.
738
+ else if (!(held.get(key) && now() - held.get(key).at < ttlMs))
739
+ held.delete(key);
712
740
  return value;
713
741
  };
742
+ // One read per flag and company at a time.
743
+ const readOnce = (key, flag, company) => {
744
+ let pending = reading.get(key);
745
+ if (!pending) {
746
+ pending = readNow(flag, company).finally(() => reading.delete(key));
747
+ reading.set(key, pending);
748
+ }
749
+ return pending;
750
+ };
751
+ return async (flag, company) => {
752
+ const key = JSON.stringify([flag, company.uid, company.slug]);
753
+ const kept = held.get(key);
754
+ if (kept && now() - kept.at < ttlMs) {
755
+ if (refreshAheadMs !== undefined && now() - kept.at >= refreshAheadMs) {
756
+ void readOnce(key, flag, company).catch(() => { });
757
+ }
758
+ return kept.value;
759
+ }
760
+ return readOnce(key, flag, company);
761
+ };
714
762
  }
715
763
  /**
716
764
  * Rebuild both sections now and then every `intervalMs` after the previous
@@ -216,7 +216,7 @@ export declare function unitProcessEnv(base: NodeJS.ProcessEnv, unit: UnitPlan):
216
216
  * leave even if it is killed before it can signal. Node and exec runners do
217
217
  * not get either value.
218
218
  */
219
- export declare function daemonChildOwnershipEnv(base: NodeJS.ProcessEnv, unit: UnitPlan, handoffPath: string | null): NodeJS.ProcessEnv;
219
+ export declare function daemonChildOwnershipEnv(base: NodeJS.ProcessEnv, unit: UnitPlan, handoffPath: string | null, daemonPid?: number): NodeJS.ProcessEnv;
220
220
  type DaemonStdioSlot = "ignore" | "pipe" | "inherit" | number;
221
221
  export declare function daemonChildStdio(stdio: readonly [DaemonStdioSlot, DaemonStdioSlot, DaemonStdioSlot], trackOwner: boolean): DaemonStdioSlot[];
222
222
  /**