@indigoai-us/hq-cloud 6.14.49 → 6.15.0

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 (126) hide show
  1. package/.github/workflows/unreleased-commits-nag.yml +256 -0
  2. package/dist/bin/sync-runner-watch-loop.d.ts +12 -0
  3. package/dist/bin/sync-runner-watch-loop.d.ts.map +1 -1
  4. package/dist/bin/sync-runner-watch-loop.js +153 -25
  5. package/dist/bin/sync-runner-watch-loop.js.map +1 -1
  6. package/dist/bin/sync-runner-watch-routes.d.ts +17 -0
  7. package/dist/bin/sync-runner-watch-routes.d.ts.map +1 -1
  8. package/dist/bin/sync-runner-watch-routes.js +11 -0
  9. package/dist/bin/sync-runner-watch-routes.js.map +1 -1
  10. package/dist/bin/sync-runner-watch-routes.test.d.ts +2 -0
  11. package/dist/bin/sync-runner-watch-routes.test.d.ts.map +1 -0
  12. package/dist/bin/sync-runner-watch-routes.test.js +51 -0
  13. package/dist/bin/sync-runner-watch-routes.test.js.map +1 -0
  14. package/dist/bin/sync-runner.d.ts +11 -12
  15. package/dist/bin/sync-runner.d.ts.map +1 -1
  16. package/dist/bin/sync-runner.js.map +1 -1
  17. package/dist/bin/sync-runner.test.js +173 -52
  18. package/dist/bin/sync-runner.test.js.map +1 -1
  19. package/dist/cli/reindex-knowledge.d.ts +7 -0
  20. package/dist/cli/reindex-knowledge.d.ts.map +1 -0
  21. package/dist/cli/reindex-knowledge.js +389 -0
  22. package/dist/cli/reindex-knowledge.js.map +1 -0
  23. package/dist/cli/reindex-knowledge.test.d.ts +12 -0
  24. package/dist/cli/reindex-knowledge.test.d.ts.map +1 -0
  25. package/dist/cli/reindex-knowledge.test.js +260 -0
  26. package/dist/cli/reindex-knowledge.test.js.map +1 -0
  27. package/dist/cli/reindex.d.ts.map +1 -1
  28. package/dist/cli/reindex.js +8 -0
  29. package/dist/cli/reindex.js.map +1 -1
  30. package/dist/cli/rescue-classify-ordering.test.js +8 -2
  31. package/dist/cli/rescue-classify-ordering.test.js.map +1 -1
  32. package/dist/cli/rescue-core.d.ts +85 -0
  33. package/dist/cli/rescue-core.d.ts.map +1 -1
  34. package/dist/cli/rescue-core.js +390 -1
  35. package/dist/cli/rescue-core.js.map +1 -1
  36. package/dist/cli/rescue-settings-reconcile.test.d.ts +2 -0
  37. package/dist/cli/rescue-settings-reconcile.test.d.ts.map +1 -0
  38. package/dist/cli/rescue-settings-reconcile.test.js +523 -0
  39. package/dist/cli/rescue-settings-reconcile.test.js.map +1 -0
  40. package/dist/index.d.ts +1 -1
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +1 -1
  43. package/dist/index.js.map +1 -1
  44. package/dist/journal.d.ts.map +1 -1
  45. package/dist/journal.js +81 -51
  46. package/dist/journal.js.map +1 -1
  47. package/dist/journal.test.js +11 -19
  48. package/dist/journal.test.js.map +1 -1
  49. package/dist/sync/event-sync.d.ts +8 -25
  50. package/dist/sync/event-sync.d.ts.map +1 -1
  51. package/dist/sync/event-sync.js +23 -48
  52. package/dist/sync/event-sync.js.map +1 -1
  53. package/dist/sync/event-sync.test.js +6 -32
  54. package/dist/sync/event-sync.test.js.map +1 -1
  55. package/dist/sync/feature-flags.d.ts +20 -117
  56. package/dist/sync/feature-flags.d.ts.map +1 -1
  57. package/dist/sync/feature-flags.js +24 -147
  58. package/dist/sync/feature-flags.js.map +1 -1
  59. package/dist/sync/feature-flags.test.js +15 -61
  60. package/dist/sync/feature-flags.test.js.map +1 -1
  61. package/dist/sync/index.d.ts +1 -1
  62. package/dist/sync/index.d.ts.map +1 -1
  63. package/dist/sync/index.js +1 -1
  64. package/dist/sync/index.js.map +1 -1
  65. package/dist/sync/lease-client.d.ts +67 -0
  66. package/dist/sync/lease-client.d.ts.map +1 -0
  67. package/dist/sync/lease-client.js +158 -0
  68. package/dist/sync/lease-client.js.map +1 -0
  69. package/dist/sync/lease-client.test.d.ts +2 -0
  70. package/dist/sync/lease-client.test.d.ts.map +1 -0
  71. package/dist/sync/lease-client.test.js +119 -0
  72. package/dist/sync/lease-client.test.js.map +1 -0
  73. package/dist/sync/push-receiver.d.ts +8 -19
  74. package/dist/sync/push-receiver.d.ts.map +1 -1
  75. package/dist/sync/push-receiver.js +6 -50
  76. package/dist/sync/push-receiver.js.map +1 -1
  77. package/dist/sync/push-receiver.test.js +6 -57
  78. package/dist/sync/push-receiver.test.js.map +1 -1
  79. package/dist/sync/realtime-rollout.d.ts +85 -0
  80. package/dist/sync/realtime-rollout.d.ts.map +1 -0
  81. package/dist/sync/realtime-rollout.js +206 -0
  82. package/dist/sync/realtime-rollout.js.map +1 -0
  83. package/dist/sync/realtime-rollout.test.d.ts +2 -0
  84. package/dist/sync/realtime-rollout.test.d.ts.map +1 -0
  85. package/dist/sync/realtime-rollout.test.js +71 -0
  86. package/dist/sync/realtime-rollout.test.js.map +1 -0
  87. package/dist/sync/state-store.d.ts +40 -0
  88. package/dist/sync/state-store.d.ts.map +1 -0
  89. package/dist/sync/state-store.js +680 -0
  90. package/dist/sync/state-store.js.map +1 -0
  91. package/dist/sync/state-store.test.d.ts +2 -0
  92. package/dist/sync/state-store.test.d.ts.map +1 -0
  93. package/dist/sync/state-store.test.js +159 -0
  94. package/dist/sync/state-store.test.js.map +1 -0
  95. package/dist/types.d.ts +12 -0
  96. package/dist/types.d.ts.map +1 -1
  97. package/package.json +1 -1
  98. package/src/bin/sync-runner-watch-loop.ts +176 -32
  99. package/src/bin/sync-runner-watch-routes.test.ts +71 -0
  100. package/src/bin/sync-runner-watch-routes.ts +27 -0
  101. package/src/bin/sync-runner.test.ts +188 -53
  102. package/src/bin/sync-runner.ts +11 -12
  103. package/src/cli/reindex-knowledge.test.ts +307 -0
  104. package/src/cli/reindex-knowledge.ts +450 -0
  105. package/src/cli/reindex.ts +9 -0
  106. package/src/cli/rescue-classify-ordering.test.ts +9 -3
  107. package/src/cli/rescue-core.ts +459 -1
  108. package/src/cli/rescue-settings-reconcile.test.ts +637 -0
  109. package/src/index.ts +2 -4
  110. package/src/journal.test.ts +19 -21
  111. package/src/journal.ts +87 -54
  112. package/src/sync/event-sync.test.ts +9 -44
  113. package/src/sync/event-sync.ts +26 -52
  114. package/src/sync/feature-flags.test.ts +22 -72
  115. package/src/sync/feature-flags.ts +32 -199
  116. package/src/sync/index.ts +2 -4
  117. package/src/sync/lease-client.test.ts +128 -0
  118. package/src/sync/lease-client.ts +207 -0
  119. package/src/sync/push-receiver.test.ts +6 -58
  120. package/src/sync/push-receiver.ts +9 -74
  121. package/src/sync/realtime-rollout.test.ts +86 -0
  122. package/src/sync/realtime-rollout.ts +262 -0
  123. package/src/sync/state-store.test.ts +194 -0
  124. package/src/sync/state-store.ts +727 -0
  125. package/src/types.ts +14 -0
  126. package/test/e2e/sync/transient-company-leg.test.ts +8 -4
