@indigoai-us/hq-cli 5.345.257 → 5.345.260

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 (45) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/assets/scaffold/core/scripts/handoff-knowledge-commit.sh +163 -5
  3. package/assets/scaffold/core/scripts/handoff-sync-prefetch.sh +39 -0
  4. package/assets/scaffold/core/scripts/handoff-sync-publish.sh +51 -3
  5. package/contracts/host-canary-release.json +7 -7
  6. package/dist/commands/cloud.d.ts +2 -7
  7. package/dist/commands/cloud.js +6 -30
  8. package/dist/commands/core-bucket-c-handoff-knowledge-native.d.ts +24 -2
  9. package/dist/commands/core-bucket-c-handoff-knowledge-native.js +170 -19
  10. package/dist/commands/core-bucket-c-handoff-sync-native.d.ts +4 -2
  11. package/dist/commands/core-bucket-c-handoff-sync-native.js +153 -34
  12. package/dist/commands/core-bucket-c-handoff-sync-worker.cjs +201 -0
  13. package/dist/commands/core-handoff.js +57 -14
  14. package/dist/commands/keyed-sync-pull.d.ts +7 -3
  15. package/dist/commands/keyed-sync-pull.js +90 -22
  16. package/dist/commands/reindex.d.ts +3 -0
  17. package/dist/commands/reindex.js +11 -5
  18. package/dist/commands/rescue.js +7 -2
  19. package/dist/commands/sync-core.js +24 -7
  20. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +3227 -2138
  21. package/dist/hq-cloud-sync-runner/package.json +1 -1
  22. package/dist/lib/canonical-person.d.ts +19 -0
  23. package/dist/lib/canonical-person.js +30 -0
  24. package/dist/lib/company-sessions-cli.d.ts +12 -0
  25. package/dist/lib/company-sessions-cli.js +54 -0
  26. package/dist/lib/company-sessions.d.ts +31 -0
  27. package/dist/lib/company-sessions.js +304 -0
  28. package/dist/lib/doctor/checks/replay-recorder.js +3 -3
  29. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  30. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  31. package/dist/lib/flag-snapshot-file.d.ts +47 -1
  32. package/dist/lib/flag-snapshot-file.js +143 -20
  33. package/dist/lib/hook-engine/coverage.d.ts +115 -7
  34. package/dist/lib/hook-engine/coverage.js +280 -10
  35. package/dist/lib/mesh/live/company-flag-refresh.js +2 -2
  36. package/dist/lib/onboarding/orchestrator.js +4 -2
  37. package/dist/lib/sync-core/engine-home.d.ts +5 -1
  38. package/dist/lib/sync-core/engine-home.js +6 -2
  39. package/dist/lib/sync-core/reconcile.d.ts +5 -0
  40. package/dist/lib/sync-core/reconcile.js +21 -1
  41. package/dist/lib/sync-core/vault-uid.d.ts +2 -0
  42. package/dist/lib/sync-core/vault-uid.js +4 -0
  43. package/dist/utils/sync-operation-lock.d.ts +2 -1
  44. package/dist/utils/sync-operation-lock.js +13 -2
  45. package/package.json +8 -8
