@indigoai-us/hq-cloud 6.14.22 → 6.14.24

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 (120) hide show
  1. package/dist/bin/sync-runner-company.d.ts.map +1 -1
  2. package/dist/bin/sync-runner-company.js +20 -0
  3. package/dist/bin/sync-runner-company.js.map +1 -1
  4. package/dist/bin/sync-runner-events.test.js +22 -0
  5. package/dist/bin/sync-runner-events.test.js.map +1 -1
  6. package/dist/bin/sync-runner-planning.d.ts +11 -0
  7. package/dist/bin/sync-runner-planning.d.ts.map +1 -1
  8. package/dist/bin/sync-runner-planning.js +37 -2
  9. package/dist/bin/sync-runner-planning.js.map +1 -1
  10. package/dist/bin/sync-runner-planning.test.js +1 -0
  11. package/dist/bin/sync-runner-planning.test.js.map +1 -1
  12. package/dist/bin/sync-runner-watch-loop.d.ts.map +1 -1
  13. package/dist/bin/sync-runner-watch-loop.js +17 -1
  14. package/dist/bin/sync-runner-watch-loop.js.map +1 -1
  15. package/dist/bin/sync-runner.d.ts +33 -1
  16. package/dist/bin/sync-runner.d.ts.map +1 -1
  17. package/dist/bin/sync-runner.js +28 -3
  18. package/dist/bin/sync-runner.js.map +1 -1
  19. package/dist/bin/sync-runner.test.js +206 -2
  20. package/dist/bin/sync-runner.test.js.map +1 -1
  21. package/dist/cli/doctor.d.ts +119 -0
  22. package/dist/cli/doctor.d.ts.map +1 -0
  23. package/dist/cli/doctor.js +485 -0
  24. package/dist/cli/doctor.js.map +1 -0
  25. package/dist/cli/doctor.test.d.ts +13 -0
  26. package/dist/cli/doctor.test.d.ts.map +1 -0
  27. package/dist/cli/doctor.test.js +485 -0
  28. package/dist/cli/doctor.test.js.map +1 -0
  29. package/dist/cli/index.d.ts +2 -0
  30. package/dist/cli/index.d.ts.map +1 -1
  31. package/dist/cli/index.js +4 -0
  32. package/dist/cli/index.js.map +1 -1
  33. package/dist/cli/share.js +6 -1
  34. package/dist/cli/share.js.map +1 -1
  35. package/dist/cli/share.test.js +1 -0
  36. package/dist/cli/share.test.js.map +1 -1
  37. package/dist/cli/sync.d.ts +54 -0
  38. package/dist/cli/sync.d.ts.map +1 -1
  39. package/dist/cli/sync.js +223 -3
  40. package/dist/cli/sync.js.map +1 -1
  41. package/dist/cli/sync.test.js +394 -1
  42. package/dist/cli/sync.test.js.map +1 -1
  43. package/dist/cognito-auth.test.js +7 -0
  44. package/dist/cognito-auth.test.js.map +1 -1
  45. package/dist/index.d.ts +2 -0
  46. package/dist/index.d.ts.map +1 -1
  47. package/dist/index.js +3 -0
  48. package/dist/index.js.map +1 -1
  49. package/dist/lib/conflict-file.d.ts.map +1 -1
  50. package/dist/lib/conflict-file.js +5 -1
  51. package/dist/lib/conflict-file.js.map +1 -1
  52. package/dist/lib/conflict-index.d.ts +7 -0
  53. package/dist/lib/conflict-index.d.ts.map +1 -1
  54. package/dist/lib/conflict-index.js +10 -2
  55. package/dist/lib/conflict-index.js.map +1 -1
  56. package/dist/lib/conflict.test.js +31 -0
  57. package/dist/lib/conflict.test.js.map +1 -1
  58. package/dist/lib/machine-id.test.js +14 -0
  59. package/dist/lib/machine-id.test.js.map +1 -1
  60. package/dist/local-path-codec.d.ts +18 -0
  61. package/dist/local-path-codec.d.ts.map +1 -1
  62. package/dist/local-path-codec.js +63 -0
  63. package/dist/local-path-codec.js.map +1 -1
  64. package/dist/local-path-codec.test.d.ts +14 -0
  65. package/dist/local-path-codec.test.d.ts.map +1 -0
  66. package/dist/local-path-codec.test.js +102 -0
  67. package/dist/local-path-codec.test.js.map +1 -0
  68. package/dist/machine-auth.test.js +7 -0
  69. package/dist/machine-auth.test.js.map +1 -1
  70. package/dist/s3.d.ts +5 -0
  71. package/dist/s3.d.ts.map +1 -1
  72. package/dist/s3.js +129 -3
  73. package/dist/s3.js.map +1 -1
  74. package/dist/s3.symlink-materialize.test.d.ts +18 -0
  75. package/dist/s3.symlink-materialize.test.d.ts.map +1 -0
  76. package/dist/s3.symlink-materialize.test.js +394 -0
  77. package/dist/s3.symlink-materialize.test.js.map +1 -0
  78. package/dist/s3.test.js +19 -0
  79. package/dist/s3.test.js.map +1 -1
  80. package/dist/skill-telemetry.d.ts.map +1 -1
  81. package/dist/skill-telemetry.js +23 -2
  82. package/dist/skill-telemetry.js.map +1 -1
  83. package/dist/skill-telemetry.test.js +17 -0
  84. package/dist/skill-telemetry.test.js.map +1 -1
  85. package/dist/watcher.d.ts.map +1 -1
  86. package/dist/watcher.js +10 -1
  87. package/dist/watcher.js.map +1 -1
  88. package/dist/watcher.test.js +28 -0
  89. package/dist/watcher.test.js.map +1 -1
  90. package/package.json +1 -1
  91. package/src/bin/sync-runner-company.ts +18 -0
  92. package/src/bin/sync-runner-events.test.ts +31 -0
  93. package/src/bin/sync-runner-planning.test.ts +1 -0
  94. package/src/bin/sync-runner-planning.ts +46 -3
  95. package/src/bin/sync-runner-watch-loop.ts +19 -1
  96. package/src/bin/sync-runner.test.ts +236 -1
  97. package/src/bin/sync-runner.ts +57 -2
  98. package/src/cli/doctor.test.ts +581 -0
  99. package/src/cli/doctor.ts +640 -0
  100. package/src/cli/index.ts +14 -0
  101. package/src/cli/share.test.ts +1 -0
  102. package/src/cli/share.ts +6 -1
  103. package/src/cli/sync.test.ts +473 -1
  104. package/src/cli/sync.ts +310 -3
  105. package/src/cognito-auth.test.ts +5 -0
  106. package/src/index.ts +10 -0
  107. package/src/lib/conflict-file.ts +6 -1
  108. package/src/lib/conflict-index.ts +18 -2
  109. package/src/lib/conflict.test.ts +33 -0
  110. package/src/lib/machine-id.test.ts +10 -0
  111. package/src/local-path-codec.test.ts +138 -0
  112. package/src/local-path-codec.ts +66 -0
  113. package/src/machine-auth.test.ts +5 -0
  114. package/src/s3.symlink-materialize.test.ts +492 -0
  115. package/src/s3.test.ts +24 -0
  116. package/src/s3.ts +148 -4
  117. package/src/skill-telemetry.test.ts +19 -0
  118. package/src/skill-telemetry.ts +31 -2
  119. package/src/watcher.test.ts +33 -0
  120. package/src/watcher.ts +10 -1
