Skip to content

Commit 095f30a

Browse files
authored
feat(skills): review interrupted deep turns in experience review (#115887)
* feat(skills): review interrupted deep turns in experience review * test(skills): stabilize experience-review live eval and cover interrupted turns
1 parent 107f1e6 commit 095f30a

5 files changed

Lines changed: 167 additions & 19 deletions

File tree

‎docs/tools/self-learning.md‎

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -42,13 +42,19 @@ write bounded and recoverable.
4242

4343
### Experience review
4444

45-
After substantial successful work, OpenClaw can run one isolated background
46-
review to find a reusable recovery technique or a stable procedure that would
47-
remove at least two future model or tool round trips.
45+
After substantial work, OpenClaw can run one isolated background review to find
46+
a reusable recovery technique or a stable procedure that would remove at least
47+
two future model or tool round trips. Deep turns the user interrupted qualify
48+
too: the wrong path and its correction are exactly the evidence worth keeping.
49+
The reviewer is told when a turn was interrupted and captures only procedures
50+
that visibly worked before the stop. Turns that ended in a provider or prompt
51+
error never schedule a review; that failure is transient environment noise, and
52+
a review on the same model would likely hit it again.
4853

4954
Experience review starts only when all of these conditions hold:
5055

51-
- the foreground turn completed successfully;
56+
- the foreground turn completed or was interrupted, but did not end in a
57+
provider or prompt error;
5258
- the current turn used at least 10 model iterations;
5359
- the run was an eligible foreground conversation, not cron, heartbeat, memory,
5460
overflow, hook, subagent, or review work;
@@ -171,7 +177,7 @@ applying them.
171177

172178
Deterministic correction capture does not make an extra model call. Experience
173179
review adds one bounded model run on the configured provider only after a
174-
substantial successful turn, not after every message. The review can make more
180+
substantial turn, not after every message. The review can make more
175181
than one provider request while it inspects or drafts its single proposal.
176182

177183
The reviewer receives only the current turn beginning with its most recent user
@@ -256,8 +262,8 @@ Check the following:
256262

257263
1. `skills.workshop.autonomous.mode` is `propose` or `auto` in the active Gateway
258264
config.
259-
2. The correction uses durable language, or the successful turn reached at least
260-
10 model iterations.
265+
2. The correction uses durable language, or the turn reached at least 10 model
266+
iterations without ending in a provider or prompt error.
261267
3. The conversation is eligible foreground work.
262268
4. The runtime reported the resolved model and actual `skill_workshop`
263269
availability.

‎src/skills/workshop/experience-review-prompt.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ type ExperienceReviewPromptCandidate = {
77
ctx: { runId?: string };
88
transcript: string;
99
modelIterations: number;
10+
turnAborted?: boolean;
1011
};
1112

1213
function safeJson(value: unknown): string {
@@ -73,7 +74,7 @@ export function buildSkillExperienceReviewPrompt(
7374
candidate: ExperienceReviewPromptCandidate,
7475
): string {
7576
return [
76-
"Review this completed agent turn after the foreground run has ended.",
77+
"Review this agent turn after the foreground run has ended.",
7778
"",
7879
"This is a conservative learning pass. Use skill_workshop to mutate a proposal only when at least one high-value condition has concrete evidence in the trajectory:",
7980
"- the model struggled, took a wrong path, needed correction, repeated failures, or found a reusable recovery technique; or",
@@ -87,7 +88,14 @@ export function buildSkillExperienceReviewPrompt(
8788
"",
8889
"Use list/inspect before mutation when useful. Prefer revising a relevant pending proposal. Otherwise create one broad skill. Make at most one create/revise call. The tool cannot update a live skill or apply, reject, or quarantine a proposal. If nothing clears the bar, make no mutation and answer NOTHING_TO_LEARN.",
8990
"",
90-
`Completed run: ${candidate.ctx.runId ?? "unknown"}`,
91+
candidate.turnAborted === true
92+
? `Interrupted run (stopped before completion): ${candidate.ctx.runId ?? "unknown"}`
93+
: `Completed run: ${candidate.ctx.runId ?? "unknown"}`,
94+
...(candidate.turnAborted === true
95+
? [
96+
"The trajectory may end mid-task. Only capture procedures that visibly worked before the interruption.",
97+
]
98+
: []),
9199
`Model iterations in turn: ${candidate.modelIterations}`,
92100
"",
93101
"Trajectory:",

‎src/skills/workshop/experience-review.live.test.ts‎

Lines changed: 73 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,11 @@ const tempDirs = createTrackedTempDirs();
1717
let testState: OpenClawTestState;
1818
let workspaceDir = "";
1919

20-
function candidate(runId: string, messages: unknown[]): ExperienceReviewCandidate {
20+
function candidate(
21+
runId: string,
22+
messages: unknown[],
23+
options: { turnAborted?: boolean } = {},
24+
): ExperienceReviewCandidate {
2125
const modelId = process.env.OPENCLAW_LIVE_SKILL_EXPERIENCE_MODEL ?? "gpt-5.6-luna";
2226
return {
2327
ctx: {
@@ -54,6 +58,7 @@ function candidate(runId: string, messages: unknown[]): ExperienceReviewCandidat
5458
},
5559
},
5660
agents: {
61+
entries: { main: { default: true } },
5762
defaults: {
5863
model: { primary: `openai/${modelId}` },
5964
models: {
@@ -65,20 +70,33 @@ function candidate(runId: string, messages: unknown[]): ExperienceReviewCandidat
6570
},
6671
},
6772
skills: { workshop: { autonomous: { mode: "propose" } } },
73+
// Only the OpenAI provider plugin is needed. A cold unrestricted load
74+
// compiles all bundled extensions and runs provider discovery inside the
75+
// review lane, which can exceed the lane's no-progress watchdog.
76+
plugins: { allow: ["openai"] },
6877
},
6978
transcript: formatSkillExperienceReviewTranscript(messages),
7079
modelIterations: 10,
80+
...(options.turnAborted === undefined ? {} : { turnAborted: options.turnAborted }),
7181
};
7282
}
7383

7484
describeLive("skill experience review live OpenAI eval", () => {
7585
beforeAll(async () => {
86+
// Full home isolation: the embedded review resolves the shared-main auth
87+
// store via HOME, and a real ~/.openclaw with pending doctor migration
88+
// must never leak into (or fail) this live run.
7689
testState = await createOpenClawTestState({
77-
layout: "state-only",
90+
layout: "home",
7891
prefix: "openclaw-live-skill-review-state-",
7992
});
8093
workspaceDir = await tempDirs.make("openclaw-live-skill-review-workspace-");
81-
});
94+
// Warm the plugin runtime outside the review lane: the first load compiles
95+
// extensions synchronously and can exceed the lane's no-progress watchdog
96+
// on a loaded machine.
97+
const { ensureRuntimePluginsLoaded } = await import("../../agents/runtime-plugins.js");
98+
ensureRuntimePluginsLoaded({ config: candidate("warmup", []).config ?? {}, workspaceDir });
99+
}, 600_000);
82100

83101
afterAll(async () => {
84102
await testState.cleanup();
@@ -174,5 +192,56 @@ describeLive("skill experience review live OpenAI eval", () => {
174192
});
175193
const afterNegative = await listSkillProposals({ workspaceDir });
176194
expect(afterNegative.proposals).toEqual(afterPositive.proposals);
177-
}, 180_000);
195+
196+
const interruptedMessages = [
197+
{
198+
role: "user",
199+
content: "Publish the package. The registry keeps rejecting the token.",
200+
},
201+
{ role: "assistant", content: [{ type: "toolCall", name: "publish", arguments: {} }] },
202+
{ role: "toolResult", toolName: "publish", isError: true, content: "401 invalid token" },
203+
{
204+
role: "assistant",
205+
content: [{ type: "toolCall", name: "publish", arguments: { retry: true } }],
206+
},
207+
{ role: "toolResult", toolName: "publish", isError: true, content: "401 invalid token" },
208+
{ role: "assistant", content: "Retrying does not help; the stored scope must be wrong." },
209+
{
210+
role: "assistant",
211+
content: [{ type: "toolCall", name: "exec", arguments: { command: "registry whoami" } }],
212+
},
213+
{
214+
role: "toolResult",
215+
toolName: "exec",
216+
content: "authenticated to legacy-registry.example, expected registry.example",
217+
},
218+
{
219+
role: "assistant",
220+
content: [
221+
{
222+
type: "toolCall",
223+
name: "exec",
224+
arguments: { command: "registry login --host registry.example" },
225+
},
226+
],
227+
},
228+
{ role: "toolResult", toolName: "exec", content: "login ok" },
229+
{ role: "assistant", content: [{ type: "toolCall", name: "publish", arguments: {} }] },
230+
{ role: "toolResult", toolName: "publish", content: "published 1.2.3" },
231+
{ role: "assistant", content: "Publish verified. Moving on to the release notes." },
232+
{
233+
role: "assistant",
234+
content: [{ type: "toolCall", name: "read", arguments: { path: "CHANGELOG.md" } }],
235+
},
236+
];
237+
238+
const interruptedCandidate = candidate("live-interrupted", interruptedMessages, {
239+
turnAborted: true,
240+
});
241+
await runSkillExperienceReview(interruptedCandidate, {
242+
getCurrentConfig: () => interruptedCandidate.config ?? {},
243+
});
244+
const afterInterrupted = await listSkillProposals({ workspaceDir });
245+
expect(afterInterrupted.proposals.length).toBeGreaterThan(afterNegative.proposals.length);
246+
}, 300_000);
178247
});

‎src/skills/workshop/experience-review.test.ts‎

Lines changed: 58 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ function completedRun(
1313
options: {
1414
iterations?: number;
1515
success?: boolean;
16+
error?: string;
1617
sessionKey?: string;
1718
runId?: string;
1819
mode?: "off" | "propose" | "auto";
@@ -26,6 +27,7 @@ function completedRun(
2627
return {
2728
event: {
2829
success: options.success ?? true,
30+
...(options.error === undefined ? {} : { error: options.error }),
2931
messages: [
3032
{ role: "user", content: "Diagnose and repair the workflow." },
3133
...Array.from({ length: iterations }, (_, index) => ({
@@ -186,7 +188,7 @@ describe("skill experience review scheduler", () => {
186188
).resolves.toBeDefined();
187189
});
188190

189-
it("skips short, failed, disabled, metadata-missing, restricted, and internal runs", async () => {
191+
it("skips short, errored, disabled, metadata-missing, restricted, and internal runs", async () => {
190192
vi.useFakeTimers();
191193
const runReview = vi.fn().mockResolvedValue(undefined);
192194
const scheduler = createSkillExperienceReviewScheduler({
@@ -195,7 +197,7 @@ describe("skill experience review scheduler", () => {
195197
});
196198

197199
scheduler.schedule(completedRun({ iterations: 9 }));
198-
scheduler.schedule(completedRun({ success: false }));
200+
scheduler.schedule(completedRun({ success: false, error: "provider failed" }));
199201
scheduler.schedule(completedRun({ compacted: true, sessionKey: "agent:main:compacted" }));
200202
scheduler.schedule(completedRun({ mode: "off" }));
201203
scheduler.schedule(
@@ -253,7 +255,7 @@ describe("skill experience review scheduler", () => {
253255
scheduler.clear();
254256
});
255257

256-
it("discards a queued candidate when the same run later fails", async () => {
258+
it("discards a queued candidate when the same run later errors", async () => {
257259
vi.useFakeTimers();
258260
const runReview = vi.fn().mockResolvedValue(undefined);
259261
const scheduler = createSkillExperienceReviewScheduler({
@@ -262,12 +264,49 @@ describe("skill experience review scheduler", () => {
262264
});
263265

264266
scheduler.schedule(completedRun({ runId: "retried-run" }));
265-
scheduler.schedule(completedRun({ runId: "retried-run", success: false }));
267+
scheduler.schedule(completedRun({ runId: "retried-run", success: false, error: "boom" }));
266268
await vi.runAllTimersAsync();
267269
expect(runReview).not.toHaveBeenCalled();
268270
scheduler.clear();
269271
});
270272

273+
it("reviews a deep user-aborted turn and marks the candidate interrupted", async () => {
274+
vi.useFakeTimers();
275+
const runReview = vi.fn().mockResolvedValue(undefined);
276+
const scheduler = createSkillExperienceReviewScheduler({
277+
isSystemActive: () => false,
278+
runReview,
279+
});
280+
281+
scheduler.schedule(completedRun({ success: false }));
282+
await vi.advanceTimersByTimeAsync(30_000);
283+
expect(runReview).toHaveBeenCalledTimes(1);
284+
expect(runReview.mock.calls[0]?.[0]).toMatchObject({
285+
modelIterations: 10,
286+
turnAborted: true,
287+
});
288+
scheduler.clear();
289+
});
290+
291+
it("replaces queued evidence when the same run is later aborted deep in the turn", async () => {
292+
vi.useFakeTimers();
293+
const runReview = vi.fn().mockResolvedValue(undefined);
294+
const scheduler = createSkillExperienceReviewScheduler({
295+
isSystemActive: () => false,
296+
runReview,
297+
});
298+
299+
scheduler.schedule(completedRun({ runId: "retried-run", iterations: 10 }));
300+
scheduler.schedule(completedRun({ runId: "retried-run", iterations: 12, success: false }));
301+
await vi.advanceTimersByTimeAsync(30_000);
302+
expect(runReview).toHaveBeenCalledTimes(1);
303+
expect(runReview.mock.calls[0]?.[0]).toMatchObject({
304+
modelIterations: 12,
305+
turnAborted: true,
306+
});
307+
scheduler.clear();
308+
});
309+
271310
it("preserves the complete requester role identity for delayed policy checks", async () => {
272311
vi.useFakeTimers();
273312
const runReview = vi.fn().mockResolvedValue(undefined);
@@ -373,6 +412,21 @@ describe("skill experience review scheduler", () => {
373412
expect(prompt).toContain("cannot update a live skill");
374413
expect(prompt).toContain("NOTHING_TO_LEARN");
375414
expect(prompt).toContain("[tool call: exec]");
415+
expect(prompt).toContain("Completed run: run-1");
416+
expect(prompt).not.toContain("Interrupted run");
417+
});
418+
419+
it("flags interrupted turns in the review prompt", () => {
420+
const params = completedRun({ success: false });
421+
const prompt = buildSkillExperienceReviewPrompt({
422+
ctx: params.ctx,
423+
transcript: formatSkillExperienceReviewTranscript(params.event.messages),
424+
modelIterations: 10,
425+
turnAborted: true,
426+
});
427+
428+
expect(prompt).toContain("Interrupted run (stopped before completion): run-1");
429+
expect(prompt).toContain("Only capture procedures that visibly worked");
376430
});
377431
});
378432

‎src/skills/workshop/experience-review.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ const log = createSubsystemLogger("skills/workshop");
3131
type ExperienceReviewAgentEndEvent = {
3232
messages: unknown[];
3333
success: boolean;
34+
error?: string;
3435
};
3536

3637
type ExperienceReviewAgentContext = {
@@ -73,6 +74,7 @@ export type ExperienceReviewCandidate = {
7374
config?: OpenClawConfig;
7475
transcript: string;
7576
modelIterations: number;
77+
turnAborted?: boolean;
7678
};
7779

7880
type ExperienceReviewRunDeps = {
@@ -276,9 +278,14 @@ export function createSkillExperienceReviewScheduler(deps: ExperienceReviewSched
276278
return;
277279
}
278280
const existing = pendingBySession.get(sessionKey);
281+
// Errored completions (provider/prompt failures) are transient environment
282+
// noise, not learnable evidence, and a same-model review would likely hit
283+
// the same failure. User aborts carry no error and stay eligible: deep
284+
// interrupted turns are exactly where corrective evidence lives.
285+
const errored = typeof params.event.error === "string" && params.event.error.trim() !== "";
279286
if (
280287
existing &&
281-
!params.event.success &&
288+
errored &&
282289
params.ctx.runId?.trim() &&
283290
params.ctx.runId === existing.candidate.ctx.runId
284291
) {
@@ -293,6 +300,9 @@ export function createSkillExperienceReviewScheduler(deps: ExperienceReviewSched
293300
if (existing) {
294301
arm(sessionKey, existing, EXPERIENCE_REVIEW_IDLE_MS);
295302
}
303+
if (errored) {
304+
return;
305+
}
296306
if (resolveSkillWorkshopConfig(params.config).autonomous.mode === "off") {
297307
return;
298308
}
@@ -314,7 +324,7 @@ export function createSkillExperienceReviewScheduler(deps: ExperienceReviewSched
314324
: Number.isSafeInteger(reportedModelIterations) && reportedModelIterations >= 0
315325
? reportedModelIterations
316326
: 0;
317-
if (params.event.success && modelIterations >= EXPERIENCE_REVIEW_MIN_MODEL_ITERATIONS) {
327+
if (modelIterations >= EXPERIENCE_REVIEW_MIN_MODEL_ITERATIONS) {
318328
if (!existing && pendingBySession.size >= EXPERIENCE_REVIEW_MAX_PENDING) {
319329
const oldest = pendingBySession.entries().next().value as
320330
| [string, PendingExperienceReview]
@@ -357,6 +367,7 @@ export function createSkillExperienceReviewScheduler(deps: ExperienceReviewSched
357367
...(params.config ? { config: params.config } : {}),
358368
transcript: formatSkillExperienceReviewTranscript(turnMessages),
359369
modelIterations,
370+
turnAborted: !params.event.success,
360371
};
361372
const pending = existing ?? { candidate, generation: 0 };
362373
pending.candidate = candidate;

0 commit comments

Comments
 (0)