-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreflexion-eval
More file actions
executable file
Β·679 lines (573 loc) Β· 22.8 KB
/
reflexion-eval
File metadata and controls
executable file
Β·679 lines (573 loc) Β· 22.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
#!/usr/bin/env bash
# reflexion-eval β post-task reflection & behavioral rule extraction
# Part of teebot-tools. Uses OpenAI gpt-4o-mini to evaluate tasks and extract rules.
#
# Usage:
# reflexion-eval evaluate '<task>' '<outcome>' Evaluate a task, extract rules
# reflexion-eval rules [--min-confidence N] List active rules
# reflexion-eval match '<task_description>' Find rules matching a task
# reflexion-eval reinforce <rule_id> <task_id> Add positive evidence to rule
# reflexion-eval contradict <rule_id> <task_id> Add negative evidence to rule
# reflexion-eval decay Decay stale rules, archive weak ones
# reflexion-eval stats Show rule store statistics
# reflexion-eval --help Show this help
set -euo pipefail
# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------
WORKSPACE="${WORKSPACE:-$HOME/.openclaw/workspace}"
RULES_FILE="$WORKSPACE/memory/reflexion-rules.json"
EVALS_DIR="$WORKSPACE/memory/reflexion-evals"
LLM_MODEL="gpt-4o-mini"
DECAY_DAYS=14
DECAY_AMOUNT=5
ARCHIVE_THRESHOLD=20
MAX_ACTIVE_RULES=50
C_RESET='\033[0m'; C_BOLD='\033[1m'; C_DIM='\033[2m'
C_YELLOW='\033[33m'; C_GREEN='\033[32m'; C_RED='\033[31m'; C_CYAN='\033[36m'
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
die() { echo -e "${C_RED}β${C_RESET} $1" >&2; exit 1; }
info() { echo -e " ${C_DIM}$1${C_RESET}"; }
ok() { echo -e " ${C_GREEN}β${C_RESET} $1"; }
warn() { echo -e " ${C_YELLOW}β ${C_RESET} $1"; }
section() { echo -e "\n${C_CYAN}${C_BOLD}$1${C_RESET}"; }
ensure_deps() {
command -v jq &>/dev/null || die "jq required but not found"
command -v curl &>/dev/null || die "curl required but not found"
[[ -n "${OPENAI_API_KEY:-}" ]] || die "OPENAI_API_KEY not set"
}
ensure_rules_file() {
mkdir -p "$(dirname "$RULES_FILE")"
if [[ ! -f "$RULES_FILE" ]]; then
echo '{"version":1,"rules":[],"archived":[]}' | jq . > "$RULES_FILE"
info "Created $RULES_FILE"
fi
}
ensure_evals_dir() {
mkdir -p "$EVALS_DIR"
}
now_iso() {
date -u +%Y-%m-%dT%H:%M:%SZ
}
uuid() {
# Portable UUID generation
if command -v uuidgen &>/dev/null; then
uuidgen | tr '[:upper:]' '[:lower:]'
else
cat /proc/sys/kernel/random/uuid 2>/dev/null || python3 -c "import uuid; print(uuid.uuid4())"
fi
}
# Call OpenAI chat completion
openai_chat() {
local system_prompt="$1"
local user_prompt="$2"
local payload
payload=$(jq -n \
--arg model "$LLM_MODEL" \
--arg sys "$system_prompt" \
--arg usr "$user_prompt" \
'{
model: $model,
messages: [
{role: "system", content: $sys},
{role: "user", content: $usr}
],
temperature: 0.3,
response_format: {type: "json_object"}
}')
local response
response=$(curl -sS --max-time 60 \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d "$payload" \
"https://api.openai.com/v1/chat/completions")
# Extract content from response
local content
content=$(echo "$response" | jq -r '.choices[0].message.content // empty')
if [[ -z "$content" ]]; then
local err
err=$(echo "$response" | jq -r '.error.message // "Unknown API error"')
die "OpenAI API error: $err"
fi
echo "$content"
}
# ---------------------------------------------------------------------------
# Commands
# ---------------------------------------------------------------------------
cmd_evaluate() {
local task="" outcome="" trace=""
# Parse positional args and --trace flag
local positional=()
while [[ $# -gt 0 ]]; do
case "$1" in
--trace) trace="${2:-}"; shift 2 ;;
--trace=*) trace="${1#--trace=}"; shift ;;
--trace-file) [[ -f "${2:-}" ]] && trace=$(cat "$2"); shift 2 ;;
*) positional+=("$1"); shift ;;
esac
done
task="${positional[0]:-}"
outcome="${positional[1]:-}"
[[ -z "$task" ]] && die "Usage: reflexion-eval evaluate '<task>' '<outcome>' [--trace '<execution trace>']"
[[ -z "$outcome" ]] && die "Usage: reflexion-eval evaluate '<task>' '<outcome>' [--trace '<execution trace>']"
ensure_deps
ensure_rules_file
ensure_evals_dir
section "Evaluating task"
info "Task: ${task:0:80}..."
local system_prompt
# Get existing rule triggers to avoid duplicates
local existing_triggers=""
if [[ -f "$RULES_FILE" ]]; then
existing_triggers=$(jq -r '[.rules[].trigger] | join("; ")' "$RULES_FILE" 2>/dev/null | head -c 1000 || true)
fi
# ===== STAGE 1: Task Reflection (episodic) =====
# Score + what worked/failed. NO rule extraction here.
# (ExpeL finding: reflection narratives confabulate causal stories that pollute rules)
local trace_section=""
if [[ -n "$trace" ]]; then
# Truncate trace to 2000 chars to stay within token budget
trace_section="
## Execution Trace (tools called, decisions made, failures)
${trace:0:2000}"
info "Trace provided (${#trace} chars)"
fi
local reflect_prompt='You are a task evaluation system. Score this task and describe what happened.
Return JSON:
{
"success": true/false,
"score": 0-100 (overall quality),
"what_worked": ["specific thing 1", "specific thing 2"],
"what_failed": ["specific thing 1", "specific thing 2"],
"diagnostic_details": ["specific diagnostic from trace 1", "specific diagnostic from trace 2"]
}
Be specific and factual. Do NOT explain WHY things worked or failed β just describe WHAT happened.
If an execution trace is provided, extract DIAGNOSTIC details: what tools were tried, what errors occurred, what decisions were made and their consequences. Include these in "diagnostic_details".'
local reflect_user="Task: $task
Outcome: $outcome
$trace_section
Score and describe what happened."
echo -e " ${C_DIM}Stage 1: Reflection ($LLM_MODEL)...${C_RESET}"
local eval_json
eval_json=$(openai_chat "$reflect_prompt" "$reflect_user")
# Validate JSON
if ! echo "$eval_json" | jq . &>/dev/null; then
die "Invalid JSON from LLM: $eval_json"
fi
local success score
success=$(echo "$eval_json" | jq -r '.success')
score=$(echo "$eval_json" | jq -r '.score')
# Display results
if [[ "$success" == "true" ]]; then
ok "Success (score: $score/100)"
else
warn "Failure (score: $score/100)"
fi
echo -e "\n ${C_BOLD}What worked:${C_RESET}"
echo "$eval_json" | jq -r '.what_worked[]? // empty' | while read -r line; do
echo -e " ${C_GREEN}+${C_RESET} $line"
done
echo -e "\n ${C_BOLD}What failed:${C_RESET}"
echo "$eval_json" | jq -r '.what_failed[]? // empty' | while read -r line; do
echo -e " ${C_RED}-${C_RESET} $line"
done
# ===== STAGE 2: Rule Extraction (separate from reflection) =====
# ExpeL finding: DO NOT feed reflection output into rule extraction.
# Compare task+outcome directly against existing rules.
local existing_rules_section=""
if [[ -n "$existing_triggers" ]]; then
existing_rules_section="
EXISTING RULES (do not duplicate):
$existing_triggers"
fi
local rule_prompt='You extract behavioral rules from task outcomes. Do NOT explain why things happened β just identify patterns.
Return JSON:
{
"rules": [
{
"trigger": "when <specific situation>",
"action": "<specific behavioral guidance>",
"reasoning": "why this rule matters"
}
]
}
CRITICAL: Only extract rules from SURPRISING or PAINFUL outcomes. Not from routine success.
Rules must be GENERALIZABLE β they should apply to a CLASS of situations, not just this exact incident. Ask: "will this trigger match future tasks?"
BAD rules (DO NOT generate):
- "when developing a system β ensure clear communication" (platitude β too vague)
- "when completing a task β implement error handling" (obvious β not learned)
- "when encountering a scoring schema mismatch" (too specific β one-time incident, trigger won'\''t match future tasks)
- "when context ordering affects synthesis results" (restates the finding as a trigger β not a reusable pattern)
- "when truncation limits are silently dropping facts" (describes THIS bug, not a class of bugs)
GOOD rules:
- "when a bash script uses set -e with grep β add || true" (specific technique, reusable)
- "when migrating databases β prefer SQLite over novel options" (class of decisions, learned from failure)
- "when measurement metrics don'\''t match expectations β check the measurement tool first" (general pattern from specific incident)
- "when two data sources conflict β check if one is truncated" (generalizes truncation finding)
If nothing surprising happened, return {"rules": []}. Zero rules is CORRECT and PREFERRED for routine tasks.
Do NOT duplicate existing rules.'
local rule_user="Task: $task
Outcome: $outcome
$trace_section
$existing_rules_section
Extract rules ONLY if something surprising or painful happened. If a trace is provided, look for specific tool failures, timing issues, decision points, and unexpected behaviors β these are the richest source of rules."
echo -e " ${C_DIM}Stage 2: Rule extraction ($LLM_MODEL)...${C_RESET}"
local rules_json
rules_json=$(openai_chat "$rule_prompt" "$rule_user")
# Merge rules into eval_json for downstream processing
eval_json=$(echo "$eval_json" | jq --argjson rules "$(echo "$rules_json" | jq '.rules // []')" '. + {rules: $rules}')
# Process rules
local rule_count
rule_count=$(echo "$eval_json" | jq '.rules | length')
local eval_id
eval_id=$(uuid)
local timestamp
timestamp=$(now_iso)
if [[ "$rule_count" -gt 0 ]]; then
echo -e "\n ${C_BOLD}Extracted rules:${C_RESET}"
for i in $(seq 0 $((rule_count - 1))); do
local trigger action reasoning rule_id
trigger=$(echo "$eval_json" | jq -r ".rules[$i].trigger")
action=$(echo "$eval_json" | jq -r ".rules[$i].action")
reasoning=$(echo "$eval_json" | jq -r ".rules[$i].reasoning // \"\"")
rule_id=$(uuid)
echo -e " ${C_CYAN}β${C_RESET} $trigger: $action"
[[ -n "$reasoning" ]] && info " ($reasoning)"
# Check for similar existing rules (simple keyword overlap)
local existing_match
existing_match=$(jq -r --arg trig "$trigger" --arg act "$action" '
.rules[] | select(
(.trigger | ascii_downcase | contains($trig | ascii_downcase | split(" ")[2:4] | join(" "))) or
(.action | ascii_downcase | contains($act | ascii_downcase | split(" ")[0:3] | join(" ")))
) | .id' "$RULES_FILE" 2>/dev/null | head -1)
if [[ -n "$existing_match" ]]; then
# Reinforce existing rule
info " Reinforcing existing rule $existing_match"
_reinforce_rule "$existing_match" "$eval_id"
else
# Add new rule
local new_rule
new_rule=$(jq -n \
--arg id "$rule_id" \
--arg trigger "$trigger" \
--arg action "$action" \
--arg reasoning "$reasoning" \
--arg eval_id "$eval_id" \
--arg ts "$timestamp" \
'{
id: $id,
trigger: $trigger,
action: $action,
reasoning: $reasoning,
confidence: 50,
evidence: [$eval_id],
created: $ts,
updated: $ts
}')
# Check active rule cap
local active_count
active_count=$(jq '.rules | length' "$RULES_FILE")
if [[ "$active_count" -ge "$MAX_ACTIVE_RULES" ]]; then
# Archive lowest confidence rule
local lowest_id
lowest_id=$(jq -r '[.rules[] | {id, confidence}] | sort_by(.confidence) | .[0].id' "$RULES_FILE")
warn "Rule cap ($MAX_ACTIVE_RULES) reached. Archiving lowest: $lowest_id"
_archive_rule "$lowest_id"
fi
# Insert new rule
local tmp
tmp=$(mktemp)
jq --argjson rule "$new_rule" '.rules += [$rule]' "$RULES_FILE" > "$tmp" && mv "$tmp" "$RULES_FILE"
ok "New rule: $rule_id"
fi
done
# Auto-embed new rules for semantic matching
if command -v rule-matcher &>/dev/null; then
rule-matcher embed >/dev/null 2>&1 || true
fi
else
info "No rules extracted"
fi
# Save evaluation
local eval_file="$EVALS_DIR/${eval_id}.json"
local full_eval
full_eval=$(jq -n \
--arg id "$eval_id" \
--arg task "$task" \
--arg outcome "$outcome" \
--arg ts "$(now_iso)" \
--argjson eval "$eval_json" \
'{
id: $id,
task: $task,
outcome: $outcome,
timestamp: $ts,
evaluation: $eval
}')
echo "$full_eval" | jq . > "$eval_file"
info "Saved evaluation: $eval_file"
}
cmd_rules() {
ensure_rules_file
local min_confidence=0
while [[ $# -gt 0 ]]; do
case "$1" in
--min-confidence) min_confidence="${2:-0}"; shift 2 ;;
*) shift ;;
esac
done
section "Active Rules (confidence β₯ $min_confidence)"
local count
count=$(jq --argjson min "$min_confidence" '[.rules[] | select(.confidence >= $min)] | length' "$RULES_FILE")
if [[ "$count" -eq 0 ]]; then
info "No rules found"
return 0
fi
jq -r --argjson min "$min_confidence" '
.rules[] | select(.confidence >= $min) |
" \(.trigger) β \(.action)\n confidence: \(.confidence) | evidence: \(.evidence | length) tasks | updated: \(.updated)\n"
' "$RULES_FILE"
info "Total: $count active rules"
local archived
archived=$(jq '.archived | length' "$RULES_FILE")
[[ "$archived" -gt 0 ]] && info "Archived: $archived rules"
}
cmd_match() {
local task="${1:-}"
[[ -z "$task" ]] && die "Usage: reflexion-eval match '<task_description>'"
ensure_rules_file
section "Matching rules for task"
# Use semantic matching via rule-matcher if available and embeddings exist
if command -v rule-matcher &>/dev/null && [[ -f "$WORKSPACE/memory/rule-embeddings.bin" ]]; then
rule-matcher match "$task"
else
# Fallback: keyword matching
local task_lower
task_lower=$(echo "$task" | tr '[:upper:]' '[:lower:]')
local matches=0
echo -e "\n## Learned Rules (from prior tasks)"
while IFS= read -r rule_json; do
local trigger action confidence
trigger=$(echo "$rule_json" | jq -r '.trigger')
action=$(echo "$rule_json" | jq -r '.action')
confidence=$(echo "$rule_json" | jq -r '.confidence')
local evidence_count
evidence_count=$(echo "$rule_json" | jq '.evidence | length')
[[ "$confidence" -lt 40 ]] && continue
local trigger_lower match_found=false
trigger_lower=$(echo "$trigger" | tr '[:upper:]' '[:lower:]')
for word in $(echo "$trigger_lower" | tr -cs '[:alpha:]' '\n' | grep -vE '^(when|the|a|an|is|are|in|on|at|to|for|of|with|and|or|it|this|that|do|be|have|from|by)$'); do
[[ ${#word} -lt 3 ]] && continue
if echo "$task_lower" | grep -qw "$word"; then
match_found=true; break
fi
done
if [[ "$match_found" == "true" ]]; then
echo "- $trigger: $action (confidence: $confidence, evidence: $evidence_count tasks)"
matches=$((matches + 1))
fi
done < <(jq -c '.rules[]' "$RULES_FILE" 2>/dev/null)
[[ "$matches" -eq 0 ]] && info "No matching rules found" || { echo ""; info "$matches rules matched"; }
fi
}
cmd_match_json() {
local task="${1:-}"
[[ -z "$task" ]] && die "Usage: reflexion-eval match-json '<task_description>'"
ensure_rules_file
# Use semantic matching if available
if command -v rule-matcher &>/dev/null && [[ -f "$WORKSPACE/memory/rule-embeddings.bin" ]]; then
rule-matcher match-json "$task"
return
fi
# Fallback: keyword matching
local task_lower
task_lower=$(echo "$task" | tr '[:upper:]' '[:lower:]')
local results="[]"
while IFS= read -r rule_json; do
local trigger confidence id
trigger=$(echo "$rule_json" | jq -r '.trigger')
confidence=$(echo "$rule_json" | jq -r '.confidence')
id=$(echo "$rule_json" | jq -r '.id')
[[ "$confidence" -lt 40 ]] && continue
local trigger_lower
trigger_lower=$(echo "$trigger" | tr '[:upper:]' '[:lower:]')
local match_found=false
for word in $(echo "$trigger_lower" | tr -cs '[:alpha:]' '\n' | grep -vE '^(when|the|a|an|is|are|in|on|at|to|for|of|with|and|or|it|this|that|do|be|have|from|by)$'); do
[[ ${#word} -lt 3 ]] && continue
if echo "$task_lower" | grep -qw "$word"; then
match_found=true
break
fi
done
if [[ "$match_found" == "true" ]]; then
results=$(echo "$results" | jq --argjson rule "$rule_json" '. + [$rule]')
fi
done < <(jq -c '.rules[]' "$RULES_FILE" 2>/dev/null)
echo "$results"
}
cmd_reinforce() {
local rule_id="${1:-}"
local task_id="${2:-}"
[[ -z "$rule_id" ]] && die "Usage: reflexion-eval reinforce <rule_id> <task_id>"
[[ -z "$task_id" ]] && die "Usage: reflexion-eval reinforce <rule_id> <task_id>"
ensure_rules_file
_reinforce_rule "$rule_id" "$task_id"
ok "Reinforced rule $rule_id (added evidence: $task_id)"
}
cmd_contradict() {
local rule_id="${1:-}"
local task_id="${2:-}"
[[ -z "$rule_id" ]] && die "Usage: reflexion-eval contradict <rule_id> <task_id>"
[[ -z "$task_id" ]] && die "Usage: reflexion-eval contradict <rule_id> <task_id>"
ensure_rules_file
_contradict_rule "$rule_id" "$task_id"
ok "Contradicted rule $rule_id (added counter-evidence: $task_id)"
}
cmd_decay() {
ensure_rules_file
section "Rule Decay"
local now_epoch
now_epoch=$(date -u +%s)
local decay_threshold=$((now_epoch - DECAY_DAYS * 86400))
local decayed=0
local archived=0
# Process each rule
local tmp
tmp=$(mktemp)
cp "$RULES_FILE" "$tmp"
local rule_count
rule_count=$(jq '.rules | length' "$tmp")
for i in $(seq $((rule_count - 1)) -1 0); do
local updated
updated=$(jq -r ".rules[$i].updated" "$tmp")
local updated_epoch
updated_epoch=$(date -u -d "$updated" +%s 2>/dev/null || echo "$now_epoch")
if [[ "$updated_epoch" -lt "$decay_threshold" ]]; then
local old_conf new_conf rule_id
old_conf=$(jq -r ".rules[$i].confidence" "$tmp")
new_conf=$((old_conf - DECAY_AMOUNT))
[[ "$new_conf" -lt 0 ]] && new_conf=0
rule_id=$(jq -r ".rules[$i].id" "$tmp")
if [[ "$new_conf" -lt "$ARCHIVE_THRESHOLD" ]]; then
# Archive it
_archive_rule "$rule_id"
archived=$((archived + 1))
info "Archived: $rule_id (confidence: $old_conf β $new_conf)"
else
# Decay confidence
local tmp2
tmp2=$(mktemp)
jq --argjson i "$i" --argjson conf "$new_conf" --arg ts "$(now_iso)" \
'.rules[$i].confidence = $conf | .rules[$i].updated = $ts' "$RULES_FILE" > "$tmp2" && mv "$tmp2" "$RULES_FILE"
decayed=$((decayed + 1))
info "Decayed: $rule_id ($old_conf β $new_conf)"
fi
fi
done
rm -f "$tmp"
ok "Decayed: $decayed rules, Archived: $archived rules"
}
cmd_stats() {
ensure_rules_file
section "Reflexion Stats"
local active archived avg_conf total_evidence most_reinforced_id most_reinforced_count eval_count
active=$(jq '.rules | length' "$RULES_FILE")
archived=$(jq '.archived | length' "$RULES_FILE")
if [[ "$active" -eq 0 ]]; then
info "No rules yet. Run 'reflexion-eval evaluate' to start learning."
return 0
fi
avg_conf=$(jq '[.rules[].confidence] | add / length | floor' "$RULES_FILE")
total_evidence=$(jq '[.rules[].evidence | length] | add' "$RULES_FILE")
most_reinforced_id=$(jq -r '[.rules[] | {id, count: (.evidence | length)}] | sort_by(.count) | last | .id' "$RULES_FILE")
most_reinforced_count=$(jq -r '[.rules[] | {id, count: (.evidence | length)}] | sort_by(.count) | last | .count' "$RULES_FILE")
eval_count=$(find "$EVALS_DIR" -name "*.json" 2>/dev/null | wc -l)
echo -e " Active rules: ${C_BOLD}$active${C_RESET}"
echo -e " Archived rules: $archived"
echo -e " Avg confidence: $avg_conf"
echo -e " Total evidence: $total_evidence references"
echo -e " Most reinforced: $most_reinforced_id ($most_reinforced_count evidence)"
echo -e " Evaluations: $eval_count"
}
# ---------------------------------------------------------------------------
# Internal helpers
# ---------------------------------------------------------------------------
_reinforce_rule() {
local rule_id="$1"
local task_id="$2"
local timestamp
timestamp=$(now_iso)
local tmp
tmp=$(mktemp)
jq --arg id "$rule_id" --arg task "$task_id" --arg ts "$timestamp" '
.rules = [.rules[] |
if .id == $id then
.confidence = ((.confidence + 10) | if . > 100 then 100 else . end) |
.evidence += [$task] |
.updated = $ts
else . end
]' "$RULES_FILE" > "$tmp" && mv "$tmp" "$RULES_FILE"
}
_contradict_rule() {
local rule_id="$1"
local task_id="$2"
local timestamp
timestamp=$(now_iso)
local tmp
tmp=$(mktemp)
jq --arg id "$rule_id" --arg task "$task_id" --arg ts "$timestamp" '
.rules = [.rules[] |
if .id == $id then
.confidence = ((.confidence - 15) | if . < 0 then 0 else . end) |
.evidence += [$task] |
.updated = $ts
else . end
]' "$RULES_FILE" > "$tmp" && mv "$tmp" "$RULES_FILE"
}
_archive_rule() {
local rule_id="$1"
local tmp
tmp=$(mktemp)
jq --arg id "$rule_id" '
(.rules[] | select(.id == $id)) as $rule |
.archived += [$rule + {archived_at: (now | todate)}] |
.rules = [.rules[] | select(.id != $id)]
' "$RULES_FILE" > "$tmp" && mv "$tmp" "$RULES_FILE"
}
# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
show_help() {
echo -e "${C_BOLD}reflexion-eval${C_RESET} β post-task reflection & behavioral rule extraction"
echo ""
echo "Usage:"
echo " reflexion-eval evaluate '<task>' '<outcome>' Evaluate a task, extract rules"
echo " reflexion-eval rules [--min-confidence N] List active rules"
echo " reflexion-eval match '<task_description>' Find rules matching a task"
echo " reflexion-eval reinforce <rule_id> <task_id> Add positive evidence"
echo " reflexion-eval contradict <rule_id> <task_id> Add negative evidence"
echo " reflexion-eval decay Decay stale rules"
echo " reflexion-eval stats Show statistics"
echo ""
echo "Environment:"
echo " OPENAI_API_KEY Required for 'evaluate' command"
echo " WORKSPACE Override workspace dir (default: ~/.openclaw/workspace)"
echo ""
echo "Files:"
echo " memory/reflexion-rules.json Rule store (active + archived)"
echo " memory/reflexion-evals/ Individual evaluation records"
}
case "${1:-}" in
evaluate) shift; cmd_evaluate "$@" ;;
rules) shift; cmd_rules "$@" ;;
match) shift; cmd_match "$@" ;;
match-json) shift; cmd_match_json "$@" ;;
reinforce) shift; cmd_reinforce "$@" ;;
contradict) shift; cmd_contradict "$@" ;;
decay) cmd_decay ;;
stats) cmd_stats ;;
--help|-h) show_help ;;
*) show_help; exit 1 ;;
esac