From 1d2c91aa60d6fbc9b51658252b7662f0ccc254bb Mon Sep 17 00:00:00 2001 From: Salim Date: Sun, 4 Oct 2026 14:31:49 +0200 Subject: [PATCH] feat(rl): record executed trajectory transitions and explicit tool counts --- CHANGELOG.md | 4 + docs/TRAJECTORY_EVIDENCE.md | 44 ++++++ examples/react-policy-optimization/README.md | 11 ++ .../src/record-trajectories.ts | 126 +++++++++++++++ .../src/trajectory-evidence.ts | 1 + packages/rl/README.md | 13 ++ packages/rl/src/index.ts | 1 + packages/rl/src/trajectory-evidence.ts | 28 +++- packages/rl/src/trajectory-fields.ts | 22 +++ packages/rl/src/trajectory-import.test.ts | 27 ++++ packages/rl/src/trajectory-import.ts | 27 +--- packages/rl/src/trajectory-recorder.test.ts | 132 ++++++++++++++++ packages/rl/src/trajectory-recorder.ts | 144 ++++++++++++++++++ 13 files changed, 554 insertions(+), 26 deletions(-) create mode 100644 examples/react-policy-optimization/src/record-trajectories.ts create mode 100644 packages/rl/src/trajectory-fields.ts create mode 100644 packages/rl/src/trajectory-recorder.test.ts create mode 100644 packages/rl/src/trajectory-recorder.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 2659211..0d9b340 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- Add executed trajectory capture with allowlisted observations, explicit quality + evaluation and measured step latency. Observed comparisons now require an + explicit tool/control action registry. Actual IgnitionRAG runtime evidence remains unproven. + - Add a versioned, pseudonymized trajectory import and observed-policy evidence comparison contract. Real IgnitionRAG evidence remains unverified without an authorized export. diff --git a/docs/TRAJECTORY_EVIDENCE.md b/docs/TRAJECTORY_EVIDENCE.md index ea49abd..c68c6ff 100644 --- a/docs/TRAJECTORY_EVIDENCE.md +++ b/docs/TRAJECTORY_EVIDENCE.md @@ -54,6 +54,41 @@ Do not reconstruct unobserved state, action choices or transition rewards from an answer-only report. If the runtime lacks these fields, a separate IgnitionRAG instrumentation PR is needed before using these records for learning. +## Executed episode recording + +`recordIgnitionRagEpisode(environment, policy, options)` executes a supplied +`AgentEnvironment` through `runLearningEpisode` and returns the episode portion +of the export envelope. It snapshots allowlisted observations and object +arguments before a mutable tool executes, then records only the returned reward, +observation and terminal status. The step budget produces explicit truncation. +Exceptions fail the recording; they never manufacture a successful episode. +`evaluateQuality` must evaluate the executed result using the pinned quality +definition independently of total reward. `readMeasuredCost` may return a +provider-measured USD cost; omitting it leaves cost unavailable. Step latency is +measured wall time around `environment.step`, including its overhead, rather +than a provider-only latency. Caller-supplied provenance and `evidenceMode` +remain declarations requiring an independent check. + +## Missing IgnitionRAG binding + +The inspected IgnitionRAG `createAgentEvaluationLiveRunner` calls `chatStream` +or `chatStreamWithMcp` and collects `text`, `tool_call` and `tool_result` events. +Its result contains an answer, trace and aggregate token/latency usage. Its +`smoke-agent-trainer-packages.ts` only verifies installed package imports and +versions; it cannot execute an isolated real learning episode. + +A real binding must provide the observable `reset` state, authorized `actions` +before each choice, and an awaited `step` yielding the actual post-tool state, +pinned transition reward and terminal flag. The learned policy must choose the +executed action at that same decision boundary. Record both policies on the same +reserved tasks and immutable snapshot, using the same reward/quality evaluator. +Do not infer per-tool USD cost from aggregate tokens or split total latency +between tool events. The existing stream collector has no pre-choice state, +reward or learned-action hook; turning its trace into these fields would invent +evidence. This recorder prepares the capture boundary, but does not supply or +claim that real binding. No authorization route or persistent deployment is +changed by this PR. + ## Import and privacy Use `importIgnitionRagTrajectories(raw, { pseudonymSalt, actionNames, @@ -82,6 +117,9 @@ the current comparator; repetitions need an explicit aggregation protocol first. The comparison reports paired quality deltas, tool deltas, measured cost/latency deltas, exclusions and uncertainty. Missing cost/latency is `null`, not zero. +The protocol must explicitly classify every observed action through +`actionKinds: { toolName: "tool", finalAnswer: "control" }`. Missing classifications +are rejected. Tool counts use this pinned registry, never naming conventions. The paired normal interval is approximate, needs at least 30 independent tasks and is not valid evidence for correlated or cherry-picked cases. Small samples retain their raw observations but cannot pass a positive-gain gate. @@ -99,12 +137,18 @@ source and still requires provenance review. No live policy is activated. ```bash bun examples/react-policy-optimization/src/trajectory-evidence.ts /tmp/trajectory-evidence bun test packages/rl/src/trajectory-import.test.ts +bun examples/react-policy-optimization/src/record-trajectories.ts /tmp/recorded-trajectories +bun test packages/rl/src/trajectory-recorder.test.ts ``` The example imports 60 explicitly synthetic episodes (30 actual fixture pairs), redacts private fields, reports a quality delta and keeps missing usage unavailable. Its decision is deliberately `do-not-adopt`: it proves the import/comparison mechanics and does not establish improvement in IgnitionRAG. +The recording example executes two written policies against the synthetic order +environment, exports their actual transitions, measures step latency, leaves +cost unavailable and imports the result. It establishes the recorder/import +boundary and declares `evidenceMode: "synthetic"`; it supplies no real gain proof. ## Required real-data proof diff --git a/examples/react-policy-optimization/README.md b/examples/react-policy-optimization/README.md index 99610a8..826e3bd 100644 --- a/examples/react-policy-optimization/README.md +++ b/examples/react-policy-optimization/README.md @@ -1,5 +1,16 @@ # ReAct policy optimization +To execute the trajectory recorder against the synthetic order environment: + +```bash +bun examples/react-policy-optimization/src/record-trajectories.ts /tmp/recorded-trajectories +``` + +This records actual demo transitions with allowlisted fields and measured wall +latency; cost remains unavailable. It compares two written demo controllers and +declares synthetic evidence. See the [binding requirements](../../docs/TRAJECTORY_EVIDENCE.md) +before using it with a real IgnitionRAG environment. + ## Observed trajectory import contract ```bash diff --git a/examples/react-policy-optimization/src/record-trajectories.ts b/examples/react-policy-optimization/src/record-trajectories.ts new file mode 100644 index 0000000..cfee426 --- /dev/null +++ b/examples/react-policy-optimization/src/record-trajectories.ts @@ -0,0 +1,126 @@ +import { mkdir, writeFile } from "node:fs/promises"; +import { pathToFileURL } from "node:url"; +import type { AgentEnvironment, Policy } from "@ignitionai/agent-trainer-environment"; +import { + importIgnitionRagTrajectories, + recordIgnitionRagEpisode, +} from "@ignitionai/agent-trainer-rl"; +import { createOrderPolicy, OrderEnvironment } from "./agent"; + +const fields = { + actionNames: ["lookup_price", "calculate_total", "answer"], + observationFields: { + quantity: "number", + unitPrice: "number", + total: "number", + correct: "boolean", + }, + argumentFields: { value: "number" }, +} as const; + +/** The export protocol uses object arguments; this adapter preserves the scalar demo action. */ +function recordingTask(strategy: "direct" | "react"): { + environment: AgentEnvironment; + policy: Policy; +} { + const environment = new OrderEnvironment({ + id: "synthetic-order", + product: "fixture-product", + quantity: 3, + unitPrice: 7, + }); + const policy = createOrderPolicy(strategy); + return { + environment: { + reset: () => environment.reset(), + actions: (state) => environment.actions(state), + step(state, action) { + const value = + action.input && typeof action.input === "object" && !Array.isArray(action.input) + ? action.input.value + : undefined; + return environment.step(state, { + name: action.name, + ...(value !== undefined ? { input: value } : {}), + }); + }, + }, + policy: { + async chooseAction(state, actions) { + const action = await policy.chooseAction(state, actions); + return { + name: action.name, + ...(action.input !== undefined ? { input: { value: action.input } } : {}), + }; + }, + }, + }; +} + +export async function runRecordedTrajectoryExample() { + const episodes = []; + for (const strategy of ["direct", "react"] as const) { + const { environment, policy } = recordingTask(strategy); + episodes.push( + await recordIgnitionRagEpisode(environment, policy, { + runId: `synthetic-${strategy}`, + episodeId: `synthetic-${strategy}`, + taskId: "synthetic-order", + workflowSnapshotId: "synthetic-order-v1", + policyId: `written-${strategy}`, + maxSteps: 4, + fields, + evaluateQuality: (episode) => (episode.finalState.observation.correct === true ? 1 : 0), + }), + ); + } + const envelope = { + schemaVersion: "ignitionrag.trajectory-export.v1", + source: "ignitionrag", + evidenceMode: "synthetic", + environmentId: "synthetic-order-demo", + authorizationReference: "synthetic-only", + rewardConfigId: "order-correctness-and-tool-cost-v1", + exportedAt: new Date().toISOString(), + episodes, + }; + return { + envelope, + imported: importIgnitionRagTrajectories(envelope, { + ...fields, + pseudonymSalt: "synthetic-demo-salt-only", + }), + realEvidence: + "NOT PROVEN: this executes the synthetic order environment, not the IgnitionRAG runner.", + }; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const report = await runRecordedTrajectoryExample(); + console.log( + JSON.stringify( + { + episodes: report.imported.episodes.length, + rejected: report.imported.rejected, + measuredLatencies: report.envelope.episodes.map((episode) => + episode.steps.map((step) => step.usage.latencyMs), + ), + quality: report.envelope.episodes.map((episode) => ({ + policyId: episode.policyId, + score: episode.qualityScore, + })), + realEvidence: report.realEvidence, + }, + null, + 2, + ), + ); + if (process.argv[2]) { + await mkdir(process.argv[2], { recursive: true }); + await writeFile( + `${process.argv[2]}/recorded-trajectories.json`, + `${JSON.stringify(report, null, 2)}\n`, + { mode: 0o600 }, + ); + } +} diff --git a/examples/react-policy-optimization/src/trajectory-evidence.ts b/examples/react-policy-optimization/src/trajectory-evidence.ts index 32d254e..8fdc7c9 100644 --- a/examples/react-policy-optimization/src/trajectory-evidence.ts +++ b/examples/react-policy-optimization/src/trajectory-evidence.ts @@ -70,6 +70,7 @@ export function runTrajectoryEvidenceExample() { minimumPairs: 30, minimumQualityGain: 0.05, maximumToolIncrease: 0, + actionKinds: { lookup_price: "tool" as const, answer: "control" as const }, }); return { imported, diff --git a/packages/rl/README.md b/packages/rl/README.md index 0b0aa93..9b2a4e3 100644 --- a/packages/rl/README.md +++ b/packages/rl/README.md @@ -2,6 +2,19 @@ ## Observed IgnitionRAG trajectory evidence +`recordIgnitionRagEpisode(environment, policy, options)` executes an environment +and returns allowlisted pre-action states, chosen actions, observed rewards and +post-action observations. Supply stable task/snapshot ids, an independent +`evaluateQuality` callback and an explicit field/action allowlist. Step latency +is measured wall time; USD cost stays unavailable unless `readMeasuredCost` +returns an actual provider measurement. Budget exhaustion records truncation; +tool exceptions reject recording. Assemble episodes into the v1 export envelope +with verified provenance. This does not authenticate an environment or create +the missing IgnitionRAG runtime binding. + +`compareObservedTrajectoryPolicies` requires `actionKinds` to classify every +observed action as `tool` or `control`; action names never imply tool counts. + `importIgnitionRagTrajectories(unknownExport, options)` validates versioned episode/transition exports, pseudonymizes ids with a private stable salt and retains only explicitly authorized numeric, boolean or enumerated-string fields. diff --git a/packages/rl/src/index.ts b/packages/rl/src/index.ts index 0f71da2..634e2cd 100644 --- a/packages/rl/src/index.ts +++ b/packages/rl/src/index.ts @@ -14,3 +14,4 @@ export * from "./strategy-bandit"; export * from "./trajectory"; export * from "./trajectory-evidence"; export * from "./trajectory-import"; +export * from "./trajectory-recorder"; diff --git a/packages/rl/src/trajectory-evidence.ts b/packages/rl/src/trajectory-evidence.ts index 89f697b..478e459 100644 --- a/packages/rl/src/trajectory-evidence.ts +++ b/packages/rl/src/trajectory-evidence.ts @@ -27,6 +27,7 @@ export interface ObservedComparisonOptions { minimumPairs: number; minimumQualityGain: number; maximumToolIncrease: number; + actionKinds: Readonly>; } /** Paired observed outcomes, never a counterfactual estimate from unchosen actions. */ @@ -41,9 +42,23 @@ export function compareObservedTrajectoryPolicies( !Number.isFinite(options.minimumQualityGain) || options.minimumQualityGain <= 0 || !Number.isFinite(options.maximumToolIncrease) || - options.maximumToolIncrease < 0 + options.maximumToolIncrease < 0 || + !options.actionKinds || + typeof options.actionKinds !== "object" || + Array.isArray(options.actionKinds) ) throw new Error("Invalid observed policy comparison protocol."); + const observedNames = data.episodes.flatMap((episode) => + episode.transitions.map((step) => step.action.name), + ); + if ( + observedNames.some( + (name) => + !Object.hasOwn(options.actionKinds, name) || + !["tool", "control"].includes(options.actionKinds[name] ?? ""), + ) + ) + throw new Error("Every observed action requires an explicit tool/control classification."); const baseline = observedByTask(data.episodes, options.baselinePolicyId); const learned = observedByTask(data.episodes, options.learnedPolicyId); const paired = []; @@ -65,7 +80,7 @@ export function compareObservedTrajectoryPolicies( taskId: a.taskId, snapshotId: a.workflowSnapshotId, qualityDelta: b.qualityScore - a.qualityScore, - toolDelta: toolCount(b) - toolCount(a), + toolDelta: toolCount(b, options.actionKinds) - toolCount(a, options.actionKinds), costDelta: measuredTotal(b, "costUsd") !== null && measuredTotal(a, "costUsd") !== null ? Number(measuredTotal(b, "costUsd")) - Number(measuredTotal(a, "costUsd")) @@ -124,10 +139,11 @@ function observedByTask(episodes: readonly ImportedEpisode[], policyId: string) return groups; } -function toolCount(episode: ImportedEpisode): number { - return episode.transitions.filter( - (step) => !["answer", "abstain", "clarify"].includes(step.action.name), - ).length; +function toolCount( + episode: ImportedEpisode, + actionKinds: ObservedComparisonOptions["actionKinds"], +): number { + return episode.transitions.filter((step) => actionKinds[step.action.name] === "tool").length; } function measuredTotal(episode: ImportedEpisode, field: "costUsd" | "latencyMs"): number | null { diff --git a/packages/rl/src/trajectory-fields.ts b/packages/rl/src/trajectory-fields.ts new file mode 100644 index 0000000..bfbb167 --- /dev/null +++ b/packages/rl/src/trajectory-fields.ts @@ -0,0 +1,22 @@ +import type { JsonRecord } from "@ignitionai/agent-trainer-core"; +import type { AllowedObservationFields } from "./trajectory-import"; + +export function redactTrajectoryFields( + input: Record, + fields: AllowedObservationFields, +): JsonRecord { + const output: JsonRecord = {}; + for (const [name, kind] of Object.entries(fields)) { + if (name === "__proto__" || name === "constructor" || name === "prototype") + throw new Error("Unsafe observation field name."); + const value = input[name]; + if (kind === "number" && typeof value === "number" && !Number.isFinite(value)) + throw new Error("Allowed numeric observation must be finite."); + if (kind === "number" && typeof value === "number" && Number.isFinite(value)) + output[name] = value; + else if (kind === "boolean" && typeof value === "boolean") output[name] = value; + else if (Array.isArray(kind) && typeof value === "string" && kind.includes(value)) + output[name] = value; + } + return output; +} diff --git a/packages/rl/src/trajectory-import.test.ts b/packages/rl/src/trajectory-import.test.ts index 68a5893..0341393 100644 --- a/packages/rl/src/trajectory-import.test.ts +++ b/packages/rl/src/trajectory-import.test.ts @@ -89,6 +89,7 @@ test("paired comparison never invents missing usage or counterfactual rewards an minimumPairs: 30, minimumQualityGain: 0.05, maximumToolIncrease: 0, + actionKinds: { lookup_price: "tool" as const, answer: "control" as const }, }; const comparison = compareObservedTrajectoryPolicies(imported, protocol); expect(comparison.paired).toHaveLength(30); @@ -96,6 +97,32 @@ test("paired comparison never invents missing usage or counterfactual rewards an expect(comparison.cost).toBeNull(); expect(comparison.latency).toBeNull(); expect(comparison.alternativeActionsEstimated).toBe(false); + expect(comparison.tools.mean).toBe(0); + expect(() => + compareObservedTrajectoryPolicies(imported, { ...protocol, actionKinds: {} }), + ).toThrow("classification"); + const moreTools = { + ...imported, + episodes: imported.episodes.map((episode) => ({ + ...episode, + transitions: episode.transitions.map((step) => ({ + ...step, + action: { + ...step.action, + name: + step.action.name === "answer" && episode.policyId === protocol.learnedPolicyId + ? "finalize" + : step.action.name, + }, + })), + })), + }; + const classified = compareObservedTrajectoryPolicies(moreTools, { + ...protocol, + actionKinds: { ...protocol.actionKinds, finalize: "tool" }, + }); + expect(classified.tools.mean).toBe(1); + expect(classified.reasons).toContain("Tool use exceeds the protocol threshold."); expect(comparison.decision).toBe("do-not-adopt"); expect(comparison.reasons).toContain( "Synthetic evidence cannot establish production improvement.", diff --git a/packages/rl/src/trajectory-import.ts b/packages/rl/src/trajectory-import.ts index 1213c09..8d66a60 100644 --- a/packages/rl/src/trajectory-import.ts +++ b/packages/rl/src/trajectory-import.ts @@ -1,5 +1,6 @@ import { createHash, createHmac } from "node:crypto"; import type { JsonRecord } from "@ignitionai/agent-trainer-core"; +import { redactTrajectoryFields } from "./trajectory-fields"; export type AllowedObservationFields = Readonly< Record @@ -148,12 +149,15 @@ function readTransition(input: unknown, options: TrajectoryImportOptions): Impor const costUsd = optionalMetric(usage.costUsd); const latencyMs = optionalMetric(usage.latencyMs); return { - state: redact(record(step.state), options.observationFields), + state: redactTrajectoryFields(record(step.state), options.observationFields), action: { name, - input: redact(action.input === undefined ? {} : record(action.input), options.argumentFields), + input: redactTrajectoryFields( + action.input === undefined ? {} : record(action.input), + options.argumentFields, + ), }, - observation: redact(record(step.observation), options.observationFields), + observation: redactTrajectoryFields(record(step.observation), options.observationFields), reward: finite(step.reward), done: step.done, ...(costUsd !== undefined ? { costUsd } : {}), @@ -161,23 +165,6 @@ function readTransition(input: unknown, options: TrajectoryImportOptions): Impor }; } -function redact(input: Record, fields: AllowedObservationFields): JsonRecord { - const output: JsonRecord = {}; - for (const [name, kind] of Object.entries(fields)) { - if (name === "__proto__" || name === "constructor" || name === "prototype") - throw new Error("Unsafe observation field name."); - const value = input[name]; - if (kind === "number" && typeof value === "number" && !Number.isFinite(value)) - throw new Error("Allowed numeric observation must be finite."); - if (kind === "number" && typeof value === "number" && Number.isFinite(value)) - output[name] = value; - else if (kind === "boolean" && typeof value === "boolean") output[name] = value; - else if (Array.isArray(kind) && typeof value === "string" && kind.includes(value)) - output[name] = value; - } - return output; -} - function record(input: unknown): Record { if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("Expected an object."); diff --git a/packages/rl/src/trajectory-recorder.test.ts b/packages/rl/src/trajectory-recorder.test.ts new file mode 100644 index 0000000..614c7b9 --- /dev/null +++ b/packages/rl/src/trajectory-recorder.test.ts @@ -0,0 +1,132 @@ +import type { + AgentEnvironment, + EnvironmentState, + Policy, +} from "@ignitionai/agent-trainer-environment"; +import { expect, test } from "vitest"; +import { importIgnitionRagTrajectories } from "./trajectory-import"; +import { recordIgnitionRagEpisode, type TrajectoryRecordingOptions } from "./trajectory-recorder"; + +const fields = { + actionNames: ["lookup"], + observationFields: { phase: "number" as const }, + argumentFields: { limit: "number" as const }, +}; +const options: TrajectoryRecordingOptions = { + runId: "run", + episodeId: "episode", + taskId: "task", + workflowSnapshotId: "snapshot", + policyId: "baseline", + maxSteps: 2, + fields, + evaluateQuality: (episode) => (episode.finalState.observation.phase === 2 ? 0.9 : 0), +}; +const policy: Policy = { + async chooseAction() { + return { name: "lookup", input: { limit: 3, credential: "private-token" } }; + }, +}; + +function mutableEnvironment(terminal: boolean): AgentEnvironment { + let current: EnvironmentState = { + id: "initial", + observation: { phase: 0, customer: "private-customer" }, + }; + return { + async reset() { + return current; + }, + async actions() { + return [{ name: "lookup" }]; + }, + async step(state, action) { + current = state; + current.observation.phase = Number(current.observation.phase) + 1; + if (action.input && typeof action.input === "object" && !Array.isArray(action.input)) + action.input.limit = 99; + return { + state: current, + reward: { name: "observed", score: -0.25, weight: 2 }, + done: terminal && current.observation.phase === 2, + metadata: { costUsd: 0.01 }, + }; + }, + }; +} + +test("records executed transitions before mutable tools change their inputs, with independent quality and measured usage", async () => { + const episode = await recordIgnitionRagEpisode(mutableEnvironment(true), policy, { + ...options, + readMeasuredCost: (result) => + typeof result.metadata?.costUsd === "number" ? result.metadata.costUsd : undefined, + }); + expect( + episode.steps.map((step) => [ + step.state.phase, + step.observation.phase, + step.action.input.limit, + step.reward, + ]), + ).toEqual([ + [0, 1, 3, -0.5], + [1, 2, 3, -0.5], + ]); + expect(episode.qualityScore).toBe(0.9); + expect(episode.done).toBe(true); + expect(episode.truncated).toBe(false); + expect( + episode.steps.every((step) => step.usage.latencyMs >= 0 && step.usage.costUsd === 0.01), + ).toBe(true); + const envelope = { + schemaVersion: "ignitionrag.trajectory-export.v1", + source: "ignitionrag", + evidenceMode: "synthetic", + environmentId: "test-fixture", + authorizationReference: "synthetic-only", + rewardConfigId: "test-reward", + exportedAt: new Date().toISOString(), + episodes: [episode], + }; + const imported = importIgnitionRagTrajectories(envelope, { + ...fields, + pseudonymSalt: "stable-private-test-salt", + }); + expect(imported.rejected).toEqual([]); + expect(imported.episodes).toHaveLength(1); + expect(JSON.stringify(envelope)).not.toContain("private-"); +}); + +test("step budget records truncation and unavailable cost without claiming success", async () => { + const episode = await recordIgnitionRagEpisode(mutableEnvironment(false), policy, { + ...options, + maxSteps: 1, + }); + expect(episode.done).toBe(false); + expect(episode.truncated).toBe(true); + expect(episode.qualityScore).toBe(0); + expect(episode.steps).toHaveLength(1); + expect(episode.steps[0]?.usage.costUsd).toBeUndefined(); +}); + +test("failed tool or invalid observed quality never returns an exportable completed episode", async () => { + const environment = mutableEnvironment(true); + environment.step = async () => { + throw new Error("provider unavailable"); + }; + await expect(recordIgnitionRagEpisode(environment, policy, options)).rejects.toThrow( + "provider unavailable", + ); + await expect( + recordIgnitionRagEpisode(mutableEnvironment(true), policy, { + ...options, + evaluateQuality: () => NaN, + }), + ).rejects.toThrow("quality"); + await expect( + recordIgnitionRagEpisode(mutableEnvironment(true), policy, { + ...options, + readMeasuredCost: () => -1, + }), + ).rejects.toThrow("cost"); +}); diff --git a/packages/rl/src/trajectory-recorder.ts b/packages/rl/src/trajectory-recorder.ts new file mode 100644 index 0000000..8e74755 --- /dev/null +++ b/packages/rl/src/trajectory-recorder.ts @@ -0,0 +1,144 @@ +import type { JsonRecord } from "@ignitionai/agent-trainer-core"; +import type { + AgentEnvironment, + EnvironmentStepResult, + Policy, +} from "@ignitionai/agent-trainer-environment"; +import { type LearningEpisodeResult, runLearningEpisode } from "./learning-episode"; +import type { LearningPolicy } from "./q-learning"; +import { redactTrajectoryFields } from "./trajectory-fields"; +import type { TrajectoryImportOptions } from "./trajectory-import"; + +export interface RecordedTrajectoryStep { + state: JsonRecord; + action: { name: string; input: JsonRecord }; + observation: JsonRecord; + reward: number; + done: boolean; + usage: { latencyMs: number; costUsd?: number }; +} + +export interface TrajectoryRecordingOptions { + runId: string; + episodeId: string; + taskId: string; + workflowSnapshotId: string; + policyId: string; + maxSteps: number; + seed?: number; + fields: Omit; + /** An independently configured evaluator of the executed episode, not totalReward. */ + evaluateQuality: (episode: LearningEpisodeResult) => number | Promise; + /** Only provider-measured cost. Undefined leaves cost unavailable. */ + readMeasuredCost?: (result: EnvironmentStepResult) => number | undefined; +} + +export interface RecordedTrajectoryEpisode { + runId: string; + episodeId: string; + taskId: string; + workflowSnapshotId: string; + policyId: string; + collectedAt: string; + done: boolean; + truncated: boolean; + qualityScore: number; + steps: RecordedTrajectoryStep[]; +} + +/** Executes the supplied environment. No replay, alternative rewards or provenance claim. */ +export async function recordIgnitionRagEpisode( + environment: AgentEnvironment, + policy: LearningPolicy | Policy, + options: TrajectoryRecordingOptions, +): Promise { + validateIdentity(options); + const collectedAt = new Date().toISOString(); + const steps: RecordedTrajectoryStep[] = []; + const episode = await runLearningEpisode( + recordingEnvironment(environment, options, steps), + policy, + { + maxSteps: options.maxSteps, + ...(options.seed !== undefined ? { seed: options.seed } : {}), + policyId: options.policyId, + }, + ); + if (steps.length === 0) throw new Error("Recording requires an executed transition."); + const qualityScore = await options.evaluateQuality(episode); + if (!Number.isFinite(qualityScore) || qualityScore < 0 || qualityScore > 1) + throw new Error("Observed episode quality must be in [0, 1]."); + return { + runId: options.runId, + episodeId: options.episodeId, + taskId: options.taskId, + workflowSnapshotId: options.workflowSnapshotId, + policyId: options.policyId, + collectedAt, + done: episode.done, + truncated: episode.truncated, + qualityScore, + steps, + }; +} + +function recordingEnvironment( + environment: AgentEnvironment, + options: TrajectoryRecordingOptions, + steps: RecordedTrajectoryStep[], +): AgentEnvironment { + return { + reset: (seed) => environment.reset(seed), + actions: (state) => environment.actions(state), + async step(state, action) { + if (!options.fields.actionNames.includes(action.name)) + throw new Error("Recorded action is not in the authorized registry."); + const recordedState = redactTrajectoryFields( + state.observation, + options.fields.observationFields, + ); + const input = readArguments(action.input); + const recordedAction = { + name: action.name, + input: redactTrajectoryFields(input, options.fields.argumentFields), + }; + const startedAt = performance.now(); + const result = await environment.step(state, action); + const latencyMs = performance.now() - startedAt; + const costUsd = options.readMeasuredCost?.(result); + if (costUsd !== undefined && (!Number.isFinite(costUsd) || costUsd < 0)) + throw new Error("Measured transition cost must be finite and nonnegative."); + steps.push({ + state: recordedState, + action: recordedAction, + observation: redactTrajectoryFields( + result.state.observation, + options.fields.observationFields, + ), + reward: result.reward.score * result.reward.weight, + done: result.done || result.state.done === true, + usage: { latencyMs, ...(costUsd !== undefined ? { costUsd } : {}) }, + }); + return result; + }, + }; +} + +function readArguments(input: unknown): JsonRecord { + if (input === undefined) return {}; + if (!input || typeof input !== "object" || Array.isArray(input)) + throw new Error("Trajectory export requires object action arguments."); + return input as JsonRecord; +} + +function validateIdentity(options: TrajectoryRecordingOptions): void { + for (const value of [ + options.runId, + options.episodeId, + options.taskId, + options.workflowSnapshotId, + options.policyId, + ]) + if (typeof value !== "string" || !value.trim() || value.length > 500) + throw new Error("Recording identity is missing or too long."); +}