Files
ruflo/v3/@claude-flow/cli/__tests__/weft-export.test.ts
T
rUv d759af6d6b feat(agenticow): COW memory substrate + governed distillation loop (ADR-170..173) (#2562)
* feat(agenticow): complete verb surface (ingest/query/diff/lineage/status) + nativeAnn + 0.2.4

Step 1 of the agenticow integration: the lifecycle verbs (branch/
checkpoint/rollback/promote) existed but the read/write verbs that make
a branch usable did not — you could create a COW branch via MCP but
couldn't populate or read it. Adds:
- agenticow_ingest — write {id?,vector,text?} records into a branch/base
- agenticow_query — k-NN across the full COW lineage (parent ∪ edits)
- agenticow_diff / _lineage / _status — introspection
- nativeAnn option on agenticow_branch (Rust dual-graph ANN fast path)
- targeted rollback via optional checkpointId

Floor bumped agenticow ~0.2.3 → ~0.2.4 (the upstream fix — text payloads
now survive the save/load round-trip our wrapper does on every call;
ruvnet/agenticow#3, published 0.2.4). 9 tools total; tests 10/10.

Co-Authored-By: RuFlo <ruv@ruv.net>

* feat(swarm): per-agent COW memory branches via agenticow (agenticow step 2)

Wire the agenticow COW-memory primitive into the swarm agent lifecycle so a
swarm agent can own an isolated ~162-byte Copy-On-Write branch of a shared
.rvf base instead of a full copy — the structural fix for the v3.14.4
worktree-bloat (3.3 GB from full-copy per-agent snapshots).

SwarmMemoryBranches service (src/services/swarm-memory-branches.ts):
  - branchForAgent(base, agentId): fork a 162-byte COW branch (nativeAnn),
    idempotent, persisted to .claude-flow/swarm/cow-branches.json
  - promoteAgent(agentId): merge the agent's edits back into base, then delete
    the branch (call on success)
  - discardAgent(agentId): drop the branch, pure-fs, works even degraded
    (call on failure)
  - Non-fatal + CLAUDE_FLOW_NO_COW_MEMORY kill switch; agenticow lazy-loaded so
    it stays off the CLI startup path (--help unchanged at ~0.09s).

Seam + wiring (src/mcp-tools/agent-tools.ts):
  agent_spawn stores agents as pure JSON metadata today — it never forks/copies
  an .rvf, so there is no full-copy to replace inline. Wired in opt-in: pass
  `memoryBase` to agent_spawn to fork a per-agent branch (recorded on the
  AgentRecord); agent_terminate promotes (promoteMemory:true) or discards it.
  Default behavior is unchanged.

Shared loader (src/mcp-tools/agenticow-loader.ts): extracted loadAgenticow /
resolveMemoryPath / manifestFor / validateLabel / openWithLineage from
agenticow-tools.ts so the MCP verbs and the service share one optional-dep
dance (behavior-preserving; existing agenticow-tools tests unchanged).

Tests (__tests__/swarm-memory-branches.test.ts): kill-switch + degraded
no-op contract (always-on) and a real branch -> ingest -> promote/discard
lifecycle against a temp .rvf (skipIf agenticow absent), following the
agenticow-tools.test.ts conventions.

Co-Authored-By: RuFlo <ruv@ruv.net>

* feat(agenticow): speculative branch-and-promote for A/B memory exploration (step 4)

Adds a self-contained SpeculativeExploration module + `agenticow_speculate`
MCP tool that composes on top of the existing agenticow COW verbs (fork /
promote). Fan out N candidate approaches, each on its own 162-byte COW branch
of a shared base .rvf; explore/score each independently; promote the winner's
branch into base and discard the losers by deleting their branch files. The
memory-state analogue of the worktree-per-agent pattern.

- src/agenticow/speculative-exploration.ts — generic `explore(base, {label,fn}[],
  score)` core + `exploreFromPath()` lifecycle wrapper. Returns
  {winner, scores, promoted, ...}.
- src/mcp-tools/_agenticow.ts — shared COW helpers (loadAgenticow / openWithLineage
  / manifestFor / resolveMemoryPath / validateLabel). ADDED alongside
  agenticow-tools.ts (kept byte-identical) to minimize merge conflict with a
  sibling branch.
- src/mcp-tools/agenticow-speculate-tools.ts — `agenticow_speculate` MCP tool
  (declarative candidates + probe-query / count scoring). Optional-dep graceful
  degradation per ADR-150.
- Registered in mcp-client.ts + mcp-tools/index.ts.
- __tests__/agenticow-speculate-tools.test.ts — 3-candidate deterministic-scorer
  test asserting winner promoted into base and loser branch files discarded
  (skipIf agenticow absent), following agenticow-tools.test.ts conventions.

Co-Authored-By: RuFlo <ruv@ruv.net>

* feat(autopilot): checkpoint/rollback gate for loop ticks (agenticow step 3)

Add CheckpointGate — an agenticow-backed checkpoint/rollback bracket for
autopilot loops and long-horizon workflows. Before a risky tick that mutates
.rvf memory, take an O(1) agenticow checkpoint (162 bytes); if the tick
regresses (throws, or the caller's verdict says the outcome is worse), roll
memory back to the checkpoint — O(edits-since-checkpoint), not an O(N) rebuild.

- New src/services/checkpoint-gate.ts: CheckpointGate.guard(memPath, label, fn)
  plus low-level checkpoint()/rollback(). Lazy-loads agenticow (optional dep,
  ADR-150) — zero startup cost, graceful degradation to unguarded pass-through
  when the package is absent, the CLAUDE_FLOW_AGENTICOW_DISABLE kill-switch is
  set, or no memory path is configured. Non-fatal: an agenticow failure never
  masks the tick's own result.
- Opt-in wiring into the autopilot loop (commands/autopilot.ts autopilotCheck):
  checkpoint the configured .rvf right before a re-engaged tick; roll back on
  the loop's regression signal (stall auto-disable). Activates only when
  CLAUDE_FLOW_AUTOPILOT_CHECKPOINT_MEM points at an .rvf the loop mutates.
  The loop's memory mutation is out-of-process, so this brackets across ticks
  rather than wrapping an in-process fn; guard() is available for callers that
  do have an in-process fn.
- Unit test (__tests__/checkpoint-gate.test.ts): 10 cases — real temp .rvf
  checkpoint→mutate→rollback restore, success-keeps, throw-rollback-rethrow,
  and degraded/kill-switch pass-through. skipIf(agenticow absent), following
  agenticow-tools.test.ts conventions.

Co-Authored-By: RuFlo <ruv@ruv.net>

* docs(adr): ADR-170..173 — agenticow substrate, provenance oracle, Fable harness, remote distillation

Records the architectural decisions of the agenticow + distillation
governance integration:
- ADR-170: agenticow COW memory as agent-scoped workspace substrate
  (9 verbs, per-agent branches, speculative, checkpoint gate, one
  shared optional-dep loader; honest 'no full-copy to replace' scope)
- ADR-171: provenance-tiered evaluation oracle (execution → fable →
  proxy, each label tagged; promote-gated on real clearance; causal
  failure receipts; never proxy-as-gold — ADR-169 applied to labels)
- ADR-172: cost-disciplined Fable advisor harness via claude -p
  (clean-cwd + batching = $1.56→~$0.02/item; judge + GEPA reflector)
- ADR-173: remote GPU distillation via weight-eft over SSH
  (dry-run default, --execute --yes gate, parameterized host, hard
  honesty rule — no false 'trains a model' claim)

Co-Authored-By: RuFlo <ruv@ruv.net>

* feat(neural): tiered `resolved` oracle for distill/weight-EFT SFT data

Replace the single structural-confidence proxy for the per-trajectory
`resolved` boolean with a 3-tier labeler where every label carries honest
provenance (ADR-169 — never present a proxy as ground truth).

- TIER 1 `oracle:test-exec` (distill-oracle.ts): real mechanical eval for
  trajectories with a SWE-bench FAIL_TO_PASS spec or a metaharness/darwin
  bench-suite case. Runs over SSH on a PARAMETERIZED remote (--remote / env
  RUFLO_DISTILL_REMOTE, never hard-coded). DRY-RUN by default: emits the
  ssh/darwin-bench/eval command plan + preflight and touches nothing; only
  execute:true runs the real eval, behind a wrapped non-fatal probe.
- TIER 2 `judge:fable` (fable-harness.ts): cost-disciplined headless Fable
  LLM-as-judge for trajectories with no mechanical spec. Runs `claude -p`
  from a FRESH EMPTY temp cwd (no CLAUDE.md — the 5x cost driver), carries
  the judge role via --append-system-prompt, BATCHES 20 items/call (~$0.02
  /item vs ~$1.56 from the project dir), and enforces --max-budget-usd.
  Off by default; second entry point reflectFailures() feeds GEPA/evolve.
- TIER 3 `proxy:structural`: existing output-verifier confidence, weakest,
  clearly labeled.

Interface consumed by distill:
  labelResolved(trajectories, opts) -> [{...traj, resolved, resolvedBy,
  resolvedConfidence?, resolvedReason?}]. Default (no opts) = dry-run oracle
  preflight + proxy fallback: ZERO spend, no SSH exec, no Fable call.
  Everything ADR-150 optional/graceful.

Tests mock `claude -p` (spawn) and the SSH exec — assert command
construction, batching, provenance tagging, tier fallback order, and the
zero-external-call default. One opt-in live smoke behind RUFLO_FABLE_LIVE=1.
37 passing, 1 skipped (live), $0.

Co-Authored-By: RuFlo <ruv@ruv.net>

* feat(neural): weight-eft $0 export slice + opt-in run-transcript capture path

Ship the ADR-150 weight-eft slice: turn ruflo run history into AUDITED
training DATA + a cost-Pareto measurement + a GPU plan. This does NOT train a
model and does NOT reduce escalation — weight-eft's own `train` never spawns
and no GPU tune has run. `resolved` is an explicitly-marked PROXY (ruflo has
no SWE-bench gold oracle).

Capture path (the blocker):
- NEW src/ruvector/run-transcript-recorder.ts — opt-in (CLAUDE_FLOW_RUN_TRANSCRIPTS=1,
  off by default; PII/retention surface mirroring the router trajectory recorder)
  recorder that persists full run records {instance_id, model, tier, resolved,
  resolved_source, messages[], model_patch} to .swarm/run-transcripts.jsonl.
- Seam wired in src/mcp-tools/agent-execute-core.ts next to the existing
  trajectory-outcome hook — the one place a run's transcript + model + tier +
  resolved-proxy are all known. resolved_source='api-success' (weakest proxy),
  model_patch='' (single-shot execute produces no diff) — both stamped honestly.
- router-trajectory.ts documents the companion split + adds unifiedRecorderStatus().

Distill command + service:
- NEW src/services/weight-eft.ts — optional-dep wrapper (dynamic import, graceful
  {degraded:true}; local type mirrors, no static @metaharness import). Archive
  builder (records → DarwinTrajectory[]), runExport/runPlan/runEval, plus a
  spend-gated remote-GPU train path (buildRemoteTrainInvocation + runRemoteTrain:
  DRY-RUN default, real compute only behind --execute --yes; ssh/rsync/ruvllm;
  host parameterized via --remote / $RUFLO_DISTILL_REMOTE, never hard-coded).
- `neural distill export|plan|eval|train` in neural.ts.
- @metaharness/weight-eft ~0.1.1 added to optionalDependencies.

Tests (18 in __tests__/weft-export.test.ts): archive-builder mapping, export E2E
(real weight-eft → sft.jsonl/dpo.jsonl/report), degraded path (absent dep →
{degraded:true}), remote-train command construction + dry-run/refused/preflight
gates, and capture-module opt-in gating. tsc build clean; CLI startup unaffected.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01S7GYqnVUVxBfZ5W8znqry3

* merge: consolidate step-2/step-4 loaders into agenticow-loader.ts

* merge: step 3 (checkpoint gate) + consolidate 3rd loader into agenticow-loader.ts

All agenticow consumers (verbs, swarm branches, speculative, checkpoint
gate) now import one canonical loader — the first-class compat layer.
checkpoint-gate's inline copies removed; delegates to shared loadAgenticow.

* merge: oracle + weft + wire ADR-171 promote-gate & causal receipts (#23)

explore() and agenticow_speculate now enforce the ADR-171 promotion gate:
- a winning branch is promote-INELIGIBLE unless cleared by oracle:test-exec
  or an explicitly-accepted judge:fable — proxy:structural can NEVER clear,
  even when it claims cleared:true (fail-closed)
- requireClearance:true fail-closes without a gate — score alone never
  graduates work into base
- every discarded loser + an ineligible/failed winner emits a causal
  receipt {label, score, diff, outcome, provenance, reason}
- result carries promotedBy + promotionDecision for auditability

Back-compat: no clearance gate → legacy score-only promotion, honestly
tagged 'unverified' (never masquerading as ground truth). Tests 9/9.

Co-Authored-By: RuFlo <ruv@ruv.net>

* security(distill): bare dry-run is fully offline — gate ssh preflight behind --preflight

Adversarial RC finding: the remote-train dry-run ran a read-only 'ssh
host true' reachability probe, contacting the host without --execute.
Now the bare dry-run contacts NOTHING (prints commands only); the
read-only reachability/GPU probes require an explicit --preflight (or
--execute). Closes the 'no implicit remote execution' gate.

Co-Authored-By: RuFlo <ruv@ruv.net>

* fix(ci): regenerate v3/pnpm-lock.yaml for agenticow ^0.2.4 + @metaharness/weight-eft

Lock drifted from cli/package.json — had agenticow ~0.2.4 (pkg says
^0.2.4) and was MISSING @metaharness/weight-eft entirely, failing
--frozen-lockfile → cascading 34 CI job failures (the #2540→#2552
lesson). Regenerated; frozen-lockfile now clean.

Co-Authored-By: RuFlo <ruv@ruv.net>

* fix(ci): ADR-112 guidance clause on the 5 new agenticow verb descriptions

ingest/query/diff/lineage/status said 'Use to/after/before'; the ADR-112
audit requires the literal 'Use when' guidance signal. Reworded; audit
360/360 pass.

Co-Authored-By: RuFlo <ruv@ruv.net>

* fix(ci): register CLAUDE_FLOW_RUN_TRANSCRIPTS* as escape-hatch env vars (ADR-125/130)

The ADR-173 run-transcript capture path adds opt-in, off-by-default
background-recorder env toggles (PII/retention surface, mirroring the
existing CLAUDE_FLOW_ROUTER_TRAJECTORY* recorder). They have no
user-facing command, so they're env-only by design — registered as
known escape hatches like their router-trajectory analog. Audit passes.

Co-Authored-By: RuFlo <ruv@ruv.net>

* fix(ci): tilde-pin @metaharness/weight-eft + agenticow (anti-caret guard 17z73)

The metaharness smoke's iter-110 anti-caret regression guard requires all
@metaharness/* optional deps to be tilde-pinned (~) for reproducibility
(ADR-150 review-round-1). My earlier npm-lock revert accidentally flipped
@metaharness/weight-eft (and agenticow) to caret (^). Restored to tilde;
lock regenerated, frozen-lockfile clean.

Co-Authored-By: RuFlo <ruv@ruv.net>
2026-07-04 09:17:01 -04:00

375 lines
17 KiB
TypeScript

/**
* weft-export.test.ts — ADR-150 weight-eft slice.
*
* Covers:
* 1. Archive-builder: ruflo run records → DarwinTrajectory[] mapping + the
* honest resolved-proxy accounting.
* 2. distill-export E2E: synthetic archive → weight-eft export produces
* sft.jsonl / dpo.jsonl / export-report.json (weight-eft installed in the
* worktree; skipped if the optional dep is genuinely absent).
* 3. Degraded path: weight-eft absent (injected failing importer) → {degraded:true}.
* 4. Remote-train: pure command construction (ssh/rsync/ruvllm argv) + dry-run
* output. NEVER touches a live host — spawn is stubbed.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { rmSync, mkdtempSync, mkdirSync, writeFileSync, existsSync, readFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import {
buildArchiveFromRecords,
runExport,
runPlan,
buildRemoteTrainInvocation,
runRemoteTrain,
loadWeightEft,
DEFAULT_BASE_MODEL,
type DarwinTrajectory,
type SpawnLike,
} from '../src/services/weight-eft.js';
import type { RunTranscriptRecord } from '../src/ruvector/run-transcript-recorder.js';
import {
recordRunTranscript,
readRunTranscripts,
tierForModel,
runTranscriptRecorderStatus,
__resetRunTranscriptRecorderForTests,
} from '../src/ruvector/run-transcript-recorder.js';
// NOTE: the CLI command surface (neuralCommand) is intentionally NOT imported
// here — it pulls in `@claude-flow/cli-core/output`, whose built subpath is not
// resolvable under vitest in a fresh worktree (the same reason the repo's
// existing __tests__/commands.test.ts loads no tests in this env). We exercise
// the command's SERVICE layer (runExport → files on disk) directly, and the
// built-CLI command is smoke-tested out-of-band via `node dist … neural distill`.
// --- fixtures ---------------------------------------------------------------
function rec(over: Partial<RunTranscriptRecord>): RunTranscriptRecord {
return {
v: 1,
ts: new Date().toISOString(),
instance_id: 'inst-1',
task_hash: 'deadbeef',
model: 'z-ai/glm-5.2',
tier: 'cheap',
resolved: true,
resolved_source: 'api-success',
messages: [
{ role: 'system', content: 'You are a coding agent.' },
{ role: 'user', content: 'Fix the null-deref in cache.ts' },
{ role: 'assistant', content: 'Here is the patch.' },
],
model_patch: 'diff --git a/cache.ts b/cache.ts\n+ if (x) return;',
sample: 0,
source: 'agent-execute',
...over,
};
}
/** A resolved + a failed sample on the SAME instance/model — enough for a DPO pair. */
function dpoPairRecords(): RunTranscriptRecord[] {
return [
rec({ instance_id: 'inst-dpo', sample: 0, resolved: true }),
rec({
instance_id: 'inst-dpo', sample: 1, resolved: false, model_patch: '',
messages: [
{ role: 'system', content: 'You are a coding agent.' },
{ role: 'user', content: 'Fix the null-deref in cache.ts' },
{ role: 'assistant', content: 'I could not solve it.' },
],
}),
];
}
let weftAvailable = false;
beforeEach(async () => { weftAvailable = (await loadWeightEft()) !== null; });
// --- 0. capture module: run-transcript recorder (opt-in) --------------------
describe('run-transcript-recorder (the capture path)', () => {
let dir: string;
let prevEnabled: string | undefined;
let prevPath: string | undefined;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'weft-cap-'));
prevEnabled = process.env.CLAUDE_FLOW_RUN_TRANSCRIPTS;
prevPath = process.env.CLAUDE_FLOW_RUN_TRANSCRIPTS_PATH;
__resetRunTranscriptRecorderForTests();
});
afterEach(() => {
if (prevEnabled === undefined) delete process.env.CLAUDE_FLOW_RUN_TRANSCRIPTS; else process.env.CLAUDE_FLOW_RUN_TRANSCRIPTS = prevEnabled;
if (prevPath === undefined) delete process.env.CLAUDE_FLOW_RUN_TRANSCRIPTS_PATH; else process.env.CLAUDE_FLOW_RUN_TRANSCRIPTS_PATH = prevPath;
__resetRunTranscriptRecorderForTests();
rmSync(dir, { recursive: true, force: true });
});
it('is OFF by default — recordRunTranscript is a no-op (no file written)', () => {
delete process.env.CLAUDE_FLOW_RUN_TRANSCRIPTS;
const p = join(dir, 'run-transcripts.jsonl');
process.env.CLAUDE_FLOW_RUN_TRANSCRIPTS_PATH = p;
__resetRunTranscriptRecorderForTests();
const r = recordRunTranscript({ task: 't', model: 'claude-haiku-4', tier: 'cheap', resolved: true, resolvedSource: 'api-success', messages: [{ role: 'user', content: 'hi' }] });
expect(r.recorded).toBe(false);
expect(existsSync(p)).toBe(false);
});
it('when enabled, writes a record that round-trips through readRunTranscripts', () => {
const p = join(dir, 'run-transcripts.jsonl');
process.env.CLAUDE_FLOW_RUN_TRANSCRIPTS = '1';
process.env.CLAUDE_FLOW_RUN_TRANSCRIPTS_PATH = p;
__resetRunTranscriptRecorderForTests();
const r = recordRunTranscript({
task: 'Fix bug', model: 'claude-haiku-4', tier: 'cheap', resolved: true,
resolvedSource: 'output-verifier', messages: [{ role: 'user', content: 'Fix bug' }],
modelPatch: 'diff', source: 'agent-execute',
});
expect(r.recorded).toBe(true);
expect(r.instanceId).toBe(`run-${r.taskHash}`);
const { records, malformed } = readRunTranscripts(p);
expect(malformed).toBe(0);
expect(records).toHaveLength(1);
expect(records[0]).toMatchObject({ v: 1, model: 'claude-haiku-4', tier: 'cheap', resolved: true, resolved_source: 'output-verifier', model_patch: 'diff' });
expect(runTranscriptRecorderStatus().enabled).toBe(true);
});
it('tierForModel maps haiku→cheap, sonnet/opus→frontier', () => {
expect(tierForModel('claude-haiku-4')).toBe('cheap');
expect(tierForModel('claude-sonnet-4')).toBe('frontier');
expect(tierForModel('anthropic/claude-opus')).toBe('frontier');
expect(tierForModel(undefined)).toBe('frontier');
});
});
// --- 1. archive-builder -----------------------------------------------------
describe('buildArchiveFromRecords', () => {
it('maps ruflo run records to DarwinTrajectory[] preserving the contract fields', () => {
const { trajectories, stats } = buildArchiveFromRecords([
rec({ instance_id: 'a', tier: 'cheap', resolved: true }),
rec({ instance_id: 'b', tier: 'frontier', resolved: false, model: 'anthropic/claude-opus' }),
]);
expect(trajectories).toHaveLength(2);
const a = trajectories[0];
expect(a).toMatchObject({
instance_id: 'a', model: 'z-ai/glm-5.2', tier: 'cheap', resolved: true, sample: 0,
});
expect(a.messages[0].role).toBe('system');
expect(a.model_patch).toContain('diff --git');
expect(trajectories[1]).toMatchObject({ instance_id: 'b', tier: 'frontier', resolved: false });
expect(stats.total).toBe(2);
expect(stats.resolved).toBe(1);
expect(stats.byTier).toEqual({ cheap: 1, frontier: 1 });
});
it('skips records missing an instance_id or messages (never throws)', () => {
const { trajectories, stats } = buildArchiveFromRecords([
rec({ instance_id: 'ok' }),
rec({ instance_id: '', messages: [] }),
rec({ instance_id: 'empty', messages: [] }),
]);
expect(trajectories.map((t) => t.instance_id)).toEqual(['ok']);
expect(stats.skipped).toBe(2);
});
it('tallies resolved provenance and emits an honest PROXY note (no gold oracle)', () => {
const { stats, proxyNote } = buildArchiveFromRecords([
rec({ instance_id: 'a', resolved_source: 'api-success' }),
rec({ instance_id: 'b', resolved_source: 'output-verifier' }),
]);
expect(stats.byResolvedSource).toEqual({ 'api-success': 1, 'output-verifier': 1 });
expect(proxyNote).toMatch(/PROXY/);
expect(proxyNote).toMatch(/no SWE-bench gold oracle/i);
});
});
// --- 2. distill-export E2E (real weight-eft) --------------------------------
describe('runExport (E2E against real weight-eft)', () => {
it('produces SFT + DPO jsonl and a guard report from a synthetic archive', async () => {
if (!weftAvailable) { console.warn('weight-eft not installed — skipping E2E'); return; }
const { trajectories } = buildArchiveFromRecords(dpoPairRecords());
const res = await runExport({ archive: trajectories, evalHoldout: [] });
expect(res.degraded).toBe(false);
if (res.degraded) return;
// SFT: at least the resolved trajectory becomes a training row.
expect(res.sftRows).toBeGreaterThanOrEqual(1);
expect(res.sftJsonl.trim().split('\n').length).toBe(res.sftRows);
expect(JSON.parse(res.sftJsonl.trim().split('\n')[0])).toHaveProperty('messages');
// DPO: the resolved+failed pair on the same instance yields a preference row.
expect(res.dpoRows).toBeGreaterThanOrEqual(1);
const dpo0 = JSON.parse(res.dpoJsonl.trim().split('\n')[0]);
expect(dpo0).toHaveProperty('chosen');
expect(dpo0).toHaveProperty('rejected');
// Report carries the guard accounting.
expect(res.report).toMatchObject({ sftRows: res.sftRows, dpoRows: res.dpoRows });
expect(res.report).toHaveProperty('droppedRewardHacked');
expect(res.report).toHaveProperty('excludedByHoldout');
});
it('honors the contamination guard: holdout instances are excluded', async () => {
if (!weftAvailable) return;
const { trajectories } = buildArchiveFromRecords([rec({ instance_id: 'held' }), rec({ instance_id: 'kept', task_hash: 'x' })]);
const res = await runExport({ archive: trajectories, evalHoldout: ['held'] });
expect(res.degraded).toBe(false);
if (res.degraded) return;
expect(res.report.excludedByHoldout).toBe(1);
expect(res.report.sftInstanceIds).not.toContain('held');
});
it('runPlan emits a two-stage GPU plan with a ruvllm command ($0 dry-run)', async () => {
if (!weftAvailable) return;
const res = await runPlan({ sftPath: '/tmp/sft.jsonl', dpoPath: '/tmp/dpo.jsonl' });
expect(res.degraded).toBe(false);
if (res.degraded) return;
expect(res.base).toEqual(DEFAULT_BASE_MODEL);
expect(res.sft.command).toMatch(/ruvllm|microlora|sft/i);
expect(res.dpo.command).toBeTruthy();
});
});
// --- 2b. export → files on disk (the command's service path) ----------------
describe('distill-export writes sft.jsonl / dpo.jsonl / export-report.json', () => {
let dir: string;
beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'weft-cli-')); });
afterEach(() => { rmSync(dir, { recursive: true, force: true }); });
it('persists the exact artifacts the CLI `neural distill export` emits', async () => {
if (!weftAvailable) return;
const { trajectories, stats, proxyNote } = buildArchiveFromRecords(dpoPairRecords());
const res = await runExport({ archive: trajectories, evalHoldout: [] });
expect(res.degraded).toBe(false);
if (res.degraded) return;
// Mirror the command's write path.
const outDir = join(dir, 'out');
mkdirSync(outDir, { recursive: true });
writeFileSync(join(outDir, 'sft.jsonl'), res.sftJsonl);
writeFileSync(join(outDir, 'dpo.jsonl'), res.dpoJsonl);
writeFileSync(join(outDir, 'export-report.json'), JSON.stringify({ report: res.report, archiveStats: stats, proxyNote }, null, 2));
expect(existsSync(join(outDir, 'sft.jsonl'))).toBe(true);
expect(existsSync(join(outDir, 'dpo.jsonl'))).toBe(true);
expect(existsSync(join(outDir, 'export-report.json'))).toBe(true);
const report = JSON.parse(readFileSync(join(outDir, 'export-report.json'), 'utf8'));
expect(report).toHaveProperty('report');
expect(report.proxyNote).toMatch(/PROXY/);
expect(readFileSync(join(outDir, 'sft.jsonl'), 'utf8').trim().length).toBeGreaterThan(0);
});
});
// --- 3. degraded path (weight-eft absent) -----------------------------------
describe('graceful degradation (ADR-150)', () => {
const failingImporter = async () => { throw new Error("Cannot find module '@metaharness/weight-eft'"); };
it('runExport returns {degraded:true} when weight-eft cannot load', async () => {
const { trajectories } = buildArchiveFromRecords([rec({})]);
const res = await runExport({ archive: trajectories, importer: failingImporter });
expect(res).toEqual({ degraded: true, reason: 'weight-eft-not-available' });
});
it('runPlan degrades without throwing', async () => {
const res = await runPlan({ sftPath: 'a', dpoPath: 'b', importer: failingImporter });
expect(res.degraded).toBe(true);
});
it('loadWeightEft returns null (not throw) on a broken import', async () => {
expect(await loadWeightEft(failingImporter)).toBeNull();
});
});
// --- 4. remote-train construction + dry-run ---------------------------------
describe('buildRemoteTrainInvocation (pure command construction)', () => {
it('builds correct ssh/rsync/ruvllm argv for host + model + paths', () => {
const plan = buildRemoteTrainInvocation({
host: 'gpu-box', base: 'Qwen/Qwen2.5-Coder-7B-Instruct',
sftPath: '/local/sft.jsonl', dpoPath: '/local/dpo.jsonl',
adapterDir: '/local/adapters', sshUser: 'ruv', sshPort: 2222,
runId: 'run42', adapterPrefix: 'ruflo-weft',
});
// ssh reachability probe targets user@host on the chosen port
expect(plan.preflight[0].argv).toEqual(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=8', '-p', '2222', 'ruv@gpu-box', 'true']);
// rsync sends the LOCAL sft file up to the remote workdir
const rsyncSft = plan.steps.find((s) => s.label === 'rsync sft up')!;
expect(rsyncSft.argv[0]).toBe('rsync');
expect(rsyncSft.argv).toContain('/local/sft.jsonl');
expect(rsyncSft.argv[rsyncSft.argv.length - 1]).toContain('ruv@gpu-box:');
// ruvllm sft uses the base model + writes an sft adapter
const sftStep = plan.steps.find((s) => s.label.startsWith('ruvllm sft'))!;
expect(sftStep.argv.join(' ')).toContain('ruvllm microlora sft --base Qwen/Qwen2.5-Coder-7B-Instruct --data sft.jsonl');
expect(sftStep.argv.join(' ')).toContain('ruflo-weft-run42-sft');
// ruvllm dpo initializes from the sft adapter (on-policy)
const dpoStep = plan.steps.find((s) => s.label.startsWith('ruvllm dpo'))!;
expect(dpoStep.argv.join(' ')).toContain('ruvllm microlora dpo --base Qwen/Qwen2.5-Coder-7B-Instruct --init-from ruflo-weft-run42-sft');
// adapter fetched back into the local dir
const back = plan.steps.find((s) => s.label === 'rsync adapter back')!;
expect(back.argv[back.argv.length - 1]).toContain('/local/adapters/ruflo-weft-run42-dpo');
expect(plan.humanCommands.length).toBe(plan.preflight.length + plan.steps.length);
});
it('defaults host param from args and uses port 22 + default base', () => {
const plan = buildRemoteTrainInvocation({ host: 'h', sftPath: 's', dpoPath: 'd', runId: 'r' });
expect(plan.base).toBe(DEFAULT_BASE_MODEL.id);
expect(plan.preflight[0].argv).toContain('-p');
expect(plan.preflight[0].argv[plan.preflight[0].argv.indexOf('-p') + 1]).toBe('22');
});
});
describe('runRemoteTrain (spend-gated; spawn stubbed — never touches a live host)', () => {
const okSpawn = (): SpawnLike => ({ status: 0, stdout: 'ok', stderr: '' });
const args = { host: 'gpu-box', sftPath: '/l/sft.jsonl', dpoPath: '/l/dpo.jsonl', runId: 'r1' };
it('BARE dry-run is fully OFFLINE — contacts nothing (no implicit remote exec)', async () => {
const spawned: string[] = [];
const spawn = (cmd: string, argv: string[]): SpawnLike => { spawned.push([cmd, ...argv].join(' ')); return okSpawn(); };
const res = await runRemoteTrain({ ...args, spawn });
expect(res.degraded).toBe(false);
if (res.degraded) return;
expect(res.mode).toBe('dry-run');
expect(res.steps).toBeUndefined();
expect(res.plan.humanCommands.some((c) => c.includes('ruvllm microlora sft'))).toBe(true);
// NOTHING spawned — not even a reachability ssh (adversarial RC hardening).
expect(spawned).toEqual([]);
expect(res.reason).toMatch(/offline/i);
});
it('--preflight opts into the read-only probes (still no training)', async () => {
const spawned: string[] = [];
const spawn = (cmd: string, argv: string[]): SpawnLike => { spawned.push([cmd, ...argv].join(' ')); return okSpawn(); };
const res = await runRemoteTrain({ ...args, preflight: true, spawn });
expect(res.degraded).toBe(false);
if (res.degraded) return;
expect(res.mode).toBe('dry-run');
// the 3 read-only preflight probes ran; no rsync / ruvllm training
expect(spawned.length).toBeGreaterThan(0);
expect(spawned.every((c) => c.startsWith('ssh'))).toBe(true);
expect(spawned.some((c) => c.includes('rsync') || c.includes('microlora'))).toBe(false);
});
it('--execute WITHOUT --yes is refused (real GPU spend needs the second gate)', async () => {
const res = await runRemoteTrain({ ...args, execute: true, spawn: okSpawn });
expect(res.degraded).toBe(false);
if (res.degraded) return;
expect(res.mode).toBe('refused');
expect(res.reason).toMatch(/--yes/);
});
it('--execute --yes on an UNREACHABLE host aborts before any data transfer', async () => {
// ssh reachability probe fails → preflight-failed, no rsync/training
const spawned: string[] = [];
const spawn = (cmd: string, argv: string[]): SpawnLike => {
spawned.push([cmd, ...argv].join(' '));
return { status: 255, stdout: '', stderr: 'ssh: connect timed out' };
};
const res = await runRemoteTrain({ ...args, execute: true, yes: true, spawn });
expect(res.degraded).toBe(false);
if (res.degraded) return;
expect(res.mode).toBe('preflight-failed');
expect(spawned.some((c) => c.includes('rsync') || c.includes('microlora'))).toBe(false);
});
});