--dataset -n 10` and open **Studio → Matrix → IssuesTab** to inspect any tickets whose priority flips across runs (`0 < c < 10`). Tighten the `promptedEnum` wording for those exact boundary cases—then ship.
## See also
- [Schema-first contracts](/core/schemas/)
- [Golden datasets](/evaluate/golden-datasets/)
- [Multi-run stability matrices](/evaluate/stability/)
---
# Playbook B: Policy auditing, compliance & code review
URL: https://aqvenstudio.com/playbooks/auditing-and-review/
> Audit long contracts, regulatory policies, or pull requests using batched extraction (andForEach) followed by a bounded Track B Critic Loop (andCriticLoop) to eliminate false positives.
## When this playbook fits
- Contract clause risk review and regulatory compliance checks
- Pull-request, infrastructure config, or SQL security auditing
- Technical specification verification against a rulebook
## Architecture: Level 2 Batching -> Level 4 Track B Critic Loop
Auditing tasks fail in two predictable ways:
1. **Recall collapse** when a 60-page contract or 40-file PR is crammed into one prompt.
2. **False-positive fatigue** when a single prompt tries to juggle 20 nuanced policy exceptions at once.
### Step 1 — Partition deterministically (`andForEach`)
Split clauses or files with `chunkByBudget(items, { maxChars: 16_000 })` and process chunks in parallel with `containment: "collect"` + `exactCoverCheck` so every clause/file ID is accounted for.
### Step 2 — Add a bounded Track B `andCriticLoop`
Pass the batched findings as `initialOutput` into `chain.andCriticLoop`:
- The **Critic** uses independent reviewer instructions focused strictly on checking whether each high-severity finding is truly backed by the clause text and not exempted by a known policy exception.
- Set `maxIterations: 3`, `stopOnRepeat: { critic: (r) => r.issues }`, and `onStopped: "salvage"`.
- Record `critic-loop` outcome and iteration count in `evaluate.metrics`.
### Step 3 — Inspect & calibrate
Use `aqven step :audit-critic#1` and `#2` (or Studio's nested `StepsTab`) to verify that the Critic removes real false positives without silently dropping genuine risks.
## See also
- [Parallel batching (`andForEach`)](/workflows/batching/)
- [Bounded Writer–Critic loops (`andCriticLoop`)](/workflows/critic-loop/)
---
# Playbooks C & D: Multi-stage extraction, reconciliation & multimodal assembly
URL: https://aqvenstudio.com/playbooks/extraction-and-multimodal/
> Walk through the complete Slice -> Prove Each Probe -> Snap Together lifecycle—from noisy unstructured text and sharded entity deduplication to schema-driven multimodal asset classification united via chain.andWorkflow.
## When these playbooks fit
- Building verified entity/product/service catalogs from noisy web pages, logs, tickets, or multilingual customer feedback (**Playbook C**)
- Classifying and linking uploaded photos, PDFs, audio/video clips, or scanned documents against a verified catalog (**Playbook D**)
## Act 1: Slice into sequential `Input -> Output` probes
Instead of one brittle mega-prompt, decompose the business process into three sequential probes:
1. **Probe 1 — Batched Extraction (`andForEach`):**
- Pack long documents with `chunkByBudget`, isolate failures with `containment: "collect"`, and gate output integrity with `check.coverage()` + `check.setCover({ mode: "subset" })` over cited source IDs (plus `validateScheduleSlots` if extracting operating hours).
2. **Probe 2 — Sharded Entity Reconciliation (`andMerge -> andForEach / andDivergent -> resolveMergeGraph`):**
- Pre-cluster candidates with `chain.andMerge` using `aliasField` + `identifierSafeEmbeddingMatcher({ threshold: 0.92 })` so numbered or Roman-numeral siblings never falsely collide.
- For large catalogs, pack connected components into bounded context shards with `packMergeShards`, validate LLM `keep | merge | drop` decisions via `validateMergeGraph` (triggering automatic schema repair on cycles or invalid targets), resolve transitive chains with `resolveMergeGraph`, and reconcile cross-shard boundary clusters selected by `selectCrossShardGroups`.
- Prove against a human-approved Golden benchmark (`Recall`, `Precision`, `F1`, `runOnlyLinked` vs. `unlinkedRunOnly`) and `aqven stabilize` (`pass@1`, `pass^m`, `intraRunSplits`, and partition `ARI`).
3. **Probe 3 — Schema-Driven Multimodal Classification (`andAgent` + `buildInterleavedMediaMessages`):**
- Annotate input/output schemas with `mediaPath`, `mediaUrl`, `mediaBase64`, `contentText`, or `withContent` from `@aqven/patterns`. Outbound provider schemas are automatically cleaned via `sanitizeProviderJsonSchema`, large base64/binary payloads offload to content-addressed `.aqven/blobs`, and **AQVEN Studio** renders `` previews (images, HTTP Range-streamed audio/video, PDFs, Markdown/code) across Run traces, Golden diffs, and Stability heatmaps.
- Assemble multimodal turns cleanly with `buildInterleavedMediaMessages(renderedPrompt, items, options)` and feed Probe 2's verified catalog IDs as dynamic `allowedSets`.
- Keep this workflow intentionally simple (**Level 1 single `andAgent` call**) once smoke and Golden accuracy hit target—never add complex patterns where a single call already wins.
## Act 2: Snap all proven probes together (`chain.andWorkflow`)
Once Probes 1, 2, and 3 each pass their Checks, Golden, and Stability gates independently, unite `stage1Workflow`, `stage2Workflow`, and `stage3Workflow` in one composite `defineWorkflow` via `chain.andWorkflow`—preserving shared `LlmQueue` rate limits, durable step checkpoints, end-to-end relational `check.*` invariants, and full Studio DAG visibility out of the box.
## See also
- [Schema-first contracts (Multimodal schemas)](/core/schemas/)
- [Agents, prompts & inferences (`buildInterleavedMediaMessages`)](/core/agents-prompts-inferences/)
- [Composable matching & merging (`andMerge` & merge graphs)](/workflows/matching-and-merge/)
- [Checks & metrics](/evaluate/checks-and-metrics/)
- [Assembling proven probes into end-to-end workflows](/workflows/assembling-pipelines/)
---
# Packages API reference
URL: https://aqvenstudio.com/reference/
> Quick lookup of every public TypeScript package and core symbol across @aqven/patterns, @aqven/matching, @aqven/runtime, @aqven/core, @aqven/journal, and @aqven/db.
## `@aqven/patterns`
- **Agents, Prompts & Inferences:** `defineAgent(config)`, `definePrompt({ template, vars })`, `collectPromptVariables(tpl)`, `defineInference(spec)`.
- **Workflows & Chain Primitives:** `defineWorkflow({ id, name, input, result, config?, inferences, build })`, `createWorkflowChain`, `andAgent`, `andForEach`, `andMerge`, `andCriticLoop`, `andDivergent`, `andWorkflow`, `andThen`, `andMap`, `andTap`, `andWhen`, `andBranch`, `andAll`, `andRace`, `andGuardrail`, `successfulOutputs`, `requireSingleSuccess`, `outputById`.
- **Schema & Completeness Constraints:** `promptedEnum(name, entries)`, `allowedField(key)`, `withCompleteness(schema, { universe, refs })`, `exactCover({ universe, refs })`, `exactCoverCheck(...)`, `applyPartition(...)`, `nonBlankString`, `nonBlank`, `refsWithin`, `uniqueBy`, `exactlyCovers`, `verify(...)`, `ViolationsError`.
- **Chunking & Dataset Helpers:** `chunkByBudget(items, { maxChars })`, `chunkBySize(items, size)`, `prepareJsonItems({ select })`.
## `@aqven/matching`
- **Primitives:** `exactMatcher`, `normalizedMatcher`, `setMatcher`, `exactSetMatcher`, `embeddingMatcher` (deferred or bound), `customMatcher`.
- **Extractors:** `identityExtractor`, `stemExtractor`, `identifierStemExtractor`, `numbersExtractor`, `tokensExtractor`, `identifiersExtractor`, `normalizeText`, `customExtractor`.
- **Combinators:** `by`, `features` (`allOf`), `anyOf`, `weighted`, `objectMatcher`, `arrayMatcher` (`bipartite | any | all | ordered`), `withNullish` (`mismatch | skip | bothNullMatch`).
- **Grouped Namespaces:** `match.*` and `extract.*`.
- **Merge Engine:** `mergeItems`, `buildMergeResult`, `mergeComponents`, `pickRepresentatives`, `cosineSimilarity`, `bindMatcher`, `hasDeferredMatcher`, `matchingImplementationHash`.
## `@aqven/runtime`, `@aqven/core`, `@aqven/journal`, `@aqven/db`
- **Probes & Evaluation (`@aqven/runtime`):** `defineProbe`, `evaluateProbe`, `pass`, `fail`, `skip`, `coverage`, `resultsCarryInputId`, `noFailedAttempts`, `exactCoverCheck`, `errorRate`, `defineAqvenConfig`, `loadAqvenConfig`, `createProbeRuntime`, `SmokeGateError`, `LlmQueue`, `computeStability`, `computePartitionReport`, `adjustedRandIndex`, `partitionF1`.
- **Core (`@aqven/core`):** `withScope`, `currentScope`, `resolvePolicy`, `classifyError`, `PlatformError`, `contentHash`, `stableStringify`.
- **Journal & DB (`@aqven/journal`, `@aqven/db`):** `Journal`, `createJournalHooks`, `createPlatformDb`, `DEFAULT_DB_URL`, canonical domain-neutral enums (`VERDICTS`, `RUN_STATUSES`, etc.).
## See also
- [CLI command reference](/reference/cli/)
- [MCP server reference](/reference/mcp/)
- [Diagnostic & error code catalog](/reference/diagnostics/)
---
# CLI command reference
URL: https://aqvenstudio.com/reference/cli/
> Every AQVEN CLI subcommand, flag, semantic step selector, and JSON output option for authoring, running, debugging, benchmarking, and serving Studio UI or MCP.
## Invocation
Inside any AQVEN project:
```bash
npx aqven [args]
# Or via package.json script:
npm run aqven -- [args]
```
## Authoring, validation & execution
```bash
aqven probes
aqven probe validate
aqven probe test --dataset [--limit N] [--chaos N] [--keep-db]
aqven run --dataset [--smoke N | --full] [--model ] \
[--concurrency max|safe|sequential|manual:N] [--retry standard|aggressive|none] \
[--matrix ] [--variant k=v,...] [--force]
aqven resume [--step | --restart]
aqven stabilize --dataset [-n 10]
aqven stability recompute
aqven run finalize --orphaned --reason "..." [--yes] [--json]
```
## Inspection, traces & iteration history
```bash
aqven runs [--probe ] [--matrix [id]] [--status a,b] [--kind smoke|full] \
[--dataset [] [--hash ] [--since ] [--limit N] [--json]
aqven run [--trace] [--steps] [--attempts] [--checks] [--metrics] \
[--notes] [--artifacts] [--result] [--input] [--events] [--golden [--recompute]] [--json]
aqven step [--input] [--output] [--attempts] [--out ] [--json]
aqven attempt [--input] [--prompt] [--messages] [--raw] [--parsed] [--error-details] [--usage] [--out ] [--json]
aqven artifact [--out ] [--json]
aqven conclude
aqven note --run ""
aqven history
aqven definitions [--probe ] [--kind probe|agent] [--json]
aqven definition [--content | --graph] [--out ] [--json]
aqven definition diff [--json]
aqven matrices [--probe ] [--limit N] [--json]
aqven matrix [--runs] [--infra] [--report] [--items] [--json]
```
## Golden datasets, servers & storage
```bash
aqven golden list | show | verdicts | queue | ingest | build | approve | fork
aqven compare --run --golden [--version N]
aqven db info [--counts] [--json]
aqven db prune-checkpoints [--older-than 7d] [--dry-run]
aqven studio [--port 4174]
aqven ui [--port 4173]
aqven api [--port 4174]
aqven mcp [--enable-finalize]
```
---
# MCP server reference
URL: https://aqvenstudio.com/reference/mcp/
> Input contracts, payload caps, offset pagination, and byte-range content reads for all aqven_* tools exposed by aqven mcp to AI coding agents.
## Starting the MCP stdio server
```bash
npx aqven mcp [--enable-finalize]
# Or via the pre-wired package.json script:
npm run --silent mcp
```
All read-only tools return `{ schemaVersion: 1, data, page }` with a `128 KiB` summary cap and `32 KiB` maximum chunk size (`16 KiB` default) for byte-ranged content reads. List, detail, and trace tools accept `offset` (default `0`) alongside `limit` for deterministic pagination without blowing context windows.
## Read-only inspection & validation tools
| Tool | Key arguments | Purpose |
|---|---|---|
| `aqven_runs_list` | `probe?`, `matrix?`, `matrixOnly?`, `statuses?`, `kind?`, `dataset?`, `hash?`, `since?`, `limit?`, `offset?` | Filter and paginate experiment runs (`limit <= 100`, default `25`). |
| `aqven_run_get` | `runId`, `selectors?` (`steps`, `attempts`, `checks`, `metrics`, `notes`, `artifacts`, `events`), `attemptStatuses?`, `item?`, `stage?`, `eventTypes?`, `limit?`, `offset?` | Fetch structured run summary and paginated detail collections (`limit <= 100`, default `50`). |
| `aqven_run_trace` | `runId`, `includeAttempts?`, `limit?`, `offset?` | Hierarchical execution trace (`parentStepRowId`, `parentStepId`, loop `iteration`, `providerObserved`, `error.code`, `retryTrace`, `llm_fallback`; `limit <= 500`, default `200`). |
| `aqven_step_get` | `step` (`stepRowId` or `:[#]`), `runId?`, `includeAttempts?`, `previewBytes?` | Step metadata, hierarchy, attempts, retry/fallback traces, and bounded previews (`previewBytes <= 4096`, default `512`). |
| `aqven_step_content` | `step`, `runId?`, `part` (`"input" \| "output" \| "attempts"`), `offset?`, `limit?` | Bounded base64 byte-range reads of full step payloads or linked attempts with `sha256` descriptor. |
| `aqven_attempt_get` | `attemptId` | Attempt metadata, usage, cost, `providerObserved`, and body descriptors. |
| `aqven_attempt_content` | `attemptId`, `field` (`input\|prompt\|messages\|raw\|parsed\|errorDetails\|usage`), `offset?`, `limit?` | Bounded base64 byte-range reads of large attempt fields with `sha256` descriptor. |
| `aqven_artifact_get` | `runId`, `name`, `offset?`, `limit?` | Artifact descriptor; supplying `limit` also returns a bounded base64 byte range. |
| `aqven_matrices_list` | `probe?`, `limit?`, `offset?` | List stability and variant matrices (`limit <= 100`, default `25`). |
| `aqven_matrix_get` | `matrixId`, `selectors?` (`runs`, `infra`, `report`, `items`), `limit?`, `offset?` | Matrix summary and paginated stored stability report collections (never recomputes). |
| `aqven_matrix_content` | `matrixId`, `part?` (`"full" \| "report" \| "goldenReport" \| "items" \| "betweenValues"`), `byteOffset?`, `maxBytes?` | Bounded base64 byte-range reads of large stored matrix stability reports (or a specific slice) with `sha256` descriptor. |
| `aqven_probe_validate` | `probeId`, `checkGoldenSet?` | Run zero-cost static & dry-build validation (`validateProbeDefinition`) with loaded `AqvenConfig`. |
## Write-gated tool (`--enable-finalize`)
- `aqven_run_finalize_orphaned`: `{ runId, orphaned: true, reason, apply? }` — dry-run by default; requires interactive human form elicitation when `--enable-finalize` and `apply: true` are set.
---
# Diagnostic & error code catalog
URL: https://aqvenstudio.com/reference/diagnostics/
> Lookup table for static probe validate warnings and errors, deterministic probe test mock assertions, and runtime PlatformError classifications.
## 1. Static `aqven probe validate` codes (`0` LLM calls)
| Code | Severity | Meaning & fix |
|---|---|---|
| `prompt-missing-var` / `prompt-unused-var` | ERROR / WARN | Align `definePrompt` template `{{var}}` placeholders with `vars`. |
| `prompt-no-placeholders` / `prompt-malformed-braces` | WARN | Fix missing placeholders on non-empty input or malformed `{{ var }}` / `{{{var}}}` syntax. |
| `agent-contract` | ERROR | Set both non-empty `model` and `instructions` on `defineAgent`. |
| `allowed-set-mismatch` / `universe-ref-missing` | ERROR | Keep `allowedField("x")`, `allowedSets.x`, and `withCompleteness` universe aligned. |
| `prompted-enum-collision` / `prompted-enum-blank-desc` | ERROR / WARN | Resolve conflicting entries for shared `promptedEnum` names and fill blank descriptions. |
| `bare-enum-in-output` / `output-object-not-strict` / `prompted-enum-duplicated` | WARN | Replace bare `z.enum` with `promptedEnum`, add `.strict()` to output objects, and remove hand-copied enum lists from prompts. |
| `schema-json-unrepresentable` / `non-durable-workflow-schema` | ERROR / WARN | Use JSON-serializable Zod types only (avoid `z.date()`, `z.map()`, `z.set()`, `z.transform()`). |
| `unused-inference` / `duplicate-step-id` / `invalid-resume-step` / `workflow-dry-build` | WARN / ERROR | Wire declared inferences, ensure unique step IDs, verify `resume.stepId`, and fix dry-build throws. |
| `missing-embedder-resource` | ERROR | Wire `resources.embedder` in `aqven.config.ts` (or `probe.stability.embedder`) when using deferred `embeddingMatcher()`. |
| `workflow-config-invalid` / `no-dead-project-config` | ERROR / WARN | Ensure `aqven.config.ts` matches `workflow.config` and drop unconsumed config keys. |
| `critic-loop-unbounded` / `critic-same-as-writer` / `divergent-writers-check` | ERROR / WARN | Bound `andCriticLoop`, use orthogonal critic instructions, and provide >= 2 distinct writers in `andDivergent`. |
| `matcher-threshold-range` / `stability-fields` / `golden-alignment` / `evaluate-contract` | ERROR / WARN | Keep thresholds in `[0, 1]`, align `stability.fields`/`identity`/`golden`, and declare checks + one `primary: true` metric. |
## 2. Mock `aqven probe test` assertions
Runs on a deterministic mock model in an isolated temp DB and verifies:
`run-completed`, `attempts-exist`, `steps-journaled`, `non-empty-result`, `input-coverage`, `request-contains-item`, `observed-model`, `structured-output`, `retry-rows` (with `--chaos`), `checks-declared`, `prompt-deterministic`, `no-unresolved-placeholders`, `prompted-enums-delivered`, `allowed-sets-healthy`, and `result-matches-schema`.
## 3. Runtime `PlatformError` classes (`@aqven/core`)
`rate_limited`, `provider_unavailable`, `upstream_error`, `timeout`, `network`, `abort`, `schema_validation`, `parse`, `unknown`.
---
# Plain-English glossary
URL: https://aqvenstudio.com/reference/glossary/
> Clear, domain-agnostic definitions of every AQVEN term for engineers and AI agents jumping directly into any page.
## Core & evaluation terms
- **Probe (`defineProbe`):** A self-contained experimental unit combining a pure `DefinedWorkflow`, dataset adapter (`prepareInput`), evaluation `checks` & `metrics`, and optional `stability` / `golden` contracts.
- **Pure Workflow (`defineWorkflow`):** A typed, JSON-serializable DAG built on VoltAgent's `createWorkflowChain` that never reads files directly, making it replayable and composable via `chain.andWorkflow`.
- **`probe_hash`:** Content hash of all `.ts` files in a probe folder plus materialized agent configs. Any prompt, schema, model, or workflow edit automatically creates a new version without overwriting prior runs (`checks.json` sidecar edits keep `probe_hash` unchanged).
- **Inference (`defineInference`):** A declarative structured LLM call binding an agent, input schema, prompt (or multimodal `messages`), dynamic `allowedSets`, output schema, custom `validate()`, and bounded schema `repair`.
- **`promptedEnum`:** A Zod enum paired with descriptions that AQVEN automatically renders into every inference prompt as the single source of truth.
- **`allowedField` & `allowedSets`:** Dynamic per-request foreign-key constraint ensuring the model can only output IDs actually present in the current input.
- **Exact Cover (`withCompleteness` / `check.setCover({ mode: "bijection" })`):** Mathematical 1-to-1 invariant proving every input ID appears once and only once across output decisions—zero silent drops or duplicates.
- **Smoke Gate:** Safety guard requiring a completed smoke run on the exact same `probe_hash` and dataset before `--full` or `aqven stabilize` can run.
- **Golden Dataset & `golden fork`:** Human-approved evaluation benchmark compared semantically against probe runs. Never injected into inference prompts; updated only via immutable forks.
- **Recall (`matched / golden`):** Fraction of Golden reference items matched across all applicable field gates in a run.
- **Precision (`matched / (matched + runOnlyClusters)`):** Fraction of distinct run output clusters that match a Golden reference item—penalizing surplus or hallucinated extractions.
- **F1:** Harmonic mean $2 \cdot \text{Precision} \cdot \text{Recall} / (\text{Precision} + \text{Recall})$ balancing Golden coverage against precision.
- **Unlinked extra (`unlinkedRunOnly`):** A run-only output cluster not linked as the nearest candidate to any missing Golden reference item ($\text{runOnlyClusters} - \text{runOnlyLinked}$), distinguishing true extra/hallucinated items from `runOnlyLinked` near-misses that failed a specific field gate.
- **Confusion matrix (`confusionMatrices`):** Automatic Golden-label vs. predicted-label contingency table computed for categorical `exact` fields (`2..20` distinct labels) in a Golden report, pinpointing systematic class-pair misclassifications.
- **Stability Matrix (`aqven stabilize`):** `N` identical full runs of one `probe_hash` + dataset measuring infra health, structural consistency (`pass@1`, `pass^m`, strict `stable + flaky + never == total` accounting), and semantic field/partition agreement (**ARI** / pairwise **F1**).
- **`pass@1` vs. `pass^m`:** Average single-run presence rate (`pass@1`) vs. the fraction of entities stable across **all** `m` runs (`pass^m`). The gap `pass@1 - pass^m` quantifies between-run flakiness.
- **Intra-run split (`intraRunSplits`):** Within-run duplication where a single run emits two or more items that align to the same entity cluster—tracked separately from between-run flakiness so duplicate extraction bugs are never confused with cross-run variance.
- **Escape Hatch:** First-class extension hooks (`customMatcher`, `customExtractor`, `.with()`, `messages()`, custom `pass`/`fail`/`skip` checks, and native VoltAgent steps/guardrails/tools) so the library never locks you in.
]