> ## Documentation Index
> Fetch the complete documentation index at: https://docs.manthan.systems/llms.txt
> Use this file to discover all available pages before exploring further.

# API Reference

> Complete API documentation for @parmanasystems/core

## executeFromSignals

Verifies authority against a policy and returns a signed attestation.

```typescript theme={null}
function executeFromSignals(
  input: {
    policyId:      string;
    policyVersion: string;
    signals:       Record<string, unknown>;
  },
  signer:              Signer,
  verifier:            Verifier,
  runtimeEnvironment?: {
    policiesRootPath:    string;
    trustPublicKeyPath:  string;
    trustRootPath:       string;
    releaseManifestPath: string;
  },
  replayStore:         ReplayStore
): Promise<ExecutionAttestation>
```

### Parameters

| Parameter             | Type                | Description                                                                                                                                                                                                 |
| --------------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `input.policyId`      | string              | Policy identifier — must match `policies/{policyId}/` directory                                                                                                                                             |
| `input.policyVersion` | string              | Semver version — must match `policies/{id}/{version}/` directory                                                                                                                                            |
| `input.signals`       | object              | Signal values — validated against `signalsSchema` before evaluation                                                                                                                                         |
| `signer`              | Signer              | Signs the attestation payload with Ed25519                                                                                                                                                                  |
| `verifier`            | Verifier            | Verifies the signature immediately after signing (self-verify)                                                                                                                                              |
| `runtimeEnvironment`  | object *(optional)* | Override the paths used to locate policy bundles, trust root, and release manifest. Omit (or pass `undefined`) to use `PARMANA_REPO_ROOT` env var or resolve from the project root.                         |
| `replayStore`         | ReplayStore         | Distributed replay authority used to enforce deterministic replay-safe execution semantics. Replay protection is required for governed execution. Parmana fails closed if replay protection is unavailable. |

### Deterministic Provenance Semantics

Signal provenance metadata is auditable but does not affect deterministic execution semantics.

Identical governed signal values must produce identical deterministic execution outcomes regardless of provenance annotations.

### Returns

`Promise<ExecutionAttestation>` — see [Attestations](/concepts/attestations) for the complete field reference.

### Throws

| Error                   | Cause                                                 |
| ----------------------- | ----------------------------------------------------- |
| `Policy not found: ...` | `policyId` / `policyVersion` directory does not exist |
| `VAL-003`               | Unknown signal not declared in `signalsSchema`        |
| `VAL-004`               | Required signal missing from input                    |
| `VAL-006` — `VAL-012`   | Signal has wrong type                                 |
| `INV-013`               | Same fingerprint already consumed by replay store     |

***

## confirmExecution

Verifies that a real-world action matches a prior governance authorization and returns a signed `ExecutionIntegrityProof`.

```typescript theme={null}
function confirmExecution(
  params: {
    attestation:        ExecutionAttestation;
    executedAction:     ExecutedAction;
    timeWindowSeconds?: number; // default: 300
  },
  signer:      Signer,
  verifier:    Verifier,
  publicKey:   string,
  store:       ReplayStore
): Promise<ExecutionIntegrityProof>
```

### Parameters

| Parameter           | Type                 | Description                                                                   |
| ------------------- | -------------------- | ----------------------------------------------------------------------------- |
| `attestation`       | ExecutionAttestation | The attestation returned by `executeFromSignals`                              |
| `executedAction`    | ExecutedAction       | Description of the real-world action that was performed                       |
| `timeWindowSeconds` | number               | Seconds between `executedAt` and confirmation that are allowed (default: 300) |
| `signer`            | Signer               | Signs the integrity proof                                                     |
| `verifier`          | Verifier             | Verifies the original attestation signature                                   |
| `publicKey`         | string               | PEM-encoded trust authority public key used to verify attestation lineage     |
| `store`             | ReplayStore          | Prevents double-confirmation and enforces replay-safe confirmation semantics  |

### ExecutedAction

```typescript theme={null}
interface ExecutedAction {
  type:        string;
  payload:     Record<string, unknown>;
  executedAt:  string; // ISO 8601
  executedBy?: string;
}
```

### ExecutionIntegrityProof

```typescript theme={null}
interface ExecutionIntegrityProof {
  executionId:     string;
  authorizationId: string;
  integrityHash:   string;
  authorized: {
    action:        string;
    reason:        string;
    policyId:      string;
    policyVersion: string;
  };
  executed:     ExecutedAction;
  match:        boolean;
  matchDetails: MatchDetails;
  signature:    string;
  confirmedAt:  string;
  verified:     true;
}
```

### MatchDetails

```typescript theme={null}
interface MatchDetails {
  actionTypeMatch:   boolean;
  payloadConsistent: boolean;
  withinTimeWindow:  boolean;
  timeWindowSeconds: number;
}
```

