@indigoai-us/hq-cli 5.345.238 → 5.345.242

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 (206) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/assets/scaffold/core/scripts/hq-delegate-grant.sh +170 -8
  3. package/assets/scaffold/core/scripts/hq-delegate-publish.sh +21 -1
  4. package/assets/scaffold/core/scripts/hq-delegate-repo.sh +7 -1
  5. package/assets/scaffold/core/scripts/hq-delegate-secrets.sh +95 -20
  6. package/assets/scaffold/core/scripts/hq-delegate-transfer.sh +57 -9
  7. package/assets/scaffold/core/scripts/lib/delegate-engine.sh +77 -0
  8. package/dist/command-catalog.generated.d.ts +212 -10
  9. package/dist/command-catalog.generated.js +260 -10
  10. package/dist/command-registration-plan.d.ts +6 -0
  11. package/dist/command-registration-plan.js +1 -0
  12. package/dist/commands/cloud-off-gate.d.ts +9 -8
  13. package/dist/commands/cloud-off-gate.js +41 -40
  14. package/dist/commands/cloud.d.ts +17 -2
  15. package/dist/commands/cloud.js +126 -24
  16. package/dist/commands/core-delegate-w1b.js +333 -27
  17. package/dist/commands/core-delegate.d.ts +2 -1
  18. package/dist/commands/core-delegate.js +209 -48
  19. package/dist/commands/core-handoff.js +1 -1
  20. package/dist/commands/core-job-model-auth.d.ts +95 -0
  21. package/dist/commands/core-job-model-auth.js +247 -0
  22. package/dist/commands/core-job-run-native.js +280 -12
  23. package/dist/commands/core.js +1 -0
  24. package/dist/commands/deploy-comments.js +8 -2
  25. package/dist/commands/deploy-events.d.ts +40 -0
  26. package/dist/commands/deploy-events.js +300 -0
  27. package/dist/commands/doctor.d.ts +4 -4
  28. package/dist/commands/doctor.js +2 -2
  29. package/dist/commands/feedback.js +2 -3
  30. package/dist/commands/files-browse.js +2 -0
  31. package/dist/commands/files.js +4 -0
  32. package/dist/commands/integrations-core.d.ts +11 -0
  33. package/dist/commands/integrations-core.js +15 -1
  34. package/dist/commands/keyed-sync-pull.d.ts +12 -0
  35. package/dist/commands/keyed-sync-pull.js +151 -0
  36. package/dist/commands/lanes-link.js +2 -2
  37. package/dist/commands/lanes-loop.d.ts +2 -2
  38. package/dist/commands/lanes-loop.js +5 -5
  39. package/dist/commands/lanes-questions.js +1 -1
  40. package/dist/commands/lanes-stories.js +1 -1
  41. package/dist/commands/lanes.js +80 -14
  42. package/dist/commands/library-add.d.ts +5 -2
  43. package/dist/commands/library-add.js +22 -9
  44. package/dist/commands/mcp-registration.d.ts +4 -18
  45. package/dist/commands/mcp-registration.js +9 -29
  46. package/dist/commands/mesh.d.ts +4 -0
  47. package/dist/commands/mesh.js +25 -5
  48. package/dist/commands/pack-install.d.ts +2 -3
  49. package/dist/commands/pack-install.js +6 -8
  50. package/dist/commands/rescue.d.ts +3 -2
  51. package/dist/commands/rescue.js +48 -34
  52. package/dist/commands/search.d.ts +6 -0
  53. package/dist/commands/search.js +24 -4
  54. package/dist/commands/secrets.d.ts +3 -4
  55. package/dist/commands/secrets.js +3 -20
  56. package/dist/commands/sources.js +6 -2
  57. package/dist/commands/sync-core.d.ts +8 -0
  58. package/dist/commands/sync-core.js +43 -0
  59. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +1830 -1468
  60. package/dist/hq-cloud-sync-runner/package.json +1 -1
  61. package/dist/lib/bot/api.d.ts +2 -1
  62. package/dist/lib/bot/api.js +2 -15
  63. package/dist/lib/capacity/accounts.d.ts +1 -1
  64. package/dist/lib/capacity/accounts.js +1 -1
  65. package/dist/lib/capacity/collectors/claude-oauth.d.ts +0 -2
  66. package/dist/lib/capacity/collectors/claude-oauth.js +0 -5
  67. package/dist/lib/capacity/freshness.d.ts +1 -1
  68. package/dist/lib/capacity/freshness.js +1 -1
  69. package/dist/lib/capacity/route.js +1 -1
  70. package/dist/lib/core-utils/delegate-helper-paths.d.ts +26 -0
  71. package/dist/lib/core-utils/delegate-helper-paths.js +33 -0
  72. package/dist/lib/daemon/catalog.d.ts +3 -0
  73. package/dist/lib/daemon/hook-requests.d.ts +1 -1
  74. package/dist/lib/daemon/hook-requests.js +4 -2
  75. package/dist/lib/daemon/jq-provision.d.ts +63 -0
  76. package/dist/lib/daemon/jq-provision.js +155 -0
  77. package/dist/lib/daemon/lanes-reconcile-guard.d.ts +4 -3
  78. package/dist/lib/daemon/lanes-reconcile-guard.js +4 -4
  79. package/dist/lib/daemon/mesh-owner.d.ts +4 -0
  80. package/dist/lib/daemon/mesh-owner.js +20 -0
  81. package/dist/lib/daemon/ops/policy.d.ts +3 -0
  82. package/dist/lib/daemon/ops/policy.js +32 -4
  83. package/dist/lib/daemon/run.js +17 -22
  84. package/dist/lib/daemon/server.d.ts +6 -0
  85. package/dist/lib/daemon/server.js +5 -0
  86. package/dist/lib/daemon/verified-jq.d.ts +96 -0
  87. package/dist/lib/daemon/verified-jq.js +337 -0
  88. package/dist/lib/doctor/checks/jq.js +16 -0
  89. package/dist/lib/doctor/deep/executor.d.ts +7 -0
  90. package/dist/lib/doctor/deep/executor.js +1 -1
  91. package/dist/lib/doctor/deep/parity.js +1 -27
  92. package/dist/lib/doctor/deep/sandbox.d.ts +2 -2
  93. package/dist/lib/doctor/deep/sandbox.js +3 -19
  94. package/dist/lib/doctor/fix/refresh-sync-handoff.js +52 -21
  95. package/dist/lib/doctor/fixtures/discover.d.ts +2 -0
  96. package/dist/lib/doctor/fixtures/discover.js +1 -1
  97. package/dist/lib/doctor/json-output.d.ts +1 -1
  98. package/dist/lib/doctor/registry.d.ts +6 -7
  99. package/dist/lib/doctor/registry.js +6 -7
  100. package/dist/lib/doctor/report.d.ts +9 -10
  101. package/dist/lib/doctor/report.js +4 -4
  102. package/dist/lib/environment/work-requirements.d.ts +1 -1
  103. package/dist/lib/environment/work-requirements.js +1 -1
  104. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  105. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  106. package/dist/lib/hook-engine/coverage.js +11 -3
  107. package/dist/lib/hook-engine/git-stop-config.json +510 -510
  108. package/dist/lib/hook-engine/native-precompact-compatibility.json +443 -443
  109. package/dist/lib/hook-engine/native-stop-compatibility.json +359 -359
  110. package/dist/lib/hot-channels/adapters/meetings.d.ts +1 -16
  111. package/dist/lib/hot-channels/adapters/meetings.js +3 -28
  112. package/dist/lib/hot-channels/adapters/slack.d.ts +3 -1
  113. package/dist/lib/hot-channels/adapters/slack.js +4 -1
  114. package/dist/lib/hot-channels/contract.d.ts +14 -0
  115. package/dist/lib/hot-channels/fleet-complete.d.ts +18 -2
  116. package/dist/lib/hot-channels/fleet-complete.js +29 -4
  117. package/dist/lib/hot-channels/meeting-source-ref.d.ts +17 -0
  118. package/dist/lib/hot-channels/meeting-source-ref.js +32 -0
  119. package/dist/lib/hot-channels/prompts/signals-pass.md +6 -1
  120. package/dist/lib/hot-channels/run.d.ts +10 -0
  121. package/dist/lib/hot-channels/run.js +34 -0
  122. package/dist/lib/hot-channels/signals-pass.d.ts +27 -0
  123. package/dist/lib/hot-channels/signals-pass.js +57 -2
  124. package/dist/lib/hot-channels/signals-runtime.js +3 -2
  125. package/dist/lib/jq/install.d.ts +27 -0
  126. package/dist/lib/jq/install.js +156 -0
  127. package/dist/lib/lanes/accounts.js +2 -2
  128. package/dist/lib/lanes/claude-balance.d.ts +6 -0
  129. package/dist/lib/lanes/claude-balance.js +124 -0
  130. package/dist/lib/lanes/grants.js +15 -2
  131. package/dist/lib/lanes/hq-root.d.ts +1 -1
  132. package/dist/lib/lanes/hq-root.js +1 -1
  133. package/dist/lib/lanes/links.d.ts +1 -1
  134. package/dist/lib/lanes/liveness.d.ts +3 -0
  135. package/dist/lib/lanes/liveness.js +61 -7
  136. package/dist/lib/lanes/models.d.ts +1 -1
  137. package/dist/lib/lanes/models.js +1 -1
  138. package/dist/lib/lanes/outpost-dispatch.d.ts +1 -1
  139. package/dist/lib/lanes/outpost-dispatch.js +13 -13
  140. package/dist/lib/lanes/outpost-pruner-install.js +1 -1
  141. package/dist/lib/lanes/questions.d.ts +1 -1
  142. package/dist/lib/lanes/questions.js +2 -2
  143. package/dist/lib/lanes/spawn.js +4 -6
  144. package/dist/lib/lanes/store.d.ts +13 -2
  145. package/dist/lib/lanes/store.js +13 -5
  146. package/dist/lib/lanes/types.d.ts +7 -7
  147. package/dist/lib/lanes/types.js +1 -1
  148. package/dist/lib/lanes/watcher-main.js +1 -1
  149. package/dist/lib/lanes/watcher.d.ts +1 -1
  150. package/dist/lib/lanes/watcher.js +1 -1
  151. package/dist/lib/mesh/live/daemon/doctor.js +7 -1
  152. package/dist/lib/mesh/live/daemon/install.d.ts +4 -0
  153. package/dist/lib/mesh/live/daemon/install.js +10 -0
  154. package/dist/lib/mesh/live/daemon/run.js +17 -0
  155. package/dist/lib/mesh/live/emit-retry.d.ts +20 -2
  156. package/dist/lib/mesh/live/emit-retry.js +57 -4
  157. package/dist/lib/mesh/live/emit.js +25 -4
  158. package/dist/lib/mesh/live/flush.d.ts +2 -0
  159. package/dist/lib/mesh/live/flush.js +21 -8
  160. package/dist/lib/mesh/live/spool.d.ts +9 -1
  161. package/dist/lib/mesh/live/spool.js +41 -29
  162. package/dist/lib/onboarding/cli/onboard.js +5 -0
  163. package/dist/lib/signals/sanitize.d.ts +19 -0
  164. package/dist/lib/signals/sanitize.js +103 -7
  165. package/dist/lib/signals/steps/upload.d.ts +40 -1
  166. package/dist/lib/signals/steps/upload.js +122 -6
  167. package/dist/lib/sync-core/access-refresh.d.ts +29 -0
  168. package/dist/lib/sync-core/access-refresh.js +97 -0
  169. package/dist/lib/sync-core/company-adoption.d.ts +33 -0
  170. package/dist/lib/sync-core/company-adoption.js +223 -0
  171. package/dist/lib/sync-core/engine-home.d.ts +1 -0
  172. package/dist/lib/sync-core/engine-owned.d.ts +13 -0
  173. package/dist/lib/sync-core/engine-owned.js +38 -0
  174. package/dist/lib/sync-core/hand-back.d.ts +17 -0
  175. package/dist/lib/sync-core/hand-back.js +23 -0
  176. package/dist/lib/sync-core/post-apply-reindex.d.ts +33 -0
  177. package/dist/lib/sync-core/post-apply-reindex.js +149 -0
  178. package/dist/lib/sync-core/reconcile.d.ts +10 -0
  179. package/dist/lib/sync-core/reconcile.js +117 -12
  180. package/dist/lib/sync-core/rollout-state.d.ts +11 -1
  181. package/dist/lib/sync-core/rollout-state.js +40 -4
  182. package/dist/lib/vault-sync-switches.d.ts +14 -0
  183. package/dist/lib/vault-sync-switches.js +22 -0
  184. package/dist/lib/windows/jq.d.ts +4 -0
  185. package/dist/lib/windows/jq.js +10 -39
  186. package/dist/lib/workers-registry/index.d.ts +1 -1
  187. package/dist/lib/workers-registry/index.js +8 -12
  188. package/dist/utils/callback-port-busy.d.ts +2 -2
  189. package/dist/utils/callback-port-busy.js +2 -2
  190. package/dist/utils/cli-network-lifecycle.js +1 -0
  191. package/dist/utils/client-health-contract.d.ts +2 -0
  192. package/dist/utils/client-health-contract.js +1 -1
  193. package/dist/utils/client-health.js +1 -9
  194. package/dist/utils/cognito-config.js +5 -0
  195. package/dist/utils/cognito-session.d.ts +4 -6
  196. package/dist/utils/cognito-session.js +4 -24
  197. package/dist/utils/github-tag-fallback.d.ts +16 -0
  198. package/dist/utils/github-tag-fallback.js +126 -0
  199. package/dist/utils/incomplete-install-error.js +1 -11
  200. package/dist/utils/install-tree-torn.d.ts +11 -0
  201. package/dist/utils/install-tree-torn.js +1 -1
  202. package/dist/utils/resident-package-preload.js +2 -1
  203. package/dist/utils/version-report.d.ts +2 -1
  204. package/dist/utils/version-report.js +40 -27
  205. package/docs/anywhere-runtime.md +8 -0
  206. package/package.json +9 -9
