@indigoai-us/hq-cli 5.345.252 → 5.345.253

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 (43) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/contracts/host-canary-release.json +5 -5
  3. package/dist/command-catalog.generated.d.ts +148 -0
  4. package/dist/command-catalog.generated.js +182 -0
  5. package/dist/command-registration-plan.d.ts +6 -0
  6. package/dist/command-registration-plan.js +1 -0
  7. package/dist/commands/ci-intake.d.ts +15 -0
  8. package/dist/commands/ci-intake.js +252 -0
  9. package/dist/commands/ci-metrics.d.ts +8 -0
  10. package/dist/commands/ci-metrics.js +55 -0
  11. package/dist/commands/ci.d.ts +13 -0
  12. package/dist/commands/ci.js +10 -0
  13. package/dist/commands/files.d.ts +62 -0
  14. package/dist/commands/files.js +249 -8
  15. package/dist/lib/bot/fleet-cron.d.ts +15 -0
  16. package/dist/lib/bot/fleet-cron.js +119 -20
  17. package/dist/lib/daemon/run.js +4 -3
  18. package/dist/lib/delivery/migrations.d.ts +32 -1
  19. package/dist/lib/delivery/migrations.js +69 -8
  20. package/dist/lib/hook-engine/adapter-core-pin.d.ts +2 -1
  21. package/dist/lib/hook-engine/adapter-core-pin.js +2 -1
  22. package/dist/lib/hook-engine/coverage.d.ts +15 -0
  23. package/dist/lib/hook-engine/coverage.js +62 -1
  24. package/dist/lib/smart-ci/cost.d.ts +72 -0
  25. package/dist/lib/smart-ci/cost.js +120 -0
  26. package/dist/lib/smart-ci/github.d.ts +112 -0
  27. package/dist/lib/smart-ci/github.js +267 -0
  28. package/dist/lib/smart-ci/intake.d.ts +288 -0
  29. package/dist/lib/smart-ci/intake.js +1078 -0
  30. package/dist/lib/smart-ci/ledger.d.ts +218 -0
  31. package/dist/lib/smart-ci/ledger.js +527 -0
  32. package/dist/lib/smart-ci/metrics.d.ts +137 -0
  33. package/dist/lib/smart-ci/metrics.js +249 -0
  34. package/dist/lib/smart-ci/records.d.ts +265 -0
  35. package/dist/lib/smart-ci/records.js +281 -0
  36. package/dist/lib/smart-ci/reducer.d.ts +67 -0
  37. package/dist/lib/smart-ci/reducer.js +261 -0
  38. package/dist/lib/sync-core/engine-holds.d.ts +14 -0
  39. package/dist/lib/sync-core/engine-holds.js +78 -11
  40. package/dist/lib/sync-core/hand-back.d.ts +1 -0
  41. package/dist/lib/sync-core/hand-back.js +7 -2
  42. package/dist/lib/sync-core/reconcile.js +10 -2
  43. package/package.json +9 -7
