@indigoai-us/hq-cli 5.345.255 → 5.345.258

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 (63) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/README.md +21 -0
  3. package/assets/scaffold/core/scripts/handoff-finalize.sh +981 -46
  4. package/assets/scaffold/core/scripts/hq-delegate-bundle.sh +51 -2
  5. package/assets/scaffold/core/scripts/hq-delegate-send.sh +49 -6
  6. package/assets/scaffold/core/scripts/hq-delegate-transfer.sh +20 -0
  7. package/assets/scaffold/core/scripts/hq-delegate-verify.sh +56 -10
  8. package/assets/scaffold/core/scripts/lib/fingerprint.sh +423 -0
  9. package/assets/scaffold/core/scripts/rebuild-companies-index.sh +10 -1
  10. package/assets/scaffold/core/scripts/rebuild-company-knowledge-index.sh +10 -1
  11. package/assets/scaffold/core/scripts/rebuild-projects-index.sh +10 -1
  12. package/assets/scaffold/core/scripts/register-project.sh +110 -19
  13. package/contracts/host-canary-release.json +7 -7
  14. package/dist/command-catalog.generated.d.ts +1 -1
  15. package/dist/command-catalog.generated.js +1 -1
  16. package/dist/commands/cloud.js +4 -1
  17. package/dist/commands/core-delegate-w1b.js +107 -16
  18. package/dist/commands/core-delegate.d.ts +7 -0
  19. package/dist/commands/core-delegate.js +66 -2
  20. package/dist/commands/core-handoff-fast.d.ts +1 -1
  21. package/dist/commands/core-handoff-fast.js +2 -2
  22. package/dist/commands/core-handoff.d.ts +3 -1
  23. package/dist/commands/core-handoff.js +1407 -177
  24. package/dist/commands/core-register-project-native.js +1 -1
  25. package/dist/commands/core.js +2 -2
  26. package/dist/commands/files.d.ts +2 -0
  27. package/dist/commands/files.js +34 -5
  28. package/dist/commands/keyed-sync-pull.d.ts +7 -3
  29. package/dist/commands/keyed-sync-pull.js +90 -22
  30. package/dist/commands/team-sync.js +1 -1
  31. package/dist/lib/company-skill-wrapper.js +72 -4
  32. package/dist/lib/daemon/requests.d.ts +14 -1
  33. package/dist/lib/daemon/requests.js +17 -3
  34. package/dist/lib/daemon/run.js +44 -2
  35. package/dist/lib/daemon/supervisor.d.ts +11 -0
  36. package/dist/lib/daemon/supervisor.js +33 -0
  37. package/dist/lib/daemon/sync-perf-telemetry.d.ts +85 -0
  38. package/dist/lib/daemon/sync-perf-telemetry.js +206 -0
  39. package/dist/lib/daemon/windows-relaunch.d.ts +55 -0
  40. package/dist/lib/daemon/windows-relaunch.js +72 -0
  41. package/dist/lib/doctor/checks/replay-recorder.js +3 -3
  42. package/dist/lib/flag-snapshot-file.d.ts +47 -1
  43. package/dist/lib/flag-snapshot-file.js +143 -20
  44. package/dist/lib/hook-engine/coverage.d.ts +82 -8
  45. package/dist/lib/hook-engine/coverage.js +192 -14
  46. package/dist/lib/index-render/companies.js +3 -2
  47. package/dist/lib/index-render/index.js +2 -1
  48. package/dist/lib/index-render/session-scope.d.ts +2 -3
  49. package/dist/lib/index-render/session-scope.js +2 -5
  50. package/dist/lib/index-render/shared.d.ts +7 -0
  51. package/dist/lib/index-render/shared.js +9 -0
  52. package/dist/lib/mesh/live/company-flag-refresh.js +2 -2
  53. package/dist/lib/work-context/windows-acl.d.ts +14 -0
  54. package/dist/lib/work-context/windows-acl.js +26 -0
  55. package/dist/utils/cli-telemetry.d.ts +26 -7
  56. package/dist/utils/cli-telemetry.js +70 -13
  57. package/dist/utils/git.js +1 -1
  58. package/dist/utils/resident-package-preload.js +4 -0
  59. package/dist/utils/sync-perf-telemetry-flag.d.ts +26 -0
  60. package/dist/utils/sync-perf-telemetry-flag.js +32 -0
  61. package/dist/utils/telemetry-opt-out.d.ts +13 -0
  62. package/dist/utils/telemetry-opt-out.js +19 -0
  63. package/package.json +8 -8
@@ -15,8 +15,10 @@
15
15
  # --files-touched-json '["path1","path2"]' \
16
16
  # --files-touched-json-file workspace/threads/.changeset.json \
17
17
  # --learnings-json '[]' \
18
+ # --deficiencies-json workspace/threads/.handoff-tmp/deficiencies.json \
18
19
  # --tags-json '["handoff"]' \
19
20
  # --slug "handoff-short-tag" \
21
+ # --company "owner-slug" \
20
22
  # --next-command "/startwork"
21
23
  #
22
24
  # The changeset (files-touched) may be supplied inline via --files-touched-json
@@ -47,14 +49,55 @@
47
49
  # incomplete even if a commit landed for the rest; exit 4.
48
50
  # This is the shape a held .git/index.lock takes.
49
51
  # stage_failures lists paths git add rejected for a reason other than gitignore.
52
+ # On a stage failure, hq_commit_error carries git's first stderr line, and
53
+ # stage_failure_class classifies it: "permission" (the process may not write
54
+ # .git, e.g. a sandboxed run; re-run outside the sandbox), "index-lock" (another
55
+ # git process holds .git/index.lock), or "other". It is "" when nothing failed.
56
+ # index_lock_waits counts the retries of git index operations that waited for
57
+ # another process to release .git/index.lock (feedback 29213da4). The wait is
58
+ # bounded by HQ_HANDOFF_INDEX_LOCK_WAIT_SECONDS (default 60) so a long
59
+ # `git status` from the desktop app or Xcode is waited out (thread
60
+ # T-20261022-140549).
61
+ # stale_index_lock_removed is true when the run deleted an orphaned
62
+ # .git/index.lock (older than HQ_HANDOFF_STALE_LOCK_SECONDS, default 600, with
63
+ # no git process older than it) and re-ran the stage; see hq_clear_stale_index_lock.
64
+ #
65
+ # --deficiencies-json <path> takes a file holding the Step 2 environment
66
+ # deficiencies array (lever, kind, severity, summary, evidence, proposed_fix).
67
+ # Items whose evidence is missing or blank are dropped before storage. A
68
+ # missing file is a hard error (exit 3). An empty path warns and stores an
69
+ # empty array instead of looking like the flag was omitted.
70
+ # The thread also gets one system_info
71
+ # block (hq_version, hq_cli_version, host, os, hooks_enforced) with no paths,
72
+ # emails, or tokens.
50
73
  #
51
74
  # Exit codes: 0 ok · 2 bad argument · 3 changeset file missing · 4 handoff not
52
- # durable (commit refused or paths unstageable).
75
+ # durable (commit refused or paths unstageable) · 5 company mirror refused
76
+ # (--company in an unbound session, or the mirror hook failed) · 6 jq is not
77
+ # installed (checked before anything is written). A company mirror miss or
78
+ # failure still writes the canonical thread and handoff.json pointer
79
+ # (feedback_0ee565a1, feedback_4140f6ba, feedback_1039db92), then exits 5 so
80
+ # the caller does not treat the refused mirror as success.
53
81
 
54
82
  set -euo pipefail
55
83
 
84
+ # jq builds every JSON file this script writes. Check for it before the first
85
+ # mkdir or write so a host without jq gets one clear message and an untouched
86
+ # workspace, instead of a half-written handoff and "jq: command not found".
87
+ if ! command -v jq >/dev/null 2>&1; then
88
+ echo "handoff-finalize: jq is required but was not found on PATH. Nothing was written. Install jq (macOS: brew install jq; Debian/Ubuntu: sudo apt-get install jq; Windows: winget install jqlang.jq), then re-run /handoff." >&2
89
+ exit 6
90
+ fi
91
+
56
92
  HQ_ROOT="${HQ_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)}"
57
93
  cd "$HQ_ROOT"
94
+ # Keep both spellings of the root. The physical one is the working directory
95
+ # for git; the logical one (a symlinked checkout, macOS /var -> /private/var)
96
+ # is what absolute changeset paths from the caller are prefixed with. Both are
97
+ # stripped when paths are relativized, so a company reached through the alias
98
+ # prefix still counts when the handoff's company scope is derived
99
+ # (feedback 7a3e83c2).
100
+ HQ_ROOT_LOGICAL="$(pwd -L)"
58
101
  HQ_ROOT="$(pwd -P)"
59
102
  HANDOFF_SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
60
103
  source "$HANDOFF_SCRIPT_DIR/lib/session-id.sh"
@@ -84,12 +127,17 @@ NEXT_STEPS_JSON="[]"
84
127
  FILES_TOUCHED_JSON="[]"
85
128
  FILES_TOUCHED_JSON_FILE=""
86
129
  LEARNINGS_JSON="[]"
130
+ LEARNINGS_JSON_FILE=""
131
+ DEFICIENCIES_JSON_FILE=""
132
+ DEFICIENCIES_JSON_GIVEN=0
87
133
  TAGS_JSON='["handoff"]'
88
134
  SLUG="handoff"
89
135
  NEXT_COMMAND="__auto__"
136
+ OWNER_COMPANY=""
90
137
 
91
138
  while [[ $# -gt 0 ]]; do
92
139
  case "$1" in
140
+ --company) OWNER_COMPANY="$2"; shift 2 ;;
93
141
  --title) TITLE="$2"; shift 2 ;;
94
142
  --summary) SUMMARY="$2"; shift 2 ;;
95
143
  --message) MESSAGE="$2"; shift 2 ;;
@@ -97,6 +145,8 @@ while [[ $# -gt 0 ]]; do
97
145
  --files-touched-json) FILES_TOUCHED_JSON="$2"; shift 2 ;;
98
146
  --files-touched-json-file) FILES_TOUCHED_JSON_FILE="$2"; shift 2 ;;
99
147
  --learnings-json) LEARNINGS_JSON="$2"; shift 2 ;;
148
+ --learnings-json-file) LEARNINGS_JSON_FILE="$2"; shift 2 ;;
149
+ --deficiencies-json) DEFICIENCIES_JSON_GIVEN=1; DEFICIENCIES_JSON_FILE="$2"; shift 2 ;;
100
150
  --tags-json) TAGS_JSON="$2"; shift 2 ;;
101
151
  --slug) SLUG="$2"; shift 2 ;;
102
152
  --next-command) NEXT_COMMAND="$2"; shift 2 ;;
