Files
gbrain/src/core/fail-improve.ts
T
83e55ffcdb v0.22.16 feat: gbrain claw-test — end-to-end fresh-install friction harness (#522)
* feat: hermeticity migration — every $GBRAIN_HOME write site honors the env override

configDir() in src/core/config.ts already implemented $GBRAIN_HOME as a
parent-dir override (returns <override>/.gbrain), but ~12 consumers built paths
from os.homedir() directly and bypassed it. Critically, loadConfig/saveConfig
themselves used a private getConfigDir() that ignored the env. Fixed.

Migrated every write site to gbrainPath() — fail-improve, validator-lint, cycle
lock, shell-audit, backpressure-audit, sync-failures, integrity logs,
integrations heartbeat, init pglite path, migrate-engine manifest, import
checkpoint, v0_13_1 rollback, v0_14_0 host-work. Read-side host-detection in
init.ts (~/.claude / ~/.openclaw probes) intentionally NOT migrated; that's a
v1.1 follow-up under a separate $GBRAIN_HOST_HOME override.

Adds gbrainPath(...segments) sugar plus path validation: $GBRAIN_HOME must be
absolute and contain no '..' segments (throws GbrainHomeInvalidError).

test/gbrain-home-isolation.test.ts proves write-isolation across all migrated
sites. test/migrations-v0_14_0.test.ts updated to use $GBRAIN_HOME instead of
the old HOME-swap pattern.

Closes part of the claw-test E2E harness preconditions (D13 + D21).

* feat: gbrain friction {log,render,list,summary} — agent friction reporter

Append-only JSONL writer at $GBRAIN_HOME/friction/<run-id>.jsonl. Schema is a
flat extension of StructuredAgentError (D20), one envelope shape across both
agent-emitted entries and harness-wrapped command failures. Run-id resolves
from --run-id > $GBRAIN_FRICTION_RUN_ID > 'standalone'.

Subcommands stay ≤30 LOC each; core lives in src/core/friction.ts (writer +
reader + renderer + redactor). render --redact (default for md output) strips
\$HOME / \$CWD to placeholders so reports paste safely in PRs/issues.

Severity: confused | error | blocker | nit. Kind: friction | delight (D7) |
phase-marker | interrupted. Readers tolerate malformed lines (skip + warn).

40 unit tests; this is the channel the claw-test harness writes to and that
agents emit through during live-mode runs.

* feat: gbrain claw-test — end-to-end fresh-install friction harness

Two modes: scripted (CI gate, no agent) and --live (real agent subprocess).
Phases: setup → install_brain (gbrain init --pglite) → import (--no-embed) →
query → extract all --source fs → verify (gbrain doctor --json, asserts
status==='ok' and progress.jsonl phase coverage).

AgentRunner interface + registry — interface stays narrow (detect, invoke,
optional postInstallHook). v1 ships only OpenClawRunner; the registry pattern
lets v1.1 land hermes/codex as ~50-line additions without refactoring callers.
OpenClaw invocation: 'openclaw agent --local --agent <name> --message <brief>'
matching test/e2e/skills.test.ts (NOT --prompt-file, which doesn't exist).

transcript-capture: spawns child with piped stdio, async-drains via
fs.createWriteStream + 'drain' events so 256KB+ bursts don't stall the child
(D17 backpressure). Writes <run>/transcript.jsonl with schema_version + ts +
channel + byte_offset + bytes_b64. Friction entries' transcript_offset field
references byte offsets here so render --transcripts can resolve back.

progress-tail: parses gbrain's --progress-json events out of child stderr.
Phase verification asserts each scenario.expected_phases entry (dotted names
like import.files, extract.links_fs, doctor.db_checks) saw at least one event
from the actual command — proves the COMMAND ran, not that the agent obeyed
prompts.

seed-pglite: ~50 LOC SQL replay primitive for the upgrade-from-v0.18 scenario.
Existing migration helpers (test/e2e/helpers.ts) are Postgres-only; PGLite has
no equivalent. seedPglite opens a fresh PGLite, executes each statement
individually (errors name the failing one), then disconnects so gbrain init
can take over and walk forward.

53 unit tests covering registry selection, runner detection, multi-byte UTF-8
chunk-boundary safety, PIPE buffer drain, scenario load+validate, progress
event parsing, and SQL splitter.

* feat: claw-test scenario fixtures + friction-protocol skills convention

Two scenarios ship in v1 — fresh-install and upgrade-from-v0.18. Each is a
self-contained directory: brain/ (markdown pages), BRIEF.md (live-mode prompt),
expected.json (scripted-mode assertions), scenario.json (kind, expected_phases,
optional from_version + seed paths). Schema is owned by src/core/claw-test/
scenarios.ts.

upgrade-from-v0.18 ships scaffolded — seed/dump.sql is the v1.1 follow-up
(needs a real v0.18-shape PGLite dump; seed/README.md documents the gen
procedure). The harness gracefully no-ops the seed phase when dump.sql is
absent.

skills/_friction-protocol.md is a cross-cutting convention skill (like
_brain-filing-rules.md). Tells agents when to call gbrain friction log and how
to choose severity. Skills the claw-test exercises will gain a > Convention:
callout pointing here in a v1.1 sweep.

13 unit tests for the scenario loader + 'shipped scenarios load cleanly' for
both.

* feat: register gbrain claw-test + gbrain friction; CLAUDE.md + llms sync

Wires both commands into src/cli.ts CLI_ONLY allow-list and adds dispatch
in handleCliOnly so neither command requires a brain engine connection.

CLAUDE.md gains entries for src/commands/{friction,claw-test}.ts +
src/core/claw-test/ + skills/_friction-protocol.md, and a Commands section
listing all 8 new gbrain claw-test ... and gbrain friction ... invocations
with the v0.23 marker. Documents the GBRAIN_HOME write-isolation contract
and the v1 caveat (read-side host-fingerprint detection deferred to v1.1).
llms.txt + llms-full.txt regenerated via 'bun run build:llms' so the
committed generator-output gate passes.

test/e2e/claw-test.test.ts is the scripted-mode E2E. Builds a tiny shim that
delegates to 'bun run src/cli.ts' (NOT bun --compile, which doesn't bundle
PGLite's runtime assets), points the harness at it via GBRAIN_BIN_OVERRIDE,
runs --scenario fresh-install end-to-end. Asserts exit 0, zero error/blocker
friction. Includes a deliberate-break test that proves the friction signal
fires when a phase command rejects.

test/claw-test-cli.test.ts covers shipped-scenario load + agent registry +
OpenClawRunner detection (relative-path / .. / missing-bin guards) + the
GBRAIN_FRICTION_RUN_ID env handoff between harness and friction CLI.

Closes the v0.23 claw-test E2E feature.

* chore: bump version and changelog (v0.24.0)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(tests): typecheck failures + spawnWithCapture timeout headroom in CI

Three CI fixes after PR #522 landed:

1. test/agent-runner.test.ts:89 — UnavailableRunner.invoke() returns
   Promise<void> by default but the AgentRunner contract requires
   Promise<InvokeResult>. Annotate the throw-only invoke explicitly so tsc
   sees the contract is satisfied (the throw makes the body unreachable as
   far as the return type is concerned).

2. test/seed-pglite.test.ts — bun:test signature is test(name, fn, timeoutMs:
   number), not test(name, opts: {timeout}, fn). The {timeout: 30_000} object
   form was a guess that tsc on bun 1.3.13 rejects. Move the 30s cap to the
   trailing positional number arg on each PGLite-using test.

3. test/transcript-capture.test.ts — `spawnWithCapture > timeout fires
   SIGTERM/SIGKILL` blew the 10s outer cap on the GitHub runner. Two fixes:
   (a) use `exec sleep` so the child we spawn IS sleep — SIGTERM goes
   directly to it, no `/bin/sh` fork-vs-exec process-group ambiguity that
   could orphan the sleep and force the SIGKILL grace path. (b) bump outer
   cap to 30s for headroom even when the runner is slow and SIGKILL after
   the 5s grace is what actually ends the child.

* chore: rebump to v0.22.16 (next free 0.22.x patch slot per queue)

PR #506 claims v0.22.15, PR #521 claims v0.22.10, intermediate slots
(.11/.12/.13/.14) are claimed by other open PRs. v0.22.16 is the next
clean PATCH slot. v0.23.0 is claimed by PR #462 so MINOR isn't free.
This release fits the 0.22.x train; v0.23.0 lands when #462 ships.

Updates VERSION, package.json, CHANGELOG.md header, TODOS.md follow-up
labels. Code is unchanged.

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-29 23:46:36 -07:00

288 lines
10 KiB
TypeScript

/**
* Fail-improve loop: deterministic-first, LLM-fallback pattern.
*
* Tries deterministic code first (regex, parser). If it fails, falls back
* to LLM. Logs every fallback as a JSONL entry for future improvement.
* Over time, failure patterns reveal which regex rules are missing.
*
* Each operation writes to its own JSONL file (~/.gbrain/fail-improve/{operation}.jsonl).
* Atomic append assumption: individual log entries are <1KB, well under OS page size.
* No cross-operation file conflicts since each operation has its own file.
*/
import { appendFileSync, readFileSync, existsSync, mkdirSync, writeFileSync, renameSync } from 'fs';
import { join, dirname } from 'path';
import { gbrainPath } from './config.ts';
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export interface FailureEntry {
timestamp: string;
operation: string;
input: string;
deterministic_result: string | null;
llm_result: string | null;
metadata?: Record<string, any>;
}
export interface FailureAnalysis {
operation: string;
total_failures: number;
failures_by_pattern: Map<string, number>;
total_improvements: number;
last_improvement?: string;
total_calls: number;
deterministic_hits: number;
deterministic_rate: number;
}
export interface TestCase {
name: string;
input: string;
expected: string;
source: 'fail-improve-loop';
}
// Lazy: GBRAIN_HOME may be set after module load, so resolve at call time.
const getLogDir = () => gbrainPath('fail-improve');
const MAX_ENTRIES = 1000;
// ---------------------------------------------------------------------------
// AbortSignal helpers
// ---------------------------------------------------------------------------
/**
* Construct a DOM-style AbortError. Matches what fetch() throws on
* AbortController.abort(), so downstream callers that already branch on
* `err.name === 'AbortError'` work without change.
*/
function makeAbortError(where: string): Error {
const err = new Error(`Aborted at ${where}`);
err.name = 'AbortError';
return err;
}
function isAbortError(err: unknown): boolean {
return !!err && typeof err === 'object' &&
('name' in err && (err as { name: string }).name === 'AbortError');
}
// ---------------------------------------------------------------------------
// Core class
// ---------------------------------------------------------------------------
export class FailImproveLoop {
private logDir: string;
constructor(logDir?: string) {
this.logDir = logDir || getLogDir();
}
/**
* Try deterministic first, fall back to LLM, log mismatches.
* When both fail, throws the LLM error and logs both failures.
*
* Optional `opts.signal` threads an AbortSignal through the flow:
* - Checked before the deterministic call and again before the LLM call.
* - Forwarded to both callbacks as an optional second arg. Existing
* callbacks that take only `(input: string)` are structurally compatible
* and ignore the extra arg (TypeScript widens on call).
* - When aborted, throws an Error with name='AbortError' (standard Web
* AbortController semantics). Does not write a failure log entry for
* aborted runs since they're not informative.
*/
async execute<T>(
operation: string,
input: string,
deterministicFn: (input: string, signal?: AbortSignal) => T | null,
llmFallbackFn: (input: string, signal?: AbortSignal) => Promise<T>,
opts?: { signal?: AbortSignal },
): Promise<T> {
// Pre-flight abort check
if (opts?.signal?.aborted) throw makeAbortError('fail-improve:before-start');
// Track call
this.incrementCallCount(operation, 'total');
// Try deterministic first
const deterResult = deterministicFn(input, opts?.signal);
if (deterResult !== null && deterResult !== undefined) {
this.incrementCallCount(operation, 'deterministic');
return deterResult;
}
// Abort check between deterministic miss and LLM call
if (opts?.signal?.aborted) throw makeAbortError('fail-improve:before-fallback');
// Deterministic failed, try LLM
let llmResult: T;
try {
llmResult = await llmFallbackFn(input, opts?.signal);
} catch (llmError: any) {
// Abort propagates unlogged — not a useful failure record
if (isAbortError(llmError)) throw llmError;
// Both failed — log both, throw LLM error
this.logFailure({
timestamp: new Date().toISOString(),
operation,
input: input.slice(0, 1000),
deterministic_result: null,
llm_result: `error: ${llmError.message || String(llmError)}`,
metadata: { cascade_failure: true },
});
throw llmError;
}
// Log the failure (deterministic failed, LLM succeeded)
this.logFailure({
timestamp: new Date().toISOString(),
operation,
input: input.slice(0, 1000),
deterministic_result: null,
llm_result: JSON.stringify(llmResult).slice(0, 1000),
});
return llmResult;
}
/** Append a failure entry to the operation's JSONL file. */
logFailure(entry: FailureEntry): void {
const filePath = this.getLogPath(entry.operation);
this.ensureDir(filePath);
const line = JSON.stringify(entry) + '\n';
appendFileSync(filePath, line, 'utf-8');
this.rotateIfNeeded(entry.operation);
}
/** Read all failures for an operation. */
getFailures(operation: string): FailureEntry[] {
const filePath = this.getLogPath(operation);
if (!existsSync(filePath)) return [];
try {
return readFileSync(filePath, 'utf-8')
.split('\n')
.filter(Boolean)
.map(line => {
try { return JSON.parse(line); }
catch { return null; }
})
.filter(Boolean) as FailureEntry[];
} catch {
return [];
}
}
/** Group failures by a key derived from the input (first 50 chars). */
getFailuresByPattern(operation: string): Map<string, FailureEntry[]> {
const failures = this.getFailures(operation);
const groups = new Map<string, FailureEntry[]>();
for (const f of failures) {
const key = f.input.slice(0, 50).replace(/\s+/g, ' ').trim();
if (!groups.has(key)) groups.set(key, []);
groups.get(key)!.push(f);
}
return groups;
}
/** Analyze failures and compute metrics. */
analyzeFailures(operation: string): FailureAnalysis {
const failures = this.getFailures(operation);
const patterns = this.getFailuresByPattern(operation);
const stats = this.getCallCounts(operation);
const improvements = this.getImprovements(operation);
return {
operation,
total_failures: failures.length,
failures_by_pattern: new Map([...patterns.entries()].map(([k, v]) => [k, v.length])),
total_improvements: improvements.length,
last_improvement: improvements.length > 0 ? improvements[improvements.length - 1].timestamp : undefined,
total_calls: stats.total,
deterministic_hits: stats.deterministic,
deterministic_rate: stats.total > 0 ? stats.deterministic / stats.total : 0,
};
}
/** Generate test cases from failure logs where LLM produced good results. */
generateTestCases(operation: string): TestCase[] {
const failures = this.getFailures(operation);
return failures
.filter(f => f.llm_result && !f.llm_result.startsWith('error:') && !f.metadata?.cascade_failure)
.map((f, i) => ({
name: `auto_${operation}_${i + 1}`,
input: f.input,
expected: f.llm_result!,
source: 'fail-improve-loop' as const,
}));
}
/** Log an improvement (when a new deterministic pattern is added). */
logImprovement(operation: string, description: string): void {
const filePath = join(this.logDir, operation, 'improvements.json');
this.ensureDir(filePath);
let improvements: any[] = [];
if (existsSync(filePath)) {
try { improvements = JSON.parse(readFileSync(filePath, 'utf-8')); } catch {}
}
improvements.push({ timestamp: new Date().toISOString(), description });
writeFileSync(filePath, JSON.stringify(improvements, null, 2), 'utf-8');
}
// -------------------------------------------------------------------------
// Private helpers
// -------------------------------------------------------------------------
private getLogPath(operation: string): string {
return join(this.logDir, `${operation}.jsonl`);
}
private getCallCountPath(operation: string): string {
return join(this.logDir, `${operation}.counts.json`);
}
private ensureDir(filePath: string): void {
const dir = dirname(filePath);
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
}
private incrementCallCount(operation: string, type: 'total' | 'deterministic'): void {
const filePath = this.getCallCountPath(operation);
this.ensureDir(filePath);
let counts = { total: 0, deterministic: 0 };
if (existsSync(filePath)) {
try { counts = JSON.parse(readFileSync(filePath, 'utf-8')); } catch {}
}
counts[type]++;
writeFileSync(filePath, JSON.stringify(counts), 'utf-8');
}
private getCallCounts(operation: string): { total: number; deterministic: number } {
const filePath = this.getCallCountPath(operation);
if (!existsSync(filePath)) return { total: 0, deterministic: 0 };
try { return JSON.parse(readFileSync(filePath, 'utf-8')); }
catch { return { total: 0, deterministic: 0 }; }
}
private getImprovements(operation: string): Array<{ timestamp: string; description: string }> {
const filePath = join(this.logDir, operation, 'improvements.json');
if (!existsSync(filePath)) return [];
try { return JSON.parse(readFileSync(filePath, 'utf-8')); }
catch { return []; }
}
private rotateIfNeeded(operation: string): void {
const filePath = this.getLogPath(operation);
if (!existsSync(filePath)) return;
const content = readFileSync(filePath, 'utf-8');
const lines = content.split('\n').filter(Boolean);
if (lines.length > MAX_ENTRIES) {
// Keep last MAX_ENTRIES entries
const kept = lines.slice(-MAX_ENTRIES);
writeFileSync(filePath, kept.join('\n') + '\n', 'utf-8');
}
}
}