# AIWS TypeScript, Rust and Python SDK Contracts and Design

**Design edition:** 0.2 (identity and hierarchy contract update)  
**Date:** 8 September 2026  
**Status:** Accepted engine identity baseline; draft structural contracts. SDK 0.3.0 / AIWS edition 0.4 finite-v1 behavior is documented in the Implementation Handbook. New engine records below are not current SDK exports. Sections 1–11 retain the historical architecture proposal; where they differ, section 12 governs this identity update. This document does not release a new SDK or revise historical journals.

## 1. Recommended direction

Maintain native TypeScript, Rust and Python SDKs against one language-neutral contract: a versioned data model, semantic decision rules, canonical examples, and a shared behavioral test corpus. TypeScript should make governed workflows accessible to application developers; Rust should support services and execution boundaries with explicit error handling and controlled ownership. All three must make the same authorization, lifecycle, accounting, and recovery decisions for the same inputs.

Begin with definition validation and a bounded reference execution boundary. A full orchestration engine is unnecessary: existing engines can schedule work while the SDK integration governs admission and records its consequences. A Rust core exposed through WebAssembly is a possible later optimization, not the initial architecture. Independent native implementations provide a better opportunity to discover ambiguous semantics and avoid making every JavaScript deployment depend on an additional runtime boundary.

The promise to developers should be precise: **construct valid contracts, obtain governed dispatch decisions, retain recoverable records, and produce assessable outcomes.** Installing a package does not make an application conformant. Domain policy, credentials, external targets, storage guarantees, and accountable human roles remain part of the assessed deployment.

## 2. Boundary and responsibilities

| Layer | SDK contribution | Integrator obligation |
|---|---|---|
| Authoring | Builders, schema validation, semantic diagnostics, dependency analysis | Supply truthful scope, limits, policies, and assessable criteria |
| Semantic core | Pure state reduction, containment, fingerprinting, success predicate | Supply trusted revisions, time, identity, and policy inputs |
| Admission service | Coordinate current checks, reservations, approval use, and durable permit creation | Operate trusted storage and an enforceable credential/dispatch boundary |
| Executor | Consume scoped permits, invoke registered adapters, report ambiguous outcomes | Prevent alternative credential or unrestricted egress paths |
| Evidence | Provenance records, criterion results, acceptance dependencies, invalidation | Supply evidence and authorized assessors; SDK cannot determine all domain truth |
| Assessment | Shared fixtures, report generation, failure-injection interfaces | Run deployment-specific tests and document limitations |

Browser-facing TypeScript may author contracts and display status. It must not possess dispatch credentials or be trusted to approve its own policy decisions. Server-side TypeScript can operate the trusted boundary when isolated and assessed appropriately. Rust's types also cannot prevent an application from opening an ungoverned network connection; enforcement requires the surrounding deployment.

## 3. Shared model

The portable model should include WorkOrder (also called Mission), ContractRevision, WorkflowDefinition, Run, ExecutionSegment, PlanRevision, Task, Step, StepAttempt, CapabilityContract, AuthorityGrant, Approval, WaitCondition, BudgetAllocation, Reservation, EffectRecord, Checkpoint, Evidence, VerificationRecord, AcceptanceRecord, and ControlEvent.

WorkOrder/Mission owns cumulative accounting; these names denote one identity. See section 12 for accepted containment and identity mapping. A run pins one immutable contract revision. Segments continue a run without refreshing authority or limits. Steps identify logical operations; attempts identify individual dispatches. Materially changed effects receive new operation identities. An acceptance record refers to the exact verification revision it accepts, not a mutable “latest” record.

Use a single source-controlled specification directory for JSON Schema Draft 2020-12, semantic tables, profile definitions, fixtures, and compatibility rules. Schemas define record shape; handwritten semantic logic handles histories, cross-record references, containment, and external guarantees. Generate structural types where helpful, but never treat generated types as the complete standard implementation.

Proposed package/module names below are working labels, not reserved or available registry names:

| Concern | TypeScript module | Rust crate/module | Main AIWS obligations |
|---|---|---|---|
| Records and parsing | `@aiws/model` | `aiws-model` | M-01–M-04, I-01, EX-02 |
| State and decisions | `@aiws/semantics` | `aiws-semantics` | L-01–L-06, P-01–P-03, V-04 |
| Authority profiles | `@aiws/authority` | `aiws-authority` | AU-01–AU-08 |
| Admission and execution | `@aiws/runtime` | `aiws-runtime` | H-01–H-04, B-01–B-03, E-01–E-09, D-01–D-04 |
| Evidence and export | `@aiws/evidence` | `aiws-evidence` | V-01–V-08, O-01–O-04, EX-01/EX-02 |
| Adapter contracts | `@aiws/adapters` | `aiws-adapters` | AU-06, BI-01, target guarantees |
| Assessment tools | `@aiws/conformance` | `aiws-conformance` | T-01–T-05, Annex A |

Start as a monorepo with internal modules; split distribution packages only when dependency boundaries justify it. Keep schema and semantic-core modules free of network and database dependencies. Keep a CLI as a thin client over tested libraries, not a third semantic implementation.

## 4. Proposed portable JSON profile

This is a candidate SDK interchange profile requiring its own review and fixtures; the standard remains encoding-neutral.

| Topic | Proposed rule |
|---|---|
| Version | Explicit `aiwsEdition: "0.2"`, separate profile version, and required-extension list |
| IDs | Opaque namespace-qualified strings; never infer authority from their format |
| Integers | Counters, amounts, durations, and sequence values use canonical unsigned decimal strings; no leading zeros except `"0"` |
| Money/quantities | Integer amount plus declared unit and scale; no implicit currency conversion or floating-point budget arithmetic |
| Time | UTC timestamps with exactly millisecond precision and `Z`; deadlines use trusted wall time with declared uncertainty |
| Optional fields | Omission means absent; `null` is allowed only when explicitly specified; no implicit defaults during validation |
| Closed records | Unknown core fields and unknown enum values reject at control boundaries; extensions belong in a separately named extension object |
| Extensions | Required extensions must be understood; optional extensions are preserved for export and may be ignored only if semantically inert |
| Parsing | Reject duplicate object keys, invalid Unicode, excessive size/depth, and unsupported representations before semantic validation |
| Canonicalization | RFC 8785 JCS over the defined material projection, followed by SHA-256; record projection/profile version with the digest |
| Material projection | Explicit capability revision, target, payload/artifact revision, and preconditions; omit secret values and nonmaterial display labels |

A digest is not a signature, authorization, or proof of truth. Any signed envelope needs a separate profile for signer trust, key rotation, algorithm policy, and verification. Unicode must not be silently normalized between fingerprint creation and verification. JCS is not equivalent to recursively sorting keys with either language's ordinary string comparison; use its specified ordering and shared vectors. Keep exact large quantities as strings before canonicalization. [JCS specification](https://www.rfc-editor.org/rfc/rfc8785.html).

Validators must configure actual checks for timestamp syntax and semantics; merely annotating a schema field with a format is insufficient as an implementation contract. Validate references, acyclic parent chains, units, revision consistency, and deadlines in a semantic pass. [JSON Schema 2020-12](https://json-schema.org/draft/2020-12).

## 5. Authority profile for the first release

Start with a deliberately bounded profile: explicit finite action/resource/audience sets, half-open validity intervals, integer limits in matching units, delegation permission/depth, and immutable policy references. Empty action/resource sets confer no permissions. No implicit wildcard, filesystem glob, natural-language predicate, or dynamic tag expansion in the initial profile.

Containment is CONTAINED only when every relevant child permission is within the parent and issuer authority, child expiry does not exceed applicable bounds, delegation depth is valid, and shared accounting preserves aggregate restrictions. NOT_CONTAINED identifies a proven expansion. INDETERMINATE identifies unsupported semantics, missing trusted data, or incompatible profiles. Both latter outcomes block delegation. A child amount less than a parent amount is not sufficient when siblings can jointly exceed the parent's remaining allocation.

Policy evaluation returns ALLOW, DENY, or INDETERMINATE, with stable reason codes and mandatory-check diagnostics. An engine-specific adapter must not discard errors when another policy permits an action. Revocation freshness includes maximum accepted age, clock uncertainty, propagation bound, and cache behavior. These are trusted service inputs, never planner-supplied declarations accepted at face value. [RFC 9396](https://www.rfc-editor.org/rfc/rfc9396.html); [Cedar authorization](https://docs.cedarpolicy.com/auth/authorization.html).

## 6. Developer-facing APIs

Both APIs should expose validated record constructors, pure semantic functions, and an integrated coordinator. Compile-time types aid correct use; externally supplied records always undergo runtime validation. TypeScript assertions are erased and do not validate data. Rust deserialization also needs explicit treatment of unknown fields and semantic constraints. [TypeScript handbook](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html); [Serde container attributes](https://serde.rs/container-attrs.html).

The following signatures are design sketches, not compilable examples or existing exports:

```typescript
type Check<T> =
  | { ok: true; value: T }
  | { ok: false; diagnostics: readonly Diagnostic[] };

type Containment = "CONTAINED" | "NOT_CONTAINED" | "INDETERMINATE";

interface SemanticCore {
  parseContract(bytes: Uint8Array): Check<ValidatedContract>;
  compareGrants(input: ContainmentInput): ContainmentResult;
  reduce(state: Snapshot, event: ValidatedEvent): Check<Snapshot>;
  assessSuccess(snapshot: Snapshot): SuccessAssessment;
}

interface Coordinator {
  execute(command: OperationCommand): Promise<OperationOutcome>;
  reconcile(operationId: OperationId): Promise<ReconciliationOutcome>;
  resume(waitId: WaitId, input: ResumeInput): Promise<ResumeOutcome>;
  recover(runId: RunId, mode: ReplayMode): Promise<RecoveryOutcome>;
}
```

```rust
// Proposed signatures; supporting types and implementations are not supplied.
pub fn parse_contract(bytes: &[u8]) -> Result<ValidatedContract, Diagnostics>;
pub fn compare_grants(input: &ContainmentInput) -> ContainmentResult;
pub fn reduce(state: &Snapshot, event: &ValidatedEvent)
    -> Result<Snapshot, Diagnostics>;
pub fn assess_success(snapshot: &Snapshot) -> SuccessAssessment;

impl Coordinator {
    pub async fn execute(&self, command: OperationCommand)
        -> Result<OperationOutcome, CoordinatorError>;
    pub async fn reconcile(&self, operation: &OperationId)
        -> Result<ReconciliationOutcome, CoordinatorError>;
}
```

Use TypeScript discriminated unions and branded validated identifiers with restricted constructors. Use Rust enums, checked newtypes, and `Result` for expected failures; no panic as a policy-denial path. Typestate may prevent obvious misuse but cannot prove that a grant remains valid after an asynchronous wait. Every actual dispatch still needs current runtime checks.

`OperationOutcome` must distinguish CONFIRMED_APPLIED, CONFIRMED_NOT_APPLIED, UNKNOWN, and no-domain-effect completion; a generic thrown timeout must not encourage blind retry. Diagnostics should carry a stable code, requirement ID, object path, safe explanation, and remediation class without exposing credentials or sensitive payloads. Initial codes should include `AUTHORITY_INDETERMINATE`, `POLICY_CHECK_ERROR`, `AUTHORITY_STALE`, `APPROVAL_INVALID`, `BUDGET_EXHAUSTED`, `REVISION_CONFLICT`, `EFFECT_UNKNOWN`, `UNSUPPORTED_EXTENSION`, and `EVIDENCE_INVALIDATED`.

## 7. Dispatch, persistence, and crash handling

The public `execute` convenience operation should encapsulate admission and dispatch. An advanced split prepare/dispatch API may exist only with opaque, short-lived, operation-bound permits; it must not let a caller claim that arbitrary JSON is a permit.

1. Parse and validate the command. Resolve immutable contract, capability, plan, payload, and policy revisions. Compute the material fingerprint and check mission/run eligibility.
2. Obtain trusted policy, authority freshness, approval eligibility, target guarantee, and ownership inputs. Failed or indeterminate mandatory checks prevent admission.
3. In a durable transaction or equivalent conditional atomic operation, verify current revisions; reserve the attempt's resources; consume or reuse approval for this logical operation; record the attempt, decision revisions, ownership epoch, and dispatch intent; issue a bounded permit. Concurrent competitors must not double-consume or over-allocate.
4. At the trusted dispatch boundary, validate permit scope, expiry, ownership, and required current controls. The deployment declares the revocation race boundary. Never hold an ordinary database transaction open across an unrelated network call.
5. Invoke the adapter with the stable operation idempotency key, unique attempt identity, and preconditions. Record target acknowledgment or conservative uncertainty.
6. Reconcile observed consumption and effects. Retain potential unknown liability until resolved. Retry only with current controls and evidence of nonapplication or a still-valid target deduplication guarantee.

| Failure boundary | Required behavior |
|---|---|
| Before durable admission | No valid permit exists; no external dispatch |
| After admission, before known dispatch | Inspect claim/permit and dispatch evidence; uncertainty is conservative, not assumed failure |
| Target committed, acknowledgment lost | UNKNOWN; query/reconcile or safely deduplicate under the target contract |
| Local outcome commit fails | Recovery retains unresolved intent and reconciles; do not report a durable terminal success |
| Concurrent worker resumes old epoch | Dispatch boundary rejects stale ownership |
| Authority revoked after target acceptance | Record the actual effect and authorized recovery; do not claim prevention |

The Store interface needs transactional or equivalent conditional mutation across the operation, allocation, approval-consumption, ownership, and event records that share an invariant. Simple `get`/`put` methods are insufficient. The first durable reference adapter should use one transactional store. In-memory storage is only for fixtures and demonstrations and cannot support a durability claim. Product selection and supported versions require implementation evaluation.

Clock, identity, policy, grant lookup, store, evidence resolver, and capability adapter are injected interfaces. The pure core reads neither system time nor the network. Recovery uses recorded decisions until it reaches eligible pending work. Audit playback must run with no invocation-capable adapters at all. New execution requires a linked new run and current admission; it never acts as an implicit retry button.

## 8. Evidence and acceptance

Provide builders for evidence manifests, criterion assessments, and acceptance requests. Validate assessor identity and separation policy through trusted identity services. Compute aggregate verification from the declared criterion set rather than accepting a caller-supplied `passed: true` flag.

Maintain a dependency index from artifact/evidence revision to verification revision to acceptance record. Invalidation appends a finding, updates the current assessment view, and produces the configured owner-notification event without rewriting historical execution. Notifications themselves are governed actions when dispatched externally. Automatic acceptance is supported only under an explicit authorized policy; manual acceptance must capture the accountable decision maker.

Export should include omissions, redactions, unresolved references, and profile versions. A consumer can validate structure and integrity yet still be unable to substantiate acceptance because restricted evidence is unavailable. That result must remain explicit. PROV mappings and SACM-style support graphs are optional representations; no RDF dependency is required for the initial SDK.

## 9. Shared conformance corpus

Use language-independent JSON fixtures with initial state, trusted input snapshots, stimulus/event sequence, virtual time, expected semantic result, forbidden effects, required records, and requirement IDs. Compare decisions, identities, accounting, and event causality; do not demand identical human-readable error prose or model text.

| Track | Minimum coverage | What a pass establishes |
|---|---|---|
| Parsing and portable records | Duplicate keys, unknown fields, Unicode, exact large quantities, time boundaries, required extensions, canonical digests | Agreement on admitted representations |
| Pure semantics | Mission/run/segment invariants, terminal states, concurrent waits, authority containment, evidence invalidation | Shared control decisions for the supplied cases |
| Coordinator failure injection | Competing reservations, quorum changes, stale permits, target commit with lost response, crash recovery, idempotency expiry | Reference integration behavior under tested failures |
| Deployment enforcement | Bypass attempts, revoked credentials, tenant isolation, storage failures, actual target guarantees | Evidence for the declared deployment boundary |
| Outcome quality | Domain-specific correctness and acceptance evaluation | Quality on the declared task/evidence population |
| Interoperability | TypeScript-produced records consumed by Rust and vice versa, plus paired execution scenarios | Preserved semantics for the tested profile and versions |

Cover all applicable AT-01 through AT-41 scenarios. Tests involving delegation or migration remain conditional on enabled features; disabled features still require rejection tests. Live migration should remain disabled in the first release. Add property-based state-machine tests for no terminal reopening, no budget creation through rollover, no permit from indeterminate authority, and no verified success without current acceptance.

Use fixed virtual clocks, seeded simulations, and deterministic event fixtures. A real-time integration suite separately checks clock/freshness and service failure behavior. Shared fixtures do not excuse shared bugs: have each implementation review ambiguous cases independently and include externally observed dispatch assertions, not just expected reducer outputs.

## 10. Implementation sequence and release gates

| Stage | Deliverable | Gate before proceeding |
|---|---|---|
| 1. Contract stabilization | Schemas, finite-set authority profile, event/state tables, canonical vectors | Resolve material ambiguity with examples and requirement traceability |
| 2. Validation pilot | TypeScript authoring/parser and semantic core; CLI validation | Valid/invalid fixtures pass; zero claim of production execution conformity |
| 3. Durable reference boundary | One store, one simulated write adapter, approval/budget/effect coordinator | Crash, concurrency, lost-acknowledgment, and revocation cases pass |
| 4. Native Rust parity | Independently implemented parsing and semantic core, then coordinator integration | Both directions of interchange and shared behavioral corpus pass |
| 5. Integration pilot | One bounded real workflow and one pinned runtime/protocol binding | Deployment assessment covers credentials, storage, adapter, and domain acceptance |
| 6. Release candidate | Versioned packages, documentation, compatibility reports, examples, assessment report | All applicable assertions pass; limitations and supported environments published |

The first demonstration should execute a document-review workflow with a simulated case-record update. Include a changed document after approval, concurrent budget requests, a target that commits while dropping its response, and later evidence invalidation. A successful demonstration must show prevented actions and recovery, not only a happy-path artifact.

Avoid beginning with universal checkpoint migration, unrestricted policy languages, every orchestration binding, or a certification badge. These add separate proof obligations. Package versions and AIWS editions are separate: each release states supported editions/profiles, compatibility changes, and reassessment impact. Unsupported semantics fail explicitly rather than being silently downgraded.

## 11. Decisions still requiring implementation evidence

The architectural choices above are recommendations for the proposed SDK project. Before freezing its public API, validate the storage transaction contract, target idempotency metadata, profile canonicalization vectors, revocation propagation measurements, and language-specific deployment support. Benchmark actual workloads before choosing FFI/WASM, caching, or additional packaging. Domain authorities still select evidence quality, acceptable exposure, separation rules, and approval thresholds.

Historical baseline: sections 1–11 originated against AIWS-001 edition 0.2. Consult the current Implementation Handbook for implemented SDK behavior and package status. The engine identity contracts in section 12 remain a design update; no engine implementation or deployment conformance is claimed here.

## 12. Accepted SDK identity contracts — 2026-09-08

The normative engine requirements are WO-01 through WO-08 in `AIWS-Engine-Handoff-Design.md`. They apply equally to Python, TypeScript and Rust. The sibling `AIWS-Engine-Identity-Contracts.schema.json` defines the closed structural draft profile `aiws-engine-identity/0.1`; `AIWS-Engine-Identity-Examples.json` is a linked example, not a current SDK command. This focused schema describes assignment and execution identity records, not the complete engine state, command protocol, grant or evidence schema.

| Engine concept | Existing SDK 0.3.0 mapping | New contract obligation |
|---|---|---|
| WorkOrder.id / workOrderId | Contract.missionId | Same value; never create a separate mission above/below it |
| contractRef.id | Contract.id | Keep contract distinct; preserve immutable revision provenance |
| Run.id / runId | run ID | Exactly one workOrderId; continuation retains ID |
| predecessorRunId | No implicit inference | Record explicit lineage for fresh execution; no terminal reopening |
| planRef / graphRef | Existing plan/graph references | Pin exact revisions; do not mutate historical bases |
| segmentId | Recovery segment identity | Preserve run and accounting; ownership transition is durable |
| nodeId / nodeInstanceId | Existing node ID; new occurrence model | Scoped definition node plus distinct loop/fan-out occurrence |
| operationId | Existing logical operation ID | Same immutable material action across safe retries |
| attemptId | Existing attempt ID | Distinct execution attempt; command replay does not create another |
| wait / assessment references | Existing wait and subject records | Preserve correlation and exact subject/evidence revision |
| handoff/delivery IDs | No built-in finite-v1 queue contract | Engine persists immutable manifest and per-consumer delivery |
| externalRefs | Adapter/application metadata | Namespace by provider/system; never substitute for engine IDs |

### Structural and semantic validation

Every record in the draft bundle has `recordType`, `namespace`, and `id`. Mutable record snapshots also carry a decimal-string `revision`. Immutable source references use `{id, revision}`. JSON keys remain camelCase across all languages; Python/Rust convenience names may use snake_case locally only with explicit serialization mappings. Unknown record fields and enum values reject. Optional references are omitted, not null. IDs are nonempty opaque strings; revisions, epochs and time values are canonical unsigned decimal strings, and time uses UTC epoch milliseconds, consistent with the current Handbook. The earlier section 4 time/version examples are historical proposals and do not override this draft profile.

References resolve within the bundle namespace or a declared trusted store. Contract/definition, artifact, approval and evidence references may resolve outside this identity-only bundle. Missing material references block admission/acceptance. Schema validation checks shape only; the engine semantic layer must enforce same-work-order run membership, acyclic single-parent containment, valid revision lineage, compatible plan changes, attempt-to-operation ownership, immutable operation material, unique delivery destinations, current authority, cumulative limits and the completion predicate. Never manufacture a missing legacy revision during import.

The engine assigns durable IDs through its trusted admission boundary; standalone SDK callers remain responsible for the IDs required by existing APIs. A replayed admission request must return its recorded identity/result. The future command envelope needs a request ID and expected revision distinct from an attempt ID. Atomic admission includes reference validation, current policy, reservations and the event record; ID allocation alone does not authorize work.

### Compatibility and migration contract

1. Keep finite-v1 Contract.missionId and original journal bytes unchanged. New WorkOrder records live in the explicitly versioned engine profile.
2. At the adapter boundary, map missionId to the same workOrderId value; reject conflicting aliases. Never silently combine old missions or rename fields in signed/hashed records.
3. Preserve existing terminal run semantics. Resumable holds are future engine controls; a legacy terminal LOOP failure requires a new linked run.
4. Preserve all accounting, effects, approvals, waits and lineage. Unsupported parentage, handoff or revision provenance must be declared unresolved and block operations that require it.
5. Activation of new plans/graphs is revision-checked and preserves mandatory gates. Do not describe it as supported graph mutation in SDK 0.3.0.
6. Require shared cross-language fixtures before publishing new parsers or runtime APIs. Shape validation of the companion example is not evidence of runtime conformance.

### Lifecycle contract

WorkOrder uses OPEN/SUSPENDED/CLOSED plus a closure disposition COMPLETED/CANCELED. Successful closure requires all required work and current acceptance conditions, terminal runs, safely closed children, settled reservations and no unresolved material effects. Cancellation blocks ordinary dispatch immediately but closes only after safe settlement; it never manufactures acceptance. Historical closure remains immutable after evidence invalidation. A terminal run requires a fresh linked run for further execution; a closed work order requires a newly authorized linked work order.

See the engine document's required verification scenarios for the implementation gate. This update establishes contracts and examples; it does not add parser exports, reducer commands, migrations or engine services to released packages.