@@ -104,6 +154,34 @@ while [[ $# -gt 0 ]]; do
104
154
  esac
105
155
  done
106
156
 
157
+ # Validate inline JSON before creating even the temporary handoff directory.
158
+ # Feed values on stdin to retain the large-changeset argv limit protection.
159
+ validate_json_arg() {
160
+ local flag="$1" value="$2"
161
+ if ! printf '%s' "$value" | jq -e -s 'length == 1' >/dev/null 2>&1; then
162
+ printf 'handoff-finalize: %s is not valid JSON (expected one JSON value). Nothing was written.\n' "$flag" >&2
163
+ exit 2
164
+ fi
165
+ }
166
+ validate_json_arg --next-steps-json "$NEXT_STEPS_JSON"
167
+ validate_json_arg --tags-json "$TAGS_JSON"
168
+ # The file form takes precedence, so do not reject an unused inline value.
169
+ if [[ -z "$LEARNINGS_JSON_FILE" ]]; then
170
+ validate_json_arg --learnings-json "$LEARNINGS_JSON"
171
+ else
172
+ if [[ ! -f "$LEARNINGS_JSON_FILE" ]]; then
173
+ echo "handoff-finalize: --learnings-json-file not found: $LEARNINGS_JSON_FILE" >&2
174
+ exit 3
175
+ fi
176
+ if ! jq -e -s 'length == 1' "$LEARNINGS_JSON_FILE" >/dev/null 2>&1; then
177
+ printf 'handoff-finalize: --learnings-json-file is not valid JSON (expected one JSON value). Nothing was written.\n' >&2
178
+ exit 2
179
+ fi
180
+ fi
181
+ if [[ -z "$FILES_TOUCHED_JSON_FILE" ]]; then
182
+ validate_json_arg --files-touched-json "$FILES_TOUCHED_JSON"
183
+ fi
184
+
107
185
  # -------- temp-file registry for off-argv JSON --------
108
186
  # The Windows argv-overflow fix: any JSON value that scales with the changeset
109
187
  # (the changeset itself, and the staged/skipped/committed path lists and status
@@ -162,6 +240,19 @@ else
162
240
  printf '%s' "$FILES_TOUCHED_JSON" > "$FILES_TOUCHED_FILE"
163
241
  fi
164
242
 
243
+ # --learnings-json-file <path> wins over inline --learnings-json; materialize
244
+ # inline JSON to a temp file so the thread emitter always reads off-argv.
245
+ if [[ -n "$LEARNINGS_JSON_FILE" ]]; then
246
+ LEARNINGS_FILE="$LEARNINGS_JSON_FILE"
247
+ case "$LEARNINGS_FILE" in
248
+ /*) : ;;
249
+ *) LEARNINGS_FILE="$PWD/$LEARNINGS_FILE" ;;
250
+ esac
251
+ else
252
+ new_tmp LEARNINGS_FILE
253
+ printf '%s' "$LEARNINGS_JSON" > "$LEARNINGS_FILE"
254
+ fi
255
+
165
256
  # -------- changeset path extraction / validation --------
166
257
  # Skipped paths accumulate as NDJSON on disk from the first record_skip — never
167
258
  # rebuild a growing JSON document via jq argv/here-string (thousands of skips
@@ -198,20 +289,111 @@ is_sensitive_path() {
198
289
  esac
199
290
  }
200
291
 
201
- normalize_rel_path() {
202
- local raw="$1"
203
- local rel="$raw"
292
+ # canonical_rel_path <raw> — print the one canonical HQ-relative spelling of a
293
+ # changeset path, or return 1 when it is unsafe. The same value is used for
294
+ # validation, company detection, and git add/commit, so no later consumer can
295
+ # read a different path than the one that was checked.
296
+ # - absolute paths must sit under the physical or logical HQ root;
297
+ # - repeated slashes, "./" segments and a trailing "/" or "/." are folded;
298
+ # - any ".." component (leading, inner or trailing) is refused outright;
299
+ # - the parent directory is resolved with symlinks (pwd -P) and must stay
300
+ # inside the physical HQ root; a symlink leaf must point inside the root
301
+ # and inside the same company folder as the link itself;
302
+ # - "companies" itself (every company at once) is refused.
303
+ # hq_first_seg_spoofed <rel> — true when the first segment is a case variant
304
+ # (not the exact spelling) of "companies" or ".git".
305
+ # The filesystem decides, not the spelling: a name that resolves to the same
306
+ # directory as companies/ or .git/ (ASCII case variants, Unicode case folding
307
+ # such as U+017F on APFS) but is not the exact name is a spoof.
308
+ hq_first_seg_spoofed() {
309
+ local first="${1%%/*}" lower real
310
+ lower="$(printf '%s' "$first" | tr '[:upper:]' '[:lower:]')"
311
+ [[ ( "$lower" == companies || "$lower" == .git ) && "$first" != "$lower" ]] && return 0
312
+ for real in companies .git; do
313
+ [[ "$first" == "$real" ]] && continue
314
+ [[ -e "$HQ_ROOT/$first" && "$HQ_ROOT/$first" -ef "$HQ_ROOT/$real" ]] && return 0
315
+ done
316
+ return 1
317
+ }
318
+
319
+ canonical_rel_path() {
320
+ local raw="$1" rel seg out="" parent leaf rest="" phys target tco lco
321
+ rel="$raw"
204
322
  if [[ "$raw" == "$HQ_ROOT/"* ]]; then
205
323
  rel="${raw#"$HQ_ROOT/"}"
324
+ elif [[ "$raw" == "$HQ_ROOT_LOGICAL/"* ]]; then
325
+ rel="${raw#"$HQ_ROOT_LOGICAL/"}"
206
326
  elif [[ "$raw" == /* ]]; then
207
327
  return 1
208
328
  fi
209
- rel="${rel#./}"
329
+ [[ "$rel" == -* ]] && return 1
330
+ local IFS=/
331
+ local -a parts
332
+ read -r -a parts <<< "$rel"
333
+ unset IFS
334
+ for seg in ${parts[@]+"${parts[@]}"}; do
335
+ case "$seg" in
336
+ ''|.) continue ;;
337
+ ..) return 1 ;;
338
+ esac
339
+ out="${out:+$out/}$seg"
340
+ done
341
+ rel="$out"
210
342
  [[ -z "$rel" ]] && return 1
211
- [[ "$rel" == -* || "$rel" == ".." || "$rel" == ../* || "$rel" == */../* || "$rel" == .git || "$rel" == .git/* ]] && return 1
343
+ [[ "$rel" == -* || "$rel" == .git || "$rel" == .git/* || "$rel" == companies ]] && return 1
344
+ # Resolve the deepest existing ancestor physically; deleted paths keep their
345
+ # missing tail verbatim (it has no symlinks to resolve).
346
+ parent="${rel%/*}"; leaf="${rel##*/}"
347
+ [[ "$parent" == "$rel" ]] && parent=""
348
+ while [[ -n "$parent" && ! -d "$HQ_ROOT/$parent" ]]; do
349
+ rest="${parent##*/}${rest:+/$rest}"
350
+ if [[ "$parent" == */* ]]; then parent="${parent%/*}"; else parent=""; fi
351
+ done
352
+ phys="$(cd "$HQ_ROOT/${parent:-.}" 2>/dev/null && pwd -P)" || return 1
353
+ if [[ "$phys" == "$HQ_ROOT" ]]; then
354
+ out=""
355
+ elif [[ "$phys" == "$HQ_ROOT/"* ]]; then
356
+ out="${phys#"$HQ_ROOT/"}"
357
+ else
358
+ return 1
359
+ fi
360
+ [[ -n "$rest" ]] && out="${out:+$out/}$rest"
361
+ rel="${out:+$out/}$leaf"
362
+ [[ "$rel" == .git || "$rel" == .git/* || "$rel" == companies ]] && return 1
363
+ # Case-insensitive filesystems (macOS default) keep the typed case through
364
+ # pwd -P, and git (core.ignorecase) stages the real file. Refuse any other
365
+ # spelling of the top-level companies or .git folder so company detection
366
+ # cannot be dodged with "Companies/<sibling>/...".
367
+ hq_first_seg_spoofed "$rel" && return 1
368
+ if [[ -L "$HQ_ROOT/$rel" ]]; then
369
+ if [[ -d "$HQ_ROOT/$rel" ]]; then
370
+ target="$(cd "$HQ_ROOT/$rel" 2>/dev/null && pwd -P)" || return 1
371
+ elif [[ -e "$HQ_ROOT/$rel" ]]; then
372
+ target="$(cd "$(dirname "$HQ_ROOT/$rel")" && cd "$(dirname "$(readlink "$HQ_ROOT/$rel")")" 2>/dev/null && pwd -P)/$(basename "$(readlink "$HQ_ROOT/$rel")")" || return 1
373
+ else
374
+ return 1
375
+ fi
376
+ [[ "$target" == "$HQ_ROOT" || "$target" == "$HQ_ROOT/"* ]] || return 1
377
+ target="${target#"$HQ_ROOT"}"; target="${target#/}"
378
+ hq_first_seg_spoofed "$target" && return 1
379
+ lco=""; tco=""
380
+ [[ "$rel" == companies/*/* ]] && { lco="${rel#companies/}"; lco="${lco%%/*}"; }
381
+ [[ "$target" == companies || "$target" == companies/* ]] && { tco="${target#companies}"; tco="${tco#/}"; tco="${tco%%/*}"; [[ -n "$tco" ]] || return 1; }
382
+ [[ "$tco" == "$lco" ]] || return 1
383
+ fi
212
384
  printf '%s\n' "$rel"
213
385
  }
214
386
 
387
+ # company_of_rel <canonical-rel> — company slug that owns the path, or empty.
388
+ company_of_rel() {
389
+ local r="$1" co
390
+ [[ "$r" == companies/* ]] || return 0
391
+ co="${r#companies/}"; co="${co%%/*}"
392
+ printf '%s' "$co"
393
+ }
394
+
395
+ normalize_rel_path() { canonical_rel_path "$1"; }
396
+
215
397
  while IFS=$'\t' read -r raw_path deleted_flag; do
216
398
  [[ -z "${raw_path:-}" ]] && continue
217
399
  if ! rel_path=$(normalize_rel_path "$raw_path"); then
@@ -224,7 +406,7 @@ while IFS=$'\t' read -r raw_path deleted_flag; do
224
406
  fi
225
407
  if [[ ! -e "$rel_path" ]]; then
226
408
  if [[ "$HAS_GIT_CHECKOUT" == "true" && "$deleted_flag" == "true" ]] \
227
- && git ls-files --error-unmatch "$rel_path" >/dev/null 2>&1; then
409
+ && GIT_LITERAL_PATHSPECS=1 git ls-files --error-unmatch -- "$rel_path" >/dev/null 2>&1; then
228
410
  SAFE_STAGE_PATHS+=("$rel_path")
229
411
  else
230
412
  record_skip "$rel_path" "missing"
@@ -245,14 +427,29 @@ done < <(
245
427
  ' "$FILES_TOUCHED_FILE" 2>/dev/null || true
246
428
  )
247
429
 
248
- # Company workspace mirrors are scoped from the already-validated changeset,
249
- # never from ambient repository state. A handoff can legitimately touch more
250
- # than one company, so preserve all unique slugs in durable thread metadata.
251
- MIRROR_COMPANIES_JSON=$(printf '%s\n' "${SAFE_STAGE_PATHS[@]:-}" | jq -R -s -c '
252
- split("\n")
253
- | [ .[] | select(length > 0) | try (capture("^companies/(?<company>[a-z][a-z0-9_-]*)/").company) ]
254
- | unique
255
- ' 2>/dev/null || printf '[]')
430
+ # Company workspace mirrors have one owner. --company is explicit; otherwise the
431
+ # session binding is used. Never treat the list of touched company paths as
432
+ # recipients. Inspect the complete handoff paths, including skipped paths, so a
433
+ # missing or excluded file cannot hide that the handoff spans multiple companies.
434
+ TOUCHED_COMPANIES_JSON=$(jq -c --arg hq_root "$HQ_ROOT" --arg hq_root_logical "$HQ_ROOT_LOGICAL" '
435
+ [ (if type == "array" then .[] else empty end)
436
+ | (if type == "string" then . elif type == "object" and (.path | type) == "string" then .path else "" end)
437
+ | (if startswith($hq_root + "/") then .[(($hq_root | length) + 1):]
438
+ elif startswith($hq_root_logical + "/") then .[(($hq_root_logical | length) + 1):]
439
+ else . end)
440
+ | sub("^\\./"; "")
441
+ | (try capture("^companies/(?<company>[a-z0-9][a-z0-9_-]*)/").company catch null)
442
+ | select(type == "string")
443
+ ] | unique
444
+ ' "$FILES_TOUCHED_FILE" 2>/dev/null || printf '[]')
445
+ # Union in the companies of the canonical stage paths, so a path that only
446
+ # reaches a company after canonicalisation (symlinked parent) still counts.
447
+ for _canon in ${SAFE_STAGE_PATHS[@]+"${SAFE_STAGE_PATHS[@]}"}; do
448
+ _co="$(company_of_rel "$_canon")"
449
+ [[ -n "$_co" ]] || continue
450
+ TOUCHED_COMPANIES_JSON="$(jq -c --arg c "$_co" '. + [$c] | unique' <<< "$TOUCHED_COMPANIES_JSON")"
451
+ done
452
+ MIRROR_COMPANIES_JSON='[]'
256
453
 
257
454
  bound_session_company() {
258
455
  local session_id metadata company
@@ -261,13 +458,110 @@ bound_session_company() {
261
458
  metadata="$HQ_ROOT/workspace/sessions/$session_id/meta.yaml"
262
459
  [[ -r "$metadata" ]] || return 0
263
460
  company="$(awk '$1 == "company_slug:" { sub(/^[^:]+:[[:space:]]*/, ""); gsub(/^"|"$/, ""); print; exit }' "$metadata" 2>/dev/null || true)"
264
- [[ "$company" =~ ^[a-z][a-z0-9_-]*$ ]] || return 0
461
+ [[ "$company" =~ ^[a-z0-9][a-z0-9_-]*$ ]] || return 0
265
462
  printf '%s' "$company"
266
463
  }
