@indigoai-us/hq-cloud 6.14.17 → 6.14.18

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 (39) hide show
  1. package/dist/active-company.d.ts +43 -0
  2. package/dist/active-company.d.ts.map +1 -0
  3. package/dist/active-company.js +132 -0
  4. package/dist/active-company.js.map +1 -0
  5. package/dist/active-company.test.d.ts +2 -0
  6. package/dist/active-company.test.d.ts.map +1 -0
  7. package/dist/active-company.test.js +149 -0
  8. package/dist/active-company.test.js.map +1 -0
  9. package/dist/bin/sync-runner-planning.d.ts +27 -1
  10. package/dist/bin/sync-runner-planning.d.ts.map +1 -1
  11. package/dist/bin/sync-runner-planning.js +33 -4
  12. package/dist/bin/sync-runner-planning.js.map +1 -1
  13. package/dist/bin/sync-runner-planning.test.d.ts +2 -0
  14. package/dist/bin/sync-runner-planning.test.d.ts.map +1 -0
  15. package/dist/bin/sync-runner-planning.test.js +115 -0
  16. package/dist/bin/sync-runner-planning.test.js.map +1 -0
  17. package/dist/bin/sync-runner.d.ts +22 -7
  18. package/dist/bin/sync-runner.d.ts.map +1 -1
  19. package/dist/bin/sync-runner.js +92 -16
  20. package/dist/bin/sync-runner.js.map +1 -1
  21. package/dist/bin/sync-runner.test.js +357 -5
  22. package/dist/bin/sync-runner.test.js.map +1 -1
  23. package/dist/manifest-reconcile.d.ts +118 -5
  24. package/dist/manifest-reconcile.d.ts.map +1 -1
  25. package/dist/manifest-reconcile.js +319 -62
  26. package/dist/manifest-reconcile.js.map +1 -1
  27. package/dist/manifest-reconcile.test.js +824 -2
  28. package/dist/manifest-reconcile.test.js.map +1 -1
  29. package/package.json +1 -1
  30. package/pnpm-workspace.yaml +1 -1
  31. package/src/active-company.test.ts +188 -0
  32. package/src/active-company.ts +168 -0
  33. package/src/bin/sync-runner-planning.test.ts +131 -0
  34. package/src/bin/sync-runner-planning.ts +60 -7
  35. package/src/bin/sync-runner.test.ts +430 -10
  36. package/src/bin/sync-runner.ts +129 -23
  37. package/src/manifest-reconcile.test.ts +1019 -3
  38. package/src/manifest-reconcile.ts +424 -66
  39. package/test/joiner-manifest-reconcile.integration.test.ts +283 -0
