@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
@@ -447,39 +447,57 @@ export function hasPendingSpoolWork(root) {
447
447
  }
448
448
  return jsonlHasBytes(workMeshSpoolPath(root));
449
449
  }
450
+ /**
451
+ * Read a claim file's non-empty lines with the streaming reader, so a claim
452
+ * larger than V8's string limit still reads. A claim that vanished reads as
453
+ * empty. Any other failure returns an error, and the caller must keep the file:
454
+ * removing it would delete the events it still holds.
455
+ */
450
456
  function readClaimFileLines(claimPath) {
451
457
  if (!fs.existsSync(claimPath))
452
- return [];
458
+ return { lines: [] };
459
+ const lines = [];
453
460
  try {
454
- const raw = fs.readFileSync(claimPath, "utf8");
455
- const lines = [];
456
- for (const line of raw.split("\n")) {
457
- if (!line.trim())
458
- continue;
459
- lines.push(line);
460
- }
461
- return lines;
461
+ const opened = forEachJsonlLine(claimPath, (line) => {
462
+ if (line.trim())
463
+ lines.push(line);
464
+ });
465
+ if (opened)
466
+ return { lines };
467
+ if (!fs.existsSync(claimPath))
468
+ return { lines: [] };
469
+ return { error: "could not open claim file" };
462
470
  }
463
- catch {
464
- return [];
471
+ catch (err) {
472
+ return { error: (err instanceof Error ? err.message : String(err)).slice(0, 200) };
465
473
  }
466
474
  }
467
- /**
468
- * Recover orphaned claim files: read their lines and return paths to unlink
469
- * after the flush dispositions them.
470
- */
471
- export function recoverOrphanClaims(root) {
472
- const claimPaths = listOrphanClaimFiles(root);
475
+ function recoverClaims(claimFiles) {
473
476
  const lines = [];
474
- for (const p of claimPaths) {
477
+ const claimPaths = [];
478
+ const unreadable = [];
479
+ for (const p of claimFiles) {
480
+ const read = readClaimFileLines(p);
481
+ if ("error" in read) {
482
+ // Not in claimPaths: the flush removes only claims it has read.
483
+ unreadable.push({ claimPath: p, error: read.error });
484
+ continue;
485
+ }
475
486
  // Plain loop: Array#push(...huge) exceeds V8's argument limit (~65k–128k)
476
487
  // and throws RangeError ("Maximum call stack size exceeded").
477
- const orphanLines = readClaimFileLines(p);
478
- for (const line of orphanLines) {
488
+ for (const line of read.lines)
479
489
  lines.push(line);
480
- }
490
+ claimPaths.push(p);
481
491
  }
482
- return { lines, claimPaths };
492
+ return { lines, claimPaths, unreadable };
493
+ }
494
+ /**
495
+ * Recover orphaned claim files: read their lines and return paths to unlink
496
+ * after the flush dispositions them. A claim that cannot be read is listed in
497
+ * `unreadable` and left out of `claimPaths`, so it stays for the next flush.
498
+ */
499
+ export function recoverOrphanClaims(root) {
500
+ return recoverClaims(listOrphanClaimFiles(root));
483
501
  }
484
502
  /** Orphaned claim files of the spool only (never held claims). */
485
503
  export function listOrphanSpoolClaims(root) {
@@ -495,13 +513,7 @@ export function listOrphanSpoolClaims(root) {
495
513
  * HQ Anywhere switched off: held lines and held claims are left where they are.
496
514
  */
497
515
  export function recoverOrphanSpoolClaims(root) {
498
- const claimPaths = listOrphanSpoolClaims(root);
499
- const lines = [];
500
- for (const p of claimPaths) {
501
- for (const line of readClaimFileLines(p))
502
- lines.push(line);
503
- }
504
- return { lines, claimPaths };
516
+ return recoverClaims(listOrphanSpoolClaims(root));
505
517
  }
506
518
  export function removeClaimFile(claimPath) {
507
519
  if (!claimPath)
@@ -8,6 +8,7 @@ import { VaultClient, VaultConflictError, VaultNotFoundError } from "@indigoai-u
8
8
  import { createCompanyFlow, joinCompanyFlow, resumeOnboarding, } from "../orchestrator.js";
9
9
  import { readCheckpoint, getCheckpointPath } from "../checkpoint.js";
10
10
  import { formatProgress, formatSummary, formatError } from "./prompts.js";
11
+ import { raiseAccessRefresh } from "../../sync-core/access-refresh.js";
11
12
  const CREATE_STEPS = 6;
12
13
  const JOIN_STEPS = 6;
13
14
  /**
@@ -63,6 +64,9 @@ export async function runOnboardCli(options) {
63
64
  }
64
65
  log(`Resuming ${checkpoint.mode} flow from step ${checkpoint.completedSteps.length + 1}...`);
65
66
  const result = await resumeOnboarding(config, onProgress);
67
+ if (checkpoint.mode === "join-company") {
68
+ raiseAccessRefresh({ companyUid: result.companyUid, companySlug: result.companySlug });
69
+ }
66
70
  log("");
67
71
  log(formatSummary(result));
68
72
  return { success: true, result };
@@ -118,6 +122,7 @@ export async function runOnboardCli(options) {
118
122
  log("Joining company via invite...");
119
123
  log("");
120
124
  const result = await joinCompanyFlow(input, config, onProgress);
125
+ raiseAccessRefresh({ companyUid: result.companyUid, companySlug: result.companySlug });
121
126
  log("");
122
127
  log(formatSummary(result));
123
128
  return { success: true, result };
@@ -9,6 +9,13 @@ export declare const MAX_CONTENT_CHARS = 600;
9
9
  export declare const MAX_CITATIONS = 8;
10
10
  export declare const MAX_ENTITIES = 16;
11
11
  export declare const MAX_FIELD_CHARS = 256;
12
+ /**
13
+ * A meeting signal's `source_ref`: the transcript path
14
+ * `sources/meetings/<file>.md`, or the hot-channel alias `meeting:<id>` the
15
+ * signals pass writes (same character set as the pass accepts). The alias id
16
+ * is a bot or transcript id, not a file name: `resolveMeetingAlias` finds the
17
+ * transcript that carries it.
18
+ */
12
19
  export declare const MEETING_SOURCE_RE: RegExp;
13
20
  export interface SanitizedContributionV1 {
14
21
  schema: string;
@@ -81,6 +88,16 @@ export interface AudienceReceiptLocal {
81
88
  }
82
89
  /** Highest-version audience receipt for a meeting, read from the local company tree. */
83
90
  export declare function readAudienceReceipt(companyRoot: string, meetingId: string): AudienceReceiptLocal | null;
91
+ /** `meeting:<id>` alias -> the transcript file names (without `.md`) in `sources/meetings/` that carry it. */
92
+ export type MeetingAliasIndex = ReadonlyMap<string, readonly string[]>;
93
+ /**
94
+ * Index the company's meeting transcripts by the `meeting:<id>` alias the
95
+ * meetings hot channel gives each one (`transcriptSignalSourceRef`: the
96
+ * `recall_bot_id`, else the transcript id) and by any `signal_source_ref` the
97
+ * file itself records. Built once per upload run. Landed hot-signal pointers
98
+ * are skipped, the same as the meetings adapter skips them.
99
+ */
100
+ export declare function buildMeetingAliasIndex(companyRoot: string): MeetingAliasIndex;
84
101
  export interface SanitizeInput {
85
102
  /** Absolute path of `companies/{co}`. */
86
103
  companyRoot: string;
@@ -90,6 +107,8 @@ export interface SanitizeInput {
90
107
  companyUid: string;
91
108
  projectionState: string;
92
109
  projectionWatermark: string;
110
+ /** The run's transcript alias index, built on first use; built from `companyRoot` when absent. */
111
+ meetingIndex?: () => MeetingAliasIndex;
93
112
  }
94
113
  export type SanitizeResult = {
95
114
  ok: true;
@@ -31,6 +31,8 @@ import { createHash } from "node:crypto";
31
31
  import * as fs from "node:fs";
32
32
  import * as path from "node:path";
33
33
  import yaml from "js-yaml";
34
+ import { HOT_SIGNAL_ORIGIN } from "../hot-channels/landing.js";
35
+ import { transcriptIdOf, transcriptSignalSourceRef } from "../hot-channels/meeting-source-ref.js";
34
36
  export const SANITIZED_CONTRIBUTION_SCHEMA = "sanitized-contribution.v1";
35
37
  export const SANITIZER_VERSION = "local-sanitizer/v1";
36
38
  export const SCHEMA_VERSION = "local-signal/v1";
@@ -55,7 +57,14 @@ const MAX_ENTITY_CHARS = 200;
55
57
  const UID_RE = /^[A-Za-z0-9_-]{1,128}$/;
56
58
  const SEGMENT_RE = /^[A-Za-z0-9_.-]{1,256}$/;
57
59
  const OBSERVATION_ID_RE = /^[0-9a-f]{64}$/;
58
- export const MEETING_SOURCE_RE = /^sources\/meetings\/([^/\\]+)\.md$/;
60
+ /**
61
+ * A meeting signal's `source_ref`: the transcript path
62
+ * `sources/meetings/<file>.md`, or the hot-channel alias `meeting:<id>` the
63
+ * signals pass writes (same character set as the pass accepts). The alias id
64
+ * is a bot or transcript id, not a file name: `resolveMeetingAlias` finds the
65
+ * transcript that carries it.
66
+ */
67
+ export const MEETING_SOURCE_RE = /^(?:sources\/meetings\/([^/\\]+)\.md|meeting:([A-Za-z0-9._-]+))$/;
59
68
  /** Same key set as hq-pro CONTRIBUTION_KEYS. */
60
69
  export const CONTRIBUTION_KEYS = new Set([
61
70
  "schema", "sanitizerVersion", "observationId", "signalType", "content", "citations", "sourceRef",
@@ -259,14 +268,14 @@ export function parseLocationMs(v) {
259
268
  const h = m[1] ? Number(m[1]) : 0;
260
269
  return Math.round((h * 3600 + Number(m[2]) * 60 + Number(m[3])) * 1000);
261
270
  }
262
- function citationRanges(raw, sourceRef) {
271
+ function citationRanges(raw, sourceRefs) {
263
272
  if (!Array.isArray(raw))
264
273
  return [];
265
274
  const out = [];
266
275
  for (const c of raw) {
267
276
  if (!isRecord(c))
268
277
  continue;
269
- if (typeof c.source_ref === "string" && c.source_ref !== sourceRef)
278
+ if (typeof c.source_ref === "string" && !sourceRefs.includes(c.source_ref))
270
279
  continue;
271
280
  const start = Number.isInteger(c.start_ms) ? c.start_ms : Number.isInteger(c.startMs) ? c.startMs : parseLocationMs(c.location ?? c.timestamp);
272
281
  if (start === null || start < 0)
@@ -332,6 +341,76 @@ export function readAudienceReceipt(companyRoot, meetingId) {
332
341
  return null;
333
342
  }
334
343
  }
344
+ /** Bytes read from the top of a transcript when looking for its frontmatter. */
345
+ const FRONTMATTER_HEAD_BYTES = 64 * 1024;
346
+ /**
347
+ * The first FRONTMATTER_HEAD_BYTES of a file, so the frontmatter can be parsed
348
+ * without reading the transcript body. A block that does not close within
349
+ * that window parses as no frontmatter. Null when the file cannot be read.
350
+ */
351
+ function readFrontmatterHead(file) {
352
+ let fd;
353
+ try {
354
+ fd = fs.openSync(file, "r");
355
+ }
356
+ catch {
357
+ return null;
358
+ }
359
+ try {
360
+ const buf = Buffer.alloc(FRONTMATTER_HEAD_BYTES);
361
+ const n = fs.readSync(fd, buf, 0, buf.length, 0);
362
+ return buf.subarray(0, n).toString("utf8");
363
+ }
364
+ catch {
365
+ return null;
366
+ }
367
+ finally {
368
+ fs.closeSync(fd);
369
+ }
370
+ }
371
+ const SIGNAL_SOURCE_ALIAS_RE = /^meeting:[A-Za-z0-9._-]+$/;
372
+ /**
373
+ * Index the company's meeting transcripts by the `meeting:<id>` alias the
374
+ * meetings hot channel gives each one (`transcriptSignalSourceRef`: the
375
+ * `recall_bot_id`, else the transcript id) and by any `signal_source_ref` the
376
+ * file itself records. Built once per upload run. Landed hot-signal pointers
377
+ * are skipped, the same as the meetings adapter skips them.
378
+ */
379
+ export function buildMeetingAliasIndex(companyRoot) {
380
+ const dir = path.join(companyRoot, "sources", "meetings");
381
+ const index = new Map();
382
+ let names;
383
+ try {
384
+ names = fs.readdirSync(dir);
385
+ }
386
+ catch {
387
+ return index;
388
+ }
389
+ for (const name of names.sort()) {
390
+ if (!name.endsWith(".md") || name.startsWith(".") || name.startsWith("_"))
391
+ continue;
392
+ const head = readFrontmatterHead(path.join(dir, name));
393
+ if (head === null)
394
+ continue;
395
+ const fm = splitFrontmatter(head).frontmatter;
396
+ if (fm.origin === HOT_SIGNAL_ORIGIN)
397
+ continue;
398
+ const base = name.slice(0, -".md".length);
399
+ const aliases = new Set();
400
+ const transcriptId = transcriptIdOf(fm);
401
+ const alias = transcriptId === undefined ? undefined : transcriptSignalSourceRef(fm, transcriptId);
402
+ if (alias !== undefined)
403
+ aliases.add(alias);
404
+ if (typeof fm.signal_source_ref === "string" && SIGNAL_SOURCE_ALIAS_RE.test(fm.signal_source_ref))
405
+ aliases.add(fm.signal_source_ref);
406
+ for (const a of aliases) {
407
+ const list = index.get(a) ?? [];
408
+ list.push(base);
409
+ index.set(a, list);
410
+ }
411
+ }
412
+ return index;
413
+ }
335
414
  const SIGNAL_REL_RE = /^signals\/(?:@([^/]+)\/)?([a-z_]+)\/([^/]+)\.md$/;
336
415
  export function sanitizeSignal(input) {
337
416
  const m = SIGNAL_REL_RE.exec(input.signalRel);
@@ -351,11 +430,27 @@ export function sanitizeSignal(input) {
351
430
  const signalType = (typeof fm.type === "string" ? fm.type : folderType);
352
431
  if (!SIGNAL_TYPES.includes(signalType) || signalType !== folderType)
353
432
  return fail("unknown-type");
354
- const sourceRef = typeof fm.source_ref === "string" ? fm.source_ref : "";
355
- const meeting = MEETING_SOURCE_RE.exec(sourceRef);
433
+ const originalSourceRef = typeof fm.source_ref === "string" ? fm.source_ref : "";
434
+ const meeting = MEETING_SOURCE_RE.exec(originalSourceRef);
356
435
  if (!meeting)
357
436
  return fail("non-meeting-source");
358
- const receipt = readAudienceReceipt(input.companyRoot, meeting[1]);
437
+ // A `meeting:<id>` alias names a bot or transcript id, never a file: find
438
+ // the one transcript that carries it. Then both forms use the same source,
439
+ // receipt, audience check and observation identity.
440
+ let meetingFile;
441
+ if (meeting[1] !== undefined) {
442
+ meetingFile = meeting[1];
443
+ }
444
+ else {
445
+ const files = (input.meetingIndex?.() ?? buildMeetingAliasIndex(input.companyRoot)).get(originalSourceRef) ?? [];
446
+ if (files.length === 0)
447
+ return fail("meeting-not-found");
448
+ if (files.length > 1)
449
+ return fail("ambiguous-meeting");
450
+ meetingFile = files[0];
451
+ }
452
+ const sourceRef = `sources/meetings/${meetingFile}.md`;
453
+ const receipt = readAudienceReceipt(input.companyRoot, meetingFile);
359
454
  if (!receipt)
360
455
  return fail("no-audience-receipt");
361
456
  if (!receipt.invitedMemberUids.includes(input.memberUid))
@@ -374,7 +469,8 @@ export function sanitizeSignal(input) {
374
469
  catch {
375
470
  // Source not on disk: the receipt's frozen digest stands.
376
471
  }
377
- const citations = citationRanges(fm.citations, sourceRef);
472
+ // A citation may name the meeting by the same reference the signal uses.
473
+ const citations = citationRanges(fm.citations, [...new Set([sourceRef, originalSourceRef])]);
378
474
  if (citations.length === 0)
379
475
  return fail("no-timestamps");
380
476
  const rawContent = typeof fm.canonical_content === "string" && fm.canonical_content.trim()
@@ -21,11 +21,36 @@ export interface UploadDeps {
21
21
  /** Reads one bucket-relative key from the company vault; null when absent. */
22
22
  readVaultObject(session: UploadSession, company: string, key: string): Promise<string | null>;
23
23
  }
24
+ /** A signal skipped for a reason that can clear without the file changing. */
25
+ export interface PendingSkip {
26
+ reason: string;
27
+ firstSkippedAt: string;
28
+ attempts: number;
29
+ }
24
30
  export interface UploadWatermark {
25
31
  lastUploadedAt: string | null;
26
32
  uploaded: string[];
27
33
  rejected: Record<string, string>;
34
+ /**
35
+ * Company-relative signal paths skipped for a retryable reason. They are
36
+ * offered again on later runs whatever the watermark says, until they upload,
37
+ * turn into a permanent skip, or have waited MAX_PENDING_AGE_MS since the
38
+ * first skip. The watermark itself never waits for them.
39
+ */
40
+ pending: Record<string, PendingSkip>;
28
41
  }
42
+ /** How long a retryable skip is tried before it is dropped (time only, however often the step runs). */
43
+ export declare const MAX_PENDING_AGE_MS: number;
44
+ /**
45
+ * A guard on the pending list's size that applies to NEW entries only. Entries
46
+ * already on the list are never dropped by count, only by age. A retryable
47
+ * skip that arrives while the list is full is not added: it is reported in
48
+ * the step detail as `pendingFull` and the watermark moves past it, the same
49
+ * as a permanent skip. Editing the signal file offers it again.
50
+ */
51
+ export declare const MAX_PENDING = 10000;
52
+ /** Most paths listed by name in the step detail per list (`expiredPaths`, `pendingFullPaths`). */
53
+ export declare const MAX_LISTED_PATHS = 200;
29
54
  export declare function contributionRoute(company: string): string;
30
55
  export declare function watermarkRel(company: string, memberUid: string): string;
31
56
  export declare function readWatermark(hqRoot: string, company: string, memberUid: string): UploadWatermark;
@@ -35,8 +60,22 @@ export interface SignalCandidate {
35
60
  sha: string;
36
61
  mtimeMs: number;
37
62
  }
38
- /** Promoted signals for a company not yet uploaded or rejected, newer than the watermark. */
63
+ /**
64
+ * Promoted signals for a company not yet uploaded or rejected: those newer
65
+ * than the watermark, plus the pending retryable skips that still exist.
66
+ */
39
67
  export declare function listSignalCandidates(hqRoot: string, company: string, wm: UploadWatermark): SignalCandidate[];
68
+ /**
69
+ * Local sanitize skips that can pass on a later run without the signal file
70
+ * changing: the meeting transcript or its audience receipt has not synced
71
+ * yet, or the file could not be read this time. These go on the pending list
72
+ * (UploadWatermark.pending) instead of holding the watermark. Every other
73
+ * skip is permanent for this file: not being in the meeting's audience, a
74
+ * defect in the signal file itself (path, type, citations, content), or a
75
+ * source the meetings route does not take. Editing the file moves its mtime
76
+ * past the watermark, so it is offered again then.
77
+ */
78
+ export declare const RETRYABLE_SKIP_REASONS: ReadonlySet<string>;
40
79
  export declare const defaultUploadDeps: UploadDeps;
41
80
  export declare function createUploadStep(overrides?: Partial<UploadDeps>): SignalsStep;
42
81
  export declare const uploadStep: SignalsStep;
@@ -23,8 +23,37 @@
23
23
  import * as fs from "node:fs";
24
24
  import * as path from "node:path";
25
25
  import { refreshMemberProjection, triggerProjectionExport, memberProjectionPrefix } from "../projection.js";
26
- import { sanitizeSignal, MEETING_SOURCE_RE, splitFrontmatter } from "../sanitize.js";
26
+ import { buildMeetingAliasIndex, sanitizeSignal, MEETING_SOURCE_RE, splitFrontmatter } from "../sanitize.js";
27
27
  const MAX_TRACKED_SHAS = 5000;
28
+ /** How long a retryable skip is tried before it is dropped (time only, however often the step runs). */
29
+ export const MAX_PENDING_AGE_MS = 14 * 24 * 60 * 60 * 1000;
30
+ /**
31
+ * A guard on the pending list's size that applies to NEW entries only. Entries
32
+ * already on the list are never dropped by count, only by age. A retryable
33
+ * skip that arrives while the list is full is not added: it is reported in
34
+ * the step detail as `pendingFull` and the watermark moves past it, the same
35
+ * as a permanent skip. Editing the signal file offers it again.
36
+ */
37
+ export const MAX_PENDING = 10_000;
38
+ /** Most paths listed by name in the step detail per list (`expiredPaths`, `pendingFullPaths`). */
39
+ export const MAX_LISTED_PATHS = 200;
40
+ const PENDING_REL_RE = /^signals\/(?:@[^/]+\/)?[a-z_]+\/[^/]+\.md$/;
41
+ function readPending(raw) {
42
+ const out = {};
43
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
44
+ return out;
45
+ for (const [rel, v] of Object.entries(raw)) {
46
+ if (!PENDING_REL_RE.test(rel) || rel.includes(".."))
47
+ continue;
48
+ const p = v;
49
+ if (!p || typeof p.reason !== "string" || typeof p.firstSkippedAt !== "string" || Number.isNaN(Date.parse(p.firstSkippedAt)))
50
+ continue;
51
+ if (typeof p.attempts !== "number" || !Number.isInteger(p.attempts) || p.attempts < 1)
52
+ continue;
53
+ out[rel] = { reason: p.reason, firstSkippedAt: p.firstSkippedAt, attempts: p.attempts };
54
+ }
55
+ return out;
56
+ }
28
57
  export function contributionRoute(company) {
29
58
  return `/v1/files/contributions/company/${encodeURIComponent(company)}/meetings`;
30
59
  }
@@ -38,13 +67,17 @@ export function readWatermark(hqRoot, company, memberUid) {
38
67
  lastUploadedAt: typeof raw.lastUploadedAt === "string" ? raw.lastUploadedAt : null,
39
68
  uploaded: Array.isArray(raw.uploaded) ? raw.uploaded.filter((s) => typeof s === "string") : [],
40
69
  rejected: raw.rejected && typeof raw.rejected === "object" ? raw.rejected : {},
70
+ pending: readPending(raw.pending),
41
71
  };
42
72
  }
43
73
  catch {
44
- return { lastUploadedAt: null, uploaded: [], rejected: {} };
74
+ return { lastUploadedAt: null, uploaded: [], rejected: {}, pending: {} };
45
75
  }
46
76
  }
47
- /** Promoted signals for a company not yet uploaded or rejected, newer than the watermark. */
77
+ /**
78
+ * Promoted signals for a company not yet uploaded or rejected: those newer
79
+ * than the watermark, plus the pending retryable skips that still exist.
80
+ */
48
81
  export function listSignalCandidates(hqRoot, company, wm) {
49
82
  const companyRoot = path.join(hqRoot, "companies", company);
50
83
  const signalsRoot = path.join(companyRoot, "signals");
@@ -77,8 +110,38 @@ export function listSignalCandidates(hqRoot, company, wm) {
77
110
  }
78
111
  };
79
112
  walk(signalsRoot, 0);
113
+ const listed = new Set(out.map((c) => c.rel));
114
+ for (const rel of Object.keys(wm.pending)) {
115
+ if (listed.has(rel))
116
+ continue;
117
+ const sha = path.posix.basename(rel, ".md");
118
+ if (done.has(sha))
119
+ continue;
120
+ let mtimeMs;
121
+ try {
122
+ const st = fs.statSync(path.join(companyRoot, ...rel.split("/")));
123
+ if (!st.isFile())
124
+ continue;
125
+ mtimeMs = st.mtimeMs;
126
+ }
127
+ catch {
128
+ continue;
129
+ }
130
+ out.push({ rel, sha, mtimeMs });
131
+ }
80
132
  return out.sort((a, b) => a.mtimeMs - b.mtimeMs || a.rel.localeCompare(b.rel));
81
133
  }
134
+ /**
135
+ * Local sanitize skips that can pass on a later run without the signal file
136
+ * changing: the meeting transcript or its audience receipt has not synced
137
+ * yet, or the file could not be read this time. These go on the pending list
138
+ * (UploadWatermark.pending) instead of holding the watermark. Every other
139
+ * skip is permanent for this file: not being in the meeting's audience, a
140
+ * defect in the signal file itself (path, type, citations, content), or a
141
+ * source the meetings route does not take. Editing the file moves its mtime
142
+ * past the watermark, so it is offered again then.
143
+ */
144
+ export const RETRYABLE_SKIP_REASONS = new Set(["no-audience-receipt", "meeting-not-found", "unreadable"]);
82
145
  /** A 422 rejection that can pass on a later run (the source or receipt is not in the vault yet). */
83
146
  function isRetryableRejection(parsed) {
84
147
  return Array.isArray(parsed.reasons) && parsed.reasons.length > 0 && parsed.reasons.every((r) => r === "source_unavailable");
@@ -203,6 +266,18 @@ export function createUploadStep(overrides = {}) {
203
266
  const wm = readWatermark(ctx.hqRoot, ctx.company, session.memberUid);
204
267
  const candidates = listSignalCandidates(ctx.hqRoot, ctx.company, wm);
205
268
  const companyRoot = path.join(ctx.hqRoot, "companies", ctx.company);
269
+ // A pending entry that is not a candidate now was deleted, uploaded or rejected.
270
+ const candidateRels = new Set(candidates.map((c) => c.rel));
271
+ for (const rel of Object.keys(wm.pending))
272
+ if (!candidateRels.has(rel))
273
+ delete wm.pending[rel];
274
+ // Read transcripts' frontmatter only when a meeting:<id> signal needs it.
275
+ let meetingIndex;
276
+ const meetingIndexFor = () => (meetingIndex ??= buildMeetingAliasIndex(companyRoot));
277
+ const nowMs = ctx.now().getTime();
278
+ const expiredPaths = [];
279
+ const pendingFullPaths = [];
280
+ let pendingCount = Object.keys(wm.pending).length;
206
281
  const url = `${session.baseUrl.replace(/\/+$/, "")}${contributionRoute(ctx.company)}`;
207
282
  const skipped = {};
208
283
  let count = 0;
@@ -219,9 +294,34 @@ export function createUploadStep(overrides = {}) {
219
294
  companyUid: session.companyUid,
220
295
  projectionState: projection.state,
221
296
  projectionWatermark: projection.watermark,
297
+ meetingIndex: meetingIndexFor,
222
298
  });
223
299
  if (!s.ok) {
224
300
  skipped[s.reason] = (skipped[s.reason] ?? 0) + 1;
301
+ if (!RETRYABLE_SKIP_REASONS.has(s.reason)) {
302
+ if (wm.pending[c.rel])
303
+ pendingCount -= 1;
304
+ delete wm.pending[c.rel];
305
+ continue;
306
+ }
307
+ const prev = wm.pending[c.rel];
308
+ if (prev) {
309
+ if (nowMs - Date.parse(prev.firstSkippedAt) >= MAX_PENDING_AGE_MS) {
310
+ delete wm.pending[c.rel];
311
+ pendingCount -= 1;
312
+ expiredPaths.push(c.rel);
313
+ }
314
+ else {
315
+ wm.pending[c.rel] = { reason: s.reason, firstSkippedAt: prev.firstSkippedAt, attempts: prev.attempts + 1 };
316
+ }
317
+ }
318
+ else if (pendingCount >= MAX_PENDING) {
319
+ pendingFullPaths.push(c.rel);
320
+ }
321
+ else {
322
+ wm.pending[c.rel] = { reason: s.reason, firstSkippedAt: new Date(nowMs).toISOString(), attempts: 1 };
323
+ pendingCount += 1;
324
+ }
225
325
  continue;
226
326
  }
227
327
  if (!s.destination.startsWith(`member-signals/${session.memberUid}/`)) {
@@ -252,6 +352,9 @@ export function createUploadStep(overrides = {}) {
252
352
  count += 1;
253
353
  bytes += Buffer.byteLength(body);
254
354
  wm.uploaded.push(c.sha);
355
+ if (wm.pending[c.rel])
356
+ pendingCount -= 1;
357
+ delete wm.pending[c.rel];
255
358
  continue;
256
359
  }
257
360
  if (status === 401) {
@@ -275,6 +378,9 @@ export function createUploadStep(overrides = {}) {
275
378
  if ((status === 422 || status === 409 || status === 400) && !isRetryableRejection(parsed)) {
276
379
  rejected += 1;
277
380
  wm.rejected[c.sha] = parsed.code ?? `http-${status}`;
381
+ if (wm.pending[c.rel])
382
+ pendingCount -= 1;
383
+ delete wm.pending[c.rel];
278
384
  continue;
279
385
  }
280
386
  if (status === 403) {
@@ -288,8 +394,8 @@ export function createUploadStep(overrides = {}) {
288
394
  // Keep the projection pull but write no watermark change.
289
395
  return { ...stop, itemsIn: candidates.length, detail };
290
396
  }
291
- // Advance the watermark to the run start, except past a signal that
292
- // must be retried.
397
+ // Advance the watermark to the run start, except past a signal whose POST
398
+ // failed transiently. Retryable skips wait on the pending list instead.
293
399
  const runStart = ctx.now().getTime();
294
400
  const next = Number.isFinite(earliestRetryMs) ? Math.min(runStart, earliestRetryMs - 1) : runStart;
295
401
  const prior = wm.lastUploadedAt ? Date.parse(wm.lastUploadedAt) : -Infinity;
@@ -302,7 +408,17 @@ export function createUploadStep(overrides = {}) {
302
408
  itemsIn: candidates.length,
303
409
  itemsOut: count,
304
410
  uploaded: { count, bytes },
305
- detail: { ...detail, rejected, skipped },
411
+ detail: {
412
+ ...detail,
413
+ rejected,
414
+ skipped,
415
+ pending: Object.keys(wm.pending).length,
416
+ expired: expiredPaths.length,
417
+ ...(expiredPaths.length > 0 ? { expiredPaths: expiredPaths.slice(0, MAX_LISTED_PATHS) } : {}),
418
+ ...(pendingFullPaths.length > 0
419
+ ? { pendingFull: pendingFullPaths.length, pendingFullPaths: pendingFullPaths.slice(0, MAX_LISTED_PATHS) }
420
+ : {}),
421
+ },
306
422
  };
307
423
  if (stop) {
308
424
  return { ...stop, status: "partial", itemsIn: candidates.length, itemsOut: count, uploaded: { count, bytes }, detail: result.detail };
@@ -0,0 +1,29 @@
1
+ /**
2
+ * The access-refresh marker the sync engine (hq-sync-core) watches.
3
+ *
4
+ * Each engine runs with `HOME` set to its engine home, and reads
5
+ * `<engine home>/.hq/sync-core/access-refresh.json`
6
+ * (`SyncCoreHome::access_refresh_path`). When `requestedAtMs` changes, and the
7
+ * optional `vault` names the engine's vault, the engine reads its access again
8
+ * at once instead of waiting for its access backoff.
9
+ *
10
+ * Commands that change what this machine's user can see in a vault call
11
+ * {@link raiseAccessRefresh}. It writes only for vaults the engine owns
12
+ * (`readEngineOwnedVaults`) and never throws: a failed write is logged when
13
+ * diagnostics are on and the command carries on.
14
+ */
15
+ export interface AccessRefreshTarget {
16
+ companyUid?: string;
17
+ companySlug?: string;
18
+ }
19
+ export interface AccessRefreshOptions {
20
+ home?: string;
21
+ now?: () => number;
22
+ }
23
+ export declare function accessRefreshMarkerPath(home: string, vaultUid: string): string;
24
+ /**
25
+ * Asks the engine that owns the target company vault to read its access now.
26
+ * Returns the vault uids whose marker was written. Never throws.
27
+ */
28
+ export declare function raiseAccessRefresh(target: AccessRefreshTarget, options?: AccessRefreshOptions): string[];
29
+ //# sourceMappingURL=access-refresh.d.ts.map