@indigoai-us/hq-cli 5.345.237 → 5.345.241

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 (115) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/assets/scaffold/core/scripts/hq-delegate-repo.sh +7 -1
  3. package/assets/scaffold/core/scripts/hq-delegate-secrets.sh +95 -20
  4. package/assets/scaffold/core/scripts/hq-delegate-transfer.sh +57 -9
  5. package/dist/command-catalog.generated.d.ts +185 -3
  6. package/dist/command-catalog.generated.js +228 -3
  7. package/dist/command-registration-plan.d.ts +6 -0
  8. package/dist/command-registration-plan.js +1 -0
  9. package/dist/commands/bot.d.ts +2 -0
  10. package/dist/commands/bot.js +23 -0
  11. package/dist/commands/cloud-off-gate.d.ts +2 -1
  12. package/dist/commands/cloud-off-gate.js +17 -4
  13. package/dist/commands/cloud.d.ts +17 -2
  14. package/dist/commands/cloud.js +126 -24
  15. package/dist/commands/core-delegate-w1b.js +35 -10
  16. package/dist/commands/core-delegate.d.ts +2 -1
  17. package/dist/commands/core-delegate.js +207 -48
  18. package/dist/commands/deploy-comments.js +8 -2
  19. package/dist/commands/deploy-events.d.ts +40 -0
  20. package/dist/commands/deploy-events.js +300 -0
  21. package/dist/commands/doctor.d.ts +4 -4
  22. package/dist/commands/doctor.js +2 -2
  23. package/dist/commands/feedback.js +2 -3
  24. package/dist/commands/keyed-sync-pull.d.ts +12 -0
  25. package/dist/commands/keyed-sync-pull.js +151 -0
  26. package/dist/commands/library-add.d.ts +5 -2
  27. package/dist/commands/library-add.js +22 -9
  28. package/dist/commands/mcp-registration.d.ts +4 -18
  29. package/dist/commands/mcp-registration.js +9 -29
  30. package/dist/commands/mesh.d.ts +4 -0
  31. package/dist/commands/mesh.js +25 -5
  32. package/dist/commands/pack-install.d.ts +2 -3
  33. package/dist/commands/pack-install.js +6 -8
  34. package/dist/commands/secrets.d.ts +3 -4
  35. package/dist/commands/secrets.js +3 -20
  36. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +307 -232
  37. package/dist/hq-cloud-sync-runner/package.json +1 -1
  38. package/dist/lib/agent-kit/inbox-state.d.ts +2 -1
  39. package/dist/lib/agent-kit/inbox-state.js +27 -3
  40. package/dist/lib/bot/api.d.ts +2 -1
  41. package/dist/lib/bot/api.js +2 -15
  42. package/dist/lib/bot/promote.d.ts +23 -0
  43. package/dist/lib/bot/promote.js +73 -0
  44. package/dist/lib/bot/promotion-hold-reconcile.d.ts +56 -0
  45. package/dist/lib/bot/promotion-hold-reconcile.js +155 -0
  46. package/dist/lib/capacity/collectors/claude-oauth.d.ts +0 -2
  47. package/dist/lib/capacity/collectors/claude-oauth.js +0 -5
  48. package/dist/lib/core-utils/delegate-helper-paths.d.ts +26 -0
  49. package/dist/lib/core-utils/delegate-helper-paths.js +33 -0
  50. package/dist/lib/daemon/jq-provision.d.ts +63 -0
  51. package/dist/lib/daemon/jq-provision.js +155 -0
  52. package/dist/lib/daemon/lanes-reconcile-guard.d.ts +4 -3
  53. package/dist/lib/daemon/lanes-reconcile-guard.js +4 -4
  54. package/dist/lib/daemon/mesh-owner.d.ts +4 -0
  55. package/dist/lib/daemon/mesh-owner.js +20 -0
  56. package/dist/lib/daemon/ops/policy.d.ts +3 -0
  57. package/dist/lib/daemon/ops/policy.js +32 -4
  58. package/dist/lib/daemon/run.d.ts +17 -1
  59. package/dist/lib/daemon/run.js +24 -3
  60. package/dist/lib/daemon/server.d.ts +6 -0
  61. package/dist/lib/daemon/server.js +5 -0
  62. package/dist/lib/daemon/verified-jq.d.ts +96 -0
  63. package/dist/lib/daemon/verified-jq.js +337 -0
  64. package/dist/lib/doctor/checks/jq.js +16 -0
  65. package/dist/lib/doctor/deep/executor.d.ts +7 -0
  66. package/dist/lib/doctor/deep/executor.js +1 -1
  67. package/dist/lib/doctor/deep/parity.js +1 -27
  68. package/dist/lib/doctor/deep/sandbox.d.ts +2 -2
  69. package/dist/lib/doctor/deep/sandbox.js +3 -19
  70. package/dist/lib/doctor/fix/refresh-sync-handoff.js +52 -21
  71. package/dist/lib/doctor/fixtures/discover.d.ts +2 -0
  72. package/dist/lib/doctor/fixtures/discover.js +1 -1
  73. package/dist/lib/doctor/json-output.d.ts +1 -1
  74. package/dist/lib/doctor/registry.d.ts +6 -7
  75. package/dist/lib/doctor/registry.js +6 -7
  76. package/dist/lib/doctor/report.d.ts +9 -10
  77. package/dist/lib/doctor/report.js +4 -4
  78. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  79. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  80. package/dist/lib/jq/install.d.ts +27 -0
  81. package/dist/lib/jq/install.js +156 -0
  82. package/dist/lib/lanes/outpost-dispatch.d.ts +1 -1
  83. package/dist/lib/lanes/outpost-dispatch.js +13 -13
  84. package/dist/lib/lanes/outpost-pruner-install.js +1 -1
  85. package/dist/lib/mesh/live/daemon/doctor.js +7 -1
  86. package/dist/lib/mesh/live/daemon/install.d.ts +4 -0
  87. package/dist/lib/mesh/live/daemon/install.js +10 -0
  88. package/dist/lib/mesh/live/daemon/run.js +17 -0
  89. package/dist/lib/mesh/live/emit-retry.d.ts +20 -2
  90. package/dist/lib/mesh/live/emit-retry.js +57 -4
  91. package/dist/lib/mesh/live/emit.js +25 -4
  92. package/dist/lib/mesh/live/flush.d.ts +2 -0
  93. package/dist/lib/mesh/live/flush.js +21 -8
  94. package/dist/lib/mesh/live/spool.d.ts +9 -1
  95. package/dist/lib/mesh/live/spool.js +41 -29
  96. package/dist/lib/sync-core/rollout-state.d.ts +9 -1
  97. package/dist/lib/sync-core/rollout-state.js +34 -4
  98. package/dist/lib/windows/jq.d.ts +4 -0
  99. package/dist/lib/windows/jq.js +10 -39
  100. package/dist/lib/workers-registry/index.js +7 -11
  101. package/dist/utils/callback-port-busy.d.ts +2 -2
  102. package/dist/utils/callback-port-busy.js +2 -2
  103. package/dist/utils/cli-network-lifecycle.js +1 -0
  104. package/dist/utils/client-health-contract.d.ts +2 -0
  105. package/dist/utils/client-health-contract.js +1 -1
  106. package/dist/utils/client-health.js +1 -9
  107. package/dist/utils/cognito-config.js +5 -0
  108. package/dist/utils/cognito-session.d.ts +4 -6
  109. package/dist/utils/cognito-session.js +4 -24
  110. package/dist/utils/incomplete-install-error.js +1 -11
  111. package/dist/utils/install-tree-torn.d.ts +11 -0
  112. package/dist/utils/install-tree-torn.js +1 -1
  113. package/dist/utils/resident-package-preload.js +2 -1
  114. package/docs/anywhere-runtime.md +8 -0
  115. package/package.json +9 -9
