dual-brain 6.0.0 → 6.0.1

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.
package/CLAUDE.md CHANGED
@@ -2,38 +2,49 @@
2
2
 
3
3
  This project uses dual-provider orchestration. Config: `.claude/orchestrator.json`.
4
4
 
5
- ## Tier Routing
5
+ ## Core Architecture (v6)
6
6
 
7
- Route subagents by task complexity:
7
+ Four modules in `src/` form the decision pipeline:
8
8
 
9
- - **Search** (`model: "haiku"`): Read-only lookups, grep, explore. Return: files found, line refs, confidence.
10
- - **Execute** (`model: "sonnet"`): Edits, tests, git ops. Return: files changed, tests run, edge cases.
11
- - **Think** (main session, Opus): Architecture, review, planning. Return: decision, alternatives, risks.
9
+ - **`profile.mjs`** Load active profile, provider availability, preferences, and subscription plan
10
+ - **`detect.mjs`** Classify task intent, risk, complexity, and tier from prompt + file paths
11
+ - **`decide.mjs`** Route to provider/model/tier; handles budget pressure and dual-brain threshold
12
+ - **`dispatch.mjs`** — Execute the decision: Claude subagent, GPT via Codex, or dual-brain flow
13
+
14
+ The hooks layer (`/home/runner/workspace/.claude/hooks/`) wraps these modules for Claude Code integration and is still valid.
15
+
16
+ ## CLI Commands
12
17
 
13
- ## GPT Lane
18
+ ```bash
19
+ dual-brain init # First-time setup
20
+ dual-brain go "task description" # Detect → decide → dispatch
21
+ dual-brain go --dry-run "..." # Show routing without executing
22
+ dual-brain go --files a.mjs,b.mjs "..." # Provide file context for risk classification
23
+ dual-brain status # Provider health, budget pressure, models
24
+ dual-brain remember "preference" # Save project-scoped preference
25
+ dual-brain forget "preference" # Remove preference by fuzzy match
26
+ ```
14
27
 
15
- For isolated or parallel work, dispatch to GPT via Codex CLI:
28
+ ## Tier Routing
16
29
 
17
- - `node .claude/hooks/gpt-work-dispatcher.mjs --task "..." --model gpt-5.4` execution tasks
30
+ - **Search** (`haiku`): Read-only lookups, grep, explore. Return: files found, line refs, confidence.
31
+ - **Execute** (`sonnet`): Edits, tests, git ops. Return: files changed, tests run, edge cases.
32
+ - **Think** (main session, Opus): Architecture, review, planning. Return: decision, alternatives, risks.
18
33
 
19
34
  ## Dual-Brain Collaboration
20
35
 
21
36
  Dual-brain is a multi-round conversation between Claude and GPT — not a single-shot dispatch.
22
37
 
23
38
  **Think flow** (architecture decisions):
24
- 1. Round 1: `node .claude/hooks/dual-brain-think.mjs --question "..."`
25
- → GPT gives independent analysis
39
+ 1. Round 1: `node .claude/hooks/dual-brain-think.mjs --question "..."` → GPT gives independent analysis
26
40
  2. You analyze the same question independently
27
- 3. Round 2: `node .claude/hooks/dual-brain-think.mjs --question "..." --round 2 --claude-says "<your analysis>"`
28
- → GPT responds to your points: agreements, pushback, refined recommendation
41
+ 3. Round 2: `node .claude/hooks/dual-brain-think.mjs --question "..." --round 2 --claude-says "<your analysis>"` → GPT responds with agreements, pushback, refined recommendation
29
42
  4. You synthesize both rounds into a final decision
30
43
 
31
44
  **Review flow** (code review):
32
- 1. Round 1: `node .claude/hooks/dual-brain-review.mjs`
33
- → GPT reviews the diff independently
45
+ 1. Round 1: `node .claude/hooks/dual-brain-review.mjs` → GPT reviews the diff independently
34
46
  2. You review the same diff independently
35
- 3. Round 2: `node .claude/hooks/dual-brain-review.mjs --round 2 --claude-review "<your findings>"`
36
- → GPT confirms shared findings, acknowledges misses, disputes false positives
47
+ 3. Round 2: `node .claude/hooks/dual-brain-review.mjs --round 2 --claude-review "<your findings>"` → GPT confirms shared findings, acknowledges misses
37
48
  4. You synthesize into a final review verdict
38
49
 
39
50
  ## Routing Rules
