UserPromptSubmit Hook API Reference¶
Developer reference for the UserPromptSubmit hook implementation, focusing on framework injection via CLAUDE.md vs AMPLIHACK.md comparison.
Overview¶
The UserPromptSubmit hook injects context on every user message:
- User preferences (behavioral guidance)
- Agent memories (when agents mentioned)
- Framework instructions (when CLAUDE.md differs from AMPLIHACK.md)
This document focuses on the framework injection mechanism (item 3).
Agent memories (item 2)¶
Memories are injected only when the prompt names an amplihack agent: by a slash command (/analyze, /fix), by an agent definition reference, or by Use <name>.md agent (with a capital U; it names any agent, and <name> is a file stem as in a definition reference). A slash word is its own whitespace-separated token, ignoring surrounding punctuation ((/analyze, /reflect.). It counts wherever it appears, including at the end of the prompt. An agent definition reference is @ and a path to a .md file under a .claude/agents/ directory, and it counts for any agent: bundled, project-defined (@.claude/agents/my-reviewer.md) or user-level (@~/.claude/agents/my-reviewer.md). The file can be at any directory depth below .claude/agents/ (@.claude/agents/team/security-reviewer.md), and the .claude directory can have a relative, ~ or absolute path before it (Include @~/.amplihack/.claude/agents/amplihack/core/architect.md, @/home/me/proj/.claude/agents/builder.md). The agent is the file's stem, one path component, so a later .md in the prompt (then check README.md) is not part of its name. Ordinary words are not agents. Neither are path segments, even ones named like an agent (docs/security), or slash words that name no agent (/skills, /bin).
Each stored memory is scored against the prompt, and only relevant memories are injected (issue #1483). The code is in crates/amplihack-hooks/src/user_prompt/:
| File | What it holds |
|---|---|
memory.rs |
Prompt agent detection (prompt_agents, which wraps agent_memory.rs), inject_memory, format_agent_memory_context and the output limits (MAX_INJECTED_MEMORIES, MAX_MEMORY_CHARS) |
memory/text.rs |
Splitting text into words, paragraphs, transcript turns, fenced blocks and backtick spans |
memory/language.rs |
The English check (ENGLISH_MARKERS) |
memory/scoring.rs |
Stop words (the SMART list, FOREIGN_FUNCTION_WORDS), the foreign-code check (FOREIGN_EVIDENCE), topic words and the relevance score (RELEVANCE_THRESHOLD, MIN_SHARED_TERMS) |
smart_stop_words.txt |
The SMART stop list, read into memory/scoring.rs at compile time |
The rules:
- Topic words. Topic words are the prompt's and the memory's English words, minus:
- the SMART stop list (a few developer words such as
valueandnameare kept), - 15 function words of German, Spanish, French, Italian, Portuguese and Dutch that are also English words (
die,hat,man,mit,son,con,era, …; seeFOREIGN_FUNCTION_WORDS), so a prompt in one of those languages can't match an English memory on them. Developer words such asbin,dos,dirandnetare kept as topic words even though they are foreign function words too. The cost of each entry is that a two-word prompt made of it and one other topic word (/fix the man page) never matches, - contractions,
- words shorter than 3 characters, and words that start with a digit, such as numbers with or without a suffix (
500,2026,2nd,10am,100ms);sha256,utf8ande2ecount, while2fadoes not, - the agent names and slash command that triggered the hook, and every agent definition reference as a whole (its directory names, such as
claude,amplihackorcore, are how the agent was invoked, not what the prompt is about), - the
Agent <name>:prefix and the transcript role labels (user:,assistant:,human:,system:,tool:,developer:,function:) that stored learnings carry.
There is no stemming.
- Relevance. A memory must share at least 2 topic words with the prompt and score at least 0.2 cosine similarity. The score is printed as (relevance: N.NN). A prompt left with a single topic word therefore never matches.
- Output. Copies of the same memory stored under different agents are printed once. At most 5 memories are injected, most relevant first, and each is cut to 400 characters. If nothing is relevant, nothing is injected.
- English memories only. Each transcript turn of a memory is checked on its own. A turn is a paragraph that starts with one of those role labels, even inside a code block, since a flattened transcript can't tell a pasted log line from a real turn. Any other paragraph continues the current turn and keeps its words. That includes one that opens with a lower-case word and a colon (sqlite: …). Only turns whose prose reads as English contribute topic words: at least 10% of their prose words must be common English function words (the, and, with, because, …) or English contractions.
- Words that are also frequent in other Latin-script languages don't count (is, to, for, has, just, most, …). The marker list shares no word with the stopwords-iso lists of 35 Latin-script languages. It still shares are and or with Romanian, it with Latvian and Lithuanian, and it, out and you with Breton; see ENGLISH_MARKERS.
- Code is ignored when judging the language: fenced blocks (a line starting with ``` or ~~~, closed by a line of at least as many of the same character; fences inside block quotes or list items are not recognised), closed backtick spans of any width, and tokens with digits or symbols in them (paths, flags, snake_case, DEFAULT_TIMEOUT, sha256). An unclosed fence or backtick opens nothing, since session-stop cuts memories at 500 characters. Words written in capitals (CI, THE) are still words. A turn with no prose outside code (an assistant reply that is only a fenced block) is judged on the words inside its code. If those aren't English, the turn contributes nothing, its code-looking tokens included. Surrounding punctuation and quotes in any script (¿, “, ») are trimmed first, so they don't make a word look like code.
- Non-ASCII words are never topic words.
This fails closed. Turns in other languages are ignored, so a Spanish question answered in English is matched only on the English answer. Terse English notes with too few function words to tell (user login uses oauth) are not injected either, even when they are relevant. The check is a screened word list, not a language identifier: a turn in an unscreened language that happens to use a marker word, or one turn mixing English with another language, is treated as English.
The prompt is not language-checked: terse English prompts (/fix flaky sqlite test timeout on linux ci, /fix clippy needless_borrow parser) have no function words to judge by, and a check would drop them. A prompt in another language matches an English memory only on the words the two share: the 15 foreign function words above are stop words, and foreign text pasted into a memory's code (a fenced log or a backtick span) contributes only its code-looking tokens, not its words, when it shows positive evidence of another language: at least two hits among its words, counted per code part, where a hit is one of 35 function words of the same six languages that are not English words, shell words, acronyms or names (der, nicht, und, le, het, por, …; see FOREIGN_EVIDENCE) or a word with a non-ASCII letter, and at least one hit is a listed word. A command line in a fence or in backticks has none (ps aux | grep ingest worker keeps its words), an accented name in an English fence (Jürgen Müller) costs nothing, and on the prompt side no such rule runs at all (/fix `cargo test sqlite timeout` on ci). Its other words are topic words like any other, so a foreign prompt that shares two real words with an English memory, such as a product name and a path, still matches it; and any paste with fewer than two hits, or with no listed word, lends its words: an ASCII paste in one of the six languages that happens to use at most one evidence word, a paste in a language outside the six whether it is written in ASCII (Indonesian, Swahili) or with diacritics (Polish, Czech, Turkish), and two one-hit fences in one turn.
Injected memory format¶
Relevant memories are added under one heading that names the agents the prompt invoked. Each memory is collapsed to one line, cut to 400 characters (with … added when it is cut), and followed by its score:
## Relevant Memory (agents: analyzer)
- <memory text, one line, cut to 400 characters plus … when longer> (relevance: N.NN)
A memory's stored code context, if it has any, is printed on the lines after it as stored. The 400-character cut and the line collapse do not apply to it.
Checking the memory rules¶
The unit tests are in user_prompt/memory/tests/ (format.rs, stop_words.rs, english_check.rs, code_spans.rs, scoring.rs) and in user_prompt/tests.rs. Run them with cargo nextest run -p amplihack-hooks --locked user_prompt::. tests/issue_1483_memory_injection_outside_in.sh runs the real binary: it stores learnings through session-stop under a temporary HOME, sends prompts to user-prompt-submit, and checks the JSON output. CI runs it against the release binary in the cross-compile job.
cargo build --release --locked -p amplihack-hooks-bin
bash tests/issue_1483_memory_injection_outside_in.sh target/release/amplihack-hooks
# last line: passed: 26, failed: 0
Workflow classification reminder¶
amplihack-hooks workflow-classification-reminder is a separate UserPromptSubmit hook in crates/amplihack-hooks/src/workflow_classification.rs. On a new topic it injects the routing prompt, which tells the agent to classify the request and launch dev-orchestrator for development work. It emits nothing for prompts written by a recipe step (AMPLIHACK_RECIPE_RUN_ID or AMPLIHACK_STEP_ID set), inside nested sessions or active workflows, for prompts that start with an envelope the harness writes (task notifications, system notices, messages from another session and loop ticks), for explicit /dev commands and for follow-up turns. See Prompts that are not a person's.
A prompt that starts with [coord] is coordination traffic between sessions and receives a short note instead of the routing prompt, unless its body is a work request that starts with a change verb such as fix or build. A work request is throttled like the same text without the marker, and receives the note while the throttle holds. A report such as fix landed on PR 12 or fix #12 merged receives the note. See Coordination Messages for the marker rules, the note text and the last_rule values recorded in the state file.
Hook Signature¶
File: ~/.amplihack/.claude/tools/amplihack/hooks/user_prompt_submit.py
Hook Type: UserPromptSubmit
Trigger: Before processing each user message
Input:
{
"session_id": "string",
"transcript_path": "path",
"cwd": "path",
"hook_event_name": "UserPromptSubmit",
"userMessage": {
"text": "user's prompt text"
}
}
Output:
When no Claude account has capacity left, the output also has a top-level
systemMessage shown to the user, and the context ends with a note telling
the model to avoid large parallel work:
{
"systemMessage": "⚠ all Claude accounts ≥90% · next reset Oct 22 2am — run 'amplihack profile usage'",
"hookSpecificOutput": {
"hookEventName": "UserPromptSubmit",
"additionalContext": "...\n\nClaude account capacity is low across all profiles (next reset Oct 22 2am). Avoid launching large parallel workflows, multi-agent fan-out or long recipe runs; prefer small sequential steps."
}
}
It is shown once per state per session, and again when the state gets worse.
Nested recipe sessions get the context note only, and Codex reads only
additionalContext. See
Capacity notice in hooks.
Core API¶
_inject_amplihack_if_different() -> str¶
Compares CLAUDE.md vs AMPLIHACK.md and injects framework instructions if they differ.
Returns: AMPLIHACK.md contents if different, empty string if identical
Algorithm:
def _inject_amplihack_if_different(self) -> str:
# 1. Find AMPLIHACK.md (priority order)
amplihack_md = self._find_amplihack_md()
if not amplihack_md:
return ""
# 2. Find CLAUDE.md (project root)
claude_md = self.project_root / "CLAUDE.md"
# 3. Check cache using mtimes
amplihack_mtime = amplihack_md.stat().st_mtime
claude_mtime = claude_md.stat().st_mtime if claude_md.exists() else 0
if self._amplihack_cache_timestamp == (amplihack_mtime, claude_mtime):
return self._amplihack_cache # Cache hit
# 4. Read both files
amplihack_content = amplihack_md.read_text(encoding="utf-8")
claude_content = claude_md.read_text(encoding="utf-8") if claude_md.exists() else ""
# 5. Compare (whitespace-normalized)
if claude_content.strip() == amplihack_content.strip():
result = "" # Files identical, skip injection
else:
result = amplihack_content # Files differ, inject framework
# 6. Update cache
self._amplihack_cache = result
self._amplihack_cache_timestamp = (amplihack_mtime, claude_mtime)
return result
Performance:
- First call: ~50-100ms (reads 2 files, ~2000 lines each)
- Cached calls: <1ms (mtime check only)
- Cache invalidation: Only when either file's mtime changes
File Resolution Priority¶
AMPLIHACK.md search order:
$CLAUDE_PLUGIN_ROOT/AMPLIHACK.md- Plugin mode (Claude Code)~/.amplihack/.claude/AMPLIHACK.md- Centralized staging (all tools).claude/AMPLIHACK.md- Per-project mode (development)
CLAUDE.md location: Always project_root/CLAUDE.md
def _find_amplihack_md(self) -> Optional[Path]:
# Try plugin location
plugin_root = os.environ.get("CLAUDE_PLUGIN_ROOT")
if plugin_root:
path = Path(plugin_root) / "AMPLIHACK.md"
if path.exists():
return path
# Try centralized staging
path = Path.home() / ".amplihack" / ".claude" / "AMPLIHACK.md"
if path.exists():
return path
# Try per-project
path = self.project_root / ".claude" / "AMPLIHACK.md"
if path.exists():
return path
return None
Caching Implementation¶
Cache Structure¶
class UserPromptSubmitHook(HookProcessor):
def __init__(self):
super().__init__("user_prompt_submit")
# Cache for comparison result
self._amplihack_cache: Optional[str] = None
# Cache key: tuple of (amplihack_mtime, claude_mtime)
self._amplihack_cache_timestamp: Optional[Tuple[float, float]] = None
Cache Invalidation Rules¶
Cache is invalidated when:
- AMPLIHACK.md changes (package update, manual edit)
- CLAUDE.md changes (user customization)
- Hook process restarts (new session, reload)
Cache is not invalidated when:
- User sends message (cache used)
- Other files change
- Environment variables change
Cache Performance¶
Cache hit rate: ~99% in typical usage
- First message: Cache miss (reads files)
- Subsequent messages: Cache hits (uses mtimes)
- File edit: Cache miss (mtime changed)
- Next message: Cache hit again
Timing measurements:
Whitespace Normalization¶
Files are compared using whitespace-normalized content:
if claude_content.strip() == amplihack_content.strip():
# Files are identical (ignoring leading/trailing whitespace)
Rationale: Formatting differences shouldn't trigger injection:
- Line ending differences (LF vs CRLF)
- Trailing whitespace
- Extra newlines at end
Not normalized:
- Internal whitespace (indentation, spacing)
- Content structure
- Comments
This balances correctness (ignore formatting) with accuracy (detect real changes).
Error Handling¶
All errors result in graceful degradation:
try:
return self._inject_amplihack_if_different()
except Exception as e:
self.log(f"Could not check AMPLIHACK.md vs CLAUDE.md: {e}", "WARNING")
return "" # Empty injection, never block Claude
Specific error cases:
| Error | Behavior | Log Level | Exit Code |
|---|---|---|---|
| AMPLIHACK.md missing | Skip injection, log info | INFO | 0 |
| CLAUDE.md missing | Treat as empty, inject | DEBUG | 0 |
| Read permission | Skip injection, log warning | WARNING | 0 |
| Encoding error | Skip injection, log warning | WARNING | 0 |
| Compare error | Skip injection, log warning | WARNING | 0 |
Never fails - hook always exits 0 to prevent blocking Claude Code.
The capacity notice follows the same rule: a missing, damaged or unreadable capacity file, or any error while checking it, adds nothing and leaves the output unchanged.
Injection Context Format¶
When files differ, full AMPLIHACK.md is injected without modification:
No processing:
- No truncation
- No summarization
- No filtering
- Complete file contents
This ensures all framework instructions are available.
Process Integration¶
Full process() Method Flow¶
def process(self, input_data: Dict[str, Any]) -> Dict[str, Any]:
context_parts = []
# 1. Inject user preferences
preferences = self._get_preferences()
if preferences:
context_parts.append(self.build_preference_context(preferences))
# 2. Inject agent memories (if agents mentioned)
user_prompt = input_data.get("userMessage", {}).get("text", "")
memory_context = self._inject_memories_for_agents(user_prompt)
if memory_context:
context_parts.append(memory_context)
# 3. Inject framework instructions (if CLAUDE.md differs)
amplihack_context = self._inject_amplihack_if_different()
if amplihack_context:
context_parts.append(amplihack_context)
self.log("Injected AMPLIHACK.md framework instructions")
# Combine all context
full_context = "\n\n".join(context_parts)
return {
"additionalContext": full_context
}
Order matters: Preferences → Memories → Framework ensures proper priority.
The capacity note, when due, is added after these parts. It is also added
when there are no other parts, in which case the hook returns it instead of
{}.
Logging and Metrics¶
Log Events¶
Log file: ~/.amplihack/.claude/runtime/logs/user_prompt_submit.log
[INFO] Detected agents: ['architect', 'builder']
[INFO] Injected 5 preferences on user prompt
[INFO] Injected AMPLIHACK.md framework instructions
[DEBUG] CLAUDE.md matches AMPLIHACK.md - skipping framework injection
[WARNING] AMPLIHACK.md not found - skipping framework injection
[WARNING] Could not check AMPLIHACK.md vs CLAUDE.md: [error]
Metrics Tracked¶
Metrics file: ~/.amplihack/.claude/runtime/metrics/user_prompt_submit_metrics.jsonl
{"timestamp": "2025-01-27T...", "preferences_injected": 5}
{"timestamp": "2025-01-27T...", "agent_memory_injected": 3}
{"timestamp": "2025-01-27T...", "agents_detected": 2}
{"timestamp": "2025-01-27T...", "context_length": 2847}
Available metrics:
preferences_injected: Number of preferences injectedagent_memory_injected: Number of agent memories injectedagents_detected: Number of agents detected in promptcontext_length: Total character count of injected context
Testing¶
Unit Testing¶
Test the comparison logic:
def test_inject_amplihack_different_files():
"""Test injection when CLAUDE.md differs from AMPLIHACK.md."""
hook = UserPromptSubmitHook()
# Setup: Create different files
write_file("CLAUDE.md", "Custom project instructions")
write_file(".claude/AMPLIHACK.md", "Framework instructions")
result = hook._inject_amplihack_if_different()
assert result == "Framework instructions"
assert "Injected AMPLIHACK.md" in hook.logs
def test_inject_amplihack_identical_files():
"""Test no injection when files are identical."""
hook = UserPromptSubmitHook()
# Setup: Create identical files
write_file("CLAUDE.md", "Same content")
write_file(".claude/AMPLIHACK.md", "Same content")
result = hook._inject_amplihack_if_different()
assert result == ""
assert "skipping framework injection" in hook.logs
Integration Testing¶
Test full hook execution:
# Test with different files
echo '{"userMessage": {"text": "test"}, "cwd": "'$(pwd)'"}' | \
python3 .claude/tools/amplihack/hooks/user_prompt_submit.py
# Verify output contains AMPLIHACK.md
Performance Testing¶
Measure cache performance:
# Run 100 messages and measure timing
for i in {1..100}; do
time echo '{"userMessage": {"text": "test '$i'"}}' | \
python3 .claude/tools/amplihack/hooks/user_prompt_submit.py > /dev/null
done
# Expected: First run ~80ms, rest <1ms
Development Guidelines¶
When to Modify This API¶
Modify _inject_amplihack_if_different() when:
- Changing comparison logic (e.g., semantic comparison)
- Adding new file locations
- Optimizing cache strategy
- Changing injection format
Do not modify for:
- Adding new context types (use new methods)
- Changing injection order (modify
process()) - Preference handling (separate method)
Backward Compatibility¶
The API maintains backward compatibility:
- Input format: Never change hook input schema
- Output format: Always return
{"additionalContext": str} - File locations: Always check old locations first
- Cache format: Version cache keys if structure changes
Performance Considerations¶
Keep these performance targets:
- First message: <100ms total hook time
- Cached messages: <5ms total hook time
- Cache hit rate: >95%
- Memory usage: <10MB per hook process
The current implementation exceeds all targets.
Related APIs¶
find_user_preferences(): Locate USER_PREFERENCES.md fileget_cached_preferences(): Read preferences with cachingbuild_preference_context(): Format preferences for injection_inject_memories_for_agents(): Agent memory injection
See USER_PROMPT_SUBMIT_README.md for preference and memory APIs.
Related¶
- Verify Framework Injection - User guide
- Framework Injection Architecture - Design rationale
- Hook Configuration Guide - Hook system overview
- Coordination Messages - The
[coord]marker in the workflow classification reminder - Capacity notice in hooks - The no-capacity notice and its dedupe