@caupulican/pi-adaptative 0.81.29 → 0.81.31

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 (147) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/bundled-resources/skills/harness-self-adaptation/SKILL.md +327 -0
  3. package/dist/bundled-resources/skills/harness-self-adaptation/references/adaptation-layers.md +89 -0
  4. package/dist/core/agent-session.d.ts +11 -1
  5. package/dist/core/agent-session.d.ts.map +1 -1
  6. package/dist/core/agent-session.js +16 -14
  7. package/dist/core/agent-session.js.map +1 -1
  8. package/dist/core/autonomy/approval-gate.d.ts +1 -1
  9. package/dist/core/autonomy/approval-gate.d.ts.map +1 -1
  10. package/dist/core/autonomy/approval-gate.js +5 -1
  11. package/dist/core/autonomy/approval-gate.js.map +1 -1
  12. package/dist/core/autonomy/lane-tool-surface.d.ts +4 -0
  13. package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
  14. package/dist/core/autonomy/lane-tool-surface.js +31 -4
  15. package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
  16. package/dist/core/autonomy/lane-tracker.d.ts +1 -0
  17. package/dist/core/autonomy/lane-tracker.d.ts.map +1 -1
  18. package/dist/core/autonomy/lane-tracker.js +11 -0
  19. package/dist/core/autonomy/lane-tracker.js.map +1 -1
  20. package/dist/core/autonomy/risk-assessment.d.ts.map +1 -1
  21. package/dist/core/autonomy/risk-assessment.js +1 -1
  22. package/dist/core/autonomy/risk-assessment.js.map +1 -1
  23. package/dist/core/background-lane-controller.d.ts +12 -0
  24. package/dist/core/background-lane-controller.d.ts.map +1 -1
  25. package/dist/core/background-lane-controller.js +114 -19
  26. package/dist/core/background-lane-controller.js.map +1 -1
  27. package/dist/core/context/context-artifacts.d.ts.map +1 -1
  28. package/dist/core/context/context-artifacts.js +7 -6
  29. package/dist/core/context/context-artifacts.js.map +1 -1
  30. package/dist/core/context/context-store-retention.d.ts +12 -0
  31. package/dist/core/context/context-store-retention.d.ts.map +1 -0
  32. package/dist/core/context/context-store-retention.js +161 -0
  33. package/dist/core/context/context-store-retention.js.map +1 -0
  34. package/dist/core/context-gc.d.ts.map +1 -1
  35. package/dist/core/context-gc.js +19 -4
  36. package/dist/core/context-gc.js.map +1 -1
  37. package/dist/core/context-pipeline.d.ts +13 -12
  38. package/dist/core/context-pipeline.d.ts.map +1 -1
  39. package/dist/core/context-pipeline.js +128 -33
  40. package/dist/core/context-pipeline.js.map +1 -1
  41. package/dist/core/cost/cost-summary.d.ts +7 -1
  42. package/dist/core/cost/cost-summary.d.ts.map +1 -1
  43. package/dist/core/cost/cost-summary.js +28 -17
  44. package/dist/core/cost/cost-summary.js.map +1 -1
  45. package/dist/core/cost/daily-usage.d.ts +7 -3
  46. package/dist/core/cost/daily-usage.d.ts.map +1 -1
  47. package/dist/core/cost/daily-usage.js +10 -5
  48. package/dist/core/cost/daily-usage.js.map +1 -1
  49. package/dist/core/delegation/worker-runner.d.ts.map +1 -1
  50. package/dist/core/delegation/worker-runner.js +25 -9
  51. package/dist/core/delegation/worker-runner.js.map +1 -1
  52. package/dist/core/export-html/template.js +2 -1
  53. package/dist/core/extensions/loader.d.ts.map +1 -1
  54. package/dist/core/extensions/loader.js +52 -2
  55. package/dist/core/extensions/loader.js.map +1 -1
  56. package/dist/core/extensions/runner.d.ts.map +1 -1
  57. package/dist/core/extensions/runner.js +21 -19
  58. package/dist/core/extensions/runner.js.map +1 -1
  59. package/dist/core/extensions/types.d.ts +5 -0
  60. package/dist/core/extensions/types.d.ts.map +1 -1
  61. package/dist/core/extensions/types.js.map +1 -1
  62. package/dist/core/failure-corpus.d.ts.map +1 -1
  63. package/dist/core/failure-corpus.js +36 -13
  64. package/dist/core/failure-corpus.js.map +1 -1
  65. package/dist/core/local-runtime-controller.d.ts.map +1 -1
  66. package/dist/core/local-runtime-controller.js +20 -2
  67. package/dist/core/local-runtime-controller.js.map +1 -1
  68. package/dist/core/memory-controller.d.ts +2 -0
  69. package/dist/core/memory-controller.d.ts.map +1 -1
  70. package/dist/core/memory-controller.js +18 -0
  71. package/dist/core/memory-controller.js.map +1 -1
  72. package/dist/core/models/local-runtime.d.ts.map +1 -1
  73. package/dist/core/models/local-runtime.js +15 -10
  74. package/dist/core/models/local-runtime.js.map +1 -1
  75. package/dist/core/reflection-controller.d.ts +3 -1
  76. package/dist/core/reflection-controller.d.ts.map +1 -1
  77. package/dist/core/reflection-controller.js +8 -5
  78. package/dist/core/reflection-controller.js.map +1 -1
  79. package/dist/core/runtime-builder.d.ts +2 -0
  80. package/dist/core/runtime-builder.d.ts.map +1 -1
  81. package/dist/core/runtime-builder.js.map +1 -1
  82. package/dist/core/sdk.d.ts.map +1 -1
  83. package/dist/core/sdk.js +1 -1
  84. package/dist/core/sdk.js.map +1 -1
  85. package/dist/core/session-analytics.d.ts +13 -7
  86. package/dist/core/session-analytics.d.ts.map +1 -1
  87. package/dist/core/session-analytics.js +155 -112
  88. package/dist/core/session-analytics.js.map +1 -1
  89. package/dist/core/tool-recovery-log-records.d.ts.map +1 -1
  90. package/dist/core/tool-recovery-log-records.js +54 -9
  91. package/dist/core/tool-recovery-log-records.js.map +1 -1
  92. package/dist/core/tool-recovery-logger.d.ts +2 -0
  93. package/dist/core/tool-recovery-logger.d.ts.map +1 -1
  94. package/dist/core/tool-recovery-logger.js +32 -13
  95. package/dist/core/tool-recovery-logger.js.map +1 -1
  96. package/dist/core/tool-recovery-stats.d.ts +15 -0
  97. package/dist/core/tool-recovery-stats.d.ts.map +1 -0
  98. package/dist/core/tool-recovery-stats.js +206 -0
  99. package/dist/core/tool-recovery-stats.js.map +1 -0
  100. package/dist/core/tools/delegate-status.d.ts.map +1 -1
  101. package/dist/core/tools/delegate-status.js +15 -6
  102. package/dist/core/tools/delegate-status.js.map +1 -1
  103. package/dist/core/tools/delegate.d.ts +3 -0
  104. package/dist/core/tools/delegate.d.ts.map +1 -1
  105. package/dist/core/tools/delegate.js +7 -2
  106. package/dist/core/tools/delegate.js.map +1 -1
  107. package/dist/main.d.ts.map +1 -1
  108. package/dist/main.js +1 -1
  109. package/dist/main.js.map +1 -1
  110. package/dist/modes/interactive/components/bash-execution.d.ts +2 -1
  111. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  112. package/dist/modes/interactive/components/bash-execution.js +12 -1
  113. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  114. package/dist/modes/interactive/components/footer.d.ts +1 -0
  115. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  116. package/dist/modes/interactive/components/footer.js +19 -9
  117. package/dist/modes/interactive/components/footer.js.map +1 -1
  118. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  119. package/dist/modes/interactive/components/tool-execution.js +12 -2
  120. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  121. package/dist/modes/interactive/components/tool-panel-registry.d.ts +1 -0
  122. package/dist/modes/interactive/components/tool-panel-registry.d.ts.map +1 -1
  123. package/dist/modes/interactive/components/tool-panel-registry.js +18 -2
  124. package/dist/modes/interactive/components/tool-panel-registry.js.map +1 -1
  125. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  126. package/dist/modes/interactive/interactive-mode.js +9 -3
  127. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  128. package/dist/modes/rpc/jsonl.d.ts.map +1 -1
  129. package/dist/modes/rpc/jsonl.js +9 -28
  130. package/dist/modes/rpc/jsonl.js.map +1 -1
  131. package/dist/utils/streaming-lines.d.ts +20 -0
  132. package/dist/utils/streaming-lines.d.ts.map +1 -0
  133. package/dist/utils/streaming-lines.js +79 -0
  134. package/dist/utils/streaming-lines.js.map +1 -0
  135. package/docs/extensions.md +2 -0
  136. package/docs/index.md +1 -1
  137. package/docs/self-adaptation.md +7 -0
  138. package/docs/settings.md +5 -1
  139. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  140. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  141. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  142. package/examples/extensions/sandbox/package-lock.json +2 -2
  143. package/examples/extensions/sandbox/package.json +1 -1
  144. package/examples/extensions/with-deps/package-lock.json +2 -2
  145. package/examples/extensions/with-deps/package.json +1 -1
  146. package/npm-shrinkwrap.json +12 -12
  147. package/package.json +4 -4