@@ -47,20 +58,15 @@ Dual-brain is a multi-round conversation between Claude and GPT — not a single
47
58
 
48
59
  **Claude MUST follow these rules before implementing multi-file changes:**
49
60
 
50
- 1. **Before starting any batch of 3+ file edits**: run `node .claude/hooks/budget-balancer.mjs` and `node .claude/hooks/vibe-router.mjs "description"` to check provider balance and classify tasks
51
- 2. **When budget-balancer recommends GPT**: dispatch execution work via `node .claude/hooks/gpt-work-dispatcher.mjs --task "..." --tier execute`
61
+ 1. **Before starting any batch of 3+ file edits**: run `node .claude/hooks/budget-balancer.mjs` to check provider balance, then `dual-brain go --dry-run "description"` to classify tasks
62
+ 2. **When budget-balancer recommends GPT**: dispatch via `src/dispatch.mjs` (or `node .claude/hooks/gpt-work-dispatcher.mjs --task "..." --tier execute`)
52
63
  3. **Security/auth/credential changes**: always require dual-brain think flow before implementation
53
64
  4. **Audit remediation batches**: plan waves with dual-brain think, dispatch execution to GPT, Claude reviews
54
65
  5. **Claude's role in multi-task work**: define acceptance criteria, dispatch agents, review results — not solo-implement everything
55
66
 
56
- **Triggers that require this workflow:**
57
- - 3+ production files being edited in one session
58
- - Any change touching auth, credentials, tokens, or secrets
59
- - Any change to dispatcher, agent routing, or tier logic
60
- - Audit or review remediation involving multiple subsystems
61
- - When Claude's think capacity is above 60% per budget-balancer
67
+ **Triggers that require this workflow:** 3+ production files edited in one session · auth/credentials/tokens/secrets · changes to dispatcher, agent routing, or tier logic · audit remediation across multiple subsystems · Claude think capacity above 60% per budget-balancer.
62
68
 
63
- **Failure to route is itself a bug.** If Claude implements a large batch solo when GPT has capacity, the user should treat this as a process failure and correct it.
69
+ **Failure to route is itself a bug.**
64
70
 
65
71
  ## Quality Gate
66
72
 
@@ -72,91 +78,60 @@ Gate statuses: `pass` (safe to end), `issues_found` (fix first), `needs_human_re
72
78
 
73
79
  ## Profiles
74
80
 
75
- Active profile controls routing posture, budgets, and quality gate behavior.
76
81
  Profile persists to `.claude/dual-brain.profile.json` (gitignored).
77
82
 
78
- - **auto** (default): Adapts routing based on task risk, provider health, and outcomes. Uses file-path risk classification and failure-loop detection to auto-escalate when needed.
83
+ - **auto** (default): Adapts routing based on task risk, provider health, and outcomes
79
84
  - **balanced**: Best model per tier, normal budgets, reviews at medium+ risk
80
85
  - **cost-saver**: Prefer cheaper models, lower budgets, skip GPT for non-critical
81
86
  - **quality-first**: Dual-brain for medium+ risk, higher budgets, stricter reviews
82
87
 
83
- Switch profiles: `npx dual-brain mode cost-saver`
84
- Check status: `npx dual-brain status`
85
-
86
- Natural language aliases work everywhere: "go aggressive", "be careful", "cheap mode", "fast", "thorough", "smart". The system strips prefixes like "go"/"be"/"use" and resolves to the canonical profile name.
88
+ Switch: `dual-brain mode cost-saver` · Natural language aliases work: "be careful", "cheap mode", "thorough"
87
89
 
88
90
  ## Adaptive Routing (Auto Mode)
89
91
 
90
- Auto mode classifies risk from file paths and adjusts routing in real-time:
91
-
92
92
  - **Risk classification**: auth/secrets→critical, billing/migrations→high, tests/utils→medium, docs→low
93
- - **Failure detection**: 2+ failures on same prompt in 2 hours → auto-escalate tier or trigger dual-brain. Uses time-weighted decay (recent failures count more) and ledger pruning for entries >24hrs.
93
+ - **Failure detection**: 2+ failures on same prompt in 2 hours → auto-escalate tier or trigger dual-brain
94
94
  - **Provider balance**: Routes to underused provider when one subscription is hot
95
- - **Burst awareness**: Suppresses duplicate warnings and balance hints during agent waves (3+ agents in 90s)
95
+ - **Burst awareness**: Suppresses duplicate warnings during agent waves (3+ agents in 90s)
96
96
 
97
- ## Vibe Coding
97
+ ## Budget Balancer
98
98
 
99
- Casual natural language → structured work. The vibe coding system translates informal requests into properly routed, risk-classified, quality-gated work.
99
+ `src/decide.mjs` handles routing decisions using the same token data internally. For inspection:
100
100
 
101
- **Wave Orchestrator** — the primary way to run multi-step work:
102
101
  ```bash
