@indigoai-us/hq-cli 5.345.244 → 5.345.246

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 (116) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/dist/command-catalog.generated.d.ts +93 -6
  3. package/dist/command-catalog.generated.js +114 -6
  4. package/dist/commands/bot.js +1 -1
  5. package/dist/commands/core-checkpoint-native.d.ts +5 -1
  6. package/dist/commands/core-checkpoint-native.js +13 -5
  7. package/dist/commands/deploy-comments.js +139 -0
  8. package/dist/commands/deploy-list.d.ts +5 -0
  9. package/dist/commands/deploy-list.js +8 -0
  10. package/dist/commands/dm.d.ts +4 -1
  11. package/dist/commands/dm.js +11 -2
  12. package/dist/commands/files.d.ts +11 -2
  13. package/dist/commands/files.js +48 -3
  14. package/dist/commands/lanes-loop.js +4 -1
  15. package/dist/commands/lanes.js +16 -5
  16. package/dist/commands/mesh.d.ts +2 -0
  17. package/dist/commands/mesh.js +26 -6
  18. package/dist/commands/reindex.js +2 -1
  19. package/dist/commands/rescue.d.ts +22 -1
  20. package/dist/commands/rescue.js +56 -9
  21. package/dist/commands/sources.d.ts +1 -1
  22. package/dist/commands/sources.js +1 -1
  23. package/dist/commands/storage.d.ts +15 -2
  24. package/dist/commands/storage.js +74 -7
  25. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +2033 -1829
  26. package/dist/hq-cloud-sync-runner/package.json +1 -1
  27. package/dist/lib/agent-kit/mcp/tools.js +22 -0
  28. package/dist/lib/bot/jobs/hot-signal-sync.js +4 -1
  29. package/dist/lib/daemon/fleet-members-cache.d.ts +55 -0
  30. package/dist/lib/daemon/fleet-members-cache.js +266 -0
  31. package/dist/lib/daemon/handoff.d.ts +4 -0
  32. package/dist/lib/daemon/handoff.js +2 -1
  33. package/dist/lib/daemon/hook-requests.d.ts +2 -1
  34. package/dist/lib/daemon/hook-requests.js +19 -2
  35. package/dist/lib/daemon/install.d.ts +9 -1
  36. package/dist/lib/daemon/install.js +11 -2
  37. package/dist/lib/daemon/ops/policy.d.ts +23 -3
  38. package/dist/lib/daemon/ops/policy.js +62 -15
  39. package/dist/lib/daemon/run.js +12 -0
  40. package/dist/lib/daemon/server.d.ts +5 -0
  41. package/dist/lib/daemon/server.js +1 -1
  42. package/dist/lib/daemon/supervisor.d.ts +6 -0
  43. package/dist/lib/daemon/supervisor.js +31 -2
  44. package/dist/lib/doctor/checks/sync-runtime.js +8 -1
  45. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  46. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  47. package/dist/lib/hook-engine/coverage.d.ts +68 -0
  48. package/dist/lib/hook-engine/coverage.js +163 -0
  49. package/dist/lib/hook-engine/native-precompact-compatibility.json +1 -0
  50. package/dist/lib/hot-channels/signals-pass.d.ts +52 -2
  51. package/dist/lib/hot-channels/signals-pass.js +65 -3
  52. package/dist/lib/install/claude-targets.d.ts +6 -0
  53. package/dist/lib/install/claude-targets.js +9 -1
  54. package/dist/lib/lanes/reconcile-result.d.ts +1 -1
  55. package/dist/lib/lanes/reconcile.js +19 -4
  56. package/dist/lib/lanes/remote-control-lane.d.ts +6 -0
  57. package/dist/lib/lanes/remote-control-lane.js +10 -1
  58. package/dist/lib/lanes/spawn.d.ts +2 -0
  59. package/dist/lib/lanes/spawn.js +19 -3
  60. package/dist/lib/lanes/worker-env-scrub.d.ts +48 -0
  61. package/dist/lib/lanes/worker-env-scrub.js +146 -0
  62. package/dist/lib/lanes/worker-process.js +4 -1
  63. package/dist/lib/mesh/client.js +5 -1
  64. package/dist/lib/mesh/live/daemon/doctor.d.ts +9 -0
  65. package/dist/lib/mesh/live/daemon/doctor.js +51 -6
  66. package/dist/lib/mesh/live/daemon/install.d.ts +39 -0
  67. package/dist/lib/mesh/live/daemon/install.js +70 -0
  68. package/dist/lib/mesh/live/daemon/outbox-company.d.ts +47 -0
  69. package/dist/lib/mesh/live/daemon/outbox-company.js +77 -0
  70. package/dist/lib/mesh/live/daemon/run.d.ts +2 -0
  71. package/dist/lib/mesh/live/daemon/run.js +48 -3
  72. package/dist/lib/mesh/live/daemon/state.d.ts +5 -0
  73. package/dist/lib/mesh/live/daemon/system-unit.d.ts +21 -0
  74. package/dist/lib/mesh/live/daemon/system-unit.js +80 -0
  75. package/dist/lib/mesh/live/daemon/transcript-watch.d.ts +4 -1
  76. package/dist/lib/mesh/live/daemon/transcript-watch.js +42 -38
  77. package/dist/lib/mesh/live/direct-drain.js +3 -1
  78. package/dist/lib/mesh/live/emit.js +4 -2
  79. package/dist/lib/mesh/live/flush.d.ts +61 -0
  80. package/dist/lib/mesh/live/flush.js +434 -114
  81. package/dist/lib/mesh/live/paths.d.ts +10 -0
  82. package/dist/lib/mesh/live/paths.js +14 -0
  83. package/dist/lib/mesh/live/reporting-privacy.d.ts +41 -1
  84. package/dist/lib/mesh/live/reporting-privacy.js +81 -7
  85. package/dist/lib/mesh/live/spool.d.ts +171 -17
  86. package/dist/lib/mesh/live/spool.js +777 -62
  87. package/dist/lib/signals/engine.d.ts +82 -2
  88. package/dist/lib/signals/engine.js +389 -53
  89. package/dist/lib/signals/steps/extract.js +5 -0
  90. package/dist/lib/sync-core/engine-holds.d.ts +17 -1
  91. package/dist/lib/sync-core/engine-holds.js +73 -3
  92. package/dist/lib/sync-core/reconcile.js +10 -2
  93. package/dist/lib/work-context/organize.d.ts +22 -4
  94. package/dist/lib/work-context/organize.js +50 -21
  95. package/dist/lib/work-context/paths.d.ts +6 -0
  96. package/dist/lib/work-context/paths.js +9 -0
  97. package/dist/lib/work-context/reconcile.d.ts +1 -1
  98. package/dist/lib/work-context/reconcile.js +1 -1
  99. package/dist/startup-registration.d.ts +14 -0
  100. package/dist/startup-registration.js +26 -0
  101. package/dist/utils/cli-telemetry.d.ts +6 -0
  102. package/dist/utils/cli-telemetry.js +154 -9
  103. package/dist/utils/github-tag-fallback.d.ts +7 -2
  104. package/dist/utils/github-tag-fallback.js +17 -8
  105. package/dist/utils/hq-core-source.d.ts +31 -0
  106. package/dist/utils/hq-core-source.js +144 -0
  107. package/dist/utils/interactive-caller.d.ts +6 -0
  108. package/dist/utils/interactive-caller.js +8 -0
  109. package/dist/utils/shipped-codex-hooks.d.ts +6 -4
  110. package/dist/utils/shipped-codex-hooks.js +22 -10
  111. package/dist/utils/vault-api.js +1 -0
  112. package/dist/utils/version-report.d.ts +3 -1
  113. package/dist/utils/version-report.js +13 -5
  114. package/docs/anywhere-runtime.md +2 -2
  115. package/package.json +8 -8
  116. package/scripts/check-function-manifest.mjs +99 -18