@@ -14,6 +14,7 @@ import { resolveLiveRoot } from "../utils/hq-roots.js";
14
14
  import { acquireDelegateLock } from "../utils/delegate-lock.js";
15
15
  import { runBundledScript } from "../utils/run-bundled-script.js";
16
16
  import { brainstormFrontmatterSet, brainstormSummary, brainstormTitle } from "./core-delegate-brainstorm.js";
17
+ import { delegateBoardPath, delegateRepoDirectory, secretsSourcePaths } from "../lib/core-utils/delegate-helper-paths.js";
17
18
  export const CORE_NATIVE_DELEGATE_FLAG = "core-native-delegate";
18
19
  const SCRIPT_ASSETS = {
19
20
  resolve: "core/scripts/hq-delegate-resolve.sh",
@@ -54,8 +55,8 @@ const USAGE_TEXT = {
54
55
  // Preserve the companion usage function’s historical raw source lines.
55
56
  pickup: "# hq-core: public\n# hq-delegate-pickup.sh — close the delegation loop with a receipt or a FAILED\n# state (2026-09-07).\n#\n# Why: the delegate pipeline ended at \"sent\", which is a send receipt, not a\n# delivery receipt. Seven delegations sat at sent/building with no way to tell\n# whether the recipient could act. This script adds the two missing states:\n#\n# sent --(evidence)--> picked-up recipient demonstrably has the work\n# sent --(silence past window)--> failed nobody picked it up; sender is told why\n#\n# Evidence, checked in order (any one suffices):\n# 1. --ack \"<text>\" an explicit acknowledgement (DM reply, chat) —\n# recorded verbatim with a timestamp\n# 2. repo branch has a commit by the recipient after sentAt\n# (manifest.repo.path + repo.branch, author email == to.principal)\n# 3. --evidence \"<free text>\" any other proof the operator observed\n#\n# Usage:\n# hq-delegate-pickup.sh --manifest <path> --ack \"<text>\" # record receipt\n# hq-delegate-pickup.sh --manifest <path> --evidence \"<text>\" # record receipt\n# hq-delegate-pickup.sh --manifest <path> --check [--window-hours N] # probe repo; fail if silent past window (default 72)\n# hq-delegate-pickup.sh --manifest <path> --status # print state line\n#\n# Exit 0: picked-up (or already). Exit 5: failed (window elapsed, no evidence).\n# Exit 6: still waiting (inside window, no evidence). Exit 2: usage/precondition.\nset -uo pipefail\n",
56
57
  repo: "hq-delegate-repo.sh — code/branch handover for a delegation: make sure the\nproject's branch exists on the remote, record uncommitted work as NOT\ntransferred, and verify the recipient's repository access read-only.\n\nUsage:\n core/scripts/hq-delegate-repo.sh --manifest <path> [--yes] [--github-user <login>]\n\nBehavior (driven by the manifest's repo{} block; no-op when repo is null):\n - records remote URL and the branch's headSha into the manifest\n - a branch that exists only locally requires confirmation: without --yes\n the helper prints the plan and exits 2; with --yes it pushes via an\n explicitly anchored `git -C <abs path> push -u origin <branch>`\n - dirty/untracked files are captured into repo.dirtyFiles[] and appended\n to BRIEF.md as work NOT transferred — never silently dropped\n - recipient access is checked read-only via gh when --github-user is\n given; otherwise (or on a gh failure) repo.accessVerified stays false\n and the brief says so plainly — the helper never claims unverified access\n - never touches vaultPrefixes[] and never pushes repo content to the vault\n\nEnv: HQ_ROOT — HQ root override (default: resolved from script location)\n",
57
- secrets: "hq-delegate-secrets.sh — grant a delegation recipient access to the secrets\na project needs, BY NAME ONLY. No command in this helper ever reads,\nprints, logs, or interpolates a secret value.\n\nUsage:\n core/scripts/hq-delegate-secrets.sh --manifest <path> [--yes] [--no-secrets]\n [--env-schema <path>]\n\nBehavior:\n - derives required secret NAMES from the project's / repo's .env.schema\n (--env-schema overrides discovery); no schema -> records secrets: []\n and says so plainly rather than guessing at credentials\n - without --yes: prints a full-prose confirmation listing every name and\n the principal, then exits 2 granting nothing — this step is a privilege\n handover and gets its own confirmation, separate from the file grants\n - with --yes: hq secrets share <NAME> --with <principal> --permission read\n per name, then records the names (and only the names) in the manifest\n - --no-secrets: skips everything, records {secrets: [], secretsSkipped: true}\n\nConsumption on the recipient's side is via `hq run` / `hq secrets exec` —\ndocumented in the brief; values never appear in any delegation artifact\n(policy hq-delegate-never-inlines-secrets-or-share-urls).\n",
58
- transfer: "hq-delegate-transfer.sh — make a delegation real everywhere HQ tracks\nownership: board entry, PRD metadata, work mesh, and the project journal.\n\nUsage:\n core/scripts/hq-delegate-transfer.sh --manifest <path>\n\nBehavior (mode \"transfer\"; mode \"share\" skips every mutation):\n 1. companies/<co>/board.json — the project's entry gets owner=<recipient>\n and a bumped updated_at; created (once) if absent. A brainstorm-stage\n entry (status exploring, brainstorm_path set) is matched by\n brainstorm_path and keeps its status.\n 2. prd.json metadata gains owner, delegatedFrom, delegatedAt; for a\n brainstorm-stage project the same three keys land in the\n brainstorm.md frontmatter (owner, delegated_from, delegated_at)\n 3. work-mesh: `done` event closes the delegator's in-progress thread and\n broadcasts the reassignment; silently skipped when the helper is\n unavailable (local/offline installs) — the transfer still succeeds\n 4. a dated \"Delegated\" stanza is appended to the project journal naming\n the recipient, delegation id, and transferred scope\n\nIdempotent: re-running updates owner/timestamps in place — never a\nduplicate board entry, never a duplicated journal stanza.\n\n",
58
+ secrets: "hq-delegate-secrets.sh — grant a delegation recipient access to the secrets\na project needs, BY NAME ONLY. No command in this helper ever reads,\nprints, logs, or interpolates a secret value.\n\nUsage:\n core/scripts/hq-delegate-secrets.sh --manifest <path> [--yes] [--no-secrets]\n [--env-schema <path>]\n\nBehavior:\n - derives required secret NAMES from, in order: --env-schema, the project\n folder's .env.schema, prd.json metadata.secrets, then the repo's\n .env.schema (the widest source, used only when the project declares\n nothing); no source -> records secrets: [] and says so plainly rather\n than guessing at credentials. The plan output names the source.\n - before sharing anything, every name is checked against\n `hq secrets list --company <co>` (names only); one missing name aborts\n the whole step with nothing shared\n - without --yes: prints a full-prose confirmation listing every name and\n the principal, then exits 2 granting nothing — this step is a privilege\n handover and gets its own confirmation, separate from the file grants\n - with --yes: hq secrets --company <co> share <NAME> --with <principal>\n --permission read (agent/person uids use the grant step's grantPrincipal)\n",
59
+ transfer: "hq-delegate-transfer.sh — make a delegation real everywhere HQ tracks\nownership: board entry, PRD metadata, work mesh, and the project journal.\n\nUsage:\n core/scripts/hq-delegate-transfer.sh --manifest <path>\n\nBehavior (mode \"transfer\"; mode \"share\" skips every mutation):\n 1. companies/<co>/board.json — the project's entry gets owner=<recipient>\n and a bumped updated_at; created (once) if absent. A brainstorm-stage\n entry (status exploring, brainstorm_path set) is matched by\n brainstorm_path and keeps its status.\n 2. prd.json metadata gains owner, delegatedFrom, delegatedAt; for a\n brainstorm-stage project the same three keys land in the\n brainstorm.md frontmatter (owner, delegated_from, delegated_at)\n 3. work-mesh: a thread note broadcasts the reassignment and\n `hq mesh project reassign` transfers project ownership and the\n delegator's open stories; manifest workMeshOwnership becomes\n \"confirmed\" only on a server receipt naming the recipient. Silently\n skipped when hq is unavailable — the transfer still succeeds\n 4. a dated \"Delegated\" stanza is appended to the project journal naming\n the recipient, delegation id, and transferred scope\n\nIdempotent: re-running updates owner/timestamps in place — never a\n",
59
60
  };
60
61
  function usage(name) {
61
62
  return USAGE_TEXT[name];
@@ -663,8 +664,8 @@ function runRepo(args, context) {
663
664
  writeErr(`${prefix} manifest repo block has no path\n`);
664
665
  return 1;
665
666
  }
666
- const repoDir = path.join(root, repoRel);
667
- const gitDir = path.join(repoDir, ".git");
667
+ const repoDir = delegateRepoDirectory(root, repoRel);
668
+ const gitDir = `${repoDir}/.git`;
668
669
  let isGitDir = false;
669
670
  try {
670
671
  isGitDir = fs.statSync(gitDir).isDirectory();
@@ -787,6 +788,48 @@ function updateSecretsManifest(file, document, names, skipped, grantedAt) {
787
788
  document.secretsGrantedAt = grantedAt;
788
789
  writeJsonAtomically(file, document);
789
790
  }
791
+ export { delegateBoardPath, delegateRepoDirectory, secretsSourcePaths };
792
+ const SECRET_NAME_PATTERN = /^[A-Z][A-Z0-9_]*(\/[A-Z][A-Z0-9_]+)*$/;
793
+ /**
794
+ * The principal `hq secrets share` accepts for this recipient. Secret ACLs
795
+ * take an email, grp_<id>, out_<id> or @all, so an agent or person uid shares
796
+ * through the principal the grant step recorded: the per-agent delegation
797
+ * group for an agent, the mapped email for a person uid. Empty when none is
798
+ * recorded, so the caller refuses before any share.
799
+ */
800
+ function secretSharePrincipal(principal, document) {
801
+ if (!principal.startsWith("agt_") && !principal.startsWith("prs_"))
802
+ return principal;
803
+ const recorded = jqRawPath(document, "grantPrincipal").replaceAll("\r", "");
804
+ if (principal.startsWith("agt_") && recorded.startsWith("grp_dlg"))
805
+ return recorded;
806
+ if (principal.startsWith("prs_") && /^.+@.+$/s.test(recorded))
807
+ return recorded;
808
+ return "";
809
+ }
810
+ /** prd.json metadata.secrets names, one per line as `jq -r` prints them, sorted and unique. */
811
+ function prdSecretNames(entries) {
812
+ const lines = [];
813
+ for (const entry of entries) {
814
+ const value = isRecord(entry) ? entry.name : entry;
815
+ if (isRecord(entry) && (value === undefined || value === null || value === false))
816
+ continue;
817
+ if (typeof value === "string")
818
+ lines.push(...value.split("\n"));
819
+ else
820
+ lines.push(JSON.stringify(value) ?? "null");
821
+ }
822
+ return [...new Set(lines)].sort();
823
+ }
824
+ function readableSchemaNames(file) {
825
+ try {
826
+ fs.accessSync(file, fs.constants.R_OK);
827
+ }
828
+ catch {
829
+ return undefined;
830
+ }
831
+ return scanSecretFiles(file);
832
+ }
790
833
  function runSecrets(args, context) {
791
834
  const loaded = existingManifest("secrets", args, context);
792
835
  if (loaded.code !== undefined)
@@ -797,85 +840,148 @@ function runSecrets(args, context) {
797
840
  throw new TypeError("Cannot read secrets from a non-object delegation manifest");
798
841
  const options = loaded.parsed.values;
799
842
  const prefix = "hq-delegate-secrets:";
843
+ const die = (message) => { writeErr(`${prefix} ${message}\n`); return 1; };
800
844
  const company = jqRawPath(document, "company");
801
845
  const principal = jqRawPath(document, "to.principal");
802
846
  const project = jqRawPath(document, "project.name");
803
- if (!company) {
804
- writeErr(`${prefix} manifest has no company\n`);
805
- return 1;
806
- }
807
- if (!principal) {
808
- writeErr(`${prefix} manifest has no to.principal\n`);
809
- return 1;
810
- }
847
+ if (!company)
848
+ return die("manifest has no company");
849
+ if (!principal)
850
+ return die("manifest has no to.principal");
851
+ const sharePrincipal = secretSharePrincipal(principal, document);
811
852
  if (options.noSecrets) {
812
853
  updateSecretsManifest(file, document, [], true);
813
854
  writeOut(`${prefix} skipped (--no-secrets) — no credential access granted\n`);
814
855
  return 0;
815
856
  }
816
- let envSchema = String(options.envSchema ?? "");
817
- let names;
857
+ // Narrowest declaration first: --env-schema, the project's .env.schema,
858
+ // prd.json metadata.secrets, then the repo's .env.schema, which names
859
+ // everything the whole repo needs and is used only when the project
860
+ // declares nothing. An unreadable schema stops the step; it never falls
861
+ // through to a wider source.
862
+ const { projectSchema, prdFile, repoSchema } = secretsSourcePaths(context.root, company, project, jqRawPath(document, "repo.path"));
863
+ const envSchema = String(options.envSchema ?? "");
864
+ let sourceKind = "";
865
+ let sourcePath = "";
866
+ let readPath = "";
867
+ let names = [];
868
+ let prdEntries;
869
+ if (!envSchema && !isRegularFile(projectSchema) && isRegularFile(prdFile)) {
870
+ try {
871
+ const prd = readJsonFile(prdFile);
872
+ const declared = isRecord(prd) && isRecord(prd.metadata) ? prd.metadata.secrets : undefined;
873
+ if (Array.isArray(declared) && declared.length > 0)
874
+ prdEntries = declared;
875
+ }
876
+ catch { /* an unreadable or invalid prd.json declares nothing, as jq -e reports */ }
877
+ }
818
878
  if (envSchema) {
819
- envSchema = path.resolve(context.cwd, envSchema);
820
- if (isRegularFile(envSchema))
821
- names = scanSecretFiles(envSchema);
879
+ readPath = path.resolve(context.cwd, envSchema);
880
+ if (!isRegularFile(readPath))
881
+ return die(`--env-schema not found: ${envSchema}`);
882
+ sourceKind = "--env-schema";
883
+ sourcePath = envSchema;
884
+ }
885
+ else if (isRegularFile(projectSchema)) {
886
+ sourceKind = "project .env.schema";
887
+ sourcePath = projectSchema;
888
+ readPath = projectSchema;
889
+ }
890
+ else if (prdEntries) {
891
+ sourceKind = "prd.json metadata.secrets";
892
+ sourcePath = prdFile;
893
+ const lines = prdSecretNames(prdEntries);
894
+ const bad = lines.filter((line) => line !== "" && !SECRET_NAME_PATTERN.test(line));
895
+ if (bad.length > 0) {
896
+ return die(`prd.json metadata.secrets has an entry that is not a secret name: ${bad.join(" ")}— nothing granted`);
897
+ }
898
+ names = lines.filter((line) => line !== "");
822
899
  }
823
900
  else {
824
- const repoRel = jqRawPath(document, "repo.path");
825
- const candidates = [
826
- path.join(context.root, "companies", company, "projects", project, ".env.schema"),
827
- repoRel ? path.join(context.root, repoRel, ".env.schema") : "",
828
- ];
829
- for (const candidate of candidates) {
830
- if (!candidate || !isRegularFile(candidate))
831
- continue;
832
- const candidateNames = scanSecretFiles(candidate);
833
- if (candidateNames === undefined)
834
- continue;
835
- envSchema = candidate;
836
- names = candidateNames;
837
- break;
901
+ if (repoSchema && isRegularFile(repoSchema)) {
902
+ sourceKind = "repo .env.schema";
903
+ sourcePath = repoSchema;
904
+ readPath = repoSchema;
905
+ }
906
+ }
907
+ if (readPath) {
908
+ const scanned = readableSchemaNames(readPath);
909
+ if (scanned === undefined) {
910
+ writeErr(`${prefix} cannot read ${sourcePath} — nothing granted\n`);
911
+ return 2;
912
+ }
913
+ if (scanned.length === 0) {
914
+ // The shell's pipefail exits on grep's status 1 before its empty-name
915
+ // handling branch; leave the manifest untouched to retain that behavior.
916
+ return 1;
838
917
  }
918
+ names = scanned;
839
919
  }
840
- if (!envSchema || names === undefined) {
920
+ if (!sourcePath) {
841
921
  updateSecretsManifest(file, document, [], false);
842
- writeOut(`${prefix} no .env.schema found for this project or its repo — no secret names to grant. If the project needs credentials, add an .env.schema and re-run, or grant them manually with 'hq secrets share'.\n`);
922
+ writeOut(`${prefix} no .env.schema found for this project or its repo, and prd.json declares no metadata.secrets — no secret names to grant. If the project needs credentials, add a project .env.schema (or prd.json metadata.secrets) and re-run, or grant them manually with 'hq secrets share'.\n`);
843
923
  return 0;
844
924
  }
845
925
  if (names.length === 0) {
846
- // The source's pipefail exits on grep's status 1 before its empty-name
847
- // handling branch; leave the manifest untouched to retain that behavior.
848
- return 1;
926
+ updateSecretsManifest(file, document, [], false);
927
+ writeOut(`${prefix} ${sourcePath} declares no secret names — nothing to grant\n`);
928
+ return 0;
849
929
  }
850
- const schemaName = path.basename(envSchema);
930
+ const schemaName = path.basename(sourcePath);
851
931
  writeOut("Secret access handover — this grants the recipient the ability to use these credentials.\n\n");
932
+ writeOut(`Source: ${sourceKind} (${sourcePath})\n`);
933
+ if (sourceKind === "repo .env.schema") {
934
+ writeOut("The project declares no secrets of its own, so the repo-wide schema is used. Narrow it with a project .env.schema or prd.json metadata.secrets if the lane needs fewer.\n");
935
+ }
936
+ writeOut("\n");
852
937
  writeOut(`The following ${names.length} secret name(s), declared by ${schemaName} for project '${project}', will be shared with read permission to '${principal}' in company '${company}':\n\n`);
853
938
  writeOut(`${names.map((name) => ` - ${name}`).join("\n")}\n\n`);
939
+ if (sharePrincipal !== principal) {
940
+ if (sharePrincipal)
941
+ writeOut(`Access flows through '${sharePrincipal}', the principal the grant step resolved for '${principal}'.\n`);
942
+ else
943
+ writeOut(`Access will flow through the principal the grant step records for '${principal}' (run hq-delegate-grant.sh --yes first).\n`);
944
+ writeOut("\n");
945
+ }
854
946
  writeOut("Only the names are granted and recorded; no secret value is read, printed, or transmitted by this step. The recipient consumes them through 'hq run' / 'hq secrets exec'.\n");
855
947
  if (!options.yes) {
856
948
  writeOut("\n");
857
949
  writeErr(`${prefix} confirmation required — re-run with --yes after the user approves (or --no-secrets to skip)\n`);
858
950
  return 2;
859
951
  }
952
+ if (!sharePrincipal) {
953
+ return die(`recipient '${principal}' cannot be a secret-ACL principal and the manifest has no usable grantPrincipal — run hq-delegate-grant.sh --yes first; nothing granted`);
954
+ }
955
+ // Every name must exist in the company vault before any share runs, so a
956
+ // typo or an undeclared secret never leaves a partial grant behind. Names
957
+ // only: `hq secrets list` prints no values.
958
+ const listed = subprocess("hq", ["secrets", "list", "--company", company], context.cwd, { stderr: "ignore" });
959
+ if (listed.code !== 0) {
960
+ return die(`could not list secret names for company '${company}' (hq secrets list failed) — nothing granted`);
961
+ }
962
+ const listedNames = new Set((listed.stdout ?? "").split("\n").map((line) => line.trim().split(/[ \t]+/)[0] ?? "").filter(Boolean));
963
+ const missing = names.filter((name) => !listedNames.has(name));
964
+ if (missing.length > 0) {
965
+ return die(`these name(s) from ${sourceKind} do not exist in company '${company}':${missing.map((name) => ` ${name}`).join("")} — nothing granted; add them with 'hq secrets set' or remove them from ${sourcePath}, then re-run`);
966
+ }
860
967
  const namesDir = fs.mkdtempSync(path.join(os.tmpdir(), "hq-delegate-secret-names-"));
861
968
  const namesFile = path.join(namesDir, "names");
862
969
  let namesFd;
863
970
  try {
864
971
  // The shell's `while read` and each hq child share the same input stream.
865
972
  // A child that reads stdin advances the next loop read just as it does in
866
- // the bundled script; normal hq commands leave the name stream untouched.
973
+ // the staging script; normal hq commands leave the name stream untouched.
867
974
  fs.writeFileSync(namesFile, `${names.join("\n")}\n`, { mode: 0o600 });
868
975
  namesFd = fs.openSync(namesFile, "r");
869
976
  let name = readLineFromFd(namesFd);
870
977
  while (name !== undefined) {
871
- const share = subprocess("hq", ["secrets", "share", name, "--with", principal, "--permission", "read", "--company", company], context.cwd, { stdinFd: namesFd, stdout: "inherit" });
978
+ const share = subprocess("hq", ["secrets", "--company", company, "share", name, "--with", sharePrincipal, "--permission", "read"], context.cwd, { stdinFd: namesFd, stdout: "inherit" });
872
979
  if (share.code !== 0) {
873
980
  if (share.stderr)
874
981
  writeErr(share.stderr);
875
- writeErr(`${prefix} failed to grant '${name}' to '${principal}' — aborting; manifest not updated\n`);
876
- return 1;
982
+ return die(`failed to grant '${name}' to '${sharePrincipal}' — aborting; manifest not updated`);
877
983
  }
878
- writeOut(`${prefix} granted read on '${name}' to '${principal}'\n`);
984
+ writeOut(`${prefix} granted read on '${name}' to '${sharePrincipal}'\n`);
879
985
  name = readLineFromFd(namesFd);
880
986
  }
881
987
  }
@@ -889,6 +995,53 @@ function runSecrets(args, context) {
889
995
  writeOut(`${prefix} ${names.length} secret name(s) granted and recorded (names only)\n`);
890
996
  return 0;
891
997
  }
998
+ /**
999
+ * Move Work Mesh project ownership and the delegator's open stories to the
1000
+ * recipient with `hq mesh project reassign`. "confirmed" only when the server
1001
+ * names the recipient as owner; "not-registered" when the project has no
1002
+ * board; otherwise "unconfirmed" and the transfer continues.
1003
+ */
1004
+ function reassignMeshProject(document, prd, company, project, delegationId, context, prefix) {
1005
+ let toUid = jqRawPaths(document, ["to.uid", "to.personUid", "to.agentUid", "to.principal"]);
1006
+ let meshProject = project;
1007
+ if (prd !== undefined) {
1008
+ const metadata = isRecord(prd) && isRecord(prd.metadata) ? prd.metadata : {};
1009
+ for (const key of ["workMeshProjectId", "projectId"]) {
1010
+ if (jqTruthy(metadata[key])) {
1011
+ meshProject = rawJsonValue(metadata[key]);
1012
+ break;
1013
+ }
1014
+ }
1015
+ }
1016
+ // The mesh directory matches uids, not emails: look up the personUid from
1017
+ // company membership first, and pass the email through if that fails.
1018
+ if (toUid.includes("@")) {
1019
+ const resolved = subprocess("hq", ["people", "resolve", toUid, "--company", company, "--membership-only", "--json"], context.cwd, { stderr: "ignore" });
1020
+ try {
1021
+ const body = readJsonText(resolved.stdout ?? "");
1022
+ const uid = isRecord(body) && body.status === "found" && isRecord(body.person) ? body.person.personUid : undefined;
1023
+ if (typeof uid === "string" && uid.startsWith("prs_"))
1024
+ toUid = uid;
1025
+ }
1026
+ catch { /* not found or not JSON: keep the email */ }
1027
+ }
1028
+ const reassign = subprocess("hq", ["mesh", "project", "reassign", meshProject, "--company", company, "--to", toUid, "--include-open-stories", "--note", `Delegated via /delegate (${delegationId})`, "--json"], context.cwd, { stderr: "pipe" });
1029
+ let confirmed = false;
1030
+ try {
1031
+ const body = readJsonText(reassign.stdout ?? "");
1032
+ const owner = isRecord(body) && typeof body.ownerUid === "string" ? body.ownerUid : "";
1033
+ confirmed = isRecord(body) && body.ok !== false && owner !== "" && (owner === toUid || toUid.includes("@"));
1034
+ }
1035
+ catch { /* no JSON answer: not confirmed */ }
1036
+ if (confirmed)
1037
+ return "confirmed";
1038
+ if (/PROJECT_(VIEW|THREAD)_NOT_FOUND/.test(`${reassign.stdout ?? ""}\n${reassign.stderr ?? ""}`)) {
1039
+ writeErr(`${prefix} project ${meshProject} has no Work Mesh board; local ownership is authoritative; nothing to reassign. To track it on the board, register it with \`hq mesh project register\` (see \`hq mesh project --help\`)\n`);
1040
+ return "not-registered";
1041
+ }
1042
+ writeErr(`${prefix} hq mesh project reassign did not confirm; Work Mesh ownership remains unconfirmed\n`);
1043
+ return "unconfirmed";
1044
+ }
892
1045
  function runTransfer(args, context) {
893
1046
  const loaded = existingManifest("transfer", args, context);
894
1047
  if (loaded.code !== undefined)
@@ -938,7 +1091,7 @@ function runTransfer(args, context) {
938
1091
  const brainstormPath = `companies/${company}/projects/${project}/brainstorm.md`;
939
1092
  const brainstormAbs = path.join(root, brainstormPath);
940
1093
  const projectDir = path.join(root, "companies", company, "projects", project);
941
- const board = path.join(root, "companies", company, "board.json");
1094
+ const board = delegateBoardPath(root, company);
942
1095
  if (stage !== "prd" && stage !== "brainstorm") {
943
1096
  writeErr(`${prefix} manifest project.stage is '${stage}' — expected prd or brainstorm\n`);
944
1097
  return 1;
@@ -1013,11 +1166,17 @@ function runTransfer(args, context) {
1013
1166
  brainstormFrontmatterSet(brainstormAbs, "delegated_from", from);
1014
1167
  brainstormFrontmatterSet(brainstormAbs, "delegated_at", now);
1015
1168
  }
1169
+ let meshOwnership = "unconfirmed";
1016
1170
  if (commandExists("hq", context.cwd)) {
1017
- const sessionId = process.env.HQ_SESSION_ID || "delegate";
1171
+ // The mesh keys session ownership on (company, sessionId). A shared
1172
+ // literal is owned by whoever delegated first in the company, and every
1173
+ // later delegator is rejected with SESSION_OWNER_MISMATCH, so the session
1174
+ // id is unique per delegation.
1175
+ const sessionId = process.env.HQ_SESSION_ID || delegationId;
1018
1176
  const mesh = subprocess("hq", ["mesh", "session", "note", "--enqueue", "--session-id", sessionId, "--seq", "1", "--harness", "claude-code", "--adapter-version", "1.0.0", "--company-slug", company, "--project", project, "--summary", `Delegated to ${display} (${principal}) — delegation ${delegationId}; ownership transferred`], context.cwd, { stdout: "inherit" });
1019
1177
  if (mesh.code !== 0)
1020
1178
  writeErr(`${prefix} mesh note failed; authoritative mesh ownership remains unconfirmed\n`);
1179
+ meshOwnership = reassignMeshProject(document, stage === "prd" ? prd : undefined, company, project, delegationId, context, prefix);
1021
1180
  }
1022
1181
  const journalDir = path.join(projectDir, "journal");
1023
1182
  const journal = path.join(journalDir, "delegations.md");
@@ -1030,16 +1189,16 @@ function runTransfer(args, context) {
1030
1189
  const vaultPrefixes = Array.isArray(prefixesValue) ? prefixesValue : [];
1031
1190
  const scope = vaultPrefixes.map((entry) => jqRawPath(entry, "prefix")).join(", ");
1032
1191
  const ownershipLine = stage === "prd"
1033
- ? "Local board and PRD ownership updated; Work Mesh ownership is unconfirmed. Existing delegator access is unchanged."
1034
- : "Brainstorm-stage project (no PRD yet). Local board and brainstorm.md ownership updated; Work Mesh ownership is unconfirmed. Existing delegator access is unchanged.";
1192
+ ? `Local board and PRD ownership updated; Work Mesh ownership is ${meshOwnership}. Existing delegator access is unchanged.`
1193
+ : `Brainstorm-stage project (no PRD yet). Local board and brainstorm.md ownership updated; Work Mesh ownership is ${meshOwnership}. Existing delegator access is unchanged.`;
1035
1194
  fs.appendFileSync(journal, `\n## ${today} — Delegated to ${display}\n\n- Delegation: \`${delegationId}\`\n- From: ${from}\n- To: ${display} (${principal})\n- Transferred scope: ${scope}\n- ${ownershipLine}\n`);
1036
1195
  }
1037
1196
  document.ownershipTransferredAt = now;
1038
- document.workMeshOwnership = "unconfirmed";
1197
+ document.workMeshOwnership = meshOwnership;
1039
1198
  writeJsonAtomically(file, document);
1040
1199
  const sourceLabel = stage === "prd" ? "PRD" : "brainstorm.md";
1041
1200
  const stageLabel = stage === "prd" ? "" : " (brainstorm stage)";
1042
- writeOut(`${prefix} ownership of '${project}'${stageLabel} transferred to ${display} (${principal}) — local board, ${sourceLabel}, and journal updated; Work Mesh ownership unconfirmed\n`);
1201
+ writeOut(`${prefix} ownership of '${project}'${stageLabel} transferred to ${display} (${principal}) — local board, ${sourceLabel}, and journal updated; Work Mesh ownership ${meshOwnership}\n`);
1043
1202
  return 0;
1044
1203
  }
1045
1204
  function runNativeUnlocked(name, args, context) {
@@ -108,8 +108,13 @@ async function listAction(appNameOrId, options) {
108
108
  if (status !== "open" && status !== "resolved" && status !== "all") {
109
109
  throw new DeployCommentsError("--status must be open, resolved, or all.");
110
110
  }
111
+ if (options.personal && options.company !== undefined) {
112
+ throw new DeployCommentsError("Choose one of --company <slug> or --personal, not both.");
113
+ }
111
114
  const token = await ensureCognitoToken();
112
- const orgHeaders = callerOrgHeaders(options.company);
115
+ // Personal apps live outside every company: the API reads them with the
116
+ // personal scope header, and the active company must not be sent.
117
+ const orgHeaders = options.personal ? { "X-HQ-Deploy-Scope": "personal" } : callerOrgHeaders(options.company);
113
118
  const appId = await resolveAppId(token, appNameOrId, orgHeaders);
114
119
  const result = await listComments(token, appId, orgHeaders);
115
120
  const comments = status === "all"
@@ -178,8 +183,9 @@ export function registerDeployCommentsCommand(deploy) {
178
183
  const comments = deploy.command("comments").description("Read and configure comments on your deployed apps");
179
184
  comments
180
185
  .command("list <app>")
181
- .description("List comments on an app in your org")
186
+ .description("List comments on an app in your org, or on a personal app with --personal")
182
187
  .option("--company <slug>", "use this company instead of the active company")
188
+ .option("--personal", "read a personal app (personal deploy scope) instead of a company app")
183
189
  .option("--json", "print the API comment array as JSON")
184
190
  .option("--status <status>", "filter by open, resolved, or all", "all")
185
191
  .action((app, options) => run(() => listAction(app, options)));
@@ -0,0 +1,40 @@
1
+ import type { Command } from "commander";
2
+ /**
3
+ * Owner side of the hq-deploy site-events loop (US-033). A deployed page records
4
+ * visitor actions with POST /site-events; the owner reads them, acts on them,
5
+ * and answers with a reply the page shows. Event `data` and `actor` are visitor
6
+ * input: they are printed as JSON data and never interpreted.
7
+ */
8
+ interface ScopeOptions {
9
+ company?: string;
10
+ personal?: boolean;
11
+ }
12
+ export interface WatchOptions extends ScopeOptions {
13
+ cursorFile?: string;
14
+ label?: string;
15
+ interval?: string;
16
+ status?: string;
17
+ once?: boolean;
18
+ }
19
+ export interface WatchDeps {
20
+ sleep: (ms: number) => Promise<void>;
21
+ now: () => number;
22
+ emit: (line: string) => void;
23
+ heartbeatMs: number;
24
+ }
25
+ /** One-line JSON with terminal control and bidi characters escaped. */
26
+ export declare function jsonLine(value: unknown): string;
27
+ /**
28
+ * Poll for new events and print one JSON line per result: armed, event,
29
+ * poll_failing (first failure, then every fifth), poll_recovered,
30
+ * cursor_write_failed, heartbeat. The cursor advances only once it is on disk,
31
+ * so after a successful write a restart does not replay those events. When the
32
+ * write fails the cursor stays where it was: the next poll reports the same
33
+ * events again (at least once) together with cursor_write_failed. Each poll opens a
34
+ * fresh sign-in, so a long-running watch survives token refresh. Returns the
35
+ * exit code for --once; otherwise it runs until stopped.
36
+ */
37
+ export declare function watchSiteEvents(appId: string, options: WatchOptions, deps: WatchDeps): Promise<number>;
38
+ export declare function registerDeployEventsCommand(deploy: Command): void;
39
+ export {};
40
+ //# sourceMappingURL=deploy-events.d.ts.map