brain-dev 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +152 -0
  3. package/agents/brain-checker.md +33 -0
  4. package/agents/brain-debugger.md +35 -0
  5. package/agents/brain-executor.md +37 -0
  6. package/agents/brain-mapper.md +44 -0
  7. package/agents/brain-planner.md +49 -0
  8. package/agents/brain-researcher.md +47 -0
  9. package/agents/brain-synthesizer.md +43 -0
  10. package/agents/brain-verifier.md +41 -0
  11. package/bin/brain-tools.cjs +185 -0
  12. package/bin/lib/adr.cjs +283 -0
  13. package/bin/lib/agents.cjs +152 -0
  14. package/bin/lib/anti-patterns.cjs +183 -0
  15. package/bin/lib/audit.cjs +268 -0
  16. package/bin/lib/commands/adr.cjs +126 -0
  17. package/bin/lib/commands/complete.cjs +270 -0
  18. package/bin/lib/commands/config.cjs +306 -0
  19. package/bin/lib/commands/discuss.cjs +237 -0
  20. package/bin/lib/commands/execute.cjs +415 -0
  21. package/bin/lib/commands/health.cjs +103 -0
  22. package/bin/lib/commands/map.cjs +101 -0
  23. package/bin/lib/commands/new-project.cjs +885 -0
  24. package/bin/lib/commands/pause.cjs +142 -0
  25. package/bin/lib/commands/phase-manage.cjs +357 -0
  26. package/bin/lib/commands/plan.cjs +451 -0
  27. package/bin/lib/commands/progress.cjs +167 -0
  28. package/bin/lib/commands/quick.cjs +447 -0
  29. package/bin/lib/commands/resume.cjs +196 -0
  30. package/bin/lib/commands/storm.cjs +590 -0
  31. package/bin/lib/commands/verify.cjs +504 -0
  32. package/bin/lib/commands.cjs +263 -0
  33. package/bin/lib/complexity.cjs +138 -0
  34. package/bin/lib/complexity.test.cjs +108 -0
  35. package/bin/lib/config.cjs +452 -0
  36. package/bin/lib/core.cjs +62 -0
  37. package/bin/lib/detect.cjs +603 -0
  38. package/bin/lib/git.cjs +112 -0
  39. package/bin/lib/health.cjs +356 -0
  40. package/bin/lib/init.cjs +310 -0
  41. package/bin/lib/logger.cjs +100 -0
  42. package/bin/lib/platform.cjs +58 -0
  43. package/bin/lib/requirements.cjs +158 -0
  44. package/bin/lib/roadmap.cjs +228 -0
  45. package/bin/lib/security.cjs +237 -0
  46. package/bin/lib/state.cjs +353 -0
  47. package/bin/lib/templates.cjs +48 -0
  48. package/bin/templates/advocate.md +182 -0
  49. package/bin/templates/checkpoint.md +55 -0
  50. package/bin/templates/debugger.md +148 -0
  51. package/bin/templates/discuss.md +60 -0
  52. package/bin/templates/executor.md +201 -0
  53. package/bin/templates/mapper.md +129 -0
  54. package/bin/templates/plan-checker.md +134 -0
  55. package/bin/templates/planner.md +165 -0
  56. package/bin/templates/researcher.md +78 -0
  57. package/bin/templates/storm.html +376 -0
  58. package/bin/templates/synthesis.md +30 -0
  59. package/bin/templates/verifier.md +181 -0
  60. package/commands/brain/adr.md +34 -0
  61. package/commands/brain/complete.md +37 -0
  62. package/commands/brain/config.md +37 -0
  63. package/commands/brain/discuss.md +35 -0
  64. package/commands/brain/execute.md +38 -0
  65. package/commands/brain/health.md +33 -0
  66. package/commands/brain/map.md +35 -0
  67. package/commands/brain/new-project.md +38 -0
  68. package/commands/brain/pause.md +26 -0
  69. package/commands/brain/plan.md +38 -0
  70. package/commands/brain/progress.md +28 -0
  71. package/commands/brain/quick.md +51 -0
  72. package/commands/brain/resume.md +28 -0
  73. package/commands/brain/storm.md +30 -0
  74. package/commands/brain/verify.md +39 -0
  75. package/hooks/bootstrap.sh +54 -0
  76. package/hooks/post-tool-use.sh +45 -0
  77. package/hooks/statusline.sh +130 -0
  78. package/package.json +36 -0