@@ -6,6 +6,13 @@
6
6
  * Records (run record contract v2): workspace/signals/runs/{date}/{company}.json
7
7
  * is the source of truth for one company's day; summary.json in the same
8
8
  * folder is read-modify-written per company and never drops other companies.
9
+ * Once that record holds a job that finished complete (jobRanAt, status
10
+ * complete), a brief, chat or manual run leaves it in place and writes
11
+ * sidecars/{company}/manual-{HHMMSS}.json in the same date folder; after a
12
+ * partial or failed job such a run still replaces the record and carries
13
+ * jobRanAt forward. An incremental pass never replaces a record that has
14
+ * jobRanAt: every pass writes the one sidecars/{company}/incremental.json.
15
+ * sidecars/{company}/alerted-runs.json lists the runs the owner was alerted for.
9
16
  * Each company runs under workspace/signals/runs/{date}/{company}.lock.
10
17
  */
11
18
  import { spawnSync } from "node:child_process";
@@ -21,7 +28,7 @@ import { gardenStep } from "./steps/garden.js";
21
28
  import { adaptersStep } from "./steps/adapters.js";
22
29
  import { extractStep, redoItemChannel } from "./steps/extract.js";
23
30
  import { uploadStep } from "./steps/upload.js";
24
- import { SIGNALS_RUN_ALERT_ADAPTER, raiseSignalsRunAlerts, resolveSignedInAlertPerson, } from "./failure-alert.js";
31
+ import { SIGNALS_RUN_ALERT_ADAPTER, isSignalsRunFailure, raiseSignalsRunAlerts, resolveSignedInAlertPerson, } from "./failure-alert.js";
25
32
  import { signalsAlertKey, signalsAlertStatePath } from "../hot-channels/alert.js";
26
33
  import { readSignalsPassDetail } from "./steps/types.js";
27
34
  import { canonicalHostIdHere } from "../lanes/run-size.js";
@@ -147,6 +154,126 @@ export { localDate };
147
154
  export function runRecordRel(date, company) {
148
155
  return `workspace/signals/runs/${date}/${company}.json`;
149
156
  }
