@indigoai-us/hq-cli 5.345.208 → 5.345.210

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 (126) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/assets/scaffold/core/scripts/derive-trigger-facts.sh +22 -3
  3. package/dist/command-catalog.generated.d.ts +33 -8
  4. package/dist/command-catalog.generated.js +40 -8
  5. package/dist/command-registration-plan.d.ts +2 -2
  6. package/dist/command-registration-plan.js +1 -1
  7. package/dist/commands/access.js +11 -5
  8. package/dist/commands/agents.d.ts +8 -0
  9. package/dist/commands/agents.js +5 -0
  10. package/dist/commands/bot.d.ts +8 -0
  11. package/dist/commands/bot.js +67 -7
  12. package/dist/commands/channels.js +4 -0
  13. package/dist/commands/cloud.d.ts +83 -2
  14. package/dist/commands/cloud.js +161 -31
  15. package/dist/commands/company.d.ts +9 -0
  16. package/dist/commands/company.js +44 -14
  17. package/dist/commands/core-checkpoint-native.js +21 -0
  18. package/dist/commands/core-derive-trigger-facts-native.js +14 -3
  19. package/dist/commands/core-generate-workers-registry-fast.d.ts +1 -1
  20. package/dist/commands/core-generate-workers-registry-fast.js +7 -1
  21. package/dist/commands/core-job-run-native.d.ts +8 -0
  22. package/dist/commands/core-job-run-native.js +11 -3
  23. package/dist/commands/core-jobs-native.js +1 -1
  24. package/dist/commands/core-register-project-native.js +31 -1
  25. package/dist/commands/core-scan-packages-fast.d.ts +1 -1
  26. package/dist/commands/core-scan-packages-fast.js +8 -1
  27. package/dist/commands/core.js +12 -3
  28. package/dist/commands/dm-attach.d.ts +10 -0
  29. package/dist/commands/dm-attach.js +33 -5
  30. package/dist/commands/integrations-connect.js +47 -2
  31. package/dist/commands/lanes-session-start.d.ts +17 -0
  32. package/dist/commands/lanes-session-start.js +281 -13
  33. package/dist/commands/lanes-watch.js +11 -3
  34. package/dist/commands/lanes.d.ts +4 -0
  35. package/dist/commands/lanes.js +95 -22
  36. package/dist/commands/library.d.ts +10 -0
  37. package/dist/commands/library.js +30 -3
  38. package/dist/commands/meetings.d.ts +42 -0
  39. package/dist/commands/meetings.js +157 -12
  40. package/dist/commands/mesh.js +3 -0
  41. package/dist/commands/monitor.d.ts +6 -0
  42. package/dist/commands/monitor.js +29 -19
  43. package/dist/commands/onboard.js +8 -1
  44. package/dist/commands/sources.js +7 -3
  45. package/dist/index.js +9 -0
  46. package/dist/lanes-monitor-check-argv.d.ts +1 -1
  47. package/dist/lanes-monitor-check-argv.js +2 -2
  48. package/dist/lanes-session-start-argv.d.ts +4 -1
  49. package/dist/lanes-session-start-argv.js +5 -2
  50. package/dist/lib/bot/fleet-daemon.d.ts +101 -0
  51. package/dist/lib/bot/fleet-daemon.js +227 -0
  52. package/dist/lib/bot/fleet-local.d.ts +26 -0
  53. package/dist/lib/bot/fleet-local.js +51 -2
  54. package/dist/lib/bot/index.d.ts +1 -0
  55. package/dist/lib/bot/index.js +1 -0
  56. package/dist/lib/bot/jobs/hot-signal-sync.d.ts +4 -0
  57. package/dist/lib/bot/jobs/hot-signal-sync.js +8 -1
  58. package/dist/lib/bot/log.js +3 -1
  59. package/dist/lib/bot/probe.js +2 -0
  60. package/dist/lib/bot/run.js +28 -3
  61. package/dist/lib/bot/runtime-failure.d.ts +4 -2
  62. package/dist/lib/bot/runtime-failure.js +9 -1
  63. package/dist/lib/bot/status.d.ts +17 -0
  64. package/dist/lib/bot/status.js +53 -2
  65. package/dist/lib/capacity/collectors/claude-oauth.d.ts +5 -5
  66. package/dist/lib/capacity/collectors/claude-oauth.js +6 -6
  67. package/dist/lib/core-utils/native-scaffold-help.d.ts +16 -0
  68. package/dist/lib/core-utils/native-scaffold-help.js +26 -0
  69. package/dist/lib/core-utils/session-company.d.ts +25 -8
  70. package/dist/lib/core-utils/session-company.js +59 -17
  71. package/dist/lib/daemon/catalog.d.ts +25 -1
  72. package/dist/lib/daemon/catalog.js +29 -2
  73. package/dist/lib/daemon/run.d.ts +0 -1
  74. package/dist/lib/daemon/run.js +3 -11
  75. package/dist/lib/daemon/server.js +26 -7
  76. package/dist/lib/daemon/supervisor.js +1 -1
  77. package/dist/lib/daemon/tools.js +17 -1
  78. package/dist/lib/db/sqlite-binding.js +2 -1
  79. package/dist/lib/doctor/checks/bots.d.ts +2 -0
  80. package/dist/lib/doctor/checks/bots.js +11 -0
  81. package/dist/lib/doctor/checks/runtime-health.js +3 -2
  82. package/dist/lib/doctor/checks/work-context.js +5 -2
  83. package/dist/lib/hook-engine/resolve.d.ts +1 -1
  84. package/dist/lib/hook-engine/resolve.js +4 -1
  85. package/dist/lib/hot-channels/adapters/meeting-providers.d.ts +2 -0
  86. package/dist/lib/hot-channels/adapters/meeting-providers.js +13 -2
  87. package/dist/lib/lanes/index.d.ts +1 -1
  88. package/dist/lib/lanes/index.js +1 -1
  89. package/dist/lib/lanes/monitor.d.ts +14 -0
  90. package/dist/lib/lanes/monitor.js +51 -10
  91. package/dist/lib/lanes/outpost-dispatch.d.ts +3 -0
  92. package/dist/lib/lanes/outpost-dispatch.js +1 -0
  93. package/dist/lib/lanes/store.d.ts +1 -1
  94. package/dist/lib/lanes/store.js +2 -1
  95. package/dist/lib/mesh/client.js +7 -1
  96. package/dist/lib/mesh/live/backfill-held.d.ts +3 -0
  97. package/dist/lib/mesh/live/backfill-held.js +167 -7
  98. package/dist/lib/mesh/live/flush.d.ts +7 -0
  99. package/dist/lib/mesh/live/flush.js +10 -1
  100. package/dist/lib/monitor.d.ts +9 -0
  101. package/dist/lib/monitor.js +33 -7
  102. package/dist/lib/onboarding/orchestrator.js +269 -132
  103. package/dist/lib/onboarding/types.d.ts +2 -0
  104. package/dist/lib/scaffold-cli-floor.js +2 -1
  105. package/dist/lib/signals/failure-alert.js +3 -1
  106. package/dist/lib/work-context/organize.d.ts +6 -0
  107. package/dist/lib/work-context/organize.js +28 -0
  108. package/dist/lib/work-context/paths.d.ts +9 -0
  109. package/dist/lib/work-context/paths.js +15 -0
  110. package/dist/lib/work-context/prd-sync.js +2 -1
  111. package/dist/runners-alias.d.ts +54 -0
  112. package/dist/runners-alias.js +86 -0
  113. package/dist/utils/install-tree-torn.js +5 -3
  114. package/dist/utils/npm-install-flags.d.ts +27 -0
  115. package/dist/utils/npm-install-flags.js +68 -0
  116. package/dist/utils/package-use-lease.js +1 -1
  117. package/dist/utils/qmd-native-binding-error.js +2 -1
  118. package/dist/utils/self-update.js +2 -1
  119. package/dist/utils/staged-install.js +2 -1
  120. package/dist/utils/staged-npm-install.js +2 -1
  121. package/dist/utils/upload-author.d.ts +2 -1
  122. package/dist/utils/upload-author.js +9 -5
  123. package/dist/utils/version-check.js +2 -1
  124. package/dist/utils/version-gate.js +7 -6
  125. package/package.json +7 -7
  126. package/scripts/install-hook-engine.mjs +7 -3