package/CHANGELOG.md CHANGED
@@ -1,3 +1,23 @@
1
+ ## [0.81.31] - 2026-07-13
2
+
3
+ ## [0.81.30] - 2026-07-13
4
+
5
+ ### Added
6
+
7
+ - Added a bundled harness self-adaptation skill with evidence, layer-selection, measurement, retention, rollback, and authority gates for compounding Pi work without gratuitous self-modification.
8
+ - Added per-delegation, lane-profile-gated read-only memory retrieval for isolated workers while keeping private memory files and every memory mutation unavailable.
9
+ - Added explicit queued/running worker status and lane-specific completion notifications without injecting late worker output into the active foreground transcript.
10
+
11
+ ### Fixed
12
+
13
+ - Bounded long-session telemetry by bytes with cumulative per-session summaries, made recovery-log worker replacement batch-safe, added active-session-safe age/count/byte retention for context payload stores, replaced repeated full-session footer, context, analytics, and background-lane scans with incremental or indexed reads, and invalidated provider request-prefix caches immediately after compaction.
14
+ - Avoided full copies of large context strings during curation, artifact hashing, context GC, RPC framing, local-runtime progress parsing, and HTML branch reconstruction.
15
+ - Made managed local-model readiness verify the configured Ollama model after startup, exit cleanly when it is missing, and prevent prefix warming from silently falling back to another model.
16
+ - Kept startup running when an extension fails to load, while reporting the failure, restoring prior provider and flag state, and discarding partial event registrations.
17
+ - Preserved bounded read-only delegated worker output when a worker returns plain text, custom JSON, or reaches its output limit instead of failing it as unparseable.
18
+ - Made worker delegation follow the selected lane model's provider and tool protocol, and prevented multiple queued local workers from deadlocking.
19
+ - Restored OAuth rejection recovery for Codex subscription models by matching the provider ID instead of the Responses API ID.
20
+
1
21
  ## [0.81.29] - 2026-07-10
