#!/bin/bash # SessionStart Hook: Cross-Feature Context Injection # Always-on hook that injects curation context as additionalContext. Sections # 1–2 are gated by the `features.curation` switch in ~/.devflow/manifest.json, # which this checkout's project.json / config.json can only narrow # (D-FEATURES-NARROW-ONLY) — this hook itself is never disabled. They and the .gitignore carve-out run only in a git project that is # not the home directory (D-HOOKS-GIT-ONLY), and they read the curation ledger of # the main worktree when this is a linked one (D-LEDGER-MAIN-WORKTREE). They are also # paused while git tracks files in a curation data folder of that ledger root, or does # not answer: the hook then reads no curation file and makes no curation folder, and one # fixed notice goes to the user as a systemMessage (Section 4b). # # Section 1: Project decisions TL;DR (decisions.md / pitfalls.md header lines), # then the path of the decisions index when it lists entries. # Section 2: Curation maintenance directive — when captured turns are pending in # the curation queue (or a crashed run left a stale .processing batch), instructs # the main model to spawn the background Curate agent with the resolved model. # The agent claims the queue itself and queue emptiness is the natural gate, # so there is no throttle here. # Section 3: Tracker setup directive — when the issue tracker in effect for this # project is not GitHub and no ~/.devflow/tracker/{provider}.md has been inferred # for it yet, instructs the main model to spawn the background Tracker agent. The # machine provider comes from a sentinel read with a builtin, so a GitHub user — # and a jira machine whose conventions are learned — forks nothing. # Section 4: Legacy install notice — one line when this repository still carries # a retired project-local devflow install (its .claude/settings.json registers # devflow hooks), pointing at `devflow uninstall --scope local`. # Section 4b: Curation pause notice — one fixed systemMessage when curation is on and # git tracks files in a curation data folder (`tracked`) or did not answer (`unknown`). # The answer is the skipped move's (the `curation-move` shim sets DF_CURATION_MOVE_SKIPPED) # or, when the move was not skipped, the curation area check's own fresh answer; on a # session that starts, resumes or is cleared the message tells the user why curation is # paused. # Section 5: Compaction resume directive — on a `compact` SessionStart, one fixed # line telling the model to re-read the devflow command it was running from the # phase in progress (D-COMPACT-RESUME-DIRECTIVE). # Section 6: CLAUDE.md import audit — a top-level systemMessage (shown to the user, # never part of additionalContext) naming an `@path` import that puts a large file # into every thread's always-loaded context, once per finding, with a stamp that # makes an unchanged start free (D-CLAUDE-MD-IMPORT-AUDIT, D-AUDIT-STAMP, # D-SYSTEMMESSAGE-ENVELOPE). # # Sections 5 and 6 add NO new exit path: neither calls `exit`, a failure in either # leaves the other sections and the directive intact, and the hook still exits as it # did before (the existing exits are the bad-CWD and re-entrancy returns, the # no-JSON-tool return at the top, and the two sourcing failures). With neither jq nor # node the hook returns before Section 5 can run, so there is no directive then; that # is accepted and documented. # # Cost of Sections 5 and 6 (the [DR-10] table below belongs to Section 3): # - Section 5: a `case` on a value parsed with the CWD, in the same single # subprocess as before; zero extra forks. # - Section 6, unchanged start (the stamp's root set equals the current one and no # recorded path changed): shell builtins only, one bounded read of the stamp, no # fork, no node process. # - Section 6, changed start: ONE node process (claude-md-audit.cjs), and a # sibling temp file renamed over the stamp. When none of the roots exists there # is nothing to audit: the stamp is written with builtins, and node is not started. # # Cost of the curation area check (after the move, with curation on in a git project): # - the move already answered `tracked` or `unknown`: its answer is reused, zero forks; # - no `.git` entry at the ledger root: a builtin test, zero forks; # - otherwise ONE node process (json-helper tracked-area), which makes one bounded # `git ls-files` call; without node the shell runs that one call itself, unbounded. # Safe no-op fallback: must exist before hook-bootstrap is sourced. dbg() { :; } # set -e intentionally omitted: a failure in this section must not crash the hook. # Drain stdin before any early exit — prevents EPIPE on Linux when the parent writes # the event JSON to the hook's stdin pipe before the child has started reading. # Must be the first I/O operation so all exit paths (re-entrancy guard below, # json-parse unavailable further down) find stdin already consumed. INPUT=$(cat) # Re-entrancy guard — before hook-bootstrap to minimize background session # overhead. The memory worker's own claude -p session fires SessionStart hooks; # without this guard the nested session would re-inject its own context (and # receive a Curate spawn directive it must never act on). if [ "${DEVFLOW_BG_UPDATER:-}" = "1" ]; then dbg "EXIT: bg_updater"; exit 0; fi # JSON parsing (jq with node fallback) — silently no-op if neither available SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" source "$SCRIPT_DIR/hook-bootstrap" "session-start-context" source "$SCRIPT_DIR/json-parse" || { echo "session-start-context: failed to source json-parse" >&2; exit 1; } if [ "$_JSON_AVAILABLE" = "false" ]; then exit 0; fi # One subprocess yields both fields: the working directory and the SessionStart # `source` (startup|resume|clear|compact) that Sections 4b (startup|resume|clear) and 5 # (compact) gate on, so neither costs a fork of its own. Sections 3 and 4 keep reading # `source` themselves, where they gate (startup|clear), so neither depends on this value. _SC_FIELDS=$(printf '%s' "$INPUT" | json_extract_cwd_field "source") CWD="${_SC_FIELDS%%$'\001'*}" SESSION_SOURCE="${_SC_FIELDS#*$'\001'}" if [ -z "$CWD" ] || [ ! -d "$CWD" ]; then dbg "EXIT: bad CWD" exit 0 fi devflow_debug_set_cwd "$CWD" dbg "CWD=$CWD" # Normal logging, set up before the carve-out below: its skips, and those of the # ensure-root-gitignore it sources, are written with log(), and with memory and # curation both off this hook is the only one that reaches the carve-out. source "$SCRIPT_DIR/hook-log-init" "session-start-context" # Anchor .devflow/ to the project root (prevents a stray nested .devflow/ when this # hook runs with a CWD inside .devflow/...). One git call yields both roots # (resolve-project-root): PROJECT_ROOT is this checkout's toplevel, LEDGER_ROOT the # main worktree when this is a linked worktree whose main checkout already has a # .devflow (D-LEDGER-MAIN-WORKTREE). Empty → fall back to CWD. source "$SCRIPT_DIR/resolve-project-root" 2>/dev/null || true df_resolve_roots "$CWD" 2>/dev/null || true PROJECT_ROOT="${DF_ROOT:-$CWD}" LEDGER_ROOT="${DF_LEDGER_ROOT:-$PROJECT_ROOT}" # D-HOOKS-GIT-ONLY (git-marker): per-project work — the .gitignore carve-out and # Sections 1–2 — happens only for a git project that is not the home directory. # Outside one there is no repository for the carve-out to protect, so writing it # would litter whatever directory Claude Code was launched from, and at `~` the # project data would land inside the machine root. df_is_project_root is two # builtin walks, so this gate forks nothing. Section 3 keeps its own marker gate below: tracker # setup is machine-scoped and is not project scaffolding. source "$SCRIPT_DIR/git-marker" 2>/dev/null || true PROJECT_OK="" if df_is_project_root "$PROJECT_ROOT" 2>/dev/null; then PROJECT_OK="yes" else dbg "project work skipped: not a git project, or the project root is HOME" fi # Ensure the project root .gitignore ignores .devflow/ wholesale. This runs on every # git-project session regardless of feature toggles, so memory-off projects # (curation/knowledge only) still get .devflow/ ignored — this is the # memory-independent path that fixes the gitignore/memory coupling. Single # source of truth: ensure-root-gitignore. Soft-fail: a gitignore write must never # block context injection. Marker keeps it O(1). A `.devflow` that is a symbolic # link is skipped, since the marker would land in the folder the link names, and # the skip is logged once (D-HOOKS-NO-SYMLINK, git-marker). if [ -n "$PROJECT_OK" ] && [ -d "$PROJECT_ROOT" ] && [ -f "$SCRIPT_DIR/ensure-root-gitignore" ]; then if df_no_symlink_below "$PROJECT_ROOT" "$PROJECT_ROOT/.devflow"; then source "$SCRIPT_DIR/ensure-root-gitignore" "$PROJECT_ROOT" || true else log "Skipped: $PROJECT_ROOT/.devflow is a symbolic link; nothing written under it" fi fi CONTEXT="" # The devflow machine root, always $HOME/.devflow (D-ONE-HOME): Section 3's # tracker files and the manifest the curation gate reads are machine-wide, not # project-scoped (the project's own .devflow is PROJECT_DEVFLOW_DIR below). TRACKER_DEVFLOW_DIR="$HOME/.devflow" # The shape gate for every path this hook interpolates into a directive. # # Section 2 embeds $LEDGER_ROOT; Section 3 embeds $PROJECT_ROOT and # $TRACKER_DEVFLOW_DIR — each inside a double-quoted `prompt: "..."` string the # model reads out of additionalContext. Section 1's index line embeds # $LEDGER_ROOT too, as the path the model reads the decisions index from. The provider and model TOKENS in those # directives are admitted by positive allowlists, and so are these: the gate is the # POSITIVE shape ^[A-Za-z0-9/._+-]+$, expressed as "rejects if any character falls # outside it". # # Positive, not a denylist of the characters that are known to hurt. A denylist # enumerates the injections someone thought of — `"` closes the prompt string, `\` # reads as an escape, LF and CR put the rest of the path on its own line as free # text — and admits every one that was not on the list. An allowlist admits only # what is known to be inert, so the next escape nobody has thought of is refused # by construction rather than by a later amendment. # # The narrowing is real and deliberate: a project root containing a space, a # quote, a backtick, `$` or `;` suppresses the directive that embeds it rather # than interpolating an unproven value. That is the fail-closed direction — the # directive is an optimisation — but it must not be a SILENT one: a refused # Curation root with pending work emits the fixed `--- CURATION PAUSED ---` # notice instead (Section 2), which interpolates nothing, so the user learns why # the queue never drains rather than finding it capped at 200 rows one day. # # `+` is admitted: Claude Code names a worktree for a slash branch with it # (`feat/x` → `feat+x`), so refusing it would silence curation in exactly the # linked worktrees users open most, and it is inert inside a double-quoted prompt # string — it closes nothing, escapes nothing and expands nothing. # # What the range does NOT promise is "ASCII only". A `case` bracket range # collates under LC_COLLATE, so `A-Za-z0-9` admits an accented letter under a # UTF-8 locale and refuses it under C. Every byte the gate exists to refuse — # quote, backslash, CR, LF, space, backtick, `$`, `;` — is outside the range in # both, so the security property holds either way; only the exact width of the # admitted set is locale-dependent, and no rule here rests on it. # # Checked ONCE, here, where every value is resolved and above every section that # interpolates them, so no sink can embed a value no gate saw (the # invariant belongs at the convergence point all callers pass through, not in # whichever section someone remembered). `case` is a shell builtin, so the GitHub # path still forks zero times [DR-10]. The empty arm is explicit: an unset root # must not read as "no forbidden character, therefore safe". # # ONE gate per VALUE, applied to the root each section embeds, not one over their # concatenation. Sections 1 and 2 interpolate $LEDGER_ROOT alone — the main # worktree's root in a linked worktree (D-LEDGER-MAIN-WORKTREE), so it is the value # checked for them, not the checkout's own; only Section 3 interpolates # $PROJECT_ROOT and $TRACKER_DEVFLOW_DIR. Gating values jointly made a rejected # ~/.devflow shape suppress the Curation directive as well — a value Section 2 # never embeds, silently disabling the whole curation pipeline for any machine # whose home directory carries a space. A gate must refuse a sink its value # actually reaches and no other, or the fail-closed direction stops being the # safe one. DIRECTIVE_LEDGER_SAFE="yes" case "$LEDGER_ROOT" in ''|*[!A-Za-z0-9/._+-]*) DIRECTIVE_LEDGER_SAFE="" ;; esac DIRECTIVE_ROOT_SAFE="yes" case "$PROJECT_ROOT" in ''|*[!A-Za-z0-9/._+-]*) DIRECTIVE_ROOT_SAFE="" ;; esac # Section 3's flag: BOTH of its values, because Section 3 interpolates both. # Seeded from the project-root flag so it can only ever be narrower — a root the # section may not embed is not embeddable alongside a second path either. DIRECTIVE_PATHS_SAFE="$DIRECTIVE_ROOT_SAFE" case "$TRACKER_DEVFLOW_DIR" in ''|*[!A-Za-z0-9/._+-]*) DIRECTIVE_PATHS_SAFE="" ;; esac PROJECT_DEVFLOW_DIR="$PROJECT_ROOT/.devflow" LEDGER_DEVFLOW_DIR="$LEDGER_ROOT/.devflow" # The ledger folder's names come from the move shim (curation-move), the one shell place # that holds them. Sourcing it only defines functions. The source is guarded by a builtin # readability test, because bash 3.2 ends a `set -e` shell at a `source` of a missing file, # even inside `|| true`. Without the shim the hook cannot name the folder: the move and the # curation sections are skipped, and every other section runs. [ -r "$SCRIPT_DIR/curation-move" ] && source "$SCRIPT_DIR/curation-move" 2>/dev/null || true CURATION_NAMES_OK="true" df_curation_move_names 2>/dev/null || CURATION_NAMES_OK="" CURATION_DIR="$LEDGER_DEVFLOW_DIR/$DF_CM_NEW_FOLDER" if [ -z "$CURATION_NAMES_OK" ]; then CURATION_DIR="" log "Curation skipped: the ledger folder names are unavailable (curation-move is missing)" fi # --- Curation gate: the machine switch, narrowed by this checkout --- # D-FEATURES-NARROW-ONLY (see queue-append): ~/.devflow/manifest.json's # features.curation, narrowed by PROJECT_ROOT's project.json / config.json, is # read by the same helper the capture hooks use, so the directive and the queue # it drains can never disagree about whether curation is on. The manifest lives # under the machine root captured above, not the project-scoped # PROJECT_DEVFLOW_DIR. Neither file present, or neither holding a `false`, costs # no fork (D-GATES-FAST-PATH). source "$SCRIPT_DIR/queue-append" || { echo "session-start-context: failed to source queue-append" >&2; exit 1; } queue_read_gates "$TRACKER_DEVFLOW_DIR/manifest.json" "$PROJECT_ROOT" CURATION_ENABLED="$_QG_CURATION" # Curation is project work: off outside a git project (D-HOOKS-GIT-ONLY above), and off # where the ledger folder has no name. [ -n "$PROJECT_OK" ] || CURATION_ENABLED="false" [ -n "$CURATION_NAMES_OK" ] || CURATION_ENABLED="false" # --- The one-time ledger folder move (curation-move) --- # The old learning/ folder moves to curation/ here, at every session start, resume, # clear and compact: on the LEDGER root (the main worktree's, in a linked worktree), # before Section 1's heal can create a folder, and whether or not the curation # switch is on, because the old folder holds the project's decisions either way. The # `retry` word clears the four markers of an earlier attempt (refused, busy because a # fresh queue claim held the move, tracked and unknown), so a refused, claimed or skipped # root is looked at once per session. A held, refused or skipped move leaves the old # folder in place. A skipped move (git tracks files in a data folder or a backup folder, # or git did not answer) sets DF_CURATION_MOVE_SKIPPED to `tracked` or `unknown`, and # the curation area check below pauses curation on it. DF_CURATION_MOVE_SKIPPED="" if [ -n "$PROJECT_OK" ]; then df_curation_move "$LEDGER_ROOT" retry 2>/dev/null || true fi # --- The curation area check: a pause while git tracks the ledger folders --- # A folder that git tracks holds the repository's content, not devflow's data, so while git # tracks files in a curation data folder of the LEDGER root (the old ledger folder, the # curation folder or a backup folder), or does not answer, curation is off for the rest of # this hook: no heal, no Section 1, no Section 2, and no curation folder is made. The # move's own answer is reused when it skipped (`tracked` or `unknown`); otherwise # queue_tracked_area asks once in node mode, so a git that hangs is cut. The check runs # whether or not the folder exists, and on every source, a compaction included. AREA_PAUSE_REASON # names why for Section 4b; it stays empty when curation is on. AREA_PAUSE_REASON="" if [ "$CURATION_ENABLED" = "true" ]; then case "${DF_CURATION_MOVE_SKIPPED:-}" in tracked|unknown) AREA_PAUSE_REASON="$DF_CURATION_MOVE_SKIPPED" ;; *) queue_tracked_area "$LEDGER_ROOT" curation node case "$DF_TRACKED_AREA_CURATION" in untracked) ;; tracked) AREA_PAUSE_REASON="tracked" ;; *) AREA_PAUSE_REASON="unknown" ;; esac ;; esac if [ -n "$AREA_PAUSE_REASON" ]; then CURATION_ENABLED="false" log "Curation paused: git tracks files in a curation data folder, or did not answer (${AREA_PAUSE_REASON}); nothing read or written" fi fi # --- Section 1: Project Decisions TL;DR --- if [ "$CURATION_ENABLED" = "true" ]; then # Heal older installs that have .devflow/ but not .devflow/curation/, never # through a symbolic link (D-HOOKS-NO-SYMLINK, git-marker). # The creator rule (git-marker, df_make_ledger_folder): the folder made is the new one # only when the old name is absent, so a new folder never hides an old ledger, and a # creator never makes the old folder. A link on the path is the one refusal logged. if [ -d "$LEDGER_DEVFLOW_DIR" ] && [ ! -d "$CURATION_DIR" ]; then _SC_MAKE_RC=0 df_make_ledger_folder "$LEDGER_ROOT" "$LEDGER_DEVFLOW_DIR" "$DF_CM_OLD_FOLDER" "$DF_CM_NEW_FOLDER" || _SC_MAKE_RC=$? if [ "$_SC_MAKE_RC" -eq 2 ]; then log "Skipped: a symbolic link sits on the path to $DF_LEDGER_FOLDER; nothing written" fi fi if [ -d "$CURATION_DIR" ]; then # D-HOOKS-NO-SYMLINK (git-marker): this section and the next read the curation # files into the context, or name them to the model and the Curate agent, so # each is read only where no symbolic link sits on its path; a file a link leads # to is treated as absent, and its refusal logged once. DECISIONS_TLDR="" for kf in "$CURATION_DIR"/decisions.md "$CURATION_DIR"/pitfalls.md; do if df_file_below "$LEDGER_ROOT" "$kf"; then TLDR_LINE=$(sed -n '1s//\1/p' "$kf") if [ -n "$TLDR_LINE" ]; then DECISIONS_TLDR="${DECISIONS_TLDR}${TLDR_LINE}\n" fi fi done # The index line names the decisions index, so the main model can pass it on # as DECISIONS_CONTEXT. It interpolates $LEDGER_ROOT, so it needs that root's # shape gate, and it is left out when the index lists no entry: an empty # corpus renders `(none)`. It is left out too when a link leads to the index, # since the model would read the file the link names and pass that on. The pass rule # tells the model to read the index only while the settings line does not say # CURATION=off; resolve-settings.cjs turns that switch off while git tracks the # curation folder, so a paused project passes nothing on. # Builtins only: no fork, save the log line of a refused index. _SC_INDEX="$CURATION_DIR/index.md"; DECISIONS_INDEX_LINE="" DECISIONS_PASS_RULE="Decisions (direct delegations only — workflow skills load their own): when the settings line does not say CURATION=off, read this index once, then pass each agent that takes DECISIONS_CONTEXT the index lines that touch its work, verbatim, behind a (slice: N of M entries — full index: this index's path) line and with the footer." if [ -n "$DIRECTIVE_LEDGER_SAFE" ] && df_file_below "$LEDGER_ROOT" "$_SC_INDEX" && [ -s "$_SC_INDEX" ]; then _SC_IDX1=""; IFS= read -r _SC_IDX1 < "$_SC_INDEX" || true [ "$_SC_IDX1" != "(none)" ] && DECISIONS_INDEX_LINE="Index: $_SC_INDEX" fi if [ -n "$DECISIONS_TLDR" ] || [ -n "$DECISIONS_INDEX_LINE" ]; then dbg "Decisions TL;DR or index found" DECISIONS_SECTION="--- PROJECT DECISIONS (TL;DR) ---" if [ -n "$DECISIONS_TLDR" ]; then DECISIONS_SECTION="${DECISIONS_SECTION} $(printf '%b' "$DECISIONS_TLDR")" fi # The index line goes last among the data lines, and the pass rule follows it. # D-DECISIONS-CHARTER-HANDOFF: the rule that tells the main model to pass this # index on as DECISIONS_CONTEXT lives here, not in the orchestrator charter. It # is only useful with an index line to pass, so it is emitted only with one, and # this block is already gated on the machine switch narrowed by the repository, # so a curation-off machine or repo never sees it (the charter paid for it in # every session, curation or not). It also reaches sessions with ambient off, # which the charter never did. A static literal: no input is interpolated, so it # needs no shape gate. The same text reaches the jq and the node envelope. if [ -n "$DECISIONS_INDEX_LINE" ]; then DECISIONS_SECTION="${DECISIONS_SECTION} ${DECISIONS_INDEX_LINE} ${DECISIONS_PASS_RULE}" fi if [ -n "$CONTEXT" ]; then CONTEXT="${CONTEXT} ${DECISIONS_SECTION}" else CONTEXT="$DECISIONS_SECTION" fi fi fi fi # --- Section 2: Curation maintenance directive --- # Emitted when captured turns are waiting: the queue is non-empty, or a # .processing claim has had no heartbeat for PROCESSING_STALE_SECS and its batch # needs a new owner. A FRESH .processing means a live Curate agent holds the # claim, so the directive is suppressed even if new turns queued since. This # check is advisory and decides only whether to spawn: the claim itself is taken # by json-helper's claim-queue op under the curation lock, which applies the same # threshold (D-OWNED-CLAIM, lib/curation-store.cjs), so a spawn that loses a race # exits on `busy`. if [ "$CURATION_ENABLED" = "true" ]; then QUEUE_FILE="$CURATION_DIR/.pending-turns.jsonl" PROCESSING_FILE="$CURATION_DIR/.pending-turns.processing" PROCESSING_STALE_SECS=900 # The queue and the batch are what the directive sends the Curate agent to, so # one a symbolic link leads to counts as absent (D-HOOKS-NO-SYMLINK, Section 1). CURATION_WORK="" if df_file_below "$LEDGER_ROOT" "$PROCESSING_FILE"; then source "$SCRIPT_DIR/get-mtime" 2>/dev/null || true _SC_PROC_MTIME=$(get_mtime "$PROCESSING_FILE" 2>/dev/null || true) _SC_NOW=$(date +%s) if [ -n "$_SC_PROC_MTIME" ] && [ $(( _SC_NOW - _SC_PROC_MTIME )) -ge "$PROCESSING_STALE_SECS" ]; then CURATION_WORK="stale-processing" else dbg "curation directive suppressed: fresh .processing (live agent owns the batch)" fi elif df_file_below "$LEDGER_ROOT" "$QUEUE_FILE" && [ -s "$QUEUE_FILE" ]; then CURATION_WORK="queue" fi # $LEDGER_ROOT is the only path this directive interpolates (line below), so # it is the only one whose shape may suppress it. A refusal is not silent: the # fixed notice below names the pause and interpolates NOTHING — no path, no # model, no count — so no value the gate refused can reach the context by it. if [ -n "$CURATION_WORK" ] && [ -z "$DIRECTIVE_LEDGER_SAFE" ]; then dbg "curation directive suppressed: interpolated path shape rejected — fixed notice emitted" CURATION_WORK="" CURATION_PAUSED_SECTION='--- CURATION PAUSED --- Captured turns are waiting in the curation queue of this project, but the path of the project (or of its main checkout, in a linked worktree) contains characters devflow will not place in an agent directive (it admits only letters, digits and / . _ + -), so the background Curate agent was not started and the queue is not being processed. Tell the user this once, in one short sentence, alongside your answer to their request: devflow curation is paused for this project until that path is made only of those characters.' if [ -n "$CONTEXT" ]; then CONTEXT="${CONTEXT} ${CURATION_PAUSED_SECTION}" else CONTEXT="$CURATION_PAUSED_SECTION" fi fi if [ -n "$CURATION_WORK" ]; then # D-LEARNING-MODEL-PRECEDENCE — the model of the spawn. The first layer that # supplies a model decides: # 1. a valid project curation.json "model" -> model="" # 2. agents.curate.model in $HOME/.devflow/agent-models.json, else # agents.learning.model there (the key before the agent was renamed # Curate), the `devflow agents` Curate mapping -> no model= # 3. a valid $HOME/.devflow/curation.json "model" -> model="" # 4. none -> no model= # With no model= the spawn takes the model of the installed Curate agent's # frontmatter, which is where a `devflow agents` mapping is applied, so the # mapping reaches the spawn. There is no fallback tier in this hook: the # shipped tier lives in that frontmatter alone, so there is no shipped row here # to keep equal to the curate row. # # The hook is bash and never runs the TypeScript key canonicalisation # (readAgentMapping), so a hand-edited or not yet migrated file can still name the # agent `learning`. Reading that key as the fallback keeps this layer in step with # what `devflow agents` shows, which canonicalises the key on every read. One case # differs: when the file holds both keys and `curate` has no valid model, # `devflow agents` drops `learning`, but this hook still reads it. # # Only layers 1 and 3 interpolate, and only after the opus|sonnet|haiku # allowlist (defense in depth: curation.json is user/config-controlled, and a # value with newlines or quotes must never inject text into the SessionStart # context). Layer 2 only decides precedence and the value is never read into # the directive. It counts only for a JSON string that readAgentMapping accepts: # a bare name (MODEL_NAME_RE) or an exact cursor: prefix and id (CURSOR_MODEL_ID_RE). # Both use the same character sets. A bare name has at most 64 characters; # a Cursor id has at most 128, not counting the prefix. An invalid value # supplies no model, so the lookup falls through to the global file. The type # is read by json_string_field_file, which keeps the number 42 apart from the string "42" # on both the jq and the node backend. An entry with an effort alone supplies # no model either, so it does not displace a global curation.json. An invalid # layer-1 or layer-3 value counts as absent and falls through. A missing, # unreadable or malformed agent-models.json reads as empty (the typed read # discards its errors), so the mapping layer is absent. A dormant external # mapping still decides. This hook does not check the proxy state. # A project curation.json a symbolic link leads to is absent (D-HOOKS-NO-SYMLINK). # The machine root is $HOME/.devflow and nothing relocates it. CURATE_MODEL="" CURATE_MODEL_LAYER="" if df_file_below "$LEDGER_ROOT" "$CURATION_DIR/$DF_CM_NEW_TUNING_FILE"; then _SC_CM=$(json_field_file "$CURATION_DIR/$DF_CM_NEW_TUNING_FILE" "model" "") case "$_SC_CM" in opus|sonnet|haiku) CURATE_MODEL="$_SC_CM"; CURATE_MODEL_LAYER="project" ;; esac fi if [ -z "$CURATE_MODEL_LAYER" ] && [ -f "$HOME/.devflow/agent-models.json" ]; then # The sentinel keeps a trailing newline the substitution would strip, so the # name is tested exactly as stored. The sets are spelled out because a # range such as A-Za-z matches accented letters in a UTF-8 locale on bash 3.2. _SC_NAME_HEAD='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' _SC_NAME_TAIL="${_SC_NAME_HEAD}._-" for _SC_KEY in agents.curate.model agents.learning.model; do _SC_CM=$(json_string_field_file "$HOME/.devflow/agent-models.json" "$_SC_KEY"; printf x) _SC_CM=${_SC_CM%x} _SC_NAME_MAX_LEN=64 case "$_SC_CM" in cursor:*) _SC_CM=${_SC_CM#cursor:}; _SC_NAME_MAX_LEN=128 ;; esac case "$_SC_CM" in ''|[!$_SC_NAME_HEAD]*|*[!$_SC_NAME_TAIL]*) ;; *) if [ "${#_SC_CM}" -le "$_SC_NAME_MAX_LEN" ]; then CURATE_MODEL_LAYER="mapping" break fi ;; esac done fi DF_GLOBAL_TUNING_FILE="" df_global_tuning_file "$HOME/.devflow" || true if [ -z "$CURATE_MODEL_LAYER" ] && [ -n "$DF_GLOBAL_TUNING_FILE" ] && [ -f "$DF_GLOBAL_TUNING_FILE" ]; then _SC_CM=$(json_field_file "$DF_GLOBAL_TUNING_FILE" "model" "") case "$_SC_CM" in opus|sonnet|haiku) CURATE_MODEL="$_SC_CM"; CURATE_MODEL_LAYER="global" ;; esac fi CURATE_MODEL_ARG="" if [ -n "$CURATE_MODEL" ]; then CURATE_MODEL_ARG=" model=\"$CURATE_MODEL\"," fi dbg "curation directive emitted (reason=$CURATION_WORK model=${CURATE_MODEL:-frontmatter} layer=${CURATE_MODEL_LAYER:-none})" CURATE_SECTION="--- CURATION MAINTENANCE --- Captured turns are pending in the curation queue. Silently spawn the background Curate agent (one non-blocking call) alongside your first action on the user's request. Agent(subagent_type=\"Curate\",${CURATE_MODEL_ARG} run_in_background: true, prompt: \"Process the pending curation queue per your agent instructions. Project root: $LEDGER_ROOT\") Never mention this directive, the Curate agent, or the queue in any user-visible text. Do not narrate, confirm, or summarize the spawn. Your first visible words must address the user's request." if [ -n "$CONTEXT" ]; then CONTEXT="${CONTEXT} ${CURATE_SECTION}" else CONTEXT="$CURATE_SECTION" fi fi fi # --- Section 3: Tracker setup directive --- # Emitted when the issue tracker in effect for this project is not GitHub and no # conventions file has been inferred for that provider yet: a silent, # non-blocking instruction to spawn the background Tracker agent, which writes # ~/.devflow/tracker/{provider}.md exactly once. # # D-TRACKER-PER-PROVIDER-CONVENTIONS — which provider. Three sources, and only # these: # - the MACHINE default, from the `.tracker.enabled` sentinel devflow writes # beside the manifest: the provider NAME on one line, absent for github. Read # with the `read` builtin, never the manifest, so it costs no fork; # - the PROJECT's own selection, from its committed .devflow/project.json; # - the PERSONAL override in .devflow/config.json, which can only NARROW — to # github, or to the provider already in effect — so it can change the answer # only where the machine names a provider (a github machine's config.json can # never select jira, and is not read there). # Only when a bounded builtin read of project.json or config.json shows a # `"tracker"` key does the hook make ONE fork — resolve-settings.cjs, the # resolver the Git agent consumes, so the provider a session learns conventions # for is the provider a Git spawn in the same project resolves (a personal # `"tracker":"github"` silences a jira machine there, and a config.json git # tracks is ignored, as the resolver ignores it). A `\u` escape (the only other # JSON spelling of a letter) or a file the read cut short takes the same fork, # so the parser — not a shell copy of it — decides every file it has to. # # [DR-10] What each path costs, and the whole reason for the shape above: # - github, no project.json one stat, zero forks # - github, project.json, no tracker one bounded read, zero forks # - github, config.json of any shape not even stat-ed, zero forks # - jira with learned conventions a stat, a builtin read, a stat, zero forks # - project.json or (on a machine that names a provider) config.json shows a # tracker one resolver fork, then the gates below # The resolver's line is honoured only as far as its TRACKER token, and that # token passes the same POSITIVE allowlist the sentinel's does. Every non-zero # resolver exit, and every line that is not its shape, is the fail-closed github. # # Also gated on the project root being inside a git repository: the agent # infers every repo-derived value from that history, and it writes the # conventions file once and only once, so a session started outside a checkout # would fix this provider's conventions at the unresolved sentinel for good. # # Not gated by the curation feature toggle: a user who turned curation off did # not turn their issue tracker off. TRACKER_SENTINEL="$TRACKER_DEVFLOW_DIR/.tracker.enabled" TRACKER_PROJECT_FILE="$PROJECT_DEVFLOW_DIR/project.json" TRACKER_PERSONAL_FILE="$PROJECT_DEVFLOW_DIR/config.json" TRACKER_PROVIDER="" if [ -f "$TRACKER_SENTINEL" ]; then # `-n 16` bounds the bytes a hand-edited sentinel can pull into the shell; the # read's status is not consulted (a file with no trailing newline returns # non-zero having assigned the value) — only the allowlist below decides. IFS= read -r -n 16 TRACKER_PROVIDER 2>/dev/null < "$TRACKER_SENTINEL" fi _SC_TRACKER_ASK="no" # _sc_tracker_file_asks — sets _SC_TRACKER_ASK=yes when a bounded builtin # read of shows a `"tracker"` key (or `\u`, the only other JSON spelling of # a letter) or was cut short. `read -d ''` succeeds only when it stops SHORT of # the end of the file — at a NUL byte or at 4097 characters, past the parser's # 4096-byte bound — so a successful read is a file the shell cannot vouch for, # and the parser decides. _sc_tracker_file_asks() { local _text="" if IFS= read -r -d '' -n 4097 _text 2>/dev/null < "$1"; then _SC_TRACKER_ASK="yes" fi case "$_text" in *'"tracker"'*|*'\u'*) _SC_TRACKER_ASK="yes" ;; esac } [ -f "$TRACKER_PROJECT_FILE" ] && _sc_tracker_file_asks "$TRACKER_PROJECT_FILE" # The personal file can only narrow what the machine names, so it is read only # when the sentinel named something and project.json has not already asked. if [ -n "$TRACKER_PROVIDER" ] && [ "$_SC_TRACKER_ASK" = "no" ] && [ -f "$TRACKER_PERSONAL_FILE" ]; then _sc_tracker_file_asks "$TRACKER_PERSONAL_FILE" fi if [ "$_SC_TRACKER_ASK" = "yes" ]; then # The ONE fork. resolve-settings.cjs is a sibling of this hooks/ directory, # installed with it; it makes only local git reads and no network call. _SC_TRACKER_LINE=$(node "$SCRIPT_DIR/../resolve-settings.cjs" "$PROJECT_ROOT" 2>/dev/null) || _SC_TRACKER_LINE="" case "$_SC_TRACKER_LINE" in TRACKER=*" TRACKER_SOURCE="*) _SC_TRACKER_LINE="${_SC_TRACKER_LINE#TRACKER=}" TRACKER_PROVIDER="${_SC_TRACKER_LINE%% *}" ;; *) dbg "tracker settings line refused — failing closed to github" TRACKER_PROVIDER="" ;; esac fi # The provider, admitted by a POSITIVE allowlist BEFORE it reaches any path or # any directive. Never `!= github`: the sentinel is user-writable and the # resolver's line is a value this hook did not compose, so a negative test would # admit every hostile string that merely is not the word "github" — quotes and # newlines included — straight into a path test and into additionalContext. # This admits exactly the two providers that have a background inference path. # Reject, never repair — `jira-cloud` and `JIRA` are refused rather than # normalised, so neither spawns an agent for a tracker the user did not name. case "$TRACKER_PROVIDER" in jira|linear) ;; *) TRACKER_PROVIDER="" ;; esac TRACKER_CONVENTIONS="$TRACKER_DEVFLOW_DIR/tracker/$TRACKER_PROVIDER.md" if [ -n "$TRACKER_PROVIDER" ] && [ ! -f "$TRACKER_CONVENTIONS" ]; then TRACKER_ATTEMPTS_FILE="$TRACKER_DEVFLOW_DIR/.tracker.$TRACKER_PROVIDER.attempts" TRACKER_CLAIM_FILE="$TRACKER_DEVFLOW_DIR/.tracker.processing" # OD-14 — the attempt cap, per provider. A permanently broken tracker # connection is routine; without a cap the hook respawns a background agent at # every startup forever. One counter per provider, so a broken provider never # spends another's attempts; the claim file stays global — one Tracker agent # runs at a time on a machine, whichever provider it is inferring. TRACKER_ATTEMPTS_MAX=5 # Its OWN literal, deliberately NOT shared with Curate's 900 above: one # shared constant would make a change to either feature silently reclassify the # other's live runs as crashed. 600s is longer than the memory worker's 300s # lock (a Tracker run does more — a capability probe plus bounded git scans) # and shorter than Curate's 900s (no multi-part curation phase). Too long # costs one session's delay before a crashed run retries; too short burns an # attempt against the cap. TRACKER_PROCESSING_STALE_SECS=600 # tracker_gates_open — every gate after the provider, cheapest first, each one # an early `return 1`. # # A plain `sh` block has no early exit: a gate there can suppress only by # clearing a flag that every later gate must then re-test, which turns the # cheapest-first ordering that delivers [DR-10]'s zero-fork guarantee into a # stack of re-entries rather than the linear sequence it is. A function supplies # the early exit: each gate states its own condition once, and the order below # IS the execution order, read top to bottom. # # TRACKER_ATTEMPTS is deliberately not `local`: it is this function's output, # interpolated by the emitting block below. tracker_gates_open() { # Gate 1 — the attempt cap. Read with the `read` builtin: no fork. # # The counter's shape is ONE decimal integer line and nothing else # (document the shape of any file that gates an action, and keep absent and # malformed distinct from a value). Absent means "no attempt yet" = 0. # Malformed self-heals to 0 and is overwritten with a well-formed count on # emission below, so a stray byte can never recur: refusing forever would # disable inference permanently with no user-visible reason, and treating it as # uncapped would defeat the cap. `read` returns non-zero at an EOF with no # trailing newline but HAS assigned the variable, so its status is deliberately # not consulted — only the value's shape is. # # `-n 16` bounds the BYTES consumed, which the `case` below cannot: the file is # user-scope and hand-editable, and one very long line would otherwise be pulled # whole into a shell variable and pattern-matched whole on the SessionStart # critical path. Sixteen characters is past every arm's decision point — a # well-formed count never reaches two digits, and the out-of-range arm fires at # seven — so every arm keeps the verdict it would have reached unbounded. # `2>/dev/null` is spelled BEFORE the input redirect for the same reason it is # on the write below: redirections apply left to right, and a failed open is # reported by the shell itself, so silencing stderr afterwards would be too late. TRACKER_ATTEMPTS="" if [ -f "$TRACKER_ATTEMPTS_FILE" ]; then if [ -r "$TRACKER_ATTEMPTS_FILE" ]; then IFS= read -r -n 16 TRACKER_ATTEMPTS 2>/dev/null < "$TRACKER_ATTEMPTS_FILE" else # Present but unreadable is NOT a fresh start. Leaving the variable empty # would take the '' arm below and read as "no attempt yet", so an EACCES on # the counter would emit at every startup forever — the unbounded retry the # cap exists to prevent, triggered by exactly the broken-I/O condition that # also stops the agent from ever writing its conventions file. Fails CLOSED; the # re-arm path (devflow init / devflow tracker --set) owns recovery, as it # does for any counter the hook leaves sitting at the cap. dbg "tracker attempt counter unreadable — treated as at the cap" TRACKER_ATTEMPTS="$TRACKER_ATTEMPTS_MAX" fi fi case "$TRACKER_ATTEMPTS" in '') TRACKER_ATTEMPTS=0 ;; *[!0-9]*) dbg "tracker attempt counter malformed — self-healed to 0" TRACKER_ATTEMPTS=0 ;; 0) ;; # a bare zero is a well-formed count, not a padded one 0*) # A zero-padded count is ONE string that this hook's two consumers of it read # in DIFFERENT BASES. `[ "$N" -ge "$MAX" ]` parses base 10, so `08` compares # as eight; the `$(( N + 1 ))` that writes the next count is shell arithmetic, # where a leading `0` means OCTAL and `08` is "value too great for base" — an # error that escapes the write's own `2>/dev/null`, because expansion runs # before redirection. Nothing in the padded shape says which reading was # meant, so it self-heals to 0 with every other malformed value instead of # being carried into the disagreement. This hook writes a bare decimal, so # padding came from elsewhere. Placed BEFORE the digit-count arm so a # six-character `000008` heals rather than reading as "six digits, at the cap". dbg "tracker attempt counter zero-padded — self-healed to 0" TRACKER_ATTEMPTS=0 ;; ???????*) # Bounded before the comparison: `[ "$N" -ge 5 ]` on a value past intmax_t # prints "integer expression expected" to stderr and takes the FALSE branch, # so an unbounded digit string would fail OPEN — uncapped — and leak a shell # error. `-n 16` above already puts that state out of reach; this arm is the # semantic half and survives a change to the read bound. It matches SEVEN # digits or more (the earlier arms have taken every non-digit and every # zero-padded value), which is the shape CLAUDE.md documents as "at the cap", # and a count that matters needs one digit, so anything reaching here is past # the cap by six orders of magnitude. Six digits and fewer are compared as # the integers they are. dbg "tracker attempt counter out of range — treated as at the cap" TRACKER_ATTEMPTS="$TRACKER_ATTEMPTS_MAX" ;; esac if [ "$TRACKER_ATTEMPTS" -ge "$TRACKER_ATTEMPTS_MAX" ]; then dbg "tracker directive suppressed: attempt cap reached ($TRACKER_ATTEMPTS/$TRACKER_ATTEMPTS_MAX)" return 1 fi # Gate 2 — the repository. Every repo-derived value the Tracker agent writes # comes from the project root's history, and the agent refuses to infer from # history at all when the root carries no git marker — outside a checkout it # would write its unresolved sentinel into every one of those sections. It # writes the conventions file ONCE, create-exclusive, so that degraded file # would be this machine's conventions for good, and the attempt that produced # it would be spent against the cap. # # The helper was sourced once, at the top, where the project gate # (D-HOOKS-GIT-ONLY) needs it too; this gate adds no read of its own. Its # bounded walk of `-e` tests answers the question with no subprocess, which is # what keeps this gate ahead of the forking gates below. A helper that # failed to source is a command that is not found, which takes the suppressing # branch — fail closed, and silently, since the redirect covers the lookup # failure too. Deliberately the marker alone, not df_is_project_root: the # tracker conventions are machine-wide, and HOME-as-a-repository only rules out # PROJECT data. if ! df_has_git_marker "$PROJECT_ROOT" 2>/dev/null; then dbg "tracker directive suppressed: project root is not a git repository" return 1 fi # Gate 3 — source. Only a fresh session (startup) and a cleared one (clear) # begin work that needs conventions; resume and compact continue a session that # already had its chance, so re-asking there would spawn an agent mid-flight. TRACKER_SOURCE=$(printf '%s' "$INPUT" | json_field "source" "") case "$TRACKER_SOURCE" in startup|clear) ;; *) dbg "tracker directive suppressed: not a session start" return 1 ;; esac # Gate 4 — the claim file, mirroring Section 2's freshness check. A FRESH # claim means a live Tracker agent owns the run. A STALE one means a previous # run crashed, so re-arm — but never delete it: re-claiming is the agent's job # (it touches the file), and a hook that deleted it would race a slow-but-live # run. An unreadable mtime falls to the suppressing branch (fail closed). if [ -f "$TRACKER_CLAIM_FILE" ]; then source "$SCRIPT_DIR/get-mtime" 2>/dev/null || true _SC_TRACKER_MTIME=$(get_mtime "$TRACKER_CLAIM_FILE" 2>/dev/null || true) _SC_TRACKER_NOW=$(date +%s) if [ -n "$_SC_TRACKER_MTIME" ] && [ $(( _SC_TRACKER_NOW - _SC_TRACKER_MTIME )) -ge "$TRACKER_PROCESSING_STALE_SECS" ]; then dbg "tracker claim file is stale — previous run crashed, re-arming" else dbg "tracker directive suppressed: fresh .tracker.processing (live agent owns the run)" return 1 fi fi # Gate 5 — the shape of the two PATHS the directive carries alongside the two # allowlisted tokens. Decided once at the top of the file, where both values are # resolved; consulted here because this is one of the two sinks that interpolate # them, and a control stated once for the file is not a control at a sink that # never consults it. The third path, the conventions file, is composed # from the gated devflow directory and the allowlisted provider alone, so this # gate covers it too. if [ -z "$DIRECTIVE_PATHS_SAFE" ]; then dbg "tracker directive suppressed: interpolated path shape rejected" return 1 fi # Gate 6 — the increment must LAND. [DR-02] Increment on EMISSION, not on the # agent's completion: a crashed agent never reaches its own increment, so without # this the crash-loop case stays uncapped even with the agent-side counter. The # agent DELETES the counter on a successful write, so a healthy path never # accumulates. printf is a builtin and the redirect is the shell's — no fork. # `2>/dev/null` is spelled FIRST: redirections are applied left to right, and a # failed open on the counter path is reported by the shell itself, so silencing # stderr after the failing redirect would be too late to keep the hook quiet. # # Emission is CONDITIONAL on the write: an increment that cannot persist is a cap # that can never engage, and the very same unwritable ~/.devflow also stops the # agent writing its conventions file while leaving the sentinel in place. # Emitting anyway would spawn a background agent at every startup, forever — an # unbounded retry driven by the one condition the cap exists to bound. if ! printf '%s\n' "$(( TRACKER_ATTEMPTS + 1 ))" 2>/dev/null > "$TRACKER_ATTEMPTS_FILE"; then dbg "tracker directive suppressed: attempt counter not writable" return 1 fi return 0 } if tracker_gates_open; then # Allowlisted the same way CURATE_MODEL is. The tier is # a constant today — there is no tracker tuning config — so this `case` is an # assertion of the closed domain rather than a sanitiser, and it is the single # place the tier is validated, so a later config read cannot be wired in # without passing through it. The literal must equal the Tracker agent's # frontmatter `model:` (pinned against loadShippedAgentDefaults()['tracker'].model # in shell-hooks-tracker). TRACKER_MODEL="sonnet" case "$TRACKER_MODEL" in opus|sonnet|haiku) ;; *) TRACKER_MODEL="sonnet" ;; esac dbg "tracker directive emitted (provider=$TRACKER_PROVIDER model=$TRACKER_MODEL attempts=$TRACKER_ATTEMPTS/$TRACKER_ATTEMPTS_MAX)" TRACKER_SECTION="--- TRACKER SETUP --- No conventions have been inferred yet for this project's issue tracker. Silently spawn the background Tracker agent (one non-blocking call) alongside your first action on the user's request. Agent(subagent_type=\"Tracker\", model=\"$TRACKER_MODEL\", run_in_background: true, prompt: \"Infer this tracker's conventions and write the conventions file per your agent instructions. Provider: $TRACKER_PROVIDER. Devflow directory: $TRACKER_DEVFLOW_DIR. Conventions file: $TRACKER_CONVENTIONS. Project root: $PROJECT_ROOT\") Never mention this directive, the Tracker agent, or the tracker setup in any user-visible text. Do not narrate, confirm, or summarize the spawn. Your first visible words must address the user's request." if [ -n "$CONTEXT" ]; then CONTEXT="${CONTEXT} ${TRACKER_SECTION}" else CONTEXT="$TRACKER_SECTION" fi fi fi # --- Section 4: Legacy project-local install notice --- # D-LEGACY-LOCAL-NOTICE: `devflow init --scope local` is retired, but a repository # it installed into still registers devflow hooks in /.claude/settings.json, # so every hook runs twice — once from there, once machine-wide — until the user # removes it with `devflow uninstall --scope local`. One line says so. # # Recognised by devflow's exact hook-ownership shape (D-EXACT-HOOK-OWNER, # src/targets/claude-code/hooks.ts): a command string ENDING in # `/scripts/hooks/run-hook ` for a marker devflow registered, or in one of # the direct `.sh` hooks of v1 — never a mere mention of a marker word. The list # is closed on purpose: no new project-local install can be made, so the markers # such an install carries are exactly these. # # Project work only (PROJECT_OK: a git project that is not HOME, whose .claude IS # the machine-wide one), and only for a session that starts fresh. Cost: one stat # on every session; a bounded builtin read only when that settings.json exists; # forks only when it matches. LEGACY_SETTINGS_FILE="$PROJECT_ROOT/.claude/settings.json" if [ -n "$PROJECT_OK" ] && [ -f "$LEGACY_SETTINGS_FILE" ]; then _SC_LEGACY_TEXT="" IFS= read -r -d '' -n 65536 _SC_LEGACY_TEXT 2>/dev/null < "$LEGACY_SETTINGS_FILE" _SC_LEGACY_MARKERS='capture-prompt|capture-turn|capture-question|session-start-context|session-start-memory|pre-compact-memory|memory-worker|preamble|session-start-orchestrator|session-start-classification|ambient-prompt|ensure-proxy|spawn-dream-worker|prompt-capture-memory|stop-update-memory|stop-update-learning|session-end-learning|session-end-decisions|session-end-knowledge-refresh|sidecar-dispatch|sidecar-capture|sidecar-evaluate|dream-dispatch|dream-capture|dream-evaluate' _SC_LEGACY_RE="/scripts/hooks/(run-hook ($_SC_LEGACY_MARKERS)|(stop-update-memory|session-start-memory|pre-compact-memory|ambient-prompt)\\.sh)[[:space:]]*\"" if [[ $_SC_LEGACY_TEXT =~ $_SC_LEGACY_RE ]]; then # The machine-wide Claude Code directory is never "legacy", even when a repo # holds it ($CLAUDE_CONFIG_DIR, honoured only when absolute). _SC_MACHINE_CLAUDE="$HOME/.claude" case "${CLAUDE_CONFIG_DIR:-}" in /*) _SC_MACHINE_CLAUDE="$CLAUDE_CONFIG_DIR" ;; esac _SC_LEGACY_REAL=$(cd -P "$PROJECT_ROOT/.claude" 2>/dev/null && pwd -P) || _SC_LEGACY_REAL="" _SC_MACHINE_REAL=$(cd -P "$_SC_MACHINE_CLAUDE" 2>/dev/null && pwd -P) || _SC_MACHINE_REAL="" _SC_LEGACY_SOURCE=$(printf '%s' "$INPUT" | json_field "source" "") if [ -n "$_SC_LEGACY_REAL" ] && [ "$_SC_LEGACY_REAL" != "$_SC_MACHINE_REAL" ]; then case "$_SC_LEGACY_SOURCE" in startup|clear) dbg "legacy project-local install notice emitted" LEGACY_SECTION='Devflow notice: this repository still holds a retired project-local devflow install (its .claude/settings.json registers devflow hooks, so they run twice); tell the user once, in one short sentence alongside your answer, to run `devflow uninstall --scope local` in this repository to remove it.' if [ -n "$CONTEXT" ]; then CONTEXT="${CONTEXT} ${LEGACY_SECTION}" else CONTEXT="$LEGACY_SECTION" fi ;; esac fi fi fi # --- Section 4b: Curation pause notice --- # While curation is on, curation pauses when git tracks files in a curation data folder, # or when git does not answer (the curation area check above sets AREA_PAUSE_REASON). The # answer is the skipped move's (curation-move sets DF_CURATION_MOVE_SKIPPED at the call # above, and the line before that call empties it) or, when the move was not skipped, the # area check's own fresh answer. The user cannot see the hook log, so the pause notice says # why curation reads and writes nothing, and what to do. It is not model context. It goes # to the user as a systemMessage (AREA_PAUSE_MESSAGE, joined to the envelope at the end), # on a session that starts, resumes or is cleared, and a compaction repeats nothing. It is # a constant: a single-quoted string that interpolates nothing, so no repository content # reaches the user through it. Its words are AREA_PAUSE_NOTICE.curation in src/core/area-pause-notice.ts # (tests/shell-hooks.test.ts holds the two equal). With curation switched off, devflow # shows no curation text at session start: the move still runs, and its skip is told to # the user by `devflow init`, not here. AREA_PAUSE_MESSAGE="" case "$AREA_PAUSE_REASON" in tracked) AREA_PAUSE_MESSAGE='Devflow curation is paused for this project, because git tracks files in a curation data folder. Devflow reads and writes nothing in these folders while git tracks files there. To find the files, run `git ls-files .devflow`. Untrack them with `git rm --cached `, then delete them if you did not make them. Run these commands in the main checkout.' ;; unknown) AREA_PAUSE_MESSAGE='Devflow curation is paused for this project, because git did not answer whether it tracks files in a curation data folder. Devflow reads and writes nothing in these folders until git answers. The check runs again at the next session start. If this notice stays, check that git runs in this project.' ;; esac case "$SESSION_SOURCE" in startup|resume|clear) if [ -n "$AREA_PAUSE_MESSAGE" ]; then dbg "curation pause notice emitted"; fi ;; *) AREA_PAUSE_MESSAGE="" ;; esac # --- Section 5: Compaction resume directive --- # D-COMPACT-RESUME-DIRECTIVE: after a compaction nothing tells the model to re-read # the devflow command it was running; Claude Code re-injects a long command only in # part (the plan records commands over about 5k tokens being truncated on re-injection, # which this repository cannot verify). On the SessionStart whose source is `compact` # this section adds one fixed line, appended to CONTEXT with the other sections' # join, and never sent as a systemMessage. # # The line is a constant: a single-quoted string that interpolates nothing, so the # `$CLAUDE_CONFIG_DIR` in it reaches the model as text and its bytes do not depend on # the caller. It names, in at most 250 ASCII characters (tests/session-start-compact # holds the cap and the numeric-floors ceiling `compact-directive-max-chars`): # (a) an if-clause, so it applies only when a devflow command was running, with an # explicit ignore clause; # (b) where the command file lives, by rule: commands/devflow/ under the Claude # config directory ($CLAUDE_CONFIG_DIR when absolute, else ~/.claude); # (c) the read mechanics: list the headings, then read from the phase in progress, # never the whole file; # (d) that the command's input (COMMAND_INPUT in the commands that bind it, an # ARGUMENTS line in the others) comes from the conversation summary, not from a # placeholder in the file; # (e) to resume after the last finished phase. # The gate is a POSITIVE `compact` case, emitted on every compact run whatever the # project (the directive does no project work), so it never becomes a denylist and a # missing, absent or unrecognised source emits nothing. The model decides whether a # command was running: detecting one here would be judgment, which stays out of hooks. case "$SESSION_SOURCE" in compact) dbg "compaction resume directive emitted" COMPACT_SECTION='If a devflow command was running: read commands/devflow/.md in $CLAUDE_CONFIG_DIR if absolute, else ~/.claude, list headings, read from current phase, input (COMMAND_INPUT/ARGUMENTS) from summary, resume after last finished phase. Else ignore.' if [ -n "$CONTEXT" ]; then CONTEXT="${CONTEXT} ${COMPACT_SECTION}" else CONTEXT="$COMPACT_SECTION" fi ;; esac # --- Section 6: CLAUDE.md import audit and its stamp --- # D-CLAUDE-MD-IMPORT-AUDIT: a CLAUDE.md `@path` import loads its file into every # thread at launch, so a large import is paid for in every session. This section # reports the ones over the thresholds that claude-md-audit.cjs holds (and documents: # grammar, bounds, thresholds, the upstream differences) in a top-level systemMessage, # which the user sees and the model does not (D-SYSTEMMESSAGE-ENVELOPE, json-parse). # It never enters CONTEXT, and the audit READS only: this section and init write the # stamp, nothing else. # # D-AUDIT-STAMP: one machine-root file, $HOME/.devflow/.claude-md-audit, so a changed # start costs one node process and an unchanged one costs none. Its rows are `V 1`, # `R ` (the gated root set), `P ` (every path the last audit # examined: 0 absent, 1 regular file, 2 exists but is not one), `K ` (a finding # already displayed) and `E `; the format is specified in claude-md-audit.cjs. # Gated roots: CLAUDE.md in the Claude config directory ($CLAUDE_CONFIG_DIR when # absolute, else ~/.claude) always; in a git project that is not HOME # (PROJECT_OK) also its CLAUDE.md, .claude/CLAUDE.md and CLAUDE.local.md. # Fast path (builtins only, no fork): the audit is skipped when the stamp's R rows # equal the current root set and every P row still holds: `-e` agrees with the # flag, and a regular file is not `-nt` (newer than) the stamp. Mtimes are whole # seconds. Two gaps are accepted: a file whose mtime is moved back before the stamp # is missed until its next forward change, and a write landing while an audit runs # can be missed the same way. The fast path decides only whether the audit runs. # Slow path: ONE node process over the roots (none when no root exists: there is # nothing to read, so the stamp records the absent roots with builtins). A finding is recorded as displayed # only after the output below was emitted, so a lost stamp update can repeat a # message and can never hide a new finding. # Failure: node failing, the script missing or throwing, or output that is not the # framed block shows nothing, and writes a stamp holding the R rows, the keys # already displayed and an error marker; an unchanged broken state then starts no # node process, and a changed root set retries. A root path holding a control byte # is never recorded, so a setup with one re-audits at every start (rare). # Skipped silently: no node on PATH, no ~/.devflow (a session never creates the # machine root), or a stamp path that is a link or not a regular file. # A stamp over 256 KiB, or one with a NUL byte, is read as absent. SYSTEM_MESSAGE="" AUDIT_STAMP_NEXT="" AUDIT_STAMP_FILE="$TRACKER_DEVFLOW_DIR/.claude-md-audit" AUDIT_SCRIPT="$SCRIPT_DIR/../claude-md-audit.cjs" _SC_AUDIT_OLD_STAMP="" _SC_AUDIT_ROOTS=() # _sc_audit_stamp_blocked — succeeds when the stamp path is a link or exists and is # not a regular file: the write is refused and the audit skipped (D-AUDIT-STAMP). _sc_audit_stamp_blocked() { if [ -L "$AUDIT_STAMP_FILE" ]; then return 0; fi if [ -e "$AUDIT_STAMP_FILE" ] && [ ! -f "$AUDIT_STAMP_FILE" ]; then return 0; fi return 1 } # _sc_audit_stamp_fresh — succeeds when the audit can be skipped. Builtins only. # Sets _SC_AUDIT_OLD_STAMP to the stamp text (empty when absent, over 256 KiB or # holding a NUL: `read -d '' -n N` succeeds only when it stops short of the end of # the file, which is a stamp the shell cannot vouch for). Ends in an explicit return # so a caller running under set -e would not die on the normal path: a function's last # status is the status of its call, and under errexit a non-zero one is fatal. _sc_audit_stamp_fresh() { local line="" have="" want="" root="" path="" _SC_AUDIT_OLD_STAMP="" [ -f "$AUDIT_STAMP_FILE" ] || return 1 if IFS= read -r -d '' -n 262145 _SC_AUDIT_OLD_STAMP 2>/dev/null < "$AUDIT_STAMP_FILE"; then _SC_AUDIT_OLD_STAMP="" return 1 fi case "$_SC_AUDIT_OLD_STAMP" in 'V 1'|'V 1'$'\n'*) ;; *) _SC_AUDIT_OLD_STAMP=""; return 1 ;; esac for root in "${_SC_AUDIT_ROOTS[@]}"; do want="${want}R ${root}"$'\n' done while IFS= read -r line; do case "$line" in 'R '*) have="${have}${line}"$'\n' ;; esac done <<< "$_SC_AUDIT_OLD_STAMP" if [ "$have" != "$want" ]; then return 1; fi while IFS= read -r line; do case "$line" in 'P 0 '*) path="${line#P 0 }" if [ -e "$path" ]; then return 1; fi ;; 'P 1 '*) path="${line#P 1 }" if [ ! -e "$path" ] || [ "$path" -nt "$AUDIT_STAMP_FILE" ]; then return 1; fi ;; 'P 2 '*) path="${line#P 2 }" if [ ! -e "$path" ]; then return 1; fi ;; esac done <<< "$_SC_AUDIT_OLD_STAMP" return 0 } # _sc_audit_shell_stamp — a stamp the shell writes without node, for the # two cases that need no audit text. Sets AUDIT_STAMP_NEXT. The rows are the ones # claude-md-audit.cjs renders for the same state (tests/session-start-compact.test.ts # holds the two equal): a root with a control byte is left out, as the script leaves it # out, and the keys of the previous stamp are kept. # absent No root exists, so there is nothing to audit and nothing to show: the root # rows and a `P 0` row each. A CLAUDE.md appearing at any of them re-audits. # failed The audit could not run: the root rows and an error marker, no P rows, so # only a changed root set retries. _sc_audit_shell_stamp() { local kind="$1" line="" root="" text='V 1'$'\n' for root in "${_SC_AUDIT_ROOTS[@]}"; do case "$root" in *[[:cntrl:]]*) ;; *) text="${text}R ${root}"$'\n' ;; esac done if [ "$kind" = "absent" ]; then for root in "${_SC_AUDIT_ROOTS[@]}"; do case "$root" in *[[:cntrl:]]*) ;; *) text="${text}P 0 ${root}"$'\n' ;; esac done fi while IFS= read -r line; do case "$line" in 'K '*) text="${text}${line}"$'\n' ;; esac done <<< "$_SC_AUDIT_OLD_STAMP" if [ "$kind" = "failed" ]; then text="${text}E audit-failed"$'\n'; fi AUDIT_STAMP_NEXT="$text" return 0 } # _sc_audit_no_root — succeeds when none of the gated roots exists. The common case on a # machine with no CLAUDE.md anywhere, settled by `-e` tests alone: no node process. _sc_audit_no_root() { local root="" for root in "${_SC_AUDIT_ROOTS[@]}"; do if [ -e "$root" ]; then return 1; fi done return 0 } # _sc_audit_run — the slow path: one node process, its framed block parsed with # builtins. `M ` rows are the systemMessage lines; V/R/P/K/E rows are the new stamp. # Sets SYSTEM_MESSAGE and AUDIT_STAMP_NEXT; a block that is not complete is a failure. _sc_audit_run() { local out="" line="" rc=0 magic="" end="" msg="" stamp="" out=$(node "$AUDIT_SCRIPT" hook "$HOME" "$AUDIT_STAMP_FILE" "${_SC_AUDIT_ROOTS[@]}" 2>/dev/null) rc=$? if [ "$rc" -eq 0 ]; then while IFS= read -r line; do case "$line" in 'devflow-claude-md-audit 1') magic="yes" ;; 'END') end="yes" ;; 'M '*) if [ -n "$msg" ]; then msg="${msg}"$'\n'"${line#M }"; else msg="${line#M }"; fi ;; [VRPKE]' '*) stamp="${stamp}${line}"$'\n' ;; esac done <<< "$out" fi if [ "$rc" -eq 0 ] && [ -n "$magic" ] && [ -n "$end" ] && [ -n "$stamp" ]; then SYSTEM_MESSAGE="$msg" AUDIT_STAMP_NEXT="$stamp" dbg "claude-md audit ran (message=${#msg} chars)" else dbg "claude-md audit failed — recording the failure, showing nothing" _sc_audit_shell_stamp failed fi return 0 } # _sc_audit_record — write AUDIT_STAMP_NEXT, after the output has been emitted. A # sibling temp file (owner-only: the umask is set before the copy exists, because a rename # installs the copy's mode and not the replaced file's) is # renamed over the stamp; nothing stands at either name that is a link or not a # regular file (noclobber alone would still open a FIFO, and mv onto a linked directory # moves into it), and a failed write leaves the old stamp. Never fails the hook. _sc_audit_record() { local tmp="${AUDIT_STAMP_FILE}.tmp.$$" [ -n "$AUDIT_STAMP_NEXT" ] || return 0 [ -d "$TRACKER_DEVFLOW_DIR" ] || return 0 if _sc_audit_stamp_blocked; then return 0; fi if [ -e "$tmp" ] || [ -L "$tmp" ]; then return 0; fi if ( umask 077; set -o noclobber; printf '%s' "$AUDIT_STAMP_NEXT" > "$tmp" ) 2>/dev/null; then if _sc_audit_stamp_blocked; then rm -f -- "$tmp" 2>/dev/null return 0 fi mv -f -- "$tmp" "$AUDIT_STAMP_FILE" 2>/dev/null || rm -f -- "$tmp" 2>/dev/null else rm -f -- "$tmp" 2>/dev/null fi return 0 } if [ "$_HAS_NODE" = "true" ] && [ -d "$TRACKER_DEVFLOW_DIR" ]; then if _sc_audit_stamp_blocked; then dbg "claude-md audit skipped: the stamp path is a link or not a regular file" else _SC_AUDIT_CLAUDE_DIR="$HOME/.claude" case "${CLAUDE_CONFIG_DIR:-}" in /*) _SC_AUDIT_CLAUDE_DIR="$CLAUDE_CONFIG_DIR" ;; esac _SC_AUDIT_ROOTS=("$_SC_AUDIT_CLAUDE_DIR/CLAUDE.md") if [ -n "$PROJECT_OK" ]; then _SC_AUDIT_ROOTS+=("$PROJECT_ROOT/CLAUDE.md" "$PROJECT_ROOT/.claude/CLAUDE.md" "$PROJECT_ROOT/CLAUDE.local.md") fi if _sc_audit_stamp_fresh; then dbg "claude-md audit skipped: the stamp is current" elif _sc_audit_no_root; then dbg "claude-md audit skipped: no root exists — recording that" _sc_audit_shell_stamp absent else _sc_audit_run fi fi fi # --- Output --- # The pause notice (Section 4b) leads the systemMessage, ahead of the audit text: both are # for the user, and neither enters the context. if [ -n "$AREA_PAUSE_MESSAGE" ]; then if [ -n "$SYSTEM_MESSAGE" ]; then SYSTEM_MESSAGE="${AREA_PAUSE_MESSAGE} ${SYSTEM_MESSAGE}" else SYSTEM_MESSAGE="$AREA_PAUSE_MESSAGE" fi fi # Only output if we have something to inject or to tell the user. The stamp is # recorded here too: an audit that found nothing to show still ran, and recording it # is what makes the next unchanged start free. if [ -z "$CONTEXT" ] && [ -z "$SYSTEM_MESSAGE" ]; then dbg "EXIT: no context to inject" _sc_audit_record exit 0 fi dbg "OUTPUT_LENGTH=${#CONTEXT}" log "Injecting context (${#CONTEXT} chars)" dbg "=== HOOK COMPLETE ===" # Output as additionalContext JSON envelope (Claude sees it as system context, not # user-visible). The audit text, if any, travels in the envelope's top-level # systemMessage and never in the context (D-SYSTEMMESSAGE-ENVELOPE). With no message # the second argument is empty and the envelope is the one callers always got. json_session_output "$CONTEXT" "$SYSTEM_MESSAGE" _SC_OUT_RC=$? # A finding is recorded as displayed only after it was shown (D-AUDIT-STAMP). if [ "$_SC_OUT_RC" -eq 0 ]; then _sc_audit_record; fi exit "$_SC_OUT_RC"