@indigoai-us/hq-cli 5.345.208 → 5.345.211

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 (133) hide show
  1. package/CHANGELOG.md +106 -0
  2. package/assets/scaffold/core/scripts/derive-trigger-facts.sh +22 -3
  3. package/assets/scaffold/core/scripts/lib/trigger-fact-text.awk +152 -41
  4. package/dist/command-catalog.generated.d.ts +33 -8
  5. package/dist/command-catalog.generated.js +40 -8
  6. package/dist/command-registration-plan.d.ts +2 -2
  7. package/dist/command-registration-plan.js +1 -1
  8. package/dist/commands/access.js +11 -5
  9. package/dist/commands/agents.d.ts +8 -0
  10. package/dist/commands/agents.js +5 -0
  11. package/dist/commands/bot.d.ts +8 -0
  12. package/dist/commands/bot.js +67 -7
  13. package/dist/commands/channels.js +4 -0
  14. package/dist/commands/cloud.d.ts +83 -2
  15. package/dist/commands/cloud.js +161 -31
  16. package/dist/commands/company.d.ts +9 -0
  17. package/dist/commands/company.js +44 -14
  18. package/dist/commands/core-checkpoint-native.js +21 -0
  19. package/dist/commands/core-derive-trigger-facts-native.d.ts +1 -0
  20. package/dist/commands/core-derive-trigger-facts-native.js +75 -14
  21. package/dist/commands/core-generate-workers-registry-fast.d.ts +1 -1
  22. package/dist/commands/core-generate-workers-registry-fast.js +7 -1
  23. package/dist/commands/core-job-run-native.d.ts +8 -0
  24. package/dist/commands/core-job-run-native.js +11 -3
  25. package/dist/commands/core-jobs-native.js +1 -1
  26. package/dist/commands/core-register-project-native.js +31 -1
  27. package/dist/commands/core-scan-packages-fast.d.ts +1 -1
  28. package/dist/commands/core-scan-packages-fast.js +8 -1
  29. package/dist/commands/core-work-mesh-bind-trusted-native.d.ts +14 -2
  30. package/dist/commands/core-work-mesh-bind-trusted-native.js +62 -8
  31. package/dist/commands/core.js +12 -3
  32. package/dist/commands/dm-attach.d.ts +10 -0
  33. package/dist/commands/dm-attach.js +33 -5
  34. package/dist/commands/integrations-connect.d.ts +16 -0
  35. package/dist/commands/integrations-connect.js +70 -6
  36. package/dist/commands/lanes-session-start.d.ts +17 -0
  37. package/dist/commands/lanes-session-start.js +281 -13
  38. package/dist/commands/lanes-watch.js +11 -3
  39. package/dist/commands/lanes.d.ts +4 -0
  40. package/dist/commands/lanes.js +95 -22
  41. package/dist/commands/library.d.ts +10 -0
  42. package/dist/commands/library.js +30 -3
  43. package/dist/commands/meetings.d.ts +42 -0
  44. package/dist/commands/meetings.js +157 -12
  45. package/dist/commands/mesh.js +3 -0
  46. package/dist/commands/monitor.d.ts +6 -0
  47. package/dist/commands/monitor.js +29 -19
  48. package/dist/commands/onboard.js +8 -1
  49. package/dist/commands/sources.js +7 -3
  50. package/dist/index.js +9 -0
  51. package/dist/lanes-monitor-check-argv.d.ts +1 -1
  52. package/dist/lanes-monitor-check-argv.js +2 -2
  53. package/dist/lanes-session-start-argv.d.ts +4 -1
  54. package/dist/lanes-session-start-argv.js +5 -2
  55. package/dist/lib/bot/fleet-daemon.d.ts +101 -0
  56. package/dist/lib/bot/fleet-daemon.js +227 -0
  57. package/dist/lib/bot/fleet-local.d.ts +26 -0
  58. package/dist/lib/bot/fleet-local.js +51 -2
  59. package/dist/lib/bot/index.d.ts +1 -0
  60. package/dist/lib/bot/index.js +1 -0
  61. package/dist/lib/bot/jobs/hot-signal-sync.d.ts +4 -0
  62. package/dist/lib/bot/jobs/hot-signal-sync.js +8 -1
  63. package/dist/lib/bot/log.js +3 -1
  64. package/dist/lib/bot/probe.js +2 -0
  65. package/dist/lib/bot/run.js +28 -3
  66. package/dist/lib/bot/runtime-failure.d.ts +4 -2
  67. package/dist/lib/bot/runtime-failure.js +9 -1
  68. package/dist/lib/bot/status.d.ts +17 -0
  69. package/dist/lib/bot/status.js +53 -2
  70. package/dist/lib/capacity/collectors/claude-oauth.d.ts +5 -5
  71. package/dist/lib/capacity/collectors/claude-oauth.js +6 -6
  72. package/dist/lib/core-utils/native-scaffold-help.d.ts +16 -0
  73. package/dist/lib/core-utils/native-scaffold-help.js +26 -0
  74. package/dist/lib/core-utils/session-company.d.ts +25 -8
  75. package/dist/lib/core-utils/session-company.js +59 -17
  76. package/dist/lib/daemon/catalog.d.ts +34 -1
  77. package/dist/lib/daemon/catalog.js +42 -3
  78. package/dist/lib/daemon/run.d.ts +5 -4
  79. package/dist/lib/daemon/run.js +40 -16
  80. package/dist/lib/daemon/server.js +26 -7
  81. package/dist/lib/daemon/supervisor.d.ts +2 -0
  82. package/dist/lib/daemon/supervisor.js +60 -1
  83. package/dist/lib/daemon/tools.js +17 -1
  84. package/dist/lib/db/sqlite-binding.js +2 -1
  85. package/dist/lib/doctor/checks/bots.d.ts +2 -0
  86. package/dist/lib/doctor/checks/bots.js +11 -0
  87. package/dist/lib/doctor/checks/runtime-health.js +3 -2
  88. package/dist/lib/doctor/checks/work-context.js +5 -2
  89. package/dist/lib/hook-engine/resolve.d.ts +1 -1
  90. package/dist/lib/hook-engine/resolve.js +4 -1
  91. package/dist/lib/hot-channels/adapters/meeting-providers.d.ts +2 -0
  92. package/dist/lib/hot-channels/adapters/meeting-providers.js +13 -2
  93. package/dist/lib/lanes/index.d.ts +1 -1
  94. package/dist/lib/lanes/index.js +1 -1
  95. package/dist/lib/lanes/monitor.d.ts +14 -0
  96. package/dist/lib/lanes/monitor.js +51 -10
  97. package/dist/lib/lanes/outpost-dispatch.d.ts +3 -0
  98. package/dist/lib/lanes/outpost-dispatch.js +1 -0
  99. package/dist/lib/lanes/store.d.ts +1 -1
  100. package/dist/lib/lanes/store.js +2 -1
  101. package/dist/lib/mesh/client.js +7 -1
  102. package/dist/lib/mesh/live/backfill-held.d.ts +3 -0
  103. package/dist/lib/mesh/live/backfill-held.js +167 -7
  104. package/dist/lib/mesh/live/flush.d.ts +7 -0
  105. package/dist/lib/mesh/live/flush.js +10 -1
  106. package/dist/lib/monitor.d.ts +9 -0
  107. package/dist/lib/monitor.js +33 -7
  108. package/dist/lib/onboarding/orchestrator.js +269 -132
  109. package/dist/lib/onboarding/types.d.ts +2 -0
  110. package/dist/lib/scaffold-cli-floor.js +2 -1
  111. package/dist/lib/signals/failure-alert.js +3 -1
  112. package/dist/lib/sync-core/reconcile.js +15 -11
  113. package/dist/lib/work-context/organize.d.ts +6 -0
  114. package/dist/lib/work-context/organize.js +28 -0
  115. package/dist/lib/work-context/paths.d.ts +9 -0
  116. package/dist/lib/work-context/paths.js +15 -0
  117. package/dist/lib/work-context/prd-sync.js +2 -1
  118. package/dist/runners-alias.d.ts +54 -0
  119. package/dist/runners-alias.js +86 -0
  120. package/dist/utils/install-tree-torn.js +5 -3
  121. package/dist/utils/npm-install-flags.d.ts +27 -0
  122. package/dist/utils/npm-install-flags.js +68 -0
  123. package/dist/utils/package-use-lease.js +1 -1
  124. package/dist/utils/qmd-native-binding-error.js +2 -1
  125. package/dist/utils/self-update.js +2 -1
  126. package/dist/utils/staged-install.js +2 -1
  127. package/dist/utils/staged-npm-install.js +2 -1
  128. package/dist/utils/upload-author.d.ts +2 -1
  129. package/dist/utils/upload-author.js +9 -5
  130. package/dist/utils/version-check.js +2 -1
  131. package/dist/utils/version-gate.js +7 -6
  132. package/package.json +7 -7
  133. package/scripts/install-hook-engine.mjs +7 -3
