Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
44 changes: 44 additions & 0 deletions docs/TRAJECTORY_EVIDENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand All @@ -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

Expand Down
11 changes: 11 additions & 0 deletions examples/react-policy-optimization/README.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
126 changes: 126 additions & 0 deletions examples/react-policy-optimization/src/record-trajectories.ts
Original file line number Diff line number Diff line change
@@ -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 },
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
13 changes: 13 additions & 0 deletions packages/rl/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions packages/rl/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@ export * from "./strategy-bandit";
export * from "./trajectory";
export * from "./trajectory-evidence";
export * from "./trajectory-import";
export * from "./trajectory-recorder";
28 changes: 22 additions & 6 deletions packages/rl/src/trajectory-evidence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export interface ObservedComparisonOptions {
minimumPairs: number;
minimumQualityGain: number;
maximumToolIncrease: number;
actionKinds: Readonly<Record<string, "tool" | "control">>;
}

/** Paired observed outcomes, never a counterfactual estimate from unchosen actions. */
Expand All @@ -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 = [];
Expand All @@ -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"))
Expand Down Expand Up @@ -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 {
Expand Down
22 changes: 22 additions & 0 deletions packages/rl/src/trajectory-fields.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import type { JsonRecord } from "@ignitionai/agent-trainer-core";
import type { AllowedObservationFields } from "./trajectory-import";

export function redactTrajectoryFields(
input: Record<string, unknown>,
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;
}
27 changes: 27 additions & 0 deletions packages/rl/src/trajectory-import.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,13 +89,40 @@ 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);
expect(comparison.quality.mean).toBeCloseTo(0.1);
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.",
Expand Down
Loading
Loading