157
+ /** Local HHMMSS stamp for a sidecar record. Seconds keep two runs in the same minute apart. */
158
+ export function manualRunStamp(startedAt) {
159
+ const p = (n) => String(n).padStart(2, "0");
160
+ return `${p(startedAt.getHours())}${p(startedAt.getMinutes())}${p(startedAt.getSeconds())}`;
161
+ }
162
+ /**
163
+ * Folder for the records a company's runs write beside its day record. It is a
164
+ * subfolder of the day's runs folder, one per company: the Daily Brief gate
165
+ * lists `runs/<date>/*.json` and takes every file name there as a company, so
166
+ * no record other than a day record may sit at that level. A folder per
167
+ * company also keeps a slug with a dot in it away from another company's files.
168
+ * Windows drops the dots at the end of a folder name, so `acme.` would share
169
+ * `acme`'s folder there: each dot at the end is written as `%2E`, which no
170
+ * slug can contain.
171
+ */
172
+ export function sidecarDirRel(date, company) {
173
+ const folder = company.replace(/\.+$/, (dots) => "%2E".repeat(dots.length));
174
+ return `workspace/signals/runs/${date}/sidecars/${folder}`;
175
+ }
176
+ /**
177
+ * Sidecar for a non-job run on a day whose job record must stay put. `n` (2
178
+ * and up) tells apart runs that started in the same second.
179
+ */
180
+ export function manualRunRecordRel(date, company, startedAt, n) {
181
+ const suffix = n === undefined ? "" : `-${n}`;
182
+ return `${sidecarDirRel(date, company)}/manual-${manualRunStamp(startedAt)}${suffix}.json`;
183
+ }
184
+ /**
185
+ * The one record every incremental pass writes on a day whose job record must
186
+ * stay put. Each pass overwrites it: a meeting runs a pass every few seconds,
187
+ * so a file per pass would grow without bound.
188
+ */
189
+ export function incrementalRunRecordRel(date, company) {
190
+ return `${sidecarDirRel(date, company)}/incremental.json`;
191
+ }
192
+ /**
193
+ * The runs of the day the owner was alerted for, one key per run. The
194
+ * stopped-run check reads it so each stopped run is alerted once, whatever
195
+ * other run was alerted before or after it.
196
+ */
197
+ export function alertedRunsRel(date, company) {
198
+ return `${sidecarDirRel(date, company)}/alerted-runs.json`;
199
+ }
200
+ /**
201
+ * One run's key in the alerted-runs file: its record's file name and its
202
+ * start. The file name tells a manual run from a job that started in the same
203
+ * instant; the start tells apart the runs that wrote `{company}.json` in turn.
204
+ */
205
+ function alertedRunKey(recordRel, startedAt) {
206
+ return `${path.posix.basename(recordRel)}|${startedAt}`;
207
+ }
208
+ function readAlertedRuns(hqRoot, date, company) {
209
+ const state = readJson(hqRoot, alertedRunsRel(date, company));
210
+ if (!state || typeof state !== "object" || !Array.isArray(state.runs))
211
+ return [];
212
+ return state.runs.filter((k) => typeof k === "string");
213
+ }
214
+ function writeAlertedRuns(hqRoot, date, company, runs) {
215
+ guardedWrite(hqRoot, alertedRunsRel(date, company), `${JSON.stringify({ v: 1, runs }, null, 2)}\n`, { company });
216
+ }
217
+ /**
218
+ * Runs the owner was alerted for in this process whose key could not be
219
+ * written to the alerted-runs file. The stopped-run check reads it beside the
220
+ * file, so a file that cannot be written does not send the same DM again for
221
+ * as long as this process lives (the bot is one long-lived process).
222
+ */
223
+ const alertedRunsNotListed = new Set();
224
+ function notListedKey(hqRoot, date, company, runKey) {
225
+ return [path.resolve(hqRoot), date, company, runKey].join("\n");
226
+ }
227
+ /**
228
+ * Record that the owner was alerted for this run. Never throws: the DM is
229
+ * already out, so a file that cannot be written is logged, the run is kept in
230
+ * memory for this process, and false is returned.
231
+ */
232
+ function markRunAlerted(hqRoot, date, company, recordRel, startedAt, log) {
233
+ const key = alertedRunKey(recordRel, startedAt);
234
+ try {
235
+ const runs = readAlertedRuns(hqRoot, date, company);
236
+ if (!runs.includes(key))
237
+ writeAlertedRuns(hqRoot, date, company, [...runs, key]);
238
+ return true;
239
+ }
240
+ catch (err) {
241
+ alertedRunsNotListed.add(notListedKey(hqRoot, date, company, key));
242
+ try {
243
+ log(`signals alert for ${company} was sent but not recorded in ${alertedRunsRel(date, company)}: ${err instanceof Error ? err.message : String(err)}`);
244
+ }
245
+ catch {
246
+ // a log that throws must not hide that the DM went out
247
+ }
248
+ return false;
249
+ }
250
+ }
251
+ /** True when the alerted-runs file can be written: writes back what it holds. Never throws. */
252
+ function alertedRunsWritable(hqRoot, date, company) {
253
+ try {
254
+ writeAlertedRuns(hqRoot, date, company, readAlertedRuns(hqRoot, date, company));
255
+ return true;
256
+ }
257
+ catch {
258
+ return false;
259
+ }
260
+ }
261
+ const MANUAL_SIDECAR_RE = /^manual-\d{6}(?:-\d+)?\.json$/;
262
+ /** The company's manual-run sidecar records for the day, by file name. */
263
+ export function manualRunRecordRels(hqRoot, date, company) {
264
+ const dir = sidecarDirRel(date, company);
265
+ let names;
266
+ try {
267
+ names = fs.readdirSync(path.join(hqRoot, dir));
268
+ }
269
+ catch {
270
+ return [];
271
+ }
272
+ return names
273
+ .filter((n) => MANUAL_SIDECAR_RE.test(n))
274
+ .sort()
275
+ .map((n) => `${dir}/${n}`);
276
+ }
150
277
  export function summaryRel(date) {
151
278
  return `workspace/signals/runs/${date}/summary.json`;
152
279
  }
