@indigoai-us/hq-cli 5.345.241 → 5.345.243

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 (125) hide show
  1. package/CHANGELOG.md +54 -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/lib/delegate-engine.sh +77 -0
  5. package/dist/command-catalog.generated.d.ts +28 -8
  6. package/dist/command-catalog.generated.js +33 -8
  7. package/dist/commands/cloud-off-gate.d.ts +7 -7
  8. package/dist/commands/cloud-off-gate.js +26 -38
  9. package/dist/commands/core-delegate-w1b.js +307 -26
  10. package/dist/commands/core-delegate.js +2 -0
  11. package/dist/commands/core-handoff.js +1 -1
  12. package/dist/commands/core-job-model-auth.d.ts +95 -0
  13. package/dist/commands/core-job-model-auth.js +247 -0
  14. package/dist/commands/core-job-run-native.js +280 -12
  15. package/dist/commands/core.js +1 -0
  16. package/dist/commands/files-browse.js +2 -0
  17. package/dist/commands/files.js +4 -0
  18. package/dist/commands/integrations-core.d.ts +11 -0
  19. package/dist/commands/integrations-core.js +15 -1
  20. package/dist/commands/lanes-link.js +2 -2
  21. package/dist/commands/lanes-loop.d.ts +2 -2
  22. package/dist/commands/lanes-loop.js +5 -5
  23. package/dist/commands/lanes-questions.js +1 -1
  24. package/dist/commands/lanes-stories.js +1 -1
  25. package/dist/commands/lanes.js +80 -14
  26. package/dist/commands/rescue.d.ts +3 -2
  27. package/dist/commands/rescue.js +48 -34
  28. package/dist/commands/search.d.ts +6 -0
  29. package/dist/commands/search.js +24 -4
  30. package/dist/commands/sources.js +6 -2
  31. package/dist/commands/sync-core.d.ts +8 -0
  32. package/dist/commands/sync-core.js +43 -0
  33. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +1737 -1450
  34. package/dist/hq-cloud-sync-runner/package.json +1 -1
  35. package/dist/lib/capacity/accounts.d.ts +1 -1
  36. package/dist/lib/capacity/accounts.js +1 -1
  37. package/dist/lib/capacity/freshness.d.ts +1 -1
  38. package/dist/lib/capacity/freshness.js +1 -1
  39. package/dist/lib/capacity/route.js +1 -1
  40. package/dist/lib/claude-md-imports.d.ts +52 -0
  41. package/dist/lib/claude-md-imports.js +226 -0
  42. package/dist/lib/daemon/catalog.d.ts +3 -0
  43. package/dist/lib/daemon/hook-requests.d.ts +1 -1
  44. package/dist/lib/daemon/hook-requests.js +4 -2
  45. package/dist/lib/daemon/run.js +16 -22
  46. package/dist/lib/doctor/checks/claude-imports.d.ts +29 -0
  47. package/dist/lib/doctor/checks/claude-imports.js +131 -0
  48. package/dist/lib/doctor/fix/apply.d.ts +7 -0
  49. package/dist/lib/doctor/fix/apply.js +77 -0
  50. package/dist/lib/doctor/fix/remediation.d.ts +11 -1
  51. package/dist/lib/doctor/fix/remediation.js +42 -0
  52. package/dist/lib/doctor/registry.js +4 -0
  53. package/dist/lib/environment/work-requirements.d.ts +1 -1
  54. package/dist/lib/environment/work-requirements.js +1 -1
  55. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  56. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  57. package/dist/lib/hook-engine/coverage.js +11 -3
  58. package/dist/lib/hook-engine/git-stop-config.json +510 -510
  59. package/dist/lib/hook-engine/native-precompact-compatibility.json +443 -443
  60. package/dist/lib/hook-engine/native-stop-compatibility.json +359 -359
  61. package/dist/lib/hot-channels/adapters/meetings.d.ts +1 -16
  62. package/dist/lib/hot-channels/adapters/meetings.js +3 -28
  63. package/dist/lib/hot-channels/adapters/slack.d.ts +3 -1
  64. package/dist/lib/hot-channels/adapters/slack.js +4 -1
  65. package/dist/lib/hot-channels/contract.d.ts +14 -0
  66. package/dist/lib/hot-channels/fleet-complete.d.ts +18 -2
  67. package/dist/lib/hot-channels/fleet-complete.js +29 -4
  68. package/dist/lib/hot-channels/meeting-source-ref.d.ts +17 -0
  69. package/dist/lib/hot-channels/meeting-source-ref.js +32 -0
  70. package/dist/lib/hot-channels/prompts/signals-pass.md +6 -1
  71. package/dist/lib/hot-channels/run.d.ts +10 -0
  72. package/dist/lib/hot-channels/run.js +34 -0
  73. package/dist/lib/hot-channels/signals-pass.d.ts +27 -0
  74. package/dist/lib/hot-channels/signals-pass.js +57 -2
  75. package/dist/lib/hot-channels/signals-runtime.js +3 -2
  76. package/dist/lib/lanes/accounts.js +2 -2
  77. package/dist/lib/lanes/claude-balance.d.ts +6 -0
  78. package/dist/lib/lanes/claude-balance.js +124 -0
  79. package/dist/lib/lanes/grants.js +15 -2
  80. package/dist/lib/lanes/hq-root.d.ts +1 -1
  81. package/dist/lib/lanes/hq-root.js +1 -1
  82. package/dist/lib/lanes/links.d.ts +1 -1
  83. package/dist/lib/lanes/liveness.d.ts +3 -0
  84. package/dist/lib/lanes/liveness.js +61 -7
  85. package/dist/lib/lanes/models.d.ts +1 -1
  86. package/dist/lib/lanes/models.js +1 -1
  87. package/dist/lib/lanes/questions.d.ts +1 -1
  88. package/dist/lib/lanes/questions.js +2 -2
  89. package/dist/lib/lanes/spawn.js +4 -6
  90. package/dist/lib/lanes/store.d.ts +13 -2
  91. package/dist/lib/lanes/store.js +13 -5
  92. package/dist/lib/lanes/types.d.ts +7 -7
  93. package/dist/lib/lanes/types.js +1 -1
  94. package/dist/lib/lanes/watcher-main.js +1 -1
  95. package/dist/lib/lanes/watcher.d.ts +1 -1
  96. package/dist/lib/lanes/watcher.js +1 -1
  97. package/dist/lib/onboarding/cli/onboard.js +5 -0
  98. package/dist/lib/signals/sanitize.d.ts +19 -0
  99. package/dist/lib/signals/sanitize.js +103 -7
  100. package/dist/lib/signals/steps/upload.d.ts +40 -1
  101. package/dist/lib/signals/steps/upload.js +122 -6
  102. package/dist/lib/sync-core/access-refresh.d.ts +29 -0
  103. package/dist/lib/sync-core/access-refresh.js +97 -0
  104. package/dist/lib/sync-core/company-adoption.d.ts +33 -0
  105. package/dist/lib/sync-core/company-adoption.js +223 -0
  106. package/dist/lib/sync-core/engine-home.d.ts +1 -0
  107. package/dist/lib/sync-core/engine-owned.d.ts +13 -0
  108. package/dist/lib/sync-core/engine-owned.js +38 -0
  109. package/dist/lib/sync-core/hand-back.d.ts +17 -0
  110. package/dist/lib/sync-core/hand-back.js +23 -0
  111. package/dist/lib/sync-core/post-apply-reindex.d.ts +33 -0
  112. package/dist/lib/sync-core/post-apply-reindex.js +149 -0
  113. package/dist/lib/sync-core/reconcile.d.ts +10 -0
  114. package/dist/lib/sync-core/reconcile.js +117 -12
  115. package/dist/lib/sync-core/rollout-state.d.ts +2 -0
  116. package/dist/lib/sync-core/rollout-state.js +6 -0
  117. package/dist/lib/vault-sync-switches.d.ts +14 -0
  118. package/dist/lib/vault-sync-switches.js +22 -0
  119. package/dist/lib/workers-registry/index.d.ts +1 -1
  120. package/dist/lib/workers-registry/index.js +1 -1
  121. package/dist/utils/github-tag-fallback.d.ts +16 -0
  122. package/dist/utils/github-tag-fallback.js +126 -0
  123. package/dist/utils/version-report.d.ts +2 -1
  124. package/dist/utils/version-report.js +40 -27
  125. package/package.json +8 -8
