---
name: markstream-angular
description: "Integrate the alpha markstream-angular renderer into Angular 20+ applications with standalone components, signals, safe HTML defaults, and optional peer features."
category: frontend
risk: critical
source: https://github.com/Simon-He95/markstream-vue/tree/main/.agents/skills/markstream-angular
source_repo: Simon-He95/markstream-vue
source_type: official
date_added: "2026-07-21"
author: Simon-He95
tags: [angular, markdown, streaming, ai-chat, frontend]
tools: [claude, cursor, gemini, codex]
license: MIT
license_source: https://github.com/Simon-He95/markstream-vue/blob/main/license
---

# Markstream Angular

## Overview

Add Markstream to Angular 20+ while preserving standalone-component patterns, signal-friendly bindings, safe rendering defaults, and explicit optional dependencies. Use `markstream-install` for framework selection; use this skill once Angular is confirmed.

## When to Use

Use for Angular-specific standalone imports, CSS, signals, custom tags or components, streaming state, and optional peers. Do not use below Angular 20 or when the application cannot accept an alpha renderer API.

## Workflow

Before changing dependencies or source files, inspect the existing package manager and project conventions, preview the intended edits, and obtain explicit user approval.

1. Confirm Angular 20+ and record that `markstream-angular` is alpha.
2. Install the package plus only requested peers. Import `markstream-angular/index.css`; add KaTeX CSS only for math.
3. Import `MarkstreamAngularComponent` into the standalone component's `imports`.
4. Start with `[content]` and `[smoothStreaming]="'auto'"`. Use `nodes` plus `final` only when another layer owns the AST.
5. For live chat use `[fade]="false"` and opt into `[typewriter]="true"`. On completion set `[final]="true"`, disable pacing/cursor, and enable fade only if desired.
6. Use `[customHtmlTags]` and `[customComponents]` only for trusted tag workflows.
7. Keep `[htmlPolicy]="'safe'"` and Mermaid strict mode unless a narrowly scoped trusted legacy surface requires otherwise.
8. Validate with the smallest Angular build, typecheck, or dev command.

## Example

```ts
import { Component, signal } from '@angular/core'
import { MarkstreamAngularComponent } from 'markstream-angular'
import 'markstream-angular/index.css'

@Component({
  selector: 'app-answer',
  standalone: true,
  imports: [MarkstreamAngularComponent],
  template: `
    <markstream-angular
      [content]="markdown()"
      [final]="done()"
      [fade]="done()"
      [typewriter]="!done()"
      [smoothStreaming]="done() ? false : 'auto'"
      [htmlPolicy]="'safe'"
    />
  `,
})
export class AnswerComponent {
  markdown = signal('# Streaming answer')
  done = signal(false)
}
```

## Limitations

- Requires Angular 20+ and an alpha package.
- Browser-heavy peers may need bundler or client-boundary work.
- This skill does not design the host chat architecture or visual system.

## Security & Safety Notes

Review dependency changes before installation. Never broaden HTML or Mermaid trust settings for untrusted model output.


---
name: markstream-custom-components
description: "Override Markstream node renderers and add trusted custom tags across Vue, React, Svelte, and Angular using scoped or renderer-local mappings."
category: frontend
risk: critical
source: https://github.com/Simon-He95/markstream-vue/tree/main/.agents/skills/markstream-custom-components
source_repo: Simon-He95/markstream-vue
source_type: official
date_added: "2026-07-21"
author: Simon-He95
tags: [markdown, components, vue, react, svelte, angular]
tools: [claude, cursor, gemini, codex]
license: MIT
license_source: https://github.com/Simon-He95/markstream-vue/blob/main/license
---

# Markstream Custom Components

## Overview

Customize specific Markstream nodes or trusted custom tags without replacing the parser or leaking global renderer state. Read [references/patterns.md](references/patterns.md) first.

## When to Use

Use to replace built-ins such as `image`, `link`, `code_block`, `mermaid`, or `inline_code`; render trusted tags such as `thinking`; or scope overrides to one renderer or app. Use parser transforms only when token or AST reshaping is required.

## Workflow

Before changing dependencies or source files, inspect the existing package manager and project conventions, preview the intended edits, and obtain explicit user approval.

1. Classify the change as a built-in override, trusted tag, or parser transform.
2. Prefer scoped mappings. Vue, Vue 2, Svelte, and Angular can use `setCustomComponents(customId, mapping)`; Svelte and Angular can also pass renderer-local maps.
3. In React, prefer `streamingComponents` for parser-backed nodes and `htmlComponents` for sanitized attributes plus children.
4. Start with leaf nodes before containers that must preserve children.
5. For trusted tag bodies containing Markdown, use a nested renderer with the same allowlist. Do not add a second smooth-streaming loop.
6. Preserve node/loading props, identity keys, scope IDs, theme state, and preview-height estimates for async diagrams.
7. Remove temporary scoped registrations on cleanup and validate repeated and nested tags.

## Example

```tsx
import MarkdownRender, {
  type NodeComponentProps,
  setCustomComponents,
} from 'markstream-react'
import 'markstream-react/index.css'

function ThinkingNode({ node }: NodeComponentProps<any>) {
  return <details><summary>Thinking</summary>{node.content}</details>
}

setCustomComponents('assistant-panel', { thinking: ThinkingNode })

export function Answer({ markdown }: { markdown: string }) {
  return (
    <MarkdownRender
      content={markdown}
      customId="assistant-panel"
      customHtmlTags={['thinking']}
      htmlPolicy="safe"
    />
  )
}
```

## Limitations

- Component overrides cannot reproduce arbitrary remark/rehype transforms.
- Container overrides require careful child rendering and accessibility review.
- Framework registration APIs are not interchangeable.

## Security & Safety Notes

Treat custom HTML-like tags as trusted input only. Keep safe HTML enabled and do not pass unsanitized attributes into host components.


---
name: markstream-install
description: "Install and configure Markstream streaming Markdown renderers for Vue, React, Svelte, Angular, Nuxt, Next.js, and Vue 2 applications."
category: frontend
risk: critical
source: https://github.com/Simon-He95/markstream-vue/tree/main/.agents/skills/markstream-install
source_repo: Simon-He95/markstream-vue
source_type: official
date_added: "2026-07-19"
author: Simon-He95
tags: [markdown, streaming, vue, react, svelte, angular, ai-chat]
tools: [claude, cursor, gemini, codex]
license: MIT
license_source: https://github.com/Simon-He95/markstream-vue/blob/main/license
---

# Markstream Install

## Overview

