@indigoai-us/hq-cloud 5.48.3 → 6.0.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 (56) hide show
  1. package/dist/cli/index.d.ts +2 -2
  2. package/dist/cli/index.d.ts.map +1 -1
  3. package/dist/cli/index.js +2 -2
  4. package/dist/cli/index.js.map +1 -1
  5. package/dist/cli/reindex.d.ts +23 -0
  6. package/dist/cli/reindex.d.ts.map +1 -0
  7. package/dist/cli/reindex.js +45 -0
  8. package/dist/cli/reindex.js.map +1 -0
  9. package/dist/cli/reindex.test.d.ts +11 -0
  10. package/dist/cli/reindex.test.d.ts.map +1 -0
  11. package/dist/cli/{master-sync.test.js → reindex.test.js} +15 -15
  12. package/dist/cli/reindex.test.js.map +1 -0
  13. package/dist/cli/rescue-drift-reconcile.test.d.ts +2 -0
  14. package/dist/cli/rescue-drift-reconcile.test.d.ts.map +1 -0
  15. package/dist/cli/rescue-drift-reconcile.test.js +139 -0
  16. package/dist/cli/rescue-drift-reconcile.test.js.map +1 -0
  17. package/dist/cli/rescue.d.ts.map +1 -1
  18. package/dist/cli/rescue.js +16 -1
  19. package/dist/cli/rescue.js.map +1 -1
  20. package/dist/cli/rescue.reindex.test.d.ts +2 -0
  21. package/dist/cli/rescue.reindex.test.d.ts.map +1 -0
  22. package/dist/cli/rescue.reindex.test.js +41 -0
  23. package/dist/cli/rescue.reindex.test.js.map +1 -0
  24. package/dist/cli/share.test.js +2 -2
  25. package/dist/cli/share.test.js.map +1 -1
  26. package/dist/cli/sync.d.ts +9 -0
  27. package/dist/cli/sync.d.ts.map +1 -1
  28. package/dist/cli/sync.js +17 -0
  29. package/dist/cli/sync.js.map +1 -1
  30. package/dist/cli/sync.test.js +20 -0
  31. package/dist/cli/sync.test.js.map +1 -1
  32. package/dist/index.d.ts +2 -2
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +2 -2
  35. package/dist/index.js.map +1 -1
  36. package/package.json +1 -1
  37. package/scripts/{master-sync.sh → reindex.sh} +10 -10
  38. package/scripts/replace-rescue.sh +48 -19
  39. package/src/cli/index.ts +3 -3
  40. package/src/cli/{master-sync.test.ts → reindex.test.ts} +14 -14
  41. package/src/cli/reindex.ts +57 -0
  42. package/src/cli/rescue-drift-reconcile.test.ts +158 -0
  43. package/src/cli/rescue.reindex.test.ts +46 -0
  44. package/src/cli/rescue.ts +15 -1
  45. package/src/cli/share.test.ts +2 -2
  46. package/src/cli/sync.test.ts +23 -0
  47. package/src/cli/sync.ts +27 -0
  48. package/src/index.ts +3 -3
  49. package/dist/cli/master-sync.d.ts +0 -22
  50. package/dist/cli/master-sync.d.ts.map +0 -1
  51. package/dist/cli/master-sync.js +0 -44
  52. package/dist/cli/master-sync.js.map +0 -1
  53. package/dist/cli/master-sync.test.d.ts +0 -11
  54. package/dist/cli/master-sync.test.d.ts.map +0 -1
  55. package/dist/cli/master-sync.test.js.map +0 -1
  56. package/src/cli/master-sync.ts +0 -56
@@ -1,16 +1,16 @@
1
1
  #!/bin/bash
2
- # master-sync.sh — surfaces namespace skills as Claude Code skills under
2
+ # reindex.sh — surfaces namespace skills as Claude Code skills under
3
3
  # .claude/skills/<ns>:<skill>/ with every file in the source skill folder
4
4
  # mirrored as a symlink. Also mirrors personal/{knowledge,policies,workers,
5
5
  # settings}/* into core/<type>/<name>.
6
6
  #
7
7
  # This script ships inside the @indigoai-us/hq-cloud package and is invoked via
8
- # `hq master-sync` (which passes the HQ root as $1). It is idempotent and cheap
8
+ # `hq reindex` (which passes the HQ root as $1). It is idempotent and cheap
9
9
  # to re-run, so it doesn't gate on whether personal/ was actually touched. Real
10
10
  # files/dirs already at the link path are left untouched.
11
11
  #
12
12
  # REPO_ROOT resolution (in priority order):
13
- # 1. $1 — passed by `hq master-sync` (the HQ root)
13
+ # 1. $1 — passed by `hq reindex` (the HQ root)
14
14
  # 2. $HQ_REPO_ROOT — env override
15
15
  # 3. $PWD — fallback when invoked directly
16
16
  #
@@ -40,7 +40,7 @@ set -uo pipefail
40
40
 
41
41
  REPO_ROOT="${1:-${HQ_REPO_ROOT:-$PWD}}"
42
42
  if [ ! -d "$REPO_ROOT" ]; then
43
- echo "master-sync: REPO_ROOT '$REPO_ROOT' is not a directory" >&2
43
+ echo "reindex: REPO_ROOT '$REPO_ROOT' is not a directory" >&2
44
44
  exit 1
45
45
  fi
46
46
  REPO_ROOT="$(cd "$REPO_ROOT" && pwd)"
@@ -128,7 +128,7 @@ while [ "$i" -lt "${#namespaces[@]}" ]; do
128
128
  fi
