cc-sessions-hooks
Type: WRITE-CAPABLE
DAIC Modes: IMPLEMENT only
Priority: High
Trigger Reference
This skill activates on:
- Keywords: "hook", "sessions_enforce", "post_tool_use", "user_messages", "subagent_hooks", "shared_state"
- Intent patterns: "(create|modify|fix).?hook", "hook.?(enforcement|validation)"
- File patterns:
sessions/hooks/**/*.js
From: skill-rules.json - cc-sessions-hooks configuration
Purpose
Specialized guidance for creating, modifying, and debugging cc-sessions hooks. Hooks are the enforcement layer that ensures DAIC discipline, write-gating, and framework integrity.
Core Behavior
When activated in IMPLEMENT mode with an active cc-sessions task:
Hook Types & Purposes
UserPromptSubmit Hook:
- Fires when user submits a prompt
- Use for: Mode transition triggers, startup protocols, context warnings
- Access: User message content, current session state
PreToolUse Hook:
- Fires BEFORE any tool executes
- Use for: Write-gating enforcement, permission checks, guardrails
- Access: Tool name, parameters, current mode, task state
- Can: Block tool execution, modify parameters, inject warnings
PostToolUse Hook:
- Fires AFTER tool completes
- Use for: State updates, logging, cleanup, validation
- Access: Tool name, parameters, result, errors
SessionStart Hook:
- Fires when Claude Code session begins
- Use for: Initialization, state loading, environment checks
- Access: Session configuration, environment variables
Hook Development Patterns
Basic Hook Structure:
// sessions/hooks/example_hook.js
module.exports = {
name: 'example_hook',
description: 'Brief description of what this hook does',
async execute(context) {
// Hook logic here
// Return { success: true } or { success: false, error: 'message' }
}
};
Enforcement Hook Pattern:
async execute(context) {
const { toolName, toolParams, sessionState } = context;
// Check conditions
if (shouldBlock(toolName, sessionState)) {
return {
success: false,
error: 'Tool blocked: [reason]',
additionalContext: '[guidance for user]'
};
}
return { success: true };
}
Write-Gating Enforcement
The sessions_enforce.js hook is CRITICAL for framework integrity:
What it enforces:
- Write tools (Edit, Write, MultiEdit) only in IMPLEMENT mode
- Only cc-sessions may modify CC_SESSION_MODE / CC_SESSION_TASK_ID
- Todo list changes require user approval
- No writes when no active task exists
How to extend:
- Add new tool checks to
WRITE_TOOLS array
- Add new state validations to
checkWriteGating()
- Log enforcement decisions for debugging
- Never weaken existing checks
Shared State Access
Hooks can read/modify shared state:
const state = require('../sessions-state.json');
const fs = require('fs');
// Read state
const currentMode = state.mode;
const activeTask = state.task;
// Modify state (carefully!)
state.flags.contextWarning85 = true;
fs.writeFileSync(
path.join(__dirname, '../sessions-state.json'),
JSON.stringify(state, null, 2)
);
Hook Execution Order
Understand execution flow:
- UserPromptSubmit (user input processed)
- PreToolUse (before each tool call)
- Tool executes
- PostToolUse (after each tool call)
Hooks execute synchronously within their phase.
Safety Guardrails
CRITICAL WRITE-GATING RULES:
- ✓ Only execute write operations when in IMPLEMENT mode
- ✓ Verify active cc-sessions task exists before writing hooks
- ✓ Follow approved manifest/todos from task file
- ✓ NEVER weaken write-gating logic
- ✓ NEVER allow hooks to bypass DAIC discipline
Hook-Specific Safety:
- Test hooks thoroughly before deployment (they can break the entire framework)
- Always return
{ success: true/false } from execute()
- Include clear error messages when blocking actions
- Log hook decisions for debugging
- Never create infinite loops (hook triggering hook)
- Handle async operations properly (await all promises)
- Validate all inputs (context might be malformed)
State Mutation Safety:
- Only modify state when necessary
- Always validate state structure before writing
- Use atomic writes (read-modify-write pattern)
- Log state changes for auditability
- Never corrupt state (keep backups during development)
Examples
When to Activate
✓ "Add a hook to validate task manifest format"
✓ "Fix the sessions_enforce.js write-gating for MultiEdit tool"
✓ "Create a PostToolUse hook to log all file modifications"
✓ "Modify UserPromptSubmit to detect '/squish' command"
✓ "Debug why the IMPLEMENT mode transition isn't triggering"
When NOT to Activate
✗ In DISCUSS/ALIGN/CHECK mode (hook development requires IMPLEMENT)
✗ No active cc-sessions task (violates write-gating)
✗ User wants to create non-hook cc-sessions code (use cc-sessions-core)
✗ Changes would weaken enforcement mechanisms
Hook Testing Checklist
Before deploying a new or modified hook:
Common Hook Patterns
1. Blocking Pattern
if (invalidCondition) {
return {
success: false,
error: '[CATEGORY: Clear Error Message]',
additionalContext: 'What user should do instead'
};
}
2. Warning Pattern
if (warningCondition) {
console.warn('[Hook Warning]', message);
// Continue execution
}
return { success: true };
3. State Update Pattern
const state = loadState();
state.flags.someFlag = true;
saveState(state);
return { success: true };
4. Conditional Execution
if (context.toolName === 'Write' && context.sessionState.mode !== 'IMPLEMENT') {
return { success: false, error: 'Write only in IMPLEMENT mode' };
}
Decision Logging
When creating or modifying hooks, log in context/decisions.md:
### Hook Change: [Date]
- **Hook:** sessions/hooks/sessions_enforce.js
- **Change:** Added MultiEdit to WRITE_TOOLS array
- **Rationale:** MultiEdit can write to multiple files, needs same gating as Write/Edit
- **Testing:** Verified blocks in DISCUSS, allows in IMPLEMENT
- **Risk:** Low (additive change, follows existing pattern)
Related Skills
- cc-sessions-core - For broader framework development beyond hooks
- framework_health_check - To validate hook behavior after changes
- framework_repair_suggester - If hooks malfunction or cause framework issues
- daic_mode_guidance - For understanding mode transitions that hooks enforce
Last Updated: 2025-11-15
Framework Version: 2.0
1---2name: cc-sessions-hooks3description: Specialized guidance for creating, modifying, and debugging cc-sessions hooks that enforce DAIC discipline, write-gating, and framework integrity4---5
6# cc-sessions-hooks
7
8**Type:** WRITE-CAPABLE
9**DAIC Modes:** IMPLEMENT only
10**Priority:** High
11
12## Trigger Reference
13
14This skill activates on:
15- Keywords: "hook", "sessions_enforce", "post_tool_use", "user_messages", "subagent_hooks", "shared_state"
16- Intent patterns: "(create|modify|fix).*?hook", "hook.*?(enforcement|validation)"
17- File patterns: `sessions/hooks/**/*.js`
18
19From: `skill-rules.json` - cc-sessions-hooks configuration
20
21## Purpose
22
23Specialized guidance for creating, modifying, and debugging cc-sessions hooks. Hooks are the enforcement layer that ensures DAIC discipline, write-gating, and framework integrity.
24
25## Core Behavior
26
27When activated in IMPLEMENT mode with an active cc-sessions task:
28
291. **Hook Types & Purposes**
30
31 **UserPromptSubmit Hook:**
32 - Fires when user submits a prompt
33 - Use for: Mode transition triggers, startup protocols, context warnings
34 - Access: User message content, current session state
35
36 **PreToolUse Hook:**
37 - Fires BEFORE any tool executes
38 - Use for: Write-gating enforcement, permission checks, guardrails
39 - Access: Tool name, parameters, current mode, task state
40 - Can: Block tool execution, modify parameters, inject warnings
41
42 **PostToolUse Hook:**
43 - Fires AFTER tool completes
44 - Use for: State updates, logging, cleanup, validation
45 - Access: Tool name, parameters, result, errors
46
47 **SessionStart Hook:**
48 - Fires when Claude Code session begins
49 - Use for: Initialization, state loading, environment checks
50 - Access: Session configuration, environment variables
51
522. **Hook Development Patterns**
53
54 **Basic Hook Structure:**
55 ```javascript
56 // sessions/hooks/example_hook.js
57 module.exports = {
58 name: 'example_hook',
59 description: 'Brief description of what this hook does',
60
61 async execute(context) {
62 // Hook logic here
63 // Return { success: true } or { success: false, error: 'message' }
64 }
65 };
66 ```
67
68 **Enforcement Hook Pattern:**
69 ```javascript
70 async execute(context) {
71 const { toolName, toolParams, sessionState } = context;
72
73 // Check conditions
74 if (shouldBlock(toolName, sessionState)) {
75 return {
76 success: false,
77 error: 'Tool blocked: [reason]',
78 additionalContext: '[guidance for user]'
79 };
80 }
81
82 return { success: true };
83 }
84 ```
85
863. **Write-Gating Enforcement**
87
88 The `sessions_enforce.js` hook is CRITICAL for framework integrity:
89
90 **What it enforces:**
91 - Write tools (Edit, Write, MultiEdit) only in IMPLEMENT mode
92 - Only cc-sessions may modify CC_SESSION_MODE / CC_SESSION_TASK_ID
93 - Todo list changes require user approval
94 - No writes when no active task exists
95
96 **How to extend:**
97 - Add new tool checks to `WRITE_TOOLS` array
98 - Add new state validations to `checkWriteGating()`
99 - Log enforcement decisions for debugging
100 - Never weaken existing checks
101
1024. **Shared State Access**
103
104 Hooks can read/modify shared state:
105
106 ```javascript
107 const state = require('../sessions-state.json');
108 const fs = require('fs');
109
110 // Read state
111 const currentMode = state.mode;
112 const activeTask = state.task;
113
114 // Modify state (carefully!)
115 state.flags.contextWarning85 = true;
116 fs.writeFileSync(
117 path.join(__dirname, '../sessions-state.json'),
118 JSON.stringify(state, null, 2)
119 );
120 ```
121
1225. **Hook Execution Order**
123
124 Understand execution flow:
125 1. UserPromptSubmit (user input processed)
126 2. PreToolUse (before each tool call)
127 3. Tool executes
128 4. PostToolUse (after each tool call)
129
130 Hooks execute synchronously within their phase.
131
132## Safety Guardrails
133
134**CRITICAL WRITE-GATING RULES:**
135- ✓ Only execute write operations when in IMPLEMENT mode
136- ✓ Verify active cc-sessions task exists before writing hooks
137- ✓ Follow approved manifest/todos from task file
138- ✓ NEVER weaken write-gating logic
139- ✓ NEVER allow hooks to bypass DAIC discipline
140
141**Hook-Specific Safety:**
142- Test hooks thoroughly before deployment (they can break the entire framework)
143- Always return `{ success: true/false }` from execute()
144- Include clear error messages when blocking actions
145- Log hook decisions for debugging
146- Never create infinite loops (hook triggering hook)
147- Handle async operations properly (await all promises)
148- Validate all inputs (context might be malformed)
149
150**State Mutation Safety:**
151- Only modify state when necessary
152- Always validate state structure before writing
153- Use atomic writes (read-modify-write pattern)
154- Log state changes for auditability
155- Never corrupt state (keep backups during development)
156
157## Examples
158
159### When to Activate
160
161✓ "Add a hook to validate task manifest format"
162✓ "Fix the sessions_enforce.js write-gating for MultiEdit tool"
163✓ "Create a PostToolUse hook to log all file modifications"
164✓ "Modify UserPromptSubmit to detect '/squish' command"
165✓ "Debug why the IMPLEMENT mode transition isn't triggering"
166
167### When NOT to Activate
168
169✗ In DISCUSS/ALIGN/CHECK mode (hook development requires IMPLEMENT)
170✗ No active cc-sessions task (violates write-gating)
171✗ User wants to create non-hook cc-sessions code (use cc-sessions-core)
172✗ Changes would weaken enforcement mechanisms
173
174## Hook Testing Checklist
175
176Before deploying a new or modified hook:
177
178- [ ] Hook returns proper `{ success, error? }` structure
179- [ ] Error messages are clear and actionable
180- [ ] Hook doesn't block legitimate operations
181- [ ] Hook doesn't create infinite loops
182- [ ] Async operations are properly awaited
183- [ ] State modifications are atomic and validated
184- [ ] Hook behavior logged for debugging
185- [ ] Tested in all DAIC modes
186- [ ] Doesn't introduce performance issues
187- [ ] Documented in hook file comments
188
189## Common Hook Patterns
190
191### 1. Blocking Pattern
192```javascript
193if (invalidCondition) {
194 return {
195 success: false,
196 error: '[CATEGORY: Clear Error Message]',
197 additionalContext: 'What user should do instead'
198 };
199}
200```
201
202### 2. Warning Pattern
203```javascript
204if (warningCondition) {
205 console.warn('[Hook Warning]', message);
206 // Continue execution
207}
208return { success: true };
209```
210
211### 3. State Update Pattern
212```javascript
213const state = loadState();
214state.flags.someFlag = true;
215saveState(state);
216return { success: true };
217```
218
219### 4. Conditional Execution
220```javascript
221if (context.toolName === 'Write' && context.sessionState.mode !== 'IMPLEMENT') {
222 return { success: false, error: 'Write only in IMPLEMENT mode' };
223}
224```
225
226## Decision Logging
227
228When creating or modifying hooks, log in `context/decisions.md`:
229
230```markdown
231### Hook Change: [Date]
232- **Hook:** sessions/hooks/sessions_enforce.js
233- **Change:** Added MultiEdit to WRITE_TOOLS array
234- **Rationale:** MultiEdit can write to multiple files, needs same gating as Write/Edit
235- **Testing:** Verified blocks in DISCUSS, allows in IMPLEMENT
236- **Risk:** Low (additive change, follows existing pattern)
237```
238
239## Related Skills
240
241- **cc-sessions-core** - For broader framework development beyond hooks
242- **framework_health_check** - To validate hook behavior after changes
243- **framework_repair_suggester** - If hooks malfunction or cause framework issues
244- **daic_mode_guidance** - For understanding mode transitions that hooks enforce
245
246---
247
248**Last Updated:** 2025-11-15
249**Framework Version:** 2.0