From a2cde2598a171c1d7892d2a3f7c54f57571d3d32 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 16 Nov 2026 12:31:01 +0000 Subject: [PATCH] docs(skills): add ignition-create-env skill Add the Agent Skill for writing a valid TrainingEnv, plus a 1D LineWorld example and tests that exercise validation, terminated vs truncated, and a declared-budget qtable run on three seeds. Co-authored-by: Salim --- examples/skill-create-env.test.ts | 82 ++++++++ examples/skill-create-env.ts | 191 ++++++++++++++++++ skills/ignition-create-env/SKILL.md | 133 ++++++++++++ .../ignition-create-env/frontmatter.test.ts | 33 +++ .../references/env-contract.md | 108 ++++++++++ 5 files changed, 547 insertions(+) create mode 100644 examples/skill-create-env.test.ts create mode 100644 examples/skill-create-env.ts create mode 100644 skills/ignition-create-env/SKILL.md create mode 100644 skills/ignition-create-env/frontmatter.test.ts create mode 100644 skills/ignition-create-env/references/env-contract.md diff --git a/examples/skill-create-env.test.ts b/examples/skill-create-env.test.ts new file mode 100644 index 0000000..dd72fed --- /dev/null +++ b/examples/skill-create-env.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it } from 'vitest'; +import { IgnitionEnv, validateTrainingEnv } from '@ignitionai/core'; +import { CartPoleEnv, GridWorldEnv, MountainCarEnv } from '@ignitionai/environments'; +import { + TRAINING_BUDGET_STEPS, + TRAINING_SEEDS, + createInvalidTrainingEnv, + LineWorldEnv, + runLineWorldTraining, + scriptedStep, + spaceKind, +} from './skill-create-env'; + +/** + * Budget and seeds declared before execution: + * - budget = TRAINING_BUDGET_STEPS (200 env steps / seed) + * - seeds = TRAINING_SEEDS (7, 11, 19) + * Measurements are printed; this file does not assert convergence. + */ +describe('skill-create-env LineWorld', () => { + it('passes TrainingEnv validation and wraps in IgnitionEnv', () => { + const world = new LineWorldEnv(); + expect(() => validateTrainingEnv(world)).not.toThrow(); + expect(() => new IgnitionEnv(world)).not.toThrow(); + expect(spaceKind(world.actionSpace())).toBe('discrete n=2'); + expect(spaceKind(world.observationSpace())).toBe('box shape=1'); + expect(world.observe()).toEqual([0]); + }); + + it('rejects an invalid env with the real validation error', () => { + const invalid = createInvalidTrainingEnv(); + expect(() => validateTrainingEnv(invalid)).toThrowError( + '[IgnitionAI] TrainingEnv must implement done() as a function', + ); + expect( + () => new IgnitionEnv(invalid as never), + ).toThrowError('[IgnitionAI] TrainingEnv must implement done() as a function'); + }); + + it('reports terminated when the 1D goal is reached', async () => { + const world = new LineWorldEnv(3, 20); + world.position = 1; + const result = await scriptedStep(world); + expect(result).toMatchObject({ + observation: [1], + reward: 1, + terminated: true, + truncated: false, + }); + expect(world.position).toBe(0); + }); + + it('reports truncated when the step limit hits before the goal', async () => { + const world = new LineWorldEnv(5, 1); + const result = await scriptedStep(world); + expect(result.terminated).toBe(false); + expect(result.truncated).toBe(true); + expect(result.reward).toBe(-0.01); + expect(world.position).toBe(0); + }); + + it('runs the declared qtable budget on three seeds and records raw returns', async () => { + expect(TRAINING_SEEDS).toHaveLength(3); + const measurements = []; + for (const seed of TRAINING_SEEDS) { + const measurement = await runLineWorldTraining(seed, TRAINING_BUDGET_STEPS); + measurements.push(measurement); + expect(measurement.completedSteps).toBe(TRAINING_BUDGET_STEPS); + expect(measurement.terminatedEpisodes + measurement.truncatedEpisodes).toBe( + measurement.episodeReturns.length, + ); + } + // Raw measurements (failures included). Not a convergence claim. + console.log(JSON.stringify({ budgetSteps: TRAINING_BUDGET_STEPS, measurements }, null, 2)); + }); + + it('reference envs still satisfy TrainingEnv validation', () => { + expect(() => validateTrainingEnv(new GridWorldEnv())).not.toThrow(); + expect(() => validateTrainingEnv(new CartPoleEnv())).not.toThrow(); + expect(() => validateTrainingEnv(new MountainCarEnv())).not.toThrow(); + }); +}); diff --git a/examples/skill-create-env.ts b/examples/skill-create-env.ts new file mode 100644 index 0000000..2000653 --- /dev/null +++ b/examples/skill-create-env.ts @@ -0,0 +1,191 @@ +import { + IgnitionEnv, + type ActionSpace, + type BoxSpace, + type DiscreteSpace, + type MultiDiscreteSpace, + type ObservationSpace, + type StepResult, + type TrainingEnv, +} from '@ignitionai/core'; +import { IgnitionEnvTFJS } from '@ignitionai/backend-tfjs'; + +/** + * Declared before any training run. + * + * Budget: 200 environment steps per seed (manual `step()`, not the async loop). + * Seeds: 7, 11, 19. Algorithm: qtable. No convergence claim without measurement. + */ +export const TRAINING_BUDGET_STEPS = 200; +export const TRAINING_SEEDS = [7, 11, 19] as const; +export const TRAINING_OVERRIDES = { + lr: 0.3, + epsilon: 1, + epsilonDecay: 0.99, + minEpsilon: 0.05, + stateBins: 8, + stateLow: [0], + stateHigh: [1], +} as const; + +/** 1D line: start at 0, goal at `length - 1`, discrete left/right actions. */ +export class LineWorldEnv implements TrainingEnv { + actions = ['left', 'right']; + position = 0; + stepCount = 0; + readonly length: number; + readonly maxSteps: number; + + constructor(length = 5, maxSteps = 12) { + this.length = length; + this.maxSteps = maxSteps; + } + + observe(): number[] { + return [this.position / (this.length - 1)]; + } + + step(action: number | number[]): void { + const a = typeof action === 'number' ? action : action[0]; + if (a === 1) { + this.position = Math.min(this.length - 1, this.position + 1); + } else { + this.position = Math.max(0, this.position - 1); + } + this.stepCount += 1; + } + + reward(): number { + if (this.terminated()) return 1; + return -0.01; + } + + done(): boolean { + return this.terminated() || this.truncated(); + } + + terminated(): boolean { + return this.position === this.length - 1; + } + + truncated(): boolean { + return !this.terminated() && this.stepCount >= this.maxSteps; + } + + reset(): void { + this.position = 0; + this.stepCount = 0; + } + + actionSpace(): DiscreteSpace { + return { type: 'discrete', n: this.actions.length }; + } + + observationSpace(): BoxSpace { + return { type: 'box', low: [0], high: [1], shape: [1] }; + } +} + +/** Missing `done()` — rejected by `validateTrainingEnv`. */ +export function createInvalidTrainingEnv(): unknown { + return { + actions: ['left', 'right'], + observe(): number[] { + return [0]; + }, + step(): void {}, + reward(): number { + return 0; + }, + reset(): void {}, + }; +} + +export function spaceKind(space: ActionSpace | ObservationSpace): string { + switch (space.type) { + case 'discrete': + return `discrete n=${(space as DiscreteSpace).n}`; + case 'box': + return `box shape=${(space as BoxSpace).shape.join('x')}`; + case 'multidiscrete': + return `multidiscrete nvec=${(space as MultiDiscreteSpace).nvec.join(',')}`; + default: { + const unexpected: never = space; + throw new Error(`unhandled space: ${JSON.stringify(unexpected)}`); + } + } +} + +function mulberry32(seed: number): () => number { + let state = seed >>> 0; + return () => { + state += 0x6d2b79f5; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +export interface TrainingRunMeasurement { + seed: number; + budgetSteps: number; + completedSteps: number; + terminatedEpisodes: number; + truncatedEpisodes: number; + episodeReturns: number[]; +} + +export async function runLineWorldTraining( + seed: number, + budgetSteps: number = TRAINING_BUDGET_STEPS, +): Promise { + const rng = mulberry32(seed); + const originalRandom = Math.random; + Math.random = rng; + const world = new LineWorldEnv(); + const runner = new IgnitionEnvTFJS(world); + try { + runner.train('qtable', { ...TRAINING_OVERRIDES }); + runner.stop(); + const episodeReturns: number[] = []; + let episodeReturn = 0; + let terminatedEpisodes = 0; + let truncatedEpisodes = 0; + let completedSteps = 0; + for (let i = 0; i < budgetSteps; i++) { + const result: StepResult = await runner.step(); + completedSteps += 1; + episodeReturn += result.reward; + if (result.terminated || result.truncated) { + if (result.terminated) terminatedEpisodes += 1; + if (result.truncated) truncatedEpisodes += 1; + episodeReturns.push(episodeReturn); + episodeReturn = 0; + } + } + return { + seed, + budgetSteps, + completedSteps, + terminatedEpisodes, + truncatedEpisodes, + episodeReturns, + }; + } finally { + runner.stop(); + runner.agent?.dispose?.(); + Math.random = originalRandom; + } +} + +/** Scripted always-right agent for episode-end semantics (real `IgnitionEnv.step`). */ +export async function scriptedStep(world: TrainingEnv): Promise { + const runner = new IgnitionEnv(world); + runner.agent = { + getAction: async () => 1, + remember() {}, + train: async () => {}, + }; + return runner.step(); +} diff --git a/skills/ignition-create-env/SKILL.md b/skills/ignition-create-env/SKILL.md new file mode 100644 index 0000000..7ad5a4b --- /dev/null +++ b/skills/ignition-create-env/SKILL.md @@ -0,0 +1,133 @@ +--- +name: ignition-create-env +description: Use when writing, validating, or wrapping a custom IgnitionRL TrainingEnv (discrete, box, or multidiscrete observations/actions), distinguishing terminated vs truncated, calling validateTrainingEnv, or constructing IgnitionEnv / IgnitionEnvTFJS. Teaches a valid 1D env, rejection of invalid envs, and a short measured training run. +--- + +# ignition-create-env + +Teach an agent how to write a custom environment that matches the framework +contract on `dev` at SHA `343a76952f9dcd6594674c3526ee03ee45b4d93e`. + +Executable example: `examples/skill-create-env.ts` (tests in +`examples/skill-create-env.test.ts`). Full signatures: +[references/env-contract.md](references/env-contract.md). + +## When to use + +- The user wants a **custom** env (game, sim, 1D toy), not only CartPole. +- Validation throws `[IgnitionAI] TrainingEnv must implement …`. +- Episode ends mix **goal/failure** with a **step limit**. +- You need to wrap a world in `IgnitionEnv` / `IgnitionEnvTFJS` and call `train()`. + +Do not use this skill for ONNX export, checkpoint I/O, or reward-shaping recipes. + +## Contract (minimum) + +Implement `TrainingEnv` (`packages/core/src/types.ts:95-112`): + +```ts +import type { TrainingEnv } from '@ignitionai/core'; + +class LineWorldEnv implements TrainingEnv { + actions = ['left', 'right']; // or a positive number + observe(): number[] { /* vector */ } + step(action: number | number[]): void { /* mutate world */ } + reward(): number { /* scalar */ } + done(): boolean { return this.terminated() || this.truncated(); } + terminated(): boolean { /* goal / failure */ } + truncated(): boolean { /* time limit, and not terminated */ } + reset(): void { /* start of episode */ } +} +``` + +`observe()` is the observation **vector** (typically a `BoxSpace` of `shape [k]`). +`actions` is the discrete action count or names (`DiscreteSpace.n`). +Space **interfaces** (`DiscreteSpace` `:5-8`, `BoxSpace` `:11-16`, +`MultiDiscreteSpace` `:18-22`) are types only — the runner never reads a `space` +field. See the reference table in `references/env-contract.md`. + +## Validate, then wrap + +```ts +import { IgnitionEnv, validateTrainingEnv } from '@ignitionai/core'; +import { IgnitionEnvTFJS } from '@ignitionai/backend-tfjs'; + +validateTrainingEnv(world); // packages/core/src/env-validation.ts:9-40 +const inspect = new IgnitionEnv(world); // constructor validates: ignition-env.ts:27-31 +inspect; // no factories — train() throws Unknown algorithm + +const runner = new IgnitionEnvTFJS(world); // packages/backend-tfjs/src/ignition-env-tfjs.ts:26-32 +runner.train('qtable', { stateBins: 8, stateLow: [0], stateHigh: [1] }); +runner.stop(); // halt the async loop; drive with await runner.step() +``` + +Invalid worlds must be rejected with the **real** message, for example missing +`done()`: + +`[IgnitionAI] TrainingEnv must implement done() as a function` + +(`packages/core/src/env-validation.ts:3-6`, `:16-20`). + +## `terminated` vs `truncated` + +Comments on `Experience` (`packages/core/src/types.ts:34-37`) and `StepResult` +(`:43-49`): + +| Flag | Meaning | Typical cause | +|---|---|---| +| `terminated` | Episode hit a **terminal** condition | Goal reached, pole fell, crash | +| `truncated` | Episode hit an **external** limit | `maxSteps`, wall-clock | + +`IgnitionEnv.performStep` (`packages/core/src/ignition-env.ts:96-108`): + +1. `truncated = env.truncated?.() ?? false` +2. `terminated = env.terminated?.() ?? (env.done() && !truncated)` +3. If either is true, `reset()` runs **after** `remember()`, and `step()` still + returns the **last** observation. + +Prefer implementing both optional methods so a time-limit end is not treated as +a terminal success/failure. `done()` should stay true when either flag is true +(legacy path). + +## Reference envs + +Copy structure, not their episode-end mixing: + +- `GridWorldEnv` — `packages/environments/src/gridworld.ts:3` +- `CartPoleEnv` — `packages/environments/src/cartpole.ts:23` +- `MountainCarEnv` — `packages/environments/src/mountaincar.ts:12` + +Each uses `done()` for **both** success/failure and a step cap. New code should +split flags (see LineWorld in the example). + +## Short training (declare budget first) + +Do not claim the policy solved the env without numbers. + +Declared in `examples/skill-create-env.ts` **before** any run: + +- Budget: `200` env steps per seed (`TRAINING_BUDGET_STEPS`) +- Seeds: `7`, `11`, `19` +- Algorithm: `qtable` (tabular; no neural net) +- Drive with `await runner.step()` after `train()` + `stop()` so the test stays + under 60s CPU + +Record `completedSteps`, `terminatedEpisodes`, `truncatedEpisodes`, and +`episodeReturns`. Print raw JSON. Failures stay in the log. + +## Common mistakes + +- Forgetting `done()` or `reset()` — validation throws at construct time. +- Empty `actions` / `actions: 0` — “must have at least one action”. +- Using core `IgnitionEnv.train()` without TF.js factories. +- Putting the step cap only in `done()` and omitting `truncated()`. +- Asserting `toThrow(/done/)` instead of the exact `[IgnitionAI] …` string. +- Mutating package code to “fix” spaces or reference envs — report the gap. + +## Checklist + +1. Class implements `TrainingEnv` (and optional `terminated` / `truncated`). +2. `validateTrainingEnv(world)` succeeds; an invalid object throws the real error. +3. `new IgnitionEnvTFJS(world)` + `train('qtable'| 'dqn' | 'ppo')`. +4. `StepResult.terminated` / `.truncated` match the intended end condition. +5. Budget and ≥3 seeds declared, then measured. diff --git a/skills/ignition-create-env/frontmatter.test.ts b/skills/ignition-create-env/frontmatter.test.ts new file mode 100644 index 0000000..f29e425 --- /dev/null +++ b/skills/ignition-create-env/frontmatter.test.ts @@ -0,0 +1,33 @@ +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'vitest'; + +const skillDir = dirname(fileURLToPath(import.meta.url)); +const folderName = 'ignition-create-env'; + +function parseSkill(): { name: string; description: string; bodyLines: number } { + const text = readFileSync(join(skillDir, 'SKILL.md'), 'utf8'); + const match = text.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/); + if (!match) throw new Error('SKILL.md must start with YAML frontmatter'); + const frontmatter = match[1]; + const body = match[2]; + const name = frontmatter.match(/^name:\s*(.+)$/m)?.[1]?.trim(); + const description = frontmatter.match(/^description:\s*(.+)$/m)?.[1]?.trim(); + if (!name || !description) throw new Error('frontmatter requires name and description'); + return { + name, + description, + bodyLines: body.replace(/\n$/, '').split('\n').length, + }; +} + +describe('ignition-create-env frontmatter', () => { + it('matches the folder name, caps description at 1024 chars, and body at 500 lines', () => { + const skill = parseSkill(); + expect(skill.name).toBe(folderName); + expect(skill.description.length).toBeGreaterThan(0); + expect(skill.description.length).toBeLessThanOrEqual(1024); + expect(skill.bodyLines).toBeLessThanOrEqual(500); + }); +}); diff --git a/skills/ignition-create-env/references/env-contract.md b/skills/ignition-create-env/references/env-contract.md new file mode 100644 index 0000000..569c9b5 --- /dev/null +++ b/skills/ignition-create-env/references/env-contract.md @@ -0,0 +1,108 @@ +# TrainingEnv contract (dev SHA 343a769) + +Signatures below are from this checkout. Do not copy APIs from unmerged PRs. + +## Spaces (`packages/core/src/types.ts`) + +These types describe geometry. `TrainingEnv` does **not** attach them; the runner +reads `actions` and `observe()`. + +- `DiscreteSpace` — `packages/core/src/types.ts:5-8` (`type: 'discrete'`, `n`) +- `BoxSpace` — `packages/core/src/types.ts:11-16` (`type: 'box'`, `low`, `high`, `shape`) +- `MultiDiscreteSpace` — `packages/core/src/types.ts:18-22` (`type: 'multidiscrete'`, `nvec`) +- `ActionSpace` / `ObservationSpace` — `packages/core/src/types.ts:24-25` + +Map a custom env: + +| World | ActionSpace | ObservationSpace | +|---|---|---| +| 1D line, left/right | `{ type: 'discrete', n: 2 }` | `{ type: 'box', low: [0], high: [1], shape: [1] }` | +| GridWorld 4-move | discrete `n=4` (`actions` length) | box shape `[4]` (normalized row/col + target) | +| CartPole left/right | discrete `n=2` | box shape `[4]` (x, xDot, theta, thetaDot) | +| MountainCar 3-push | discrete `n=3` | box shape `[2]` (position, velocity) | + +## `TrainingEnv` (`packages/core/src/types.ts:95-112`) + +Required: + +- `actions: string[] | number` +- `observe(): number[]` +- `step(action: number | number[]): void` +- `reward(): number` +- `done(): boolean` +- `reset(): void` + +Optional: + +- `terminated?(): boolean` — terminal condition (goal, failure) +- `truncated?(): boolean` — external limit (time / step cap); default false + +`InferenceEnv` (`packages/core/src/types.ts:117-122`) is `observe` + `step` only. + +## `StepResult` and flags (`packages/core/src/types.ts:34-49`) + +`Experience` and `StepResult` both carry: + +- `terminated` — episode ended because of a terminal condition +- `truncated` — episode ended because of a time/step limit + +## How `IgnitionEnv` computes flags (`packages/core/src/ignition-env.ts:87-108`) + +``` +truncated = env.truncated?.() ?? false +terminated = env.terminated?.() ?? (env.done() && !truncated) +``` + +If `terminated || truncated`, the runner calls `env.reset()` **after** recording +the last observation. `step()` returns that last observation, not the post-reset +one (`packages/core/src/ignition-env.ts:73-75`, `:102-108`). + +`new IgnitionEnv(env)` validates then snapshots `env.observe()` (`packages/core/src/ignition-env.ts:27-31`). + +`train(algorithm?, overrides?)` needs a factory (`packages/core/src/ignition-env.ts:41-71`). +Bare `@ignitionai/core` `IgnitionEnv` has none; use `IgnitionEnvTFJS` +(`packages/backend-tfjs/src/ignition-env-tfjs.ts:26-32`) whose factories include +`qtable` (`packages/backend-tfjs/src/ignition-env-tfjs.ts:8-13`). + +## Validation (`packages/core/src/env-validation.ts`) + +`validateTrainingEnv` (`packages/core/src/env-validation.ts:9-40`) requires +`observe`, `step`, `reward`, `done`, `reset` as functions, optional +`terminated`/`truncated` as functions if present, and `actions` as a non-empty +`string[]` or a positive number. + +`validateInferenceEnv` (`packages/core/src/env-validation.ts:42-50`) requires +`observe` and `step`. + +Real errors (assert them, do not match loosely): + +- not an object: `[IgnitionAI] Environment must be an object implementing TrainingEnv` +- missing method: `[IgnitionAI] TrainingEnv must implement () as a function` +- missing actions: `[IgnitionAI] TrainingEnv must have an actions property (string[] or number)` +- empty / non-positive actions: `[IgnitionAI] TrainingEnv.actions must have at least one action` +- wrong actions type: `[IgnitionAI] TrainingEnv.actions must be a string[] or a positive number` + +## Reference environments + +- `GridWorldEnv` — `packages/environments/src/gridworld.ts:3-59` +- `CartPoleEnv` — `packages/environments/src/cartpole.ts:23-82` +- `MountainCarEnv` — `packages/environments/src/mountaincar.ts:12-61` + +All three implement `done()` only. Their `done()` mixes success/failure with a +step cap (`gridworld.ts:48-51`, `cartpole.ts:71-77`, `mountaincar.ts:47-49`). +New envs should split `terminated()` and `truncated()` as in +`examples/skill-create-env.ts`. + +## Q-learning and truncation + +`QTableAgent.train` (`packages/backend-tfjs/src/agents/qtable.ts:147-152`) uses +`terminated` as the Bellman `done` flag. A **truncated** (non-terminal) +transition still bootstraps from the successor. That matches time-limit +semantics: the world did not end, the episode was cut. + +## Known gaps (report, do not patch packages) + +1. Space types are exported from `packages/core/src/index.ts:15-19` but unused by + `TrainingEnv` / `IgnitionEnv`. +2. Reference envs do not implement `terminated()` / `truncated()`; their `done()` + mixes goal/failure with a step cap.