# Learning Loop Refactor — Verification Log

> Generated: 2026-06-05 22:51 CST
> Purpose: 逐条终端原始输出归档，避免仅剩"摘要表"

---

## 1. AGENTS.md §2b — Learning Context Injector (MANDATORY)

### Command
```
sed -n '90,114p' /Users/a1234/.openclaw/workspace/AGENTS.md
```

### Raw Output
#### 2b. Learning Context Injector (MANDATORY — 3 searches)

**Search 1: Similar failures**
```
ctx_search(queries: ["<task_type> failure pattern lesson"], source: "reflections", sort: "timeline")
```

**Search 2: Relevant best practices**
```
memory_search(query: "<task_domain> best practice checklist pattern")
```

**Search 3: Relevant playbook**
```
Check playbooks/ for matching task type
```

Inject top findings into PLAN > Risks. Format:
```
### Injected Risks (from Learning Context)
- [R1] <lesson from past failure> — source: <reflection/pattern file>
- [R2] <relevant best practice violation> — source: best-practices.md #N
- [R3] <playbook recommendation> — source: playbooks/<name>.md
```


---

## 2. AGENTS.md §2c — 6 Domain Checklists

### Command
```
sed -n '116,155p' /Users/a1234/.openclaw/workspace/AGENTS.md
```

### Raw Output

**Based on task type, append the relevant checklist to PLAN:**

**SQL / Schema tasks:**
- □ FK 引用：所有 FK 用 ON CONFLICT DO UPDATE，不用 REPLACE（SQLite REPLACE = DELETE+INSERT）
- □ DDL 解析：PRIMARY KEY / CONSTRAINT 行不能当数据字段
- □ 迁移安全：先检查所有引用方，再改 schema
- □ WAL 模式：多进程读写不阻塞

**JavaScript / TypeScript tasks:**
- □ Falsy 陷阱：0、''、false 用 `??` 替代 `||`（|| 会把 0 判为 falsy）
- □ 类型生成：entity names 复数→单数（Albums→Album），但不碰 status/bus 等词根
- □ 模板语法：模板字面量内嵌反引号用 \` 转义或字符串拼接
- □ 启发式检测：必须 2+ 信号同时匹配，单信号不可靠

**Next.js / Frontend tasks:**
- □ 路径：Next.js App Router 用 `app/` 不是 `src/app/`
- □ Tailwind content 路径匹配实际目录
- □ tsconfig paths 匹配实际目录结构
- □ JSX：三元表达式嵌套使用括号包裹，避免 `{}` 嵌套错误

**Backend / API tasks:**
- □ generateTypes 必须包含 User 实体 → CreateUserInput 类型
- □ 所有 resource types 生成完整的 CRUD Input 类型
- □ route params 命名与 service 函数签名一致

**Generator / Builder tasks:**
- □ 输出路径：验证生成目录结构与实际 runtime 预期一致
- □ DDL→TS：schema.ts 中 CONSTRAINT/FK 行不能被解析为 interface 字段
- □ Type mapping：SQL types 到 TS types 的映射表完整
- □ Template safety：模板字面量不输出裸反引号

**Release / CI tasks:**
- □ Exit code 规范：PASS/WARN→0, FAIL→1
- □ 回退路径：每个 destructive 操作有对应回退步骤
- □ backward compat：新代码不改老接口

If no checklist matches, add:
- □ No domain-specific checklist available — proceed with extra caution


---

## 3. AGENTS.md §4 — MANDATORY GATE

### Command
```
sed -n '194,207p' /Users/a1234/.openclaw/workspace/AGENTS.md
```

### Raw Output
```

**MANDATORY GATE: Pre-flight Compliance Check**

Before closing any complex task, verify ALL of:

- [ ] PLAN contains `### Injected Risks (from Learning Context)` section
- [ ] At least 2 knowledge sources were searched (ctx_search / memory_search / playbooks)
- [ ] Matching domain checklist from §2c is included in PLAN
- [ ] If failure occurred: structured Reflection was written to `reflections/YYYY-MM-DD-<task>.md`
- [ ] Reflection contains ALL 7 required fields (Context/Root Cause/Fix/Pattern Class/Future Trigger/Checklist/Recurrence)

