@indigoai-us/hq-cloud 6.18.7 → 6.18.8

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.
@@ -6,6 +6,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
6
6
  import * as fs from "fs";
7
7
  import * as path from "path";
8
8
  import * as os from "os";
9
+ import crypto from "crypto";
9
10
  import { clearContextCache } from "../context.js";
10
11
  // Re-export node:fs as a mutable module so the large-tree regression can
11
12
  // replace only readdirSync; normal tests retain the real implementation.
@@ -32,7 +33,7 @@ vi.mock("../s3.js", async (importOriginal) => {
32
33
  primeObjectTransport: vi.fn().mockResolvedValue(undefined),
33
34
  primeUploads: vi.fn().mockResolvedValue(undefined),
34
35
  publishedContentHash: actual.publishedContentHash,
35
- setUploadContentHash: actual.setUploadContentHash,
36
+ setUploadContentHash: vi.fn(actual.setUploadContentHash),
36
37
  // Real exports share.ts now imports for the HQ-DESKTOP-54 privilege skip.
37
38
  WINDOWS_SYMLINK_PRIVILEGE_REMEDY: "Enable Windows Developer Mode (Settings > Privacy & security > For developers) or run HQ sync once from an elevated terminal, then sync again.",
38
39
  WindowsSymlinkPrivilegeError: class WindowsSymlinkPrivilegeError extends Error {
@@ -58,6 +59,10 @@ vi.mock("../s3.js", async (importOriginal) => {
58
59
  // prompt lifecycle (createInterface + close) without ever touching stdin.
59
60
  // Default impl never resolves; conflict-prompt tests below override per-test
60
61
  // to script answers.
62
+ vi.mock("../lib/skill-register-landed-bytes.js", async (importOriginal) => {
63
+ const actual = await importOriginal();
64
+ return { ...actual, resolveSkillRegisterLandedBytes: vi.fn().mockResolvedValue(false) };
65
+ });
61
66
  vi.mock("readline", () => ({
62
67
  createInterface: vi.fn(() => ({
63
68
  question: vi.fn(),
@@ -66,10 +71,11 @@ vi.mock("readline", () => ({
66
71
  }));
67
72
  import * as readline from "readline";
68
73
  import { share, ServerOwnedPushPathsError, UnreachablePushPathsError, UnregisteredCompanySkillError, currentUploadBytes, FULL_PUSH_COOPERATIVE_CHECKPOINT_BATCH_SIZE, parseRegisteredCompanySkillUid, setPushCollectCooperativeYieldMsForTesting, _testing as shareTesting, } from "./share.js";
69
- import { deleteRemoteFile, downloadFile, headRemoteFile, primeObjectTransport, primeUploads, uploadFile, uploadSymlink, WindowsSymlinkPrivilegeError, } from "../s3.js";
74
+ import { deleteRemoteFile, downloadFile, headRemoteFile, primeObjectTransport, primeUploads, setUploadContentHash, uploadFile, uploadSymlink, WindowsSymlinkPrivilegeError, } from "../s3.js";
70
75
  import { VaultAuthError, VaultClientError, VaultConflictError, VaultPermissionDeniedError, } from "../vault-client.js";
71
76
  import { CognitoRefreshError } from "../cognito-auth.js";
72
77
  import { RateLimitedError } from "../object-io.js";
78
+ import { resolveSkillRegisterLandedBytes } from "../lib/skill-register-landed-bytes.js";
73
79
  import { AreaLedgerMigration, closeCachedAreaJournalMigration, hashFile, openJournalStateStoreForMigration, readJournal, readJournalScoped, setAreaLedgerMigrationTestHooksForTest, writeJournal, } from "../journal.js";
74
80
  import { ReconcileCursorStore } from "../sync/reconcile-cursor.js";
75
81
  import { AreaResolver } from "../sync/area-resolver.js";
@@ -242,6 +248,107 @@ describe("company skill identity preflight", () => {
242
248
  landed: true,
243
249
  });
244
250
  });
251
+ it("registers the exact upload bytes when the landed-bytes flag is on", async () => {
252
+ const original = "---\nname: Existing\ndescription: Ready\nskill_uid: skl_EXISTING1\ntags: [sales]\n---\n";
253
+ const changedDuringUpload = original.replace("[sales]", "[support]");
254
+ const file = createSkill("same-bytes", original);
255
+ vi.mocked(resolveSkillRegisterLandedBytes).mockResolvedValueOnce(true);
256
+ let uploadedBody;
257
+ vi.mocked(uploadFile).mockImplementationOnce(async (...args) => {
258
+ fs.writeFileSync(file, changedDuringUpload);
259
+ uploadedBody = args[6] ?? fs.readFileSync(file);
260
+ fs.writeFileSync(file, original);
261
+ return { etag: '"upload-etag"' };
262
+ });
263
+ const registrar = vi.fn(async (input) => registered(input, "skl_EXISTING1"));
264
+ await share({
265
+ paths: [file],
266
+ hqRoot,
267
+ entityContext: makeEntityContext(),
268
+ registerCompanySkill: registrar,
269
+ });
270
+ const landed = registrar.mock.calls.find(([input]) => input.landed === true);
271
+ expect(uploadedBody).toBeDefined();
272
+ expect(landed?.[0].content).toBe(uploadedBody.toString("utf8"));
273
+ });
274
+ it("replans a skill edited before landed-byte capture and keeps its upload hash aligned", async () => {
275
+ const original = "---\nname: Existing\ndescription: Ready\nskill_uid: skl_EXISTING1\ntags: [sales]\n---\n";
276
+ const changed = original.replace("[sales]", "[other]");
277
+ const file = createSkill("changed-before-capture", original);
278
+ vi.mocked(resolveSkillRegisterLandedBytes).mockResolvedValueOnce(true);
279
+ vi.mocked(setUploadContentHash).mockClear();
280
+ const realReadFileSync = fs.readFileSync.bind(fs);
281
+ let skillByteReads = 0;
282
+ let changedAfterHash = false;
283
+ const readSpy = vi.spyOn(fs, "readFileSync").mockImplementation(((pathname, options) => {
284
+ if (pathname === file && options === undefined) {
285
+ skillByteReads += 1;
286
+ if (skillByteReads === 2) {
287
+ changedAfterHash = true;
288
+ const before = fs.statSync(file);
289
+ fs.writeFileSync(file, changed);
290
+ fs.utimesSync(file, before.atime, new Date(before.mtimeMs + 2_000));
291
+ }
292
+ }
293
+ return realReadFileSync(pathname, options);
294
+ }));
295
+ let uploadedBytes;
296
+ let uploadedHash;
297
+ let byteReadsWhenUploaded = 0;
298
+ vi.mocked(uploadFile).mockImplementationOnce(async (...args) => {
299
+ uploadedBytes = args[6];
300
+ uploadedHash = vi.mocked(setUploadContentHash).mock.calls.at(-1)?.[1];
301
+ byteReadsWhenUploaded = skillByteReads;
302
+ return { etag: '"upload-etag"' };
303
+ });
304
+ const registrar = vi.fn(async (input) => registered(input, "skl_EXISTING1"));
305
+ let result;
306
+ try {
307
+ result = await share({
308
+ paths: [file],
309
+ hqRoot,
310
+ entityContext: makeEntityContext(),
311
+ registerCompanySkill: registrar,
312
+ });
313
+ }
314
+ finally {
315
+ readSpy.mockRestore();
316
+ }
317
+ const landed = registrar.mock.calls.find(([input]) => input.landed === true);
318
+ expect(changedAfterHash).toBe(true);
319
+ expect(result.filesUploaded).toBe(1);
320
+ expect(uploadFile).toHaveBeenCalledOnce();
321
+ expect(uploadedBytes?.toString("utf8")).toBe(changed);
322
+ expect(uploadedHash).toBe(crypto.createHash("sha256").update(uploadedBytes).digest("hex"));
323
+ expect(headRemoteFile).toHaveBeenCalledTimes(2);
324
+ expect(byteReadsWhenUploaded).toBeGreaterThan(2);
325
+ expect(setUploadContentHash).toHaveBeenCalledOnce();
326
+ expect(landed?.[0]).toMatchObject({ content: changed, landed: true });
327
+ expect(crypto.createHash("sha256").update(landed[0].content).digest("hex")).toBe(uploadedHash);
328
+ expect(readJournal("acme").files["skills/changed-before-capture/SKILL.md"]?.hash)
329
+ .toBe(uploadedHash);
330
+ });
331
+ it("keeps the current upload and registration path when the flag is off", async () => {
332
+ const content = "---\nname: Existing\ndescription: Ready\nskill_uid: skl_EXISTING1\ntags: [sales]\n---\n";
333
+ const file = createSkill("flag-off", content);
334
+ let uploadedBody;
335
+ vi.mocked(uploadFile).mockImplementationOnce(async (...args) => {
336
+ uploadedBody = fs.readFileSync(args[1]);
337
+ return { etag: '"upload-etag"' };
338
+ });
339
+ const registrar = vi.fn(async (input) => registered(input, "skl_EXISTING1"));
340
+ const result = await share({
341
+ paths: [file],
342
+ hqRoot,
343
+ entityContext: makeEntityContext(),
344
+ registerCompanySkill: registrar,
345
+ });
346
+ const landed = registrar.mock.calls.find(([input]) => input.landed === true);
347
+ expect(uploadedBody?.toString("utf8")).toBe(content);
348
+ expect(landed?.[0].content).toBe(uploadedBody?.toString("utf8"));
349
+ expect(vi.mocked(uploadFile).mock.calls.at(-1)).toHaveLength(5);
350
+ expect(result).not.toHaveProperty("skillRegistrationFallbacks");
351
+ });
245
352
  it("fails closed without an authenticated registration seam", async () => {
246
353
  const file = createSkill("manual", "---\nname: Manual\ndescription: Missing id\n---\n");
247
354
  await expect(share({
@@ -972,9 +1079,10 @@ describe("company skill identity preflight", () => {
972
1079
  const copied = "---\nname: Copied\ndescription: Copied skill\nskill_uid: skl_SOURCE1\n---\n\nWork.\n";
973
1080
  const file = createSkill("copied", copied);
974
1081
  const landedCalls = [];
975
- // Model the server: a landed call for the source-stamped copy 409s; a
976
- // non-landed call forks a fresh identity for this path; and a landed call
977
- // that now carries the FORKED identity reconciles successfully.
1082
+ let nonLandedCalls = 0;
1083
+ // Model the server: preflight reuses the source identity, its landed call
1084
+ // 409s, the one recovery fallback forks a fresh identity, and its landed
1085
+ // retry reconciles successfully.
978
1086
  const registrar = vi.fn(async (input) => {
979
1087
  landedCalls.push(input.landed === true);
980
1088
  const uid = parseRegisteredCompanySkillUid(input.content);
@@ -995,9 +1103,13 @@ describe("company skill identity preflight", () => {
995
1103
  // skill on a landed call — the exact 409 behind HQ-DESKTOP-6T/64.
996
1104
  throw new VaultConflictError("The landed skill does not carry the registered identity for this path");
997
1105
  }
998
- return forkedRegistration(input);
1106
+ nonLandedCalls += 1;
1107
+ return nonLandedCalls === 1
1108
+ ? registered(input, "skl_SOURCE1")
1109
+ : forkedRegistration(input);
999
1110
  });
1000
1111
  const events = [];
1112
+ vi.mocked(resolveSkillRegisterLandedBytes).mockResolvedValueOnce(true);
1001
1113
  const result = await share({
1002
1114
  paths: [file],
1003
1115
  hqRoot,
@@ -1007,9 +1119,11 @@ describe("company skill identity preflight", () => {
1007
1119
  });
1008
1120
  expect(result.filesUploaded).toBe(1);
1009
1121
  expect(result.aborted).toBe(false);
1010
- // The landed reconcile 409'd, then the non-landed fallback ran (a fork).
1011
- expect(landedCalls).toContain(true);
1012
- expect(landedCalls).toContain(false);
1122
+ expect(result.skillRegistrationFallbacks).toBe(1);
1123
+ // Preflight reserved once, then the landed reconcile 409'd and recovery
1124
+ // performed exactly one non-landed fallback before one landed retry.
1125
+ expect(nonLandedCalls).toBe(2);
1126
+ expect(landedCalls.filter(Boolean)).toHaveLength(2);
1013
1127
  // The forked, re-stamped bytes were written back so the planner re-uploads.
1014
1128
  expect(parseRegisteredCompanySkillUid(fs.readFileSync(file, "utf8"))).toBe("skl_FORKED1");
1015
1129
  // No per-file error (the pass-1 HQ-DESKTOP-6T error) and no unresolved
@@ -2729,6 +2843,9 @@ describe("share", () => {
2729
2843
  const before = fs.lstatSync(abs);
2730
2844
  await new Promise((resolve) => setTimeout(resolve, 5));
2731
2845
  fs.writeFileSync(abs, CONTENT_B); // same length, different bytes
2846
+ // Keep the rewrite and timestamp restoration in distinct ctime ticks on
2847
+ // filesystems whose ctime clock is coarser than the file writes.
2848
+ await new Promise((resolve) => setTimeout(resolve, 10));
2732
2849
  fs.utimesSync(abs, before.atime, before.mtime); // put the old mtime back
2733
2850
  const after = fs.lstatSync(abs);
2734
2851
  // Preconditions. The disguise worked on size, and as closely on mtime as