Skip to content
Back to skills

Aqven Build

ASecurity

Builds AQVEN schemas, prompts, inferences, workflows, and custom matchers in TypeScript: promptedEnum, allowedField vs withCompleteness, evidence-gated workflow escalation (Level 1 single call to batching, merge, 2-step critic loop, and divergent), multimodal messages, and remeda transforms. Use before creating or editing schemas/, probes/<name>/*.ts, or custom matchers.

  • 5 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added December 3, 2026
ai-agentstypescriptgonode

Works with

  • cli

Security analysis

A100/100

Scanned December 5, 2026

npx -y skills add lastonoga/AQVEN --skill aqven-build --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Aqven Build?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Aqven Build
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/lastonoga-aqven-build/badge)](https://www.skillsdirectory.com/skills/lastonoga-aqven-build)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: aqven-build
description: Builds AQVEN schemas, prompts, inferences, workflows, and custom matchers in TypeScript: promptedEnum, allowedField vs withCompleteness, evidence-gated workflow escalation (Level 1 single call to batching, merge, 2-step critic loop, and divergent), multimodal messages, and remeda transforms. Use before creating or editing schemas/, probes/<name>/*.ts, or custom matchers.
---

# Building Schemas, Inferences & Minimal Workflows (`aqven-build`)

## MUST

1. **Start at Level 1 (1 LLM Call -> Inspect -> Instrument -> Improve):** Every probe starts as **one constrained `andAgent` call**. Run a small `--smoke` first, inspect the raw emitted items for duplicates, child bloat, field echo, verbosity, and unstable boundaries, and **lock in `probe.evaluate` metrics (`$0` `aqven evaluate recompute`) BEFORE tuning prompts or adding workflow steps**. Never build multi-agent loops, splitters, or divergent ensembles until instrumented trace evidence proves a single call hit a real ceiling.
2. **Derive deterministic facts in TypeScript (`remeda`), never in the LLM:** Never ask the model to compute character offsets, array lengths, sums, occurrence ordinals, or copy input text verbatim. Ask the model only for semantic choices + source IDs; compute everything else with `R.indexBy`, `R.groupBy`, `R.unique`, `R.countBy`, `R.sumBy`.
3. **Workflows never perform file or network I/O:** Dataset loading/slicing belongs exclusively in `probe.prepareInput`. `defineWorkflow` takes pure JSON-serializable input and returns pure data so proven steps compose directly in production.
4. **Declare enums once with `promptedEnum`:** Never hand-copy enum lists or descriptions into prompt templates — AQVEN injects `promptedEnum` values + descriptions automatically.
5. **Every output `z.object(...)` is `.strict()` and flat by default:** Only require fields decidable from the step's actual input; include explicit `"other"` or `"cannot_tell"` enum states instead of forcing guesses.

---

## Probe Folder Anatomy

Keep every probe folder self-contained so AQVEN hashes revisions deterministically:

```text
probes/<probe-name>/
  schema.ts       # Input/output Zod schemas, promptedEnum, allowedField (single source of truth; types via z.infer)
  prompt.ts       # definePrompt({ template, vars }) — compile-time {{var}} checked
  inferences.ts   # 1-arg defineInference({ agent, input, prompt, messages?, allowedSets?, output, validate? })
  workflow.ts     # defineWorkflow({ id, name, input, result, config?, inferences, build })
  probe.ts        # export const probe = defineProbe({ workflow, prepareInput, stability, golden?, evaluate })
```

---

## Schema Contract Primitives (`@aqven/patterns`)

Know the exact invariant each primitive enforces — do not confuse or duplicate them:

| Primitive | What it guarantees | Typical usage |
|---|---|---|
| `promptedEnum(name, entries)` | Closed vocabulary with auto-injected prompt definitions. | `category: categoryEnum.schema` (include `"other"` / `"cannot_tell"` when real inputs vary). |
| `allowedField("itemId")` | **Subset (`output IDs ⊆ input IDs`)**: zero hallucinated/invented IDs. Already returns a `z.ZodString` (do **not** append `.pipe(z.string())`). | Paired with `allowedSets: { itemId: (input) => input.items.map((x) => x.id) }` on `defineInference`. |
| `withCompleteness(schema, { universe, refs })` | **Exact 1-to-1 cover (`output IDs = input IDs`)**: zero silent drops AND zero duplicates. | Wrap `defineInference({ output: withCompleteness(...) })` whenever every input item must be answered once. |
| `nonBlankString` | Rejects empty or whitespace-only strings. | Summaries, rationales, extracted labels. |
| `mediaPath(mime, opts?)` / `mediaUrl(mime, opts?)` / `mediaBase64(mime, opts?)` | Attaches `x-content` multimodal metadata (`image/*`, `video/*`, `audio/*`, `application/pdf`; `timeRange?: true` for `#t=start,end` / `#page=N`). `mediaBase64` automatically offloads payloads to `.aqven/blobs` on journal write! | Dataset/input media fields; omit `description` on fields passed to `renderSchemaFormat` when preserving existing prompt text. |
| `contentText(kind, opts?)` / `withContent(schema, meta)` | Marks `"markdown" | "code" | "plain"` strings (`language?`, `allowEmpty?`) or attaches `WithContentMeta` to existing `allowedField` / `z.object` schemas. | Rich Studio rendering; provider-strict JSON Schema sanitization strips `x-*` / unsupported keywords automatically before LLM calls. |
| `validate: ({ output, input }) => issues` | Cross-field deterministic business invariants triggering bounded auto-repair on failure. | Checking non-overlapping spans, `validateMergeGraph(output.decisions, spec)`, or evidence conservation. |

> **State-space caution:** Huge arrays × huge enums (`maxItems: 100` × 60 enum values) can exceed provider grammar limits (`OUTPUT_SCHEMA_REJECTED`). Keep enums sized to the real downstream decision (~5–15 values) or batch large `input_scaling` corpora via `andForEach`.

### JSON Schema Physics Checklist (Mandatory Before Saving `schema.ts`)
1. **`evidence` / `rationale` BEFORE `label` / `decision`:** Constrained decoding emits keys strictly left-to-right. Putting `label` first forces a zero-shot guess on token 1 and turns `rationale` into post-hoc rationalization (3–9 pp "Format Tax").
2. **Model the 5 states of an answer (`present`, `absent`, `cannot_tell`, `other`):** Never require a non-nullable field when the input may omit it (causes forced hallucination; use `.nullable()`). Separate `absent` from `cannot_tell` (illegible/cut-off input) and add `"other"` for real-world out-of-scope inputs. Ask about content directly — never *"Can you read this?"*.
3. **Depth & width ceilings:** Keep nesting `<= 2–3` levels (`4+` levels drop accuracy by `17–30+ pp`) and `<= 20` fields per step; build nested trees in TypeScript (`remeda`) after parsing.
4. **Empty-array (`[]`) permission:** Grammar automata bias models against closing `[]` immediately, causing phantom extractions on clean inputs. Always state *"Return `[]` when zero items match"* in `.describe(...)`.
5. **Portable unions:** Use `z.discriminatedUnion("<discriminator>", [...])` (e.g. `"type"` or `"action"`) with `z.literal(...)` tags (`anyOf` + discriminator; bare `oneOf` fails on OpenAI strict mode and is ignored by Gemini).
6. **Final vs Intermediate schemas:** Minimal fields apply to *final* outputs. When Step A feeds Step B, include the discriminating fields that separate Step B's confusion pairs (pilot on ~10 cases: fields constant on `>80%` of cases carry no signal).

---

## The Evidence-Gated Escalation Ladder

**When to split steps (Lusser's Law: $0.95^5 \approx 77\%$, $0.95^{10} \approx 59\%$):** Split ONLY where uncertainty type changes (extraction -> classification -> judgment), where a deterministic gate checks the intermediate artifact, or where error cost / model tier changes. Never chain `> 5–7` sequential LLM steps without hard gates; do not split short homogeneous tasks that benefit from shared context.

Offer complex shapes as **options backed by an experiment** (and compare multi-call shapes against an **equal-budget baseline**), never as a default:

| Level | Combinator | Add ONLY when trace evidence shows… | Key rules & empirical bounds |
|---|---|---|---|
| **L1 (Default)** | `chain.andAgent({ id, inference, input?, map? })` | Baseline for ~80% of tasks. Always build and measure L1 first. | Use `andAgent` (there is no `andInference`). Keep deterministic mapping inside `map`. |
| **L2 (Scale)** | `chain.andForEach({ id, items, concurrency?, step, map })` | Output scales with input (`input_scaling`) and long batches suffer context rot, drop tail items, or hit `max_tokens`. | Batch size bounds: **`b ≈ 4–16`** for simple extraction/triage, **`b < 8`** for reasoning-heavy items. Reconcile cross-batch duplicates at L3 if needed. |
| **L3 (Reconcile)** | `chain.andMerge({ items?, fields \| strategy, clustering?, output? })` | Parallel batches (L2) or divergent writers (L4) produce duplicate/overlapping semantic entities. | Use `@aqven/matching` (`identifierSafeEmbeddingMatcher`, `aliasField`) and `@aqven/patterns` graph/shard helpers (`packMergeShards`, `validateMergeGraph`, `resolveMergeGraph`, `selectCrossShardGroups`). Never deduplicate LLM concepts by naive string equality! |
| **L4a (Verify)** | `chain.andCriticLoop({ writer, critic, shouldStop, finalize, ... })` | Rubric violations persist after tightening `promptedEnum` & `validate()`, **AND** an external signal or asymmetric (prefer cross-family) critic exists. | **Intrinsic self-critique (same model + same context, no external check) degrades accuracy (ICLR 2024)!** Use **2 roles ONLY (`writer` + `critic`)**, localize errors by item/span, cap at **`2–3` iterations** (>80% of gain occurs in rounds 1–2), enforce **Scope-Lock on rounds 2+** (do not reverse accepted round-1 edits or expand scope to prevent flip-flop), and keep critic context compact (avoid duplicating raw upstream excerpts that trigger context rot). |
| **L4b (Recall)** | `chain.andDivergent({ writers, ... })` -> `andMerge` | Single model family consistently misses hard recall items or exhibits high variance. | Diversity rank: **different model families / distinct prompt angles `>>` temperature alone**. Reduces *variance*, never systematic prompt *bias*; keep `N = 2–5` writers. |

---

## Multimodal Inputs, L3 Reconciliation & Custom Matchers

- **Multimodal Messages & Media Schemas (`@aqven/patterns`):**
  - Annotate media fields in `schema.ts` with `mediaPath`, `mediaUrl`, `mediaBase64` (auto-offloaded to `.aqven/blobs`), `contentText`, or `withContent` — AQVEN sanitizes `x-content` / non-portable JSON Schema keys automatically for strict provider grammars.
  - Assemble attachments in `messages.ts` / `defineInference({ messages })` via `buildInterleavedMediaMessages(renderedPrompt, items, { label?, data | src, mediaType, filename?, epilogue? } | { toParts, epilogue? })`, which interleaves per-item text headers with `ImagePart` (`image/*`) or `FilePart` (PDF, audio, video). Ensure prompt wording matches the exact number of attached items.
- **L3 Graph, Shard & Schedule Primitives (`@aqven/patterns`):**
  - **Directed `keep | merge | drop` graphs:** Validate in `defineInference({ validate })` with `validateMergeGraph(decisions, spec)` (catches cycles, self-merges, missing universe IDs, and merges into `drop`ped nodes for auto-repair), then materialize roots/members deterministically with `resolveMergeGraph(decisions, spec)`.
  - **Bounded merge sharding:** `packMergeShards(mergeResult, items, { idOf, maxShardSize, sortKey? })` packs connected components via First-Fit with an exact-cover assertion; `selectCrossShardGroups(mergeResult, { shardOf, idOf? })` isolates clusters spanning `>= 2` shards.
  - **Deterministic aggregation:** `uniqueByKey(lists, keyOf)` (collision-free `stableStringify` dedup) and `pickMostFrequent(candidates)` (frequency/weight winner with deterministic tie-breaking).
- **Matchers & Alias Rules (`@aqven/matching`):**
  - Use `identifierSafeEmbeddingMatcher({ threshold: 0.85, numbersOnly?, nullish? })` whenever labels may carry numbers, codes, or Roman numerals, and `aliasField({ primary, aliases, matcher?, nullish? })` to compare `[primary, ...aliases]` via best-pair (`mode: "any"`).
  - Any custom domain/modality comparison (CLIP image embeddings, perceptual hashes, unit normalizers) plugs into both `andMerge` and `probe.stability.fields` via `by(extractor, matcher)` / `features({ ... })`. Deferred `embeddingMatcher()` binds `resources.embedder` from `aqven.config.ts`.

## Chaining Proven Steps into Production

Once Probe A and Probe B each pass their production gates independently, import their `workflow` exports directly (`createWorkflowChain` + `.andWorkflow(stepAWorkflow)` / `.andThen(...)`) — **never copy-paste or rewrite tested probe logic into a separate "production" codebase**.

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.