package/CHANGELOG.md CHANGED
@@ -2,6 +2,37 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [5.345.260] — 2026-11-26
6
+ - Added: `hq reindex`, `hq rescue`, `hq sync` (every hq-cloud `sync()` leg), the first sync of `hq onboard` and the reindex after `hq sync-core reconcile` pass hq-cloud a `companySessions` option. For a person: the `prs_` person uid, the cloud-backed companies and an `uploadEvidence` lookup. For an agent (`HQ_MACHINE_CREDS_FILE`, or `~/.hq-agent/machine-creds.json` with no person session, or an `agt_` sign-in): `{ identity: "agent" }`, so its transcripts stay in its own vault. A company counts as cloud-backed when its `companies/manifest.yaml` entry has a `cmp_` `cloud_uid`, when the new sync engine runs or is handing back its vault, or when its `company.yaml` says `cloud: true` (an unreadable `company.yaml` counts as cloud-backed), and hq-cloud's personal-vault scope (`isCompanyInPersonalVaultScope`, else `computePersonalCompanySubdirs`) does not hold it. `personal` never counts. Folder names follow hq-cloud's rule (`^[A-Za-z0-9_-]+$`). The lookup reads the new sync engine's confirmed-upload ledger (`~/.hq/sync-core/engines/<cmp>/.hq/sync-core/state/push-only-confirmed/<cmp>.json`) for companies the engine owns in full, and answers nothing for companies on the current sync so hq-cloud uses its own journal. The ledger is read only when it and its folders are not symlinks, is at most 16 MiB and is valid JSON; malformed entries are skipped. The person uid is cached in `~/.hq/company-sessions/person-uid.json` for the signed-in account; a reindex from a hook never looks it up over the network, and other commands wait at most 10 s. When the uid is not known the option is left out, and the message, printed once, says company-bound transcripts are held on this computer. Nobody signed in: no option and no message. `HQ_COMPANY_SESSIONS_HOME` replaces the home folder for this routing (the test setup points it at a temp folder). This needs `@indigoai-us/hq-cloud` 6.18.127 (indigoai-us/hq-cloud#1180), which this release bundles.
7
+ - Added: every engine `config.toml` written by `hq sync-core reconcile` carries `person_uid = "prs_..."` under `[sync]` when the person uid is known (resolved, else cached), so the engine uploads `sessions/<uid>/` in company vaults (indigoai-us/hq-sync-core#242). Engines before that release ignore the key.
8
+ - Changed: on Windows, `hq-hook` can match a released hook script that a checkout rewrote with Windows line endings when the `hook-engine-crlf-pins` flag is enabled in the local flag snapshot; without it, behavior is unchanged.
9
+ - Changed: the host canary record shipped with the CLI is refreshed for this release build.
10
+ - Changed: version 5.345.259 was tagged but not published, so its changes ship in this release. The host canary record is rebuilt for the 5.345.260 build.
11
+ - Changed: hq-cli now uses hq-cloud 6.18.126. The sync runner keeps one upload memory budget (up to 1 GB) for the whole process instead of one per sync pass, and a file larger than the budget uploads one at a time alongside it, so small edits keep syncing while a large file uploads. The background reindex step has a fixed memory ceiling of 1024 MB (`HQ_REINDEX_WORKER_MAX_OLD_SPACE_MB` changes it, up to 3584); if it reaches the ceiling, only that step stops and sync carries on. While the runner uses 1 GB or more, the sync log gets one line a minute that splits its memory into heap, buffers and other memory. Token usage from busy machines now reaches HQ: each sync pass keeps uploading Claude Code, Codex and Grok transcript usage for up to 20 seconds (up to 6,000 rows each) instead of stopping at 400 rows, and picks up where it stopped on the next pass.
12
+ - On hq-agents-v2 bots, the Rust hook engine now does master-hook's own SessionStart work natively (session bind, twin dedupe, nested-install warning, scope pin, timeout journal), so `hq reindex` can move an agents-v2 SessionStart with the stock settings off the bash adapter. A twin start skips master-hook's folder hooks and keeps the registry hooks, as the adapter does. An input the native work does not model, such as a Task agent payload or a settings entry that starts master-hook for another event, is refused natively. Roots whose `core/scripts/lib/session-id.sh` is not the hq-core 16.0.48 to 16.0.50 revision stay on the adapter at registration, as before.
13
+ - The Rust hook engine's native PostToolUse for agents-v2 and fleet-local bots now reads a `hook-registry.json` matcher that uses regex syntax, such as `Agent|Task|Write|Edit|MultiEdit|NotebookEdit|Read|mcp__.*`, the same way the shell adapter matches it. A bot HQ with such a matcher now stays on the native engine for PostToolUse. Before, the engine handed every PostToolUse back to the adapter. A matcher the engine cannot read exactly still goes to the adapter.
14
+ - The Rust hook engine's native PreToolUse now reads the company scope script of the HQ it runs in. When that script is not one of the hq-core 16.0.45 to 16.0.52 revisions the native scope check answers for (for example the hq-core 16.0.53-beta.1 script, which also checks PowerShell tool calls), `hq reindex` keeps PreToolUse on the old dispatcher for Claude Code and Codex, and an HQ already on the new core refuses PreToolUse calls with a message that names the script and asks for `hq reindex`. An HQ on a released core is answered as before.
15
+ - hq-hook: the credential-file check on a very long command with many repeated words runs faster on Windows; its answers are unchanged.
16
+ - Fixed: the knowledge step of `hq core handoff run` now looks only at the company the session is bound to, as the hq-core handoff helper does. It used to check every company's knowledge folder and could list other companies' folders in its result. The session lock is read through the HQ root's own `core/scripts/hq-session.sh`, as the helper reads it, so a missing session library, a failing or slow lock read, or a host without bash leaves the session unbound. With no bound company the step reports `SKIPPED-COMPANY-KNOWLEDGE` with the reason, and a bound company's knowledge that is its own git repository has its listed files committed, both as the helper does.
17
+ - Fixed: the bundled `handoff-knowledge-commit.sh`, used by `hq core handoff-knowledge-commit` when the built-in route is off, is now hq-core's current helper and also reads only the bound company.
18
+ - Fixed: `hq core handoff run` and `hq core handoff finalize` build the thread id (`T-YYYYMMDD-HHMMSS-…`) from the local clock, as the hq-core helper does, so new thread ids sort in line with existing ones. `created_at` and the other timestamps stay in UTC.
19
+ - Fixed: native `hq core handoff-sync-prefetch` now snapshots a valid local `workspace/threads/handoff.json` pointer before pulling from the personal vault and restores it atomically if the pull lands an older `created_at`, removes the file, or writes non-object or invalid JSON.
20
+ - Fixed: `hq core handoff finalize` now runs the in-process continuity publish (`runHandoffSyncPublish`) by default and whenever `core/scripts/handoff-sync-publish.sh` is absent, instead of silently skipping publish. It follows the `core-native-handoff` kill switch (falling back to the installed script or bundled asset when disabled), pushes only the continuity pointer and its referenced thread file (falling back once to a full personal push on older CLIs), and leaves other companies' folders untouched.
21
+ - Fixed: native `conduct-link-inherit` standing rules and join failure logs in both `UserPromptSubmit` and `PostToolUse`/`PreToolUse` ports now choose `hq runners` on post-rename HQ core installs while preserving `hq lanes` on pre-rename installs, and native in-process join failures now match the CLI's `hq runners link:` prefix (US-035).
22
+ - Fixed: on Windows, HQ's check that a session is not running from a git worktree of HQ works again, at the start of a session and on each prompt. It had been turning every prompt away there.
23
+ - Claim `fleet-local-adapter:PreToolUse` on `fleet-local`, and `merged-write-guard-shadow` on `fleet-local` and `agents-v2` (`PreToolUse@agents-v2,fleet-local`). The fleet-local adapter check accepts a stock `hook-registry.json` whose rows the dispatcher reads, so each row is answered by its own member. On both hosts the shadow row records under the adapter's own HQ root and honours `HQ_FLEET_LOCAL_HOOK_SKIP` and `HQ_AGENTS_V2_HOOK_SKIP`. Differential parity tests against `fleet-local-v0.4.33.sh` and `agents-v2-6490142.sh`. `lanes-repo-merge-hold` stays unclaimed on both hosts pending an owner decision.
24
+
25
+ ## [5.345.258] — 2026-11-26
26
+ - Fixed hooks switching between the hook engine and the shell scripts from one event to the next when an `hq` older than 5.345.252 also runs on the same machine. That older release asks for flags without reporting its version, gets a different answer, and saved it to the same local flag file. The CLI now saves flags to `snapshot-v2-<scope>.json`, and the CLI and `hq-hook` read only that file. The CLI still writes `snapshot-<scope>.json` with the same contents for older readers. Until a scope has a `snapshot-v2-` file, a feature that is turned off in its old file stays off; nothing else is read from the old file, so hook ports stay on the shell scripts until a current `hq` command or the daemon writes the new file.
27
+ - Changed: the host canary record shipped with the CLI is refreshed for this release build.
28
+ - Fixed: on Windows, hq-hook now starts `git` (credential-guard `rev-parse` and glob toplevel lookup) with `CREATE_NO_WINDOW`, so those probes no longer open a console window on every file read.
29
+ - Fixed: `hq sync pull` with `HQ_API_KEY` (the keyed pull used to hydrate a MicroVM) no longer fails the whole pull when the vault holds keys that normal sync never writes. It now skips `.git` internals, `.hq/` reserved files, folder markers such as `lambda/`, paths excluded by the HQ ignore files, unsafe paths (traversal, absolute, control characters), both spellings of a case-only collision, and directory overlay markers, writes the rest, and prints the skip count for each reason.
30
+ - Fixed: the keyed pull (`HQ_API_KEY`) now skips, and counts as `forbidden`, an object its key may not read (a per-object 403 from the presign route or from storage), instead of failing the whole hydrate. The object is never written. A 401, a 5xx, a size mismatch, a 403 on the list call, a 403 that did not come from storage, and a key refused on every listed object still fail the pull.
31
+ - The Rust hook engine's native PreToolUse now accepts the hq-core 16.0.52 credential-file read script, so an HQ on 16.0.52 with the new core switched on is no longer kept on the old dispatcher for that file. On such an HQ, on macOS and Linux and on every host, the native credential-file read check gives the same answer as the 16.0.52 shell version for a URL operand of `curl` or `wget` in a line with more than one command and for template files such as `example.env`. Its answers for `git grep`, `git diff`, `git log -p` and `git show` are unchanged. On such an HQ the check also refuses every Bash call when `HQ_CREDENTIAL_GUARD_BUDGET_SECONDS` is `00`, and refuses git content reads when `GIT_INDEX_FILE` is set. An HQ on an older core is answered as before. On Windows, where the native check answers, an HQ on 16.0.52 gets those two refusals and is otherwise answered as before.
32
+ - hq-hook: Codex on hq-core 16.0.51 and 16.0.52 now gets PreToolUse answers from the Rust engine. The engine reads `core/scripts/lib/hook-adapter-core.sh` at the 16.0.51 (`09f5a3e0`) and 16.0.52 (`cf1abd5c`) revisions on Codex, as it already did on Claude Code. The entry `hq reindex` writes into `.claude/settings.json` for Claude Code (`hq-hook run --host claude PreToolUse --hq-root <root>`) is read on Codex as the shell adapter reads it. Any other `.claude/settings.json` PreToolUse entry written with an `args` list is a shape HQ does not write and does not support on Codex: on any hq-core release, 16.0.50 included, the engine refuses the tool call with a message that names the settings file, and `hq reindex` keeps Codex PreToolUse on the shell dispatcher for that HQ.
33
+ - Port the `hook-lib.sh` v16.0.52 (`436493e3`) `hd_text_arg` lexer rule for `hq core handoff finalize --summary`/`--title` and pin `436493e3` in `pre_tool_use_master::DISPATCHER_PINS`.
34
+ - The native merged write check accepts the `core/scripts/hook-lib.sh` that hq-core 16.0.52 ships beside the released shadow wrapper, off Windows, so `hq reindex` no longer keeps PreToolUse on the shell dispatcher for that file on its account.
35
+
5
36
  ## [5.345.257] — 2026-11-25
6
37
  - hq-hook: on agents-v2 bots running the hq-agents-v2 #347 adapter, company PostToolUse hooks now run in the native hook engine when `HQ_MASTER_CHILD_TIMEOUT` is short enough that every hook can run to its limit inside the call budget and the adapter's 18 s start window (for example two hooks at 2 s in the 5 s budget). Before, the engine always handed these calls back to the adapter. Each hook is killed at the same limit master-hook uses. With the stock 120 s limit, more hooks than fit, or a lowered adapter budget, the call still goes to the adapter, and SessionStart is unchanged.
7
38
  - Fixed: preserve `RUSTUP_HOME` and `CARGO_HOME` in `credential_grep_sources::real_stdout` when redirecting `HOME` to the fixture directory so `round12_formatter` (`cargo fmt && git diff`) finds the runner's toolchain on AWS Linux runners.
@@ -19,6 +19,26 @@ done
19
19
  [ -n "$changeset" ] && [ -f "$changeset" ] || usage
20
20
  root="$(cd "$root" && pwd -P)"
21
21
  tmp_parent="$root/workspace/threads/.handoff-tmp"
22
+
23
+ # These commits run hooks. When the HQ git-hooks dispatcher is installed (a
24
+ # global core.hooksPath), its commit-msg hook stamps HQ-Fingerprint, so an
25
+ # explicit trailer here would be a second copy. Pass it only when no global
26
+ # hooks path is set, i.e. the dispatcher is absent. The trailer is loaded
27
+ # lazily, once, before the first commit, so a handoff with nothing to commit
28
+ # never pays for it. A failing lib leaves the array empty and never blocks the
29
+ # commit.
30
+ HQ_FINGERPRINT_TRAILER_ARGS=()
31
+ fingerprint_lib="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib/fingerprint.sh"
32
+ fingerprint_loaded=0
33
+ load_fingerprint_trailer_once() {
34
+ [ "$fingerprint_loaded" -eq 0 ] || return 0
35
+ fingerprint_loaded=1
36
+ if [ -z "$(git config --global --get core.hooksPath 2>/dev/null || true)" ] && [ -f "$fingerprint_lib" ]; then
37
+ # shellcheck source=lib/fingerprint.sh
38
+ { . "$fingerprint_lib" 2>/dev/null && hq_fingerprint_trailer_load "$root"; } || HQ_FINGERPRINT_TRAILER_ARGS=()
39
+ fi
40
+ return 0
41
+ }
22
42
  mkdir -p "$tmp_parent"
23
43
  tmp_dir="$(mktemp -d "$tmp_parent/handoff-knowledge-commit.XXXXXX")"
24
44
  trap 'rm -rf "$tmp_dir"' EXIT
@@ -31,7 +51,137 @@ jq -e 'def safe_path: type == "string" and length > 0 and (startswith("/") | not
31
51
  exit 1
32
52
  }