267
464
 
465
+ # True when the company is in the session's locked set (the primary plus any
466
+ # added with hq-session.sh add company), not only the first-bound company.
467
+ owner_in_locked_set() {
468
+ local want="$1" sid locked cap
469
+ sid="$(session_id_resolve "$HQ_ROOT")"
470
+ [[ -n "$sid" ]] || return 1
471
+ cap="$HQ_ROOT/workspace/sessions/$sid/scope-capability.json"
472
+ [[ -f "$cap" && -f "$HQ_ROOT/core/scripts/lib/session-scope-capability.sh" ]] || return 1
473
+ # shellcheck source=lib/session-scope-capability.sh
474
+ . "$HQ_ROOT/core/scripts/lib/session-scope-capability.sh"
475
+ locked="$(session_scope_read_companies "$HQ_ROOT" "$sid" 2>/dev/null || true)"
476
+ grep -qxF -- "$want" <<< "$locked"
477
+ }
478
+
268
479
  BOUND_SESSION_COMPANY="$(bound_session_company)"
269
- if [[ -n "$BOUND_SESSION_COMPANY" && -d "companies/$BOUND_SESSION_COMPANY" ]]; then
270
- MIRROR_COMPANIES_JSON="$(jq -c --arg company "$BOUND_SESSION_COMPANY" '. + [$company] | unique' <<< "$MIRROR_COMPANIES_JSON")"
480
+ if [[ -n "$OWNER_COMPANY" ]]; then
481
+ if [[ ! "$OWNER_COMPANY" =~ ^[a-z0-9][a-z0-9_-]*$ ]] || [[ ! -d "$HQ_ROOT/companies/$OWNER_COMPANY" ]]; then
482
+ echo "handoff-finalize: invalid or missing owner company: $OWNER_COMPANY" >&2
483
+ exit 2
484
+ fi
485
+ if [[ -n "$BOUND_SESSION_COMPANY" && "$BOUND_SESSION_COMPANY" != "$OWNER_COMPANY" ]] \
486
+ && ! owner_in_locked_set "$OWNER_COMPANY"; then
487
+ echo "handoff-finalize: --company $OWNER_COMPANY does not match the bound session company $BOUND_SESSION_COMPANY" >&2
488
+ exit 2
489
+ fi
490
+ BOUND_SESSION_COMPANY="$OWNER_COMPANY"
491
+ fi
492
+ SESSION_LOCKED_COMPANIES_JSON='[]'
493
+ if [[ -n "$BOUND_SESSION_COMPANY" ]]; then
494
+ SESSION_ID_FOR_COMPANIES="$(session_id_resolve "$HQ_ROOT")"
495
+ SESSION_CAP="$HQ_ROOT/workspace/sessions/$SESSION_ID_FOR_COMPANIES/scope-capability.json"
496
+ LOCKED_COMPANIES="$BOUND_SESSION_COMPANY"
497
+ if [[ -f "$SESSION_CAP" && -f "$HQ_ROOT/core/scripts/lib/session-scope-capability.sh" ]]; then
498
+ # shellcheck source=lib/session-scope-capability.sh
499
+ . "$HQ_ROOT/core/scripts/lib/session-scope-capability.sh"
500
+ LOCKED_COMPANIES="$(session_scope_read_companies "$HQ_ROOT" "$SESSION_ID_FOR_COMPANIES" 2>/dev/null | paste -sd, -)"
501
+ fi
502
+ [[ -n "$LOCKED_COMPANIES" ]] && SESSION_LOCKED_COMPANIES_JSON="$(jq -cn --arg slugs "$LOCKED_COMPANIES" '$slugs | split(",") | map(select(length > 0))')"
503
+ fi
504
+ # A handoff with an owner may only stage paths in companies it owns (the bound
505
+ # company plus the session's locked set). Anything else is refused, never
506
+ # committed under this owner's label.
507
+ if [[ -n "$BOUND_SESSION_COMPANY" ]]; then
508
+ _owned=",${LOCKED_COMPANIES:-$BOUND_SESSION_COMPANY},$BOUND_SESSION_COMPANY,"
509
+ _kept=()
510
+ for _canon in ${SAFE_STAGE_PATHS[@]+"${SAFE_STAGE_PATHS[@]}"}; do
511
+ _co="$(company_of_rel "$_canon")"
512
+ if [[ -n "$_co" && "$_owned" != *",$_co,"* ]]; then
513
+ record_skip "$_canon" "foreign-company"
514
+ continue
515
+ fi
516
+ _kept+=("$_canon")
517
+ done
518
+ SAFE_STAGE_PATHS=(${_kept[@]+"${_kept[@]}"})
519
+ else
520
+ # No owner: a handoff may still carry one company's paths, but never two
521
+ # companies in one commit with nobody to own it.
522
+ _seen=""
523
+ for _canon in ${SAFE_STAGE_PATHS[@]+"${SAFE_STAGE_PATHS[@]}"}; do
524
+ _co="$(company_of_rel "$_canon")"
525
+ [[ -n "$_co" && ",$_seen," != *",$_co,"* ]] && _seen="${_seen:+$_seen,}$_co"
526
+ done
527
+ if [[ "$_seen" == *,* ]]; then
528
+ _kept=()
529
+ for _canon in ${SAFE_STAGE_PATHS[@]+"${SAFE_STAGE_PATHS[@]}"}; do
530
+ if [[ -n "$(company_of_rel "$_canon")" ]]; then
531
+ record_skip "$_canon" "multi-company-no-owner"
532
+ continue
533
+ fi
534
+ _kept+=("$_canon")
535
+ done
536
+ SAFE_STAGE_PATHS=(${_kept[@]+"${_kept[@]}"})
537
+ fi
538
+ fi
539
+ TOUCHED_COMPANY_COUNT="$(jq 'length' <<< "$TOUCHED_COMPANIES_JSON")"
540
+ if [[ "$TOUCHED_COMPANY_COUNT" -gt 1 ]]; then
541
+ printf 'handoff-finalize: company mirror skipped (handoff spans multiple companies)\n' >&2
542
+ elif [[ -z "$BOUND_SESSION_COMPANY" || ! -d "companies/$BOUND_SESSION_COMPANY" ]]; then
543
+ printf 'handoff-finalize: company mirror skipped (no bound company for this session)\n' >&2
544
+ elif [[ "$TOUCHED_COMPANY_COUNT" -eq 1 ]] && \
545
+ [[ "$(jq -r '.[0]' <<< "$TOUCHED_COMPANIES_JSON")" != "$BOUND_SESSION_COMPANY" ]]; then
546
+ printf 'handoff-finalize: company mirror skipped (handoff paths do not match the bound company)\n' >&2
547
+ elif [[ -z "$OWNER_COMPANY" && "$TOUCHED_COMPANY_COUNT" -eq 0 ]] && \
548
+ [[ "$(jq -r --arg hq_root "$HQ_ROOT" --arg hq_root_logical "$HQ_ROOT_LOGICAL" '
549
+ [ (if type == "array" then .[] else empty end)
550
+ | (if type == "string" then . elif type == "object" and (.path | type) == "string" then .path else "" end)
551
+ | select(. != "")
552
+ | (if startswith($hq_root + "/") then .[(($hq_root | length) + 1):]
553
+ elif startswith($hq_root_logical + "/") then .[(($hq_root_logical | length) + 1):]
554
+ else . end)
555
+ | sub("^\\./"; "")
556
+ ] | if length > 0 and (map(select(startswith("companies/") or startswith("repos/"))) | length) == 0
557
+ then "personal" else "other" end' <<< "$FILES_TOUCHED_JSON" 2>/dev/null || printf 'other')" == "personal" ]]; then
558
+ # Files were touched but none under companies/ or repos/: personal or
559
+ # HQ-only work. Do not stamp or mirror it into the bound company
560
+ # (feedback_c8465cde). Repo code still follows the bound company. Pass
561
+ # --company to file a handoff under a company on purpose.
562
+ printf 'handoff-finalize: company mirror skipped (handoff touched no company or repo paths; pass --company %s to file it there)\n' "$BOUND_SESSION_COMPANY" >&2
563
+ else
564
+ MIRROR_COMPANIES_JSON="$(jq -cn --arg company "$BOUND_SESSION_COMPANY" '[$company]')"
271
565
  fi
272
566
 
273
567
  # -------- bg git reap (if launched by caller) --------
@@ -285,9 +579,33 @@ fi
285
579
 
286
580
  # -------- thread file --------
287
581
  TS=$(date -u +%Y%m%dT%H%M%SZ)
582
+ # The session that writes this handoff. Recorded on the thread and the pointer
583
+ # so the archive check can recognize its own handoff after another session's
584
+ # finalize moved the shared pointer on.
585
+ HANDOFF_SESSION_ID="$(session_id_resolve "$HQ_ROOT" 2>/dev/null || true)"
288
586
  DAY=$(date +%Y%m%d)
289
587
  HM=$(date +%H%M%S)
290
588
  THREAD_ID="T-${DAY}-${HM}-${SLUG}"
589
+ # Thread ids must be unique: /resumework selects by full thread id, and two
590
+ # handoffs in the same second with the same slug would otherwise share one id
591
+ # and overwrite each other (feedback_b75f1436). Probe the local thread store,
592
+ # its archive and the session's company mirrors for an existing id and append
593
+ # -2, -3, ... until free.
594
+ thread_id_taken() {
595
+ local candidate="$1" co
596
+ [[ -e "workspace/threads/${candidate}.json" ]] && return 0
597
+ [[ -n "$(find workspace/threads/archive -name "${candidate}.json" -print -quit 2>/dev/null)" ]] && return 0
598
+ local locked="${LOCKED_COMPANIES:-}"
599
+ for co in ${locked//,/ }; do
600
+ [[ -n "$co" && -e "companies/${co}/workspace/sessions/${candidate}.json" ]] && return 0
601
+ done
602
+ return 1
603
+ }
604
+ if thread_id_taken "$THREAD_ID"; then
605
+ n=2
606
+ while thread_id_taken "${THREAD_ID}-${n}"; do n=$((n + 1)); done
607
+ THREAD_ID="${THREAD_ID}-${n}"
608
+ fi
291
609
  THREAD_PATH="workspace/threads/${THREAD_ID}.json"
292
610
  CHANGESET_PATH="workspace/threads/${THREAD_ID}.changeset.json"
293
611
 
@@ -314,19 +632,73 @@ else
314
632
  printf '[]' > "$STAGED_PATHS_FILE"
315
633
  fi
316
634
 
635
+ # -------- environment deficiencies + system_info --------
636
+ DEFICIENCIES_JSON="[]"
637
+ if [[ "$DEFICIENCIES_JSON_GIVEN" -eq 1 && -z "$DEFICIENCIES_JSON_FILE" ]]; then
638
+ echo "handoff-finalize: --deficiencies-json value is empty, expected a file path — deficiencies will be empty" >&2
639
+ fi
640
+ if [[ -n "$DEFICIENCIES_JSON_FILE" ]]; then
641
+ if [[ ! -f "$DEFICIENCIES_JSON_FILE" ]]; then
642
+ echo "handoff-finalize: deficiencies file not found: $DEFICIENCIES_JSON_FILE" >&2
643
+ exit 3
644
+ fi
645
+ if ! DEFICIENCIES_JSON="$(jq -c '
646
+ if type == "array" then . else [] end
647
+ | map(select(type == "object"
648
+ and ((.evidence // "") | type) == "string"
649
+ and ((.evidence // "") | gsub("^\\s+|\\s+$"; "")) != ""))
650
+ | map({lever, kind, severity, summary, evidence, proposed_fix})
651
+ ' "$DEFICIENCIES_JSON_FILE" 2>/dev/null)"; then
652
+ echo "handoff-finalize: deficiencies file is not valid JSON: $DEFICIENCIES_JSON_FILE" >&2
653
+ exit 2
654
+ fi
655
+ fi
656
+
657
+ SYSINFO_HQ_VERSION="$(sed -n 's/^hqVersion:[[:space:]]*"\{0,1\}\([^"]*\)"\{0,1\}[[:space:]]*$/\1/p' core/core.yaml 2>/dev/null | head -n 1 || true)"
658
+ SYSINFO_CLI_VERSION=""
659
+ if command -v hq >/dev/null 2>&1; then
660
+ SYSINFO_CLI_VERSION="$(hq --version 2>/dev/null | head -n 1 | grep -oE '[0-9]+\.[0-9]+\.[0-9]+[0-9A-Za-z.+-]*' | head -n 1 || true)"
661
+ fi
662
+ case "${HQ_HANDOFF_HOST:-${CLAUDE_CODE_ENTRYPOINT:-cli}}" in
663
+ sdk*) SYSINFO_HOST="sdk" ;;
664
+ *desktop*) SYSINFO_HOST="desktop" ;;
665
+ *) SYSINFO_HOST="cli" ;;
666
+ esac
667
+ SYSINFO_OS="$(uname -s 2>/dev/null | tr '[:upper:]' '[:lower:]' || true)"
668
+ SYSINFO_HOOKS="false"
669
+ if [[ -f core/scripts/check-hq-hooks.sh ]] && \
670
+ bash core/scripts/check-hq-hooks.sh --root "$HQ_ROOT" --require-ledger >/dev/null 2>&1; then
671
+ SYSINFO_HOOKS="true"
672
+ fi
673
+ SYSTEM_INFO_JSON="$(jq -cn \
674
+ --arg hq_version "$SYSINFO_HQ_VERSION" \
675
+ --arg hq_cli_version "$SYSINFO_CLI_VERSION" \
676
+ --arg host "$SYSINFO_HOST" \
677
+ --arg os "$SYSINFO_OS" \
678
+ --argjson hooks_enforced "$SYSINFO_HOOKS" \
679
+ '{hq_version: $hq_version, hq_cli_version: $hq_cli_version, host: $host, os: $os, hooks_enforced: $hooks_enforced}')"
680
+
317
681
  mkdir -p workspace/threads
318
682
  # Every next step carries an id and a closure status (2026-09-07). Handoffs
319
683
  # used to record steps with no way to close one; an audit found a task copied
320
684
  # forward through three consecutive handoffs and never started. Ids are
321
685
  # `<thread_id>#<n>`; status starts "open" and is closed by
322
686
  # core/scripts/handoff-open-steps.sh close. Strings and {step:...} objects are
323
- # both accepted; already-normalized objects keep their fields.
687
+ # both accepted; already-normalized objects keep their fields. Objects that
688
+ # used content or text instead of step are rewritten to step so list/close
689
+ # do not print null. An object that already has step keeps its text and
690
+ # content fields.
324
691
  NEXT_STEPS_NORMALIZED_JSON="$(jq -c --arg tid "$THREAD_ID" '
325
692
  to_entries | map(.key as $k |
326
693
  (if (.value|type) == "string" then {step: .value} else .value end)
327
694
  | .id = (.id // ($tid + "#" + (($k + 1)|tostring)))
328
695
  | .status = (.status // "open")
329
696
  ) | map(del(.key))' <<<"$NEXT_STEPS_JSON" 2>/dev/null || printf '%s' "$NEXT_STEPS_JSON")"
697
+ NEXT_STEPS_NORMALIZED_JSON="$(printf '%s' "$NEXT_STEPS_NORMALIZED_JSON" | jq -c 'map(if .step == null then
698
+ (if .["text"] != null then .step = .["text"] | del(.["text"])
699
+ elif .["content"] != null then .step = .["content"] | del(.["content"])
700
+ else .step = "" end)
701
+ else . end)' 2>/dev/null || printf '%s' "$NEXT_STEPS_NORMALIZED_JSON")"
330
702
 
331
703
  jq -n \
332
704
  --arg thread_id "$THREAD_ID" \
@@ -341,15 +713,20 @@ jq -n \
341
713
  --arg title "$TITLE" \
342
714
  --argjson next_steps "$NEXT_STEPS_NORMALIZED_JSON" \
343
715
  --slurpfile files_touched "$FILES_TOUCHED_FILE" \
344
- --argjson learnings "$LEARNINGS_JSON" \
716
+ --slurpfile learnings "$LEARNINGS_FILE" \
717
+ --argjson deficiencies "$DEFICIENCIES_JSON" \
718
+ --argjson system_info "$SYSTEM_INFO_JSON" \
345
719
  --argjson tags "$TAGS_JSON" \
346
720
  --argjson companies "$MIRROR_COMPANIES_JSON" \
721
+ --argjson company_slugs "$SESSION_LOCKED_COMPANIES_JSON" \
722
+ --arg session_id "$HANDOFF_SESSION_ID" \
347
723
  '{
348
724
  thread_id: $thread_id,
349
725
  version: 1,
350
726
  type: "handoff",
351
727
  created_at: $ts,
352
728
  updated_at: $ts,
729
+ session_id: (if $session_id == "" then null else $session_id end),
353
730
  workspace_root: $root,
354
731
  cwd: $cwd,
355
732
  git: { branch: $branch, current_commit: $commit, dirty: $dirty },
@@ -357,18 +734,39 @@ jq -n \
357
734
  conversation_summary: $summary,
358
735
  next_steps: $next_steps,
359
736
  files_touched: ($files_touched[0] // []),
360
- learnings: $learnings,
361
- metadata: { title: $title, tags: $tags, company: $companies }
737
+ learnings: ($learnings[0] // []),
738
+ deficiencies: $deficiencies,
739
+ system_info: $system_info,
740
+ metadata: { title: $title, tags: $tags, company: $companies, company_slugs: $company_slugs }
362
741
  }' > "$THREAD_PATH"
363
742
 
364
743
  # `handoff-finalize.sh` writes from a shell subprocess, so its thread creation
365
744
  # does not pass through editor PostToolUse hooks. Replay the installed mirror
366
745
  # hook with Bash: hooks are source files and do not require an executable bit.
367
746
  MIRROR_HOOK="$HQ_ROOT/.claude/hooks/mirror-thread-to-company.sh"
747
+ # Do not exit before writing handoff.json. A --company handoff in a session
748
+ # with no company lock used to stop at exit 5 here, leaving the pointer on
749
+ # the previous session (feedback_0ee565a1, feedback_4140f6ba, feedback_1039db92).
750
+ # Warn, keep going, then exit 5 after the pointer is written.
751
+ COMPANY_MIRROR_FAILED=0
368
752
  if [[ -f "$MIRROR_HOOK" ]]; then
369
753
  jq -n --arg file_path "$HQ_ROOT/$THREAD_PATH" \
370
754
  '{tool_name:"Write", tool_input:{file_path:$file_path}}' | \
371
- bash "$MIRROR_HOOK" >/dev/null 2>&1 || true
755
+ bash "$MIRROR_HOOK" >/dev/null 2>&1 || {
756
+ if [[ "$MIRROR_COMPANIES_JSON" != '[]' ]]; then
757
+ COMPANY_MIRROR_FAILED=1
758
+ echo "handoff-finalize: company mirror failed; canonical thread retained" >&2
759
+ if [[ -n "$OWNER_COMPANY" ]] && ! owner_in_locked_set "$OWNER_COMPANY"; then
760
+ echo "handoff-finalize: session has no company lock for $OWNER_COMPANY; run core/scripts/hq-session.sh add company $OWNER_COMPANY, then re-run /handoff to mirror" >&2
761
+ fi
762
+ fi
763
+ }
764
+ elif [[ "$MIRROR_COMPANIES_JSON" != '[]' ]]; then
765
+ COMPANY_MIRROR_FAILED=1
766
+ echo "handoff-finalize: company mirror hook missing; canonical thread retained" >&2
767
+ if [[ -n "$OWNER_COMPANY" ]] && ! owner_in_locked_set "$OWNER_COMPANY"; then
768
+ echo "handoff-finalize: session has no company lock for $OWNER_COMPANY; run core/scripts/hq-session.sh add company $OWNER_COMPANY, then re-run /handoff to mirror" >&2
769
+ fi
372
770
  fi
373
771
  while IFS= read -r company; do
374
772
  [[ -n "$company" ]] || continue
@@ -423,19 +821,40 @@ jq -n \
423
821
  # Keep the pointer readable as one complete file at all times. The temp is in
424
822
  # the destination directory so mv publishes it with a same-filesystem rename.
425
823
  # The pointer path is checkout-relative so the synced handoff stays portable.
824
+ #
825
+ # The pointer is one shared, last-writer-wins file for every session on this
826
+ # checkout. Two sessions handing off minutes apart is normal and the later one
827
+ # takes it. What must not happen is an OLDER handoff (clock skew, a replayed
828
+ # copy racing a fresh one) replacing a NEWER pointer: /startwork would then
829
+ # resume the wrong thread and the newer session's archive check would refuse.
830
+ # created_at is a sortable UTC stamp, so a plain string compare orders them.
831
+ POINTER_KEPT_NEWER="false"
426
832
  write_handoff_pointer() {
427
- local destination="$1" thread_path="$2" destination_dir pointer_tmp
833
+ local destination="$1" thread_path="$2" destination_dir pointer_tmp existing_ts
428
834
  destination_dir="$(dirname "$destination")"
429
835
  mkdir -p "$destination_dir"
836
+ if [[ -f "$destination" ]]; then
837
+ existing_ts="$(jq -r '.created_at // empty' "$destination" 2>/dev/null || true)"
838
+ if [[ -n "$existing_ts" && "$existing_ts" > "$TS" ]]; then
839
+ echo "handoff-finalize: kept newer handoff pointer at $destination ($existing_ts > $TS); this thread stays at $thread_path" >&2
840
+ POINTER_KEPT_NEWER="true"
841
+ return 0
842
+ fi
843
+ fi
430
844
  pointer_tmp="$(mktemp "$destination_dir/.handoff-pointer.XXXXXX")"
431
845
  FINALIZE_TMP_FILES+=("$pointer_tmp")
432
- if ! jq -n --arg ts "$TS" --arg msg "$MESSAGE" --arg thread_id "$THREAD_ID" --arg thread_path "$thread_path" --arg summary "$SUMMARY" '{
846
+ # Company context: /discover reads a scalar top-level `.company` from this
847
+ # pointer, so write the slug when exactly one company is bound. `companies`
848
+ # carries the full list (same values as the thread's metadata.company).
849
+ if ! jq -n --arg ts "$TS" --arg msg "$MESSAGE" --arg thread_id "$THREAD_ID" --arg thread_path "$thread_path" --arg summary "$SUMMARY" --argjson companies "$MIRROR_COMPANIES_JSON" --arg session_id "$HANDOFF_SESSION_ID" '{
433
850
  created_at: $ts,
434
851
  message: $msg,
435
852
  last_thread: $thread_id,
436
853
  thread_path: $thread_path,
437
- context_notes: $summary
438
- }' > "$pointer_tmp"; then
854
+ context_notes: $summary,
855
+ companies: $companies,
856
+ session_id: (if $session_id == "" then null else $session_id end)
857
+ } + (if ($companies | length) == 1 then {company: $companies[0]} else {} end)' > "$pointer_tmp"; then
439
858
  rm -f "$pointer_tmp"
440
859
  return 1
441
860
  fi
@@ -514,43 +933,459 @@ EXPLICIT_PATHS=(
514
933
  "INDEX.md"
515
934
  )
516
935
  STAGED=0
936
+ # Big files and swept-in media never ride a handoff commit (feedback_c682f3ad).
937
+ # A changeset that names a project folder used to stage every render under it,
938
+ # and the HQ root history grew by gigabytes a day. Two rules, applied to what
939
+ # each `git add` actually staged:
940
+ # - any file above HQ_OFFLOAD_MIN_BYTES (default 50 MiB, the same cap the
941
+ # autosave hook uses) is unstaged, named or not;
942
+ # - a media or archive file that only arrived because its parent directory
943
+ # was listed is unstaged at any size. A media file the changeset names
944
+ # directly is the agent's explicit choice and still commits.
945
+ # HQ_HANDOFF_ALLOW_MEDIA=1 turns off the second rule. Every unstaged path is
946
+ # reported in skipped_paths with reason "oversize" or "media-in-directory".
947
+ HANDOFF_MAX_BYTES="${HQ_OFFLOAD_MIN_BYTES:-52428800}"
948
+ [[ "$HANDOFF_MAX_BYTES" =~ ^[0-9]+$ && "$HANDOFF_MAX_BYTES" -gt 0 ]] || HANDOFF_MAX_BYTES=52428800
949
+ HANDOFF_STAGE_SKIPS=0
950
+ # Paths whose `git add` succeeded, NUL-separated. The filter runs once after the
951
+ # staging loop: a per-path pass costs a git process per entry, which a
952
+ # 5000-path changeset cannot afford. HANDOFF_ADDED_PATHS holds the same paths
953
+ # normalized (see handoff_norm_path), one per line, to match git's spelling.
954
+ # The same list drives the commit: it is restricted to exactly these paths, so
955
+ # anything another process left in the index stays staged and out of the
956
+ # handoff commit (feedback 25b250a7). OWN_STAGED_FILE is the name the commit
957
+ # step uses for it.
958
+ new_tmp HANDOFF_ADDED_PATHS_FILE
959
+ : > "$HANDOFF_ADDED_PATHS_FILE"
960
+ OWN_STAGED_FILE="$HANDOFF_ADDED_PATHS_FILE"
961
+ HANDOFF_ADDED_PATHS=""
962
+ # hq_git_index_retry <git args...> — run a git command that takes the index
963
+ # lock. When it fails because another process holds .git/index.lock (concurrent
964
+ # sessions commit their own handoff checkpoints in the same minute, feedback
965
+ # 29213da4; the desktop app's or Xcode's own `git status --porcelain --ignored`
966
+ # over the whole HQ tree, thread T-20261022-140549), wait for the lock to go
967
+ # away and try again. The wait is bounded by wall clock, not by a count: a
968
+ # `git status` over a large tree holds the lock for tens of seconds, which the
969
+ # old 8-try (~6 s) budget never covered, so the handoff ended stage-failed
970
+ # while the holder was about to exit. HQ_HANDOFF_INDEX_LOCK_WAIT_SECONDS
971
+ # (default 60) is the total budget; HQ_HANDOFF_INDEX_LOCK_RETRIES (default 0 =
972
+ # no cap) additionally caps the number of retries. Between tries the lock file
973
+ # is polled every 0.1 s (up to a 1 s backoff), so a released lock is noticed
974
+ # at once. Any other failure, and a lock that outlives the budget, returns
975
+ # git's status with its stderr intact so the caller classifies it.
976
+ HQ_HANDOFF_INDEX_LOCK_RETRIES="${HQ_HANDOFF_INDEX_LOCK_RETRIES:-0}"
977
+ [[ "$HQ_HANDOFF_INDEX_LOCK_RETRIES" =~ ^[0-9]+$ ]] || HQ_HANDOFF_INDEX_LOCK_RETRIES=0
978
+ HQ_HANDOFF_INDEX_LOCK_WAIT_SECONDS="${HQ_HANDOFF_INDEX_LOCK_WAIT_SECONDS:-60}"
979
+ [[ "$HQ_HANDOFF_INDEX_LOCK_WAIT_SECONDS" =~ ^[0-9]+$ ]] || HQ_HANDOFF_INDEX_LOCK_WAIT_SECONDS=60
980
+ HQ_HANDOFF_INDEX_LOCK_WAITS=0
981
+ # Tenths of a second spent waiting on the lock so far, across every index
982
+ # operation of this run: the budget is per handoff, not per `git add`, so a
983
+ # lock that is never released cannot stall the finalizer for 60 s per path.
984
+ HQ_HANDOFF_INDEX_LOCK_WAITED_TENTHS=0
985
+ new_tmp HQ_RETRY_ERR_FILE
986
+ # A lock nobody holds. A git process that died mid-write (a killed session, a
987
+ # crashed editor integration) leaves .git/index.lock behind for good, and every
988
+ # later handoff ends stage-failed (rc=4) until someone deletes the file by hand
989
+ # — which the HQ-root git-mutation hook then refuses to let the agent do. The
990
+ # backoff below cannot help there: that lock never clears on its own.
991
+ #
992
+ # A lock counts as stale only when BOTH hold:
993
+ # - it is older than HQ_HANDOFF_STALE_LOCK_SECONDS (default 600, 10 min);
994
+ # - no git process on this machine is older than the lock. The process that
995
+ # created the lock started before it, so any git older than the lock could
996
+ # still be its holder and the lock is left alone. Younger git processes
997
+ # (other sessions' quick commits) cannot own it.
998
+ # At most one stale lock is removed per run, and the removal is reported on
999
+ # stderr and in the payload (stale_index_lock_removed) so it is never silent.
1000
+ HQ_HANDOFF_STALE_LOCK_SECONDS="${HQ_HANDOFF_STALE_LOCK_SECONDS:-600}"
1001
+ [[ "$HQ_HANDOFF_STALE_LOCK_SECONDS" =~ ^[0-9]+$ ]] || HQ_HANDOFF_STALE_LOCK_SECONDS=600
1002
+ HQ_HANDOFF_STALE_LOCK_REMOVED="false"
1003
+ HQ_HANDOFF_STALE_LOCK_CHECKED=0
1004
+ # Callers redirect the retry wrapper's stderr into a per-path error file, so
1005
+ # the stale-lock notes go to the script's own stderr through a saved fd.
1006
+ exec 7>&2
1007
+ hq_index_lock_mtime() { # hq_index_lock_mtime <file> — epoch seconds, or empty
1008
+ # GNU `stat -f` is file-system status and exits 0 with a non-number for %m,
1009
+ # so take whichever form prints digits (GNU -c first, then BSD -f).
1010
+ local m
1011
+ m="$(stat -c %Y "$1" 2>/dev/null)" && [[ "$m" =~ ^[0-9]+$ ]] && { printf '%s\n' "$m"; return 0; }
1012
+ m="$(stat -f %m "$1" 2>/dev/null)" && [[ "$m" =~ ^[0-9]+$ ]] && { printf '%s\n' "$m"; return 0; }
1013
+ return 0
1014
+ }
1015
+ # hq_git_process_older_than <seconds> — true when any running git process has
1016
+ # been alive at least that long. `ps -o etime` prints [[dd-]hh:]mm:ss on macOS
1017
+ # and Linux (macOS ps has no `etimes`); unparseable rows count as older, so a
1018
+ # doubt keeps the lock.
1019
+ hq_git_process_older_than() {
1020
+ local min="$1" etime comm days=0 hms secs
1021
+ while read -r etime comm; do
1022
+ case "$comm" in git|*/git) ;; *) continue ;; esac
1023
+ hms="$etime"
1024
+ case "$hms" in *-*) days="${hms%%-*}"; hms="${hms#*-}" ;; *) days=0 ;; esac
1025
+ case "$hms" in
1026
+ [0-9]*:[0-9][0-9]:[0-9][0-9])
1027
+ secs=$(( 10#${hms%%:*} * 3600 ))
1028
+ hms="${hms#*:}"
1029
+ secs=$(( secs + 10#${hms%%:*} * 60 + 10#${hms#*:} )) ;;
1030
+ [0-9]*:[0-9][0-9])
1031
+ secs=$(( 10#${hms%%:*} * 60 + 10#${hms#*:} )) ;;
1032
+ *) return 0 ;;
1033
+ esac
1034
+ [[ "$days" =~ ^[0-9]+$ ]] || return 0
1035
+ secs=$(( days * 86400 + secs ))
1036
+ [[ $secs -lt $min ]] || return 0
1037
+ done < <(ps -axo etime=,comm= 2>/dev/null)
1038
+ return 1
1039
+ }
1040
+ hq_clear_stale_index_lock() {
1041
+ [[ $HQ_HANDOFF_STALE_LOCK_CHECKED -eq 0 ]] || return 1
1042
+ HQ_HANDOFF_STALE_LOCK_CHECKED=1
1043
+ local lock mtime now age
1044
+ lock="$(git rev-parse --git-path index.lock 2>/dev/null)" || return 1
1045
+ [[ -n "$lock" && -f "$lock" ]] || return 1
1046
+ mtime="$(hq_index_lock_mtime "$lock")"
1047
+ [[ "$mtime" =~ ^[0-9]+$ ]] || return 1
1048
+ now="$(date +%s)"
1049
+ age=$((now - mtime))
1050
+ [[ $age -ge $HQ_HANDOFF_STALE_LOCK_SECONDS ]] || return 1
1051
+ if hq_git_process_older_than "$age"; then
1052
+ echo "handoff-finalize: ${lock} is ${age}s old but a git process older than it is still running; leaving it alone" >&7
1053
+ return 1
1054
+ fi
1055
+ rm -f -- "$lock" 2>/dev/null || return 1
1056
+ HQ_HANDOFF_STALE_LOCK_REMOVED="true"
1057
+ echo "handoff-finalize: removed stale ${lock} (${age}s old, no git process older than it); retrying the stage" >&7
1058
+ return 0
1059
+ }
1060
+ hq_git_index_retry() {
1061
+ local attempt=0 rc=0 polls lock_path budget_tenths
1062
+ budget_tenths=$((HQ_HANDOFF_INDEX_LOCK_WAIT_SECONDS * 10))
1063
+ lock_path="$(git rev-parse --git-path index.lock 2>/dev/null || true)"
1064
+ while :; do
1065
+ rc=0
1066
+ "$@" 2>"$HQ_RETRY_ERR_FILE" || rc=$?
1067
+ if [[ $rc -eq 0 ]] || ! grep -q 'index\.lock' "$HQ_RETRY_ERR_FILE" 2>/dev/null; then
1068
+ cat "$HQ_RETRY_ERR_FILE" >&2
1069
+ return $rc
1070
+ fi
1071
+ # A stale lock is removed once per run and the command re-run at once; the
1072
+ # backoff below is for a lock a live process is about to release.
1073
+ if hq_clear_stale_index_lock; then
1074
+ continue
1075
+ fi
1076
+ # Only a HELD lock is worth waiting for: git says "File exists", or the
1077
+ # lock file is on disk. "Permission denied" / "Operation not permitted" on
1078
+ # index.lock is a sandbox or ownership problem that no wait fixes, so it
1079
+ # returns at once for the caller to classify.
1080
+ if { ! grep -qi 'File exists' "$HQ_RETRY_ERR_FILE" 2>/dev/null && [[ -z "$lock_path" || ! -e "$lock_path" ]]; } \
1081
+ || [[ $HQ_HANDOFF_INDEX_LOCK_WAITED_TENTHS -ge $budget_tenths ]] \
1082
+ || { [[ $HQ_HANDOFF_INDEX_LOCK_RETRIES -gt 0 ]] && [[ $attempt -ge $HQ_HANDOFF_INDEX_LOCK_RETRIES ]]; }; then
1083
+ cat "$HQ_RETRY_ERR_FILE" >&2
1084
+ return $rc
1085
+ fi
1086
+ attempt=$((attempt+1))
1087
+ HQ_HANDOFF_INDEX_LOCK_WAITS=$((HQ_HANDOFF_INDEX_LOCK_WAITS+1))
1088
+ # Backoff 0.1, 0.2, 0.4, 0.8, then 1 s per try, each spent polling the
1089
+ # lock file in 0.1 s steps so the retry fires as soon as the holder exits.
1090
+ case $attempt in 1) polls=1 ;; 2) polls=2 ;; 3) polls=4 ;; 4) polls=8 ;; *) polls=10 ;; esac
1091
+ while [[ $polls -gt 0 ]]; do
1092
+ sleep 0.1
1093
+ polls=$((polls-1))
1094
+ HQ_HANDOFF_INDEX_LOCK_WAITED_TENTHS=$((HQ_HANDOFF_INDEX_LOCK_WAITED_TENTHS+1))
1095
+ if [[ -n "$lock_path" && ! -e "$lock_path" ]]; then
1096
+ break
1097
+ fi
1098
+ done
1099
+ done
1100
+ }
1101
+ # Set when the filter could not run or could not unstage. The commit is then
1102
+ # withheld so unfiltered media never lands; the run reports stage-failed.
1103
+ HANDOFF_FILTER_FAILED=0
1104
+ # Skips queued as "reason<TAB>path" lines and written with one jq call, so a
1105
+ # large skip list does not cost a jq process per path.
1106
+ HANDOFF_SKIP_QUEUE_FILE=""
1107
+ handoff_queue_skip() { # handoff_queue_skip <reason> <path>
1108
+ [[ -n "$HANDOFF_SKIP_QUEUE_FILE" ]] || new_tmp HANDOFF_SKIP_QUEUE_FILE
1109
+ printf '%s\t%s\n' "$1" "$2" >> "$HANDOFF_SKIP_QUEUE_FILE"
1110
+ HANDOFF_STAGE_SKIPS=$((HANDOFF_STAGE_SKIPS+1))
1111
+ }
1112
+ handoff_flush_skips() {
1113
+ [[ -n "$HANDOFF_SKIP_QUEUE_FILE" && -s "$HANDOFF_SKIP_QUEUE_FILE" ]] || return 0
1114
+ jq -Rc 'split("\t") | {path: (.[1:] | join("\t")), reason: .[0]}' \
1115
+ "$HANDOFF_SKIP_QUEUE_FILE" >> "$SKIPPED_NDJSON_FILE"
1116
+ }
1117
+ # handoff_norm_path <path> — sets HANDOFF_NORM to the path with `//` and `/./`
1118
+ # collapsed, leading `./` and trailing `/` removed. Sets a global instead of
1119
+ # printing so the staging loop does not fork a subshell per path.
1120
+ handoff_norm_path() {
1121
+ local p="$1" dd='//' dsd='/./' s='/'
1122
+ while [[ "$p" == *"$dd"* ]]; do p="${p//$dd/$s}"; done
1123
+ while [[ "$p" == *"$dsd"* ]]; do p="${p//$dsd/$s}"; done
1124
+ while [[ "$p" == ./* ]]; do p="${p#./}"; done
1125
+ while [[ "$p" == */ && "$p" != "/" ]]; do p="${p%/}"; done
1126
+ HANDOFF_NORM="$p"
1127
+ }
1128
+ handoff_note_added() {
1129
+ printf '%s\0' "$1" >> "$HANDOFF_ADDED_PATHS_FILE"
1130
+ handoff_norm_path "$1"
1131
+ HANDOFF_ADDED_PATHS="${HANDOFF_ADDED_PATHS}${HANDOFF_NORM}"$'\n'
1132
+ }
1133
+ handoff_is_media() {
1134
+ local rc=1 restore_nocase=0
1135
+ shopt -q nocasematch || { shopt -s nocasematch; restore_nocase=1; }
1136
+ case "$1" in
1137
+ *.mp4|*.mov|*.m4v|*.avi|*.mkv|*.webm|*.wmv|*.flv|*.mpg|*.mpeg|*.prores|\
1138
+ *.wav|*.mp3|*.m4a|*.aac|*.flac|*.aif|*.aiff|*.ogg|*.opus|\
1139
+ *.png|*.jpg|*.jpeg|*.gif|*.webp|*.heic|*.heif|*.tif|*.tiff|*.bmp|*.psd|*.exr|*.raw|\
1140
+ *.zip|*.tar|*.gz|*.tgz|*.bz2|*.xz|*.7z|*.rar|*.dmg|*.iso)
1141
+ rc=0 ;;
1142
+ esac
1143
+ [[ $restore_nocase -eq 0 ]] || shopt -u nocasematch
1144
+ return $rc
1145
+ }
1146
+ # The handoff's own metadata (thread files, pointer, indexes) and offload
1147
+ # placeholders always commit, whatever the size cap.
1148
+ handoff_is_exempt() {
1149
+ case "$1" in
1150
+ *.hqcloud|workspace/threads/*|workspace/orchestrator/INDEX.md|INDEX.md) return 0 ;;
1151
+ esac
1152
+ return 1
1153
+ }
1154
+ handoff_filter_failed() { # handoff_filter_failed <what failed>
1155
+ HANDOFF_FILTER_FAILED=1
1156
+ STAGE_FAILURES="${STAGE_FAILURES}handoff-filter: $1"$'\n'
1157
+ STAGE_FAILURE_COUNT=$((STAGE_FAILURE_COUNT+1))
1158
+ # Best effort: leave nothing unfiltered staged for a later commit to pick up.
1159
+ hq_git_index_retry git reset -q --pathspec-from-file="$HANDOFF_ADDED_PATHS_FILE" --pathspec-file-nul >/dev/null 2>&1 || true
1160
+ }
1161
+ # handoff_add_ignored_dir <dir> — an ignored directory that holds tracked
1162
+ # files. Update only what is already tracked; `git add -f` here would force
1163
+ # every ignored render under it into history (feedback_c682f3ad). Untracked
1164
+ # ignored entries are reported as skipped instead of dropped silently.
1165
+ # --directory collapses a wholly untracked subdirectory into one entry.
1166
+ handoff_add_ignored_dir() {
1167
+ local p="$1" f
1168
+ hq_git_index_retry git add -u -- "$p" >/dev/null 2>"$STAGE_ERR_FILE" || return 1
1169
+ while IFS= read -r -d '' f; do
1170
+ [[ -n "$f" ]] || continue
1171
+ handoff_queue_skip "ignored-untracked" "$f"
1172
+ done < <(git ls-files -z -o -i --exclude-standard --directory -- "$p" 2>/dev/null)
1173
+ return 0
1174
+ }
1175
+ # handoff_unstage_unwanted — inspect what the staging loop added at or under
1176
+ # the changeset paths and unstage what the rules above exclude. Sizes come from
1177
+ # the staged blobs, not the working tree, so a path spelled `a/./b` or in
1178
+ # another Unicode form cannot dodge the cap, and deleted files need no stat.
1179
+ handoff_unstage_unwanted() {
1180
+ [[ -n "$HANDOFF_ADDED_PATHS_FILE" && -s "$HANDOFF_ADDED_PATHS_FILE" ]] || return 0
1181
+ local raw_file renames_file shas_file sizes_file unstage_file
1182
+ local meta rest path status size reason renamed n=0 i=0
1183
+ local -a h_paths=() h_status=()
1184
+ new_tmp raw_file
1185
+ new_tmp renames_file
1186
+ new_tmp shas_file
1187
+ new_tmp sizes_file
1188
+ new_tmp unstage_file
1189
+ if ! xargs -0 git diff --cached --raw -z --no-abbrev --no-renames --diff-filter=AMT -- \
1190
+ < "$HANDOFF_ADDED_PATHS_FILE" > "$raw_file" 2>/dev/null; then
1191
+ handoff_filter_failed "could not list staged changes"
1192
+ return 0
1193
+ fi
1194
+ # A tracked file moved to a new name shows as a rename here. Its destination
1195
+ # is not new media and must stay staged next to the staged deletion.
1196
+ if ! xargs -0 git diff --cached -z --name-status -M --diff-filter=R -- \
1197
+ < "$HANDOFF_ADDED_PATHS_FILE" > "$renames_file" 2>/dev/null; then
1198
+ handoff_filter_failed "could not list staged renames"
1199
+ return 0
1200
+ fi
1201
+ renamed=$'\n'
1202
+ while IFS= read -r -d '' status && IFS= read -r -d '' rest && IFS= read -r -d '' path; do
1203
+ renamed="${renamed}${path}"$'\n'
1204
+ done < "$renames_file"
1205
+ # --raw -z: ":<mode> <mode> <sha> <sha> <status>" NUL "<path>" NUL.
1206
+ while IFS= read -r -d '' meta && IFS= read -r -d '' path; do
1207
+ status="${meta##* }"
1208
+ rest="${meta% *}"
1209
+ printf '%s\n' "${rest##* }" >> "$shas_file"
1210
+ h_paths[n]="$path"
1211
+ h_status[n]="$status"
1212
+ n=$((n+1))
1213
+ done < "$raw_file"
1214
+ [[ $n -gt 0 ]] || return 0
1215
+ # One cat-file call sizes every staged blob, in input order. A gitlink or
1216
+ # missing object prints a non-numeric line and counts as size 0.
1217
+ if ! git cat-file --batch-check='%(objectsize)' < "$shas_file" > "$sizes_file" 2>/dev/null; then
1218
+ handoff_filter_failed "could not size staged files"
1219
+ return 0
1220
+ fi
1221
+ while IFS= read -r size && [[ $i -lt $n ]]; do
1222
+ path="${h_paths[i]}"
1223
+ status="${h_status[i]}"
1224
+ i=$((i+1))
1225
+ handoff_is_exempt "$path" && continue
1226
+ [[ "$size" =~ ^[0-9]+$ ]] || size=0
1227
+ reason=""
1228
+ [[ $size -gt $HANDOFF_MAX_BYTES ]] && reason="oversize"
1229
+ # Only new media is swept in by a directory. A media file the changeset
1230
+ # names directly still commits.
1231
+ if [[ -z "$reason" && "$status" == "A" && "${HQ_HANDOFF_ALLOW_MEDIA:-}" != "1" ]] \
1232
+ && handoff_is_media "$path"; then
1233
+ case $'\n'"$HANDOFF_ADDED_PATHS"$renamed in
1234
+ *$'\n'"$path"$'\n'*) ;;
1235
+ *) reason="media-in-directory" ;;
1236
+ esac
1237
+ fi
1238
+ [[ -n "$reason" ]] || continue
1239
+ printf '%s\0' "$path" >> "$unstage_file"
1240
+ handoff_queue_skip "$reason" "$path"
1241
+ done < "$sizes_file"
1242
+ if [[ $i -ne $n ]]; then
1243
+ handoff_filter_failed "sized ${i} of ${n} staged files"
1244
+ return 0
1245
+ fi
1246
+ if [[ -s "$unstage_file" ]] \
1247
+ && ! hq_git_index_retry git reset -q --pathspec-from-file="$unstage_file" --pathspec-file-nul >/dev/null 2>&1; then
1248
+ handoff_filter_failed "could not unstage filtered files"
1249
+ fi
1250
+ return 0
1251
+ }
517
1252
  # Newline-separated, not an array: `${#arr[@]}` on an empty array is an unbound
518
1253
  # variable under bash 3.2 + `set -u` (the same trap the SAFE_STAGE_PATHS
519
1254
  # regression hit), and macOS still ships bash 3.2.
520
1255
  STAGE_FAILURES=""
521
1256
  STAGE_FAILURE_COUNT=0
1257
+ # git's stderr for the first rejected path. It used to go to /dev/null, so a
1258
+ # sandbox permission denial on .git read as an unexplained "git add failed for
1259
+ # N path(s)" (feedback_98f2ce49-5065-4670-8544-1a3dccd9985e).
1260
+ FIRST_STAGE_ERROR=""
1261
+ STAGE_FAILURE_CLASS=""
1262
+ new_tmp STAGE_ERR_FILE
1263
+ NESTED_REPO_PATHS=""
1264
+ NESTED_DIRTY_MSG=""
1265
+ # nested_repo_root <path> -> prints the gitlink (a nested repository the HQ
1266
+ # index records, such as companies/<co>/knowledge) that contains <path>, or
1267
+ # nothing. A nested repo that is only excluded or ignored (repos/, info/exclude)
1268
+ # is not a gitlink; its paths keep the ordinary ignored-path handling below. `git add` from the
1269
+ # HQ root cannot stage a path inside one (feedback d4fcd2e4, 121735c2).
1270
+ # Gitlinks are listed once up front, so the per-path walk runs no git
1271
+ # command (it still costs one subshell per path for the substitution).
1272
+ HQ_GITLINKS=""
1273
+ if [[ "$HAS_GIT_CHECKOUT" == "true" ]]; then
1274
+ HQ_GITLINKS="$(git ls-files -s 2>/dev/null | awk '$1 == "160000" { sub(/^[^\t]*\t/, ""); print }')"
1275
+ fi
1276
+ nested_repo_root() {
1277
+ local d="$1"
1278
+ while [[ "$d" == */* ]]; do
1279
+ d="${d%/*}"
1280
+ [[ -n "$d" ]] || break
1281
+ if [[ -n "$HQ_GITLINKS" ]]; then
1282
+ case $'\n'"$HQ_GITLINKS"$'\n' in
1283
+ *$'\n'"$d"$'\n'*) printf '%s' "$d"; return 0 ;;
1284
+ esac
1285
+ fi
1286
+ done
1287
+ return 0
1288
+ }
1289
+ # record_stage_failure <path> — append the path; keep the first stderr line.
1290
+ record_stage_failure() {
1291
+ STAGE_FAILURES="${STAGE_FAILURES}${1}"$'\n'
1292
+ STAGE_FAILURE_COUNT=$((STAGE_FAILURE_COUNT+1))
1293
+ if [[ -z "$FIRST_STAGE_ERROR" ]]; then
1294
+ FIRST_STAGE_ERROR="$(grep -v '^[[:space:]]*$' "$STAGE_ERR_FILE" 2>/dev/null | head -n 1 | tr -d '\r' | cut -c1-300 || true)"
1295
+ fi
1296
+ }
522
1297
  if [[ "$HAS_GIT_CHECKOUT" == "true" ]]; then