@@ -0,0 +1,492 @@
1
+ /**
2
+ * Regression tests for US-001 (hq-sync-windows-skill-symlink-collision):
3
+ * Windows-safe, idempotent symlink materialization in downloadFile.
4
+ *
5
+ * Background: the .claude/skills/<ns>:<skill> link farm is materialized from
6
+ * `hq-symlink:<target>` records. Pre-fix, downloadFile always did
7
+ * symlinkSync(temp) + renameSync(temp, dest). On Windows that is doubly
8
+ * broken: (1) rename() can never replace an existing directory — and a
9
+ * directory symlink counts as one — so every pull over the farm EPERM'd,
10
+ * never journaled, and re-downloaded forever; (2) a bare symlinkSync mints a
11
+ * FILE-type link, which is broken for directory targets on Windows.
12
+ *
13
+ * Windows semantics are exercised via the injectable `win32` option (the
14
+ * local-path-codec.ts convention) plus scripted fs fakes, so these tests are
15
+ * deterministic on POSIX CI and on a real Windows host alike.
16
+ */
17
+
18
+ import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
19
+ import * as fs from "fs";
20
+ import * as os from "os";
21
+ import * as path from "path";
22
+
23
+ // Re-export node:fs as a plain mutable object so vi.spyOn can instrument
24
+ // individual functions (the frozen ESM namespace of a builtin cannot be
25
+ // spied on directly). Every copied function still delegates to the real
26
+ // implementation until a test overrides it.
27
+ vi.mock("fs", async (importOriginal) => {
28
+ const actual = await importOriginal<typeof import("fs")>();
29
+ return { ...actual };
30
+ });
31
+
32
+ import { downloadFile, SYMLINK_BODY_PREFIX, SYMLINK_MARKER_META_VALUE } from "./s3.js";
33
+ import { localPathForVaultKey } from "./local-path-codec.js";
34
+ import { setObjectIOFactory, type ObjectIO } from "./object-io.js";
35
+ import type { EntityContext } from "./types.js";
36
+
37
+ function makeCtx(): EntityContext {
38
+ return {
39
+ uid: "cmp_TEST",
40
+ slug: "acme",
41
+ bucketName: "hq-vault-acme-123",
42
+ region: "us-east-1",
43
+ credentials: {
44
+ accessKeyId: "ASIA_TEST",
45
+ secretAccessKey: "secret",
46
+ sessionToken: "session",
47
+ },
48
+ expiresAt: new Date(Date.now() + 15 * 60 * 1000).toISOString(),
49
+ };
50
+ }
51
+
52
+ /** ObjectIO stub serving a single symlink record (marker + prefixed body). */
53
+ function symlinkRecordIO(target: string): ObjectIO {
54
+ return {
55
+ putObject: async () => ({ etag: '"unused"' }),
56
+ getObject: async () => ({
57
+ body: Buffer.from(SYMLINK_BODY_PREFIX + target, "utf-8"),
58
+ metadata: { "hq-symlink-target": SYMLINK_MARKER_META_VALUE },
59
+ }),
60
+ listObjects: async () => ({ objects: [] }),
61
+ deleteObject: async () => undefined,
62
+ headObject: async () => null,
63
+ };
64
+ }
65
+
66
+ function errnoError(code: string): NodeJS.ErrnoException {
67
+ const err = new Error(`${code}: scripted test failure`) as NodeJS.ErrnoException;
68
+ err.code = code;
69
+ return err;
70
+ }
71
+
72
+ /** Minimal fs.Stats fake — only the predicates downloadFile consults. */
73
+ function fakeStats(shape: {
74
+ symlink?: boolean;
75
+ dir?: boolean;
76
+ file?: boolean;
77
+ }): fs.Stats {
78
+ return {
79
+ isSymbolicLink: () => shape.symlink ?? false,
80
+ isDirectory: () => shape.dir ?? false,
81
+ isFile: () => shape.file ?? false,
82
+ } as unknown as fs.Stats;
83
+ }
84
+
85
+ describe("downloadFile symlink materialization (US-001)", () => {
86
+ let tmpRoot: string;
87
+
88
+ beforeEach(() => {
89
+ tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), "s3-symlink-mat-test-"));
90
+ });
91
+
92
+ afterEach(() => {
93
+ vi.restoreAllMocks();
94
+ setObjectIOFactory(null);
95
+ fs.rmSync(tmpRoot, { recursive: true, force: true });
96
+ });
97
+
98
+ it("fast path: an unchanged symlink is a success WITHOUT touching disk", async () => {
99
+ // The perpetual-churn half of the bug: an already-correct link went
100
+ // through temp+rename anyway, EPERM'd on Windows, never journaled, and
101
+ // re-downloaded every pass. A pull whose incoming target matches the
102
+ // existing link must return success (so the caller journals it) with
103
+ // zero writes — no temp link, no rename, no beforeReplace.
104
+ const target = "../real-target.md";
105
+ const localPath = path.join(tmpRoot, "skills", "link.md");
106
+ fs.mkdirSync(path.dirname(localPath), { recursive: true });
107
+ // Real target on disk: the win32 fast path stat-follows the link to
108
+ // confirm it functions as the desired type (a dangling link would
109
+ // deliberately fall through to replacement).
110
+ fs.writeFileSync(path.join(tmpRoot, "real-target.md"), "target body");
111
+ fs.symlinkSync(target, localPath);
112
+ setObjectIOFactory(() => symlinkRecordIO(target));
113
+
114
+ const symlinkSpy = vi.spyOn(fs, "symlinkSync");
115
+ const renameSpy = vi.spyOn(fs, "renameSync");
116
+ const beforeReplace = vi.fn();
117
+
118
+ const res = await downloadFile(makeCtx(), "skills/link.md", localPath, {
119
+ beforeReplace,
120
+ });
121
+
122
+ // Success shape matches a materializing pull, so the caller journals it.
123
+ expect(res.metadata?.["hq-symlink-target"]).toBe(SYMLINK_MARKER_META_VALUE);
124
+ expect(symlinkSpy).not.toHaveBeenCalled();
125
+ expect(renameSpy).not.toHaveBeenCalled();
126
+ expect(beforeReplace).not.toHaveBeenCalled();
127
+ expect(fs.lstatSync(localPath).isSymbolicLink()).toBe(true);
128
+ });
129
+
130
+ it("fast path compares readlink() separator-insensitively on win32", async () => {
131
+ // Windows stores the substitute path with backslashes (Node converts
132
+ // '/' at symlink() time), so readlink() of a link created from the
133
+ // POSIX-slashed wire target returns '..\\dir\\target'. The comparison
134
+ // must treat that as equal to the incoming '../dir/target' or the fast
135
+ // path would never fire for any multi-segment target on Windows.
136
+ const wireTarget = "../companies/indigo/skills/call-prep-brief";
137
+ const localPath = path.join(tmpRoot, "farm", "indigo%3Acall-prep-brief");
138
+ fs.mkdirSync(path.dirname(localPath), { recursive: true });
139
+ // Real directory at the resolved target: the link farm's normal shape,
140
+ // and what makes the desired flavor directory-ish (a junction, post-#219).
141
+ fs.mkdirSync(path.resolve(path.dirname(localPath), wireTarget), {
142
+ recursive: true,
143
+ });
144
+ setObjectIOFactory(() => symlinkRecordIO(wireTarget));
145
+
146
+ vi.spyOn(fs, "lstatSync").mockImplementation(() =>
147
+ fakeStats({ symlink: true }),
148
+ );
149
+ // A RELATIVE substitute path — the spelling an older client's 'dir'
150
+ // symlink left behind. It still resolves to the same target, so the
151
+ // fast path must accept it rather than churn the link.
152
+ vi.spyOn(fs, "readlinkSync").mockImplementation(
153
+ () => "..\\companies\\indigo\\skills\\call-prep-brief",
154
+ );
155
+ const realStatSync = fs.statSync.bind(fs) as (p: fs.PathLike) => fs.Stats;
156
+ // The follow-probe on the link itself reports a traversable directory,
157
+ // matching the flavor createStagedSymlink would mint — fast path holds.
158
+ vi.spyOn(fs, "statSync").mockImplementation(((p: fs.PathLike) =>
159
+ p === localPath
160
+ ? fakeStats({ dir: true })
161
+ : realStatSync(p)) as typeof fs.statSync);
162
+ const symlinkSpy = vi.spyOn(fs, "symlinkSync");
163
+ const renameSpy = vi.spyOn(fs, "renameSync");
164
+
165
+ const res = await downloadFile(
166
+ makeCtx(),
167
+ ".claude/skills/indigo:call-prep-brief",
168
+ localPath,
169
+ { win32: true },
170
+ );
171
+
172
+ expect(res.metadata).toBeDefined();
173
+ expect(symlinkSpy).not.toHaveBeenCalled();
174
+ expect(renameSpy).not.toHaveBeenCalled();
175
+ });
176
+
177
+ it("fast path accepts a JUNCTION's absolute substitute path against a relative wire target", async () => {
178
+ // Post-#219, win32 directory overlays are materialized as junctions, and
179
+ // a junction can only store an ABSOLUTE substitute path. readlink() of a
180
+ // link this client itself created therefore returns
181
+ // 'C:\\...\\companies\\indigo\\skills\\call-prep-brief' while the wire
182
+ // target stays '../companies/...'. If equality were a raw string compare
183
+ // the fast path could never fire for the link farm on Windows — every
184
+ // pull would re-stage the whole farm, which is precisely the perpetual
185
+ // churn US-001 exists to kill. Both sides must be resolved before compare.
186
+ const wireTarget = "../companies/indigo/skills/call-prep-brief";
187
+ const localPath = path.join(tmpRoot, "farm", "indigo%3Acall-prep-brief");
188
+ fs.mkdirSync(path.dirname(localPath), { recursive: true });
189
+ const absTarget = path.resolve(path.dirname(localPath), wireTarget);
190
+ fs.mkdirSync(absTarget, { recursive: true });
191
+ setObjectIOFactory(() => symlinkRecordIO(wireTarget));
192
+
193
+ vi.spyOn(fs, "lstatSync").mockImplementation(() =>
194
+ fakeStats({ symlink: true }),
195
+ );
196
+ vi.spyOn(fs, "readlinkSync").mockImplementation(() =>
197
+ absTarget.split("/").join("\\"),
198
+ );
199
+ const realStatSync = fs.statSync.bind(fs) as (p: fs.PathLike) => fs.Stats;
200
+ vi.spyOn(fs, "statSync").mockImplementation(((p: fs.PathLike) =>
201
+ p === localPath
202
+ ? fakeStats({ dir: true })
203
+ : realStatSync(p)) as typeof fs.statSync);
204
+ const symlinkSpy = vi.spyOn(fs, "symlinkSync");
205
+ const renameSpy = vi.spyOn(fs, "renameSync");
206
+
207
+ const res = await downloadFile(
208
+ makeCtx(),
209
+ ".claude/skills/indigo:call-prep-brief",
210
+ localPath,
211
+ { win32: true },
212
+ );
213
+
214
+ expect(res.metadata).toBeDefined();
215
+ expect(symlinkSpy).not.toHaveBeenCalled();
216
+ expect(renameSpy).not.toHaveBeenCalled();
217
+ });
218
+
219
+ it("win32: a FILE-flavor link at a DIRECTORY target is broken despite a matching target string — recreated as a junction, never fast-pathed", async () => {
220
+ // Round-3 review P1: flavors matter on Windows. An older client (or a
221
+ // pull that ran while the target dir was absent) can leave a file-type
222
+ // link whose target string matches the incoming record exactly; it
223
+ // still cannot be traversed. The fast path must fall through and the
224
+ // materializer must mint the correct directory flavor — post-#219 that
225
+ // is a junction (unprivileged) rather than a 'dir' NTFS symlink.
226
+ const wireTarget = "../companies/indigo/skills/call-prep-brief";
227
+ const localPath = path.join(tmpRoot, "farm", "indigo%3Acall-prep-brief");
228
+ fs.mkdirSync(path.dirname(localPath), { recursive: true });
229
+ const resolvedTarget = path.resolve(path.dirname(localPath), wireTarget);
230
+ fs.mkdirSync(resolvedTarget, { recursive: true });
231
+ setObjectIOFactory(() => symlinkRecordIO(wireTarget));
232
+
233
+ const realStatSync = fs.statSync.bind(fs) as (p: fs.PathLike) => fs.Stats;
234
+ vi.spyOn(fs, "lstatSync").mockImplementation(((p: fs.PathLike) =>
235
+ p === localPath
236
+ ? fakeStats({ symlink: true })
237
+ : fakeStats({})) as typeof fs.lstatSync);
238
+ vi.spyOn(fs, "readlinkSync").mockImplementation(
239
+ (() => "..\\companies\\indigo\\skills\\call-prep-brief") as unknown as typeof fs.readlinkSync,
240
+ );
241
+ // Windows refuses to traverse the wrong-flavor link: stat on the link
242
+ // throws, while the resolved target itself stats as a real directory.
243
+ vi.spyOn(fs, "statSync").mockImplementation(((p: fs.PathLike) => {
244
+ if (p === localPath) throw errnoError("EINVAL");
245
+ return realStatSync(p);
246
+ }) as typeof fs.statSync);
247
+ const symlinkSpy = vi
248
+ .spyOn(fs, "symlinkSync")
249
+ .mockImplementation(() => undefined);
250
+ vi.spyOn(fs, "unlinkSync").mockImplementation(() => undefined);
251
+ vi.spyOn(fs, "renameSync").mockImplementation(() => undefined);
252
+
253
+ await downloadFile(makeCtx(), ".claude/skills/indigo:call-prep-brief", localPath, {
254
+ win32: true,
255
+ });
256
+
257
+ // Fell through the fast path and minted the correct flavor: a junction,
258
+ // which requires an absolute substitute path.
259
+ expect(symlinkSpy).toHaveBeenCalledTimes(1);
260
+ expect(symlinkSpy.mock.calls[0]![2]).toBe("junction");
261
+ expect(symlinkSpy.mock.calls[0]![0]).toBe(resolvedTarget);
262
+ });
263
+
264
+ it("win32: replaces a directory symlink via backup-swap, minting a junction temp link", async () => {
265
+ // Failure signature 1 from the incident: EPERM on rename over
266
+ // '...\\indigo%3Acall-prep-brief\\scripts' — the destination was a
267
+ // directory symlink, which Windows rename() can never replace.
268
+ // replaceStagedPath (upstream #193) swaps a symlink destination out to
269
+ // a sibling backup, installs the staged link, then removes the backup.
270
+ const wireTarget = "../companies/indigo/skills/call-prep-brief";
271
+ const localPath = path.join(tmpRoot, "farm", "indigo%3Acall-prep-brief");
272
+ fs.mkdirSync(path.dirname(localPath), { recursive: true });
273
+ // Real directory at the resolved target so the type probe picks 'dir'.
274
+ fs.mkdirSync(path.resolve(path.dirname(localPath), wireTarget), {
275
+ recursive: true,
276
+ });
277
+ setObjectIOFactory(() => symlinkRecordIO(wireTarget));
278
+
279
+ const realLstatSync = fs.lstatSync.bind(fs) as (p: fs.PathLike) => fs.Stats;
280
+ const realStatSync = fs.statSync.bind(fs) as (p: fs.PathLike) => fs.Stats;
281
+ // Destination is scripted as a live directory symlink to a STALE target.
282
+ vi.spyOn(fs, "lstatSync").mockImplementation(((p: fs.PathLike) =>
283
+ p === localPath
284
+ ? fakeStats({ symlink: true })
285
+ : realLstatSync(p)) as typeof fs.lstatSync);
286
+ vi.spyOn(fs, "readlinkSync").mockImplementation(
287
+ (() => "..\\stale\\old-skill") as unknown as typeof fs.readlinkSync,
288
+ );
289
+ vi.spyOn(fs, "statSync").mockImplementation(((p: fs.PathLike) =>
290
+ p === localPath
291
+ ? fakeStats({ dir: true })
292
+ : realStatSync(p)) as typeof fs.statSync);
293
+ const symlinkSpy = vi
294
+ .spyOn(fs, "symlinkSync")
295
+ .mockImplementation(() => undefined);
296
+ const unlinkSpy = vi
297
+ .spyOn(fs, "unlinkSync")
298
+ .mockImplementation(() => undefined);
299
+ const renameSpy = vi
300
+ .spyOn(fs, "renameSync")
301
+ .mockImplementation(() => undefined);
302
+
303
+ await downloadFile(makeCtx(), ".claude/skills/indigo:call-prep-brief", localPath, {
304
+ win32: true,
305
+ });
306
+
307
+ // Typed temp link: directory target ⇒ junction with an ABSOLUTE
308
+ // substitute path (#219 — a bare symlinkSync mints a broken file-type
309
+ // link, and a 'dir' NTFS symlink EPERMs without Developer Mode).
310
+ expect(symlinkSpy).toHaveBeenCalledTimes(1);
311
+ expect(symlinkSpy.mock.calls[0]![0]).toBe(
312
+ path.resolve(path.dirname(localPath), wireTarget),
313
+ );
314
+ expect(String(symlinkSpy.mock.calls[0]![1])).toContain(".hq-tmp-");
315
+ expect(symlinkSpy.mock.calls[0]![2]).toBe("junction");
316
+ // Backup-swap: old link → .hq-backup-*, staged link → destination,
317
+ // backup removed. The destination itself is never rm'd in place.
318
+ expect(renameSpy).toHaveBeenCalledTimes(2);
319
+ expect(renameSpy.mock.calls[0]![0]).toBe(localPath);
320
+ expect(String(renameSpy.mock.calls[0]![1])).toContain(".hq-backup-");
321
+ expect(String(renameSpy.mock.calls[1]![0])).toContain(".hq-tmp-");
322
+ expect(renameSpy.mock.calls[1]![1]).toBe(localPath);
323
+ expect(unlinkSpy).not.toHaveBeenCalledWith(localPath);
324
+ expect(
325
+ unlinkSpy.mock.calls.some((c) => String(c[0]).includes(".hq-backup-")),
326
+ ).toBe(true);
327
+ });
328
+
329
+ it("win32: replaces a file symlink via backup-swap, minting a 'file'-type temp link", async () => {
330
+ const wireTarget = "../personal/skills/dm/SKILL.md";
331
+ const localPath = path.join(tmpRoot, "farm", "personal%3Adm");
332
+ fs.mkdirSync(path.dirname(localPath), { recursive: true });
333
+ // A GENUINE regular file at the resolved target — the only shape that
334
+ // still earns a real 'file' symlink post-#219. An unresolvable target is
335
+ // deliberately materialized as a junction instead (vault overlays are
336
+ // directories, and a junction needs no Windows symlink privilege).
337
+ const resolvedTarget = path.resolve(path.dirname(localPath), wireTarget);
338
+ fs.mkdirSync(path.dirname(resolvedTarget), { recursive: true });
339
+ fs.writeFileSync(resolvedTarget, "# dm skill");
340
+ setObjectIOFactory(() => symlinkRecordIO(wireTarget));
341
+
342
+ const realLstatSync = fs.lstatSync.bind(fs) as (p: fs.PathLike) => fs.Stats;
343
+ vi.spyOn(fs, "lstatSync").mockImplementation(((p: fs.PathLike) =>
344
+ p === localPath
345
+ ? fakeStats({ symlink: true })
346
+ : realLstatSync(p)) as typeof fs.lstatSync);
347
+ vi.spyOn(fs, "readlinkSync").mockImplementation(
348
+ (() => "..\\stale\\dm.md") as unknown as typeof fs.readlinkSync,
349
+ );
350
+ const symlinkSpy = vi
351
+ .spyOn(fs, "symlinkSync")
352
+ .mockImplementation(() => undefined);
353
+ const rmdirSpy = vi.spyOn(fs, "rmdirSync");
354
+ const unlinkSpy = vi
355
+ .spyOn(fs, "unlinkSync")
356
+ .mockImplementation(() => undefined);
357
+ const renameSpy = vi
358
+ .spyOn(fs, "renameSync")
359
+ .mockImplementation(() => undefined);
360
+
361
+ await downloadFile(makeCtx(), ".claude/skills/personal:dm", localPath, {
362
+ win32: true,
363
+ });
364
+
365
+ expect(symlinkSpy.mock.calls[0]![2]).toBe("file");
366
+ // Backup-swap: two renames (old→backup, staged→destination) and the
367
+ // backup removed; the destination is never unlinked in place.
368
+ expect(renameSpy).toHaveBeenCalledTimes(2);
369
+ expect(unlinkSpy).not.toHaveBeenCalledWith(localPath);
370
+ expect(
371
+ unlinkSpy.mock.calls.some((c) => String(c[0]).includes(".hq-backup-")),
372
+ ).toBe(true);
373
+ expect(rmdirSpy).not.toHaveBeenCalledWith(localPath);
374
+ });
375
+
376
+ it("win32: NEVER deletes a real (non-symlink) directory — the rename failure surfaces", async () => {
377
+ // The engine-level guarantee behind the caller's "manual reconciliation
378
+ // required" warning: a real directory at the destination is the user's
379
+ // data. The replace path may only remove SYMLINK destinations; a real
380
+ // dir is left in place and the (scripted, Windows-faithful) EPERM from
381
+ // rename-over-dir propagates.
382
+ const wireTarget = "../companies/indigo/skills/capture";
383
+ const localPath = path.join(tmpRoot, "farm", "indigo%3Acapture");
384
+ fs.mkdirSync(localPath, { recursive: true }); // REAL directory
385
+ fs.mkdirSync(path.resolve(path.dirname(localPath), wireTarget), {
386
+ recursive: true,
387
+ });
388
+ setObjectIOFactory(() => symlinkRecordIO(wireTarget));
389
+
390
+ vi.spyOn(fs, "symlinkSync").mockImplementation(() => undefined);
391
+ const rmdirSpy = vi.spyOn(fs, "rmdirSync");
392
+ const unlinkSpy = vi.spyOn(fs, "unlinkSync");
393
+ const renameSpy = vi.spyOn(fs, "renameSync").mockImplementation(() => {
394
+ throw errnoError("EPERM");
395
+ });
396
+
397
+ await expect(
398
+ downloadFile(makeCtx(), ".claude/skills/indigo:capture", localPath, {
399
+ win32: true,
400
+ }),
401
+ ).rejects.toThrow(/EPERM/);
402
+
403
+ // Surfaced on the first failure — never silently swallowed, and a
404
+ // non-symlink destination gets no backup-swap (nothing to roll back).
405
+ expect(renameSpy).toHaveBeenCalledTimes(1);
406
+ // The real directory was never removed (temp cleanup may touch the
407
+ // .hq-tmp- path, but the destination itself is untouchable).
408
+ expect(rmdirSpy).not.toHaveBeenCalledWith(localPath);
409
+ expect(unlinkSpy).not.toHaveBeenCalledWith(localPath);
410
+ expect(fs.statSync(localPath).isDirectory()).toBe(true);
411
+ });
412
+
413
+ it("POSIX: symlink destination is replaced cleanly — fresh target installed, no temp/backup litter", async () => {
414
+ // replaceStagedPath backup-swaps symlink destinations on every
415
+ // platform; the observable contract is a clean replacement with no
416
+ // .hq-tmp-/.hq-backup- litter and a bare (no type hint) staged link.
417
+ const localPath = path.join(tmpRoot, "posix-link.md");
418
+ fs.symlinkSync("stale-target.md", localPath);
419
+ setObjectIOFactory(() => symlinkRecordIO("fresh-target.md"));
420
+
421
+ const symlinkSpy = vi.spyOn(fs, "symlinkSync");
422
+
423
+ await downloadFile(makeCtx(), "posix-link.md", localPath, {
424
+ win32: false,
425
+ });
426
+
427
+ expect(symlinkSpy).toHaveBeenCalledTimes(1);
428
+ expect(symlinkSpy.mock.calls[0]![2]).toBeUndefined();
429
+ expect(fs.readlinkSync(localPath)).toBe("fresh-target.md");
430
+ const litter = fs
431
+ .readdirSync(tmpRoot)
432
+ .filter((n) => n.startsWith(".hq-tmp-") || n.startsWith(".hq-backup-"));
433
+ expect(litter).toEqual([]);
434
+ });
435
+
436
+ it("2026-07-16 ENOENT mode (US-002): parents are created at the ENCODED local path, never the raw-colon path", async () => {
437
+ // Failure signature 2 from the incident:
438
+ // ENOENT mkdir 'C:\...\skills\indigo:team-agent-telemetry-report'
439
+ // — the pre-codec caller handed downloadFile a RAW-key local path, and
440
+ // Windows cannot mkdir a colon segment. The pull pipeline now derives
441
+ // localPath through the codec (sync.ts resolveContainedVaultPath →
442
+ // localPathForVaultKey); this pins the contract end-to-end: pulling the
443
+ // incident's exact key with a codec-derived localPath materializes the
444
+ // parent chain at `indigo%3Ateam-agent-telemetry-report`, and no
445
+ // raw-colon sibling ever appears.
446
+ const key = ".claude/skills/indigo:team-agent-telemetry-report/agents";
447
+ const wireTarget =
448
+ "../../../companies/indigo/skills/team-agent-telemetry-report/agents";
449
+ const localPath = localPathForVaultKey(tmpRoot, key, true);
450
+ setObjectIOFactory(() => symlinkRecordIO(wireTarget));
451
+ // Leaf materialization is exercised by the suites above; this test is
452
+ // about the parent chain, so the link+rename pair is inert.
453
+ vi.spyOn(fs, "symlinkSync").mockImplementation(() => undefined);
454
+ vi.spyOn(fs, "renameSync").mockImplementation(() => undefined);
455
+
456
+ await downloadFile(makeCtx(), key, localPath, { win32: true });
457
+
458
+ const encodedParent = path.join(
459
+ tmpRoot,
460
+ ".claude",
461
+ "skills",
462
+ "indigo%3Ateam-agent-telemetry-report",
463
+ );
464
+ expect(fs.existsSync(encodedParent)).toBe(true);
465
+ expect(fs.statSync(encodedParent).isDirectory()).toBe(true);
466
+ // The raw-colon spelling must not exist anywhere in the farm.
467
+ expect(
468
+ fs.readdirSync(path.join(tmpRoot, ".claude", "skills")),
469
+ ).toEqual(["indigo%3Ateam-agent-telemetry-report"]);
470
+ });
471
+
472
+ it("POSIX: fast path also fires with exact string equality", async () => {
473
+ // Separator normalization is win32-only; POSIX equality is exact (a
474
+ // backslash is an ordinary filename character there). A separator-free
475
+ // target makes this deterministic on any host platform.
476
+ const target = "plain-target.md";
477
+ const localPath = path.join(tmpRoot, "posix-noop.md");
478
+ fs.symlinkSync(target, localPath);
479
+ setObjectIOFactory(() => symlinkRecordIO(target));
480
+
481
+ const symlinkSpy = vi.spyOn(fs, "symlinkSync");
482
+ const renameSpy = vi.spyOn(fs, "renameSync");
483
+
484
+ const res = await downloadFile(makeCtx(), "posix-noop.md", localPath, {
485
+ win32: false,
486
+ });
487
+
488
+ expect(res.metadata).toBeDefined();
489
+ expect(symlinkSpy).not.toHaveBeenCalled();
490
+ expect(renameSpy).not.toHaveBeenCalled();
491
+ });
492
+ });
package/src/s3.test.ts CHANGED
@@ -1067,6 +1067,30 @@ describe("downloadFile", () => {
1067
1067
  );
1068
1068
  });