33
53
 
34
- for knowledge_path in "$root"/core/knowledge/public/* "$root"/core/knowledge/private/* "$root"/personal/knowledge/* "$root"/companies/*/knowledge; do
54
+ # Company scope: only the session's bound (primary) company is considered.
55
+ # Other companies' knowledge is never read or committed, including the other
56
+ # members of a multi-company lock (company_slugs). The bound company is
57
+ # HQ_ACTIVE_COMPANY; when that is empty (a company bound mid-session writes the
58
+ # session lock but cannot change the env of the running process) it is the
59
+ # lock's primary company_slug, read ONLY for a session id taken from the
60
+ # environment (session_id_from_env) and passed to hq-session.sh explicitly.
61
+ # workspace/sessions/.current is a global last-writer-wins pointer that can name
62
+ # another live session, so it is never used here. The reserved value "personal"
63
+ # means no company. A resolved slug must be a real directory under companies/
64
+ # and appear with exact case in companies/manifest.yaml, otherwise it is treated
65
+ # as unbound. With no bound company, company knowledge is skipped and the skip
66
+ # is reported with its reason.
67
+ skip_reason="no bound company"
68
+
69
+ # run_with_timeout <seconds> <cmd...>: timeout/gtimeout when present, else a
70
+ # background job with a bounded poll (portable to stock macOS).
71
+ run_with_timeout() {
72
+ local secs="$1"; shift
73
+ if command -v timeout >/dev/null 2>&1; then timeout "$secs" "$@"; return $?; fi
74
+ if command -v gtimeout >/dev/null 2>&1; then gtimeout "$secs" "$@"; return $?; fi
75
+ # Fallback. Call this only from a background subshell (see the lock read
76
+ # below): the TERM/INT/HUP trap set here then never replaces the main shell's
77
+ # traps. The output file lives in $tmp_dir, which the main EXIT trap removes.
78
+ {
79
+ out="$(mktemp "$tmp_dir/hkc-timeout.XXXXXX")" || exit 1
80
+ pid=""
81
+ kill_tree() {
82
+ local parent="$1" child
83
+ for child in $(pgrep -P "$parent" 2>/dev/null); do kill_tree "$child"; done
84
+ kill "$parent" 2>/dev/null || true
85
+ }
86
+ cleanup_job() {
87
+ [ -z "$pid" ] || { kill_tree "$pid"; wait "$pid" 2>/dev/null || true; }
88
+ rm -f "$out"
89
+ }
90
+ trap 'cleanup_job; exit 143' TERM INT HUP
91
+ "$@" >"$out" 2>/dev/null &
92
+ pid=$!
93
+ i=0
94
+ while [ "$i" -lt $((secs * 10)) ]; do
95
+ kill -0 "$pid" 2>/dev/null || break
96
+ sleep 0.1
97
+ i=$((i + 1))
98
+ done
99
+ if kill -0 "$pid" 2>/dev/null; then
100
+ cleanup_job
101
+ exit 124
102
+ fi
103
+ rc=0
104
+ wait "$pid" || rc=$?
105
+ cat "$out"; rm -f "$out"
106
+ exit "$rc"
107
+ }
108
+ }
109
+
110
+ # company_is_registered <slug>: real (non-symlink) company directory and an
111
+ # exact-case key under companies: in companies/manifest.yaml.
112
+ company_is_registered() {
113
+ local slug="$1" manifest="$root/companies/manifest.yaml" company_dir="$root/companies/$1"
114
+ [ -d "$company_dir" ] && [ ! -L "$company_dir" ] || return 1
115
+ [ -f "$manifest" ] || return 1
116
+ awk -v want="$slug" '
117
+ /^companies:[[:space:]]*$/ { inco = 1; next }
118
+ inco && /^[^[:space:]#]/ { inco = 0 }
119
+ inco && match($0, /^ [^[:space:]#][^:]*:/) {
120
+ key = substr($0, 3, RLENGTH - 3)
121
+ if (key == want) { found = 1; exit }
122
+ }
123
+ END { exit found ? 0 : 1 }' "$manifest" 2>/dev/null
124
+ }
125
+
126
+ bound_company="${HQ_ACTIVE_COMPANY:-}"
127
+ # The reserved value "personal" means no company, same as the lock route; do not
128
+ # fall through to the session lock.
129
+ if [ "$bound_company" = personal ]; then
130
+ bound_company=""
131
+ elif [ -z "$bound_company" ]; then
132
+ lock_session_id=""
133
+ lib_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
134
+ if [ -f "$lib_dir/lib/session-id.sh" ]; then
135
+ # shellcheck source=lib/session-id.sh
136
+ . "$lib_dir/lib/session-id.sh" 2>/dev/null || true
137
+ if declare -F session_id_from_env >/dev/null 2>&1; then
138
+ lock_session_id="$(session_id_from_env)"
139
+ fi
140
+ fi
141
+ if [ -z "$lock_session_id" ]; then
142
+ skip_reason="no bound company (no session id in the environment, session lock not read)"
143
+ elif [ ! -f "$lib_dir/hq-session.sh" ]; then
144
+ skip_reason="session lock unreadable"
145
+ else
146
+ lock_meta="$root/workspace/sessions/$lock_session_id/meta.yaml"
147
+ if [ -e "$lock_meta" ] && [ ! -r "$lock_meta" ]; then
148
+ skip_reason="session lock unreadable"
149
+ else
150
+ # Run the read as a background job and wait, so a TERM to this helper is
151
+ # handled at once and takes the job (and its children) down with it.
152
+ lock_out_file="$tmp_dir/lock-out"
153
+ HQ_ROOT="$root" HQ_HQ_SESSION_NO_CLI=1 \
154
+ run_with_timeout "${HQ_HANDOFF_LOCK_TIMEOUT:-5}" bash "$lib_dir/hq-session.sh" --session-id "$lock_session_id" get company_slug \
155
+ >"$lock_out_file" &
156
+ lock_job=$!
157
+ trap 'kill -TERM "$lock_job" 2>/dev/null || true; wait "$lock_job" 2>/dev/null || true; exit 143' TERM INT HUP
158
+ lock_rc=0
159
+ wait "$lock_job" || lock_rc=$?
160
+ trap - TERM INT HUP
161
+ if [ "$lock_rc" -eq 0 ]; then
162
+ lock_out="$(cat "$lock_out_file")"
163
+ bound_company="$(printf '%s' "$lock_out" | tr -d '[:space:]')"
164
+ [ "$bound_company" != personal ] || bound_company=""
165
+ else
166
+ skip_reason="session lock unreadable"
167
+ fi
168
+ fi
169
+ fi
170
+ fi
171
+ company_knowledge=()
172
+ if [ -n "$bound_company" ]; then
173
+ if [[ "$bound_company" =~ ^[A-Za-z0-9_-]+$ ]] && company_is_registered "$bound_company"; then
174
+ company_knowledge=("$root/companies/$bound_company/knowledge")
175
+ else
176
+ skip_reason="company '$bound_company' is not a registered company"
177
+ bound_company=""
178
+ fi
179
+ fi
180
+ if [ -z "$bound_company" ]; then
181
+ echo "SKIPPED-COMPANY-KNOWLEDGE: $skip_reason; company knowledge repositories were not processed"
182
+ fi
183
+
184
+ for knowledge_path in "$root"/core/knowledge/public/* "$root"/core/knowledge/private/* "$root"/personal/knowledge/* ${company_knowledge[@]+"${company_knowledge[@]}"}; do
35
185
  [ -e "$knowledge_path" ] || [ -L "$knowledge_path" ] || continue
36
186
  knowledge_rel="${knowledge_path#"$root"/}"
37
187
  if [ -L "$knowledge_path" ]; then
@@ -53,9 +203,8 @@ for knowledge_path in "$root"/core/knowledge/public/* "$root"/core/knowledge/pri
53
203
  esac
54
204
  continue
55
205
  fi
56
- case "$knowledge_path" in
57
- "$root"/companies/*/knowledge) continue ;;
58
- esac
206
+ # A plain company knowledge directory syncs through its vault; only a bound
207
+ # company's knowledge that is its own git repository is committed here.
59
208
  [ -e "$knowledge_path/.git" ] || continue
60
209
  repo_dir="$(git -C "$knowledge_path" rev-parse --show-toplevel 2>/dev/null)" || continue
61
210
  knowledge_real="$(cd "$knowledge_path" && pwd -P)"
@@ -109,7 +258,8 @@ for knowledge_path in "$root"/core/knowledge/public/* "$root"/core/knowledge/pri
109
258
  changed="$(git -C "$repo_dir" status --porcelain -- "${repo_paths[@]}")"
110
259
  [ -n "$changed" ] || continue
111
260
  git -C "$repo_dir" add -- "${repo_paths[@]}"
112
- git -C "$repo_dir" commit --only -m "checkpoint: save session knowledge changes" -- "${repo_paths[@]}"
261
+ load_fingerprint_trailer_once
262
+ git -C "$repo_dir" commit --only -m "checkpoint: save session knowledge changes" ${HQ_FINGERPRINT_TRAILER_ARGS[@]+"${HQ_FINGERPRINT_TRAILER_ARGS[@]}"} -- "${repo_paths[@]}"
113
263
  done
114
264
 
115
265
  while IFS= read -r touched_path; do
@@ -119,5 +269,13 @@ while IFS= read -r touched_path; do
119
269
  echo "NOT-COMMITTED: $touched_path is listed in the handoff changeset but no knowledge repository committed it"
120
270
  fi
121
271
  ;;
272
+ companies/*/knowledge/*)
273
+ [ -n "$bound_company" ] || continue
274
+ case "$touched_path" in "companies/$bound_company/knowledge/"*) ;; *) continue ;; esac
275
+ [ -e "$root/companies/$bound_company/knowledge/.git" ] || continue
276
+ if ! grep -Fqx -- "$touched_path" "$handled_paths"; then
277
+ echo "NOT-COMMITTED: $touched_path is listed in the handoff changeset but no knowledge repository committed it"
278
+ fi
279
+ ;;
122
280
  esac
123
281
  done < <(jq -r '.[] | if type == "string" then . else .path end' "$changeset")
@@ -98,12 +98,51 @@ run_with_timeout() {
98
98
  return "$rc"
99
99
  }
100
100
 
101
+ # The pull lands the vault's copy of workspace/threads/handoff.json over the
102
+ # local one. The vault copy can be OLDER than what this machine already has
103
+ # (a handoff finalized here minutes ago that the vault has not caught up to,
104
+ # or a stale replay): seen 2026-10-25 when an 11:46 pointer replaced a 22:06
105
+ # one and the newer session's archive check then refused. Snapshot the local
106
+ # pointer first and, if the pull regressed it by created_at, put the newer one
107
+ # back. A pulled pointer that is not valid JSON never replaces a valid one.
108
+ POINTER="$HQ_ROOT/workspace/threads/handoff.json"
109
+ POINTER_SNAPSHOT=""
110
+ if [[ -f "$POINTER" ]] && command -v jq >/dev/null 2>&1 \
111
+ && jq -e 'type == "object"' "$POINTER" >/dev/null 2>&1; then
112
+ POINTER_SNAPSHOT="$(mktemp "${TMPDIR:-/tmp}/handoff-pointer-snapshot.XXXXXX")"
113
+ cp "$POINTER" "$POINTER_SNAPSHOT" 2>/dev/null || { rm -f "$POINTER_SNAPSHOT"; POINTER_SNAPSHOT=""; }
114
+ fi
115
+
101
116
  rc=0
102
117
  run_with_timeout "$TIMEOUT" \
103
118
  hq sync pull --personal --hq-root "$HQ_ROOT" --lock-timeout 0 \
104
119
  || rc=$?
105
120
  printf 'exit=%s\n' "$rc" >>"$LOG"
106
121
 
122
+ if [[ -n "$POINTER_SNAPSHOT" ]]; then
123
+ keep_local=0
124
+ if [[ ! -f "$POINTER" ]] || ! jq -e 'type == "object"' "$POINTER" >/dev/null 2>&1; then
125
+ keep_local=1
126
+ else
127
+ local_ts="$(jq -r '.created_at // empty' "$POINTER_SNAPSHOT" 2>/dev/null || true)"
128
+ pulled_ts="$(jq -r '.created_at // empty' "$POINTER" 2>/dev/null || true)"
129
+ if [[ -n "$local_ts" && -n "$pulled_ts" && "$pulled_ts" < "$local_ts" ]]; then
130
+ keep_local=1
131
+ fi
132
+ fi
133
+ if [[ "$keep_local" = 1 ]]; then
134
+ restore_tmp="$(mktemp "$(dirname "$POINTER")/.handoff-pointer.XXXXXX")"
135
+ if cp "$POINTER_SNAPSHOT" "$restore_tmp" && mv -f "$restore_tmp" "$POINTER"; then
136
+ printf 'kept newer local handoff pointer (local created_at=%s, pulled created_at=%s)\n' \
137
+ "${local_ts:-?}" "${pulled_ts:-invalid}" >>"$LOG"
138
+ else
139
+ rm -f "$restore_tmp"
140
+ printf 'could not restore the newer local handoff pointer\n' >>"$LOG"
141
+ fi
142
+ fi
143
+ rm -f "$POINTER_SNAPSHOT"
144
+ fi
145
+
107
146
  case "$rc" in
108
147
  0) echo "ok" ;;
109
148
  124) echo "timed-out" ;;
@@ -92,14 +92,62 @@ run_with_timeout() {
92
92
  return "$rc"
93
93
  }
94
94
 
95
+ # continuity_paths: print the absolute paths the continuity push must carry:
96
+ # the pointer and the one thread file it references. A thread_path that is
97
+ # not a plain file under workspace/threads/ is ignored (same containment rule
98
+ # as hq-cloud computeContinuityPointerPaths).
99
+ continuity_paths() {
100
+ local pointer="$HQ_ROOT/workspace/threads/handoff.json"
101
+ [[ -f "$pointer" ]] || return 0
102
+ printf '%s\n' "$pointer"
103
+ local tp
104
+ tp="$(sed -n 's/.*"thread_path"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$pointer" | head -n1)"
105
+ case "$tp" in
106
+ workspace/threads/*) ;;
107
+ *) return 0 ;;
108
+ esac
109
+ case "/$tp/" in
110
+ */../*|*/./*) return 0 ;;
111
+ esac
112
+ if [[ -f "$HQ_ROOT/$tp" ]]; then printf '%s\n' "$HQ_ROOT/$tp"; fi
113
+ return 0
114
+ }
115
+
95
116
  run_publish() {
96
117
  # `hq sync push --personal` is the canonical publish path for the session
97
- # continuity pointer (the vault scope that carves out handoff.json + the
98
- # referenced thread file). A `--lock-timeout 0` keeps the push from queueing
118
+ # continuity pointer. A `--lock-timeout 0` keeps the push from queueing
99
119
  # behind a long-running sync pass; the operator can rerun later.
120
+ #
121
+ # Push only the pointer and its thread file. A bare `--personal` push walks
122
+ # the whole personal scope, including thousands of workspace/.session-logs
123
+ # files, and never reaches the pointer inside the timebox. The stale vault
124
+ # copy then gets pulled back over the fresh local pointer.
125
+ local paths=()
126
+ local p
127
+ while IFS= read -r p; do
128
+ [[ -n "$p" ]] && paths+=("$p")
129
+ done < <(continuity_paths)
130
+ if [[ ${#paths[@]} -eq 0 ]]; then
131
+ echo "handoff-sync-publish: no continuity pointer to publish" >>"$LOG"
132
+ return 0
133
+ fi
134
+
135
+ local rc=0
100
136
  run_with_timeout "$TIMEOUT" \
101
137
  hq sync push --personal --hq-root "$HQ_ROOT" --lock-timeout 0 \
102
- --message "handoff continuity pointer"
138
+ --message "handoff continuity pointer" "${paths[@]}" || rc=$?
139
+ # CLIs without targeted personal pushes (or with the
140
+ # cli.personal-targeted-push-paths flag off) refuse `--personal` with
141
+ # explicit paths. Only then fall back to the full personal push.
142
+ if [[ "$rc" -ne 0 && "$rc" -ne 124 ]] \
143
+ && tail -n 20 "$LOG" 2>/dev/null | grep -q 'cannot be combined with explicit \[paths\]'; then
144
+ echo "handoff-sync-publish: targeted push refused by this CLI; falling back to full personal push" >>"$LOG"
145
+ rc=0
146
+ run_with_timeout "$TIMEOUT" \
147
+ hq sync push --personal --hq-root "$HQ_ROOT" --lock-timeout 0 \
148
+ --message "handoff continuity pointer" || rc=$?
149
+ fi
150
+ return "$rc"
103
151
  }
104
152
 
105
153
  mkdir -p "$(dirname "$LOG")" 2>/dev/null || true
@@ -1,24 +1,24 @@
1
1
  {
2
2
  "schema": "hq.host-canary-release.v1",
3
- "cliVersion": "5.345.257",
3
+ "cliVersion": "5.345.260",
4
4
  "hosts": {
5
5
  "claude": [
6
6
  {
7
7
  "passed": true,
8
- "at": "2026-11-25T20:07:54.394Z",
9
- "engineVersion": "0.3.1+hq.5.345.257.src.c469d58a7b027d94faefc6a1d4b18ffed5c6a52cdcf89f7c9158542d4e2527dc",
8
+ "at": "2026-11-26T05:37:28.299Z",
9
+ "engineVersion": "0.3.1+hq.5.345.260.src.71d80c1c52c2bb8aa9047db0fc43a30f74a29c00faee418c313ab6f97d3b1bba",
10
10
  "gateSha256": "a2879dfe692233f5953bac86672947bbd82f3c5247292f3efcb80f16c3d2c6b1"
11
11
  },
12
12
  {
13
13
  "passed": true,
14
- "at": "2026-11-25T20:08:38.408Z",
15
- "engineVersion": "0.3.1+hq.5.345.257.src.c469d58a7b027d94faefc6a1d4b18ffed5c6a52cdcf89f7c9158542d4e2527dc",
14
+ "at": "2026-11-26T05:37:58.590Z",
15
+ "engineVersion": "0.3.1+hq.5.345.260.src.71d80c1c52c2bb8aa9047db0fc43a30f74a29c00faee418c313ab6f97d3b1bba",
16
16
  "gateSha256": "ca58a94859eae0a345c11c8d9c59303eb76350dc1cf223391037d21979c28718"
17
17
  },
18
18
  {
19
19
  "passed": true,
20
- "at": "2026-11-25T20:09:12.395Z",
21
- "engineVersion": "0.3.1+hq.5.345.257.src.c469d58a7b027d94faefc6a1d4b18ffed5c6a52cdcf89f7c9158542d4e2527dc",
20
+ "at": "2026-11-26T05:38:26.407Z",
21
+ "engineVersion": "0.3.1+hq.5.345.260.src.71d80c1c52c2bb8aa9047db0fc43a30f74a29c00faee418c313ab6f97d3b1bba",
22
22
  "gateSha256": "ecdbab7c2e0a1d94eb9c98f15e760390f215bc7115a217ded24b4275322722d2"
23
23
  }
24
24
  ]
@@ -16,6 +16,7 @@
16
16
  import { Command } from "commander";
17
17
  import { type CliManifestTarget } from "../lib/sync/cli-manifest-reconcile.js";
18
18
  import { VaultClient, scopeLookupSkipMessage, SyncScopeLookupError, type ConflictStrategy, type EntityContext, type MembershipSyncConfig, type SyncMode, type PullScope, type ExplicitGrant, type ShareOptions, type VaultServiceConfig } from "@indigoai-us/hq-cloud";
19
+ import { resolveCanonicalPersonUid } from "../lib/canonical-person.js";
19
20
  import { withSyncWatchdog, type SyncWatchdogLimits } from "../utils/sync-watchdog.js";
20
21
  import { type BannerLevel } from "../lib/narrow-hint-banner.js";
21
22
  import { type PlanLimitRefusalSummary } from "../lib/billing/plan-limit-refusals.js";
@@ -608,13 +609,7 @@ export declare function pushShareCredentials(input: {
608
609
  vaultConfig?: VaultServiceConfig;
609
610
  scopeVaultConfig?: VaultServiceConfig;
610
611
  }): Pick<ShareOptions, "entityContext" | "vaultConfig" | "privateFolderVaultConfig">;
611
- /**
612
- * Resolve the canonical person entity UID for the logged-in user. Used by
613
- * `hq sync {push,pull,now} --personal` to target the personal vault without
614
- * the caller needing to know the UID. Throws a clean error if the user has
615
- * no person entity (typically means they haven't run `hq onboard`).
616
- */
617
- export declare function resolveCanonicalPersonUid(vaultClient: PullAllVaultClient): Promise<string>;
612
+ export { resolveCanonicalPersonUid };
618
613
  /**
619
614
  * Keep `hq sync push --personal <path>` refused by default. Positional paths
620
615
  * bypass `computePersonalVaultPaths` and can send excluded `companies/`,
@@ -23,6 +23,7 @@ import * as fs from "fs";
23
23
  import * as path from "path";
24
24
  import { share, getStateDir, listJournals, createIgnoreFilter, VaultClient, computePersonalVaultPaths, PERSONAL_VAULT_JOURNAL_SLUG, resolvePullScope, readSyncProgress, syncDoctor, isTerminalIdentityRefusal, scopeLookupSkipMessage, SyncScopeLookupError, } from "@indigoai-us/hq-cloud";
25
25
  import { syncLeg, syncUnderOperationLock } from "../utils/sync-operation-lock.js";
26
+ import { pickCanonicalPerson, resolveCanonicalPersonUid } from "../lib/canonical-person.js";
26
27
  import { keyedSyncPull } from "./keyed-sync-pull.js";
27
28
  import { SYNC_WATCHDOG_EXIT_CODE, SYNC_WATCHDOG_REPORT_GRACE_MS, SyncWatchdogTimeoutError, createSnapshotProgressProbe, resolveSyncWatchdogLimits, withSyncWatchdog, } from "../utils/sync-watchdog.js";
28
29
  import { DEFAULT_HQ_ROOT, ensureCognitoToken, buildVaultConfig, IdentitySwapRefusal, cognitoCachePrincipalUid, isDefinitivePersonAuthRejection, isIdentitySwapRefusal, loadCachedTokens, refreshCachedSession, } from "../utils/cognito-session.js";
@@ -775,19 +776,6 @@ export function configureSyncLockTimeout(raw) {
775
776
  }
776
777
  process.env.HQ_OP_LOCK_TIMEOUT = String(seconds);
777
778
  }
778
- // Oldest-first by createdAt, ties broken by uid lexicographic — matches
779
- // `pickCanonicalPersonEntity` in @indigoai-us/hq-cloud so the CLI lands on
780
- // the same person bucket that `hq-sync-runner` picks.
781
- function pickCanonicalPerson(persons) {
782
- const onlyPersons = persons.filter((e) => e.type === "person");
783
- if (onlyPersons.length === 0)
784
- return null;
785
- return [...onlyPersons].sort((a, b) => {
786
- if (a.createdAt !== b.createdAt)
787
- return a.createdAt < b.createdAt ? -1 : 1;
788
- return a.uid < b.uid ? -1 : 1;
789
- })[0];
790
- }
791
779
  /**
792
780
  * Read the sessions-exclusion prefix set off a resolved {@link PullScope}.
793
781
  *
@@ -1223,22 +1211,7 @@ export function pushShareCredentials(input) {
1223
1211
  }
1224
1212
  return input.vaultConfig ? { vaultConfig: input.vaultConfig } : {};
1225
1213
  }
1226
- /**
1227
- * Resolve the canonical person entity UID for the logged-in user. Used by
1228
- * `hq sync {push,pull,now} --personal` to target the personal vault without
1229
- * the caller needing to know the UID. Throws a clean error if the user has
1230
- * no person entity (typically means they haven't run `hq onboard`).
1231
- */
1232
- export async function resolveCanonicalPersonUid(vaultClient) {
1233
- const persons = await vaultClient.listPersonEntities();
1234
- const pick = pickCanonicalPerson(persons);
1235
- if (!pick) {
1236
- throw new Error("No personal vault found for the logged-in user. Run `hq onboard` " +
1237
- "first, or check `hq whoami` to confirm you're signed in to the " +
1238
- "right account.");
1239
- }
1240
- return pick.uid;
1241
- }
1214
+ export { resolveCanonicalPersonUid };
1242
1215
  /**
1243
1216
  * Keep `hq sync push --personal <path>` refused by default. Positional paths
1244
1217
  * bypass `computePersonalVaultPaths` and can send excluded `companies/`,
@@ -1906,7 +1879,10 @@ export function registerCloudCommands(program) {
1906
1879
  companySlug: options.companySlug,
1907
1880
  token: process.env.HQ_API_KEY.trim(),
1908
1881
  }, { sync: keyedSyncPull });
1909
- console.log(`Keyed pull: ${result.filesDownloaded} files downloaded; unlisted local files preserved.`);
1882
+ const skips = Object.entries(result.skipped).filter(([, count]) => count > 0);
1883
+ const skipped = skips.reduce((sum, [, count]) => sum + count, 0);
1884
+ const skipText = skipped === 0 ? "none skipped" : `${skipped} skipped (${skips.map(([reason, count]) => `${reason} ${count}`).join(", ")})`;
1885
+ console.log(`Keyed pull: ${result.filesDownloaded} files downloaded; ${skipText}; unlisted local files preserved.`);
1910
1886
  return;
1911
1887
  }
1912
1888
  const skips = refuseSyncForOffVaults("pull", {
@@ -18,7 +18,28 @@ declare function safePath(value: unknown): value is string;
18
18
  declare function validChangeset(value: unknown): value is (string | {
19
19
  path: string;
20
20
  })[];
21
- declare function entriesUnder(root: string): string[];
21
+ /**
22
+ * The session's bound company, resolved as handoff-knowledge-commit.sh does.
23
+ * Only this one company's knowledge is ever looked at; other companies,
24
+ * including the other members of a multi-company lock, are never read.
25
+ *
26
+ * HQ_ACTIVE_COMPANY first ("personal" means no company). When it is empty, the
27
+ * primary `company_slug` of the session lock, read only for a session id taken
28
+ * from the environment; workspace/sessions/.current is never used because it
29
+ * can name another live session. The lock is read by running the HQ root's own
30
+ * `core/scripts/hq-session.sh --session-id <id> get company_slug`, as the
31
+ * helper does, so a missing library, a failing or slow script, or no bash
32
+ * leaves the session unbound. The slug must be a real (non-symlink) directory
33
+ * under companies/ and an exact-case key under `companies:` in
34
+ * companies/manifest.yaml. With no bound company, `skipReason` says why.
35
+ */
36
+ export type BoundKnowledgeCompany = {
37
+ company: string;
38
+ skipReason: string;
39
+ };
40
+ declare function companyIsRegistered(root: string, slug: string): boolean;
41
+ export declare function resolveBoundKnowledgeCompany(root: string, env?: NodeJS.ProcessEnv): BoundKnowledgeCompany;
42
+ declare function entriesUnder(root: string, boundCompany?: string): string[];
22
43
  declare function gitRoot(git: GitRunner, cwd: string): string;
23
44
  declare function statusPaths(git: GitRunner, repo: string, relative: string): {
24
45
  paths: string[];
@@ -32,11 +53,12 @@ declare function parseNulPaths(status: string): {
32
53
  paths: string[];
33
54
  originals: string[];
34
55
  };
35
- export declare function runHandoffKnowledgeCommit(args: readonly string[], cwd?: string, git?: GitRunner, buildFingerprint?: FingerprintBuilder): KnowledgeCommitResult;
56
+ export declare function runHandoffKnowledgeCommit(args: readonly string[], cwd?: string, git?: GitRunner, buildFingerprint?: FingerprintBuilder, env?: NodeJS.ProcessEnv): KnowledgeCommitResult;
36
57
  export declare const __handoffKnowledgeTest: {
37
58
  safePath: typeof safePath;
38
59
  validChangeset: typeof validChangeset;
39
60
  entriesUnder: typeof entriesUnder;
61
+ companyIsRegistered: typeof companyIsRegistered;
40
62
  statusPaths: typeof statusPaths;
41
63
  parseNulPaths: typeof parseNulPaths;
42
64
  expandTouched: typeof expandTouched;