Skip to content

Latest commit

 

History

History
167 lines (125 loc) · 7.81 KB

label-sync-lib.md

File metadata and controls

167 lines (125 loc) · 7.81 KB

hooks/label-sync-lib.sh

Revision: 1 Last modified: 2026-12-04T19:00:00Z

Overview

This is a SOURCE-ONLY helper library. It defines functions and variables for the label-sync hook scripts; it produces no output of its own and is not runnable as a command.

Every label-sync Claude Code hook (label-sync-<event>.sh) sources this file. It gives them one shared answer to four questions that would otherwise be answered four times, differently:

  1. Where is the labelctl binary? — resolved via bincache.sh, with a detached background build kicked off when it is missing or stale.
  2. What did the hook receive? — the stdin payload is read once and parsed into shell variables.
  3. What is the live label? — track / branch / alias / model / effort, derived by the canonical labeler rather than re-derived per hook.
  4. How do I fail safely and fast? — bounded-latency, fail-soft primitives, because a hook that hangs or errors degrades the whole session.

Nothing here prints to stdout on its own. Hooks decide their own output; a library that printed would corrupt an additionalContext payload.

Hooks never break the session

Hooks that source this library always exit 0. That is the fail-soft contract: a label-sync fault is a reporting gap, not a reason to block a prompt, a tool call or a turn. LABEL_SYNC_DISABLE=1 makes every hook a silent no-op, which is the kill switch if the system itself is the problem.

Prerequisites

  • bash, jq, and labelctl-capable sources (or a prebuilt binary via the cache).
  • Sourced from a directory alongside this file (${BASH_SOURCE[0]} is used to resolve paths).
  • bincache.sh reachable through the label-sync module.

Environment variables (names only):

Variable Meaning
LABEL_SYNC_DIR State dir (CONTRACT §1; tests point it at a temp dir).
LABEL_SYNC_BIN Binary cache dir, as for labelctl.sh.
LABEL_SYNC_LABELER Canonical labeler (default: the sibling multitrack labeler).
LABEL_SYNC_DISABLE 1 = every hook becomes a silent no-op.
LABEL_SYNC_NO_BUILD 1 = never spawn the background binary build.
LABEL_SYNC_CLAUDE_PID Override the discovered claude process pid.
LABEL_SYNC_HOOK_DEBUG 1 = append hook diagnostics to $LABEL_SYNC_DIR/hooks/debug.log.
LABEL_SYNC_DEBUG 1 = let hook stderr through (ledger failures are reported there).
LABEL_SYNC_CTL_TIMEOUT Optional per-labelctl-call timeout in seconds (default: none).
LABEL_SYNC_HOOK_LOCK_TIMEOUT Writer-lock wait per call (default 500ms).

Usage examples

#!/usr/bin/env bash
. "$(dirname "${BASH_SOURCE[0]}")/label-sync-lib.sh"

ls_init || exit 0          # returns 1 => the hook must exit 0 silently
ls_read_payload            # stdin JSON -> LS_* variables
ls_derive                  # derive the live label fields
ls_emit_context            # print additionalContext for the model
exit 0                     # hooks ALWAYS exit 0

Exported surface

Setup and binary resolution

Function Contract
ls_init Resolves paths and state. Returns 1 when the hook must exit 0 silently (disabled, unresolvable, etc.).
ls_have_bin Is a usable labelctl binary available?
ls_kick_build Spawns one detached labelctl.sh --build when the binary is missing/stale.
ls_ctl <args...> Invokes labelctl with the bounded-latency and lock-timeout machinery.
ls_hookdir The hook-private state directory.
ls_drop_pending_dir Removes the pending-subagent directory for the session.

Payload and identity

Function Contract
ls_read_payload Reads the hook JSON from stdin once into LS_* variables.
ls_claude_pid Discovers (or takes the override for) the owning claude pid.
ls_session_entity Prints the entity id form session:<sid>.
ls_valid_id <id> Validates an id against LS_ID_RE.
ls_ensure_session Level-triggered: registers the session entity if missing.
ls_transcript_path Resolves the session transcript path.

Label derivation

Function Contract
ls_derive Derives the live label fields for the payload.
ls_parse_label Parses a label string into its fields.
ls_model_short Short model name (e.g. opus) for display.
ls_record_model_switch / ls_switched_model / ls_drop_model_switch Track a mid-session model switch so the next emission reflects it.

Output and plumbing

Function Contract
ls_emit_context Emits the additionalContext JSON for the model (stdout, hook exits 0).
ls_flock Bounded writer-lock helper (uses flock -w when available).
ls_hook_run The standard fail-soft hook wrapper.
ls_dbg Debug line, only when LABEL_SYNC_HOOK_DEBUG=1; never stdout, never stderr.

Exit codes

The library has no exit codes — it is sourced and returns. Its documented contract is "Exit: n/a (library). Hooks that source it ALWAYS exit 0 (fail-soft)."

Two functions return statuses a caller must honour:

  • ls_init returns 1 ⇒ the hook must exit 0 silently (do not treat it as an error to report).
  • ls_valid_id returns non-zero for an invalid id.

Side effects

  • Creates $LABEL_SYNC_DIR/hooks/{pending,agentmap,ledger-last,modelswitch} with mode 0700, for hook-private correlation state.
  • May spawn one detached labelctl.sh --build.

Both are documented and are why it pre-creates its directories with a restrictive mode rather than inheriting the ambient umask.

Edge cases

  • LABEL_SYNC_DISABLE=1. Every hook becomes a silent no-op — the kill switch.
  • Binary missing or stale. One detached build is kicked off and the hook proceeds without it; the hook must not block on a build. LABEL_SYNC_NO_BUILD=1 suppresses even that.
  • Lock held by another writer. With --lock-timeout 500ms, a busy lock makes labelctl exit 2 promptly rather than stalling the hook.
  • No flock on the host. Falls back to invoking the command without the lock rather than failing.
  • A malformed stdin payload. ls_init / ls_read_payload fail soft; the hook exits 0.
  • Diagnostics wanted. LABEL_SYNC_HOOK_DEBUG=1 writes to hooks/debug.log — never to stdout, because stdout carries the additionalContext payload.

Internal behaviour

  1. On source, defines the functions and resolves the module directory from ${BASH_SOURCE[0]}.
  2. ls_init resolves state paths, checks the kill switch, and reports 1 when the hook should bail silently.
  3. ls_read_payload reads stdin once (a second read would see nothing) and parses the fields.
  4. ls_derive invokes the canonical labeler to obtain track/branch/alias/model/effort rather than re-deriving them.
  5. ls_emit_context prints the additionalContext JSON so the model sees its live label.
  6. ls_hook_run wraps the above with fail-soft error handling and the bounded timeouts.

Related scripts

Sourced by every hook in scripts/label-sync/hooks/ — including label-sync-session-start.sh, label-sync-prompt.sh, label-sync-stop.sh, label-sync-agent-register.sh, label-sync-subagent-start.sh, label-sync-subagent-stop.sh, label-sync-session-end.sh and label-sync-model-switch.sh.

Uses scripts/label-sync/bincache.sh (staleness rule) and scripts/label-sync/labelctl.sh (binary entry).

Cross-reference: docs/label-sync/CONTRACT.md (§1, §4.2, §4.3).

See also docs/scripts/bincache.md, docs/scripts/labelctl.md, docs/scripts/label-sync-prompt.md and docs/scripts/request_history_append.md.

Last verified

2026-12-04 — bash -n scripts/label-sync/hooks/label-sync-lib.sh → exit 0. Sourcing it in a bash shell and running type ls_init prints the function definition (source succeeds, nothing executes).