@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
@@ -0,0 +1,223 @@
1
+ /**
2
+ * Sets up the local side of a company the person joined, on a machine where
3
+ * the new sync engine handles that company: the `companies/<slug>` folder and
4
+ * its `companies/manifest.yaml` entry. Until now only the old sync runner's
5
+ * `--companies` pass wrote these, after its first pull.
6
+ *
7
+ * The manifest entry mirrors `reconcileManifest` in hq-cloud
8
+ * `src/manifest-reconcile.ts` (not exported from the package): same fields
9
+ * (`cloud_uid` always, `name` and `bucket_name` when the entity carries them),
10
+ * same liveness rule (an active company), same temp-file-then-rename write
11
+ * beside the manifest. Unlike the runner it only adds a missing entry, never
12
+ * changes an existing one, and appends the entry as text so the file's
13
+ * comments survive; it falls back to `yaml.dump(document, { lineWidth: -1 })`,
14
+ * the runner's form, only when the text append would not parse to the same
15
+ * document. The manifest is re-read just before the rename and the write is
16
+ * retried when another writer changed it in between.
17
+ */
18
+ import { randomUUID } from "node:crypto";
19
+ import * as fs from "node:fs";
20
+ import * as path from "node:path";
21
+ import yaml from "js-yaml";
22
+ const SLUG_PATTERN = /^[a-z0-9][a-z0-9_-]*$/;
23
+ const HQ_TREE_MARKERS = ["core", ".claude", "personal"];
24
+ const WRITE_ATTEMPTS = 3;
25
+ function isRecord(value) {
26
+ if (value === null || typeof value !== "object")
27
+ return false;
28
+ const proto = Object.getPrototypeOf(value);
29
+ return proto === Object.prototype || proto === null;
30
+ }
31
+ function isDirectory(target) {
32
+ try {
33
+ return fs.statSync(target).isDirectory();
34
+ }
35
+ catch {
36
+ return false;
37
+ }
38
+ }
39
+ function optionalField(value) {
40
+ return typeof value === "string" && value.length > 0 ? value : undefined;
41
+ }
42
+ export function isLiveCompanyEntity(entity, uid) {
43
+ return !!entity && entity.uid === uid && entity.type === "company" && entity.status === "active";
44
+ }
45
+ /** The folder name a joined company gets: its cloud slug, when that is a plain slug. */
46
+ export function joinedCompanySlug(entity) {
47
+ const slug = entity.slug?.trim();
48
+ return slug && SLUG_PATTERN.test(slug) ? slug : undefined;
49
+ }
50
+ function readManifestText(manifestPath) {
51
+ try {
52
+ return fs.readFileSync(manifestPath, "utf8");
53
+ }
54
+ catch (error) {
55
+ if (error.code === "ENOENT")
56
+ return null;
57
+ throw error;
58
+ }
59
+ }
60
+ function planManifest(hqRoot, raw, slug, entity) {
61
+ let document = {};
62
+ if (raw !== null && raw.trim() !== "") {
63
+ let parsed;
64
+ try {
65
+ parsed = yaml.load(raw);
66
+ }
67
+ catch {
68
+ return { kind: "refused", reason: "companies/manifest.yaml could not be parsed" };
69
+ }
70
+ if (!isRecord(parsed))
71
+ return { kind: "refused", reason: "companies/manifest.yaml is not a mapping" };
72
+ document = parsed;
73
+ }
74
+ else if (!HQ_TREE_MARKERS.some((marker) => isDirectory(path.join(hqRoot, marker)))) {
75
+ return { kind: "refused", reason: `${hqRoot} has no companies/manifest.yaml and is not an HQ folder` };
76
+ }
77
+ let companies;
78
+ if (document.companies === undefined || document.companies === null) {
79
+ companies = {};
80
+ }
81
+ else if (isRecord(document.companies)) {
82
+ companies = document.companies;
83
+ }
84
+ else {
85
+ return { kind: "refused", reason: "companies/manifest.yaml has a companies key that is not a mapping" };
86
+ }
87
+ const existing = Object.prototype.hasOwnProperty.call(companies, slug) ? companies[slug] : undefined;
88
+ if (existing !== undefined && !(isRecord(existing) && existing.cloud_uid === entity.uid)) {
89
+ return { kind: "refused", reason: `companies/manifest.yaml already has a "${slug}" entry that is not this company` };
90
+ }
91
+ for (const [key, value] of Object.entries(companies)) {
92
+ if (key !== slug && isRecord(value) && value.cloud_uid === entity.uid) {
93
+ return { kind: "refused", reason: `companies/manifest.yaml already binds this company to "${key}"` };
94
+ }
95
+ }
96
+ if (existing !== undefined)
97
+ return { kind: "has-entry" };
98
+ const entry = { cloud_uid: entity.uid };
99
+ const name = optionalField(entity.name);
100
+ if (name !== undefined)
101
+ entry.name = name;
102
+ const bucketName = optionalField(entity.bucketName);
103
+ if (bucketName !== undefined)
104
+ entry.bucket_name = bucketName;
105
+ return { kind: "add", document, entry };
106
+ }
107
+ function isContentLine(line) {
108
+ const trimmed = line.trim();
109
+ return trimmed !== "" && !trimmed.startsWith("#");
110
+ }
111
+ function indentOf(line) {
112
+ return line.length - line.trimStart().length;
113
+ }
114
+ /** The manifest text with the entry appended to the `companies:` block, or null when that cannot be done as text. */
115
+ function appendEntryText(raw, slug, entry) {
116
+ const eol = raw.includes("\r\n") ? "\r\n" : "\n";
117
+ const lines = raw.split(/\r?\n/);
118
+ const start = lines.findIndex((line) => /^companies:\s*(#.*)?$/.test(line));
119
+ if (start === -1)
120
+ return null;
121
+ let end = lines.length;
122
+ for (let i = start + 1; i < lines.length; i += 1) {
123
+ if (isContentLine(lines[i]) && indentOf(lines[i]) === 0) {
124
+ end = i;
125
+ break;
126
+ }
127
+ }
128
+ let last = start;
129
+ let indent = 2;
130
+ for (let i = start + 1; i < end; i += 1) {
131
+ if (!isContentLine(lines[i]))
132
+ continue;
133
+ if (last === start) {
134
+ indent = indentOf(lines[i]);
135
+ if (/^\s*[-{[]/.test(lines[i]))
136
+ return null;
137
+ }
138
+ last = i;
139
+ }
140
+ const block = yaml.dump({ [slug]: entry }, { lineWidth: -1 }).trimEnd().split("\n").map((line) => `${" ".repeat(indent)}${line}`);
141
+ lines.splice(last + 1, 0, ...block);
142
+ return lines.join(eol);
143
+ }
144
+ function manifestText(raw, slug, document, entry) {
145
+ const companies = isRecord(document.companies) ? document.companies : {};
146
+ const expected = { ...document, companies: { ...companies } };
147
+ Object.defineProperty(expected.companies, slug, { value: entry, enumerable: true, writable: true, configurable: true });
148
+ if (raw !== null && raw.trim() !== "") {
149
+ const appended = appendEntryText(raw, slug, entry);
150
+ if (appended !== null) {
151
+ let reparsed;
152
+ try {
153
+ reparsed = yaml.load(appended);
154
+ }
155
+ catch {
156
+ reparsed = undefined;
157
+ }
158
+ if (JSON.stringify(reparsed) === JSON.stringify(expected))
159
+ return appended;
160
+ }
161
+ }
162
+ return yaml.dump(expected, { lineWidth: -1 });
163
+ }
164
+ /**
165
+ * Creates `companies/<slug>` and adds the manifest entry for `entity` when
166
+ * either is missing. `slug` is the manifest key already bound to the company's
167
+ * uid, or the company's cloud slug when the manifest has none.
168
+ * `keepFolderMissing` names why a missing folder must not be created (an
169
+ * engine or the current sync synced the company here before and would read an
170
+ * empty new folder as every file deleted). A folder that already has files but
171
+ * no manifest entry is left alone: adopting it would upload whatever is in it.
172
+ */
173
+ export function setUpJoinedCompany(hqRoot, slug, entity, opts = {}) {
174
+ if (!SLUG_PATTERN.test(slug))
175
+ return { status: "refused", reason: `"${slug}" is not a usable company folder name` };
176
+ const manifestPath = path.join(hqRoot, "companies", "manifest.yaml");
177
+ const companyDir = path.join(hqRoot, "companies", slug);
178
+ let createdFolder = false;
179
+ for (let attempt = 0; attempt < WRITE_ATTEMPTS; attempt += 1) {
180
+ let raw;
181
+ try {
182
+ raw = readManifestText(manifestPath);
183
+ }
184
+ catch {
185
+ return { status: "refused", reason: "companies/manifest.yaml could not be read" };
186
+ }
187
+ const plan = planManifest(hqRoot, raw, slug, entity);
188
+ if (plan.kind === "refused")
189
+ return { status: "refused", reason: plan.reason };
190
+ if (!isDirectory(companyDir)) {
191
+ if (opts.keepFolderMissing) {
192
+ return { status: "refused", reason: `companies/${slug} is missing and ${opts.keepFolderMissing}, so no empty folder is created` };
193
+ }
194
+ fs.mkdirSync(companyDir, { recursive: true });
195
+ createdFolder = true;
196
+ }
197
+ else if (plan.kind === "add" && !createdFolder && fs.readdirSync(companyDir).length > 0) {
198
+ return { status: "refused", reason: `companies/${slug} already has files but no entry in companies/manifest.yaml; it is left alone` };
199
+ }
200
+ if (plan.kind === "has-entry")
201
+ return { status: "ready", slug, createdFolder, wroteEntry: false };
202
+ const temporaryPath = path.join(path.dirname(manifestPath), `.manifest-${process.pid}-${randomUUID()}.yaml`);
203
+ try {
204
+ fs.writeFileSync(temporaryPath, manifestText(raw, slug, plan.document, plan.entry), "utf8");
205
+ let now;
206
+ try {
207
+ now = readManifestText(manifestPath);
208
+ }
209
+ catch {
210
+ return { status: "refused", reason: "companies/manifest.yaml could not be read" };
211
+ }
212
+ if (now !== raw)
213
+ continue;
214
+ fs.renameSync(temporaryPath, manifestPath);
215
+ return { status: "ready", slug, createdFolder, wroteEntry: true };
216
+ }
217
+ finally {
218
+ fs.rmSync(temporaryPath, { force: true });
219
+ }
220
+ }
221
+ return { status: "refused", reason: `companies/manifest.yaml kept changing while the entry was being added (${WRITE_ATTEMPTS} tries)` };
222
+ }
223
+ //# sourceMappingURL=company-adoption.js.map
@@ -12,6 +12,7 @@ export interface SyncCoreVaultPlan extends SyncCoreVault {
12
12
  binaryPath: string;
13
13
  release: string;
14
14
  legacyOffSince?: string;
15
+ legacyAlreadyOff?: true;
15
16
  blockedReason?: string;
16
17
  settings?: SyncCoreVaultSettings;
17
18
  }
@@ -0,0 +1,13 @@
1
+ import { type SyncCoreRolloutState } from "./rollout-state.js";
2
+ export interface EngineOwnedVaults {
3
+ personal: boolean;
4
+ companies: ReadonlySet<string>;
5
+ uidSlugs: ReadonlyMap<string, string>;
6
+ /** Lowercase uid to the uid as rollout.json spells it, for every engine-owned vault. */
7
+ uids: ReadonlyMap<string, string>;
8
+ }
9
+ /** The vaults a rollout state (or `hq sync-core status --json`) puts on the engine: full and not held. */
10
+ export declare function engineOwnedVaultsFromState(state: Pick<SyncCoreRolloutState, "vaults" | "held">): EngineOwnedVaults;
11
+ export declare const NO_ENGINE_VAULTS: EngineOwnedVaults;
12
+ export declare function readEngineOwnedVaults(home?: string): EngineOwnedVaults;
13
+ //# sourceMappingURL=engine-owned.d.ts.map
@@ -0,0 +1,38 @@
1
+ import * as os from "node:os";
2
+ import { readSyncCoreRolloutState } from "./rollout-state.js";
3
+ /** The vaults a rollout state (or `hq sync-core status --json`) puts on the engine: full and not held. */
4
+ export function engineOwnedVaultsFromState(state) {
5
+ const held = new Set((state.held ?? []).map((h) => h.uid.toLowerCase()));
6
+ let personal = false;
7
+ const companies = new Set();
8
+ const uidSlugs = new Map();
9
+ const uids = new Map();
10
+ for (const vault of state.vaults) {
11
+ if (vault.phase !== "full" || held.has(vault.uid.toLowerCase()))
12
+ continue;
13
+ uids.set(vault.uid.toLowerCase(), vault.uid);
14
+ if (vault.kind === "personal") {
15
+ personal = true;
16
+ continue;
17
+ }
18
+ const slug = vault.slug?.trim().toLowerCase();
19
+ if (!slug)
20
+ continue;
21
+ companies.add(slug);
22
+ uidSlugs.set(vault.uid.toLowerCase(), slug);
23
+ }
24
+ return { personal, companies, uidSlugs, uids };
25
+ }
26
+ export const NO_ENGINE_VAULTS = {
27
+ personal: false,
28
+ companies: new Set(),
29
+ uidSlugs: new Map(),
30
+ uids: new Map(),
31
+ };
32
+ export function readEngineOwnedVaults(home = os.homedir()) {
33
+ const state = readSyncCoreRolloutState(home, { strict: true });
34
+ if (!state)
35
+ return NO_ENGINE_VAULTS;
36
+ return engineOwnedVaultsFromState(state);
37
+ }
38
+ //# sourceMappingURL=engine-owned.js.map
@@ -0,0 +1,17 @@
1
+ import { legacySwitchRestorePatch, type VaultSyncSwitches } from "../vault-sync-switches.js";
2
+ export interface HandBackVault {
3
+ uid: string;
4
+ kind: "personal" | "company";
5
+ slug?: string;
6
+ legacyAlreadyOff?: boolean;
7
+ }
8
+ export declare function engineOwnsVault(home: string, uid: string): boolean;
9
+ /**
10
+ * Returns vaults whose engine has stopped to the current sync: turns the
11
+ * old-sync switch back on (not for a vault the user had off before the move),
12
+ * then removes the engine ownership record. Call only once each vault's engine
13
+ * has exited; the runner resumes a vault as soon as both are done. Throws
14
+ * before removing any record when menubar.json cannot be written.
15
+ */
16
+ export declare function finishLegacyHandBack(home: string, vaults: readonly HandBackVault[], switches?: Pick<VaultSyncSwitches, "personalOff" | "offCompanies">): ReturnType<typeof legacySwitchRestorePatch>;
17
+ //# sourceMappingURL=hand-back.d.ts.map
@@ -0,0 +1,23 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { legacySwitchRestorePatch, writeVaultSyncSwitches } from "../vault-sync-switches.js";
4
+ import { removeEngineOwnership, syncCoreEngineHome } from "./engine-home.js";
5
+ export function engineOwnsVault(home, uid) {
6
+ return fs.existsSync(path.join(syncCoreEngineHome(home, uid), ".hq", "sync-core", "owned", `${uid}.json`));
7
+ }
8
+ /**
9
+ * Returns vaults whose engine has stopped to the current sync: turns the
10
+ * old-sync switch back on (not for a vault the user had off before the move),
11
+ * then removes the engine ownership record. Call only once each vault's engine
12
+ * has exited; the runner resumes a vault as soon as both are done. Throws
13
+ * before removing any record when menubar.json cannot be written.
14
+ */
15
+ export function finishLegacyHandBack(home, vaults, switches) {
16
+ const patch = legacySwitchRestorePatch(vaults, switches);
17
+ if (patch.personal || Object.keys(patch.companies).length > 0)
18
+ writeVaultSyncSwitches(home, patch);
19
+ for (const vault of vaults)
20
+ removeEngineOwnership(home, vault.uid);
21
+ return patch;
22
+ }
23
+ //# sourceMappingURL=hand-back.js.map
@@ -0,0 +1,33 @@
1
+ import type { RolloutVault } from "./rollout-state.js";
2
+ export declare const REINDEX_INPUTS_FILE = "reindex-inputs.json";
3
+ export declare function reindexInputsPath(home: string): string;
4
+ /**
5
+ * A digest of what `reindex` reads under the vaults the new sync engine owns in full mode:
6
+ * each skill's top-level entries and its SKILL.md, the command files, and each worker.yaml
7
+ * under `workers/`. Like `reindex`, it follows a symlinked skill folder or SKILL.md and
8
+ * ignores dot-entries. Null when the engine owns no vault here.
9
+ */
10
+ export declare function reindexInputsFingerprint(hqRoot: string, vaults: readonly RolloutVault[]): string | null;
11
+ export interface PostApplyReindexDeps {
12
+ home: string;
13
+ hqRoot: string;
14
+ vaults: readonly RolloutVault[];
15
+ /** Runs the reindex against the HQ folder; a status other than 0 means it did not run. */
16
+ reindex: (hqRoot: string) => {
17
+ status: number;
18
+ } | Promise<{
19
+ status: number;
20
+ }>;
21
+ now?: () => Date;
22
+ log?: (line: string) => void;
23
+ }
24
+ export type PostApplyReindexOutcome = "no-engine-vault" | "unchanged" | "reindexed" | "retry";
25
+ /**
26
+ * The old sync runner reindexed after every pull that changed files. With the engine owning a
27
+ * vault nothing does, so a company skill that arrives is never registered. This runs the same
28
+ * reindex when the engine-owned vaults' skills, commands or workers differ from the last run.
29
+ * A reindex that fails or does not run is tried again on every run; its warning is logged once
30
+ * and again only when the failure changes.
31
+ */
32
+ export declare function reindexAfterEngineChanges(deps: PostApplyReindexDeps): Promise<PostApplyReindexOutcome>;
33
+ //# sourceMappingURL=post-apply-reindex.d.ts.map
@@ -0,0 +1,149 @@
1
+ import { createHash } from "node:crypto";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ export const REINDEX_INPUTS_FILE = "reindex-inputs.json";
5
+ export function reindexInputsPath(home) {
6
+ return path.join(home, ".hq", "sync-core", REINDEX_INPUTS_FILE);
7
+ }
8
+ function entries(dir) {
9
+ try {
10
+ return fs
11
+ .readdirSync(dir, { withFileTypes: true })
12
+ .filter((entry) => !entry.name.startsWith("."))
13
+ .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
14
+ }
15
+ catch {
16
+ return [];
17
+ }
18
+ }
19
+ function isDirectory(entry, file) {
20
+ if (entry.isDirectory())
21
+ return true;
22
+ if (!entry.isSymbolicLink())
23
+ return false;
24
+ try {
25
+ return fs.statSync(file).isDirectory();
26
+ }
27
+ catch {
28
+ return false;
29
+ }
30
+ }
31
+ function fileLine(rel, file) {
32
+ try {
33
+ const stat = fs.statSync(file);
34
+ return `${rel}\t${stat.size}\t${Math.floor(stat.mtimeMs)}`;
35
+ }
36
+ catch {
37
+ return undefined;
38
+ }
39
+ }
40
+ function skillLines(hqRoot, base, lines) {
41
+ for (const skill of entries(path.join(hqRoot, base, "skills"))) {
42
+ const rel = `${base}/skills/${skill.name}`;
43
+ if (!isDirectory(skill, path.join(hqRoot, rel)))
44
+ continue;
45
+ for (const entry of entries(path.join(hqRoot, rel))) {
46
+ const line = entry.name === "SKILL.md" ? fileLine(`${rel}/SKILL.md`, path.join(hqRoot, rel, "SKILL.md")) : `${rel}/${entry.name}`;
47
+ if (line)
48
+ lines.push(line);
49
+ }
50
+ }
51
+ }
52
+ function commandLines(hqRoot, base, lines) {
53
+ for (const entry of entries(path.join(hqRoot, base, "commands")))
54
+ lines.push(`${base}/commands/${entry.name}`);
55
+ }
56
+ function workerLines(hqRoot, rel, lines) {
57
+ for (const entry of entries(path.join(hqRoot, rel))) {
58
+ const child = `${rel}/${entry.name}`;
59
+ if (entry.isDirectory())
60
+ workerLines(hqRoot, child, lines);
61
+ else if (entry.name === "worker.yaml") {
62
+ const line = fileLine(child, path.join(hqRoot, child));
63
+ if (line)
64
+ lines.push(line);
65
+ }
66
+ }
67
+ }
68
+ /**
69
+ * A digest of what `reindex` reads under the vaults the new sync engine owns in full mode:
70
+ * each skill's top-level entries and its SKILL.md, the command files, and each worker.yaml
71
+ * under `workers/`. Like `reindex`, it follows a symlinked skill folder or SKILL.md and
72
+ * ignores dot-entries. Null when the engine owns no vault here.
73
+ */
74
+ export function reindexInputsFingerprint(hqRoot, vaults) {
75
+ const bases = new Set();
76
+ for (const vault of vaults) {
77
+ if (vault.phase !== "full")
78
+ continue;
79
+ if (vault.kind === "personal")
80
+ bases.add("personal");
81
+ else if (vault.slug)
82
+ bases.add(`companies/${vault.slug}`);
83
+ }
84
+ if (bases.size === 0)
85
+ return null;
86
+ const lines = [];
87
+ for (const base of [...bases].sort()) {
88
+ lines.push(`# ${base}`);
89
+ skillLines(hqRoot, base, lines);
90
+ commandLines(hqRoot, base, lines);
91
+ workerLines(hqRoot, `${base}/workers`, lines);
92
+ }
93
+ return createHash("sha256").update(lines.join("\n")).digest("hex");
94
+ }
95
+ function readRecord(home) {
96
+ try {
97
+ const parsed = JSON.parse(fs.readFileSync(reindexInputsPath(home), "utf8"));
98
+ return {
99
+ ...(typeof parsed.fingerprint === "string" ? { fingerprint: parsed.fingerprint } : {}),
100
+ ...(typeof parsed.at === "string" ? { at: parsed.at } : {}),
101
+ ...(typeof parsed.failure === "string" ? { failure: parsed.failure } : {}),
102
+ };
103
+ }
104
+ catch {
105
+ return {};
106
+ }
107
+ }
108
+ function writeRecord(home, record) {
109
+ const file = reindexInputsPath(home);
110
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
111
+ const tmp = `${file}.${process.pid}.tmp`;
112
+ fs.writeFileSync(tmp, `${JSON.stringify({ version: 1, ...record }, null, 2)}\n`, { mode: 0o600 });
113
+ fs.renameSync(tmp, file);
114
+ }
115
+ /**
116
+ * The old sync runner reindexed after every pull that changed files. With the engine owning a
117
+ * vault nothing does, so a company skill that arrives is never registered. This runs the same
118
+ * reindex when the engine-owned vaults' skills, commands or workers differ from the last run.
119
+ * A reindex that fails or does not run is tried again on every run; its warning is logged once
120
+ * and again only when the failure changes.
121
+ */
122
+ export async function reindexAfterEngineChanges(deps) {
123
+ const log = deps.log ?? (() => { });
124
+ const fingerprint = reindexInputsFingerprint(deps.hqRoot, deps.vaults);
125
+ if (fingerprint === null)
126
+ return "no-engine-vault";
127
+ const record = readRecord(deps.home);
128
+ if (record.fingerprint === fingerprint)
129
+ return "unchanged";
130
+ let failure;
131
+ try {
132
+ const { status } = await deps.reindex(deps.hqRoot);
133
+ failure = status === 0 ? "" : `did not run (status ${status})`;
134
+ }
135
+ catch (error) {
136
+ failure = `failed: ${error instanceof Error ? error.message : String(error)}`;
137
+ }
138
+ if (failure) {
139
+ if (record.failure !== failure) {
140
+ log(`warning: reindex after new-sync changes ${failure}; trying again on each run without repeating this warning`);
141
+ writeRecord(deps.home, { ...record, failure });
142
+ }
143
+ return "retry";
144
+ }
145
+ writeRecord(deps.home, { fingerprint, at: (deps.now ?? (() => new Date()))().toISOString() });
146
+ log("skills, commands or workers changed under a vault on the new sync engine; reindexed");
147
+ return "reindexed";
148
+ }
149
+ //# sourceMappingURL=post-apply-reindex.js.map
@@ -1,5 +1,7 @@
1
1
  import { type SyncCoreVault } from "./engine-home.js";
2
2
  import { type SyncCoreBinaryInstall, type SyncCorePin } from "./release.js";
3
+ import type { MachineType } from "../daemon/machine-type.js";
4
+ import { type SyncCoreCompanyEntity } from "./company-adoption.js";
3
5
  import { type SyncCoreRolloutState } from "./rollout-state.js";
4
6
  export interface SyncCoreMembership {
5
7
  companyUid: string;
@@ -19,6 +21,14 @@ export interface SyncCoreReconcileDeps {
19
21
  * read; the vault then keeps the value it had. Omitted: no company value.
20
22
  */
21
23
  readDownloadStreams?: (companyUid: string) => Promise<number | undefined>;
24
+ /**
25
+ * Looks up one company entity. With machineType, lets reconcile create the
26
+ * folder and manifest entry of a company the person joined, so the engine
27
+ * can adopt it without a pass of the current sync. Omitted: nothing is set up.
28
+ */
29
+ resolveCompany?: (companyUid: string) => Promise<SyncCoreCompanyEntity | null>;
30
+ /** Only desktop and self-hosted machines set up a joined company. */
31
+ machineType?: MachineType;
22
32
  ensureBinary: (release: string) => Promise<SyncCoreBinaryInstall>;
23
33
  /** A fixed release (tests). Otherwise readPin decides, then SYNC_CORE_RELEASE. */
24
34
  release?: string;