@@ -307,32 +434,114 @@ function summaryEntry(r) {
307
434
  }
308
435
  function buildSummary(date, trigger, entries, finishedAt, dryRun) {
309
436
  const totals = { itemsIn: 0, itemsOut: 0, estimatedSpendUsd: 0 };
437
+ const manualTotals = { itemsIn: 0, itemsOut: 0, estimatedSpendUsd: 0 };
310
438
  for (const e of entries) {
311
439
  totals.itemsIn += e.itemsIn;
312
440
  totals.itemsOut += e.itemsOut;
313
441
  totals.estimatedSpendUsd += e.estimatedSpendUsd;
314
442
  }
315
- const statuses = entries.map((e) => e.status);
316
- const status = dryRun
317
- ? "dry-run"
318
- : statuses.includes("failed")
319
- ? "failed"
320
- : statuses.includes("partial")
321
- ? "partial"
322
- : statuses.includes("running")
323
- ? "running"
324
- : statuses.length > 0 && statuses.every((s) => s === "skipped")
325
- ? "skipped"
326
- : "complete";
327
- return { schemaVersion: RUN_RECORD_SCHEMA_VERSION, date, trigger, companies: entries, totals, status, finishedAt };
328
- }
329
- /** Replaces this company's entry in summary.json, keeping every other company's. */
330
- function updateSummaryFile(hqRoot, date, record, finishedAt) {
443
+ // A run beside a job's record is counted once, here, and never in its company's row.
444
+ const beside = entries.flatMap((e) => [...(e.manualRuns ?? []), ...(e.incrementalRun ? [e.incrementalRun] : [])]);
445
+ for (const r of beside) {
446
+ manualTotals.itemsIn += r.itemsIn;
447
+ manualTotals.itemsOut += r.itemsOut;
448
+ manualTotals.estimatedSpendUsd += r.estimatedSpendUsd;
449
+ }
450
+ totals.itemsIn += manualTotals.itemsIn;
451
+ totals.itemsOut += manualTotals.itemsOut;
452
+ totals.estimatedSpendUsd += manualTotals.estimatedSpendUsd;
453
+ const status = dryRun ? "dry-run" : rollupStatus(entries.map((e) => e.status));
454
+ return {
455
+ schemaVersion: RUN_RECORD_SCHEMA_VERSION,
456
+ date,
457
+ trigger,
458
+ companies: entries,
459
+ totals,
460
+ status,
461
+ ...(beside.length > 0 ? { manualStatus: rollupStatus(beside.map((r) => r.status)), manualTotals } : {}),
462
+ finishedAt,
463
+ };
464
+ }
465
+ function rollupStatus(statuses) {
466
+ return statuses.includes("failed")
467
+ ? "failed"
468
+ : statuses.includes("partial")
469
+ ? "partial"
470
+ : statuses.includes("running")
471
+ ? "running"
472
+ : statuses.length > 0 && statuses.every((s) => s === "skipped")
473
+ ? "skipped"
474
+ : "complete";
475
+ }
476
+ function isManualRunRef(v) {
477
+ if (typeof v !== "object" || v === null)
478
+ return false;
479
+ const r = v;
480
+ return (typeof r.path === "string" &&
481
+ typeof r.status === "string" &&
482
+ typeof r.startedAt === "string" &&
483
+ Number.isFinite(r.itemsIn) &&
484
+ Number.isFinite(r.itemsOut) &&
485
+ Number.isFinite(r.estimatedSpendUsd));
486
+ }
487
+ function isSummaryEntry(e) {
488
+ return typeof e === "object" && e !== null && typeof e.company === "string";
489
+ }
490
+ /**
491
+ * Replaces this company's entry in summary.json, keeping every other company's.
492
+ * When `beside` is set, the record was written beside a finished job's record:
493
+ * the company's row is the job's, and the run is listed under manualRuns (or
494
+ * added into incrementalRun). The day's trigger and finishedAt stay the job's.
495
+ */
496
+ function updateSummaryFile(hqRoot, date, record, finishedAt, beside) {
331
497
  withSummaryLock(hqRoot, date, () => {
332
498
  const existing = readJson(hqRoot, summaryRel(date));
333
- const others = (Array.isArray(existing?.companies) ? existing.companies : []).filter((e) => typeof e === "object" && e !== null && typeof e.company === "string" && e.company !== record.company);
334
- const entries = [...others, summaryEntry(record)].sort((a, b) => a.company.localeCompare(b.company));
335
- const summary = buildSummary(date, record.trigger, entries, finishedAt, false);
499
+ const companies = Array.isArray(existing?.companies) ? existing.companies : [];
500
+ const others = companies.filter((e) => isSummaryEntry(e) && e.company !== record.company);
501
+ const current = companies.find((e) => isSummaryEntry(e) && e.company === record.company);
502
+ let manualRuns = (Array.isArray(current?.manualRuns) ? current.manualRuns : []).filter(isManualRunRef);
503
+ let incrementalRun = isManualRunRef(current?.incrementalRun) ? current.incrementalRun : undefined;
504
+ let row = summaryEntry(record);
505
+ let trigger = record.trigger;
506
+ let summaryFinished = finishedAt;
507
+ if (beside) {
508
+ const ref = {
509
+ path: beside.path,
510
+ status: record.status,
511
+ startedAt: record.startedAt,
512
+ finishedAt: record.finishedAt,
513
+ itemsIn: row.itemsIn,
514
+ itemsOut: row.itemsOut,
515
+ estimatedSpendUsd: row.estimatedSpendUsd,
516
+ };
517
+ if (beside.incremental) {
518
+ // Every pass overwrites the one record file, so the passes' items and
519
+ // spend are added up here; each pass reaches this line once.
520
+ const passes = incrementalRun && Number.isInteger(incrementalRun.passes) ? (incrementalRun.passes ?? 0) : 0;
521
+ incrementalRun = {
522
+ ...ref,
523
+ itemsIn: ref.itemsIn + (incrementalRun?.itemsIn ?? 0),
524
+ itemsOut: ref.itemsOut + (incrementalRun?.itemsOut ?? 0),
525
+ estimatedSpendUsd: ref.estimatedSpendUsd + (incrementalRun?.estimatedSpendUsd ?? 0),
526
+ passes: passes + 1,
527
+ };
528
+ }
529
+ else {
530
+ manualRuns = [...manualRuns.filter((r) => r.path !== ref.path), ref];
531
+ }
532
+ row = beside.jobEntry;
533
+ trigger = existing?.trigger ?? row.trigger;
534
+ if (typeof existing?.finishedAt === "string")
535
+ summaryFinished = existing.finishedAt;
536
+ }
537
+ // A job that replaces the day record (--force) keeps the list: those record files are still there.
538
+ const entry = {
539
+ ...row,
540
+ ...(manualRuns.length > 0 ? { manualRuns, lastManualRun: manualRuns[manualRuns.length - 1] } : {}),
541
+ ...(incrementalRun ? { incrementalRun } : {}),
542
+ };
543
+ const entries = [...others, entry].sort((a, b) => a.company.localeCompare(b.company));
544
+ const summary = buildSummary(date, trigger, entries, summaryFinished, false);
336
545
  guardedWrite(hqRoot, summaryRel(date), `${JSON.stringify(summary, null, 2)}\n`);
337
546
  });
338
547
  }