103
- node .claude/hooks/wave-orchestrator.mjs "fix the login bug and update the nav"
104
- node .claude/hooks/wave-orchestrator.mjs --dry-run "refactor auth module"
105
- node .claude/hooks/wave-orchestrator.mjs --resume <manifestId>
106
- node .claude/hooks/wave-orchestrator.mjs --show <manifestId>
107
- ```
108
- The wave orchestrator decomposes intent, plans dependency-aware waves, assigns file ownership to prevent conflicts, dispatches agents with transparent routing tables, checkpoints between waves, and supports resume on failure. Every dispatch shows: provider, model, tier, effort, agent type, and routing reason.
109
-
110
- Manifests persist to `.dualbrain/manifests/`, checkpoints to `.dualbrain/checkpoints/`.
111
-
112
- Also available via the control panel: `[w]` Vibe workflow.
113
-
114
- **Intent compiler** — decompose multi-task requests:
115
- ```bash
116
- node .claude/hooks/vibe-router.mjs "fix the login bug and also update the nav"
117
- ```
118
- Returns structured tasks with tier/risk classification, complexity level, quality gates, and wave strategy.
119
-
120
- **Plan generator** — Steve-style 3-part markdown plans:
121
- ```bash
122
- node .claude/hooks/plan-generator.mjs --utterance "..." [--write]
123
- ```
124
- Generates: (1) dependency-ordered task table, (2) user stories + edge cases, (3) questions with suggested answers. Pass `--write` to save to `.claude/plans/`.
125
-
126
- **Durable memory** — preferences persist across sessions:
127
- ```bash
128
- node .claude/hooks/vibe-memory.mjs # show state
129
- node .claude/hooks/vibe-memory.mjs --set preferences.risk_tolerance=careful
130
- node .claude/hooks/vibe-memory.mjs --threads # active work
131
- node .claude/hooks/vibe-memory.mjs --infer # preference suggestions
102
+ node .claude/hooks/budget-balancer.mjs
132
103
  ```
133
- Tracks preferred profile, risk tolerance, active threads, and learns from usage patterns.
134
-
135
- ## Budget Balancer (Token-Based)
136
104
 
137
- The budget balancer tracks real token usage against actual subscription limits.
105
+ Tracks 5-hour and 7-day rolling windows against subscription limits (Claude Pro/Max, ChatGPT Plus/Pro). The higher pressure window is the binding constraint. Uses actual `input_tokens + output_tokens` from usage logs.
138
106
 
139
107
  **Subscription tiers** (configured in `orchestrator.json` → `subscriptions.*.plan`):
140
108
  - Claude: Pro $20, Max x5 $100, Max x20 $200
141
109
  - ChatGPT: Plus $20, Pro $100, Pro $200
142
110
 
143
- **Two rolling windows**: 5-hour and 7-day weekly. The higher pressure is the binding constraint.
111
+ ## Multi-Step Work
144
112
 
145
- **Token tracking**: Uses actual `input_tokens + output_tokens` from usage logs when available, falls back to conservative estimates only when logs lack token data.
113
+ The wave orchestrator is available for complex multi-step tasks:
146
114
 
147
115
  ```bash
