rsi-loop 0.1.0__tar.gz

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,29 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ permissions:
8
+ id-token: write # Required for trusted publishing
9
+
10
+ jobs:
11
+ publish:
12
+ runs-on: ubuntu-latest
13
+ environment: pypi
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+
17
+ - name: Set up Python
18
+ uses: actions/setup-python@v5
19
+ with:
20
+ python-version: "3.12"
21
+
22
+ - name: Install build tools
23
+ run: pip install build
24
+
25
+ - name: Build package
26
+ run: python -m build
27
+
28
+ - name: Publish to PyPI
29
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,7 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .coverage
4
+ *.egg-info/
5
+ dist/
6
+ build/
7
+ .venv/
@@ -0,0 +1,19 @@
1
+ # Changelog
2
+
3
+ ## [0.1.0] - 2026-02-22
4
+
5
+ ### Added
6
+ - Initial release
7
+ - Core modules: Observer, Analyzer, Fixer, RSILoop
8
+ - Type definitions: Outcome, Pattern, Fix, Config
9
+ - Auto-classification of error messages
10
+ - Recurrence detection (3+ occurrences in window)
11
+ - Health scoring (0.0–1.0, recency-weighted)
12
+ - Cross-source correlation for related issues
13
+ - Error message clustering with normalization
14
+ - Safe auto-fix for configurable categories
15
+ - Fix proposal generation for unsafe categories
16
+ - Background loop with configurable interval
17
+ - Integrations: Claude Code adapter, generic file-based adapter, webhook adapter
18
+ - Full test suite with 85%+ coverage
19
+ - CI with Python 3.10/3.11/3.12, pytest, ruff
rsi_loop-0.1.0/LICENSE ADDED
@@ -0,0 +1,189 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work.
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean any work of authorship, including
48
+ the original version of the Work and any modifications or additions
49
+ to that Work or Derivative Works thereof, that is intentionally
50
+ submitted to the Licensor for inclusion in the Work by the copyright owner
51
+ or by an individual or Legal Entity authorized to submit on behalf of
52
+ the copyright owner. For the purposes of this definition, "submitted"
53
+ means any form of electronic, verbal, or written communication sent
54
+ to the Licensor or its representatives, including but not limited to
55
+ communication on electronic mailing lists, source code control systems,
56
+ and issue tracking systems that are managed by, or on behalf of, the
57
+ Licensor for the purpose of discussing and improving the Work, but
58
+ excluding communication that is conspicuously marked or otherwise
59
+ designated in writing by the copyright owner as "Not a Contribution."
60
+
61
+ "Contributor" shall mean Licensor and any individual or Legal Entity
62
+ on behalf of whom a Contribution has been received by the Licensor and
63
+ subsequently incorporated within the Work.
64
+
65
+ 2. Grant of Copyright License. Subject to the terms and conditions of
66
+ this License, each Contributor hereby grants to You a perpetual,
67
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
68
+ copyright license to reproduce, prepare Derivative Works of,
69
+ publicly display, publicly perform, sublicense, and distribute the
70
+ Work and such Derivative Works in Source or Object form.
71
+
72
+ 3. Grant of Patent License. Subject to the terms and conditions of
73
+ this License, each Contributor hereby grants to You a perpetual,
74
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
75
+ (except as stated in this section) patent license to make, have made,
76
+ use, offer to sell, sell, import, and otherwise transfer the Work,
77
+ where such license applies only to those patent claims licensable
78
+ by such Contributor that are necessarily infringed by their
79
+ Contribution(s) alone or by combination of their Contribution(s)
80
+ with the Work to which such Contribution(s) was submitted. If You
81
+ institute patent litigation against any entity (including a
82
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
83
+ or a Contribution incorporated within the Work constitutes direct
84
+ or contributory patent infringement, then any patent licenses
85
+ granted to You under this License for that Work shall terminate
86
+ as of the date such litigation is filed.
87
+
88
+ 4. Redistribution. You may reproduce and distribute copies of the
89
+ Work or Derivative Works thereof in any medium, with or without
90
+ modifications, and in Source or Object form, provided that You
91
+ meet the following conditions:
92
+
93
+ (a) You must give any other recipients of the Work or
94
+ Derivative Works a copy of this License; and
95
+
96
+ (b) You must cause any modified files to carry prominent notices
97
+ stating that You changed the files; and
98
+
99
+ (c) You must retain, in the Source form of any Derivative Works
100
+ that You distribute, all copyright, patent, trademark, and
101
+ attribution notices from the Source form of the Work,
102
+ excluding those notices that do not pertain to any part of
103
+ the Derivative Works; and
104
+
105
+ (d) If the Work includes a "NOTICE" text file as part of its
106
+ distribution, then any Derivative Works that You distribute must
107
+ include a readable copy of the attribution notices contained
108
+ within such NOTICE file, excluding any notices that do not
109
+ pertain to any part of the Derivative Works, in at least one
110
+ of the following places: within a NOTICE text file distributed
111
+ as part of the Derivative Works; within the Source form or
112
+ documentation, if provided along with the Derivative Works; or,
113
+ within a display generated by the Derivative Works, if and
114
+ wherever such third-party notices normally appear. The contents
115
+ of the NOTICE file are for informational purposes only and
116
+ do not modify the License. You may add Your own attribution
117
+ notices within Derivative Works that You distribute, alongside
118
+ or as an addendum to the NOTICE text from the Work, provided
119
+ that such additional attribution notices cannot be construed
120
+ as modifying the License.
121
+
122
+ You may add Your own copyright statement to Your modifications and
123
+ may provide additional or different license terms and conditions
124
+ for use, reproduction, or distribution of Your modifications, or
125
+ for any such Derivative Works as a whole, provided Your use,
126
+ reproduction, and distribution of the Work otherwise complies with
127
+ the conditions stated in this License.
128
+
129
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
130
+ any Contribution intentionally submitted for inclusion in the Work
131
+ by You to the Licensor shall be under the terms and conditions of
132
+ this License, without any additional terms or conditions.
133
+ Notwithstanding the above, nothing herein shall supersede or modify
134
+ the terms of any separate license agreement you may have executed
135
+ with Licensor regarding such Contributions.
136
+
137
+ 6. Trademarks. This License does not grant permission to use the trade
138
+ names, trademarks, service marks, or product names of the Licensor,
139
+ except as required for reasonable and customary use in describing the
140
+ origin of the Work and reproducing the content of the NOTICE file.
141
+
142
+ 7. Disclaimer of Warranty. Unless required by applicable law or
143
+ agreed to in writing, Licensor provides the Work (and each
144
+ Contributor provides its Contributions) on an "AS IS" BASIS,
145
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
146
+ implied, including, without limitation, any warranties or conditions
147
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
148
+ PARTICULAR PURPOSE. You are solely responsible for determining the
149
+ appropriateness of using or redistributing the Work and assume any
150
+ risks associated with Your exercise of permissions under this License.
151
+
152
+ 8. Limitation of Liability. In no event and under no legal theory,
153
+ whether in tort (including negligence), contract, or otherwise,
154
+ unless required by applicable law (such as deliberate and grossly
155
+ negligent acts) or agreed to in writing, shall any Contributor be
156
+ liable to You for damages, including any direct, indirect, special,
157
+ incidental, or consequential damages of any character arising as a
158
+ result of this License or out of the use or inability to use the
159
+ Work (including but not limited to damages for loss of goodwill,
160
+ work stoppage, computer failure or malfunction, or any and all
161
+ other commercial damages or losses), even if such Contributor
162
+ has been advised of the possibility of such damages.
163
+
164
+ 9. Accepting Warranty or Additional Liability. While redistributing
165
+ the Work or Derivative Works thereof, You may choose to offer,
166
+ and charge a fee for, acceptance of support, warranty, indemnity,
167
+ or other liability obligations and/or rights consistent with this
168
+ License. However, in accepting such obligations, You may act only
169
+ on Your own behalf and on Your sole responsibility, not on behalf
170
+ of any other Contributor, and only if You agree to indemnify,
171
+ defend, and hold each Contributor harmless for any liability
172
+ incurred by, or claims asserted against, such Contributor by reason
173
+ of your accepting any such warranty or additional liability.
174
+
175
+ END OF TERMS AND CONDITIONS
176
+
177
+ Copyright 2026 ClawInfra
178
+
179
+ Licensed under the Apache License, Version 2.0 (the "License");
180
+ you may not use this file except in compliance with the License.
181
+ You may obtain a copy of the License at
182
+
183
+ http://www.apache.org/licenses/LICENSE-2.0
184
+
185
+ Unless required by applicable law or agreed to in writing, software
186
+ distributed under the License is distributed on an "AS IS" BASIS,
187
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
188
+ See the License for the specific language governing permissions and
189
+ limitations under the License.
@@ -0,0 +1,151 @@
1
+ Metadata-Version: 2.4
2
+ Name: rsi-loop
3
+ Version: 0.1.0
4
+ Summary: Universal self-improvement loop for AI agents. Observe → Analyze → Fix → Verify.
5
+ Project-URL: Homepage, https://github.com/clawinfra/rsi-loop
6
+ Project-URL: Repository, https://github.com/clawinfra/rsi-loop
7
+ Project-URL: Issues, https://github.com/clawinfra/rsi-loop/issues
8
+ Author-email: ClawInfra <alex.chen31337@gmail.com>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: agents,ai,feedback-loop,rsi,self-improvement
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Requires-Python: >=3.10
21
+ Provides-Extra: dev
22
+ Requires-Dist: pytest-cov>=5.0; extra == 'dev'
23
+ Requires-Dist: pytest>=8.0; extra == 'dev'
24
+ Requires-Dist: ruff>=0.4; extra == 'dev'
25
+ Provides-Extra: webhook
26
+ Requires-Dist: flask>=3.0; extra == 'webhook'
27
+ Description-Content-Type: text/markdown
28
+
29
+ # 🔄 RSI Loop
30
+
31
+ [![CI](https://github.com/clawinfra/rsi-loop/actions/workflows/ci.yml/badge.svg)](https://github.com/clawinfra/rsi-loop/actions/workflows/ci.yml)
32
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
33
+ [![Python](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://python.org)
34
+
35
+ **Every AI agent makes mistakes. RSI Loop makes them learn.**
36
+
37
+ ---
38
+
39
+ ## The Problem
40
+
41
+ AI agents repeat the same failures. They hit rate limits, return empty responses, lose context, pick the wrong model — and do it all again next session. There's no feedback loop. No memory of what went wrong. No automatic improvement.
42
+
43
+ RSI Loop is the missing primitive: a universal **recursive self-improvement** loop that works with *any* agent framework.
44
+
45
+ ## How It Works
46
+
47
+ ```
48
+ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐
49
+ │ OBSERVE │────▶│ ANALYZE │────▶│ FIX │────▶│ VERIFY │
50
+ │ │ │ │ │ │ │ │
51
+ │ Record │ │ Detect │ │ Generate │ │ Check │
52
+ │ outcomes │ │ patterns │ │ & apply │ │ health │
53
+ └──────────┘ └──────────┘ └──────────┘ └────┬─────┘
54
+ ▲ │
55
+ └───────────────────────────────────────────────────┘
56
+ ```
57
+
58
+ 1. **Observe** — Record task outcomes: success/failure, quality, errors, model used, duration
59
+ 2. **Analyze** — Detect patterns: recurring failures, error clusters, cross-source correlations
60
+ 3. **Fix** — Auto-fix safe categories (routing, retries, thresholds); propose fixes for the rest
61
+ 4. **Verify** — Track health score over time; confirm fixes reduced failure rates
62
+
63
+ ## Quick Start
64
+
65
+ ```bash
66
+ uv add rsi-loop
67
+ ```
68
+
69
+ > **Not using uv?** `uv add rsi-loop` works too.
70
+
71
+ ```python
72
+ from rsi_loop import RSILoop
73
+
74
+ loop = RSILoop()
75
+ loop.observer.record_simple("code_generation", success=True, model="sonnet-4.6")
76
+ loop.observer.record_simple("api_call", success=False, error="429 Too Many Requests")
77
+ loop.observer.record_simple("api_call", success=False, error="429 Too Many Requests")
78
+ loop.observer.record_simple("api_call", success=False, error="429 Too Many Requests")
79
+
80
+ # Run improvement cycle
81
+ patterns = loop.run_cycle()
82
+ print(f"Health: {loop.health_score():.0%}")
83
+ print(f"Patterns found: {len(patterns)}")
84
+ ```
85
+
86
+ ## Framework Integrations
87
+
88
+ ### Claude Code / OpenClaw
89
+
90
+ ```python
91
+ from rsi_loop.integrations.claude_code import ClaudeCodeAdapter
92
+
93
+ adapter = ClaudeCodeAdapter(data_dir="./rsi_data")
94
+ adapter.on_task_complete("code_review", success=True, model="claude-sonnet-4")
95
+ adapter.on_model_fallback("claude-opus-4", "claude-sonnet-4", "rate_limit")
96
+ adapter.on_session_reset()
97
+ ```
98
+
99
+ ### Generic (File-Based)
100
+
101
+ Drop JSON files into a watch directory — works with any agent:
102
+
103
+ ```python
104
+ from rsi_loop.integrations.generic import GenericAdapter
105
+
106
+ adapter = GenericAdapter(watch_dir="./rsi_inbox")
107
+ # Your agent writes: {"task": "search", "success": false, "error": "timeout"}
108
+ # RSI picks it up automatically
109
+ outcomes = adapter.poll()
110
+ ```
111
+
112
+ ### Webhook
113
+
114
+ ```python
115
+ from rsi_loop.integrations.webhook import WebhookAdapter
116
+
117
+ app = WebhookAdapter(data_dir="./rsi_data").create_app()
118
+ # POST /observe {"task": "code_gen", "success": true, "quality": 4}
119
+ # GET /health
120
+ # GET /patterns
121
+ ```
122
+
123
+ ## Features
124
+
125
+ - **Auto-classification** — Categorizes errors automatically: rate_limit, empty_response, timeout, context_loss, etc.
126
+ - **Recurrence detection** — Flags issues that repeat 3+ times within the analysis window
127
+ - **Health scoring** — 0.0 (broken) to 1.0 (healthy), recency-weighted
128
+ - **Cross-source correlation** — Detects related issues across different agent sources
129
+ - **Error clustering** — Groups similar error messages even with different IDs/numbers
130
+ - **Safe auto-fix** — Automatically applies fixes for safe categories (routing, retries, thresholds)
131
+ - **Fix proposals** — Generates detailed proposals for unsafe categories, saved for human review
132
+ - **Background loop** — Run continuous improvement cycles in a background thread
133
+ - **Framework-agnostic** — Works with Claude Code, Cursor, Codex, or any custom agent
134
+ - **Zero dependencies** — Core package has no external dependencies (integrations optional)
135
+
136
+ ## Documentation
137
+
138
+ - [Architecture](docs/architecture.md) — How RSI Loop works internally
139
+ - [Source Taxonomy](docs/sources.md) — Source classification and cross-source correlation
140
+ - [Auto-Fix](docs/auto_fix.md) — How auto-fix works, safe categories, and fix templates
141
+
142
+ ## Examples
143
+
144
+ - [Claude Code Setup](examples/claude_code_setup.md)
145
+ - [Cursor Setup](examples/cursor_setup.md)
146
+ - [Generic Agent Setup](examples/generic_agent_setup.md)
147
+ - [Quick Start Script](examples/quick_start.py)
148
+
149
+ ---
150
+
151
+ Built by [ClawInfra](https://github.com/clawinfra) — infrastructure for autonomous agents.
@@ -0,0 +1,123 @@
1
+ # 🔄 RSI Loop
2
+
3
+ [![CI](https://github.com/clawinfra/rsi-loop/actions/workflows/ci.yml/badge.svg)](https://github.com/clawinfra/rsi-loop/actions/workflows/ci.yml)
4
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
5
+ [![Python](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://python.org)
6
+
7
+ **Every AI agent makes mistakes. RSI Loop makes them learn.**
8
+
9
+ ---
10
+
11
+ ## The Problem
12
+
13
+ AI agents repeat the same failures. They hit rate limits, return empty responses, lose context, pick the wrong model — and do it all again next session. There's no feedback loop. No memory of what went wrong. No automatic improvement.
14
+
15
+ RSI Loop is the missing primitive: a universal **recursive self-improvement** loop that works with *any* agent framework.
16
+
17
+ ## How It Works
18
+
19
+ ```
20
+ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐
21
+ │ OBSERVE │────▶│ ANALYZE │────▶│ FIX │────▶│ VERIFY │
22
+ │ │ │ │ │ │ │ │
23
+ │ Record │ │ Detect │ │ Generate │ │ Check │
24
+ │ outcomes │ │ patterns │ │ & apply │ │ health │
25
+ └──────────┘ └──────────┘ └──────────┘ └────┬─────┘
26
+ ▲ │
27
+ └───────────────────────────────────────────────────┘
28
+ ```
29
+
30
+ 1. **Observe** — Record task outcomes: success/failure, quality, errors, model used, duration
31
+ 2. **Analyze** — Detect patterns: recurring failures, error clusters, cross-source correlations
32
+ 3. **Fix** — Auto-fix safe categories (routing, retries, thresholds); propose fixes for the rest
33
+ 4. **Verify** — Track health score over time; confirm fixes reduced failure rates
34
+
35
+ ## Quick Start
36
+
37
+ ```bash
38
+ uv add rsi-loop
39
+ ```
40
+
41
+ > **Not using uv?** `uv add rsi-loop` works too.
42
+
43
+ ```python
44
+ from rsi_loop import RSILoop
45
+
46
+ loop = RSILoop()
47
+ loop.observer.record_simple("code_generation", success=True, model="sonnet-4.6")
48
+ loop.observer.record_simple("api_call", success=False, error="429 Too Many Requests")
49
+ loop.observer.record_simple("api_call", success=False, error="429 Too Many Requests")
50
+ loop.observer.record_simple("api_call", success=False, error="429 Too Many Requests")
51
+
52
+ # Run improvement cycle
53
+ patterns = loop.run_cycle()
54
+ print(f"Health: {loop.health_score():.0%}")
55
+ print(f"Patterns found: {len(patterns)}")
56
+ ```
57
+
58
+ ## Framework Integrations
59
+
60
+ ### Claude Code / OpenClaw
61
+
62
+ ```python
63
+ from rsi_loop.integrations.claude_code import ClaudeCodeAdapter
64
+
65
+ adapter = ClaudeCodeAdapter(data_dir="./rsi_data")
66
+ adapter.on_task_complete("code_review", success=True, model="claude-sonnet-4")
67
+ adapter.on_model_fallback("claude-opus-4", "claude-sonnet-4", "rate_limit")
68
+ adapter.on_session_reset()
69
+ ```
70
+
71
+ ### Generic (File-Based)
72
+
73
+ Drop JSON files into a watch directory — works with any agent:
74
+
75
+ ```python
76
+ from rsi_loop.integrations.generic import GenericAdapter
77
+
78
+ adapter = GenericAdapter(watch_dir="./rsi_inbox")
79
+ # Your agent writes: {"task": "search", "success": false, "error": "timeout"}
80
+ # RSI picks it up automatically
81
+ outcomes = adapter.poll()
82
+ ```
83
+
84
+ ### Webhook
85
+
86
+ ```python
87
+ from rsi_loop.integrations.webhook import WebhookAdapter
88
+
89
+ app = WebhookAdapter(data_dir="./rsi_data").create_app()
90
+ # POST /observe {"task": "code_gen", "success": true, "quality": 4}
91
+ # GET /health
92
+ # GET /patterns
93
+ ```
94
+
95
+ ## Features
96
+
97
+ - **Auto-classification** — Categorizes errors automatically: rate_limit, empty_response, timeout, context_loss, etc.
98
+ - **Recurrence detection** — Flags issues that repeat 3+ times within the analysis window
99
+ - **Health scoring** — 0.0 (broken) to 1.0 (healthy), recency-weighted
100
+ - **Cross-source correlation** — Detects related issues across different agent sources
101
+ - **Error clustering** — Groups similar error messages even with different IDs/numbers
102
+ - **Safe auto-fix** — Automatically applies fixes for safe categories (routing, retries, thresholds)
103
+ - **Fix proposals** — Generates detailed proposals for unsafe categories, saved for human review
104
+ - **Background loop** — Run continuous improvement cycles in a background thread
105
+ - **Framework-agnostic** — Works with Claude Code, Cursor, Codex, or any custom agent
106
+ - **Zero dependencies** — Core package has no external dependencies (integrations optional)
107
+
108
+ ## Documentation
109
+
110
+ - [Architecture](docs/architecture.md) — How RSI Loop works internally
111
+ - [Source Taxonomy](docs/sources.md) — Source classification and cross-source correlation
112
+ - [Auto-Fix](docs/auto_fix.md) — How auto-fix works, safe categories, and fix templates
113
+
114
+ ## Examples
115
+
116
+ - [Claude Code Setup](examples/claude_code_setup.md)
117
+ - [Cursor Setup](examples/cursor_setup.md)
118
+ - [Generic Agent Setup](examples/generic_agent_setup.md)
119
+ - [Quick Start Script](examples/quick_start.py)
120
+
121
+ ---
122
+
123
+ Built by [ClawInfra](https://github.com/clawinfra) — infrastructure for autonomous agents.
@@ -0,0 +1,72 @@
1
+ # Architecture
2
+
3
+ RSI Loop implements a four-phase recursive self-improvement cycle.
4
+
5
+ ## Components
6
+
7
+ ### Observer
8
+ Records task outcomes to a JSONL store. Each outcome captures: task type, success/failure, quality (1-5), error messages, model used, duration, and arbitrary tags/metadata.
9
+
10
+ **Auto-classification**: Error messages are automatically classified into issue types (rate_limit, timeout, empty_response, context_loss, etc.) using keyword matching.
11
+
12
+ **Storage**: Outcomes are appended to `{data_dir}/outcomes.jsonl` — one JSON object per line.
13
+
14
+ ### Analyzer
15
+ Scans recorded outcomes and detects improvement patterns.
16
+
17
+ **Pattern detection** works two ways:
18
+ 1. **Task/issue grouping** — Groups outcomes by `(task_type, issue)` pairs. Patterns with ≥2 occurrences (or ≥1 for high-severity issues) are surfaced.
19
+ 2. **Error clustering** — Normalizes error messages (strips IDs, numbers) and groups similar errors. Catches patterns that span multiple task types.
20
+
21
+ **Health score**: `success_rate × (avg_quality / 5.0)`, computed over the analysis window. Range: 0.0 (broken) to 1.0 (healthy).
22
+
23
+ **Cross-source correlation**: Detects when related issues (e.g., session_reset + context_loss) appear across different agent sources, suggesting systemic problems.
24
+
25
+ **Recurrence detection**: Compares current patterns against the previous analysis cycle. Recurring patterns are flagged with trend direction (increasing/stable).
26
+
27
+ ### Fixer
28
+ Generates fix proposals for detected patterns.
29
+
30
+ **Safe categories** (configurable, default: routing_config, threshold_tuning, retry_logic) get auto-applied status. Everything else produces a draft proposal saved to `{data_dir}/proposals/` for human review.
31
+
32
+ ### RSILoop
33
+ The main orchestrator. Ties Observer, Analyzer, and Fixer together. Provides:
34
+ - `run_cycle()` — One full observe → analyze → fix pass
35
+ - `health_score()` — Current health
36
+ - `start_background(interval)` — Background improvement loop in a daemon thread
37
+
38
+ ## Data Flow
39
+
40
+ ```
41
+ Agent task completes
42
+
43
+
44
+ Observer.record_simple(task, success, error, model)
45
+ │ auto-classify issues from error message
46
+ │ append to outcomes.jsonl
47
+
48
+ Analyzer.analyze()
49
+ │ load outcomes from window
50
+ │ group by (task_type, issue)
51
+ │ cluster similar errors
52
+ │ detect recurrences
53
+ │ compute health score
54
+
55
+ Fixer.propose_and_apply(pattern)
56
+ │ generate fix proposal
57
+ │ auto-apply if safe category
58
+ │ save proposal to proposals/
59
+
60
+ Health score improves (or doesn't → next cycle catches it)
61
+ ```
62
+
63
+ ## Storage Layout
64
+
65
+ ```
66
+ {data_dir}/
67
+ ├── outcomes.jsonl # Raw outcome records (append-only)
68
+ ├── patterns.json # Latest analysis results (overwritten each cycle)
69
+ └── proposals/ # Fix proposals (one JSON file per fix)
70
+ ├── abc12345.json
71
+ └── def67890.json
72
+ ```
@@ -0,0 +1,78 @@
1
+ # Auto-Fix
2
+
3
+ RSI Loop can automatically apply fixes for "safe" categories — changes that are low-risk and well-understood.
4
+
5
+ ## Safe Categories
6
+
7
+ By default, three fix types are considered safe for auto-application:
8
+
9
+ | Category | Description | Example |
10
+ |----------|-------------|---------|
11
+ | `routing_config` | Model routing changes | Adjusting fallback chains |
12
+ | `threshold_tuning` | Timeout/threshold adjustments | Increasing request timeouts |
13
+ | `retry_logic` | Adding/adjusting retry behavior | Backoff for rate-limited endpoints |
14
+
15
+ Configure via `Config.safe_categories`:
16
+
17
+ ```python
18
+ from rsi_loop import RSILoop, Config
19
+
20
+ loop = RSILoop(Config(
21
+ safe_categories=["routing_config", "retry_logic", "threshold_tuning", "investigation"]
22
+ ))
23
+ ```
24
+
25
+ ## Fix Templates
26
+
27
+ Each issue type maps to a fix template:
28
+
29
+ | Issue | Fix Type | Action |
30
+ |-------|----------|--------|
31
+ | rate_limit | retry_logic | Add/increase retry backoff |
32
+ | model_fallback | routing_config | Update fallback chain |
33
+ | wrong_model_tier | routing_config | Adjust tier thresholds |
34
+ | cost_overrun | routing_config | Lower cost ceiling |
35
+ | slow_response | threshold_tuning | Increase timeouts |
36
+ | timeout | threshold_tuning | Increase timeouts |
37
+ | empty_response | retry_logic | Add empty-response detection and retry |
38
+ | session_reset | investigation | Investigate (not auto-fixable by default) |
39
+
40
+ ## How It Works
41
+
42
+ 1. `Fixer.propose(pattern)` generates a `Fix` with changes and a `safe_category`
43
+ 2. `Fixer.apply_if_safe(fix)` checks if `safe_category` is in `Config.safe_categories`
44
+ 3. If safe → status set to "applied", proposal saved
45
+ 4. If not safe → status stays "draft", proposal saved for human review
46
+
47
+ **Important**: Even "applied" fixes only update their status in the proposal file. Actual code/config changes require agent-specific implementation — RSI Loop tells you *what* to fix, your agent decides *how*.
48
+
49
+ ## Proposals
50
+
51
+ All fix proposals are saved as JSON files in `{data_dir}/proposals/`:
52
+
53
+ ```json
54
+ {
55
+ "id": "abc12345",
56
+ "pattern_id": "api_call-rate_lim-5",
57
+ "type": "auto",
58
+ "status": "applied",
59
+ "target": "relevant integration code",
60
+ "changes": [
61
+ {
62
+ "target": "relevant integration code",
63
+ "action": "Add retry with backoff for 'rate_limit' errors",
64
+ "detail": "Detected 5x occurrences"
65
+ }
66
+ ],
67
+ "safe_category": "retry_logic",
68
+ "description": "Add/increase retry backoff for rate-limited endpoints"
69
+ }
70
+ ```
71
+
72
+ ## Disabling Auto-Fix
73
+
74
+ ```python
75
+ loop = RSILoop(Config(auto_fix_enabled=False))
76
+ # Or set safe_categories to empty:
77
+ loop = RSILoop(Config(safe_categories=[]))
78
+ ```