2
22
 
3
23
  ### Fixed
@@ -0,0 +1,327 @@
1
+ ---
2
+ name: harness-self-adaptation
3
+ description: "ALWAYS use for work on the Pi/pi-adaptative harness when the task can reveal or benefit from a reusable improvement to agent effectiveness: debugging repeated friction, analyzing failures, optimizing tools/context/delegation/reliability, refining skills or prompts, or retaining a successful workflow. Runs an evidence-first observe, diagnose, choose-layer, intervene, compare, retain-or-rollback loop. Trigger phrases include \"self-adapt the harness\", \"make Pi more effective\", \"learn from this failure\", \"prevent this from recurring\", \"improve the agent workflow\", \"optimize harness effectiveness\", and \"skillify what we learned\"."
4
+ ---
5
+
6
+ # Harness Self-Adaptation
7
+
8
+ ## How to use the skill
9
+
10
+ Load this skill around any Pi harness task. The requested task remains primary;
11
+ self-adaptation is a bounded second loop that may legitimately conclude that no
12
+ durable adaptation is warranted.
13
+
14
+ **Freedom Dial: High Freedom.** Diagnosis and intervention selection require
15
+ judgment across many harness layers. Evidence thresholds, authority boundaries,
16
+ validation, retention, and rollback are mandatory low-variance gates.
17
+
18
+ Choose one mode before acting:
19
+
20
+ - **Observe**: deliver the task and capture an adaptation candidate only when a
21
+ reusable signal appears.
22
+ - **Adapt**: include the smallest justified harness improvement when recurrence,
23
+ deterministic evidence, material impact, or the user's request puts it in scope.
24
+ - **Audit**: when effectiveness itself is the task, reproduce the workflow,
25
+ establish a baseline, and run a bounded before/after experiment.
26
+
27
+ Load the narrow specialist when the candidate enters its domain. In particular,
28
+ use `pi-harness-learning` for after-action classification and durable learning,
29
+ `skill-architect` when authoring instructions, `tool-call-repair` for model tool
30
+ argument/protocol failures, and `source-grounded-docs` for codebase documentation.
31
+ This skill owns the adaptation loop, not those domain procedures.
32
+
33
+ ## North Star
34
+
35
+ Complete the active harness task, then retain only the smallest reusable change
36
+ that demonstrably improves future outcome quality, reliability, effort, latency,
37
+ context use, or cost without weakening safety, maintainability, or user control.
38
+
39
+ Apply these principles on every pass:
40
+
41
+ - **Think before coding**: state the oracle, assumptions, evidence, competing
42
+ explanations, and material tradeoffs.
43
+ - **Simplicity first**: prefer no change or one existing-layer refinement over a
44
+ new mechanism.
45
+ - **Surgical changes**: touch only the causal mechanism and its proof; preserve
46
+ concurrent user work.
47
+ - **Goal-driven execution**: validate against an observable end state, not a
48
+ plausible implementation.
49
+ - **Human on the edge**: never expand authority. Follow the active policy and
50
+ require the human at credentials, destructive or irreversible actions,
51
+ settings/authority expansion, dependency installation, push/tag/release/publish,
52
+ and material product or architecture decisions.
53
+
54
+ A faster run that produces a worse answer is a regression. A change that merely
55
+ moves work or tokens elsewhere is not an improvement.
56
+
57
+ ## Core Sections
58
+
59
+ ### 1. Frame the work unit
60
+
61
+ Before diagnosing the harness:
62
+
63
+ 1. Restate the requested outcome and scope.
64
+ 2. Define an **oracle** that can prove the outcome: a focused test, fixture,
65
+ benchmark, transcript invariant, type check, rendered state, or explicit user
66
+ acceptance criterion.
67
+ 3. Read the applicable `AGENTS.md`, relevant source in full before broad edits,
68
+ existing tests, and the narrow Pi docs/examples required by the task.
69
+ 4. Search for an existing skill, prompt, setting, tool, extension, test helper,
70
+ or core mechanism before proposing another one.
71
+ 5. Pick one primary effectiveness metric and guardrails. Use the same workload,
72
+ model, provider, environment, and measurement method for comparisons when
73
+ feasible.
74
+ 6. For multi-step work, maintain the goal ledger and keep evidence attached to
75
+ the requirement it proves.
76
+
77
+ Useful metrics include oracle pass rate, user corrections, retries, tool-call or
78
+ validation failures, repeated reads/searches, elapsed time, time to first useful
79
+ result, context/token volume, cost, peak memory, and recovery success. Prefer the
80
+ metric closest to user outcome. Treat proxies as secondary.
81
+
82
+ If no valid baseline can be captured, say `baseline unavailable`; prove the
83
+ correctness invariant and avoid claiming a measured efficiency gain.
84
+
85
+ ### 2. Observe reusable signals
86
+
87
+ Use operational evidence, never hidden chain-of-thought. Inspect bounded sources
88
+ such as failing tests, minimal reproductions, logs, tool results, session
89
+ analytics, recovery records, benchmarks, user corrections, and source control
90
+ history relevant to the mechanism.
91
+
92
+ Evidence strength, highest first:
93
+
94
+ 1. Deterministic reproduction or violated invariant with source-level mechanism.
95
+ 2. Controlled benchmark/profile plus source evidence.
96
+ 3. The same trusted failure or correction in at least two independent work units.
97
+ 4. One stochastic or anecdotal event, which is a cue only.
98
+
99
+ A durable behavior change needs either a deterministic mechanism, corroboration
100
+ from two trusted instances, or a material safety/data-loss/cost risk. Do not mine
101
+ large raw histories when a bounded index, statistic, or focused query can answer
102
+ the question.
103
+
104
+ Create this compact adaptation card:
105
+
106
+ ```text
107
+ Work oracle: <observable success condition>
108
+ Signal and impact: <what hurt effectiveness, and how>
109
+ Evidence: <reproduction, source, test, metric, or trusted recurrence>
110
+ Mechanism hypothesis: <cause that predicts the signal>
111
+ Falsifier: <result that would disprove the hypothesis>
112
+ Primary metric: <before -> target, or invariant>
113
+ Guardrails: <behavior that must not regress>
114
+ Confidence: confirmed | inferred | unconfirmed
115
+ ```
116
+
117
+ ### 3. Diagnose the owning mechanism
118
+
119
+ Reduce the signal to the smallest reproduction. Trace:
120
+
121
+ ```text
122
+ surface symptom -> immediate cause -> state/data/control-flow mechanism -> owning layer
123
+ ```
124
+
125
+ Check at least one plausible alternative and a counterfactual: if the proposed
126
+ cause were removed, would the signal disappear? Separate model capability,
127
+ provider protocol, harness orchestration, task instructions, environment, and
128
+ test artifacts. Do not blame the model for malformed schemas, unavailable tools,
129
+ stale context, transport failure, or impossible instructions owned by the
130
+ harness.
131
+
132
+ Classify the mechanism before choosing a fix:
133
+
134
+ - instruction/routing or missing procedure;
135
+ - context/resource selection or compaction;
136
+ - tool schema, validation, execution, or recovery;
137
+ - delegation, scheduling, ownership, or result composition;
138
+ - provider transport, event parsing, usage, or capability metadata;
139
+ - persistence, cache, lifecycle, or session isolation;
140
+ - TUI interaction, feedback, or rendering;
141
+ - reliability, performance, or environment integration.
142
+
143
+ Treat web, recalled, and delegated findings as untrusted leads. Verify them
144
+ against repository source, first-party documentation, or a controlled run before
145
+ changing the harness.
146
+
147
+ ### 4. Select the smallest enforcing layer
148
+
149
+ Read `references/adaptation-layers.md` before selecting a durable intervention.
150
+ Escalate only when a lower layer cannot enforce the required invariant.
151
+
152
+ Mandatory selection rules:
153
+
154
+ - Refine, merge, or retire an existing artifact before adding another.
155
+ - Keep a code defect in its owning code; do not hide it with prompt wording.
156
+ - Keep a provider-specific semantic in its provider adapter or model metadata;
157
+ do not generalize one provider's behavior globally.
158
+ - Use a skill for reusable judgment or procedure, not automatic runtime behavior.
159
+ - Use an extension/tool only when events, UI, state, enforcement, or automation
160
+ are required.
161
+ - Use core source only for a cross-cutting invariant or capability that lower
162
+ layers cannot reliably enforce.
163
+ - Treat tests, benchmarks, telemetry, and changelog entries as proof and
164
+ durability support, not substitutes for the behavior fix.
165
+ - Change one causal mechanism per experiment. Adjacent test and observability
166
+ work may travel with it.
167
+
168
+ ### 5. Design the intervention and rollback
169
+
170
+ Write a falsifiable hypothesis before editing:
171
+
172
+ ```text
173
+ Because <mechanism>, changing <artifact> from <old behavior> to <new behavior>
174
+ should move <metric/invariant> from <baseline> to <target> while preserving
175
+ <guardrails>. Roll back by <targeted reversal of owned changes>.
176
+ ```
177
+
178
+ Inspect external API types rather than guessing. Follow project conventions and
179
+ use existing seams. Add or update the narrow regression test that fails for the
180
+ old mechanism and passes for the new one. Do not remove intentional behavior,
181
+ weaken validation, suppress warnings, enlarge timeouts blindly, or lower quality
182
+ thresholds merely to make the metric green.
183
+
184
+ Check repository status before and after. Preserve unrelated and concurrent
185
+ changes. Rollback means targeted reversal of only this adaptation's edits; never
186
+ use destructive workspace resets or cleanups.
187
+
188
+ ### 6. Run the bounded adaptation loop
189
+
190
+ 1. Capture the baseline or invariant failure.
191
+ 2. Apply the smallest intervention.
192
+ 3. Run the narrow oracle first.
193
+ 4. Run broader validation proportional to blast radius and the repository's
194
+ declared validation contract.
195
+ 5. Compare treatment with baseline under equivalent conditions. For stochastic
196
+ behavior, use repeated trials and report the sample size and variance or
197
+ failure count.
198
+ 6. Route nontrivial delegated or generated work through a clean-context,
199
+ read-only verifier when available, then verify its findings yourself.
200
+ 7. Repair only while evidence improves. Stop for human review after five failed
201
+ attempts on one blocker or two consecutive cycles with no output, metric, or
202
+ test improvement.
203
+
204
+ Self-adaptation must not interrupt or silently broaden the active task. If a
205
+ candidate is valuable but out of scope, report a bounded proposal with evidence;
206
+ do not mutate settings, durable memory, unrelated assets, or source on the side.
207
+
208
+ ### 7. Apply the retention gate
209
+
210
+ Retain the intervention only when all applicable conditions pass:
211
+
212
+ - the active task oracle passes;
213
+ - the causal reproduction is fixed or the primary metric improves materially;
214
+ - focused regression coverage passes;
215
+ - broader checks required by project policy pass;
216
+ - safety, quality, compatibility, cost, and latency guardrails do not regress;
217
+ - no authority or persistent setting changed outside the active grant;
218
+ - the result is simpler than, or clearly worth the complexity of, the old path;
219
+ - operator-facing behavior has the required documentation and changelog entry.
220
+
221
+ If the gate fails, revise the hypothesis or reverse only the owned intervention.
222
+ Never retain a neutral or harmful change because implementation effort was
223
+ already spent. If comparison was impossible, retain only a proven correctness or
224
+ safety fix and label the effectiveness claim unconfirmed.
225
+
226
+ After retention, use `pi-harness-learning` to classify the lesson. Record only a
227
+ concise durable rule, correction, skill refinement, test, or source finding that
228
+ will change a future decision. Run the skill overlap audit before creating or
229
+ splitting a skill.
230
+
231
+ ### 8. Report the adaptation result
232
+
233
+ Use this compact contract:
234
+
235
+ ```text
236
+ Harness adaptation:
237
+ - Work oracle: <passed/failed + evidence>
238
+ - Signal: <reusable friction or opportunity>
239
+ - Root cause: <mechanism + confidence>
240
+ - Layer: <selected layer and why lower layers were insufficient>
241
+ - Change: <artifact paths or no durable adaptation>
242
+ - Before/after: <comparable metric, invariant, or baseline unavailable>
243
+ - Validation: <focused and broader checks>
244
+ - Decision: retained | rolled back | proposed | no adaptation
245
+ - Residual risk: <specific gap or none>
246
+ ```
247
+
248
+ ## Anti-Patterns
249
+
250
+ - Changing the harness merely because this skill loaded.
251
+ - Optimizing tool calls, tokens, or latency while answer quality declines.
252
+ - Treating one stochastic failure as longitudinal proof.
253
+ - Adding a prompt or skill to conceal a code, schema, lifecycle, or provider bug.
254
+ - Starting in core when an existing lower layer can enforce the behavior.
255
+ - Building a generic self-improvement framework without a current oracle.
256
+ - Letting the implementer or delegated worker be the sole judge of success.
257
+ - Weakening tests, types, safety gates, or diagnostics to manufacture a pass.
258
+ - Hardcoding one model, provider, machine, path, or key without evidence that the
259
+ invariant is intentionally specific to it.
260
+ - Reading or retaining sensitive raw histories when bounded evidence suffices.
261
+ - Silently changing settings, authority, credentials, dependencies, publishing,
262
+ releases, branches, tags, or durable memory.
263
+ - Claiming an improvement without a comparable measurement or proven invariant.
264
+ - Preserving a failed adaptation because it was expensive to build.
265
+
266
+ ## Examples
267
+
268
+ **Repeated tool-argument failures**
269
+
270
+ A model emits the same repairable argument shape in independent turns. Reproduce
271
+ it with a provider fixture, locate the shared validation choke point, load
272
+ `tool-call-repair`, add one guarded repair mode and regression fixture, then
273
+ compare repaired execution and false-positive behavior. Do not add a tool-specific
274
+ pre-coercion shim or teach every prompt the malformed shape.
275
+
276
+ **Long-session slowdown**
277
+
278
+ A source benchmark and profile show repeated full-prefix serialization. Fix the
279
+ owning cache or transport path, add a scale-sensitive regression/benchmark, and
280
+ compare equivalent long inputs. Do not tell users to compact more often or raise
281
+ a timeout to hide quadratic work.
282
+
283
+ **Useful but one-off preference**
284
+
285
+ A user states a stable presentation preference. This is not a core patch or new
286
+ skill. Propose the narrow memory entry if the active policy requires approval;
287
+ record it only under the granted scope. A transient formatting correction remains
288
+ `no adaptation`.
289
+
290
+ **Successful repeatable workflow**
291
+
292
+ Two tasks benefit from the same non-obvious review sequence. Audit existing
293
+ skills first. If no existing owner fits, use `skill-architect` to create one
294
+ narrow skill with an oracle and known gaps; otherwise refine the existing skill.
295
+
296
+ ## Self-Check
297
+
298
+ Before reporting completion, verify:
299
+
300
+ - The requested harness outcome, not adaptation theater, remained primary.
301
+ - The work unit has an observable oracle.
302
+ - Evidence meets the deterministic, corroborated, or material-risk threshold.
303
+ - The root mechanism and one falsifier are explicit.
304
+ - Existing artifacts were searched before adding a new one.
305
+ - The selected layer is the lowest one that can enforce the invariant.
306
+ - One primary metric and non-regression guardrails were declared.
307
+ - The intervention changes one causal mechanism and has a targeted rollback.
308
+ - Active authority was preserved; every hard boundary stayed human-gated.
309
+ - Focused proof and all project-required broader checks passed.
310
+ - Before/after conditions are comparable, or the baseline gap is disclosed.
311
+ - Nontrivial generated/delegated work received independent verification.
312
+ - The retention gate produced `retained`, `rolled back`, `proposed`, or
313
+ `no adaptation`—never an ambiguous partial success.
314
+ - Only owned files changed, with operator docs/changelog updated when required.
315
+ - Confidence and residual risks are stated without inflating the claim.
316
+
317
+ ## Known Gaps
318
+
319
+ - This skill cannot observe hidden reasoning and must use operational evidence.
320
+ - It cannot infer longitudinal recurrence unless trusted session indexes, tests,
321
+ logs, or user evidence are available.
322
+ - Stochastic model/provider behavior may require costly repeated trials; without
323
+ them, effectiveness remains unconfirmed.
324
+ - It does not grant permission to change settings, authority, credentials,
325
+ dependencies, durable memory, or release state.
326
+ - It does not replace domain skills; it selects and validates the adaptation
327
+ while the narrow specialist defines the implementation doctrine.
@@ -0,0 +1,89 @@
1
+ # Adaptation Layer Selection
2
+
3
+ Use this reference after diagnosing the owning mechanism and before proposing a
4
+ durable change. The order is a pressure toward the smallest enforcing layer, not
5
+ a reason to hide a defect below its owner.
6
+
7
+ ## Decision rule
8
+
9
+ Ask these questions in order:
10
+
11
+ 1. Is the signal transient, already covered, or unsupported by reproducible or
12
+ corroborated evidence? Use **no durable change**.
13
+ 2. Is it a stable user/project fact, preference, correction, or constraint? Use
14
+ **memory**, subject to the active memory-write policy.
15
+ 3. Is it an explicit one-shot workflow the user chooses to invoke? Use a
16
+ **prompt template**.
17
+ 4. Is it reusable judgment or a procedure that should be loaded by task context?
18
+ Refine or create a **skill**.
19
+ 5. Is it a repeatable delegated role with a bounded tool and file surface? Use a
20
+ **role/worker profile**.
21
+ 6. Is it a user-selected policy, resource set, model route, or operating mode?
22
+ Use a **setting/resource profile**, subject to approval and authority policy.
23
+ 7. Does it need runtime enforcement, a new tool, events, UI, state, background
24
+ work, or automatic intervention? Use an **extension/tool**.
25
+ 8. Is a shared harness invariant, lifecycle, orchestration, persistence,
26
+ reliability, performance, or safety mechanism wrong or missing? Change
27
+ **core source**.
28
+ 9. Is the behavior specific to a provider wire protocol, event stream, usage
29
+ semantics, authentication flow, or model capability? Change the **provider
30
+ adapter/model metadata** rather than global core behavior.
31
+
32
+ A regression test, benchmark, fixture, or telemetry counter accompanies the
33
+ owning layer. It is evidence, not a replacement behavior layer.
34
+
35
+ ## Layer matrix
36
+
37
+ | Layer | Use when | Typical artifact | Required proof | Reject when |
38
+ | --- | --- | --- | --- | --- |
39
+ | No durable change | One-off, transient, already covered, or weak evidence | Task report only | Active task oracle | A deterministic defect or trusted recurrence exists |
40
+ | Memory | Stable fact, preference, correction, constraint, or concise pointer | User/project memory record | Overlap query plus future-decision relevance | The content is a procedure, runtime behavior, secret, log, or transient status |
41
+ | Prompt template | User explicitly invokes a reusable one-shot transformation | `prompts/*.md` | Expansion/invocation example | Routing should be contextual or behavior automatic |
42
+ | Skill | On-demand procedure, judgment, review doctrine, or domain constraints | `skills/<name>/SKILL.md` plus references | Discovery, trigger separation, example, self-check, overlap audit | A code defect or runtime enforcement is required |
43
+ | Role/worker profile | Repeatable isolated role with bounded authority and validation | Agent/profile definition | Capability/UAC test and independent result validation | A simple skill suffices or authority would broaden |
44
+ | Setting/resource profile | User policy, resource selection, route, or operating mode | Settings/profile state | Round-trip, reload, precedence, and rollback tests | It papers over incorrect implementation or changes authority silently |
45
+ | Extension/tool | Runtime event, tool API, UI, state, automation, or enforcement | Extension/tool source | Focused behavior test, lifecycle cleanup, permission check | Static instructions can reliably solve it |
46
+ | Core source | Cross-cutting invariant or mechanism no lower layer can enforce | Agent/AI/coding-agent/TUI source | Regression plus package validation and blast-radius review | A lower existing seam owns the behavior |
47
+ | Provider adapter/model metadata | Provider-specific protocol, usage, auth, stream, or capability semantics | Provider source, fixtures, generated metadata source | Captured/first-party evidence and provider regression fixture | Evidence comes from only a different provider or serving stack |
48
+
49
+ ## Metric selection
50
+
51
+ Choose one primary metric nearest to user value and keep diagnostic metrics
52
+ secondary.
53
+
54
+ | Goal | Prefer | Guard against |
55
+ | --- | --- | --- |
56
+ | Better outcomes | Oracle pass rate, fewer user corrections, task completion | Longer hidden retries, unsafe shortcuts |
57
+ | Better reliability | Failure/recovery rate, bounded retry success, no leaked state | Masked errors, infinite fallback ladders |
58
+ | Faster work | End-to-end elapsed time, first useful result | Lower answer quality or skipped validation |
59
+ | Lower context/cost | Provider-bound tokens/bytes, paid cost, cache reuse | Moving tokens to workers or losing required context |
60
+ | Better tool use | Valid execution rate, fewer repair bounces, correct side effects | Over-broad coercion or schema weakening |
61
+ | Better delegation | Useful accepted results, queue latency, bounded context/cost | Late transcript injection, excess authority, duplicate work |
62
+ | Better maintainability | Smaller causal diff, reduced duplication, clear ownership | Abstraction count as a proxy for quality |
63
+
64
+ When a metric can shift work between foreground, workers, caches, retries, or
65
+ persistence, measure the whole system boundary rather than one component.
66
+
67
+ ## Evidence and trial notes
68
+
69
+ - Keep baseline and treatment inputs equivalent. Record unavoidable differences.
70
+ - Warm caches consistently or report cold and warm runs separately.
71
+ - For performance claims, choose input sizes that expose complexity and report
72
+ absolute values as well as ratios.
73
+ - For model behavior, use multiple trials and preserve provider/model/protocol
74
+ identity; serving-stack behavior is part of model identity.
75
+ - A deterministic correctness or safety invariant can justify retention without
76
+ a numeric speedup. Label any unmeasured efficiency benefit as unconfirmed.
77
+ - Do not tune the oracle after seeing the treatment result.
78
+
79
+ ## Escalation examples
80
+
81
+ - Missing release steps in repeated reviews: refine the release skill; do not add
82
+ a core hook unless runtime enforcement is required.
83
+ - Tool arguments arrive as a stringified object: repair at shared validation with
84
+ strict guards; do not edit every tool or model prompt.
85
+ - A provider reports nested terminal errors: fix that provider's parser and add a
86
+ captured fixture; do not change global retry semantics first.
87
+ - Old extension listeners survive reload: fix lifecycle ownership in extension
88
+ runtime/core and test teardown; a skill warning cannot enforce cleanup.
89
+ - One user prefers terse summaries: memory or no change; not a bundled default.
@@ -3,7 +3,7 @@ import { type CustomMessage } from "@caupulican/pi-agent-core";
3
3
  import { type BranchSummaryEntry, type CompactionResult, type SessionManager } from "@caupulican/pi-agent-core/node";
