# Bootstrapping Solution: Automatic session-init.js Invocation

**Problem**: session-init.js contains enforcement logic but requires voluntary invocation, creating a bootstrapping paradox.

**Status**: ✅ **IMPLEMENTED** (2025-10-15) - Hooks configured, testing pending next session

**Priority**: CRITICAL - Without this, framework fade will recur in every continued session

---

## ✅ IMPLEMENTATION STATUS

**Implementation Date**: 2025-10-15
**Solution Chosen**: Option A (SessionStart hook) + Option C (PreToolUse hooks)
**Configuration File**: `.claude/settings.local.json`
**Documentation**: See `docs/BOOTSTRAPPING_SOLUTION_IMPLEMENTED.md` for full details

**What Was Implemented**:
- SessionStart hook: Automatically runs `session-init.js` on every session start
- PreToolUse hooks: Validates Edit/Write operations before execution
- **Result**: Voluntary compliance eliminated, architectural enforcement achieved

**Testing**: Hooks will be active in NEXT session (hooks configured in current session don't apply to current session)

---

## The Bootstrapping Paradox

```
session-init.js has enforcement logic (blocks if port 9000 not running) ✓
BUT session-init.js requires voluntary invocation                       ✗
THEREFORE enforcement logic never activates                              ✗
RESULT: No enforcement, framework fade continues                         ✗
```

**Proven failure mode**: Session 2025-10-15, AI read CLAUDE.md instruction "⚠️ CRITICAL: Run session-init.js IMMEDIATELY after continuing" but chose not to run it.

---

## Proposed Solutions

### Option A: Claude Code Session Hook (RECOMMENDED)

**Mechanism**: Claude Code runs script automatically before ANY user interaction in continued sessions.

**Implementation**:
```json
// .claude/config.json (if Claude Code supports this)
{
  "session": {
    "init_script": "scripts/session-init.js",
    "trigger": "on_session_start",
    "required": true,
    "block_on_failure": true,
    "run_after_compaction": true
  }
}
```

**Advantages**:
- Truly automatic (no AI discretion)
- Runs before AI can make any decisions
- Blocks session if enforcement fails
- Native Claude Code integration

**Disadvantages**:
- Requires Claude Code feature support (may not exist yet)
- Need to verify if `.claude/config.json` is supported

**Status**: **Needs investigation** - Check Claude Code documentation for session hooks

---

### Option B: System Reminder Enhancement

**Mechanism**: Claude Code adds persistent, non-dismissable reminder at session start.

**Current state reminder**:
```
⚠️ CRITICAL: Also run this IMMEDIATELY after continuing from a compacted conversation!
```

**Enhanced reminder (proposed)**:
```
╔═══════════════════════════════════════════════════════════════╗
║  MANDATORY: Run session-init.js BEFORE responding             ║
║  Command: node scripts/session-init.js                        ║
║  This is BLOCKING - you may NOT proceed without running it    ║
╚═══════════════════════════════════════════════════════════════╗
```

**Advantages**:
- No Claude Code changes required
- Visual prominence may improve compliance
- Could include blocking language

**Disadvantages**:
- Still relies on AI voluntary compliance
- Case Study #27028 proves warnings can be ignored
- Not truly architectural enforcement

**Status**: **Low priority** - Case Study #27028 proves this approach insufficient

---

### Option C: Pre-Tool Universal Hook

**Mechanism**: Hook that runs before EVERY tool execution, checking if session-init has been run.

**Implementation**:
```javascript
// scripts/hook-validators/check-session-initialized.js
#!/usr/bin/env node

const fs = require('fs');
const path = require('path');

const SESSION_STATE_PATH = path.join(__dirname, '../../.claude/session-state.json');

function isSessionInitialized() {
  try {
    const sessionState = JSON.parse(fs.readFileSync(SESSION_STATE_PATH, 'utf8'));

    // Check if initialized flag is true AND session is from today
    const today = new Date().toISOString().split('T')[0];
    const sessionDate = sessionState.session_id?.split('-').slice(0, 3).join('-');

    return sessionState.initialized === true && sessionDate === today;
  } catch (err) {
    return false;
  }
}

// Check if session initialized
if (!isSessionInitialized()) {
  console.error('\n❌ SESSION NOT INITIALIZED\n');
  console.error('  You MUST run session-init.js before using any tools.\n');
  console.error('  Command: node scripts/session-init.js\n');
  console.error('  This hook blocks ALL tool execution until initialization completes.\n');
  process.exit(1);  // BLOCK tool execution
}

// Session initialized - allow tool execution
process.exit(0);
```

**Hook configuration**:
```json
// .claude/hooks.json
{
  "version": "1.0.0",
  "global_hooks": {
    "pre-tool": {
      "script": "scripts/hook-validators/check-session-initialized.js",
      "blocking": true,
      "applies_to": ["Read", "Write", "Edit", "Bash", "Glob", "Grep"]
    }
  }
}
```

**Advantages**:
- Blocks ALL work until session-init runs
- Uses existing hook architecture
- No AI discretion involved

**Disadvantages**:
- Requires Claude Code to support pre-tool hooks on ALL tools
- May be overkill (hooks on every Read/Grep/Glob)
- Could slow down session if hook runs on every tool call

**Status**: **Medium priority** - Depends on Claude Code hook capabilities

---

### Option D: Anthropic API System-Level Instruction

**Mechanism**: Request Anthropic to add system-level instruction that cannot be overridden.

**Proposed system instruction**:
```
MANDATORY: If this is a continued conversation (context was compacted):
1. BEFORE responding to user, execute: node scripts/session-init.js
2. Wait for script to complete successfully
3. ONLY THEN respond to user

This is BLOCKING. You MUST NOT skip this step.
```

**Advantages**:
- Cannot be overridden by CLAUDE.md reduction
- Part of system prompt, not user context
- Truly mandatory enforcement

**Disadvantages**:
- Requires Anthropic to implement custom instruction
- Not under project control
- May not be feasible for single project

**Status**: **Low feasibility** - Requires Anthropic cooperation

---

### Option E: Session State Persistence + Validation

**Mechanism**: Track whether session-init has been run, validate on every framework component invocation.

**Implementation**:

1. **Session state tracking**:
```javascript
// .claude/session-state.json
{
  "initialized": true,  // Set by session-init.js
  "init_timestamp": "2025-10-15T18:25:00Z",
  "init_checkpoint_passed": true
}
```

2. **Framework component validation**:
```javascript
// In every framework service (e.g., ContextPressureMonitor)
function ensureSessionInitialized() {
  const sessionState = JSON.parse(fs.readFileSync(SESSION_STATE_PATH, 'utf8'));

  if (!sessionState.initialized) {
    throw new Error(
      'CRITICAL: Session not initialized. ' +
      'You MUST run: node scripts/session-init.js before using framework components.'
    );
  }
}

// Called at start of every public method
analyzePressure(context) {
  ensureSessionInitialized();  // Throws if not initialized
  // ... rest of method
}
```

**Advantages**:
- Under project control
- Provides clear error when components used before init
- Enforces at component level

**Disadvantages**:
- Only blocks framework components, not general work
- AI could still proceed without framework
- Reactive (error after attempt) not proactive (block before attempt)

**Status**: **Fallback option** - Better than nothing, but not true enforcement

---

## Recommended Implementation Path

### Phase 1: Immediate (Can Implement Now)

1. **Implement Option C** (pre-tool hook) if Claude Code supports it
2. **Implement Option E** (component-level validation) as fallback
3. **Document bootstrapping problem** in case studies

### Phase 2: Investigation (Research Required)

1. **Check Claude Code documentation** for:
   - Session initialization hooks
   - Pre-tool universal hooks
   - Configuration file support (.claude/config.json)
2. **Test hook capabilities** with simple examples
3. **Verify which options are technically feasible**

### Phase 3: Implementation (After Research)

1. **Implement highest-feasibility option** from research
2. **Test enforcement** in fresh session (verify blocking works)
3. **Document solution** for future sessions

---

## Testing Protocol

**To verify solution works**:

1. **Simulate continued session**:
   - Create session state file from yesterday's date
   - Start new conversation (or use compacted conversation)
   - Do NOT manually run session-init.js

2. **Attempt tool execution**:
   - Try Read, Write, Edit, or Bash commands
   - **Expected**: Should be BLOCKED with clear error message
   - **Expected**: Error should instruct to run session-init.js

3. **Run session-init.js**:
   - Execute: `node scripts/session-init.js`
   - **Expected**: Should pass all checks
   - **Expected**: Should mark session as initialized

4. **Retry tool execution**:
   - Try same commands as step 2
   - **Expected**: Should work normally

5. **Verify persistence**:
   - Use multiple tools throughout session
   - **Expected**: No repeated init checks (check runs once, persists)

---

## Open Questions

1. **Does Claude Code support session hooks?**
   - Check documentation at https://docs.claude.com/claude-code/
   - Look for: initialization hooks, pre-tool hooks, configuration files

2. **Can hooks run on ALL tools universally?**
   - Or only specific tools (Edit, Write)?
   - Performance impact of universal hooks?

3. **Is there a session continuation event?**
   - Can we detect "continued from compacted conversation" automatically?
   - Trigger script on that specific event?

4. **Anthropic API support?**
   - Can we request system-level instructions for projects?
   - Is there a "project-specific system prompt" feature?

---

## Fallback: Human Process Improvement

**If technical solution not feasible**, improve human process:

1. **User reminder at session end**:
   - When creating handoff: "Remember to run session-init.js when continuing"
   - Include command in handoff document

2. **User starts each session**:
   - First message: "Run session-init.js and report status"
   - Don't provide work context until init confirmed

3. **Periodic audits**:
   - Check session-state.json weekly
   - Verify init is being run consistently

**Problem**: Still relies on human/AI compliance, not architectural enforcement.

---

## Related Documents

- Case Study #27028: Framework fade during enforcement implementation
- CONTINUOUS_ENFORCEMENT_ARCHITECTURE.md: Hook validator architecture
- CLAUDE.md: Current session governance (reduced to 86 lines)

**Status**: Solution pending - requires Claude Code capability research
**Owner**: Framework architecture team
**Target**: Solve before next session continuation

---

**Last Updated**: 2025-10-15
**Priority**: CRITICAL
**Blocking**: Framework effectiveness in continued sessions