If ANY gate fails: **task is NOT complete**. Go back and fill the gap.


---

## 4. AGENTS.md §5 — T1-T7 Auto-Capture

### Command
```
sed -n '210,238p' /Users/a1234/.openclaw/workspace/AGENTS.md
```

### Raw Output
**ALWAYS check these conditions after fixing a failure. Write Reflection when ANY condition matches:**

| # | Trigger Condition | Why |
|---|------------------|-----|
| T1 | `build` command failed | Build failure always indicates systemic error |
| T2 | `test` command returned non-zero or unexpected failures | Test failure = regression risk |
| T3 | `lint` / `tsc --noEmit` failed | Syntax/type errors in generated code |
| T4 | Fix time > 30 minutes elapsed | Long fix = complex root cause worth documenting |
| T5 | Same error class appeared before (check ctx_search / Promotion Log) | Recurrence → must upgrade |
| T6 | Generated output path/format/structure mismatched target convention | E.g. `src/app/` vs `app/`, wrong SQL dialect, missing types |
| T7 | Generated content caused runtime crash or data corruption | Silent data corruption is highest severity |

**Skip reflection (not worth recording) when:**
- Fix < 5 min AND never seen before AND no test/build/lint failure
- Typo fix (single character, no logic change)
- Expected external service failure (network timeout, API rate limit)

**Reflection write checklist (ALL 7 fields REQUIRED):**
```
[ ] Context — what task was being performed
[ ] Root Cause — the bug, not the symptom (banned: "以后注意", "下次小心")
[ ] Fix — exact change, with code diff if applicable
[ ] Pattern Class — abstract category (e.g. "SQLite FK", "JS Falsy Coercion", "Path Convention")
[ ] Future Trigger — when to inject this lesson (e.g. "any SQL schema change")
[ ] Checklist — ≥2 actionable checks for next time
[ ] Recurrence Count — 1 (update on each recurrence)
```

---

---

## 5. AGENTS.md §3 — Auto-Capture + Promotion Check

### Command
```
sed -n '165,182p' /Users/a1234/.openclaw/workspace/AGENTS.md
```

### Raw Output
3. If local → fix, verify, continue
4. If structural → **REPLAN** — output a revised PLAN section
5. If same step fails 3 times → **PAUSE** and ask user
6. **Auto-Capture Check** (after fix, before continuing):
   → See complete trigger rules in §5 Auto-Capture Trigger (T1-T7)
   → If ANY trigger matches → write structured Reflection to `reflections/YYYY-MM-DD-<task>.md`
   → Reflection MUST contain ALL 7 required fields (Context/Root Cause/Fix/Pattern Class/Future Trigger/Checklist/Recurrence Count)
   → Skip only when: fix < 5 min + first occurrence + no test/build/lint failure

7. **Promotion Check** (after Reflection written):
   | Appearances | Action | Destination |
   |------------|--------|------------|
   | 1st | Reflection | reflections/ |
   | 2nd | Pattern | patterns/design-patterns.md (new section) |
   | 3rd | Best Practice | patterns/best-practices.md (numbered entry) |
   | 4th | Checklist Item | AGENTS.md §2c Domain Checklists |
   | 5th | Hard Rule | AGENTS.md §2c (bolded, marked ⚠️ HARD RULE) |


---

## 6. AGENTS.md — Learning Loop §

### Command
```
sed -n '240,305p' /Users/a1234/.openclaw/workspace/AGENTS.md
```

### Raw Output
## Learning Loop 🔄

> Knowledge stored in reflections/patterns/playbooks MUST flow back into Planning.
> This section closes the loop.

### Loop Architecture

```
Failure/Success
    ↓
Reflection (structured, with Pattern Class)
    ↓
Promotion Check (1→2→3→4→5 appearances)
    ↓
Pattern → Best Practice → Checklist → Hard Rule
    ↓
Pre-flight Injector (§2b) + Domain Checklists (§2c)
    ↓
Next Plan includes past lessons
    ↓
Execution
    ↓
Verification → triggers new Reflection if needed
    ↓
(loop closes)
```

### Promotion Rules