@@ -15,6 +15,8 @@ export interface BotsDoctorDeps {
15
15
  claudeLogin?: () => ClaudeLoginCheck;
16
16
  /** Whether and why a legacy bot moves to the HQ Fleet Runtime at its next start (tests). */
17
17
  legacyMove?: (dir: string, config: BotConfig) => LegacyMoveState;
18
+ /** Whether hq daemon runs this Mac's HQ Fleet bots (tests). */
19
+ fleetDaemon?: () => boolean;
18
20
  }
19
21
  /** The last reported failure, unless a later turn worked. */
20
22
  export declare function unresolvedLastFailure(status: BotStatusFile | null): BotStatusFile["lastFailure"] | null;
@@ -8,6 +8,8 @@ import * as os from "node:os";
8
8
  import * as path from "node:path";
9
9
  import { botsRoot, botDir, launchdLabel } from "../../bot/paths.js";
10
10
  import { HQ_FLEET_RUNTIME_ENGINE_ID, readBotConfig } from "../../bot/config.js";
11
+ import { fleetBotsManagedByDaemon } from "../../bot/fleet-daemon.js";
12
+ import { fleetLocalLaunchAgentLabel, fleetLocalLaunchAgentPlist } from "../../bot/fleet-local.js";
11
13
  import { checkClaudeCodeLogin, claudeLoginFix, describeClaudeLoginSources, } from "../../bot/claude-login.js";
