OR Key
drop another .md file to compare - side-by-side diff against voice

voice

Turns your text into natural, expressive spoken audio.
description: "Triggers on prompt mention of 'voice'."
personal 2 files

What it does for you

Turns your text into natural, expressive spoken audio.

What it produces

A recent result, so you can see the kind of work it returns.

loading…

How to get it

These run inside the Snappy workspace. Want this working in your business? I set skills like this up with you, in one focused week.

Work with me
For developers how this skill is built, graded, and how it runs

at a glance- the short version

eval modeauto-shape
categorySystem
stages4
dependsopenrouter, elevenlabs

what's inside - the parts that make up a skill 3/4 present

A skill is just a few plain-text files. Only the main one is required. The rest are optional, added as the work needs them. This is what the skill is made of; how it runs is just below.

The skill
state/skills/voice/SKILL.md present
the skill itself, in plain text
The main file. It says what the skill is and lays out the steps in plain English.
Code
state/lib/voice.ts present
code the skill can run
Reusable code this skill can call when it needs to.
Scripts
state/bin/voice/ not present
helper scripts
Optional. Added when a skill has a few commands to run.
Loader
state/skills/voice/AGENTS.md present
what the AI loads on the fly
Loaded automatically the moment this skill is needed. Kept short on purpose.

how it's graded - what counts as a good run 5 criteria · 4 deterministic · 1 judge

Each row is one thing a good run has to get right. deterministic means a quick check decides, pass or fail. judge means the AI reads the result and rates it. Grading each piece on its own (instead of one overall score) shows exactly where a run fell short, so the fix is obvious.

name
kind
check
api_creds_present
deterministic
ELEVENLABS_API_KEY and OPENROUTER_API_KEY are present in .env.cache; neither is empty or malformed.
enhancement_callable
deterministic
Gemini-3-Flash enhancement endpoint responds when enhance=true; returns tagged text with [happy], [sad], [pause], etc.
synthesis_completes
deterministic
ElevenLabs v3 synthesis with eleven_v3 model completes; response is valid audio/mpeg stream (not empty, not HTML error).
audio_quality_acceptable
judge
Synthesized audio plays without artifacts; tone (professional|sultry|hype|calm) is perceptible; enhancement makes audio noticeably more expressive than raw text.
logging_accurate
deterministic
state/log/voice-speak.ndjson row is written with ok=true, durationMs, bytes, enhanced flag; all values are correct and in plausible ranges.

how it runs - the shared frame every skill uses 2/5 present

Every skill runs the same way. One part does the work, a separate part checks it, and a short loader hands the AI exactly what it needs for the job. Anything this skill doesn't use shows a one-line note saying why, on purpose, not by accident.

makes the work The worker
inferred
ELEVENLABS_API_KEY=sk_... from a command
No worker named, so the first command in the skill is treated as the worker.
checks the work The reviewer
inferred
shape gate an automatic check
The check is an automatic pass or fail on the shape of the result, run separately from the work itself.
frame
learns Self-correction
not present

This skill doesn't fix its own gaps yet.

tidies up Background fixes
present
queued for rewrite runs in the background
Bigger fixes that can't be made on the spot get queued and rewritten in the background later.
remembers Run history
present
state/log/evals.ndjson auto-shape runs
Every run is written down here, so the next time this skill is used it already knows how the last runs went.
Critical rules the things this skill must not get wrong
  1. Compose any voice UI through the current OpenUI path. Persist as artifact lang_body only when reusable.
  2. TTS calls bill per character. POST http://127.0.0.1:3147/voice/speak hits
  3. state/lib/voice.ts is the tone-gate / citation-gate library - NOT the
  4. Snappy OS mic input must use the local head-screen proxy
  5. Snappy OS voice UX mirrors Codex: the mic sits immediately beside Send;
  6. Without OPENROUTER_API_KEY the enhancer silently skips and the audio

what it has learned - fixes written back in over time sample