`match` is `true` only when all three match checks pass. Inspect `matchDetails` when `match` is `false`.

### Throws

| Error                           | Cause                                         |
| ------------------------------- | --------------------------------------------- |
| `INTEGRITY_INVALID_ATTESTATION` | Attestation signature verification failed     |
| `INTEGRITY_ALREADY_CONFIRMED`   | This `executionId` has already been confirmed |

***

## verifyAttestation

Verifies an attestation's signature and provenance chain.

```typescript theme={null}
function verifyAttestation(
  attestation:       ExecutionAttestation,
  verifier:          Verifier,
  runtimeManifest?:  RuntimeManifest,
  provenanceInput?:  ProvenanceVerificationInput
): OperationalVerificationResult
```

### Returns

```typescript theme={null}
{
  valid:    boolean;
  checks: {
    signature_verified:    boolean;
    runtime_verified:      boolean;
    schema_compatible:     boolean;
    bundle_verified:       boolean;
    release_verified:      boolean;
    trust_root_verified:   boolean;
    evaluator_verified:    boolean;
    governed:              boolean;
  };
  warnings: string[];
  errors:   string[];
}
```

`valid` is `true` only when all checks pass. Inspect `checks` and `errors` when `valid` is `false`.

***

## LocalSigner

Ed25519 signer backed by Node.js crypto, initialized from a PEM-encoded PKCS8 private key.

```typescript theme={null}
const signer = new LocalSigner(privateKeyPem: string);

signer.sign(payload: string): string
// Returns a base64-encoded Ed25519 signature over the UTF-8 payload.
```

***

## LocalVerifier

Ed25519 verifier initialized from a PEM-encoded SPKI public key.

```typescript theme={null}
const verifier = new LocalVerifier(publicKeyPem: string);

verifier.verify(payload: string, signature: string): boolean
// Returns true when the base64 signature is valid for the given payload.
```

***

## MemoryReplayStore

In-process replay store for development and testing.

```typescript theme={null}
const store = new MemoryReplayStore(options?: {
  warnInProduction?:      boolean; // default: true — logs warning when NODE_ENV=production
  maxSize?:               number;  // default: 1,000,000 — throws when exceeded
  reservationTtlSeconds?: number;  // default: 300
  failedTtlSeconds?:      number;  // default: 30
});
```

<Warning>
  Not suitable for production. Does not persist across process restarts and does not work across multiple processes. Use `RedisReplayStore` in production.
</Warning>

***

## RedisReplayStore

Redis-backed distributed replay store for production.

```typescript theme={null}
import { RedisReplayStore } from "@parmanasystems/core";

const store = new RedisReplayStore(
  "redis://localhost:6379",
  options?: {
    reservationTtlSeconds?: number; // default: 300
    failedTtlSeconds?:      number; // default: 30
  }
);
```

### Replay Lifecycle Semantics

Production replay stores should implement the reservation lifecycle methods (`reserve`, `confirm`, `fail`, `expire`) to support atomic replay-safe governed execution.

***

## getRuntimeManifest

Returns the current runtime manifest.

```typescript theme={null}
function getRuntimeManifest(): RuntimeManifest

// RuntimeManifest shape
{
  runtimeVersion:           string;   // e.g. "1.0.0"
  runtimeHash:              string;   // SHA-256 of the runtime definition
  supported_schemaVersions: string[]; // e.g. ["1.0.0"]
  capabilities:             string[]; // e.g. ["replay-protection", "ed25519-signing"]
}
```

### Runtime Signing Domains

Runtime manifests are signed using isolated runtime signing domains to prevent cross-artifact signature ambiguity.

***

## compilePolicy

Validates a policy directory through all 8 compilation phases.

```typescript theme={null}
import { compilePolicy } from "@parmanasystems/governance";

const result = compilePolicy("./policies/loan-approval/1.0.0");
// { valid: boolean, errors: PolicyCompileError[], warnings: PolicyCompileWarning[], ... }
```

***

## generateBundle

Compiles and content-addresses a policy, producing `bundle.manifest.json` and optionally `bundle.sig`.

```typescript theme={null}
import { generateBundle } from "@parmanasystems/governance";

const result = await generateBundle(
  "loan-approval",
  "1.0.0",
  "./policies/loan-approval/1.0.0",
  signer? // optional — omit for unsigned development bundles
);
// { success: boolean, manifest_path: string, signature_path: string | null, bundle_hash: string }
```

***

## approveOverride

Records a human override for a decision in `pending_override` state.

```typescript theme={null}
import { approveOverride } from "@parmanasystems/core";

const override = await approveOverride(
  {
    execution_fingerprint: "b3c4f8...",
    approved_by:   "user@example.com",
    approver_role: "risk-manager",
    reason:        "Manually reviewed and approved.",
  },
  signer // optional — omit for SHA-256, provide for Ed25519
);
```