| Count | Promotion To | Location |
|-------|-------------|----------|
| 1st | Reflection | `reflections/YYYY-MM-DD-<task>.md` |
| 2nd | Design Pattern | `patterns/design-patterns.md` (new Anti-Pattern section) |
| 3rd | Best Practice | `patterns/best-practices.md` (numbered entry) |
| 4th | Domain Checklist | AGENTS.md §2c (update matching checklist, or create new) |
| 5th | Hard Rule | AGENTS.md §2c (bolded, marked ⚠️ HARD RULE) |

### Quality Gate for Reflections

A valid Reflection MUST include ALL of:
- [ ] Context (what task)
- [ ] Root Cause (the bug, not the symptom)
- [ ] Fix (exact change)
- [ ] Pattern Class (abstract category)
- [ ] Future Trigger (when to re-inject)
- [ ] Checklist (actionable items)
- [ ] Recurrence Count

**Rejected:** "以后注意", "下次小心", "当时没想清楚", "应该多测试"
**Accepted:** "SQLite FK: REPLACE=DELETE+INSERT, use ON CONFLICT DO UPDATE"

### Storage Locations

```
reflections/              ← First occurrence of a failure pattern
patterns/design-patterns  ← Abstract reusable anti-patterns (≥2 occurrences)
patterns/best-practices   ← Validated rules (≥3 occurrences)
AGENTS.md §2c             ← Domain Checklists (≥4 occurrences)
AGENTS.md §2c ⚠️          ← Hard Rules (≥5 occurrences)

playbooks/                ← Successful multi-step workflows (not failure-driven)
vault.md §Self-Evolution  ← History of promotions (timeline)
```

---


---

## 7. Reflection: falsy-coercion (full file)

### Command
```
cat /Users/a1234/.openclaw/workspace/reflections/2026-06-05-falsy-coercion.md
```

### Raw Output
```
# Reflection: `||` vs `??` Falsy Coercion Bug

> Date: 2026-06-05 | Severity: P1 | Recurrence: 2

## Context
Cross-Agent Certification (PR-30) — Fleet score ranking. Using `order[status] || 6` for certification ranking.

## Root Cause
JavaScript `||` operator treats `0` as falsy. When `order["healthy"] = 0`, `order["healthy"] || 6` evaluates to `6`, pushing healthy agents to bottom of ranking instead of top. The certification result was reversed — healthy fleets got low scores.

## Fix
Changed `order[status] || 6` → `order[status] ?? 6`. Nullish coalescing (`??`) only triggers on `null`/`undefined`, not on `0`.

## Pattern Class
**JS/TS Falsy Coercion Trap** — `||` treats `0`, `""`, `false` as falsy. Use `??` for numeric/boolean defaults.

## Future Trigger
- Any JS/TS code writing numeric defaults
- Any ranking/scoring/ordering logic
- Any code with `value || default` where value can legitimately be 0

## Checklist
- [ ] Grep all `||` in scoring/ranking/ordering code → replace with `??` if value can be 0
- [ ] For all numeric defaults: `||` → `??`
- [ ] Add `||` vs `??` check to JS/TS Domain Checklist

## Recurrence Count
2 — previously hit in Agent Evolution FK index scoring (same pattern: `count || 0` skipped real zeros)
```

### 7-field check
```
grep -c '^## Context\|^## Root Cause\|^## Fix\|^## Pattern Class\|^## Future Trigger\|^## Checklist\|^## Recurrence' /Users/a1234/.openclaw/workspace/reflections/2026-06-05-falsy-coercion.md
```
Result:
7

### Banned phrase check
```
grep -ic '以后注意\|下次小心\|当时没想清楚\|应该多测试' /Users/a1234/.openclaw/workspace/reflections/2026-06-05-falsy-coercion.md; echo "(exit=$?  ;  1=clean)"
```
Result:
0
exit=1

---

## 8. Reflection: nextjs-path (full file)

### Command
```
cat /Users/a1234/.openclaw/workspace/reflections/2026-06-05-nextjs-path.md
```

