@miller-tech/uap 1.136.2 → 1.137.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/benchmarks/paired/report.d.ts +13 -0
  3. package/dist/benchmarks/paired/report.d.ts.map +1 -1
  4. package/dist/benchmarks/paired/report.js +29 -3
  5. package/dist/benchmarks/paired/report.js.map +1 -1
  6. package/dist/benchmarks/paired/types.d.ts +59 -0
  7. package/dist/benchmarks/paired/types.d.ts.map +1 -1
  8. package/dist/benchmarks/paired/types.js +60 -0
  9. package/dist/benchmarks/paired/types.js.map +1 -1
  10. package/dist/bin/cli.js +30 -0
  11. package/dist/bin/cli.js.map +1 -1
  12. package/dist/cli/deliver.d.ts.map +1 -1
  13. package/dist/cli/deliver.js +111 -7
  14. package/dist/cli/deliver.js.map +1 -1
  15. package/dist/cli/react.d.ts.map +1 -1
  16. package/dist/cli/react.js +18 -0
  17. package/dist/cli/react.js.map +1 -1
  18. package/dist/cli/self-tuning.d.ts +33 -0
  19. package/dist/cli/self-tuning.d.ts.map +1 -0
  20. package/dist/cli/self-tuning.js +139 -0
  21. package/dist/cli/self-tuning.js.map +1 -0
  22. package/dist/cli/tune-adapter.d.ts +8 -0
  23. package/dist/cli/tune-adapter.d.ts.map +1 -0
  24. package/dist/cli/tune-adapter.js +26 -0
  25. package/dist/cli/tune-adapter.js.map +1 -0
  26. package/dist/config/settings-registry.d.ts.map +1 -1
  27. package/dist/config/settings-registry.js +10 -0
  28. package/dist/config/settings-registry.js.map +1 -1
  29. package/dist/coordination/adaptation-signal.d.ts +19 -0
  30. package/dist/coordination/adaptation-signal.d.ts.map +1 -0
  31. package/dist/coordination/adaptation-signal.js +36 -0
  32. package/dist/coordination/adaptation-signal.js.map +1 -0
  33. package/dist/delivery/agentic-executor.d.ts +16 -1
  34. package/dist/delivery/agentic-executor.d.ts.map +1 -1
  35. package/dist/delivery/agentic-executor.js +45 -4
  36. package/dist/delivery/agentic-executor.js.map +1 -1
  37. package/dist/delivery/decompose.d.ts +27 -0
  38. package/dist/delivery/decompose.d.ts.map +1 -1
  39. package/dist/delivery/decompose.js +31 -1
  40. package/dist/delivery/decompose.js.map +1 -1
  41. package/dist/delivery/repair-escalation.d.ts +49 -0
  42. package/dist/delivery/repair-escalation.d.ts.map +1 -0
  43. package/dist/delivery/repair-escalation.js +83 -0
  44. package/dist/delivery/repair-escalation.js.map +1 -0
  45. package/dist/delivery/verifier-ladder.d.ts +47 -0
  46. package/dist/delivery/verifier-ladder.d.ts.map +1 -1
  47. package/dist/delivery/verifier-ladder.js +87 -1
  48. package/dist/delivery/verifier-ladder.js.map +1 -1
  49. package/dist/self-harness/mods.d.ts +20 -1
  50. package/dist/self-harness/mods.d.ts.map +1 -1
  51. package/dist/self-harness/mods.js +41 -0
  52. package/dist/self-harness/mods.js.map +1 -1
  53. package/dist/self-harness/orchestrator.js +4 -0
  54. package/dist/self-harness/orchestrator.js.map +1 -1
  55. package/dist/self-harness/transfer.d.ts.map +1 -1
  56. package/dist/self-harness/transfer.js +2 -0
  57. package/dist/self-harness/transfer.js.map +1 -1
  58. package/dist/self-tuning/flag-writer.d.ts +48 -0
  59. package/dist/self-tuning/flag-writer.d.ts.map +1 -0
  60. package/dist/self-tuning/flag-writer.js +102 -0
  61. package/dist/self-tuning/flag-writer.js.map +1 -0
  62. package/dist/self-tuning/flags.d.ts +88 -0
  63. package/dist/self-tuning/flags.d.ts.map +1 -0
  64. package/dist/self-tuning/flags.js +189 -0
  65. package/dist/self-tuning/flags.js.map +1 -0
  66. package/dist/self-tuning/index.d.ts +25 -0
  67. package/dist/self-tuning/index.d.ts.map +1 -0
  68. package/dist/self-tuning/index.js +25 -0
  69. package/dist/self-tuning/index.js.map +1 -0
  70. package/dist/self-tuning/judge.d.ts +66 -0
  71. package/dist/self-tuning/judge.d.ts.map +1 -0
  72. package/dist/self-tuning/judge.js +145 -0
  73. package/dist/self-tuning/judge.js.map +1 -0
  74. package/dist/self-tuning/llm-tuner.d.ts +83 -0
  75. package/dist/self-tuning/llm-tuner.d.ts.map +1 -0
  76. package/dist/self-tuning/llm-tuner.js +191 -0
  77. package/dist/self-tuning/llm-tuner.js.map +1 -0
  78. package/dist/self-tuning/orchestrator.d.ts +90 -0
  79. package/dist/self-tuning/orchestrator.d.ts.map +1 -0
  80. package/dist/self-tuning/orchestrator.js +126 -0
  81. package/dist/self-tuning/orchestrator.js.map +1 -0
  82. package/dist/self-tuning/paired-validator.d.ts +50 -0
  83. package/dist/self-tuning/paired-validator.d.ts.map +1 -0
  84. package/dist/self-tuning/paired-validator.js +78 -0
  85. package/dist/self-tuning/paired-validator.js.map +1 -0
  86. package/dist/self-tuning/profiles/index.d.ts +11 -0
  87. package/dist/self-tuning/profiles/index.d.ts.map +1 -0
  88. package/dist/self-tuning/profiles/index.js +15 -0
  89. package/dist/self-tuning/profiles/index.js.map +1 -0
  90. package/dist/self-tuning/profiles/opus48.d.ts +11 -0
  91. package/dist/self-tuning/profiles/opus48.d.ts.map +1 -0
  92. package/dist/self-tuning/profiles/opus48.js +27 -0
  93. package/dist/self-tuning/profiles/opus48.js.map +1 -0
  94. package/dist/self-tuning/profiles/qwen36.d.ts +11 -0
  95. package/dist/self-tuning/profiles/qwen36.d.ts.map +1 -0
  96. package/dist/self-tuning/profiles/qwen36.js +33 -0
  97. package/dist/self-tuning/profiles/qwen36.js.map +1 -0
  98. package/dist/self-tuning/quality-scorer.d.ts +90 -0
  99. package/dist/self-tuning/quality-scorer.d.ts.map +1 -0
  100. package/dist/self-tuning/quality-scorer.js +180 -0
  101. package/dist/self-tuning/quality-scorer.js.map +1 -0
  102. package/dist/self-tuning/realtime-adaptor.d.ts +78 -0
  103. package/dist/self-tuning/realtime-adaptor.d.ts.map +1 -0
  104. package/dist/self-tuning/realtime-adaptor.js +127 -0
  105. package/dist/self-tuning/realtime-adaptor.js.map +1 -0
  106. package/dist/self-tuning/run.d.ts +61 -0
  107. package/dist/self-tuning/run.d.ts.map +1 -0
  108. package/dist/self-tuning/run.js +122 -0
  109. package/dist/self-tuning/run.js.map +1 -0
  110. package/dist/self-tuning/search-reducer.d.ts +76 -0
  111. package/dist/self-tuning/search-reducer.d.ts.map +1 -0
  112. package/dist/self-tuning/search-reducer.js +349 -0
  113. package/dist/self-tuning/search-reducer.js.map +1 -0
  114. package/dist/self-tuning/tuning-profile.d.ts +72 -0
  115. package/dist/self-tuning/tuning-profile.d.ts.map +1 -0
  116. package/dist/self-tuning/tuning-profile.js +134 -0
  117. package/dist/self-tuning/tuning-profile.js.map +1 -0
  118. package/dist/telemetry/session-telemetry.d.ts +25 -0
  119. package/dist/telemetry/session-telemetry.d.ts.map +1 -1
  120. package/dist/telemetry/session-telemetry.js +32 -0
  121. package/dist/telemetry/session-telemetry.js.map +1 -1
  122. package/dist/types/config.d.ts +13 -0
  123. package/dist/types/config.d.ts.map +1 -1
  124. package/dist/types/config.js +3 -0
  125. package/dist/types/config.js.map +1 -1
  126. package/docs/design/LLM_SELF_TUNING_ANALYSIS.md +617 -0
  127. package/docs/guides/SELF_TUNING.md +137 -0
  128. package/package.json +1 -1
  129. package/src/policies/enforcers/__pycache__/_common.cpython-312.pyc +0 -0
  130. package/tools/agents/scripts/__pycache__/toolcall_path_normalizer.cpython-312.pyc +0 -0
  131. package/tools/agents/scripts/anthropic_proxy.py +355 -29
  132. package/tools/agents/scripts/confidence_escalation.py +60 -4
  133. package/tools/agents/tests/test_confidence_escalation.py +77 -0
