@indigoai-us/hq-cli 5.345.255 → 5.345.257

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 (56) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/README.md +21 -0
  3. package/assets/scaffold/core/scripts/handoff-finalize.sh +981 -46
  4. package/assets/scaffold/core/scripts/hq-delegate-bundle.sh +51 -2
  5. package/assets/scaffold/core/scripts/hq-delegate-send.sh +49 -6
  6. package/assets/scaffold/core/scripts/hq-delegate-transfer.sh +20 -0
  7. package/assets/scaffold/core/scripts/hq-delegate-verify.sh +56 -10
  8. package/assets/scaffold/core/scripts/lib/fingerprint.sh +423 -0
  9. package/assets/scaffold/core/scripts/rebuild-companies-index.sh +10 -1
  10. package/assets/scaffold/core/scripts/rebuild-company-knowledge-index.sh +10 -1
  11. package/assets/scaffold/core/scripts/rebuild-projects-index.sh +10 -1
  12. package/assets/scaffold/core/scripts/register-project.sh +110 -19
  13. package/contracts/host-canary-release.json +7 -7
  14. package/dist/command-catalog.generated.d.ts +1 -1
  15. package/dist/command-catalog.generated.js +1 -1
  16. package/dist/commands/core-delegate-w1b.js +107 -16
  17. package/dist/commands/core-delegate.d.ts +7 -0
  18. package/dist/commands/core-delegate.js +66 -2
  19. package/dist/commands/core-handoff-fast.d.ts +1 -1
  20. package/dist/commands/core-handoff-fast.js +2 -2
  21. package/dist/commands/core-handoff.d.ts +3 -1
  22. package/dist/commands/core-handoff.js +1407 -177
  23. package/dist/commands/core-register-project-native.js +1 -1
  24. package/dist/commands/core.js +2 -2
  25. package/dist/commands/files.d.ts +2 -0
  26. package/dist/commands/files.js +34 -5
  27. package/dist/commands/team-sync.js +1 -1
  28. package/dist/lib/company-skill-wrapper.js +72 -4
  29. package/dist/lib/daemon/requests.d.ts +14 -1
  30. package/dist/lib/daemon/requests.js +17 -3
  31. package/dist/lib/daemon/run.js +44 -2
  32. package/dist/lib/daemon/supervisor.d.ts +11 -0
  33. package/dist/lib/daemon/supervisor.js +33 -0
  34. package/dist/lib/daemon/sync-perf-telemetry.d.ts +85 -0
  35. package/dist/lib/daemon/sync-perf-telemetry.js +206 -0
  36. package/dist/lib/daemon/windows-relaunch.d.ts +55 -0
  37. package/dist/lib/daemon/windows-relaunch.js +72 -0
  38. package/dist/lib/hook-engine/coverage.d.ts +10 -1
  39. package/dist/lib/hook-engine/coverage.js +40 -5
  40. package/dist/lib/index-render/companies.js +3 -2
  41. package/dist/lib/index-render/index.js +2 -1
  42. package/dist/lib/index-render/session-scope.d.ts +2 -3
  43. package/dist/lib/index-render/session-scope.js +2 -5
  44. package/dist/lib/index-render/shared.d.ts +7 -0
  45. package/dist/lib/index-render/shared.js +9 -0
  46. package/dist/lib/work-context/windows-acl.d.ts +14 -0
  47. package/dist/lib/work-context/windows-acl.js +26 -0
  48. package/dist/utils/cli-telemetry.d.ts +26 -7
  49. package/dist/utils/cli-telemetry.js +70 -13
  50. package/dist/utils/git.js +1 -1
  51. package/dist/utils/resident-package-preload.js +4 -0
  52. package/dist/utils/sync-perf-telemetry-flag.d.ts +26 -0
  53. package/dist/utils/sync-perf-telemetry-flag.js +32 -0
  54. package/dist/utils/telemetry-opt-out.d.ts +13 -0
  55. package/dist/utils/telemetry-opt-out.js +19 -0
  56. package/package.json +8 -8
@@ -501,7 +501,7 @@ function storyNotDone(prd, deps, diagnostics) {
501
501
  diagnostics.push(jq.stderr);
502
502
  else if (jq.error?.code === "ENOENT") {
503
503
  const script = resolveBundledAsset(REGISTER_PROJECT_ASSET);
504
- diagnostics.push(`${script}: line 65: jq: command not found\n`);
504
+ diagnostics.push(`${script}: line 120: jq: command not found\n`);
505
505
  }
506
506
  return false;
507
507
  }
@@ -61,7 +61,7 @@ import { registerCoreWorkflowRunCommand } from "./core-workflow-run-command.js";
61
61
  import { resolveLiveRoot } from "../utils/hq-roots.js";
62
62
  import { interpreterFor, runBundledScript } from "../utils/run-bundled-script.js";
63
63
  import { CompanyIndexUserError, renderIndexTarget } from "../lib/index-render/index.js";
64
- import { planScopedRebuild, SESSION_SCOPE_HELP } from "../lib/index-render/session-scope.js";
64
+ import { planScopedRebuild } from "../lib/index-render/session-scope.js";
65
65
  import { generateWorkersRegistry } from "../lib/workers-registry/index.js";
66
66
  import { scanPackages } from "../lib/scan-packages/index.js";
67
67
  import { GENERATE_WORKERS_REGISTRY_SUMMARY, isNativeScaffoldHelpRequest, nativeScaffoldUsage, SCAN_PACKAGES_SUMMARY, } from "../lib/core-utils/native-scaffold-help.js";
