@indigoai-us/hq-cloud 6.18.109 → 6.18.111

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 (152) hide show
  1. package/dist/bin/area-ledger-migration.d.ts.map +1 -1
  2. package/dist/bin/area-ledger-migration.js +5 -3
  3. package/dist/bin/area-ledger-migration.js.map +1 -1
  4. package/dist/bin/backup-prune-runner.js +2 -2
  5. package/dist/bin/backup-prune-runner.js.map +1 -1
  6. package/dist/bin/runner-output-guard.d.ts +39 -0
  7. package/dist/bin/runner-output-guard.d.ts.map +1 -0
  8. package/dist/bin/runner-output-guard.js +104 -0
  9. package/dist/bin/runner-output-guard.js.map +1 -0
  10. package/dist/bin/sync-runner-company.d.ts +20 -0
  11. package/dist/bin/sync-runner-company.d.ts.map +1 -1
  12. package/dist/bin/sync-runner-company.js +134 -6
  13. package/dist/bin/sync-runner-company.js.map +1 -1
  14. package/dist/bin/sync-runner.d.ts +42 -1
  15. package/dist/bin/sync-runner.d.ts.map +1 -1
  16. package/dist/bin/sync-runner.js +37 -3
  17. package/dist/bin/sync-runner.js.map +1 -1
  18. package/dist/cli/conflict.d.ts +30 -1
  19. package/dist/cli/conflict.d.ts.map +1 -1
  20. package/dist/cli/conflict.js +69 -3
  21. package/dist/cli/conflict.js.map +1 -1
  22. package/dist/cli/reconcile-skip-reason.d.ts +13 -3
  23. package/dist/cli/reconcile-skip-reason.d.ts.map +1 -1
  24. package/dist/cli/reconcile-skip-reason.js +18 -0
  25. package/dist/cli/reconcile-skip-reason.js.map +1 -1
  26. package/dist/cli/reindex.d.ts.map +1 -1
  27. package/dist/cli/reindex.js +231 -44
  28. package/dist/cli/reindex.js.map +1 -1
  29. package/dist/cli/rescue-core.d.ts +98 -2
  30. package/dist/cli/rescue-core.d.ts.map +1 -1
  31. package/dist/cli/rescue-core.js +501 -76
  32. package/dist/cli/rescue-core.js.map +1 -1
  33. package/dist/cli/rescue-hq-registrations.d.ts +45 -0
  34. package/dist/cli/rescue-hq-registrations.d.ts.map +1 -0
  35. package/dist/cli/rescue-hq-registrations.js +252 -0
  36. package/dist/cli/rescue-hq-registrations.js.map +1 -0
  37. package/dist/cli/rescue.d.ts +8 -0
  38. package/dist/cli/rescue.d.ts.map +1 -1
  39. package/dist/cli/rescue.js +64 -17
  40. package/dist/cli/rescue.js.map +1 -1
  41. package/dist/cli/share.d.ts +35 -8
  42. package/dist/cli/share.d.ts.map +1 -1
  43. package/dist/cli/share.js +491 -32
  44. package/dist/cli/share.js.map +1 -1
  45. package/dist/cli/sync.d.ts +70 -5
  46. package/dist/cli/sync.d.ts.map +1 -1
  47. package/dist/cli/sync.js +445 -79
  48. package/dist/cli/sync.js.map +1 -1
  49. package/dist/cognito-auth.d.ts +10 -0
  50. package/dist/cognito-auth.d.ts.map +1 -1
  51. package/dist/cognito-auth.js +162 -1
  52. package/dist/cognito-auth.js.map +1 -1
  53. package/dist/ignore.d.ts.map +1 -1
  54. package/dist/ignore.js +43 -21
  55. package/dist/ignore.js.map +1 -1
  56. package/dist/index.d.ts +3 -3
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js +2 -2
  59. package/dist/index.js.map +1 -1
  60. package/dist/journal-row-store.d.ts +3 -0
  61. package/dist/journal-row-store.d.ts.map +1 -1
  62. package/dist/journal-row-store.js +21 -0
  63. package/dist/journal-row-store.js.map +1 -1
  64. package/dist/journal-snapshot-decoder.js +2 -0
  65. package/dist/journal-snapshot-decoder.js.map +1 -1
  66. package/dist/journal-snapshot-v4.d.ts.map +1 -1
  67. package/dist/journal-snapshot-v4.js +6 -1
  68. package/dist/journal-snapshot-v4.js.map +1 -1
  69. package/dist/journal.d.ts +1 -1
  70. package/dist/journal.d.ts.map +1 -1
  71. package/dist/journal.js +20 -20
  72. package/dist/journal.js.map +1 -1
  73. package/dist/lib/append-log-merge.d.ts +43 -0
  74. package/dist/lib/append-log-merge.d.ts.map +1 -0
  75. package/dist/lib/append-log-merge.js +424 -0
  76. package/dist/lib/append-log-merge.js.map +1 -0
  77. package/dist/lib/same-path-upload-lock.d.ts +27 -1
  78. package/dist/lib/same-path-upload-lock.d.ts.map +1 -1
  79. package/dist/lib/same-path-upload-lock.js +32 -1
  80. package/dist/lib/same-path-upload-lock.js.map +1 -1
  81. package/dist/object-io.d.ts +36 -1
  82. package/dist/object-io.d.ts.map +1 -1
  83. package/dist/object-io.js +97 -13
  84. package/dist/object-io.js.map +1 -1
  85. package/dist/operation-lock.d.ts +27 -1
  86. package/dist/operation-lock.d.ts.map +1 -1
  87. package/dist/operation-lock.js +94 -8
  88. package/dist/operation-lock.js.map +1 -1
  89. package/dist/outposts/client.d.ts +19 -6
  90. package/dist/outposts/client.d.ts.map +1 -1
  91. package/dist/outposts/client.js +16 -5
  92. package/dist/outposts/client.js.map +1 -1
  93. package/dist/outposts/command.d.ts +2 -1
  94. package/dist/outposts/command.d.ts.map +1 -1
  95. package/dist/outposts/command.js +81 -13
  96. package/dist/outposts/command.js.map +1 -1
  97. package/dist/outposts/self-deploy.d.ts.map +1 -1
  98. package/dist/outposts/self-deploy.js +3 -0
  99. package/dist/outposts/self-deploy.js.map +1 -1
  100. package/dist/private-folder-transport.d.ts +0 -2
  101. package/dist/private-folder-transport.d.ts.map +1 -1
  102. package/dist/private-folder-transport.js +17 -16
  103. package/dist/private-folder-transport.js.map +1 -1
  104. package/dist/push-identity-fence.d.ts +116 -3
  105. package/dist/push-identity-fence.d.ts.map +1 -1
  106. package/dist/push-identity-fence.js +625 -62
  107. package/dist/push-identity-fence.js.map +1 -1
  108. package/dist/qmd-reindex.d.ts.map +1 -1
  109. package/dist/qmd-reindex.js +3 -2
  110. package/dist/qmd-reindex.js.map +1 -1
  111. package/dist/s3.d.ts +30 -9
  112. package/dist/s3.d.ts.map +1 -1
  113. package/dist/s3.js +110 -82
  114. package/dist/s3.js.map +1 -1
  115. package/dist/session-log-retention.d.ts +86 -0
  116. package/dist/session-log-retention.d.ts.map +1 -1
  117. package/dist/session-log-retention.js +127 -19
  118. package/dist/session-log-retention.js.map +1 -1
  119. package/dist/sync/area-ledger-migration.d.ts +17 -0
  120. package/dist/sync/area-ledger-migration.d.ts.map +1 -1
  121. package/dist/sync/area-ledger-migration.js +37 -3
  122. package/dist/sync/area-ledger-migration.js.map +1 -1
  123. package/dist/sync/scattered-delete-burst.d.ts +61 -0
  124. package/dist/sync/scattered-delete-burst.d.ts.map +1 -0
  125. package/dist/sync/scattered-delete-burst.js +111 -0
  126. package/dist/sync/scattered-delete-burst.js.map +1 -0
  127. package/dist/sync/unattended-delete-hold.d.ts +102 -0
  128. package/dist/sync/unattended-delete-hold.d.ts.map +1 -0
  129. package/dist/sync/unattended-delete-hold.js +164 -0
  130. package/dist/sync/unattended-delete-hold.js.map +1 -0
  131. package/dist/sync-core.d.ts +5 -6
  132. package/dist/sync-core.d.ts.map +1 -1
  133. package/dist/sync-core.js +5 -6
  134. package/dist/sync-core.js.map +1 -1
  135. package/dist/types.d.ts +13 -2
  136. package/dist/types.d.ts.map +1 -1
  137. package/dist/vault-client.d.ts +6 -0
  138. package/dist/vault-client.d.ts.map +1 -1
  139. package/dist/vault-client.js +53 -8
  140. package/dist/vault-client.js.map +1 -1
  141. package/dist/vault-key-grammar.d.ts +44 -0
  142. package/dist/vault-key-grammar.d.ts.map +1 -0
  143. package/dist/vault-key-grammar.js +158 -0
  144. package/dist/vault-key-grammar.js.map +1 -0
  145. package/dist/watcher.d.ts.map +1 -1
  146. package/dist/watcher.js +4 -1
  147. package/dist/watcher.js.map +1 -1
  148. package/dist/windows-extended-path.d.ts +22 -0
  149. package/dist/windows-extended-path.d.ts.map +1 -0
  150. package/dist/windows-extended-path.js +55 -0
  151. package/dist/windows-extended-path.js.map +1 -0
  152. package/package.json +1 -1
