continuous-improvement 1.0.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.
@@ -0,0 +1,1666 @@
1
+ # Mulahazah Implementation Plan
2
+
3
+ > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
+
5
+ **Goal:** Upgrade continuous-improve from a static 6-law discipline framework to a 7-law learning system with instinct-based behavioral observation, project-scoped learning, and a background Haiku observer.
6
+
7
+ **Architecture:** Hooks (observe.sh) capture every tool call as JSONL. A background Haiku agent periodically analyzes observations to create instincts. Law 5 reflections also feed instincts at higher confidence. One master command (`/continuous-improve`) surfaces everything. Instincts are project-scoped by default with graduated behavior (silent/suggest/auto-apply).
8
+
9
+ **Tech Stack:** Bash (hooks, observer scripts), Node.js (installer), YAML (instincts), JSONL (observations), Markdown (SKILL.md, observer prompt)
10
+
11
+ ---
12
+
13
+ ## Phase 1: Update continuous-improve Repo
14
+
15
+ ### File Map
16
+
17
+ | Action | File | Responsibility |
18
+ |--------|------|---------------|
19
+ | Create | `hooks/observe.sh` | PreToolUse/PostToolUse hook — append JSONL observations |
20
+ | Create | `agents/observer.md` | Background Haiku observer agent prompt |
21
+ | Create | `agents/observer-loop.sh` | Periodic loop that launches observer agent |
22
+ | Create | `agents/start-observer.sh` | Launcher — starts loop, writes PID |
23
+ | Create | `config.json` | Default observer configuration |
24
+ | Modify | `skills/continuous-improve/SKILL.md` | Upgrade from 6 Laws to 7 Laws + instinct behavior |
25
+ | Modify | `scripts/install.js` | Add hook installation, directory setup, observer files |
26
+ | Modify | `package.json` | Bump version, add new files to `files` array |
27
+ | Modify | `README.md` | Document Mulahazah, Law 7, new install flow |
28
+
29
+ ---
30
+
31
+ ### Task 1: Create the Observation Hook
32
+
33
+ **Files:**
34
+ - Create: `hooks/observe.sh`
35
+
36
+ This is the most critical component — it runs on every tool call and must be fast (<50ms).
37
+
38
+ - [ ] **Step 1: Create hooks directory**
39
+
40
+ ```bash
41
+ mkdir -p hooks
42
+ ```
43
+
44
+ - [ ] **Step 2: Write observe.sh**
45
+
46
+ ```bash
47
+ cat > hooks/observe.sh << 'HOOKEOF'
48
+ #!/usr/bin/env bash
49
+ # Mulahazah observation hook — appends one JSONL line per tool event.
50
+ # Runs on PreToolUse and PostToolUse. Must complete in <50ms.
51
+ # Never blocks the session. Never does analysis. Append only.
52
+
53
+ set -euo pipefail
54
+
55
+ # Read hook input from stdin
56
+ INPUT=$(cat)
57
+
58
+ # Determine event type from hook context
59
+ # Claude Code passes tool_name, tool_input (PreToolUse) or tool_output (PostToolUse)
60
+ TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name // empty' 2>/dev/null || true)
61
+ TOOL_INPUT=$(echo "$INPUT" | jq -r '.tool_input // empty' 2>/dev/null | head -c 500 || true)
62
+ TOOL_OUTPUT=$(echo "$INPUT" | jq -r '.tool_output // empty' 2>/dev/null | head -c 200 || true)
63
+ SESSION_ID=$(echo "$INPUT" | jq -r '.session_id // empty' 2>/dev/null || true)
64
+
65
+ # Skip if no tool name (malformed input)
66
+ if [ -z "$TOOL_NAME" ]; then
67
+ exit 0
68
+ fi
69
+
70
+ # Determine event type
71
+ if [ -n "$TOOL_OUTPUT" ]; then
72
+ EVENT="tool_complete"
73
+ else
74
+ EVENT="tool_start"
75
+ fi
76
+
77
+ # --- Project Detection ---
78
+ MULAHAZAH_DIR="$HOME/.claude/mulahazah"
79
+ PROJECT_ID=""
80
+ PROJECT_NAME=""
81
+ OBS_DIR="$MULAHAZAH_DIR"
82
+
83
+ # Priority 1: CLAUDE_PROJECT_DIR env var
84
+ if [ -n "${CLAUDE_PROJECT_DIR:-}" ]; then
85
+ PROJECT_ROOT="$CLAUDE_PROJECT_DIR"
86
+ # Priority 2: git remote URL
87
+ elif REMOTE_URL=$(git remote get-url origin 2>/dev/null); then
88
+ PROJECT_ROOT="$REMOTE_URL"
89
+ # Priority 3: git repo root
90
+ elif REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null); then
91
+ PROJECT_ROOT="$REPO_ROOT"
92
+ else
93
+ PROJECT_ROOT=""
94
+ fi
95
+
96
+ if [ -n "$PROJECT_ROOT" ]; then
97
+ PROJECT_ID=$(echo -n "$PROJECT_ROOT" | sha256sum | cut -c1-12)
98
+ PROJECT_NAME=$(basename "${PROJECT_ROOT%.git}")
99
+ OBS_DIR="$MULAHAZAH_DIR/projects/$PROJECT_ID"
100
+ fi
101
+
102
+ # --- Ensure directories exist ---
103
+ mkdir -p "$OBS_DIR"
104
+ if [ -n "$PROJECT_ID" ]; then
105
+ mkdir -p "$OBS_DIR/instincts/personal"
106
+
107
+ # Write project.json if it doesn't exist
108
+ if [ ! -f "$OBS_DIR/project.json" ]; then
109
+ cat > "$OBS_DIR/project.json" << PJEOF
110
+ {"id":"$PROJECT_ID","name":"$PROJECT_NAME","root":"$PROJECT_ROOT","created":"$(date -u +%Y-%m-%dT%H:%M:%SZ)"}
111
+ PJEOF
112
+ fi
113
+
114
+ # Update global projects.json registry
115
+ REGISTRY="$MULAHAZAH_DIR/projects.json"
116
+ if [ ! -f "$REGISTRY" ]; then
117
+ echo '{}' > "$REGISTRY"
118
+ fi
119
+ # Add project if not already registered (fast jq check)
120
+ if ! jq -e ".[\"$PROJECT_ID\"]" "$REGISTRY" >/dev/null 2>&1; then
121
+ jq ". + {\"$PROJECT_ID\": {\"name\": \"$PROJECT_NAME\", \"root\": \"$PROJECT_ROOT\"}}" "$REGISTRY" > "${REGISTRY}.tmp" && mv "${REGISTRY}.tmp" "$REGISTRY"
122
+ fi
123
+ fi
124
+
125
+ # --- Append observation ---
126
+ OBS_FILE="$OBS_DIR/observations.jsonl"
127
+ TIMESTAMP=$(date -u +%Y-%m-%dT%H:%M:%SZ)
128
+
129
+ # Build JSON line (no jq for speed — raw echo)
130
+ echo "{\"ts\":\"$TIMESTAMP\",\"event\":\"$EVENT\",\"session\":\"$SESSION_ID\",\"tool\":\"$TOOL_NAME\",\"input_summary\":$(echo "$TOOL_INPUT" | jq -Rs .),\"output_summary\":$(echo "$TOOL_OUTPUT" | jq -Rs .),\"project_id\":\"$PROJECT_ID\",\"project_name\":\"$PROJECT_NAME\"}" >> "$OBS_FILE"
131
+
132
+ # --- Rotate if too large (>10000 lines) ---
133
+ if [ -f "$OBS_FILE" ]; then
134
+ LINE_COUNT=$(wc -l < "$OBS_FILE" 2>/dev/null || echo 0)
135
+ if [ "$LINE_COUNT" -gt 10000 ]; then
136
+ ARCHIVE_DIR="$OBS_DIR/observations.archive"
137
+ mkdir -p "$ARCHIVE_DIR"
138
+ mv "$OBS_FILE" "$ARCHIVE_DIR/$(date -u +%Y-%m-%d).jsonl"
139
+ fi
140
+ fi
141
+
142
+ exit 0
143
+ HOOKEOF
144
+ chmod +x hooks/observe.sh
145
+ ```
146
+
147
+ - [ ] **Step 3: Test observe.sh locally with mock input**
148
+
149
+ ```bash
150
+ echo '{"tool_name":"Edit","tool_input":"editing file.js","session_id":"test123"}' | bash hooks/observe.sh
151
+ ```
152
+
153
+ Expected: Exit 0, one line appended to `~/.claude/mulahazah/observations.jsonl` (or project-scoped if in a git repo).
154
+
155
+ - [ ] **Step 4: Verify the JSONL line was written correctly**
156
+
157
+ ```bash
158
+ tail -1 ~/.claude/mulahazah/projects/*/observations.jsonl 2>/dev/null || tail -1 ~/.claude/mulahazah/observations.jsonl
159
+ ```
160
+
161
+ Expected: Valid JSON with `ts`, `event`, `session`, `tool`, `input_summary`, `output_summary`, `project_id`, `project_name` fields.
162
+
163
+ - [ ] **Step 5: Test with PostToolUse mock input**
164
+
165
+ ```bash
166
+ echo '{"tool_name":"Edit","tool_output":"File edited successfully","session_id":"test123"}' | bash hooks/observe.sh
167
+ ```
168
+
169
+ Expected: Second line appended with `"event":"tool_complete"`.
170
+
171
+ - [ ] **Step 6: Clean up test data**
172
+
173
+ ```bash
174
+ rm -rf ~/.claude/mulahazah/projects/*/observations.jsonl ~/.claude/mulahazah/observations.jsonl
175
+ ```
176
+
177
+ - [ ] **Step 7: Commit**
178
+
179
+ ```bash
180
+ git add hooks/observe.sh
181
+ git commit -m "feat: add Mulahazah observation hook (observe.sh)"
182
+ ```
183
+
184
+ ---
185
+
186
+ ### Task 2: Create the Background Observer Agent
187
+
188
+ **Files:**
189
+ - Create: `agents/observer.md`
190
+
191
+ The observer prompt tells a Haiku agent how to analyze observations and create instincts.
192
+
193
+ - [ ] **Step 1: Create agents directory**
194
+
195
+ ```bash
196
+ mkdir -p agents
197
+ ```
198
+
199
+ - [ ] **Step 2: Write observer.md**
200
+
201
+ ```bash
202
+ cat > agents/observer.md << 'OBSEOF'
203
+ ---
204
+ name: mulahazah-observer
205
+ description: Background agent that analyzes session observations to detect patterns and create instincts. Uses Haiku for cost-efficiency.
206
+ model: haiku
207
+ ---
208
+
209
+ # Mulahazah Observer Agent
210
+
211
+ You are a background observer for the Mulahazah learning system. Your job is to analyze session observations and create or update instincts — small, atomic learned behaviors.
212
+
213
+ ## Input
214
+
215
+ You will be given:
216
+ 1. A path to an `observations.jsonl` file containing recent tool usage events
217
+ 2. A path to existing instincts directory (YAML files)
218
+ 3. Project context (project_id, project_name) or "global"
219
+
220
+ ## Your Task
221
+
222
+ 1. Read ALL observations in the JSONL file
223
+ 2. Read ALL existing instincts in the instincts directory
224
+ 3. Detect patterns (see Pattern Detection below)
225
+ 4. For each pattern found:
226
+ - If an existing instinct matches: UPDATE its confidence (+0.05 per confirming observation) and update `last_observed` date and evidence
227
+ - If no matching instinct exists AND the pattern has 3+ observations: CREATE a new instinct YAML file
228
+ 5. Never create duplicate instincts — merge similar ones
229
+
230
+ ## Pattern Detection
231
+
232
+ Look for these patterns in the observations:
233
+
234
+ ### 1. User Corrections
235
+ When tool_complete is immediately followed by the same tool with different input:
236
+ - Indicates the user corrected the agent's approach
237
+ - Create instinct: "When doing X, prefer Y instead of Z"
238
+ - Confidence: 0.3 (single correction), 0.5 (2+ corrections of same type)
239
+
240
+ ### 2. Error Resolution Sequences
241
+ When tool_complete contains error indicators followed by tools that fix it:
242
+ - Error keywords: "error", "Error", "failed", "FAIL", "not found", "undefined"
243
+ - Create instinct: "When encountering [error type], try [resolution approach]"
244
+ - Confidence based on frequency: 1-2 times = 0.3, 3-5 = 0.5, 6+ = 0.7
245
+
246
+ ### 3. Repeated Workflows
247
+ When the same tool sequence appears 3+ times:
248
+ - Same tools in same order with similar input patterns
249
+ - Create instinct: "When [trigger], follow workflow: [tool1] -> [tool2] -> [tool3]"
250
+ - Confidence: 0.5 (3 occurrences), 0.7 (6+), 0.85 (11+)
251
+
252
+ ### 4. Tool Preferences
253
+ When one tool is consistently chosen over alternatives:
254
+ - e.g., Grep always before Edit, Read always before Write
255
+ - Create instinct: "When [task], use [preferred tool]"
256
+ - Confidence based on consistency ratio
257
+
258
+ ### 5. Rejected Suggestions
259
+ When agent output is immediately undone or replaced:
260
+ - Create instinct: "Avoid [approach] in [context]"
261
+ - Confidence: 0.3 per rejection, increases with repetition
262
+
263
+ ## Scope Decision
264
+
265
+ Determine whether each instinct should be project-scoped or global:
266
+
267
+ - **project** (default): Language/framework conventions, file structure, code style, error handling strategies
268
+ - **global**: Security practices, general best practices, tool workflow preferences, git practices
269
+
270
+ When in doubt, use `scope: project`.
271
+
272
+ ## Instinct YAML Format
273
+
274
+ Write each instinct as a separate `.yaml` file named `{id}.yaml`:
275
+
276
+ ```yaml
277
+ ---
278
+ id: prefer-grep-before-edit
279
+ trigger: "when modifying code"
280
+ confidence: 0.65
281
+ domain: "workflow"
282
+ source: "session-observation"
283
+ scope: project
284
+ project_id: "a1b2c3d4e5f6"
285
+ project_name: "my-app"
286
+ created: "2026-04-05"
287
+ last_observed: "2026-04-05"
288
+ ---
289
+
290
+ # Prefer Grep Before Edit
291
+
292
+ ## Action
293
+ Always search with Grep to confirm location before using Edit.
294
+
295
+ ## Evidence
296
+ - Observed 6 times in sessions on 2026-04-05
297
+ - Pattern: Grep -> Read -> Edit sequence repeated consistently
298
+ ```
299
+
300
+ ## Confidence Rules
301
+
302
+ - Never set confidence above 0.85 from observation alone
303
+ - Cap at 0.9 (only reflection + observation agreement can reach this)
304
+ - Decrease by 0.1 for each contradicting observation
305
+ - Decrease by 0.02 per week without any observation (decay)
306
+
307
+ ## Domain Tags
308
+
309
+ Use exactly one of: `code-style`, `testing`, `git`, `debugging`, `workflow`, `security`, `architecture`
310
+
311
+ ## Rules
312
+
313
+ 1. Be conservative — only create instincts for 3+ observations
314
+ 2. Be specific — narrow triggers are better than broad ones
315
+ 3. Track evidence — always include what observations led to the instinct
316
+ 4. Respect privacy — never include actual code snippets, only patterns
317
+ 5. Merge similar — update rather than duplicate
318
+ 6. Default to project scope — safer to be specific and promote later
319
+ 7. Include project context — always set project_id and project_name for project-scoped instincts
320
+ OBSEOF
321
+ ```
322
+
323
+ - [ ] **Step 3: Commit**
324
+
325
+ ```bash
326
+ git add agents/observer.md
327
+ git commit -m "feat: add Mulahazah background observer agent prompt"
328
+ ```
329
+
330
+ ---
331
+
332
+ ### Task 3: Create Observer Shell Scripts
333
+
334
+ **Files:**
335
+ - Create: `agents/observer-loop.sh`
336
+ - Create: `agents/start-observer.sh`
337
+
338
+ - [ ] **Step 1: Write observer-loop.sh**
339
+
340
+ ```bash
341
+ cat > agents/observer-loop.sh << 'LOOPEOF'
342
+ #!/usr/bin/env bash
343
+ # Mulahazah observer loop — runs every N minutes, launches Haiku observer
344
+ # when enough observations accumulate.
345
+
346
+ set -euo pipefail
347
+
348
+ MULAHAZAH_DIR="$HOME/.claude/mulahazah"
349
+ CONFIG_FILE="$MULAHAZAH_DIR/config.json"
350
+
351
+ # Read config
352
+ if [ -f "$CONFIG_FILE" ]; then
353
+ INTERVAL=$(jq -r '.observer.run_interval_minutes // 5' "$CONFIG_FILE")
354
+ MIN_OBS=$(jq -r '.observer.min_observations_to_analyze // 20' "$CONFIG_FILE")
355
+ ENABLED=$(jq -r '.observer.enabled // false' "$CONFIG_FILE")
356
+ else
357
+ INTERVAL=5
358
+ MIN_OBS=20
359
+ ENABLED=false
360
+ fi
361
+
362
+ if [ "$ENABLED" != "true" ]; then
363
+ echo "Observer is disabled in config.json. Set observer.enabled to true."
364
+ exit 0
365
+ fi
366
+
367
+ echo "Mulahazah observer started (interval: ${INTERVAL}m, min observations: ${MIN_OBS})"
368
+
369
+ # Handle SIGTERM for graceful shutdown
370
+ trap 'echo "Observer shutting down..."; exit 0' SIGTERM SIGINT
371
+
372
+ # Handle SIGUSR1 for immediate analysis
373
+ FORCE_RUN=false
374
+ trap 'FORCE_RUN=true' SIGUSR1
375
+
376
+ analyze_project() {
377
+ local project_dir="$1"
378
+ local obs_file="$project_dir/observations.jsonl"
379
+ local instincts_dir="$project_dir/instincts/personal"
380
+
381
+ if [ ! -f "$obs_file" ]; then
382
+ return
383
+ fi
384
+
385
+ local line_count
386
+ line_count=$(wc -l < "$obs_file" 2>/dev/null || echo 0)
387
+
388
+ if [ "$line_count" -lt "$MIN_OBS" ] && [ "$FORCE_RUN" != "true" ]; then
389
+ return
390
+ fi
391
+
392
+ echo "$(date -u +%H:%M:%S) Analyzing $project_dir ($line_count observations)..."
393
+ mkdir -p "$instincts_dir"
394
+
395
+ # Launch claude with observer prompt
396
+ # The observer agent reads the observations and creates/updates instincts
397
+ claude --model haiku --print \
398
+ --system-prompt "$(cat "$(dirname "$0")/observer.md")" \
399
+ "Analyze observations at: $obs_file
400
+ Write instincts to: $instincts_dir
401
+ Project context: $(cat "$project_dir/project.json" 2>/dev/null || echo '{"scope":"global"}')" \
402
+ 2>/dev/null || echo " Warning: observer analysis failed for $project_dir"
403
+ }
404
+
405
+ while true; do
406
+ # Analyze each project
407
+ if [ -d "$MULAHAZAH_DIR/projects" ]; then
408
+ for project_dir in "$MULAHAZAH_DIR/projects"/*/; do
409
+ if [ -d "$project_dir" ]; then
410
+ analyze_project "$project_dir"
411
+ fi
412
+ done
413
+ fi
414
+
415
+ # Analyze global observations
416
+ GLOBAL_OBS="$MULAHAZAH_DIR/observations.jsonl"
417
+ if [ -f "$GLOBAL_OBS" ]; then
418
+ local_count=$(wc -l < "$GLOBAL_OBS" 2>/dev/null || echo 0)
419
+ if [ "$local_count" -ge "$MIN_OBS" ] || [ "$FORCE_RUN" = "true" ]; then
420
+ echo "$(date -u +%H:%M:%S) Analyzing global observations ($local_count)..."
421
+ mkdir -p "$MULAHAZAH_DIR/instincts/personal"
422
+ claude --model haiku --print \
423
+ --system-prompt "$(cat "$(dirname "$0")/observer.md")" \
424
+ "Analyze observations at: $GLOBAL_OBS
425
+ Write instincts to: $MULAHAZAH_DIR/instincts/personal
426
+ Project context: {\"scope\":\"global\"}" \
427
+ 2>/dev/null || echo " Warning: global observer analysis failed"
428
+ fi
429
+ fi
430
+
431
+ FORCE_RUN=false
432
+ sleep $((INTERVAL * 60))
433
+ done
434
+ LOOPEOF
435
+ chmod +x agents/observer-loop.sh
436
+ ```
437
+
438
+ - [ ] **Step 2: Write start-observer.sh**
439
+
440
+ ```bash
441
+ cat > agents/start-observer.sh << 'STARTEOF'
442
+ #!/usr/bin/env bash
443
+ # Start the Mulahazah background observer.
444
+ # Writes PID to ~/.claude/mulahazah/observer.pid
445
+
446
+ set -euo pipefail
447
+
448
+ MULAHAZAH_DIR="$HOME/.claude/mulahazah"
449
+ PID_FILE="$MULAHAZAH_DIR/observer.pid"
450
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
451
+
452
+ mkdir -p "$MULAHAZAH_DIR"
453
+
454
+ # Check if already running
455
+ if [ -f "$PID_FILE" ]; then
456
+ OLD_PID=$(cat "$PID_FILE")
457
+ if kill -0 "$OLD_PID" 2>/dev/null; then
458
+ echo "Observer already running (PID $OLD_PID)"
459
+ echo "To force-analyze now: kill -USR1 $OLD_PID"
460
+ echo "To stop: kill $OLD_PID"
461
+ exit 0
462
+ else
463
+ rm -f "$PID_FILE"
464
+ fi
465
+ fi
466
+
467
+ # Start in background
468
+ nohup "$SCRIPT_DIR/observer-loop.sh" > "$MULAHAZAH_DIR/observer.log" 2>&1 &
469
+ OBSERVER_PID=$!
470
+ echo "$OBSERVER_PID" > "$PID_FILE"
471
+
472
+ echo "Mulahazah observer started (PID $OBSERVER_PID)"
473
+ echo " Log: $MULAHAZAH_DIR/observer.log"
474
+ echo " Force analyze: kill -USR1 $OBSERVER_PID"
475
+ echo " Stop: kill $OBSERVER_PID"
476
+ STARTEOF
477
+ chmod +x agents/start-observer.sh
478
+ ```
479
+
480
+ - [ ] **Step 3: Test start-observer.sh launches and writes PID**
481
+
482
+ ```bash
483
+ bash agents/start-observer.sh
484
+ cat ~/.claude/mulahazah/observer.pid
485
+ ```
486
+
487
+ Expected: PID printed, file exists.
488
+
489
+ - [ ] **Step 4: Test stop**
490
+
491
+ ```bash
492
+ kill $(cat ~/.claude/mulahazah/observer.pid)
493
+ ```
494
+
495
+ Expected: Process stops gracefully.
496
+
497
+ - [ ] **Step 5: Commit**
498
+
499
+ ```bash
500
+ git add agents/observer-loop.sh agents/start-observer.sh
501
+ git commit -m "feat: add observer loop and launcher scripts"
502
+ ```
503
+
504
+ ---
505
+
506
+ ### Task 4: Create Default Configuration
507
+
508
+ **Files:**
509
+ - Create: `config.json`
510
+
511
+ - [ ] **Step 1: Write config.json**
512
+
513
+ ```bash
514
+ cat > config.json << 'CFGEOF'
515
+ {
516
+ "version": "2.0",
517
+ "observer": {
518
+ "enabled": true,
519
+ "run_interval_minutes": 5,
520
+ "min_observations_to_analyze": 20,
521
+ "model": "haiku"
522
+ }
523
+ }
524
+ CFGEOF
525
+ ```
526
+
527
+ - [ ] **Step 2: Commit**
528
+
529
+ ```bash
530
+ git add config.json
531
+ git commit -m "feat: add default Mulahazah observer config"
532
+ ```
533
+
534
+ ---
535
+
536
+ ### Task 5: Upgrade SKILL.md to 7 Laws
537
+
538
+ **Files:**
539
+ - Modify: `skills/continuous-improve/SKILL.md`
540
+
541
+ - [ ] **Step 1: Read the current SKILL.md to confirm starting state**
542
+
543
+ ```bash
544
+ cat skills/continuous-improve/SKILL.md
545
+ ```
546
+
547
+ Expected: 6 Laws, ending with "The Loop" section.
548
+
549
+ - [ ] **Step 2: Replace SKILL.md with the 7-Law version**
550
+
551
+ Write the complete new `skills/continuous-improve/SKILL.md`:
552
+
553
+ ```markdown
554
+ ---
555
+ name: continuous-improve
556
+ description: "Install structured self-improvement loops with instinct-based learning into Claude Code — research, plan, execute, verify, reflect, learn, iterate. Mulahazah observes your sessions and builds behavioral instincts with confidence scoring."
557
+ ---
558
+
559
+ # continuous-improve
560
+
561
+ You follow the continuous-improve framework. These 7 laws govern all your work.
562
+
563
+ ## Law 1: Research Before Executing
564
+
565
+ Before writing code or taking action:
566
+ - What already exists? Search the codebase and package registries.
567
+ - What are the constraints? Rate limits, quotas, memory, time.
568
+ - What can break? Side effects, dependencies, data risks.
569
+ - What's the simplest path? Fewest files, fewest dependencies.
570
+
571
+ If you can't answer these, research first.
572
+
573
+ ## Law 2: Plan Is Sacred
574
+
575
+ Before executing, state:
576
+ - **WILL build:** Specific deliverables with completion criteria
577
+ - **Will NOT build:** Explicit anti-scope
578
+ - **Verification:** The exact check that proves it works
579
+ - **Fallback:** What to do if it fails (not "try again")
580
+
581
+ ## Law 3: One Thing at a Time
582
+
583
+ - Complete and verify one task before starting the next
584
+ - Never spawn parallel work for tasks you can do directly
585
+ - Never report completion until you've checked actual output
586
+ - If you want to "also quickly add" something — stop. Finish first.
587
+
588
+ ## Law 4: Verify Before Reporting
589
+
590
+ "Done" requires ALL of:
591
+ - Code runs without errors
592
+ - Output matches expected result
593
+ - You checked the **actual** result, not assumed it
594
+ - Build passes
595
+ - You can explain what changed in one sentence
596
+
597
+ ## Law 5: Reflect After Every Session
598
+
599
+ After non-trivial tasks:
600
+ ```
601
+ ## Reflection
602
+ - What worked:
603
+ - What failed:
604
+ - What I'd do differently:
605
+ - Rule to add:
606
+ ```
607
+
608
+ The "Rule to add" field feeds Law 7 — it becomes an instinct with 0.6 starting confidence.
609
+
610
+ ## Law 6: Iterate Means One Thing
611
+
612
+ One change → verify → next change.
613
+
614
+ Never: add features before fixing bugs, make multiple untested changes, "improve" working code while the task is incomplete.
615
+
616
+ ## Law 7: Learn From Every Session
617
+
618
+ Your sessions create knowledge. Capture it.
619
+
620
+ - Patterns you repeat become instincts (automatic via hooks)
621
+ - Rules you discover become instincts (explicit via reflection)
622
+ - Corrections you receive reduce confidence in wrong behaviors
623
+ - Instincts you confirm strengthen over time
624
+
625
+ Low-confidence instincts suggest. High-confidence instincts apply.
626
+ If the user corrects you, the instinct weakens. If they don't, it strengthens.
627
+
628
+ Nothing learned is permanent. Everything decays without reinforcement.
629
+
630
+ ### Instinct Behavior
631
+
632
+ Before starting work, check for relevant instincts in `~/.claude/mulahazah/`:
633
+ - Load project-scoped instincts from `projects/<hash>/instincts/personal/`
634
+ - Load global instincts from `instincts/personal/`
635
+
636
+ Apply instincts based on confidence:
637
+ - **0.3-0.5 (silent):** Stored but not surfaced. Learning in progress.
638
+ - **0.5-0.7 (suggest):** Mention inline when relevant. "Consider: [instinct action]"
639
+ - **0.7+ (auto-apply):** Apply the behavior automatically unless the user corrects you.
640
+
641
+ If the user corrects an auto-applied instinct, reduce its confidence by 0.1.
642
+
643
+ ## The Loop
644
+
645
+ ```
646
+ Research → Plan → Execute (one thing) → Verify → Reflect → Learn → Iterate
647
+ ```
648
+
649
+ If you're skipping a step, that's the step you need most.
650
+
651
+ ## /continuous-improve Command
652
+
653
+ Run `/continuous-improve` after completing significant work. It provides:
654
+
655
+ 1. **Reflect** — Generate Law 5 reflection for the session
656
+ 2. **Analyze** — Process pending observations into instincts
657
+ 3. **Status** — Show all instincts with confidence levels
658
+ 4. **Suggest** — Surface actionable insights
659
+
660
+ Subcommands:
661
+ - `/continuous-improve status` — Instinct overview only
662
+ - `/continuous-improve projects` — List all known projects
663
+ - `/continuous-improve analyze` — Force analysis of pending observations
664
+ - `/continuous-improve reflect` — Trigger reflection manually
665
+ ```
666
+
667
+ - [ ] **Step 3: Verify the new SKILL.md is valid**
668
+
669
+ ```bash
670
+ head -3 skills/continuous-improve/SKILL.md
671
+ ```
672
+
673
+ Expected: YAML frontmatter with `name: continuous-improve`.
674
+
675
+ - [ ] **Step 4: Commit**
676
+
677
+ ```bash
678
+ git add skills/continuous-improve/SKILL.md
679
+ git commit -m "feat: upgrade SKILL.md from 6 Laws to 7 Laws with Mulahazah instinct behavior"
680
+ ```
681
+
682
+ ---
683
+
684
+ ### Task 6: Update the Installer
685
+
686
+ **Files:**
687
+ - Modify: `scripts/install.js`
688
+
689
+ The installer needs to:
690
+ 1. Keep all existing functionality (Claude, Codex, Cursor, OpenClaw, ChatGPT)
691
+ 2. Add: hook installation for Claude Code
692
+ 3. Add: `~/.claude/mulahazah/` directory creation
693
+ 4. Add: observer file copying
694
+ 5. Update: the CODING_AGENT_BLOCK to include Law 7
695
+
696
+ - [ ] **Step 1: Read current install.js**
697
+
698
+ ```bash
699
+ cat scripts/install.js
700
+ ```
701
+
702
+ - [ ] **Step 2: Update CODING_AGENT_BLOCK to include Law 7**
703
+
704
+ Replace the `CODING_AGENT_BLOCK` constant in `scripts/install.js` with:
705
+
706
+ ```javascript
707
+ const CODING_AGENT_BLOCK = `## Operating Rules (continuous-improve)
708
+
709
+ 1. RESEARCH before executing — check docs, rate limits, existing implementations
710
+ 2. PLAN before coding — write what you will build, what you won't, how to verify, and fallback
711
+ 3. ONE THING at a time — complete and verify each task before starting the next
712
+ 4. VERIFY before reporting — run it, check the output, confirm it matches expected
713
+ 5. REFLECT after sessions — log what worked, what failed, what to change
714
+ 6. ITERATE means one change at a time — fix before adding, verify before proceeding
715
+ 7. LEARN from every session — patterns become instincts, corrections weaken bad behaviors, nothing is permanent without reinforcement
716
+ `;
717
+ ```
718
+
719
+ - [ ] **Step 3: Add Mulahazah setup functions to install.js**
720
+
721
+ Add these functions after the existing `copySkill()` function:
722
+
723
+ ```javascript
724
+ function setupMulahazah() {
725
+ const mulahazahDir = path.join(homeDir, '.claude', 'mulahazah');
726
+ const dirs = [
727
+ mulahazahDir,
728
+ path.join(mulahazahDir, 'instincts', 'personal'),
729
+ path.join(mulahazahDir, 'projects'),
730
+ ];
731
+
732
+ for (const dir of dirs) {
733
+ ensureDir(dir);
734
+ }
735
+
736
+ // Copy config.json if it doesn't exist
737
+ const configSrc = path.join(rootDir, 'config.json');
738
+ const configDest = path.join(mulahazahDir, 'config.json');
739
+ if (!exists(configDest)) {
740
+ writeUtf8(configDest, readUtf8(configSrc));
741
+ }
742
+
743
+ // Initialize empty projects.json if it doesn't exist
744
+ const registryFile = path.join(mulahazahDir, 'projects.json');
745
+ if (!exists(registryFile)) {
746
+ writeUtf8(registryFile, '{}');
747
+ }
748
+
749
+ return { location: mulahazahDir, changed: true };
750
+ }
751
+
752
+ function installHooks() {
753
+ const settingsPath = path.join(homeDir, '.claude', 'settings.json');
754
+ const hookScript = path.join(rootDir, 'hooks', 'observe.sh');
755
+
756
+ // Ensure the hook script is accessible
757
+ const hookDest = path.join(homeDir, '.claude', 'mulahazah', 'observe.sh');
758
+ if (!exists(hookDest) || readUtf8(hookDest) !== readUtf8(hookScript)) {
759
+ writeUtf8(hookDest, readUtf8(hookScript));
760
+ if (!dryRun) {
761
+ fs.chmodSync(hookDest, '755');
762
+ }
763
+ }
764
+
765
+ // Read or create settings.json
766
+ let settings = {};
767
+ if (exists(settingsPath)) {
768
+ try {
769
+ settings = JSON.parse(readUtf8(settingsPath));
770
+ } catch {
771
+ settings = {};
772
+ }
773
+ }
774
+
775
+ // Add hooks if not already present
776
+ if (!settings.hooks) {
777
+ settings.hooks = {};
778
+ }
779
+
780
+ const hookEntry = {
781
+ matcher: '*',
782
+ hooks: [{
783
+ type: 'command',
784
+ command: hookDest,
785
+ }],
786
+ };
787
+
788
+ let changed = false;
789
+ const hookCommand = hookDest;
790
+
791
+ for (const event of ['PreToolUse', 'PostToolUse']) {
792
+ if (!settings.hooks[event]) {
793
+ settings.hooks[event] = [];
794
+ }
795
+
796
+ const alreadyInstalled = settings.hooks[event].some(
797
+ (entry) => entry.hooks && entry.hooks.some((h) => h.command === hookCommand)
798
+ );
799
+
800
+ if (!alreadyInstalled) {
801
+ settings.hooks[event].push(hookEntry);
802
+ changed = true;
803
+ }
804
+ }
805
+
806
+ if (changed) {
807
+ writeUtf8(settingsPath, JSON.stringify(settings, null, 2));
808
+ }
809
+
810
+ return { location: settingsPath, changed };
811
+ }
812
+
813
+ function copyObserverFiles() {
814
+ const agentsSrc = path.join(rootDir, 'agents');
815
+ const agentsDest = path.join(homeDir, '.claude', 'mulahazah', 'agents');
816
+
817
+ ensureDir(agentsDest);
818
+
819
+ const files = ['observer.md', 'observer-loop.sh', 'start-observer.sh'];
820
+ let changed = false;
821
+
822
+ for (const file of files) {
823
+ const src = path.join(agentsSrc, file);
824
+ const dest = path.join(agentsDest, file);
825
+
826
+ if (!exists(src)) continue;
827
+
828
+ const content = readUtf8(src);
829
+ if (!exists(dest) || readUtf8(dest) !== content) {
830
+ writeUtf8(dest, content);
831
+ if (!dryRun && file.endsWith('.sh')) {
832
+ fs.chmodSync(dest, '755');
833
+ }
834
+ changed = true;
835
+ }
836
+ }
837
+
838
+ return { location: agentsDest, changed };
839
+ }
840
+ ```
841
+
842
+ - [ ] **Step 4: Update installClaude() to call Mulahazah setup**
843
+
844
+ Replace the `installClaude` function and add Mulahazah steps to the install flow. Find the section where `installTarget` is called and update:
845
+
846
+ ```javascript
847
+ function installTarget(target) {
848
+ switch (target) {
849
+ case 'claude': {
850
+ const claudeResult = installClaude(false);
851
+ const mulahazahResult = setupMulahazah();
852
+ const hookResult = installHooks();
853
+ const observerResult = copyObserverFiles();
854
+ return {
855
+ ...claudeResult,
856
+ mulahazah: mulahazahResult.changed,
857
+ hooks: hookResult.changed,
858
+ observer: observerResult.changed,
859
+ };
860
+ }
861
+ case 'claude-global': {
862
+ const claudeResult = installClaude(true);
863
+ const mulahazahResult = setupMulahazah();
864
+ const hookResult = installHooks();
865
+ const observerResult = copyObserverFiles();
866
+ return {
867
+ ...claudeResult,
868
+ mulahazah: mulahazahResult.changed,
869
+ hooks: hookResult.changed,
870
+ observer: observerResult.changed,
871
+ };
872
+ }
873
+ case 'codex':
874
+ return installCodex();
875
+ case 'cursor':
876
+ return installCursor();
877
+ case 'openclaw':
878
+ return copySkill();
879
+ case 'chatgpt':
880
+ return installChatgpt();
881
+ default:
882
+ throw new Error(`Unknown target: ${target}`);
883
+ }
884
+ }
885
+ ```
886
+
887
+ - [ ] **Step 5: Update the result output to show Mulahazah status**
888
+
889
+ Replace the result logging section at the bottom of install.js:
890
+
891
+ ```javascript
892
+ console.log(`continuous-improve ${command}\n`);
893
+ for (const result of results) {
894
+ if (result.printed) {
895
+ console.log(`✓ ${result.target}: copy this into ChatGPT Custom Instructions\n`);
896
+ console.log(result.printed);
897
+ continue;
898
+ }
899
+
900
+ const status = command === 'install'
901
+ ? (result.changed ? 'installed' : (result.reason || 'unchanged'))
902
+ : (result.changed ? 'removed' : (result.reason || 'unchanged'));
903
+ console.log(`✓ ${result.target}: ${status} → ${result.location}${dryRun ? ' (dry-run)' : ''}`);
904
+
905
+ if (command === 'install' && result.mulahazah) {
906
+ console.log(` ✓ mulahazah: directory created → ~/.claude/mulahazah/`);
907
+ }
908
+ if (command === 'install' && result.hooks) {
909
+ console.log(` ✓ hooks: PreToolUse + PostToolUse → ~/.claude/settings.json`);
910
+ }
911
+ if (command === 'install' && result.observer) {
912
+ console.log(` ✓ observer: agent files copied → ~/.claude/mulahazah/agents/`);
913
+ console.log(`\n To start background observer: ~/.claude/mulahazah/agents/start-observer.sh`);
914
+ }
915
+ }
916
+
917
+ if (command === 'install' && results.some((r) => r.target === 'claude' || r.target === 'claude-global')) {
918
+ console.log(`\n Run /continuous-improve after your next session to see what was learned.`);
919
+ }
920
+ ```
921
+
922
+ - [ ] **Step 6: Add uninstall support for Mulahazah hooks**
923
+
924
+ Add a function to cleanly remove hooks:
925
+
926
+ ```javascript
927
+ function uninstallHooks() {
928
+ const settingsPath = path.join(homeDir, '.claude', 'settings.json');
929
+ if (!exists(settingsPath)) return { changed: false, reason: 'no-settings' };
930
+
931
+ let settings;
932
+ try {
933
+ settings = JSON.parse(readUtf8(settingsPath));
934
+ } catch {
935
+ return { changed: false, reason: 'parse-error' };
936
+ }
937
+
938
+ if (!settings.hooks) return { changed: false, reason: 'no-hooks' };
939
+
940
+ const hookCommand = path.join(homeDir, '.claude', 'mulahazah', 'observe.sh');
941
+ let changed = false;
942
+
943
+ for (const event of ['PreToolUse', 'PostToolUse']) {
944
+ if (!settings.hooks[event]) continue;
945
+ const before = settings.hooks[event].length;
946
+ settings.hooks[event] = settings.hooks[event].filter(
947
+ (entry) => !(entry.hooks && entry.hooks.some((h) => h.command === hookCommand))
948
+ );
949
+ if (settings.hooks[event].length < before) changed = true;
950
+ if (settings.hooks[event].length === 0) delete settings.hooks[event];
951
+ }
952
+
953
+ if (Object.keys(settings.hooks).length === 0) delete settings.hooks;
954
+
955
+ if (changed) {
956
+ writeUtf8(settingsPath, JSON.stringify(settings, null, 2));
957
+ }
958
+
959
+ return { location: settingsPath, changed };
960
+ }
961
+ ```
962
+
963
+ Update `uninstallTarget` for claude:
964
+
965
+ ```javascript
966
+ function uninstallTarget(target) {
967
+ switch (target) {
968
+ case 'claude': {
969
+ const claudeResult = uninstallClaude(false);
970
+ const hookResult = uninstallHooks();
971
+ return { ...claudeResult, hooks: hookResult.changed };
972
+ }
973
+ case 'claude-global': {
974
+ const claudeResult = uninstallClaude(true);
975
+ const hookResult = uninstallHooks();
976
+ return { ...claudeResult, hooks: hookResult.changed };
977
+ }
978
+ case 'codex':
979
+ return uninstallCodex();
980
+ case 'cursor':
981
+ return uninstallCursor();
982
+ case 'openclaw':
983
+ return uninstallOpenclaw();
984
+ default:
985
+ throw new Error(`Unknown target for uninstall: ${target}`);
986
+ }
987
+ }
988
+ ```
989
+
990
+ - [ ] **Step 7: Test the installer in dry-run mode**
991
+
992
+ ```bash
993
+ node scripts/install.js install --claude --dry-run
994
+ ```
995
+
996
+ Expected: Shows what would be installed without making changes.
997
+
998
+ - [ ] **Step 8: Commit**
999
+
1000
+ ```bash
1001
+ git add scripts/install.js
1002
+ git commit -m "feat: update installer with Mulahazah hooks, directory setup, and observer files"
1003
+ ```
1004
+
1005
+ ---
1006
+
1007
+ ### Task 7: Update package.json
1008
+
1009
+ **Files:**
1010
+ - Modify: `package.json`
1011
+
1012
+ - [ ] **Step 1: Update package.json**
1013
+
1014
+ ```json
1015
+ {
1016
+ "name": "continuous-improve",
1017
+ "version": "1.0.0",
1018
+ "description": "Install structured self-improvement loops with instinct-based learning into Claude Code — research, plan, execute, verify, reflect, learn, iterate.",
1019
+ "license": "MIT",
1020
+ "bin": {
1021
+ "continuous-improve": "scripts/install.js"
1022
+ },
1023
+ "files": [
1024
+ "scripts/",
1025
+ "prompts/",
1026
+ "skills/",
1027
+ "hooks/",
1028
+ "agents/",
1029
+ "config.json",
1030
+ "README.md",
1031
+ "LICENSE",
1032
+ "docs/"
1033
+ ],
1034
+ "engines": {
1035
+ "node": ">=18"
1036
+ }
1037
+ }
1038
+ ```
1039
+
1040
+ - [ ] **Step 2: Commit**
1041
+
1042
+ ```bash
1043
+ git add package.json
1044
+ git commit -m "chore: bump to v1.0.0, add hooks/agents/config to package files"
1045
+ ```
1046
+
1047
+ ---
1048
+
1049
+ ### Task 8: Update README.md
1050
+
1051
+ **Files:**
1052
+ - Modify: `README.md`
1053
+
1054
+ - [ ] **Step 1: Write updated README.md**
1055
+
1056
+ Update the README to document Mulahazah, Law 7, the instinct system, and the `/continuous-improve` command. Keep the existing install flow but add the new capabilities.
1057
+
1058
+ Key sections to add/update:
1059
+ - Mention "7 rules" instead of "6 rules"
1060
+ - Add Law 7 to the rules list
1061
+ - Add "What's new in v1.0" section describing Mulahazah
1062
+ - Document `/continuous-improve` command
1063
+ - Document the instinct system briefly
1064
+ - Add "Background Observer" section
1065
+ - Keep all existing install/uninstall commands
1066
+
1067
+ The README should remain sharp and opinionated. Add this section after the existing "The 6 rules" section:
1068
+
1069
+ ```markdown
1070
+ ## What's new in v1.0: Mulahazah
1071
+
1072
+ Mulahazah (Arabic: observation) adds **instinct-based learning** to continuous-improve.
1073
+
1074
+ Your agent doesn't just follow rules — it learns from every session:
1075
+
1076
+ - **Hooks** observe every tool call (100% reliable, <50ms)
1077
+ - **Instincts** are atomic learned behaviors with confidence scoring (0.3-0.9)
1078
+ - **Graduated behavior** — low confidence suggests, high confidence auto-applies
1079
+ - **Project scoping** — React patterns stay in React projects
1080
+ - **Confidence decay** — instincts weaken without reinforcement
1081
+
1082
+ One command to see everything:
1083
+
1084
+ ```bash
1085
+ /continuous-improve
1086
+ ```
1087
+
1088
+ ### Background Observer
1089
+
1090
+ Optionally run a background Haiku agent that continuously analyzes your sessions:
1091
+
1092
+ ```bash
1093
+ ~/.claude/mulahazah/agents/start-observer.sh
1094
+ ```
1095
+
1096
+ The observer creates instincts automatically. Without it, learning happens on-demand when you run `/continuous-improve`.
1097
+
1098
+ ## The 7 rules
1099
+
1100
+ 1. **Research before executing**
1101
+ 2. **Plan before coding**
1102
+ 3. **Do one thing at a time**
1103
+ 4. **Verify before reporting**
1104
+ 5. **Reflect after non-trivial work**
1105
+ 6. **Iterate one change at a time**
1106
+ 7. **Learn from every session** ← new
1107
+ ```
1108
+
1109
+ - [ ] **Step 2: Commit**
1110
+
1111
+ ```bash
1112
+ git add README.md
1113
+ git commit -m "docs: update README with Mulahazah, Law 7, and instinct system"
1114
+ ```
1115
+
1116
+ ---
1117
+
1118
+ ### Task 9: Update Prompt Variants
1119
+
1120
+ **Files:**
1121
+ - Modify: `prompts/coding-agent.md`
1122
+ - Modify: `prompts/core.md`
1123
+ - Modify: `prompts/minimal.md`
1124
+ - Modify: `prompts/research-agent.md`
1125
+ - Modify: `prompts/product-agent.md`
1126
+
1127
+ All prompt variants need Law 7 added. The core loop changes from 6 steps to 7.
1128
+
1129
+ - [ ] **Step 1: Read all prompt files to understand current format**
1130
+
1131
+ ```bash
1132
+ for f in prompts/*.md; do echo "=== $f ==="; cat "$f"; echo; done
1133
+ ```
1134
+
1135
+ - [ ] **Step 2: Add Law 7 to each prompt file**
1136
+
1137
+ For each file in `prompts/`, append Law 7 before the closing loop section. The exact wording adapts per variant:
1138
+
1139
+ **For coding-agent.md and core.md** (full version):
1140
+ ```markdown
1141
+ ## Law 7: Learn From Every Session
1142
+
1143
+ Your sessions create knowledge. Capture it.
1144
+
1145
+ - Patterns you repeat become instincts (automatic via hooks)
1146
+ - Rules you discover become instincts (explicit via reflection)
1147
+ - Corrections you receive reduce confidence in wrong behaviors
1148
+ - Instincts you confirm strengthen over time
1149
+
1150
+ Low-confidence instincts suggest. High-confidence instincts apply.
1151
+ Nothing learned is permanent. Everything decays without reinforcement.
1152
+ ```
1153
+
1154
+ **For research-agent.md and product-agent.md** (adapted):
1155
+ ```markdown
1156
+ ## Law 7: Learn From Every Session
1157
+
1158
+ Sessions generate knowledge. Capture what worked, what failed, and what rules to add.
1159
+ Repeated patterns become automatic. Corrections weaken bad habits. Nothing sticks without reinforcement.
1160
+ ```
1161
+
1162
+ **For minimal.md** (one line):
1163
+ ```markdown
1164
+ 7. LEARN from sessions — patterns become instincts, corrections weaken bad habits, nothing is permanent
1165
+ ```
1166
+
1167
+ Update the loop in all files:
1168
+ ```
1169
+ Research → Plan → Execute (one thing) → Verify → Reflect → Learn → Iterate
1170
+ ```
1171
+
1172
+ - [ ] **Step 3: Commit**
1173
+
1174
+ ```bash
1175
+ git add prompts/
1176
+ git commit -m "feat: add Law 7 to all prompt variants"
1177
+ ```
1178
+
1179
+ ---
1180
+
1181
+ ### Task 10: Verify Full Package
1182
+
1183
+ - [ ] **Step 1: Check all files are present**
1184
+
1185
+ ```bash
1186
+ ls -la hooks/observe.sh agents/observer.md agents/observer-loop.sh agents/start-observer.sh config.json skills/continuous-improve/SKILL.md scripts/install.js package.json README.md
1187
+ ```
1188
+
1189
+ Expected: All files exist with correct permissions.
1190
+
1191
+ - [ ] **Step 2: Test full install flow**
1192
+
1193
+ ```bash
1194
+ node scripts/install.js install --claude --dry-run
1195
+ ```
1196
+
1197
+ Expected: Shows all installation targets including Mulahazah setup.
1198
+
1199
+ - [ ] **Step 3: Run observe.sh end-to-end test**
1200
+
1201
+ ```bash
1202
+ echo '{"tool_name":"Grep","tool_input":"searching for pattern","session_id":"e2e-test"}' | bash hooks/observe.sh
1203
+ echo '{"tool_name":"Grep","tool_output":"Found 3 matches","session_id":"e2e-test"}' | bash hooks/observe.sh
1204
+ echo '{"tool_name":"Edit","tool_input":"editing file","session_id":"e2e-test"}' | bash hooks/observe.sh
1205
+ wc -l ~/.claude/mulahazah/projects/*/observations.jsonl 2>/dev/null || wc -l ~/.claude/mulahazah/observations.jsonl
1206
+ ```
1207
+
1208
+ Expected: 3 lines in observations file.
1209
+
1210
+ - [ ] **Step 4: Clean up test data**
1211
+
1212
+ ```bash
1213
+ rm -rf ~/.claude/mulahazah/projects/*/observations.jsonl ~/.claude/mulahazah/observations.jsonl
1214
+ ```
1215
+
1216
+ - [ ] **Step 5: Push to origin**
1217
+
1218
+ ```bash
1219
+ git push origin main
1220
+ ```
1221
+
1222
+ ---
1223
+
1224
+ ## Phase 2: Fork MemoryCore and Contribute
1225
+
1226
+ ### Task 11: Fork and Clone Project-AI-MemoryCore
1227
+
1228
+ **Files:**
1229
+ - Fork creates: `Feature/Mulahazah-System/` (multiple files)
1230
+
1231
+ - [ ] **Step 1: Fork the repo**
1232
+
1233
+ ```bash
1234
+ gh repo fork Kiyoraka/Project-AI-MemoryCore --clone --remote
1235
+ cd Project-AI-MemoryCore
1236
+ ```
1237
+
1238
+ - [ ] **Step 2: Create feature branch**
1239
+
1240
+ ```bash
1241
+ git checkout -b feat/mulahazah-instinct-learning
1242
+ ```
1243
+
1244
+ - [ ] **Step 3: Commit**
1245
+
1246
+ (No changes yet — just branch created.)
1247
+
1248
+ ---
1249
+
1250
+ ### Task 12: Create Mulahazah Feature Module
1251
+
1252
+ **Files:**
1253
+ - Create: `Feature/Mulahazah-System/README.md`
1254
+ - Create: `Feature/Mulahazah-System/SKILL.md`
1255
+ - Create: `Feature/Mulahazah-System/install-mulahazah.md`
1256
+ - Create: `Feature/Mulahazah-System/hooks/observe.sh`
1257
+ - Create: `Feature/Mulahazah-System/agents/observer.md`
1258
+ - Create: `Feature/Mulahazah-System/agents/observer-loop.sh`
1259
+ - Create: `Feature/Mulahazah-System/agents/start-observer.sh`
1260
+ - Create: `Feature/Mulahazah-System/config.json`
1261
+
1262
+ - [ ] **Step 1: Create directory structure**
1263
+
1264
+ ```bash
1265
+ mkdir -p Feature/Mulahazah-System/{hooks,agents}
1266
+ ```
1267
+
1268
+ - [ ] **Step 2: Write README.md**
1269
+
1270
+ ```markdown
1271
+ # Mulahazah System — Instinct-Based Behavioral Learning
1272
+
1273
+ *The AI that learns how you work, not just what you said.*
1274
+
1275
+ ## What It Does
1276
+
1277
+ Mulahazah (Arabic: ملاحظة — "observation") adds **unconscious behavioral learning** to AI MemoryCore. While Forge creates skills through deliberate pattern recognition, Mulahazah quietly observes every session and builds atomic "instincts" that strengthen or weaken over time.
1278
+
1279
+ **Forge = conscious skill creation.** "I noticed I keep doing X, let me make a skill."
1280
+ **Mulahazah = unconscious behavioral adaptation.** The system quietly learns your preferences.
1281
+
1282
+ ## Key Features
1283
+
1284
+ - **100% observation** via PreToolUse/PostToolUse hooks (deterministic, not probabilistic)
1285
+ - **Atomic instincts** with confidence scoring (0.3-0.9) and natural decay
1286
+ - **Project-scoped learning** — React patterns stay in React projects
1287
+ - **Graduated behavior** — silent (0.3-0.5), suggest (0.5-0.7), auto-apply (0.7+)
1288
+ - **Background Haiku observer** — periodic pattern detection
1289
+ - **Three learning channels** — passive hooks, active reflection, manual command
1290
+
1291
+ ## How It Differs From Forge
1292
+
1293
+ | Forge | Mulahazah |
1294
+ |-------|-----------|
1295
+ | Deliberate — detects when AI/user notices a pattern | Automatic — hooks observe every session |
1296
+ | Requires 3+ occurrences + human approval | Creates tentative instincts from first sighting |
1297
+ | Creates full skills (SKILL.md) | Creates atomic instincts (YAML) |
1298
+ | No confidence scoring | 0.3-0.9 confidence with decay |
1299
+ | No project isolation | Project-scoped by default |
1300
+ | No background processing | Background Haiku observer |
1301
+
1302
+ ## Synergy With Other Features
1303
+
1304
+ | Feature | Integration |
1305
+ |---------|------------|
1306
+ | **Forge** | High-confidence instinct clusters become Forge skill proposals |
1307
+ | **Observation System** | Mulahazah feeds instincts into Refine quality checks |
1308
+ | **Decision Log** | Instinct promotions logged as decisions |
1309
+ | **Save Diary** | Session learning summary included in diary entries |
1310
+ | **Memory Consolidation** | Instincts as a new memory type |
1311
+
1312
+ ## Install
1313
+
1314
+ See `install-mulahazah.md` for the installation protocol.
1315
+
1316
+ ## Commands
1317
+
1318
+ | Command | Description |
1319
+ |---------|-------------|
1320
+ | `/continuous-improve` | Full dashboard — reflect, analyze, status, suggestions |
1321
+ | `/continuous-improve status` | Instinct overview (project + global) |
1322
+ | `/continuous-improve projects` | List known projects and instinct counts |
1323
+ | `/continuous-improve analyze` | Force analysis of pending observations |
1324
+ | `/continuous-improve reflect` | Trigger reflection manually |
1325
+ ```
1326
+
1327
+ - [ ] **Step 3: Write install-mulahazah.md**
1328
+
1329
+ ```markdown
1330
+ # Install Mulahazah System
1331
+
1332
+ ## Prerequisites
1333
+ - Claude Code installed
1334
+ - `jq` available on PATH
1335
+ - Git (for project detection)
1336
+
1337
+ ## Installation Steps
1338
+
1339
+ ### Step 1: Create Directory Structure
1340
+
1341
+ ```bash
1342
+ mkdir -p ~/.claude/mulahazah/{instincts/personal,projects}
1343
+ ```
1344
+
1345
+ ### Step 2: Copy Hook Script
1346
+
1347
+ Copy `hooks/observe.sh` to `~/.claude/mulahazah/observe.sh` and make it executable:
1348
+
1349
+ ```bash
1350
+ cp hooks/observe.sh ~/.claude/mulahazah/observe.sh
1351
+ chmod +x ~/.claude/mulahazah/observe.sh
1352
+ ```
1353
+
1354
+ ### Step 3: Configure Hooks
1355
+
1356
+ Add to `~/.claude/settings.json`:
1357
+
1358
+ ```json
1359
+ {
1360
+ "hooks": {
1361
+ "PreToolUse": [{
1362
+ "matcher": "*",
1363
+ "hooks": [{
1364
+ "type": "command",
1365
+ "command": "~/.claude/mulahazah/observe.sh"
1366
+ }]
1367
+ }],
1368
+ "PostToolUse": [{
1369
+ "matcher": "*",
1370
+ "hooks": [{
1371
+ "type": "command",
1372
+ "command": "~/.claude/mulahazah/observe.sh"
1373
+ }]
1374
+ }]
1375
+ }
1376
+ }
1377
+ ```
1378
+
1379
+ ### Step 4: Copy Observer Agent Files
1380
+
1381
+ ```bash
1382
+ cp -r agents/ ~/.claude/mulahazah/agents/
1383
+ chmod +x ~/.claude/mulahazah/agents/*.sh
1384
+ ```
1385
+
1386
+ ### Step 5: Copy Configuration
1387
+
1388
+ ```bash
1389
+ cp config.json ~/.claude/mulahazah/config.json
1390
+ ```
1391
+
1392
+ ### Step 6: Initialize Registry
1393
+
1394
+ ```bash
1395
+ echo '{}' > ~/.claude/mulahazah/projects.json
1396
+ ```
1397
+
1398
+ ### Step 7: (Optional) Start Background Observer
1399
+
1400
+ ```bash
1401
+ ~/.claude/mulahazah/agents/start-observer.sh
1402
+ ```
1403
+
1404
+ ## Verification
1405
+
1406
+ After installation, run any Claude Code session. Then check:
1407
+
1408
+ ```bash
1409
+ ls ~/.claude/mulahazah/projects/
1410
+ ```
1411
+
1412
+ You should see a project directory with observations.
1413
+ ```
1414
+
1415
+ - [ ] **Step 4: Copy observe.sh from continuous-improve**
1416
+
1417
+ ```bash
1418
+ cp /home/naim/.openclaw/workspace/continuous-improve/hooks/observe.sh Feature/Mulahazah-System/hooks/observe.sh
1419
+ ```
1420
+
1421
+ - [ ] **Step 5: Copy observer agent files from continuous-improve**
1422
+
1423
+ ```bash
1424
+ cp /home/naim/.openclaw/workspace/continuous-improve/agents/observer.md Feature/Mulahazah-System/agents/observer.md
1425
+ cp /home/naim/.openclaw/workspace/continuous-improve/agents/observer-loop.sh Feature/Mulahazah-System/agents/observer-loop.sh
1426
+ cp /home/naim/.openclaw/workspace/continuous-improve/agents/start-observer.sh Feature/Mulahazah-System/agents/start-observer.sh
1427
+ ```
1428
+
1429
+ - [ ] **Step 6: Copy config.json**
1430
+
1431
+ ```bash
1432
+ cp /home/naim/.openclaw/workspace/continuous-improve/config.json Feature/Mulahazah-System/config.json
1433
+ ```
1434
+
1435
+ - [ ] **Step 7: Write SKILL.md adapted for MemoryCore context**
1436
+
1437
+ The SKILL.md for MemoryCore should follow MemoryCore's skill format (activation message, context guard, protocol, level history):
1438
+
1439
+ ```markdown
1440
+ ---
1441
+ name: mulahazah
1442
+ description: "Auto-triggers on session start to load instincts, and when user says
1443
+ 'continuous-improve', 'instinct status', 'what have you learned',
1444
+ 'show instincts', 'analyze session', 'reflect on session',
1445
+ or when the AI completes a non-trivial task (triggers reflection).
1446
+ Also triggers on 'learn from this', 'remember this pattern'."
1447
+ ---
1448
+
1449
+ # Mulahazah — Instinct-Based Behavioral Learning
1450
+ *"The AI that learns how you work."*
1451
+
1452
+ ## Activation
1453
+
1454
+ When this skill activates, output:
1455
+
1456
+ `"Mulahazah active — loading instincts for this project..."`
1457
+
1458
+ Then load project-scoped and global instincts from `~/.claude/mulahazah/`.
1459
+
1460
+ ## Context Guard
1461
+
1462
+ | Context | Status |
1463
+ |---------|--------|
1464
+ | **Session start (any project)** | ACTIVE — load instincts silently |
1465
+ | **User says "continuous-improve", "instinct status"** | ACTIVE — show full dashboard |
1466
+ | **User says "analyze session", "what have you learned"** | ACTIVE — run analysis |
1467
+ | **After completing non-trivial task** | ACTIVE — trigger reflection + instinct creation |
1468
+ | **User says "learn from this", "remember this pattern"** | ACTIVE — create instinct from explicit input |
1469
+ | **Casual conversation, no work context** | DORMANT |
1470
+
1471
+ ## Protocol
1472
+
1473
+ ### Step 1: Load Instincts
1474
+
1475
+ On session start:
1476
+ 1. Detect current project (git remote → 12-char hash)
1477
+ 2. Load project instincts from `~/.claude/mulahazah/projects/<hash>/instincts/personal/`
1478
+ 3. Load global instincts from `~/.claude/mulahazah/instincts/personal/`
1479
+ 4. Apply based on confidence: silent (0.3-0.5), suggest (0.5-0.7), auto-apply (0.7+)
1480
+
1481
+ ### Step 2: Observe (Passive)
1482
+
1483
+ Hooks (PreToolUse/PostToolUse) capture every tool call to `observations.jsonl`. No action needed from the skill — hooks handle this automatically.
1484
+
1485
+ ### Step 3: Reflect (Active)
1486
+
1487
+ After non-trivial tasks, generate reflection:
1488
+ ```
1489
+ ## Reflection
1490
+ - What worked:
1491
+ - What failed:
1492
+ - What I'd do differently:
1493
+ - Rule to add:
1494
+ ```
1495
+
1496
+ Parse "Rule to add" into an instinct with 0.6 starting confidence.
1497
+
1498
+ ### Step 4: Analyze (On-Demand)
1499
+
1500
+ When user runs `/continuous-improve`:
1501
+ 1. Read pending observations
1502
+ 2. Detect patterns (corrections, errors, repeated workflows, tool preferences)
1503
+ 3. Create/update instincts
1504
+ 4. Show dashboard with confidence levels and suggestions
1505
+
1506
+ ## Instinct Model
1507
+
1508
+ Each instinct is a YAML file:
1509
+ ```yaml
1510
+ ---
1511
+ id: prefer-grep-before-edit
1512
+ trigger: "when modifying code"
1513
+ confidence: 0.65
1514
+ domain: "workflow"
1515
+ source: "session-observation"
1516
+ scope: project
1517
+ project_id: "a1b2c3d4e5f6"
1518
+ project_name: "my-app"
1519
+ created: "2026-04-05"
1520
+ last_observed: "2026-04-05"
1521
+ ---
1522
+ # Prefer Grep Before Edit
1523
+ ## Action
1524
+ Always search with Grep before editing.
1525
+ ## Evidence
1526
+ - Observed 6 times in sessions on 2026-04-05
1527
+ ```
1528
+
1529
+ ## Mandatory Rules
1530
+
1531
+ 1. **Never block sessions** — hooks must complete in <50ms
1532
+ 2. **Never log secrets** — only tool names and patterns, never file contents
1533
+ 3. **Default to project scope** — promote to global only when seen in 2+ projects
1534
+ 4. **Merge, don't duplicate** — update existing instincts rather than creating similar ones
1535
+ 5. **Confidence caps at 0.9** — never fully certain
1536
+ 6. **Decay is natural** — -0.02 per week without observation
1537
+ 7. **User corrections always win** — -0.1 per correction, immediate
1538
+
1539
+ ## Synergy with Other MemoryCore Features
1540
+
1541
+ | Feature | Integration |
1542
+ |---------|-------------|
1543
+ | **Forge** | When instinct cluster reaches 3+ related instincts at 0.7+ confidence, suggest Forge skill proposal |
1544
+ | **Observation System** | Mulahazah instincts inform Refine's quality checklist |
1545
+ | **Decision Log** | Log instinct promotions (project→global) as decisions |
1546
+ | **Save Diary** | Include "Session Learning" section in diary with new/updated instincts |
1547
+
1548
+ ## Level History
1549
+ - **Lv.1** — Base: Hook-based observation (100% reliable), atomic instincts with confidence scoring (0.3-0.9), project-scoped learning, graduated behavior (silent/suggest/auto-apply), background Haiku observer, confidence decay. (Origin: Forked from continuous-improve Mulahazah system, inspired by Homunculus v2 instinct architecture)
1550
+ ```
1551
+
1552
+ - [ ] **Step 8: Commit all MemoryCore files**
1553
+
1554
+ ```bash
1555
+ git add Feature/Mulahazah-System/
1556
+ git commit -m "feat: add Mulahazah System — instinct-based behavioral learning
1557
+
1558
+ Adds a new Feature module that provides unconscious behavioral learning
1559
+ through hook-based observation, atomic instincts with confidence scoring,
1560
+ project-scoped isolation, and a background Haiku observer agent.
1561
+
1562
+ Complements Forge (conscious skill creation) with automatic pattern
1563
+ detection and graduated behavior application."
1564
+ ```
1565
+
1566
+ ---
1567
+
1568
+ ### Task 13: Create Pull Request to MemoryCore
1569
+
1570
+ - [ ] **Step 1: Push feature branch**
1571
+
1572
+ ```bash
1573
+ git push -u origin feat/mulahazah-instinct-learning
1574
+ ```
1575
+
1576
+ - [ ] **Step 2: Create PR**
1577
+
1578
+ ```bash
1579
+ gh pr create --title "feat: Mulahazah System — instinct-based behavioral learning" --body "$(cat <<'EOF'
1580
+ ## Summary
1581
+
1582
+ Adds **Mulahazah** (Arabic: ملاحظة — "observation"), a new Feature module that provides unconscious behavioral learning for AI MemoryCore.
1583
+
1584
+ ### What it does
1585
+
1586
+ - **Hook-based observation** (PreToolUse/PostToolUse) captures every tool call — 100% reliable, deterministic
1587
+ - **Atomic instincts** with confidence scoring (0.3-0.9) and natural decay
1588
+ - **Project-scoped learning** — React patterns stay in React projects, Python conventions stay in Python projects
1589
+ - **Graduated behavior** — silent (0.3-0.5), suggest (0.5-0.7), auto-apply (0.7+)
1590
+ - **Background Haiku observer** — periodic pattern detection without blocking sessions
1591
+ - **Three learning channels** — passive hooks, active reflection, manual command
1592
+
1593
+ ### How it differs from Forge
1594
+
1595
+ | Forge | Mulahazah |
1596
+ |-------|-----------|
1597
+ | Deliberate — requires human recognition | Automatic — hooks observe everything |
1598
+ | 3+ occurrences + human approval | Tentative instincts from first sighting |
1599
+ | Creates full skills | Creates atomic instincts |
1600
+ | No confidence scoring | 0.3-0.9 with decay |
1601
+ | No project isolation | Project-scoped by default |
1602
+
1603
+ **Forge = conscious skill creation.** Mulahazah = unconscious behavioral adaptation. They're complementary — instinct clusters become Forge candidates.
1604
+
1605
+ ### Files added
1606
+
1607
+ ```
1608
+ Feature/Mulahazah-System/
1609
+ ├── README.md
1610
+ ├── SKILL.md
1611
+ ├── install-mulahazah.md
1612
+ ├── config.json
1613
+ ├── hooks/observe.sh
1614
+ └── agents/
1615
+ ├── observer.md
1616
+ ├── observer-loop.sh
1617
+ └── start-observer.sh
1618
+ ```
1619
+
1620
+ ## Test plan
1621
+
1622
+ - [ ] Run `observe.sh` with mock PreToolUse input — verify JSONL line appended
1623
+ - [ ] Run `observe.sh` with mock PostToolUse input — verify tool_complete event
1624
+ - [ ] Verify project detection creates correct hash from git remote
1625
+ - [ ] Start observer with `start-observer.sh` — verify PID file created
1626
+ - [ ] Run in a Claude Code session — verify observations accumulate
1627
+ - [ ] Run `/continuous-improve` — verify instinct dashboard appears
1628
+ EOF
1629
+ )"
1630
+ ```
1631
+
1632
+ - [ ] **Step 3: Note the PR URL**
1633
+
1634
+ Record the PR URL for tracking.
1635
+
1636
+ ---
1637
+
1638
+ ### Task 14: Final Verification
1639
+
1640
+ - [ ] **Step 1: Return to continuous-improve repo**
1641
+
1642
+ ```bash
1643
+ cd /home/naim/.openclaw/workspace/continuous-improve
1644
+ ```
1645
+
1646
+ - [ ] **Step 2: Verify git log shows all Phase 1 commits**
1647
+
1648
+ ```bash
1649
+ git log --oneline -10
1650
+ ```
1651
+
1652
+ Expected: All Task 1-9 commits visible.
1653
+
1654
+ - [ ] **Step 3: Verify package is publishable**
1655
+
1656
+ ```bash
1657
+ npm pack --dry-run
1658
+ ```
1659
+
1660
+ Expected: Lists all files that would be included in the package, including hooks/, agents/, config.json.
1661
+
1662
+ - [ ] **Step 4: Push continuous-improve to origin**
1663
+
1664
+ ```bash
1665
+ git push origin main
1666
+ ```