@@ -0,0 +1,617 @@
1
+ # LLM Self-Tuning Analysis: Raising Small Models Toward Opus 4.8
2
+
3
+ **Date**: 2026-07-11
4
+ **Scope**: UAP flags, self-harness, recipes/escalation, telemetry, benchmarks
5
+ **Goal**: Identify and plan options for LLM-driven self-tuning of UAP configuration to maximize small-model (qwen3.6) output quality toward Opus 4.8 levels.
6
+
7
+ ---
8
+
9
+ ## 1. Current State Assessment
10
+
11
+ ### 1.1 Existing Self-Tuning Infrastructure
12
+
13
+ | System | Location | Lines | Status |
14
+ |--------|----------|-------|--------|
15
+ | **Self-Harness** | `src/self-harness/` | ~1,600 | Mature, ships with `uap self-harness run` |
16
+ | **Paired Benchmarks** | `src/benchmarks/paired/` | ~2,000 | A/B testing with stats, ablation, scaffold |
17
+ | **Speculative Autotune** | `src/benchmarks/speculative-autotune.ts` | ~240 | Throughput/latency knob tuning (not quality) |
18
+ | **Settings Registry** | `src/config/settings-registry.ts` | ~400 | Single source of truth for all tunable flags |
19
+ | **Telemetry** | `src/telemetry/session-telemetry.ts` | ~1,500 | Session-level spans, costs, task trees |
20
+ | **Recipes/Escalation** | `src/config/settings-registry.ts:152-187` | ~35 | Confidence/fusion routing to judge model |
21
+ | **Cross-Model Transfer** | `src/self-harness/transfer.ts` | ~200 | Stores accept/reject outcomes per weakness signature |
22
+
23
+ ### 1.2 Tunable Flag Surface (42+ flags across 10 categories)
24
+
25
+ | Category | Flags | Tunable Range |
26
+ |----------|-------|---------------|
27
+ | **Proxy** | `PROXY_CONTEXT_WINDOW` (65536), `PROXY_CONCURRENCY_LIMIT`, `PROXY_LOOP_BREAKER` (bool), `PROXY_STUCK_BREAK` (bool), `PROXY_RECON_CONVERGENCE_THRESHOLD` (40), `PROXY_RECIPE` (enum) | numeric + bool + enum |
28
+ | **Recipes/Escalation** | `recipes.enabled` (bool), `recipes.recipe` (auto/single/confidence/fusion/ratings/remom), `recipes.confidenceThreshold` (0-1), `recipes.fusionN` (2-6), `recipes.allowSelfJudge` (bool), `recipes.judge.model` (string) | bool + enum + numeric |
29
+ | **Delivery** | `delivery.enforcement` (block/advisory/off), `delivery.localMode` (advisory/deliver/block), `delivery.runtimeVerify` (bool) | enum + bool |
30
+ | **Concurrency** | `modelConcurrency.slots`, `modelConcurrency.headroom`, `modelConcurrency.adaptive` (bool), `UAP_MAX_PARALLEL` (4) | numeric + bool |
31
+ | **Handsfree** | `handsfree.enabled` (bool), `handsfree.intensity` (gentle/normal/aggressive), `UAP_HANDSFREE_STAGNATION_LIMIT` (8) | bool + enum + numeric |
32
+ | **Memory** | `memory.longTerm.enabled` (bool), `memory.longTerm.provider` (qdrant/none), `memory.shortTerm.maxEntries` (50), `memory.patternRag.enabled` (bool) | bool + enum + numeric |
33
+ | **Reactor** | `reactor.enabled` (bool) | bool |
34
+ | **Worktrees** | `worktrees.enabled` (bool), `worktrees.branchPrefix` (feature/), `worktrees.autoCleanup` (bool) | bool + string + bool |
35
+ | **Optimization** | `costOptimization.enabled` (bool), `timeOptimization.parallelExecution.maxParallelDroids` (4) | bool + numeric |
36
+ | **Collaboration** | `collaboration.mode` (auto/always/off) | enum |
37
+
38
+ ### 1.3 What Self-Harness Already Does
39
+
40
+ The Self-Harness orchestrator runs a closed-loop:
41
+ 1. **Mine** — analyzes benchmark `RunRecord[]` to find failure patterns (wrong output, timeouts, tool misuse, guardrail wedges, RECON loops)
42
+ 2. **Propose** — generates `Mod` objects (environment changes, scaffolding, middleware) from weakness reports
43
+ 3. **Validate** — runs paired benchmark with mod applied vs baseline
44
+ 4. **Decide** — accepts if validation delta > threshold AND held-out suite doesn't regress
45
+ 5. **Transfer** — records outcome into cross-model store keyed by weakness signature
46
+
47
+ **Key insight**: The Mod DSL only touches a handful of knobs today (PROXY_RECON_CONVERGENCE_THRESHOLD, PROXY_CONTEXT_WINDOW, etc.). It does NOT touch recipes, escalation, concurrency, memory, or handsfree settings.
48
+
49
+ ### 1.4 What Self-Harness Does NOT Do
50
+
51
+ | Gap | Current State |
52
+ |-----|---------------|
53
+ | **Recipe tuning** | No exploration of recipe type, confidence threshold, fusion N |
54
+ | **Escalation tuning** | No tuning of judge model selection, escalation trigger |
55
+ | **Concurrency tuning** | No optimization of slots, headroom, parallelism |
56
+ | **Memory tuning** | No tuning of short-term entries, pattern RAG, long-term provider |
57
+ | **Handsfree tuning** | No tuning of intensity, stagnation limits |
58
+ | **Cross-flag interaction** | Each mod tested in isolation; no combinatorial tuning |
59
+ | **Real-time adaptation** | All tuning is offline (between benchmark runs); no per-session adaptation |
60
+ | **LLM-guided search** | Proposal is heuristic-based only; no LLM to reason about flag interactions |
61
+ | **Outcome quality signal** | Benchmarks measure pass/fail on task suites; no "quality score" that correlates with Opus-level output |
62
+
63
+ ---
64
+
65
+ ## 2. Core Problem: Why Small Models Fall Short of Opus 4.8
66
+
67
+ ### 2.1 Quality Gap Sources
68
+
69
+ | Factor | Opus 4.8 | Qwen 3.6 | UAP Mitigation |
70
+ |--------|----------|----------|----------------|
71
+ | **Reasoning depth** | Native, deep chain-of-thought | Shallow, needs prompting | `recipes.fusionN` (sample N, judge picks best) |
72
+ | **Tool use reliability** | High | Moderate (required-tool re-rolls) | `PROXY_LOOP_BREAKER`, `PROXY_STUCK_BREAK` |
73
+ | **Context management** | Large window, good retention | Smaller window, drift | `PROXY_CONTEXT_WINDOW`, `memory.shortTerm.maxEntries` |
74
+ | **Self-correction** | Native | Needs explicit guidance | `delivery.runtimeVerify`, `handsfree.intensity` |
75
+ | **Planning** | Strong multi-step planning | Weak, gets stuck | `handsfree.enabled`, `PROXY_RECON_CONVERGENCE_THRESHOLD` |
76
+ | **Guardrail awareness** | Understands constraints | Violates, gets wedged | `recipes.confidenceThreshold`, `recipes.judge.model` |
77
+
78
+ ### 2.2 The "Generator ≠ Evaluator" Problem
79
+
80
+ This is the fundamental challenge. A small model cannot reliably judge its own output quality. UAP already addresses this partially:
81
+ - **Recipes/fusion**: Generate N candidates, judge (stronger model) picks the best
82
+ - **Self-Harness**: Benchmarks measure external correctness, not self-assessment
83
+ - **Delivery**: Convergence loop with auto-mine catches failures
84
+
85
+ **Key gap**: There is no per-session quality signal that approximates "how close to Opus 4.8 is this output?" — only pass/fail on predefined test suites.
86
+
87
+ ---
88
+
89
+ ## 3. Proposed Architecture: LLM-Guided Self-Tuning System
90
+
91
+ ### 3.1 Design Principles
92
+
93
+ 1. **LLM as tuner, not executor** — The LLM (Opus or similar) analyzes telemetry and recommends flag configurations; the small model executes them
94
+ 2. **Closed-loop validation** — Every tuning recommendation is validated by paired benchmarks before acceptance
95
+ 3. **Compositional** — Flags are tuned in groups (not individually) to capture interactions
96
+ 4. **Model-specific profiles** — Each executor model gets its own tuning profile stored in the cross-model transfer store
97
+ 5. **Progressive disclosure** — Start with coarse tuning (recipe type, enabled/disabled), refine to fine-grained (thresholds, N values)
98
+
99
+ ### 3.2 System Components
100
+
101
+ ```
102
+ ┌─────────────────────────────────────────────────────────────┐
103
+ │ LLM Self-Tuning System │
104
+ │ │
105
+ │ ┌──────────┐ ┌──────────────┐ ┌──────────────────┐ │
106
+ │ │ Telemetry │───▶│ Quality │───▶│ LLM Tuner │ │
107
+ │ │ Collector │ │ Scorer │ │ (Opus-guided) │ │
108
+ │ └──────────┘ └──────────────┘ └────────┬─────────┘ │
109
+ │ │ │
110
+ │ ┌──────────┐ ┌──────────────┐ ┌────────┴─────────┐ │
111
+ │ │ Flag │◀───│ Mod │◀───│ Search │ │
112
+ │ │ Writer │ │ Generator │ │ Space Reducer │ │
113
+ │ └──────────┘ └──────────────┘ └──────────────────┘ │
114
+ │ │ │
115
+ │ ┌────────────────────────────────────────────────────────┐ │
116
+ │ │ Paired Benchmark Validator │ │
117
+ │ │ (baseline vs tuned config, statistical significance) │ │
118
+ │ └────────────────────────────────────────────────────────┘ │
119
+ │ │ │
120
+ │ ┌────────────────────────────────────────────────────────┐ │
121
+ │ │ Cross-Model Tuning Store (extends transfer.ts) │ │
122
+ │ │ (model → config → outcome mapping) │ │
123
+ │ └────────────────────────────────────────────────────────┘ │
124
+ └─────────────────────────────────────────────────────────────┘
125
+ ```
126
+
127
+ ### 3.3 Component Details
128
+
129
+ #### 3.3.1 Quality Scorer (`src/self-tuning/quality-scorer.ts`)
130
+
131
+ Replaces the pass/fail binary with a multi-dimensional quality score:
132
+
133
+ ```typescript
134
+ interface QualityScore {
135
+ // Behavioral correctness (0-100)
136
+ correctness: number;
137
+ // Output quality relative to reference (0-100)
138
+ quality: number;
139
+ // Efficiency (tokens per correct answer)
140
+ efficiency: number;
141
+ // Tool use reliability
142
+ toolReliability: number;
143
+ // Planning coherence across turns
144
+ planning: number;
145
+ // Overall weighted score
146
+ composite: number;
147
+ }
148
+ ```
149
+
150
+ **Implementation approach**:
151
+ - Use Opus 4.8 (or the judge model) as the quality scorer
152
+ - Feed it the task spec + agent output + any test results
153
+ - Score on a 0-100 scale per dimension
154
+ - Composite = weighted average (correctness 40%, quality 30%, efficiency 15%, toolReliability 15%)
155
+
156
+ #### 3.3.2 LLM Tuner (`src/self-tuning/llm-tuner.ts`)
157
+
158
+ The core intelligence — an LM-guided tuner that:
159
+
160
+ 1. **Receives**: Quality scores + flag configuration + benchmark results
161
+ 2. **Analyzes**: Which flags correlate with quality improvements?
162
+ 3. **Proposes**: New flag combinations to try next
163
+ 4. **Outputs**: A `TuningProposal` (extends `Mod` type)
164
+
165
+ ```typescript
166
+ interface TuningProposal {
167
+ // Which flags to change and to what values
168
+ changes: FlagChange[];
169
+ // Why these changes (LLM reasoning)
170
+ rationale: string;
171
+ // Expected improvement (LLM estimate)
172
+ expectedDelta: number;
173
+ // Confidence in this proposal (0-1)
174
+ confidence: number;
175
+ // Which model profile this is optimized for
176
+ targetModel: string;
177
+ // Which benchmark suites to validate against
178
+ validationSuites: string[];
179
+ }
180
+
181
+ interface FlagChange {
182
+ key: string; // e.g., "recipes.confidenceThreshold"
183
+ from: number | string | boolean;
184
+ to: number | string | boolean;
185
+ category: string; // recipe, proxy, concurrency, etc.
186
+ }
187
+ ```
188
+
189
+ **Search strategy**:
190
+ - **Phase 1** (coarse): Binary exploration — enable/disable each major category
191
+ - **Phase 2** (medium): Enum exploration — try each recipe type, each handsfree intensity
192
+ - **Phase 3** (fine): Numeric optimization — tune thresholds, N values, concurrency limits
193
+ - **Phase 4** (combinatorial): Joint optimization of interacting flags
194
+
195
+ #### 3.3.3 Search Space Reducer (`src/self-tuning/search-reducer.ts`)
196
+
197
+ Prunes the combinatorial explosion. With 42 flags and even 3 options each: 3^42 ≈ 10^20 possibilities.
198
+
199
+ **Reduction techniques**:
200
+ 1. **Category pruning**: Skip categories known to be irrelevant for the model/task type
201
+ 2. **Dependency awareness**: Some flags only matter when others are enabled (e.g., `recipes.confidenceThreshold` only matters when `recipes.enabled=true`)
202
+ 3. **Bayesian optimization**: Maintain a Gaussian process over flag space, sample from acquisition function
203
+ 4. **Transfer learning**: Use tuning profiles from similar models/tasks as priors
204
+
205
+ #### 3.3.4 Flag Writer (`src/self-tuning/flag-writer.ts`)
206
+
207
+ Applies tuning proposals to the UAP configuration:
208
+ - Writes to `.uap.json` for JSON-config flags
209
+ - Writes to `.uap/proxy.env` for proxy env flags
210
+ - Exports shell env vars for shell flags
211
+ - **Atomic swap**: reads current config, applies changes, validates, writes — on failure, rolls back
212
+
213
+ ### 3.4 Integration with Existing Systems
214
+
215
+ ```
216
+ ┌─────────────────────────────────────────────────────────────┐
217
+ │ Existing UAP Systems │
218
+ │ │
219
+ │ ┌─────────────┐ ┌─────────────┐ ┌────────────────┐ │
220
+ │ │ Self-Harness │ │ Paired │ │ Settings │ │
221
+ │ │ (weakness │ │ Benchmarks │ │ Registry │ │
222
+ │ │ mining) │ │ (validation)│ │ (flag schema) │ │
223
+ │ └──────┬──────┘ └──────┬──────┘ └────────┬───────┘ │
224
+ │ │ │ │ │
225
+ │ ▼ ▼ │ │
226
+ │ ┌─────────────┐ ┌─────────────┐ │ │
227
+ │ │ New: │ │ Reuses: │ │ │
228
+ │ │ Quality │ │ Validation │ │ │
229
+ │ │ Scorer │ │ Pipeline │ │ │
230
+ │ └──────┬──────┘ └─────────────┘ │ │
231
+ │ │ │ │
232
+ │ ▼ │ │
233
+ │ ┌─────────────┐ │ │
234
+ │ │ LLM Tuner │─────▶ Mod Generator ──────────┤ │
235
+ │ │ + Search │ │ │
236
+ │ │ Reducer │◀──────────────────────────────┤ │
237
+ │ └─────────────┘ │ │
238
+ │ │ │
239
+ │ ┌────────────────────────────────────────────────────┐ │
240
+ │ │ Cross-Model Tuning Store (extends transfer.ts) │ │
241
+ │ └────────────────────────────────────────────────────┘ │
242
+ └─────────────────────────────────────────────────────────────┘
243
+ ```
244
+
245
+ ---
246
+
247
+ ## 4. Implementation Plan
248
+
249
+ ### Phase 0: Foundation (Week 1-2)
250
+
251
+ **Goal**: Add quality scoring to the benchmark pipeline.
252
+
253
+ | Task | File | Description |
254
+ |------|------|-------------|
255
+ | Q1 | `src/self-tuning/quality-scorer.ts` | Multi-dimensional quality scoring (correctness, quality, efficiency, toolReliability, planning) |
256
+ | Q2 | `src/benchmarks/paired/types.ts` | Extend `RunRecord` with `qualityScore?: QualityScore` |
257
+ | Q3 | `src/benchmarks/paired/report.ts` | Include quality scores in comparison reports |
258
+ | Q4 | `src/benchmarks/paired/stats.ts` | Statistical tests on quality scores (not just pass/fail) |
259
+
260
+ **Key decision**: Quality scorer uses Opus 4.8 as judge, or the configured judge model?
261
+ **Recommendation**: Use the configured judge model (`recipes.judge.model`) to keep costs down. Fall back to Opus if no judge configured.
262
+
263
+ ### Phase 1: LLM Tuner Core (Week 3-4)
264
+
265
+ **Goal**: LLM-guided flag proposal system.
266
+
267
+ | Task | File | Description |
268
+ |------|------|-------------|
269
+ | T1 | `src/self-tuning/llm-tuner.ts` | Core tuner: receives quality scores, proposes flag changes |
270
+ | T2 | `src/self-tuning/search-reducer.ts` | Search space pruning and Bayesian optimization |
271
+ | T3 | `src/self-tuning/flag-writer.ts` | Atomic config write/rollback |
272
+ | T4 | `src/self-tuning/tuning-profile.ts` | Model-specific tuning profile storage |
273
+ | T5 | `src/self-harness/transfer.ts` | Extend with tuning outcome records |
274
+
275
+ **LLM prompt design** (critical):
276
+ ```
277
+ You are a configuration optimizer for the Universal Agent Protocol (UAP).
278
+
279
+ EXECUTOR MODEL: qwen3.6-35b
280
+ CURRENT CONFIG: {json of current flags}
281
+ QUALITY SCORES: {quality scores from benchmark}
282
+ PAST ATTEMPTS: [{config, scores, result}] for previous tuning attempts
283
+
284
+ TASK: Propose the next configuration to try.
285
+
286
+ CONSTRAINTS:
287
+ - Only change 2-4 flags per proposal (keep changes interpretable)
288
+ - Respect flag dependencies (e.g., confidenceThreshold requires recipes.enabled)
289
+ - Prefer changes that have transferred well from other models
290
+ - Target: maximize composite quality score
291
+
292
+ OUTPUT FORMAT:
293
+ {
294
+ "changes": [{"key": "...", "from": ..., "to": ..., "category": "..."}],
295
+ "rationale": "explanation",
296
+ "expectedDelta": 5.2,
297
+ "confidence": 0.75
298
+ }
299
+ ```
300
+
301
+ ### Phase 2: Closed-Loop Integration (Week 5-6)
302
+
303
+ **Goal**: Full tuning loop — propose → validate → accept/reject → learn.
304
+
305
+ | Task | File | Description |
306
+ |------|------|-------------|
307
+ | L1 | `src/self-tuning/orchestrator.ts` | Extends self-harness orchestrator with tuning loop |
308
+ | L2 | `src/self-harness/run.ts` | Add `uap self-harness tune` command |
309
+ | L3 | `src/cli/self-tuning.ts` | CLI entry point |
310
+ | L4 | `src/benchmarks/paired/suite.ts` | Add "tuning" suite type for iterative validation |
311
+
312
+ **Loop flow**:
313
+ ```
314
+ 1. Run baseline benchmark → collect RunRecord[]
315
+ 2. Score quality for each record
316
+ 3. LLM Tuner proposes next config
317
+ 4. Apply config (flag-writer)
318
+ 5. Run benchmark with new config
319
+ 6. Score quality
320
+ 7. Compare: did quality improve?
321
+ - Yes: accept, record in transfer store, go to step 3
322
+ - No: reject, record in transfer store, go to step 3
323
+ 8. Stop when: budget exhausted, or quality plateaus (3 consecutive rejections)
324
+ ```
325
+
326
+ ### Phase 3: Small Model Optimization Profile (Week 7-8)
327
+
328
+ **Goal**: A pre-tuned profile specifically for qwen3.6 → Opus 4.8 quality gap reduction.
329
+
330
+ | Task | File | Description |
331
+ |------|------|-------------|
332
+ | P1 | `src/self-tuning/profiles/qwen36.json` | Default tuning profile for qwen3.6 |
333
+ | P2 | `src/self-tuning/profiles/opus48.json` | Reference profile for Opus 4.8 (upper bound) |
334
+ | P3 | `scripts/tune-model.ts` | CLI tool: `uap tune model qwen3.6` |
335
+ | P4 | `docs/guides/SELF_TUNING.md` | User documentation |
336
+
337
+ **Expected qwen3.6 profile** (hypothesis, needs validation):
338
+ ```json
339
+ {
340
+ "recipes": {
341
+ "enabled": true,
342
+ "recipe": "fusion",
343
+ "confidenceThreshold": 0.6,
344
+ "fusionN": 3,
345
+ "allowSelfJudge": false,
346
+ "judge": { "model": "opus-4-8" }
347
+ },
348
+ "proxy": {
349
+ "CONTEXT_WINDOW": 65536,
350
+ "LOOP_BREAKER": true,
351
+ "STUCK_BREAK": true,
352
+ "RECON_CONVERGENCE_THRESHOLD": 30,
353
+ "RECIPE": "fusion"
354
+ },
355
+ "handsfree": {
356
+ "enabled": true,
357
+ "intensity": "aggressive",
358
+ "stagnationLimit": 6
359
+ },
360
+ "modelConcurrency": {
361
+ "slots": 4,
362
+ "adaptive": true
363
+ },
364
+ "delivery": {
365
+ "enforcement": "advisory",
366
+ "runtimeVerify": true
367
+ },
368
+ "memory": {
369
+ "shortTerm": { "maxEntries": 80 },
370
+ "patternRag": { "enabled": true }
371
+ }
372
+ }
373
+ ```
374
+
375
+ ### Phase 4: Real-Time Adaptation (Week 9-10)
376
+
377
+ **Goal**: Per-session flag adaptation (not just between sessions).
378
+
379
+ | Task | File | Description |
380
+ |------|------|-------------|
381
+ | R1 | `src/self-tuning/realtime-adaptor.ts` | Mid-session flag adjustment |
382
+ | R2 | `src/coordination/reactor.ts` | Integrate with reactor for live tuning |
383
+ | R3 | `src/telemetry/session-telemetry.ts` | Add per-turn quality estimation |
384
+ | R4 | Proxy integration | Apply tuning at proxy layer (not just config file) |
385
+
386
+ **Real-time signals**:
387
+ - Tool-use failure rate → adjust `PROXY_LOOP_BREAKER` aggressiveness
388
+ - Context window utilization → adjust `PROXY_CONTEXT_WINDOW`
389
+ - RECON loop detection → adjust `PROXY_RECON_CONVERGENCE_THRESHOLD`
390
+ - Turn quality degradation → trigger escalation via recipes
391
+
392
+ ---
393
+
394
+ ## 5. Alternative Approaches Considered
395
+
396
+ ### 5.1 Pure Heuristic Tuning (No LLM)
397
+
398
+ **Approach**: Grid search, random search, or Bayesian optimization over flag space.
399
+
400
+ **Pros**: Deterministic, no API cost, reproducible
401
+ **Cons**: Cannot handle combinatorial complexity; no understanding of flag interactions; slow convergence
402
+
403
+ **Verdict**: Use as a fallback for Phase 0 (quality scoring). Not sufficient for the full system.
404
+
405
+ ### 5.2 Reinforcement Learning
406
+
407
+ **Approach**: Train a policy network that maps session state → flag configuration.
408
+
409
+ **Pros**: Once trained, inference is instant; can learn complex policies
410
+ **Cons**: Requires massive training data; training is expensive; fragile to distribution shift
411
+
412
+ **Verdict**: Too expensive for current data volume. Could be a Phase 5+ after collecting enough tuning data.
413
+
414
+ ### 5.3 Meta-Learning Across Models
415
+
416
+ **Approach**: Train a meta-learner that takes a model's capabilities as input and outputs an optimal config.
417
+
418
+ **Pros**: One-shot tuning for new models
419
+ **Cons**: Requires diverse model training data; complex to implement
420
+
421
+ **Verdict**: Aligns with existing `transfer.ts` design. Defer to Phase 4+.
422
+
423
+ ### 5.4 Direct Prompt Engineering (No Flag Tuning)
424
+
425
+ **Approach**: Instead of tuning UAP flags, improve the system prompt / Claude Code instructions for small models.
426
+
427
+ **Pros**: Simpler, no config complexity
428
+ **Cons**: Prompt tokens are expensive; doesn't leverage UAP's structural advantages (recipes, escalation, guardrails)
429
+
430
+ **Verdict**: Complementary. The LLM tuner should consider prompt-level changes as one type of "Mod".
431
+
432
+ ---
433
+
434
+ ## 6. Key Risks and Mitigations
435
+
436
+ | Risk | Impact | Mitigation |
437
+ |------|--------|------------|
438
+ | **LLM tuner makes bad suggestions** | Wastes benchmark runs, degrades quality | Conservative proposal bounds; always validate via paired bench; reject on regression |
439
+ | **Combinatorial explosion** | Tuning takes too long | Limit to 2-4 flag changes per proposal; category-level pruning; transfer learning priors |
440
+ | **Overfitting to benchmark suite** | Good on bench, bad in production | Held-out validation suites; diverse task types; periodic real-world validation |
441
+ | **Cost of Opus-as-judge** | Expensive quality scoring | Use configured judge model; batch scoring; sample-based estimation |
442
+ | **Config instability** | Flags oscillate between runs | Hysteresis threshold (need >5% improvement to accept); momentum in numeric tuning |
443
+ | **Small model can't follow tuned config** | Config assumes capabilities small model lacks | Capability-aware tuning: profile model capabilities first, only enable flags within capability envelope |
444
+
445
+ ---
446
+
447
+ ## 7. Success Metrics
448
+
449
+ | Metric | Baseline (qwen3.6, no tuning) | Target (qwen3.6 + self-tuning) |
450
+ |--------|-------------------------------|--------------------------------|
451
+ | **Task suite pass rate** | ~60-70% (varies) | ~85-90% |
452
+ | **Quality composite score** | ~55/100 | ~75/100 |
453
+ | **Tokens per correct answer** | ~15K | ~12K (more efficient) |
454
+ | **Tool-use success rate** | ~70% | ~85% |
455
+ | **RECON loop rate** | ~15% | <5% |
456
+ | **Time to first green** | Manual (hours) | Automated (~30 min) |
457
+
458
+ ---
459
+
460
+ ## 8. Recommendation
461
+
462
+ ### Short-term (immediate, 2-3 weeks)
463
+
464
+ 1. **Add quality scoring** to the benchmark pipeline (Phase 0)
465
+ - This is the highest-leverage, lowest-risk change
466
+ - Extends existing `RunRecord` type
467
+ - Uses existing judge model infrastructure
468
+ - Enables all downstream tuning work
469
+
470
+ 2. **Extend Self-Harness Mod DSL** to cover recipe and concurrency flags
471
+ - Add knob specs for `recipes.confidenceThreshold`, `recipes.fusionN`, `recipes.recipe`
472
+ - Add knob specs for `modelConcurrency.slots`, `handsfree.intensity`
473
+ - Reuse existing `heuristicProposer` with new knob targets
474
+
475
+ ### Medium-term (4-8 weeks)
476
+
477
+ 3. **Build LLM Tuner** (Phase 1-2)
478
+ - The core innovation: Opus-guided flag space exploration
479
+ - Integrates with existing self-harness orchestrator
480
+ - Validates all changes through paired benchmarks
481
+
482
+ 4. **Build tuning profile system** (Phase 3)
483
+ - Pre-tuned profiles for qwen3.6, llama, etc.
484
+ - `uap tune model <name>` CLI command
485
+ - Profiles stored in transfer store with provenance
486
+
487
+ ### Long-term (8-12 weeks)
488
+
489
+ 5. **Real-time adaptation** (Phase 4)
490
+ - Mid-session flag adjustment based on live telemetry
491
+ - Requires proxy integration for live config changes
492
+
493
+ 6. **Meta-learning** (Phase 5)
494
+ - Cross-model transfer of tuning knowledge
495
+ - One-shot tuning for new executor models
496
+
497
+ ### Priority Rationale
498
+
499
+ The quality scorer is the bottleneck. Without a quality signal beyond pass/fail, the LLM tuner has nothing to optimize toward. The existing paired benchmarks measure whether code works, not whether the output is *good*. Raising qwen3.6 toward Opus 4.8 is fundamentally a quality problem, not a correctness problem.
500
+
501
+ The Self-Harness Mod DSL extension is the second priority because it unlocks the existing orchestrator infrastructure for recipe/concurrency tuning without building new validation pipelines.
502
+
503
+ The LLM Tuner is the third priority because it depends on both the quality signal and the expanded Mod DSL.
504
+
505
+ ---
506
+
507
+ ## 9. Files to Create/Modify
508
+
509
+ ### New files
510
+
511
+ | File | Purpose |
512
+ |------|---------|
513
+ | `src/self-tuning/quality-scorer.ts` | Multi-dimensional quality scoring |
514
+ | `src/self-tuning/llm-tuner.ts` | LLM-guided flag proposal |
515
+ | `src/self-tuning/search-reducer.ts` | Search space pruning |
516
+ | `src/self-tuning/flag-writer.ts` | Atomic config write/rollback |
517
+ | `src/self-tuning/tuning-profile.ts` | Model-specific tuning profiles |
518
+ | `src/self-tuning/realtime-adaptor.ts` | Per-session flag adaptation |
519
+ | `src/self-tuning/orchestrator.ts` | Extends self-harness with tuning loop |
520
+ | `src/cli/self-tuning.ts` | CLI entry point |
521
+ | `src/self-tuning/profiles/qwen36.json` | Default qwen3.6 tuning profile |
522
+ | `src/self-tuning/profiles/opus48.json` | Opus 4.8 reference profile |
523
+ | `scripts/tune-model.ts` | `uap tune model` CLI |
524
+ | `docs/guides/SELF_TUNING.md` | User documentation |
525
+
526
+ ### Modified files
527
+
528
+ | File | Change |
529
+ |------|--------|
530
+ | `src/benchmarks/paired/types.ts` | Add `qualityScore` to `RunRecord` |
531
+ | `src/benchmarks/paired/report.ts` | Include quality scores in comparisons |
532
+ | `src/benchmarks/paired/stats.ts` | Statistical tests on quality scores |
533
+ | `src/self-harness/mods.ts` | Add knob specs for recipe/concurrency/handsfree flags |
534
+ | `src/self-harness/transfer.ts` | Extend with tuning outcome records |
535
+ | `src/self-harness/orchestrator.ts` | Wire in LLM tuner as alternative proposer |
536
+ | `src/self-harness/run.ts` | Add `uap self-harness tune` command |
537
+ | `src/config/settings-registry.ts` | Add any new tunable flags |
538
+ | `src/telemetry/session-telemetry.ts` | Add per-turn quality estimation |
539
+ | `src/index.ts` | Export new modules |
540
+
541
+ ---
542
+
543
+ ## 10. Relationship to Existing Work
544
+
545
+ | Existing System | How Self-Tuning Relates |
546
+ |----------------|------------------------|
547
+ | **Self-Harness** | Self-tuning extends Self-Harness; uses same orchestrator, validation pipeline, transfer store |
548
+ | **Paired Benchmarks** | Self-tuning reuses the benchmark pipeline; adds quality scoring on top |
549
+ | **Recipes/Escalation** | Self-tuning optimizes recipe config; recipes provide the quality signal (judge model) |
550
+ | **Cross-Model Transfer** | Self-tuning stores tuning outcomes in transfer store; uses transfer as priors for new models |
551
+ | **Speculative Autotune** | Separate concern: autotune optimizes throughput/latency; self-tuning optimizes quality |
552
+ | **Delivery Convergence** | Self-tuning validates changes through delivery; delivery provides real-world validation signal |
553
+ | **Dashboard** | Self-tuning results visible in dashboard (tuning history, quality trends, profile comparison) |
554
+
555
+ ---
556
+
557
+ ## 11. Appendix: Flag Dependency Map
558
+
559
+ Understanding which flags interact is critical for search space reduction.
560
+
561
+ ```
562
+ recipes.enabled
563
+ ├── recipes.recipe (enum)
564
+ │ ├── confidence → recipes.confidenceThreshold
565
+ │ ├── fusion → recipes.fusionN
566
+ │ └── ratings → (standalone)
567
+ ├── recipes.allowSelfJudge (bool, conflicts with recipes.judge.model)
568
+ └── recipes.judge.model (requires PROXY_ESCALATE_API_KEY)
569
+
570
+ PROXY_RECIPE (must match recipes.recipe)
571
+
572
+ handsfree.enabled
573
+ ├── handsfree.intensity
574
+ └── UAP_HANDSFREE_STAGNATION_LIMIT
575
+
576
+ modelConcurrency.slots
577
+ ├── modelConcurrency.headroom
578
+ └── modelConcurrency.adaptive
579
+
580
+ memory.patternRag.enabled
581
+ └── QDRANT_URL (runtime dep)
582
+
583
+ delivery.enforcement
584
+ └── UAP_ENFORCE_DELIVERY (env override)
585
+
586
+ PROXY_CONTEXT_WINDOW
587
+ └── (affects all models proportionally)
588
+
589
+ PROXY_LOOP_BREAKER + PROXY_STUCK_BREAK
590
+ └── PROXY_RECON_CONVERGENCE_THRESHOLD (threshold for loop detection)
591
+ ```
592
+
593
+ ---
594
+
595
+ ## 12. Appendix: Existing Self-Harness Mod DSL
596
+
597
+ Current knob allowlist (from `src/self-harness/mods.ts`):
598
+
599
+ ```typescript
600
+ const KNOB_ALLOWLIST = {
601
+ // Llama.cpp serving params
602
+ LLAMA_CONTEXT_SIZE: { type: 'number', min: 512, max: 16384, integer: true, target: 'llama' },
603
+ LLAMA_TEMP: { type: 'number', min: 1.0, max: 1.3, target: 'llama' },
604
+
605
+ // Proxy env params
606
+ PROXY_MAX_TURNS: { type: 'number', min: 10, max: 80, integer: true, target: 'proxy' },
607
+ PROXY_RECON_CONVERGENCE_THRESHOLD: { type: 'number', min: 5, max: 40, integer: true, target: 'proxy' },
608
+ PROXY_CONCURRENCY_LIMIT: { type: 'number', min: 2, max: 24, integer: true, target: 'proxy' },
609
+ PROXY_CONTEXT_WINDOW: { type: 'number', min: 5, max: 40, integer: true, target: 'proxy' },
610
+ } as const;
611
+ ```
612
+
613
+ **Note**: These are all numeric knobs targeting proxy/llama env vars. The self-tuning system needs to extend this to:
614
+ - Enum knobs (e.g., `recipes.recipe`, `handsfree.intensity`)
615
+ - Boolean knobs (e.g., `recipes.enabled`, `handsfree.enabled`)
616
+ - Nested JSON config knobs (e.g., `recipes.judge.model`)
617
+ - String knobs (e.g., `worktrees.branchPrefix`)