@@ -22,7 +22,8 @@
22
22
  */
23
23
  import * as fs from "node:fs";
24
24
  import * as path from "node:path";
25
- import { readSessionState } from "../../work-context/state.js";
25
+ import { readSessionState, updateSessionState, } from "../../work-context/state.js";
26
+ import { holdsForCompany } from "./flush.js";
26
27
  import { listOutboxOperations, writeAckedRegisterState, } from "../../work-context/outbox.js";
27
28
  import { WORK_CONTEXT_CONTRACT_VERSION, } from "../../work-context/contract.js";
28
29
  import { resolveCompany, sameCompany } from "../../work-context/company.js";
@@ -77,7 +78,52 @@ function verifiedHqRoot(hqRoot) {
77
78
  return null;
78
79
  }
79
80
  }
80
- function verifiedMetaCompanySlug(sessionId, hqRoot) {
81
+ /**
82
+ * company_source values hq-core stamps for a binding a person or a trusted
83
+ * hook chose: `hq-session set` (explicit), a parent session (parent), a spawn
84
+ * company (spawn, spawn_intent), or a single company named in the first prompt
85
+ * (prompt_mention). A SessionStart device default writes device_default, and
86
+ * an older or unrecognised writer leaves the source unknown.
87
+ *
88
+ * Left out on purpose, so they fail closed when they are the only proof for a
89
+ * device-default binding:
90
+ * - manifest_single_company: hq-core's guess from a one-company manifest.
91
+ * - no company_source: meta written before device defaults existed, and the
92
+ * meta agent sessions write (session_bootstrap_meta), whose company the
93
+ * agent entrypoint resolved.
94
+ * - session: a carried-forward binding. hq-core also writes it when
95
+ * SessionStart repairs a stale case alias (session_auto_bind_write_binding_
96
+ * meta), and that rewrite replaces a company_source: device_default, so a
97
+ * session label can be a relabeled device default.
98
+ * The ordinary (non-device-default) path still accepts these, since they are
99
+ * real evidence for legacy and agent sessions.
100
+ */
101
+ const INDEPENDENT_META_SOURCES = new Set([
102
+ "explicit",
103
+ "parent",
104
+ "spawn",
105
+ "spawn_intent",
106
+ "prompt_mention",
107
+ ]);
108
+ function metaScalar(text, key) {
109
+ const pattern = new RegExp(`^\\s*${key}\\s*:\\s*["']?([A-Za-z0-9._-]+)["']?\\s*$`);
110
+ for (const line of text.split(/\r?\n/)) {
111
+ const m = pattern.exec(line);
112
+ if (m?.[1])
113
+ return m[1].toLowerCase();
114
+ }
115
+ return undefined;
116
+ }
117
+ /**
118
+ * Read the company a verified session meta names, or undefined when the meta
119
+ * cannot be company evidence. A binding hq-core made from the device default
120
+ * (company_source: device_default, or company_confidence:
121
+ * device_default_repair) is never evidence: the device default must not vouch
122
+ * for itself. With `requireIndependentSource`, a meta whose source is unknown
123
+ * is refused too, so only an explicit, parent, spawn or prompt-mention bind
124
+ * counts.
125
+ */
126
+ function verifiedMetaCompanySlug(sessionId, hqRoot, requireIndependentSource = false) {
81
127
  try {
82
128
  const root = verifiedHqRoot(hqRoot);
83
129
  if (!root)
@@ -89,6 +135,14 @@ function verifiedMetaCompanySlug(sessionId, hqRoot) {
89
135
  const realMeta = fs.realpathSync(meta);
90
136
  if (path.relative(root, realMeta).startsWith(".."))
91
137
  return undefined;
138
+ const text = fs.readFileSync(realMeta, "utf8");
139
+ const source = metaScalar(text, "company_source");
140
+ const confidence = metaScalar(text, "company_confidence");
141
+ if (source === "device_default" || confidence?.startsWith("device_default"))
142
+ return undefined;
143
+ if (requireIndependentSource && !(source && INDEPENDENT_META_SOURCES.has(source))) {
144
+ return undefined;
145
+ }
92
146
  return readMetaCompanySlug(sessionId, root);
93
147
  }
94
148
  catch {
@@ -119,7 +173,7 @@ function consistentCandidate(candidates) {
119
173
  }
120
174
  return { candidate: chosen, conflict: false };
121
175
  }
122
- function localCompanyCandidates(ref, state, canonicalHqRoot, canonicalHqRoots = []) {
176
+ function localCompanyCandidates(ref, state, canonicalHqRoot, canonicalHqRoots = [], requireIndependentMetaSource = false) {
123
177
  const candidates = [];
124
178
  // A slug without a UID can be the failed/stale projection this repair is
125
179
  // investigating. Only a persisted UID is a durable registration signal.
@@ -140,7 +194,7 @@ function localCompanyCandidates(ref, state, canonicalHqRoot, canonicalHqRoots =
140
194
  return false;
141
195
  }
142
196
  })) {
143
- const slug = verifiedMetaCompanySlug(ref.sessionId, root);
197
+ const slug = verifiedMetaCompanySlug(ref.sessionId, root, requireIndependentMetaSource);
144
198
  if (slug)
145
199
  candidates.push({ slug, hqRoot: root });
146
200
  // The event cwd itself is not company evidence. The repository's origin is,
@@ -242,6 +296,17 @@ export function observationFromHeldRef(ref, contractVersion, clientOperationId)
242
296
  function isSuccessfulBackfillRecovery(kind) {
243
297
  return kind === "bound" || kind === "needs_project" || kind === "needs_task" || kind === "queued";
244
298
  }
299
+ const DEVICE_DEFAULT_STILL_HELD = "needs_company: device default only; flush keeps holding";
300
+ /**
301
+ * The one rule the dry-run preview and the live post-reconcile check share for
302
+ * "this recovery releases the held events". A persisted slug or uid counts
303
+ * (a slug-only binding gets its uid on the daemon's next held retry). A
304
+ * device-default binding never does: flush holds it as NEEDS_COMPANY and
305
+ * mayEmitConversation refuses its conversation text (#2398).
306
+ */
307
+ function releasesHeldEvents(binding) {
308
+ return Boolean(binding.slug || binding.uid) && !binding.deviceDefault;
309
+ }
245
310
  async function previewCompanyRecovery(ref, workContextRoot, remoteOwnerHint, env, useDeviceDefault, validateMembership) {
246
311
  // This predictor is called only with a ref already rebuilt from trusted local
247
312
  // evidence. Do not let raw held-event cwd/hqRoot values re-enter resolution.
@@ -291,6 +356,9 @@ async function previewCompanyRecovery(ref, workContextRoot, remoteOwnerHint, env
291
356
  };
292
357
  }
293
358
  }
359
+ if (!releasesHeldEvents({ ...resolved, deviceDefault: resolved.source === "device_default" })) {
360
+ return { kind: "needs_company", reason: DEVICE_DEFAULT_STILL_HELD };
361
+ }
294
362
  return { kind: "queued" };
295
363
  }
296
364
  /**
@@ -304,11 +372,91 @@ async function previewCompanyRecovery(ref, workContextRoot, remoteOwnerHint, env
304
372
  * Requiring companyUid causes dry-run and live counts to diverge when offline
305
373
  * reconcile writes only a slug (resolveCompany returns trusted_explicit with
306
374
  * no uid when no manifest lookup occurs), making live report reconciled=0 for
307
- * sessions the dry-run correctly predicted as recoverable.
375
+ * sessions the dry-run correctly predicted as recoverable. The decision itself
376
+ * is releasesHeldEvents, which the dry-run preview applies to the same binding.
308
377
  */
309
378
  function hasDurableCompanyRecovery(sessionId, workContextRoot, readState) {
310
379
  const state = readState(sessionId, workContextRoot);
311
- return Boolean(state?.companyUid || state?.companySlug);
380
+ return Boolean(state) && releasesHeldEvents({
381
+ slug: state.companySlug,
382
+ uid: state.companyUid,
383
+ deviceDefault: state.companyConfidence === "device_default",
384
+ });
385
+ }
386
+ /**
387
+ * A device-default binding is not attribution evidence, so flush holds its
388
+ * events (see holdsForCompany). Release it only when durable local evidence
389
+ * (session meta under a verified HQ root, or a manifest-mapped repository)
390
+ * names the same company; the device default must not prove itself. Session
391
+ * meta counts here only when its company_source is an independent bind
392
+ * (explicit, parent, spawn or prompt mention): hq-core's SessionStart writes
393
+ * the device default into that same meta, and a meta with no source cannot
394
+ * show it was not one. Removing companyConfidence lets flush post the
395
+ * session's conversation (mayEmitConversation), so this gate is the #2398
396
+ * privacy rule for the backfill.
397
+ */
398
+ function confirmDeviceDefaultBinding(ref, state, deps, dryRun, readState, result) {
399
+ const { sessionId } = ref;
400
+ const unbound = { ...state, companyUid: undefined, companySlug: undefined };
401
+ const proof = consistentCandidate(localCompanyCandidates(ref, unbound, deps.hqRoot, deps.hqRoots, true));
402
+ const bound = { slug: state.companySlug, uid: state.companyUid };
403
+ const unresolved = (reason) => {
404
+ result.unresolved += 1;
405
+ result.unresolvedReasons.push({ sessionId, reason });
406
+ deps.log?.(`unresolved ${sessionId} (${reason})`);
407
+ };
408
+ // Local proof is a slug (meta or a manifest-mapped remote). A binding with a
409
+ // uid and no slug cannot be compared with it, which is missing evidence, not
410
+ // conflicting evidence.
411
+ const comparable = (candidate) => Boolean((candidate.uid && bound.uid) || (candidate.slug && bound.slug));
412
+ if (!proof.conflict && proof.candidate && !comparable(proof.candidate)) {
413
+ result.noEvidence += 1;
414
+ unresolved("device-default binding has no slug to compare with local evidence");
415
+ return;
416
+ }
417
+ if (proof.conflict || (proof.candidate && !candidatesAgree(proof.candidate, bound))) {
418
+ result.conflictingEvidence += 1;
419
+ unresolved("device-default company does not match local evidence");
420
+ return;
421
+ }
422
+ if (!proof.candidate) {
423
+ result.noEvidence += 1;
424
+ unresolved("device default only; no local company evidence");
425
+ return;
426
+ }
427
+ if (dryRun) {
428
+ result.reconciled += 1;
429
+ deps.log?.(`would confirm device-default company for ${sessionId} from local evidence`);
430
+ return;
431
+ }
432
+ updateSessionState(sessionId, deps.workContextRoot, (current) => {
433
+ if (!current ||
434
+ current.companyConfidence !== "device_default" ||
435
+ current.companyUid !== state.companyUid ||
436
+ current.companySlug !== state.companySlug) {
437
+ return null;
438
+ }
439
+ const { companyConfidence: _deviceDefault, ...rest } = current;
440
+ return {
441
+ ...rest,
442
+ contextStatus: rest.contextStatus === "needs_company"
443
+ ? (rest.projectId ? (rest.taskId ? "bound" : "needs_task") : "needs_project")
444
+ : rest.contextStatus,
445
+ updatedAt: new Date().toISOString(),
446
+ };
447
+ });
448
+ const after = readState(sessionId, deps.workContextRoot);
449
+ // The same rule the dry-run applied above: a slug-only binding counts, and
450
+ // gets its uid on the daemon's next held retry.
451
+ if (after &&
452
+ !holdsForCompany(after) &&
453
+ releasesHeldEvents({ slug: after.companySlug, uid: after.companyUid, deviceDefault: false })) {
454
+ result.reconciled += 1;
455
+ deps.log?.(`reconciled ${sessionId} → device-default company confirmed by local evidence`);
456
+ }
457
+ else {
458
+ unresolved("device-default binding changed during confirmation");
459
+ }
312
460
  }
313
461
  function latestAcknowledgedRegistration(sessionId, operations) {
314
462
  for (let index = operations.length - 1; index >= 0; index -= 1) {
@@ -467,10 +615,22 @@ export async function backfillHeldSessions(deps) {
467
615
  for (const ref of considered) {
468
616
  const { sessionId, harness } = ref;
469
617
  const state = readState(sessionId, deps.workContextRoot);
470
- if (state?.companyUid) {
618
+ // "Attributed" must mean what flush means by it. A companyUid from a device
619
+ // default (or one left on a needs_company state) is still held, so it is
620
+ // not attributed and must not be skipped here.
621
+ if (state?.companyUid && !holdsForCompany(state)) {
471
622
  result.alreadyAttributed += 1;
472
623
  continue;
473
624
  }
625
+ // A slug-only device-default binding goes here too. On the ordinary path
626
+ // the dry-run would resolve its slug as trusted and predict a release,
627
+ // while live reconcile keeps companyConfidence: device_default (see
628
+ // mergeLocalSessionFields) and stays held.
629
+ if (state?.companyConfidence === "device_default" &&
630
+ (state.companyUid || state.companySlug)) {
631
+ confirmDeviceDefaultBinding(ref, state, deps, dryRun, readState, result);
632
+ continue;
633
+ }
474
634
  const evidence = consistentCandidate(localCompanyCandidates(ref, state, deps.hqRoot, deps.hqRoots));
475
635
  if (evidence.conflict) {
476
636
  result.unresolved += 1;
@@ -86,6 +86,13 @@ export interface FlushSummary {
86
86
  * Recovers orphan `*.claimed` files first; restores unprocessed lines on throw.
87
87
  */
88
88
  export declare function flushSessionEvents(inputDeps: FlushDeps): Promise<FlushSummary>;
89
+ /**
90
+ * True when flush holds a session as NEEDS_COMPANY even though its state may
91
+ * carry a companyUid: a device-default binding is not attribution evidence,
92
+ * and needs_company always holds. The held backfill uses this same predicate
93
+ * so it never reports such a session as already attributed.
94
+ */
95
+ export declare function holdsForCompany(state: SessionStateFile): boolean;
89
96
  /**
90
97
  * Assert flush never opens the machine-global bind cache.
91
98
  * Used by tests; production flush has no reference to this path.
@@ -1014,6 +1014,15 @@ function dropOwnerMismatchedSession(input) {
1014
1014
  input.deps.log?.(`work-mesh: session ${input.sessionId} is reported by another actor (403 SESSION_OWNER_MISMATCH); dropped ${input.items.length} event(s), not dead-lettered`);
1015
1015
  }
1016
1016
  }
1017
+ /**
1018
+ * True when flush holds a session as NEEDS_COMPANY even though its state may
1019
+ * carry a companyUid: a device-default binding is not attribution evidence,
1020
+ * and needs_company always holds. The held backfill uses this same predicate
1021
+ * so it never reports such a session as already attributed.
1022
+ */
1023
+ export function holdsForCompany(state) {
1024
+ return state.companyConfidence === "device_default" || state.contextStatus === "needs_company";
1025
+ }
1017
1026
  function classifySession(state) {
1018
1027
  if (!state) {
1019
1028
  return { action: "hold", heldReason: "STATE_ABSENT" };
@@ -1027,7 +1036,7 @@ function classifySession(state) {
1027
1036
  state.companyUid === state.ownerMismatch.companyUid) {
1028
1037
  return { action: "drop", reason: "owner_mismatch" };
1029
1038
  }
1030
- if (state.companyConfidence === "device_default" || state.contextStatus === "needs_company") {
1039
+ if (holdsForCompany(state)) {
1031
1040
  return { action: "hold", heldReason: "NEEDS_COMPANY" };
1032
1041
  }
1033
1042
  if (state.contextStatus === "company_conflict") {
@@ -2,6 +2,7 @@ import type { LaneCompanyRef, LaneProvider } from "./lanes/types.js";
2
2
  export declare const MONITOR_SCHEMA_VERSION: "hq-monitor.v1";
3
3
  export declare const MONITOR_FLAG = "monitor.enabled";
4
4
  export declare const MONITOR_FLAG_DEFAULT = false;
5
+ /** Default lifetime when `hq monitor start` has neither --timeout nor --persistent. */
5
6
  export declare const MONITOR_DEFAULT_TIMEOUT_MS: number;
6
7
  export declare const MONITOR_DEFAULT_CHECKIN_MS: number;
7
8
  export declare const MONITOR_BATCH_WINDOW_MS = 200;
@@ -143,6 +144,14 @@ export declare function recordMonitorTargetActivity(hqRoot: string, targetKey: s
143
144
  export declare function recordMonitorTargetDeliveryAtPath(activityPath: string, now?: () => Date, kind?: MonitorTargetActivity["last_delivery_kind"]): void;
144
145
  /** Elapsed idle time in whole units; live timers never land on exact multiples. */
145
146
  export declare function formatElapsed(ms: number): string;
147
+ /**
148
+ * Scan-free test run before each supervisor tick's check-in. A supervisor only
149
+ * tests its own interval: every eligible monitor has a live supervisor of its
150
+ * own, so the one holding the target's shortest interval passes this test
151
+ * whenever runMonitorCheckinTick would send. A missing or unreadable activity
152
+ * file passes too, so the full path keeps creating or reporting it.
153
+ */
154
+ export declare function monitorCheckinMayBeDue(hqRoot: string, targetKey: string, checkinMs: number | null, nowMs: number, targetActivityAt: number | null): boolean;
146
155
  export declare function runMonitorCheckinTick(hqRoot: string, targetKey: string, deps: MonitorCheckinDeps): Promise<MonitorCheckinResult>;
147
156
  export declare function readMonitorPidLiveness(pid: number | null, starttime: number | null, readStarttime?: (pid: number) => number | null): boolean;
148
157
  export {};
@@ -7,7 +7,8 @@ import { readProcStarttime } from "./lanes/spawn.js";
7
7
  export const MONITOR_SCHEMA_VERSION = "hq-monitor.v1";
8
8
  export const MONITOR_FLAG = "monitor.enabled";
9
9
  export const MONITOR_FLAG_DEFAULT = false;
10
- export const MONITOR_DEFAULT_TIMEOUT_MS = 5 * 60_000;
10
+ /** Default lifetime when `hq monitor start` has neither --timeout nor --persistent. */
11
+ export const MONITOR_DEFAULT_TIMEOUT_MS = 30 * 60_000;
11
12
  export const MONITOR_DEFAULT_CHECKIN_MS = 55 * 60_000;
12
13
  const MONITOR_PROMPT_CACHE_TTL_MS = 60 * 60_000;
13
14
  export const MONITOR_BATCH_WINDOW_MS = 200;
@@ -462,6 +463,35 @@ export function formatElapsed(ms) {
462
463
  return `${minutes}m`;
463
464
  return `${Math.max(0, Math.floor(ms / 1_000))}s`;
464
465
  }
466
+ /** Idle time since the target's last activity when a check-in at this interval is due, otherwise null. */
467
+ function dueCheckinElapsed(activity, targetActivityAt, nowMs, intervalMs) {
468
+ const lastActivityMs = Math.max(activity.last_delivery_ms, activity.last_activity_ms ?? Number.NEGATIVE_INFINITY, targetActivityAt ?? Number.NEGATIVE_INFINITY);
469
+ const elapsed = nowMs - lastActivityMs;
470
+ if (elapsed < intervalMs)
471
+ return null;
472
+ if (activity.last_checkin_attempt_ms !== undefined && nowMs - activity.last_checkin_attempt_ms < intervalMs)
473
+ return null;
474
+ return elapsed;
475
+ }
476
+ /**
477
+ * Scan-free test run before each supervisor tick's check-in. A supervisor only
478
+ * tests its own interval: every eligible monitor has a live supervisor of its
479
+ * own, so the one holding the target's shortest interval passes this test
480
+ * whenever runMonitorCheckinTick would send. A missing or unreadable activity
481
+ * file passes too, so the full path keeps creating or reporting it.
482
+ */
483
+ export function monitorCheckinMayBeDue(hqRoot, targetKey, checkinMs, nowMs, targetActivityAt) {
484
+ if (checkinMs === null || checkinMs <= 0)
485
+ return false;
486
+ let activity;
487
+ try {
488
+ activity = readJson(path.join(targetStorageDir(hqRoot, targetKey), "activity.json"));
489
+ }
490
+ catch {
491
+ return true;
492
+ }
493
+ return activity === null || dueCheckinElapsed(activity, targetActivityAt, nowMs, checkinMs) !== null;
494
+ }
465
495
  function formatCheckinText(elapsedMs, monitors) {
466
496
  const descriptions = monitors.map(({ meta }) => meta.description).join(", ");
467
497
  return `hq monitor check-in — idle for ${formatElapsed(elapsedMs)}; ${monitors.length} monitor(s) still armed: ${descriptions}. If you are idle, confirm nothing needs action and end your turn. If you are mid-task, ignore this and continue.`;
@@ -488,13 +518,9 @@ export async function runMonitorCheckinTick(hqRoot, targetKey, deps) {
488
518
  });
489
519
  return { sent: false, sequence: null, text: null, outcome: null };
490
520
  }
491
- const lastActivityMs = Math.max(activity.last_delivery_ms, activity.last_activity_ms ?? Number.NEGATIVE_INFINITY, targetActivityAt ?? Number.NEGATIVE_INFINITY);
492
- const elapsed = nowMs - lastActivityMs;
493
- if (elapsed < shortestInterval)
521
+ const elapsed = dueCheckinElapsed(activity, targetActivityAt, nowMs, shortestInterval);
522
+ if (elapsed === null)
494
523
  return { sent: false, sequence: null, text: null, outcome: null };
495
- if (activity.last_checkin_attempt_ms !== undefined && nowMs - activity.last_checkin_attempt_ms < shortestInterval) {
496
- return { sent: false, sequence: null, text: null, outcome: null };
497
- }
498
524
  const text = formatCheckinText(elapsed, monitors);
499
525
  const sequence = activity.checkin_count + 1;
500
526
  const delivery = await deps.deliver(text, sequence);