148
- node .claude/hooks/budget-balancer.mjs
116
+ node .claude/hooks/wave-orchestrator.mjs "fix the login bug and update the nav"
117
+ node .claude/hooks/wave-orchestrator.mjs --dry-run "refactor auth module"
118
+ node .claude/hooks/wave-orchestrator.mjs --resume <manifestId>
149
119
  ```
150
- Shows per-provider per-tier pressure with real token counts (e.g., `136.0K/350.0K`), weekly pressure when binding, and routing recommendation with reason.
120
+
121
+ For most tasks, prefer `dual-brain go "..."` — it runs the same detect→decide→dispatch pipeline with less overhead.
151
122
 
152
123
  ## Available Tools
153
124
 
154
- - `node .claude/hooks/wave-orchestrator.mjs "..."` — auto-wave orchestrator (plan, dispatch, test, review)
155
- - `node .claude/hooks/vibe-router.mjs "..."` — decompose casual requests into structured work
156
- - `node .claude/hooks/plan-generator.mjs --utterance "..."` generate execution plans
157
- - `node .claude/hooks/vibe-memory.mjs` persistent preferences and work threads
158
- - `node .claude/hooks/cost-report.mjs` activity and cost estimates
159
- - `node .claude/hooks/health-check.mjs` verify system health
160
- - `node .claude/hooks/budget-balancer.mjs` provider balance (token-based, real limits)
161
- - `node .claude/hooks/decision-ledger.mjs` routing outcome insights
162
- - `node .claude/hooks/test-orchestrator.mjs` run self-tests (40 tests)
125
+ | Tool | Purpose |
126
+ |------|---------|
127
+ | `dual-brain go "..."` | Primary entry point: detect, decide, dispatch |
128
+ | `dual-brain status` | Provider health, budget, models |
129
+ | `node .claude/hooks/budget-balancer.mjs` | Token usage and routing recommendation |
130
+ | `node .claude/hooks/dual-brain-think.mjs` | Multi-round architecture decisions with GPT |
131
+ | `node .claude/hooks/dual-brain-review.mjs` | Multi-round code review with GPT |
132
+ | `node .claude/hooks/wave-orchestrator.mjs "..."` | Dependency-aware multi-wave dispatch |
133
+ | `node .claude/hooks/session-report.mjs` | End-of-session summary |
134
+ | `node .claude/hooks/quality-gate.mjs` | Gate check before ending session |
135
+ | `node .claude/hooks/health-check.mjs` | System health |
136
+ | `node .claude/hooks/test-orchestrator.mjs` | Self-tests (40 tests) |
137
+ | `node .claude/hooks/vibe-memory.mjs` | Persistent preferences across sessions |
package/README.md CHANGED
@@ -1,133 +1,197 @@
1
- # Dual-Brain Orchestrator
1
+ # dual-brain
2
2
 
3
- One command. Both brains. Auto-detected. Auto-configured. Default profile: **auto**.
3
+ AI orchestration across Claude + OpenAI subscriptions smart routing, budget awareness, and dual-brain collaboration.
4
4
 
5
- Dual-provider orchestration for Claude Code across Claude and OpenAI subscriptions. Routes search to cheap models, execution to mid-tier, thinking to the most capable. Dispatches work to GPT via Codex CLI. Dual-brain analysis for high-risk decisions.
6
-
7
- ## Install
5
+ ## Quick Start
8
6
 
9
7
  ```bash
10
- npx -y dual-brain
8
+ npm install -g dual-brain
9
+ dual-brain init
10
+ dual-brain go "fix the login bug"
11
11
  ```
12
12
 
13
- That's it. The installer auto-detects your environment:
14
- - Finds Claude CLI and checks auth status
15
- - Finds Codex CLI and checks auth status
16
- - Detects Replit and replit-tools if present
17
- - Configures dual-provider, Claude-only, or OpenAI-only mode automatically
18
- - Registers hooks in `.claude/settings.json`
19
- - No wizard. No restart. No manual steps.
13
+ ## How It Works
20
14
 
21
- Run it again anytime it's idempotent. Re-detects providers, updates hooks, preserves your config.
15
+ dual-brain detects the intent and risk of your task, picks the best model based on your subscriptions and current budget pressure, and dispatches to Claude or OpenAI. For high-risk decisions (auth, architecture, critical changes), it runs both providers in parallel and surfaces a consensus. It learns from usage patterns to improve routing over time.
22
16
 
23
- ### Unlock full features
17
+ **Pipeline:** `detect` `decide` → `dispatch`
24
18
 
25
- ```bash
26
- # Claude (you probably have this already)
27
- claude login
19
+ - **detect** — classifies intent (edit, refactor, debug, search, architecture…), risk (low/medium/high/critical), complexity, and effort from the task prompt and file paths
20
+ - **decide** picks provider, model, and effort level based on your subscription plan, current budget pressure, and routing bias
21
+ - **dispatch** — runs the agent via `claude` CLI or `codex` CLI, records token usage, returns a structured result
28
22
 
29
- # OpenAI (optional — enables GPT lane + dual-brain)
30
- npm i -g @openai/codex
31
- codex login
23
+ ## Commands
24
+
25
+ ### `dual-brain init`
26
+
27
+ First-time setup. Three questions: which providers you have, subscription tiers, and optimization preference.
32
28
 