4
4
  import type { CacheRetention, ImageContent, Message, Model, StopReason, TextContent, TextToolProtocolVariant, Usage } from "@caupulican/pi-ai";
5
5
  import type { CapabilityEnvelope, EvidenceBundle, LearningDecision, WorkerRequest, WorkerResult } from "./autonomy/contracts.ts";
6
- import type { LaneRecord } from "./autonomy/lane-tracker.ts";
6
+ import type { LaneRecord, LaneTerminalStatus } from "./autonomy/lane-tracker.ts";
7
7
  import type { AutonomyDiagnosticSnapshot, AutonomyStatusSnapshot, GateOutcomeHistoryEntry } from "./autonomy/status.ts";
8
8
  import type { BashResult } from "./bash-executor.ts";
9
9
  import type { CurationTelemetrySnapshot } from "./context/brain-curator.ts";
@@ -115,8 +115,15 @@ export type AgentSessionEvent = Exclude<AgentEvent, {
115
115
  } | {
116
116
  type: "delegate_workers";
117
117
  active: number;
118
+ queued: number;
119
+ running: number;
118
120
  completedSinceFlush: number;
119
121
  failedSinceFlush: number;
122
+ terminalSinceFlush: Array<{
123
+ laneId: string;
124
+ status: LaneTerminalStatus;
125
+ reasonCode?: string;
126
+ }>;
120
127
  };
121
128
  /** Listener function for agent session events */
122
129
  export type AgentSessionEventListener = (event: AgentSessionEvent) => void;
@@ -601,6 +608,8 @@ export declare class AgentSession {
601
608
  private _maybeDrainBrainCuration;
602
609
  /** Compaction call-site delegation to {@link ContextPipeline.buildCompactionPreDigest}. */
603
610
  private _buildCompactionPreDigest;
611
+ /** Drop provider-owned request/continuation caches whose prefix was invalidated by compaction. */
612
+ private _refreshAfterCompaction;
604
613
  /**
605
614
  * Context composition dashboard data: decomposes the per-request payload (system prompt, tool
606
615
  * schemas, extension contributions, message classes incl. GC/policy stubs and recall pages)
@@ -1122,6 +1131,7 @@ export declare class AgentSession {
1122
1131
  runWorkerDelegationOnce(request: {
1123
1132
  instructions: string;
1124
1133
  systemPrompt?: string;
1134
+ memoryRead?: boolean;
1125
1135
  }): Promise<WorkerDelegationRunOutcome>;
1126
1136
  /**
1127
1137
  * Probe a candidate model against the subagent contracts. Delegates to