129
129
  done
130
130
  if [ "$already" -eq 1 ]; then
131
- echo "master-sync: namespace '$ns' already claimed by an earlier source; skipping $src_rel" >&2
131
+ echo "reindex: namespace '$ns' already claimed by an earlier source; skipping $src_rel" >&2
132
132
  continue
133
133
  fi
134
134
  seen+=("$ns")
@@ -147,7 +147,7 @@ while [ "$i" -lt "${#namespaces[@]}" ]; do
147
147
 
148
148
  # If something non-directory occupies the slot, bail.
149
149
  if [ -e "$wrapper" ] && [ ! -L "$wrapper" ] && [ ! -d "$wrapper" ]; then
150
- echo "master-sync: $wrapper exists and is not a directory; skipping" >&2
150
+ echo "reindex: $wrapper exists and is not a directory; skipping" >&2
151
151
  continue
152
152
  fi
153
153
  # If it's a symlink (e.g. legacy directory-symlink form from earlier
@@ -171,10 +171,10 @@ while [ "$i" -lt "${#namespaces[@]}" ]; do
171
171
  if [ "$current" = "$relative_target" ]; then
172
172
  continue
173
173
  fi
174
- echo "master-sync: .claude/skills/$wrapper_name/$entry already points to '$current' (expected '$relative_target'); leaving alone" >&2
174
+ echo "reindex: .claude/skills/$wrapper_name/$entry already points to '$current' (expected '$relative_target'); leaving alone" >&2
175
175
  continue
176
176
  elif [ -e "$link_path" ]; then
177
- echo "master-sync: $link_path already exists and is not a symlink; skipping" >&2
177
+ echo "reindex: $link_path already exists and is not a symlink; skipping" >&2
178
178
  continue
179
179
  fi
180
180
 
@@ -298,10 +298,10 @@ for type in knowledge policies workers settings; do
298
298
  if [ "$current" = "$relative_target" ]; then
299
299
  continue
300
300
  fi
301
- echo "master-sync: core/$type/$entry already points to '$current' (expected '$relative_target'); leaving alone" >&2
301
+ echo "reindex: core/$type/$entry already points to '$current' (expected '$relative_target'); leaving alone" >&2
302
302
  continue
303
303
  elif [ -e "$link_path" ]; then
304
- echo "master-sync: core/$type/$entry already exists and is not a symlink; skipping" >&2
304
+ echo "reindex: core/$type/$entry already exists and is not a symlink; skipping" >&2
305
305
  continue
306
306
  fi
307
307
 
@@ -77,7 +77,7 @@
77
77
  # not a customization — saving it under personal/ or .hq-conflicts/ just
78
78
  # accumulates noise.
79
79
  #
80
- # Symlinks generated by `master-sync.sh` (targets resolving into
80
+ # Symlinks generated by `reindex.sh` (targets resolving into
81
81
  # `personal/`) are DELETED during the walk rather than preserved. They
82
82
  # rebuild deterministically on the next Stop-hook pass — keeping the old
83
83
  # link risks shadowing the upstream file the overlay writes at the same
@@ -245,7 +245,7 @@ BACKUP_DIR="" # resolved at snapshot time (BACKUP_ROOT/pre-update-<RUN_TS>)
245
245
  # personal + installed-pack workers. Its content is a function of the
246
246
  # user's install state, not the upstream tree, so an overlay that
247
247
  # replaces it produces a registry that doesn't match what's on disk
248
- # (and `master-sync` regenerates it on the next Stop hook anyway).
248
+ # (and `reindex` regenerates it on the next Stop hook anyway).
249
249
  # Shuttling preserves the up-to-date local version across the rescue.
250
250
  # Why .claude/settings.local.json: per-user local settings (denied paths,
251
251
  # env vars, allow-listed tool patterns) authored by the user via the CLI
@@ -436,7 +436,7 @@ if [ "${#PRESERVE_SUBPATHS[@]}" -ne 0 ]; then
436
436
  fi
437
437
  done
438
438
  fi
439
- echo "==> Drift policy: rescue user-edited files to personal/; route .agents|.codex|.obsidian|MIGRATION.md user-edits to .hq-conflicts/rescue-$RUN_TS/; silently overwrite AGENTS.md|USER-GUIDE.md|core/policies/_digest.md (regenerable); leave user-only files untouched; drop master-sync symlinks (regenerated by master-sync.sh)"
439
+ echo "==> Drift policy: rescue user-edited files to personal/; route .agents|.codex|.obsidian|MIGRATION.md user-edits to .hq-conflicts/rescue-$RUN_TS/; silently overwrite AGENTS.md|USER-GUIDE.md|core/policies/_digest.md (regenerable); leave user-only files untouched; drop reindex symlinks (regenerated by reindex.sh)"
440
440
  if [ "$CLOUD_UPDATE" = "1" ]; then
441
441
  echo "==> Cloud-update mode: ON (recognize \`hq-symlink:<target>\` flat files as upstream-symlink-equivalent — reconciled as UNCHANGED)"
442
442
  fi
@@ -459,7 +459,7 @@ if [ "$ASSUME_YES" != "1" ] && [ "$DRY_RUN" != "1" ]; then
459
459
  if [ "$CLOUD_UPDATE" = "1" ]; then
460
460
  _cloud_line="\n * reconcile \`hq-symlink:<target>\` flat files against upstream symlinks (cloud-update mode),"
461
461
  fi
462
- printf "\nThis will:\n%s\n * rescue user-edited files (vs the last sync) into personal/,\n * route user-edited .agents/.codex/.obsidian/MIGRATION.md into .hq-conflicts/rescue-%s/ for review,\n * silently overwrite AGENTS.md / USER-GUIDE.md / core/policies/_digest.md (regenerable from upstream or master-sync — no copy preserved),%b\n * drop master-sync-generated symlinks (regenerated by master-sync.sh on next Stop hook),\n * leave user-only files (not in upstream) untouched,\n * delete upstream files unchanged since last sync, then unpack %s@%s on top.\nType 'yes' to proceed: " "$_backup_line" "$RUN_TS" "$_cloud_line" "$SOURCE_REPO" "$REF"
462
+ printf "\nThis will:\n%s\n * rescue user-edited files (vs the last sync) into personal/,\n * route user-edited .agents/.codex/.obsidian/MIGRATION.md into .hq-conflicts/rescue-%s/ for review,\n * silently overwrite AGENTS.md / USER-GUIDE.md / core/policies/_digest.md (regenerable from upstream or reindex — no copy preserved),%b\n * drop reindex-generated symlinks (regenerated by reindex.sh on next Stop hook),\n * leave user-only files (not in upstream) untouched,\n * delete upstream files unchanged since last sync, then unpack %s@%s on top.\nType 'yes' to proceed: " "$_backup_line" "$RUN_TS" "$_cloud_line" "$SOURCE_REPO" "$REF"
463
463
  read -r confirm
464
464
  [ "$confirm" = "yes" ] || { echo "Aborted."; exit 4; }
465
465
  fi
@@ -617,6 +617,7 @@ COUNT_USER_OVERWRITE=0
617
617
  COUNT_CLAUDE_DIFF_APPEND=0
618
618
  COUNT_SYMLINK_DROPPED=0
619
619
  COUNT_CLOUD_SYMLINK_RECONCILED=0
620
+ COUNT_DRIFT_RECONCILED=0
620
621
 
621
622
  # True if $rel is under any always-preserved subpath. Drift detection
622
623
  # skips these — they're shuttled out, the wipe+overlay runs, then they're