1298
+ # Changeset paths are file names, never globs: a file named `d/*` must not
1299
+ # stage all of d/. Restored after the filter.
1300
+ HANDOFF_PRIOR_LITERAL="${GIT_LITERAL_PATHSPECS-__unset__}"
1301
+ export GIT_LITERAL_PATHSPECS=1
523
1302
  for p in "${EXPLICIT_PATHS[@]}"; do
524
1303
  [[ -n "$p" ]] || continue
1304
+ nested="$(nested_repo_root "$p")"
1305
+ if [[ -n "$nested" ]]; then
1306
+ # The owning repository saves its own files (the knowledge helper commits
1307
+ # them there). The HQ root can only record the nested repo's pointer, so
1308
+ # stage that and report an inner file that is still uncommitted by name.
1309
+ inner="${p#"$nested"/}"
1310
+ if [[ -n "$(GIT_LITERAL_PATHSPECS=1 git -C "$nested" status --porcelain -- "$inner" 2>/dev/null)" ]]; then
1311
+ record_stage_failure "$p"
1312
+ NESTED_DIRTY_MSG="${NESTED_DIRTY_MSG:+$NESTED_DIRTY_MSG; }$p is uncommitted inside nested repository $nested (commit it there, then re-run)"
1313
+ continue
1314
+ fi
1315
+ case $'\n'"$NESTED_REPO_PATHS" in *$'\n'"$p"$'\n'*) ;; *) NESTED_REPO_PATHS="${NESTED_REPO_PATHS}${p}"$'\n' ;; esac
1316
+ if [[ -n "$(GIT_LITERAL_PATHSPECS=1 git status --porcelain --ignore-submodules=untracked -- "$nested" 2>/dev/null)" ]] \
1317
+ && GIT_LITERAL_PATHSPECS=1 git ls-files --error-unmatch -- "$nested" >/dev/null 2>&1; then
1318
+ if GIT_LITERAL_PATHSPECS=1 hq_git_index_retry git add -- "$nested" >/dev/null 2>"$STAGE_ERR_FILE"; then
1319
+ STAGED=$((STAGED+1))
1320
+ handoff_note_added "$nested"
1321
+ else
1322
+ record_stage_failure "$nested"
1323
+ fi
1324
+ fi
1325
+ continue
1326
+ fi
525
1327
  if [[ -e "$p" || -n "$(git status --porcelain -- "$p" 2>/dev/null)" ]]; then