@@ -0,0 +1,35 @@
1
+ ---
2
+ name: brain:discuss
3
+ description: Capture implementation decisions for a phase
4
+ argument-hint: "<phase>"
5
+ allowed-tools:
6
+ - Read
7
+ - Write
8
+ - Edit
9
+ - Glob
10
+ - Grep
11
+ - Bash
12
+ - Task
13
+ - AskUserQuestion
14
+ ---
15
+ <objective>
16
+ Capture implementation decisions, constraints, and technical context for a specific phase before planning begins.
17
+ Creates a CONTEXT.md file that feeds into the planning process.
18
+ </objective>
19
+
20
+ <context>
21
+ `$ARGUMENTS` is the phase number (e.g., `1`, `2`).
22
+ </context>
23
+
24
+ <process>
25
+ 1. Run the brain CLI for the given phase:
26
+ ```bash
27
+ npx brain-dev discuss $ARGUMENTS
28
+ ```
29
+
30
+ 2. The CLI will present implementation questions and trade-offs. Use AskUserQuestion to gather the user's preferences on each decision point.
31
+
32
+ 3. Review the generated CONTEXT.md to confirm all decisions are captured accurately.
33
+
34
+ 4. **Next step:** Run `/brain:plan $ARGUMENTS` to create execution plans informed by these decisions.
35
+ </process>
@@ -0,0 +1,38 @@
1
+ ---
2
+ name: brain:execute
3
+ description: Execute all plans in a phase with wave-based agents
4
+ argument-hint: "<phase> [--gaps-only]"
5
+ allowed-tools:
6
+ - Read
7
+ - Write
8
+ - Edit
9
+ - Glob
10
+ - Grep
11
+ - Bash
12
+ - Task
13
+ - AskUserQuestion
14
+ ---
15
+ <objective>
16
+ Execute all plans in a phase using wave-based parallel execution.
17
+ Discovers plans, analyzes dependencies, groups into waves, spawns subagents, and collects results.
18
+ </objective>
19
+
20
+ <context>
21
+ `$ARGUMENTS` contains the phase number and optional flags:
22
+ - `--gaps-only` — Execute only gap closure plans created by verify
23
+ </context>
24
+
25
+ <process>
26
+ 1. Run the brain CLI to execute plans:
27
+ ```bash
28
+ npx brain-dev execute $ARGUMENTS
29
+ ```
30
+
31
+ 2. The CLI groups plans into dependency-ordered waves and executes each wave in parallel via subagents. Monitor progress as each wave completes.
32
+
33
+ 3. Report results per wave: which plans succeeded, which failed, and any errors encountered.
34
+
35
+ 4. Verification runs automatically after execution. Review the verification output.
36
+
37
+ 5. **Next step:** If all verified, run `/brain:discuss {next_phase}` for the next phase. If gaps found, run `/brain:plan {phase} --gaps` to create fix plans.
38
+ </process>
@@ -0,0 +1,33 @@
1
+ ---
2
+ name: brain:health
3
+ description: Diagnose issues and auto-repair
4
+ argument-hint: "[--fix] [--quick]"
5
+ allowed-tools:
6
+ - Read
7
+ - Write
8
+ - Edit
9
+ - Glob
10
+ - Grep
11
+ - Bash
12
+ ---
13
+ <objective>
14
+ Diagnose project health issues including broken references, missing files, inconsistent state, and configuration problems.
15
+ Optionally auto-repairs safe issues with --fix.
16
+ </objective>
17
+
18
+ <context>
19
+ `$ARGUMENTS` contains optional flags:
20
+ - `--fix` — Automatically repair detected issues that are safe to fix
21
+ - `--quick` — Run only critical checks, skip deep analysis
22
+ </context>
23
+
24
+ <process>
25
+ 1. Run the brain CLI to check health:
26
+ ```bash
27
+ npx brain-dev health $ARGUMENTS
28
+ ```
29
+
30
+ 2. Review the diagnostic output. Report issues found grouped by severity (critical, warning, info).
31
+
32
+ 3. If `--fix` was used, confirm which issues were auto-repaired and which still need manual attention.
33
+ </process>
@@ -0,0 +1,35 @@
1
+ ---
2
+ name: brain:map
3
+ description: Run codebase mapper with 4 focus agents
4
+ argument-hint: "[--focus tech|arch|quality|concerns]"
5
+ allowed-tools:
6
+ - Read
7
+ - Write
8
+ - Glob
9
+ - Grep
10
+ - Bash
11
+ - Task
12
+ ---
13
+ <objective>
14
+ Spawn 4 mapper agents to analyze the codebase from different perspectives (tech, architecture, quality, concerns).
15
+ Generates 7 documents in .brain/codebase/ including a security scan.
16
+ </objective>
17
+
18
+ <context>
19
+ `$ARGUMENTS` contains optional flags:
20
+ - `--focus tech` — Focus on technology stack and dependencies
21
+ - `--focus arch` — Focus on architecture and patterns
22
+ - `--focus quality` — Focus on code quality and test coverage
23
+ - `--focus concerns` — Focus on risks, debt, and security concerns
24
+ </context>
25
+
26
+ <process>
27
+ 1. Run the brain CLI to map the codebase:
28
+ ```bash
29
+ npx brain-dev map $ARGUMENTS
30
+ ```
31
+
32
+ 2. The CLI spawns 4 focus agents that analyze the codebase in parallel. Wait for all agents to complete.
33
+
34
+ 3. Review the generated documents in .brain/codebase/. Present a summary of key findings from each focus area, highlighting any security concerns.
35
+ </process>
@@ -0,0 +1,38 @@
1
+ ---
2
+ name: brain:new-project
3
+ description: Initialize a new project with guided questioning
4
+ allowed-tools:
5
+ - Read
6
+ - Write
7
+ - Edit
8
+ - Glob
9
+ - Grep
10
+ - Bash
11
+ - Task
12
+ - AskUserQuestion
13
+ ---
14
+ <objective>
15
+ Start a new brain project through interactive questioning to establish scope, goals, and initial roadmap.
16
+ Creates PROJECT.md, REQUIREMENTS.md, and ROADMAP.md with the gathered context.
17
+ </objective>
18
+
19
+ <context>
20
+ No arguments required. The CLI handles interactive setup.
21
+ </context>
22
+
23
+ <process>
24
+ 1. Run the brain CLI to start the guided project creation flow:
25
+ ```bash
26
+ npx brain-dev new-project
27
+ ```
28
+
29
+ 2. The CLI auto-detects whether this is a new or existing project:
30
+ - **New project (greenfield):** Asks vision-first questions about what you want to build
31
+ - **Existing project (brownfield):** Analyzes the codebase first, then asks context-aware questions about what to add/change. Also spawns mapper agents to deeply analyze the existing stack and architecture.
32
+
33
+ 3. Follow the interactive prompts and provide answers via AskUserQuestion.
34
+
35
+ 4. Review the generated files: PROJECT.md, REQUIREMENTS.md, and ROADMAP.md. Confirm the project structure looks correct.
36
+
37
+ 5. **Next step:** Run `/brain:discuss 1` to capture implementation decisions for the first phase.
38
+ </process>
@@ -0,0 +1,26 @@
1
+ ---
2
+ name: brain:pause
3
+ description: Save work state for session continuity
4
+ allowed-tools:
5
+ - Read
6
+ - Bash
7
+ ---
8
+ <objective>
9
+ Save the current work state to .continue-here.md so work can be restored in a future session.
10
+ Safe to close the session after this command completes.
11
+ </objective>
12
+
13
+ <context>
14
+ No arguments required. Captures current session state automatically.
15
+ </context>
16
+
17
+ <process>
18
+ 1. Run the brain CLI to save state:
19
+ ```bash
20
+ npx brain-dev pause $ARGUMENTS
21
+ ```
22
+
23
+ 2. Confirm that .continue-here.md was created with the current phase, pending tasks, and context.
24
+
25
+ 3. Inform the user it is safe to close the session. To restore later, use `/brain:resume`.
26
+ </process>
@@ -0,0 +1,38 @@
1
+ ---
2
+ name: brain:plan
3
+ description: Create verified execution plans for a phase
4
+ argument-hint: "<phase> [--research] [--gaps] [--skip-verify]"
5
+ allowed-tools:
6
+ - Read
7
+ - Write
8
+ - Edit
9
+ - Glob
10
+ - Grep
11
+ - Bash
12
+ - Task
13
+ - AskUserQuestion
14
+ ---
15
+ <objective>
16
+ Create detailed, executable PLAN.md files for a roadmap phase with integrated research, planning, and checker verification.
17
+ Default flow: Research (if needed) -> Plan -> Verify -> Done.
18
+ </objective>
19
+
20
+ <context>
21
+ `$ARGUMENTS` contains the phase number and optional flags:
22
+ - `--research` — Force re-research even if RESEARCH.md exists
23
+ - `--gaps` — Gap closure mode: reads VERIFICATION.md and creates fix plans
24
+ - `--skip-verify` — Skip the verification loop after plan creation
25
+ </context>
26
+
27
+ <process>
28
+ 1. Run the brain CLI to generate plans:
29
+ ```bash
30
+ npx brain-dev plan $ARGUMENTS
31
+ ```
32
+
33
+ 2. The CLI researches domain context, creates step-by-step plans, and verifies them against requirements. It iterates until plans pass verification or max iterations are reached.
34
+
35
+ 3. Review the generated PLAN.md files. Confirm the plans cover all phase requirements and the checker passed.
36
+
37
+ 4. **Next step:** Run `/brain:execute $ARGUMENTS` to execute the plans with wave-based agents.
38
+ </process>
@@ -0,0 +1,28 @@
1
+ ---
2
+ name: brain:progress
3
+ description: Show project status and next action
4
+ allowed-tools:
5
+ - Read
6
+ - Glob
7
+ - Grep
8
+ - Bash
9
+ ---
10
+ <objective>
11
+ Display current project status including phase progress, pending tasks, and recommended next action.
12
+ Read-only command with no side effects.
13
+ </objective>
14
+
15
+ <context>
16
+ No arguments required. Reads project state automatically.
17
+ </context>
18
+
19
+ <process>
20
+ 1. Run the brain CLI to check progress:
21
+ ```bash
22
+ npx brain-dev progress
23
+ ```
24
+
25
+ 2. Review the output: current phase, plan completion percentages, blockers, and suggested next command.
26
+
27
+ 3. Present a summary to the user showing where the project stands and what to do next.
28
+ </process>
@@ -0,0 +1,51 @@
1
+ ---
2
+ name: brain:quick
3
+ description: Execute quick tasks without full phase ceremony
4
+ allowed-tools:
5
+ - Read
6
+ - Write
7
+ - Edit
8
+ - Glob
9
+ - Grep
10
+ - Bash
11
+ - Agent
12
+ - AskUserQuestion
13
+ ---
14
+ <objective>
15
+ Execute a quick, atomic task with plan → execute → (optional verify) → commit.
16
+ Bypasses the full discuss → plan → execute → verify lifecycle.
17
+ </objective>
18
+
19
+ <context>
20
+ Quick tasks live in `.brain/quick/` separate from planned phases.
21
+ Use `--full` flag for plan checking + verification.
22
+ </context>
23
+
24
+ <agents>
25
+ Use subagent_type "brain-planner" for planning.
26
+ Use subagent_type "brain-executor" for execution.
27
+ Use subagent_type "brain-verifier" for verification (--full mode only).
28
+ </agents>
29
+
30
+ <process>
31
+ 1. Run: `npx brain-dev quick [--full] "task description"`
32
+ - CLI creates task directory, generates planner prompt
33
+ - Spawn brain-planner agent with the provided prompt
34
+ - Wait for planner to complete
35
+
36
+ 2. Run: `npx brain-dev quick --execute --task N`
37
+ - CLI generates executor prompt from the plan
38
+ - Spawn brain-executor agent with the provided prompt
39
+ - Wait for executor to complete
40
+
41
+ 3. (Only with --full) Run: `npx brain-dev quick --verify --task N`
42
+ - CLI generates verifier prompt
43
+ - Spawn brain-verifier agent
44
+ - Wait for verification
45
+
46
+ 4. Run: `npx brain-dev quick --complete --task N`
47
+ - CLI outputs STATE.md update instructions and commit file list
48
+ - Update STATE.md and commit artifacts
49
+
50
+ Follow the `nextAction` field in each CLI output to know the next command.
51
+ </process>
@@ -0,0 +1,28 @@
1
+ ---
2
+ name: brain:resume
3
+ description: Restore work from previous session
4
+ allowed-tools:
5
+ - Read
6
+ - Glob
7
+ - Grep
8
+ - Bash
9
+ ---
10
+ <objective>
11
+ Restore work state from .continue-here.md and re-establish context for continued work.
12
+ Picks up exactly where the previous session left off.
13
+ </objective>
14
+
15
+ <context>
16
+ No arguments required. Reads the most recent saved state automatically.
17
+ </context>
18
+
19
+ <process>
20
+ 1. Run the brain CLI to restore state:
21
+ ```bash
22
+ npx brain-dev resume
23
+ ```
24
+
25
+ 2. Review the restored context: active phase, in-progress plans, and what was happening when the session was paused.
26
+
27
+ 3. Present a summary to the user and suggest the next action to continue work seamlessly.
28
+ </process>
@@ -0,0 +1,30 @@
1
+ ---
2
+ name: brain:storm
3
+ description: Launch visual brainstorming server
4
+ argument-hint: "[topic] [--stop] [--port <port>]"
5
+ allowed-tools:
6
+ - Read
7
+ - Bash
8
+ ---
9
+ <objective>
10
+ Start a WebSocket-based brainstorming server with an interactive browser interface.
11
+ Sessions are stored in .brain/storm/ for later reference.
12
+ </objective>
13
+
14
+ <context>
15
+ `$ARGUMENTS` contains optional topic and flags:
16
+ - `[topic]` — Seed the session with an initial brainstorming topic
17
+ - `--stop` — Stop a running brainstorming server
18
+ - `--port <port>` — Use a specific port for the server
19
+ </context>
20
+
21
+ <process>
22
+ 1. Run the brain CLI to start (or stop) the brainstorming server:
23
+ ```bash
24
+ npx brain-dev storm $ARGUMENTS
25
+ ```
26
+
27
+ 2. If starting: the CLI launches the server and opens the browser. Report the URL to the user.
28
+
29
+ 3. If `--stop` was used: confirm the server was shut down. Session data remains in .brain/storm/.
30
+ </process>
@@ -0,0 +1,39 @@
1
+ ---
2
+ name: brain:verify
3
+ description: Verify completed work against must-haves
4
+ argument-hint: "<phase> [--auto-recover]"
5
+ allowed-tools:
6
+ - Read
7
+ - Write
8
+ - Edit
9
+ - Glob
10
+ - Grep
11
+ - Bash
12
+ - Task
13
+ - AskUserQuestion
14
+ ---
15
+ <objective>
16
+ Run 3-level verification of completed phase work against defined must-have requirements and acceptance criteria.
17
+ Produces a VERIFICATION.md report with pass/gaps/human_needed status.
18
+ </objective>
19
+
20
+ <context>
21
+ `$ARGUMENTS` contains the phase number and optional flags:
22
+ - `--auto-recover` — Automatically create and execute gap closure plans for failures
23
+ </context>
24
+
25
+ <process>
26
+ 1. Run the brain CLI to verify the phase:
27
+ ```bash
28
+ npx brain-dev verify $ARGUMENTS
29
+ ```
30
+
31
+ 2. The CLI checks all completed work against phase requirements at 3 levels. Review the VERIFICATION.md report.
32
+
33
+ 3. Report the outcome:
34
+ - **pass** — All requirements met. Proceed to next phase.
35
+ - **gaps** — Some requirements unmet. Fix plans needed.
36
+ - **human_needed** — Issues requiring manual intervention.
37
+
38
+ 4. **Next step:** If gaps found, run `/brain:plan $ARGUMENTS --gaps` to create fix plans. If all passed, run `/brain:complete` to archive the milestone.
39
+ </process>
@@ -0,0 +1,54 @@
1
+ #!/bin/bash
2
+ # Brain SessionStart hook -- injects project context into Claude Code
3
+ # Registered in .claude/settings.json during brain-dev init
4
+
5
+ BRAIN_DIR="${CLAUDE_PROJECT_DIR:-.}/.brain"
6
+
7
+ # Clean stale bridge file from previous session
8
+ rm -f "$BRAIN_DIR/.context-bridge.json"
9
+
10
+ # Pre-project state
11
+ if [ ! -f "$BRAIN_DIR/brain.json" ]; then
12
+ echo "[brain] Ready. No project yet. Run /brain:new-project to begin."
13
+ exit 0
14
+ fi
15
+
16
+ # Get status and format for context injection
17
+ # Use npx to ensure brain-dev is found regardless of install method
18
+ STATUS=$(npx brain-dev status --json 2>/dev/null)
19
+
20
+ if [ $? -ne 0 ] || [ -z "$STATUS" ]; then
21
+ echo "[brain] Warning: Could not read project state."
22
+ exit 0
23
+ fi
24
+
25
+ # Format output for Claude Code context (target: 500-800 tokens)
26
+ echo "$STATUS" | node -e "
27
+ const fs = require('fs');
28
+ try {
29
+ const raw = fs.readFileSync('/dev/stdin', 'utf8');
30
+ const data = JSON.parse(raw);
31
+ const lines = [
32
+ '--- Brain Context ---',
33
+ 'Project: ' + (data.project && data.project.name || 'unnamed'),
34
+ 'Phase: ' + (data.phase && data.phase.current || 0) + ' (' + (data.phase && data.phase.status || 'initialized') + ')',
35
+ 'Next: ' + (data.nextAction || '/brain:new-project'),
36
+ '',
37
+ 'Commands: /brain:new-project, /brain:discuss, /brain:plan, /brain:execute, /brain:verify, /brain:complete, /brain:quick, /brain:progress, /brain:pause, /brain:resume, /brain:help, /brain:health, /brain:storm, /brain:adr, /brain:phase, /brain:config, /brain:map',
38
+ '',
39
+ 'Instructions for Claude:',
40
+ '- When user types /brain:<command>, run: npx brain-dev <command> [args]',
41
+ '- Read output and present results. Follow any instructions in output.',
42
+ '- Use /brain:progress to check current state before suggesting next steps.',
43
+ '--- End Brain Context ---'
44
+ ];
45
+ console.log(lines.join('\n'));
46
+ } catch(e) {
47
+ console.log('[brain] Ready. Run /brain:progress for status.');
48
+ }
49
+ " 2>/dev/null
50
+
51
+ # Quick health check: auto-repair safe issues silently
52
+ if [ -f "$BRAIN_DIR/brain.json" ]; then
53
+ npx brain-dev health --quick 2>/dev/null
54
+ fi
@@ -0,0 +1,45 @@
1
+ #!/bin/bash
2
+ # hooks/post-tool-use.sh
3
+ # PostToolUse hook for Claude Code - reads bridge file and injects context warnings
4
+ # Does NOT receive context_window data - reads from bridge file written by StatusLine
5
+
6
+ BRAIN_DIR="${CLAUDE_PROJECT_DIR:-.}/.brain"
7
+ BRIDGE="$BRAIN_DIR/.context-bridge.json"
8
+
9
+ # If bridge file doesn't exist, exit silently (normal early in session)
10
+ if [ ! -f "$BRIDGE" ]; then
11
+ exit 0
12
+ fi
13
+
14
+ # Use node -e to read bridge file and check level (no jq dependency)
15
+ node -e "
16
+ const fs = require('fs');
17
+ try {
18
+ const bridge = JSON.parse(fs.readFileSync('$BRIDGE', 'utf8'));
19
+ const level = bridge.level;
20
+ const pct = bridge.context_remaining_pct;
21
+
22
+ if (level === 'critical') {
23
+ const output = {
24
+ hookSpecificOutput: {
25
+ hookEventName: 'PostToolUse',
26
+ additionalContext: '[brain] CRITICAL: Context at ' + pct + '% remaining. Consider running /brain:pause to save state and continue in a fresh session.'
27
+ }
28
+ };
29
+ console.log(JSON.stringify(output));
30
+ } else if (level === 'warning') {
31
+ const output = {
32
+ hookSpecificOutput: {
33
+ hookEventName: 'PostToolUse',
34
+ additionalContext: '[brain] WARNING: Context at ' + pct + '% remaining. Start wrapping up current task.'
35
+ }
36
+ };
37
+ console.log(JSON.stringify(output));
38
+ }
39
+ // normal level: no output needed
40
+ } catch {
41
+ // Bridge file unreadable/corrupt - exit silently
42
+ }
43
+ " 2>/dev/null
44
+
45
+ exit 0
@@ -0,0 +1,130 @@
1
+ #!/bin/bash
2
+ # hooks/statusline.sh
3
+ # StatusLine script for Claude Code - displays brain status with context bar
4
+ # Receives session JSON on stdin with context_window data
5
+ # Writes bridge file for PostToolUse to read
6
+
7
+ BRAIN_DIR="${CLAUDE_PROJECT_DIR:-.}/.brain"
8
+ BRIDGE="$BRAIN_DIR/.context-bridge.json"
9
+ BRIDGE_TMP="$BRIDGE.tmp"
10
+
11
+ # Guard: if brain.json doesn't exist, output minimal status and exit
12
+ if [ ! -f "$BRAIN_DIR/brain.json" ]; then
13
+ echo "brain | not initialized"
14
+ exit 0
15
+ fi
16
+
17
+ # Read stdin
18
+ input=$(cat)
19
+
20
+ # Use node -e to parse data, write bridge file, and output status line
21
+ # No jq dependency - consistent with bootstrap.sh pattern
22
+ node -e "
23
+ const fs = require('fs');
24
+
25
+ const input = (() => {
26
+ try { return JSON.parse(process.argv[1] || '{}'); }
27
+ catch { return {}; }
28
+ })();
29
+
30
+ // Extract context window data
31
+ const cw = input.context_window || {};
32
+ const usedPct = cw.used_percentage;
33
+ const remainPct = cw.remaining_percentage;
34
+
35
+ // Read brain.json for project name and thresholds
36
+ let projectName = 'brain';
37
+ let warningThreshold = 35;
38
+ let criticalThreshold = 25;
39
+ let phaseCurrent = '';
40
+ let phaseStatus = '';
41
+
42
+ try {
43
+ const brain = JSON.parse(fs.readFileSync('$BRAIN_DIR/brain.json', 'utf8'));
44
+ projectName = (brain.project && brain.project.name) || 'brain';
45
+ if (brain.monitoring) {
46
+ warningThreshold = brain.monitoring.warning_threshold || 35;
47
+ criticalThreshold = brain.monitoring.critical_threshold || 25;
48
+ }
49
+ if (brain.phase) {
50
+ phaseCurrent = brain.phase.current || '';
51
+ phaseStatus = brain.phase.status || '';
52
+ }
53
+ } catch {}
54
+
55
+ // Determine level
56
+ let level = 'normal';
57
+ let remainInt = null;
58
+ let message = '';
59
+ let suggestion = '';
60
+ let autoPause = false;
61
+
62
+ if (remainPct != null && !isNaN(remainPct)) {
63
+ remainInt = Math.round(remainPct);
64
+ if (remainInt <= criticalThreshold) {
65
+ level = 'critical';
66
+ message = 'Context at ' + remainInt + '% remaining - CRITICAL';
67
+ suggestion = 'Run /brain:pause to save state and continue in a fresh session';
68
+ autoPause = true;
69
+ } else if (remainInt <= warningThreshold) {
70
+ level = 'warning';
71
+ message = 'Context at ' + remainInt + '% remaining';
72
+ suggestion = 'Start wrapping up current task';
73
+ } else {
74
+ message = 'Context at ' + remainInt + '% remaining';
75
+ suggestion = '';
76
+ }
77
+ }
78
+
79
+ // Write bridge file atomically (tmp then rename)
80
+ if (remainInt !== null) {
81
+ const bridge = JSON.stringify({
82
+ context_remaining_pct: remainInt,
83
+ level: level,
84
+ message: message,
85
+ suggestion: suggestion,
86
+ auto_pause_suggested: autoPause,
87
+ last_updated: new Date().toISOString()
88
+ }, null, 2);
89
+ try {
90
+ fs.writeFileSync('$BRIDGE_TMP', bridge, 'utf8');
91
+ fs.renameSync('$BRIDGE_TMP', '$BRIDGE');
92
+ } catch {}
93
+ }
94
+
95
+ // Build status bar
96
+ let usedInt = usedPct != null ? Math.round(usedPct) : null;
97
+ let bar = '[----------] ---%';
98
+
99
+ if (usedInt !== null && remainInt !== null) {
100
+ const barLen = 10;
101
+ const filled = Math.round((usedInt / 100) * barLen);
102
+ const empty = barLen - filled;
103
+ const barStr = '#'.repeat(filled) + '-'.repeat(empty);
104
+
105
+ // ANSI colors based on remaining percentage
106
+ let colorStart = '';
107
+ let colorEnd = '\x1b[0m';
108
+
109
+ if (remainInt <= criticalThreshold) {
110
+ colorStart = '\x1b[5;31m'; // blinking red
111
+ } else if (remainInt < 35) {
112
+ colorStart = '\x1b[31m'; // red
113
+ } else if (remainInt <= 50) {
114
+ colorStart = '\x1b[33m'; // yellow
115
+ } else {
116
+ colorStart = '\x1b[32m'; // green
117
+ }
118
+
119
+ bar = colorStart + '[' + barStr + '] ' + usedInt + '%' + colorEnd;
120
+ }
121
+
122
+ // Phase display
123
+ let phaseDisplay = '';
124
+ if (phaseCurrent) {
125
+ phaseDisplay = ' | P' + phaseCurrent + (phaseStatus ? ': ' + phaseStatus : '');
126
+ }
127
+
128
+ // Output status line to stdout
129
+ process.stdout.write(projectName + phaseDisplay + ' | ' + bar);
130
+ " "$input" 2>/dev/null || echo "brain | ---"