12
14
  import { isPidAlive, readBotStatus } from "../../bot/status.js";
13
15
  import { legacyMoveState } from "../../bot/legacy-convert.js";
@@ -142,6 +144,15 @@ function runChecks(deps) {
142
144
  });
143
145
  }
144
146
  }
147
+ if (!isLegacyBot(config) && (deps.fleetDaemon ?? (() => fleetBotsManagedByDaemon({ home })))() && fs.existsSync(fleetLocalLaunchAgentPlist(config.agentUid, home))) {
148
+ results.push({
149
+ status: "WARN",
150
+ checkId: `bots.${name}.own-login-item`,
151
+ target: fleetLocalLaunchAgentPlist(config.agentUid, home),
152
+ message: `${name} still has its own login item (${fleetLocalLaunchAgentLabel(config.agentUid)}), which macOS reports as "python" running in the background. hq daemon runs HQ Fleet bots on this Mac.`,
153
+ remediation: `hq bot start ${name}`,
154
+ });
155
+ }
145
156
  const lastFailure = unresolvedLastFailure(status);
146
157
  if (lastFailure) {
147
158
  results.push({
@@ -30,6 +30,7 @@ import * as fs from "node:fs";
30
30
  import * as os from "node:os";
31
31
  import * as path from "node:path";
32
32
  import { planCommandSpawn } from "../../../utils/windows-spawn.js";
33
+ import { npmGlobalInstallArgv } from "../../../utils/npm-install-flags.js";
33
34
  /** The id of the AI-runtime-health family. */
34
35
  export const RUNTIMES_FAMILY_ID = "runtimes";
35
36
  /** Common id prefix for every result this family emits. */
@@ -54,7 +55,7 @@ export const AI_RUNTIMES = [
54
55
  binary: "claude",
55
56
  versionArgs: ["--version"],
56
57
  probeArgs: ["-p", PROBE_PROMPT],
57
- installHint: "npm install -g @anthropic-ai/claude-code",
58
+ installHint: `npm ${npmGlobalInstallArgv("@anthropic-ai/claude-code", { allowScripts: ["@anthropic-ai/claude-code"] }).join(" ")}`,
58
59
  },
59
60
  {
60
61
  key: "codex",
@@ -68,7 +69,7 @@ export const AI_RUNTIMES = [
68
69
  "read-only",
69
70
  PROBE_PROMPT,
70
71
  ],
71
- installHint: "npm install -g @openai/codex",
72
+ installHint: `npm ${npmGlobalInstallArgv("@openai/codex", { allowScripts: [] }).join(" ")}`,
72
73
  },
73
74
  {
74
75
  key: "grok",
@@ -9,7 +9,7 @@ import * as path from "node:path";
9
9
  import { readDeviceConfig, } from "../../work-context/config.js";
10
10
  import { outboxStats, listOutboxOperations } from "../../work-context/outbox.js";
11
11
  import { outboxQuarantineStatusEnabled } from "../../work-context/outbox-quarantine-status-flag.js";
12
- import { workContextRoot, workContextSessionsDir } from "../../work-context/paths.js";
12
+ import { isWorkContextSessionStateFileName, workContextRoot, workContextSessionsDir, } from "../../work-context/paths.js";
13
13
  import { countDistinctHeldEvents, countJsonlLines, deadLetterNonEmpty, } from "../../mesh/live/spool.js";
14
14
  import { workMeshDeadLetterPath, workMeshHeldPath, workMeshRoot, workMeshSpoolPath, } from "../../mesh/live/paths.js";
15
15
  import { collectDaemonDoctor, formatDaemonDoctor, } from "../../mesh/live/daemon/doctor.js";
@@ -54,7 +54,10 @@ function runChecks(deps) {
54
54
  });
55
55
  }
56
56
  else {
57
- const files = fs.readdirSync(sessionsDir).filter((n) => n.endsWith(".json"));
57
+ // Only `<sessionId>.json` is session state. Sidecars such as
58
+ // `<sessionId>.prd-snapshot.json` have their own shape and were counted
59
+ // as corrupt (feedback_e99bf6b5).
60
+ const files = fs.readdirSync(sessionsDir).filter(isWorkContextSessionStateFileName);
58
61
  let corrupt = 0;
59
62
  let healthy = 0;
60
63
  for (const name of files) {
@@ -1,5 +1,5 @@
1
1
  import { type SpawnSyncReturns } from 'node:child_process';
2
- export declare const HOOK_ENGINE_REPAIR = "npm install -g @indigoai-us/hq-cli --include=optional";
2
+ export declare const HOOK_ENGINE_REPAIR = "npm install -g @indigoai-us/hq-cli --allow-scripts=@indigoai-us/hq-cli --allow-scripts=better-sqlite3 --allow-scripts=node-llama-cpp --allow-scripts=tree-sitter-go --allow-scripts=tree-sitter-python --allow-scripts=tree-sitter-rust --allow-scripts=tree-sitter-typescript --allow-scripts=tree-sitter-javascript --include=optional";
3
3
  export declare const HOOK_ENGINE_REPAIR_PIN = "hq core hook-engine-path --repair";
4
4
  export interface EngineOptions {
5
5
  home?: string;
@@ -7,7 +7,10 @@ const require = createRequire(import.meta.url);
7
7
  // Capture metadata while the package-use lease protects this install tree.
8
8
  // Resident commands may call doctor after an update removes the old manifest.
9
9
  const cliManifest = JSON.parse(readFileSync(new URL('../../../package.json', import.meta.url), 'utf8'));
10
- export const HOOK_ENGINE_REPAIR = 'npm install -g @indigoai-us/hq-cli --include=optional';
10
+ // Inlined so this file keeps importing only node builtins (it must load from a
11
+ // resident process after an update replaced the tree, and from postinstall).
12
+ // Equal to HQ_CLI_NPM_REPAIR_COMMAND; npm-install-flags.test.ts checks parity.
13
+ export const HOOK_ENGINE_REPAIR = 'npm install -g @indigoai-us/hq-cli --allow-scripts=@indigoai-us/hq-cli --allow-scripts=better-sqlite3 --allow-scripts=node-llama-cpp --allow-scripts=tree-sitter-go --allow-scripts=tree-sitter-python --allow-scripts=tree-sitter-rust --allow-scripts=tree-sitter-typescript --allow-scripts=tree-sitter-javascript --include=optional';
11
14
  export const HOOK_ENGINE_REPAIR_PIN = 'hq core hook-engine-path --repair';
12
15
  const platforms = new Set(['win32-x64', 'win32-arm64', 'darwin-x64', 'darwin-arm64', 'linux-x64', 'linux-arm64']);
13
16
  /** US-020 must set this package capability when the replaced bash hooks retire. */
@@ -77,6 +77,8 @@ export interface MeetingIdentity {
77
77
  }
78
78
  /** Recordings that start this close together may be the same meeting. */
79
79
  export declare const SAME_MEETING_WINDOW_MS: number;
80
+ /** A real calendar event id, or undefined for missing / Fireflies placeholder. */
81
+ export declare function usableCalendarEventId(id: string | undefined): string | undefined;
80
82
  /**
81
83
  * Whether two recordings are the same meeting: the same calendar event, or
82
84
  * starts within 30 minutes plus the same call link, a matching title, or at
@@ -119,7 +119,7 @@ export const firefliesProvider = {
119
119
  async read(gateway, meeting) {
120
120
  const transcript = resultText(await gateway.call(FIREFLIES_TRANSCRIPT_TOOL, { transcriptId: meeting.id }));
121
121
  const summary = resultText(await gateway.call(FIREFLIES_SUMMARY_TOOL, { transcriptId: meeting.id }));
122
- const calId = firefliesField(transcript, "Cal Id");
122
+ const calId = usableCalendarEventId(firefliesField(transcript, "Cal Id"));
123
123
  if (calId && !meeting.calendarEventId)
124
124
  meeting.calendarEventId = calId;
125
125
  const noSentences = /^Sentences:\s*No sentences\s*$/m.test(transcript) || transcript.trim() === "";
@@ -227,13 +227,24 @@ function urlKey(url) {
227
227
  }
228
228
  /** Recordings that start this close together may be the same meeting. */
229
229
  export const SAME_MEETING_WINDOW_MS = 30 * 60 * 1000;
230
+ /** Fireflies writes this when a recording has no calendar invite. */
231
+ const NO_CALENDAR_EVENT = /^(no cal id|null|none|n\/a)$/i;
232
+ /** A real calendar event id, or undefined for missing / Fireflies placeholder. */
233
+ export function usableCalendarEventId(id) {
234
+ const v = id?.trim();
235
+ if (!v || NO_CALENDAR_EVENT.test(v))
236
+ return undefined;
237
+ return v;
238
+ }
230
239
  /**
231
240
  * Whether two recordings are the same meeting: the same calendar event, or
232
241
  * starts within 30 minutes plus the same call link, a matching title, or at
233
242
  * least two participants and more than half of the smaller list in common.
234
243
  */
235
244
  export function sameMeeting(a, b) {
236
- if (a.calendarEventId && b.calendarEventId && a.calendarEventId === b.calendarEventId)
245
+ const calA = usableCalendarEventId(a.calendarEventId);
246
+ const calB = usableCalendarEventId(b.calendarEventId);
247
+ if (calA && calB && calA === calB)
237
248
  return true;
238
249
  if (Math.abs(a.startMs - b.startMs) > SAME_MEETING_WINDOW_MS)
239
250
  return false;
@@ -24,7 +24,7 @@ export { LANES_STORE_REL, LANE_RECORDS_DIR, PENDING_INDEX_DIR, QUESTION_RECORDS_
24
24
  export type { StoreDeps } from "./store.js";
25
25
  export { DEFAULT_LANE_WATCH_INTERVAL_MS, MAX_LANE_WATCH_INTERVAL_MS, MAX_WATCHED_LANES, MAX_WATCH_OUTPUT_LINES, runLaneWatch, } from "./watch.js";
26
26
  export type { LaneWatchDeps, LaneWatchResult } from "./watch.js";
27
- export { MONITOR_ERROR_EXIT_CODE, MONITOR_ENGINES, MONITOR_MAX_TIMEOUT_MS, MONITOR_TASK_OUTPUT_MAX_BYTES, MONITOR_TRANSCRIPT_MAX_BYTES, MONITOR_UNCOVERED_EXIT_CODE, coveredLaneIds, isMonitorTaskLive, monitorReminderText, parseCanonicalWatchCommand, parseMonitorTranscript, readLiveMonitorEvidence, } from "./monitor.js";
27
+ export { MONITOR_ERROR_EXIT_CODE, MONITOR_ENGINES, MONITOR_MAX_TIMEOUT_MS, MONITOR_TASK_OUTPUT_MAX_BYTES, MONITOR_TRANSCRIPT_MAX_BYTES, MONITOR_UNCOVERED_EXIT_CODE, coveredLaneIds, expiredLaneIds, isMonitorTaskLive, monitorReminderText, parseCanonicalWatchCommand, parseMonitorTranscript, readLiveMonitorEvidence, } from "./monitor.js";
28
28
  export type { LiveMonitorEvidenceOptions, MonitorEngine, MonitorEvidence, MonitorEvidenceReader, MonitorTaskEvidence, } from "./monitor.js";
29
29
  export { IMDS_HOST, IMDS_INSTANCE_ID_URL, IMDS_TIMEOUT_MS, IMDS_TOKEN_URL, defaultReadImdsInstanceId, resolveMachineIdentity, } from "./machine-identity.js";
30
30
  export type { MachineIdentity, MachineIdentityDeps } from "./machine-identity.js";
@@ -14,7 +14,7 @@ export { LANE_STORY_LEDGER_FLAG, buildLaneStatusSnapshot, formatLaneStatusHuman,
14
14
  export { buildOutpostPickupCommand, parseOutpostPickupPayload, } from "./outpost-dispatch.js";
15
15
  export { LANES_STORE_REL, LANE_RECORDS_DIR, PENDING_INDEX_DIR, QUESTION_RECORDS_DIR, appendCappedHistory, appendLaneAttribution, appendLaneSeniorHistory, appendQuestionRouting, createLane, createQuestion, isConflictSidecarName, laneRecordPath, lanesStoreRoot, listLaneIds, expandLocalLaneIdPrefix, LANE_ID_PREFIX_MIN, listQuestionIds, mergeLaneRecords, mergeQuestionRecords, mintLaneId, mintQuestionId, parseLaneRecord, parseQuestionRecord, pendingMarkerPath, questionRecordPath, readAllLanes, readLane, readQuestion, resolveStoreHqRoot, sanitizeHostComponent, tryReadLane, tryReadQuestion, retryUpdateLane, retryUpdateQuestion, syncLaneRecordFromOwner, updateLane, updateQuestion, withLaneHireLocks, } from "./store.js";
16
16
  export { DEFAULT_LANE_WATCH_INTERVAL_MS, MAX_LANE_WATCH_INTERVAL_MS, MAX_WATCHED_LANES, MAX_WATCH_OUTPUT_LINES, runLaneWatch, } from "./watch.js";
17
- export { MONITOR_ERROR_EXIT_CODE, MONITOR_ENGINES, MONITOR_MAX_TIMEOUT_MS, MONITOR_TASK_OUTPUT_MAX_BYTES, MONITOR_TRANSCRIPT_MAX_BYTES, MONITOR_UNCOVERED_EXIT_CODE, coveredLaneIds, isMonitorTaskLive, monitorReminderText, parseCanonicalWatchCommand, parseMonitorTranscript, readLiveMonitorEvidence, } from "./monitor.js";
17
+ export { MONITOR_ERROR_EXIT_CODE, MONITOR_ENGINES, MONITOR_MAX_TIMEOUT_MS, MONITOR_TASK_OUTPUT_MAX_BYTES, MONITOR_TRANSCRIPT_MAX_BYTES, MONITOR_UNCOVERED_EXIT_CODE, coveredLaneIds, expiredLaneIds, isMonitorTaskLive, monitorReminderText, parseCanonicalWatchCommand, parseMonitorTranscript, readLiveMonitorEvidence, } from "./monitor.js";
18
18
  export { IMDS_HOST, IMDS_INSTANCE_ID_URL, IMDS_TIMEOUT_MS, IMDS_TOKEN_URL, defaultReadImdsInstanceId, resolveMachineIdentity, } from "./machine-identity.js";
19
19
  export { PID_LIVENESS_DECISIONS, PROVIDER_COMMAND, PROVIDER_MODEL_FLAG, SPAWN_TERMINAL_REASONS, ANSWERED_QUESTIONS_FILE, appendModelFlag, armLaneWatcher, buildProviderCommand, parseCliModel, resolveLaneModel, defaultProveDetached, isPidRecordAlive, laneRunDir, missingPidProbe, nextEnvelopePath, markSpawnFailure, parsePidRecord, parseProcStat, parseSpawnTerminalReason, probePidRecord, readPidRecord, readProcStarttime, readProcStarttimeDetailed, readSpawnManifest, resumePrompt, envelopeInstruction, spawnLaneWorker, stopLaneProcesses, watcherMainPath, workerEnv, } from "./spawn.js";
20
20
  export { SILENCE_MS, WATCHER_DECISION_EVENTS, WATCHER_OUT_MAX_BYTES, WATCHER_POLL_MS, WATCHER_SIGNAL_KINDS, appendCappedLog, appendWatcherSignal, applyTerminalToLane, classifyLaneExit, clearLaneStalled, isPidAlive, laneIdentityFromRecord, markLaneStalled, notifySlotFreed, parseWatcherSignalKind, readLatestEnvelope, runWatcherLoop, stalledReason, tickWatcher, watcherEventsPath, watcherLastSignalPath, watcherOutLogPath, writeWatcherDecision, } from "./watcher.js";
@@ -40,7 +40,21 @@ export interface LiveMonitorEvidenceOptions {
40
40
  export declare function parseMonitorTranscript(text: string): MonitorTaskEvidence[];
41
41
  /** Return argv only for the exact command form the gate arms. */
42
42
  export declare function parseCanonicalWatchCommand(command: string): string[] | null;
43
+ /**
44
+ * A Monitor covers its lanes only inside the 30-minute cap. `persistent` is
45
+ * deliberately ignored: current Claude Code builds stop every Monitor at 30
46
+ * minutes whatever it was armed with, so the only way a lane stays covered is
47
+ * a Monitor re-armed within the last 30 minutes (feedback 208fd2ea).
48
+ */
43
49
  export declare function isMonitorTaskLive(task: MonitorTaskEvidence, now: Date): boolean;
50
+ /**
51
+ * Lanes that HAD a watch Monitor in this session which has since ended on its
52
+ * own (the 30-minute cap passed, or its output shows it stopped or expired)
53
+ * and was not stopped with TaskStop. These lanes are uncovered because the
54
+ * Monitor needs re-arming, not because none was ever armed; the gate says so.
55
+ * A lane another live Monitor still covers is not included.
56
+ */
57
+ export declare function expiredLaneIds(evidence: MonitorEvidence, now: Date): Set<string>;
44
58
  export declare function coveredLaneIds(evidence: MonitorEvidence, now: Date): Set<string>;
45
59
  export declare function readLiveMonitorEvidence(sessionId: string, options?: LiveMonitorEvidenceOptions): MonitorEvidence;
46
60
  export type MonitorEvidenceReader = (sessionId: string) => MonitorEvidence | Promise<MonitorEvidence>;
@@ -193,7 +193,7 @@ export function parseCanonicalWatchCommand(command) {
193
193
  if (tokens.length < 4)
194
194
  return null;
195
195
  const executable = path.basename(tokens[0]);
196
- if (executable !== "hq" || tokens[1] !== "lanes" || tokens[2] !== "watch") {
196
+ if (executable !== "hq" || (tokens[1] !== "runners" && tokens[1] !== "lanes") || tokens[2] !== "watch") {
197
197
  return null;
198
198
  }
199
199
  const laneIds = tokens.slice(3);
@@ -204,17 +204,55 @@ export function parseCanonicalWatchCommand(command) {
204
204
  function taskOutputIsTerminal(outputText) {
205
205
  return outputText ? TERMINAL_TASK_OUTPUT.test(outputText) : false;
206
206
  }
207
+ function monitorDeadlineMs(task) {
208
+ const startedAt = Date.parse(task.startedAt);
209
+ if (!Number.isFinite(startedAt) || !Number.isFinite(task.timeoutMs) || task.timeoutMs <= 0) {
210
+ return null;
211
+ }
212
+ return startedAt + Math.min(task.timeoutMs, MONITOR_MAX_TIMEOUT_MS);
213
+ }
214
+ /**
215
+ * A Monitor covers its lanes only inside the 30-minute cap. `persistent` is
216
+ * deliberately ignored: current Claude Code builds stop every Monitor at 30
217
+ * minutes whatever it was armed with, so the only way a lane stays covered is
218
+ * a Monitor re-armed within the last 30 minutes (feedback 208fd2ea).
219
+ */
207
220
  export function isMonitorTaskLive(task, now) {
208
221
  if (task.stopped || task.processAlive !== true)
209
222
  return false;
210
223
  if (taskOutputIsTerminal(task.outputText))
211
224
  return false;
212
- const startedAt = Date.parse(task.startedAt);
213
- if (!Number.isFinite(startedAt) || !Number.isFinite(task.timeoutMs) || task.timeoutMs <= 0) {
214
- return false;
225
+ const deadline = monitorDeadlineMs(task);
226
+ return deadline !== null && now.getTime() < deadline;
227
+ }
228
+ /**
229
+ * Lanes that HAD a watch Monitor in this session which has since ended on its
230
+ * own (the 30-minute cap passed, or its output shows it stopped or expired)
231
+ * and was not stopped with TaskStop. These lanes are uncovered because the
232
+ * Monitor needs re-arming, not because none was ever armed; the gate says so.
233
+ * A lane another live Monitor still covers is not included.
234
+ */
235
+ export function expiredLaneIds(evidence, now) {
236
+ const covered = coveredLaneIds(evidence, now);
237
+ const expired = new Set();
238
+ for (const task of evidence.tasks) {
239
+ if (task.stopped)
240
+ continue;
241
+ const laneIds = parseCanonicalWatchCommand(task.command);
242
+ if (!laneIds)
243
+ continue;
244
+ const deadline = monitorDeadlineMs(task);
245
+ if (deadline === null)
246
+ continue;
247
+ const ended = now.getTime() >= deadline || taskOutputIsTerminal(task.outputText);
248
+ if (!ended)
249
+ continue;
250
+ for (const laneId of laneIds) {
251
+ if (!covered.has(laneId))
252
+ expired.add(laneId);
253
+ }
215
254
  }
216
- const deadline = startedAt + Math.min(task.timeoutMs, MONITOR_MAX_TIMEOUT_MS);
217
- return now.getTime() < deadline;
255
+ return expired;
218
256
  }
219
257
  export function coveredLaneIds(evidence, now) {
220
258
  const covered = new Set();
@@ -350,7 +388,7 @@ function defaultProcessCommands() {
350
388
  const WATCH_RUNTIME_EXECUTABLES = ["bun", "deno", "node", "nodejs", "ts-node", "tsx"];
351
389
  // The hq executable path may contain spaces (the desktop toolchain installs
352
390
  // under "~/Library/Application Support/Indigo HQ/..."), so the ps line cannot
353
- // be split on whitespace to find it. Match the fixed "lanes watch <ids>" suffix
391
+ // be split on whitespace to find it. Match the fixed "<group> watch <ids>" suffix
354
392
  // on the raw line, then validate whatever precedes it as an hq invocation.
355
393
  // A path form (absolute or ./, ../) is required so an unrelated leading
356
394
  // command such as "vim /tmp/hq" is not absorbed into the path.
@@ -388,7 +426,10 @@ function processHasExactCommand(processCommands, command) {
388
426
  const laneIds = parseCanonicalWatchCommand(command);
389
427
  if (!laneIds)
390
428
  return false;
391
- const expectedSuffix = ` lanes watch ${laneIds.join(" ")}`;
429
+ // Match the group name the Monitor used: `hq runners watch` or the
430
+ // `hq lanes watch` alias produce different process lines.
431
+ const groupToken = command.trim().split(/\s+/u)[1];
432
+ const expectedSuffix = ` ${groupToken} watch ${laneIds.join(" ")}`;
392
433
  return processCommands.some((rawLine) => {
393
434
  const line = rawLine.trim().replace(/\s+/gu, " ");
394
435
  if (!line.endsWith(expectedSuffix))
@@ -447,8 +488,8 @@ export function readLiveMonitorEvidence(sessionId, options = {}) {
447
488
  export function monitorReminderText() {
448
489
  return [
449
490
  "For active Claude senior lanes, arm one live Claude Code Monitor task per uncovered lane:",
450
- 'Monitor(command="hq lanes watch <lane-id>...", timeout_ms=1800000, persistent=true)',
451
- "Use `hq lanes monitor-check --session <id>` to verify coverage. `persistent=true` is requested where the installed Monitor tool honors it; Claude Code caps Monitor tasks at 30 minutes, so re-arm after expiry.",
491
+ 'Monitor(command="hq lanes watch <lane-id>...", timeout_ms=1800000)',
492
+ "Claude Code stops every Monitor after 30 minutes, so a lane stays covered only while a Monitor armed in the last 30 minutes watches it. Re-arm the same call when `hq lanes monitor-check --session <id>` reports the lane as expired.",
452
493
  "The caller must pass `--engine codex` or `--engine grok` (or set HQ_LANE_ENGINE; deprecated alias HQ_CONDUCT_ENGINE) for sessions whose engine has no Claude Monitor tool; those engines are never required to provide one.",
453
494
  ].join("\n");
454
495
  }
@@ -25,6 +25,8 @@ export interface OutpostDispatchResult {
25
25
  exitCode: number | null;
26
26
  stdout: string;
27
27
  stderr: string;
28
+ /** True when the Outpost exec transport clipped stdout/stderr at its inline output limit. */
29
+ truncated?: boolean;
28
30
  }
29
31
  export interface OutpostLaneCommand {
30
32
  action: "message" | "resume" | "stop" | "show" | "logs" | "grant" | "grant-target" | "reparent-target" | "approve-target" | "repair-company-target" | "set-target" | "blocked-escalation-target";
@@ -81,6 +83,7 @@ export interface OutpostExecPort {
81
83
  exitCode?: number | null;
82
84
  stdout?: string;
83
85
  stderr?: string;
86
+ truncated?: boolean;
84
87
  }>;
85
88
  }
86
89
  export declare function parseOutpostPickupPayload(raw: unknown): OutpostPickupPayload;
@@ -284,6 +284,7 @@ export async function dispatchOutpostPickup(port, input) {
284
284
  exitCode: result.exitCode ?? null,
285
285
  stdout: result.stdout ?? "",
286
286
  stderr: result.stderr ?? "",
287
+ ...(result.truncated === true ? { truncated: true } : {}),
287
288
  };
288
289
  }
289
290
  catch (err) {
@@ -67,7 +67,7 @@ export declare function tryReadQuestion(hqRoot: string, questionId: string, deps
67
67
  export declare function readQuestion(hqRoot: string, questionId: string, deps?: StoreDeps): QuestionRecord;
68
68
  /** Semver precedence includes prerelease identifiers (for example, rc.2 > rc.1). */
69
69
  export declare function isLaneStoreVersionNewer(storedVersion: string, runningVersion: string): boolean;
70
- export declare const LANE_STORE_UPGRADE_COMMAND = "npm install -g @indigoai-us/hq-cli@latest";
70
+ export declare const LANE_STORE_UPGRADE_COMMAND: string;
71
71
  export declare function createLane(hqRoot: string, init: Omit<LaneRecord, "schema_version" | "lane_id" | "version" | "created_at" | "updated_at"> & Partial<Pick<LaneRecord, "schema_version" | "lane_id" | "version" | "created_at" | "updated_at">>, deps?: StoreDeps): LaneRecord;
72
72
  /** Hierarchy lock: separate from record writes so callers can CAS-write while holding it. */
73
73
  export declare function withLaneHireLocks<T>(hqRoot: string, laneIds: readonly string[], fn: () => T, deps?: StoreDeps): T;
@@ -22,6 +22,7 @@ import { laneStories } from "./stories.js";
22
22
  import { parseLaneOutcomeShape } from "./outcome.js";
23
23
  import { laneStoryLedgerEnabled, syncLaneToProjectStoryLedger, validateProjectStories, } from "./story-ledger.js";
24
24
  import { liveOwnerMaxMs, reclaimStaleLock } from "./stale-lock.js";
25
+ import { HQ_CLI_NPM_UPDATE_COMMAND } from "../../utils/npm-install-flags.js";
25
26
  /** Signal identity is company-scoped and survives terminal lane states. */
26
27
  export function findLaneBySignal(company, signalId, hqRoot = resolveStoreHqRoot()) {
27
28
  return readAllLanes(hqRoot).find(lane => lane.company?.slug === company && lane.signal?.signal_id === signalId);
@@ -1671,7 +1672,7 @@ export function isLaneStoreVersionNewer(storedVersion, runningVersion) {
1671
1672
  return semver.gt(storedVersion, runningVersion);
1672
1673
  }
1673
1674
  const OLDER_LANE_STORE_WRITE_OVERRIDE = "HQ_LANES_ALLOW_OLDER_WRITE";
1674
- export const LANE_STORE_UPGRADE_COMMAND = "npm install -g @indigoai-us/hq-cli@latest";
1675
+ export const LANE_STORE_UPGRADE_COMMAND = HQ_CLI_NPM_UPDATE_COMMAND;
1675
1676
  const warnedBackgroundWriterLaneIds = new Set();
1676
1677
  function assertLaneStoreWriteAllowed(lane, laneId, writer) {
1677
1678
  const storedVersion = lane.written_by_version;
@@ -30,7 +30,13 @@ export function createWorkSessionDeliverer(opts) {
30
30
  clientOperationId: op.clientOperationId,
31
31
  operationId: op.operationId,
32
32
  digest: op.digest,
33
- contextStatus: op.projectId && op.taskId ? "bound" : op.projectId ? "needs_task" : "unresolved",
33
+ // Company-bound sessions with no project are needs_project, not unresolved.
34
+ // Recomputing from ids only used to collapse that case (feedback_802ad6cf).
35
+ contextStatus: op.projectId && op.taskId
36
+ ? "bound"
37
+ : op.projectId
38
+ ? "needs_task"
39
+ : "needs_project",
34
40
  };
35
41
  if (op.projectId)
36
42
  body.projectId = op.projectId;
@@ -71,6 +71,9 @@ export interface BackfillHeldResult {
71
71
  /**
72
72
  * A recovered company binding was persisted locally (would-recover in
73
73
  * dry-run). A reconcile attempt that ends in needs_company is unresolved.
74
+ * It means "released now or on the daemon's next held retry": a slug-only
75
+ * binding counts, and flush keeps holding it until that retry resolves its
76
+ * companyUid.
74
77
  */
75
78
  reconciled: number;
76
79
  /** Reconcile ran but resolver found no company. */
@@ -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;