@@ -678,6 +678,7 @@ export function registerFilesCommand(program) {
678
678
  .option("--dry-run", "List what WOULD be deleted without deleting anything")
679
679
  .option("--personal", "Target your own personal vault instead of a company vault (mutually exclusive with --company)")
680
680
  .option("-y, --yes", "Skip the confirmation prompt (for scripts); not above 1000 objects")
681
+ .option("--confirmation <token>", "Send an hqdc_ delete confirmation token with a real company-vault delete; asks you to type the confirmation in a terminal first (not with --dry-run or --personal)")
681
682
  .action(async (prefix, opts) => {
682
683
  try {
683
684
  const companySlug = files.opts().company;
@@ -692,6 +693,7 @@ export function registerFilesCommand(program) {
692
693
  yes: opts.yes === true,
693
694
  personal,
694
695
  companySlug,
696
+ ...(opts.confirmation !== undefined ? { confirmation: opts.confirmation } : {}),
695
697
  });
696
698
  }
697
699
  catch (err) {
@@ -1350,6 +1352,112 @@ async function runShareSession(params) {
1350
1352
  console.log(chalk.dim(" --no-open: copy the URL above to share manually."));
1351
1353
  }
1352
1354
  }
1355
+ export const DELETE_CEILING_EXCEEDED_CODE = "FILES_DELETE_CEILING_EXCEEDED";
1356
+ export const DELETE_CEILING_APPROVAL_REQUIRED_CODE = "FILES_DELETE_CEILING_APPROVAL_REQUIRED";
1357
+ export const DELETE_CONFIRMATION_INVALID_CODE = "FILES_DELETE_CONFIRMATION_INVALID";
1358
+ export const DELETE_CONFIRMATION_FIELD = "deleteConfirmation";
1359
+ function readUsage(v) {
1360
+ if (!v || typeof v !== "object")
1361
+ return undefined;
1362
+ const u = v;
1363
+ const n = (x) => (typeof x === "number" && Number.isFinite(x) ? x : undefined);
1364
+ const limit = n(u.limit);
1365
+ const requested = n(u.requested);
1366
+ const usedInWindow = n(u.usedInWindow);
1367
+ const windowSeconds = n(u.windowSeconds);
1368
+ if (limit === undefined || requested === undefined || usedInWindow === undefined || windowSeconds === undefined) {
1369
+ return undefined;
1370
+ }
1371
+ return {
1372
+ limit,
1373
+ requested,
1374
+ usedInWindow,
1375
+ windowSeconds,
1376
+ confirmLimit: n(u.confirmLimit) ?? limit,
1377
+ ...(typeof u.basis === "string" ? { basis: u.basis } : {}),
1378
+ ...(u.mode === "shadow" || u.mode === "enforce" ? { mode: u.mode } : {}),
1379
+ ...(typeof u.enforced === "boolean" ? { enforced: u.enforced } : {}),
1380
+ };
1381
+ }
1382
+ function safeText(v, max) {
1383
+ if (typeof v !== "string" || v.trim() === "")
1384
+ return undefined;
1385
+ if ([...v].some((c) => c.charCodeAt(0) < 0x20 || c.charCodeAt(0) === 0x7f))
1386
+ return undefined;
1387
+ return v.trim().slice(0, max);
1388
+ }
1389
+ export function isWellFormedConfirmationToken(v) {
1390
+ return typeof v === "string" && /^hqdc_[A-Za-z0-9_-]{32,123}$/.test(v);
1391
+ }
1392
+ export function parseCeilingRefusal(body) {
1393
+ if (!body || typeof body !== "object")
1394
+ return undefined;
1395
+ const b = body;
1396
+ if (b.code !== DELETE_CEILING_EXCEEDED_CODE && b.code !== DELETE_CEILING_APPROVAL_REQUIRED_CODE)
1397
+ return undefined;
1398
+ const c = b.confirmation && typeof b.confirmation === "object" ? b.confirmation : undefined;
1399
+ const a = b.approval && typeof b.approval === "object" ? b.approval : undefined;
1400
+ const expiresAt = safeText(c?.expiresAt, 64);
1401
+ const confirmation = c && isWellFormedConfirmationToken(c.token) && expiresAt !== undefined
1402
+ ? { token: c.token, expiresAt, sufficient: c.sufficient === true }
1403
+ : null;
1404
+ const roles = Array.isArray(a?.roles) ? a.roles.filter((r) => typeof r === "string").slice(0, 5) : [];
1405
+ const usage = readUsage(b.deleteCeiling);
1406
+ const rejected = safeText(b.confirmationRejected, 32);
1407
+ const error = safeText(b.error, 600);
1408
+ return {
1409
+ code: b.code,
1410
+ ...(error !== undefined ? { error } : {}),
1411
+ ...(usage ? { deleteCeiling: usage } : {}),
1412
+ confirmation,
1413
+ approval: {
1414
+ required: a?.required === true || b.code === DELETE_CEILING_APPROVAL_REQUIRED_CODE,
1415
+ roles: roles.map((r) => r.slice(0, 20)),
1416
+ },
1417
+ ...(rejected !== undefined ? { confirmationRejected: rejected } : {}),
1418
+ };
1419
+ }
1420
+ function describeUsage(u) {
1421
+ const minutes = Math.max(1, Math.round(u.windowSeconds / 60));
1422
+ return (`This delete would remove ${u.requested} objects, and ${u.usedInWindow} were already deleted in this vault ` +
1423
+ `in the last ${minutes} minutes. The company's delete limit is ${u.limit} per ${minutes} minutes.`);
1424
+ }
1425
+ /**
1426
+ * The way forward that works today when a delete needs another admin's
1427
+ * approval: no HQ command can send that approval yet. The server's window
1428
+ * total includes the requested count, so when one delete alone is over the
1429
+ * approval tier, waiting never helps and the only path without approval is
1430
+ * chunks no bigger than the limit, one window apart. Otherwise waiting for
1431
+ * the window to pass is the way forward.
1432
+ */
1433
+ function ceilingWaysForward(u) {
1434
+ const window = u
1435
+ ? `the ${Math.max(1, Math.round(u.windowSeconds / 60))}-minute window`
1436
+ : "the delete limit's time window";
1437
+ if (u && u.requested > u.confirmLimit) {
1438
+ return (`This one delete of ${u.requested} objects is over the ${u.confirmLimit}-object approval limit by itself, ` +
1439
+ "so waiting will not let it through. To go ahead without approval, split it into chunks of no more than " +
1440
+ `${u.limit} objects and wait for ${window} to pass between chunks.`);
1441
+ }
1442
+ return (`To go ahead, wait for ${window} to pass so earlier deletes stop counting. ` +
1443
+ "Splitting the delete into smaller prefixes does not help here, because the limit counts every delete in the window.");
1444
+ }
1445
+ function needsApproval(r) {
1446
+ return r.approval.required || (r.confirmation !== null && !r.confirmation.sufficient);
1447
+ }
1448
+ export function describeCeilingRefusal(r) {
1449
+ const parts = ["The server stopped this delete. Nothing was deleted."];
1450
+ if (r.deleteCeiling)
1451
+ parts.push(describeUsage(r.deleteCeiling));
1452
+ if (r.confirmationRejected)
1453
+ parts.push(`The confirmation sent was not accepted (${r.confirmationRejected}).`);
1454
+ if (needsApproval(r)) {
1455
+ const roles = r.approval.roles.length > 0 ? r.approval.roles.join(" or ") : "owner or admin";
1456
+ parts.push(`Another company ${roles} must approve this delete before it can run, and no HQ command can give that approval yet.`);
1457
+ parts.push(ceilingWaysForward(r.deleteCeiling));
1458
+ }
1459
+ return parts.join(" ");
1460
+ }
1353
1461
  export class FilesDeleteHttpError extends Error {
1354
1462
  status;
1355
1463
  code;
@@ -1360,6 +1468,14 @@ export class FilesDeleteHttpError extends Error {
1360
1468
  this.name = "FilesDeleteHttpError";
1361
1469
  }
1362
1470
  }
1471
+ export class FilesDeleteCeilingError extends FilesDeleteHttpError {
1472
+ refusal;
1473
+ constructor(status, refusal) {
1474
+ super(status, describeCeilingRefusal(refusal), refusal.code);
1475
+ this.refusal = refusal;
1476
+ this.name = "FilesDeleteCeilingError";
1477
+ }
1478
+ }
1363
1479
  /** Client-side ceiling: more objects than this in one delete needs a typed confirmation. */
1364
1480
  export const DELETE_CEILING_COUNT = 1000;
1365
1481
  /** Why a previewed delete is over the client-side ceiling, or undefined. */
@@ -1371,6 +1487,11 @@ export function clientCeilingReason(preview) {
1371
1487
  }
1372
1488
  /** Map a FilesDeleteHttpError to user-facing copy. */
1373
1489
  export function formatFilesDeleteError(err, prefix) {
1490
+ if (err instanceof FilesDeleteCeilingError)
1491
+ return err.message;
1492
+ if (err.code === DELETE_CONFIRMATION_INVALID_CODE) {
1493
+ return `${err.message || "The delete confirmation was not accepted."} Nothing was deleted.`;
1494
+ }
1374
1495
  if (err.status === 401) {
1375
1496
  return "Not authenticated — please run `hq login`";
1376
1497
  }
@@ -1420,6 +1541,7 @@ function realPrompt(message) {
1420
1541
  * `personal` flag — so there is nothing for the client to get wrong or spoof.
1421
1542
  */
1422
1543
  export async function callDeleteEndpoint(params) {
1544
+ const confirm = params.deleteConfirmation !== undefined ? { [DELETE_CONFIRMATION_FIELD]: params.deleteConfirmation } : {};
1423
1545
  const res = await vaultApiFetch({
1424
1546
  token: params.token,
1425
1547
  path: "/v1/files/delete",
@@ -1429,15 +1551,20 @@ export async function callDeleteEndpoint(params) {
1429
1551
  personal: true,
1430
1552
  prefix: params.prefix,
1431
1553
  dryRun: params.dryRun,
1554
+ ...confirm,
1432
1555
  }
1433
1556
  : {
1434
1557
  company: params.companyUid,
1435
1558
  prefix: params.prefix,
1436
1559
  dryRun: params.dryRun,
1560
+ ...confirm,
1437
1561
  },
1438
1562
  });
1439
1563
  if (!res.ok) {
1440
1564
  const body = (await res.json().catch(() => ({})));
1565
+ const refusal = res.status === 409 ? parseCeilingRefusal(body) : undefined;
1566
+ if (refusal)
1567
+ throw new FilesDeleteCeilingError(res.status, refusal);
1441
1568
  throw new FilesDeleteHttpError(res.status, body.message ?? body.error ?? res.statusText, body.code);
1442
1569
  }
1443
1570
  return (await res.json());
@@ -1624,10 +1751,63 @@ function normalizeCompanyFilePrefix(prefix, options = {}) {
1624
1751
  `is already company-scoped; using bucket-relative '${scope.prefix}'.`));
1625
1752
  return normalizeFilePrefix(scope.prefix);
1626
1753
  }
1754
+ /**
1755
+ * Handle the server's delete-ceiling refusal. The confirmation token is sent
1756
+ * only after the person types the confirmation in a terminal; --yes alone
1757
+ * never sends it. Returns the token to send, or undefined when the person
1758
+ * declined. Exits 1 when the delete cannot be confirmed here.
1759
+ */
1760
+ export async function confirmServerCeiling(refusal, deps) {
1761
+ const summary = describeCeilingRefusal(refusal);
1762
+ const confirmation = refusal.confirmation;
1763
+ if (needsApproval(refusal)) {
1764
+ console.error(chalk.red(summary));
1765
+ process.exit(1);
1766
+ }
1767
+ if (confirmation === null) {
1768
+ console.error(chalk.red(`${summary} The server did not issue a confirmation. Run the command again to get one.`));
1769
+ process.exit(1);
1770
+ }
1771
+ if (!deps.isInteractive()) {
1772
+ console.error(chalk.red(`${summary} Going ahead needs the confirmation typed in a terminal; --yes does not apply.`));
1773
+ process.exit(1);
1774
+ }
1775
+ const expiresAt = Date.parse(confirmation.expiresAt);
1776
+ const expired = () => !Number.isFinite(expiresAt) || deps.now().getTime() >= expiresAt;
1777
+ const expiredMessage = "The confirmation has expired or has no readable expiry time. Nothing was deleted. Run the command again.";
1778
+ if (expired()) {
1779
+ console.error(chalk.red(`${summary} ${expiredMessage}`));
1780
+ process.exit(1);
1781
+ }
1782
+ console.log(chalk.yellow(summary));
1783
+ const count = refusal.deleteCeiling?.requested;
1784
+ const phrase = count !== undefined ? `delete ${count} over the limit` : "delete over the limit";
1785
+ const answer = await deps.prompt(`Type '${phrase}' to go ahead (the confirmation expires at ${confirmation.expiresAt}): `);
1786
+ if (answer.trim() !== phrase) {
1787
+ console.log(chalk.dim("Aborted — nothing was deleted."));
1788
+ return undefined;
1789
+ }
1790
+ if (expired()) {
1791
+ console.error(chalk.red(expiredMessage));
1792
+ process.exit(1);
1793
+ }
1794
+ return confirmation.token;
1795
+ }
1627
1796
  export async function runFilesDelete(params, deps = {}) {
1628
1797
  const confirm = deps.confirm ?? realConfirm;
1629
1798
  const prompt = deps.prompt ?? realPrompt;
1630
1799
  const isInteractive = deps.isInteractive ?? (() => process.stdin.isTTY === true && process.stdout.isTTY === true);
1800
+ const now = deps.now ?? (() => new Date());
1801
+ if (params.dryRun && params.confirmation !== undefined) {
1802
+ console.error(chalk.red("--confirmation cannot be used with --dry-run: a dry run deletes nothing and never sends the confirmation. " +
1803
+ "Drop --dry-run to send it, or drop --confirmation to preview. Nothing was deleted."));
1804
+ process.exit(1);
1805
+ }
1806
+ if (params.personal === true && params.confirmation !== undefined) {
1807
+ console.error(chalk.red("--confirmation cannot be used with --personal: the delete confirmation applies only to company vaults. " +
1808
+ "Drop --confirmation to delete from your personal vault. Nothing was deleted."));
1809
+ process.exit(1);
1810
+ }
1631
1811
  // Strip the local company anchor before preview/confirmation (HQ-8F/HQ-CA).
1632
1812
  // Personal keys are already bucket-relative and must keep any such anchor.
1633
1813
  // Deletion intentionally expands a folder spelling to a recursive glob, then
@@ -1695,6 +1875,26 @@ export async function runFilesDelete(params, deps = {}) {
1695
1875
  if (overCeiling) {
1696
1876
  console.log(chalk.yellow(`A real delete would stop here: ${overCeiling}. It needs the confirmation typed in a terminal; --yes does not skip it.`));
1697
1877
  }
1878
+ const usage = readUsage(preview.deleteCeiling);
1879
+ if (usage && usage.usedInWindow + usage.requested > usage.limit) {
1880
+ const overConfirmLimit = usage.usedInWindow + usage.requested > usage.confirmLimit;
1881
+ if (usage.enforced === false) {
1882
+ // hq-pro #5656 watch-only mode: the server records the over-limit
1883
+ // delete but lets it through, so do not say it would be stopped.
1884
+ console.log(chalk.yellow("The company delete limit is in watch-only mode on the server, so a real delete would go through. " +
1885
+ `${describeUsage(usage)} ` +
1886
+ (overConfirmLimit
1887
+ ? "Once the server enforces the limit, a delete like this would be stopped until another owner or admin approves it."
1888
+ : "Once the server enforces the limit, a delete like this would need a confirmation typed in a terminal.")));
1889
+ }
1890
+ else {
1891
+ console.log(chalk.yellow(`A real delete would be stopped by the company delete limit: ${describeUsage(usage)} ` +
1892
+ (overConfirmLimit
1893
+ ? "Going ahead needs another owner or admin's approval. No HQ command can give that approval yet. " +
1894
+ ceilingWaysForward(usage)
1895
+ : "Going ahead needs a confirmation typed in a terminal.")));
1896
+ }
1897
+ }
1698
1898
  console.log(chalk.dim("Nothing was deleted (--dry-run)."));
1699
1899
  return;
1700
1900
  }
@@ -1730,22 +1930,63 @@ export async function runFilesDelete(params, deps = {}) {
1730
1930
  return;
1731
1931
  }
1732
1932
  }
1933
+ let approvedToken;
1934
+ if (params.confirmation !== undefined) {
1935
+ if (!isWellFormedConfirmationToken(params.confirmation)) {
1936
+ console.error(chalk.red("--confirmation must be a delete confirmation from HQ (it starts with hqdc_). Nothing was deleted."));
1937
+ process.exit(1);
1938
+ }
1939
+ if (!isInteractive()) {
1940
+ console.error(chalk.red("--confirmation is sent only after you type the confirmation in a terminal. Nothing was deleted."));
1941
+ process.exit(1);
1942
+ }
1943
+ const phrase = `delete ${preview.matched} with approval`;
1944
+ const answer = await prompt(`Type '${phrase}' to send the approved confirmation and delete: `);
1945
+ if (answer.trim() !== phrase) {
1946
+ console.log(chalk.dim("Aborted — nothing was deleted."));
1947
+ return;
1948
+ }
1949
+ approvedToken = params.confirmation;
1950
+ }
1733
1951
  // 3. Execute the delete.
1952
+ const realDelete = (deleteConfirmation) => callDeleteEndpoint({
1953
+ token,
1954
+ ...scopeArgs,
1955
+ prefix: normalized,
1956
+ dryRun: false,
1957
+ ...(deleteConfirmation !== undefined ? { deleteConfirmation } : {}),
1958
+ });
1734
1959
  let result;
1735
1960
  try {
1736
- result = await callDeleteEndpoint({
1737
- token,
1738
- ...scopeArgs,
1739
- prefix: normalized,
1740
- dryRun: false,
1741
- });
1961
+ result = await realDelete(approvedToken);
1742
1962
  }
1743
1963
  catch (err) {
1744
- if (err instanceof FilesDeleteHttpError) {
1964
+ if (err instanceof FilesDeleteCeilingError && approvedToken !== undefined) {
1965
+ console.error(chalk.red(err.message));
1966
+ process.exit(1);
1967
+ }
1968
+ else if (err instanceof FilesDeleteCeilingError) {
1969
+ const confirmed = await confirmServerCeiling(err.refusal, { prompt, isInteractive, now });
1970
+ if (confirmed === undefined)
1971
+ return;
1972
+ try {
1973
+ result = await realDelete(confirmed);
1974
+ }
1975
+ catch (retryErr) {
1976
+ if (retryErr instanceof FilesDeleteHttpError) {
1977
+ console.error(chalk.red(formatFilesDeleteError(retryErr, normalized)));
1978
+ process.exit(1);
1979
+ }
1980
+ throw retryErr;
1981
+ }
1982
+ }
1983
+ else if (err instanceof FilesDeleteHttpError) {
1745
1984
  console.error(chalk.red(formatFilesDeleteError(err, normalized)));
1746
1985
  process.exit(1);
1747
1986
  }
1748
- throw err;
1987
+ else {
1988
+ throw err;
1989
+ }
1749
1990
  }
1750
1991
  const deletedNoun = result.deleted === 1 ? "object" : "objects";
1751
1992
  console.log(chalk.green(`Deleted ${result.deleted} ${deletedNoun} under '${normalized}'.`));
@@ -108,6 +108,19 @@ export declare const FLEET_HOT_SIGNAL_SYNC_NAME = "hot-signal-sync";
108
108
  export declare const FLEET_HOT_SIGNAL_SYNC_SCHEDULE = "30 6 * * *";
109
109
  export declare function fleetHotSignalSyncScript(company: string): string;
110
110
  export declare function companyOfHotSignalSyncJob(job: FleetCronJob): string | null;
111
+ /**
112
+ * Waits between tries when a run fails because HQ could not reach the network.
113
+ * The job often fires the moment a laptop wakes, before Wi-Fi and DNS are back
114
+ * (Fleet catches up a missed daily run for up to 2 hours), so a short retry
115
+ * finds the connection. About 3.5 minutes in all, well inside Fleet's 1-hour
116
+ * script timeout.
117
+ */
118
+ export declare const HOT_SIGNAL_SYNC_NETWORK_RETRY_DELAYS_SEC: readonly number[];
119
+ /**
120
+ * A network failure reaches the owner only once it repeats this many runs in a
121
+ * row. A single morning on a sleeping laptop is not worth a message.
122
+ */
123
+ export declare const HOT_SIGNAL_SYNC_TRANSIENT_ALERT_AFTER = 2;
111
124
  /**
112
125
  * pnpm global installs land the CLI under `.../pnpm/global/vN/<hash>/...`.
113
126
  * That hash folder is removed on the next CLI update. The stable launcher is
@@ -128,6 +141,8 @@ export declare function renderFleetHotSignalSyncScript(input: {
128
141
  signalsEngine?: boolean;
129
142
  /** Override the baked pnpm `bin/hq` fallback. Tests pass this. */
130
143
  hqLauncher?: string;
144
+ /** Seconds between network retries. Default HOT_SIGNAL_SYNC_NETWORK_RETRY_DELAYS_SEC; tests pass zeros. */
145
+ networkRetryDelaysSec?: readonly number[];
131
146
  }): string;
132
147
  export interface EnsureFleetHotSignalSyncInput {
133
148
  dir: string;
@@ -464,6 +464,71 @@ def signals_failures(err):
464
464
  errors.append(error)
465
465
  return found, errors
466
466
  `;
467
+ /**
468
+ * Waits between tries when a run fails because HQ could not reach the network.
469
+ * The job often fires the moment a laptop wakes, before Wi-Fi and DNS are back
470
+ * (Fleet catches up a missed daily run for up to 2 hours), so a short retry
471
+ * finds the connection. About 3.5 minutes in all, well inside Fleet's 1-hour
472
+ * script timeout.
473
+ */
474
+ export const HOT_SIGNAL_SYNC_NETWORK_RETRY_DELAYS_SEC = [30, 60, 120];
475
+ /**
476
+ * A network failure reaches the owner only once it repeats this many runs in a
477
+ * row. A single morning on a sleeping laptop is not worth a message.
478
+ */
479
+ export const HOT_SIGNAL_SYNC_TRANSIENT_ALERT_AFTER = 2;
480
+ /**
481
+ * Python helper for the flag-off script: one alert per failure streak.
482
+ *
483
+ * The state file next to the log counts failed runs in a row and the reasons
484
+ * already sent to the owner in this streak. A failure the owner already heard
485
+ * about stays in the log only, and the script exits 0 so Fleet sends nothing
486
+ * (Fleet turns any non-zero exit of a no-agent job into a DM). A new reason
487
+ * alerts again. A clean run deletes the file, which ends the streak. A
488
+ * network-only failure alerts from HOT_SIGNAL_SYNC_TRANSIENT_ALERT_AFTER runs
489
+ * in a row. When the file cannot be read or written the script alerts, as it
490
+ * did before the state file existed.
491
+ */
492
+ const HOT_SIGNAL_SYNC_STREAK = String.raw `def read_streak():
493
+ try:
494
+ with open(STATE, encoding='utf-8') as f:
495
+ data = json.load(f)
496
+ if isinstance(data, dict):
497
+ return data
498
+ except Exception:
499
+ pass
500
+ return {}
501
+
502
+ def note_failure(reason, transient):
503
+ # Returns (alert, failures in a row including this run).
504
+ try:
505
+ state = read_streak()
506
+ failures = int(state.get('failures') or 0) + 1
507
+ alerted = [r for r in (state.get('alerted') or []) if isinstance(r, str)]
508
+ alert = reason not in alerted and (not transient or failures >= TRANSIENT_ALERT_AFTER)
509
+ if alert:
510
+ alerted.append(reason)
511
+ tmp = STATE + '.tmp'
512
+ with open(tmp, 'w', encoding='utf-8') as f:
513
+ json.dump({'failures': failures, 'alerted': alerted, 'last': reason, 'at': time.strftime('%Y-%m-%dT%H:%M:%S%z', STARTED)}, f)
514
+ os.replace(tmp, STATE)
515
+ return alert, failures
516
+ except Exception:
517
+ return True, 1
518
+
519
+ def clear_streak():
520
+ try:
521
+ os.remove(STATE)
522
+ except OSError:
523
+ pass
524
+
525
+ def in_a_row(failures):
526
+ return ' (%d runs in a row)' % failures if failures > 1 else ''
527
+
528
+ def log_quiet(failures):
529
+ with open(LOG, 'a', encoding='utf-8') as log:
530
+ log.write('Not sent to the owner: they already heard about this failure in this streak, or it is a network failure seen fewer than %d runs in a row (%d so far).\n' % (TRANSIENT_ALERT_AFTER, failures))
531
+ `;
467
532
  /** How a run ended, for the log line after it: `exit 1` or `signal 9`. */
468
533
  const HOT_SIGNAL_SYNC_RUN_END = String.raw `def run_end(code):
469
534
  return 'signal %d' % -code if code < 0 else 'exit %d' % code
@@ -547,6 +612,12 @@ export function renderFleetHotSignalSyncScript(input) {
547
612
  // lines (US-018 AC1). A clean run that landed sources and found no signals
548
613
  // also raises the alert, but with no error; it stays in the log. The exit
549
614
  // code stays 0: the sync itself finished.
615
+ //
616
+ // Each failure streak alerts once (HOT_SIGNAL_SYNC_STREAK): a reason the
617
+ // owner already heard about in this streak stays in the log and the script
618
+ // exits 0, because Fleet DMs every non-zero exit. A network failure is
619
+ // retried within the run (NETWORK_RETRY_DELAYS) and alerts only from its
620
+ // second run in a row.
550
621
  const launcher = input.hqLauncher ?? fleetPnpmHqLauncher(input.hqBinary);
551
622
  // HQ is often the pnpm hash folder's dist/index.js. That path dies on the
552
623
  // next CLI update (feedback_614121bf). Prefer it while it exists so tests
@@ -554,31 +625,51 @@ export function renderFleetHotSignalSyncScript(input) {
554
625
  // launcher without node (it is a shell/cmd shim, not JS).
555
626
  const run = plainSync
556
627
  ? [
557
- " command = hq_argv() + ARGS",
558
- " result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8', errors='replace')",
559
- " note = ''",
628
+ " def sync_once():",
629
+ " command = hq_argv() + ARGS",
630
+ " result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8', errors='replace')",
631
+ " note = ''",
560
632
  // Commander rejects the option before the sync starts, so the retry is
561
633
  // the only run that does any work.
562
- " if result.returncode != 0 and \"unknown option '--trigger'\" in result.stderr:",
563
- " note = 'This hq has no --trigger option; ran the sync without it.\\n'",
564
- " command = hq_argv() + LEGACY_ARGS",
565
- " result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8', errors='replace')",
566
- " with open(LOG, 'a', encoding='utf-8') as log:",
567
- header,
568
- " log.write(note)",
569
- " log.write(result.stderr)",
570
- " log.write(result.stdout)",
571
- " if result.returncode != 0 and not output_lines(result.stderr) and not output_lines(result.stdout):",
572
- " log.write('hq printed nothing. Command: ' + shlex.join(command) + '\\n')",
573
- footer,
634
+ " if result.returncode != 0 and \"unknown option '--trigger'\" in result.stderr:",
635
+ " note = 'This hq has no --trigger option; ran the sync without it.\\n'",
636
+ " command = hq_argv() + LEGACY_ARGS",
637
+ " result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8', errors='replace')",
638
+ " with open(LOG, 'a', encoding='utf-8') as log:",
639
+ header.replace(/^ {8}/, " "),
640
+ " log.write(note)",
641
+ " log.write(result.stderr)",
642
+ " log.write(result.stdout)",
643
+ " if result.returncode != 0 and not output_lines(result.stderr) and not output_lines(result.stdout):",
644
+ " log.write('hq printed nothing. Command: ' + shlex.join(command) + '\\n')",
645
+ footer.replace(/^ {8}/, " "),
646
+ " return result",
647
+ // A network failure is retried a few times before it counts: the job
648
+ // often fires the moment a laptop wakes, before the connection is back.
649
+ " result = sync_once()",
650
+ " for delay in NETWORK_RETRY_DELAYS:",
651
+ " if result.returncode == 0 or classify(result.stdout, result.stderr, result.returncode)[1] != FIXES['network']:",
652
+ " break",
653
+ " with open(LOG, 'a', encoding='utf-8') as log:",
654
+ " log.write('HQ could not reach the network; trying again in %d s.\\n' % delay)",
655
+ " time.sleep(delay)",
656
+ " result = sync_once()",
574
657
  " if result.returncode != 0:",
575
658
  " reason, fix = classify(result.stdout, result.stderr, result.returncode)",
576
- ` sys.stdout.write('The ' + scheduled_time() + ${JSON.stringify(` hot-channel sync for ${input.company} did not finish: `)} + reason + '.\\n')`,
659
+ " alert, failures = note_failure(reason, fix == FIXES['network'])",
660
+ " if not alert:",
661
+ " log_quiet(failures)",
662
+ // Exit 0 so Fleet sends nothing: it turns any non-zero exit into a DM.
663
+ // The failure is in the log and in the sync's own run ledger.
664
+ " sys.exit(0)",
665
+ ` sys.stdout.write('The ' + scheduled_time() + ${JSON.stringify(` hot-channel sync for ${input.company} did not finish: `)} + reason + in_a_row(failures) + '.\\n')`,
577
666
  " sys.stdout.write('Fix: ' + fix + '\\n')",
578
667
  " sys.stdout.write('Log: ' + LOG + ' (run started ' + time.strftime('%Y-%m-%d %H:%M', STARTED) + ')\\n')",
579
668
  " sys.exit(128 - result.returncode if result.returncode < 0 else result.returncode)",
580
669
  " found, errors = signals_failures(result.stderr)",
581
- " if found:",
670
+ " if not found:",
671
+ " clear_streak()",
672
+ " else:",
582
673
  " reasons, fixes = [], []",
583
674
  " for error in errors:",
584
675
  " reason, fix = classify('', error, 1)",
@@ -586,9 +677,13 @@ export function renderFleetHotSignalSyncScript(input) {
586
677
  " reasons.append(reason)",
587
678
  " if fix not in fixes:",
588
679
  " fixes.append(fix)",
589
- ` sys.stdout.write('The ' + scheduled_time() + ${JSON.stringify(` hot-channel sync for ${input.company} landed sources but the signals step failed: `)} + '; '.join(found) + '. Cause: ' + '; '.join(reasons) + '.\\n')`,
590
- " sys.stdout.write('Fix: ' + ' Also, '.join(fixes) + '\\n')",
591
- " sys.stdout.write('Log: ' + LOG + ' (run started ' + time.strftime('%Y-%m-%d %H:%M', STARTED) + ')\\n')",
680
+ " alert, failures = note_failure('signals: ' + '; '.join(reasons), all(f == FIXES['network'] for f in fixes))",
681
+ " if not alert:",
682
+ " log_quiet(failures)",
683
+ " else:",
684
+ ` sys.stdout.write('The ' + scheduled_time() + ${JSON.stringify(` hot-channel sync for ${input.company} landed sources but the signals step failed: `)} + '; '.join(found) + '. Cause: ' + '; '.join(reasons) + in_a_row(failures) + '.\\n')`,
685
+ " sys.stdout.write('Fix: ' + ' Also, '.join(fixes) + '\\n')",
686
+ " sys.stdout.write('Log: ' + LOG + ' (run started ' + time.strftime('%Y-%m-%d %H:%M', STARTED) + ')\\n')",
592
687
  ]
593
688
  : [
594
689
  " with open(LOG, 'a', encoding='utf-8') as log:",
@@ -611,11 +706,15 @@ export function renderFleetHotSignalSyncScript(input) {
611
706
  ...(plainSync
612
707
  ? [
613
708
  `LEGACY_ARGS = ${JSON.stringify(legacyArgs)}`,
709
+ `STATE = ${JSON.stringify(path.join(path.dirname(input.logFile), `hot-signal-sync-${input.company}.state.json`))}`,
710
+ `NETWORK_RETRY_DELAYS = ${JSON.stringify(input.networkRetryDelaysSec ?? HOT_SIGNAL_SYNC_NETWORK_RETRY_DELAYS_SEC)}`,
711
+ `TRANSIENT_ALERT_AFTER = ${HOT_SIGNAL_SYNC_TRANSIENT_ALERT_AFTER}`,
614
712
  `FIXES = ${JSON.stringify(fixes)}`,
615
713
  "FIXES = dict((k, v.replace('DATE', time.strftime('%Y-%m-%d', STARTED))) for k, v in FIXES.items())",
616
714
  HOT_SIGNAL_SYNC_ALERT_HELPERS,
617
715
  `SIGNALS_FAILURE_PREFIX = ${JSON.stringify(SIGNALS_FAILURE_PREFIX)}`,
618
716
  HOT_SIGNAL_SYNC_SIGNALS_FAILURES,
717
+ HOT_SIGNAL_SYNC_STREAK,
619
718
  ]
620
719
  : []),
621
720
  "try:",
@@ -34,7 +34,7 @@ import { serveQmdWorker } from "../search-index/worker-process.js";
34
34
  import { inspectEngineHome, syncCoreUnitId } from "../sync-core/engine-home.js";
35
35
  import { fullModeHold } from "../sync-core/reconcile.js";
36
36
  import { engineVaultCount, readSyncCoreRolloutState } from "../sync-core/rollout-state.js";
37
- import { engineOwnsVault, finishLegacyHandBack } from "../sync-core/hand-back.js";
37
+ import { engineHoldBlocksHandBack, engineOwnsVault, finishLegacyHandBack } from "../sync-core/hand-back.js";
38
38
  import { effectiveEngineSettings, readSyncCoreVaultSettings } from "../sync-core/vault-settings.js";
39
39
  import { assertPersonalServiceSessionCapability, readRemoteControlPoolsConfig, remoteControlPoolSecretsEnv, } from "./remote-control-pools.js";
40
40
  import { loadLanesConfig } from "../lanes/config.js";
@@ -147,8 +147,9 @@ export function planUnitsWithSyncCoreInterlock(services, context, supervisor, re
147
147
  let personalOff = context.vaultSync.personalOff;
148
148
  const offCompanies = new Set(context.vaultSync.offCompanies);
149
149
  const engineStopped = (uid) => !!supervisor && supervisor.runningPlanKey(syncCoreUnitId(uid)) === undefined;
150
- const held = (context.syncCoreVaults ?? []).filter((vault) => vault.phase === "full" && engineStopped(vault.uid) && fullModeHold(vault, vault.release, context.platform));
151
- const handingBack = (context.syncCoreHandingBack ?? []).filter((vault) => engineStopped(vault.uid) && engineOwnsVault(context.home, vault.uid));
150
+ const held = (context.syncCoreVaults ?? []).filter((vault) => vault.phase === "full" && engineStopped(vault.uid) && fullModeHold(vault, vault.release, context.platform)
151
+ && !engineHoldBlocksHandBack(context.home, vault.uid));
152
+ const handingBack = (context.syncCoreHandingBack ?? []).filter((vault) => engineStopped(vault.uid) && engineOwnsVault(context.home, vault.uid) && !engineHoldBlocksHandBack(context.home, vault.uid));
152
153
  const handBack = [...held, ...handingBack];
153
154
  const restore = legacySwitchRestorePatch(handBack, context.vaultSync);
154
155
  if (restore.personal)
@@ -12,8 +12,10 @@ export declare const STORE_SCHEMA_V5 = "hq-delivery.store.v5";
12
12
  export declare const STORE_SCHEMA_V6 = "hq-delivery.store.v6";
13
13
  /** v7 (US-011 slice 4) adds a claim lease to every attempt (leaseExpiresAt). */
14
14
  export declare const STORE_SCHEMA_V7 = "hq-delivery.store.v7";
15
+ /** v8 (smart-ci US-001) adds the smart-ci namespace: keyed records and stream cursors. */
16
+ export declare const STORE_SCHEMA_V8 = "hq-delivery.store.v8";
15
17
  /** The store schema version this code writes. */
16
- export declare const STORE_SCHEMA_VERSION = "hq-delivery.store.v7";
18
+ export declare const STORE_SCHEMA_VERSION = "hq-delivery.store.v8";
17
19
  /** Every version this code can open, oldest first. Older ones migrate forward on open. */
18
20
  export declare const KNOWN_STORE_SCHEMA_VERSIONS: readonly string[];
19
21
  export type DeliveryStoreErrorCode = "STORE_CORRUPT" | "STORE_SCHEMA_NEWER" | "STORE_SCHEMA_UNKNOWN" | "STORE_INVALID_RECORD" | "CONTROLLER_OWNED" | "CONTROLLER_AMBIGUOUS" | "FENCED" | "STORE_CLOSED" | "STORE_IO" | "INVALID_RECORD" | "DUPLICATE_CONFLICT" | "UNKNOWN_RUN" | "UNKNOWN_JOB" | "UNKNOWN_DEPENDENCY" | "DEPENDENCY_CYCLE" | "NOT_CLAIMABLE" | "UNKNOWN_ATTEMPT" | "ATTEMPT_CONFLICT" | "ATTEMPT_ABANDONED" | "ACCESS_DENIED" | "WORKER_REVOKED" | "PRIVILEGE_REJECTED" | "CREDENTIAL_UNAVAILABLE" | "NOTIFICATION_UNVERIFIED" | "ARTIFACT_UNKNOWN" | "ARTIFACT_TAMPERED" | "ARTIFACT_NOT_PROMOTABLE" | "SIGNING_KEY_UNCONFIGURED" | "BACKUP_INVALID" | "RESTORE_PENDING" | "STORE_RETIRED" | "DEPLOY_BLOCKED" | "ENV_BUSY" | "DEPLOY_OUTCOME_UNKNOWN" | "STALE_PUBLICATION" | "UNKNOWN_DEPLOYMENT" | "TARGET_UNREACHABLE" | "RPC_TIMEOUT" | "RPC_CLOSED" | "RPC_UNREACHABLE" | "RPC_BAD_REQUEST" | "RPC_UNKNOWN_METHOD" | "RPC_TOO_LARGE" | "RPC_BAD_ANSWER" | "RPC_SERVER_ERROR" | "RPC_NOT_LOOPBACK" | "RPC_BUSY" | "LEASE_UNCONFIRMED";
@@ -129,6 +131,35 @@ export interface StoreState {
129
131
  deployments: StoredDeployment[];
130
132
  /** US-009: one admin-set, signed deploy policy per company. Workers never write it. */
131
133
  deployPolicies: StoredDeployPolicy[];
134
+ /** v8: the smart-ci namespace. Smart CI records and cursors live here and nowhere else. */
135
+ smartCi: SmartCiNamespace;
136
+ }
137
+ /**
138
+ * One smart-ci record (v8). `kind` and `id` together are unique, so writing
139
+ * the same observation again replaces the record and never adds a second one.
140
+ * The store checks this envelope only; src/lib/smart-ci owns each kind's body.
141
+ */
142
+ export interface StoredSmartCiRecord {
143
+ kind: string;
144
+ id: string;
145
+ /** When the record was first written, on the controller's clock. */
146
+ recordedAt: string;
147
+ recordedEpoch: number;
148
+ /** When the body last changed, on the controller's clock. */
149
+ updatedAt: string;
150
+ updatedEpoch: number;
151
+ body: Record<string, unknown>;
152
+ }
153
+ /** How far one smart-ci input stream has been read (v8). One entry per stream. */
154
+ export interface StoredSmartCiCursor {
155
+ stream: string;
156
+ position: string;
157
+ updatedAt: string;
158
+ updatedEpoch: number;
159
+ }
160
+ export interface SmartCiNamespace {
161
+ records: StoredSmartCiRecord[];
162
+ cursors: StoredSmartCiCursor[];
132
163
  }
133
164
  /**
134
165
  * blocked: refused by admission; carries a decision, no fence, no effect.