1069
1069
 
1070
+ it("default ops replace a directory symlink destination end-to-end (dir-reparse-safe cleanup)", () => {
1071
+ // No ops seam: exercises DEFAULT_REPLACE_STAGED_PATH_OPS on the real
1072
+ // filesystem. The backup of the old DIR-type link must be removable on
1073
+ // every platform (unlink with rmdir fallback for directory reparse
1074
+ // points), or the replacement rolls back and the Windows churn returns.
1075
+ const oldTarget = path.join(tmpRoot, "default-ops-old");
1076
+ const newTarget = path.join(tmpRoot, "default-ops-new");
1077
+ const localPath = path.join(tmpRoot, "default-ops-link");
1078
+ const stagedPath = path.join(tmpRoot, ".hq-tmp-default-ops-test");
1079
+ fs.mkdirSync(oldTarget);
1080
+ fs.mkdirSync(newTarget);
1081
+ fs.symlinkSync(oldTarget, localPath, "dir");
1082
+ fs.symlinkSync(newTarget, stagedPath, "dir");
1083
+
1084
+ replaceStagedPath(stagedPath, localPath);
1085
+
1086
+ expect(fs.lstatSync(localPath).isSymbolicLink()).toBe(true);
1087
+ expect(fs.readlinkSync(localPath)).toBe(newTarget);
1088
+ expect(
1089
+ fs.readdirSync(tmpRoot).filter((n) => n.startsWith(".hq-backup-")),
1090
+ ).toEqual([]);
1091
+ expect(fs.existsSync(stagedPath)).toBe(false);
1092
+ });
1093
+
1070
1094
  it("restores an existing directory link when staged replacement fails", () => {
1071
1095
  const targetDir = path.join(tmpRoot, "rollback-source");
1072
1096
  const localPath = path.join(tmpRoot, "rollback-link");