@@ -766,7 +767,7 @@ rescue_one() {
766
767
  #
767
768
  # Routing them to .hq-conflicts/rescue-<RUN_TS>/<rel> keeps them quarantined
768
769
  # under a timestamped bucket the user can inspect and discard, without
769
- # polluting the personal/ overlay tree (where master-sync would then try
770
+ # polluting the personal/ overlay tree (where reindex would then try
770
771
  # to re-mirror them into core/).
771
772
  is_conflict_class() {
772
773
  local rel="$1"
@@ -813,7 +814,7 @@ conflict_one() {
813
814
  # core/docs/hq/USER-GUIDE.md — current release doc; always re-shipped.
814
815
  # core/policies/_digest.md — generated by `core/scripts/build-policy-digest.sh`
815
816
  # from the union of policy files; rebuilt on
816
- # the next Stop-hook master-sync pass.
817
+ # the next Stop-hook reindex pass.
817
818
  # Same rationale as core/workers/registry.yaml,
818
819
  # minus the carve-out (digest is small + cheap
819
820
  # to regenerate, so just let the overlay win).
@@ -893,11 +894,11 @@ is_cloud_flattened_symlink_equiv() {
893
894
  [ "$local_target" = "$upstream_target" ]
894
895
  }
895
896
 
896
- # True when $local_path is a symlink generated by master-sync.sh — those
897
+ # True when $local_path is a symlink generated by reindex.sh — those
897
898
  # point into personal/ (e.g. `core/<type>/<entry>` -> `../../personal/...`,
898
899
  # `.claude/skills/<ns>:<entry>` -> `../../../personal/skills/<entry>/...`,
899
900
  # `.claude/commands/<ns>/<entry>.md` -> `../../../personal/skills/<entry>/SKILL.md`).
900
- # They are deterministically rebuilt on the next master-sync.sh run, so the
901
+ # They are deterministically rebuilt on the next reindex.sh run, so the
901
902
  # safe move during rescue is to delete rather than preserve — a leftover
902
903
  # symlink can shadow an overlaid-from-upstream real file at the same path.
903
904
  is_master_sync_symlink() {
@@ -957,20 +958,20 @@ process_one() {
957
958
  ;;
958
959
  esac
959
960
 
960
- # Symlinks (mid-tree). master-sync.sh deterministically rebuilds the
961
+ # Symlinks (mid-tree). reindex.sh deterministically rebuilds the
961
962
  # personal/-targeted ones on its next Stop-hook pass, so the safe move
962
963
  # here is to delete them — a leftover symlink at a path the overlay
963
964
  # also writes to creates an ambiguous "is this the symlink or the
964
- # overlaid file?" state on disk. Non-master-sync symlinks (user-created,
965
+ # overlaid file?" state on disk. Non-reindex symlinks (user-created,
965
966
  # absolute targets, or targets outside personal/) are left alone.
966
967
  if [ -L "$local_path" ]; then
967
968
  if is_master_sync_symlink "$local_path"; then
968
969
  COUNT_SYMLINK_DROPPED=$((COUNT_SYMLINK_DROPPED + 1))
969
970
  if [ "$DRY_RUN" = "1" ]; then
970
- echo " drop master-sync symlink: $rel -> $(readlink "$local_path" 2>/dev/null || true)"
971
+ echo " drop reindex symlink: $rel -> $(readlink "$local_path" 2>/dev/null || true)"
971
972
  else
972
973
  rm -f "$local_path"
973
- printf 'symlink-dropped\t%s\t(master-sync regenerable)\n' "$rel" >> "$RESCUE_LOG" 2>/dev/null || true
974
+ printf 'symlink-dropped\t%s\t(reindex regenerable)\n' "$rel" >> "$RESCUE_LOG" 2>/dev/null || true
974
975
  fi
975
976
  fi
976
977
  return 0
@@ -1035,6 +1036,31 @@ process_one() {
1035
1036
  return 0
1036
1037
  fi
1037
1038
 
1039
+ # Convergence guard: in history_floor mode a file is flagged USER-EDIT when
1040
+ # its blob differs from the *old* baseline (the floor). But HQ's own Stop
1041
+ # hooks (reindex symlinking personal/->core/, autocommit, registry/
1042
+ # _digest/core.yaml regeneration) rewrite scaffold files every session, so a
1043
+ # file routinely drifts from the floor yet lands byte-for-byte identical to
1044
+ # the *new* upstream HEAD this overlay is about to write. Rescuing it into
1045
+ # personal/ then just deposits a redundant `.drift-<ts>-<pid>` copy of bytes
1046
+ # the overlay would have written anyway (this is what produced the 32-file
1047
+ # `.drift-*` litter on a live tree). If local already equals upstream HEAD
1048
+ # there is nothing to preserve, so reclassify as UNCHANGED (delete; the
1049
+ # overlay re-writes the identical bytes). Parallels the cloud-symlink
1050
+ # reconcile above and the sync-side convergence guard. Gated on in_head so an
1051
+ # upstream-removed file (in_head=0) is still rescued; a no-op in head_compare
1052
+ # mode, where `cmp` already settled user_edited against upstream HEAD.
1053
+ if [ "$user_edited" = "1" ] && [ "$in_head" = "1" ] && cmp -s "$local_path" "$src_path"; then
1054
+ COUNT_DRIFT_RECONCILED=$((COUNT_DRIFT_RECONCILED + 1))
1055
+ if [ "$DRY_RUN" = "1" ]; then
1056
+ echo " drift reconciled (identical to upstream HEAD; no rescue): $rel"
1057
+ else
1058
+ rm -f "$local_path"
1059
+ printf 'drift-reconciled\t%s\t(identical to upstream HEAD; drifted from floor only — no personal/ copy)\n' "$rel" >> "$RESCUE_LOG" 2>/dev/null || true
1060
+ fi
1061
+ return 0
1062
+ fi
1063
+
1038
1064
  if [ "$user_edited" = "1" ]; then
1039
1065
  if [ "$DRY_RUN" = "1" ]; then
1040
1066
  if [ "$rel" = ".claude/CLAUDE.md" ]; then
@@ -1097,16 +1123,16 @@ walk_and_process() {
1097
1123
  # convenience aliases the overlay overwrites cleanly (rsync -a preserves
1098
1124
  # link semantics from source). Master-sync personal-overlay symlinks at
1099
1125
  # the top level — rare but possible — are dropped here so the overlay
1100
- # can land a real file at the same path without ambiguity; master-sync
1126
+ # can land a real file at the same path without ambiguity; reindex
1101
1127
  # regenerates the link on its next Stop-hook pass.
1102
1128
  if [ -L "$root_abs" ]; then
1103
1129
  if is_master_sync_symlink "$root_abs"; then
1104
1130
  COUNT_SYMLINK_DROPPED=$((COUNT_SYMLINK_DROPPED + 1))
1105
1131
  if [ "$DRY_RUN" = "1" ]; then
1106
- echo " drop master-sync symlink: $root_rel -> $(readlink "$root_abs" 2>/dev/null || true)"
1132
+ echo " drop reindex symlink: $root_rel -> $(readlink "$root_abs" 2>/dev/null || true)"
1107
1133
  else
1108
1134
  rm -f "$root_abs"
1109
- printf 'symlink-dropped\t%s\t(master-sync regenerable)\n' "$root_rel" >> "$RESCUE_LOG" 2>/dev/null || true
1135
+ printf 'symlink-dropped\t%s\t(reindex regenerable)\n' "$root_rel" >> "$RESCUE_LOG" 2>/dev/null || true
1110
1136
  fi
1111
1137
  fi
1112
1138
  return 0
@@ -1120,7 +1146,7 @@ walk_and_process() {
1120
1146
 
1121
1147
  # Top-level directory: walk recursively, pruning node_modules + nested
1122
1148
  # .git (v0.1.103 perf + correctness guard). Symlinks are surfaced via
1123
- # `-type l` so master-sync-generated links (targets resolving into
1149
+ # `-type l` so reindex-generated links (targets resolving into
1124
1150
  # personal/) can be dropped — see process_one + is_master_sync_symlink.
1125
1151
  # Under -P (the default), find does not descend INTO directory symlinks,
1126
1152
  # which keeps the walk bounded even when those links exist.
@@ -1190,7 +1216,8 @@ if [ "$DRY_RUN" = "1" ]; then
1190
1216
  echo " user-edit (conflict quarantine): $COUNT_USER_CONFLICT files"
1191
1217
  echo " user-edit (overwrite-safe): $COUNT_USER_OVERWRITE files"
1192
1218
  echo " cloud-symlink reconciled: $COUNT_CLOUD_SYMLINK_RECONCILED files"
1193
- echo " master-sync symlinks dropped: $COUNT_SYMLINK_DROPPED entries"
1219
+ echo " drift reconciled (== upstream): $COUNT_DRIFT_RECONCILED files"
1220
+ echo " reindex symlinks dropped: $COUNT_SYMLINK_DROPPED entries"
1194
1221
  if [ "$COUNT_CLAUDE_DIFF_APPEND" -gt 0 ]; then
1195
1222
  echo " of which .claude/CLAUDE.md would diff-append to personal/CLAUDE.md"
1196
1223
  fi
@@ -1333,7 +1360,8 @@ echo " user-edits (rescued): $COUNT_USER_EDIT files"
1333
1360
  echo " user-edits (conflict quarantine): $COUNT_USER_CONFLICT files"
1334
1361
  echo " user-edits (overwrite-safe): $COUNT_USER_OVERWRITE files"
1335
1362
  echo " cloud-symlink reconciled: $COUNT_CLOUD_SYMLINK_RECONCILED files"
1336
- echo " master-sync symlinks dropped: $COUNT_SYMLINK_DROPPED entries"
1363
+ echo " drift reconciled (== upstream): $COUNT_DRIFT_RECONCILED files"
1364
+ echo " reindex symlinks dropped: $COUNT_SYMLINK_DROPPED entries"
1337
1365
  if [ "$COUNT_CLAUDE_DIFF_APPEND" -gt 0 ]; then
1338
1366
  echo " of which .claude/CLAUDE.md diff-appended to personal/CLAUDE.md"
1339
1367
  fi
@@ -1367,7 +1395,8 @@ if [ "$DO_BACKUP" = "1" ] && [ -n "$BACKUP_DIR" ] && [ -d "$BACKUP_DIR" ]; then
1367
1395
  echo " user-edit (conflict quarantine): $COUNT_USER_CONFLICT"
1368
1396
  echo " user-edit (overwrite-safe): $COUNT_USER_OVERWRITE"
1369
1397
  echo " cloud-symlink reconciled: $COUNT_CLOUD_SYMLINK_RECONCILED"
1370
- echo " master-sync symlinks dropped: $COUNT_SYMLINK_DROPPED"
1398
+ echo " drift reconciled (== upstream HEAD): $COUNT_DRIFT_RECONCILED"
1399
+ echo " reindex symlinks dropped: $COUNT_SYMLINK_DROPPED"
1371
1400
  if [ "$COUNT_USER_CONFLICT" -gt 0 ]; then
1372
1401
  echo " conflict bucket: .hq-conflicts/rescue-$RUN_TS/"
1373
1402
  fi
package/src/cli/index.ts CHANGED
@@ -25,9 +25,9 @@ export { promote } from "./promote.js";
25
25
  export type { PromoteOptions, PromoteResult } from "./promote.js";
26
26
 
27
27
  // Skill/personal-overlay mirroring + workers-registry regen (formerly the
28
- // hq-core master-sync.sh hook).
29
- export { masterSync, masterSyncScriptPath } from "./master-sync.js";
30
- export type { MasterSyncOptions, MasterSyncResult } from "./master-sync.js";
28
+ // hq-core master-sync.sh hook; `hq reindex`).
29
+ export { reindex, reindexScriptPath } from "./reindex.js";
30
+ export type { ReindexOptions, ReindexResult } from "./reindex.js";
31
31
 
32
32
  // Drift-preserving HQ-core re-sync (formerly bundled only inside the HQ Sync
33
33
  // menubar app). Now shared between the app and `hq rescue`.
@@ -1,9 +1,9 @@
1
1
  /**
2
- * Unit tests for `hq master-sync` (the formerly-bash hq-core hook, now shipped
2
+ * Unit tests for `hq reindex` (the formerly-bash hq-core hook, now shipped
3
3
  * in this package and invoked via the CLI).
4
4
  *
5
- * The logic itself lives in scripts/master-sync.sh; these tests exercise it via
6
- * the masterSync() wrapper against a temp HQ tree, asserting the observable
5
+ * The logic itself lives in scripts/reindex.sh; these tests exercise it via
6
+ * the reindex() wrapper against a temp HQ tree, asserting the observable
7
7
  * filesystem outcomes (skill wrappers, personal-overlay mirroring) rather than
8
8
  * re-deriving the bash internals.
9
9
  */
@@ -12,17 +12,17 @@ import { describe, it, expect, beforeEach, afterEach } from "vitest";
12
12
  import * as fs from "fs";
13
13
  import * as path from "path";
14
14
  import * as os from "os";
15
- import { masterSync, masterSyncScriptPath } from "./master-sync.js";
15
+ import { reindex, reindexScriptPath } from "./reindex.js";
16
16
 
17
- describe("masterSyncScriptPath", () => {
17
+ describe("reindexScriptPath", () => {
18
18
  it("resolves to the bundled script and the file exists", () => {
19
- const p = masterSyncScriptPath();
20
- expect(p.endsWith(path.join("scripts", "master-sync.sh"))).toBe(true);
19
+ const p = reindexScriptPath();
20
+ expect(p.endsWith(path.join("scripts", "reindex.sh"))).toBe(true);
21
21
  expect(fs.existsSync(p)).toBe(true);
22
22
  });
23
23
  });
24
24
 
25
- describe("masterSync", () => {
25
+ describe("reindex", () => {
26
26
  let root: string;
27
27
 
28
28
  beforeEach(() => {
@@ -44,7 +44,7 @@ describe("masterSync", () => {
44
44
  fs.writeFileSync(path.join(root, "core/skills/demo/helper.md"), "h\n");
45
45
  writeSkill("companies/acme/skills/widget");
46
46
 
47
- const { status } = masterSync({ repoRoot: root });
47
+ const { status } = reindex({ repoRoot: root });
48
48
  expect(status).toBe(0);
49
49
 
50
50
  const coreWrapper = path.join(root, ".claude/skills/core:demo");
@@ -65,7 +65,7 @@ describe("masterSync", () => {
65
65
  fs.mkdirSync(path.join(root, "personal/policies"), { recursive: true });
66
66
  fs.writeFileSync(path.join(root, "personal/policies/myrule.md"), "rule\n");
67
67
 
68
- const { status } = masterSync({ repoRoot: root });
68
+ const { status } = reindex({ repoRoot: root });
69
69
  expect(status).toBe(0);
70
70
 
71
71
  const link = path.join(root, "core/policies/myrule.md");
@@ -75,18 +75,18 @@ describe("masterSync", () => {
75
75
 
76
76
  it("prunes orphan managed wrappers when the source skill disappears", () => {
77
77
  writeSkill("core/skills/demo");
78
- masterSync({ repoRoot: root });
78
+ reindex({ repoRoot: root });
79
79
  expect(fs.existsSync(path.join(root, ".claude/skills/core:demo"))).toBe(true);
80
80
 
81
81
  fs.rmSync(path.join(root, "core/skills/demo"), { recursive: true, force: true });
82
- masterSync({ repoRoot: root });
82
+ reindex({ repoRoot: root });
83
83
  expect(fs.existsSync(path.join(root, ".claude/skills/core:demo"))).toBe(false);
84
84
  });
85
85
 
86
86
  it("is idempotent — a second run is a no-op", () => {
87
87
  writeSkill("core/skills/demo");
88
- expect(masterSync({ repoRoot: root }).status).toBe(0);
89
- expect(masterSync({ repoRoot: root }).status).toBe(0);
88
+ expect(reindex({ repoRoot: root }).status).toBe(0);
89
+ expect(reindex({ repoRoot: root }).status).toBe(0);
90
90
  expect(
91
91
  fs.readlinkSync(path.join(root, ".claude/skills/core:demo/SKILL.md")),
92
92
  ).toBe("../../../core/skills/demo/SKILL.md");
@@ -0,0 +1,57 @@
1
+ /**
2
+ * hq reindex — surfaces namespaced skills as Claude Code skill wrappers,
3
+ * mirrors personal/{knowledge,policies,workers,settings} into core/, prunes
4
+ * orphan wrappers, and regenerates the workers registry.
5
+ *
6
+ * The implementation lives in scripts/reindex.sh, shipped with this package.
7
+ * This module resolves that script relative to the package (dist/cli → package
8
+ * root) and execs it against the caller's HQ root. Historically the script ran
9
+ * directly as a Claude Code hook inside hq-core (named "master-sync"); it now
10
+ * lives here so a single copy is maintained, and the hq-core hook is a thin
11
+ * shim over `hq reindex`.
12
+ */
13
+ import { spawnSync } from "child_process";
14
+ import { fileURLToPath } from "url";
15
+ import path from "path";
16
+
17
+ const __filename = fileURLToPath(import.meta.url);
18
+ const __dirname = path.dirname(__filename);
19
+
20
+ /**
21
+ * Absolute path to the bundled reindex.sh. From the compiled module at
22
+ * dist/cli/reindex.js, the package root is two levels up; the script lives
23
+ * at <package-root>/scripts/reindex.sh.
24
+ */
25
+ export function reindexScriptPath(): string {
26
+ return path.resolve(__dirname, "..", "..", "scripts", "reindex.sh");
27
+ }
28
+
29
+ export interface ReindexOptions {
30
+ /** HQ root to operate on. Defaults to process.cwd(). */
31
+ repoRoot?: string;
32
+ }
33
+
34
+ export interface ReindexResult {
35
+ /** Exit status of the underlying script (0 = success). */
36
+ status: number;
37
+ }
38
+
39
+ /**
40
+ * Run reindex against an HQ root. Synchronous — the script is cheap and
41
+ * idempotent, and callers (the hook shim, sync/rescue, tests) want the exit
42
+ * status. stdout/stderr from the script are forwarded to stderr so the
43
+ * caller's stdout stays clean (hooks must not emit stdout that the agent
44
+ * interprets).
45
+ */
46
+ export function reindex(opts: ReindexOptions = {}): ReindexResult {
47
+ const repoRoot = opts.repoRoot ?? process.cwd();
48
+ const script = reindexScriptPath();
49
+ const res = spawnSync("bash", [script, repoRoot], {
50
+ stdio: ["ignore", "inherit", "inherit"],
51
+ });
52
+ if (res.error) {
53
+ process.stderr.write(`reindex: failed to run ${script}: ${res.error.message}\n`);
54
+ return { status: 1 };
55
+ }
56
+ return { status: res.status ?? 1 };
57
+ }
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Integration test for the rescue convergence guard in scripts/replace-rescue.sh.
3
+ *
4
+ * Regression for the false `.drift-*` litter: in `history_floor` mode the
5
+ * rescue overlay flags a scaffold file as USER-EDIT whenever its blob differs
6
+ * from the *old* baseline (floor). HQ's own Stop hooks rewrite scaffold files
7
+ * every session, so a file routinely drifts from the floor yet lands
8
+ * byte-for-byte identical to the *new* upstream HEAD the overlay is about to
9
+ * write — and the old code rescued it into personal/ with a redundant
10
+ * `.drift-<ts>-<pid>` copy. The guard reclassifies "drifted from floor but
11
+ * identical to upstream HEAD" as UNCHANGED (no rescue).
12
+ *
13
+ * The script clones its source from GitHub, so we shim `git clone` to clone a
14
+ * local fixture repo instead. Everything runs under --dry-run (no destructive
15
+ * ops, no backup) and we assert the classification the script reports.
16
+ */
17
+ import { describe, it, expect, beforeAll, afterAll } from "vitest";
18
+ import { execFileSync, spawnSync } from "child_process";
19
+ import * as fs from "fs";
20
+ import * as os from "os";
21
+ import * as path from "path";
22
+
23
+ const RESCUE_SCRIPT = path.resolve(process.cwd(), "scripts/replace-rescue.sh");
24
+
25
+ function hasGit(): boolean {
26
+ try {
27
+ execFileSync("git", ["--version"], { stdio: "ignore" });
28
+ return true;
29
+ } catch {
30
+ return false;
31
+ }
32
+ }
33
+
34
+ const gitAvailable = hasGit();
35
+
36
+ describe.skipIf(!gitAvailable)("rescue drift convergence guard", () => {
37
+ let workDir: string;
38
+ let upstream: string;
39
+ let hqRoot: string;
40
+ let shimDir: string;
41
+ let floorSha: string;
42
+ let env: NodeJS.ProcessEnv;
43
+
44
+ const git = (cwd: string, ...args: string[]) =>
45
+ execFileSync("git", args, {
46
+ cwd,
47
+ stdio: ["ignore", "pipe", "pipe"],
48
+ env: {
49
+ ...process.env,
50
+ GIT_AUTHOR_NAME: "t",
51
+ GIT_AUTHOR_EMAIL: "t@t",
52
+ GIT_COMMITTER_NAME: "t",
53
+ GIT_COMMITTER_EMAIL: "t@t",
54
+ },
55
+ })
56
+ .toString()
57
+ .trim();
58
+
59
+ beforeAll(() => {
60
+ workDir = fs.mkdtempSync(path.join(os.tmpdir(), "hq-rescue-drift-"));
61
+
62
+ // --- Build a local "upstream" repo: floor commit, then a HEAD commit
63
+ // where core/x.md changed (v1 -> v2) and the others stayed put. ---
64
+ upstream = path.join(workDir, "upstream");
65
+ fs.mkdirSync(path.join(upstream, "core"), { recursive: true });
66
+ git(workDir, "init", "-b", "main", "upstream");
67
+ fs.writeFileSync(path.join(upstream, "core/x.md"), "v1\n");
68
+ fs.writeFileSync(path.join(upstream, "core/edited.md"), "base\n");
69
+ fs.writeFileSync(path.join(upstream, "core/keep.md"), "same\n");
70
+ git(upstream, "add", "-A");
71
+ git(upstream, "commit", "-m", "floor");
72
+ floorSha = git(upstream, "rev-parse", "HEAD");
73
+ // HEAD: only x.md advances.
74
+ fs.writeFileSync(path.join(upstream, "core/x.md"), "v2\n");
75
+ git(upstream, "add", "-A");
76
+ git(upstream, "commit", "-m", "head");
77
+
78
+ // --- Build the local HQ root being rescued. ---
79
+ hqRoot = path.join(workDir, "hq");
80
+ fs.mkdirSync(path.join(hqRoot, "core"), { recursive: true });
81
+ // `companies/` + `personal/` make it "look like" an HQ root (script guard);
82
+ // both are preserved (never walked).
83
+ fs.mkdirSync(path.join(hqRoot, "personal"), { recursive: true });
84
+ fs.mkdirSync(path.join(hqRoot, "companies"), { recursive: true });
85
+ // Drifted from floor ("v1") but byte-identical to upstream HEAD ("v2").
86
+ // OLD behavior: rescued to personal/x.md (+ .drift on collision).
87
+ // NEW behavior: reconciled as UNCHANGED — no rescue.
88
+ fs.writeFileSync(path.join(hqRoot, "core/x.md"), "v2\n");
89
+ // Genuinely user-edited: differs from both floor and HEAD -> still rescued.
90
+ fs.writeFileSync(path.join(hqRoot, "core/edited.md"), "MINE\n");
91
+ // Untouched vs floor -> UNCHANGED.
92
+ fs.writeFileSync(path.join(hqRoot, "core/keep.md"), "same\n");
93
+
94
+ // --- git shim: rewrite `git clone <github-url> dest` to the local fixture. ---
95
+ // Resolve the real git BEFORE the shim is on PATH so we don't recurse.
96
+ const realGit = execFileSync("bash", ["-lc", "command -v git"]).toString().trim() || "/usr/bin/git";
97
+ shimDir = path.join(workDir, "shim");
98
+ fs.mkdirSync(shimDir, { recursive: true });
99
+ const shim = `#!/usr/bin/env bash
100
+ if [ "$1" = "clone" ]; then
101
+ args=()
102
+ for a in "$@"; do
103
+ case "$a" in
104
+ https://github.com/*) a=${JSON.stringify(upstream)} ;;
105
+ esac
106
+ args+=("$a")
107
+ done
108
+ exec ${JSON.stringify(realGit)} "\${args[@]}"
109
+ fi
110
+ exec ${JSON.stringify(realGit)} "$@"
111
+ `;
112
+ fs.writeFileSync(path.join(shimDir, "git"), shim, { mode: 0o755 });
113
+
114
+ env = { ...process.env, PATH: `${shimDir}:${process.env.PATH ?? ""}` };
115
+ });
116
+
117
+ afterAll(() => {
118
+ if (workDir) fs.rmSync(workDir, { recursive: true, force: true });
119
+ });
120
+
121
+ function runRescue() {
122
+ return spawnSync(
123
+ "bash",
124
+ [
125
+ RESCUE_SCRIPT,
126
+ "--hq-root", hqRoot,
127
+ "--source", "test/repo",
128
+ "--ref", "main",
129
+ "--floor-sha", floorSha,
130
+ "--dry-run",
131
+ "--yes",
132
+ "--no-backup",
133
+ ],
134
+ { env, encoding: "utf-8" },
135
+ );
136
+ }
137
+
138
+ it("reconciles a floor-drifted file that is identical to upstream HEAD (no rescue)", () => {
139
+ const r = runRescue();
140
+ const out = `${r.stdout}\n${r.stderr}`;
141
+ // Sanity: ran in history_floor mode against our floor.
142
+ expect(r.status, out).toBe(0);
143
+ expect(out).toContain(`Baseline: ${floorSha}`);
144
+
145
+ // The drifted-but-identical-to-HEAD file is reconciled, NOT rescued.
146
+ expect(out).toContain("drift reconciled (identical to upstream HEAD; no rescue): core/x.md");
147
+ expect(out).not.toMatch(/user-edit \(rescue\): core\/x\.md/);
148
+
149
+ // The genuinely-edited file is still rescued into personal/.
150
+ expect(out).toContain("user-edit (rescue): core/edited.md -> personal/edited.md");
151
+
152
+ // Untouched file classified UNCHANGED.
153
+ expect(out).toContain("unchanged (delete + replace): core/keep.md");
154
+
155
+ // Summary reflects exactly one reconcile.
156
+ expect(out).toMatch(/drift reconciled \(== upstream\):\s+1 files/);
157
+ });
158
+ });
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Wiring tests: `rescue()` runs `reindex()` after a successful, non-dry-run
3
+ * rescue so the generated skill wrappers / personal mirrors / workers registry
4
+ * are refreshed once core/ has been re-laid-down.
5
+ *
6
+ * child_process is mocked so the real replace-rescue.sh never runs, and
7
+ * ./reindex.js is mocked to a spy so we assert the call without spawning.
8
+ */
9
+ import { describe, it, expect, vi, beforeEach } from "vitest";
10
+
11
+ vi.mock("child_process", () => ({
12
+ spawnSync: vi.fn(() => ({ status: 0 })),
13
+ }));
14
+ vi.mock("./reindex.js", () => ({
15
+ reindex: vi.fn(() => ({ status: 0 })),
16
+ }));
17
+
18
+ import { spawnSync } from "child_process";
19
+ import { reindex } from "./reindex.js";
20
+ import { rescue } from "./rescue.js";
21
+
22
+ describe("rescue → reindex", () => {
23
+ beforeEach(() => {
24
+ vi.clearAllMocks();
25
+ (spawnSync as unknown as ReturnType<typeof vi.fn>).mockReturnValue({ status: 0 });
26
+ });
27
+
28
+ it("refreshes via reindex after a successful rescue", () => {
29
+ const r = rescue({ hqRoot: "/tmp/hq", assumeYes: true });
30
+ expect(r.status).toBe(0);
31
+ expect(reindex).toHaveBeenCalledTimes(1);
32
+ expect(reindex).toHaveBeenCalledWith({ repoRoot: "/tmp/hq" });
33
+ });
34
+
35
+ it("does NOT run reindex on a dry-run", () => {
36
+ rescue({ hqRoot: "/tmp/hq", dryRun: true });
37
+ expect(reindex).not.toHaveBeenCalled();
38
+ });
39
+
40
+ it("does NOT run reindex when the rescue script fails", () => {
41
+ (spawnSync as unknown as ReturnType<typeof vi.fn>).mockReturnValueOnce({ status: 1 });
42
+ const r = rescue({ hqRoot: "/tmp/hq", assumeYes: true });
43
+ expect(r.status).toBe(1);
44
+ expect(reindex).not.toHaveBeenCalled();
45
+ });
46
+ });
package/src/cli/rescue.ts CHANGED
@@ -17,6 +17,7 @@
17
17
  import { spawnSync } from "child_process";
18
18
  import { fileURLToPath } from "url";
19
19
  import path from "path";
20
+ import { reindex } from "./reindex.js";
20
21
 
21
22
  const __filename = fileURLToPath(import.meta.url);
22
23
  const __dirname = path.dirname(__filename);
@@ -118,5 +119,18 @@ export function rescue(opts: RescueOptions = {}): RescueResult {
118
119
  process.stderr.write(`rescue: failed to run ${script}: ${res.error.message}\n`);
119
120
  return { status: 1 };
120
121
  }
121
- return { status: res.status ?? 1 };
122
+ const status = res.status ?? 1;
123
+ // A successful, non-dry-run rescue re-lays-down core/, so refresh the
124
+ // generated skill wrappers, personal-overlay mirrors, and workers registry.
125
+ // Best-effort + idempotent — never overrides the rescue's own exit status.
126
+ // repoRoot falls back to process.cwd() (reindex's default) when hqRoot is
127
+ // omitted, matching the rescue script's own cwd-based default.
128
+ if (status === 0 && !opts.dryRun) {
129
+ try {
130
+ reindex({ repoRoot: opts.hqRoot });
131
+ } catch {
132
+ // best-effort
133
+ }
134
+ }
135
+ return { status };
122
136
  }