526
1328
  add_rc=0
527
- git add -- "$p" >/dev/null 2>&1 || add_rc=$?
1329
+ hq_git_index_retry git add -- "$p" >/dev/null 2>"$STAGE_ERR_FILE" || add_rc=$?
528
1330
  if [[ $add_rc -eq 0 ]]; then
529
1331
  STAGED=$((STAGED+1))
530
- elif git ls-files --error-unmatch -- "$p" >/dev/null 2>&1; then
1332
+ handoff_note_added "$p"
1333
+ elif [[ -d "$p" ]] && GIT_LITERAL_PATHSPECS=0 git check-ignore --no-index -q -- "$p" 2>/dev/null \
1334
+ && git ls-files --error-unmatch -- "$p" >/dev/null 2>&1; then
1335
+ # An ignored DIRECTORY that holds tracked files. check-ignore rejects
1336
+ # literal pathspec magic, hence the override; it takes plain paths.
1337
+ if handoff_add_ignored_dir "$p"; then
1338
+ STAGED=$((STAGED+1))
1339
+ handoff_note_added "$p"
1340
+ else
1341
+ record_stage_failure "$p"
1342
+ fi
1343
+ elif [[ ! -d "$p" ]] && git ls-files --error-unmatch -- "$p" >/dev/null 2>&1; then
531
1344
  # The path is already TRACKED but a broad later ignore rule now shadows it