When a run hits something this skill didn't handle, the fix gets written back into the skill so it doesn't happen again. FIXED means it was corrected on the spot. LOGGED means it's queued for a bigger rewrite. Either way, the skill gets a little better and never makes the same mistake twice.

  1. Loading feedback rows…

how the work flows- step by step

inputs openrouterelevenlabs
1 control
Scope - no side effects
Decide tone + length based on the message's intent, not just content:
what this step does
Decide tone + length based on the message's intent, not just content: - **professional** for status updates, build results, neutral notifications - **sultry** for one-off flirty/atmospheric moments (use sparingly) - **hype** for shipping news, deploy success, big wins - **calm** for narration, recap, end-of-session summary Length: - **minimal** - 1-3 words ("Done.") - **short** - under 10 words - **normal** - 1-2 sentences (default) - **verbose** - 2-3 sentences, conversation
2 stage
Gate
Two creds must exist in .env.cache:
ELEVENLABS_API_KEY=sk_...
what this step does
Two creds must exist in .env.cache: Without ELEVENLABS_API_KEY → 503. Without OPENROUTER_API_KEY → enhancement silently skips, raw text goes to ElevenLabs (still works, just sounds flatter).
3 stage
Act
```bash
curl -sS -X POST http://127.0.0.1:3147/voice/speak \
what this step does
In the snappy-os SwiftUI app: DataClient.voiceSpeak(text:) POSTs and returns the bytes. SpeechPlayer.play(_:) hands them to AVAudioPlayer with a tmp-file fallback for MP3 ADTS streams the in-memory init refuses.
4 generator
Log + eval
The endpoint writes one row per call to state/log/voice-speak.ndjson:
what this step does
The endpoint writes one row per call to state/log/voice-speak.ndjson: Score 1.0 if enhanced: true AND bytes > 5000 (real audio). Score 0.5 if enhanced: false (raw fallback fired). Score 0.0 if ok: false.

SKILL.md- the skill, written out in plain English

voice

Three-layer pipeline; the realism is from layer 2:

raw text → Gemini-3-Flash (tag enhancer) → ElevenLabs eleven_v3 → audio/mpeg

Without enhancement you get flat TTS. Without eleven_v3 the audio tags get spoken aloud as "open bracket happy close bracket" instead of being interpreted.

Rubric

criteria:
  - name: api_creds_present
    kind: deterministic
    check: "ELEVENLABS_API_KEY and OPENROUTER_API_KEY are present in .env.cache; neither is empty or malformed."
  - name: enhancement_callable
    kind: deterministic
    check: "Gemini-3-Flash enhancement endpoint responds when enhance=true; returns tagged text with [happy], [sad], [pause], etc."
  - name: synthesis_completes
    kind: deterministic
    check: "ElevenLabs v3 synthesis with eleven_v3 model completes; response is valid audio/mpeg stream (not empty, not HTML error)."
  - name: audio_quality_acceptable
    kind: judge
    check: "Synthesized audio plays without artifacts; tone (professional|sultry|hype|calm) is perceptible; enhancement makes audio noticeably more expressive than raw text."
  - name: logging_accurate
    kind: deterministic
    check: "state/log/voice-speak.ndjson row is written with ok=true, durationMs, bytes, enhanced flag; all values are correct and in plausible ranges."

Ported from Robert's Sloane × ElevenLabs recipe. The recipe is the long-form reference; this skill is the per-turn loader.

Endpoint

POST http://127.0.0.1:3147/voice/speak
Body: {
  "text": "raw text",
  "voiceId"?: "cgSgspJ2msm6clMCkdW9",   // default: Jessica (warm British)
  "modelId"?: "eleven_v3",              // default: eleven_v3 (tags work)
  "tone"?: "professional",              // professional|sultry|hype|calm
  "length"?: "normal",                  // minimal|short|normal|verbose
  "enhance"?: true,                     // default true; false bypasses Gemini
  "voiceSettings"?: { ... }             // overrides tone preset if given
}
Response: audio/mpeg
Headers: x-snappy-voice-enhanced: 0|1, x-snappy-voice-tone, x-snappy-voice-id

Steps

1. Scope - no side effects

Decide tone + length based on the message's intent, not just content:

  • professional for status updates, build results, neutral notifications
  • sultry for one-off flirty/atmospheric moments (use sparingly)
  • hype for shipping news, deploy success, big wins
  • calm for narration, recap, end-of-session summary

Length:

  • minimal - 1-3 words ("Done.")
  • short - under 10 words
  • normal - 1-2 sentences (default)
  • verbose - 2-3 sentences, conversational

2. Gate

Two creds must exist in .env.cache:

ELEVENLABS_API_KEY=sk_...
OPENROUTER_API_KEY=sk-or-v1-...   # for the enhancement step

Without ELEVENLABS_API_KEY → 503. Without OPENROUTER_API_KEY → enhancement silently skips, raw text goes to ElevenLabs (still works, just sounds flatter).

3. Act

curl -sS -X POST http://127.0.0.1:3147/voice/speak \
  -H "Content-Type: application/json" \
  -d '{"text":"the build is green","tone":"professional","length":"short"}' \
  -o /tmp/out.mp3 && afplay /tmp/out.mp3

In the snappy-os SwiftUI app: DataClient.voiceSpeak(text:) POSTs and returns the bytes. SpeechPlayer.play(_:) hands them to AVAudioPlayer with a tmp-file fallback for MP3 ADTS streams the in-memory init refuses.

4. Log + eval

The endpoint writes one row per call to state/log/voice-speak.ndjson:

{
  "ts": "2026-04-25T22:57:24Z",
  "voiceId": "cgSgspJ2msm6clMCkdW9",
  "modelId": "eleven_v3",
  "tone": "professional",
  "length": "short",
  "enhanced": true,
  "raw_chars": 41,
  "chars": 65,
  "durationMs": 3564,
  "bytes": 88233,
  "ok": true
}

Score 1.0 if enhanced: true AND bytes > 5000 (real audio). Score 0.5 if enhanced: false (raw fallback fired). Score 0.0 if ok: false.

Voice IDs (recipe §3)

SlugVoice IDCharacter
jessica (default)cgSgspJ2msm6clMCkdW9Warm, British
rachel21m00Tcm4TlvDq8ikWAMClear, professional
domiAZnzlk1XvdvUeBnXmlldConfident, assertive
bellaEXAVITQu4vr4xnSDxMaLSoft, gentle
charlotteXB0fDUnXU5powFXDhCwaSeductive, smooth
serenapMsXgVXv3BLzUgSXRplESoft, pleasant
graceoWAxZDx7w5VEj9dCyTzzSouthern, warm

Browse more: https://elevenlabs.io/voice-library

Tone presets (recipe §2)

Tonestabilitystylesimilarity_boost
professional0.50.00.75
sultry0.00.40.85
hype0.00.50.75
calm1.00.00.7

use_speaker_boost: true always.

Audio tags (recipe §5)

Use 1-3 emotion tags + at most 1 non-verbal sound + sparing timing tags.

Emotion: [happy] [sad] [angry] [excited] [confident] [playful] [serious] [whispered] [tender] [cheerful] [concerned] [amused]

Timing: [beat] (comedy), [dramatic pause] (tension), [quick], [slow]

Non-verbal: [sigh] [chuckle] [laughs] [satisfied sigh]

AVOID: environmental tags [rain] [thunder] [footsteps] - cause artifacts.

Known Pitfalls

  • Tags spoken aloud = wrong model. Verify modelId: "eleven_v3".
  • Voice sounds flat = enhancer skipped. Check x-snappy-voice-enhanced: 1

in response headers; check OPENROUTER_API_KEY is in .env.cache.

  • Sultry/hype sounds same as professional = stability not lowered.

TONE_PRESETS in the server handle this, but caller-supplied voiceSettings overrides - don't pass voiceSettings unless you mean it.

  • No audio plays in the macOS shell = AVAudioPlayer choking on MP3 ADTS.

SpeechPlayer's tmp-file fallback handles this - verify the tmp file gets written.

  • Enhancement adds latency (~3s round trip vs ~1s raw). For

status-bar-style notifications use enhance: false.

Self-Test

An agent reading this should correctly:

  1. [ ] Default to Jessica voice + eleven_v3 model + professional tone
  2. [ ] Pick tone based on message intent, not just content
  3. [ ] Bypass enhancement (enhance: false) when latency matters more than realism
  4. [ ] Read the response header x-snappy-voice-enhanced to verify enhancement fired

Self-report

If this loader fell short, edit this SKILL.md or the AGENTS.md inline with the rule. Found a gap - edit this file.

AGENTS.md- what the AI loads when this skill comes up

voice - loader

Per-turn rules for the voice skill. Full reference: state/skills/voice/SKILL.md. Do not skip these.

Critical Rules

  • Compose any voice UI through the current OpenUI path. Persist as artifact lang_body only when reusable.
  • TTS calls bill per character. POST http://127.0.0.1:3147/voice/speak hits

ElevenLabs (and OpenRouter for the enhancer). For scope-only / dry-run, do NOT invoke the endpoint - run a shape check instead (verify SKILL.md frontmatter, AGENTS.md, state/lib/voice.ts import) and score with eval_mode=shape. Real audio only when the user explicitly confirms apply: true.

  • state/lib/voice.ts is the tone-gate / citation-gate library - NOT the

TTS client. Don't expect a speak() export; use checkTone() / requireCitations(). The TTS pipeline lives behind the local HTTP server.

  • Snappy OS mic input must use the local head-screen proxy

POST /voice/transcribe for batch fallback STT. Do NOT call ElevenLabs Speech-to-Text directly from the WebView; browser CORS and exposed credentials make that path fragile. Live interim words should come from browser SpeechRecognition when available, with /voice/transcribe only as the fallback after stop.

  • Snappy OS voice UX mirrors Codex: the mic sits immediately beside Send;

recording changes the mic into a square stop control; clicking the square only stops and leaves editable transcript text in the composer. Clicking Send while recording stops/transcribes and sends once. Do not auto-send from the square-stop path, and do not add separate dot/waveform/timer chrome.

  • Without OPENROUTER_API_KEY the enhancer silently skips and the audio

sounds flat. Verify the response header x-snappy-voice-enhanced: 1 whenever realism matters.

Commands

This is the canonical machine-parseable Commands table (CONSTITUTION #2: prose is executable). The server reads this same table at startup (state/lib/skill-verbs.ts) and routes POST /skill/<slug>/<verb> through it. Keep header columns + verb syntax exact.

verbinvokeinputoutput
speakPOST /voice/speak-and-store{text, voiceId?, tone?, length?, enhance?}audio

Notes:

  • speak proxies to the legacy POST /voice/speak-and-store route during the

Phase 1 migration. Phase 2 will move the body into a script the generic dispatcher spawns directly; the verb name + input shape stay the same.

  • Tone-gate lib is state/lib/voice.ts (checkTone, requireCitations) -

pure, no network, importable for shape checks; not a verb.

  • Defaults: voiceId=Jessica (cgSgspJ2msm6clMCkdW9), modelId=eleven_v3,

tone=professional, enhance=true.

  • Eval log: state/log/evals.ndjson (skill: "voice"); per-call

telemetry also at state/log/voice-speak.ndjson.

Self-Test

An agent reading this should correctly:

  1. [ ] Know which lib/bin artifact backs this skill (or that it is prose-only)
  2. [ ] Know what to write to state/log/evals.ndjson after invoking
  3. [ ] Know the eval mode (auto / shape / manual) from the .md frontmatter

Found a gap? Edit this file. <!-- footer-injection-point -->

api.ts- the code it can call

#!/usr/bin/env npx tsx
/**
 * state/lib/voice.ts -- Tone gate and citation gate for snappy-os.
 *
 * checkTone(text) -- banned phrases + rhythm-slop regex + em-dash gate.
 * requireCitations(draft) -- forces mining pods to stitch verbatim with
 *   [source: mtg ~mm:ss] tags and wrap connective tissue in
 *   <connective>...</connective>. <=35% connective ratio.
 *
 * FlowProfile, FLOW_PROFILES, and checkFlow are local so this public voice
 * gate does not depend on a private positioning skill.
 */

const BANNED_PHRASES: string[] = [
  "10x faster",
  "10x developer",
  "100x speed",
  "in minutes",
  "the operating system for",
  "the X for Y",
  "without the Z",
  "before you Q",
  "at the intersection of",
  "one-stop shop",
  "revolutionize",
  "revolutionary",
  "transform",
  "unleash",
  "unlock",
  "unlock the power of",
  "supercharge",
  "empower",
  "empowering",
  "leverage",
  "synergy",
  "game changer",
  "game-changing",
  "ultimate",
  "cutting edge",
  "bleeding edge",
  "next-gen",
  "next generation",
  "seamless",
  "seamlessly",
  "effortless",
  "effortlessly",
  "AI-powered",
  "AI-native",
  "agentic-first",
  "founder-led",
  "ship-ready",
  "vibe coding",
  "Snappy is",
  "feel confident",
  "feel in control",
  "feel unstuck",
  "my stack is opinionated",
  "i dog-food everything",
  "clear boxes, not black boxes",
  "delve",
  "showcase",
  "noteworthy",
  "multifaceted",
  "tapestry",
  "beacon",
  "meticulous",
  "intricate",
  "commendable",
  "paramount",
  "commence",
  "utilize",
  "robust",
  "streamline",
  "harness",
  "illuminate",
  "facilitate",
  "bolster",
  "underscore",
  "pivotal",
  "realm",
  "foster",
  "landscape",
  "paradigm",
  "ecosystem",
  "spearhead",
  "groundbreaking",
  "transformative",
  "game-changer",
  "elevate",
  "deep dive",
  "unpack",
  "in today's fast-paced",
  "it's worth noting",
  "here's where it gets interesting",
  "here's the kicker",
  "let's break this down",
  "let's unpack",
  "the truth is simple",
  "think of it as",
  "imagine a world where",
  "in conclusion",
  "to sum up",
  "studies show",
  "experts say",
  "it goes without saying",
  "importantly,",
  "interestingly,",
  "notably,",
  "furthermore,",
  "moreover,",
  "additionally,",
  "despite its challenges",
  "i'm excited to announce",
  "without further ado",
  "agree?",
  "thoughts?",
  "at its core",
  "whether you're a",
  "whether you're an",
  "the catch?",
  "your ideas, ai's polish",
];

const RHYTHM_PATTERNS: Array<[RegExp, string]> = [
  [/\bnot\s+\w+,\s+not\s+\w+\s*[—-]/i, "Not X, not Y — Z (rhetorical negation trifecta)"],
  [
    /\bif\s+you're\s+(?:a|an)\s+\w+\s+(?:founder|dev|team|builder|engineer)[^.]*stuck\s+between\b/i,
    "'If you're a [X] stuck between' (AI sales opener)",
  ],
  [
    /\bon\s+your\s+repo,\s+on\s+your\s+\w+\s+problem\b/i,
    "'on your repo, on your real problem' (parallel-clause slop)",
  ],
  [/—\s+that's\s+how\s+you\b/i, "'— that's how you' (AI didactic dash)"],
  [/\bnever\s+\w+[,.].{0,40}\balways\b/i, "Never X, always Y (false-symmetry rule)"],
  [
    /\bthe\s+real\s+\w+\s+is\s+(?:simple|that|this)\b/i,
    "'The real [X] is [reveal]' (AI reveal framing)",
  ],
  [/\bhere's\s+the\s+thing\b/i, "'Here's the thing' (AI pivot)"],
  [/\bat\s+the\s+end\s+of\s+the\s+day\b/i, "'At the end of the day' (filler)"],
  [/—/, "em dash — dead AI tell (voice: use commas/periods or restructure)"],
  [/–/, "en dash — dead AI tell (voice: use commas/periods or restructure)"],
  [
    /\b(agree|thoughts|right\?|make sense)\?\s*$/im,
    "engagement-bait closer ('Agree?' / 'Thoughts?'): LinkedIn slop tell",
  ],
  [
    /\bwhether you're (?:a|an)\s+\w+[,\s]+(?:a|an)?\s*\w+[,\s]+or\s+(?:a|an)?\s*\w+/i,
    "'Whether you're X, Y, or Z' template opener",
  ],
  [
    /\b\d{2,}\+?(?:\s+[\w-]+){0,3}\s+(endpoints|tools|clients|projects|integrations|playbooks|skills|apis|deploys|agents|workflows|automations)\b/i,
    "author-scoreboard count: numbers-about-author are decoys",
  ],
  [
    /(?:^|\n)\s*(?:the catch|the twist|the kicker|the surprise|the result|the reality)\?\s*\n/i,
    "mini-question intro fragment",
  ],
  [
    /(?:^|\n)\s*(?:I was |I noticed |Last (?:week|month|year) I |I had a session |I caught an? |I watched an? |I spent |I realized )/i,
    "personal story opener: lead with insight, not diary",
  ],
];

export function getBannedPhrases(): string[] {
  return [...BANNED_PHRASES];
}

export function checkTone(text: string): { pass: boolean; violations: string[] } {
  const cleaned = text
    .replace(/\[source:[^\]]*\]/gi, "")
    .replace(/<connective>[\s\S]*?<\/connective>/gi, "");
  const lower = cleaned.toLowerCase();
  const violations: string[] = [];

  for (const phrase of BANNED_PHRASES) {
    if (lower.includes(phrase.toLowerCase())) violations.push(phrase);
  }

  const nxMatch = text.match(/\b\d+x\b/gi);
  if (nxMatch) {
    for (const m of nxMatch) {
      if (!violations.includes(m)) violations.push(`${m} (Nx claim)`);
    }
  }

  for (const [re, label] of RHYTHM_PATTERNS) {
    if (re.test(text)) violations.push(label);
  }

  return { pass: violations.length === 0, violations };
}

// Canonical Voice rules block, model-facing. Imported by every system-prompt
// builder so the rules never drift across copies. Robert / Genius BUG-02
// 2026-05-19: was duplicated in conversational-prompt.ts, dispatch.ts, and
// system-prompt-builder.ts with slightly different wording. One source.
//
// BEHAVIORAL rules only (2026-06-10 reminder-density audit). The MECHANICAL
// bans (em-dashes, exclamation points - and the callers' emoji lines) were
// deleted from the prompt: writeAgUI normalizes every streamed
// TEXT_MESSAGE_CONTENT and TOOL_CALL_ARGS delta deterministically at the SSE
// boundary, so prompt rules teaching them were pure cognitive weight - the
// in-app AI named the reminder-stack density as real friction. A rule a
// deterministic boundary enforces does not belong in the prompt. Behavioral
// rules stay: no boundary can rewrite hype into earnestness.
export const VOICE_RULES_LINES: string[] = [
  "- Never use hype words: supercharge, powerful, blazing, unleash, seamlessly, effortlessly.",
];

export function getToneGuide(): {
  oneLiner: string;
  shortTagline: string;
  longTagline: string;
  tuningFork: string[];
  principles: string[];
  doRules: string[];
  dontRules: string[];
} {
  return {
    oneLiner: "Snappy helps developers build and control agents that ship real systems.",
    shortTagline: "We build businesses, not demos.",
    longTagline:
      "Faster than vibe coding. Private AI tools to ship real systems while others prompt. We build businesses, not demos.",
    tuningFork: [
      "You built it. You're stuck. Let's fix that, live on your screen.",
      "We open your codebase together, map the architecture, and start fixing what's blocking you.",
      "I burn the hours so you don't.",
      "Build and control agents to get huge results.",
    ],
    principles: [
      "Lead with what happens, not what Snappy is.",
      "First person. 'I' by default. 'We' only when literally true.",
      "Builder-to-builder. Assume the reader has shipped real software.",
      "Earn every adjective. If you can't defend it on a call, delete it.",
      "The four reference sentences are the tuning fork.",
    ],
    doRules: [
      "Write first person. 'I', 'you', 'we built'. Never marketing third person.",
      "Be direct. State the problem, state the fix, stop talking.",
      "Builder-to-builder. Assume the reader has shipped real software.",
      "Lead with the work. Screens, repos, agents running, commits landing.",
      "Short sentences beat clever sentences.",
      "Name the tool when it matters -- but the tool is never the hero. The outcome is.",
      "Earn every adjective. If you can't defend it on a call, delete it.",
    ],
    dontRules: [
      "No hype. No adjective stacking.",
      "No vibe coding language as our own. We build and control.",
      "No false novelty.",
      "No fake urgency.",
      "No third-person hero narration about Robert.",
      "No personification of Snappy.",
      "No 'MCP integration' or 'Xano MCP' as the headline.",
    ],
  };
}

export type FlowProfile = {
  name: string;
  source: string;
  stdev: number;
  rolling5: number;
  shortMax: number;
  longMin: number;
  shortFloor: number;
  longFloor: number;
};

export const FLOW_PROFILES: Record<string, FlowProfile> = {
  balanced: {
    name: "balanced",
    source: "writer-agnostic rhythm detector",
    stdev: 6.0,
    rolling5: 4.5,
    shortMax: 7,
    longMin: 24,
    shortFloor: 0.18,
    longFloor: 0.10,
  },
};

export function splitSentences(text: string): string[] {
  return text
    .split(/(?<=[.!?])\s+/)
    .map((s) => s.trim())
    .filter((s) => s.length > 0 && /[A-Za-z]/.test(s));
}

function mean(values: number[]): number {
  return values.length === 0 ? 0 : values.reduce((sum, n) => sum + n, 0) / values.length;
}

function median(values: number[]): number {
  if (values.length === 0) return 0;
  const sorted = [...values].sort((a, b) => a - b);
  const mid = Math.floor(sorted.length / 2);
  return sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid];
}

function stdev(values: number[]): number {
  if (values.length === 0) return 0;
  const m = mean(values);
  return Math.sqrt(mean(values.map((n) => (n - m) ** 2)));
}

function rollingWindowStdev(values: number[], size: number): number {
  if (values.length < size) return stdev(values);
  return Math.max(...values.slice(0, values.length - size + 1).map((_, i) => stdev(values.slice(i, i + size))));
}

export function checkFlow(
  text: string,
  opts: { minSentences?: number; profile?: string } = {},
): {
  pass: boolean;
  profile: string;
  reasons: string[];
  stats: {
    sentences: number;
    meanLength: number;
    medianLength: number;
    stdev: number;
    rolling5Stdev: number;
    shortRatio: number;
    longRatio: number;
  };
} {
  const minSentences = opts.minSentences ?? 10;
  const profileName = opts.profile ?? "balanced";
  const profile = FLOW_PROFILES[profileName];
  if (!profile) {
    throw new Error(`[checkFlow] unknown profile '${profileName}'. Available: ${Object.keys(FLOW_PROFILES).join(", ")}`);
  }

  const stripped = text
    .replace(/```[\s\S]*?```/g, "")
    .replace(/^#.*$/gm, "")
    .replace(/^---[\s\S]*?---/m, "")
    .replace(/<\/?connective>/gi, "")
    .replace(/\[source:[^\]]*\]/gi, "");

  const sentences = splitSentences(stripped);
  const lengths = sentences.map((s) => s.split(/\s+/).filter(Boolean).length);
  const stats = {
    sentences: lengths.length,
    meanLength: Number(mean(lengths).toFixed(2)),
    medianLength: Number(median(lengths).toFixed(2)),
    stdev: Number(stdev(lengths).toFixed(2)),
    rolling5Stdev: Number(rollingWindowStdev(lengths, 5).toFixed(2)),
    shortRatio: lengths.length === 0 ? 0 : Number((lengths.filter((n) => n <= profile.shortMax).length / lengths.length).toFixed(2)),
    longRatio: lengths.length === 0 ? 0 : Number((lengths.filter((n) => n >= profile.longMin).length / lengths.length).toFixed(2)),
  };

  const reasons: string[] = [];
  if (lengths.length < minSentences) return { pass: true, profile: profileName, reasons, stats };
  if (stats.stdev < profile.stdev) reasons.push(`sentence length stdev ${stats.stdev} < ${profile.stdev}`);
  if (stats.rolling5Stdev < profile.rolling5) reasons.push(`rolling-5 stdev ${stats.rolling5Stdev} < ${profile.rolling5}`);
  if (stats.shortRatio < profile.shortFloor) reasons.push(`short sentence ratio ${stats.shortRatio} < ${profile.shortFloor}`);
  if (stats.longRatio < profile.longFloor) reasons.push(`long sentence ratio ${stats.longRatio} < ${profile.longFloor}`);

  return { pass: reasons.length === 0, profile: profileName, reasons, stats };
}

export function requireCitations(draft: string): {
  pass: boolean;
  totalSentences: number;
  citedSentences: number;
  connectiveSentences: number;
  uncitedSentences: string[];
  connectiveRatio: number;
  reasons: string[];
} {
  const stripped = draft
    .replace(/```[\s\S]*?```/g, "")
    .replace(/^#.*$/gm, "")
    .replace(/^---.*$/gm, "");

  const connectiveMatches: string[] = stripped.match(/<connective>[\s\S]*?<\/connective>/gi) ?? [];
  const connectiveSentences = connectiveMatches.reduce<number>((n, chunk) => {
    const inner = chunk.replace(/<\/?connective>/gi, "");
    return n + splitSentences(inner).length;
  }, 0);
  const withoutConnective = stripped.replace(/<connective>[\s\S]*?<\/connective>/gi, "");

  const sentences = splitSentences(withoutConnective);
  const citeRe = /\[source:\s*[^\]]+?~\s*\d{1,3}:\d{2}[^\]]*\]/i;

  const cited: string[] = [];
  const uncited: string[] = [];
  for (const s of sentences) {
    if (citeRe.test(s)) cited.push(s);
    else uncited.push(s);
  }

  const totalSentences = sentences.length + connectiveSentences;
  const citedSentences = cited.length;
  const connectiveRatio = totalSentences === 0 ? 0 : connectiveSentences / totalSentences;

  const reasons: string[] = [];
  if (uncited.length > 0) {
    reasons.push(
      `${uncited.length} prose sentence(s) lack [source: ...~mm:ss] citation and are not wrapped in <connective>...`,
    );
  }
  if (connectiveRatio > 0.35) {
    reasons.push(
      `connective tissue ratio ${(connectiveRatio * 100).toFixed(0)}% exceeds 35% budget`,
    );
  }

  return {
    pass: reasons.length === 0,
    totalSentences,
    citedSentences,
    connectiveSentences,
    uncitedSentences: uncited,
    connectiveRatio,
    reasons,
  };
}

scripts- helper scripts it can run

prose-only skill - 6 inline code blocks live in SKILL.md above (no state/bin/ sidecar yet).

how we check it- the checks, plus the last 10 runs

rubric auto-shape no rubric declared
recent no runs actor/auditor: unverifiable
deps openrouter elevenlabs

no recent runs logged - the eval contract is declared but nothing has been graded yet