@@ -370,6 +370,7 @@ export const SCAFFOLD_ONLY_ASSETS = [
370
370
  { asset: "core/scripts/pipeline-driver.sh", root: "live", summary: "Rollback shell for native pipeline driver" },
371
371
  { asset: "core/scripts/pipeline-envelope.sh", root: "live", summary: "Validation helper for the pipeline shell rollback companions" },
372
372
  { asset: "core/scripts/lib/portable.sh", root: "live", summary: "Shared portable helpers sourced by bundled scripts" },
373
+ { asset: "core/scripts/lib/fingerprint.sh", root: "live", summary: "Offline HQ-Fingerprint trailer helper sourced by handoff-finalize" },
373
374
  ...NATIVE_UTILITY_COMMANDS.map(({ asset, root, summary }) => ({
374
375
  asset,
375
376
  root,
@@ -701,7 +702,6 @@ export function registerCoreCommands(program) {
701
702
  const wantsHelp = rendererArgs.some((arg) => arg === "--help" || arg === "-h");
702
703
  if (wantsHelp && ["companies", "company-knowledge", "projects"].includes(entry.renderer)) {
703
704
  renderIndexTarget(entry.renderer, { root: "", output: (message) => process.stdout.write(message) }, rendererArgs);
704
- process.stdout.write(SESSION_SCOPE_HELP);
705
705
  return;
706
706
  }
707
707
  if (wantsHelp) {
@@ -209,6 +209,8 @@ export declare class FilesDeleteCeilingError extends FilesDeleteHttpError {
209
209
  readonly refusal: FilesDeleteCeilingRefusal;
210
210
  constructor(status: number, refusal: FilesDeleteCeilingRefusal);
211
211
  }
212
+ /** Clock skew allowed in the local expiry check of a server confirmation. */
213
+ export declare const DELETE_CONFIRMATION_CLOCK_SKEW_MS = 60000;
212
214
  /** Client-side ceiling: more objects than this in one delete needs a typed confirmation. */
213
215
  export declare const DELETE_CEILING_COUNT = 1000;
214
216
  /** Why a previewed delete is over the client-side ceiling, or undefined. */
@@ -1,3 +1,4 @@
1
+ import { Option } from "commander";
1
2
  import chalk from "chalk";
2
3
  import { aclLockedBy, describeAclLock } from "./acl-lock.js";
3
4
  import open from "open";
@@ -678,7 +679,11 @@ export function registerFilesCommand(program) {
678
679
  .option("--dry-run", "List what WOULD be deleted without deleting anything")
679
680
  .option("--personal", "Target your own personal vault instead of a company vault (mutually exclusive with --company)")
680
681
  .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)")
682
+ // Hidden until an HQ approve command ships: the CLI never shows an hqdc_
683
+ // token, so a CLI user has no way to get one (PR 3466 review I-1). It still
684
+ // parses, with every guard in runFilesDelete, for callers who got a token
685
+ // from the API.
686
+ .addOption(new 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)").hideHelp())
682
687
  .action(async (prefix, opts) => {
683
688
  try {
684
689
  const companySlug = files.opts().company;
@@ -1439,8 +1444,22 @@ function ceilingWaysForward(u) {
1439
1444
  "so waiting will not let it through. To go ahead without approval, split it into chunks of no more than " +
1440
1445
  `${u.limit} objects and wait for ${window} to pass between chunks.`);
1441
1446
  }
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.");
1447
+ const wait = `To go ahead, wait for ${window} to pass so earlier deletes stop counting.`;
1448
+ if (!u)
1449
+ return wait;
1450
+ // The server needs approval when usedInWindow + requested > confirmLimit, so
1451
+ // a smaller delete that keeps the window total at or under confirmLimit can
1452
+ // still go ahead with at most a typed confirmation (PR 3466 review I-2).
1453
+ const room = u.confirmLimit - u.usedInWindow;
1454
+ if (room <= 0) {
1455
+ return (`${wait} Splitting the delete into smaller prefixes does not help here, because the ${u.usedInWindow} deletes ` +
1456
+ `already in the window reach the ${u.confirmLimit}-object approval limit.`);
1457
+ }
1458
+ if (room < u.requested) {
1459
+ return (`${wait} Or delete a smaller part now: a delete of at most ${room} objects stays within the ` +
1460
+ `${u.confirmLimit}-object approval limit and can go ahead with a confirmation typed in a terminal.`);
1461
+ }
1462
+ return wait;
1444
1463
  }
1445
1464
  function needsApproval(r) {
1446
1465
  return r.approval.required || (r.confirmation !== null && !r.confirmation.sufficient);
@@ -1476,6 +1495,8 @@ export class FilesDeleteCeilingError extends FilesDeleteHttpError {
1476
1495
  this.name = "FilesDeleteCeilingError";
1477
1496
  }
1478
1497
  }
1498
+ /** Clock skew allowed in the local expiry check of a server confirmation. */
1499
+ export const DELETE_CONFIRMATION_CLOCK_SKEW_MS = 60_000;
1479
1500
  /** Client-side ceiling: more objects than this in one delete needs a typed confirmation. */
1480
1501
  export const DELETE_CEILING_COUNT = 1000;
1481
1502
  /** Why a previewed delete is over the client-side ceiling, or undefined. */
@@ -1772,8 +1793,11 @@ export async function confirmServerCeiling(refusal, deps) {
1772
1793
  console.error(chalk.red(`${summary} Going ahead needs the confirmation typed in a terminal; --yes does not apply.`));
1773
1794
  process.exit(1);
1774
1795
  }
1796
+ // The server checks expiry itself; the local check only saves a pointless
1797
+ // prompt, so it allows for a client clock a little ahead of the server
1798
+ // (PR 3466 review I-4).
1775
1799
  const expiresAt = Date.parse(confirmation.expiresAt);
1776
- const expired = () => !Number.isFinite(expiresAt) || deps.now().getTime() >= expiresAt;
1800
+ const expired = () => !Number.isFinite(expiresAt) || deps.now().getTime() >= expiresAt + DELETE_CONFIRMATION_CLOCK_SKEW_MS;
1777
1801
  const expiredMessage = "The confirmation has expired or has no readable expiry time. Nothing was deleted. Run the command again.";
1778
1802
  if (expired()) {
1779
1803
  console.error(chalk.red(`${summary} ${expiredMessage}`));
@@ -1962,7 +1986,12 @@ export async function runFilesDelete(params, deps = {}) {
1962
1986
  }
1963
1987
  catch (err) {
1964
1988
  if (err instanceof FilesDeleteCeilingError && approvedToken !== undefined) {
1965
- console.error(chalk.red(err.message));
1989
+ // A rejected token with a fresh, sufficient offer can be confirmed in
1990
+ // this terminal by running without --confirmation (PR 3466 review I-3).
1991
+ const hint = needsApproval(err.refusal)
1992
+ ? ""
1993
+ : " Run the command again without --confirmation to confirm in this terminal.";
1994
+ console.error(chalk.red(`${err.message}${hint}`));
1966
1995
  process.exit(1);
1967
1996
  }
1968
1997
  else if (err instanceof FilesDeleteCeilingError) {
@@ -13,7 +13,7 @@ import * as fs from 'fs';
13
13
  import * as path from 'path';
14
14
  import { execSync } from 'child_process';
15
15
  import chalk from 'chalk';
16
- import simpleGit from 'simple-git';
16
+ import { simpleGit } from 'simple-git';
17
17
  import { resolveDefaultHqRoot } from '../utils/cognito-session.js';
18
18
  import { ensureCognitoToken } from '../utils/cognito-session.js';
19
19
  import { readCompaniesManifestMap } from '../lib/work-context/repo-remote.js';
@@ -1,10 +1,22 @@
1
+ import { randomBytes } from "node:crypto";
1
2
  import * as fs from "node:fs";
2
3
  import * as path from "node:path";
4
+ import { markExpectedUserError } from "../utils/expected-cli-error.js";
3
5
  import { removeEntryNoFollow } from "../utils/safe-link.js";
4
6
  const WIN32_RESERVED_CHARS = /[<>:"/\\|?*]/;
5
7
  const WIN32_DEVICE_NAME = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i;
6
8
  const LOCAL_SLUG = /^[a-z0-9][a-z0-9-]*$/;
7
9
  const WRAPPER_MARKER_DIR = ".hq-company-skill-wrappers";
10
+ // Version 3 binds the marker to a random nonce stored inside the wrapper.
11
+ // Version 2 bound it only to the wrapper's dev, inode and birthtime. A folder
12
+ // deleted and recreated at the same path can get all three back (seen on the
13
+ // overlay filesystem in the Mac CI runners' Docker VM), so a hand-made
14
+ // replacement could pass as HQ-generated (#3594).
15
+ const WRAPPER_MARKER_VERSION = 3;
16
+ // Hidden, so Claude/Codex skill discovery and the bridge-state count (which
17
+ // both skip dot entries) never treat it as skill content.
18
+ const WRAPPER_NONCE_FILE = ".hq-generated-wrapper-nonce";
19
+ const WRAPPER_NONCE = /^[0-9a-f]{64}$/;
8
20
  function encodeLocalSegment(segment, win32) {
9
21
  if (!win32)
10
22
  return segment;
@@ -97,15 +109,35 @@ function linksIntoCompanySkills(linkPath, target, companySkillsRoot) {
97
109
  function generatedMarkerPath(wrapperPath) {
98
110
  return path.join(path.dirname(wrapperPath), WRAPPER_MARKER_DIR, `${path.basename(wrapperPath)}.json`);
99
111
  }
100
- function writeGeneratedMarker(wrapperPath, companySlug, skillSlug) {
112
+ /**
113
+ * The nonce stored inside a wrapper folder, or undefined when the folder has
114
+ * no regular nonce file (a hand-made folder, a bridged source file of the
115
+ * same name, or a symlink are all rejected).
116
+ */
117
+ function readWrapperNonce(wrapperPath) {
118
+ const noncePath = path.join(wrapperPath, WRAPPER_NONCE_FILE);
119
+ try {
120
+ if (!fs.lstatSync(noncePath).isFile())
121
+ return undefined;
122
+ const nonce = fs.readFileSync(noncePath, "utf8").trim();
123
+ return WRAPPER_NONCE.test(nonce) ? nonce : undefined;
124
+ }
125
+ catch {
126
+ return undefined;
127
+ }
128
+ }
129
+ function writeGeneratedMarker(wrapperPath, companySlug, skillSlug, wrapperNonce) {
101
130
  const markerPath = generatedMarkerPath(wrapperPath);
102
131
  try {
103
132
  const wrapper = fs.lstatSync(wrapperPath);
104
133
  fs.mkdirSync(path.dirname(markerPath), { recursive: true });
105
134
  fs.writeFileSync(markerPath, `${JSON.stringify({
106
- version: 2,
135
+ version: WRAPPER_MARKER_VERSION,
107
136
  companySlug,
108
137
  skillSlug,
138
+ // Absent when no nonce could be placed in the wrapper; such a marker is
139
+ // never "bound", and ownership falls back to the live bridges.
140
+ ...(wrapperNonce === undefined ? {} : { wrapperNonce }),
109
141
  wrapperDev: wrapper.dev,
110
142
  wrapperIno: wrapper.ino,
111
143
  wrapperBirthtimeMs: wrapper.birthtimeMs,
@@ -180,6 +212,11 @@ function inspectGeneratedNamespacedWrapper(wrapperPath, hqRoot, companySlug) {
180
212
  };
181
213
  }
182
214
  const entries = fs.readdirSync(wrapperPath).filter((entry) => !entry.startsWith("."));
215
+ // A bridge counts as live when its link text resolves into the company
216
+ // skills folder, even if the source file it names was since renamed or
217
+ // deleted (a dangling link). So a generated wrapper, including one with a
218
+ // version 2 marker, stays "all_live" and owned after its source changes;
219
+ // only a wrapper holding real files or links elsewhere needs the marker.
183
220
  const liveBridgeCount = entries.reduce((count, entry) => {
184
221
  const entryPath = path.join(wrapperPath, entry);
185
222
  const target = symlinkTarget(entryPath);
@@ -223,9 +260,19 @@ function generatedMarkerState(wrapperPath, companySlug) {
223
260
  catch {
224
261
  return "invalid";
225
262
  }
263
+ if (typeof marker !== "object" || marker === null)
264
+ return "invalid";
265
+ // An older marker identifies the wrapper only by inode and birthtime, which a
266
+ // deleted-and-recreated folder can reuse. It is never sufficient on its own;
267
+ // the next successful surface through live bridges rewrites it.
268
+ if (marker.version !== WRAPPER_MARKER_VERSION)
269
+ return "legacy";
226
270
  try {
227
271
  const wrapper = fs.lstatSync(wrapperPath);
228
- return marker.version === 2 &&
272
+ const wrapperNonce = readWrapperNonce(wrapperPath);
273
+ return typeof marker.wrapperNonce === "string" &&
274
+ wrapperNonce !== undefined &&
275
+ marker.wrapperNonce === wrapperNonce &&
229
276
  marker.companySlug === companySlug &&
230
277
  marker.wrapperDev === wrapper.dev &&
231
278
  marker.wrapperIno === wrapper.ino &&
@@ -314,6 +361,7 @@ export function surfaceCompanySkill(input) {
314
361
  throw new Error(`Cannot surface the skill because '${wrapperPath}' is not a directory.`);
315
362
  }
316
363
  const sourceEntries = fs.readdirSync(sourceDir).sort();
364
+ let wrapperNonce;
317
365
  const runtimeRoot = path.dirname(wrapperPath);
318
366
  fs.mkdirSync(runtimeRoot, { recursive: true });
319
367
  const stagingPath = fs.mkdtempSync(path.join(runtimeRoot, `.${wrapperName}.tmp-`));
@@ -335,6 +383,16 @@ export function surfaceCompanySkill(input) {
335
383
  const relativeTarget = path.relative(wrapperPath, sourcePath);
336
384
  bridgeEntry(sourcePath, entryWrapper, relativeTarget, fs.statSync(sourcePath).isDirectory() ? "dir" : "file", input.symlinkEntry ?? fs.symlinkSync);
337
385
  }
386
+ // A source file of the same name stays bridged as customer content; the
387
+ // wrapper then carries no nonce and its marker can never be "bound".
388
+ if (!sourceEntries.includes(WRAPPER_NONCE_FILE)) {
389
+ const nonce = randomBytes(32).toString("hex");
390
+ fs.writeFileSync(path.join(stagingPath, WRAPPER_NONCE_FILE), `${nonce}\n`, {
391
+ encoding: "utf8",
392
+ flag: "wx",
393
+ });
394
+ wrapperNonce = nonce;
395
+ }
338
396
  }
339
397
  const currentWrapper = lstat(wrapperPath);
340
398
  if (currentWrapper &&
@@ -348,6 +406,16 @@ export function surfaceCompanySkill(input) {
348
406
  if (currentWrapper) {
349
407
  const ownership = inspectGeneratedNamespacedWrapper(wrapperPath, input.hqRoot, input.companySlug);
350
408
  if (!ownership.owned) {
409
+ if (ownership.diagnostics.markerState === "legacy") {
410
+ // The folder holds something other than links into the company skill
411
+ // and its marker predates the nonce, so HQ cannot tell an older
412
+ // generated wrapper from a hand-made replacement. That is the user's
413
+ // local state with a clear remedy, not an hq-cli defect.
414
+ throw markExpectedUserError(new Error(`Cannot replace '${wrapperPath}' because it is not an HQ-generated skill wrapper ` +
415
+ "this HQ version can verify: it holds files that are not links into " +
416
+ `companies/${input.companySlug}/skills/, and its marker was made by an older HQ version. ` +
417
+ `If HQ made this folder, remove '${wrapperPath}' and rerun; if you wrote it, rename it first.`));
418
+ }
351
419
  const runtimePlatform = process.platform;
352
420
  const platform = win32
353
421
  ? "win32"
@@ -407,7 +475,7 @@ export function surfaceCompanySkill(input) {
407
475
  removeGeneratedMarker(wrapperPath);
408
476
  throw new Error(`The bridged skill '${wrapperPath}' does not match the canonical SKILL.md at '${skillFile}'.`);
409
477
  }
410
- writeGeneratedMarker(wrapperPath, input.companySlug, input.skillSlug);
478
+ writeGeneratedMarker(wrapperPath, input.companySlug, input.skillSlug, wrapperNonce);
411
479
  pruneStaleNamespacedWrappers(runtimeRoot, wrapperName, input.hqRoot, input.companySlug, win32);
412
480
  if (input.legacyPrefix) {
413
481
  const legacyBase = path.join(runtimeRoot, `${input.legacyPrefix}-${input.skillSlug}`);
@@ -25,5 +25,18 @@ export type ControlRequest = {
25
25
  deferUntilSyncIdle?: boolean;
26
26
  };
27
27
  export declare function writeControlRequest(dir: string, request: ControlRequest, now?: () => number): string;
28
- export declare function takeControlRequests(dir: string): ControlRequest[];
28
+ /** The write time a request file name starts with, or null for a name this module did not write. */
29
+ export declare function controlRequestWrittenAt(name: string): number | null;
30
+ export interface TakeControlRequestsOptions {
31
+ /**
32
+ * The running daemon's start time. A restart-daemon request written before it
33
+ * is dropped: this daemon already started on the CLI that was on disk then.
34
+ * Without this, `hq daemon restart --daemon` run while the daemon was down
35
+ * made the next `hq daemon start` come up and exit again (feedback_a89efa81).
36
+ */
37
+ restartDaemonNotBefore?: number;
38
+ /** Called once per dropped restart-daemon request. */
39
+ onStaleRestartDaemon?: (writtenAt: number) => void;
40
+ }
41
+ export declare function takeControlRequests(dir: string, opts?: TakeControlRequestsOptions): ControlRequest[];
29
42
  //# sourceMappingURL=requests.d.ts.map
@@ -36,7 +36,12 @@ export function writeControlRequest(dir, request, now = Date.now) {
36
36
  fs.renameSync(tmp, file);
37
37
  return file;
38
38
  }
39
- export function takeControlRequests(dir) {
39
+ /** The write time a request file name starts with, or null for a name this module did not write. */
40
+ export function controlRequestWrittenAt(name) {
41
+ const m = /^(\d{15})-/.exec(name);
42
+ return m ? Number(m[1]) : null;
43
+ }
44
+ export function takeControlRequests(dir, opts = {}) {
40
45
  let names;
41
46
  try {
42
47
  names = fs.readdirSync(dir).filter((n) => n.endsWith(".json")).sort();
@@ -57,8 +62,17 @@ export function takeControlRequests(dir) {
57
62
  parsed = null;
58
63
  }
59
64
  fs.rmSync(file, { force: true });
60
- if (isControlRequest(parsed))
61
- requests.push(parsed);
65
+ if (!isControlRequest(parsed))
66
+ continue;
67
+ const writtenAt = controlRequestWrittenAt(name);
68
+ if (parsed.action === "restart-daemon"
69
+ && opts.restartDaemonNotBefore !== undefined
70
+ && writtenAt !== null
71
+ && writtenAt < opts.restartDaemonNotBefore) {
72
+ opts.onStaleRestartDaemon?.(writtenAt);
73
+ continue;
74
+ }
75
+ requests.push(parsed);
62
76
  }
63
77
  return requests;
64
78
  }
@@ -63,7 +63,8 @@ import { meshOwnerHere } from "./mesh-owner.js";
63
63
  import { repairMeshUnitFromOtherHome } from "../mesh/live/daemon/install.js";
64
64
  import { registryDir, registryFile } from "../registry/registry.js";
65
65
  import { updateAnywhereRuntimeRevocationMarker } from "../anywhere-runtime-revocation-marker.js";
66
- import { classifyWindowsTask, currentWindowsIdentity, daemonRootRefusal } from "./install.js";
66
+ import { classifyWindowsTask, currentDaemonWindowsTaskName, currentWindowsIdentity, currentWindowsUser, daemonRootRefusal } from "./install.js";
67
+ import { needsWindowsTaskRelaunch, scheduleWindowsTaskRelaunch } from "./windows-relaunch.js";
67
68
  import { detectMachineType } from "./machine-type.js";
68
69
  import { appendPrivate, daemonPaths, ensurePrivateDir, openPrivateAppend } from "./paths.js";
69
70
  import { SELF_CHECK_RESULT_FILE, readSelfCheckResult } from "./selfcheck.js";
@@ -84,6 +85,8 @@ import { runnerSessionName } from "./remote-control.js";
84
85
  import { adoptChild, createChildTracker, finishSuccession, handoffEligible, readProcStart, stopOrphans, successionPaths, systemdKillMode, takeSuccession, writeHandoff, } from "./succession.js";
85
86
  import { listSyncRunnerProcesses, readWatchRunnerOwnerStatus, SYNC_RUNNER_LEASE_CONFLICT_EXIT, syncHeartbeatTimeoutMs, syncRunnerNodeOptions, watchRunnerOwnerStatusPath, } from "./sync-runner.js";
86
87
  import { STOP_ESCALATION_MS, SYNC_RUNNER_PERSIST_GRACE_MS, createSupervisor, planKey, } from "./supervisor.js";
88
+ import { createSyncPerfForwarder } from "./sync-perf-telemetry.js";
89
+ import { isSyncPerfCollectionEnabled } from "../../utils/sync-perf-telemetry-flag.js";
87
90
  import { userToolDirs } from "./tools.js";
88
91
  import { logOffset, readLogSince, readUnitHolds, writeUnitHolds } from "./unit-holds.js";
89
92
  import { createTccEpermGuard, filesAccessLaunch, TCC_EPERM_SENTRY_FINGERPRINT } from "./tcc-eperm.js";
@@ -869,6 +872,8 @@ export function checkMeshUnitHome(opts) {
869
872
  return true;
870
873
  }
871
874
  export async function runDaemon(opts) {
875
+ // A restart-daemon request written before this moment is stale (requests.ts).
876
+ const daemonStartedAtMs = Date.now();
872
877
  // Before anything reads the environment: hqd and every service inherit it.
873
878
  const started = daemonStartEnv(opts.env);
874
879
  const env = withUserRuntimeDir(started.env, {
@@ -1890,6 +1895,17 @@ export async function runDaemon(opts) {
1890
1895
  // Set once the shutdown path exists below; a restart request before then is dropped.
1891
1896
  let restartDaemon = () => false;
1892
1897
  let extendSyncShutdownCap;
1898
+ // Sampled sync-engine perf lines, queued and sent in batches off the supervisor's line loop.
1899
+ // The telemetry module loads on the first send, not at daemon start.
1900
+ const syncPerfForwarder = createSyncPerfForwarder({
1901
+ // HQ_TELEMETRY and the default-on kill switch: when either is off, the forwarder queues and
1902
+ // schedules nothing and the telemetry module never loads. The supervisor still checks each line first.
1903
+ enabled: () => isSyncPerfCollectionEnabled(env),
1904
+ send: async (events) => {
1905
+ const { emitSyncPerfEvents } = await import("../../utils/cli-telemetry.js");
1906
+ await emitSyncPerfEvents(events);
1907
+ },
1908
+ });
1893
1909
  supervisor = createSupervisor({
1894
1910
  machineType,
1895
1911
  host: opts.host,
@@ -1921,7 +1937,10 @@ export async function runDaemon(opts) {
1921
1937
  },
1922
1938
  takeRequests: () => {
1923
1939
  handoffForPackageUpdateRequest(currentPackageUseUpdateRequested(), restartDaemon);
1924
- return takeControlRequests(paths.requestsDir);
1940
+ return takeControlRequests(paths.requestsDir, {
1941
+ restartDaemonNotBefore: daemonStartedAtMs,
1942
+ onStaleRestartDaemon: (writtenAt) => log("info", `ignored a daemon restart queued at ${new Date(writtenAt).toISOString()}, before this daemon started`),
1943
+ });
1925
1944
  },
1926
1945
  restartDaemon: () => restartDaemon(),
1927
1946
  runGuard: daemonRunGuard,
@@ -1964,6 +1983,8 @@ export async function runDaemon(opts) {
1964
1983
  meshOwnerReason,
1965
1984
  cliVersion: CLI_VERSION,
1966
1985
  adopt,
1986
+ env,
1987
+ onSyncPerfEvent: (event) => syncPerfForwarder.push(event),
1967
1988
  });
1968
1989
  /** Hand services over on this restart: the unit leaves them running and the flag is on. */
1969
1990
  const handoffWanted = async () => {
@@ -2057,6 +2078,23 @@ export async function runDaemon(opts) {
2057
2078
  stopHqdInputWatch();
2058
2079
  void hqdListener.close().catch((err) => log("warn", `hqd socket did not close cleanly: ${err.message}`));
2059
2080
  };
2081
+ // The Scheduled Task does not start the daemon again after it exits with
2082
+ // RESTART_EXIT_CODE (launchd and systemd do), so a detached helper runs the
2083
+ // task once this process is gone (windows-relaunch.ts).
2084
+ const relaunchWindowsTaskAfterExit = () => {
2085
+ if (!needsWindowsTaskRelaunch(process.platform, opts))
2086
+ return;
2087
+ const run = (cmd, args) => {
2088
+ const r = spawnSync(cmd, args, { encoding: "utf8", windowsHide: true });
2089
+ return { status: r.status ?? 1, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
2090
+ };
2091
+ const taskName = currentDaemonWindowsTaskName(run, currentWindowsUser(env));
2092
+ const scheduled = scheduleWindowsTaskRelaunch({ taskName, env });
2093
+ if (scheduled.ok)
2094
+ log("info", `the Scheduled Task ${taskName} will start the daemon again once this one exits`);
2095
+ else
2096
+ log("error", `could not schedule the daemon to start again (${scheduled.error}); run \`hq daemon start\``);
2097
+ };
2060
2098
  return await new Promise((resolve) => {
2061
2099
  let stopping = false;
2062
2100
  let restartPending = false;
@@ -2076,6 +2114,7 @@ export async function runDaemon(opts) {
2076
2114
  if (supervisor.hasStoppingSyncRunner())
2077
2115
  cap.extendForSyncRunnerPersist();
2078
2116
  const servicesStopped = supervisor.stop();
2117
+ syncPerfForwarder.stop();
2079
2118
  void Promise.race([Promise.all([servicesStopped, stopJobsClosed]).then(([result]) => result), cap.promise]).then((result) => {
2080
2119
  cap.clear();
2081
2120
  extendSyncShutdownCap = undefined;
@@ -2157,6 +2196,9 @@ export async function runDaemon(opts) {
2157
2196
  return false;
2158
2197
  })
2159
2198
  .then((handoff) => {
2199
+ // A stop that began meanwhile (SIGTERM, `hq daemon stop`) wins: no relaunch.
2200
+ if (!stopping)
2201
+ relaunchWindowsTaskAfterExit();
2160
2202
  if (handoff && succession)
2161
2203
  handOver();
2162
2204
  else
@@ -31,6 +31,7 @@ import type { UnitPlan } from "./catalog.js";
31
31
  import type { MachineType } from "./machine-type.js";
32
32
  import type { ControlRequest } from "./requests.js";
33
33
  import { syncPassResult } from "./sync-runner.js";
34
+ import { type SyncPerfEvent } from "./sync-perf-telemetry.js";
34
35
  export declare const HEALTHY_RUN_MS = 60000;
35
36
  /**
36
37
  * Failures in one episode before the unit is held: the first start plus five
@@ -224,7 +225,17 @@ export interface SupervisorDeps {
224
225
  };
225
226
  /** Whether a process is alive (signal 0). Enables releasing exit-17 holds when the lock holder exits. */
226
227
  pidAlive?: (pid: number) => boolean;
228
+ /**
229
+ * Receives each valid `{"type":"perf"}` line from a sync-core engine. Must return
230
+ * at once (queue and send elsewhere); a throw is caught and logged. Not called
231
+ * while `HQ_TELEMETRY` turns telemetry off for the daemon or the engine unit.
232
+ */
233
+ onSyncPerfEvent?: (event: SyncPerfEvent) => void;
234
+ /** The daemon's environment, read for the `HQ_TELEMETRY` opt-out (defaults to `process.env`). */
235
+ env?: NodeJS.ProcessEnv;
227
236
  }
237
+ /** Invalid perf lines logged per engine run; later ones are dropped without a log line. */
238
+ export declare const SYNC_PERF_INVALID_LOG_MAX = 5;
228
239
  export interface Supervisor {
229
240
  start(): void;
230
241
  /** Resolves once every child process has exited. */
@@ -32,6 +32,8 @@ import { StringDecoder } from "node:string_decoder";
32
32
  import { classifyExit } from "./exit-cause.js";
33
33
  import { runFleetBotsUpdateWorker } from "../bot/fleet-bots-update-task.js";
34
34
  import { SYNC_RUNNER_LEASE_CONFLICT_EXIT, SYNC_RUNNER_LEASE_RETRY_MS, parseSyncRunnerProtocolLine, syncPassResult, } from "./sync-runner.js";
35
+ import { syncPerfCompanyUid, validateSyncPerfEvent } from "./sync-perf-telemetry.js";
36
+ import { isCliTelemetryDisabled } from "../../utils/telemetry-opt-out.js";
35
37
  const BACKOFF_BASE_MS = 1_000;
36
38
  const BACKOFF_MAX_MS = 60_000;
37
39
  export const HEALTHY_RUN_MS = 60_000;
@@ -148,6 +150,8 @@ function recordPassRequestDir(state, dir) {
148
150
  else
149
151
  delete state.passRequestDir;
150
152
  }
153
+ /** Invalid perf lines logged per engine run; later ones are dropped without a log line. */
154
+ export const SYNC_PERF_INVALID_LOG_MAX = 5;
151
155
  /** Plan reads in a row that must find a running remote-control host blocked before it is paused. */
152
156
  const BLOCKED_READS_BEFORE_PAUSE = 2;
153
157
  function backoffMs(attempt) {
@@ -752,6 +756,33 @@ export function createSupervisor(deps) {
752
756
  emit();
753
757
  }, timeoutMs);
754
758
  };
759
+ let invalidPerfLogged = 0;
760
+ // A perf line still counts as protocol activity below, as before; this only adds forwarding.
761
+ const acceptPerfEvent = (event) => {
762
+ const forward = deps.onSyncPerfEvent;
763
+ if (!forward)
764
+ return;
765
+ if (isCliTelemetryDisabled(deps.env ?? process.env) || isCliTelemetryDisabled(slot.plan.env))
766
+ return;
767
+ const result = validateSyncPerfEvent(event);
768
+ if (!result.ok) {
769
+ if (invalidPerfLogged < SYNC_PERF_INVALID_LOG_MAX) {
770
+ invalidPerfLogged++;
771
+ deps.log("info", `debug: dropped a perf event from ${slot.plan.id}: ${result.reason}`);
772
+ }
773
+ return;
774
+ }
775
+ // A company vault's engine attributes its samples to that company, so
776
+ // hq-pro applies its company-scope consent rule; a personal vault's
777
+ // samples stay personal rows (the person's opt-in decides).
778
+ const companyUid = syncPerfCompanyUid(slot.plan.id);
779
+ try {
780
+ forward(companyUid ? { ...result.event, companyUid } : result.event);
781
+ }
782
+ catch (err) {
783
+ deps.log("info", `debug: could not queue a perf event from ${slot.plan.id}: ${errorMessage(err)}`);
784
+ }
785
+ };
755
786
  const acceptProtocolLine = (line) => {
756
787
  let event;
757
788
  try {
@@ -788,6 +819,8 @@ export function createSupervisor(deps) {
788
819
  runDeferredCliRestart();
789
820
  }
790
821
  }
822
+ if (slot.plan.service === "sync-core" && event.type === "perf")
823
+ acceptPerfEvent(event);
791
824
  if (slot.plan.service === "sync-core") {
792
825
  if (event.type === "fanout-plan")
793
826
  slot.engineCycleActive = true;
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Sampled perf events from the sync engine (hq-syncd), forwarded to HQ telemetry.
3
+ *
4
+ * Under `HQ_SYNC_PROTOCOL=1` the engine writes `{"type":"perf","v":1,...}` lines on
5
+ * the protocol stdout the supervisor already reads (hq-sync-core
6
+ * `crates/hq-sync-daemon/src/perf_telemetry.rs`). This module validates a line
7
+ * strictly against that v1 schema and queues valid events for an asynchronous,
8
+ * batched send. Nothing here blocks or throws into the supervisor's line loop.
9
+ *
10
+ * A valid event holds only an operation name from a closed set, a duration, the
11
+ * sample rate, size buckets from a closed set, small counts and booleans. Any
12
+ * other key, any other string, or any out-of-range number rejects the whole line.
13
+ */
14
+ export declare const SYNC_PERF_EVENT_VERSION = 1;
15
+ export declare const SYNC_PERF_OPS: readonly ["plan", "snapshot_ingest", "index_open", "first_sync"];
16
+ export type SyncPerfOp = (typeof SYNC_PERF_OPS)[number];
17
+ export declare const SYNC_PERF_SIZE_BUCKETS: readonly ["0-1k", "1k-10k", "10k-100k", "100k+"];
18
+ export type SyncPerfSizeBucket = (typeof SYNC_PERF_SIZE_BUCKETS)[number];
19
+ /** A day, in milliseconds. A longer sampled operation is not a plausible measurement. */
20
+ export declare const SYNC_PERF_MAX_DURATION_MS = 86400000;
21
+ /** Upper bound for `pages` and `migrationBatches` (u32 on the engine side; real values are tens). */
22
+ export declare const SYNC_PERF_MAX_COUNT = 100000;
23
+ export interface SyncPerfEvent {
24
+ op: SyncPerfOp;
25
+ durationMs: number;
26
+ sampleRate: number;
27
+ files?: SyncPerfSizeBucket;
28
+ actions?: SyncPerfSizeBucket;
29
+ placed?: SyncPerfSizeBucket;
30
+ pages?: number;
31
+ migrationBatches?: number;
32
+ resumed?: boolean;
33
+ created?: boolean;
34
+ /**
35
+ * The company whose vault the engine syncs (`sync-core:cmp_*` units). Set by
36
+ * the supervisor from the unit id, never from the protocol line (the
37
+ * validator rejects the key there). hq-pro membership-checks it.
38
+ */
39
+ companyUid?: string;
40
+ }
41
+ /** The company UID of a sync-core engine unit for a company vault, else undefined. */
42
+ export declare function syncPerfCompanyUid(unitId: string): string | undefined;
43
+ export type SyncPerfValidation = {
44
+ ok: true;
45
+ event: SyncPerfEvent;
46
+ }
47
+ /** `reason` names the failed check only; it never echoes a value or an unknown key from the line. */
48
+ | {
49
+ ok: false;
50
+ reason: string;
51
+ };
52
+ /** Validate one parsed protocol event against the v1 perf schema. Never throws. */
53
+ export declare function validateSyncPerfEvent(raw: Record<string, unknown>): SyncPerfValidation;
54
+ /** Rows per POST /v1/usage request (cli-telemetry SYNC_PERF_USAGE_MAX_ROWS). */
55
+ export declare const SYNC_PERF_MAX_BATCH = 50;
56
+ /** Events held while a send is pending; newer events are dropped past this. */
57
+ export declare const SYNC_PERF_MAX_QUEUE = 200;
58
+ /** How long queued events wait for more to join their batch. */
59
+ export declare const SYNC_PERF_FLUSH_DELAY_MS = 30000;
60
+ /** A send still pending after this stops holding the queue (the send itself times out sooner). */
61
+ export declare const SYNC_PERF_SEND_STALL_MS = 60000;
62
+ export interface SyncPerfForwarderDeps {
63
+ /** Sends one batch. May reject or never settle; the forwarder does not wait on it. */
64
+ send: (events: SyncPerfEvent[]) => Promise<void> | void;
65
+ /** False while telemetry is off. Checked when an event arrives and again before each send. */
66
+ enabled: () => boolean;
67
+ setTimeout?: (fn: () => void, ms: number) => unknown;
68
+ clearTimeout?: (handle: unknown) => void;
69
+ flushDelayMs?: number;
70
+ maxBatch?: number;
71
+ maxQueue?: number;
72
+ sendStallMs?: number;
73
+ }
74
+ export interface SyncPerfForwarder {
75
+ /** Queue one validated event. Synchronous and constant time; never throws. */
76
+ push(event: SyncPerfEvent): void;
77
+ /** Drop queued events and clear timers. */
78
+ stop(): void;
79
+ /** Events waiting to be sent (for tests and status). */
80
+ queued(): number;
81
+ /** Events dropped because the queue was full. */
82
+ dropped(): number;
83
+ }
84
+ export declare function createSyncPerfForwarder(deps: SyncPerfForwarderDeps): SyncPerfForwarder;
85
+ //# sourceMappingURL=sync-perf-telemetry.d.ts.map