### Raw Output
```
# Reflection: Next.js `src/app/` vs `app/` Path Convention

> Date: 2026-06-05 | Severity: P0 | Recurrence: 1

## Context
Domain Benchmark Suite v1 — frontend-builder-agent.mjs 生成的 Next.js 项目输出到 `src/app/` 目录。10/10 项目 Build 失败（0/10 Build）。Next.js App Router 默认 pages directory 是 `app/`。

## Root Cause
Frontend Builder Agent 的初始设计内嵌了错误的路径假设。模板代码输出到 `src/app/`，但 Next.js `app/` router 不从 `src/app/` 读取。Tailwind content 配置和 tsconfig paths 也指向了错误路径。

## Fix
全局替换：
- `src/app/` → `app/`
- 更新 tsconfig paths 匹配 `app/`
- 更新 tailwind.config content 匹配 `app/**/*.{ts,tsx}`

## Pattern Class
**Path Convention Mismatch** — Generator/Builders 有硬编码路径假设，与实际 runtime 的 convention 不一致。

## Future Trigger
- Any Next.js project generation
- Any framework-specific builder agent creation
- Any path-dependent code generation

## Checklist
- [ ] 验证生成器输出目录与目标框架的 default convention 一致
- [ ] 在生成器写完第一版后立即跑 build smoke test
- [ ] tsconfig paths 与 tailwind content 与 pages directory 三者一致性检查

## Recurrence Count
1
```

### 7-field check
Result:
7

---

## 9. Reflection: ddl-leakage (full file)

### Command
```
cat /Users/a1234/.openclaw/workspace/reflections/2026-06-05-ddl-leakage.md
```