532
1345
  # (the scaffold's /workspace/ entry over the tracked handoff pointer/index
533
1346
  # files), so a plain `git add` refuses it. A tracked file must still be
534
1347
  # committed, so force-add it. Only a force-add that ALSO fails (e.g. a held
535
- # .git/index.lock) is a genuine stage failure.
536
- if git add -f -- "$p" >/dev/null 2>&1; then
1348
+ # .git/index.lock) is a genuine stage failure. Never for a directory:
1349
+ # `git add -f` there would force in every ignored file under it, and a
1350
+ # directory whose plain add failed for another reason (an unreadable
1351
+ # file) is a stage failure below.
1352
+ if hq_git_index_retry git add -f -- "$p" >/dev/null 2>"$STAGE_ERR_FILE"; then
537
1353
  STAGED=$((STAGED+1))
1354
+ handoff_note_added "$p"
538
1355
  else
539
- STAGE_FAILURES="${STAGE_FAILURES}${p}"$'\n'
540
- STAGE_FAILURE_COUNT=$((STAGE_FAILURE_COUNT+1))
1356
+ record_stage_failure "$p"
541
1357
  fi
542
- elif git check-ignore --no-index -q -- "$p" 2>/dev/null; then
1358
+ elif GIT_LITERAL_PATHSPECS=0 git check-ignore --no-index -q -- "$p" 2>/dev/null; then
543
1359
  # An UNtracked, gitignored path is a deliberate exclusion, not a failed