@@ -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
@@ -0,0 +1,97 @@
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
+ import * as fs from "node:fs";
16
+ import * as os from "node:os";
17
+ import * as path from "node:path";
18
+ import { readEngineOwnedVaults } from "./engine-owned.js";
19
+ import { diagnosticsEnabled } from "../diagnostics.js";
20
+ import { syncCoreEngineHome } from "./engine-home.js";
21
+ export function accessRefreshMarkerPath(home, vaultUid) {
22
+ return path.join(syncCoreEngineHome(home, vaultUid), ".hq", "sync-core", "access-refresh.json");
23
+ }
24
+ function debug(message) {
25
+ if (diagnosticsEnabled())
26
+ process.stderr.write(`[hq] access refresh: ${message}\n`);
27
+ }
28
+ function engineVaultUids(engine, target) {
29
+ const found = new Set();
30
+ const uid = target.companyUid?.trim().toLowerCase();
31
+ if (uid && engine.uidSlugs.has(uid))
32
+ found.add(uid);
33
+ const slug = target.companySlug?.trim().toLowerCase();
34
+ if (slug) {
35
+ for (const [owned, ownedSlug] of engine.uidSlugs) {
36
+ if (ownedSlug === slug)
37
+ found.add(owned);
38
+ }
39
+ }
40
+ return [...found].flatMap((key) => {
41
+ const spelled = engine.uids.get(key);
42
+ return spelled ? [spelled] : [];
43
+ });
44
+ }
45
+ function previousRequestedAtMs(file) {
46
+ try {
47
+ const value = JSON.parse(fs.readFileSync(file, "utf8")).requestedAtMs;
48
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0;
49
+ }
50
+ catch {
51
+ return 0;
52
+ }
53
+ }
54
+ function writeMarker(home, vaultUid, nowMs) {
55
+ const file = accessRefreshMarkerPath(home, vaultUid);
56
+ if (!fs.existsSync(path.dirname(file))) {
57
+ debug(`no engine home for ${vaultUid}; marker not written`);
58
+ return false;
59
+ }
60
+ // The engine acts only when the value changes, so two raises in the same millisecond still differ.
61
+ const requestedAtMs = Math.max(nowMs, previousRequestedAtMs(file) + 1);
62
+ const tmp = `${file}.${process.pid}.tmp`;
63
+ try {
64
+ fs.writeFileSync(tmp, `${JSON.stringify({ requestedAtMs, vault: vaultUid })}\n`, { mode: 0o600 });
65
+ fs.renameSync(tmp, file);
66
+ }
67
+ catch (error) {
68
+ fs.rmSync(tmp, { force: true });
69
+ throw error;
70
+ }
71
+ return true;
72
+ }
73
+ /**
74
+ * Asks the engine that owns the target company vault to read its access now.
75
+ * Returns the vault uids whose marker was written. Never throws.
76
+ */
77
+ export function raiseAccessRefresh(target, options = {}) {
78
+ const raised = [];
79
+ try {
80
+ const home = options.home ?? os.homedir();
81
+ const nowMs = (options.now ?? Date.now)();
82
+ for (const vaultUid of engineVaultUids(readEngineOwnedVaults(home), target)) {
83
+ try {
84
+ if (writeMarker(home, vaultUid, nowMs))
85
+ raised.push(vaultUid);
86
+ }
87
+ catch (error) {
88
+ debug(`marker for ${vaultUid} not written: ${error instanceof Error ? error.message : String(error)}`);
89
+ }
90
+ }
91
+ }
92
+ catch (error) {
93
+ debug(`engine vaults not read: ${error instanceof Error ? error.message : String(error)}`);
94
+ }
95
+ return raised;
96
+ }
97
+ //# sourceMappingURL=access-refresh.js.map
@@ -0,0 +1,33 @@
1
+ export interface SyncCoreCompanyEntity {
2
+ uid: string;
3
+ slug?: string;
4
+ type?: string;
5
+ status?: string;
6
+ name?: string;
7
+ bucketName?: string;
8
+ }
9
+ export type JoinedCompanySetup = {
10
+ status: "ready";
11
+ slug: string;
12
+ createdFolder: boolean;
13
+ wroteEntry: boolean;
14
+ } | {
15
+ status: "refused";
16
+ reason: string;
17
+ };
18
+ export declare function isLiveCompanyEntity(entity: SyncCoreCompanyEntity | null | undefined, uid: string): entity is SyncCoreCompanyEntity;
19
+ /** The folder name a joined company gets: its cloud slug, when that is a plain slug. */
20
+ export declare function joinedCompanySlug(entity: SyncCoreCompanyEntity): string | undefined;
21
+ /**
22
+ * Creates `companies/<slug>` and adds the manifest entry for `entity` when
23
+ * either is missing. `slug` is the manifest key already bound to the company's
24
+ * uid, or the company's cloud slug when the manifest has none.
25
+ * `keepFolderMissing` names why a missing folder must not be created (an
26
+ * engine or the current sync synced the company here before and would read an
27
+ * empty new folder as every file deleted). A folder that already has files but
28
+ * no manifest entry is left alone: adopting it would upload whatever is in it.
29
+ */
30
+ export declare function setUpJoinedCompany(hqRoot: string, slug: string, entity: SyncCoreCompanyEntity, opts?: {
31
+ keepFolderMissing?: string;
32
+ }): JoinedCompanySetup;
33
+ //# sourceMappingURL=company-adoption.d.ts.map