@@ -12,6 +12,7 @@ import { matchingSecretPatterns } from "../lib/core-utils/secret-patterns.js";
12
12
  import { describeCoreCommand } from "./core-command-catalog.js";
13
13
  import { commandExists, delegateDiagnosticPath, isRecord, jsonAt, jqFallback, jqRawPath, jqRawPaths, moveFile, readJsonFile, subprocess, writeJsonAtomically, } from "./core-delegate.js";
14
14
  import { resolveLiveRoot } from "../utils/hq-roots.js";
15
+ import { engineOwnedVaultsFromState } from "../lib/sync-core/engine-owned.js";
15
16
  import { ACL_SOURCE_DISPLAY_LABELS } from "../utils/files-browse-acl.js";
16
17
  import { runBundledScript } from "../utils/run-bundled-script.js";
17
18
  import { resolveWindowsBash } from "../utils/windows-bash.js";
@@ -36,7 +37,7 @@ const DESCRIPTIONS = {
36
37
  };
37
38
  const USAGE = {
38
39
  bundle: "hq-delegate-bundle.sh — freeze a project into a portable delegation bundle.\n\nUsage:\n core/scripts/hq-delegate-bundle.sh build \\\n --company <slug> --project <name> --to <principal> \\\n [--to-kind person|agent] [--to-name <display name>] \\\n [--mode transfer|share] [--dry-run]\n\n--dry-run prints the manifest JSON to stdout and writes nothing.\n\nWrites workspace/delegations/<delegationId>/{manifest.json,BRIEF.md} and\n",
39
- grant: "hq-delegate-grant.sh — materialize a delegation's dossier in the vault and\nwrite the ACL grants its manifest declares, verifying each one landed.\n\nUsage:\n core/scripts/hq-delegate-grant.sh --manifest <path> [--yes]\n\nWithout --yes: prints the full grant plan (prefix, principal, permission —\nthe write grant is a privilege escalation and needs explicit confirmation)\nand exits 2 without mutating anything. The caller (the /delegate skill)\nconfirms with the user, then re-invokes with --yes.\n\nWith --yes:\n 1. hq sync push the project directory so the vault prefix exists\n 2. hq files share each manifest vaultPrefix to the recipient\n 3. read each grant back with hq files acl and match grantee + permission\n 4. advance manifest status building -> granted, stamping verifiedAt\n\nDirect ACL grants ONLY — this helper never mints a share-session URL\n(policy hq-delegate-never-inlines-secrets-or-share-urls).\n\nIdempotent: a prefix whose grant already exists is reported, not an error.\nA failed read-back exits non-zero and leaves manifest status unchanged.\n\n",
40
+ grant: "hq-delegate-grant.sh — materialize a delegation's dossier in the vault and\nwrite the ACL grants its manifest declares, verifying each one landed.\n\nUsage:\n core/scripts/hq-delegate-grant.sh --manifest <path> [--yes]\n\nWithout --yes: prints the full grant plan (prefix, principal, permission —\nthe write grant is a privilege escalation and needs explicit confirmation)\nand exits 2 without mutating anything. The caller (the /delegate skill)\nconfirms with the user, then re-invokes with --yes.\n\nWith --yes:\n 1. hq sync push the project directory so the vault prefix exists\n 2. hq files share each manifest vaultPrefix to the recipient\n 3. read each grant back with hq files acl and match grantee + permission\n 4. advance manifest status building -> granted, stamping verifiedAt\n\nWhen the new sync engine owns the company vault on this machine, the CLI\nrefuses `hq sync push`. Step 1 is then skipped, and after the grants the\nhelper waits for the engine to upload the dossier and referenced files\n(lib/delegate-engine.sh) before it advances the status.\n\nDirect ACL grants ONLY — this helper never mints a share-session URL\n(policy hq-delegate-never-inlines-secrets-or-share-urls).\n\nIdempotent: a prefix whose grant already exists is reported, not an error.\nA failed read-back exits non-zero and leaves manifest status unchanged.\n\n",
40
41
  send: "hq-delegate-send.sh — generate the self-sufficient pickup prompt for a\ndelegation and deliver it by DM. The prompt IS the handoff: pasted into a\nfresh agent session on a clean HQ install, it pulls every file on demand\n(hq files get per prefix — no /hq-sync run) and reaches the first\nnext-step with no follow-up question to the delegator.\n\nUsage:\n core/scripts/hq-delegate-send.sh --manifest <path> [--send]\n [--headline <text>] [--note <text>]\n\nWithout --send: (re)generates PICKUP-PROMPT.md next to the manifest and\nprints its path — inspectable, idempotent, sends nothing.\nWith --send: requires manifest status \"verified\" (the US-008 probe must\nhave passed), then delivers ONE `hq dm` with --prompt-file/--details-file\nand advances status to \"sent\", recording the DM eventId.\n\nThe caller (the /delegate skill) humanizes --headline / --note per\ncore/knowledge/public/hq-core/humanize-before-send.md (channel dm, light)\nBEFORE invoking; this helper never rewrites recipients, flags, or the\ngenerated command lines.\n\nFail-closed: the generated prompt is scanned for secret-shaped content and\nshare-session URLs; a match aborts before anything is written or sent\n(policy hq-delegate-never-inlines-secrets-or-share-urls).\n\n",
41
42
  verify: "hq-delegate-verify.sh — prove a delegation can actually be picked up\nbefore anyone is told it is theirs, or print the full plan without\ntouching anything.\n\nUsage (probe mode — after grants, before the DM):\n core/scripts/hq-delegate-verify.sh --manifest <path>\n\nProbes every manifest vaultPrefix with `hq files browse` and requires it\nreachable AND non-empty. All pass -> manifest advances granted -> verified\n(send is gated on this). Any failure -> non-zero, the failing prefix and\nlikely cause named, status left at its last successful value so a re-run\nresumes without re-granting.\n\nUsage (dry-run mode — full plan, zero mutation):\n core/scripts/hq-delegate-verify.sh --dry-run \\\n --company <slug> --project <name> --to <principal> [--mode transfer|share]\n\nPrints recipient, mode, project stage (prd, or brainstorm with the dossier\nfiles and the /plan next step), every prefix with its permission, the secret\nnames an .env.schema would grant, repo + branch, and the DM headline that\nwould be sent. Exits 0. Creates nothing under workspace/delegations/ and\ninvokes no mutating command.\n\n",
42
43
  publish: "usage: --manifest <path>",
@@ -495,6 +496,169 @@ function emitJqParseDiagnostic(input, args, context) {
495
496
  if (diagnostic.length)
496
497
  err(diagnostic);
497
498
  }
499
+ // The dossier files the grant step compares, re-pushes and waits for, in the
500
+ // order the staging helper walks them.
501
+ const DOSSIER_FILES = ["prd.json", "README.md", "brainstorm.md"];
502
+ function isRegularFile(file) {
503
+ try {
504
+ return fs.statSync(file).isFile();
505
+ }
506
+ catch {
507
+ return false;
508
+ }
509
+ }
510
+ function compareCodePoints(left, right) {
511
+ return left < right ? -1 : left > right ? 1 : 0;
512
+ }
513
+ function sha256Hex(bytes) {
514
+ return createHash("sha256").update(bytes).digest("hex");
515
+ }
516
+ function asciiLowercase(value) {
517
+ return value.replace(/[A-Z]/gu, (letter) => letter.toLowerCase());
518
+ }
519
+ /**
520
+ * Maps a prs_ recipient to its one email through `hq people list`, as the
521
+ * staging helper does: the roster's JSON starts at the first line opening with
522
+ * `{` or `[`, and exactly one non-empty email must belong to that personUid.
523
+ */
524
+ function personUidEmail(principal, company, context) {
525
+ const retry = "set to.principal to the recipient's email and re-run";
526
+ const listed = subprocess("hq", ["people", "list", "--company", company, "--json"], context.cwd, { timeout: 120_000 });
527
+ if (listed.code !== 0)
528
+ return { error: `could not list people to map personUid ${principal} to an email; ${retry}` };
529
+ const lines = (listed.stdout ?? "").split("\n");
530
+ const start = lines.findIndex((line) => /^[\t\n\v\f\r ]*[{[]/u.test(line));
531
+ const body = start < 0 ? "" : lines.slice(start).join("\n");
532
+ const unexpected = { error: `people list returned unexpected JSON while mapping ${principal}; ${retry}` };
533
+ const emails = new Set();
534
+ if (body.trim() !== "") {
535
+ let roster;
536
+ try {
537
+ roster = JSON.parse(body);
538
+ }
539
+ catch {
540
+ return unexpected;
541
+ }
542
+ let people;
543
+ if (Array.isArray(roster))
544
+ people = roster;
545
+ else if (isRecord(roster))
546
+ people = roster.people;
547
+ else
548
+ return unexpected;
549
+ if (people === undefined || people === null || people === false)
550
+ return unexpected;
551
+ let rows;
552
+ if (Array.isArray(people))
553
+ rows = people;
554
+ else if (isRecord(people))
555
+ rows = Object.values(people);
556
+ else
557
+ return unexpected;
558
+ for (const row of rows) {
559
+ if (row === null)
560
+ continue;
561
+ if (!isRecord(row))
562
+ return unexpected;
563
+ if (row.personUid !== principal)
564
+ continue;
565
+ if (typeof row.email === "string" && row.email.length > 0)
566
+ emails.add(asciiLowercase(row.email));
567
+ }
568
+ }
569
+ const matches = [...emails].sort(compareCodePoints);
570
+ if (matches.length !== 1 || !matches[0]) {
571
+ return { error: `personUid ${principal} maps to ${matches.length} emails in company '${company}' (need exactly 1); ${retry}` };
572
+ }
573
+ return { email: matches[0] };
574
+ }
575
+ /** True when `hq sync-core status --json` lists the company vault in full mode and not held. */
576
+ function engineOwnsVault(company, context) {
577
+ const status = subprocess("hq", ["sync-core", "status", "--json"], context.cwd, { stderr: "ignore", timeout: 120_000 });
578
+ if (status.code !== 0)
579
+ return false;
580
+ let value;
581
+ try {
582
+ value = JSON.parse(status.stdout ?? "");
583
+ }
584
+ catch {
585
+ return false;
586
+ }
587
+ if (!isRecord(value))
588
+ return false;
589
+ const vaults = (Array.isArray(value.vaults) ? value.vaults : isRecord(value.vaults) ? Object.values(value.vaults) : []).filter((vault) => vault !== null);
590
+ const held = value.held === undefined || value.held === null ? [] : value.held;
591
+ if (!vaults.every((vault) => isRecord(vault) && typeof vault.uid === "string"))
592
+ return false;
593
+ if (!Array.isArray(held) || !held.every((entry) => isRecord(entry) && typeof entry.uid === "string"))
594
+ return false;
595
+ const state = { vaults: vaults, held: held };
596
+ return engineOwnedVaultsFromState(state).companies.has(company.trim().toLowerCase());
597
+ }
598
+ /** Adds company-relative paths to <root>/.hq/pins.json, sorted and unique. */
599
+ function pinForEngine(root, company, paths) {
600
+ const file = path.join(root, ".hq", "pins.json");
601
+ try {
602
+ fs.mkdirSync(path.dirname(file), { recursive: true });
603
+ let pins = { version: 1, pins: {} };
604
+ if (fs.existsSync(file) && fs.statSync(file).size > 0)
605
+ pins = JSON.parse(fs.readFileSync(file, "utf8"));
606
+ if (!isRecord(pins))
607
+ return false;
608
+ if (pins.pins === undefined || pins.pins === null)
609
+ pins.pins = {};
610
+ if (!isRecord(pins.pins))
611
+ return false;
612
+ const existing = pins.pins[company];
613
+ const current = existing === undefined || existing === null || existing === false ? [] : existing;
614
+ if (!Array.isArray(current) || !current.every((entry) => typeof entry === "string"))
615
+ return false;
616
+ pins.pins[company] = [...new Set([...current, ...paths])].sort(compareCodePoints);
617
+ writeJsonAtomically(file, pins, true);
618
+ return true;
619
+ }
620
+ catch {
621
+ return false;
622
+ }
623
+ }
624
+ /**
625
+ * True when every local dossier file matches the vault copy byte for byte and
626
+ * at least one was compared; any failed read falls back to the full push.
627
+ */
628
+ function vaultHasProject(company, project, projectDir, context) {
629
+ let compared = 0;
630
+ for (const dossierFile of DOSSIER_FILES) {
631
+ const local = path.join(projectDir, dossierFile);
632
+ if (!isRegularFile(local))
633
+ continue;
634
+ const remote = subprocess("hq", ["files", "cat", `projects/${project}/${dossierFile}`, "--company", company], context.cwd, { stderr: "ignore", timeout: 120_000 });
635
+ if (remote.code !== 0)
636
+ return false;
637
+ if (sha256Hex(remote.stdoutBytes ?? Buffer.from(remote.stdout ?? "")) !== sha256Hex(fs.readFileSync(local)))
638
+ return false;
639
+ compared += 1;
640
+ }
641
+ return compared > 0;
642
+ }
643
+ /** HQ_DELEGATE_ENGINE_WAIT_SECONDS as whole seconds; 180 when unset or not a whole number (staging lib/delegate-engine.sh). */
644
+ function engineWaitSeconds() {
645
+ const raw = process.env.HQ_DELEGATE_ENGINE_WAIT_SECONDS ?? "";
646
+ return /^[0-9]+$/.test(raw) ? Number(raw) : 180;
647
+ }
648
+ const ENGINE_WAIT_CAUSES = "the engine skips a file an ignore rule matches, a symlink, or a path this machine is not granted";
649
+ /** Polls `hq files cat` until it succeeds and the vault holds exactly the expected bytes. */
650
+ function waitForEngineUpload(company, vaultPath, expected, context) {
651
+ const pollSeconds = Number(process.env.HQ_DELEGATE_ENGINE_POLL_SECONDS || "5");
652
+ const deadline = Date.now() + engineWaitSeconds() * 1000;
653
+ for (;;) {
654
+ const read = subprocess("hq", ["files", "cat", vaultPath, "--company", company], context.cwd, { stderr: "ignore", timeout: 120_000 });
655
+ if (read.code === 0 && sha256Hex(read.stdoutBytes ?? Buffer.from(read.stdout ?? "")) === expected)
656
+ return true;
657
+ if (Date.now() >= deadline)
658
+ return false;
659
+ sleepNative((Number.isFinite(pollSeconds) ? pollSeconds : 5) * 1000);
660
+ }
661
+ }
498
662
  const RESOLVE_FOUND_FILTER = '.status == "found" and (.person.personUid | type == "string") and (.person.companyUid | type == "string")';
499
663
  const RESOLVE_NOT_FOUND_FILTER = '.status == "not_found"';
500
664
  const ACL_FILTER = `
@@ -570,10 +734,24 @@ function runGrant(args, context) {
570
734
  }).map((entry) => jqRawPath(entry, "prefix"));
571
735
  if (badPrefixes.length)
572
736
  return fail("grant", `prefix violates the hq-files prefix conventions (must be company-relative folder form ending in '/'): ${badPrefixes.join("\n")}`);
737
+ // `hq people resolve` matches names and emails only, and `hq files share
738
+ // --with` accepts only email / grp_ / @all. Map a prs_ uid to its one email
739
+ // through the people roster; the membership resolve below must return this
740
+ // exact personUid (staging hq-delegate-grant.sh).
741
+ let resolveKey = principal;
742
+ if (principal.startsWith("prs_")) {
743
+ const mapped = personUidEmail(principal, company, context);
744
+ if ("error" in mapped)
745
+ return fail("grant", mapped.error);
746
+ resolveKey = mapped.email;
747
+ grantPrincipal = mapped.email;
748
+ }
573
749
  out(`Delegation grant plan — company '${company}', recipient '${principal}':\n`);
574
- if (grantPrincipal !== principal)
750
+ if (principal.startsWith("prs_"))
751
+ out(` 0. Person recipient: personUid ${principal} maps to ${grantPrincipal}; grants are shared to that email\n`);
752
+ if (principal.startsWith("agt_"))
575
753
  out(` 0. Agent recipient: grants flow through group ${grantPrincipal} (created if absent, containing exactly ${display})\n`);
576
- out(` 1. Push companies/${company}/projects/${project}/ to the vault (on-conflict keep)\n`);
754
+ out(` 1. Push companies/${company}/projects/${project}/ to the vault (on-conflict keep); where the sync engine owns the vault, pin it in .hq/pins.json and wait for its upload after the grants instead\n`);
577
755
  for (const entry of prefixes)
578
756
  out(` 2. Grant ${jqRawPath(entry, "permission")} on ${jqRawPath(entry, "prefix")} — ${jqRawPath(entry, "reason")}\n`);
579
757
  const writePrefixes = prefixes.map((entry) => jqRawPath(entry, "permission") === "write" ? jqRawPath(entry, "prefix") : "").filter(Boolean);
@@ -585,24 +763,54 @@ function runGrant(args, context) {
585
763
  err("hq-delegate-grant: confirmation required — re-run with --yes after the user approves\n");
586
764
  return 2;
587
765
  }
588
- let result = grantHq(["sync", "push", `companies/${company}/projects/${project}/`, "--company", company, "--on-conflict", "keep"], context, "inherit");
589
- if (result.code !== 0)
590
- return fail("grant", `vault push failed for companies/${company}/projects/${project}/`);
766
+ const hqRoot = context.root ?? context.cwd;
767
+ const projectDir = path.join(hqRoot, "companies", company, "projects", project);
591
768
  const referencePaths = [
592
769
  ...list(getPath(manifest, "knowledge", [])),
593
770
  ...list(getPath(manifest, "policies", [])),
594
771
  ].filter((entry) => typeof entry === "string" && entry.startsWith(`companies/${company}/`));
595
- for (const reference of referencePaths) {
596
- if (fs.existsSync(path.join(context.root ?? context.cwd, reference))) {
597
- result = grantHq(["sync", "push", reference, "--company", company, "--on-conflict", "keep"], context, "inherit");
772
+ // Where the sync engine owns the company vault, the CLI refuses `hq sync
773
+ // push`: pin the project and referenced files instead, then wait for the
774
+ // engine's upload after the grants (staging lib/delegate-engine.sh).
775
+ const engineOwned = engineOwnsVault(company, context);
776
+ let result;
777
+ if (engineOwned) {
778
+ out(`hq-delegate-grant: the sync engine owns the '${company}' vault on this machine — no push; pinning the project and referenced files so the engine uploads them\n`);
779
+ const pins = [`projects/${project}/`, ...referencePaths.map((entry) => entry.slice(`companies/${company}/`.length))];
780
+ if (!pinForEngine(hqRoot, company, pins))
781
+ return fail("grant", `could not add the project to ${shellDisplayPath(hqRoot)}/.hq/pins.json for the sync engine`);
782
+ }
783
+ else if (vaultHasProject(company, project, projectDir, context)) {
784
+ out(`hq-delegate-grant: vault already has companies/${company}/projects/${project}/ (dossier checksums match) — skipping full-folder push\n`);
785
+ }
786
+ else {
787
+ result = grantHq(["sync", "push", `companies/${company}/projects/${project}/`, "--company", company, "--on-conflict", "keep"], context, "inherit");
788
+ if (result.code !== 0)
789
+ return fail("grant", `vault push failed for companies/${company}/projects/${project}/`);
790
+ // on-conflict keep drops the delegator's fresh local edits when the vault
791
+ // copy differs. The delegator owns the dossier, so push it again with overwrite.
792
+ for (const dossierFile of DOSSIER_FILES) {
793
+ if (!isRegularFile(path.join(projectDir, dossierFile)))
794
+ continue;
795
+ const dossierPath = `companies/${company}/projects/${project}/${dossierFile}`;
796
+ result = grantHq(["sync", "push", dossierPath, "--company", company, "--on-conflict", "overwrite"], context, "inherit");
598
797
  if (result.code !== 0)
599
- return fail("grant", `vault push failed for referenced knowledge: ${reference}`);
798
+ return fail("grant", `vault push failed for dossier file ${dossierPath}`);
600
799
  }
601
- else {
602
- err(`hq-delegate-grant: referenced path missing locally (cannot push): ${reference} — the verify probe will fail if it is not already in the vault\n`);
800
+ }
801
+ if (!engineOwned) {
802
+ for (const reference of referencePaths) {
803
+ if (fs.existsSync(path.join(hqRoot, reference))) {
804
+ result = grantHq(["sync", "push", reference, "--company", company, "--on-conflict", "keep"], context, "inherit");
805
+ if (result.code !== 0)
806
+ return fail("grant", `vault push failed for referenced knowledge: ${reference}`);
807
+ }
808
+ else {
809
+ err(`hq-delegate-grant: referenced path missing locally (cannot push): ${reference} — the verify probe will fail if it is not already in the vault\n`);
810
+ }
603
811
  }
604
812
  }
605
- if (grantPrincipal !== principal) {
813
+ if (principal.startsWith("agt_")) {
606
814
  result = grantHq(["groups", "create", grantPrincipal, "--name", `Delegation: ${display}`, "--company", company], context, "inherit");
607
815
  if (result.timedOut)
608
816
  return fail("grant", "group creation timed out; retain this manifest and resume");
@@ -632,7 +840,7 @@ function runGrant(args, context) {
632
840
  expectedType = "company-wide";
633
841
  }
634
842
  else {
635
- const resolved = grantHq(["people", "resolve", principal, "--company", company, "--json", "--membership-only"], context);
843
+ const resolved = grantHq(["people", "resolve", resolveKey, "--company", company, "--json", "--membership-only"], context);
636
844
  let response;
637
845
  try {
638
846
  response = JSON.parse(resolved.stdout ?? "");
@@ -651,8 +859,13 @@ function runGrant(args, context) {
651
859
  expectedType = "person";
652
860
  expectedId = response.person.personUid;
653
861
  expectedCompany = response.person.companyUid;
862
+ if (principal.startsWith("prs_") && expectedId !== principal) {
863
+ return fail("grant", `personUid ${principal} mapped to ${resolveKey}, but membership resolves that email to ${expectedId}; set to.principal to the recipient's email and re-run`);
864
+ }
654
865
  }
655
866
  else if (isRecord(response) && response.status === "not_found") {
867
+ if (principal.startsWith("prs_"))
868
+ return fail("grant", `personUid ${principal} (${resolveKey}) is not an active member of company '${company}'`);
656
869
  if (principal.includes("@")) {
657
870
  expectedType = "email";
658
871
  expectedId = principal.toLowerCase().trim();
@@ -704,18 +917,71 @@ function runGrant(args, context) {
704
917
  return fail("grant", `share timed out for ${prefix}; retain this manifest and resume`);
705
918
  if (shareRc !== 0)
706
919
  err(`hq-delegate-grant: share reported an error on ${prefix}; checking exact grant\n`);
707
- let landed = false;
708
- for (const delay of [0, 1, 2]) {
709
- if (delay)
710
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, delay * 1000);
711
- const after = readAcl(aclPattern);
712
- if (after.ok && after.value?.exists === true && list(after.value.direct).some((row) => isRecord(row) && row.granteeType === expectedType && row.granteeId === expectedId && row.permission === permission)) {
713
- landed = true;
714
- break;
920
+ const grantLanded = (pattern) => {
921
+ for (const delay of [0, 1, 2]) {
922
+ if (delay)
923
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, delay * 1000);
924
+ const after = readAcl(pattern);
925
+ if (after.ok && after.value?.exists === true && list(after.value.direct).some((row) => isRecord(row) && row.granteeType === expectedType && row.granteeId === expectedId && row.permission === permission)) {
926
+ return after.value;
927
+ }
715
928
  }
716
- }
717
- if (!landed)
929
+ return undefined;
930
+ };
931
+ const landedAcl = grantLanded(aclPattern);
932
+ if (!landedAcl)
718
933
  return fail("grant", `grant outcome unconfirmed for ${principal} on ${prefix}; retain this manifest and resume`);
934
+ // Full-transfer mode: a more specific rule under the project prefix (for
935
+ // example projects/<name>/design/* or projects/<name>/design) outranks
936
+ // the root grant, so the recipient would keep the narrower permission
937
+ // there, or have none at all. Grant the same permission on every such
938
+ // rule and verify each one. The ACL tree lists rules that carry grants
939
+ // as `children` and rules with no grants only as `masking`, so both are
940
+ // read; a truncated masking list stops the grant rather than leave an
941
+ // unseen rule ungranted. Only rules under the project prefix are
942
+ // considered, so the outside-project check below is defensive.
943
+ if (jqRawPath(manifest, "mode") === "transfer" && prefix.startsWith(`projects/${project}/`)) {
944
+ if (landedAcl.maskingTruncated === true) {
945
+ return fail("grant", `the ACL tree for ${prefix} lists too many overriding rules to check; grant them by hand, then resume`);
946
+ }
947
+ const underProject = (source) => typeof source === "string"
948
+ && source.startsWith(prefix) && source !== aclPattern;
949
+ const heldAtLeast = new Set();
950
+ const rank = (value) => value === "admin" ? 3 : value === "write" ? 2 : value === "read" ? 1 : 0;
951
+ const holds = (grant) => isRecord(grant) && grant.granteeType === expectedType
952
+ && grant.granteeId === expectedId && rank(grant.permission) >= rank(permission);
953
+ const candidates = new Set();
954
+ for (const child of list(landedAcl.children)) {
955
+ if (!isRecord(child) || !underProject(child.sourcePrefix))
956
+ continue;
957
+ candidates.add(child.sourcePrefix);
958
+ if (holds(child))
959
+ heldAtLeast.add(child.sourcePrefix);
960
+ }
961
+ for (const row of list(landedAcl.masking)) {
962
+ if (!isRecord(row) || !underProject(row.path))
963
+ continue;
964
+ candidates.add(row.path);
965
+ if (list(row.grantees).some(holds))
966
+ heldAtLeast.add(row.path);
967
+ }
968
+ for (const child of [...candidates].sort()) {
969
+ if (!child.startsWith(`projects/${project}/`))
970
+ return fail("grant", `more specific rule ${child} is outside projects/${project}/`);
971
+ if (heldAtLeast.has(child)) {
972
+ out(`hq-delegate-grant: ${principal} already holds ${permission} or higher on more specific rule ${child}\n`);
973
+ continue;
974
+ }
975
+ const childShare = grantHq(["files", "share", child, "--with", grantPrincipal, "--permission", permission, "--company", company], context, "inherit");
976
+ if (childShare.timedOut)
977
+ return fail("grant", `share timed out for more specific rule ${child}; retain this manifest and resume`);
978
+ if (childShare.code !== 0)
979
+ err(`hq-delegate-grant: share reported an error on ${child}; checking exact grant\n`);
980
+ if (!grantLanded(child))
981
+ return fail("grant", `grant outcome unconfirmed for ${principal} on more specific rule ${child}; retain this manifest and resume`);
982
+ out(`hq-delegate-grant: verified ${permission} on more specific rule ${child} for ${principal}\n`);
983
+ }
984
+ }
719
985
  const current = list(manifest.vaultPrefixes)[i];
720
986
  if (!isRecord(current))
721
987
  return fail("grant", "manifest has an invalid vaultPrefixes entry");
@@ -724,6 +990,30 @@ function runGrant(args, context) {
724
990
  writeJsonAtomically(manifestPath, manifest, true);
725
991
  out(`hq-delegate-grant: verified ${permission} on ${prefix} for ${principal}\n`);
726
992
  }
993
+ if (engineOwned) {
994
+ // The pins bring the files into the engine's scope; confirm the exact
995
+ // bytes of the dossier and every referenced company file have landed.
996
+ const companyPrefix = `companies/${company}/`;
997
+ const uploads = new Set();
998
+ for (const dossierFile of DOSSIER_FILES) {
999
+ if (isRegularFile(path.join(projectDir, dossierFile)))
1000
+ uploads.add(`${companyPrefix}projects/${project}/${dossierFile}`);
1001
+ }
1002
+ for (const entry of [...list(getPath(manifest, "project.dossier", [])), ...list(getPath(manifest, "knowledge", [])), ...list(getPath(manifest, "policies", []))]) {
1003
+ if (typeof entry === "string" && entry.startsWith(companyPrefix))
1004
+ uploads.add(entry);
1005
+ }
1006
+ for (const upload of [...uploads].sort(compareCodePoints)) {
1007
+ const local = path.join(hqRoot, upload);
1008
+ if (!isRegularFile(local))
1009
+ continue;
1010
+ const expected = createHash("sha256").update(fs.readFileSync(local)).digest("hex");
1011
+ if (!waitForEngineUpload(company, upload.slice(companyPrefix.length), expected, context)) {
1012
+ return fail("grant", `the sync engine has not uploaded ${upload} after ${engineWaitSeconds()}s (${ENGINE_WAIT_CAUSES}); check 'hq sync-core status', then re-run (grants are idempotent)`);
1013
+ }
1014
+ }
1015
+ out("hq-delegate-grant: the sync engine uploaded the dossier; vault bytes match\n");
1016
+ }
727
1017
  manifest.status = "granted";
728
1018
  manifest.grantPrincipal = grantPrincipal;
729
1019
  manifest.vaultPrefixes = list(manifest.vaultPrefixes).map((entry) => isRecord(entry) ? { ...entry, verifiedAt: now } : entry);
@@ -879,15 +1169,31 @@ function runPublish(args, context, legacyHandoff, nativeLock) {
879
1169
  atomicCopy(stagedBrief, path.join(dest, "BRIEF.md"), 0o600);
880
1170
  atomicCopy(stagedManifest, path.join(dest, "manifest.json"), 0o600);
881
1171
  atomicCopy(stagedManifest, manifestPath, 0o600);
882
- const push = runHq(["sync", "push", `${relative}/`, "--company", company, "--on-conflict", "keep"], context, "inherit");
883
- if (push.code !== 0)
884
- return fail("publish", "final dossier push failed; resume publication");
1172
+ // Where the sync engine owns the company vault it uploads the files and the
1173
+ // read-back below waits for them. Otherwise push only the dossier paths.
1174
+ const engineOwned = engineOwnsVault(company, context);
1175
+ if (!engineOwned) {
1176
+ const pushTargets = [
1177
+ `${relative}/delegation/${id}/`,
1178
+ ...snapshotFiles.filter((file) => fs.existsSync(file)).map((file) => path.relative(root, file).split(path.sep).join("/")),
1179
+ ];
1180
+ for (const target of pushTargets) {
1181
+ const push = runHq(["sync", "push", target, "--company", company, "--on-conflict", "keep"], context, "inherit");
1182
+ if (push.code !== 0)
1183
+ return fail("publish", "final dossier push failed; resume publication");
1184
+ }
1185
+ }
885
1186
  const receipts = { ...hashed };
886
1187
  receipts[`${relative}/delegation/${id}/manifest.json`] = checksum(path.join(dest, "manifest.json"));
887
1188
  const stagedRemote = path.join(stage, "remote");
888
1189
  for (const [file, expected] of Object.entries(receipts)) {
889
1190
  let matched = false;
890
1191
  const cloudPath = file.startsWith(`companies/${company}/`) ? file.slice(`companies/${company}/`.length) : file;
1192
+ if (engineOwned) {
1193
+ if (waitForEngineUpload(company, cloudPath, expected, context))
1194
+ continue;
1195
+ return fail("publish", `the sync engine has not uploaded ${file} (or the vault holds other bytes) after ${engineWaitSeconds()}s (${ENGINE_WAIT_CAUSES}); check 'hq sync-core status', then resume`);
1196
+ }
891
1197
  for (const delay of [0, 1, 2]) {
892
1198
  if (delay)
893
1199
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, delay * 1000);
@@ -2,6 +2,7 @@
2
2
  import * as fs from "node:fs";
3
3
  import { Command } from "commander";
4
4
  import { type SpawnPlan } from "../utils/windows-spawn.js";
5
+ import { delegateBoardPath, delegateRepoDirectory, secretsSourcePaths } from "../lib/core-utils/delegate-helper-paths.js";
5
6
  export declare const CORE_NATIVE_DELEGATE_FLAG = "core-native-delegate";
6
7
  type DelegateName = "resolve" | "pickup" | "repo" | "secrets" | "transfer";
7
8
  export type DelegateContext = {
@@ -55,6 +56,7 @@ export declare function moveFile(source: string, target: string, fileSystem?: Pi
55
56
  export declare function writeJsonAtomically(target: string, value: unknown, siblingTemp?: boolean, fileSystem?: DelegateAtomicWriteFileSystem): void;
56
57
  export declare function delegateDiagnosticPath(argument: string): string;
57
58
  export declare function scanSecretFiles(file: string): string[] | undefined;
59
+ export { delegateBoardPath, delegateRepoDirectory, secretsSourcePaths };
58
60
  export declare function runNative(name: DelegateName, args: string[], context: DelegateContext): number;
59
61
  /** Fast-entry adapter; family gating and shell fallback happen before import. */
60
62
  export declare function runDelegateFast(args: readonly string[], _stdin: string, cwd: string, hqRoot: string | undefined, commandName: string): number;
@@ -74,5 +76,4 @@ export type DelegateRunOptions = {
74
76
  export declare function runDelegateFlow(options: DelegateRunOptions, context: DelegateContext): Promise<number>;
75
77
  /** Register the Wave 1a delegate commands and preserve the shell rollback path. */
76
78
  export declare function registerCoreDelegateCommand(core: Command, registerWave1b?: (delegate: Command, core: Command) => void): void;
77
- export {};
78
79
  //# sourceMappingURL=core-delegate.d.ts.map