### Raw Output
```
# Reflection: DDL CONSTRAINT Leakage into TypeScript Interfaces

> Date: 2026-06-05 | Severity: P0 | Recurrence: 1

## Context
Backend Builder Agent (SF-04) — `schema.ts` 生成时 DDL PRIMARY KEY / FOREIGN KEY / CONSTRAINT 行被当作数据列，泄露进 TypeScript interface 定义。

Example: `"PRIMARY KEY (id)"` → parsed as column `PRIMARY` with type `KEY`, `FOREIGN KEY (user_id) REFERENCES users(id)` → parsed as column `FOREIGN` etc.

## Root Cause
DDL parser 没有区分 "column definition" 行和 "constraint" 行。`CREATE TABLE` 语句中的 CONSTRAINT 子句以特殊关键字开头（PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK），不应被解析为列定义。

## Fix
Added `isConstraintLine()` check before parsing each line as a column. Lines starting with `PRIMARY KEY`, `FOREIGN KEY`, `UNIQUE (`, `CHECK (` are skipped in column parsing.

## Pattern Class
**DDL-to-Code Mapping Error** — SQL DDL 的多层结构（column/constraint/index）被扁平化为单一映射时丢失语义。

## Future Trigger
- Any SQL schema → code generation
- Any DDL parser
- Any ORM code generator

## Checklist
- [ ] DDL 解析器必须有 column / constraint / index 三层分离
- [ ] Constraint 行识别：PRIMARY KEY, FOREIGN KEY, UNIQUE (, CHECK (
- [ ] 生成后验证：interface 字段数 ≤ 表列数（不含约束行）
- [ ] 跑 benchmark 验证所有领域 schema 生成正确

## Recurrence Count
1
```

### 7-field check
Result:
7

---

## 10. Reflection: jsx-template (full file)

### Command
```
cat /Users/a1234/.openclaw/workspace/reflections/2026-06-05-jsx-template.md
```

### Raw Output
```
# Reflection: JSX Template Ternary Nesting Syntax Error

> Date: 2026-06-05 | Severity: P0 | Recurrence: 1

## Context
Frontend Builder Agent (SF-03) — fallback page 模板中的三元表达式产生了语法错误。模板生成代码如 `{loading ? {<Spinner />} : {<div>No data</div>}}`。

## Root Cause
生成器模板中 JSX 三元表达式嵌套了多余的 `{}`。模板本身输出 `{` 字符，内嵌的 JSX 也带 `{` — 双层花括号导致 React 解析失败。

Incorrect output pattern: `{condition ? {<JSX />} : {<AnotherJSX />}}`
Correct: `{condition ? <JSX /> : <AnotherJSX />}` 或 `{condition ? (<JSX />) : null}`

## Fix
Fixed template to not wrap JSX branches in extra `{}`. The outer `{}` (JSX expression) already handles one level; inner JSX elements don't get re-wrapped.

## Pattern Class
**Template Code Generation Syntax** — 代码生成器的模板本身使用目标语言语法时，转义/嵌套层次需仔细处理。

## Future Trigger
- Any code generator that outputs JSX/TSX
- Any template-based code generation
- Any string-template code with nested braces/quotes

## Checklist
- [ ] 生成器模板验证：输出后立即 `tsc --noEmit` 检查语法
- [ ] JSX 三元表达式：禁止 `{cond ? {<X />} : {<Y />}}` 模式
- [ ] 模板中使用 `\`` 或字符串拼接替代包含反引号的模板字面量
- [ ] Benchmark smoke test 覆盖所有生成项目的 build

## Recurrence Count
1
```

### 7-field check
Result:
7

---

## 11. Old Reflection: 2026-06-03 (upgraded, head 30)

### Command
```
head -30 /Users/a1234/.openclaw/workspace/reflections/2026-06-03-agent-evolution.md
```

### Raw Output
```
# Reflection: Agent Evolution Mode — 四阶段全流程

> Date: 2026-06-03 | Severity: P0/P1 (multiple failures) | Recurrence: see individual patterns

## Context
深度学习 ECC/Headroom/CodeGraph → 提取能力 → 增强 OpenClaw。4 Phase，16 模块，7,000 行，5h（预估 42.5h）。

## Pattern Classes Extracted

### PC-1: SQLite FK Constraint (P0) — Pattern Class: SQL FK/DELETE semantic
- **Root Cause**: INSERT OR REPLACE causes rowid change → FK breaks
- **Fix**: ON CONFLICT DO UPDATE preserves original rowid
- **Future Trigger**: any SQL schema modification, batch inserts with FK

### PC-2: Heuristic False Positive (P1) — Pattern Class: single-signal detection
- **Root Cause**: `[2026-...` prefix triggered JSON detection without valid parse
- **Fix**: require 2+ signals (prefix + valid JSON.parse)
- **Future Trigger**: any heuristic/content-type detection logic

### PC-3: Nested Structure Parsing (P1) — Pattern Class: protocol-level vs structural parsing
- **Root Cause**: parser relied on structured JSON nesting, failed on content arrays
- **Fix**: match "type":"tool_result" byte patterns instead of tree traversal
- **Future Trigger**: any nested data structure parsing

### PC-4: Overly Aggressive Sampling (P2) — Pattern Class: lossy strategy without safety net
- **Root Cause**: TimeSeries strategy kept only anchor points (500→5), dropped errors
- **Fix**: include error/outlier detection alongside anchor selection
- **Future Trigger**: any sampling/compression strategy design

## 成功经验
```

### Pattern Class / Future Trigger / Recurrence count
Result:
10

---

## 12. Old Reflection: 2026-06-04 (upgraded, head 20)

### Command
```
head -20 /Users/a1234/.openclaw/workspace/reflections/2026-06-04-memory-audit.md
```

### Raw Output
```
# Reflection: Memory System Full Audit

> Date: 2026-06-04 | Severity: P0/P1/P2 mixed | Recurrence: 1

## Context
记忆系统全量审计 + 全链路修复。6 维度扫描（文件/远程/版本/自动化/索引/寄存器），P0(5)→P1(5)→P2(4)。

## Pattern Class: Infrastructure Drift

**Root Cause**: 脚本存在 ≠ 脚本在运行。Dream Cycle cron 从未配置，index.md 从未自动更新（15→75 条差距）。

**Fix**: 添加 3 个 cron jobs（Dream Cycle + Git push + Health check），session-compact.sh 加 pre-compact hook。

**Future Trigger**: any automated maintenance system, any cron-scheduled task, any script that "should run automatically"

**Checklist**:
- [ ] 新脚本添加后立即验证 cron/trigger 是否配置
- [ ] 定期检查 index/registers 的 freshness
- [ ] 引用即承诺——引用未创建的文件要么创建要么删引用

```

### Pattern Class / Future Trigger / Recurrence count
Result:
3

---

## 13. patterns/best-practices.md — full numbered entry list

### Command
```
grep -n '^[0-9]*\.' /Users/a1234/.openclaw/workspace/patterns/best-practices.md
```

### Raw Output
```
11:1. **写完即测，不等集成** — 每个模块 run 一次确认输出正确
12:2. **边界用例覆盖** — 空输入、超大输入、非法输入都要测
13:3. **零依赖优先** — 核心算法不自带 npm 依赖（例外: better-sqlite3 等已安装的稳定库）
14:4. **CLI + Library 双接口** — `node module.js` 和 `require('./module')` 都要能用
15:5. **passthrough 是默认** — 任何操作失败时返回原始输入，不丢数据
19:6. **Phase Isolation** — 分析/设计/实现三阶段不交叉
20:7. **先 MVP 再扩展** — 1-3h 出第一个可用版本，验证后扩展
21:8. **策略可插拔** — 用分发模式，新增策略不碰核心逻辑
22:9. **降级路径明确** — 每个操作至少 2 条降级路径
23:10. **配置可覆盖** — 全局默认 → 项目覆盖 → 运行时参数
27:11. **FK 约束用 ON CONFLICT DO UPDATE** — SQLite 的 REPLACE = DELETE+INSERT
28:12. **检测需多重信号** — 启发式规则必须 2+ 个信号同时匹配
29:13. **WAL 模式开** — 多进程读不阻塞写
30:14. **大文件分批处理** — 每 250 文件回收一次 WASM/内存
31:15. **stderr 和 stdout 分离** — 元数据用 stderr，数据用 stdout
35:16. **`||` vs `??` — 用 ?? 处理数字 0** — `value || default` 把 0/''/false 当 falsy。数字类用 `value ?? default`。已犯 2 次（Agent Evolution FK索引 + Cross-Agent Certification 评分排序）
36:17. **模板字面量反引号** — 模板内嵌反引号用 \` 转义或改用字符串拼接。不输出裸反引号到生成代码
37:18. **类型单数化** — entity 复数→单数（Albums→Album, Pets→Pet），但不碰 status/bus 等不可变词根
41:19. **Next.js 路径：app/ 不是 src/app/** — Next.js App Router 默认 pages in `app/`。生成器必须输出到 `app/` 目录
42:20. **DDL CONSTRAINT 泄露** — schema.ts 生成时 PRIMARY KEY / FOREIGN KEY / CONSTRAINT 行不能被解析为 TS interface 字段
43:21. **CreateInput 完整性** — generateTypes 必须包含所有实体（包括 User）→ CreateUserInput 不能缺失
44:22. **JSX 三元嵌套** — `{a ? {b} : {c}}` 错误。改为 `{a ? b : c}` 或 `{a ? (<Comp />) : null}`
48:23. **子 agent 并行分析** — 3 个项目同时 spawn，2-3 分钟完成
49:24. **子 agent 用 Pro 模型** — 代码/方案决策用 DeepSeek V4 Pro
50:25. **任务描述要包含完整输出路径** — 子 agent 不需要父 agent 上下文也能工作
51:26. **用 sessions_yield 等完成** — 不 poll loop
55:27. **Exit code 规范** — PASS/WARN→0, FAIL→1。不要 PASS 也 exit 1
56:28. **向后兼容** — 新增参数用 optional，不改既有函数签名。所有 PR 遵守零修改约束
60:29. **每完成一个 Phase 写 daily** — 不等到全部做完
61:30. **提取模式后立即写 patterns/** — "mental notes 不存活"
62:31. **MEMORY.md 尽量不动** — 在缓存线以上，每次改动全缓存爆炸
63:32. **Reflection 必须结构化** — 含 Pattern Class + Future Trigger + Checklist，禁止"以后注意"

### New sections proof
```
grep -n 'JavaScript.*TypeScript 陷阱\|Generator.*Builder 陷阱\|CI.*Release' /Users/a1234/.openclaw/workspace/patterns/best-practices.md
```
Result:
33:## JavaScript / TypeScript 陷阱
39:## Generator / Builder 陷阱
53:## CI / Release

---

## 14. patterns/design-patterns.md — Anti-Patterns

### Command
```
grep -n 'Anti-Patterns\|AP-[123]' /Users/a1234/.openclaw/workspace/patterns/design-patterns.md
```

### Raw Output
```
5:> 新增: Anti-Patterns (≥2 occurrences → promoted from reflections)
117:## Anti-Patterns (from failures, ≥2 occurrences)
119:### AP-1: Operator Coercion Trap (2 occurrences)
136:### AP-2: Generator Path Assumption (1 occurrence)
147:### AP-3: DDL Flat Mapping (1 occurrence)

### AP-1 full body
```
sed -n '119,138p' /Users/a1234/.openclaw/workspace/patterns/design-patterns.md
```

### Raw Output
```
### AP-1: Operator Coercion Trap (2 occurrences)

**问题**: JavaScript `||` 把 `0`/`""`/`false` 当 falsy，导致排序/评分/计数逻辑出错

**症状**:
- 排序结果反转（healthy=0 排到最后）
- FK 索引计数字段被跳过

**方案**: 数值/布尔默认值用 `??`（nullish coalescing），`||` 仅用于字符串默认值。
Grep `||` in scoring/ranking code.

**来源**:
- 2026-06-03: Agent Evolution FK 索引 `count || 0`
- 2026-06-05: PR-30 Cross-Agent Certification `order[status] || 6`

---

### AP-2: Generator Path Assumption (1 occurrence)

**问题**: Builder/Generator 有硬编码路径假设（如 `src/app/`），与实际 framework convention 不一致

---

## 15. vault.md — Promotion Log + Learning Loop

### Command
```
grep -n 'Learning Loop\|Promotion Log\|闭环\|1st→\|2nd→\|3rd→' /Users/a1234/.openclaw/workspace/memory/vault.md
```

### Raw Output
```
142:### Learning Loop v1 (2026-06-05 建立)
144:闭环架构：
152:1st→Reflection  2nd→Anti-Pattern  3rd→Best Practice  4th→Domain Checklist  5th→Hard Rule
159:### Promotion Log (≥2 occurrences tracked)

### Promotion Log table
```
sed -n '/Promotion Log/,/已验证模式/p' /Users/a1234/.openclaw/workspace/memory/vault.md
```

### Raw Output
```
### Promotion Log (≥2 occurrences tracked)

| Pattern Class | Count | Stage | Promoted To |
|--------------|-------|-------|------------|
| JS Falsy Coercion (`\|\|` vs `??`) | 2 | Anti-Pattern | patterns/design-patterns.md §AP-1 |
| Generator Path Assumption | 1 | Reflection | reflections/2026-06-05-nextjs-path.md |
| DDL Flat Mapping | 1 | Reflection | reflections/2026-06-05-ddl-leakage.md |
| JSX Template Nesting | 1 | Reflection | reflections/2026-06-05-jsx-template.md |

### 已验证模式 (从 Agent Evolution 提取)

---

## 16. MEMORY.md — Learning Loop reference

### Command
```
grep 'Learning Loop' /Users/a1234/.openclaw/workspace/MEMORY.md
```

### Raw Output
```
具体技巧：注释写 WHY · Fast-Path 入口 · 错误三分类 · 目录即模块 · 失败快速 · Pre-flight Check · Failure Replanning · Learning Loop (2026-06-05)

---

## 17. Reflections directory listing

### Command
```
ls -la /Users/a1234/.openclaw/workspace/reflections/
```

### Raw Output
```
total 56
drwx------   8 a1234  staff   256 Jun  5 22:37 .
drwx------  62 a1234  staff  1984 Jun  5 22:05 ..
-rw-------   1 a1234  staff  5304 Jun  5 22:41 2026-06-03-agent-evolution.md
-rw-------   1 a1234  staff  2630 Jun  5 22:41 2026-06-04-memory-audit.md
-rw-------   1 a1234  staff  1432 Jun  5 22:37 2026-06-05-ddl-leakage.md
-rw-------   1 a1234  staff  1258 Jun  5 22:36 2026-06-05-falsy-coercion.md
-rw-------   1 a1234  staff  1436 Jun  5 22:37 2026-06-05-jsx-template.md
-rw-------   1 a1234  staff  1265 Jun  5 22:36 2026-06-05-nextjs-path.md

---

## 18. Cross-file consistency: vault Promotion Log ↔ design-patterns AP counts

### vault says about AP-1
```
grep -A1 'JS Falsy Coercion' /Users/a1234/.openclaw/workspace/memory/vault.md | head -2
```
Result:
| JS Falsy Coercion (`\|\|` vs `??`) | 2 | Anti-Pattern | patterns/design-patterns.md §AP-1 |
| Generator Path Assumption | 1 | Reflection | reflections/2026-06-05-nextjs-path.md |

### design-patterns says about AP-1
```
grep 'AP-1.*occurrences' /Users/a1234/.openclaw/workspace/patterns/design-patterns.md
```
Result:
### AP-1: Operator Coercion Trap (2 occurrences)

### vault says about Path Assumption
```
grep -A1 'Generator Path' /Users/a1234/.openclaw/workspace/memory/vault.md
```
Result:
| Generator Path Assumption | 1 | Reflection | reflections/2026-06-05-nextjs-path.md |
| DDL Flat Mapping | 1 | Reflection | reflections/2026-06-05-ddl-leakage.md |

### design-patterns says about AP-2
```
grep 'AP-2.*occurrence' /Users/a1234/.openclaw/workspace/patterns/design-patterns.md
```
Result:
### AP-2: Generator Path Assumption (1 occurrence)

---

## 19. 4 new reflections — aggregate 7-field + banned check

### Command
```
for f in /Users/a1234/.openclaw/workspace/reflections/2026-06-05-*.md; do
  name=$(basename "$f")
  fields=$(grep -c '^## Context\|^## Root Cause\|^## Fix\|^## Pattern Class\|^## Future Trigger\|^## Checklist\|^## Recurrence' "$f")
  banned=$(grep -ic '以后注意\|下次小心\|当时没想清楚\|应该多测试' "$f" || echo 0)
  echo "$name: fields=$fields/7 banned=$banned"
done
```

### Raw Output
```
2026-06-05-ddl-leakage.md: fields=7/7 banned=0
0
2026-06-05-falsy-coercion.md: fields=7/7 banned=0
0
2026-06-05-jsx-template.md: fields=7/7 banned=0
0
2026-06-05-nextjs-path.md: fields=7/7 banned=0
0

---

## 20. AGENTS.md section structure (numbering integrity)

### Command
```
grep -n '^###\|^##' /Users/a1234/.openclaw/workspace/AGENTS.md | head -35
```

### Raw Output
```
5:## Cache Stability ⚡
12:## Session Startup
18:## Execution Protocol — Planning Layer 🔵
24:### 0. Complexity Classification (MUST run first)
52:### 1. Planning Protocol (Complex Tasks ONLY)
57:## PLAN
58:### Goal
61:### Subtasks
66:### Risks
70:### Verification Strategy
78:### 2. Pre-flight Check (Complex Tasks ONLY)
82:#### 2a. Dependency Scan
90:#### 2b. Learning Context Injector (MANDATORY — 3 searches)
109:### Injected Risks (from Learning Context)
115:#### 2c. Domain Checklist Injection
156:### 3. Failure Replanning Protocol
183:### 4. Verification Protocol (Complex Tasks ONLY)
188:## VERIFICATION
208:### 5. Auto-Capture Trigger — COMPLETE Rule Set (after ANY failure)
240:## Learning Loop 🔄
245:### Loop Architecture
267:### Promotion Rules
277:### Quality Gate for Reflections
291:### Storage Locations
306:## Memory
314:## Red Lines
322:## External vs Internal
327:## Group Chats
335:## Security Baseline 🔒
344:## Heartbeats

---

## END OF VERIFICATION LOG

- Total checks: 20
- Files verified: AGENTS.md, patterns/best-practices.md, patterns/design-patterns.md, memory/vault.md, MEMORY.md
- Reflections: 2026-06-05-falsy-coercion.md, 2026-06-05-nextjs-path.md, 2026-06-05-ddl-leakage.md, 2026-06-05-jsx-template.md
- Old reflections upgraded: 2026-06-03-agent-evolution.md, 2026-06-04-memory-audit.md
- Cross-file consistency: vault Promotion Log ↔ design-patterns AP counts — MATCH
- All 4 new reflections: 7/7 required fields, 0 banned phrases
- ARCHIVED for future audit traceability