@@ -0,0 +1,450 @@
1
+ /**
2
+ * Legacy knowledge-repo materialization — the migration arm of policy
3
+ * `knowledge-repositories-never-symlink` (hq-core).
4
+ *
5
+ * Every knowledge repository must be a REAL directory at its canonical HQ
6
+ * path (`core/knowledge/`, `personal/knowledge/`, `companies/{co}/knowledge/`),
7
+ * with git initialized inside that directory when independent history is
8
+ * needed. The legacy layout — a repo under `repos/` (or any separate git
9
+ * repo) with the knowledge path symlinked to it — breaks cloud sync: sync
10
+ * records a directory symlink as a ~50-byte vault marker, so teammates
11
+ * receive nothing.
12
+ *
13
+ * On every reindex this module scours the canonical knowledge locations for
14
+ * that legacy shape and migrates each occurrence in place:
15
+ *
16
+ * 1. `git pull --ff-only` the legacy repo (best-effort — offline or dirty
17
+ * repos still migrate with their local content),
18
+ * 2. copy the link target to a temp sibling — INCLUDING `.git/` when the
19
+ * target is the repo root, so history is preserved as a supported
20
+ * embedded repo at the canonical path,
21
+ * 3. swap the symlink for the copied real directory, and
22
+ * 4. remove the legacy repo under `repos/` once every symlink that
23
+ * referenced it has been materialized and nothing else lives in it
24
+ * (a repo whose knowledge was only a subdirectory is left in place).
25
+ *
26
+ * Deliberately NOT migrated:
27
+ * - package-manager links from `core/knowledge/` into the pack knowledge
28
+ * dirs under `core/packages/` — immutable pack mounts, a supported
29
+ * non-repo link;
30
+ * - symlinks that resolve inside the HQ tree itself (aliases tracked by HQ
31
+ * git are not separate repositories);
32
+ * - real directories with an embedded `.git/` — already the supported form;
33
+ * - broken symlinks — warned about and left for a human, since there is no
34
+ * content to materialize.
35
+ *
36
+ * Steady-state cost is a handful of lstats: git subprocesses are spawned only
37
+ * when a symlink candidate is actually present. Everything is best-effort —
38
+ * a failed migration warns to stderr and never fails the reindex. Escape
39
+ * hatch: HQ_REINDEX_SKIP_KNOWLEDGE_MIGRATION=1 disables the whole pass.
40
+ */
41
+ import { spawnSync } from "child_process";
42
+ import * as fs from "fs";
43
+ import * as path from "path";
44
+
45
+ function warn(msg: string): void {
46
+ process.stderr.write(`${msg}\n`);
47
+ }
48
+
49
+ function lstatOrNull(p: string): fs.Stats | null {
50
+ try {
51
+ return fs.lstatSync(p);
52
+ } catch {
53
+ return null;
54
+ }
55
+ }
56
+
57
+ function isDir(p: string): boolean {
58
+ try {
59
+ return fs.statSync(p).isDirectory();
60
+ } catch {
61
+ return false;
62
+ }
63
+ }
64
+
65
+ /** Non-hidden entries of `dir`, sorted; [] when missing/unreadable. */
66
+ function entries(dir: string): string[] {
67
+ try {
68
+ return fs
69
+ .readdirSync(dir)
70
+ .filter((n) => !n.startsWith("."))
71
+ .sort();
72
+ } catch {
73
+ return [];
74
+ }
75
+ }
76
+
77
+ function realpathOrNull(p: string): string | null {
78
+ try {
79
+ return fs.realpathSync(p);
80
+ } catch {
81
+ return null;
82
+ }
83
+ }
84
+
85
+ /** True when `child` is `parent` or lexically inside it. */
86
+ function isUnder(child: string, parent: string): boolean {
87
+ const rel = path.relative(parent, child);
88
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
89
+ }
90
+
91
+ /** `git rev-parse --show-toplevel` for `dir`, realpath'd; null when not in a repo. */
92
+ function gitToplevel(dir: string): string | null {
93
+ try {
94
+ const res = spawnSync("git", ["-C", dir, "rev-parse", "--show-toplevel"], {
95
+ encoding: "utf8",
96
+ stdio: ["ignore", "pipe", "pipe"],
97
+ timeout: 15_000,
98
+ });
99
+ if (res.status !== 0) return null;
100
+ const top = res.stdout.trim();
101
+ return top ? realpathOrNull(top) ?? top : null;
102
+ } catch {
103
+ return null;
104
+ }
105
+ }
106
+
107
+ /** One legacy symlink occurrence: canonical link path → resolved target. */
108
+ interface LegacyLink {
109
+ /** The canonical knowledge path currently occupied by the symlink. */
110
+ linkPath: string;
111
+ /** Link path relative to the HQ root (for messages). */
112
+ linkRel: string;
113
+ /** Resolved (real) target directory the symlink points at. */
114
+ target: string;
115
+ /** Toplevel of the separate git repo the target belongs to, if any. */
116
+ repoTop: string | null;
117
+ }
118
+
119
+ /**
120
+ * Candidate knowledge locations, per the HQ layout contract. Only these are
121
+ * scanned — knowledge repositories are defined to live at canonical paths, so
122
+ * a full-tree walk would add cost without adding coverage.
123
+ */
124
+ function knowledgeCandidates(root: string): string[] {
125
+ const out: string[] = [];
126
+ const push = (p: string): void => {
127
+ if (lstatOrNull(p)) out.push(p);
128
+ };
129
+
130
+ for (const slug of entries(path.join(root, "companies"))) {
131
+ const knowledge = path.join(root, "companies", slug, "knowledge");
132
+ push(knowledge);
133
+ // One level deep: /newcompany-era docs showed per-base links such as
134
+ // companies/acme/knowledge/acme → repos/private/knowledge-acme.
135
+ const st = lstatOrNull(knowledge);
136
+ if (st?.isDirectory()) {
137
+ for (const base of entries(knowledge)) push(path.join(knowledge, base));
138
+ }
139
+ }
140
+
141
+ const personal = path.join(root, "personal", "knowledge");
142
+ push(personal);
143
+ if (lstatOrNull(personal)?.isDirectory()) {
144
+ for (const base of entries(personal)) push(path.join(personal, base));
145
+ }
146
+
147
+ const coreKnowledge = path.join(root, "core", "knowledge");
148
+ for (const entry of entries(coreKnowledge)) {
149
+ const p = path.join(coreKnowledge, entry);
150
+ if (entry === "public" || entry === "private") {
151
+ for (const base of entries(p)) push(path.join(p, base));
152
+ } else {
153
+ push(p); // flat starter-kit layout
154
+ }
155
+ }
156
+ return out;
157
+ }
158
+
159
+ /**
160
+ * Classify a symlink candidate. Returns the legacy occurrence to migrate, or
161
+ * null when the link is supported (pack mount, in-tree alias) or unusable
162
+ * (broken — warned here).
163
+ */
164
+ function classifyLink(root: string, linkPath: string, rootTop: string | null): LegacyLink | null {
165
+ const linkRel = path.relative(root, linkPath);
166
+ const target = realpathOrNull(linkPath);
167
+ if (target === null) {
168
+ warn(
169
+ `reindex: knowledge symlink '${linkRel}' is broken (target missing) — nothing to materialize; remove or repair it by hand`,
170
+ );
171
+ return null;
172
+ }
173
+ if (!isDir(target)) return null; // file links are not knowledge repositories
174
+
175
+ // Supported pack mount: core/knowledge/* → core/packages/*/knowledge/*.
176
+ if (isUnder(target, path.join(root, "core", "packages"))) return null;
177
+
178
+ const repoTop = gitToplevel(target);
179
+ const underRepos = isUnder(target, path.join(root, "repos"));
180
+ const separateRepo = repoTop !== null && repoTop !== rootTop;
181
+
182
+ // Legacy iff the target lives under repos/ (code-only tree) or is a separate
183
+ // git repo OUTSIDE the HQ tree. Anything else is left alone: an in-HQ alias
184
+ // is not a knowledge repository, and an in-HQ symlink to an embedded repo at
185
+ // another canonical path (e.g. a retired-release mirror core/knowledge/<x> →
186
+ // personal/knowledge/<x> whose personal side has its own .git) is the
187
+ // mirror-cleanup pass's to prune — materializing it here would double-surface
188
+ // the same knowledge as a real duplicate before that cleanup runs.
189
+ const insideHq = isUnder(target, root);
190
+ if (!underRepos && (insideHq || !separateRepo)) return null;
191
+
192
+ return { linkPath, linkRel, target, repoTop: separateRepo ? repoTop : null };
193
+ }
194
+
195
+ /** Best-effort `git pull --ff-only`; failures warn and never block migration. */
196
+ function pullLegacyRepo(root: string, repoTop: string): void {
197
+ try {
198
+ // A repo with no remote has nothing to pull; migrate its local content
199
+ // without the noise of a doomed pull attempt.
200
+ const remotes = spawnSync("git", ["-C", repoTop, "remote"], {
201
+ encoding: "utf8",
202
+ stdio: ["ignore", "pipe", "pipe"],
203
+ timeout: 15_000,
204
+ });
205
+ if (remotes.status !== 0 || !remotes.stdout.trim()) return;
206
+ const res = spawnSync("git", ["-C", repoTop, "pull", "--ff-only", "--quiet"], {
207
+ encoding: "utf8",
208
+ stdio: ["ignore", "pipe", "pipe"],
209
+ timeout: 60_000,
210
+ });
211
+ if (res.status !== 0) {
212
+ const detail = `${res.stderr ?? ""}`.trim().split("\n")[0] || `exit ${res.status}`;
213
+ warn(
214
+ `reindex: could not pull legacy knowledge repo '${path.relative(root, repoTop)}' (${detail}); migrating its local content as-is`,
215
+ );
216
+ }
217
+ } catch (err) {
218
+ warn(
219
+ `reindex: could not pull legacy knowledge repo '${path.relative(root, repoTop)}' (${(err as Error).message}); migrating its local content as-is`,
220
+ );
221
+ }
222
+ }
223
+
224
+ /**
225
+ * Paths under a link's target that must NOT be materialized, and whether their
226
+ * presence means the legacy repo has to survive the migration.
227
+ */
228
+ interface CopyExclusions {
229
+ /** Absolute paths (files or dirs) to skip during the copy. */
230
+ paths: Set<string>;
231
+ /** Human reasons the legacy repo must be kept in place (empty → deletable). */
232
+ keepLegacyReasons: string[];
233
+ }
234
+
235
+ /**
236
+ * Work out what the copy must skip.
237
+ *
238
+ * - A `.git` FILE (not directory) marks a linked git worktree / gitdir
239
+ * pointer: copying it verbatim would leave the materialized directory
240
+ * pointing at metadata inside the main repository, and deleting the legacy
241
+ * path would strand that registration. Skip the pointer file and keep the
242
+ * legacy worktree for `git worktree remove` by hand.
243
+ * - Files the legacy repo git-ignores (e.g. a local `credentials.json`) stay
244
+ * out of the copy: cloud sync's ignore layer reads only the HQ ROOT
245
+ * `.gitignore`, so materializing them under a synced knowledge path would
246
+ * upload files their own repo deliberately kept local. The legacy repo is
247
+ * kept so those local-only files are never destroyed.
248
+ */
249
+ function copyExclusions(root: string, link: LegacyLink): CopyExclusions {
250
+ const paths = new Set<string>();
251
+ const keepLegacyReasons: string[] = [];
252
+
253
+ const gitEntry = path.join(link.target, ".git");
254
+ if (lstatOrNull(gitEntry)?.isFile()) {
255
+ paths.add(gitEntry);
256
+ keepLegacyReasons.push(
257
+ "it is a linked git worktree (its history lives in the main repository; remove it with `git worktree remove` after verifying the migrated content)",
258
+ );
259
+ }
260
+
261
+ if (link.repoTop) {
262
+ try {
263
+ const res = spawnSync(
264
+ "git",
265
+ ["-C", link.repoTop, "ls-files", "--others", "--ignored", "--exclude-standard", "-z"],
266
+ { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 30_000 },
267
+ );
268
+ if (res.status === 0) {
269
+ const ignored = res.stdout
270
+ .split("\0")
271
+ .filter(Boolean)
272
+ .map((rel) => path.join(link.repoTop as string, rel))
273
+ .filter((abs) => isUnder(abs, link.target));
274
+ if (ignored.length > 0) {
275
+ for (const abs of ignored) paths.add(abs);
276
+ keepLegacyReasons.push(
277
+ `it holds ${ignored.length} git-ignored local file(s) that must not enter a cloud-synced knowledge path`,
278
+ );
279
+ }
280
+ } else {
281
+ keepLegacyReasons.push(
282
+ "its git-ignored local files could not be enumerated, so the copy may be incomplete",
283
+ );
284
+ }
285
+ } catch (err) {
286
+ keepLegacyReasons.push(
287
+ `its git-ignored local files could not be enumerated (${(err as Error).message})`,
288
+ );
289
+ }
290
+ }
291
+ return { paths, keepLegacyReasons };
292
+ }
293
+
294
+ /**
295
+ * Replace the symlink at `link.linkPath` with a real directory holding a full
296
+ * copy of its target (`.git/` included when the target is the repo root).
297
+ * Relative symlinks inside the content are copied verbatim so they still
298
+ * resolve after the legacy repo is removed. Returns true when the canonical
299
+ * path ends as a real, non-symlink directory.
300
+ */
301
+ function materializeLink(link: LegacyLink, exclude: Set<string>): boolean {
302
+ // PID-suffixed so a standalone `hq reindex` overlapping the post-sync/rescue
303
+ // inline reindex (skipLock — an overlap that pass tolerates by design) can
304
+ // never rename/delete a temp directory out from under the other process.
305
+ const tmp = path.join(
306
+ path.dirname(link.linkPath),
307
+ `.${path.basename(link.linkPath)}.hq-knowledge-migrate.${process.pid}.tmp`,
308
+ );
309
+ try {
310
+ fs.rmSync(tmp, { recursive: true, force: true });
311
+ fs.cpSync(link.target, tmp, {
312
+ recursive: true,
313
+ verbatimSymlinks: true,
314
+ filter: (src) => !exclude.has(src),
315
+ });
316
+ } catch (err) {
317
+ warn(
318
+ `reindex: could not copy knowledge content for '${link.linkRel}' from '${link.target}' (${(err as Error).message}); leaving the legacy symlink in place`,
319
+ );
320
+ fs.rmSync(tmp, { recursive: true, force: true });
321
+ return false;
322
+ }
323
+
324
+ const previousTarget = (() => {
325
+ try {
326
+ return fs.readlinkSync(link.linkPath);
327
+ } catch {
328
+ return null;
329
+ }
330
+ })();
331
+
332
+ try {
333
+ fs.rmSync(link.linkPath);
334
+ fs.renameSync(tmp, link.linkPath);
335
+ } catch (err) {
336
+ // Restore the link if the swap died between rm and rename, so the
337
+ // knowledge path never ends up missing entirely.
338
+ if (previousTarget !== null && lstatOrNull(link.linkPath) === null) {
339
+ try {
340
+ fs.symlinkSync(previousTarget, link.linkPath);
341
+ } catch {
342
+ /* best-effort restore */
343
+ }
344
+ }
345
+ fs.rmSync(tmp, { recursive: true, force: true });
346
+ warn(
347
+ `reindex: could not swap knowledge symlink '${link.linkRel}' for its materialized copy (${(err as Error).message}); leaving the legacy layout in place`,
348
+ );
349
+ return false;
350
+ }
351
+
352
+ const st = lstatOrNull(link.linkPath);
353
+ return st !== null && st.isDirectory() && !st.isSymbolicLink();
354
+ }
355
+
356
+ /**
357
+ * Scour the HQ tree for legacy knowledge-repo layouts and migrate each to a
358
+ * real canonical directory, removing fully-migrated legacy repos under
359
+ * `repos/`. Best-effort throughout; never throws.
360
+ */
361
+ export function materializeLegacyKnowledgeRepos(root: string): void {
362
+ if (process.env.HQ_REINDEX_SKIP_KNOWLEDGE_MIGRATION === "1") return;
363
+ try {
364
+ const symlinkCandidates = knowledgeCandidates(root).filter((p) =>
365
+ lstatOrNull(p)?.isSymbolicLink(),
366
+ );
367
+ if (symlinkCandidates.length === 0) return;
368
+
369
+ const rootTop = gitToplevel(root);
370
+ const links = symlinkCandidates
371
+ .map((p) => classifyLink(root, p, rootTop))
372
+ .filter((l): l is LegacyLink => l !== null);
373
+ if (links.length === 0) return;
374
+
375
+ // Pull each distinct legacy repo once, before any copies are taken.
376
+ const pulled = new Set<string>();
377
+ for (const link of links) {
378
+ if (link.repoTop && !pulled.has(link.repoTop)) {
379
+ pulled.add(link.repoTop);
380
+ pullLegacyRepo(root, link.repoTop);
381
+ }
382
+ }
383
+
384
+ // Materialize every link first; legacy repos are only removed once no
385
+ // remaining symlink references them (aliases to one repo each get a copy).
386
+ const byRepo = new Map<
387
+ string,
388
+ { targets: Set<string>; allMigrated: boolean; keepReasons: Set<string> }
389
+ >();
390
+ for (const link of links) {
391
+ const exclusions = copyExclusions(root, link);
392
+ const ok = materializeLink(link, exclusions.paths);
393
+ if (ok) {
394
+ warn(
395
+ `reindex: materialized knowledge repo at '${link.linkRel}' (was a symlink to '${path.relative(root, link.target)}')`,
396
+ );
397
+ }
398
+ if (link.repoTop) {
399
+ const rec = byRepo.get(link.repoTop) ?? {
400
+ targets: new Set<string>(),
401
+ allMigrated: true,
402
+ keepReasons: new Set<string>(),
403
+ };
404
+ rec.targets.add(link.target);
405
+ rec.allMigrated = rec.allMigrated && ok;
406
+ for (const reason of exclusions.keepLegacyReasons) rec.keepReasons.add(reason);
407
+ byRepo.set(link.repoTop, rec);
408
+ }
409
+ }
410
+
411
+ // Remove a legacy repo only when it (a) lives under repos/ inside this HQ,
412
+ // (b) had every referencing symlink migrated, and (c) held nothing beyond
413
+ // the knowledge itself — i.e. every link targeted the repo root. A repo
414
+ // whose knowledge was a subdirectory (e.g. <repo>/docs) is left in place.
415
+ for (const [repoTop, rec] of byRepo) {
416
+ const repoRel = path.relative(root, repoTop);
417
+ if (!isUnder(repoTop, path.join(root, "repos"))) {
418
+ warn(
419
+ `reindex: legacy knowledge repo '${repoTop}' lives outside this HQ's repos/ — content was materialized; remove the old repo yourself once verified`,
420
+ );
421
+ continue;
422
+ }
423
+ if (!rec.allMigrated) continue;
424
+ if (rec.keepReasons.size > 0) {
425
+ for (const reason of rec.keepReasons) {
426
+ warn(`reindex: keeping legacy knowledge repo '${repoRel}' — ${reason}`);
427
+ }
428
+ continue;
429
+ }
430
+ if (![...rec.targets].every((t) => t === repoTop)) {
431
+ warn(
432
+ `reindex: legacy repo '${repoRel}' also holds content beyond the migrated knowledge subdirectory; leaving it in place`,
433
+ );
434
+ continue;
435
+ }
436
+ try {
437
+ fs.rmSync(repoTop, { recursive: true, force: true });
438
+ warn(`reindex: removed legacy knowledge repo '${repoRel}' (fully materialized inline)`);
439
+ } catch (err) {
440
+ warn(
441
+ `reindex: could not remove legacy knowledge repo '${repoRel}' (${(err as Error).message}); its content was already materialized`,
442
+ );
443
+ }
444
+ }
445
+ } catch (err) {
446
+ warn(
447
+ `reindex: legacy knowledge-repo migration pass failed (${(err as Error).message}); skipping`,
448
+ );
449
+ }
450
+ }
@@ -37,6 +37,7 @@ import {
37
37
  type TelemetryClaims,
38
38
  } from "../telemetry-events.js";