@@ -40,8 +40,9 @@ import { assertRescuePathTypeUnchanged, isRescueTransientDirectory, rescueSnapsh
40
40
  import { applyBackupPrune, canonicalRootHash, inventoryManagedSnapshots, isManagedSnapshotManifest, } from "../backup-prune.js";
41
41
  import { makeRestoreProbePath, makeRestoreStagePath, } from "../restore-staging.js";
42
42
  import { readCoreSourceStamp, writeCoreSourceStamp } from "./core-source-stamp.js";
43
- import { rsyncFilterRuleMatches, runNativeOverlay } from "./rescue-native-copy.js";
43
+ import { compileRsyncPattern, rsyncFilterRuleMatches, runNativeOverlay, } from "./rescue-native-copy.js";
44
44
  import { chooseRescueGit, GIT_VERSION_PROBE_TIMEOUT_MS, gitTooOldMessage, parseGitVersion, pinGitFirstOnPath, RESCUE_MIN_GIT_VERSION, } from "./rescue-git.js";
45
+ import { collectHqRegistrations, placeHqRegistrations, removeHqRegistrations, withoutHqRegistrations, } from "./rescue-hq-registrations.js";
45
46
  const MAX_CLONE_FILES_PER_BATCH = 200;
46
47
  const MAX_CLONE_BATCH_PATH_BYTES = 64 * 1024;
47
48
  const require = createRequire(import.meta.url);
@@ -320,6 +321,12 @@ function classifyGitFailure(result) {
320
321
  if (isMissingMacCommandLineTools(diagnostic)) {
321
322
  return "missing-dependency";
322
323
  }
324
+ // A dead or unresolvable http.proxy in git config is not a flaky network.
325
+ // Retrying it three times only delays the same error, and blaming the
326
+ // Internet connection hides the setting that caused it.
327
+ if (diagnostic.includes("could not resolve proxy")) {
328
+ return "proxy-config";
329
+ }
323
330
  // Interrupted transfers are retryable. Corrupt packs, checksum mismatches,
324
331
  // and other integrity failures are not: retrying those three times hides the
325
332
  // real error and can write a bad clone more than once.
@@ -328,7 +335,6 @@ function classifyGitFailure(result) {
328
335
  const transientNetworkSignals = [
329
336
  "resolving timed out",
330
337
  "could not resolve host",
331
- "could not resolve proxy",
332
338
  "temporary failure in name resolution",
333
339
  "network is unreachable",
334
340
  "connection timed out",
@@ -545,14 +551,38 @@ function buildRsyncLauncher(candidatePath) {
545
551
  }
546
552
  return { command: "rsync", leadingArgs: [] };
547
553
  }
554
+ /** The `rsync --version` probe may not hang the rescue; a hung shim fails closed. */
555
+ export const RSYNC_PROBE_TIMEOUT_MS = 15_000;
556
+ /** Error code for a Windows shim path that cmd.exe cannot be trusted to parse. */
557
+ export const RSYNC_UNSAFE_SHIM_PATH = "EUNSAFEPATH";
558
+ /**
559
+ * True when a `.cmd`/`.bat` path can be passed to `cmd.exe /d /c` as one
560
+ * argument. Node quotes an argument only for spaces and quotes, and cmd.exe
561
+ * still expands `%VAR%` and treats `& | < > ^ ( ) @ !` specially, so a path
562
+ * with any of them is refused rather than launched.
563
+ */
564
+ export function isCmdSafeShimPath(candidatePath) {
565
+ return !/[&|<>^%!"()@]/.test(candidatePath);
566
+ }
548
567
  /** Find rsync on PATH and run `rsync --version` through the overlay's launcher. */
549
568
  function probeRsync(env) {
550
569
  const resolvedPath = envValue(env, "PATH");
551
570
  const entries = pathEntries(resolvedPath);
552
571
  const foundRsync = findRsyncOnPath(entries, env);
553
572
  const launcher = buildRsyncLauncher(foundRsync?.path);
573
+ if (process.platform === "win32" &&
574
+ foundRsync &&
575
+ isWindowsShimPath(foundRsync.path) &&
576
+ !isCmdSafeShimPath(foundRsync.path)) {
577
+ // cmd.exe would re-parse these characters inside the path, so the shim
578
+ // is never launched (here or by the overlay).
579
+ const error = Object.assign(new Error("rsync shim path contains characters cmd.exe would interpret"), { code: RSYNC_UNSAFE_SHIM_PATH });
580
+ const probe = { status: 126, stdout: "", stderr: "", error, signal: null };
581
+ return { launcher, foundRsync, entries, resolvedPath, probe, output: "\n", working: false };
582
+ }
554
583
  const probe = runWithSpawnError(launcher.command, [...launcher.leadingArgs, "--version"], {
555
584
  env,
585
+ timeout: RSYNC_PROBE_TIMEOUT_MS,
556
586
  });
557
587
  const output = `${probe.stdout}\n${probe.stderr}`;
558
588
  const working = probe.status === 0 && /\brsync\b.*\bversion\b/i.test(output);
@@ -563,6 +593,30 @@ function probeRsync(env) {
563
593
  * with ENOENT. A present but unexecutable, failing, or unrecognised rsync is
564
594
  * not "absent" and still stops the rescue.
565
595
  */
596
+ /**
597
+ * On Windows, the rsync on PATH plainly cannot run: it could not be spawned
598
+ * (ENOENT, EACCES), its shim path is unsafe for cmd.exe, or it exited non-zero
599
+ * with no output at all. A timeout, a signal, unrecognised version output or
600
+ * a non-zero exit that printed something is not "cannot run" and still stops
601
+ * the rescue, so a misconfigured rsync the user installed stays loud.
602
+ */
603
+ export function rsyncCannotRunOnWindows(result) {
604
+ const code = result.probe.error && "code" in result.probe.error
605
+ ? result.probe.error.code
606
+ : undefined;
607
+ if (code === "ENOENT" || code === "EACCES" || code === RSYNC_UNSAFE_SHIM_PATH)
608
+ return true;
609
+ if (result.probe.error || result.probe.signal)
610
+ return false;
611
+ return result.probe.status !== 0 && result.output.trim() === "";
612
+ }
613
+ /** One-line reason for the log when the Windows fallback is taken. */
614
+ function rsyncProbeFailureSummary(result) {
615
+ const error = result.probe.error;
616
+ if (error)
617
+ return error.code ?? error.name;
618
+ return `exit ${result.probe.status}, no output`;
619
+ }
566
620
  function rsyncIsMissing(result) {
567
621
  const code = result.probe.error && "code" in result.probe.error
568
622
  ? result.probe.error.code
@@ -583,8 +637,9 @@ export const COPY_ENGINE_ENV = "HQ_RESCUE_COPY_ENGINE";
583
637
  *
584
638
  * A working rsync is used as before. When rsync is not on PATH at all, the
585
639
  * overlay uses the built-in file copy (./rescue-native-copy.ts) with the same
586
- * filters, instead of failing with exit 127. An rsync that is on PATH but
587
- * broken still fails the preflight, as before. `HQ_RESCUE_COPY_ENGINE=rsync`
640
+ * filters, instead of failing with exit 127. On Windows an rsync that is on
641
+ * PATH but plainly cannot run (see rsyncCannotRunOnWindows) also uses the
642
+ * built-in copy; any other broken rsync still fails the preflight. `HQ_RESCUE_COPY_ENGINE=rsync`
588
643
  * keeps the old rsync-only behaviour; `HQ_RESCUE_COPY_ENGINE=native` uses
589
644
  * the built-in copy even when rsync works.
590
645
  */
@@ -605,6 +660,16 @@ export function selectOverlayCopyEngine(env, out, err) {
605
660
  out("==> Copy engine: built-in file copy (rsync not found on PATH)\n");
606
661
  return { kind: "native" };
607
662
  }
663
+ // On Windows an rsync that is on PATH but plainly cannot run (a .cmd shim
664
+ // whose target is gone, an MSYS rsync missing its DLLs) is common and not
665
+ // something the user chose. Use the built-in copy there too, and say why.
666
+ // Any other probe failure, every failure off Windows, and
667
+ // HQ_RESCUE_COPY_ENGINE=rsync still stop the rescue.
668
+ if (forced === "" && process.platform === "win32" && rsyncCannotRunOnWindows(result)) {
669
+ const where = result.foundRsync?.path ?? "PATH";
670
+ out(`==> Copy engine: built-in file copy (rsync at ${boundedDiagnostic(where, 256)} could not run: ${boundedDiagnostic(rsyncProbeFailureSummary(result), 128)})\n`);
671
+ return { kind: "native" };
672
+ }
608
673
  return reportRsyncPreflightFailure(result, err);
609
674
  }
610
675
  /** Print the rsync preflight diagnostic and stop the rescue. */
@@ -614,7 +679,9 @@ function reportRsyncPreflightFailure({ foundRsync, entries, resolvedPath, probe,
614
679
  const errorDetail = "code" in probe.error && typeof probe.error.code === "string"
615
680
  ? probe.error.code
616
681
  : probe.error.name;
617
- err(` rsync was not found or could not be executed (${errorDetail}).\n`);
682
+ err(errorDetail === "ETIMEDOUT"
683
+ ? ` rsync --version did not finish within ${RSYNC_PROBE_TIMEOUT_MS / 1000}s (ETIMEDOUT).\n`
684
+ : ` rsync was not found or could not be executed (${errorDetail}).\n`);
618
685
  }
619
686
  else if (probe.signal) {
620
687
  err(` rsync was terminated by signal ${probe.signal}.\n`);
@@ -1954,6 +2021,144 @@ export function fullOverlayRsyncFilters(extraPreserve = []) {
1954
2021
  filters.push(`--exclude=${p}`);
1955
2022
  return filters;
1956
2023
  }
2024
+ /**
2025
+ * The full overlay filter list for a rescue run. rsync and the native copy
2026
+ * engine apply the first rule that matches, so the order is:
2027
+ * 1. `--preserve` entries (full mode), so a preserved path is never written,
2028
+ * even when a kept install rule below names it;
2029
+ * 2. the install exclusions (kept rules, then excluded ones), in both modes;
2030
+ * 3. the mode's own rules: the narrow-path includes, or the full overlay list.
2031
+ */
2032
+ export function overlayRsyncFilters(narrowPaths, extraPreserve) {
2033
+ if (narrowPaths.length !== 0) {
2034
+ const filters = [...installExcludedRsyncFilters()];
2035
+ for (const n of narrowPaths) {
2036
+ filters.push(`--include=/${n}`, `--include=/${n}/***`);
2037
+ }
2038
+ filters.push("--exclude=/*");
2039
+ return filters;
2040
+ }
2041
+ return [
2042
+ ...extraPreserve.map((p) => `--exclude=${p}`),
2043
+ ...installExcludedRsyncFilters(),
2044
+ ...fullOverlayRsyncFilters([...extraPreserve]),
2045
+ ];
2046
+ }
2047
+ /**
2048
+ * Test and build files of a release that an install does not receive.
2049
+ *
2050
+ * The release tree (hq-core, and hq-core-staging on the staging channel) keeps
2051
+ * its tests, fixtures and hook corpora, because its own CI runs them. An
2052
+ * install runs none of them, so the overlay does not copy them and the
2053
+ * classifier treats them as absent from the release.
2054
+ *
2055
+ * The list is explicit, in rsync filter syntax. A name with no `/` matches at
2056
+ * any depth, a trailing `/` matches directories only, and a leading `/`
2057
+ * anchors the pattern at the release root. It was derived from the files the
2058
+ * hq-core-staging promotion carried on 2026-11-13:
2059
+ * - `tests/`, `__tests__/`, `__fixtures__/`, `__snapshots__/`: test folders
2060
+ * at any depth (core/scripts/tests, .claude/hooks/tests, skill and worker
2061
+ * test folders, the root `tests/`).
2062
+ * - the anchored folders: the root `test/`, the hook corpus, and two
2063
+ * fixture folders with other names.
2064
+ * - `*.test.<ext>` and `*.spec.<ext>` for code extensions, and `test_*.py`:
2065
+ * test files that sit beside the code they test.
2066
+ * - the anchored files: test runners whose names do not fit a pattern.
2067
+ *
2068
+ * No pattern matches on `-test.` or `test-` alone: worker skill documents such
2069
+ * as `keyboard-test.md`, `screen-reader-test.md`, `write-test.md` and
2070
+ * `load-test.md` are shipped content. `core/hook-tests/` is not listed either:
2071
+ * `hq doctor --deep` reads those hook cases on an install.
2072
+ */
2073
+ const INSTALL_TEST_EXTENSIONS = ["sh", "bash", "mjs", "cjs", "js", "ts", "tsx", "py", "ps1"];
2074
+ export const INSTALL_EXCLUDED_PATTERNS = [
2075
+ // Everything in core/scripts/tests that INSTALL_KEPT_PATTERNS does not name.
2076
+ "/core/scripts/tests/*",
2077
+ "tests/",
2078
+ "__tests__/",
2079
+ "__fixtures__/",
2080
+ "__snapshots__/",
2081
+ "/test/",
2082
+ "/core/scripts/hook-corpus/",
2083
+ "/core/workers/public/content-shared/test/",
2084
+ "/.claude/skills/daily-brief/scripts/fixtures/",
2085
+ ...INSTALL_TEST_EXTENSIONS.flatMap((ext) => [`*.test.${ext}`, `*.spec.${ext}`]),
2086
+ "test_*.py",
2087
+ "/core/scripts/test-codex-hook-adapter.sh",
2088
+ "/core/scripts/anywhere-parity-test.sh",
2089
+ "/core/scripts/anywhere-vm-test.sh",
2090
+ "/.claude/skills/outpost-host/test-guard.sh",
2091
+ ];
2092
+ /**
2093
+ * Release paths that match a pattern above and are still installed, because a
2094
+ * shipped script runs them. A kept pattern wins over an excluded one. Remove
2095
+ * an entry when its caller stops shipping.
2096
+ */
2097
+ export const INSTALL_KEPT_PATTERNS = [
2098
+ // core/workers/public/qa-tester/src/runner.ts runs these Playwright specs
2099
+ // against a target site. They are the worker's payload.
2100
+ "/core/workers/public/qa-tester/tests/***",
2101
+ // The folder itself, so the files named below can be reached.
2102
+ "/core/scripts/tests/",
2103
+ // core/scripts/check-skill-edit.sh runs these six.
2104
+ "/core/scripts/tests/skill-script-refs.test.sh",
2105
+ "/core/scripts/tests/skill-core-script-references.test.sh",
2106
+ "/core/scripts/tests/skill-body-positional-placeholders.test.sh",
2107
+ "/core/scripts/tests/skill-company-bind-before-read.test.sh",
2108
+ "/core/scripts/tests/agent-runtime-skill-metadata.test.sh",
2109
+ "/core/scripts/tests/agent-runtime-permissions.test.sh",
2110
+ // core/scripts/ci/run-shell-smoke-timeout-tests.sh runs these two.
2111
+ "/core/scripts/tests/hook-timeout-sentry.test.sh",
2112
+ "/core/scripts/tests/hook-timeout-watchdog-attribution.test.sh",
2113
+ ];
2114
+ /** The install exclusions as overlay filters. They go first: the first match wins. */
2115
+ export function installExcludedRsyncFilters() {
2116
+ return [
2117
+ ...INSTALL_KEPT_PATTERNS.map((pattern) => `--include=${pattern}`),
2118
+ ...INSTALL_EXCLUDED_PATTERNS.map((pattern) => `--exclude=${pattern}`),
2119
+ ];
2120
+ }
2121
+ const INSTALL_KEPT_MATCHERS = INSTALL_KEPT_PATTERNS.map(compileRsyncPattern);
2122
+ const INSTALL_EXCLUDED_MATCHERS = INSTALL_EXCLUDED_PATTERNS.map(compileRsyncPattern);
2123
+ /**
2124
+ * True when `rel` (POSIX separators, relative to the HQ root) is a release
2125
+ * file that an install does not receive. Every ancestor folder is checked, as
2126
+ * rsync does, and a kept pattern wins over an excluded one at each level.
2127
+ */
2128
+ export function isInstallExcluded(rel) {
2129
+ const segments = rel.split("/").filter((segment) => segment.length > 0);
2130
+ for (let depth = 1; depth <= segments.length; depth++) {
2131
+ const prefix = segments.slice(0, depth).join("/");
2132
+ const isDir = depth < segments.length;
2133
+ if (INSTALL_KEPT_MATCHERS.some((matches) => matches(prefix, isDir)))
2134
+ continue;
2135
+ if (INSTALL_EXCLUDED_MATCHERS.some((matches) => matches(prefix, isDir)))
2136
+ return true;
2137
+ }
2138
+ return false;
2139
+ }
2140
+ /**
2141
+ * True when the folder that holds `rel` is the physical folder that path names
2142
+ * under the HQ root. A folder on the way that is a link makes this false,
2143
+ * whether the link points inside or outside the HQ root, so a release file is
2144
+ * never removed through a link.
2145
+ */
2146
+ export function installPathIsInsideRoot(hqRoot, rel) {
2147
+ const parentSegments = rel
2148
+ .split("/")
2149
+ .filter((segment) => segment.length > 0)
2150
+ .slice(0, -1);
2151
+ if (path.isAbsolute(rel) || rel.split("/").includes(".."))
2152
+ return false;
2153
+ try {
2154
+ const root = fs.realpathSync.native(hqRoot);
2155
+ const parent = fs.realpathSync.native(path.join(hqRoot, ...parentSegments));
2156
+ return parent === path.join(root, ...parentSegments);
2157
+ }
2158
+ catch {
2159
+ return false;
2160
+ }
2161
+ }
1957
2162
  /**
1958
2163
  * True when rsync's overlay, run with `filters` (the rescue's `--include=` and
1959
2164
  * `--exclude=` list), would transfer `rel`. Every ancestor directory is
@@ -2313,10 +2518,10 @@ function assertClaudeSettingsAdmission(hqRoot, err) {
2313
2518
  function doRescue(cfg, env, out, err, setTmp, retainTmp, gitReachabilityProbeTimeoutMs = GIT_REACHABILITY_PROBE_TIMEOUT_MS, stampWriter = writeCoreSourceStamp, restoreOnRsyncFailure = false, setupPathSettingsLocal = false, backupCapacityStatfsSync = fs.statfsSync, backupCapacityCloneProbe, backupCapacityStatSync = fs.statSync, pathSep = path.sep, snapshotClonePlatform = process.platform, snapshotCloneRunner = runDarwinClone) {
2314
2519
  const hqRoot = resolveHqRoot(cfg, err);
2315
2520
  const RUN_TS = utcStamp(new Date(), "dash");
2316
- // Choose the overlay engine before classification/allocation. A shim which
2317
- // merely starts but exits non-zero used to trigger an enormous cp -a
2318
- // fallback, then fail later at overlay, so a broken rsync still stops here.
2319
- // No rsync at all (stock Windows) uses the built-in copy instead.
2521
+ // Choose the overlay engine before classification/allocation. No rsync at
2522
+ // all (stock Windows) uses the built-in copy, and so does a Windows rsync
2523
+ // that plainly cannot run. Any other broken rsync stops here, before an
2524
+ // enormous snapshot is allocated, rather than failing later at overlay.
2320
2525
  const copyEngine = selectOverlayCopyEngine(env, out, err);
2321
2526
  // The release clone uses `--filter=blob:none`, which needs git 2.19+. Check
2322
2527
  // before the prompt so an old git fails with a plain message instead of a
@@ -2508,7 +2713,11 @@ function doRescue(cfg, env, out, err, setTmp, retainTmp, gitReachabilityProbeTim
2508
2713
  err(`git ${gitResult.command} did not finish${bound} and was stopped ` +
2509
2714
  `(${gitResult.attempts} attempt${gitResult.attempts === 1 ? "" : "s"}).\n`);
2510
2715
  }
2511
- if (gitResult.failureKind === "network-unreachable") {
2716
+ if (gitResult.failureKind === "proxy-config") {
2717
+ err("HQ_RESCUE_FAILURE_KIND=proxy-config\n");
2718
+ err("error: Git could not resolve the http.proxy setting. Check git config http.proxy (including the HQ root's local .git/config), then retry. Nothing was changed.\n");
2719
+ }
2720
+ else if (gitResult.failureKind === "network-unreachable") {
2512
2721
  err("HQ_RESCUE_FAILURE_KIND=network-unreachable\n");
2513
2722
  err("error: HQ could not reach GitHub after retries. Check your Internet connection, then retry. Nothing was changed.\n");
2514
2723
  }
@@ -2522,18 +2731,19 @@ function doRescue(cfg, env, out, err, setTmp, retainTmp, gitReachabilityProbeTim
2522
2731
  throw new ExitError(5);
2523
2732
  };
2524
2733
  // One bounded ls-remote per update, not per clone or checkout attempt.
2525
- // Only network-unreachable and missing-dependency stop the rescue here;
2526
- // any other probe error is left for the clone to report, so a successful
2527
- // probe cannot mask a later clone failure.
2528
- const probeResult = runGitWithNetworkRetry(["ls-remote", "--exit-code", cloneUrl, cfg.ref], { env, timeout: gitReachabilityProbeTimeoutMs }, out);
2734
+ // network-unreachable, missing-dependency, and proxy-config stop the rescue
2735
+ // here; any other probe error is left for the clone to report, so a
2736
+ // successful probe cannot mask a later clone failure.
2737
+ const probeResult = runGitWithNetworkRetry(["ls-remote", "--exit-code", cloneUrl, cfg.ref], { cwd: tmpdir, env, timeout: gitReachabilityProbeTimeoutMs }, out);
2529
2738
  if (probeResult.failureKind === "network-unreachable" ||
2530
- probeResult.failureKind === "missing-dependency") {
2739
+ probeResult.failureKind === "missing-dependency" ||
2740
+ probeResult.failureKind === "proxy-config") {
2531
2741
  reportFatalGitFailure(probeResult, "error: clone failed\n");
2532
2742
  }
2533
2743
  out("\n");
2534
2744
  if (cfg.historyCheck) {
2535
2745
  out(`==> Cloning ${cloneUrlDisplay} @${cfg.ref} (full history, blob:none filter) ...\n`);
2536
- const cloneResult = runGitWithNetworkRetry(["clone", "--filter=blob:none", cloneUrl, srcDir], { env }, out, () => fs.rmSync(srcDir, { recursive: true, force: true }));
2746
+ const cloneResult = runGitWithNetworkRetry(["clone", "--filter=blob:none", cloneUrl, srcDir], { cwd: tmpdir, env }, out, () => fs.rmSync(srcDir, { recursive: true, force: true }));
2537
2747
  if (cloneResult.result.status !== 0) {
2538
2748
  reportFatalGitFailure(cloneResult, "error: clone failed\n");
2539
2749
  }
@@ -2544,7 +2754,7 @@ function doRescue(cfg, env, out, err, setTmp, retainTmp, gitReachabilityProbeTim
2544
2754
  }
2545
2755
  else {
2546
2756
  out(`==> Cloning ${cloneUrlDisplay} @${cfg.ref} (shallow) ...\n`);
2547
- const shallowCloneResult = runGitWithNetworkRetry(["clone", "--depth", "1", "--branch", cfg.ref, cloneUrl, srcDir], { env }, out, () => fs.rmSync(srcDir, { recursive: true, force: true }));
2757
+ const shallowCloneResult = runGitWithNetworkRetry(["clone", "--depth", "1", "--branch", cfg.ref, cloneUrl, srcDir], { cwd: tmpdir, env }, out, () => fs.rmSync(srcDir, { recursive: true, force: true }));
2548
2758
  if (shallowCloneResult.result.status !== 0) {
2549
2759
  if (shouldStopAfterShallowCloneFailure(shallowCloneResult)) {
2550
2760
  reportFatalGitFailure(shallowCloneResult, "error: clone failed\n");
@@ -2552,7 +2762,7 @@ function doRescue(cfg, env, out, err, setTmp, retainTmp, gitReachabilityProbeTim
2552
2762
  reportGitFailure(shallowCloneResult.result);
2553
2763
  out(" (shallow branch clone failed; trying full clone + checkout)\n");
2554
2764
  fs.rmSync(srcDir, { recursive: true, force: true });
2555
- const cloneResult = runGitWithNetworkRetry(["clone", cloneUrl, srcDir], { env }, out, () => fs.rmSync(srcDir, { recursive: true, force: true }));
2765
+ const cloneResult = runGitWithNetworkRetry(["clone", cloneUrl, srcDir], { cwd: tmpdir, env }, out, () => fs.rmSync(srcDir, { recursive: true, force: true }));
2556
2766
  if (cloneResult.result.status !== 0) {
2557
2767
  reportFatalGitFailure(cloneResult, "error: clone failed\n");
2558
2768
  }
@@ -2606,20 +2816,12 @@ function doRescue(cfg, env, out, err, setTmp, retainTmp, gitReachabilityProbeTim
2606
2816
  }
2607
2817
  // --- Build wipe/overlay arg sets per mode ---
2608
2818
  const pruneNames = [];
2609
- let rsyncExcludes = [];
2610
- if (cfg.narrowPaths.length !== 0) {
2611
- for (const n of cfg.narrowPaths) {
2612
- rsyncExcludes.push(`--include=/${n}`);
2613
- rsyncExcludes.push(`--include=/${n}/***`);
2614
- }
2615
- rsyncExcludes.push("--exclude=/*");
2616
- }
2617
- else {
2819
+ if (cfg.narrowPaths.length === 0) {
2618
2820
  pruneNames.push(...ALWAYS_PRESERVED_NAMES);
2619
2821
  for (const p of cfg.extraPreserve)
2620
2822
  pruneNames.push(p);
2621
- rsyncExcludes = fullOverlayRsyncFilters(cfg.extraPreserve);
2622
2823
  }
2824
+ const rsyncExcludes = overlayRsyncFilters(cfg.narrowPaths, cfg.extraPreserve);
2623
2825
  // --- Compute the wipe-set top-level roots ---
2624
2826
  const wipeToplevel = [];
2625
2827
  if (cfg.narrowPaths.length !== 0) {
@@ -2655,6 +2857,7 @@ function doRescue(cfg, env, out, err, setTmp, retainTmp, gitReachabilityProbeTim
2655
2857
  userConflict: 0,
2656
2858
  userOverwrite: 0,
2657
2859
  userKeptLocal: 0,
2860
+ installExcludedKept: 0,
2658
2861
  claudeDiffAppend: 0,
2659
2862
  symlinkDropped: 0,
2660
2863
  cloudSymlinkReconciled: 0,
@@ -2699,6 +2902,11 @@ function doRescue(cfg, env, out, err, setTmp, retainTmp, gitReachabilityProbeTim
2699
2902
  }
2700
2903
  else {
2701
2904
  out(`==> Walking wipe set, classifying vs. ${cfg.sourceRepo}@${cfg.ref} ...\n`);
2905
+ const packDirs = installedSkillPackDirs(hqRoot, releaseSkillNames(ctx));
2906
+ if (packDirs.length > 0) {
2907
+ ctx.skipDirs = new Set(packDirs);
2908
+ out(`==> Leaving ${packDirs.length} installed skill pack${packDirs.length === 1 ? "" : "s"} from ${SKILLS_LOCK_FILE} in place without classifying: ${packDirs.map((d) => d.slice(SKILLS_DIR.length + 1)).join(", ")}\n`);
2909
+ }
2702
2910
  // Batch the per-file git facts (hashes + floor lookups) up front so the
2703
2911
  // walk below is map lookups, not ~3 git spawns per file.
2704
2912
  precomputeGitMaps(ctx, wipeToplevel);
@@ -2716,6 +2924,7 @@ function doRescue(cfg, env, out, err, setTmp, retainTmp, gitReachabilityProbeTim
2716
2924
  out(` user-edit (conflict quarantine): ${counts.userConflict} files\n`);
2717
2925
  out(` user-edit (overwrite-safe): ${counts.userOverwrite} files\n`);
2718
2926
  out(` user-edit (kept local): ${counts.userKeptLocal} files\n`);
2927
+ out(` release test files kept (not installed): ${counts.installExcludedKept} files\n`);
2719
2928
  out(` cloud-symlink reconciled: ${counts.cloudSymlinkReconciled} files\n`);
2720
2929
  out(` drift reconciled (== upstream): ${counts.driftReconciled} files\n`);
2721
2930
  out(` reindex symlinks dropped: ${counts.symlinkDropped} entries\n`);
@@ -3037,7 +3246,7 @@ function doRescue(cfg, env, out, err, setTmp, retainTmp, gitReachabilityProbeTim
3037
3246
  mutationStarted = true;
3038
3247
  applyClassifiedActions(ctx, backupDir);
3039
3248
  out("\n");
3040
- out(`==> Walk complete (user-only: ${counts.userOnly}, unchanged: ${counts.unchanged}, user-edit-rescued: ${counts.userEdit}, conflict-quarantined: ${counts.userConflict}, overwrite-safe: ${counts.userOverwrite}, kept-local: ${counts.userKeptLocal}, cloud-symlink-reconciled: ${counts.cloudSymlinkReconciled}, symlinks-dropped: ${counts.symlinkDropped})\n`);
3249
+ out(`==> Walk complete (user-only: ${counts.userOnly}, unchanged: ${counts.unchanged}, user-edit-rescued: ${counts.userEdit}, conflict-quarantined: ${counts.userConflict}, overwrite-safe: ${counts.userOverwrite}, kept-local: ${counts.userKeptLocal}, release-test-kept: ${counts.installExcludedKept}, cloud-symlink-reconciled: ${counts.cloudSymlinkReconciled}, symlinks-dropped: ${counts.symlinkDropped})\n`);
3041
3250
  // --- Overlay source onto HQ root ---
3042
3251
  out("==> Overlaying source onto HQ root ...\n");
3043
3252
  // `unchangedList` is only populated during applyClassifiedActions above, so
@@ -3221,6 +3430,7 @@ function doRescue(cfg, env, out, err, setTmp, retainTmp, gitReachabilityProbeTim
3221
3430
  out(` user-edits (conflict quarantine): ${counts.userConflict} files\n`);
3222
3431
  out(` user-edits (overwrite-safe): ${counts.userOverwrite} files\n`);
3223
3432
  out(` user-edit (kept local): ${counts.userKeptLocal} files\n`);
3433
+ out(` release test files kept (not installed): ${counts.installExcludedKept} files\n`);
3224
3434
  out(` cloud-symlink reconciled: ${counts.cloudSymlinkReconciled} files\n`);
3225
3435
  out(` drift reconciled (== upstream): ${counts.driftReconciled} files\n`);
3226
3436
  out(` reindex symlinks dropped: ${counts.symlinkDropped} entries\n`);
@@ -3256,6 +3466,7 @@ function doRescue(cfg, env, out, err, setTmp, retainTmp, gitReachabilityProbeTim
3256
3466
  lines.push(` user-edit (conflict quarantine): ${counts.userConflict}`);
3257
3467
  lines.push(` user-edit (overwrite-safe): ${counts.userOverwrite}`);
3258
3468
  lines.push(` user-edit (kept local, ignore file): ${counts.userKeptLocal}`);
3469
+ lines.push(` release test files kept (not installed): ${counts.installExcludedKept}`);
3259
3470
  lines.push(` cloud-symlink reconciled: ${counts.cloudSymlinkReconciled}`);
3260
3471
  lines.push(` drift reconciled (== upstream HEAD): ${counts.driftReconciled}`);
3261
3472
  lines.push(` reindex symlinks dropped: ${counts.symlinkDropped}`);
@@ -3399,6 +3610,9 @@ function recordDecision(ctx, decision) {
3399
3610
  case "user-only":
3400
3611
  ctx.counts.userOnly += 1;
3401
3612
  return;
3613
+ case "install-excluded-kept":
3614
+ ctx.counts.installExcludedKept += 1;
3615
+ return;
3402
3616
  case "cloud-symlink-reconciled":
3403
3617
  ctx.counts.cloudSymlinkReconciled += 1;
3404
3618
  return;
@@ -4008,6 +4222,24 @@ export function applyArrayRemovals(theirs, ours, base) {
4008
4222
  }
4009
4223
  }
4010
4224
  }
4225
+ /**
4226
+ * True when every array element that `release` and `ours` share (at the same
4227
+ * path) is also present in `candidate`. Used to find how far back an older
4228
+ * release settings.json can be while still being one the local file could have
4229
+ * been laid from: a version missing an element the local file has from the
4230
+ * release is older than the version the local file was laid from.
4231
+ */
4232
+ export function holdsSharedArrayEntries(candidate, ours, release) {
4233
+ if (Array.isArray(release) && Array.isArray(ours)) {
4234
+ const cand = Array.isArray(candidate) ? candidate : [];
4235
+ return release.every((e) => !ours.some((o) => jsonDeepEqual(o, e)) || cand.some((c) => jsonDeepEqual(c, e)));
4236
+ }
4237
+ if (isPlainObject(release) && isPlainObject(ours)) {
4238
+ const cand = isPlainObject(candidate) ? candidate : {};
4239
+ return Object.keys(release).every((k) => holdsSharedArrayEntries(cand[k], ours[k], release[k]));
4240
+ }
4241
+ return true;
4242
+ }
4011
4243
  /**
4012
4244
  * Re-compose the machine env.PATH for the freshly-overlaid release template.
4013
4245
  * Runs the SAME composer setup.sh uses (core/scripts/compose-settings-path.sh)
@@ -4320,6 +4552,14 @@ export function reconcileClaudeSettings(ctx, preRescueSettingsJson, out, err) {
4320
4552
  // PATH must never become release drift when lookup fails or defaults off.
4321
4553
  const writePathLocally = Boolean(composedPath);
4322
4554
  const releaseBaseline = structuredClone(theirs);
4555
+ // Hook entries `hq reindex` registers (hq-hook in place of a shipped
4556
+ // master-hook entry) are HQ's, not user edits. Diff `ours` with each one
4557
+ // standing for the shipped entry it replaced, and put them back into
4558
+ // settings.json after the merge. Registrations an HQ settings merge moved
4559
+ // into settings.local.json count too, and come back out of it.
4560
+ const localRegistrations = collectHqRegistrations([existingLocalForPath], hqRoot);
4561
+ const hqRegistrations = collectHqRegistrations([oursIsValid ? ours : null, existingLocalForPath], hqRoot);
4562
+ const oursAgainst = (base) => withoutHqRegistrations(ours, base, hqRoot, localRegistrations);
4323
4563
  // Relocate genuine user drift into settings.local, and apply user array
4324
4564
  // removals to the release baseline.
4325
4565
  let drift;
@@ -4327,30 +4567,84 @@ export function reconcileClaudeSettings(ctx, preRescueSettingsJson, out, err) {
4327
4567
  // realBase = settings.json at the last-sync floor (only trustworthy in
4328
4568
  // history_floor mode). Removals require it; additions fall back to theirs.
4329
4569
  let realBase;
4570
+ let removalBase;
4330
4571
  if (baselineMode === "history_floor" && historyFloor) {
4331
- const show = run("git", ["show", `${historyFloor}:.claude/settings.json`], {
4332
- cwd: srcDir,
4333
- env,
4334
- });
4335
- if (show.status === 0)
4336
- realBase = jsonParseOrNull(show.stdout);
4572
+ const settingsAt = (rev) => {
4573
+ const show = run("git", ["show", `${rev}:.claude/settings.json`], {
4574
+ cwd: srcDir,
4575
+ env,
4576
+ });
4577
+ return show.status === 0 ? jsonParseOrNull(show.stdout) : undefined;
4578
+ };
4579
+ const revParse = (rev) => {
4580
+ const r = run("git", ["rev-parse", "--verify", "--quiet", `${rev}^{commit}`], {
4581
+ cwd: srcDir,
4582
+ env,
4583
+ });
4584
+ return r.status === 0 ? r.stdout.trim() : "";
4585
+ };
4586
+ realBase = settingsAt(historyFloor);
4587
+ removalBase = realBase;
4588
+ const floorCommit = revParse(historyFloor);
4589
+ if (isPlainObject(realBase) && floorCommit !== "" && floorCommit === revParse("HEAD")) {
4590
+ // DEV-6811: the floor IS the release being applied, so its settings.json
4591
+ // is the release file itself and every release entry missing locally
4592
+ // (e.g. a hook a recent release added that never got wired in) would
4593
+ // look like a user removal. Walk back through older versions of
4594
+ // settings.json while each still holds every release array entry the
4595
+ // local file has: the local file was laid from such a version or an
4596
+ // older one, so entries added after it were never there to remove.
4597
+ // Removals are then detected against the oldest such version. When the
4598
+ // previous version already lacks an entry the local file has, the base
4599
+ // stays the release file (a repeat run at the same release).
4600
+ const changes = run("git", ["log", "-n", "50", "--format=%H", "HEAD", "--", ".claude/settings.json"], { cwd: srcDir, env });
4601
+ const changeShas = changes.status === 0 ? changes.stdout.split("\n").map((s) => s.trim()).filter(Boolean) : [];
4602
+ let readFailed = changes.status !== 0;
4603
+ for (const sha of changeShas) {
4604
+ const older = settingsAt(`${sha}^`);
4605
+ if (!isPlainObject(older)) {
4606
+ // The tree is local in a blob:none clone, so a path that exists but
4607
+ // whose content could not be read (failed blob fetch) or parsed is
4608
+ // a read failure. A path that does not exist ends the walk normally.
4609
+ const exists = run("git", ["rev-parse", "--verify", "--quiet", `${sha}^:.claude/settings.json`], {
4610
+ cwd: srcDir,
4611
+ env,
4612
+ });
4613
+ if (exists.status === 0)
4614
+ readFailed = true;
4615
+ break;
4616
+ }
4617
+ if (!holdsSharedArrayEntries(older, oursAgainst(realBase), realBase))
4618
+ break;
4619
+ removalBase = older;
4620
+ }
4621
+ if (readFailed) {
4622
+ // Fall back to the floor file, as before this fix. The drift may stay
4623
+ // unfixed this run, but a user's deliberate removals are never undone
4624
+ // (undoing them would be permanent: the next run sees them as kept).
4625
+ removalBase = realBase;
4626
+ err(" WARN: could not read an older release version of .claude/settings.json; kept the previous behavior\n");
4627
+ }
4628
+ }
4337
4629
  }
4338
- // Removals: only with a REAL floor base (never theirs — release-only entries
4339
- // would look like removals).
4340
- if (isPlainObject(realBase)) {
4341
- applyArrayRemovals(theirs, ours, realBase);
4630
+ // Removals: only with a REAL older-release base (never theirs — release-only
4631
+ // entries would look like removals).
4632
+ if (isPlainObject(removalBase)) {
4633
+ applyArrayRemovals(theirs, oursAgainst(removalBase), removalBase);
4342
4634
  }
4343
4635
  // Additions drift: base = realBase when available, else theirs (conservative
4344
4636
  // head_compare fallback — never loses a customization). See design note.
4345
4637
  const additionsBase = isPlainObject(realBase)
4346
4638
  ? realBase
4347
4639
  : theirs;
4348
- drift = settingsDrift(ours, additionsBase);
4640
+ drift = settingsDrift(oursAgainst(additionsBase), additionsBase);
4349
4641
  }
4642
+ const placedRegistrations = placeHqRegistrations(theirs, hqRegistrations);
4643
+ const stripLocalRegistrations = new Set([...placedRegistrations].filter((event) => localRegistrations.has(event)));
4350
4644
  let driftKeys = 0;
4351
4645
  let relocationFailed = false;
4352
4646
  const hasDrift = isPlainObject(drift) && Object.keys(drift).length > 0;
4353
- if (hasDrift || writePathLocally) {
4647
+ if (hasDrift || writePathLocally || stripLocalRegistrations.size > 0) {
4354
4648
  let existingLocalRaw = null;
4355
4649
  let existingLocalReadable = true;
4356
4650
  if (isFileFollow(localPath)) {
@@ -4385,6 +4679,7 @@ export function reconcileClaudeSettings(ctx, preRescueSettingsJson, out, err) {
4385
4679
  deepMergeSettings(localObj, drift);
4386
4680
  driftKeys = Object.keys(drift).length;
4387
4681
  }
4682
+ removeHqRegistrations(localObj, stripLocalRegistrations, hqRoot);
4388
4683
  try {
4389
4684
  fs.mkdirSync(path.dirname(localPath), { recursive: true });
4390
4685
  writeSettingsAtomically(localPath, JSON.stringify(localObj, null, 2) + "\n");
@@ -4680,8 +4975,10 @@ function classifyOne(ctx, filesystemRel) {
4680
4975
  }
4681
4976
  return { kind: "skip", rel };
4682
4977
  }
4683
- // Is path in upstream HEAD?
4684
- const inHead = existsFollow(srcPath) ? 1 : 0;
4978
+ // Is path in upstream HEAD? A test or build file of the release counts as
4979
+ // absent: the release tree holds it and the install does not receive it.
4980
+ const installExcluded = isInstallExcluded(rel);
4981
+ const inHead = !installExcluded && existsFollow(srcPath) ? 1 : 0;
4685
4982
  // Is path in last-sync floor? Read the batched precompute (floorShas); fall
4686
4983
  // back to a per-file probe for any rel not represented there. A non-null
4687
4984
  // entry both proves presence (inFloor=1) and carries the baseline blob SHA,
@@ -4707,6 +5004,26 @@ function classifyOne(ctx, filesystemRel) {
4707
5004
  if (inHead === 0 && inFloor === 0) {
4708
5005
  return { kind: "user-only", rel };
4709
5006
  }
5007
+ // A release test file the previous release installed. Remove it only when
5008
+ // it is byte-identical to that released copy and no folder on its path is a
5009
+ // link. Anything else is kept in place and reported. Without a
5010
+ // floor (head_compare) inFloor is 0 and the file was left as user-only above.
5011
+ if (installExcluded) {
5012
+ if (!installPathIsInsideRoot(ctx.hqRoot, rel)) {
5013
+ return { kind: "install-excluded-kept", rel, reason: "linked-folder" };
5014
+ }
5015
+ const localSha = ctx.localShas?.get(rel) ??
5016
+ run("git", ["hash-object", localPath], { env: ctx.env }).stdout.trim();
5017
+ const floorSha = baselineSha ??
5018
+ run("git", ["rev-parse", `${ctx.historyFloor}:${rel}`], {
5019
+ cwd: ctx.srcDir,
5020
+ env: ctx.env,
5021
+ }).stdout.trim();
5022
+ if (!localSha || !floorSha || localSha !== floorSha) {
5023
+ return { kind: "install-excluded-kept", rel, reason: "edited" };
5024
+ }
5025
+ return { kind: "unchanged-delete", rel };
5026
+ }
4710
5027
  // Path is/was in upstream. Determine if user edited it.
4711
5028
  let userEdited = 0;
4712
5029
  // Set only by the floor comparison below — the one arm that proves the local
@@ -4833,6 +5150,9 @@ function renderDryRunDecision(ctx, decision) {
4833
5150
  ctx.out(` unchanged (delete; absent upstream): ${decision.rel}\n`);
4834
5151
  }
4835
5152
  break;
5153
+ case "install-excluded-kept":
5154
+ ctx.out(` ${installExcludedKeptLine(decision)}\n`);
5155
+ break;
4836
5156
  case "wholesale-replace-template":
4837
5157
  ctx.out(" wholesale-replace: companies/_template (template carve-out)\n");
4838
5158
  break;
@@ -4975,6 +5295,13 @@ function buildRescueActions(ctx) {
4975
5295
  });
4976
5296
  }
4977
5297
  break;
5298
+ case "install-excluded-kept":
5299
+ // Nothing moves or is deleted, and the overlay never writes here.
5300
+ add(`keep release test file: ${decision.rel}`, [], () => {
5301
+ ctx.out(` ${installExcludedKeptLine(decision)}\n`);
5302
+ ctx.appendLog(`kept-release-test-file\t${decision.rel}\t(${decision.reason === "edited" ? "differs from the released copy" : "a folder on its path is a link"}; no longer installed, left in place)\n`);
5303
+ });
5304
+ break;
4978
5305
  case "wholesale-replace-template":
4979
5306
  add("wholesale-replace: companies/_template", [decision.rel], () => fs.rmSync(path.join(ctx.hqRoot, "companies", "_template"), {
4980
5307
  recursive: true,
@@ -4986,8 +5313,16 @@ function buildRescueActions(ctx) {
4986
5313
  return actions;
4987
5314
  }
4988
5315
  function unchangedDeletePathExistsUpstream(ctx, rel) {
5316
+ // The release clone still holds its test files; the install does not get them.
5317
+ if (isInstallExcluded(normalizeRescueRelativePath(rel, ctx.pathSep)))
5318
+ return false;
4989
5319
  return lexists(path.join(ctx.srcDir, rel));
4990
5320
  }
5321
+ export function installExcludedKeptLine(decision) {
5322
+ return decision.reason === "edited"
5323
+ ? `kept (release test file you changed; HQ no longer installs it, delete it by hand): ${decision.rel}`
5324
+ : `kept (release test file reached through a linked folder; rescue does not delete through a link): ${decision.rel}`;
5325
+ }
4991
5326
  /** Make rsync's size+mtime quick check notice changed bytes in the same second. */
4992
5327
  function ensureRsyncDetectsChangedFile(localPath, upstreamPath) {
4993
5328
  const local = lstatOrNull(localPath);
@@ -5028,7 +5363,7 @@ function precomputeGitMaps(ctx, wipeToplevel) {
5028
5363
  const rels = lst.isFile()
5029
5364
  ? [rootRel]
5030
5365
  : lst.isDirectory()
5031
- ? findFilesAndSymlinks(rootAbs, ctx.hqRoot)
5366
+ ? findFilesAndSymlinks(rootAbs, ctx.hqRoot, ctx.skipDirs)
5032
5367
  : [];
5033
5368
  for (const filesystemRel of rels) {
5034
5369
  // A path containing a newline can't survive line-delimited batch stdin;
@@ -5051,27 +5386,26 @@ function precomputeGitMaps(ctx, wipeToplevel) {
5051
5386
  ctx.localShas = new Map();
5052
5387
  return;
5053
5388
  }
5054
- // Pass 1: floor existence + blob SHA for every rel, in chunked batches.
5055
- // `cat-file --batch-check` prints "<sha> <type> <size>" for a present object
5056
- // or "<input> missing" otherwise, one line per input in order. This
5057
- // replaces BOTH the per-file `cat-file -e` (existence) and `rev-parse`
5058
- // (sha). It reads only the git object DB — never local file contents — so it
5059
- // stays cheap even on a 100k-file wipe set. A batch failure aborts the
5060
- // rescue before anything is touched: falling back to per-file spawns across
5061
- // a wipe set this size would mean tens of thousands of git processes and a
5062
- // machine-wide slowdown for the better part of an hour.
5063
5389
  const floorShas = new Map();
5064
5390
  if (allRels.length > 0) {
5065
- const lines = runGitBatchOrAbort(["cat-file", "--batch-check"], allRels.map((rel) => `${ctx.historyFloor}:${rel}`), { cwd: ctx.srcDir, env: ctx.env });
5066
- for (let i = 0; i < allRels.length; i++) {
5067
- const line = lines[i];
5068
- if (line === "" || line.endsWith(" missing")) {
5069
- floorShas.set(allRels[i], null);
5070
- }
5071
- else {
5072
- const sha = line.split(" ")[0];
5073
- floorShas.set(allRels[i], sha || null);
5074
- }
5391
+ let tree;
5392
+ try {
5393
+ tree = readTreeObjectShas(ctx.historyFloor, {
5394
+ cwd: ctx.srcDir,
5395
+ env: ctx.env,
5396
+ });
5397
+ }
5398
+ catch (e) {
5399
+ if (!(e instanceof GitBatchError))
5400
+ throw e;
5401
+ process.stderr.write(`\nERROR: listing the last-synced release failed while classifying ${allRels.length} paths; aborting before any file is touched.\n${e.message}\n`);
5402
+ throw new ExitError(1);
5403
+ }
5404
+ for (const [rel, sha] of tree)
5405
+ floorShas.set(rel, sha);
5406
+ for (const rel of allRels) {
5407
+ if (!floorShas.has(rel))
5408
+ floorShas.set(rel, null);
5075
5409
  }
5076
5410
  }
5077
5411
  ctx.floorShas = floorShas;
@@ -5128,16 +5462,31 @@ export function hashLocalFilesInChunks(absPaths, env, warn, chunkSize = GIT_BATC
5128
5462
  }
5129
5463
  return out;
5130
5464
  }
5131
- function runGitBatchOrAbort(args, inputs, opts) {
5132
- try {
5133
- return runGitBatch(args, inputs, opts);
5465
+ /**
5466
+ * Object SHA for every blob, symlink and tree path in `ref`, keyed by its
5467
+ * repo-relative path. Reads tree objects only, so a `--filter=blob:none`
5468
+ * clone answers it from its local object store with no promisor fetch.
5469
+ */
5470
+ export function readTreeObjectShas(ref, opts) {
5471
+ const args = ["ls-tree", "-r", "-t", "-z", "--full-tree", ref];
5472
+ const res = run("git", args, {
5473
+ cwd: opts.cwd,
5474
+ env: opts.env,
5475
+ maxBuffer: GIT_BATCH_MAX_BUFFER,
5476
+ });
5477
+ if (res.status !== 0 || res.error || res.signal) {
5478
+ throw new GitBatchError(args, res, 0, 1);
5134
5479
  }
5135
- catch (e) {
5136
- if (!(e instanceof GitBatchError))
5137
- throw e;
5138
- process.stderr.write(`\nERROR: batched git lookup failed while classifying ${inputs.length} paths; aborting before any file is touched.\n${e.message}\n`);
5139
- throw new ExitError(1);
5480
+ const shas = new Map();
5481
+ for (const entry of res.stdout.split("\0")) {
5482
+ const tab = entry.indexOf("\t");
5483
+ if (tab < 0)
5484
+ continue;
5485
+ const [, type, sha] = entry.slice(0, tab).split(" ");
5486
+ if (type === "blob" || type === "tree")
5487
+ shas.set(entry.slice(tab + 1), sha);
5140
5488
  }
5489
+ return shas;
5141
5490
  }
5142
5491
  function walkAndProcess(ctx, rootRel) {
5143
5492
  const rootAbs = path.join(ctx.hqRoot, rootRel);
@@ -5188,7 +5537,7 @@ function walkAndProcess(ctx, rootRel) {
5188
5537
  return;
5189
5538
  }
5190
5539
  // Top-level directory: recursive walk, pruning canonical transient state.
5191
- for (const rel of findFilesAndSymlinks(rootAbs, ctx.hqRoot)) {
5540
+ for (const rel of findFilesAndSymlinks(rootAbs, ctx.hqRoot, ctx.skipDirs)) {
5192
5541
  recordDecision(ctx, classifyOne(ctx, rel));
5193
5542
  }
5194
5543
  }
@@ -5197,7 +5546,7 @@ function walkAndProcess(ctx, rootRel) {
5197
5546
  * transient directories and never descending into directory symlinks. Order is
5198
5547
  * deterministic so classification and apply plans remain reproducible.
5199
5548
  */
5200
- function findFilesAndSymlinks(rootAbs, hqRoot) {
5549
+ function findFilesAndSymlinks(rootAbs, hqRoot, skipDirs = EMPTY_SKIP_DIRS) {
5201
5550
  const found = [];
5202
5551
  const walk = (dir) => {
5203
5552
  let entries;
@@ -5226,6 +5575,8 @@ function findFilesAndSymlinks(rootAbs, hqRoot) {
5226
5575
  const rel = abs.slice(hqRoot.length + 1);
5227
5576
  if (isRescueTransientDirectory(rel))
5228
5577
  continue;
5578
+ if (skipDirs.size > 0 && skipDirs.has(rel.replace(/\\/g, "/")))
5579
+ continue;
5229
5580
  walk(abs);
5230
5581
  continue;
5231
5582
  }
@@ -5237,6 +5588,75 @@ function findFilesAndSymlinks(rootAbs, hqRoot) {
5237
5588
  walk(rootAbs);
5238
5589
  return found;
5239
5590
  }
5591
+ const EMPTY_SKIP_DIRS = new Set();
5592
+ const SKILLS_LOCK_FILE = "skills-lock.json";
5593
+ const SKILLS_DIR = ".claude/skills";
5594
+ /**
5595
+ * Skill packs the operator installed from a third-party source are recorded
5596
+ * in `<hqRoot>/skills-lock.json` and copied under `.claude/skills/<name>`.
5597
+ * The release never ships them, so every file inside classifies as user-only
5598
+ * and is left in place; walking them only costs time (one Shopify toolkit is
5599
+ * 27k files). Return the `.claude/skills/<name>` directories that are safe to
5600
+ * leave out of the walk: listed in the lock file, a real directory locally,
5601
+ * and absent from both the release HEAD and the baseline floor, so no file
5602
+ * inside can be release content.
5603
+ */
5604
+ export function installedSkillPackDirs(hqRoot, releaseSkillNames) {
5605
+ let lock;
5606
+ try {
5607
+ lock = JSON.parse(fs.readFileSync(path.join(hqRoot, SKILLS_LOCK_FILE), "utf-8"));
5608
+ }
5609
+ catch {
5610
+ return [];
5611
+ }
5612
+ const skills = lock && typeof lock === "object" ? lock.skills : undefined;
5613
+ if (!skills || typeof skills !== "object" || Array.isArray(skills))
5614
+ return [];
5615
+ const dirs = [];
5616
+ for (const name of Object.keys(skills).sort()) {
5617
+ if (name === "" ||
5618
+ name === "." ||
5619
+ name === ".." ||
5620
+ name.includes("/") ||
5621
+ name.includes("\\") ||
5622
+ name.includes("\n")) {
5623
+ continue;
5624
+ }
5625
+ if (releaseSkillNames.has(name))
5626
+ continue;
5627
+ const st = lstatOrNull(path.join(hqRoot, SKILLS_DIR, name));
5628
+ if (!st || !st.isDirectory())
5629
+ continue;
5630
+ dirs.push(`${SKILLS_DIR}/${name}`);
5631
+ }
5632
+ return dirs;
5633
+ }
5634
+ /** Skill directory names present in the release HEAD and, when there is one, the baseline floor. */
5635
+ function releaseSkillNames(ctx) {
5636
+ const names = new Set();
5637
+ let headEntries = [];
5638
+ try {
5639
+ headEntries = fs.readdirSync(path.join(ctx.srcDir, SKILLS_DIR));
5640
+ }
5641
+ catch {
5642
+ headEntries = [];
5643
+ }
5644
+ for (const name of headEntries)
5645
+ names.add(name);
5646
+ if (ctx.baselineMode === "history_floor") {
5647
+ const res = run("git", ["ls-tree", "--name-only", `${ctx.historyFloor}:${SKILLS_DIR}`], {
5648
+ cwd: ctx.srcDir,
5649
+ env: ctx.env,
5650
+ });
5651
+ if (res.status === 0) {
5652
+ for (const line of res.stdout.split("\n")) {
5653
+ if (line !== "")
5654
+ names.add(line);
5655
+ }
5656
+ }
5657
+ }
5658
+ return names;
5659
+ }
5240
5660
  // --- restore file mtimes from git commit history ---
5241
5661
  function restoreMtimesFromGit(srcDir, env, out) {
5242
5662
  // Deepen a shallow clone so per-file commit times are real.
@@ -6474,13 +6894,18 @@ function isSkippedSnapshotPath(ctx, rel) {
6474
6894
  * backslash escapes only in a pattern that holds a wildcard (`*`, `?`, `[`,
6475
6895
  * or the `/***` suffix of a recursive entry), so escape only then; a plain
6476
6896
  * name with a backslash is compared literally and must stay as it is.
6897
+ * A backslash inside an escaped entry is written as a bracket class holding
6898
+ * one escaped backslash, because openrsync ignores a doubled backslash there.
6477
6899
  */
6478
6900
  export function appendLiteralRsyncExclude(excludeList, rel, recursive = false) {
6479
6901
  let pattern = rel;
6480
6902
  if (recursive || /[*?[]/.test(pattern)) {
6481
- pattern = pattern
6482
- .replace(/\\/g, "\\\\")
6483
- .replace(/([*?[])/g, "\\$1");
6903
+ // A backslash becomes a bracket class holding one escaped backslash, not a
6904
+ // doubled backslash. GNU rsync reads both, but openrsync (the /usr/bin/rsync
6905
+ // on macOS) does not honour the doubled form and would leave the path
6906
+ // unprotected. The bracket form matches a literal backslash in GNU rsync,
6907
+ // openrsync, and the built-in copy.
6908
+ pattern = pattern.replace(/[\\*?[]/g, (ch) => ch === "\\" ? "[\\\\]" : `\\${ch}`);
6484
6909
  }
6485
6910
  fs.appendFileSync(excludeList, `/${pattern}${recursive ? "/***" : ""}\0`);
6486
6911
  }