33
- # Re-run to detect new providers
34
- npx -y dual-brain
35
29
  ```
30
+ Dual-Brain Orchestrator — First-time setup
36
31
 
37
- ## How it works
32
+ Which AI subscriptions do you have?
33
+ (1) Claude only (2) OpenAI only (3) Both
34
+ > 3
38
35
 
39
- **Two advisory hooks** are registered in `.claude/settings.json` and fire on each tool use. They detect and recommend — they do not execute actions without user confirmation:
36
+ Claude tier?
37
+ (1) $20/mo (2) $100/mo (3) $200/mo
38
+ > 2
40
39
 
41
- - **enforce-tier.mjs** (PreToolUse on Agent): Classifies tasks, recommends the correct model tier, detects duplicates, suggests cross-provider routing
42
- - **cost-logger.mjs** (PostToolUse on all tools): Logs usage to daily rotated files for cost tracking
40
+ Default optimization?
41
+ (1) Save usage (2) Balanced (3) Best quality
42
+ > 2
43
43
 
44
- **Three tiers route work by complexity:**
44
+ Profile saved. Providers: Claude ($100), OpenAI ($20). Mode: dual. Runtime: claude-code
45
+ ```
45
46
 
46
- | Tier | Claude | OpenAI | Use for |
47
- |------|--------|--------|---------|
48
- | Search | Haiku | GPT-4.1-mini | grep, explore, file reads |
49
- | Execute | Sonnet | GPT-5.4 | edits, tests, git ops |
50
- | Think | Opus | GPT-5.5 | architecture, review, planning |
47
+ Profile is written to `.dualbrain/profile.json` in your project (or `~/.config/dual-brain/profile.json` globally).
51
48
 
52
- **Dual-brain** is recommended automatically for high-risk decisions — hooks detect the risk level and suggest dual-brain analysis, where both providers think on the same problem independently.
49
+ ### `dual-brain go "task"`
53
50
 
54
- ## Vibe Coding
51
+ Detects, decides, and dispatches in one command.
55
52
 
56
- Speak naturally. The orchestrator handles the structure.
53
+ ```
54
+ $ dual-brain go "refactor the auth middleware to use JWT" --files src/middleware/auth.js
57
55
 
58
- ```bash
59
- # Decompose a casual request into structured work
60
- node .claude/hooks/vibe-router.mjs "fix the login bug and also update the nav"
56
+ Moderate critical-risk security touching 1 file.
57
+ provider : claude
58
+ model : opus (high)
59
+ tier : think
60
+ dual-brain : yes
61
+ reason : Using opus high with dual-brain review because this security change is critical risk.
62
+
63
+ Dispatching...
64
+
65
+ Consensus: both-passed
66
+ Claude : Refactored auth.js to validate JWT using jsonwebtoken...
67
+ OpenAI : Updated middleware to verify tokens with proper expiry...
68
+ ```
69
+
70
+ **Options:**
71
+
72
+ ```
73
+ dual-brain go "task" --dry-run # show routing decision, don't execute
74
+ dual-brain go "task" --files a.mjs,b.mjs # add file context for risk classification
75
+ ```
76
+
77
+ ### `dual-brain status`
78
+
79
+ Shows provider health, budget pressure, available models, and active preferences.
80
+
81
+ ```
82
+ $ dual-brain status
83
+
84
+ === Dual-Brain Status ===
61
85
 
62
- # Generate a Steve-style execution plan
63
- node .claude/hooks/plan-generator.mjs --utterance "refactor the auth flow" --write
86
+ Providers:
87
+ Claude plan=$100 budget=23% used
88
+ OpenAI plan=$20 budget=5% used
64
89
 
65
- # Switch profiles with natural language
66
- npx dual-brain mode "go aggressive"
67
- npx dual-brain mode "be careful"
68
- npx dual-brain mode "cheap"
90
+ Available models:
91
+ Claude : haiku, sonnet, opus
92
+ OpenAI : gpt-4.1-mini, gpt-4.1, gpt-5.2, gpt-5.4-mini, gpt-5.3-codex, gpt-5.4, gpt-5.5
69
93
 
