Skip to content

You are currently viewing documentation for0.1.0-alpha.2

Saved documentation for 0.1.0-alpha.2 (npm) / 0.1.0a1 (PyPI). Interactive tools use the current release. View latest documentation.

Quickstart

Install from the registries

Node 22+ and Python 3.11+ are supported. Install the pre-alpha packages with npm install agindow@0.1.0-alpha.2 or pip install agindow==0.1.0a1. The embedded SDK needs no separate AGINDOW credential; your application still supplies any credentials its vendor API requires. Select and configure a detector after installation. Otherwise the statistical guest is default; configure windows to detect. Statistical detection requires baseline and current-traffic data windows. See Modes for the separate detector and mode setup requirements.

Detect a labelled simulated change

After npm install agindow@0.1.0-alpha.2, save the TypeScript sample below as detect.mts and run node --experimental-strip-types detect.mts. Prerequisites: Node.js 22+, a clean directory, and network access only to install the package. The sample makes no vendor call, so it needs neither vendor credentials nor an AGINDOW credential, a monorepo, the Rust/WASM toolchain or paid services. It selects an explicit statistical window, awaits readiness, and reports a real Unit finding for a labelled numeric magnitude shift (baseline value 1 → current value 100). An otherwise identical unchanged current window, a default engine with no selection, and insufficient windows report no detection. For Python, install the pinned Python package, save the Python tab as detect.py, and run python detect.py. Its boolean readiness and finding fields follow the Python API. Both tabs assert the changed, unchanged, unconfigured and insufficient-window cases. The printed JSON is the stable finding summary; latencyUs and host timing vary. This is observe-mode detection evidence, not an applied repair, not a bypass event, and not evidence of production accuracy.

import { createAgindow } from 'agindow';
import type { Event, StatisticalSelection } from 'agindow';

/** Labelled simulated break: numeric magnitude shift (1 → 100). Not a vendor migration story. */
const documents = (value: number): string[] =>
  Array.from({ length: 128 }, () => JSON.stringify({ value }));

function selectionFor(live: number): StatisticalSelection {
  return {
    tenant: 'demo',
    connection: 'local',
    vendor: 'synthetic',
    operation: 'demo.detect',
    segment: 'default',
    fields: [{
      side: 'request',
      path: '/value',
      baseline: documents(1),
      live: documents(live),
      enumeration: true,
    }],
  };
}

async function observe(label: string, selection?: StatisticalSelection, bodyValue = 100): Promise<readonly Event[]> {
  const sdk = createAgindow(selection === undefined
    ? { mode: 'observe' }
    : { mode: 'observe', selection });
  await sdk.ready;
  const body = { value: bodyValue };
  const result = sdk.guard((input: { value: number }) => input, {
    tool: 'demo.detect',
    operation: 'read',
  })(body);
  if (result !== body) throw Error(`${label}: observe mutated the result (not an applied repair path)`);
  if (sdk.recent().some((event: Event) => event.type === 'repair')) {
    throw Error(`${label}: unexpected repair event`);
  }
  if (sdk.recent().some((event: Event) => event.type === 'bypass')) {
    throw Error(`${label}: unexpected bypass; this sample is detection, not an availability fixture`);
  }
  return sdk.recent();
}

const changed = await observe('changed', selectionFor(100), 100);
const drift = changed.find((event: Event) => event.type === 'drift');
if (!drift?.verdict
  || drift.verdict.bypassed
  || drift.verdict.halt
  || drift.verdict.repair
  || drift.verdict.findings !== 1
  || drift.verdict.detectors !== 5
  || drift.verdict.class !== 'semantic'
  || !drift.verdict.eligibleDetectors?.includes('Unit')) {
  throw Error('expected a real Unit finding for the labelled numeric magnitude shift');
}

const unchanged = await observe('unchanged', selectionFor(1), 1);
if (unchanged.some((event: Event) => event.type === 'drift')) {
  throw Error('unchanged live window reported drift');
}

const withoutDetector = await observe('default');
if (withoutDetector.some((event: Event) => event.type === 'drift')) {
  throw Error('default engine reported detection without an explicit selection');
}

const insufficient: StatisticalSelection = {
  tenant: 'demo',
  connection: 'local',
  vendor: 'synthetic',
  operation: 'demo.detect',
  segment: 'default',
  fields: [{
    side: 'request',
    path: '/value',
    baseline: Array.from({ length: 4 }, () => '{"value":1}'),
    live: Array.from({ length: 4 }, () => '{"value":100}'),
    enumeration: true,
  }],
};
const thin = await observe('insufficient', insufficient, 100);
if (thin.some((event: Event) => event.type === 'drift')) {
  throw Error('insufficient windows reported a successful detection');
}

const observed = {
  labelledChange: 'numeric magnitude shift',
  detector: drift.verdict.eligibleDetectors.find(name => name === 'Unit'),
  event: drift.type,
  findings: drift.verdict.findings,
  detectors: drift.verdict.detectors,
  eligibleDetectors: drift.verdict.eligibleDetectors,
  class: drift.verdict.class,
  bypassed: Boolean(drift.verdict.bypassed),
  halt: Boolean(drift.verdict.halt),
  repairApplied: Boolean(drift.verdict.repair),
  resultUnchanged: true, // observe() checked reference identity above.
};
console.log(JSON.stringify(observed, null, 2));
console.log('Variable per run (not part of the stable finding above): latencyUs and host timing.');
import json
from agindow import Agindow, Event

# Labelled local fixture: numeric magnitude shift, not live vendor traffic.
def selection_for(value: int, count: int = 128) -> dict[str, object]:
    return {
        "tenant": "demo", "connection": "local", "vendor": "synthetic",
        "operation": "demo.detect", "segment": "default",
        "fields": [{"side": "request", "path": "/value", "enumeration": True,
                    "baseline": [json.dumps({"value": 1}) for _ in range(count)],
                    "live": [json.dumps({"value": value}) for _ in range(count)]}],
    }


def observe(selection: dict[str, object] | None, value: int = 100) -> tuple[Event, ...]:
    sdk = Agindow(mode="observe", selection=selection)
    try:
        assert sdk.ready, sdk.load_error
        payload = {"value": value}

        @sdk.guard(tool="demo.detect", operation="read")
        def read(body: dict[str, int]) -> dict[str, int]:
            return body

        assert read(payload) is payload
        events = sdk.recent()
        assert not any(event.type in ("bypass", "repair", "blocked") for event in events)
        return events
    finally:
        sdk.close()


changed = observe(selection_for(100))
drift = next(event for event in changed if event.type == "drift")
verdict = drift.verdict
assert verdict is not None
assert verdict.findings == 1 and verdict.detectors == 5
assert verdict.drift_class == "semantic"
assert not verdict.bypassed and not verdict.halt and verdict.repair is None
assert not any(event.type == "drift" for event in observe(selection_for(1), 1))
assert not any(event.type == "drift" for event in observe(None))
assert not any(event.type == "drift" for event in observe(selection_for(100, 4)))
print(json.dumps({"event": drift.type, "findings": verdict.findings,
                  "detectors": verdict.detectors, "class": verdict.drift_class,
                  "bypassed": verdict.bypassed, "halt": verdict.halt,
                  "repairApplied": verdict.repair is not None,
                  "resultUnchanged": True}, indent=2))

Expected result

The TypeScript summary below is asserted by the publication fixture. Python prints the same finding count, class and safety flags; its Verdict does not expose the detector-name arrays or latency fields. It reports one configured Unit finding for the changed window while the sample also asserts that unchanged, default-engine and insufficient-window controls do not report successful detection. Timing fields are deliberately excluded.

json
{
  "labelledChange": "numeric magnitude shift",
  "detector": "Unit",
  "event": "drift",
  "findings": 1,
  "detectors": 5,
  "eligibleDetectors": [
    "Unit"
  ],
  "class": "semantic",
  "bypassed": false,
  "halt": false,
  "repairApplied": false,
  "resultUnchanged": true
}

Availability and identity fixtures

The separately labelled ts/py examples below run a synthetic local read and an explicitly unavailable or closed-engine fixture. They assert return identity and one bypass event. They are availability fixtures, not detection. Use the language tab that matches your install, then run the sample with node --experimental-strip-types example.ts or python example.py.

import { createAgindow } from 'agindow';
const sdk = createAgindow({ mode: 'observe' });
await sdk.ready;
const payload = { id: 'synthetic-customer' };
let calls = 0;
const read = sdk.guard(() => { calls++; return payload; }, { tool: 'vendor.read', operation: 'read' });
const result = read();
if (result !== payload || calls !== 1) throw Error('Fixture identity changed');
// A labelled unavailable-engine fixture produces one bypass without a hosted key.
const unavailable = createAgindow({ mode: 'observe' }, async () => { throw Error('Synthetic loading fault'); });
await unavailable.ready;
const fallback = unavailable.wrap(() => payload);
if (fallback() !== payload || unavailable.recent().filter(e => e.type === 'bypass').length !== 1) throw Error('Missing bypass');
sdk.configure({ mode: 'observe' });
console.log('Synthetic fixture: original result retained; unavailable engine bypassed once.');
import asyncio
from agindow import Agindow
sdk = Agindow(mode="observe")
payload = {"id": "synthetic-customer"}
@sdk.guard(tool="vendor.read", operation="read")
def read() -> dict[str, str]:
    return payload
@sdk.guard(tool="vendor.read", operation="read")
async def read_async() -> dict[str, str]:
    return payload
with sdk.context(mode="observe"):
    assert read() is payload
async def main() -> None:
    async with sdk.context(mode="observe"):
        assert await read_async() is payload
asyncio.run(main())
# A closed engine is a labelled availability fixture, not vendor drift.
sdk.close()
assert read() is payload
assert len([event for event in sdk.recent() if event.type == "bypass"]) == 1
print("Synthetic fixture: sync/async identity retained; closed engine bypassed once.")

Read the first outcome

Inspect sdk.recent() or subscribe with sdk.on. A drift event with findings is detection evidence; bypass is an availability event and leaves the result body unchanged. A healthy default engine can return no findings without proving drift safety. Audit artifact production requires explicit audit options and a host drain; missing artifact IDs must stay unavailable.

Use the modes reference for policy and the guard loop for call behavior.