@@ -0,0 +1,283 @@
1
+ /**
2
+ * Joiner manifest reconciliation — end-to-end regression (indigo/joiner-manifest-reconcile).
3
+ *
4
+ * Reproduces michelle@boringecom.com's exact state: an active company
5
+ * membership on the server, and a local `companies/manifest.yaml` that is still
6
+ * the stock empty template because a joiner only ever receives the manifest as
7
+ * a synced file from their personal vault. /setup grepped that file, concluded
8
+ * "solo", and routed her to /newcompany for a company she already belonged to.
9
+ *
10
+ * These drive the REAL runner with the REAL reconciler and the REAL activeCompany
11
+ * seeder — no stubs on the code under test. That matters: every stubbed
12
+ * assertion in sync-runner.test.ts passed while the end-to-end path was broken,
13
+ * because the stub is exactly what hid the defect.
14
+ *
15
+ * Reverting US-001/US-002 (the reconciler and its wiring) turns "restores the
16
+ * manifest entry" and "seeds activeCompany" red — verified locally by reverting
17
+ * both and re-running; the failure is recorded in the PR body.
18
+ */
19
+
20
+ import { afterEach, describe, expect, it, vi } from "vitest";
21
+ import * as fs from "node:fs";
22
+ import * as os from "node:os";
23
+ import * as path from "node:path";
24
+ import yaml from "js-yaml";
25
+
26
+ import { runRunner } from "../src/bin/sync-runner.js";
27
+ import type { RunnerDeps, VaultClientSurface } from "../src/bin/sync-runner.js";
28
+ import type { EntityInfo, Membership } from "../src/vault-client.js";
29
+
30
+ // The template a fresh HQ install ships, and what a joiner's personal vault
31
+ // hands them. 298 bytes of nothing, which is what made her look solo.
32
+ const EMPTY_MANIFEST_TEMPLATE = `# HQ company manifest.
33
+ # Source of truth for which company slugs this HQ root routes.
34
+ # Edited by humans; reconciled by hq-sync. Keep this header.
35
+ companies: {}
36
+ `;
37
+
38
+ let hqRoot: string | undefined;
39
+
40
+ afterEach(() => {
41
+ if (hqRoot) {
42
+ fs.rmSync(hqRoot, { recursive: true, force: true });
43
+ hqRoot = undefined;
44
+ }
45
+ });
46
+
47
+ interface CompanyFixture {
48
+ uid: string;
49
+ slug: string;
50
+ name: string;
51
+ }
52
+
53
+ function makeJoinerRoot(companies: readonly CompanyFixture[]): string {
54
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "hq-joiner-"));
55
+ fs.mkdirSync(path.join(root, "companies"), { recursive: true });
56
+ // The pull materializes the company directory; the manifest entry is the
57
+ // thing that was missing.
58
+ for (const c of companies) {
59
+ fs.mkdirSync(path.join(root, "companies", c.slug), { recursive: true });
60
+ }
61
+ fs.writeFileSync(
62
+ path.join(root, "companies", "manifest.yaml"),
63
+ EMPTY_MANIFEST_TEMPLATE,
64
+ "utf8",
65
+ );
66
+ return root;
67
+ }
68
+
69
+ function readManifest(root: string): Record<string, Record<string, unknown>> {
70
+ const doc = yaml.load(
71
+ fs.readFileSync(path.join(root, "companies", "manifest.yaml"), "utf8"),
72
+ ) as { companies?: Record<string, Record<string, unknown>> };
73
+ return doc.companies ?? {};
74
+ }
75
+
76
+ function readConfig(root: string): Record<string, unknown> {
77
+ const p = path.join(root, ".hq", "config.json");
78
+ if (!fs.existsSync(p)) return {};
79
+ return JSON.parse(fs.readFileSync(p, "utf8")) as Record<string, unknown>;
80
+ }
81
+
82
+ function makeWriter(): {
83
+ write: (chunk: string) => boolean;
84
+ raw: () => string;
85
+ } {
86
+ let buf = "";
87
+ return {
88
+ write: (chunk: string) => {
89
+ buf += chunk;
90
+ return true;
91
+ },
92
+ raw: () => buf,
93
+ };
94
+ }
95
+
96
+ /**
97
+ * A vault client for a user who genuinely belongs to `companies` — the server
98
+ * side is correct and untouched by this project.
99
+ */
100
+ function joinerVaultClient(companies: readonly CompanyFixture[]): VaultClientSurface {
101
+ const byUid = new Map(companies.map((c) => [c.uid, c]));
102
+ return {
103
+ listMyMemberships: () =>
104
+ Promise.resolve(
105
+ companies.map((c) => ({ companyUid: c.uid })) as Membership[],
106
+ ),
107
+ listMyPendingInvitesByEmail: () => Promise.resolve([]),
108
+ claimPendingInvitesByEmail: () => Promise.resolve(undefined),
109
+ ensureMyPersonEntity: () =>
110
+ Promise.resolve({
111
+ uid: "prs_01KY0B91T726CBRKT16P5H9TRX",
112
+ type: "person",
113
+ slug: "michelle",
114
+ status: "active",
115
+ } as unknown as EntityInfo),
116
+ entity: {
117
+ get: (uid: string) => {
118
+ const c = byUid.get(uid);
119
+ if (!c) return Promise.resolve(undefined as unknown as EntityInfo);
120
+ return Promise.resolve({
121
+ uid: c.uid,
122
+ slug: c.slug,
123
+ name: c.name,
124
+ type: "company",
125
+ status: "active",
126
+ bucketName: `hq-vault-${c.slug}`,
127
+ createdAt: "2026-01-01T00:00:00Z",
128
+ } as unknown as EntityInfo);
129
+ },
130
+ listByType: () => Promise.resolve([]),
131
+ },
132
+ } as unknown as VaultClientSurface;
133
+ }
134
+
135
+ function makeDeps(
136
+ companies: readonly CompanyFixture[],
137
+ ): RunnerDeps & { stdout: ReturnType<typeof makeWriter>; stderr: ReturnType<typeof makeWriter> } {
138
+ const stdout = makeWriter();
139
+ const stderr = makeWriter();
140
+ return {
141
+ getAccessToken: vi.fn().mockResolvedValue("test-access-token"),
142
+ clearSession: vi.fn(),
143
+ getIdTokenClaims: vi.fn().mockReturnValue(null),
144
+ createVaultClient: vi.fn(() => joinerVaultClient(companies)),
145
+ sync: vi.fn().mockResolvedValue({
146
+ filesDownloaded: 0,
147
+ bytesDownloaded: 0,
148
+ filesSkipped: 0,
149
+ conflicts: 0,
150
+ conflictPaths: [],
151
+ aborted: false,
152
+ newFiles: [],
153
+ newFilesCount: 0,
154
+ filesExcludedByPolicy: 0,
155
+ filesTombstoned: 0,
156
+ filesOutOfScope: 0,
157
+ scopeOrphansRemoved: 0,
158
+ scopeOrphansBlocked: 0,
159
+ changedPaths: [],
160
+ }),
161
+ reindex: vi.fn(() => ({ status: 0 })),
162
+ qmdReindex: vi.fn(() => ({
163
+ qmdAvailable: true,
164
+ collectionsAdded: [],
165
+ updated: true,
166
+ embedded: false,
167
+ pendingDirty: false,
168
+ })),
169
+ // NOTE: reconcileManifest and seedActiveCompany are deliberately NOT
170
+ // stubbed. Stubbing them is what let this defect hide.
171
+ stdout,
172
+ stderr,
173
+ } as unknown as RunnerDeps & {
174
+ stdout: ReturnType<typeof makeWriter>;
175
+ stderr: ReturnType<typeof makeWriter>;
176
+ };
177
+ }
178
+
179
+ const BORING_ECOM: CompanyFixture = {
180
+ uid: "cmp_01KR1QTBSATVKFRTZ5CFNEYA0Q",
181
+ slug: "boring-ecom",
182
+ name: "Boring Ecom",
183
+ };
184
+
185
+ describe("joiner manifest reconciliation (end to end)", () => {
186
+ it("restores the manifest entry and seeds activeCompany for a single-company joiner", async () => {
187
+ hqRoot = makeJoinerRoot([BORING_ECOM]);
188
+ const deps = makeDeps([BORING_ECOM]);
189
+
190
+ expect(await runRunner(["--companies", "--hq-root", hqRoot], deps)).toBe(0);
191
+
192
+ // The entry she was missing — with the real cloud_uid, not an invented one.
193
+ const companies = readManifest(hqRoot);
194
+ expect(Object.keys(companies)).toEqual(["boring-ecom"]);
195
+ expect(companies["boring-ecom"]).toEqual({
196
+ name: "Boring Ecom",
197
+ cloud_uid: "cmp_01KR1QTBSATVKFRTZ5CFNEYA0Q",
198
+ bucket_name: "hq-vault-boring-ecom",
199
+ });
200
+
201
+ // ...and HQ now knows which company is current, so she is not left unrouted.
202
+ expect(readConfig(hqRoot).activeCompany).toBe("boring-ecom");
203
+ });
204
+
205
+ it("writes both entries but refuses to guess activeCompany for a two-company member", async () => {
206
+ const acme: CompanyFixture = { uid: "cmp_acme", slug: "acme", name: "Acme" };
207
+ hqRoot = makeJoinerRoot([BORING_ECOM, acme]);
208
+ const deps = makeDeps([BORING_ECOM, acme]);
209
+
210
+ expect(await runRunner(["--companies", "--hq-root", hqRoot], deps)).toBe(0);
211
+
212
+ const companies = readManifest(hqRoot);
213
+ expect(Object.keys(companies).sort()).toEqual(["acme", "boring-ecom"]);
214
+ expect(companies["acme"]).toMatchObject({ cloud_uid: "cmp_acme" });
215
+
216
+ // Two companies is a real choice and it is hers. Picking one would route
217
+ // her somewhere arbitrary.
218
+ expect(readConfig(hqRoot).activeCompany).toBeUndefined();
219
+ });
220
+
221
+ // The conflict-loop guard. manifest.yaml rides in the personal vault, so an
222
+ // unconditional rewrite would be pushed on every sync and re-create the
223
+ // documented conflict loop for every user on every machine.
224
+ it("performs no manifest write on a second, steady-state sync", async () => {
225
+ hqRoot = makeJoinerRoot([BORING_ECOM]);
226
+
227
+ expect(
228
+ await runRunner(["--companies", "--hq-root", hqRoot], makeDeps([BORING_ECOM])),
229
+ ).toBe(0);
230
+
231
+ const manifestPath = path.join(hqRoot, "companies", "manifest.yaml");
232
+ const afterFirst = fs.readFileSync(manifestPath, "utf8");
233
+ // Freeze the mtime far enough back that any rewrite is unmistakable.
234
+ const frozen = new Date("2020-01-01T00:00:00.000Z");
235
+ fs.utimesSync(manifestPath, frozen, frozen);
236
+
237
+ const second = makeDeps([BORING_ECOM]);
238
+ expect(await runRunner(["--companies", "--hq-root", hqRoot], second)).toBe(0);
239
+
240
+ expect(fs.readFileSync(manifestPath, "utf8")).toBe(afterFirst);
241
+ expect(fs.statSync(manifestPath).mtimeMs).toBe(frozen.getTime());
242
+ // Silence is the contract: a steady-state sync that reports a reconcile is
243
+ // the signal that skip-if-unchanged has regressed.
244
+ expect(second.stderr.raw()).not.toContain("manifest-reconciled");
245
+ });
246
+
247
+ it("never overwrites an activeCompany the user already chose", async () => {
248
+ hqRoot = makeJoinerRoot([BORING_ECOM]);
249
+ fs.mkdirSync(path.join(hqRoot, ".hq"), { recursive: true });
250
+ fs.writeFileSync(
251
+ path.join(hqRoot, ".hq", "config.json"),
252
+ JSON.stringify({ activeCompany: "chosen-by-user" }),
253
+ "utf8",
254
+ );
255
+
256
+ expect(
257
+ await runRunner(["--companies", "--hq-root", hqRoot], makeDeps([BORING_ECOM])),
258
+ ).toBe(0);
259
+
260
+ expect(readConfig(hqRoot).activeCompany).toBe("chosen-by-user");
261
+ // The manifest repair still happens — the two are independent.
262
+ expect(Object.keys(readManifest(hqRoot))).toEqual(["boring-ecom"]);
263
+ });
264
+
265
+ it("preserves the manifest header comment through the first write", async () => {
266
+ hqRoot = makeJoinerRoot([BORING_ECOM]);
267
+
268
+ expect(
269
+ await runRunner(["--companies", "--hq-root", hqRoot], makeDeps([BORING_ECOM])),
270
+ ).toBe(0);
271
+
272
+ const raw = fs.readFileSync(
273
+ path.join(hqRoot, "companies", "manifest.yaml"),
274
+ "utf8",
275
+ );
276
+ expect(Object.keys(readManifest(hqRoot))).toEqual(["boring-ecom"]);
277
+ // Documents the CURRENT behaviour: the write re-dumps the document, so the
278
+ // human-authored header does not survive. Tracked as a follow-up (see
279
+ // review-findings P1) — this assertion exists so a fix flips it loudly
280
+ // rather than silently.
281
+ expect(raw).not.toContain("# HQ company manifest.");
282
+ });
283
+ });