544
1360
  # write. --no-index is required: plain `git check-ignore` SKIPS tracked
545
1361
  # files (it would wrongly report a tracked-but-ignored path as not-ignored,
546
1362
  # the bug that made this a stage-failure); the tracked case is handled above.
547
1363
  :
548
1364
  else
549
- STAGE_FAILURES="${STAGE_FAILURES}${p}"$'\n'
550
- STAGE_FAILURE_COUNT=$((STAGE_FAILURE_COUNT+1))
1365
+ record_stage_failure "$p"
551
1366
  fi
552
1367
  fi
553
1368
  done
1369
+ handoff_unstage_unwanted
1370
+ if [[ "$HANDOFF_PRIOR_LITERAL" == "__unset__" ]]; then
1371
+ unset GIT_LITERAL_PATHSPECS
1372
+ else
1373
+ export GIT_LITERAL_PATHSPECS="$HANDOFF_PRIOR_LITERAL"
1374
+ fi
1375
+ fi
1376
+ handoff_flush_skips
1377
+ # Fold the staging skips into skipped_paths. It was materialized earlier for
1378
+ # the thread file; the emitted payload reads the file again below.
1379
+ if [[ $HANDOFF_STAGE_SKIPS -gt 0 && -s "$SKIPPED_NDJSON_FILE" ]]; then
1380
+ jq -s '.' "$SKIPPED_NDJSON_FILE" > "$SKIPPED_PATHS_FILE"
1381
+ fi
1382
+ if [[ $STAGE_FAILURE_COUNT -gt 0 ]]; then
1383
+ case "$FIRST_STAGE_ERROR" in
1384
+ *"Operation not permitted"*|*"Permission denied"*|*"Read-only file system"*)
1385
+ STAGE_FAILURE_CLASS="permission" ;;
1386
+ *index.lock*) STAGE_FAILURE_CLASS="index-lock" ;;
1387
+ *) STAGE_FAILURE_CLASS="other" ;;
1388
+ esac
554
1389
  fi
555
1390
  # committed_paths scales with the staged set; capture it to a file (git piped to
556
1391
  # jq via stdin, then the result written to disk) so it too stays off argv.
@@ -562,14 +1397,55 @@ if [[ -n "$STAGE_FAILURES" ]]; then
562
1397
  printf '%s' "$STAGE_FAILURES" \
563
1398
  | jq -R -s 'split("\n") | map(select(length > 0))' > "$STAGE_FAILURES_FILE"
564
1399
  fi
565
- if [[ $STAGED -gt 0 ]] && [[ -n "$(git diff --cached --name-only 2>/dev/null)" ]]; then
566
- # Snapshot the staged set separately. It only becomes committed_paths once the
567
- # commit actually lands; a refused commit must not report paths as committed.
1400
+ # `git diff` has no --pathspec-from-file, and a large changeset must stay off
1401
+ # argv, so feed this run's own paths through xargs (it splits an oversize list
1402
+ # into several git calls). A listed directory covers the files staged under it
1403
+ # (minus what the filter above unstaged); a staged nested-repo gitlink matches
1404
+ # itself. The result is this run's staged FILES, one per line; paths someone
1405
+ # else staged are not part of it.
1406
+ new_tmp OWN_STAGED_CHANGES_FILE
1407
+ : > "$OWN_STAGED_CHANGES_FILE"
1408
+ if [[ $STAGED -gt 0 && -s "$OWN_STAGED_FILE" ]]; then
1409
+ GIT_LITERAL_PATHSPECS=1 xargs -0 git -c core.quotePath=false diff --cached --name-only --no-renames -- \
1410
+ < "$OWN_STAGED_FILE" 2>/dev/null | awk 'NF && !seen[$0]++' > "$OWN_STAGED_CHANGES_FILE" || true
1411
+ fi
1412
+ if [[ $STAGED -gt 0 && $HANDOFF_FILTER_FAILED -eq 0 ]] && [[ -s "$OWN_STAGED_CHANGES_FILE" ]]; then
1413
+ # Snapshot this run's staged set separately. It only becomes committed_paths
1414
+ # once the commit actually lands; a refused commit must not report paths as
1415
+ # committed.
568
1416
  new_tmp PENDING_PATHS_FILE
569
- git diff --cached --name-only | jq -R -s 'split("\n") | map(select(length > 0))' > "$PENDING_PATHS_FILE"
1417
+ jq -R -s 'split("\n") | map(select(length > 0))' < "$OWN_STAGED_CHANGES_FILE" > "$PENDING_PATHS_FILE"
570
1418
  commit_out=""