70
- # Check persistent preferences and work threads
71
- node .claude/hooks/vibe-memory.mjs --threads
94
+ Head model : sonnet
95
+ Mode : dual
96
+ Solo brain : no
97
+
98
+ Runtime:
99
+ claude CLI : available
100
+ codex CLI : available
101
+ detected : claude-code
102
+
103
+ Preferences: (none)
72
104
  ```
73
105
 
74
- The vibe-router splits multi-task requests, classifies risk, assigns tiers, and recommends quality gates. The plan-generator produces 3-part plans (dependency-ordered tasks, user stories, questions with suggested answers). Vibe-memory learns your preferences over time.
75
-
76
- ## Scripts
77
-
78
- | Script | Purpose |
79
- |--------|---------|
80
- | `hooks/vibe-router.mjs` | Decompose casual language into structured work orders |
81
- | `hooks/plan-generator.mjs` | Generate Steve-style 3-part execution plans |
82
- | `hooks/vibe-memory.mjs` | Persistent preferences, work threads, preference inference |
83
- | `hooks/cost-report.mjs` | Activity & cost estimates by model tier |
84
- | `hooks/dual-brain-review.mjs` | Send git diff to GPT for independent review |
85
- | `hooks/dual-brain-think.mjs` | Dual-perspective analysis on architecture decisions |
86
- | `hooks/quality-gate.mjs` | Sensitivity-scored quality gate with review artifacts |
87
- | `hooks/budget-balancer.mjs` | Provider balance and routing recommendations |
88
- | `hooks/gpt-work-dispatcher.mjs` | Dispatch execution tasks to GPT via Codex CLI |
89
- | `hooks/session-report.mjs` | Session-end summary: activity, compliance, quality |
90
- | `hooks/health-check.mjs` | Verify all hooks and dependencies are working |
91
- | `hooks/test-orchestrator.mjs` | Self-test harness (40 tests) |
92
- | `hooks/setup-wizard.mjs` | Interactive config (optional — for custom plans) |
93
- | `hooks/install-git-hooks.mjs` | Git pre-commit hook for quality gate |
94
-
95
- ## CLI options
106
+ ### `dual-brain remember "preference"`
107
+
108
+ Saves a project-scoped preference that influences routing decisions.
96
109
 
97
110
  ```bash
98
- npx -y dual-brain # detect, configure, install
99
- npx dual-brain --force # overwrite all config
100
- npx dual-brain --dry-run # detect only, don't write
101
- npx dual-brain --json # output detection as JSON
102
- npx dual-brain --help # show help
111
+ dual-brain remember "always use opus for security tasks"
112
+ dual-brain remember "prefer cost-saver mode this sprint"
113
+ dual-brain forget "cost-saver"
114
+ ```
115
+
116
+ Preferences are stored in `.dualbrain/profile.json` and applied on every `go` invocation.
117
+
118
+ ## Programmatic API
119
+
120
+ ```js
121
+ import { orchestrate } from 'dual-brain';
122
+
123
+ const result = await orchestrate({ prompt: "fix the bug", cwd: "." });
124
+ console.log(result.summary);
125
+ ```
126
+
127
+ Individual modules are also exported:
128
+
129
+ ```js
130
+ import { detectTask } from 'dual-brain/detect';
131
+ import { decideRoute } from 'dual-brain/decide';
132
+ import { dispatch } from 'dual-brain/dispatch';
133
+ import { loadProfile } from 'dual-brain/profile';
134
+
135
+ const profile = loadProfile(process.cwd());
136
+ const detection = detectTask({ prompt: "refactor auth", files: ["src/auth.js"] });
137
+ const decision = decideRoute({ profile, detection });
138
+ const result = await dispatch({ decision, prompt: "refactor auth" });
103
139
  ```
104
140
 
105
- ## Customize
141
+ ## Configuration
142
+
143
+ Profile shape (`~/.config/dual-brain/profile.json` or `.dualbrain/profile.json`):
144
+
145
+ ```json
146
+ {
147
+ "schemaVersion": 1,
148
+ "providers": {
149
+ "claude": { "plan": "$100", "enabled": true },
150
+ "openai": { "plan": "$20", "enabled": true }
151
+ },
152
+ "mode": "dual",
153
+ "bias": "balanced",
154
+ "preferences": []
155
+ }
156
+ ```
157
+
158
+ **`mode`** is set automatically: `dual` (both providers), `solo-claude`, or `solo-openai`.
159
+
160
+ **`bias`** controls routing posture:
161
+ - `balanced` — best model per task, normal budgets (default)
162
+ - `cost-saver` — cheapest available model, skip GPT for non-critical work
163
+ - `quality-first` — strongest model per task, dual-brain for medium+ risk
106
164
 
107
- After install, edit these files:
165
+ Token usage is tracked in `.dualbrain/usage/` (daily JSONL files). Budget pressure is computed from real token counts against your subscription limits and influences model downgrade decisions automatically.
108
166
 
109
- - `orchestrator.json` subscriptions, tiers, quality gate, budgets, routing
110
- - `review-rules.md` — project-specific rules for GPT code review
111
- - `settings.json` — hook registrations (auto-generated, safe to extend)
167
+ ## Solo vs Dual Brain
112
168
 
113
- ## Profiles
169
+ dual-brain works with just Claude, just OpenAI, or both. There is no degraded experience in solo mode — routing, budget tracking, and preferences all work the same way. Dual-brain analysis (parallel dispatch to both providers) activates only when both are configured and the task qualifies (critical risk, architecture, or security intent).
114
170
 
115
- The active profile controls routing posture, budgets, and quality gate behavior. Default: **auto**.
171
+ ## Claude Code Integration
172
+
173
+ For Claude Code users, a hooks layer provides deeper integration. Hooks fire on each tool use to enforce tier routing, log usage, and surface routing recommendations inline.
116
174
 
117
175
  ```bash
