Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(skillopt): verify rollout hook scores, keep baseline out of candidate count, no resume command for explicit tasks; verify fixes

garrytana37612b93f5e
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index ee69192b8f..f8cd5abb8f 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -1307,6 +1307,14 @@ More: [docs/guides/move-to-postgres.md#graduated-datastore](../../docs/guides/mo
|---|---|---|---|---|---|---|
| `gbrain eval run-all` was asked for a suite it does not run in-process (longmemeval or replay); nothing ran. | run-all runs only wired suites (brainbench). Recording a skipped run and exiting 0 would read as a completed sweep with no numbers behind it. | Run each requested suite with its own command (`gbrain eval longmemeval <dataset.jsonl> --mode <mode> --record`, `gbrain eval replay --mode <mode>`), once per mode, or drop it from --suites. | agent | `repeat the read that failed` | 1 | no |
+### explicit_tasks_conflict
+
+<a id="explicit_tasks_conflict"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| SkillOpt was given explicit task lists and a benchmark file; it takes one or the other. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+
### export_limit
<a id="export_limit"></a>
diff --git a/plugin/skills/skill-optimizer/SKILL.md b/plugin/skills/skill-optimizer/SKILL.md
index 42b77d9ae7..2827e7dfc7 100644
--- a/plugin/skills/skill-optimizer/SKILL.md
+++ b/plugin/skills/skill-optimizer/SKILL.md
@@ -58,7 +58,9 @@ gbrain skillopt <skill-name> [flags]
│
├── Baseline eval on D_sel (sets best_sel_score)
│
- ├── for epoch in 1..N:
+ ├── default: one rewrite of the body from a D_train forward pass,
+ │ accepted only through the same D12 validation gate
+ ├── --loop (opt-in; has not beaten one-shot on benchmarks): for epoch in 1..N:
│ for step in 1..steps_per_epoch:
│ ├── forward pass: rollouts on D_train batch
│ ├── backward pass: reflect × 2 (failures + successes per D7)
@@ -144,7 +146,8 @@ https://github.com/garrytan/gbrain/blob/master/docs/tutorials/improving-skills-w
| Costly run, want preview | Add `--dry-run` |
| Bundled skill (skills/ in gbrain repo) | Default writes proposed.md; to commit in place add `--allow-mutate-bundled` AND `--held-out <path>` (>=5 benchmark-disjoint tasks) — else it hard-refuses. Plugin installs cannot mutate bundled skills in place (the snapshot is read-only): copy the SKILL.md into your own skills dir to iterate, or stick with the default proposed.md review flow |
| Want to review changes before applying | Add `--no-mutate` (writes proposed.md, no held-out needed) |
-| Guard against benchmark overfitting | Add `--held-out <path>` — a candidate that beats the benchmark but regresses on the held-out set is refused |
+| Guard against benchmark overfitting | Add `--held-out <path>` — checked once on the final candidate; one that beats the benchmark but regresses on the held-out set is refused |
+| Want the iterative edit loop | Add `--loop` (about 1.8x the cost; it tied one-shot on gbrain-evals Cat 31) |
| Mid-run crash | `gbrain skillopt foo --resume <run-id>` |
## Output Format
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index 86b6d796ca..3aa4900645 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -51,8 +51,7 @@ src/core/ops/search.ts query.handler 338 +5 GBRA-81 item 5 per-stage search timi
src/core/persistence/page-prepare.ts prepareInlineOrSegmentedMutation 303 +3 #7841: a put_page that asks for visibility: private is kept or refused (visibility_not_applied), checked before the no-op test and after the trust stamp (logic in persistence/visibility-request.ts)
src/core/progressive-batch/orchestrator.ts runProgressiveBatch 348 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/remediation/run.ts runRemediation 428 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/core/skillopt/orchestrator.ts runOptimizationLoop 704 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/core/skillopt/orchestrator.ts runOptimizationLoop>withBudgetTracker(#1) 405 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
+src/core/skillopt/orchestrator.ts runOptimizationLoop 646 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/sources-ops.ts addSource 317 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/think/index.ts runThink 450 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/mcp/http-transport.ts startHttpTransport 409 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): dispatch resultRows from X-Gbrain-Client / mcp.result_rows (logic in mcp/result-rows.ts)
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index f53a697d43..198f7e6a92 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -275,6 +275,7 @@ export const CODES = {
why: "Entity types come from the active pack per source (the get_health predicate). Grading a fixed person/company list would count the wrong population on a pack with its own entity types, so the checks name the sources whose pack failed.",
suggestion: 'Run gbrain schema active --json (add --source <id> for a named source) to see which pack is active and why it did not load; fix or reinstall the pack, then gbrain onboard --json.' },
eval_suite_unwired: { class: 'caller', summary: "`gbrain eval run-all` was asked for a suite it does not run in-process (longmemeval or replay); nothing ran.", why: "run-all runs only wired suites (brainbench). Recording a skipped run and exiting 0 would read as a completed sweep with no numbers behind it.", suggestion: 'Run each requested suite with its own command (`gbrain eval longmemeval <dataset.jsonl> --mode <mode> --record`, `gbrain eval replay --mode <mode>`), once per mode, or drop it from --suites.' },
+ explicit_tasks_conflict: { class: 'caller', summary: "SkillOpt was given explicit task lists and a benchmark file; it takes one or the other." },
export_limit: { class: 'caller', summary: "This migration is bounded to 5,000 active pages per source; split or use a reviewed bulk export." },
extraction_failed: { class: 'server', summary: "The accepted atom extraction failed (malformed output, or a response stopped before the end); a new attempt needs approval.", why: "The drain retries a failed managed atom batch on its own up to 3 times per content (then holds it, code held_failed); this code reports a failed explicit retry, or a failure the drain cannot attribute to a checkpoint, so the same input is not paid for again without approval." },
extractor_identity_mismatch: { class: 'server', summary: "The approved extractor differs from the installed extractor; this receipt cannot resume or admit another revision." },
diff --git a/src/core/skillopt/benchmark.ts b/src/core/skillopt/benchmark.ts
index ebd2949d8d..7776db386f 100644
--- a/src/core/skillopt/benchmark.ts
+++ b/src/core/skillopt/benchmark.ts
@@ -349,13 +349,13 @@ export function loadRunTasks(opts: {
}): { bench: Benchmark; split: BenchmarkSplit } {
if (!opts.tasks) {
if (!opts.benchmarkPath) {
- throw errorFor({ class: 'BenchmarkNotFound', code: 'benchmark_not_found', message: 'No benchmark: pass benchmarkPath or explicit tasks.', hint: 'Pass --benchmark <path>.' });
+ throw errorFor({ class: 'BenchmarkNotFound', code: 'benchmark_not_found', message: 'No benchmark: pass benchmarkPath or explicit tasks.' });
}
const bench = loadBenchmark(opts.benchmarkPath, { bootstrapReviewed: opts.bootstrapReviewed });
return { bench, split: splitBench(bench, opts.split ?? [4, 1, 5]) };
}
if (opts.benchmarkPath) {
- throw errorFor({ class: 'BadSplit', code: 'explicit_tasks_conflict', message: 'Explicit tasks and a benchmark file were both given.', hint: 'Pass either tasks or benchmarkPath, not both.' });
+ throw errorFor({ class: 'BadSplit', code: 'explicit_tasks_conflict', message: 'Explicit tasks and a benchmark file were both given; pass one of them.' });
}
const label = '(explicit tasks)';
const check = (list: BenchmarkTask[], name: string) => list.map((t, i) => validateRow(t, i + 1, `${label} ${name}`));
@@ -364,15 +364,15 @@ export function loadRunTasks(opts: {
const seen = new Set<string>();
for (const t of all) {
if (seen.has(t.task_id)) {
- throw errorFor({ class: 'BenchmarkDuplicateId', code: 'benchmark_duplicate_task_id', message: `task_id '${t.task_id}' appears more than once across train, sel and test.`, hint: 'Each task belongs to exactly one list.' });
+ throw errorFor({ class: 'BenchmarkDuplicateId', code: 'benchmark_duplicate_task_id', message: `task_id '${t.task_id}' appears more than once across train, sel and test; each task belongs to exactly one list.` });
}
seen.add(t.task_id);
}
if (split.train.length === 0) {
- throw errorFor({ class: 'BenchmarkEmpty', code: 'benchmark_empty', message: 'Explicit train list is empty.', hint: 'Pass at least one train task.' });
+ throw errorFor({ class: 'BenchmarkEmpty', code: 'benchmark_empty', message: 'Explicit train list is empty; pass at least one train task.' });
}
if (split.sel.length < D_SEL_MIN_SIZE) {
- throw errorFor({ class: 'DSelTooSmall', code: 'd_sel_too_small', message: `Explicit sel list has ${split.sel.length} task(s) (need >=${D_SEL_MIN_SIZE} for meaningful validation).`, hint: `Pass at least ${D_SEL_MIN_SIZE} selection tasks.` });
+ throw errorFor({ class: 'DSelTooSmall', code: 'd_sel_too_small', message: `Explicit sel list has ${split.sel.length} task(s); pass at least ${D_SEL_MIN_SIZE} for meaningful validation.` });
}
const canonical = JSON.stringify({ train: split.train, sel: split.sel, test: split.test });
return { bench: { source_path: label, tasks: all, benchmark_sha8: createHash('sha256').update(canonical).digest('hex').slice(0, 8) }, split };
diff --git a/src/core/skillopt/orchestrator.ts b/src/core/skillopt/orchestrator.ts
index 2a83211921..61a37d4c7d 100644
--- a/src/core/skillopt/orchestrator.ts
+++ b/src/core/skillopt/orchestrator.ts
@@ -614,7 +614,7 @@ async function runOptimizationLoop(
...(hook ? { rolloutHook: hook } : {}),
});
rollouts[phase] += tasks.length * runsPerTask;
- if (phase === 'sel_gate') selCandidates.add(createHash('sha256').update(skillText).digest('hex'));
+ if (phase === 'sel_gate' && skillText !== baselineText) selCandidates.add(createHash('sha256').update(skillText).digest('hex'));
return result;
};
// D2: with a held-out set, nothing is written until the single held-out
@@ -1009,7 +1009,7 @@ async function runOptimizationLoop(
...(remediation.length > 0 ? { remediation } : {}),
reflect_max_tokens: reflectCap.maxTokens,
reflect_max_tokens_source: reflectCap.source,
- ...(checkpointRetained ? { resume_command: buildResumeCommand(skillName, runId, runSpec, failureCode, {
+ ...(checkpointRetained && !opts.tasks ? { resume_command: buildResumeCommand(skillName, runId, runSpec, failureCode, {
mode: opts.mode, maxCostUsd: opts.maxCostUsd, maxRuntimeMin: opts.maxRuntimeMin,
force: opts.force,
modelsStrict: opts.modelsStrict === true,
diff --git a/src/core/skillopt/validate-gate.ts b/src/core/skillopt/validate-gate.ts
index 1484b23c62..63824d4fca 100644
--- a/src/core/skillopt/validate-gate.ts
+++ b/src/core/skillopt/validate-gate.ts
@@ -87,8 +87,11 @@ async function hookBatch(opts: ValidateGateOpts, hook: RolloutBatchHook, runsPer
epoch: opts.epoch ?? 0,
step: opts.step ?? 0,
}, opts.abortSignal);
- if (!Array.isArray(rows) || rows.length !== opts.selSet.length || rows.some((r) => !Array.isArray(r) || r.length !== runsPerTask)) {
- throw new Error(`${SKILLOPT_HOOK_INFRA_ERROR}: rollout hook returned a malformed batch for ${opts.phase ?? 'sel_gate'} (want ${opts.selSet.length} rows of ${runsPerTask})`);
+ const needsTrajectory = opts.phase === 'train_forward';
+ const badRun = (r: ScoredRollout | undefined) => typeof r?.score !== 'number' || !(r.score >= 0 && r.score <= 1)
+ || (needsTrajectory && (typeof r.trajectory !== 'object' || r.trajectory === null));
+ if (!Array.isArray(rows) || rows.length !== opts.selSet.length || rows.some((r) => !Array.isArray(r) || r.length !== runsPerTask || r.some(badRun))) {
+ throw new Error(`${SKILLOPT_HOOK_INFRA_ERROR}: rollout hook returned a malformed batch for ${opts.phase ?? 'sel_gate'} (want ${opts.selSet.length} rows of ${runsPerTask} runs, each a score in [0,1]${needsTrajectory ? ' with a trajectory' : ''})`);
}
return opts.selSet.map((task, i) => {
const runs = rows[i]!.map((r) => r.score);
diff --git a/test/skillopt/benchmark-hooks.test.ts b/test/skillopt/benchmark-hooks.test.ts
index 994d78d208..2a5d14fd77 100644
--- a/test/skillopt/benchmark-hooks.test.ts
+++ b/test/skillopt/benchmark-hooks.test.ts
@@ -35,6 +35,9 @@ describe('rollout hook (B1.3)', () => {
['too few rows', (req: RolloutBatchRequest) => req.tasks.slice(1).map(() => [row(1), row(1), row(1)])],
['too few runs', (req: RolloutBatchRequest) => req.tasks.map(() => [row(1)])],
['not an array', () => ({}) as unknown as ScoredRollout[][]],
+ ['a string score', (req: RolloutBatchRequest) => req.tasks.map(() => [row(1), row(1), { ...row(1), score: '0.9' } as unknown as ScoredRollout])],
+ ['a NaN score', (req: RolloutBatchRequest) => req.tasks.map(() => [row(1), row(1), row(Number.NaN)])],
+ ['a score above 1', (req: RolloutBatchRequest) => req.tasks.map(() => [row(7), row(7), row(7)])],
])('a malformed batch (%s) is an infra error that aborts, never a score', async (_name, reply) => {
const hook: RolloutBatchHook = async (req) => reply(req);
const err = await runValidationGate({ engine, candidateSkillText: 'S', selSet: tasks('s', 5), bestScore: 0, targetModel: 'm', rolloutHook: hook })
@@ -42,6 +45,13 @@ describe('rollout hook (B1.3)', () => {
expect(String(err?.message)).toContain(SKILLOPT_HOOK_INFRA_ERROR);
expect(isSkilloptMustAbort(err)).toBe(true);
});
+
+ test('a train_forward row without a trajectory is an infra error', async () => {
+ const hook: RolloutBatchHook = async (req) => req.tasks.map(() => [{ score: 1 } as ScoredRollout]);
+ const err = await scoreSkillPerTask({ engine, skillText: 'S', tasks: tasks('t', 2), targetModel: 'm', runsPerTask: 1, phase: 'train_forward', rolloutHook: hook })
+ .then(() => null, (e) => e);
+ expect(String(err?.message)).toContain(SKILLOPT_HOOK_INFRA_ERROR);
+ });
});
describe('explicit task lists (B1.2)', () => {