***

## Types

### Signer

```typescript theme={null}
interface Signer {
  sign(payload: string): string;
}
```

### Verifier

```typescript theme={null}
interface Verifier {
  verify(payload: string, signature: string): boolean;
}
```

### ReplayStore

```typescript theme={null}
interface ReplayStore {

  // Required deterministic replay authority

  markExecuted(
    execution_fingerprint: string
  ): void | Promise<void>;

  hasExecuted(
    execution_fingerprint: string
  ): boolean | Promise<boolean>;

  // Strongly recommended atomic replay lifecycle methods

  reserve?(
    execution_fingerprint: string,
    ttlSeconds?: number
  ): Promise<void>;

  startExecution?(
    execution_fingerprint: string
  ): Promise<void>;

  confirm?(
    execution_fingerprint: string
  ): Promise<void>;

  fail?(
    execution_fingerprint: string,
    ttlSeconds?: number
  ): Promise<void>;

  expire?(
    execution_fingerprint: string
  ): Promise<void>;

  override?(
    execution_fingerprint: string
  ): Promise<void>;

  getReplayState?(
    execution_fingerprint: string
  ): ReplayState | null | Promise<ReplayState | null>;
}
```

## Use Cases

### End-to-end personal loan governance

A complete flow from signal collection to disbursement confirmation:

```typescript theme={null}
import {
  executeFromSignals,
  confirmExecution,
  verifyAttestation,
  LocalSigner,
  LocalVerifier,
  RedisReplayStore,
} from "@parmanasystems/core";

const signer   = new LocalSigner(process.env.PARMANA_PRIVATE_KEY);
const verifier = new LocalVerifier(process.env.PARMANA_PUBLIC_KEY);
const store    = new RedisReplayStore(process.env.REDIS_URL);

// Step 1: govern the loan decision

const attestation = await executeFromSignals(
  {
    policyId:      "personal-loan",
    policyVersion: "1.0.0",
    signals: {
      monthly_income:    82000,
      loan_amount:       500000,
      credit_score:      720,
      emi_obligations:   18000,
      employed:          true,
      employment_type:   "salaried",
      blacklisted:       false,
    },
  },
  signer,
  verifier,
  undefined,
  store
);

// Step 2: verify the attestation before acting

const check =
  verifyAttestation(
    attestation,
    verifier
  );

if (!check.valid) {
  throw new Error(
    "Attestation verification failed"
  );
}

// Step 3: disburse, then confirm

await disburse(
  attestation.executionId,
  500000
);

const proof =
  await confirmExecution(
    {
      attestation,

      executedAction: {

        type:
          "LOAN_DISBURSED",

        payload: {
          amount: 500000,
          account: "ACC-98765"
        },

        executedAt:
          new Date().toISOString(),

        executedBy:
          "disbursement-service-v3",
      },

      timeWindowSeconds:
        300,
    },

    signer,

    verifier,

    process.env.PARMANA_PUBLIC_KEY,

    store
  );

console.log(proof.match);
console.log(proof.integrityHash);
```

### Verifying an attestation without infrastructure

An IRDAI auditor receives an `ExecutionAttestation` and the insurer's public key. Using only these two values, the auditor verifies the governance record:

```typescript theme={null}
import {
  verifyAttestation,
  LocalVerifier
} from "@parmanasystems/core";

const verifier =
  new LocalVerifier(
    insurerPublicKeyPem
  );

const result =
  verifyAttestation(
    attestation,
    verifier
  );

console.log(result.valid);
console.log(result.checks.signature_verified);
console.log(result.checks.runtime_verified);
console.log(result.checks.bundle_verified);
```

No database, no runtime, no network. All checks are local, portable, and deterministic.

### Building a custom replay store for PostgreSQL

A fintech uses PostgreSQL for all persistence and wants replay protection in the same database as its application records:

```typescript theme={null}
import type {
  ReplayStore
} from "@parmanasystems/execution";

import {
  Pool
} from "pg";

class PostgresReplayStore
  implements ReplayStore {

  constructor(
    private pool: Pool
  ) {}

  async hasExecuted(
    fingerprint: string
  ): Promise<boolean> {

    const { rows } =
      await this.pool.query(
        "SELECT 1 FROM replay_store WHERE fingerprint = $1 AND status = 'CONFIRMED'",
        [fingerprint]
      );

    return rows.length > 0;
  }

  async markExecuted(
    fingerprint: string
  ): Promise<void> {

    await this.pool.query(
      "INSERT INTO replay_store (fingerprint, status) VALUES ($1, 'CONFIRMED') ON CONFLICT DO NOTHING",
      [fingerprint]
    );
  }
}
```

Production replay stores should additionally implement:

* `reserve`
* `confirm`
* `fail`
* `expire`

to support distributed atomic replay-safe execution guarantees.