571
1419
  commit_rc=0
572
- commit_out="$(git commit -m "checkpoint: handoff ${THREAD_ID}" 2>&1)" || commit_rc=$?
1420
+ # This commit runs hooks. When the HQ git-hooks dispatcher is installed (a
1421
+ # global core.hooksPath), its commit-msg hook stamps HQ-Fingerprint, so an
1422
+ # explicit trailer here would be a second copy. Pass it only when no global
1423
+ # hooks path is set, i.e. the dispatcher is absent. A lib that fails to
1424
+ # source or load leaves the array empty and never aborts the commit.
1425
+ HQ_FINGERPRINT_TRAILER_ARGS=()
1426
+ if [[ -z "$(git config --global --get core.hooksPath 2>/dev/null || true)" ]] \
1427
+ && [[ -f "$HANDOFF_SCRIPT_DIR/lib/fingerprint.sh" ]]; then
1428
+ # shellcheck source=lib/fingerprint.sh
1429
+ { source "$HANDOFF_SCRIPT_DIR/lib/fingerprint.sh" 2>/dev/null \
1430
+ && hq_fingerprint_trailer_load "$HQ_ROOT"; } || HQ_FINGERPRINT_TRAILER_ARGS=()
1431
+ fi
1432
+ # When the index holds only this run's changes, a plain commit is exact and
1433
+ # fast. When something else is staged too, commit --only this run's paths so
1434
+ # the foreign entries stay staged and out of the handoff commit. (--only
1435
+ # matches every index entry against every pathspec, so it is not used for
1436
+ # the common case, where a large changeset would make it quadratic.)
1437
+ # The pathspec lists the staged FILES, never a listed directory: --only takes
1438
+ # a path's working-tree state, so a directory pathspec would pull back in a
1439
+ # file the media/oversize filter just unstaged.
1440
+ COMMIT_SCOPE_ARGS=()
1441
+ if [[ "$(git diff --cached --name-only --no-renames 2>/dev/null | wc -l | tr -d ' ')" != "$(jq 'length' "$PENDING_PATHS_FILE")" ]]; then
1442
+ new_tmp COMMIT_PATHSPEC_FILE
1443
+ tr '\n' '\0' < "$OWN_STAGED_CHANGES_FILE" > "$COMMIT_PATHSPEC_FILE"
1444
+ COMMIT_SCOPE_ARGS=(--only --pathspec-from-file="$COMMIT_PATHSPEC_FILE" --pathspec-file-nul)
1445
+ fi
1446
+ new_tmp COMMIT_OUT_FILE
1447
+ GIT_LITERAL_PATHSPECS=1 hq_git_index_retry git commit ${COMMIT_SCOPE_ARGS[@]+"${COMMIT_SCOPE_ARGS[@]}"} -m "checkpoint: handoff ${THREAD_ID}" ${HQ_FINGERPRINT_TRAILER_ARGS[@]+"${HQ_FINGERPRINT_TRAILER_ARGS[@]}"} >"$COMMIT_OUT_FILE" 2>&1 || commit_rc=$?
1448
+ commit_out="$(cat "$COMMIT_OUT_FILE" 2>/dev/null || true)"
573
1449
  if [[ $commit_rc -eq 0 ]]; then
574
1450
  HQ_COMMITTED="true"
575
1451
  HQ_COMMIT_STATUS="committed"
@@ -588,10 +1464,36 @@ if [[ $STAGE_FAILURE_COUNT -gt 0 && "$HQ_COMMIT_STATUS" != "failed" ]]; then
588
1464
  HQ_COMMIT_STATUS="stage-failed"
589
1465
  if [[ -z "$HQ_COMMIT_ERROR" ]]; then
590
1466
  HQ_COMMIT_ERROR="git add failed for ${STAGE_FAILURE_COUNT} path(s) — see stage_failures"
1467
+ case "$STAGE_FAILURE_CLASS" in
1468
+ permission)
1469
+ HQ_COMMIT_ERROR="${HQ_COMMIT_ERROR}; permission denied writing the git repository (a sandboxed run cannot write .git; re-run /handoff outside the sandbox)" ;;
1470
+ index-lock)
1471
+ HQ_COMMIT_ERROR="${HQ_COMMIT_ERROR}; another git process holds .git/index.lock (wait for it and re-run /handoff)" ;;
1472
+ esac
1473
+ [[ -z "$FIRST_STAGE_ERROR" ]] || HQ_COMMIT_ERROR="${HQ_COMMIT_ERROR}; first git error: ${FIRST_STAGE_ERROR}"
1474
+ [[ -z "$NESTED_DIRTY_MSG" ]] || HQ_COMMIT_ERROR="${HQ_COMMIT_ERROR}: ${NESTED_DIRTY_MSG}"
591
1475
  fi
592
1476
  fi
593
1477
  COMMIT_AFTER=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")
594
1478
 
1479
+ # -------- publish continuity pointer to the personal vault (cross-device) --------
1480
+ # workspace/ is otherwise excluded from the personal vault; only handoff.json
1481
+ # plus the referenced thread file are carved in (hq-cloud-sync
1482
+ # computeContinuityPointerPaths). Without a push between A's /handoff and B's
1483
+ # /startwork, machine B sees stale state. Fire the publisher in the background
1484
+ # so handoff never blocks on cloud reachability. Fail-soft: a missing hq CLI,
1485
+ # an offline host, or a logged-out operator all exit 0 inside the helper.
1486
+ HANDOFF_PUBLISH_PID=""
1487
+ HANDOFF_PUBLISH_STATUS="skipped"
1488
+ _PUBLISH_SH="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/handoff-sync-publish.sh"
1489
+ if [[ "$HQ_COMMITTED" == "true" && -f "$_PUBLISH_SH" ]]; then
1490
+ HANDOFF_PUBLISH_PID="$(bash "$_PUBLISH_SH" --hq-root "$HQ_ROOT" \
1491
+ --log /tmp/handoff-sync-publish.log 2>/dev/null || true)"
1492
+ if [[ -n "$HANDOFF_PUBLISH_PID" ]]; then
1493
+ HANDOFF_PUBLISH_STATUS="dispatched"
1494
+ fi
1495
+ fi
1496
+
595
1497
  # -------- qmd reindex fire-and-forget (agent: skip; laptop: single-flight) --------
596
1498
  # Agent boxes: managed timer owns indexing — handoff never kicks qmd.
597
1499
  # Laptop: qmd-reindex-bg single-flight reindex. See qmd-reindex-bg.sh.
@@ -626,7 +1528,23 @@ if [[ -n "$NEXT_COMMAND" ]]; then
626
1528
  fi
627
1529
 
628
1530
  # -------- emit result --------
629
- jq -n \
1531
+ # Git Bash/MSYS rewrites slash-leading argv values for native executables.
1532
+ # next_command is command text, not a filesystem path; preserve it for jq.
1533
+ # When cygpath is available, convert the slurpfile paths to native Windows
1534
+ # paths first so native jq can open them while MSYS_NO_PATHCONV protects the
1535
+ # slash-leading command text. On POSIX systems the paths stay unchanged.
1536
+ jq_slurpfile_path() {
1537
+ local path="$1"
1538
+ if command -v cygpath >/dev/null 2>&1; then
1539
+ cygpath -m "$path"
1540
+ else
1541
+ printf '%s\n' "$path"
1542
+ fi
1543
+ }
1544
+ COMMITTED_PATHS_JQ_FILE="$(jq_slurpfile_path "$COMMITTED_PATHS_FILE")"
1545
+ STAGE_FAILURES_JQ_FILE="$(jq_slurpfile_path "$STAGE_FAILURES_FILE")"
1546
+ SKIPPED_PATHS_JQ_FILE="$(jq_slurpfile_path "$SKIPPED_PATHS_FILE")"
1547
+ MSYS_NO_PATHCONV=1 jq -n \
630
1548
  --arg thread_id "$THREAD_ID" \
631
1549
  --arg thread_path "$THREAD_PATH" \
632
1550
  --arg handoff_path "workspace/threads/handoff.json" \
@@ -637,33 +1555,47 @@ jq -n \
637
1555
  --arg changeset_path "$CHANGESET_PATH" \
638
1556
  --arg hq_commit_status "$HQ_COMMIT_STATUS" \
639
1557
  --arg hq_commit_error "$HQ_COMMIT_ERROR" \
640
- --slurpfile committed_paths "$COMMITTED_PATHS_FILE" \
641
- --slurpfile stage_failures "$STAGE_FAILURES_FILE" \
642
- --slurpfile skipped_paths "$SKIPPED_PATHS_FILE" \
1558
+ --slurpfile committed_paths "$COMMITTED_PATHS_JQ_FILE" \
1559
+ --slurpfile stage_failures "$STAGE_FAILURES_JQ_FILE" \
1560
+ --arg stage_failure_class "$STAGE_FAILURE_CLASS" \
1561
+ --argjson index_lock_waits "$HQ_HANDOFF_INDEX_LOCK_WAITS" \
1562
+ --argjson stale_index_lock_removed "$HQ_HANDOFF_STALE_LOCK_REMOVED" \
1563
+ --slurpfile skipped_paths "$SKIPPED_PATHS_JQ_FILE" \
1564
+ --arg nested_repo_paths "$NESTED_REPO_PATHS" \
643
1565
  --argjson baseline_noise_count "$BASELINE_NOISE_COUNT" \
644
1566
  --arg commit_after_finalize "$COMMIT_AFTER" \
645
1567
  --arg next_command "$NEXT_COMMAND" \
646
1568
  --argjson clipboard_copied "$CLIPBOARD_COPIED" \
647
1569
  --argjson mirror_companies "$MIRRORED_COMPANIES_JSON" \
1570
+ --arg handoff_publish_pid "${HANDOFF_PUBLISH_PID:-}" \
1571
+ --arg handoff_publish_status "${HANDOFF_PUBLISH_STATUS:-skipped}" \
1572
+ --argjson pointer_kept_newer "$POINTER_KEPT_NEWER" \
648
1573
  '{
649
1574
  thread_id: $thread_id,
650
1575
  thread_path: $thread_path,
651
1576
  changeset_path: $changeset_path,
652
1577
  handoff_path: $handoff_path,
1578
+ pointer_kept_newer: $pointer_kept_newer,
653
1579
  hq_committed: $hq_committed,
654
1580
  hq_commit_status: $hq_commit_status,
655
1581
  hq_commit_error: $hq_commit_error,
656
1582
  commit_after_finalize: $commit_after_finalize,
657
1583
  committed_paths: ($committed_paths[0] // []),
658
1584
  stage_failures: ($stage_failures[0] // []),
1585
+ stage_failure_class: $stage_failure_class,
1586
+ index_lock_waits: $index_lock_waits,
1587
+ stale_index_lock_removed: $stale_index_lock_removed,
659
1588
  skipped_paths: ($skipped_paths[0] // []),
1589
+ nested_repo_paths: ($nested_repo_paths | split("\n") | map(select(length > 0))),
660
1590
  baseline_noise_count: $baseline_noise_count,
661
1591
  indexes_regen: $indexes_regen,
662
1592
  qmd_pid: $qmd_pid,
663
1593
  git_bg_errors: $git_bg_errors,
664
1594
  next_command: $next_command,
665
1595
  clipboard_copied: $clipboard_copied,
666
- mirror_companies: $mirror_companies
1596
+ mirror_companies: $mirror_companies,
1597
+ handoff_publish_pid: $handoff_publish_pid,
1598
+ handoff_publish_status: $handoff_publish_status
667
1599
  }'
668
1600
 
669
1601
  # -------- fail loudly on a git write that did not land --------
@@ -685,4 +1617,7 @@ case "$HQ_COMMIT_STATUS" in
685
1617
  exit 4
686
1618
  ;;
687
1619
  esac
1620
+ if [[ "${COMPANY_MIRROR_FAILED:-0}" -eq 1 ]]; then
1621
+ exit 5
1622
+ fi
688
1623
  exit 0