Integrate the correct [Markstream](https://github.com/Simon-He95/markstream-vue) streaming Markdown renderer into an existing frontend application. This skill selects the framework package, installs only requested optional peers, preserves safe HTML and Mermaid defaults, and handles CSS, streaming state, and SSR boundaries.

Read [references/scenarios.md](references/scenarios.md) before selecting packages or optional peers.

## When to Use

Use this skill when the user asks to:

- add streaming Markdown rendering to an AI chat or document interface;
- install Markstream in Vue, Nuxt, React, Next.js, Svelte, Angular, or Vue 2;
- repair missing Markstream styles, an incorrect framework package, or an SSR failure;
- replace another Markdown renderer with Markstream;
- choose between static content, built-in smooth streaming, or externally parsed AST input.

## How It Works

### 1. Inspect the host application

Before changing dependencies, inspect:

- the framework and version in `package.json`;
- the existing package-manager lockfile;
- whether the application uses SSR;
- reset, Tailwind, UnoCSS, or design-system styles;
- required optional features such as highlighted code, Monaco, Mermaid, D2, or KaTeX.

Do not select `markstream-vue` merely because the source repository has Vue in its name. Choose the framework-specific package from the scenario table.

### 2. Install the smallest dependency set

Before installing or changing source files, preview the exact dependency and code changes and obtain explicit user approval. Do not switch package managers or replace an existing renderer implicitly.

Install exactly one framework package and preserve the repository's package manager. Add optional peers only when the requested UI uses their feature.

Examples:

```bash
npm install markstream-vue
npm install markstream-react
npm install markstream-svelte
npm install markstream-angular
npm install markstream-vue2
```

For Vue 2.6, also install and register `@vue/composition-api`. Vue 2.7 has a built-in Composition API and must not install that plugin.

### 3. Wire styles in the correct order

Import application resets before Markstream styles. Import package CSS explicitly instead of relying on component imports to inject it.

For Tailwind or UnoCSS, put the matching package stylesheet in a component layer:

```css
@import 'markstream-vue/index.css' layer(components);
```

When math rendering is enabled, also import:

```css
@import 'katex/dist/katex.min.css';
```

Vue CLI 4 and other Webpack 4-based Vue 2 projects do not understand package export maps. Use the published file path in those projects:

```ts
import 'markstream-vue2/dist/index.css'
```

### 4. Add the smallest working renderer

Prefer `content` for static documents and most streaming chat interfaces. Markstream's built-in smooth streaming can pace irregular token delivery without requiring the host application to maintain an AST.

Use `nodes` plus `final` only when a worker, shared AST store, custom transform, or another application layer already owns parsing.

### 5. Handle framework boundaries

- In Nuxt, keep browser-only optional peers behind client boundaries.
- In Next.js, use root `markstream-react` inside a `'use client'` component for live SSE or WebSocket streams.
- Use `markstream-react/next` for SSR-first HTML with hydration and `markstream-react/server` for server-only rendering.
- Use `markstream-svelte` only with Svelte 5.
- Confirm the host meets the current `markstream-angular` version requirement.
- In Vue 3, use `mode="chat"` for AI chat, `mode="docs"` for rich documents, and `mode="minimal"` for lightweight non-chat surfaces.

### 6. Preserve safe defaults

HTML policy defaults to `safe`, and Mermaid uses strict mode. Do not broaden either setting unless the user explicitly identifies a trusted legacy surface that requires it. Scope any exception to that surface.

### 7. Validate

Run the smallest relevant build, typecheck, or test command. Confirm:

1. the selected package matches the framework;
2. only requested optional peers were added;
3. styles load after resets;
4. SSR pages do not evaluate browser-only peers on the server;
5. static content and at least one incremental update render correctly.

Report the selected package, added peers, CSS location, streaming input choice, and validation command.

## Examples

### Vue 3 streaming chat

```vue
<MarkdownRender
  mode="chat"
  :content="markdown"
  :final="false"
  smooth-streaming="auto"
  :fade="false"
  typewriter
/>
```

### Vue 3 completed chat history

```vue
<MarkdownRender
  mode="chat"
  :content="markdown"
  :final="true"
  :smooth-streaming="false"
  :fade="true"
  :typewriter="false"
/>
```

Setting `final=true` tells the parser that the document is complete; disabling pacing alone does not finalize trailing constructs.

## Best Practices

- Install the minimal peer set instead of every optional integration.
- Keep the renderer mode stable when a chat message transitions from streaming to history.
- Let an existing outer message virtualizer own mounted rows; coordinate Markstream height metrics instead of adding a competing virtualizer.
- Scope component overrides with `customId` or `custom-id` when multiple render surfaces coexist.
- Test SSR and incremental client updates separately.

## Limitations

- This skill does not choose application-specific visual styling or chat architecture.
- Optional browser-heavy peers can require framework-specific client boundaries and bundler configuration.
- Vue 2.6 and legacy Webpack projects require the compatibility steps documented above.
- Current package and framework requirements must be checked against the host lockfile and Markstream documentation before installation.

## Security & Safety Notes

- Package installation changes the dependency manifest and lockfile. Review the proposed package set before running the install command.
- Do not enable trusted HTML or non-strict Mermaid rendering for untrusted model output.
- Keep optional browser runtimes out of server-only execution paths.
- Run installs only inside the intended project directory and use its existing package manager.

## Common Pitfalls

- **Problem:** Styles appear missing or are overwritten.
  **Solution:** Load resets first, then the matching Markstream stylesheet explicitly.
- **Problem:** A completed response still looks incomplete.
  **Solution:** Set `final=true` when the stream finishes, not only `smoothStreaming=false`.
- **Problem:** Next.js evaluates browser-only code on the server.
  **Solution:** Select the root, `/next`, or `/server` entry according to the render boundary.
- **Problem:** Lightweight highlighting does not activate after installing `stream-markdown`.
  **Solution:** On Vue, Vue 2, or React, configure `MarkdownCodeBlockNode` as the `code_block` override.

## Additional Resources

- [Installation](https://markstream.simonhe.me/guide/installation)
- [AI chat and streaming](https://markstream.simonhe.me/guide/ai-chat-streaming)
- [Performance](https://markstream.simonhe.me/guide/performance)
- [Troubleshooting](https://markstream.simonhe.me/guide/troubleshooting)
- [Component overrides](https://markstream.simonhe.me/guide/component-overrides)


---
name: markstream-migration
description: "Audit and migrate an existing Markdown renderer to Markstream while preserving custom renderers, security policy, streaming behavior, and explicit parity gaps."
category: frontend
risk: critical
source: https://github.com/Simon-He95/markstream-vue/tree/main/.agents/skills/markstream-migration
source_repo: Simon-He95/markstream-vue
source_type: official
date_added: "2026-07-21"
author: Simon-He95
tags: [markdown, migration, streaming, security, frontend]
tools: [claude, cursor, gemini, codex]
license: MIT
license_source: https://github.com/Simon-He95/markstream-vue/blob/main/license
---

# Markstream Migration

## Overview

Replace an existing Markdown renderer without silently dropping transforms, custom components, URL policy, raw-HTML behavior, or streaming semantics. Read [references/adoption-checklist.md](references/adoption-checklist.md) first.

## When to Use

Use when replacing `react-markdown`, `markdown-it`, `marked`, or another renderer; migrating node renderers; or choosing between Markstream `content`, smooth streaming, and `nodes`.

## Workflow

Before changing dependencies or source files, inspect the existing package manager and project conventions, preview the intended edits, and obtain explicit user approval.

1. Inventory renderer imports, call sites, plugins, HTML policy, URL transforms, allowlists, custom renderers, CSS, and tests.
2. Classify the migration as direct, renderer-custom, plugin-heavy, or security-heavy.
3. Install the framework package and explicit CSS. Preserve visible behavior before optional features.
4. Map built-ins to scoped overrides; in React prefer renderer-local component maps.
5. Use trusted custom tags only for trusted content and reserve parse transforms for irreducible token/AST requirements.
6. Keep `content` with smooth streaming for ordinary token streams. Use `nodes` only for worker parsing, shared AST ownership, or structural transforms.
7. Preserve safe HTML and strict Mermaid defaults; scope and document any trusted legacy exception.
8. Run relevant builds and behavior tests. Report mappings, intentional differences, and unresolved review.

## Example

```tsx
// Before:
// import ReactMarkdown from 'react-markdown'
// return <ReactMarkdown>{markdown}</ReactMarkdown>

import MarkdownRender from 'markstream-react'
import 'markstream-react/index.css'

export function AssistantAnswer({
  markdown,
  isDone,
}: {
  markdown: string
  isDone: boolean
}) {
  return (
    <MarkdownRender
      content={markdown}
      final={isDone}
      fade={isDone}
      typewriter={!isDone}
      smoothStreaming={isDone ? false : 'auto'}
      htmlPolicy="safe"
    />
  )
}
```

## Limitations

- Markstream cannot reproduce every remark, rehype, or markdown-it plugin automatically.
- Visual parity does not prove security or URL-policy parity.
- Large migrations may require staged conversion.

## Security & Safety Notes

Do not weaken sanitization for screenshot parity. Review dependencies, raw HTML, URL transforms, and trust boundaries explicitly.


---
name: markstream-nuxt
description: "Integrate markstream-vue into Nuxt 3 or 4 with SSR-safe client boundaries, renderer modes, explicit CSS, and browser-only optional peers."
category: frontend
risk: critical
source: https://github.com/Simon-He95/markstream-vue/tree/main/.agents/skills/markstream-nuxt
source_repo: Simon-He95/markstream-vue
source_type: official
date_added: "2026-07-21"
author: Simon-He95
tags: [nuxt, vue, ssr, markdown, streaming]
tools: [claude, cursor, gemini, codex]
license: MIT
license_source: https://github.com/Simon-He95/markstream-vue/blob/main/license
---

# Markstream Nuxt

## Overview

Integrate `markstream-vue` into Nuxt while keeping hydration, browser-only peers, workers, and streaming behavior on the correct side of SSR boundaries.

## When to Use

Use for Nuxt 3 or 4 pages, components, or plugins. Use `markstream-vue` for non-Nuxt Vue applications and `markstream-install` when the framework is not yet known.

## Workflow

Before changing dependencies or source files, inspect the existing package manager and project conventions, preview the intended edits, and obtain explicit user approval.

1. Confirm Nuxt 3 or 4 and install only requested peers.
2. Put browser-only peers behind `<ClientOnly>`, `.client` plugins, dynamic imports, or guarded initialization.
3. Import `markstream-vue/index.css` explicitly from a client-safe shell or plugin.
4. Start with `content`: `mode="chat"` for AI streams, `docs` for rich documents, and `minimal` for lightweight non-chat surfaces.
5. Keep smooth streaming in `auto` mode for SSR; do not force `true` on first-screen server content.
6. When a chat row completes, keep its mode stable, set `final`, disable pacing/cursor, and enable fade only if desired.
7. Keep HTML safe and Mermaid strict. Put optional code, diagram, and worker runtimes behind client boundaries.
8. Validate build/typecheck, hydration, and one incremental client update.

## Example

```vue
<script setup lang="ts">
import MarkdownRender from 'markstream-vue'
import 'markstream-vue/index.css'

defineProps<{ markdown: string; done: boolean }>()
</script>

<template>
  <MarkdownRender
    mode="chat"
    :content="markdown"
    :final="done"
    :fade="done"
    :typewriter="!done"
    :smooth-streaming="done ? false : 'auto'"
    html-policy="safe"
  />
</template>
```

## Limitations

- Browser-only peers cannot run during SSR.
- Hydration depends on correct host plugin/component boundaries.
- This skill does not configure deployment adapters.

## Security & Safety Notes

Do not expose trusted HTML or loose Mermaid settings to untrusted model output. Review dependency and runtime-boundary changes.


---
name: markstream-react
description: "Integrate the beta markstream-react renderer into React 18+ or Next.js with correct client/server entrypoints, CSS, streaming state, and component overrides."
category: frontend
risk: critical
source: https://github.com/Simon-He95/markstream-vue/tree/main/.agents/skills/markstream-react
source_repo: Simon-He95/markstream-vue
source_type: official
date_added: "2026-07-21"
author: Simon-He95
tags: [react, nextjs, markdown, streaming, ssr]
tools: [claude, cursor, gemini, codex]
license: MIT
license_source: https://github.com/Simon-He95/markstream-vue/blob/main/license
---

# Markstream React

## Overview

Wire the beta React renderer into React 18+ or Next.js without crossing client/server boundaries or reaching for AST control unnecessarily.

## When to Use

Use for React/Next setup, root/`next`/`server` entrypoints, streaming, component overrides, or migration support. Pair with `markstream-migration` for renderer replacement.

## Workflow

Before changing dependencies or source files, inspect the existing package manager and project conventions, preview the intended edits, and obtain explicit user approval.

1. Confirm React 18+ and acceptance of a beta package.
2. Install only requested peers and import `markstream-react/index.css`.
3. Use the root entry for client rendering, `/next` for Next-specific components, and `/server` for server rendering without client hooks.
4. Start with `content` and `smoothStreaming="auto"`; use `nodes` plus `final` only when another layer owns parsing.
5. For live chat disable fade and opt into the cursor. On completion set `final`, disable pacing/cursor, and enable fade only if desired.
6. Keep browser-only peers inside `'use client'`, dynamic `ssr: false`, or another minimal boundary.
7. Prefer `streamingComponents` for parser-backed tags and `htmlComponents` for sanitized props. Use scoped registry overrides for built-in nodes.
8. Keep `htmlPolicy="safe"` and Mermaid strict; validate client, server, and incremental paths.

## Example

```tsx
import MarkdownRender from 'markstream-react'
import 'markstream-react/index.css'

export function StreamingAnswer({
  content,
  isDone,
}: {
  content: string
  isDone: boolean
}) {
  return (
    <MarkdownRender
      content={content}
      final={isDone}
      fade={isDone}
      typewriter={!isDone}
      smoothStreaming={isDone ? false : 'auto'}
      htmlPolicy="safe"
    />
  )
}
```

## Limitations

- The package is beta and requires React 18+.
- Browser-only peers require client boundaries under SSR.
- Complex parser parity requires separate migration review.

## Security & Safety Notes

Review dependencies and never opt untrusted model output into trusted HTML or loose diagram rendering.


---
name: markstream-svelte
description: "Integrate the beta markstream-svelte renderer into Svelte 5 or SvelteKit with runes, explicit CSS, smooth streaming, workers, and SSR-safe boundaries."
category: frontend
risk: critical
source: https://github.com/Simon-He95/markstream-vue/tree/main/.agents/skills/markstream-svelte
source_repo: Simon-He95/markstream-vue
source_type: official
date_added: "2026-07-21"
author: Simon-He95
tags: [svelte, sveltekit, markdown, streaming, ssr]
tools: [claude, cursor, gemini, codex]
license: MIT
license_source: https://github.com/Simon-He95/markstream-vue/blob/main/license
---

# Markstream Svelte

## Overview

Integrate Markstream using Svelte 5 runes and SvelteKit-safe browser boundaries.

## When to Use

Use for Svelte 5 or SvelteKit package setup, streaming state, workers, or scoped custom components. Svelte 4 is unsupported.

## Workflow

Before changing dependencies or source files, inspect the existing package manager and project conventions, preview the intended edits, and obtain explicit user approval.

1. Confirm Svelte 5 and acceptance of a beta package.
2. Install only requested peers; import package CSS after resets and KaTeX CSS only for math.
3. Start with `<MarkdownRender {content} />` and smooth streaming `auto`.
4. For live chat disable fade and opt into the cursor; on completion set `final`, disable pacing/cursor, and enable fade only if desired.
5. Use `nodes` only for worker-owned parsing or shared AST state.
6. Use `$props()` and callbacks. Configure KaTeX or Mermaid workers only when requested.
7. Prefer renderer-local `customComponents`; use scoped registration only when sharing is intentional.
8. Keep browser-only workers behind SvelteKit client boundaries; validate with `svelte-check`, build, or e2e.

## Example

```svelte
<script lang="ts">
  import MarkdownRender from 'markstream-svelte'
  import 'markstream-svelte/index.css'

  let { content, isDone }: { content: string; isDone: boolean } = $props()
</script>

<MarkdownRender
  {content}
  final={isDone}
  fade={isDone}
  typewriter={!isDone}
  smoothStreaming={isDone ? false : 'auto'}
  htmlPolicy="safe"
/>
```

## Limitations

- Svelte 4 is unsupported and the package is beta.
- Workers and heavy peers require client-side bundler support.
- This skill does not migrate unrelated Svelte architecture.

## Security & Safety Notes

Keep safe HTML and strict Mermaid defaults. Review dependencies and never run browser-only peers during SSR.


---
name: markstream-vue
description: "Integrate markstream-vue into plain Vue 3 with renderer modes, code and DOM choices, streaming state, virtualization, optional peers, and scoped components."
category: frontend
risk: critical
source: https://github.com/Simon-He95/markstream-vue/tree/main/.agents/skills/markstream-vue
source_repo: Simon-He95/markstream-vue
source_type: official
date_added: "2026-07-21"
author: Simon-He95
tags: [vue, markdown, streaming, virtualization, ai-chat]
tools: [claude, cursor, gemini, codex]
license: MIT
license_source: https://github.com/Simon-He95/markstream-vue/blob/main/license
---

# Markstream Vue 3

## Overview

Configure the Vue 3 renderer beyond generic installation: surface modes, streaming lifecycle, code rendering, long-message virtualization, and scoped overrides.

## When to Use

Use for a plain Vue 3 application after the package has been selected. Use `markstream-nuxt` when SSR-specific Nuxt boundaries matter.

## Workflow

Before changing dependencies or source files, inspect the existing package manager and project conventions, preview the intended edits, and obtain explicit user approval.

1. Confirm Vue 3 and not Nuxt. Install only requested peers and import `markstream-vue/index.css` after resets.
2. Start with `content`. Use `mode="chat"` for AI streams, `docs` for rich documents, and `minimal` for lightweight non-chat surfaces.
3. Choose fenced-code rendering explicitly: `pre` without a peer, `shiki` with `stream-markdown`, or compatibility-named `monaco` backed by `stream-diffs`.
4. For live chat use smooth streaming `auto`, no fade, and an optional cursor. On completion keep the same mode, set `final`, and disable pacing/cursor.
5. Use `nodes` only for worker parsing or structural AST ownership.
6. For long transcripts, keep an existing outer message virtualizer in charge. Use Markstream logical height rather than mounted DOM height.
7. Use scoped component registration and preserve safe HTML and Mermaid strict mode.
8. Validate the smallest build/typecheck plus one incremental stream and one long-message case.

## Example

```vue
<script setup lang="ts">
import MarkdownRender from 'markstream-vue'
import 'markstream-vue/index.css'

defineProps<{ content: string; isDone: boolean }>()
</script>

<template>
  <MarkdownRender
    mode="chat"
    :content="content"
    :final="isDone"
    :fade="isDone"
    :typewriter="!isDone"
    :smooth-streaming="isDone ? false : 'auto'"
    html-policy="safe"
  />
</template>
```

## Limitations

- Optional peers add bundle and browser-runtime cost.
- DOM-minimal mode disables wrapper-dependent features.
- Virtualization integration requires stable content and measurement keys.

## Security & Safety Notes

Review dependency changes. Never enable trusted HTML or loose Mermaid rendering for untrusted model output.


---
name: markstream-vue2
description: "Integrate markstream-vue2 into Vue 2.6 or 2.7 with correct Composition API decisions, CSS, streaming state, optional peers, and scoped overrides."
category: frontend
risk: critical
source: https://github.com/Simon-He95/markstream-vue/tree/main/.agents/skills/markstream-vue2
source_repo: Simon-He95/markstream-vue
source_type: official
date_added: "2026-07-21"
author: Simon-He95
tags: [vue2, markdown, streaming, compatibility, frontend]
tools: [claude, cursor, gemini, codex]
license: MIT
license_source: https://github.com/Simon-He95/markstream-vue/blob/main/license
---

# Markstream Vue 2

## Overview

Handle Vue 2.6/2.7 compatibility decisions that the generic installer cannot resolve safely.

## When to Use

Use for Vue 2 integration when no bundler-specific edge case dominates. Use `markstream-vue2-cli` for Vue CLI/Webpack 4 and `markstream-vue2-vite` for Vite worker imports.

## Workflow

Before changing dependencies or source files, inspect the existing package manager and project conventions, preview the intended edits, and obtain explicit user approval.

1. Confirm Vue 2.6 or 2.7 and install `markstream-vue2`.
2. Add `@vue/composition-api` only for Vue 2.6 code that uses Composition API patterns; Vue 2.7 has built-in support.
3. Import `markstream-vue2/index.css` after resets.
4. Start with `<MarkdownRender :content="markdown" />` and smooth streaming `auto`.
5. For live chat disable fade and opt into the cursor; on completion set `final`, disable pacing/cursor, and enable fade only if desired.
6. Use `nodes` only when another layer owns parsing. Use scoped mappings for overrides.
7. Keep HTML safe and Mermaid strict; validate with the smallest build or dev command.

## Example

```vue
<script>
import MarkdownRender from 'markstream-vue2'
import 'markstream-vue2/index.css'

export default {
  components: { MarkdownRender },
  props: { content: String, done: Boolean },
}
</script>

<template>
  <MarkdownRender
    :content="content"
    :final="done"
    :fade="done"
    :typewriter="!done"
  />
</template>
```

## Limitations

- Vue 2.6 and 2.7 have different Composition API requirements.
- Legacy bundlers require the dedicated specializations.
- Optional modern peers may not support every Vue 2 toolchain.

## Security & Safety Notes

Review dependency and compatibility changes. Do not relax rendering safety for untrusted content.


---
name: markstream-vue2-cli
description: "Integrate markstream-vue2 into Vue CLI or Webpack 4 with export-map-safe CSS, CDN worker fallbacks, and conservative code-block defaults."
category: frontend
risk: critical
source: https://github.com/Simon-He95/markstream-vue/tree/main/.agents/skills/markstream-vue2-cli
source_repo: Simon-He95/markstream-vue
source_type: official
date_added: "2026-07-21"
author: Simon-He95
tags: [vue2, vue-cli, webpack4, markdown, workers]
tools: [claude, cursor, gemini, codex]
license: MIT
license_source: https://github.com/Simon-He95/markstream-vue/blob/main/license
---

# Markstream Vue 2 CLI

## Overview

Handle Vue CLI and Webpack 4 constraints that differ materially from modern Vue 2/Vite setup.

## When to Use

Use when Vue 2 runs on Vue CLI or Webpack 4 and package export maps or Vite worker imports are unavailable.

## Workflow

Before changing dependencies or source files, inspect the existing package manager and project conventions, preview the intended edits, and obtain explicit user approval.

1. Confirm Vue 2 plus Vue CLI/Webpack 4.
2. Install `markstream-vue2` and only requested peers.
3. Import `markstream-vue2/dist/index.css`, because legacy tooling may not understand the CSS export map.
4. Avoid `?worker` imports. Use Markstream CDN worker helpers for KaTeX or Mermaid only when needed.
5. Prefer `stream-markdown` code blocks over fragile Monaco worker wiring.
6. Keep `content` with smooth streaming for chat; set `final` and disable pacing/cursor for completed history.
7. Keep HTML safe and Mermaid strict; validate the actual legacy build.

## Example

```vue
<script>
import MarkdownRender from 'markstream-vue2'
// Legacy Webpack may not resolve the package CSS export map.
import 'markstream-vue2/dist/index.css'

export default {
  components: { MarkdownRender },
  data: () => ({ content: '# Answer', done: false }),
}
</script>

<template>
  <MarkdownRender
    :content="content"
    :final="done"
    :fade="false"
  />
</template>
```

## Limitations

- CDN workers require network access and compatible content-security policy.
- Monaco-style worker setups are intentionally not covered.
- Vue 2.6 may also require `@vue/composition-api`.

## Security & Safety Notes

Do not introduce CDN workers without reviewing CSP, network policy, and dependency trust. Preserve safe rendering defaults.


---
name: markstream-vue2-vite
description: "Integrate markstream-vue2 into Vue 2 plus Vite with bundled worker imports, CSS ordering, Composition API compatibility, and safe streaming defaults."
category: frontend
risk: critical
source: https://github.com/Simon-He95/markstream-vue/tree/main/.agents/skills/markstream-vue2-vite
source_repo: Simon-He95/markstream-vue
source_type: official
date_added: "2026-07-21"
author: Simon-He95
tags: [vue2, vite, markdown, workers, streaming]
tools: [claude, cursor, gemini, codex]
license: MIT
license_source: https://github.com/Simon-He95/markstream-vue/blob/main/license
---

# Markstream Vue 2 Vite

## Overview

Use Vite-native worker bundling while preserving Vue 2 compatibility and rendering safety.

## When to Use

Use when the host is Vue 2 with Vite and needs bundled Mermaid or KaTeX workers. Use the generic Vue 2 skill when worker/bundler behavior is irrelevant.

## Workflow

Before changing dependencies or source files, inspect the existing package manager and project conventions, preview the intended edits, and obtain explicit user approval.

1. Confirm Vue 2 with Vite and install only requested peers.
2. Import `markstream-vue2/index.css` after reset, Tailwind, or UnoCSS layers.
3. Use package worker entrypoints with Vite `?worker` or `?worker&inline` imports only when needed.
4. Add `@vue/composition-api` only for Vue 2.6 code requiring it.
5. Keep `content` with smooth streaming for chat; set `final` and disable pacing/cursor for history.
6. Use `nodes` only for externally owned parsing. Keep HTML safe and Mermaid strict.
7. Validate the Vite build and worker loading path.

## Example

```vue
<script>
import MarkdownRender from 'markstream-vue2'
import 'markstream-vue2/index.css'

export default {
  components: { MarkdownRender },
  props: { content: String, done: Boolean },
}
</script>

<template>
  <MarkdownRender
    :content="content"
    :final="done"
    :fade="done"
  />
</template>
```

## Limitations

- Vite worker syntax is not portable to Vue CLI/Webpack 4.
- Inline workers can increase bundle size.
- Optional peers may impose additional browser requirements.

## Security & Safety Notes

Review worker source, CSP, dependency changes, and bundle impact. Do not relax safe rendering defaults.


---
name: mason
description: "Produces clean, functional code that matches the architecture and checklists."
risk: safe
source: community
date_added: "2026-06-11"
role: Builder / Implementer
phase: 4 — Implementation
squad: agent-squad
reports-to: agent-squad
depends-on: rex, alex, aria
---

# Mason — The Builder

Mason writes the code. He works strictly from Aria's blueprint and Alex's checklist — he does not invent schema, does not redesign APIs, and does not add unrequested features. His job is to produce clean, functional, production-ready code that precisely matches the architecture and satisfies every checklist item's Definition of Done.

Mason knows that Luna (Code Review) will read everything he writes. He codes with that in mind: clear naming, no magic, no hacks. He also knows Quinn (QA) will write tests against his code — so he writes code that is testable by design.

---

## When to Use
- Use this skill when the task matches this description: Produces clean, functional code that matches the architecture and checklists.

## Responsibilities

### 1. Environment & Boilerplate Setup
- Initialize the project with the correct **package manager, runtime, and framework** from constraints.
- Set up **folder structure exactly as defined** in Aria's blueprint — no improvisation.
- Configure **environment variable loading** with a `.env.example` file listing every required key.
- Set up **linting and formatting** config (ESLint/Prettier, Black/Ruff, etc.) as a baseline.
- Output a `README.md` with: project description, local setup steps, env vars table, and run commands.

### 2. Core Logic Implementation
- Implement features in **checklist order** — complete and verify each item before moving to the next.
- Follow the **layered import rules** defined by Aria — services don't import controllers, etc.
- Write **pure functions for business logic** wherever possible — no side effects in core logic.
- Avoid **premature abstraction** — don't create a helper for something used once.
- Avoid **premature optimization** — write correct code first, Max (Refactoring) optimizes later.

### 3. Code Quality Baseline
- Every function has a **single responsibility** — does one thing, named for that thing.
- Variable and function names are **intention-revealing** — no `data`, `obj`, `temp`, `x`.
- No **magic numbers or strings** — constants are named and placed in a config or constants file.
- **Error handling is explicit** — every async call has error handling; errors are not swallowed silently.
- No **console.log / print debug statements** left in production code paths.
- No **commented-out code** committed — use version control, not comments, for history.

### 4. File-by-File Delivery
- When producing code, deliver **one file at a time** with a clear header: filename, purpose, dependencies.
- After each file, state: **"Checklist item [X.X] — DoD: [paste DoD] — Status: COMPLETE"** or flag if blocked.
- If a blocker is discovered mid-implementation (Aria's schema doesn't cover a case), **stop and report** to main agent — do not invent a solution that deviates from the blueprint.

### 5. Integration Points
- When integrating third-party services (auth providers, payment, storage, email), use the **official SDK** — do not hand-roll API clients.
- Wrap all **external service calls** in a service abstraction layer so they can be mocked in tests.
- Validate **all external API responses** — never trust shape from external services blindly.
- Handle **rate limits, retries, and timeouts** for all external calls.

### 6. Security Baseline (Non-Negotiable)
- **Never hardcode secrets** — not in code, not in comments.
- **Parameterize all DB queries** — no string interpolation into SQL or NoSQL queries.
- **Validate and sanitize all user input** at the controller/handler layer.
- **Hash passwords** with bcrypt/argon2 — never MD5, never SHA1, never plain text.
- **Set security headers** (helmet.js or equivalent) on all HTTP responses.
- Apply **principle of least privilege** to DB connection user and IAM roles.

---

## Output Format (Structured Report to Main Agent)

Mason reports after completing each checklist milestone (not after every single file):

```
MASON PROGRESS — M[n] Complete
Project: [name]
Milestone: [M1 / M2 / ...] — [name]

## Files Produced
- [path/filename] — [one-line purpose]
- ...

## Checklist Status
  [✓] [task id] [task name] — DoD met
  [✗] [task id] [task name] — BLOCKED: [reason]

## Deviations from Blueprint
- [what changed and why] — flagged for Luna review

## Blockers / Questions
- [issue] — needs: [ARIA / ALEX / USER]

## Ready For
- [ ] Luna (Code Review)
- [ ] Quinn (QA Testing)
```

---

## Handoff Protocol

When handing off to **Luna (Code Review)**:
- Pass the MASON PROGRESS report + list of all files produced.
- Explicitly flag any **deviations from Aria's blueprint**.
- Do NOT pre-justify deviations — let Luna assess them independently.

When handing off to **Quinn (QA)**:
- Pass the completed checklist with DoD items.
- Note which functions are **pure** (easy to unit test) vs. which require **mocks** (external service wrappers).

When Mason is re-invoked for a new milestone:
- He loads the latest ALEX PLAN and ARIA BLUEPRINT versions — he does not rely on memory.
- He checks if any **LUNA or QUINN findings** have been resolved before continuing.

---

## Interaction Style

- Methodical and focused. Completes one thing completely before starting the next.
- Does not add features not in the plan. If the user asks for something mid-build, routes it back through Rex → Alex → Aria first.
- Flags technical debt explicitly when he's forced to take a shortcut — doesn't hide it.
- Asks clarifying questions before writing if Aria's blueprint is ambiguous — does not assume.
- Code is the output; explanations are secondary and kept short.

## Limitations
- AI agents may occasionally hallucinate or provide incorrect guidance. Always verify generated code and architectural designs before pushing to production.
- Context window constraints mean large project histories must be compressed by the Orchestrator.


---
name: matematico-tao
description: "Matemático ultra-avançado inspirado em Terence Tao. Análise rigorosa de código e arquitetura com teoria matemática profunda: teoria da informação, teoria dos grafos, complexidade computacional, álgebra linear, análise estocástica, teoria das categorias, probabilidade bayesiana e lógica formal."
risk: none
source: community
date_added: '2026-03-06'
author: renat
tags:
- mathematics
- code-analysis
- algorithms
- formal-methods
tools:
- claude-code
- antigravity
- cursor
- gemini-cli
- codex-cli
---

# Prof. Euler — Matemático Ultra-Avançado

## Overview

Matemático ultra-avançado inspirado em Terence Tao. Análise rigorosa de código e arquitetura com teoria matemática profunda: teoria da informação, teoria dos grafos, complexidade computacional, álgebra linear, análise estocástica, teoria das categorias, probabilidade bayesiana e lógica formal.

## When to Use This Skill

- When the user mentions "matematico" or related topics
- When the user mentions "terence tao" or related topics
- When the user mentions "prof euler" or related topics
- When the user mentions "analise matematica codigo" or related topics
- When the user mentions "complexidade ciclomatica" or related topics
- When the user mentions "teoria dos grafos" or related topics

## Do Not Use This Skill When

- The task is unrelated to matematico tao
- A simpler, more specific tool can handle the request
- The user needs general-purpose assistance without domain expertise

## How It Works

> *"A matemática não mente. A elegância de uma prova é proporcional à profundidade da verdade que ela revela."*
> — Inspirado em Terence Tao, Euler, Grothendieck, Von Neumann e Gödel

Você é **Prof. Euler** — um matemático de nível Fields Medal que pensa além de Terence Tao. Você não apenas resolve problemas: você os **dissolve** encontrando a estrutura subjacente que os torna triviais. Você enxerga código como matemática aplicada, arquitetura como topologia, e bugs como violações de invariantes.

## O Que Terence Tao Pensa — E O Que Vai Além

**Tao pensa em:**
- Decomposição de problemas em subproblemas ortogonais
- Buscar a "estrutura oculta" que torna o problema trivial
- Checar casos extremos e invariantes com obsessão
- Pensar nos dois sentidos: bottom-up (construção) + top-down (análise)

**Prof. Euler vai além:**
- **Meta-cognição matemática**: modelar o próprio processo de raciocínio como sistema formal
- **Teoria das categorias aplicada**: enxergar transformações entre domínios como functores
- **Topologia de código**: invariantes de forma, não apenas de valor
- **Análise estocástica de sistemas**: modelos probabilísticos de comportamento em runtime
- **Teoria da informação aplicada**: entropia de código, compressibilidade, invariância de Kolmogorov
- **Geometria diferencial de espaços de parâmetros**: como pequenas mudanças propagam por sistemas
- **Lógica de Hoare estendida**: pre/post-condições como contratos provados formalmente

---

## 1. Análise Matemática De Código

Quando analisa código, Prof. Euler sempre aplica:

**Teoria de Complexidade:**
```
Para cada algoritmo/pipeline, calcular:
- Complexidade de tempo: T(n) com constantes explícitas
- Complexidade de espaço: S(n) incluindo stack frames
- Complexidade amortizada: Φ(estrutura) com potencial de Banach
- Complexidade de comunicação: para sistemas distribuídos/BT
```

**Teoria dos Grafos:**
```
Modelar como grafo dirigido G = (V, E) onde:
- V = componentes/módulos/funções
- E = dependências/chamadas/fluxo de dados
- Detectar: ciclos (dependências circulares), cliques (acoplamento excessivo)
- Calcular: centralidade de betweenness (single points of failure)
- Analisar: componentes fortemente conectados (SCCs)
```

**Álgebra Linear para State Machines:**
```
Representar máquinas de estado como matrizes de transição M:
- M[i][j] = probabilidade de i→j
- Eigenvalues de M = estados estacionários
- Matriz de acessibilidade R = I + M + M² + ... + Mⁿ
```

**Teoria da Informação:**
```
Para cada interface/API, calcular:
- Entropia H(X) = -Σ p(x)log₂p(x) dos estados possíveis
- Informação mútua I(X;Y) entre inputs e outputs
- Capacidade de canal C = max I(X;Y) para otimização de throughput
```

---

## 2. Análise De Concorrência E Sistemas Reativos

Para coroutines, StateFlow, canais Kotlin, e sistemas Android assíncronos:

**Modelo CSP (Communicating Sequential Processes):**
```
Processo P = (S, s₀, Σ, δ, F) onde:
- S = conjunto de estados
- s₀ = estado inicial
- Σ = alfabeto de eventos
- δ: S × Σ → S = função de transição
- F ⊆ S = estados de aceitação

Verificar:
- Deadlock: estado s onde ∄ evento e: δ(s,e) definido
- Livelock: ciclo de estados não-produtivos
- Race condition: ∃ dois processos P, Q onde P ≻ Q ≠ Q ≻ P (não-comutatividade)
```

**Lógica Temporal (LTL/CTL):**
```
Propriedades a verificar:
- Safety: AG(¬bad_state) — "nunca acontece algo ruim"
- Liveness: AG(AF(good_state)) — "sempre eventualmente algo bom"
- Fairness: GF(enabled) → GF(executed) — "habilitado implica executado"
```

**Análise de Happens-Before (Lamport):**
```
Relação → (happens-before):
- a → b se ∃ sequência de comunicações a₁→a₂→...→b
- Race condition iff ∃ a,b: ¬(a→b) ∧ ¬(b→a) ∧ acessam mesmo dado
```

---

## 3. Análise De Performance E Otimização

**Teoria de Filas (Queuing Theory):**
```
Para pipelines de dados (voz → STT → LLM → TTS):
- Modelar como rede de Jackson: M/M/1 ou M/M/k queues
- λ = taxa de chegada, μ = taxa de serviço
- ρ = λ/μ = utilização (deve ser < 1 para estabilidade)
- E[W] = ρ/(μ(1-ρ)) = tempo médio de espera
- E[N] = ρ/(1-ρ) = número médio de itens
```

**Otimização Convexa:**
```
Para problemas de scheduling e alocação de recursos:
- Reformular como min f(x) s.t. g(x) ≤ 0, h(x) = 0
- Verificar convexidade: ∇²f(x) ⪰ 0 (Hessiana PSD)
- Dual de Lagrange: máx L(x,λ,ν) = f(x) + λᵀg(x) + νᵀh(x)
- Condições KKT para otimalidade global
```

**Análise de Séries Temporais para Latência:**
```
Para sistemas de tempo real (Bluetooth SCO, STT latency):
- Modelar como processo estocástico {X_t}
- Calcular: média μ, variância σ², autocorrelação R(τ)
- Detectar: estacionariedade (ADF test), outliers (Grubbs test)
- Predizer: ARIMA(p,d,q) para latência futura
- Bounds probabilísticos: P(latência > T) com concentração de Markov/Chebyshev
```

---

## 4. Análise Formal De Corretude

**Lógica de Hoare Estendida:**
```
Para cada função/método, escrever:
{Pré-condição P} código {Pós-condição Q}

Onde:
- P = conjunto de estados válidos de entrada (em lógica predicativa)
- Q = conjunto de estados válidos de saída
- Invariante de loop I: P→I, {I∧B}corpo{I}, I∧¬B→Q

Exemplos para Kotlin:
{token ≠ null ∧ |token| > 0} sendRequest(token) {result.isSuccess ∨ result.isError}
{isConnected = true} startSCO() {isRecording = true ∨ throws BluetoothException}
```

**Teoria dos Tipos como Lógica (Curry-Howard):**
```
Em Kotlin, tipos são proposições:
- A? = A ∨ ⊥ (nullable = pode falhar)
- Result<A,E> = A ∨ E (pode ser sucesso ou erro)
- Flow<A> = □A (sempre A, eventualmente)
- suspend fun = continuação monadica

Analisar: força o compilador a provar propriedades? Ou há "buracos" (force unwrap `!!`)?
```

---

## 5. Teoria Das Categorias Para Arquitetura

**Functores entre Camadas:**
```
Para arquitetura MVVM:
- Model: categoria de dados (objetos = tipos, morfismos = transformações)
- ViewModel: functor F: Model → ViewModel que preserva estrutura
- View: functor G: ViewModel → View

Composição: G∘F: Model → View (deve ser functorial — preservar identidades e composição)

Verificar: naturalidade das transformações (não depende de implementação específica)
```

**Mônadas para Side Effects:**
```
Identificar padrões monádicos no código:
- Maybe/Option: computação que pode falhar
- IO/Suspend: computação com efeitos colaterais
- State: computação com estado mutável
- Reader: computação com ambiente/configuração

Uma mônada M deve satisfazer:
1. Left identity: return a >>= f ≡ f a
2. Right identity: m >>= return ≡ m
3. Associativity: (m >>= f) >>= g ≡ m >>= (λx. f x >>= g)

Violações dessas leis = bugs sutis de composição
```

---

## Passo 1: Síntese Topológica

Antes de qualquer detalhe, construir o mapa de alto nível:
- Grafo de dependências (DGraph)
- Invariantes do sistema
- Fronteiras de abstração (interfaces formais)
- Fluxos de informação (setas de dados)

## Passo 2: Análise Multi-Escala

Analisar em 5 escalas simultâneas:
1. **Micro**: linha a linha — tipos, null safety, recursos
2. **Função**: complexidade, pré/pós-condições, side effects
3. **Módulo**: coesão, acoplamento, interfaces
4. **Sistema**: arquitetura, fluxos, estado global
5. **Meta**: corretude das abstrações, evoluibilidade, manutenibilidade

## Passo 3: Prova Por Contradição (Busca De Bugs)

Para cada invariante identificado, tentar **refutá-lo**:
- Existe estado inicial que viola a pré-condição?
- Existe sequência de eventos que quebra o invariante?
- Existe condição de contorno onde a pós-condição falha?
- Existe interleaving de threads que cria inconsistência?

## Passo 4: Síntese E Recomendações

Ordenar por impacto × probabilidade × corrigibilidade:
- Score = (Severidade: 1-10) × (P(ocorrência): 0-1) / (Custo de correção: 1-10)
- Priorizar os top-3 com maior score

## Passo 5: Prova Construtiva

Para cada recomendação, fornecer:
- Argumento matemático de por que é correto
- Contra-exemplo do estado atual (se aplicável)
- Código concreto da solução
- Invariantes que a solução preserva

---

## Análise Específica Do Projeto Auri/Earllm

Leia `references/auri-analysis.md` para o contexto completo do projeto.

## Módulos Críticos Para Análise Matemática

**Voice Pipeline** (`VoicePipeline.kt`):
```
Modelar como máquina de Mealy M = (S, I, O, δ, λ, s₀):
S = {IDLE, RECORDING, TRANSCRIBING, QUERYING_LLM, SPEAKING, ERROR}
I = {startRecording, stopRecording, sttResult, llmResult, ttsComplete, error}
O = {audioCapture, sttRequest, llmRequest, ttsRequest, notification}

Verificar:
- Completude: δ definida para todos (s,i) ∈ S×I?
- Determinismo: δ é função (não relação)?
- Alcançabilidade: todos estados em S são alcançáveis?
- Ausência de deadlock: ∄ s ∈ S: ∀i, δ(s,i) = s (estado absorvente indesejado)
```

**Bluetooth SCO** (`BluetoothController.kt`, `AudioRouteController.kt`):
```
Sistema de prioridade de roteamento como função monotônica:
priority: AudioSource → ℤ
priority(BLE) > priority(SCO) > priority(USB) > priority(WIRED) > priority(BUILTIN)

Invariante: O sistema sempre usa o source disponível de maior prioridade.
Verificar: quando um source de maior prioridade aparece, ocorre switching correto?
Corolário: sem starvation — source de alta prioridade não é ignorado indefinidamente
```

**Multi-LLM Client Factory** (`LlmClientFactory.kt`):
```
Factory como functor F: Provider → LlmClient
F deve ser:
- Total: definido para todos providers
- Determinístico: mesmo provider → mesmo tipo de cliente
- Composável: F(provider).send(msg) tem semântica consistente para todos providers

Análise de interface: LlmClient.send() deve satisfazer contrato uniforme:
{msg ≠ null ∧ apiKey válida} send(msg) {result é LlmResponse ∨ throws tipificado}
```

**AuriToolExecutor** (`AuriToolExecutor.kt`):
```
9 ferramentas = 9 operações com side effects sobre sistema Android
Cada tool é uma IO monad: IO<Result<ToolResult, ToolError>>

Analisar:
- Idempotência: tool(x) = tool(tool(x))? (critical para retry logic)
- Comutatividade: executar tool A então B = B então A? (para paralelização)
- Atomicidade: tool falha parcialmente ou tudo-ou-nada?
```

**Coroutines e StateFlow** (`MainViewModel.kt`):
```
StateFlow como processo reativo S = (State, Ev

## Relatório De Análise Matemática

```

### 1. Estrutura Formal

[Definição matemática do componente]

### 2. Invariantes Identificados

1. INV-01: [invariante em notação matemática ou pseudocódigo formal]
2. INV-02: ...

### 3. Propriedades Verificadas

✅ [Propriedade que foi verificada como correta + argumento]
⚠  [Propriedade suspeita + evidência]
❌ [Violação encontrada + contra-exemplo]

### 4. Análise De Complexidade

- Tempo: O(?) com argumento
- Espaço: O(?) com argumento
- Caso médio: Θ(?) com análise probabilística se relevante

### 5. Riscos Matemáticos Prioritizados

| Rank | Risco | Severidade | P(ocorrência) | Score |
|------|-------|-----------|--------------|-------|
| 1 | ... | 9/10 | 0.8 | 7.2 |

### 6. Recomendações Provadas

#### R-01: [Título]
**Argumento**: [Por que matematicamente esta mudança é correta]
**Implementação**:
```kotlin
// código concreto
```
**Invariante preservado**: [qual invariante esta solução mantém]
```

---

## 6. Modelo De Ciclo De Vida Android × Coroutines (Evolução V2)

A intersecção mais crítica de bugs Android — e raramente modelada formalmente.

## Escopos De Coroutine Como Autômatos De Ciclo De Vida

```
viewModelScope: Ciclo = onCreate → onCleared()
  - Sobrevive a rotações de tela (Configuration Changes)
  - Cancela apenas quando ViewModel é destruído (backstack pop, finish())
  - Usado para: operações de dados, observação de StateFlow

lifecycleScope: Ciclo = onCreate → onDestroy()
  - Cancela em qualquer destruição, incluindo rotações
  - Menos útil que repeatOnLifecycle para maioria dos casos

repeatOnLifecycle(State.STARTED): Ciclo = onStart → onStop (cicla!)
  - O padrão moderno correto para coletar Flows na UI
  - A cada onStop, cancela o collect; a cada onStart, reinicia
  - Evita processamento de updates quando app está em background

Invariante crítico para Auri VoicePipeline:
observeSttResults() usa viewModelScope → collect() continua em background
Correto para voice assistant (queries LLM mesmo em background)
Mas: STT callbacks chegam mesmo com UI destruída → UI updates tentam
atualizar Compose que não existe mais → crash potencial se não há guarda

Verificar: toda emissão para _state (StateFlow de UI) deve verificar
se há collector ativo, OU usar repeatOnLifecycle na UI
```

## Modelo Formal De Repeatonlifecycle

```
Seja L = (CREATED, STARTED, RESUMED, PAUSED, STOPPED, DESTROYED)
repeatOnLifecycle(State.X) define um processo que:
- ACTIVE quando lifecycle.state >= X
- CANCELLED quando lifecycle.state < X

Para cada transição de ciclo de vida → restart automático do Flow collect
Semantica: exatamente como ligar/desligar uma tomada em onStart/onStop

Quando usar o quê:
- StateFlow de UI state → repeatOnLifecycle(STARTED)
- StateFlow de dados de negócio → viewModelScope (sem parar)
- Events one-shot (toast, navigation) → SharedFlow ou Channel + viewModelScope
```

---

## Semântica Formal De Buffer

```
StateFlow<T>:
  - Buffer = 1 (apenas último valor)
  - Replay = 1 (novo subscriber recebe último valor imediatamente)
  - Fusão: emissões rápidas são fundidas — estados intermediários PERDIDOS
  - Invariante: _state.value sempre reflete o estado ATUAL

SharedFlow<T>(replay=0, extraBufferCapacity=N):
  - Buffer = N (configurgável)
  - Replay = configurgável (0 = sem replay para novos subscribers)
  - Sem fusão: cada emissão distinta é entregue (se buffer não transborda)
  - Uso: eventos one-shot (erros, navegação, toasts)

Channel<T>(BUFFERED):
  - Produção-consumo: cada item entregue exatamente uma vez
  - Sem replay
  - Hot: produção pode bloquear se buffer cheio
  - Uso: comunicação ponto-a-ponto entre coroutines

Decisão matemática para cada caso em Auri:
pipelineState         → StateFlow ✅ (UI quer estado atual, não histórico)
erros para toast      → SharedFlow(extraBufferCapacity=10) ✅ (one-shot events)
audio PCM chunks      → Channel(BUFFERED) ✅ (stream point-to-point)
sttResult            → StateFlow ✅ (UI quer resultado atual)
```

## Anti-Padrão: Stateflow Para Eventos One-Shot

```kotlin
// ERRADO: usar StateFlow para eventos one-shot
private val _error = MutableStateFlow<String?>(null)

// Problema 1: novo observer recebe o erro antigo ao se registrar
// Problema 2: para "consumir" o erro, precisa emitir null depois
// Problema 3: race condition entre emitir null e próxima leitura

// CORRETO: SharedFlow para eventos one-shot
private val _error = MutableSharedFlow<String>(extraBufferCapacity = 1)
fun sendError(msg: String) { _error.tryEmit(msg) }
```

---

## Recomposition Complexity Index (Rci)

```
RCI(C) = CC(C) × (1 - stability_ratio(C)) × depth_of_state_reads(C)

Onde:
- CC = complexidade ciclomática da função @Composable
- stability_ratio = fração de parâmetros @Stable ou primitivos
- depth_of_state_reads = quantos StateFlows diferentes são lidos em C

Para DiagnosticsScreen (CC=54, lê 4+ StateFlows, poucos params estáveis):
RCI ≈ 54 × 0.8 × 4 = 172.8  ← CRÍTICO

Para comparação: HomeScreen ideal teria RCI < 20

Consequência: qualquer mudança em qualquer um dos 4+ StateFlows
aciona recomposição do scope INTEIRO de DiagnosticsScreen.
Se STT state muda 10x/segundo → DiagnosticsScreen recompõe 10x/segundo.
```

## Otimizações Para Reduzir Rci

```kotlin
// PADRÃO 1: derivedStateOf — só recompõe se resultado muda
val isRecording by remember {
    derivedStateOf { pipelineState.value.stage == RECORDING }
}

// PADRÃO 2: dividir em sub-composables menores
@Composable fun DiagnosticsScreen(...) {
    Column {
        SttDiagnostics(sttState)      // recompõe só quando sttState muda
        BtDiagnostics(btState)        // recompõe só quando btState muda
        LlmDiagnostics(llmState)      // recompõe só quando llmState muda
    }
}

// PADRÃO 3: key() para forçar identidade estável
LazyColumn {
    items(items = tools, key = { it.id }) { tool ->
        ToolCard(tool)  // apenas o item com id mudado recompõe
    }
}
```

---

## Taxonomia De Segurança De Intents

```
Intent I = (action?, componentName?, data?, extras, flags)

Segurança formal:
- Explicit Intent: componentName ≠ null
  → Entregue exatamente ao componente especificado
  → Seguro: só aquele app recebe

- Implicit Intent: componentName = null, action ≠ null
  → Sistema resolve para apps com intent-filter matching
  → INSEGURO se múltiplos apps podem responder
  → Risco: app malicioso declara intent-filter → intercepta

Análise AuriToolExecutor:
makePhoneCall()  → ACTION_CALL (implicit) → qualquer app pode interceptar
setAlarm()       → ACTION_SET_ALARM (implicit) → qualquer app de alarme
sendEmail()      → GmailClient direto (API) → não usa Intent → SEGURO
sendWhatsApp()   → URL scheme "https://wa.me/" → qualquer browser intercepta
                   EXCETO quando usa ACTION_SEND + setPackage("com.whatsapp") → SEGURO

Risco de Intent Hijacking para chamada telefônica:
P(interceptado | app malicioso instalado) = 1.0 (se app registrou ACTION_CALL)
P(app malicioso instalado) = baixo em dispositivos normais, mas não zero
Mitigação: verificar intent.resolveActivity() antes de lançar, ou usar
ACTION_DIAL (mais seguro: exige confirmação do usuário)
```

## Correção Formal Para Sendwhatsapp()

```kotlin
// INSEGURO: URL scheme pode ir para qualquer browser
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://wa.me/$phone?text=$text")))

// SEGURO: explicit via setPackage
val intent = Intent(Intent.ACTION_SEND).apply {
    type = "text/plain"
    putExtra(Intent.EXTRA_TEXT, "$phone: $text")
    setPackage("com.whatsapp")  // força WhatsApp específico
}
if (intent.resolveActivity(packageManager) != null) {
    startActivity(intent)
} else {
    // fallback gracioso
}
```

---

## Modelo De Custo Como Random Walk

```
Seja C_n = custo acumulado após n chamadas LLM (em USD)
C_n = Σ(i=1..n) X_i

Onde X_i = custo da i-ésima chamada:
X_i = (input_tokens_i × price_input + output_tokens_i × price_output) / 1000

Para gpt-4o (2025): price_input=$0.0025/1K, price_output=$0.010/1K
X_i típico: 200 input tokens + 150 output tokens ≈ $0.0005 + $0.0015 = $0.002

E[C_n] = n × E[X_i] = n × $0.002
Var[C_n] = n × Var[X_i]

Risco de ruína: P(C_n > L) → 1 para n → ∞ (crescimento inevitável)

Concentração de Chebyshev:
P(|C_n - E[C_n]| > k×sqrt(Var[C_n])) ≤ 1/k²

Para n=100 chamadas: E[C_100] ≈ $0.20, P(> $0.50) < 10% (k≈3)
Para n=1000 chamadas: E[C_1000] ≈ $2.00, P(> $5.00) < 10%
```

## Crescimento De Contexto — Ponto De Ruptura

```
Histórico de conversação em Auri: _conversationHistory.value = history + listOf(...)
Crescimento: O(n) tokens por n turnos (sem truncamento)

Para gpt-4o com max_context=128k tokens:
Ponto de ruptura: n_max = 128000 / avg_tokens_per_turn ≈ 128000 / 350 ≈ 365 turnos

Após 365 turnos: HTTP 400 "context_length_exceeded" — não tratado explicitamente
Comportamento atual: exceção genérica → estado ERROR no pipeline

Estratégia ótima de truncamento (Sliding Window com preservação):
Manter: [system_prompt] + [últimas K mensagens completas] + [resumo comprimido das antigas]
K ótimo: K = max_context / (2 × avg_tokens_per_turn) — usa metade do contexto
Resumo: comprimir messages[0..n-K] em 1-2 frases via LLM summary call
Custo extra do resumo: 1 chamada adicional a cada K turnos ≈ amortizado para 0
```

---

## Referências Técnicas

Para análise detalhada, consulte:
- `references/auri-analysis.md` — Contexto completo do projeto Auri (invariantes, estados, riscos)
- `references/complexity-patterns.md` — Padrões de complexidade em Android: CC, cognitiva, acoplamento
- `references/concurrency-models.md` — CSP, Actor Model, JMM, deadlocks, race conditions Kotlin
- `references/information-theory.md` — Entropia de Shannon, Kolmogorov, teoria de filas, backpressure
- `scripts/complexity_analyzer.py` — Análise automática CC + acoplamento (run: `python complexity_analyzer.py C:/project`)
- `scripts/dependency_graph.py` — Grafo de dependências: ciclos, betweenness, PageRank (run: `python dependency_graph.py C:/project`)

---

## Quando Acionado, Prof. Euler Sempre:

1. **Pergunta antes de assumir** — "Qual aspecto você quer analisar mais profundamente?"
2. **Mostra o trabalho matemático** — não apenas conclusões, mas o raciocínio formal
3. **Dá exemplos concretos** — cada abstração matemática tem um exemplo em código real
4. **Prioriza por impacto** — não lista 50 problemas, mas os 3-5 mais críticos com scores
5. **Oferece múltiplas perspectivas** — o mesmo problema visto por teoria dos grafos, teoria da informação, e teoria dos tipos
6. **É honesto sobre incerteza** — "com os dados disponíveis, há 70% de probabilidade de que..."
7. **Propõe experimentos** — "para confirmar esta hipótese, execute: [comando/teste específico]"

## Quando Não Tem Informação Suficiente:

- Solicitar arquivos específicos para análise
- Listar exatamente quais informações precisaria
- Dar análise parcial com as informações disponíveis + hipóteses explícitas

## Tom E Estilo:

- Rigoroso mas acessível — explica matemática complexa com analogias concretas
- Confiante mas humilde — mostra incerteza quando existe
- Construtivo — cada problema tem solução proposta
- Preciso — usa notação matemática quando clarifica, linguagem natural quando suficiente

## Best Practices

- Provide clear, specific context about your project and requirements
- Review all suggestions before applying them to production code
- Combine with other complementary skills for comprehensive analysis

## Common Pitfalls

- Using this skill for tasks outside its domain expertise
- Applying recommendations without understanding your specific context
- Not providing enough project context for accurate analysis

## Related Skills

- `007` - Complementary skill for enhanced analysis
- `claude-code-expert` - Complementary skill for enhanced analysis

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: material-design
description: Web and App implementation guide for Material Design. Trigger when user wants Google's aesthetic, elevation, motion, and consistent components.
date_added: "2026-06-17"
risk: safe
source: self
source_type: self
---

# Material Design

> "Digital paper and ink. Interfaces built on the physical properties of stacked material."

## When to Use
Use this sub-style when the user's request matches the aesthetic described above. This is a child reference of the `design-it` skill and is not meant to be triggered directly.

## Core Principles
1. **Z-Axis Elevation**: Everything exists on a specific layer. Shadows communicate hierarchy and state.
2. **Meaningful Motion**: Animations are continuous, guiding the user's focus from one state to the next (e.g., ripple effects, shared element transitions).
3. **Structured Layout**: Strict adherence to an 8dp baseline grid and specific component anatomies (cards, FABs, app bars).

## Visual DNA
- **Colors**: Works excellently with **Desert Mirage** or **Minimalist Slate**. Utilize primary, secondary, surface, and error semantic mapping.
- **Typography**: `Roboto` or `Google Sans` (or equivalent clean geometric sans). Stick strictly to the Material Type Scale (H1-H6, Subtitle, Body, Caption, Overline).
- **Shapes**: Moderately rounded corners (4px to 16px).

## Web Implementation
- Do not reinvent the wheel: mimic standard Material elevations.
- **CSS Example**:
```css
.material-card {
  background: var(--bg-surface);
  border-radius: 8px;
  padding: 16px;
  /* Material Elevation 2 */
  box-shadow: 0 3px 1px -2px rgba(0,0,0,0.2),
              0 2px 2px 0 rgba(0,0,0,0.14),
              0 1px 5px 0 rgba(0,0,0,0.12);
  transition: box-shadow 0.28s cubic-bezier(0.4, 0, 0.2, 1);
}

.material-btn {
  text-transform: uppercase;
  font-weight: 500;
  letter-spacing: 1.25px;
  padding: 0 16px;
  height: 36px;
  border-radius: 4px;
  background: var(--cta-highlight);
  color: #fff;
  border: none;
  /* Ripple effect is usually handled via JS, but structure is key */
}
```

## App Implementation

### SwiftUI
```swift
struct MaterialCard: View {
    var body: some View {
        VStack(alignment: .leading, spacing: 12) {
            Text("Material Card")
                .font(.system(size: 20, weight: .medium))
            Text("Digital paper and ink. Shadows communicate where this surface sits.")
                .font(.system(size: 14))
                .foregroundColor(.secondary)
            HStack {
                Spacer()
                Button("ACTION") {}
                    .font(.system(size: 14, weight: .medium))
                    .foregroundColor(.accentColor)
                    .padding(.horizontal, 12)
                    .padding(.vertical, 8)
            }
        }
        .padding(16)
        .background(Color(.systemBackground))
        .cornerRadius(8)
        // Material Elevation 2 equivalent
        .shadow(color: Color.black.opacity(0.12), radius: 3, x: 0, y: 1)
        .shadow(color: Color.black.opacity(0.08), radius: 2, x: 0, y: 2)
    }
}

// Material FAB
struct MaterialFAB: View {
    var body: some View {
        Button(action: {}) {
            Image(systemName: "plus")
                .font(.system(size: 24))
                .foregroundColor(.white)
                .frame(width: 56, height: 56)
                .background(Color.accentColor)
                .cornerRadius(16)
                .shadow(color: Color.black.opacity(0.2), radius: 6, x: 0, y: 3)
                .shadow(color: Color.black.opacity(0.14), radius: 4, x: 0, y: 2)
        }
    }
}
```
- Emulate Material elevation levels by stacking multiple `.shadow()` modifiers at different blur/offset values.
- Use `.cornerRadius(8...16)` — Material Design 3 uses more rounded shapes than M2.
- Animate shadow changes using `.animation(.easeInOut(duration: 0.28))` — Material uses 280ms transitions.

### Flutter
```dart
// Flutter IS Material Design — use it natively
class MaterialScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        useMaterial3: true,
        colorSchemeSeed: const Color(0xFF6750A4), // Material You seed
        // Map your universal palette here
      ),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Material Design'),
          // M3 appbar elevation is 0 by default, scrolled = 3
        ),
        body: Padding(
          padding: const EdgeInsets.all(16),
          child: Card(
            elevation: 2,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text('Material Card',
                    style: Theme.of(context).textTheme.titleLarge),
                  const SizedBox(height: 8),
                  Text('Digital paper and ink.',
                    style: Theme.of(context).textTheme.bodyMedium),
                  const SizedBox(height: 16),
                  Align(
                    alignment: Alignment.centerRight,
                    child: TextButton(
                      onPressed: () {},
                      child: const Text('ACTION'),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {},
          child: const Icon(Icons.add),
          // M3 FAB automatically gets correct elevation & shape
        ),
      ),
    );
  }
}
```
- **Flutter is the native home of Material Design.** Use `MaterialApp`, `ThemeData(useMaterial3: true)`, and standard widgets.
- Map the universal palette via `colorSchemeSeed` or manually build a `ColorScheme`.
- Use the Material type scale via `Theme.of(context).textTheme`.
- Ripple effects come free with `InkWell` and `ElevatedButton`.

### React Native
```jsx
import { Provider as PaperProvider, Card, Button, Title, Paragraph } from 'react-native-paper';

const materialTheme = {
  ...DefaultTheme,
  roundness: 8,
  colors: {
    ...DefaultTheme.colors,
    primary: '#6750A4',    // Material You purple
    surface: '#FFFBFE',
    background: '#FFFBFE',
  },
};

const MaterialScreen = () => (
  <PaperProvider theme={materialTheme}>
    <ScrollView style={{ flex: 1, padding: 16 }}>
      <Card style={{ marginBottom: 16 }} elevation={2}>
        <Card.Content>
          <Title>Material Card</Title>
          <Paragraph>Digital paper and ink. Shadows communicate hierarchy.</Paragraph>
        </Card.Content>
        <Card.Actions>
          <Button mode="text" onPress={() => {}}>ACTION</Button>
        </Card.Actions>
      </Card>

      {/* Filled button — Material M3 style */}
      <Button
        mode="contained"
        onPress={() => {}}
        style={{ alignSelf: 'flex-start', borderRadius: 20 }}
        labelStyle={{ fontWeight: '500', letterSpacing: 1.25 }}
      >
        Filled Button
      </Button>
    </ScrollView>
  </PaperProvider>
);
```
- Use `react-native-paper` — it implements Material Design 3 natively for React Native.
- Configure the theme to map your universal palettes to Material semantic colors.
- Use `Card` (with `elevation` prop), `Button` (with `mode` prop), and `TextInput` for correct Material behavior.
- Ripple effects on Android come free via `Pressable`; on iOS, use `react-native-paper`'s `TouchableRipple`.

### Jetpack Compose
```kotlin
// Jetpack Compose IS Material Design — use it natively
@Composable
fun MaterialScreen() {
    MaterialTheme(
        colorScheme = lightColorScheme(
            primary = Color(0xFF6750A4),
            onPrimary = Color.White,
            surface = Color(0xFFFFFBFE),
        ),
        typography = Typography(
            titleLarge = TextStyle(fontSize = 22.sp, fontWeight = FontWeight.Medium),
            bodyMedium = TextStyle(fontSize = 14.sp, lineHeight = 20.sp),
        ),
    ) {
        Scaffold(
            topBar = {
                TopAppBar(title = { Text("Material Design") })
            },
            floatingActionButton = {
                FloatingActionButton(onClick = {}) {
                    Icon(Icons.Default.Add, contentDescription = "Add")
                }
            },
        ) { padding ->
            Column(modifier = Modifier.padding(padding).padding(16.dp)) {
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
                    shape = RoundedCornerShape(12.dp),
                ) {
                    Column(modifier = Modifier.padding(16.dp)) {
                        Text("Material Card",
                            style = MaterialTheme.typography.titleLarge)
                        Spacer(Modifier.height(8.dp))
                        Text("Digital paper and ink.",
                            style = MaterialTheme.typography.bodyMedium)
                        Spacer(Modifier.height(16.dp))
                        TextButton(
                            onClick = {},
                            modifier = Modifier.align(Alignment.End),
                        ) { Text("ACTION") }
                    }
                }
            }
        }
    }
}
```
- **Jetpack Compose is Material Design.** Use `MaterialTheme`, `Card`, `Scaffold`, `TopAppBar`, and `FloatingActionButton` as-is.
- Map the universal palette into `lightColorScheme()` or `darkColorScheme()`.
- Use `MaterialTheme.typography` for the complete type scale.
- Motion uses `animateFloatAsState` with Material easing: `FastOutSlowInEasing` (equivalent to `cubic-bezier(0.4, 0.0, 0.2, 1)`).

## Do's and Don'ts
- **DO**: Use the standard Material easing curves for animations (`cubic-bezier(0.4, 0.0, 0.2, 1)`).
- **DON'T**: Mix overlapping shadows arbitrarily. Elements should clearly sit 'above' or 'below' others.

## Limitations
- This is a styling reference and does not replace environment-specific validation, accessibility testing, or expert review.
- Ensure appropriate contrast ratios and responsive behaviors are verified separately.


---
name: mathguard
description: "Math-heavy escalation for n >= 10^6 — Bloom, HyperLogLog, Count-Min, MinHash/LSH, FFT, JL projection, sweep line. Use when classical O(n log n) is the floor and approximate or math wins."
risk: safe
source: community
source_repo: morsechimwai/lemmaly
source_type: community
date_added: "2026-05-26"
author: morsechimwai
tags: [algorithms, probabilistic-data-structures, approximate-algorithms, bloom-filter, hyperloglog, fft, performance]
tools: [claude-code, antigravity, cursor, gemini-cli, codex-cli]
license: "Apache-2.0"
license_source: "https://github.com/morsechimwai/lemmaly/blob/main/LICENSE"
---

# mathguard — Math-Heavy Optimization for AI Code

`lemmaly` makes you pick the right classical algorithm. `mathguard` kicks in when the classical algorithm is already optimal but **mathematics gives a better bound** — usually by accepting bounded approximation, exploiting structure, or moving to a smarter algebraic space.

The model knows these techniques. It almost never proposes them spontaneously. mathguard fixes that.

**Violating the letter of these rules is violating the spirit of the skill.** A Bloom filter where the caller assumed exact answers is a production incident, not an optimization.

## When to Use This Skill

Use **mathguard** when:

- Working with large-scale data (`n ≥ 10⁶`): similarity search, deduplication, top-K / heavy-hitters, streaming analytics, cardinality estimation, embeddings, recommender systems.
- Doing signal/image processing, polynomial or big-integer arithmetic, convolution, graph distance, computational geometry, randomized algorithms.
- The classical O(n log n) is already the floor and you need an asymptotic win (Bloom filter, HyperLogLog, Count-Min Sketch, MinHash/LSH, FFT/NTT, Johnson-Lindenstrauss projection, sweep line, kd-tree/BVH, fast exponentiation, monoid parallel reduction, amortized potential method).
- Loaded *after* `lemmaly` has confirmed the classical answer is not enough.

Do **not** use mathguard when:
- The caller needs exact answers (auth, billing, dedup-for-correctness, primary keys).
- `n` is small (n < 10⁴) and the path is not hot.
- The bottleneck is I/O, not CPU/memory.

## The Iron Law

```text
NO APPROXIMATE STRUCTURE WITHOUT WRITTEN ε/δ AND EXPLICIT CALLER ACCEPTANCE
```

Probabilistic data structures (Bloom, HyperLogLog, Count-Min, MinHash/LSH, t-digest), randomized projections (JL), and lossy transforms (floating FFT) all change the answer's meaning. Before proposing one:

1. Write the error parameter the caller will see (false-positive rate, relative error, distortion bound).
2. Identify the caller and state, in one sentence, that they tolerate this kind of wrong answer.
3. If you cannot identify the caller, or they need exact (auth checks, billing, dedup keys, deduplication for correctness, anything that flows into a primary key), DO NOT propose the approximate structure. Keep classical, or escalate to a sharded/streaming exact design.

This rule has saved more incidents than any other in this skill. Do not soften it.

## Non-negotiable rules

1. **Declare exact vs approximate up front.** Before suggesting a math-level technique, state:
   - `mode: exact` or `mode: approximate`
   - If approximate: the error parameter (ε, δ, false-positive rate) and a sentence on whether the caller can tolerate it.
   - If the caller needs exact and there is no exact win, say so and stop — do not silently degrade to approximate.

2. **Cite the technique by name.** Never describe a probabilistic or numerical trick in vague terms. Name it: `Bloom filter`, `HyperLogLog`, `Count-Min Sketch`, `MinHash + LSH`, `Johnson–Lindenstrauss projection`, `FFT`, `NTT`, `fast exponentiation`, `Karatsuba`, `Strassen`, `sweep line`, `kd-tree`, `BVH`, `union-find with path compression`, `Floyd's cycle detection`, `Boyer-Moore majority`, `reservoir sampling`, `Knuth shuffle`, `Aho-Corasick`, `suffix automaton`, `segment tree with lazy propagation`, `Fenwick tree`, `monoid scan / parallel prefix`. A named technique is auditable; "a smart approximation" is not.

3. **State the trade you are making.** Every math-level optimization buys something at a cost. In one line:
   - Buys: `space`, `time`, `wall-clock`, `parallelism`.
   - Costs: `accuracy ε=?`, `code complexity`, `dependency`, `non-determinism`, `numerical stability`.
   - If the cost is invisible to the caller, write "callers see no change".

4. **Justify the asymptotic win.** Do not propose a math technique without a one-line bound argument:
   - "HyperLogLog: count uniques in O(log log n) bits at standard error 1.04/√m."
   - "FFT: polynomial multiplication O(n log n) vs schoolbook O(n²)."
   - "JL projection: preserves pairwise distances within (1±ε) using O(log n / ε²) dimensions."
   - "Sweep line: rectangle overlap from O(n²) pair checks to O(n log n) events."
   No bound, no proposal.

5. **Forbid math cargo-culting.** Do not introduce these techniques when:
   - n is small enough that a linear scan finishes in microseconds (n < ~10⁴ unless it is a hot path).
   - The problem is I/O-bound — the math win disappears behind network/disk.
   - Exact answers are required and no exact technique exists.
   - The team will not maintain it (write that down: "team familiarity: ?").

## The pre-proposal protocol

Before suggesting a math-level technique, your message must contain — in this order:

1. **The classical floor** — what is the best non-mathy algorithm and its Big-O? ("Hash join is O(n+m); we're already there.")
2. **Why classical is not enough** — n too large, space blows up, real-time deadline, etc.
3. **The math technique** — named (rule 2).
4. **Exact or approximate** — with ε if approximate (rule 1).
5. **The new bound** — with one-line derivation (rule 4).
6. **The trade** — buys/costs (rule 3).
7. **When NOT to use this** — at least one disqualifier.
8. **The code or pseudocode.**

If any of 1–7 is missing, do not propose the technique.

## Playbook — math technique → problem → win → caveat

### Sketches and probabilistic structures (massive data, approximate)

| Problem | Classical | Math technique | Win | Caveat |
|---|---|---|---|---|
| Membership: "have I seen this key?" at scale | `Set<id>`, O(n) space | **Bloom filter** | O(n) bits at chosen ε false-positive | False positives only; cannot remove (use Cuckoo if needed) |
| Count distinct values in a stream | `Set` to count, O(unique) space | **HyperLogLog** | O(log log n) bits, ~1% relative error | Approximate; cannot list elements |
| Top-K / heavy hitters in a stream | full counter, O(unique) space | **Count-Min Sketch** + heap | O(log(1/δ)·1/ε) space | Overestimates; choose ε,δ deliberately |
| Document / set similarity at scale | full Jaccard, O(n·m) | **MinHash + LSH** | Sub-linear ANN query | Tunes recall vs precision; param search |
| k-NN in high-dim vectors | brute O(n·d) | **JL projection → HNSW / IVF** | O(log n) per query, (1±ε) distortion | Index build cost; recall < 1 |
| Reservoir of size k from a stream of unknown length | buffer all, O(n) space | **Reservoir sampling** | O(k) space, uniform sample | Single-pass only |
| Find majority element | counter map | **Boyer-Moore majority vote** | O(1) space, O(n) time | Requires majority exists; verify pass |
| Quantiles in a stream | sort, O(n log n) | **t-digest / GK** | O(1/ε) space, ε-accurate quantiles | Approximate |

### Fast arithmetic / transforms (numeric and combinatorial)

| Problem | Classical | Math technique | Win | Caveat |
|---|---|---|---|---|
| Multiply two polynomials / big integers | O(n²) | **FFT / NTT / Karatsuba** | O(n log n) | Floating FFT loses precision — use NTT for integers |
| Convolution of two signals | O(n·m) | **FFT-based convolution** | O((n+m) log(n+m)) | Numerical noise at very small magnitudes |
| `pow(a, b) mod p`, b large | O(b) multiplications | **Fast exponentiation (square-and-multiply)** | O(log b) | Watch for overflow inside; use modular arithmetic |
| GCD of large integers | repeated subtraction | **Euclidean algorithm** | O(log min) | Standard; AI sometimes still writes the subtraction loop |
| Matrix multiplication, n large | O(n³) | **Strassen** (then Coppersmith-Winograd family) | O(n^2.81) | High constant; only wins for very large dense |
| Solving Ax=b for sparse A | O(n³) dense | **Conjugate gradient / sparse LU** | O(nnz · iterations) | Numerical conditioning matters |
| Modular inverse | brute force | **Extended Euclidean** or **Fermat** when p prime | O(log p) | p must be prime for Fermat |

### Dimensionality reduction and linear algebra

| Problem | Classical | Math technique | Win | Caveat |
|---|---|---|---|---|
| Similarity in d-dim, d large | O(n·d) brute | **JL projection** to k = O(log n / ε²) | O(n·k) at (1±ε) distortion | Random; verify on validation set |
| Recommender from rating matrix | iterate full matrix | **Truncated SVD / matrix factorization** | O(k·(n+m)) for rank-k | Choose k; refresh strategy |
| Document-term similarity | TF-IDF O(n·m) | **LSA via SVD** | rank-k approximation | Latent dims are not interpretable |
| PCA on n samples in d dims | O(n·d²) | **Randomized SVD** | O(n·d·k) for rank-k | Randomized; set oversampling |

### Geometry (spatial queries)

| Problem | Classical | Math technique | Win | Caveat |
|---|---|---|---|---|
| Range / nearest-neighbor in 2D-3D | O(n) per query | **kd-tree / R-tree / BVH** | O(log n) per query | Degrades in high d; use ANN instead |
| Rectangle / interval overlap pairs | O(n²) pair check | **Sweep line + active set (BBST)** | O((n+k) log n) | k = output size; segment tree variant exists |
| Polygon point-in-polygon at scale | O(n·v) | **BSP / monotone decomposition / R-tree** | O(log v) per query after build | Build cost |
| Convex hull of n points | O(n²) gift wrap | **Graham scan / Andrew's monotone chain** | O(n log n) | Numerical robustness for collinear |
| Closest pair of points | O(n²) | **Divide and conquer** | O(n log n) | Carefully merge across the strip |

### Graph and algebraic tricks

| Problem | Classical | Math technique | Win | Caveat |
|---|---|---|---|---|
| Connected components under merges | recompute BFS each merge | **Union-Find with path compression + rank** | α(n) ≈ O(1) per op amortized | Inverse Ackermann is effectively constant |
| Range sum / update on array | O(n) per query | **Fenwick tree** | O(log n) per op | Inclusive ranges; off-by-one risk |
| Range query with monoid (sum/min/max/gcd) | O(n) per query | **Segment tree (with lazy if range updates)** | O(log n) | More code than Fenwick; more general |
| LCA in a tree, many queries | O(n) per query | **Binary lifting** or **Euler tour + RMQ** | O(log n) or O(1) per query | Preprocessing cost |
| Shortest path on DAG | Dijkstra | **Topo sort + relax** | O(V+E) | Only works on DAG |
| Detect cycle in linked list | hash visited | **Floyd's tortoise and hare** | O(1) space | Same big-O time, dramatic space win |
| Parallel reduction over n items | sequential fold | **Monoid + parallel scan** | O(n/p + log p) on p cores | Operation must be associative; verify it |

### Amortized and online algorithms

| Problem | Classical | Math technique | Win | Caveat |
|---|---|---|---|---|
| "Dynamic array push is expensive" | per-op O(n) on resize | **Amortized analysis (doubling)** | O(1) amortized | This is what `ArrayList` / `vec` already do; just defend it |
| Streaming median | re-sort | **Two heaps (max-heap + min-heap)** | O(log n) per insert | Maintain size invariant |
| Online interval scheduling | re-sort by deadline | **Greedy with priority queue** | O(log n) per arrival | Specific objective; check problem fit |
| Sliding-window max | O(n·k) | **Monotonic deque** | O(n) total | Window invariant subtle to maintain |

## Canonical example — counting distinct users

**Problem.** Count unique users seen across a 24-hour event stream. ~2B events/day, ~50M unique users. Reported on a dashboard, ±2% is acceptable.

### Without the protocol — silent OOM, or worse, silent billing error

```ts
// "Just use a Set" — silently OOMs the box at ~50M strings
const seen = new Set<string>();
for await (const event of stream) {
  seen.add(event.userId);
}
return seen.size; // exact, but the process died at row 41M
```

Or worse — proposed *with* a HyperLogLog "for performance" but plugged into the billing pipeline, which keys off the result. Billing then sees 49.7M instead of 50.0M users and a fraction never get charged.

### With the protocol — auditable HLL

```ts
// Classical floor: O(unique) memory for an exact Set. At 50M strings × ~50B each, ~2.5GB.
// Why classical is not enough: dashboard box has 512MB and refreshes every minute.
// Technique: HyperLogLog (HLL).
// Mode: approximate. ε ≈ 1.04/√m. With m=2^14 registers → ~0.8% relative error.
// Trade: buys O(log log n)-bit space (~12KB); costs ±0.8% on the displayed count.
// When NOT to use: anything that flows into billing, primary keys, or per-user actions.
// Caller acceptance: confirmed — dashboard product owner accepts ±2%, written in PR.

import { createHLL } from 'hyperloglog-lite';
const hll = createHLL({ precision: 14 });
for await (const event of stream) {
  hll.add(event.userId);
}
return hll.estimate(); // 49.6M ± 0.4M; dashboard reads ~50M
```

The first version is not "no HLL" — it is "HLL without writing down ε and who tolerates it." The second is identical in technique but auditable: ε is in the comment, the caller is named, the disqualifier (billing) is explicit.

## Output discipline

Code that uses a math-level technique must include:

- One comment naming the technique with a doc link or one-line citation.
- The exact error parameters chosen (ε, δ, bits, dimensions, etc.) and why those values.
- A measured or asymptotic justification next to the chosen parameters.
- An exact-mode fallback path, if the caller might need it.

## When to escalate or redirect

- The bottleneck is I/O, not CPU/memory → go back to `lemmaly` rule 4; math will not help.
- You need bit-exact reproducibility → avoid floating FFT, randomized projections, and probabilistic structures.
- The result is consumed by a downstream system that assumes exact → keep classical or wrap with a validation pass.
- You need a correctness proof (not just a bound) → load **invariant-guard** after picking the technique.

## Rationalizations to watch for

| Excuse | Reality |
| --- | --- |
| "A `set` works — I'll flag the memory issue in a comment." | Noticing the problem is not solving it. If memory is the budget, ship the structure that respects it. |
| "Probabilistic structures sound fancy / academic." | Cloudflare runs Bloom filters in the request path. Redis ships HyperLogLog. These are production-tested, not academic. |
| "Approximate is risky — I'll do exact and let it OOM later." | Silent OOM at 3am is riskier than a stated 0.81% error. State the ε, pick parameters, ship. |
| "I'll just shard the set across machines." | Sharding multiplies your infra cost; HLL solves it in 12KB on one box. Ask whether you actually need exact. |
| "FFT is overkill for this." | True 99% of the time. But state the n. At n ≥ ~64 for polynomial mult, schoolbook is already losing. |
| "JL projection feels too lossy for embeddings." | At ε = 0.1, JL preserves pairwise distances within 10%. For ANN this is almost always fine — measure recall, do not eyeball. |

## Red flags — STOP

- Proposing a probabilistic structure without stating ε and δ.
- Saying "we can use FFT here" without writing the n at which FFT actually beats schoolbook.
- Using `JSON.parse(JSON.stringify(...))` to deep-clone when `structuredClone` exists, then claiming it as an optimization.
- Recommending Strassen on a 100×100 matrix.
- Switching to approximate output without the caller having agreed to it.
- Naming a technique you cannot derive the bound for.
- Math optimization where n is small and not on a hot path.
- "Should be O(log n) on average" with no average-case argument.

## Verification checklist

Before shipping code that uses a math-level technique:

- [ ] The technique is named (no "a smart approximation").
- [ ] If approximate: ε and δ (or the equivalent error parameter) are written in code or in the PR description.
- [ ] The caller has been identified and their tolerance for that error is stated.
- [ ] A one-line bound derivation is present (asymptotic or measured).
- [ ] At least one disqualifier ("when NOT to use this") is documented.
- [ ] An exact-mode fallback exists, OR a one-line note explains why exact is impossible.
- [ ] If randomized: the seed strategy is documented (fixed for reproducibility, or stated as non-deterministic).
- [ ] Downstream consumers that assume exactness (joins on this value, billing, auth, primary keys) have been audited.

Cannot check every box? The technique is not ready to ship. Keep classical, or stop and ask.

## Limitations

- **Not for exact-required pipelines.** Any system where the result is a primary key, dedup key, billing input, or auth decision is out of scope — keep classical.
- **Assumes representative inputs.** ε/δ bounds are average-case or high-probability; adversarial inputs can blow past them. State the threat model.
- **Library quality varies.** Bloom / HLL / MinHash implementations differ in seed strategy, hash function, and memory layout — pick a maintained library and pin the version.
- **Numerical stability.** Floating FFT, randomized SVD, and JL projection accumulate float error; for combinatorial exactness use NTT or exact integer variants.
- **Team-familiarity risk.** A technique nobody can debug at 3 a.m. is a liability — write the maintainer note next to the trade-off.
- **Not a profiler.** mathguard tells you which asymptotic ceiling you can break; it does not measure constant factors. Benchmark before claiming a wall-clock win.

## The thesis, in one line

> **When classical algorithms hit their floor, mathematics still has another floor below. mathguard makes the model reach for it instead of accepting the first answer.**

## Related Skills

- `lemmaly` — gateway; pick the classical algorithm first before reaching for math.
- `invariant-guard` — for stating ε-bounds as part of the postcondition of an approximate algorithm.
- `complexity-cuts` — when baseline code already exists and the bottleneck is CPU/memory, not approximation.