@@ -386,9 +595,15 @@ export async function runSignals(opts) {
386
595
  if (opts.incremental)
387
596
  plan = ["extract"];
388
597
  const records = [];
598
+ /** Where each pushed record was written, for the alerted-runs file. */
599
+ const recordRels = new Map();
389
600
  const locked = [];
390
601
  for (const company of companies) {
391
- const rel = runRecordRel(date, company);
602
+ let rel = runRecordRel(date, company);
603
+ let keepJob = null;
604
+ const summaryUpdate = (finishedAt) => {
605
+ updateSummaryFile(hqRoot, date, record, finishedAt, keepJob ? { jobEntry: keepJob.jobEntry, path: rel, incremental: opts.incremental === true } : undefined);
606
+ };
392
607
  // One company scope per run: every write for this company is held to
393
608
  // companies/{company}/ (plus the workspace and personal signals roots), and
394
609
  // a link that resolves into another company's folder is refused.
@@ -451,7 +666,7 @@ export async function runSignals(opts) {
451
666
  }
452
667
  stampRunPlacement(record, opts.placement ?? {}, opts.incremental === true);
453
668
  persist();
454
- updateSummaryFile(hqRoot, date, record, record.finishedAt ?? now().toISOString());
669
+ summaryUpdate(record.finishedAt ?? now().toISOString());
455
670
  };
456
671
  try {
457
672
  if (takeover) {
@@ -479,7 +694,37 @@ export async function runSignals(opts) {
479
694
  records.push(marked);
480
695
  continue;
481
696
  }
482
- record.jobRanAt = priorJobRanAt;
697
+ // A day record that holds a job which finished complete is kept: a
698
+ // non-job run writes beside it. A job that ended partial or failed left
699
+ // work undone, and the Daily Brief gate reads only the day record, so a
700
+ // non-job run (brief, chat, manual) replaces that record and carries
701
+ // jobRanAt forward; the already-ran guard reads jobRanAt there. An
702
+ // incremental pass (any trigger) is never the day's run, so it never
703
+ // replaces a record that has jobRanAt.
704
+ const keepDayRecord = opts.incremental === true || (trigger !== "job" && prior?.status === "complete");
705
+ if (!dryRun && prior && priorJobRanAt && keepDayRecord) {
706
+ if (opts.incremental) {
707
+ // One fixed file, overwritten by every pass. The meeting rider runs
708
+ // a pass every few seconds; a file per pass would never stop growing.
709
+ rel = incrementalRunRecordRel(date, company);
710
+ }
711
+ else {
712
+ const parsed = new Date(record.startedAt);
713
+ const started = Number.isNaN(parsed.getTime()) ? now() : parsed;
714
+ // The company lock is held, so no other run is choosing a name for
715
+ // this company now. A name that exists is never reused.
716
+ let sidecar = manualRunRecordRel(date, company, started);
717
+ for (let n = 2; fs.existsSync(path.join(hqRoot, sidecar)); n += 1) {
718
+ sidecar = manualRunRecordRel(date, company, started, n);
719
+ }
720
+ rel = sidecar;
721
+ }
722
+ const jobRecord = Array.isArray(prior.steps) ? prior : { ...prior, steps: [] };
723
+ keepJob = { jobEntry: summaryEntry(jobRecord) };
724
+ }
725
+ else {
726
+ record.jobRanAt = priorJobRanAt;
727
+ }
483
728
  // 3. Mark the run as running before any step.
484
729
  persist();
485
730
  let prefsOff;
@@ -498,20 +743,23 @@ export async function runSignals(opts) {
498
743
  if (!dryRun) {
499
744
  stampRunPlacement(record, opts.placement ?? {}, opts.incremental === true);
500
745
  persist();
501
- updateSummaryFile(hqRoot, date, record, record.finishedAt ?? now().toISOString());
746
+ summaryUpdate(record.finishedAt ?? now().toISOString());
502
747
  }
748
+ recordRels.set(record, rel);
503
749
  records.push(record);
504
750
  continue;
505
751
  }
506
752
  if (prefsOff) {
507
753
  record.skipReason = "prefs-off";
508
754
  finish();
755
+ recordRels.set(record, rel);
509
756
  records.push(record);
510
757
  continue;
511
758
  }
512
759
  if (plan.length === 0) {
513
760
  record.skipReason = lateStart ? "late-start" : "nothing-to-run";
514
761
  finish();
762
+ recordRels.set(record, rel);
515
763
  records.push(record);
516
764
  continue;
517
765
  }
@@ -594,6 +842,7 @@ export async function runSignals(opts) {
594
842
  }
595
843
  // 5. Final record and summary entry.
596
844
  finish();
845
+ recordRels.set(record, rel);
597
846
  records.push(record);
598
847
  }
599
848
  catch (err) {
@@ -611,11 +860,16 @@ export async function runSignals(opts) {
611
860
  if (!dryRun)
612
861
  stampRunPlacement(record, opts.placement ?? {}, opts.incremental === true);
613
862
  persist();
863
+ // The job's row would otherwise hide this failure: summary.json would
864
+ // show only the job, complete.
865
+ if (!dryRun && keepJob)
866
+ summaryUpdate(record.finishedAt);
614
867
  }
615
868
  catch {
616
869
  // the failure is already reported on stderr below
617
870
  }
618
871
  process.stderr.write(`hq signals: ${company}: ${msg}\n`);
872
+ recordRels.set(record, rel);
619
873
  records.push(record);
620
874
  }
621
875
  finally {
@@ -626,6 +880,18 @@ export async function runSignals(opts) {
626
880
  if (!dryRun && opts.signalsAlert) {
627
881
  // The signals-failure alert (US-018). Already-ran and dry-run records are never judged.
628
882
  const alerts = await raiseSignalsRunAlerts({ hqRoot, records, senders: opts.signalsAlert, now });
883
+ // A run alerted here is not alerted again by the stopped-run check. A
884
+ // sender that keeps no record (the terminal) leaves the owner DM to it.
885
+ if (opts.signalsAlert.recordsDelivery !== false) {
886
+ for (const record of records) {
887
+ const recordRel = recordRels.get(record);
888
+ if (recordRel === undefined || (alerts[record.company]?.sent.length ?? 0) === 0 || !isSignalsRunFailure(record))
889
+ continue;
890
+ markRunAlerted(hqRoot, date, record.company, recordRel, record.startedAt, (message) => {
891
+ process.stderr.write(`hq signals: ${message}\n`);
892
+ });
893
+ }
894
+ }
629
895
  return { date, records, locked, summary, alerts };
630
896
  }
631
897
  return { date, records, locked, summary };
@@ -670,8 +936,17 @@ function stoppedRunReason(hqRoot, record, date, nowMs, isPidAlive) {
670
936
  * same rule, formatter, owner DM and hourly dedupe as the end-of-run alert
671
937
  * (`raiseSignalsRunAlerts`). A run whose extract step never finished alerts
672
938
  * only when its adapters step landed sources, as the end-of-run alert does.
673
- * One run is alerted once: when the shared dedupe file already holds an
674
- * alert sent at or after the run started, nothing is sent. Never throws.
939
+ * Each stopped run is alerted once: a run the owner was alerted for is
940
+ * listed in the day's alerted-runs file, by this check and by the end-of-run
941
+ * alert, and is not sent again. An alert for one run never covers another.
942
+ * When that file cannot be written, the check falls back to what it can
943
+ * still read: the runs this process alerted for (kept in memory), and the
944
+ * shared dedupe file in the company vault, where an alert sent at or after a
945
+ * run started covers that run. A DM that went out is always returned as sent.
946
+ * The manual runs written beside the day record are judged the same way,
947
+ * whether or not a later run finished after them. An incremental pass is not
948
+ * judged: it has no adapters step, so the rule above never counts it. Never
949
+ * throws.
675
950
  */
676
951
  export async function raiseStoppedRunAlert(input) {
677
952
  const log = input.senders.log ?? (() => { });
@@ -679,40 +954,101 @@ export async function raiseStoppedRunAlert(input) {
679
954
  const at = input.now();
680
955
  const day = input.daysAgo === 1 ? new Date(at.getFullYear(), at.getMonth(), at.getDate() - 1, 12) : at;
681
956
  const date = localDate(day);
682
- const record = readJson(input.hqRoot, runRecordRel(date, input.company));
683
- if (!record || typeof record !== "object" || record.dryRun || !Array.isArray(record.steps))
684
- return null;
685
- if (record.company !== input.company || typeof record.startedAt !== "string")
686
- return null;
687
- const reason = stoppedRunReason(input.hqRoot, record, date, at.getTime(), input.isPidAlive ?? defaultIsPidAlive);
688
- if (reason === null)
689
- return null;
690
- const person = await (input.senders.resolvePerson ?? resolveSignedInAlertPerson)(input.company);
691
- if (!person) {
692
- log(`signals alert for ${input.company} skipped: no signed-in person to alert`);
693
- return null;
957
+ // Every record of the day, newest first: the day record and each manual
958
+ // run written beside it. The first one that stopped (failed, or running
959
+ // with no live lock), is a failure by the end-of-run rule, and is not in
960
+ // the alerted-runs file is reported, and the call ends there: one call
961
+ // sends at most one DM. An older stopped run that was never alerted is
962
+ // reported by a later call, once the shared hourly dedupe lets it through.
963
+ const isPidAlive = input.isPidAlive ?? defaultIsPidAlive;
964
+ const alerted = new Set(readAlertedRuns(input.hqRoot, date, input.company));
965
+ let person = null;
966
+ /** Whether the alerted-runs file can be written; checked once, before the first send. */
967
+ let listWritable = null;
968
+ for (const { record, rel } of dayRunRecordFiles(input.hqRoot, date, input.company)) {
969
+ const runKey = alertedRunKey(rel, record.startedAt);
970
+ if (alerted.has(runKey) || alertedRunsNotListed.has(notListedKey(input.hqRoot, date, input.company, runKey)))
971
+ continue;
972
+ const reason = stoppedRunReason(input.hqRoot, record, date, at.getTime(), isPidAlive);
973
+ if (reason === null)
974
+ continue;
975
+ // Judge the record as the failed run it is: a running record never wrote
976
+ // its outcome, and an extract that never ran is a failed extract.
977
+ const steps = record.steps.some((s) => s.name === "extract")
978
+ ? record.steps
979
+ : [...record.steps, { name: "extract", itemsIn: 0, itemsOut: 0, durationMs: 0, status: "failed", error: reason }];
980
+ const judged = { ...record, status: "failed", alreadyRanToday: false, steps };
981
+ if (!isSignalsRunFailure(judged))
982
+ continue;
983
+ if (!person) {
984
+ person = await (input.senders.resolvePerson ?? resolveSignedInAlertPerson)(input.company);
985
+ if (!person) {
986
+ log(`signals alert for ${input.company} skipped: no signed-in person to alert`);
987
+ return null;
988
+ }
989
+ }
990
+ // A run can only be listed after its DM is out. When the file cannot be
991
+ // written, a DM sent now would be sent again by every later check, so
992
+ // the check uses the shared dedupe file instead: an alert sent at or
993
+ // after this run started covers it (one alert can then cover several
994
+ // runs, which is better than one run alerted every hour).
995
+ if (listWritable === null) {
996
+ listWritable = alertedRunsWritable(input.hqRoot, date, input.company);
997
+ if (!listWritable) {
998
+ log(`signals alert for ${input.company}: ${alertedRunsRel(date, input.company)} cannot be written; using the shared dedupe file to tell which runs were alerted`);
999
+ }
1000
+ }
1001
+ if (!listWritable && alertedSince(input.hqRoot, input.company, person, record.startedAt))
1002
+ continue;
1003
+ const alertPerson = person;
1004
+ const out = await raiseSignalsRunAlerts({
1005
+ hqRoot: input.hqRoot,
1006
+ records: [judged],
1007
+ senders: { ...input.senders, resolvePerson: () => alertPerson },
1008
+ now: input.now,
1009
+ });
1010
+ const result = out[input.company] ?? null;
1011
+ // Only a DM that went out marks the run. One held back by the hourly
1012
+ // dedupe, or one that failed to send, is tried again by a later call.
1013
+ if (result && result.sent.length > 0)
1014
+ markRunAlerted(input.hqRoot, date, input.company, rel, record.startedAt, log);
1015
+ return result;
694
1016
  }
695
- if (alertedSince(input.hqRoot, input.company, person, record.startedAt))
696
- return null;
697
- // Judge the record as the failed run it is: a running record never wrote
698
- // its outcome, and an extract that never ran is a failed extract.
699
- const steps = record.steps.some((s) => s.name === "extract")
700
- ? record.steps
701
- : [...record.steps, { name: "extract", itemsIn: 0, itemsOut: 0, durationMs: 0, status: "failed", error: reason }];
702
- const judged = { ...record, status: "failed", alreadyRanToday: false, steps };
703
- const out = await raiseSignalsRunAlerts({
704
- hqRoot: input.hqRoot,
705
- records: [judged],
706
- senders: { ...input.senders, resolvePerson: () => person },
707
- now: input.now,
708
- });
709
- return out[input.company] ?? null;
1017
+ return null;
710
1018
  }
711
1019
  catch (err) {
712
1020
  log(`signals alert for ${input.company} failed: ${err instanceof Error ? err.message : String(err)}`);
713
1021
  return null;
714
1022
  }
715
1023
  }
1024
+ /**
1025
+ * The company's records for the day that the stopped-run check can judge: the
1026
+ * day record and every manual-run sidecar, newest start first. A sidecar that
1027
+ * started in the same instant as the day record sorts first: it is only ever
1028
+ * written after that job finished. The shared incremental record is left out:
1029
+ * a pass has only an extract step, which the alert rule never counts.
1030
+ */
1031
+ export function dayRunRecords(hqRoot, date, company) {
1032
+ return dayRunRecordFiles(hqRoot, date, company).map((f) => f.record);
1033
+ }
1034
+ /** `dayRunRecords` with the file each record was read from. */
1035
+ function dayRunRecordFiles(hqRoot, date, company) {
1036
+ const rels = [...manualRunRecordRels(hqRoot, date, company).reverse(), runRecordRel(date, company)];
1037
+ const found = [];
1038
+ for (const rel of rels) {
1039
+ const record = readJson(hqRoot, rel);
1040
+ if (!record || typeof record !== "object" || record.dryRun || !Array.isArray(record.steps))
1041
+ continue;
1042
+ if (record.company !== company || typeof record.startedAt !== "string")
1043
+ continue;
1044
+ const at = Date.parse(record.startedAt);
1045
+ if (Number.isNaN(at))
1046
+ continue;
1047
+ found.push({ record, rel, at });
1048
+ }
1049
+ // Array.prototype.sort is stable: equal starts keep the order above.
1050
+ return found.sort((a, b) => b.at - a.at).map((f) => ({ record: f.record, rel: f.rel }));
1051
+ }
716
1052
  /** True when the shared dedupe file records a signals-run alert sent at or after `startedAt`. */
717
1053
  function alertedSince(hqRoot, company, person, startedAt) {
718
1054
  const file = signalsAlertStatePath(path.join(hqRoot, "companies", company), person.personKey);
@@ -1306,6 +1306,11 @@ function runTurn(ctx, runtime, prompt, scope, budgetUsd, opts) {
1306
1306
  const authDir = path.join(grokHome, ".grok");
1307
1307
  fs.mkdirSync(authDir, { mode: 0o700 });
1308
1308
  if (fs.existsSync(sourceAuth)) {
1309
+ // copyFileSync does not refuse a directory on every filesystem: where a
1310
+ // directory's size reads as 0 (btrfs, overlayfs on btrfs) it "copies"
1311
+ // it as an empty file. Require a regular file so a bad login fails here.
1312
+ if (!fs.statSync(sourceAuth).isFile())
1313
+ throw new Error(`grok login is not a regular file: ${sourceAuth}`);
1309
1314
  const authCopy = path.join(authDir, "auth.json");
1310
1315
  fs.copyFileSync(sourceAuth, authCopy, fs.constants.COPYFILE_EXCL);
1311
1316
  fs.chmodSync(authCopy, 0o600);
@@ -8,7 +8,23 @@ export interface EngineHeldDeletes {
8
8
  count: number;
9
9
  deletes: EngineHeldDelete[];
10
10
  }
11
+ /**
12
+ * hq-cloud's runner reads this file and never applies a delete it lists: the
13
+ * server copy stays (and downloads again when the local file is missing) and
14
+ * the local copy stays. The runner drops a path after a later positive signal.
15
+ */
16
+ export declare function handbackKeepFile(home: string): string;
17
+ /**
18
+ * Adds a vault's held deletes to the hand-back keep list, merged with any
19
+ * paths already listed for it. Throws when the file cannot be written.
20
+ */
21
+ export declare function writeHandbackKeep(home: string, vault: {
22
+ uid: string;
23
+ slug?: string;
24
+ }, held: EngineHeldDeletes, at: string,
25
+ /** Test seam: runs after the temp file is written, before the re-read that guards the rename. */
26
+ beforeRename?: (attempt: number) => void): void;
11
27
  export declare function engineHoldFile(engineHome: string, vaultUid: string): string;
12
28
  export declare function readEngineHeldDeletes(engineHome: string, vaultUid: string): EngineHeldDeletes | "unreadable" | null;
13
- export declare function heldDeletesHandoverLine(vaultUid: string, held: EngineHeldDeletes | "unreadable", engineHome: string): string;
29
+ export declare function heldDeletesHandoverLine(vaultUid: string, held: EngineHeldDeletes | "unreadable", engineHome: string, home: string): string;
14
30
  //# sourceMappingURL=engine-holds.d.ts.map