monora-ai
v2.1.4
Published
Lightweight governance and trace SDK for AI systems
Downloads
257
Maintainers
Readme
Monora SDK for Node.js v2.1.4
Lightweight governance and trace SDK for AI systems.

Streamlined Setup (Recommended)
Use this local-first onboarding flow to get production-ready governance/reporting quickly:
# 1. Install and generate a base config
npm install monora-ai
npx monora-ai init --preset production
# 2. Initialize onboarding contract + model spec + enrichment bundles
npx monora-ai onboard init --config monora.yml
# 3. Validate logs + schema mapping + role mapping
npx monora-ai onboard validate --config monora.yml --pretty
# 4. Complete onboarding and auto-generate baseline reports
npx monora-ai onboard complete --config monora.yml --completed-by "platform-team" --pretty
# 5. Check onboarding status and generated artifacts
npx monora-ai onboard status --config monora.yml --prettyOn completion, Monora writes baseline reports and summaries under onboarding.artifacts.baseline_reports_dir (default ./monora_reports/onboarding):
soc2_baseline_report.jsongdpr_baseline_report.jsoniso27001_baseline_report.jsoniso42001_baseline_report.jsononboarding_validation.jsononboarding_summary.json
Each baseline report includes:
claims[].severityclaims[].remediationfindings_summary(totals, status breakdown, remediation recommendations)
CLI Reference
# Configuration
npx monora-ai init # Interactive setup wizard
npx monora-ai init --yes # Quick setup with defaults
npx monora-ai init --preset minimal # Minimal preset
npx monora-ai init --preset dev # Dev preset (file + pretty stdout)
npx monora-ai init --preset production # Production preset
npx monora-ai validate # Validate config file
npx monora-ai validate --mode lenient # Lenient validation
npx monora-ai doctor # Diagnose configuration issues
npx monora-ai config fix # Auto-fix common config issues
# Onboarding lifecycle
npx monora-ai onboard init --config monora.yml
npx monora-ai onboard validate --config monora.yml --input ./monora_events.jsonl --pretty
npx monora-ai onboard complete --config monora.yml --completed-by "platform-team" --pretty
npx monora-ai onboard status --config monora.yml --pretty
# Schema/model bootstrapping
npx monora-ai schema infer \
--input ./monora_events.jsonl \
--output ./monora_spec.json \
--compliance-target gdpr \
--compliance-target soc2 \
--compliance-target iso42001 \
--report ./monora_inference_report.json \
--contract ./onboarding/schema_contract.json
npx monora-ai model create \
--input ./monora_events.jsonl \
--output ./monora_model.json \
--model-name support-bot \
--risk-category high \
--compliance-target gdpr \
--compliance-target soc2 \
--compliance-target iso42001 \
--config-out ./monora_model_config.json \
--config-format json \
--contract-out ./onboarding/schema_contract.json
# Reports
npx monora-ai report --input events.jsonl --output report.json
npx monora-ai report --input events.jsonl --output report.md --format markdown
# Security & Verification
npx monora-ai security-review --input events.jsonl --output security.json
npx monora-ai verify --input events.jsonl --config monora.yml --pretty
# Trust Packages
npx monora-ai trust-package --input events.jsonl --trace-id trc_123 --output trust.json --control-standard SOC2
# HTTP Queue Management
npx monora-ai retry-queue --config monora.yml
npx monora-ai retry-queue --path ./monora_http_queue --clearQuick Start
After setup, initialize Monora in your app:
import { init, llmCall, trace } from 'monora-ai';
await init({ configPath: './monora.yml' });
const ask = llmCall({ purpose: 'support' })(function ask(
question: string,
model: string = 'gpt-4o-mini'
) {
return { choices: [{ message: { content: 'ok' } }] };
});
// Create a trace
trace('my-ai-task', (span) => {
console.log('Trace ID:', span.traceId);
ask('hello');
});Production gate behavior:
- If
defaults.environment=production - And
onboarding.enabled=true - And
onboarding.required_in_production=true - And
onboarding.status!=completed
init() fails fast with an onboarding-required error.
Presets
Use presets to generate opinionated configs:
- minimal: file sink only, relaxed validation, minimal setup
- dev: file + pretty stdout, relaxed validation for local development
- production: file sink with daily rotation + symlink, strict validation
Example:
npx monora-ai init --preset devConfiguration
monora.yml is the default config path (monora.json is also supported). For onboarding-driven production setup:
defaults:
data_classification: internal
environment: production
onboarding:
enabled: true
required_in_production: true
status: draft # draft | validated | completed
standards: [SOC2, GDPR, ISO27001, ISO42001]
artifacts:
production_logs_path: ./monora_events.jsonl
schema_contract_path: ./onboarding/schema_contract.json
dataset_sample_path: ./onboarding/dataset_sample.jsonl # optional
baseline_reports_dir: ./monora_reports/onboarding
validation:
min_log_records: 100
required_field_presence_threshold: 0.95
type_conformance_threshold: 0.90
model_spec:
name: monora_default
version: v1
event_ts_field: timestamp
schema_ref: ./onboarding/schema_contract.json
roles:
inputs: [body.prompt]
outputs: [body.response]
metadata: [event_type, service_name, timestamp]
identifiers: [event_id, trace_id, span_id]
enrichments:
profile: recommended
bundles: [core_observability, soc2_access, gdpr_privacy, iso27001_security]
toggles:
identity_tracking: true
risk_tracking: true
bias_tracking: false
oversight_tracking: true
data_governance_tracking: true
lifecycle_tracking: trueNotes:
onboard validatereturnscoverage.profilingandcoverage.inference(field profiles, role suggestions, timestamp suggestion, schema mapping gaps).onboard completegenerates one report per selected standard and records outputs inartifacts.baseline_reports.- Enrichment bundles map to existing Monora observability, access, privacy, and security controls.
Programmatic Onboarding API
import {
buildModelSpec,
validateOnboarding,
completeOnboarding,
} from 'monora-ai';
const modelSpec = buildModelSpec({
schemaRef: './onboarding/schema_contract.json',
roles: {
inputs: ['body.prompt'],
outputs: ['body.response'],
metadata: ['event_type', 'service_name', 'timestamp'],
identifiers: ['event_id', 'trace_id', 'span_id'],
},
});
const validation = validateOnboarding({ configPath: './monora.yml' });
if (validation.status === 'validated') {
const completion = completeOnboarding({
configPath: './monora.yml',
completedBy: 'platform-team',
});
console.log(completion.status);
}Allowlist/denylist patterns use glob syntax (minimatch), for example gpt-* matches gpt-4o-mini.
HTTP Retry Queue + Idempotency
sinks:
- type: https
endpoint: https://api.example.com/events # replace with your endpoint
retry_queue:
enabled: true
path: ./monora_http_queue
max_items: 10000
flush_interval_sec: 5.0
idempotency:
enabled: true
header_name: Idempotency-KeyIdempotency keys are computed per batch as a SHA-256 digest of the canonical event JSON in order.
npx monora-ai retry-queue --config monora.yml
npx monora-ai retry-queue --path ./monora_http_queue --clearFile Sink Rotation
sinks:
- type: file
path: ./monora_events.jsonl
rotation: daily # none | daily | size
symlink: true # keeps monora_events.jsonl and monora_events.latest.jsonl pointing to the newest fileWhen rotation is enabled, use ./monora_events.latest.jsonl in scripts to always read the current file.
Features
- Immutable Event Logs: SHA-256 hash chains for tamper-evident audit trails
- Policy Enforcement: Model allowlist/denylist with classification-based rules
- Model Registry: Centralized model and provider metadata
- Tracing: Distributed tracing for AI system observability
- Event Processing: Background event dispatcher with batching and buffering
- Multiple Sinks: Output to stdout, file (JSON-lines), or HTTPS endpoints
- Durable HTTPS Delivery: Retry queue + idempotency headers for HTTP sinks
- Event Enrichment: Automatic metadata (timestamp, host, process, environment)
- Attribution + Usage Telemetry: Optional project registration and anonymous usage stats (opt-in)
- Compliance Assessment Hooks: Built-in checks and usage profiles for audits
New in v2.1.4
- SOC2/GDPR Workflow Parity: First-class SOC2/GDPR control catalogs and standard-aware workflow gap prioritization
- ISO42001 Onboarding Defaults: Onboarding standards defaults now include
SOC2,GDPR,ISO27001, andISO42001 - Trust Package Selector:
trust-package --control-standard ISO42001|SOC2|GDPRselects bundled catalogs without custom paths
Usage Examples
Decorator Helpers (TypeScript)
import { init, llmCallDecorator, toolCallDecorator, agentStepDecorator } from 'monora-ai';
init({ configPath: './monora.yml' });
class SupportAgent {
@llmCallDecorator({ purpose: 'support' })
async ask(question: string, model: string = 'gpt-4o-mini') {
return { choices: [{ message: { content: 'ok' } }] };
}
@toolCallDecorator({ toolName: 'lookup', purpose: 'support' })
async lookupAccount(accountId: string) {
return { accountId, status: 'active' };
}
@agentStepDecorator({ agentName: 'support', stepType: 'analysis', purpose: 'support' })
planNextStep(context: string) {
return `Review context: ${context}`;
}
}Enable decorators in your tsconfig.json:
{
"compilerOptions": {
"experimentalDecorators": true
}
}High-level Runtime Helpers
import { init, logEvent, toolCall, agentStep, setViolationHandler } from 'monora-ai';
init({ configPath: './monora.yml' });
setViolationHandler((violation) => {
console.error('Violation:', violation.message);
});
const fetchTool = toolCall({ toolName: 'fetch', purpose: 'integration' })(async (url: string) => {
return { ok: true, url };
});
const plan = agentStep({ agentName: 'planner', stepType: 'planning', purpose: 'analysis' })(
(goal: string) => [`step for ${goal}`]
);
logEvent('custom', { message: 'hello' }, { purpose: 'manual' });Reports & Trust Packages
The runtime automatically generates compliance reports at trace completion (default: ./monora_reports/<trace_id>/compliance.json) and emits a trust_summary event.
import { exportTrustPackage } from 'monora-ai';
const trustPackage = exportTrustPackage('trc_123', {
inputPath: 'events.jsonl',
configPath: 'monora.yml',
});Data Handling + Alerts
import { DataHandlingEngine, ViolationWebhookDispatcher } from 'monora-ai';
const dataHandling = new DataHandlingEngine({
enabled: true,
mode: 'redact',
rules: [
{ name: 'email', pattern: '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}' }
]
});
const payload = { message: 'Contact me at [email protected]' };
const { value, applied } = dataHandling.sanitizePayload('request', payload, 'confidential');
const dispatcher = new ViolationWebhookDispatcher({
endpoint: 'https://hooks.example.com/monora',
headers: { Authorization: 'Bearer TOKEN' }
});
dispatcher.start();
dispatcher.send({ event_type: 'policy_violation', message: 'Example violation' });API Documentation
Policy Engine
import { PolicyEngine } from 'monora-ai';
const engine = new PolicyEngine({
model_allowlist: ['gpt-*', 'claude-*', 'o1-*', 'gemini-*'],
model_denylist: ['deepseek:*'],
enforce: true
});
// Check a model
const violation = engine.checkModel('gpt-4o-mini', 'internal');
// Check without throwing
const isAllowed = engine.isModelAllowed('gpt-4o-mini');Model Registry
import { ModelRegistry } from 'monora-ai';
const registry = new ModelRegistry({
default_provider: 'unknown',
providers: [
{ name: 'openai', model_patterns: ['gpt-*'] },
{ name: 'anthropic', model_patterns: ['claude-*'] }
]
});
// Resolve provider
const [provider, matched] = registry.resolve('gpt-4o');
console.log(provider); // 'openai'Tracing
import { trace, traceAsync, startSpan } from 'monora-ai';
// Synchronous trace
trace('my-operation', (span) => {
span.metadata.custom = 'value';
return 'result';
});
// Async trace
await traceAsync('my-async-operation', async (span) => {
const child = startSpan('child-operation');
await doWork();
return 'result';
});Hash Chain Verification
import { verifyChain, detectTampering, detectSequenceGaps } from 'monora-ai';
// Verify chain integrity
const [isValid, error] = verifyChain(events);
if (!isValid) {
console.error('Chain verification failed:', error);
}
// Detect tampering
const tampered = detectTampering(events);
console.log('Tampered events:', tampered);
// Detect sequence gaps
const gaps = detectSequenceGaps(events);
console.log('Sequence gaps:', gaps);Data Handling
Use the data handling engine for redaction or blocking decisions (modes: redact, block, allow):
import { DataHandlingEngine } from 'monora-ai';
const engine = new DataHandlingEngine({
enabled: true,
mode: 'redact',
rules: [{ name: 'email', pattern: '[^@]+@[^@]+\\.[^@]+' }]
});
const { value, applied } = engine.sanitizePayload('request', payload, 'confidential');Webhook Alerts
Send policy violation payloads to a webhook:
import { ViolationWebhookDispatcher } from 'monora-ai';
const dispatcher = new ViolationWebhookDispatcher({
endpoint: 'https://hooks.example.com/monora',
headers: { Authorization: 'Bearer TOKEN' }
});
dispatcher.start();
dispatcher.send({ event_type: 'policy_violation', message: 'Blocked model' });{
"alerts": {
"violation_webhook": "https://hooks.example.com/monora",
"headers": { "Authorization": "Bearer YOUR_TOKEN" }
}
}Event Building and Dispatching
import { EventBuilder, EventDispatcher, StdoutSink, FileSink } from 'monora-ai';
// Create event builder
const builder = new EventBuilder({
defaults: {
service_name: 'my-service',
environment: 'production',
data_classification: 'internal',
},
});
// Build events with automatic enrichment
const event = builder.build('llm_call', {
model: 'gpt-4o',
prompt_tokens: 100,
completion_tokens: 50,
});
// Setup event dispatcher with sinks
const sinks = [
new StdoutSink('pretty'),
new FileSink('./events.jsonl', { batchSize: 100 }),
];
const dispatcher = new EventDispatcher(sinks, config);
dispatcher.start();
// Emit events (buffered and batched automatically)
dispatcher.emit(event);
// Cleanup
dispatcher.close();Sink Options
// Stdout Sink
const stdoutSink = new StdoutSink('pretty'); // or 'json'
// File Sink with rotation
const fileSink = new FileSink('./logs/events.jsonl', {
batchSize: 100,
flushIntervalSec: 5.0,
rotation: 'daily', // or 'size' or 'none'
maxSizeMb: 100,
});
// HTTPS sinks are optional; the wizard will not enable them unless you provide an endpoint.
// HTTPS Sink with retry (example only)
const httpsSink = new HttpSink(
'https://api.example.com/events',
{ 'Authorization': 'Bearer token' },
{
batchSize: 50,
timeoutSec: 10.0,
retryAttempts: 3,
backoffBaseSec: 0.5,
}
);Advanced Features
Circuit Breaker
Prevent cascading failures with circuit breaker pattern for HTTPS sinks:
import { HttpSink } from 'monora-ai';
const httpsSink = new HttpSink(
'https://api.example.com/events',
{ 'Authorization': 'Bearer token' },
{
circuitBreaker: {
enabled: true,
failure_threshold: 5,
success_threshold: 2,
reset_timeout_sec: 60,
}
}
);Telemetry/Analytics
Telemetry is enabled by default with a minimal in-memory backend (queue depth, sink errors, retry queue size). Set telemetry.backend to minimal, memory, prometheus, statsd, or none. Opt out with telemetry.backend: none (or telemetry.enabled: false).
Export metrics to Prometheus or StatsD:
import { init } from 'monora-ai';
init({
configPath: './monora.yml',
config: {
telemetry: {
enabled: true,
backend: 'prometheus', // or 'statsd' | 'memory' | 'minimal' | 'none'
prometheus: {
port: 9090,
start_server: true,
}
}
}
});
// Metrics are automatically recorded:
// - monora_events_total (by event_type)
// - monora_violations_total (by policy_type)
// - monora_queue_depth
// - monora_tokens_totalAttribution & Usage Telemetry (Opt-In)
Collect optional attribution details and anonymous usage stats with explicit opt-in. No data leaves your environment unless send_data is enabled.
import { init } from 'monora-ai';
init({
configPath: './monora.yml',
config: {
attribution: {
enabled: true,
project: {
company: 'Acme Corp',
role: 'ML Engineer',
email: '[email protected]',
source: 'npm',
use_case: 'Customer Support AI',
team_size: 'small',
business_owner: 'Jane Smith',
data_categories: ['PII']
},
telemetry: {
enabled: true,
send_data: true,
data_residency: 'us'
}
}
}
});You can also call registerProject(...) and reportUsage(...) directly.
Environment-Aware Presets
Monora can auto-select presets based on environment, or you can pick explicitly:
import { init } from 'monora-ai';
await init(); // auto-detect env (dev/poc/production)
await init({ preset: 'poc' }); // low-friction POC mode
await init({ preset: 'production' });
await init({ preset: 'strict_enterprise' });Additional presets: default_secure, experimental, audit_first, low_latency.
Migration Guidance (POC -> Production)
When you promote a POC to production, Monora will warn if you use a POC/dev preset in a production environment. You can also run the readiness checks directly:
import {
validateProductionReadiness,
checkPresetEnvironmentMismatch,
logProductionWarnings,
loadConfig,
} from 'monora-ai';
const config = loadConfig({ configPath: './monora.yml' });
let warnings = validateProductionReadiness(config);
const mismatch = checkPresetEnvironmentMismatch(
'poc',
config.defaults?.environment || 'development'
);
if (mismatch) {
warnings = [mismatch, ...warnings];
}
logProductionWarnings(warnings);Production Profiles
Ship-ready templates with clear tradeoffs:
- Audit-first:
templates/monora_audit_first.yml(strongest auditability, higher I/O and shutdown checks). - Low-latency:
templates/monora_low_latency.yml(lowest overhead, weaker audit trail and reports).
Audit Hooks (onEvent)
Capture every emitted event for external audit systems or SIEM pipelines:
import { onEvent } from 'monora-ai';
const unsubscribe = onEvent((event) => {
console.log('Audit:', event.event_type, event.event_id);
// Forward to your audit sink
});
// Later: unsubscribe();Compliance Assessment & Audit Metadata
Capture audit metadata and run compliance checks for certification workflows:
import { setAuditMetadata, runComplianceCheck, reportUsageProfile } from 'monora-ai';
setAuditMetadata({
useCaseName: 'Customer Support AI',
businessOwner: 'Jane Smith',
dataCategories: ['PII', 'customer_data'],
riskLevel: 'medium',
complianceFrameworks: ['SOC2', 'ISO42001'],
});
const result = await runComplianceCheck({
eventsPath: './monora_events.jsonl',
configPath: './monora.yml',
});
const profile = reportUsageProfile();Compliance scores are weighted by framework and control category (integrity, auditability, privacy, and governance) instead of a flat pass rate.
Standards Mapping (SOC 2 / GDPR / ISO)
Evaluate external claims against Monora evidence (event IDs, causal paths, guardrails):
npx monora-ai standards-check \
--input ./monora_events.jsonl \
--report ./SOC2_Report.pdf \
--claims ./claims.json \
--output ./standards_report.json \
--prettyGenerate a claims manifest interactively (with optional coverage preview):
npx monora-ai standards-wizard \
--standard SOC2 \
--output ./claims.json \
--input ./monora_events.jsonl \
--config ./monora.ymlStart with templates/standards_claims_template.json and customize the claims. Packaged standards templates:
- SOC 2:
templates/standards/soc2_claims.json - GDPR:
templates/standards/gdpr_claims.json - ISO 27001:
templates/standards/iso27001_claims.json - ISO 42001:
templates/standards/iso42001_claims.json
Packaged control catalogs for trust-package/control-coverage workflows:
- SOC 2:
templates/controls/soc2_control_catalog.json - GDPR:
templates/controls/gdpr_control_catalog.json - ISO 42001: supported via default control catalog resolution
Supported checks: policy_violations_max, unknown_models_max, forbidden_models_max, hash_chain_status, signatures_status, sequence_gaps_max, errors_max, config_required.
Report Ingestion + Excerpts (SOC 2 / GDPR / ISO)
Ingest a report, extract text, and attach verified excerpts to your claims manifest:
npx monora-ai standards-ingest \
--report ./SOC2_Report.pdf \
--output ./report_ingest.json \
--text-out ./SOC2_Report.txt
npx monora-ai standards-excerpt \
--ingest ./report_ingest.json \
--claims ./claims.json \
--excerpts ./excerpts.json \
--output ./claims_with_excerpts.json \
--prettyAuto-suggest and approve excerpts interactively:
npx monora-ai standards-review \
--ingest ./report_ingest.json \
--claims ./claims.json \
--output ./claims_with_excerpts.jsonOr produce suggestions as JSON:
npx monora-ai standards-suggest \
--ingest ./report_ingest.json \
--claims ./claims.json \
--output ./suggestions.json \
--prettyExample excerpts.json:
{
"excerpts": [
{
"id": "soc2-cc6-1",
"claim_ids": ["SOC2-CC6.1"],
"text": "Access to AI models is restricted and enforced by policy."
}
]
}Optional dependencies for ingestion:
- PDF text:
npm install pdf-parse - DOCX text:
npm install mammoth - OCR (PDF): install system
pdftoppm+tesseract
Tool policy enforcement (optional):
policies:
tool_allowlist: ["retrieval*", "database_*"]
tool_denylist: ["shell_*"]
enforce: truePDF Report Generation
Generate compliance PDF reports:
import { generateCompliancePdf, generateAIActPdf } from 'monora-ai';
// Generate compliance PDF
await generateCompliancePdf(complianceReport, 'compliance_report.pdf');
// Generate EU AI Act transparency PDF
await generateAIActPdf(aiActReport, 'ai_act_report.pdf');Requires optional dependency: npm install puppeteer
Next.js Middleware
Automatic W3C Trace Context propagation for Next.js:
// middleware.ts
import { withMonoraMiddleware } from 'monora-ai';
export default withMonoraMiddleware({
skipPatterns: [/^\/_next/, /^\/api\/health/],
});
export const config = {
matcher: '/(.*)',
};For API routes (Pages Router):
// pages/api/users.ts
import { withMonoraApi } from 'monora-ai';
export default withMonoraApi(async (req, res) => {
const users = await fetchUsers();
res.json(users);
});For route handlers (App Router):
// app/api/users/route.ts
import { withMonoraRoute } from 'monora-ai';
import { NextRequest, NextResponse } from 'next/server';
export const GET = withMonoraRoute(async (req: NextRequest) => {
const users = await fetchUsers();
return NextResponse.json(users);
});For Server Actions:
// app/actions.ts
'use server';
import { withMonoraAction } from 'monora-ai';
export const createUser = withMonoraAction(
async (formData: FormData) => {
const name = formData.get('name');
// Create user logic
return { success: true };
},
'createUser'
);Troubleshooting
- Validation fails due to null values: run
npx monora-ai config fix --config monora.ymlor validate withnpx monora-ai validate --mode lenient. - Telemetry backend errors: set
telemetry.backendtominimal,memory,prometheus,statsd, ornone. - Daily rotation changed filenames: use
./monora_events.latest.jsonlor setrotation: none. - CLI command not found: use
npx monora-ai <command>(ornpm exec -- monora <command>). - Console flooded with JSON: remove the stdout sink, set
format: pretty, or exportMONORA_QUIET=1. - HTTPS sink errors: only enable HTTPS sinks when you have a real endpoint; the wizard leaves them off by default.
Migration Guide (Verbose/Null-Heavy Configs)
- Run
npx monora-ai config fix --config monora.yml(creates a.bakbackup). - Optionally regenerate a minimal baseline with
npx monora-ai init --preset minimaland copy over only the sections you use. - Validate with
npx monora-ai validate --mode lenient, then switch to--mode strictfor production.
License
MIT
Support
For issues and questions, please visit: https://github.com/JamesMcDaniel04/Monora_SDK