118
- npx dual-brain mode cost-saver # switch profile
119
- npx dual-brain status # check current profile and provider health
176
+ # Install hooks into .claude/settings.json
177
+ npx -y dual-brain
120
178
  ```
121
179
 
122
- - **auto** (default): Adapts routing based on task risk, provider health, and outcomes. Auto-escalates tier on repeated failures.
123
- - **balanced**: Best model per tier, normal budgets, reviews at medium+ risk.
124
- - **cost-saver**: Prefer cheaper models, lower budgets, skip GPT for non-critical work.
125
- - **quality-first**: Dual-brain for medium+ risk, higher budgets, stricter reviews.
180
+ The installer auto-detects your environment (Claude CLI, Codex CLI, Replit), registers `enforce-tier.mjs` and `cost-logger.mjs` hooks, and writes `orchestrator.json` with your subscription config. Re-run anytime it's idempotent.
181
+
182
+ See `.claude/hooks/` for the full hooks library: wave orchestrator, vibe router, budget balancer, dual-brain review, quality gate, and more.
126
183
 
127
184
  ## Requirements
128
185
 
129
- - Node 20+
130
- - Claude Code (any subscription tier)
131
- - Codex CLI (optional) `npm i -g @openai/codex && codex login`
186
+ - Node.js >= 20
187
+ - `claude` CLI and/or `codex` CLI
188
+ - Active subscription: Claude Pro/Max ($20–$200) or ChatGPT Plus/Pro ($20–$200)
132
189
 
133
- Works with any subscription combination. Without OpenAI, GPT features gracefully degrade — all work routes through Claude.
190
+ ```bash
191
+ # Claude CLI
192
+ claude login
193
+
194
+ # Codex CLI (optional — enables OpenAI lane + dual-brain)
195
+ npm i -g @openai/codex
196
+ codex login
197
+ ```
@@ -37,6 +37,7 @@ dual-brain <command> [options]
37
37
 
38
38
  Commands:
39
39
  init First-time setup (providers, plans, optimization)
40
+ install Install Claude Code hooks into the current project
40
41
  go "task description" Detect → decide → dispatch a task
41
42
  --dry-run Show routing decision without executing
42
43
  --files a.mjs,b.mjs Provide file context for risk classification
@@ -163,6 +164,12 @@ async function cmdStatus() {
163
164
  } catch { /* network unavailable — skip */ }
164
165
  }
165
166
 
167
+ async function cmdInstall() {
168
+ const { spawnSync } = await import('child_process');
169
+ const result = spawnSync('node', [join(__dirname, '..', 'install.mjs')], { stdio: 'inherit', cwd: process.cwd() });
170
+ process.exit(result.status || 0);
171
+ }
172
+
166
173
  function cmdRemember(text) {
167
174
  if (!text) err('Usage: dual-brain remember "preference text"');
168
175
  const profile = rememberPreference(text, { scope: 'project', cwd: process.cwd() });
@@ -185,6 +192,7 @@ async function main() {
185
192
  if (cmd === '--version' || cmd === '-v') { console.log(readVersion()); return; }
186
193
 
187
194
  if (cmd === 'init') { await cmdInit(); return; }
195
+ if (cmd === 'install') { await cmdInstall(); return; }
188
196
  if (cmd === 'go') { await cmdGo(args.slice(1)); return; }
189
197
  if (cmd === 'status') { await cmdStatus(); return; }
190
198
  if (cmd === 'remember') { cmdRemember(args[1]); return; }
@@ -0,0 +1,102 @@
1
+ #!/usr/bin/env node
2
+ // auto-update-wrapper.mjs — PostToolUse hook (Node.js entry point).
3
+ // Runs once per session, checks for dual-brain updates, installs silently.
4
+ // The parent exits immediately; all npm work happens in a detached child.
5
+
6
+ import { spawn } from 'child_process';
7
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
8
+ import { join, dirname, resolve } from 'path';
9
+ import { fileURLToPath } from 'url';
10
+
11
+ const __dirname = dirname(fileURLToPath(import.meta.url));
12
+ const WORKSPACE = resolve(__dirname, '..');
13
+ const STATE_DIR = join(WORKSPACE, '.dualbrain');
14
+ const LOCK_FILE = join(STATE_DIR, '.update-checked');
15
+ const TWENTY_FOUR_HOURS = 24 * 60 * 60 * 1000;
16
+
17
+ // ── 1. Already checked recently? ─────────────────────────────────────────────
18
+ if (existsSync(LOCK_FILE)) {
19
+ try {
20
+ const lastCheck = parseInt(readFileSync(LOCK_FILE, 'utf8').trim(), 10);
21
+ if (Number.isFinite(lastCheck) && Date.now() - lastCheck < TWENTY_FOUR_HOURS) {
22
+ process.exit(0);
23
+ }
24
+ } catch {
25
+ // Corrupt lock file — proceed with check
26
+ }
27
+ }
28
+
29
+ // ── 2. Write lock BEFORE spawning (prevents concurrent session races) ─────────
30
+ try {
31
+ mkdirSync(STATE_DIR, { recursive: true });
32
+ writeFileSync(LOCK_FILE, String(Date.now()));
33
+ } catch {
34
+ process.exit(0); // Can't write state — bail silently
35
+ }
36
+
37
+ // ── 3. Resolve local version ─────────────────────────────────────────────────
38
+ let localVersion = '';
39
+ try {
40
+ const pkg = JSON.parse(readFileSync(join(WORKSPACE, 'package.json'), 'utf8'));
41
+ localVersion = pkg.version || '';
42
+ } catch {
43
+ process.exit(0);
44
+ }
45
+
46
+ if (!localVersion) process.exit(0);
47
+
48
+ // ── 4. Detach background worker — parent returns immediately ─────────────────
49
+ // The worker script is inlined as a node -e string to avoid needing a temp file.
50
+ const workerScript = `
51
+ import { spawnSync } from 'child_process';
52
+ import { readFileSync } from 'fs';
53
+
54
+ const localVersion = ${JSON.stringify(localVersion)};
55
+
56
+ // 3-second timeout npm check
57
+ const npmResult = spawnSync('npm', ['view', 'dual-brain', 'version'], {
58
+ encoding: 'utf8',
59
+ stdio: ['pipe', 'pipe', 'pipe'],
60
+ timeout: 3000,
61
+ });
62
+
63
+ const latestVersion = (npmResult.stdout || '').trim();
64
+ if (!latestVersion) process.exit(0);
65
+
66
+ // Compare: is latest strictly greater than local?
67
+ function versionGt(a, b) {
68
+ const ap = a.replace(/^v/i, '').split('.').map(n => parseInt(n, 10) || 0);
69
+ const bp = b.replace(/^v/i, '').split('.').map(n => parseInt(n, 10) || 0);
70
+ const len = Math.max(ap.length, bp.length);
71
+ for (let i = 0; i < len; i++) {
72
+ const diff = (bp[i] || 0) - (ap[i] || 0);
73
+ if (diff !== 0) return diff > 0;
74
+ }
75
+ return false;
76
+ }
77
+
78
+ if (!versionGt(localVersion, latestVersion)) process.exit(0);
79
+
80
+ // Newer version found — print notice then install
81
+ process.stderr.write('dual-brain: updating v' + localVersion + ' → ' + latestVersion + '...\\n');
82
+
83
+ spawnSync('npx', ['-y', 'dual-brain@latest', '--quiet'], {
84
+ stdio: 'ignore',
85
+ timeout: 120000,
86
+ });
87
+ `;
88
+
89
+ const child = spawn(
90
+ process.execPath,
91
+ ['--input-type=module'],
92
+ {
93
+ detached: true,
94
+ stdio: ['pipe', 'ignore', 'ignore'],
95
+ }
96
+ );
97
+
98
+ child.stdin.write(workerScript);
99
+ child.stdin.end();
100
+ child.unref(); // Let parent exit without waiting
101
+
102
+ process.exit(0);