@indigoai-us/hq-cli 5.345.255 → 5.345.258

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 (63) hide show
  1. package/CHANGELOG.md +72 -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/cloud.js +4 -1
  17. package/dist/commands/core-delegate-w1b.js +107 -16
  18. package/dist/commands/core-delegate.d.ts +7 -0
  19. package/dist/commands/core-delegate.js +66 -2
  20. package/dist/commands/core-handoff-fast.d.ts +1 -1
  21. package/dist/commands/core-handoff-fast.js +2 -2
  22. package/dist/commands/core-handoff.d.ts +3 -1
  23. package/dist/commands/core-handoff.js +1407 -177
  24. package/dist/commands/core-register-project-native.js +1 -1
  25. package/dist/commands/core.js +2 -2
  26. package/dist/commands/files.d.ts +2 -0
  27. package/dist/commands/files.js +34 -5
  28. package/dist/commands/keyed-sync-pull.d.ts +7 -3
  29. package/dist/commands/keyed-sync-pull.js +90 -22
  30. package/dist/commands/team-sync.js +1 -1
  31. package/dist/lib/company-skill-wrapper.js +72 -4
  32. package/dist/lib/daemon/requests.d.ts +14 -1
  33. package/dist/lib/daemon/requests.js +17 -3
  34. package/dist/lib/daemon/run.js +44 -2
  35. package/dist/lib/daemon/supervisor.d.ts +11 -0
  36. package/dist/lib/daemon/supervisor.js +33 -0
  37. package/dist/lib/daemon/sync-perf-telemetry.d.ts +85 -0
  38. package/dist/lib/daemon/sync-perf-telemetry.js +206 -0
  39. package/dist/lib/daemon/windows-relaunch.d.ts +55 -0
  40. package/dist/lib/daemon/windows-relaunch.js +72 -0
  41. package/dist/lib/doctor/checks/replay-recorder.js +3 -3
  42. package/dist/lib/flag-snapshot-file.d.ts +47 -1
  43. package/dist/lib/flag-snapshot-file.js +143 -20
  44. package/dist/lib/hook-engine/coverage.d.ts +82 -8
  45. package/dist/lib/hook-engine/coverage.js +192 -14
  46. package/dist/lib/index-render/companies.js +3 -2
  47. package/dist/lib/index-render/index.js +2 -1
  48. package/dist/lib/index-render/session-scope.d.ts +2 -3
  49. package/dist/lib/index-render/session-scope.js +2 -5
  50. package/dist/lib/index-render/shared.d.ts +7 -0
  51. package/dist/lib/index-render/shared.js +9 -0
  52. package/dist/lib/mesh/live/company-flag-refresh.js +2 -2
  53. package/dist/lib/work-context/windows-acl.d.ts +14 -0
  54. package/dist/lib/work-context/windows-acl.js +26 -0
  55. package/dist/utils/cli-telemetry.d.ts +26 -7
  56. package/dist/utils/cli-telemetry.js +70 -13
  57. package/dist/utils/git.js +1 -1
  58. package/dist/utils/resident-package-preload.js +4 -0
  59. package/dist/utils/sync-perf-telemetry-flag.d.ts +26 -0
  60. package/dist/utils/sync-perf-telemetry-flag.js +32 -0
  61. package/dist/utils/telemetry-opt-out.d.ts +13 -0
  62. package/dist/utils/telemetry-opt-out.js +19 -0
  63. 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) {
@@ -4,9 +4,13 @@ export interface KeyedPullOptions {
4
4
  companySlug?: string;
5
5
  token: string;
6
6
  }
7
+ /** Why a listed key was not written. Counted per reason in the result. */
8
+ export type KeyedPullSkipReason = "unsafe-path" | "directory-marker" | "sync-ignored" | "case-collision" | "overlay-marker" | "forbidden";
9
+ export interface KeyedPullResult {
10
+ filesDownloaded: number;
11
+ skipped: Record<KeyedPullSkipReason, number>;
12
+ }
7
13
  /** No session discovery, journal, deletes or tombstones: absence from an
8
14
  * ACL-filtered inventory never proves deletion. */
9
- export declare function keyedSyncPull(options: KeyedPullOptions): Promise<{
10
- filesDownloaded: number;
11
- }>;
15
+ export declare function keyedSyncPull(options: KeyedPullOptions): Promise<KeyedPullResult>;
12
16
  //# sourceMappingURL=keyed-sync-pull.d.ts.map
@@ -3,12 +3,46 @@ import path from "node:path";
3
3
  import { Transform } from "node:stream";
4
4
  import { pipeline } from "node:stream/promises";
5
5
  import { GetObjectCommand } from "@aws-sdk/client-s3";
6
+ import { createIgnoreFilter, relativePathRejectionReason } from "@indigoai-us/hq-cloud";
6
7
  import { vaultApiFetch } from "../utils/vault-api.js";
7
8
  const fail = (message) => Object.assign(new Error(message), { expected: true });
8
- function safeKey(value) {
9
- return typeof value === "string" && value.length > 0 &&
10
- !/[\\:]/.test(value) && ![...value].some(char => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127) &&
11
- value.split("/").every(part => part.length > 0 && ![".", "..", ".git", ".hq"].includes(part.toLowerCase()) && !/[. ]$/.test(part));
9
+ /** The hq-cloud push/pull path grammar (traversal, absolute, empty segments,
10
+ * backslashes, NUL), plus the stricter local rules this pull has always had:
11
+ * control characters, drive colons and segments ending in a dot or space. */
12
+ function unsafePath(key) {
13
+ return relativePathRejectionReason(key) !== null || key.includes(":") ||
14
+ [...key].some(char => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127) ||
15
+ key.split("/").some(part => /[. ]$/.test(part));
16
+ }
17
+ /** Normal sync never writes `.git` internals or `.hq` reserved files. The
18
+ * ignore filter already excludes both; this keeps them out if an
19
+ * `.hqinclude` re-includes them. */
20
+ /** One object the key may not read: the presign route or its row refused
21
+ * the key (403), or storage itself refused the signed GET (403). A 403 that
22
+ * did not come from storage (a proxy or egress rule), a 401, a 5xx and every
23
+ * other failure stay fatal; a 403 on the list call never reaches here. */
24
+ function objectForbidden(err) {
25
+ if (!err || typeof err !== "object")
26
+ return false;
27
+ const e = err;
28
+ // presignedDownloadError (files-browse.ts) marks storage refusals with fromStorage.
29
+ if ("fromStorage" in e)
30
+ return e.httpStatus === 403 && e.fromStorage === true;
31
+ return e.status === 403 && e.httpStatus === undefined;
32
+ }
33
+ const reservedSegment = (key) => key.split("/").some(part => [".git", ".hq"].includes(part.toLowerCase()));
34
+ /** Classify one listed key the way the normal sync pull planner does:
35
+ * folder markers and invalid key grammar are skipped (never presigned), then
36
+ * the HQ ignore rules decide. `excluded` probes both file and directory
37
+ * hints, as the planner does, because the listing has no kind. */
38
+ function skipReason(key, excluded) {
39
+ if (key.length > 1 && key.endsWith("/") && !unsafePath(key.slice(0, -1)))
40
+ return "directory-marker";
41
+ if (unsafePath(key))
42
+ return "unsafe-path";
43
+ if (reservedSegment(key) || excluded(key))
44
+ return "sync-ignored";
45
+ return null;
12
46
  }
13
47
  /** Require a real directory chain. Hydration runs before workload execution,
14
48
  * in a launcher-owned tree without concurrent writers. */
@@ -54,8 +88,14 @@ export async function keyedSyncPull(options) {
54
88
  if (!companySlug || !/^[a-z0-9][a-z0-9_-]*$/.test(companySlug))
55
89
  throw fail("Keyed pull requires a safe --company-slug from the trusted launcher");
56
90
  const root = path.resolve(options.hqRoot, "companies", companySlug);
57
- const files = [];
58
- const names = new Set();
91
+ const listed = [];
92
+ const skipped = { "unsafe-path": 0, "directory-marker": 0, "sync-ignored": 0, "case-collision": 0, "overlay-marker": 0, forbidden: 0 };
93
+ let shouldSync;
94
+ const excluded = (key) => {
95
+ shouldSync ??= createIgnoreFilter(options.hqRoot);
96
+ const local = path.join(root, key);
97
+ return !shouldSync(local, false) && !shouldSync(local, true);
98
+ };
59
99
  const cursors = new Set();
60
100
  let cursor;
61
101
  for (let page = 0;; page++) {
@@ -81,13 +121,14 @@ export async function keyedSyncPull(options) {
81
121
  throw fail("Keyed pull inventory is incomplete or malformed");
82
122
  for (const value of body.objects) {
83
123
  const row = value;
84
- if (!row || !safeKey(row.key) || !Number.isSafeInteger(row.size) || row.size < 0)
85
- throw fail("Keyed pull inventory contains an unsafe file");
86
- const name = row.key.normalize("NFC").toLowerCase();
87
- if (names.has(name))
88
- throw fail("Keyed pull inventory contains colliding files");
89
- names.add(name);
90
- files.push({ key: row.key, size: row.size });
124
+ if (!row || typeof row.key !== "string" || !Number.isSafeInteger(row.size) || row.size < 0)
125
+ throw fail("Keyed pull inventory is incomplete or malformed");
126
+ const reason = skipReason(row.key, excluded);
127
+ if (reason) {
128
+ skipped[reason]++;
129
+ continue;
130
+ }
131
+ listed.push({ key: row.key, size: row.size });
91
132
  }
92
133
  if (!body.truncated) {
93
134
  if (body.cursor !== undefined && body.cursor !== null && body.cursor !== "")
@@ -99,17 +140,26 @@ export async function keyedSyncPull(options) {
99
140
  cursor = body.cursor;
100
141
  cursors.add(cursor);
101
142
  }
102
- for (const name of names) {
103
- const parts = name.split("/");
104
- for (let i = 1; i < parts.length; i++) {
105
- if (names.has(parts.slice(0, i).join("/")))
106
- throw fail("Keyed pull inventory has a file/directory collision");
107
- }
143
+ // Keys that differ only in case share one file on a case-folding disk.
144
+ // Normal sync has no rule for picking one live spelling, so write neither.
145
+ const fold = (key) => key.normalize("NFC").toLowerCase();
146
+ const spellings = new Map();
147
+ for (const file of listed)
148
+ spellings.set(fold(file.key), (spellings.get(fold(file.key)) ?? 0) + 1);
149
+ const unique = listed.filter(file => spellings.get(fold(file.key)) === 1 || (skipped["case-collision"]++, false));
150
+ // An object whose key is also a parent of listed objects is a directory
151
+ // overlay marker; normal sync skips it and materializes the children.
152
+ const parents = new Set();
153
+ for (const file of unique) {
154
+ const parts = fold(file.key).split("/");
155
+ for (let i = 1; i < parts.length; i++)
156
+ parents.add(parts.slice(0, i).join("/"));
108
157
  }
158
+ const files = unique.filter(file => !parents.has(fold(file.key)) || (skipped["overlay-marker"]++, false));
109
159
  for (const file of files)
110
160
  await destination(path.join(root, file.key));
111
161
  if (files.length === 0)
112
- return { filesDownloaded: 0 };
162
+ return { filesDownloaded: 0, skipped };
113
163
  await directories(root, true);
114
164
  const stage = await fs.mkdtemp(path.join(root, ".keyed-pull-"));
115
165
  try {
@@ -117,9 +167,22 @@ export async function keyedSyncPull(options) {
117
167
  // identity resolution; defer it here to avoid a static command cycle.
118
168
  const { createCompanyPresignClient } = await import("./files-browse.js");
119
169
  const client = createCompanyPresignClient({ token, companyUid: company, companySlug });
170
+ const forbidden = new Set();
120
171
  for (const [index, file] of files.entries()) {
172
+ let result;
173
+ try {
174
+ result = await client.send(new GetObjectCommand({ Bucket: "resolved-server-side", Key: file.key }));
175
+ }
176
+ catch (err) {
177
+ // Not readable with this key: count it, write nothing, keep going.
178
+ if (objectForbidden(err)) {
179
+ forbidden.add(index);
180
+ skipped.forbidden++;
181
+ continue;
182
+ }
183
+ throw fail("Keyed pull download failed; no staged files were applied");
184
+ }
121
185
  try {
122
- const result = await client.send(new GetObjectCommand({ Bucket: "resolved-server-side", Key: file.key }));
123
186
  if (!result.Body)
124
187
  throw fail("Missing body");
125
188
  let size = 0;
@@ -136,13 +199,18 @@ export async function keyedSyncPull(options) {
136
199
  throw fail("Keyed pull download failed; no staged files were applied");
137
200
  }
138
201
  }
202
+ // A key refused on every listed object is the wrong key, not a few private files.
203
+ if (forbidden.size === files.length)
204
+ throw fail("Keyed pull key could not read any listed file");
139
205
  for (const [index, file] of files.entries()) {
206
+ if (forbidden.has(index))
207
+ continue;
140
208
  const target = path.join(root, file.key);
141
209
  await destination(target);
142
210
  await directories(path.dirname(target), true);
143
211
  await fs.rename(path.join(stage, String(index)), target);
144
212
  }
145
- return { filesDownloaded: files.length };
213
+ return { filesDownloaded: files.length - forbidden.size, skipped };
146
214
  }
147
215
  finally {
148
216
  await fs.rm(stage, { recursive: true, force: true });
@@ -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