39
39
  import { decodeLocalVaultSegment, encodeLocalVaultSegment } from "../local-path-codec.js";
40
+ import { materializeLegacyKnowledgeRepos } from "./reindex-knowledge.js";
40
41
 
41
42
  export interface ReindexOptions {
42
43
  /** HQ root to operate on. Defaults to process.cwd(). */
@@ -536,6 +537,14 @@ export function reindex(opts: ReindexOptions = {}): ReindexResult {
536
537
  }
537
538
  try {
538
539
 
540
+ // --- Legacy knowledge-repo materialization --------------------------------
541
+ // Knowledge repositories must be real directories at their canonical paths
542
+ // (policy knowledge-repositories-never-symlink); a symlink to a repo under
543
+ // repos/ syncs as an empty vault marker. Scour the canonical knowledge
544
+ // locations, pull + copy each legacy repo inline, and drop the fully
545
+ // migrated legacy repo. Best-effort and a pure no-op on compliant trees.
546
+ materializeLegacyKnowledgeRepos(root);
547
+
539
548
  // Overlay/skill-wrapper mirroring is best-effort and, on a normal synced HQ,
540
549
  // legitimately no-ops for MANY entries (a real core file already sits where a
541
550
  // symlink would go, or a link already points elsewhere). Emitting one stderr
@@ -497,11 +497,17 @@ exec ${JSON.stringify(realGit)} "$@"
497
497
  expect(r.threw, out).toBeUndefined();
498
498
  expect(r.status, out).toBe(0);
499
499
  // The core fixture proves a real rescue apply occurred, while this
500
- // release-owned setting proves `.claude` reached the outpost.
500
+ // release-owned setting proves `.claude` reached the outpost. The
501
+ // post-overlay settings reconcile keeps the release baseline (`release:
502
+ // true`) and additionally composes the machine env.PATH onto it (see
503
+ // reconcileClaudeSettings), so the file is the release marker plus a
504
+ // machine-specific env.PATH rather than the verbatim template.
501
505
  expect(fs.readFileSync(path.join(hqRoot, "core/a.md"), "utf-8")).toBe("v2\n");
502
- expect(fs.readFileSync(path.join(hqRoot, ".claude/settings.json"), "utf-8")).toBe(
503
- '{"release":true}\n',
506
+ const laidSettings = JSON.parse(
507
+ fs.readFileSync(path.join(hqRoot, ".claude/settings.json"), "utf-8"),
504
508
  );
509
+ expect(laidSettings.release).toBe(true);
510
+ expect(typeof laidSettings.env?.PATH).toBe("string");
505
511
  // `.local` survives untouched and is not copied into the safety snapshot.
506
512
  expect(fs.statSync(deviceId).mode & 0o777).toBe(0o000);
507
513
  const snapshots = fs.readdirSync(backupRoot).filter((name) => name.startsWith("pre-update-"));