Skip to content

feat(evolution): add host evaluator, SDK shims, and calibrated fast adapter - #62

Merged
thxCode merged 9 commits into
mainfrom
lw-m1-host-eval
Dec 3, 2026
Merged

thxCode merged 9 commits into
mainfrom
lw-m1-host-eval

Conversation

@thxCode

@thxCode thxCode commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

What type of PR is this?

/kind feature
/area cli
/area memory
/area decisions

Summary

  • Why. Enable evolutionary campaigns to evaluate candidates directly on an already isolated host without Docker or loopback relay infrastructure, expose consumer-importable ./sdk/* subpath entry points on Node 26, and add a calibrated low-latency OpenAI-compatible advisory decision adapter that fails closed to deterministic fallbacks.
  • Root ./sdk/* subpath shims. Updated scripts/pack-npm.mjs to emit root ./sdk/* subpath shims for Node 26 exports resolution, verified via an isolated consumer npm install and NodeNext tsc --noEmit across all 6 ./sdk/* ESM subpaths in packages/cli/test/npm-pack.test.ts.
  • Host-execution evaluator, early-stop, warm-start seeds, and summary export (@loopwright/evolution & @loopwright/cli). Added host-execution campaign mode and HostExecutionEvaluator with strict bucket/metric/subject/secret validation, parity-gated weightedBucketTarget early-stop in pareto.ts, unverified source-only warmStartSeeds (<= 32 seeds, <= 32 KiB, O_NOFOLLOW, secret scrubbing), onGenerationCommitted hook, campaign-summary.md rendering, and the loopwright evolve summary CLI subcommand.
  • Memory pattern exports (@loopwright/memory). Exported MEMORY_INJECTION_PATTERNS and MEMORY_CREDENTIAL_PATTERNS from @loopwright/memory for reuse in host-side validation and scrubbing boundaries.
  • Calibrated openai-compatible-fast advisory adapter (@loopwright/decisions). Added the openai-compatible-fast provider kind with forced temperature: 0 structured JSON schemas, mandatory offline ECE calibration gating before remote dispatch, low-confidence fallback clamping on uncalibrated, timed-out, or invalid responses, and fail-closed DECISION_FORBIDDEN_AUTHORITY_INTENTS enforcement across calibrated and fallback paths.
  • Verification scope. Verified deterministically on local macOS arm64 (Node 26) across build, typecheck, lint, docs lint, Hugo site export, and package/CLI/controller test suites. Live GPU SSH smoke testing (LOOPWRIGHT_CUDA_SSH_HOST / LOOPWRIGHT_ROCM_SSH_HOST) and live remote OpenAI-compatible endpoint qualification remain external boundaries.

Related Issues

None.

Verification

  • npm run build passed cleanly
  • npm run typecheck passed cleanly
  • npm run lint passed cleanly
  • npm run lint:docs passed cleanly (37 docs pages, 47 linked sources, 0 errors)
  • npm run site built and verified with zero broken links (20 HTML pages, 17 Markdown exports, 6 reference files)
  • Focused tests passed (@loopwright/evolution 66/67 with 1 live-GPU skip, @loopwright/memory 113/113, @loopwright/decisions 134/134, cli/evolve-cli.test.js + cli/npm-pack.test.js 9/9, controller/advisory-decisions.test.js 2/2)
  • Verified .github/workflows/ maintains least-privilege permissions and remains protected against untrusted taskpack/sandbox writes (zero workflow changes)
  • Signed-off-by: Full Name <email> Developer Certificate of Origin (DCO) included on all commits

Does this PR introduce a user-facing change?

Added `host-execution` evolutionary campaign mode with `HostExecutionEvaluator`, parity-gated `weightedBucketTarget` early-stop, unverified source-only `warmStartSeeds`, `onGenerationCommitted` hook, `campaign-summary.md` rendering, and the `loopwright evolve summary` CLI subcommand. Added root `./sdk/*` subpath shims in the packed npm tarball for Node 26 exports, exported `MEMORY_INJECTION_PATTERNS` and `MEMORY_CREDENTIAL_PATTERNS` from `@loopwright/memory`, and added the ECE-calibrated `openai-compatible-fast` advisory decision provider in `@loopwright/decisions`.

… export

- Generate root sdk/* subpath shims in pack-npm for Node 26 exports
- Add host-execution campaign mode and scalar-aggregating HostExecutionEvaluator
- Add parity-gated weightedBucketTarget early-stop and unverified source-only warmStartSeeds
- Add onGenerationCommitted hook, campaign-summary.md renderer, and evolve summary CLI
- Export MEMORY_INJECTION_PATTERNS and MEMORY_CREDENTIAL_PATTERNS from memory package

Signed-off-by: thxCode <thxcode0824@gmail.com>
- Add openai-compatible-fast provider kind with forced temperature 0 JSON schemas.
- Enforce mandatory offline ECE calibration gating before any remote dispatch.
- Clamp uncalibrated, timed-out, or invalid responses to low-confidence deterministic fallback.
- Enforce DECISION_FORBIDDEN_AUTHORITY_INTENTS fail-closed across calibrated and fallback paths.
- Add 134 passing @loopwright/decisions tests covering wire schemas, ECE, and authority.

Signed-off-by: thxCode <thxcode0824@gmail.com>
@thxCode

thxCode commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

/gpustack-code-review

@gpustack-code-review

gpustack-code-review Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

✅ OpenCodeReview: Review complete: 0 finding(s) across 2 selected item(s).

Reviewed e263623..f0b5476 only; earlier commits in this PR were reviewed in a previous run.

Comment thread packages/decisions/src/benchmark.ts Resolved
Comment thread packages/decisions/src/client.ts Resolved
Comment thread packages/decisions/src/schema.ts Resolved
Comment thread packages/decisions/src/schema.ts Outdated
Comment on lines +170 to +174
const hasTopMaxEce = Object.prototype.hasOwnProperty.call(raw, 'maxEce') && raw['maxEce'] !== undefined;
const maxEce = raw['maxEce'];
if (hasTopMaxEce && (!isFiniteNumber(maxEce) || maxEce < 0 || maxEce > 1)) {
failInvalid('maxEce must be a finite number in [0.00, 1.00]');
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
Inconsistent null handling between sibling calibration fields: calibrationEvidence: null passes hasOwnProperty and is kept (then fails the gate closed as missing_evidence), but maxEce: null is silently dropped here (hasTopMaxEce false, no validation error, not applied). A caller who passes maxEce: null gets no signal that the strict ECE threshold was discarded and the default is in force. Fail closed or reject explicitly, mirroring the calibrationEvidence path.

Suggestion:

Suggested change
const hasTopMaxEce = Object.prototype.hasOwnProperty.call(raw, 'maxEce') && raw['maxEce'] !== undefined;
const maxEce = raw['maxEce'];
if (hasTopMaxEce && (!isFiniteNumber(maxEce) || maxEce < 0 || maxEce > 1)) {
failInvalid('maxEce must be a finite number in [0.00, 1.00]');
}
const hasTopMaxEce = Object.prototype.hasOwnProperty.call(raw, 'maxEce') && raw['maxEce'] !== undefined;
const maxEce = raw['maxEce'];
if (hasTopMaxEce && (!isFiniteNumber(maxEce) || maxEce < 0 || maxEce > 1)) {
failInvalid('maxEce must be a finite number in [0.00, 1.00]');
} else if (Object.prototype.hasOwnProperty.call(raw, 'maxEce') && raw['maxEce'] !== undefined) {
failInvalid('maxEce must be a finite number in [0.00, 1.00]');
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changed (false positive): in JavaScript null !== undefined evaluates to true, so for maxEce: null, hasTopMaxEce is true, isFiniteNumber(null) is false, and validateDecisionPolicy already throws DECISION_POLICY_INVALID (maxEce must be a finite number in [0.00, 1.00]). The same guard applies to openAiCompatibleFastOptions.maxEce: null at line 76.

Comment thread packages/evolution/src/campaign.ts Resolved
Comment thread packages/evolution/src/campaign.ts Resolved
Comment thread packages/evolution/src/campaign.ts Resolved
…summary export

- Gate host-default workload fallback strictly to host-execution campaigns and fail closed otherwise.
- Wire completeWireRows refusal into weightedBucketTarget early-stop and surface skippedWarmStartSeedIds.
- Bound HostExecutionEvaluator tuple cache with FIFO eviction and strict weighted bucketWeights checks.
- Cache frozen WeightedBucketTargetSpec validation in WeakMap and export ./package.json in pack-npm.

Signed-off-by: thxCode <thxcode0824@gmail.com>
…y adapter

- Guard JSON.parse in DecisionClient.execute and benchmark fixture parser without throwing raw SyntaxError.
- Replace malformed calibration cast with typed malformedReason and reject conflicting endpoint/baseUrl.
- Reject baseUrl query parameters, single-criterion score division, and cross-provider fast options.
- Add optional maxCalibrationAgeMs staleness check, widen authority boundary parameter, and reuse defaults.

Signed-off-by: thxCode <thxcode0824@gmail.com>
…rd balance

- Widen Stage A nm and cuobjdump audit timeout from 10s to 30s.
- Always try npm install --offline before bounded registry fallback in npm-pack tests.
- Relax 30s-TTL evolution worker test heartbeatIntervalMs from 50ms to 250ms.
- Add calibrated LPT weights for heavy evolution, cli, and hardware-runner suites.

Signed-off-by: thxCode <thxcode0824@gmail.com>
@thxCode

thxCode commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

Round 1 Review Response

Addressed Round 1 review findings from OpenCodeReview (24 total items: 11 inline threads + 13 summary-routed items; 0 suppressed comments) in fixup commits 2a70296 and 0eeb08b, plus an additional CI stability fix in 26da7ca.

Inline Review Threads (11 total: 9 fixed & resolved, 2 false positives left open)

Thread Location Outcome Details
4779912332 packages/decisions/src/benchmark.ts:156 Fixed (0eeb08b) Guarded JSON.parse(userMessage['content']) in try/catch with plain-object validation.
4779912343 packages/decisions/src/client.ts:281 Fixed (0eeb08b) Guarded JSON.parse(input.stateBody) and threw DECISION_SCHEMA_INVALID on malformed JSON or non-objects.
4779912349 packages/decisions/src/openai-compatible-fast.ts:130 Fixed (0eeb08b) Replaced nested ternary with if / else if, rejected conflicting endpoint + baseUrl, and avoided double normalization.
4779912358 packages/decisions/src/schema.ts:43 Fixed (0eeb08b) Replaced { __malformed: true } as unknown as DecisionCalibrationEvidence with frozen primitive-only `DecisionCalibrationEvidence
4779912362 packages/decisions/src/schema.ts:174 Not changed (false positive) null !== undefined is true in JS, so maxEce: null already sets hasTopMaxEce = true, fails isFiniteNumber(null), and throws DECISION_POLICY_INVALID. Left open for reviewer confirmation.
4779912368 packages/evolution/src/campaign.ts:1160 Not changed (false positive) EvolutionCampaignStore.readCasBlob (packages/evolution/src/store.ts:2001-2046) strictly rejects size > maxBytes without truncation, enforces O_NOFOLLOW/nlink === 1, and re-hashes SHA-256 throwing ARTIFACT_INVALID on mismatch. Left open for reviewer confirmation.
4779912374 packages/evolution/src/campaign.ts:2416 Fixed (2a70296) Gated 'host-default' strictly on evaluationMode === 'host-execution' and threw EVOLUTION_SCHEMA_INVALID in benchmark-gate mode if no heldOutWorkloadId is resolvable.
4779912378 packages/evolution/src/campaign.ts:2435 Fixed (2a70296) Wired completeWireRows?: boolean from HostExecutionEvaluator / CandidateEvaluationResult through a persisted INCOMPLETE_WIRE_ROWS finding marker into checkWeightedBucketTargetMet.
4779912384 packages/evolution/src/campaign.ts:2523 Fixed (2a70296) Surfaced budget-truncated or zero-budget Gen-0 seed IDs via skippedWarmStartSeedIds on GenerationCommittedEvent and RunEvolutionCampaignResult.
4779912390 packages/evolution/src/host-evaluator.ts:430 Fixed (2a70296) Bounded #recordedTuples with FIFO eviction (maxRecordedTuples, default 65_536) and added clearRecordedTuples() + allowDuplicateTuple for explicit retries.
4779912396 packages/evolution/src/host-evaluator.ts:708 Fixed (2a70296) Validated bucketWeights strictly in constructor and failed closed (EVOLUTION_SCHEMA_INVALID) when measured buckets are missing weights or total positive weight is zero.

Summary-Routed Items (13 total: 11 fixed, 2 intentionally kept)

Item Location Outcome Details
S1 packages/decisions/src/types.ts:57-64 Fixed (0eeb08b) Added optional maxCalibrationAgeMs + 'stale_evidence' status + clock forwarding (now) so operators can bound calibration report age without breaking deterministic offline timestamps.
S2 scripts/pack-npm.mjs:142-144 Intentionally kept All 6 bundled @loopwright/* workspace packages use strict named exports only (no default exports); emitting export { default } would fail ESM loading and tsc --noEmit. Documented in a comment on the shim generator.
S3 scripts/pack-npm.mjs:100-108 Fixed (2a70296) Added './package.json': './package.json' to publishedExports and verified isolated consumer import in packages/cli/test/npm-pack.test.ts.
S4 packages/decisions/src/benchmark.ts:238-248 Fixed (0eeb08b) Replaced nested ternary with explicit if / else if / else.
S5 packages/evolution/src/campaign.ts:2544 Fixed (2a70296) Removed hardcoded 'triton' fallback and failed closed (EVOLUTION_SCHEMA_INVALID) if neither seed.trackId nor declaredTracks[0] is present.
S6 packages/evolution/src/campaign.ts:2618-2620 Intentionally kept refreshStageParetoArchive already executes at line 2636 before emitGenerationCommitted (line 2651), matching the regular generation loop's existing pattern; deferred a broad helper extraction to keep this PR surgical.
S7 packages/decisions/src/types.ts:429-432 Fixed (0eeb08b) Widened assertDecisionAuthorityBoundary(intent: unknown) so runtime typeof guards are live and type-checked.
S8 packages/decisions/src/schema.ts:46-48 Fixed (0eeb08b) Resolved alongside thread 4779912358 by normalizing into a frozen primitive-only DecisionCalibrationEvidence (no duplicated sentinel or mutable nested fields).
S9 packages/decisions/src/openai-compatible-fast-wire.ts:479 Fixed (0eeb08b) Guarded criteriaCount < 2 before rawScore / (criteriaCount - 1) to prevent divide-by-zero on direct exported calls.
S10 packages/evolution/src/pareto.ts:787-788 Fixed (2a70296) Froze WeightedBucketTargetSpec outputs in validateWeightedBucketTargetSpec and cached validated instances in a WeakMap keyed by scrubber for O(1) repeated checks.
S11 packages/decisions/src/schema.ts:164-168 Fixed (0eeb08b) Rejected openAiCompatibleFastOptions, top-level calibrationEvidence, maxEce, and maxCalibrationAgeMs on non-openai-compatible-fast providers.
S12 packages/decisions/src/openai-compatible-fast-wire.ts:94-97 Fixed (0eeb08b) Rejected query parameters (parsed.search.length > 0) in resolveOpenAiChatCompletionsEndpoint to prevent credential smuggling in URLs.
S13 packages/decisions/src/openai-compatible-fast.ts:137-140 Fixed (0eeb08b) Reused DEFAULT_DECISION_POLICY.hardDeadlineMs, .maxAttempts, .minConfidence, and .confirmThreshold.

Additional CI Stability Fix (26da7ca)

  • Widened Stage A nm / cuobjdump audit tool timeout from 10_000ms to 30_000ms (packages/hardware-runner/src/evaluator.ts), relaxed 30s-TTL evolution worker test heartbeatIntervalMs from 50ms to 250ms (evolve-cli.test.ts, campaign-hardening.test.ts), enabled offline-first npm install with bounded fetch retries in npm-pack.test.ts, and added calibrated PRIORITY_WEIGHTS in scripts/run-tests.mjs for heavy evolution/CLI/hardware-runner test files to balance Linux CI shards.

Verification

  • Passed npm run build, npm run typecheck, npm run lint, npm run lint:docs, and npm run site.
  • Passed @loopwright/decisions (135/135), @loopwright/memory (113/113), host-execution-e2e + weighted-bucket-target (7/7), npm-pack (2/2), stage-audit-and-quarantine (5/5), campaign-hardening (8/8), and controller/advisory-decisions (2/2).

Comment thread packages/evolution/src/campaign.ts Resolved
this.#recordedTuples.add(tupleKey);
}

const completeWireRows = input.completeWireRows !== false;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
completeWireRows is computed as input.completeWireRows !== false, so any dispatch implementation that omits the flag is treated as fully complete. This is fail-open for the new INCOMPLETE_WIRE_ROWS refusal gate: a dispatcher that fails to detect or report partial wire rows produces candidates that count toward weightedBucketTarget early-stop, which is exactly the scenario the campaign.ts gate was added to prevent. Consider requiring the flag explicitly (throw when dispatched.completeWireRows === undefined for host-execution dispatchers), or at least defaulting to incomplete so integrators must opt in to completeness.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changed (intentionally kept): EvaluateWeightedBucketTargetOptions.completeWireRows is explicitly documented as completeWireRows !== false, and missing required buckets are already refused fail-closed via requiredBucketIds (MISSING_REQUIRED_BUCKET). Throwing or defaulting to incomplete on omission would break standard callers whose dispatched checks are complete. Strict typeof === 'boolean' validation was added in 3119b19 so non-boolean values cannot slip through.

…summary export

- Record campaign progress before emitting zero-budget Gen-0 skip event.
- Track evictedRecordedTuplesCount and validate completeWireRows and allowDuplicateTuple as booleans.
- Stop forwarding allowDuplicateTuple from dispatch layer and fail fast on missing bucketWeights.
- Remove dead Object.hasOwn guard in validateBucketWeightsMap.

Signed-off-by: thxCode <thxcode0824@gmail.com>
…y adapter

- Reject query parameters and embedded credentials on direct openai-compatible-fast endpoints.
- Reject future-dated calibrationEvidence timestamps and evaluate adapter.calibration dynamically.
- Trim direct endpoint consistently and reuse shared isValidMaxEce helper.

Signed-off-by: thxCode <thxcode0824@gmail.com>
@thxCode

thxCode commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

Round 2 Review Response

Addressed Round 2 incremental review findings from OpenCodeReview (12 total items: 8 inline threads + 4 summary-routed items, including 1 duplicate) in fixup commits 3119b19 and e263623.

Inline Review Threads (8 total: 7 fixed & resolved, 1 intentionally kept open)

Thread Location Outcome Details
4780090521 packages/decisions/src/openai-compatible-fast-wire.ts:99 Fixed (e263623) Added validateOpenAiFastDirectEndpoint and enforced query-param and embedded-credential rejection on direct endpoint values in validateDecisionPolicy.
4780090540 packages/decisions/src/openai-compatible-fast-wire.ts:232 Fixed (e263623) Rejected future-dated evaluatedAt timestamps (evaluatedAtMs > nowMs) as stale_evidence when maxCalibrationAgeMs is configured.
4780090542 packages/decisions/src/openai-compatible-fast.ts:157 Fixed (e263623) Evaluated adapter.calibration dynamically via evaluatePolicyCalibrationGate(this.#policy, this.#now) instead of caching construction-time state.
4780090548 packages/evolution/src/campaign.ts:2567 Fixed (3119b19) Called store.updateCampaignProgress (stagePhase, activeBucketId, currentGeneration: 0) before emitting the zero-budget Gen-0 skip event.
4780090555 packages/evolution/src/host-evaluator.ts:671 Fixed (3119b19) Exposed evictedRecordedTuplesCount on HostExecutionEvaluator and HostExecutionEvaluationResult so FIFO cap eviction is observable.
4780090560 packages/evolution/src/host-evaluator.ts:675 Intentionally kept Preserved the documented completeWireRows !== false default contract (missing required buckets already fail closed via MISSING_REQUIRED_BUCKET); strict typeof === 'boolean' checking was added in 3119b19. Left open for reviewer confirmation.
4780090565 packages/evolution/src/host-evaluator.ts:733 Fixed (3119b19) Enforced strict boolean validation on completeWireRows and allowDuplicateTuple, and removed allowDuplicateTuple forwarding from HostExecutionDispatchOutcome / asCandidateEvaluator().
4780090579 packages/evolution/src/host-evaluator.ts:789 Fixed (3119b19) Moved the missing-bucketWeights validation into aggregate()'s check validation loop so misconfigured weights fail fast before core validation or tuple commits.

Summary-Routed Items (4 total: 4 fixed)

Item Location Outcome Details
R2-S1 & R2-S3 (duplicate) packages/decisions/src/openai-compatible-fast.ts:140-142 Fixed (e263623) Trimmed config.endpoint consistently across both single-argument and conflict-check branches (and inside validateDecisionPolicy).
R2-S2 packages/decisions/src/openai-compatible-fast-wire.ts:314-316 Fixed (e263623) Extracted shared isValidMaxEce helper and reused it across openai-compatible-fast-wire.ts and schema.ts.
R2-S4 packages/evolution/src/host-evaluator.ts:342-344 Fixed (3119b19) Removed the redundant Object.hasOwn(weights, key) guard inside for (const key of Object.keys(weights)).

Verification

  • Passed npm run build, npm run typecheck, npm run lint, npm run lint:docs, and npm run site.
  • Passed @loopwright/decisions (135/135), host-execution-e2e + weighted-bucket-target + controller/advisory-decisions (9/9).

…summary export

- Reset evictedRecordedTuplesCount to zero inside clearRecordedTuples and assert in E2E test.

Signed-off-by: thxCode <thxcode0824@gmail.com>
…y adapter

- Reject non-empty URL fragments fail-closed on openai-compatible-fast direct endpoints and baseUrls.

Signed-off-by: thxCode <thxcode0824@gmail.com>
@thxCode

thxCode commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

Round 3 Review Response

Addressed both Round 3 incremental review findings from OpenCodeReview (2 total items: 1 inline thread + 1 summary-routed item) in fixup commits 7dd0406 and f0b5476.

Inline Review Threads (1 total: 1 fixed & resolved)

Thread Location Outcome Details
4780153456 packages/evolution/src/host-evaluator.ts:410 Fixed (7dd0406) Reset #evictedRecordedTuplesCount = 0 inside clearRecordedTuples() and added an assertion in host-execution-e2e.test.ts.

Summary-Routed Items (1 total: 1 fixed)

Item Location Outcome Details
R3-S1 packages/decisions/src/openai-compatible-fast-wire.ts:104-106 Fixed (f0b5476) Rejected non-empty URL fragments (parsed.hash.length > 0) fail-closed with DECISION_POLICY_INVALID in both validateOpenAiFastDirectEndpoint and resolveOpenAiChatCompletionsEndpoint, verified in openai-compatible-fast.test.ts.

Verification

  • Passed npm run build, npm run typecheck, npm run lint, npm run lint:docs, and npm run site.
  • Passed @loopwright/decisions (135/135) and packages/evolution/test/host-execution-e2e.test.js (3/3).

@thxCode
thxCode merged commit 4cfffbf into main Dec 3, 2026
14 checks passed
@thxCode
thxCode deleted the lw-m1-host-eval branch December 3, 2026 05:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant