Skip to content
anon160Public

About

The automated immune system for drifting data formats. QuickJS WebAssembly sandboxing, and GitOps review.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Rez (rezjs)

License: Apache 2.0 npm version Node.js

Multi-format data ingestion, WebAssembly sandboxing, and GitOps drift healing for TypeScript.
Rez parses incoming JSON, CSV, TSV, XML, YAML, key-value/logfmt, and raw text payloads, validates them against Zod contracts, executes approved transform(raw) patches inside a QuickJS WebAssembly isolate, and—when unseen drift occurs—synthesizes a repair patch with AI (optionally guided by vendor docs/changelogs) and opens a Git review branch / Pull Request.

Git is the source of truth. Approved patches are stored as versioned JavaScript files in patches/ (or registered in memory for edge/serverless runtimes) and reviewed via standard GitHub Pull Requests.


Architecture

flowchart TD
    A["Incoming Payload (JSON / CSV / TSV / XML / YAML / KV / Text)"] --> B["Parse & Detect Format (src/parsers.ts)"]
    B --> C{"Approved Patch in Catalog?"}
    C -- "Yes" --> D["Execute transform(raw) in QuickJS WASM"]
    D -- "Validates against Zod" --> E["Return Normalized Data (SUCCESS)"]
    C -- "No" --> F{"Matches Zod Contract?"}
    F -- "Yes" --> E
    F -- "No (Drift)" --> G["Deduplicate In-Flight / Check Open PRs"]
    G --> H["Fetch Optional Vendor Docs (docsUrl / resolveDocs)"]
    H --> I["AI Synthesizes ES2020 transform(raw) Patch"]
    I --> J["Verify Patch in QuickJS WASM + Zod"]
    J -- "Fails" --> K["Quarantine (HEALING_FAILED)"]
    J -- "Passes" --> L["Commit Branch & Open PR (GitHub REST / Local Git)"]
    L --> M["Quarantine (PENDING_GIT_REVIEW)"]
Loading
  1. Multi-Format Parsing (src/parsers.ts): Normalizes string or object/array inputs across json, csv, tsv (papaparse), xml (fast-xml-parser), yaml (yaml), kv (logfmt/.env), and raw text, with auto format detection.
  2. Contract Validation (src/contracts.ts): Validates parsed data against user-defined Zod schemas or dynamic field specification dictionaries ({ field: "str" | "int" | "float" | "bool" | "list" | "dict" }).
  3. Fast-Path Patch Execution (src/sandbox.ts, src/catalog.ts): If an active patch exists for a source, it runs transform(raw) inside an in-process QuickJS WebAssembly (quickjs-emscripten) isolate with an 8 MB memory limit and configurable execution deadline (default 2000ms), then validates the output against the target contract.
  4. Drift Deduplication (src/core.ts): Coalesces concurrent healing attempts for the same source::schema, caches pending review branches, and checks GitHub for an already-open review PR before invoking an LLM.
  5. Vendor Docs Context (src/docs-fetcher.ts): When drift occurs, optionally fetches one or more docsUrl endpoints (converting HTML to Markdown via node-html-markdown) or calls a custom resolveDocs hook, truncating to 12,000 characters by default and failing gracefully on network errors.
  6. AI Synthesis & Verification (src/ai-engine.ts): Uses the Vercel ai SDK (generateObject) across supported providers to generate function transform(raw) { ... }, a Conventional Commit message, and a Markdown PR summary, then verifies the generated function in the QuickJS WASM sandbox before accepting it.
  7. GitOps Review (src/git-ops.ts, src/git-review.ts): Commits the verified patch to a review branch (rez-patch/...) via the GitHub REST API (@octokit/rest) or local Git (simple-git) and opens a Pull Request when credentials are configured.

Installation

npm install rezjs zod

Requirements:

  • Node.js >= 20.0.0
  • Either a local Git repository (git init) or remote GitHub credentials (GITHUB_TOKEN + GITHUB_REPOSITORY).

Quick Start

1. Configure rez.config.ts (Optional)

import { defineConfig } from "rezjs";
import { z } from "zod";

export default defineConfig({
  model: {
    provider: "google", // "google" | "openai" | "anthropic" | "openrouter" | "deepseek" | "groq" | "ollama"
  },
  git: {
    baseBranch: "main",
    patchDir: "patches",
    autoPush: false,
    createPullRequest: true,
  },
  contracts: {
    LogisticsShipment: z.object({
      container_id: z.string(),
      carrier_name: z.string(),
      status: z.enum(["IN_TRANSIT", "DELIVERED", "DELAYED", "EXCEPTION"]),
      weight_kg: z.number().positive(),
    }),
  },
});

2. Ingest JSON, CSV, XML, YAML, Logfmt, or Raw Text

import { Rez } from "rezjs";
import { z } from "zod";

const ShipmentSchema = z.object({
  container_id: z.string(),
  weight_kg: z.number().positive(),
});

const rez = new Rez({
  contract: ShipmentSchema,
  docsUrl: "https://vendor.example.com/api-changelog",
});

const result = await rez.ingest({
  source: "vendor_csv_feed",
  format: "csv", // "auto" | "json" | "csv" | "tsv" | "xml" | "yaml" | "kv" | "text"
  payload: `cntr_no,gross_lbs\nMSKU100,2204.62`,
  // Optional custom hook (e.g. search API or internal wiki lookup):
  resolveDocs: async ({ source, validationError }) =>
    `Docs for ${source}: ${validationError}`,
});

if (result.isSuccess()) {
  console.log("Normalized:", result.data);
} else if (result.isQuarantined()) {
  console.warn("Quarantined:", result.status, result.reviewBranch, result.prUrl);
}

3. Pure Web-Standards Edge Entrypoint (rezjs/edge)

rezjs/edge exports the core engine without node:fs, node:path, or node:child_process, using MemoryPatchCatalog and GitHub REST GitOps:

import { Rez } from "rezjs/edge";
import { z } from "zod";

const ShipmentContract = z.object({
  container_id: z.string(),
  weight_kg: z.number(),
});

const rez = new Rez({
  contract: ShipmentContract,
  gitToken: env.GITHUB_TOKEN,
  gitRepository: env.GITHUB_REPOSITORY, // "owner/repo"
  model: {
    provider: "google",
    apiKey: env.GEMINI_API_KEY,
  },
});

// Pre-register an approved patch in memory if needed
rez.registerPatch("vendor_feed", `
  function transform(raw) {
    return { container_id: String(raw.cntr), weight_kg: Number(raw.kg) };
  }
`);

Supported Input Formats

Format format value Underlying Parser Notes
JSON "json" JSON.parse Objects, arrays, or JSON strings
CSV / TSV "csv" / "tsv" papaparse Header-keyed array of row objects
XML "xml" fast-xml-parser Attributes under @attributes, text under #text, repeated tags as arrays
YAML "yaml" yaml Full YAML document parsing
Key-Value "kv" Built-in logfmt parser key=value / key="quoted value" with scalar coercion
Raw Text "text" Passthrough Passes raw string directly to transform(raw)
Auto-Detect "auto" (default) Heuristic detector Infers format from string payloads; falls back to "text"

WebAssembly Sandbox (src/sandbox.ts)

Patches execute inside a quickjs-emscripten context rather than eval() or Node vm:

  • No Node/OS globals: require(), import, process, filesystem, and network APIs are unavailable inside the isolate.
  • Memory limit: 8 MB (1024 * 1024 * 8 bytes).
  • Execution timeout: Interrupt handler terminates infinite loops after the configured deadline (default 2000ms).
  • Contract check: Serialized return values are validated against the target Zod schema or field specs before leaving executePatch().

Supported AI Providers (src/ai-engine.ts)

Resolved via environment variables or explicit model config (provider, name, apiKey, baseURL):

  • Google (google — GEMINI_API_KEY / GOOGLE_GENERATIVE_AI_API_KEY / GOOGLE_API_KEY)
  • OpenAI (openai — OPENAI_API_KEY)
  • Anthropic (anthropic — ANTHROPIC_API_KEY)
  • OpenRouter (openrouter — OPENROUTER_API_KEY)
  • DeepSeek (deepseek — DEEPSEEK_API_KEY)
  • Groq (groq — GROQ_API_KEY)
  • Ollama (ollama — OLLAMA_BASE_URL, defaults to http://localhost:11434/v1)

Optional GitOps environment variables:

  • GITHUB_TOKEN
  • GITHUB_REPOSITORY ("owner/repo")

Patch Catalogs & Rollback

  • FilePatchCatalog (Node default): Stores versioned patch files in patches/ and supports listPatchVersions() and rollbackPatch().
  • MemoryPatchCatalog (Edge default): Stores versioned patches in memory with registerPatch(), listPatchVersions(), and rollbackPatch().

Development & Testing

Build TypeScript definitions and compiled output:

npm run build

Run the unit test suite (Vitest):

npm test

Test coverage across the 8 Vitest suites (tests/*.test.ts):

  • parsers.test.ts: CSV/TSV, XML, YAML, KV, format auto-detection, and multi-format Rez.ingest() fast-path transforms
  • docs-fetcher.test.ts: HTML-to-Markdown conversion, Markdown passthrough, resolveDocs, error fallback, and truncation (mocked fetch)
  • sandbox.test.ts: QuickJS execution, error isolation, deadline interruption, and Zod validation
  • contracts.test.ts: Dynamic schema creation, validation errors, inference, and Zod field extraction
  • catalog.test.ts: In-memory and file-backed patch versioning and rollback
  • git-review.test.ts: Local simple-git branching/commits and GitHub REST API branch/PR operations
  • ai-engine.test.ts: Provider/model resolution, PatchResultSchema, missing-key handling, and explicit edge apiKey config
  • sdk.test.ts: End-to-end Rez SDK lifecycle, defineConfig, fast-path catalog execution, drift quarantine, rollback, and rezjs/edge imports

License

Apache 2.0 © Rez Contributors.

About

The automated immune system for drifting data formats. QuickJS WebAssembly sandboxing, and GitOps review.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages