# Jev P&ID Semantic Engine

**A CAD-neutral semantic compiler and graph-repair engine, with native JavaScript modules and a typed .NET SDK.**

Version **0.1.0** · MIT · Node.js **22+** · .NET SDK targets **net8.0** · modern browsers in a secure context.

```text
CAD document / ASCII DXF / normalized entities
  → immutable evidence graph with explicit ports
  → local candidate generation and canonical question packs
  → Jev Choice / Noul / Score evidence
  → constrained finite-domain optimization
  → provisional semantic graph + findings + reviewable repair transactions
```

The JavaScript kernel is the single semantic implementation. .NET uses an embedded copy of that kernel through a process-isolated Node host, or accesses a remote HTTP service. **This is not a separate pure-managed C# solver.** No CAD vendor's binaries are required by the kernel.

## Start immediately, without credentials

From the extracted repository root:

```sh
node examples/solve.mjs
node packages/engine/bin/server.mjs
```

Open **http://127.0.0.1:8787** for the workbench. It loads a two-sheet process example with a pump, control loop, specification break, off-page connectors, and a near-miss connection. The workbench can import normalized JSON or supported ASCII DXF, solve in a browser worker, inspect entities, show review findings/proposals, and export the complete result.

**Offline mode uses deliberately weak, transparent heuristics. It is not Jev and is not a trained P&ID recognition model.** Every output records its actual provider.

## Use live Jev

On a trusted workstation/server, set a key and run the same example:

```sh
export TYPESAFE_API_KEY='your-key'
node examples/solve.mjs --live
```

PowerShell:

```powershell
$env:TYPESAFE_API_KEY = 'your-key'
node examples/solve.mjs --live
```

The adapter implements TypeSafe's documented `POST /v1/systemone` contract, pins `jev-1.13.0` by default, records the returned model version, validates probability distributions, and handles transient errors with bounded retries. Change the model explicitly with the provider configuration; the service also accepts `JEV_MODEL`. The API contract and model listing were checked on **2026-09-17**. See [Jev integration](docs/JEV.md) and [references](docs/REFERENCES.md).

Never put a provider key in a browser bundle. The workbench's live mode calls the local/server RPC proxy; only the server reads `TYPESAFE_API_KEY`.

## JavaScript

No build or install step is necessary when importing the source directly:

```js
import { readFile } from 'node:fs/promises';
import {
  PidSemanticEngine, JevProvider, HeuristicProvider
} from './packages/engine/src/index.mjs';

const graph = JSON.parse(await readFile('data/plant.json', 'utf8'));
const provider = process.env.TYPESAFE_API_KEY
  ? new JevProvider({ apiKey: process.env.TYPESAFE_API_KEY })
  : new HeuristicProvider();

const engine = new PidSemanticEngine({
  provider,
  planner: { textRadius: 35, repairRadius: 2, snapTolerance: 0.1 },
  solver: { timeLimitMs: 15000, maxStates: 100000, maxFrontier: 50000 }
});
const result = await engine.solve(graph);
console.log(result.solver.status, result.solver.gap);
console.log(result.proposals); // Nothing has been written back to CAD.
```

The npm package includes `.d.ts`/`.d.mts` declarations. See [usage](docs/USAGE.md), [API reference](docs/API.md), and `examples/typescript.ts`.

## .NET

Install Node.js 22+ on the host, then run:

```sh
dotnet run --project dotnet/PidSemantics.Sample -- data/plant.json
```

The SDK assembly embeds the JavaScript runtime and extracts it into a private temporary directory. No JavaScript path needs to be configured:

```csharp
using System.Text.Json;
using PidSemantics;

var graph = JsonSerializer.Deserialize<EvidenceGraph>(
    await File.ReadAllTextAsync("data/plant.json"), PidJson.Options)!;

await using var transport = await NodePidTransport.StartAsync();
await using var client = new PidSemanticClient(transport, ownsTransport: false);
var result = await client.SolveAsync(graph,
    new EngineSettings { Mode = "offline" },
    cancellationToken: cancellationToken);

Console.WriteLine(result.Solver.Status);
```

For a .NET process without local Node, use `HttpPidTransport`; Node runs only on the service. See [the .NET integration guide](docs/DOTNET.md).

## Included capabilities

| Area | Implemented functionality |
|---|---|
| Evidence model | Stable identities, sheets, units, explicit ports/circuits, source provenance, immutable snapshots, authority levels |
| Geometry | Affine block transforms, arc/bulge tessellation, spatial indexing, endpoint/segment/crossing candidates, overlap diagnostics |
| Inference | Entity types, text ownership, line classes, directed relations, normal flow, off-page candidates, spec-break judgments, staged control-loop motifs |
| Optimization | Hard constraints, weighted table factors, propagation, component decomposition, exact anytime branch-and-bound, valid bounds, conflict cores, bounded exact marginals, Hungarian matching |
| Process analysis | Port-level reachability, separate equipment circuits, normal-flow tracing, shared-valve graph-isolation optimization |
| Repair | Connect, remove, type/property assignment, associate text, flow assignment, off-page match, split, merge, tap, crossing-to-junction; named approval, preimages, revision checks, undo |
| QA | Capacity errors, unresolved/orphan entities, duplicate tag review, spec text mismatch/wrong-side/point mismatch, unmarked transitions, arrow contradictions |
| Assurance | Evidence replay, content-addressed request caching, calibrated review policies, temperature fitting, Brier/NLL/ECE, Wilson intervals, hash-chained audit events |
| Interchange | Lossless engine-profile GraphML, JSON-LD/PROV-O projection, CSV, standards mapping manifest, semantic revision diff |
| Hosting | Node CLI, bounded worker pool, cancellable NDJSON and HTTP transports, browser workbench, typed .NET client |

## What “universal” means

Any CAD engine can integrate by providing the normalized evidence contract and an optional native transaction adapter. It does **not** mean this archive contains a DWG decoder or complete adapters for every proprietary CAD system. The bundled DXF frontend is explicitly a bounded, planar ASCII DXF subset. Unsupported constructs produce diagnostics. DEXPI output is a mapping manifest, **not a certified DEXPI XML writer**.

An `OPTIMAL` result proves optimality for the constructed finite-domain objective under the implementation's floating-point arithmetic. It does not prove the drawing interpretation is correct. Provider confidence, local class probability, model marginal, and optimization gap are intentionally distinct.

## Documentation

Start with [the documentation index](docs/INDEX.md). The archive also includes a navigable offline HTML manual in `docs/html/index.html` and a **single-file `manual.html`** with native MathML equations, requiring no network resources.

The manual covers installation; JavaScript/.NET/browser usage; CAD integration and native transaction boundaries; architecture; the complete mathematical model and algorithms; Jev contracts; QA/repair workflows; API reference; security; deployment; test evidence; and explicit limitations.

## Validate and package

```sh
npm test
node scripts/check.mjs
node scripts/benchmark.mjs
npm pack --workspace packages/engine --pack-destination artifacts
```

Optional development checks:

```sh
tsc --noEmit --strict --target ES2022 --module NodeNext \
  --moduleResolution NodeNext --lib ES2022,DOM examples/typescript.ts
python scripts/validate-schemas.py
dotnet run --project dotnet/PidSemantics.Tests -- data/plant.json
```

The release includes actual test/benchmark logs. The JavaScript suite and TypeScript declarations were exercised in the build environment. **The .NET SDK was not compiled there because no .NET SDK was available. Live Jev was not called because no key was supplied.** A browser-navigation restriction also prevented a full hosted Chromium end-to-end run in that environment; a runnable browser test is included. See [validation evidence](docs/VALIDATION.md) for the exact scope rather than treating supplied tests as executed tests.

This library produces engineering evidence and proposed changes. It is not a process-safety assessment, hydraulic simulator, operational isolation procedure, or authorization to operate plant equipment.
