{"id":"23503b10-6179-435a-8e43-264f6e7a9332","entityType":"agent","slug":"clawhub-athola-nm-pensive-math-review","name":"math-review","canonicalUrl":"https://www.xpersona.co/agent/clawhub-athola-nm-pensive-math-review","canonicalPath":"/agent/clawhub-athola-nm-pensive-math-review","generatedAt":"2026-10-10T10:48:41.770Z","source":"CLAWHUB","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"editorial-content","verified":true,"confidence":"high","updatedAt":"2026-10-10T06:28:30.021Z","emptyReason":null},"description":"Verifies math-heavy code for algorithmic correctness and numerical stability Skill: math-review Owner: athola Summary: Verifies math-heavy code for algorithmic correctness and numerical stability Tags: latest:1.9.19 Version history: v1.9.19 | 2026-08-26T13:19:00.290Z | user Release v1.9.19 v1.9.17 | 2026-07-30T05:39:12.631Z | user Release v1.9.17 v1.9.16 | 2026-07-14T19:55:54.335Z | user Release v1.9.16 v1.9.14 | 2026-06-30T18:04:14.103Z | user Release v1.9.14 v1.9.13 | 2026-06-27T16:22:15.61","descriptionLabel":"Technical summary","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. 1.6K downloads reported by the source. Last updated 10/10/2026.","installCommand":"clawhub skill install s17emme0e2m3cpf7k2jvp3a84984b8z9:nm-pensive-math-review","sourceUrl":"https://clawhub.ai/athola/nm-pensive-math-review","homepage":"https://clawhub.ai/athola/skills/nm-pensive-math-review","primaryLinks":[{"label":"View on ClawHub","url":"https://clawhub.ai/athola/nm-pensive-math-review","kind":"source"},{"label":"Homepage","url":"https://clawhub.ai/athola/skills/nm-pensive-math-review","kind":"homepage"}],"safetyScore":84,"overallRank":62,"popularityScore":64,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"Verifies math-heavy code for algorithmic correctness and numerical stability Skill: math-review Owner: athola Summary: Verifies math-heavy code for algorithmic "},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-10-10T06:28:30.021Z","emptyReason":null},"protocols":[{"protocol":"OPENCLEW","label":"OpenClaw","status":"self-declared","notes":"Declared in the public agent profile."}],"capabilities":[],"verifiedCount":0,"selfDeclaredCount":1,"capabilityMatrix":{"rows":[{"key":"OPENCLEW","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"}],"flattenedTokens":"protocol:OPENCLEW|unknown|profile"}},"adoption":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-10T06:28:30.021Z","emptyReason":null},"stars":null,"forks":null,"downloads":1619,"packageName":null,"latestVersion":"1.9.19","tractionLabel":"1.6K downloads"},"release":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-10T06:28:30.021Z","emptyReason":null},"lastUpdatedAt":"2026-10-10T06:28:30.021Z","lastCrawledAt":"2026-10-10T06:28:30.021Z","lastIndexedAt":null,"nextCrawlAt":"2026-10-11T06:28:30.021Z","lastVerifiedAt":null,"highlights":[{"version":"1.9.19","createdAt":"2026-08-26T13:19:00.290Z","changelog":"Release v1.9.19","fileCount":7,"zipByteSize":11137},{"version":"1.9.17","createdAt":"2026-07-30T05:39:12.631Z","changelog":"Release v1.9.17","fileCount":7,"zipByteSize":11141},{"version":"1.9.16","createdAt":"2026-07-14T19:55:54.335Z","changelog":"Release v1.9.16","fileCount":7,"zipByteSize":11046},{"version":"1.9.14","createdAt":"2026-06-30T18:04:14.103Z","changelog":"Release v1.9.14","fileCount":7,"zipByteSize":11039},{"version":"1.9.13","createdAt":"2026-06-27T16:22:15.615Z","changelog":"Release v1.9.13","fileCount":7,"zipByteSize":11032},{"version":"1.9.12","createdAt":"2026-06-19T03:17:24.786Z","changelog":"Release v1.9.12","fileCount":7,"zipByteSize":11124},{"version":"1.0.3","createdAt":"2026-06-18T14:12:15.757Z","changelog":"Release v1.9.12","fileCount":7,"zipByteSize":11148},{"version":"1.0.2","createdAt":"2026-05-09T02:19:19.949Z","changelog":"Release v1.9.5","fileCount":7,"zipByteSize":11127}]},"execution":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"clawhub skill install s17emme0e2m3cpf7k2jvp3a84984b8z9:nm-pensive-math-review","setupComplexity":"low","setupSteps":["Setup complexity is classified as HIGH. You must provision dedicated cloud infrastructure or an isolated VM. Do not run this directly on your local workstation.","Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data."],"contract":{"contractStatus":"missing","authModes":[],"requires":[],"forbidden":[],"supportsMcp":false,"supportsA2a":false,"supportsStreaming":false,"inputSchemaRef":null,"outputSchemaRef":null,"dataRegion":null,"contractUpdatedAt":null,"sourceUpdatedAt":null,"freshnessSeconds":null},"invocationGuide":{"preferredApi":{"snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-pensive-math-review/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-pensive-math-review/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-pensive-math-review/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-pensive-math-review/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-pensive-math-review/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-pensive-math-review/trust\""],"jsonRequestTemplate":{"query":"summarize this repo","constraints":{"maxLatencyMs":2000,"protocolPreference":["OPENCLEW"]}},"jsonResponseTemplate":{"ok":true,"result":{"summary":"...","confidence":0.9},"meta":{"source":"CLAWHUB","generatedAt":"2026-10-10T10:48:41.767Z"}},"retryPolicy":{"maxAttempts":3,"backoffMs":[500,1500,3500],"retryableConditions":["HTTP_429","HTTP_503","NETWORK_TIMEOUT"]}},"endpoints":{"dossierUrl":"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-pensive-math-review/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-pensive-math-review/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-pensive-math-review/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-athola-nm-pensive-math-review/trust"}},"reliability":{"evidence":{"source":"runtime-metrics","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No trust, reliability, or runtime telemetry is available."},"trust":{"status":"unavailable","handshakeStatus":"UNKNOWN","verificationFreshnessHours":null,"reputationScore":null,"p95LatencyMs":null,"successRate30d":null,"fallbackRate":null,"attempts30d":null,"trustUpdatedAt":null,"trustConfidence":"unknown","sourceUpdatedAt":null,"freshnessSeconds":null},"decisionGuardrails":{"doNotUseIf":["Contract metadata is missing or unavailable for deterministic execution."],"safeUseWhen":[],"riskFlags":["missing_or_unavailable_contract","trust_data_unavailable","schema_references_missing"],"operationalConfidence":"low"},"executionMetrics":{"observedLatencyMsP50":null,"observedLatencyMsP95":null,"estimatedCostUsd":null,"uptime30d":null,"rateLimitRpm":null,"rateLimitBurst":null,"lastVerifiedAt":null,"verificationSource":null},"runtimeMetrics":{"successRate":null,"avgLatencyMs":null,"avgCostUsd":null,"hallucinationRate":null,"retryRate":null,"disputeRate":null,"p50Latency":null,"p95Latency":null,"lastUpdated":null}},"benchmarks":{"evidence":{"source":"no-benchmark-data","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No benchmark suites or observed failure patterns are available."},"suites":[],"failurePatterns":[]},"artifacts":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"high","updatedAt":"2026-10-10T06:28:30.021Z","emptyReason":null},"readme":"Skill: math-review\n\nOwner: athola\n\nSummary: Verifies math-heavy code for algorithmic correctness and numerical stability\n\nTags: latest:1.9.19\n\nVersion history:\n\nv1.9.19 | 2026-08-26T13:19:00.290Z | user\n\nRelease v1.9.19\n\nv1.9.17 | 2026-07-30T05:39:12.631Z | user\n\nRelease v1.9.17\n\nv1.9.16 | 2026-07-14T19:55:54.335Z | user\n\nRelease v1.9.16\n\nv1.9.14 | 2026-06-30T18:04:14.103Z | user\n\nRelease v1.9.14\n\nv1.9.13 | 2026-06-27T16:22:15.615Z | user\n\nRelease v1.9.13\n\nv1.9.12 | 2026-06-19T03:17:24.786Z | user\n\nRelease v1.9.12\n\nv1.0.3 | 2026-06-18T14:12:15.757Z | user\n\nRelease v1.9.12\n\nv1.0.2 | 2026-05-09T02:19:19.949Z | user\n\nRelease v1.9.5\n\nv1.0.1 | 2026-05-06T14:20:33.640Z | user\n\nRelease v1.9.4\n\nv1.0.0 | 2026-04-15T14:02:01.138Z | auto\n\nInitial release of the math-review skill.\n\n- Provides a workflow for verifying math-heavy code for algorithm correctness, numerical stability, and standards alignment.\n- Includes detailed checklists, output templates, and required workflow steps (context sync, requirements mapping, derivation verification, stability assessment, proof of work).\n- Offers progressive loading for scalable analysis depth.\n- Documents risk classification, essential checklist, and troubleshooting guidance.\n- Integration instructions and references to authoritative standards provided.\n\nArchive index:\n\nArchive v1.9.19: 7 files, 11137 bytes\n\nFiles: modules/derivation-verification.md (3255b), modules/numerical-stability.md (2650b), modules/requirements-mapping.md (3561b), modules/testing-strategies.md (4867b), skill-card.md (2394b), SKILL.md (5126b), _meta.json (142b)\n\nFile v1.9.19:SKILL.md\n\n---\nname: math-review\ndescription: Verifies math-heavy code for algorithmic correctness and numerical stability\nversion: 1.9.8\ntriggers:\n  - math\n  - algorithms\n  - numerical\n  - stability\n  - verification\n  - scientific\n  - reviewing scientific algorithms\n  - ML models\n  - or numerical code\nmetadata: {\"openclaw\": {\"homepage\": \"https://github.com/athola/claude-night-market/tree/master/plugins/pensive\", \"emoji\": \"\\ud83e\\udd9e\", \"requires\": {\"config\": [\"night-market.pensive:shared\", \"night-market.imbue:proof-of-work\"]}}}\nsource: claude-night-market\nsource_plugin: pensive\n---\n\n> **Night Market Skill** — ported from [claude-night-market/pensive](https://github.com/athola/claude-night-market/tree/master/plugins/pensive). For the full experience with agents, hooks, and commands, install the Claude Code plugin.\n\n\n## Table of Contents\n\n- [Quick Start](#quick-start)\n- [When to Use](#when-to-use)\n- [Required TodoWrite Items](#required-todowrite-items)\n- [Core Workflow](#core-workflow)\n- [1. Context Sync](#1-context-sync)\n- [2. Requirements Mapping](#2-requirements-mapping)\n- [3. Derivation Verification](#3-derivation-verification)\n- [4. Stability Assessment](#4-stability-assessment)\n- [5. Proof of Work](#5-proof-of-work)\n- [Progressive Loading](#progressive-loading)\n- [Essential Checklist](#essential-checklist)\n- [Output Format](#output-format)\n- [Summary](#summary)\n- [Context](#context)\n- [Requirements Analysis](#requirements-analysis)\n- [Derivation Review](#derivation-review)\n- [Stability Analysis](#stability-analysis)\n- [Issues](#issues)\n- [Recommendation](#recommendation)\n- [Exit Criteria](#exit-criteria)\n\n\n# Mathematical Algorithm Review\n\nIntensive analysis ensuring numerical stability and alignment with standards.\n\n## Quick Start\n\n```bash\n/math-review\n```\n**Verification:** Run the command with `--help` flag to verify availability.\n\n## When To Use\n\n- Changes to mathematical models or algorithms\n- Statistical routines or probabilistic logic\n- Numerical integration or optimization\n- Scientific computing code\n- ML/AI model implementations\n- Safety-critical calculations\n\n## When NOT To Use\n\n- General algorithm review -\n  use architecture-review\n- Performance optimization - use parseltongue:python-performance\n- General algorithm review -\n  use architecture-review\n- Performance optimization - use parseltongue:python-performance\n\n## Required TodoWrite Items\n\n1. `math-review:context-synced`\n2. `math-review:requirements-mapped`\n3. `math-review:derivations-verified`\n4. `math-review:stability-assessed`\n5. `math-review:evidence-logged`\n\n## Core Workflow\n\n### 1. Context Sync\n```bash\npwd && git status -sb && git diff --stat origin/main..HEAD\n```\n**Verification:** Run `git status` to confirm working tree state.\nEnumerate math-heavy files (source, tests, docs, notebooks). Classify risk: safety-critical, financial, ML fairness.\n\n### 2. Requirements Mapping\nTranslate requirements → mathematical invariants. Document pre/post conditions, conservation laws, bounds. **Load**: `modules/requirements-mapping.md`\n\n### 3. Derivation Verification\nRe-derive formulas using CAS. Challenge approximations. Cite authoritative standards (NASA-STD-7009, ASME VVUQ). **Load**: `modules/derivation-verification.md`\n\n### 4. Stability Assessment\nEvaluate conditioning, precision, scaling, randomness. Compare complexity. Quantify uncertainty. **Load**: `modules/numerical-stability.md`\n\n### 5. Proof of Work\n```bash\npytest tests/math/ --benchmark\njupyter nbconvert --execute derivation.ipynb\n```\n**Verification:** Run `pytest -v tests/math/` to verify.\nLog deviations, recommend: Approve / Approve with actions / Block. **Load**: `modules/testing-strategies.md`\n\n## Progressive Loading\n\n**Default (200 tokens)**: Core workflow, checklists\n**+Requirements** (+300 tokens): Invariants, pre/post conditions, coverage analysis\n**+Derivation** (+350 tokens): CAS verification, standards, citations\n**+Stability** (+400 tokens): Numerical properties, precision, complexity\n**+Testing** (+350 tokens): Edge cases, benchmarks, reproducibility\n\n**Total with all modules**: ~1600 tokens\n\n## Essential Checklist\n\n**Correctness**: Formulas match spec | Edge cases handled | Units consistent | Domain enforced\n**Stability**: Condition number OK | Precision sufficient | No cancellation | Overflow prevented\n**Verification**: Derivations documented | References cited | Tests cover invariants | Benchmarks reproducible\n**Documentation**: Assumptions stated | Limitations documented | Error bounds specified | References linked\n\n## Output Format\n\n```markdown\n## Summary\n[Brief findings]\n\n## Context\nFiles | Risk classification | Standards\n\n## Requirements Analysis\n| Invariant | Verified | Evidence |\n\n## Derivation Review\n[Status and conflicts]\n\n## Stability Analysis\nCondition number | Precision | Risks\n\n## Issues\n[M1] [Title]: Location | Issue | Fix\n\n## Recommendation\nApprove / Approve with actions / Block\n```\n**Verification:** Run the command with `--help` flag to verify availability.\n\n## Exit Criteria\n\n- Context synced, requirements mapped, derivations verified, stability assessed, evidence logged with citations\n\nFile v1.9.19:_meta.json\n\n{\n  \"ownerId\": \"kn7d107jg9jv602h9ytsegydq184a42s\",\n  \"slug\": \"nm-pensive-math-review\",\n  \"version\": \"1.9.19\",\n  \"publishedAt\": 1787750340290\n}\n\nFile v1.9.19:modules/derivation-verification.md\n\n---\nparent_skill: pensive:math-review\nload_priority: high\nestimated_tokens: 350\n---\n\n# Derivation Verification\n\n## Re-derive Critical Formulas\n\n**Symbolic Verification**\n- Use Computer Algebra Systems (SymPy, Mathematica, Maple)\n- Confirm algebraic manipulations\n- Verify calculus operations (derivatives, integrals)\n- Check limit behavior\n\n**Computational Notebooks**\n```python\n# Example: Verify gradient computation\nimport sympy as sp\nx, y = sp.symbols('x y')\nf = x**2 + y**2\ngrad_f = [sp.diff(f, var) for var in [x, y]]\n# Compare with implementation\n```\n\n**Probabilistic Reasoning**\n- Verify conditional probability formulas\n- Check Bayes rule applications\n- Confirm expectation/variance calculations\n- Validate distribution properties\n\n## Challenge Approximations\n\n**Series Truncation**\n- Document truncation order (e.g., O(h³))\n- Estimate truncation error\n- Test convergence with different orders\n- Provide error bounds across domain\n\n**Linearizations**\n- Identify linearization points\n- Estimate valid domain size\n- Test against full nonlinear model\n- Document approximation quality\n\n**Surrogate Models**\n- Compare surrogate to ground truth\n- Quantify approximation error\n- Document training/validation data\n- Test extrapolation behavior\n\n**Error Bounds**\n- Derive theoretical error bounds\n- Verify empirically\n- Document worst-case scenarios\n- Test at domain boundaries\n\n## Authoritative References\n\n**Standards and Frameworks**\n- **NASA-STD-7009**: Modeling and Simulation V&V\n- **ASME V&V 20**: Verification & Validation in CFD/HT\n- **ASME V&V 10**: Guide for V&V in Computational Solid Mechanics\n- **SIAM**: Reproducibility checklists\n- **IEEE 754**: Floating-point arithmetic\n- **NIST**: Uncertainty quantification guidelines\n\n**Academic Sources**\n- Peer-reviewed papers (DOI links)\n- Textbooks (edition and page numbers)\n- Technical reports\n- Conference proceedings\n\n**Implementation References**\n- Reference implementations (NumPy, SciPy, GSL)\n- Algorithm papers (original sources)\n- Numerical recipes\n- Domain-specific libraries\n\n## Document Conflicts\n\nWhen implementation deviates from standards:\n\n```markdown\n### Deviation: [Brief title]\n- **Standard**: NASA-STD-7009 Section 3.4.2\n- **Requirement**: Monte Carlo with n≥1000 samples\n- **Implementation**: n=100 samples\n- **Justification**: Performance constraints\n- **Risk**: Reduced confidence intervals\n- **Mitigation**: Document uncertainty, flag results\n- **Owner**: [name]\n- **Due date**: [date]\n```\n\n## Citation Format\n\n```markdown\n## References\n\n[1] Wilkinson, J.H. (1963). *Rounding Errors in Algebraic Processes*.\n    Prentice-Hall. Chapter 3.\n\n[2] NASA-STD-7009A. (2016). *Standard for Models and Simulations*.\n    Section 4.2: Verification Requirements.\n\n[3] Goldberg, D. (1991). \"What Every Computer Scientist Should Know\n    About Floating-Point Arithmetic\". *ACM Computing Surveys*, 23(1).\n    DOI: 10.1145/103162.103163\n```\n\n## Verification Checklist\n\n- [ ] Formulas re-derived from first principles\n- [ ] Symbolic verification completed (CAS)\n- [ ] Approximation order documented\n- [ ] Error bounds derived and tested\n- [ ] Authoritative references cited\n- [ ] Deviations from standards documented\n- [ ] Conflicts resolved or flagged\n- [ ] Implementation matches theory\n\nFile v1.9.19:modules/numerical-stability.md\n\n---\nparent_skill: pensive:math-review\nload_priority: high\nestimated_tokens: 400\n---\n\n# Numerical Stability Analysis\n\n## Conditioning\n\n**Condition Numbers**\n- Measure sensitivity to input perturbations\n- High condition number = unstable computation\n- Use scaled condition numbers when possible\n\n**Sensitivity Analysis**\n- Perturb inputs systematically\n- Measure output variation\n- Document acceptable tolerance ranges\n\n## Precision Management\n\n**Floating-Point Error Propagation**\n```python\n# Bad: Accumulating small values into large\ntotal = 1e15\nfor x in small_values:\n    total += x  # Precision lost\n\n# Good: Kahan summation or sort first\nsorted_values = sorted(small_values)\ntotal = sum(sorted_values)  # Better precision\n```\n\n**Catastrophic Cancellation**\n```python\n# Bad: Subtracting similar values\nresult = (a + epsilon) - a  # Catastrophic cancellation\n\n# Good: Reformulate to avoid\nresult = epsilon  # Direct computation\n```\n\n**Overflow/Underflow Prevention**\n- Check dynamic range before operations\n- Use log-space for very large/small products\n- Normalize intermediate results\n- Scale inputs to manageable ranges\n\n## Scaling and Normalization\n\n**Dynamic Range Handling**\n- Pre-scale inputs to [0, 1] or [-1, 1]\n- Use log-transforms for exponential data\n- Document scaling factors and units\n\n**Normalization Requirements**\n- L1/L2 normalization for vectors\n- Feature scaling for ML inputs\n- Unit conversions for physical quantities\n\n## Randomness Control\n\n**Reproducibility**\n- Set explicit random seeds\n- Document PRNG algorithms used\n- Version lock numerical libraries\n- Test deterministic behavior\n\n**Seed Management**\n```python\n# Good: Explicit seed control\nimport numpy as np\nnp.random.seed(42)\n\n# Better: Isolated RNG state\nrng = np.random.RandomState(42)\nsamples = rng.normal(0, 1, size=100)\n```\n\n## Complexity Analysis\n\nCompare algorithmic complexity before/after changes:\n\n```\nBefore: O(n²) time, O(n) space\nAfter:  O(n log n) time, O(n) space\nImprovement: 100x faster for n=1000\n```\n\nDocument:\n- Time complexity\n- Space complexity\n- Cache behavior\n- Parallelization potential\n\n## Uncertainty Quantification\n\nRequired for:\n- Safety-critical systems\n- Data-driven components\n- High-stakes decisions\n- Regulatory compliance\n\nMethods:\n- Monte Carlo sampling\n- Bootstrap confidence intervals\n- Sensitivity analysis\n- Error propagation formulas\n\n## Stability Checklist\n\n- [ ] Condition number < 1e6\n- [ ] Precision loss < 1e-10\n- [ ] No catastrophic cancellation\n- [ ] Overflow/underflow prevented\n- [ ] Scaling applied appropriately\n- [ ] Random seeds controlled\n- [ ] Complexity acceptable\n- [ ] Uncertainty quantified (if required)\n\nFile v1.9.19:modules/requirements-mapping.md\n\n---\nparent_skill: pensive:math-review\nload_priority: medium\nestimated_tokens: 300\n---\n\n# Requirements Mapping\n\n## Mathematical Invariants\n\nTranslate requirements into verifiable mathematical properties:\n\n| Requirement | Invariant | Test Coverage |\n|-------------|-----------|---------------|\n| Positive output | f(x) > 0 ∀ x ∈ domain | Property test |\n| Conservation | Σ mass_in = Σ mass_out | Unit test |\n| Bounded error | \\|ε\\| < 1e-6 | Benchmark |\n| Monotonicity | x₁ < x₂ ⟹ f(x₁) ≤ f(x₂) | Property test |\n| Idempotence | f(f(x)) = f(x) | Unit test |\n\n## Pre-conditions\n\n**Input Validation**\n```python\ndef compute(x: float, n: int) -> float:\n    \"\"\"Compute function with documented preconditions.\n\n    Preconditions:\n    - x ≥ 0 (non-negative input)\n    - n > 0 (positive integer)\n    - x < 1e10 (prevent overflow)\n    \"\"\"\n    if x < 0:\n        raise ValueError(\"x must be non-negative\")\n    if n <= 0:\n        raise ValueError(\"n must be positive\")\n    if x >= 1e10:\n        raise ValueError(\"x must be < 1e10\")\n    # ... implementation\n```\n\n**Domain Constraints**\n- Valid input ranges\n- Type requirements\n- Dimensional consistency\n- Unit compatibility\n\n## Post-conditions\n\n**Output Guarantees**\n```python\ndef normalize(vector: np.ndarray) -> np.ndarray:\n    \"\"\"Normalize vector to unit length.\n\n    Postconditions:\n    - ||result|| = 1.0 (± 1e-10)\n    - result ∥ vector (parallel)\n    \"\"\"\n    result = vector / np.linalg.norm(vector)\n    assert abs(np.linalg.norm(result) - 1.0) < 1e-10\n    return result\n```\n\n**Invariant Preservation**\n- Conservation laws maintained\n- Bounds respected\n- Relationships preserved\n\n## Conservation Laws\n\n**Physical Conservation**\n- Mass conservation\n- Energy conservation\n- Momentum conservation\n- Charge conservation\n\n**Numerical Conservation**\n- Probability sums to 1.0\n- Symmetry preservation\n- Balance equations\n\n## Monotonicity Guarantees\n\n**Increasing Functions**\n```python\n# Property test\n@given(st.floats(min_value=0, max_value=100))\ndef test_monotonic_increasing(x1, x2):\n    assume(x1 < x2)\n    assert f(x1) <= f(x2)\n```\n\n**Convexity/Concavity**\n- Second derivative tests\n- Jensen's inequality\n- Midpoint properties\n\n## Probabilistic Bounds\n\n**Confidence Intervals**\n- Document confidence levels (95%, 99%)\n- Specify interval type (credible, confidence)\n- Test coverage probabilities\n\n**Error Probabilities**\n- Type I/II error rates\n- False positive/negative rates\n- Statistical power\n\n## Coverage Gap Analysis\n\nIdentify untested invariants:\n\n```markdown\n### Coverage Gaps\n\n**Missing Tests**\n- [ ] Boundary condition: x = 0\n- [ ] Overflow case: x > 1e15\n- [ ] Negative input handling\n- [ ] Conservation at t → ∞\n\n**Insufficient Coverage**\n- [ ] Only 3 test cases for n-dimensional invariant\n- [ ] No property tests for monotonicity\n- [ ] Missing edge case: empty input\n```\n\n## Documentation Template\n\n```python\ndef algorithm(inputs) -> outputs:\n    \"\"\"Brief description.\n\n    Mathematical Properties:\n    - Preconditions: [domain constraints]\n    - Postconditions: [guaranteed properties]\n    - Invariants: [preserved relationships]\n    - Complexity: [time/space bounds]\n    - Stability: [condition number, error bounds]\n\n    References:\n    - [Citation to algorithm source]\n    \"\"\"\n```\n\n## Mapping Checklist\n\n- [ ] Requirements translated to invariants\n- [ ] Pre-conditions documented\n- [ ] Post-conditions verified\n- [ ] Conservation laws tested\n- [ ] Monotonicity/convexity checked\n- [ ] Probabilistic bounds specified\n- [ ] Coverage gaps identified\n- [ ] All properties have tests\n\nFile v1.9.19:modules/testing-strategies.md\n\n---\nparent_skill: pensive:math-review\nload_priority: medium\nestimated_tokens: 350\n---\n\n# Testing Strategies for Mathematical Code\n\n## Edge Case Coverage\n\n**Domain Boundaries**\n```python\n# Bad: Undefined for negative\nresult = math.sqrt(value)\n\n# Good: Validate domain\ndef safe_sqrt(value: float) -> float:\n    if value < 0:\n        raise ValueError(\"sqrt requires non-negative input\")\n    return math.sqrt(value)\n\n# Test edge cases\n@pytest.mark.parametrize(\"value\", [0, 1e-100, 1e100, float('inf')])\ndef test_sqrt_boundaries(value):\n    result = safe_sqrt(value)\n    assert result >= 0\n```\n\n**Special Values**\n- Zero\n- One\n- Infinity\n- NaN\n- Very small (underflow)\n- Very large (overflow)\n- Negative values\n- Empty inputs\n\n## Property-Based Testing\n\n**Hypothesis Framework**\n```python\nfrom hypothesis import given, strategies as st\n\n@given(st.floats(min_value=0, max_value=1e6))\ndef test_sqrt_inverse(x):\n    \"\"\"sqrt(x)² should equal x\"\"\"\n    result = safe_sqrt(x)\n    assert abs(result * result - x) < 1e-10 * x\n```\n\n**Invariant Testing**\n- Symmetry properties\n- Associativity/commutativity\n- Idempotence\n- Conservation laws\n- Monotonicity\n\n## Benchmark Testing\n\n**Performance Validation**\n```bash\npytest tests/math/ --benchmark-only\npytest tests/math/ --benchmark-compare=baseline\n```\n\n**Regression Detection**\n```python\ndef test_algorithm_performance(benchmark):\n    \"\"\"validate O(n log n) complexity maintained\"\"\"\n    n = 10000\n    data = np.random.rand(n)\n\n    result = benchmark(algorithm, data)\n\n    # Verify result correctness\n    assert len(result) == n\n    # Performance constraint\n    assert benchmark.stats['mean'] < 0.1  # seconds\n```\n\n**Complexity Verification**\n- Time scaling tests\n- Memory profiling\n- Cache behavior\n- Parallel efficiency\n\n## Reproducibility Testing\n\n**Deterministic Results**\n```python\ndef test_reproducibility():\n    \"\"\"Same seed produces same results\"\"\"\n    np.random.seed(42)\n    result1 = monte_carlo_simulation()\n\n    np.random.seed(42)\n    result2 = monte_carlo_simulation()\n\n    np.testing.assert_array_equal(result1, result2)\n```\n\n**Version Pinning**\n```toml\n# pyproject.toml\n[tool.poetry.dependencies]\nnumpy = \"==1.24.0\"  # Pin for reproducibility\nscipy = \"==1.10.0\"\n```\n\n## Reference Implementation Tests\n\n**Golden Master Testing**\n```python\ndef test_against_reference():\n    \"\"\"Compare with NumPy/SciPy reference\"\"\"\n    x = np.linspace(0, 10, 100)\n\n    our_result = our_implementation(x)\n    reference_result = scipy.special.reference_function(x)\n\n    np.testing.assert_allclose(\n        our_result,\n        reference_result,\n        rtol=1e-10,\n        atol=1e-12\n    )\n```\n\n**Cross-Validation**\n- Multiple independent implementations\n- Different algorithms\n- Analytical solutions (when available)\n- Published test cases\n\n## Numerical Accuracy Tests\n\n**Tolerance Specifications**\n```python\n# Absolute tolerance\nnp.testing.assert_allclose(result, expected, atol=1e-10)\n\n# Relative tolerance\nnp.testing.assert_allclose(result, expected, rtol=1e-8)\n\n# Both\nnp.testing.assert_allclose(\n    result, expected,\n    rtol=1e-8, atol=1e-10\n)\n```\n\n**ULP (Units in Last Place) Testing**\n```python\n# For critical floating-point comparisons\nassert abs(a - b) <= 2 * np.finfo(float).eps * max(abs(a), abs(b))\n```\n\n## Evidence Logging\n\n**Execution Records**\n```bash\n# Run tests with output capture\npytest tests/math/ -v --tb=short > test_results.txt\n\n# Benchmark with JSON output\npytest tests/math/ --benchmark-json=benchmark.json\n\n# Execute derivation notebooks\njupyter nbconvert --execute derivation.ipynb \\\n    --to html --output verification.html\n```\n\n**Documentation Template**\n```markdown\n## Test Evidence\n\n### Unit Tests\n- **Command**: `pytest tests/math/ -v`\n- **Result**: 47/47 passed\n- **Coverage**: 94%\n- **Date**: 2025-12-06\n\n### Benchmarks\n- **Command**: `pytest tests/math/ --benchmark-only`\n- **Mean time**: 23.4ms (±1.2ms)\n- **Baseline**: 24.1ms\n- **Improvement**: 3%\n\n### Derivation Verification\n- **Notebook**: derivation.ipynb\n- **Status**: All cells executed successfully\n- **Symbolic checks**: Passed\n- **Reference comparison**: Within tolerance\n```\n\n## Test Organization\n\n```\ntests/math/\n├── test_correctness.py       # Basic functionality\n├── test_edge_cases.py        # Boundary conditions\n├── test_properties.py        # Hypothesis tests\n├── test_benchmarks.py        # Performance\n├── test_stability.py         # Numerical stability\n├── test_references.py        # Golden masters\n└── fixtures/\n    ├── test_data.npz\n    └── reference_results.json\n```\n\n## Testing Checklist\n\n- [ ] Edge cases covered (0, ±∞, NaN)\n- [ ] Property tests for invariants\n- [ ] Benchmark tests for performance\n- [ ] Reproducibility verified\n- [ ] Reference implementation compared\n- [ ] Tolerances documented\n- [ ] Evidence logged and dated\n- [ ] Coverage > 90% for math code\n\nFile v1.9.19:skill-card.md\n\n## Description:\n\nVerifies math-heavy code for algorithmic correctness and numerical stability.\n\nThis skill is ready for commercial/non-commercial use.\n\n## Publisher:\n\n[athola](https://clawhub.ai/user/athola)\n\n### License/Terms of Use:\n\nMIT-0\n\n## Use Case:\n\nDevelopers and engineers use this skill to review math-heavy code, scientific algorithms, ML model implementations, and safety-critical calculations for correctness, numerical stability, and sufficient verification evidence.\n\n### Deployment Geography for Use:\n\nGlobal\n\n## Known Risks and Mitigations:\n\nRisk: The skill can guide an agent to execute repository tests and notebooks, which may run untrusted project code.\n\nMitigation: Inspect tests and notebooks before execution, run them in a disposable sandbox with no secrets and network disabled, and require reviewer approval for execution steps.\n\nRisk: Broad automatic activation can cause the skill to influence tasks where a full mathematical review is not relevant.\n\nMitigation: Confirm that the task involves math-heavy code, numerical stability, scientific algorithms, ML model implementation, or safety-critical calculation before applying the workflow.\n\n## Reference(s):\n\n- [ClawHub skill page](https://clawhub.ai/athola/skills/nm-pensive-math-review)\n- [OpenClaw homepage metadata](https://github.com/athola/claude-night-market/tree/master/plugins/pensive)\n- [Requirements Mapping](artifact/modules/requirements-mapping.md)\n- [Derivation Verification](artifact/modules/derivation-verification.md)\n- [Numerical Stability Analysis](artifact/modules/numerical-stability.md)\n- [Testing Strategies for Mathematical Code](artifact/modules/testing-strategies.md)\n\n## Skill Output:\n\n**Output Type(s):** [text, markdown, shell commands, guidance]\n\n**Output Format:** [Markdown review report with tables, issue summaries, recommendations, and inline shell commands]\n\n**Output Parameters:** [1D]\n\n**Other Properties Related to Output:** [May recommend tests, benchmarks, notebook execution, derivation checks, and evidence logging for reviewer follow-up.]\n\n## Skill Version(s):\n\n1.9.19 (source: server release metadata)\n\n## Ethical Considerations:\n\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment.\n\nArchive v1.9.17: 7 files, 11141 bytes\n\nFiles: modules/derivation-verification.md (3255b), modules/numerical-stability.md (2650b), modules/requirements-mapping.md (3561b), modules/testing-strategies.md (4867b), skill-card.md (2477b), SKILL.md (5126b), _meta.json (142b)\n\nFile v1.9.17:SKILL.md\n\n---\nname: math-review\ndescription: Verifies math-heavy code for algorithmic correctness and numerical stability\nversion: 1.9.8\ntriggers:\n  - math\n  - algorithms\n  - numerical\n  - stability\n  - verification\n  - scientific\n  - reviewing scientific algorithms\n  - ML models\n  - or numerical code\nmetadata: {\"openclaw\": {\"homepage\": \"https://github.com/athola/claude-night-market/tree/master/plugins/pensive\", \"emoji\": \"\\ud83e\\udd9e\", \"requires\": {\"config\": [\"night-market.pensive:shared\", \"night-market.imbue:proof-of-work\"]}}}\nsource: claude-night-market\nsource_plugin: pensive\n---\n\n> **Night Market Skill** — ported from [claude-night-market/pensive](https://github.com/athola/claude-night-market/tree/master/plugins/pensive). For the full experience with agents, hooks, and commands, install the Claude Code plugin.\n\n\n## Table of Contents\n\n- [Quick Start](#quick-start)\n- [When to Use](#when-to-use)\n- [Required TodoWrite Items](#required-todowrite-items)\n- [Core Workflow](#core-workflow)\n- [1. Context Sync](#1-context-sync)\n- [2. Requirements Mapping](#2-requirements-mapping)\n- [3. Derivation Verification](#3-derivation-verification)\n- [4. Stability Assessment](#4-stability-assessment)\n- [5. Proof of Work](#5-proof-of-work)\n- [Progressive Loading](#progressive-loading)\n- [Essential Checklist](#essential-checklist)\n- [Output Format](#output-format)\n- [Summary](#summary)\n- [Context](#context)\n- [Requirements Analysis](#requirements-analysis)\n- [Derivation Review](#derivation-review)\n- [Stability Analysis](#stability-analysis)\n- [Issues](#issues)\n- [Recommendation](#recommendation)\n- [Exit Criteria](#exit-criteria)\n\n\n# Mathematical Algorithm Review\n\nIntensive analysis ensuring numerical stability and alignment with standards.\n\n## Quick Start\n\n```bash\n/math-review\n```\n**Verification:** Run the command with `--help` flag to verify availability.\n\n## When To Use\n\n- Changes to mathematical models or algorithms\n- Statistical routines or probabilistic logic\n- Numerical integration or optimization\n- Scientific computing code\n- ML/AI model implementations\n- Safety-critical calculations\n\n## When NOT To Use\n\n- General algorithm review -\n  use architecture-review\n- Performance optimization - use parseltongue:python-performance\n- General algorithm review -\n  use architecture-review\n- Performance optimization - use parseltongue:python-performance\n\n## Required TodoWrite Items\n\n1. `math-review:context-synced`\n2. `math-review:requirements-mapped`\n3. `math-review:derivations-verified`\n4. `math-review:stability-assessed`\n5. `math-review:evidence-logged`\n\n## Core Workflow\n\n### 1. Context Sync\n```bash\npwd && git status -sb && git diff --stat origin/main..HEAD\n```\n**Verification:** Run `git status` to confirm working tree state.\nEnumerate math-heavy files (source, tests, docs, notebooks). Classify risk: safety-critical, financial, ML fairness.\n\n### 2. Requirements Mapping\nTranslate requirements → mathematical invariants. Document pre/post conditions, conservation laws, bounds. **Load**: `modules/requirements-mapping.md`\n\n### 3. Derivation Verification\nRe-derive formulas using CAS. Challenge approximations. Cite authoritative standards (NASA-STD-7009, ASME VVUQ). **Load**: `modules/derivation-verification.md`\n\n### 4. Stability Assessment\nEvaluate conditioning, precision, scaling, randomness. Compare complexity. Quantify uncertainty. **Load**: `modules/numerical-stability.md`\n\n### 5. Proof of Work\n```bash\npytest tests/math/ --benchmark\njupyter nbconvert --execute derivation.ipynb\n```\n**Verification:** Run `pytest -v tests/math/` to verify.\nLog deviations, recommend: Approve / Approve with actions / Block. **Load**: `modules/testing-strategies.md`\n\n## Progressive Loading\n\n**Default (200 tokens)**: Core workflow, checklists\n**+Requirements** (+300 tokens): Invariants, pre/post conditions, coverage analysis\n**+Derivation** (+350 tokens): CAS verification, standards, citations\n**+Stability** (+400 tokens): Numerical properties, precision, complexity\n**+Testing** (+350 tokens): Edge cases, benchmarks, reproducibility\n\n**Total with all modules**: ~1600 tokens\n\n## Essential Checklist\n\n**Correctness**: Formulas match spec | Edge cases handled | Units consistent | Domain enforced\n**Stability**: Condition number OK | Precision sufficient | No cancellation | Overflow prevented\n**Verification**: Derivations documented | References cited | Tests cover invariants | Benchmarks reproducible\n**Documentation**: Assumptions stated | Limitations documented | Error bounds specified | References linked\n\n## Output Format\n\n```markdown\n## Summary\n[Brief findings]\n\n## Context\nFiles | Risk classification | Standards\n\n## Requirements Analysis\n| Invariant | Verified | Evidence |\n\n## Derivation Review\n[Status and conflicts]\n\n## Stability Analysis\nCondition number | Precision | Risks\n\n## Issues\n[M1] [Title]: Location | Issue | Fix\n\n## Recommendation\nApprove / Approve with actions / Block\n```\n**Verification:** Run the command with `--help` flag to verify availability.\n\n## Exit Criteria\n\n- Context synced, requirements mapped, derivations verified, stability assessed, evidence logged with citations\n\nFile v1.9.17:_meta.json\n\n{\n  \"ownerId\": \"kn7d107jg9jv602h9ytsegydq184a42s\",\n  \"slug\": \"nm-pensive-math-review\",\n  \"version\": \"1.9.17\",\n  \"publishedAt\": 1785389952631\n}\n\nFile v1.9.17:modules/derivation-verification.md\n\n---\nparent_skill: pensive:math-review\nload_priority: high\nestimated_tokens: 350\n---\n\n# Derivation Verification\n\n## Re-derive Critical Formulas\n\n**Symbolic Verification**\n- Use Computer Algebra Systems (SymPy, Mathematica, Maple)\n- Confirm algebraic manipulations\n- Verify calculus operations (derivatives, integrals)\n- Check limit behavior\n\n**Computational Notebooks**\n```python\n# Example: Verify gradient computation\nimport sympy as sp\nx, y = sp.symbols('x y')\nf = x**2 + y**2\ngrad_f = [sp.diff(f, var) for var in [x, y]]\n# Compare with implementation\n```\n\n**Probabilistic Reasoning**\n- Verify conditional probability formulas\n- Check Bayes rule applications\n- Confirm expectation/variance calculations\n- Validate distribution properties\n\n## Challenge Approximations\n\n**Series Truncation**\n- Document truncation order (e.g., O(h³))\n- Estimate truncation error\n- Test convergence with different orders\n- Provide error bounds across domain\n\n**Linearizations**\n- Identify linearization points\n- Estimate valid domain size\n- Test against full nonlinear model\n- Document approximation quality\n\n**Surrogate Models**\n- Compare surrogate to ground truth\n- Quantify approximation error\n- Document training/validation data\n- Test extrapolation behavior\n\n**Error Bounds**\n- Derive theoretical error bounds\n- Verify empirically\n- Document worst-case scenarios\n- Test at domain boundaries\n\n## Authoritative References\n\n**Standards and Frameworks**\n- **NASA-STD-7009**: Modeling and Simulation V&V\n- **ASME V&V 20**: Verification & Validation in CFD/HT\n- **ASME V&V 10**: Guide for V&V in Computational Solid Mechanics\n- **SIAM**: Reproducibility checklists\n- **IEEE 754**: Floating-point arithmetic\n- **NIST**: Uncertainty quantification guidelines\n\n**Academic Sources**\n- Peer-reviewed papers (DOI links)\n- Textbooks (edition and page numbers)\n- Technical reports\n- Conference proceedings\n\n**Implementation References**\n- Reference implementations (NumPy, SciPy, GSL)\n- Algorithm papers (original sources)\n- Numerical recipes\n- Domain-specific libraries\n\n## Document Conflicts\n\nWhen implementation deviates from standards:\n\n```markdown\n### Deviation: [Brief title]\n- **Standard**: NASA-STD-7009 Section 3.4.2\n- **Requirement**: Monte Carlo with n≥1000 samples\n- **Implementation**: n=100 samples\n- **Justification**: Performance constraints\n- **Risk**: Reduced confidence intervals\n- **Mitigation**: Document uncertainty, flag results\n- **Owner**: [name]\n- **Due date**: [date]\n```\n\n## Citation Format\n\n```markdown\n## References\n\n[1] Wilkinson, J.H. (1963). *Rounding Errors in Algebraic Processes*.\n    Prentice-Hall. Chapter 3.\n\n[2] NASA-STD-7009A. (2016). *Standard for Models and Simulations*.\n    Section 4.2: Verification Requirements.\n\n[3] Goldberg, D. (1991). \"What Every Computer Scientist Should Know\n    About Floating-Point Arithmetic\". *ACM Computing Surveys*, 23(1).\n    DOI: 10.1145/103162.103163\n```\n\n## Verification Checklist\n\n- [ ] Formulas re-derived from first principles\n- [ ] Symbolic verification completed (CAS)\n- [ ] Approximation order documented\n- [ ] Error bounds derived and tested\n- [ ] Authoritative references cited\n- [ ] Deviations from standards documented\n- [ ] Conflicts resolved or flagged\n- [ ] Implementation matches theory\n\nFile v1.9.17:modules/numerical-stability.md\n\n---\nparent_skill: pensive:math-review\nload_priority: high\nestimated_tokens: 400\n---\n\n# Numerical Stability Analysis\n\n## Conditioning\n\n**Condition Numbers**\n- Measure sensitivity to input perturbations\n- High condition number = unstable computation\n- Use scaled condition numbers when possible\n\n**Sensitivity Analysis**\n- Perturb inputs systematically\n- Measure output variation\n- Document acceptable tolerance ranges\n\n## Precision Management\n\n**Floating-Point Error Propagation**\n```python\n# Bad: Accumulating small values into large\ntotal = 1e15\nfor x in small_values:\n    total += x  # Precision lost\n\n# Good: Kahan summation or sort first\nsorted_values = sorted(small_values)\ntotal = sum(sorted_values)  # Better precision\n```\n\n**Catastrophic Cancellation**\n```python\n# Bad: Subtracting similar values\nresult = (a + epsilon) - a  # Catastrophic cancellation\n\n# Good: Reformulate to avoid\nresult = epsilon  # Direct computation\n```\n\n**Overflow/Underflow Prevention**\n- Check dynamic range before operations\n- Use log-space for very large/small products\n- Normalize intermediate results\n- Scale inputs to manageable ranges\n\n## Scaling and Normalization\n\n**Dynamic Range Handling**\n- Pre-scale inputs to [0, 1] or [-1, 1]\n- Use log-transforms for exponential data\n- Document scaling factors and units\n\n**Normalization Requirements**\n- L1/L2 normalization for vectors\n- Feature scaling for ML inputs\n- Unit conversions for physical quantities\n\n## Randomness Control\n\n**Reproducibility**\n- Set explicit random seeds\n- Document PRNG algorithms used\n- Version lock numerical libraries\n- Test deterministic behavior\n\n**Seed Management**\n```python\n# Good: Explicit seed control\nimport numpy as np\nnp.random.seed(42)\n\n# Better: Isolated RNG state\nrng = np.random.RandomState(42)\nsamples = rng.normal(0, 1, size=100)\n```\n\n## Complexity Analysis\n\nCompare algorithmic complexity before/after changes:\n\n```\nBefore: O(n²) time, O(n) space\nAfter:  O(n log n) time, O(n) space\nImprovement: 100x faster for n=1000\n```\n\nDocument:\n- Time complexity\n- Space complexity\n- Cache behavior\n- Parallelization potential\n\n## Uncertainty Quantification\n\nRequired for:\n- Safety-critical systems\n- Data-driven components\n- High-stakes decisions\n- Regulatory compliance\n\nMethods:\n- Monte Carlo sampling\n- Bootstrap confidence intervals\n- Sensitivity analysis\n- Error propagation formulas\n\n## Stability Checklist\n\n- [ ] Condition number < 1e6\n- [ ] Precision loss < 1e-10\n- [ ] No catastrophic cancellation\n- [ ] Overflow/underflow prevented\n- [ ] Scaling applied appropriately\n- [ ] Random seeds controlled\n- [ ] Complexity acceptable\n- [ ] Uncertainty quantified (if required)\n\nFile v1.9.17:modules/requirements-mapping.md\n\n---\nparent_skill: pensive:math-review\nload_priority: medium\nestimated_tokens: 300\n---\n\n# Requirements Mapping\n\n## Mathematical Invariants\n\nTranslate requirements into verifiable mathematical properties:\n\n| Requirement | Invariant | Test Coverage |\n|-------------|-----------|---------------|\n| Positive output | f(x) > 0 ∀ x ∈ domain | Property test |\n| Conservation | Σ mass_in = Σ mass_out | Unit test |\n| Bounded error | \\|ε\\| < 1e-6 | Benchmark |\n| Monotonicity | x₁ < x₂ ⟹ f(x₁) ≤ f(x₂) | Property test |\n| Idempotence | f(f(x)) = f(x) | Unit test |\n\n## Pre-conditions\n\n**Input Validation**\n```python\ndef compute(x: float, n: int) -> float:\n    \"\"\"Compute function with documented preconditions.\n\n    Preconditions:\n    - x ≥ 0 (non-negative input)\n    - n > 0 (positive integer)\n    - x < 1e10 (prevent overflow)\n    \"\"\"\n    if x < 0:\n        raise ValueError(\"x must be non-negative\")\n    if n <= 0:\n        raise ValueError(\"n must be positive\")\n    if x >= 1e10:\n        raise ValueError(\"x must be < 1e10\")\n    # ... implementation\n```\n\n**Domain Constraints**\n- Valid input ranges\n- Type requirements\n- Dimensional consistency\n- Unit compatibility\n\n## Post-conditions\n\n**Output Guarantees**\n```python\ndef normalize(vector: np.ndarray) -> np.ndarray:\n    \"\"\"Normalize vector to unit length.\n\n    Postconditions:\n    - ||result|| = 1.0 (± 1e-10)\n    - result ∥ vector (parallel)\n    \"\"\"\n    result = vector / np.linalg.norm(vector)\n    assert abs(np.linalg.norm(result) - 1.0) < 1e-10\n    return result\n```\n\n**Invariant Preservation**\n- Conservation laws maintained\n- Bounds respected\n- Relationships preserved\n\n## Conservation Laws\n\n**Physical Conservation**\n- Mass conservation\n- Energy conservation\n- Momentum conservation\n- Charge conservation\n\n**Numerical Conservation**\n- Probability sums to 1.0\n- Symmetry preservation\n- Balance equations\n\n## Monotonicity Guarantees\n\n**Increasing Functions**\n```python\n# Property test\n@given(st.floats(min_value=0, max_value=100))\ndef test_monotonic_increasing(x1, x2):\n    assume(x1 < x2)\n    assert f(x1) <= f(x2)\n```\n\n**Convexity/Concavity**\n- Second derivative tests\n- Jensen's inequality\n- Midpoint properties\n\n## Probabilistic Bounds\n\n**Confidence Intervals**\n- Document confidence levels (95%, 99%)\n- Specify interval type (credible, confidence)\n- Test coverage probabilities\n\n**Error Probabilities**\n- Type I/II error rates\n- False positive/negative rates\n- Statistical power\n\n## Coverage Gap Analysis\n\nIdentify untested invariants:\n\n```markdown\n### Coverage Gaps\n\n**Missing Tests**\n- [ ] Boundary condition: x = 0\n- [ ] Overflow case: x > 1e15\n- [ ] Negative input handling\n- [ ] Conservation at t → ∞\n\n**Insufficient Coverage**\n- [ ] Only 3 test cases for n-dimensional invariant\n- [ ] No property tests for monotonicity\n- [ ] Missing edge case: empty input\n```\n\n## Documentation Template\n\n```python\ndef algorithm(inputs) -> outputs:\n    \"\"\"Brief description.\n\n    Mathematical Properties:\n    - Preconditions: [domain constraints]\n    - Postconditions: [guaranteed properties]\n    - Invariants: [preserved relationships]\n    - Complexity: [time/space bounds]\n    - Stability: [condition number, error bounds]\n\n    References:\n    - [Citation to algorithm source]\n    \"\"\"\n```\n\n## Mapping Checklist\n\n- [ ] Requirements translated to invariants\n- [ ] Pre-conditions documented\n- [ ] Post-conditions verified\n- [ ] Conservation laws tested\n- [ ] Monotonicity/convexity checked\n- [ ] Probabilistic bounds specified\n- [ ] Coverage gaps identified\n- [ ] All properties have tests\n\nFile v1.9.17:modules/testing-strategies.md\n\n---\nparent_skill: pensive:math-review\nload_priority: medium\nestimated_tokens: 350\n---\n\n# Testing Strategies for Mathematical Code\n\n## Edge Case Coverage\n\n**Domain Boundaries**\n```python\n# Bad: Undefined for negative\nresult = math.sqrt(value)\n\n# Good: Validate domain\ndef safe_sqrt(value: float) -> float:\n    if value < 0:\n        raise ValueError(\"sqrt requires non-negative input\")\n    return math.sqrt(value)\n\n# Test edge cases\n@pytest.mark.parametrize(\"value\", [0, 1e-100, 1e100, float('inf')])\ndef test_sqrt_boundaries(value):\n    result = safe_sqrt(value)\n    assert result >= 0\n```\n\n**Special Values**\n- Zero\n- One\n- Infinity\n- NaN\n- Very small (underflow)\n- Very large (overflow)\n- Negative values\n- Empty inputs\n\n## Property-Based Testing\n\n**Hypothesis Framework**\n```python\nfrom hypothesis import given, strategies as st\n\n@given(st.floats(min_value=0, max_value=1e6))\ndef test_sqrt_inverse(x):\n    \"\"\"sqrt(x)² should equal x\"\"\"\n    result = safe_sqrt(x)\n    assert abs(result * result - x) < 1e-10 * x\n```\n\n**Invariant Testing**\n- Symmetry properties\n- Associativity/commutativity\n- Idempotence\n- Conservation laws\n- Monotonicity\n\n## Benchmark Testing\n\n**Performance Validation**\n```bash\npytest tests/math/ --benchmark-only\npytest tests/math/ --benchmark-compare=baseline\n```\n\n**Regression Detection**\n```python\ndef test_algorithm_performance(benchmark):\n    \"\"\"validate O(n log n) complexity maintained\"\"\"\n    n = 10000\n    data = np.random.rand(n)\n\n    result = benchmark(algorithm, data)\n\n    # Verify result correctness\n    assert len(result) == n\n    # Performance constraint\n    assert benchmark.stats['mean'] < 0.1  # seconds\n```\n\n**Complexity Verification**\n- Time scaling tests\n- Memory profiling\n- Cache behavior\n- Parallel efficiency\n\n## Reproducibility Testing\n\n**Deterministic Results**\n```python\ndef test_reproducibility():\n    \"\"\"Same seed produces same results\"\"\"\n    np.random.seed(42)\n    result1 = monte_carlo_simulation()\n\n    np.random.seed(42)\n    result2 = monte_carlo_simulation()\n\n    np.testing.assert_array_equal(result1, result2)\n```\n\n**Version Pinning**\n```toml\n# pyproject.toml\n[tool.poetry.dependencies]\nnumpy = \"==1.24.0\"  # Pin for reproducibility\nscipy = \"==1.10.0\"\n```\n\n## Reference Implementation Tests\n\n**Golden Master Testing**\n```python\ndef test_against_reference():\n    \"\"\"Compare with NumPy/SciPy reference\"\"\"\n    x = np.linspace(0, 10, 100)\n\n    our_result = our_implementation(x)\n    reference_result = scipy.special.reference_function(x)\n\n    np.testing.assert_allclose(\n        our_result,\n        reference_result,\n        rtol=1e-10,\n        atol=1e-12\n    )\n```\n\n**Cross-Validation**\n- Multiple independent implementations\n- Different algorithms\n- Analytical solutions (when available)\n- Published test cases\n\n## Numerical Accuracy Tests\n\n**Tolerance Specifications**\n```python\n# Absolute tolerance\nnp.testing.assert_allclose(result, expected, atol=1e-10)\n\n# Relative tolerance\nnp.testing.assert_allclose(result, expected, rtol=1e-8)\n\n# Both\nnp.testing.assert_allclose(\n    result, expected,\n    rtol=1e-8, atol=1e-10\n)\n```\n\n**ULP (Units in Last Place) Testing**\n```python\n# For critical floating-point comparisons\nassert abs(a - b) <= 2 * np.finfo(float).eps * max(abs(a), abs(b))\n```\n\n## Evidence Logging\n\n**Execution Records**\n```bash\n# Run tests with output capture\npytest tests/math/ -v --tb=short > test_results.txt\n\n# Benchmark with JSON output\npytest tests/math/ --benchmark-json=benchmark.json\n\n# Execute derivation notebooks\njupyter nbconvert --execute derivation.ipynb \\\n    --to html --output verification.html\n```\n\n**Documentation Template**\n```markdown\n## Test Evidence\n\n### Unit Tests\n- **Command**: `pytest tests/math/ -v`\n- **Result**: 47/47 passed\n- **Coverage**: 94%\n- **Date**: 2025-12-06\n\n### Benchmarks\n- **Command**: `pytest tests/math/ --benchmark-only`\n- **Mean time**: 23.4ms (±1.2ms)\n- **Baseline**: 24.1ms\n- **Improvement**: 3%\n\n### Derivation Verification\n- **Notebook**: derivation.ipynb\n- **Status**: All cells executed successfully\n- **Symbolic checks**: Passed\n- **Reference comparison**: Within tolerance\n```\n\n## Test Organization\n\n```\ntests/math/\n├── test_correctness.py       # Basic functionality\n├── test_edge_cases.py        # Boundary conditions\n├── test_properties.py        # Hypothesis tests\n├── test_benchmarks.py        # Performance\n├── test_stability.py         # Numerical stability\n├── test_references.py        # Golden masters\n└── fixtures/\n    ├── test_data.npz\n    └── reference_results.json\n```\n\n## Testing Checklist\n\n- [ ] Edge cases covered (0, ±∞, NaN)\n- [ ] Property tests for invariants\n- [ ] Benchmark tests for performance\n- [ ] Reproducibility verified\n- [ ] Reference implementation compared\n- [ ] Tolerances documented\n- [ ] Evidence logged and dated\n- [ ] Coverage > 90% for math code\n\nFile v1.9.17:skill-card.md\n\n## Description: <br>\nVerifies math-heavy code for algorithmic correctness and numerical stability. <br>\n\nThis skill is ready for commercial/non-commercial use. <br>\n\n## Publisher: <br>\n[athola](https://clawhub.ai/user/athola) <br>\n\n### License/Terms of Use: <br>\nMIT-0 <br>\n\n\n## Use Case: <br>\nDevelopers and engineers use this skill to review mathematical, scientific, statistical, numerical, and ML code for correct formulas, documented invariants, numerical stability, reproducibility, and sufficient test evidence. <br>\n\n### Deployment Geography for Use: <br>\nGlobal <br>\n\n## Known Risks and Mitigations: <br>\nRisk: The skill may ask an agent to run local tests, benchmarks, or notebooks in the target repository. <br>\nMitigation: Review proposed test commands and notebook contents before execution, especially in untrusted projects. <br>\nRisk: Mathematical review output can be incomplete or misleading if requirements, standards, or test evidence are missing. <br>\nMitigation: Require citations, reproducible evidence, and human review before relying on approve or block recommendations. <br>\n\n\n## Reference(s): <br>\n- [ClawHub skill page](https://clawhub.ai/athola/skills/nm-pensive-math-review) <br>\n- [Metadata homepage](https://github.com/athola/claude-night-market/tree/master/plugins/pensive) <br>\n- [Derivation Verification](artifact/modules/derivation-verification.md) <br>\n- [Numerical Stability Analysis](artifact/modules/numerical-stability.md) <br>\n- [Requirements Mapping](artifact/modules/requirements-mapping.md) <br>\n- [Testing Strategies for Mathematical Code](artifact/modules/testing-strategies.md) <br>\n\n\n## Skill Output: <br>\n**Output Type(s):** [text, markdown, code, shell commands, guidance] <br>\n**Output Format:** [Markdown review report with tables, issue entries, recommendations, and inline code or shell command blocks.] <br>\n**Output Parameters:** [1D] <br>\n**Other Properties Related to Output:** [May include risk classifications, mathematical invariants, derivation notes, stability findings, test evidence, and an approve or block recommendation.] <br>\n\n## Skill Version(s): <br>\n1.9.17 (source: server release metadata; artifact frontmatter says 1.9.8) <br>\n\n## Ethical Considerations: <br>\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment. <br>\n\nArchive v1.9.16: 7 files, 11046 bytes\n\nFiles: modules/derivation-verification.md (3255b), modules/numerical-stability.md (2650b), modules/requirements-mapping.md (3561b), modules/testing-strategies.md (4867b), skill-card.md (2234b), SKILL.md (5126b), _meta.json (142b)\n\nFile v1.9.16:SKILL.md\n\n---\nname: math-review\ndescription: Verifies math-heavy code for algorithmic correctness and numerical stability\nversion: 1.9.8\ntriggers:\n  - math\n  - algorithms\n  - numerical\n  - stability\n  - verification\n  - scientific\n  - reviewing scientific algorithms\n  - ML models\n  - or numerical code\nmetadata: {\"openclaw\": {\"homepage\": \"https://github.com/athola/claude-night-market/tree/master/plugins/pensive\", \"emoji\": \"\\ud83e\\udd9e\", \"requires\": {\"config\": [\"night-market.pensive:shared\", \"night-market.imbue:proof-of-work\"]}}}\nsource: claude-night-market\nsource_plugin: pensive\n---\n\n> **Night Market Skill** — ported from [claude-night-market/pensive](https://github.com/athola/claude-night-market/tree/master/plugins/pensive). For the full experience with agents, hooks, and commands, install the Claude Code plugin.\n\n\n## Table of Contents\n\n- [Quick Start](#quick-start)\n- [When to Use](#when-to-use)\n- [Required TodoWrite Items](#required-todowrite-items)\n- [Core Workflow](#core-workflow)\n- [1. Context Sync](#1-context-sync)\n- [2. Requirements Mapping](#2-requirements-mapping)\n- [3. Derivation Verification](#3-derivation-verification)\n- [4. Stability Assessment](#4-stability-assessment)\n- [5. Proof of Work](#5-proof-of-work)\n- [Progressive Loading](#progressive-loading)\n- [Essential Checklist](#essential-checklist)\n- [Output Format](#output-format)\n- [Summary](#summary)\n- [Context](#context)\n- [Requirements Analysis](#requirements-analysis)\n- [Derivation Review](#derivation-review)\n- [Stability Analysis](#stability-analysis)\n- [Issues](#issues)\n- [Recommendation](#recommendation)\n- [Exit Criteria](#exit-criteria)\n\n\n# Mathematical Algorithm Review\n\nIntensive analysis ensuring numerical stability and alignment with standards.\n\n## Quick Start\n\n```bash\n/math-review\n```\n**Verification:** Run the command with `--help` flag to verify availability.\n\n## When To Use\n\n- Changes to mathematical models or algorithms\n- Statistical routines or probabilistic logic\n- Numerical integration or optimization\n- Scientific computing code\n- ML/AI model implementations\n- Safety-critical calculations\n\n## When NOT To Use\n\n- General algorithm review -\n  use architecture-review\n- Performance optimization - use parseltongue:python-performance\n- General algorithm review -\n  use architecture-review\n- Performance optimization - use parseltongue:python-performance\n\n## Required TodoWrite Items\n\n1. `math-review:context-synced`\n2. `math-review:requirements-mapped`\n3. `math-review:derivations-verified`\n4. `math-review:stability-assessed`\n5. `math-review:evidence-logged`\n\n## Core Workflow\n\n### 1. Context Sync\n```bash\npwd && git status -sb && git diff --stat origin/main..HEAD\n```\n**Verification:** Run `git status` to confirm working tree state.\nEnumerate math-heavy files (source, tests, docs, notebooks). Classify risk: safety-critical, financial, ML fairness.\n\n### 2. Requirements Mapping\nTranslate requirements → mathematical invariants. Document pre/post conditions, conservation laws, bounds. **Load**: `modules/requirements-mapping.md`\n\n### 3. Derivation Verification\nRe-derive formulas using CAS. Challenge approximations. Cite authoritative standards (NASA-STD-7009, ASME VVUQ). **Load**: `modules/derivation-verification.md`\n\n### 4. Stability Assessment\nEvaluate conditioning, precision, scaling, randomness. Compare complexity. Quantify uncertainty. **Load**: `modules/numerical-stability.md`\n\n### 5. Proof of Work\n```bash\npytest tests/math/ --benchmark\njupyter nbconvert --execute derivation.ipynb\n```\n**Verification:** Run `pytest -v tests/math/` to verify.\nLog deviations, recommend: Approve / Approve with actions / Block. **Load**: `modules/testing-strategies.md`\n\n## Progressive Loading\n\n**Default (200 tokens)**: Core workflow, checklists\n**+Requirements** (+300 tokens): Invariants, pre/post conditions, coverage analysis\n**+Derivation** (+350 tokens): CAS verification, standards, citations\n**+Stability** (+400 tokens): Numerical properties, precision, complexity\n**+Testing** (+350 tokens): Edge cases, benchmarks, reproducibility\n\n**Total with all modules**: ~1600 tokens\n\n## Essential Checklist\n\n**Correctness**: Formulas match spec | Edge cases handled | Units consistent | Domain enforced\n**Stability**: Condition number OK | Precision sufficient | No cancellation | Overflow prevented\n**Verification**: Derivations documented | References cited | Tests cover invariants | Benchmarks reproducible\n**Documentation**: Assumptions stated | Limitations documented | Error bounds specified | References linked\n\n## Output Format\n\n```markdown\n## Summary\n[Brief findings]\n\n## Context\nFiles | Risk classification | Standards\n\n## Requirements Analysis\n| Invariant | Verified | Evidence |\n\n## Derivation Review\n[Status and conflicts]\n\n## Stability Analysis\nCondition number | Precision | Risks\n\n## Issues\n[M1] [Title]: Location | Issue | Fix\n\n## Recommendation\nApprove / Approve with actions / Block\n```\n**Verification:** Run the command with `--help` flag to verify availability.\n\n## Exit Criteria\n\n- Context synced, requirements mapped, derivations verified, stability assessed, evidence logged with citations\n\nFile v1.9.16:_meta.json\n\n{\n  \"ownerId\": \"kn7d107jg9jv602h9ytsegydq184a42s\",\n  \"slug\": \"nm-pensive-math-review\",\n  \"version\": \"1.9.16\",\n  \"publishedAt\": 1784058954335\n}\n\nFile v1.9.16:modules/derivation-verification.md\n\n---\nparent_skill: pensive:math-review\nload_priority: high\nestimated_tokens: 350\n---\n\n# Derivation Verification\n\n## Re-derive Critical Formulas\n\n**Symbolic Verification**\n- Use Computer Algebra Systems (SymPy, Mathematica, Maple)\n- Confirm algebraic manipulations\n- Verify calculus operations (derivatives, integrals)\n- Check limit behavior\n\n**Computational Notebooks**\n```python\n# Example: Verify gradient computation\nimport sympy as sp\nx, y = sp.symbols('x y')\nf = x**2 + y**2\ngrad_f = [sp.diff(f, var) for var in [x, y]]\n# Compare with implementation\n```\n\n**Probabilistic Reasoning**\n- Verify conditional probability formulas\n- Check Bayes rule applications\n- Confirm expectation/variance calculations\n- Validate distribution properties\n\n## Challenge Approximations\n\n**Series Truncation**\n- Document truncation order (e.g., O(h³))\n- Estimate truncation error\n- Test convergence with different orders\n- Provide error bounds across domain\n\n**Linearizations**\n- Identify linearization points\n- Estimate valid domain size\n- Test against full nonlinear model\n- Document approximation quality\n\n**Surrogate Models**\n- Compare surrogate to ground truth\n- Quantify approximation error\n- Document training/validation data\n- Test extrapolation behavior\n\n**Error Bounds**\n- Derive theoretical error bounds\n- Verify empirically\n- Document worst-case scenarios\n- Test at domain boundaries\n\n## Authoritative References\n\n**Standards and Frameworks**\n- **NASA-STD-7009**: Modeling and Simulation V&V\n- **ASME V&V 20**: Verification & Validation in CFD/HT\n- **ASME V&V 10**: Guide for V&V in Computational Solid Mechanics\n- **SIAM**: Reproducibility checklists\n- **IEEE 754**: Floating-point arithmetic\n- **NIST**: Uncertainty quantification guidelines\n\n**Academic Sources**\n- Peer-reviewed papers (DOI links)\n- Textbooks (edition and page numbers)\n- Technical reports\n- Conference proceedings\n\n**Implementation References**\n- Reference implementations (NumPy, SciPy, GSL)\n- Algorithm papers (original sources)\n- Numerical recipes\n- Domain-specific libraries\n\n## Document Conflicts\n\nWhen implementation deviates from standards:\n\n```markdown\n### Deviation: [Brief title]\n- **Standard**: NASA-STD-7009 Section 3.4.2\n- **Requirement**: Monte Carlo with n≥1000 samples\n- **Implementation**: n=100 samples\n- **Justification**: Performance constraints\n- **Risk**: Reduced confidence intervals\n- **Mitigation**: Document uncertainty, flag results\n- **Owner**: [name]\n- **Due date**: [date]\n```\n\n## Citation Format\n\n```markdown\n## References\n\n[1] Wilkinson, J.H. (1963). *Rounding Errors in Algebraic Processes*.\n    Prentice-Hall. Chapter 3.\n\n[2] NASA-STD-7009A. (2016). *Standard for Models and Simulations*.\n    Section 4.2: Verification Requirements.\n\n[3] Goldberg, D. (1991). \"What Every Computer Scientist Should Know\n    About Floating-Point Arithmetic\". *ACM Computing Surveys*, 23(1).\n    DOI: 10.1145/103162.103163\n```\n\n## Verification Checklist\n\n- [ ] Formulas re-derived from first principles\n- [ ] Symbolic verification completed (CAS)\n- [ ] Approximation order documented\n- [ ] Error bounds derived and tested\n- [ ] Authoritative references cited\n- [ ] Deviations from standards documented\n- [ ] Conflicts resolved or flagged\n- [ ] Implementation matches theory\n\nFile v1.9.16:modules/numerical-stability.md\n\n---\nparent_skill: pensive:math-review\nload_priority: high\nestimated_tokens: 400\n---\n\n# Numerical Stability Analysis\n\n## Conditioning\n\n**Condition Numbers**\n- Measure sensitivity to input perturbations\n- High condition number = unstable computation\n- Use scaled condition numbers when possible\n\n**Sensitivity Analysis**\n- Perturb inputs systematically\n- Measure output variation\n- Document acceptable tolerance ranges\n\n## Precision Management\n\n**Floating-Point Error Propagation**\n```python\n# Bad: Accumulating small values into large\ntotal = 1e15\nfor x in small_values:\n    total += x  # Precision lost\n\n# Good: Kahan summation or sort first\nsorted_values = sorted(small_values)\ntotal = sum(sorted_values)  # Better precision\n```\n\n**Catastrophic Cancellation**\n```python\n# Bad: Subtracting similar values\nresult = (a + epsilon) - a  # Catastrophic cancellation\n\n# Good: Reformulate to avoid\nresult = epsilon  # Direct computation\n```\n\n**Overflow/Underflow Prevention**\n- Check dynamic range before operations\n- Use log-space for very large/small products\n- Normalize intermediate results\n- Scale inputs to manageable ranges\n\n## Scaling and Normalization\n\n**Dynamic Range Handling**\n- Pre-scale inputs to [0, 1] or [-1, 1]\n- Use log-transforms for exponential data\n- Document scaling factors and units\n\n**Normalization Requirements**\n- L1/L2 normalization for vectors\n- Feature scaling for ML inputs\n- Unit conversions for physical quantities\n\n## Randomness Control\n\n**Reproducibility**\n- Set explicit random seeds\n- Document PRNG algorithms used\n- Version lock numerical libraries\n- Test deterministic behavior\n\n**Seed Management**\n```python\n# Good: Explicit seed control\nimport numpy as np\nnp.random.seed(42)\n\n# Better: Isolated RNG state\nrng = np.random.RandomState(42)\nsamples = rng.normal(0, 1, size=100)\n```\n\n## Complexity Analysis\n\nCompare algorithmic complexity before/after changes:\n\n```\nBefore: O(n²) time, O(n) space\nAfter:  O(n log n) time, O(n) space\nImprovement: 100x faster for n=1000\n```\n\nDocument:\n- Time complexity\n- Space complexity\n- Cache behavior\n- Parallelization potential\n\n## Uncertainty Quantification\n\nRequired for:\n- Safety-critical systems\n- Data-driven components\n- High-stakes decisions\n- Regulatory compliance\n\nMethods:\n- Monte Carlo sampling\n- Bootstrap confidence intervals\n- Sensitivity analysis\n- Error propagation formulas\n\n## Stability Checklist\n\n- [ ] Condition number < 1e6\n- [ ] Precision loss < 1e-10\n- [ ] No catastrophic cancellation\n- [ ] Overflow/underflow prevented\n- [ ] Scaling applied appropriately\n- [ ] Random seeds controlled\n- [ ] Complexity acceptable\n- [ ] Uncertainty quantified (if required)\n\nFile v1.9.16:modules/requirements-mapping.md\n\n---\nparent_skill: pensive:math-review\nload_priority: medium\nestimated_tokens: 300\n---\n\n# Requirements Mapping\n\n## Mathematical Invariants\n\nTranslate requirements into verifiable mathematical properties:\n\n| Requirement | Invariant | Test Coverage |\n|-------------|-----------|---------------|\n| Positive output | f(x) > 0 ∀ x ∈ domain | Property test |\n| Conservation | Σ mass_in = Σ mass_out | Unit test |\n| Bounded error | \\|ε\\| < 1e-6 | Benchmark |\n| Monotonicity | x₁ < x₂ ⟹ f(x₁) ≤ f(x₂) | Property test |\n| Idempotence | f(f(x)) = f(x) | Unit test |\n\n## Pre-conditions\n\n**Input Validation**\n```python\ndef compute(x: float, n: int) -> float:\n    \"\"\"Compute function with documented preconditions.\n\n    Preconditions:\n    - x ≥ 0 (non-negative input)\n    - n > 0 (positive integer)\n    - x < 1e10 (prevent overflow)\n    \"\"\"\n    if x < 0:\n        raise ValueError(\"x must be non-negative\")\n    if n <= 0:\n        raise ValueError(\"n must be positive\")\n    if x >= 1e10:\n        raise ValueError(\"x must be < 1e10\")\n    # ... implementation\n```\n\n**Domain Constraints**\n- Valid input ranges\n- Type requirements\n- Dimensional consistency\n- Unit compatibility\n\n## Post-conditions\n\n**Output Guarantees**\n```python\ndef normalize(vector: np.ndarray) -> np.ndarray:\n    \"\"\"Normalize vector to unit length.\n\n    Postconditions:\n    - ||result|| = 1.0 (± 1e-10)\n    - result ∥ vector (parallel)\n    \"\"\"\n    result = vector / np.linalg.norm(vector)\n    assert abs(np.linalg.norm(result) - 1.0) < 1e-10\n    return result\n```\n\n**Invariant Preservation**\n- Conservation laws maintained\n- Bounds respected\n- Relationships preserved\n\n## Conservation Laws\n\n**Physical Conservation**\n- Mass conservation\n- Energy conservation\n- Momentum conservation\n- Charge conservation\n\n**Numerical Conservation**\n- Probability sums to 1.0\n- Symmetry preservation\n- Balance equations\n\n## Monotonicity Guarantees\n\n**Increasing Functions**\n```python\n# Property test\n@given(st.floats(min_value=0, max_value=100))\ndef test_monotonic_increasing(x1, x2):\n    assume(x1 < x2)\n    assert f(x1) <= f(x2)\n```\n\n**Convexity/Concavity**\n- Second derivative tests\n- Jensen's inequality\n- Midpoint properties\n\n## Probabilistic Bounds\n\n**Confidence Intervals**\n- Document confidence levels (95%, 99%)\n- Specify interval type (credible, confidence)\n- Test coverage probabilities\n\n**Error Probabilities**\n- Type I/II error rates\n- False positive/negative rates\n- Statistical power\n\n## Coverage Gap Analysis\n\nIdentify untested invariants:\n\n```markdown\n### Coverage Gaps\n\n**Missing Tests**\n- [ ] Boundary condition: x = 0\n- [ ] Overflow case: x > 1e15\n- [ ] Negative input handling\n- [ ] Conservation at t → ∞\n\n**Insufficient Coverage**\n- [ ] Only 3 test cases for n-dimensional invariant\n- [ ] No property tests for monotonicity\n- [ ] Missing edge case: empty input\n```\n\n## Documentation Template\n\n```python\ndef algorithm(inputs) -> outputs:\n    \"\"\"Brief description.\n\n    Mathematical Properties:\n    - Preconditions: [domain constraints]\n    - Postconditions: [guaranteed properties]\n    - Invariants: [preserved relationships]\n    - Complexity: [time/space bounds]\n    - Stability: [condition number, error bounds]\n\n    References:\n    - [Citation to algorithm source]\n    \"\"\"\n```\n\n## Mapping Checklist\n\n- [ ] Requirements translated to invariants\n- [ ] Pre-conditions documented\n- [ ] Post-conditions verified\n- [ ] Conservation laws tested\n- [ ] Monotonicity/convexity checked\n- [ ] Probabilistic bounds specified\n- [ ] Coverage gaps identified\n- [ ] All properties have tests\n\nFile v1.9.16:modules/testing-strategies.md\n\n---\nparent_skill: pensive:math-review\nload_priority: medium\nestimated_tokens: 350\n---\n\n# Testing Strategies for Mathematical Code\n\n## Edge Case Coverage\n\n**Domain Boundaries**\n```python\n# Bad: Undefined for negative\nresult = math.sqrt(value)\n\n# Good: Validate domain\ndef safe_sqrt(value: float) -> float:\n    if value < 0:\n        raise ValueError(\"sqrt requires non-negative input\")\n    return math.sqrt(value)\n\n# Test edge cases\n@pytest.mark.parametrize(\"value\", [0, 1e-100, 1e100, float('inf')])\ndef test_sqrt_boundaries(value):\n    result = safe_sqrt(value)\n    assert result >= 0\n```\n\n**Special Values**\n- Zero\n- One\n- Infinity\n- NaN\n- Very small (underflow)\n- Very large (overflow)\n- Negative values\n- Empty inputs\n\n## Property-Based Testing\n\n**Hypothesis Framework**\n```python\nfrom hypothesis import given, strategies as st\n\n@given(st.floats(min_value=0, max_value=1e6))\ndef test_sqrt_inverse(x):\n    \"\"\"sqrt(x)² should equal x\"\"\"\n    result = safe_sqrt(x)\n    assert abs(result * result - x) < 1e-10 * x\n```\n\n**Invariant Testing**\n- Symmetry properties\n- Associativity/commutativity\n- Idempotence\n- Conservation laws\n- Monotonicity\n\n## Benchmark Testing\n\n**Performance Validation**\n```bash\npytest tests/math/ --benchmark-only\npytest tests/math/ --benchmark-compare=baseline\n```\n\n**Regression Detection**\n```python\ndef test_algorithm_performance(benchmark):\n    \"\"\"validate O(n log n) complexity maintained\"\"\"\n    n = 10000\n    data = np.random.rand(n)\n\n    result = benchmark(algorithm, data)\n\n    # Verify result correctness\n    assert len(result) == n\n    # Performance constraint\n    assert benchmark.stats['mean'] < 0.1  # seconds\n```\n\n**Complexity Verification**\n- Time scaling tests\n- Memory profiling\n- Cache behavior\n- Parallel efficiency\n\n## Reproducibility Testing\n\n**Deterministic Results**\n```python\ndef test_reproducibility():\n    \"\"\"Same seed produces same results\"\"\"\n    np.random.seed(42)\n    result1 = monte_carlo_simulation()\n\n    np.random.seed(42)\n    result2 = monte_carlo_simulation()\n\n    np.testing.assert_array_equal(result1, result2)\n```\n\n**Version Pinning**\n```toml\n# pyproject.toml\n[tool.poetry.dependencies]\nnumpy = \"==1.24.0\"  # Pin for reproducibility\nscipy = \"==1.10.0\"\n```\n\n## Reference Implementation Tests\n\n**Golden Master Testing**\n```python\ndef test_against_reference():\n    \"\"\"Compare with NumPy/SciPy reference\"\"\"\n    x = np.linspace(0, 10, 100)\n\n    our_result = our_implementation(x)\n    reference_result = scipy.special.reference_function(x)\n\n    np.testing.assert_allclose(\n        our_result,\n        reference_result,\n        rtol=1e-10,\n        atol=1e-12\n    )\n```\n\n**Cross-Validation**\n- Multiple independent implementations\n- Different algorithms\n- Analytical solutions (when available)\n- Published test cases\n\n## Numerical Accuracy Tests\n\n**Tolerance Specifications**\n```python\n# Absolute tolerance\nnp.testing.assert_allclose(result, expected, atol=1e-10)\n\n# Relative tolerance\nnp.testing.assert_allclose(result, expected, rtol=1e-8)\n\n# Both\nnp.testing.assert_allclose(\n    result, expected,\n    rtol=1e-8, atol=1e-10\n)\n```\n\n**ULP (Units in Last Place) Testing**\n```python\n# For critical floating-point comparisons\nassert abs(a - b) <= 2 * np.finfo(float).eps * max(abs(a), abs(b))\n```\n\n## Evidence Logging\n\n**Execution Records**\n```bash\n# Run tests with output capture\npytest tests/math/ -v --tb=short > test_results.txt\n\n# Benchmark with JSON output\npytest tests/math/ --benchmark-json=benchmark.json\n\n# Execute derivation notebooks\njupyter nbconvert --execute derivation.ipynb \\\n    --to html --output verification.html\n```\n\n**Documentation Template**\n```markdown\n## Test Evidence\n\n### Unit Tests\n- **Command**: `pytest tests/math/ -v`\n- **Result**: 47/47 passed\n- **Coverage**: 94%\n- **Date**: 2025-12-06\n\n### Benchmarks\n- **Command**: `pytest tests/math/ --benchmark-only`\n- **Mean time**: 23.4ms (±1.2ms)\n- **Baseline**: 24.1ms\n- **Improvement**: 3%\n\n### Derivation Verification\n- **Notebook**: derivation.ipynb\n- **Status**: All cells executed successfully\n- **Symbolic checks**: Passed\n- **Reference comparison**: Within tolerance\n```\n\n## Test Organization\n\n```\ntests/math/\n├── test_correctness.py       # Basic functionality\n├── test_edge_cases.py        # Boundary conditions\n├── test_properties.py        # Hypothesis tests\n├── test_benchmarks.py        # Performance\n├── test_stability.py         # Numerical stability\n├── test_references.py        # Golden masters\n└── fixtures/\n    ├── test_data.npz\n    └── reference_results.json\n```\n\n## Testing Checklist\n\n- [ ] Edge cases covered (0, ±∞, NaN)\n- [ ] Property tests for invariants\n- [ ] Benchmark tests for performance\n- [ ] Reproducibility verified\n- [ ] Reference implementation compared\n- [ ] Tolerances documented\n- [ ] Evidence logged and dated\n- [ ] Coverage > 90% for math code\n\nFile v1.9.16:skill-card.md\n\n## Description: <br>\nVerifies math-heavy code for algorithmic correctness and numerical stability. <br>\n\nThis skill is ready for commercial/non-commercial use. <br>\n\n## Publisher: <br>\n[athola](https://clawhub.ai/user/athola) <br>\n\n### License/Terms of Use: <br>\nMIT-0 <br>\n\n\n## Use Case: <br>\nDevelopers and engineers use this skill to review mathematical, scientific, numerical, statistical, and ML code for correctness, stability, test coverage, and evidence-backed approval recommendations. <br>\n\n### Deployment Geography for Use: <br>\nGlobal <br>\n\n## Known Risks and Mitigations: <br>\nRisk: The skill may activate on broad math or algorithm topics and produce review guidance outside the user's intended scope. <br>\nMitigation: Confirm the target files and review scope before following its recommendations. <br>\nRisk: Suggested tests, benchmarks, or notebook execution commands may run repository code. <br>\nMitigation: Run proposed commands only in repositories and execution environments the user trusts. <br>\nRisk: Review findings or mathematical recommendations may be incorrect or incomplete. <br>\nMitigation: Have a qualified reviewer check findings, derivations, and cited evidence before relying on the result for high-stakes decisions. <br>\n\n\n## Reference(s): <br>\n- [ClawHub Skill Page](https://clawhub.ai/athola/skills/nm-pensive-math-review) <br>\n- [OpenClaw Homepage](https://github.com/athola/claude-night-market/tree/master/plugins/pensive) <br>\n\n\n## Skill Output: <br>\n**Output Type(s):** [Markdown, Analysis, Shell commands, Code, Guidance] <br>\n**Output Format:** [Markdown review report with issue lists, tables, recommendations, and inline shell or code blocks] <br>\n**Output Parameters:** [1D] <br>\n**Other Properties Related to Output:** [May propose tests, benchmarks, notebook execution, derivation checks, and approval or blocking recommendations.] <br>\n\n## Skill Version(s): <br>\n1.9.16 (source: server release metadata) <br>\n\n## Ethical Considerations: <br>\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment. <br>\n\nArchive v1.9.14: 7 files, 11039 bytes\n\nFiles: modules/derivation-verification.md (3255b), modules/numerical-stability.md (2650b), modules/requirements-mapping.md (3561b), modules/testing-strategies.md (4867b), skill-card.md (2253b), SKILL.md (5126b), _meta.json (142b)\n\nFile v1.9.14:SKILL.md\n\n---\nname: math-review\ndescription: Verifies math-heavy code for algorithmic correctness and numerical stability\nversion: 1.9.8\ntriggers:\n  - math\n  - algorithms\n  - numerical\n  - stability\n  - verification\n  - scientific\n  - reviewing scientific algorithms\n  - ML models\n  - or numerical code\nmetadata: {\"openclaw\": {\"homepage\": \"https://github.com/athola/claude-night-market/tree/master/plugins/pensive\", \"emoji\": \"\\ud83e\\udd9e\", \"requires\": {\"config\": [\"night-market.pensive:shared\", \"night-market.imbue:proof-of-work\"]}}}\nsource: claude-night-market\nsource_plugin: pensive\n---\n\n> **Night Market Skill** — ported from [claude-night-market/pensive](https://github.com/athola/claude-night-market/tree/master/plugins/pensive). For the full experience with agents, hooks, and commands, install the Claude Code plugin.\n\n\n## Table of Contents\n\n- [Quick Start](#quick-start)\n- [When to Use](#when-to-use)\n- [Required TodoWrite Items](#required-todowrite-items)\n- [Core Workflow](#core-workflow)\n- [1. Context Sync](#1-context-sync)\n- [2. Requirements Mapping](#2-requirements-mapping)\n- [3. Derivation Verification](#3-derivation-verification)\n- [4. Stability Assessment](#4-stability-assessment)\n- [5. Proof of Work](#5-proof-of-work)\n- [Progressive Loading](#progressive-loading)\n- [Essential Checklist](#essential-checklist)\n- [Output Format](#output-format)\n- [Summary](#summary)\n- [Context](#context)\n- [Requirements Analysis](#requirements-analysis)\n- [Derivation Review](#derivation-review)\n- [Stability Analysis](#stability-analysis)\n- [Issues](#issues)\n- [Recommendation](#recommendation)\n- [Exit Criteria](#exit-criteria)\n\n\n# Mathematical Algorithm Review\n\nIntensive analysis ensuring numerical stability and alignment with standards.\n\n## Quick Start\n\n```bash\n/math-review\n```\n**Verification:** Run the command with `--help` flag to verify availability.\n\n## When To Use\n\n- Changes to mathematical models or algorithms\n- Statistical routines or probabilistic logic\n- Numerical integration or optimization\n- Scientific computing code\n- ML/AI model implementations\n- Safety-critical calculations\n\n## When NOT To Use\n\n- General algorithm review -\n  use architecture-review\n- Performance optimization - use parseltongue:python-performance\n- General algorithm review -\n  use architecture-review\n- Performance optimization - use parseltongue:python-performance\n\n## Required TodoWrite Items\n\n1. `math-review:context-synced`\n2. `math-review:requirements-mapped`\n3. `math-review:derivations-verified`\n4. `math-review:stability-assessed`\n5. `math-review:evidence-logged`\n\n## Core Workflow\n\n### 1. Context Sync\n```bash\npwd && git status -sb && git diff --stat origin/main..HEAD\n```\n**Verification:** Run `git status` to confirm working tree state.\nEnumerate math-heavy files (source, tests, docs, notebooks). Classify risk: safety-critical, financial, ML fairness.\n\n### 2. Requirements Mapping\nTranslate requirements → mathematical invariants. Document pre/post conditions, conservation laws, bounds. **Load**: `modules/requirements-mapping.md`\n\n### 3. Derivation Verification\nRe-derive formulas using CAS. Challenge approximations. Cite authoritative standards (NASA-STD-7009, ASME VVUQ). **Load**: `modules/derivation-verification.md`\n\n### 4. Stability Assessment\nEvaluate conditioning, precision, scaling, randomness. Compare complexity. Quantify uncertainty. **Load**: `modules/numerical-stability.md`\n\n### 5. Proof of Work\n```bash\npytest tests/math/ --benchmark\njupyter nbconvert --execute derivation.ipynb\n```\n**Verification:** Run `pytest -v tests/math/` to verify.\nLog deviations, recommend: Approve / Approve with actions / Block. **Load**: `modules/testing-strategies.md`\n\n## Progressive Loading\n\n**Default (200 tokens)**: Core workflow, checklists\n**+Requirements** (+300 tokens): Invariants, pre/post conditions, coverage analysis\n**+Derivation** (+350 tokens): CAS verification, standards, citations\n**+Stability** (+400 tokens): Numerical properties, precision, complexity\n**+Testing** (+350 tokens): Edge cases, benchmarks, reproducibility\n\n**Total with all modules**: ~1600 tokens\n\n## Essential Checklist\n\n**Correctness**: Formulas match spec | Edge cases handled | Units consistent | Domain enforced\n**Stability**: Condition number OK | Precision sufficient | No cancellation | Overflow prevented\n**Verification**: Derivations documented | References cited | Tests cover invariants | Benchmarks reproducible\n**Documentation**: Assumptions stated | Limitations documented | Error bounds specified | References linked\n\n## Output Format\n\n```markdown\n## Summary\n[Brief findings]\n\n## Context\nFiles | Risk classification | Standards\n\n## Requirements Analysis\n| Invariant | Verified | Evidence |\n\n## Derivation Review\n[Status and conflicts]\n\n## Stability Analysis\nCondition number | Precision | Risks\n\n## Issues\n[M1] [Title]: Location | Issue | Fix\n\n## Recommendation\nApprove / Approve with actions / Block\n```\n**Verification:** Run the command with `--help` flag to verify availability.\n\n## Exit Criteria\n\n- Context synced, requirements mapped, derivations verified, stability assessed, evidence logged with citations\n\nFile v1.9.14:_meta.json\n\n{\n  \"ownerId\": \"kn7d107jg9jv602h9ytsegydq184a42s\",\n  \"slug\": \"nm-pensive-math-review\",\n  \"version\": \"1.9.14\",\n  \"publishedAt\": 1782842654103\n}\n\nFile v1.9.14:modules/derivation-verification.md\n\n---\nparent_skill: pensive:math-review\nload_priority: high\nestimated_tokens: 350\n---\n\n# Derivation Verification\n\n## Re-derive Critical Formulas\n\n**Symbolic Verification**\n- Use Computer Algebra Systems (SymPy, Mathematica, Maple)\n- Confirm algebraic manipulations\n- Verify calculus operations (derivatives, integrals)\n- Check limit behavior\n\n**Computational Notebooks**\n```python\n# Example: Verify gradient computation\nimport sympy as sp\nx, y = sp.symbols('x y')\nf = x**2 + y**2\ngrad_f = [sp.diff(f, var) for var in [x, y]]\n# Compare with implementation\n```\n\n**Probabilistic Reasoning**\n- Verify conditional probability formulas\n- Check Bayes rule applications\n- Confirm expectation/variance calculations\n- Validate distribution properties\n\n## Challenge Approximations\n\n**Series Truncation**\n- Document truncation order (e.g., O(h³))\n- Estimate truncation error\n- Test convergence with different orders\n- Provide error bounds across domain\n\n**Linearizations**\n- Identify linearization points\n- Estimate valid domain size\n- Test against full nonlinear model\n- Document approximation quality\n\n**Surrogate Models**\n- Compare surrogate to ground truth\n- Quantify approximation error\n- Document training/validation data\n- Test extrapolation behavior\n\n**Error Bounds**\n- Derive theoretical error bounds\n- Verify empirically\n- Document worst-case scenarios\n- Test at domain boundaries\n\n## Authoritative References\n\n**Standards and Frameworks**\n- **NASA-STD-7009**: Modeling and Simulation V&V\n- **ASME V&V 20**: Verification & Validation in CFD/HT\n- **ASME V&V 10**: Guide for V&V in Computational Solid Mechanics\n- **SIAM**: Reproducibility checklists\n- **IEEE 754**: Floating-point arithmetic\n- **NIST**: Uncertainty quantification guidelines\n\n**Academic Sources**\n- Peer-reviewed papers (DOI links)\n- Textbooks (edition and page numbers)\n- Technical reports\n- Conference proceedings\n\n**Implementation References**\n- Reference implementations (NumPy, SciPy, GSL)\n- Algorithm papers (original sources)\n- Numerical recipes\n- Domain-specific libraries\n\n## Document Conflicts\n\nWhen implementation deviates from standards:\n\n```markdown\n### Deviation: [Brief title]\n- **Standard**: NASA-STD-7009 Section 3.4.2\n- **Requirement**: Monte Carlo with n≥1000 samples\n- **Implementation**: n=100 samples\n- **Justification**: Performance constraints\n- **Risk**: Reduced confidence intervals\n- **Mitigation**: Document uncertainty, flag results\n- **Owner**: [name]\n- **Due date**: [date]\n```\n\n## Citation Format\n\n```markdown\n## References\n\n[1] Wilkinson, J.H. (1963). *Rounding Errors in Algebraic Processes*.\n    Prentice-Hall. Chapter 3.\n\n[2] NASA-STD-7009A. (2016). *Standard for Models and Simulations*.\n    Section 4.2: Verification Requirements.\n\n[3] Goldberg, D. (1991). \"What Every Computer Scientist Should Know\n    About Floating-Point Arithmetic\". *ACM Computing Surveys*, 23(1).\n    DOI: 10.1145/103162.103163\n```\n\n## Verification Checklist\n\n- [ ] Formulas re-derived from first principles\n- [ ] Symbolic verification completed (CAS)\n- [ ] Approximation order documented\n- [ ] Error bounds derived and tested\n- [ ] Authoritative references cited\n- [ ] Deviations from standards documented\n- [ ] Conflicts resolved or flagged\n- [ ] Implementation matches theory\n\nFile v1.9.14:modules/numerical-stability.md\n\n---\nparent_skill: pensive:math-review\nload_priority: high\nestimated_tokens: 400\n---\n\n# Numerical Stability Analysis\n\n## Conditioning\n\n**Condition Numbers**\n- Measure sensitivity to input perturbations\n- High condition number = unstable computation\n- Use scaled condition numbers when possible\n\n**Sensitivity Analysis**\n- Perturb inputs systematically\n- Measure output variation\n- Document acceptable tolerance ranges\n\n## Precision Management\n\n**Floating-Point Error Propagation**\n```python\n# Bad: Accumulating small values into large\ntotal = 1e15\nfor x in small_values:\n    total += x  # Precision lost\n\n# Good: Kahan summation or sort first\nsorted_values = sorted(small_values)\ntotal = sum(sorted_values)  # Better precision\n```\n\n**Catastrophic Cancellation**\n```python\n# Bad: Subtracting similar values\nresult = (a + epsilon) - a  # Catastrophic cancellation\n\n# Good: Reformulate to avoid\nresult = epsilon  # Direct computation\n```\n\n**Overflow/Underflow Prevention**\n- Check dynamic range before operations\n- Use log-space for very large/small products\n- Normalize intermediate results\n- Scale inputs to manageable ranges\n\n## Scaling and Normalization\n\n**Dynamic Range Handling**\n- Pre-scale inputs to [0, 1] or [-1, 1]\n- Use log-transforms for exponential data\n- Document scaling factors and units\n\n**Normalization Requirements**\n- L1/L2 normalization for vectors\n- Feature scaling for ML inputs\n- Unit conversions for physical quantities\n\n## Randomness Control\n\n**Reproducibility**\n- Set explicit random seeds\n- Document PRNG algorithms used\n- Version lock numerical libraries\n- Test deterministic behavior\n\n**Seed Management**\n```python\n# Good: Explicit seed control\nimport numpy as np\nnp.random.seed(42)\n\n# Better: Isolated RNG state\nrng = np.random.RandomState(42)\nsamples = rng.normal(0, 1, size=100)\n```\n\n## Complexity Analysis\n\nCompare algorithmic complexity before/after changes:\n\n```\nBefore: O(n²) time, O(n) space\nAfter:  O(n log n) time, O(n) space\nImprovement: 100x faster for n=1000\n```\n\nDocument:\n- Time complexity\n- Space complexity\n- Cache behavior\n- Parallelization potential\n\n## Uncertainty Quantification\n\nRequired for:\n- Safety-critical systems\n- Data-driven components\n- High-stakes decisions\n- Regulatory compliance\n\nMethods:\n- Monte Carlo sampling\n- Bootstrap confidence intervals\n- Sensitivity analysis\n- Error propagation formulas\n\n## Stability Checklist\n\n- [ ] Condition number < 1e6\n- [ ] Precision loss < 1e-10\n- [ ] No catastrophic cancellation\n- [ ] Overflow/underflow prevented\n- [ ] Scaling applied appropriately\n- [ ] Random seeds controlled\n- [ ] Complexity acceptable\n- [ ] Uncertainty quantified (if required)\n\nFile v1.9.14:modules/requirements-mapping.md\n\n---\nparent_skill: pensive:math-review\nload_priority: medium\nestimated_tokens: 300\n---\n\n# Requirements Mapping\n\n## Mathematical Invariants\n\nTranslate requirements into verifiable mathematical properties:\n\n| Requirement | Invariant | Test Coverage |\n|-------------|-----------|---------------|\n| Positive output | f(x) > 0 ∀ x ∈ domain | Property test |\n| Conservation | Σ mass_in = Σ mass_out | Unit test |\n| Bounded error | \\|ε\\| < 1e-6 | Benchmark |\n| Monotonicity | x₁ < x₂ ⟹ f(x₁) ≤ f(x₂) | Property test |\n| Idempotence | f(f(x)) = f(x) | Unit test |\n\n## Pre-conditions\n\n**Input Validation**\n```python\ndef compute(x: float, n: int) -> float:\n    \"\"\"Compute function with documented preconditions.\n\n    Preconditions:\n    - x ≥ 0 (non-negative input)\n    - n > 0 (positive integer)\n    - x < 1e10 (prevent overflow)\n    \"\"\"\n    if x < 0:\n        raise ValueError(\"x must be non-negative\")\n    if n <= 0:\n        raise ValueError(\"n must be positive\")\n    if x >= 1e10:\n        raise ValueError(\"x must be < 1e10\")\n    # ... implementation\n```\n\n**Domain Constraints**\n- Valid input ranges\n- Type requirements\n- Dimensional consistency\n- Unit compatibility\n\n## Post-conditions\n\n**Output Guarantees**\n```python\ndef normalize(vector: np.ndarray) -> np.ndarray:\n    \"\"\"Normalize vector to unit length.\n\n    Postconditions:\n    - ||result|| = 1.0 (± 1e-10)\n    - result ∥ vector (parallel)\n    \"\"\"\n    result = vector / np.linalg.norm(vector)\n    assert abs(np.linalg.norm(result) - 1.0) < 1e-10\n    return result\n```\n\n**Invariant Preservation**\n- Conservation laws maintained\n- Bounds respected\n- Relationships preserved\n\n## Conservation Laws\n\n**Physical Conservation**\n- Mass conservation\n- Energy conservation\n- Momentum conservation\n- Charge conservation\n\n**Numerical Conservation**\n- Probability sums to 1.0\n- Symmetry preservation\n- Balance equations\n\n## Monotonicity Guarantees\n\n**Increasing Functions**\n```python\n# Property test\n@given(st.floats(min_value=0, max_value=100))\ndef test_monotonic_increasing(x1, x2):\n    assume(x1 < x2)\n    assert f(x1) <= f(x2)\n```\n\n**Convexity/Concavity**\n- Second derivative tests\n- Jensen's inequality\n- Midpoint properties\n\n## Probabilistic Bounds\n\n**Confidence Intervals**\n- Document confidence levels (95%, 99%)\n- Specify interval type (credible, confidence)\n- Test coverage probabilities\n\n**Error Probabilities**\n- Type I/II error rates\n- False positive/negative rates\n- Statistical power\n\n## Coverage Gap Analysis\n\nIdentify untested invariants:\n\n```markdown\n### Coverage Gaps\n\n**Missing Tests**\n- [ ] Boundary condition: x = 0\n- [ ] Overflow case: x > 1e15\n- [ ] Negative input handling\n- [ ] Conservation at t → ∞\n\n**Insufficient Coverage**\n- [ ] Only 3 test cases for n-dimensional invariant\n- [ ] No property tests for monotonicity\n- [ ] Missing edge case: empty input\n```\n\n## Documentation Template\n\n```python\ndef algorithm(inputs) -> outputs:\n    \"\"\"Brief description.\n\n    Mathematical Properties:\n    - Preconditions: [domain constraints]\n    - Postconditions: [guaranteed properties]\n    - Invariants: [preserved relationships]\n    - Complexity: [time/space bounds]\n    - Stability: [condition number, error bounds]\n\n    References:\n    - [Citation to algorithm source]\n    \"\"\"\n```\n\n## Mapping Checklist\n\n- [ ] Requirements translated to invariants\n- [ ] Pre-conditions documented\n- [ ] Post-conditions verified\n- [ ] Conservation laws tested\n- [ ] Monotonicity/convexity checked\n- [ ] Probabilistic bounds specified\n- [ ] Coverage gaps identified\n- [ ] All properties have tests\n\nFile v1.9.14:modules/testing-strategies.md\n\n---\nparent_skill: pensive:math-review\nload_priority: medium\nestimated_tokens: 350\n---\n\n# Testing Strategies for Mathematical Code\n\n## Edge Case Coverage\n\n**Domain Boundaries**\n```python\n# Bad: Undefined for negative\nresult = math.sqrt(value)\n\n# Good: Validate domain\ndef safe_sqrt(value: float) -> float:\n    if value < 0:\n        raise ValueError(\"sqrt requires non-negative input\")\n    return math.sqrt(value)\n\n# Test edge cases\n@pytest.mark.parametrize(\"value\", [0, 1e-100, 1e100, float('inf')])\ndef test_sqrt_boundaries(value):\n    result = safe_sqrt(value)\n    assert result >= 0\n```\n\n**Special Values**\n- Zero\n- One\n- Infinity\n- NaN\n- Very small (underflow)\n- Very large (overflow)\n- Negative values\n- Empty inputs\n\n## Property-Based Testing\n\n**Hypothesis Framework**\n```python\nfrom hypothesis import given, strategies as st\n\n@given(st.floats(min_value=0, max_value=1e6))\ndef test_sqrt_inverse(x):\n    \"\"\"sqrt(x)² should equal x\"\"\"\n    result = safe_sqrt(x)\n    assert abs(result * result - x) < 1e-10 * x\n```\n\n**Invariant Testing**\n- Symmetry properties\n- Associativity/commutativity\n- Idempotence\n- Conservation laws\n- Monotonicity\n\n## Benchmark Testing\n\n**Performance Validation**\n```bash\npytest tests/math/ --benchmark-only\npytest tests/math/ --benchmark-compare=baseline\n```\n\n**Regression Detection**\n```python\ndef test_algorithm_performance(benchmark):\n    \"\"\"validate O(n log n) complexity maintained\"\"\"\n    n = 10000\n    data = np.random.rand(n)\n\n    result = benchmark(algorithm, data)\n\n    # Verify result correctness\n    assert len(result) == n\n    # Performance constraint\n    assert benchmark.stats['mean'] < 0.1  # seconds\n```\n\n**Complexity Verification**\n- Time scaling tests\n- Memory profiling\n- Cache behavior\n- Parallel efficiency\n\n## Reproducibility Testing\n\n**Deterministic Results**\n```python\ndef test_reproducibility():\n    \"\"\"Same seed produces same results\"\"\"\n    np.random.seed(42)\n    result1 = monte_carlo_simulation()\n\n    np.random.seed(42)\n    result2 = monte_carlo_simulation()\n\n    np.testing.assert_array_equal(result1, result2)\n```\n\n**Version Pinning**\n```toml\n# pyproject.toml\n[tool.poetry.dependencies]\nnumpy = \"==1.24.0\"  # Pin for reproducibility\nscipy = \"==1.10.0\"\n```\n\n## Reference Implementation Tests\n\n**Golden Master Testing**\n```python\ndef test_against_reference():\n    \"\"\"Compare with NumPy/SciPy reference\"\"\"\n    x = np.linspace(0, 10, 100)\n\n    our_result = our_implementation(x)\n    reference_result = scipy.special.reference_function(x)\n\n    np.testing.assert_allclose(\n        our_result,\n        reference_result,\n        rtol=1e-10,\n        atol=1e-12\n    )\n```\n\n**Cross-Validation**\n- Multiple independent implementations\n- Different algorithms\n- Analytical solutions (when available)\n- Published test cases\n\n## Numerical Accuracy Tests\n\n**Tolerance Specifications**\n```python\n# Absolute tolerance\nnp.testing.assert_allclose(result, expected, atol=1e-10)\n\n# Relative tolerance\nnp.testing.assert_allclose(result, expected, rtol=1e-8)\n\n# Both\nnp.testing.assert_allclose(\n    result, expected,\n    rtol=1e-8, atol=1e-10\n)\n```\n\n**ULP (Units in Last Place) Testing**\n```python\n# For critical floating-point comparisons\nassert abs(a - b) <= 2 * np.finfo(float).eps * max(abs(a), abs(b))\n```\n\n## Evidence Logging\n\n**Execution Records**\n```bash\n# Run tests with output capture\npytest tests/math/ -v --tb=short > test_results.txt\n\n# Benchmark with JSON output\npytest tests/math/ --benchmark-json=benchmark.json\n\n# Execute derivation notebooks\njupyter nbconvert --execute derivation.ipynb \\\n    --to html --output verification.html\n```\n\n**Documentation Template**\n```markdown\n## Test Evidence\n\n### Unit Tests\n- **Command**: `pytest tests/math/ -v`\n- **Result**: 47/47 passed\n- **Coverage**: 94%\n- **Date**: 2025-12-06\n\n### Benchmarks\n- **Command**: `pytest tests/math/ --benchmark-only`\n- **Mean time**: 23.4ms (±1.2ms)\n- **Baseline**: 24.1ms\n- **Improvement**: 3%\n\n### Derivation Verification\n- **Notebook**: derivation.ipynb\n- **Status**: All cells executed successfully\n- **Symbolic checks**: Passed\n- **Reference comparison**: Within tolerance\n```\n\n## Test Organization\n\n```\ntests/math/\n├── test_correctness.py       # Basic functionality\n├── test_edge_cases.py        # Boundary conditions\n├── test_properties.py        # Hypothesis tests\n├── test_benchmarks.py        # Performance\n├── test_stability.py         # Numerical stability\n├── test_references.py        # Golden masters\n└── fixtures/\n    ├── test_data.npz\n    └── reference_results.json\n```\n\n## Testing Checklist\n\n- [ ] Edge cases covered (0, ±∞, NaN)\n- [ ] Property tests for invariants\n- [ ] Benchmark tests for performance\n- [ ] Reproducibility verified\n- [ ] Reference implementation compared\n- [ ] Tolerances documented\n- [ ] Evidence logged and dated\n- [ ] Coverage > 90% for math code\n\nFile v1.9.14:skill-card.md\n\n## Description: <br>\nVerifies math-heavy code for algorithmic correctness and numerical stability. <br>\n\nThis skill is ready for commercial/non-commercial use. <br>\n\n## Publisher: <br>\n[athola](https://clawhub.ai/user/athola) <br>\n\n### License/Terms of Use: <br>\nMIT-0 <br>\n\n\n## Use Case: <br>\nDevelopers and engineers use this skill to review math-heavy code changes, map requirements to mathematical invariants, verify derivations, assess numerical stability, and document testing evidence. <br>\n\n### Deployment Geography for Use: <br>\nGlobal <br>\n\n## Known Risks and Mitigations: <br>\nRisk: The skill may lead an agent to run local tests or execute a Jupyter notebook. <br>\nMitigation: Use it only in trusted repositories, review notebooks before execution, and prefer explicit invocation for math-heavy code review. <br>\nRisk: Incorrect mathematical or numerical guidance could affect high-stakes calculations. <br>\nMitigation: Require human review by a domain owner and preserve cited evidence for derivations, stability claims, and test results. <br>\n\n\n## Reference(s): <br>\n- [ClawHub skill page](https://clawhub.ai/athola/skills/nm-pensive-math-review) <br>\n- [Pensive plugin homepage](https://github.com/athola/claude-night-market/tree/master/plugins/pensive) <br>\n- [Requirements mapping module](modules/requirements-mapping.md) <br>\n- [Derivation verification module](modules/derivation-verification.md) <br>\n- [Numerical stability module](modules/numerical-stability.md) <br>\n- [Testing strategies module](modules/testing-strategies.md) <br>\n\n\n## Skill Output: <br>\n**Output Type(s):** [text, markdown, shell commands, guidance] <br>\n**Output Format:** [Markdown review findings with tables and inline shell commands] <br>\n**Output Parameters:** [1D] <br>\n**Other Properties Related to Output:** [May include issue lists, recommendations, citations, and evidence from local validation.] <br>\n\n## Skill Version(s): <br>\n1.9.14 (source: server release metadata) <br>\n\n## Ethical Considerations: <br>\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment. <br>\n\nArchive v1.9.13: 7 files, 11032 bytes\n\nFiles: modules/derivation-verification.md (3255b), modules/numerical-stability.md (2650b), modules/requirements-mapping.md (3561b), modules/testing-strategies.md (4867b), skill-card.md (2147b), SKILL.md (5126b), _meta.json (142b)\n\nFile v1.9.13:SKILL.md\n\n---\nname: math-review\ndescription: Verifies math-heavy code for algorithmic correctness and numerical stability\nversion: 1.9.8\ntriggers:\n  - math\n  - algorithms\n  - numerical\n  - stability\n  - verification\n  - scientific\n  - reviewing scientific algorithms\n  - ML models\n  - or numerical code\nmetadata: {\"openclaw\": {\"homepage\": \"https://github.com/athola/claude-night-market/tree/master/plugins/pensive\", \"emoji\": \"\\ud83e\\udd9e\", \"requires\": {\"config\": [\"night-market.pensive:shared\", \"night-market.imbue:proof-of-work\"]}}}\nsource: claude-night-market\nsource_plugin: pensive\n---\n\n> **Night Market Skill** — ported from [claude-night-market/pensive](https://github.com/athola/claude-night-market/tree/master/plugins/pensive). For the full experience with agents, hooks, and commands, install the Claude Code plugin.\n\n\n## Table of Contents\n\n- [Quick Start](#quick-start)\n- [When to Use](#when-to-use)\n- [Required TodoWrite Items](#required-todowrite-items)\n- [Core Workflow](#core-workflow)\n- [1. Context Sync](#1-context-sync)\n- [2. Requirements Mapping](#2-requirements-mapping)\n- [3. Derivation Verification](#3-derivation-verification)\n- [4. Stability Assessment](#4-stability-assessment)\n- [5. Proof of Work](#5-proof-of-work)\n- [Progressive Loading](#progressive-loading)\n- [Essential Checklist](#essential-checklist)\n- [Output Format](#output-format)\n- [Summary](#summary)\n- [Context](#context)\n- [Requirements Analysis](#requirements-analysis)\n- [Derivation Review](#derivation-review)\n- [Stability Analysis](#stability-analysis)\n- [Issues](#issues)\n- [Recommendation](#recommendation)\n- [Exit Criteria](#exit-criteria)\n\n\n# Mathematical Algorithm Review\n\nIntensive analysis ensuring numerical stability and alignment with standards.\n\n## Quick Start\n\n```bash\n/math-review\n```\n**Verification:** Run the command with `--help` flag to verify availability.\n\n## When To Use\n\n- Changes to mathematical models or algorithms\n- Statistical routines or probabilistic logic\n- Numerical integration or optimization\n- Scientific computing code\n- ML/AI model implementations\n- Safety-critical calculations\n\n## When NOT To Use\n\n- General algorithm review -\n  use architecture-review\n- Performance optimization - use parseltongue:python-performance\n- General algorithm review -\n  use architecture-review\n- Performance optimization - use parseltongue:python-performance\n\n## Required TodoWrite Items\n\n1. `math-review:context-synced`\n2. `math-review:requirements-mapped`\n3. `math-review:derivations-verified`\n4. `math-review:stability-assessed`\n5. `math-review:evidence-logged`\n\n## Core Workflow\n\n### 1. Context Sync\n```bash\npwd && git status -sb && git diff --stat origin/main..HEAD\n```\n**Verification:** Run `git status` to confirm working tree state.\nEnumerate math-heavy files (source, tests, docs, notebooks). Classify risk: safety-critical, financial, ML fairness.\n\n### 2. Requirements Mapping\nTranslate requirements → mathematical invariants. Document pre/post conditions, conservation laws, bounds. **Load**: `modules/requirements-mapping.md`\n\n### 3. Derivation Verification\nRe-derive formulas using CAS. Challenge approximations. Cite authoritative standards (NASA-STD-7009, ASME VVUQ). **Load**: `modules/derivation-verification.md`\n\n### 4. Stability Assessment\nEvaluate conditioning, precision, scaling, randomness. Compare complexity. Quantify uncertainty. **Load**: `modules/numerical-stability.md`\n\n### 5. Proof of Work\n```bash\npytest tests/math/ --benchmark\njupyter nbconvert --execute derivation.ipynb\n```\n**Verification:** Run `pytest -v tests/math/` to verify.\nLog deviations, recommend: Approve / Approve with actions / Block. **Load**: `modules/testing-strategies.md`\n\n## Progressive Loading\n\n**Default (200 tokens)**: Core workflow, checklists\n**+Requirements** (+300 tokens): Invariants, pre/post conditions, coverage analysis\n**+Derivation** (+350 tokens): CAS verification, standards, citations\n**+Stability** (+400 tokens): Numerical properties, precision, complexity\n**+Testing** (+350 tokens): Edge cases, benchmarks, reproducibility\n\n**Total with all modules**: ~1600 tokens\n\n## Essential Checklist\n\n**Correctness**: Formulas match spec | Edge cases handled | Units consistent | Domain enforced\n**Stability**: Condition number OK | Precision sufficient | No cancellation | Overflow prevented\n**Verification**: Derivations documented | References cited | Tests cover invariants | Benchmarks reproducible\n**Documentation**: Assumptions stated | Limitations documented | Error bounds specified | References linked\n\n## Output Format\n\n```markdown\n## Summary\n[Brief findings]\n\n## Context\nFiles | Risk classification | Standards\n\n## Requirements Analysis\n| Invariant | Verified | Evidence |\n\n## Derivation Review\n[Status and conflicts]\n\n## Stability Analysis\nCondition number | Precision | Risks\n\n## Issues\n[M1] [Title]: Location | Issue | Fix\n\n## Recommendation\nApprove / Approve with actions / Block\n```\n**Verification:** Run the command with `--help` flag to verify availability.\n\n## Exit Criteria\n\n- Context synced, requirements mapped, derivations verified, stability assessed, evidence logged with citations\n\nFile v1.9.13:_meta.json\n\n{\n  \"ownerId\": \"kn7d107jg9jv602h9ytsegydq184a42s\",\n  \"slug\": \"nm-pensive-math-review\",\n  \"version\": \"1.9.13\",\n  \"publishedAt\": 1782577335615\n}\n\nFile v1.9.13:modules/derivation-verification.md\n\n---\nparent_skill: pensive:math-review\nload_priority: high\nestimated_tokens: 350\n---\n\n# Derivation Verification\n\n## Re-derive Critical Formulas\n\n**Symbolic Verification**\n- Use Computer Algebra Systems (SymPy, Mathematica, Maple)\n- Confirm algebraic manipulations\n- Verify calculus operations (derivatives, integrals)\n- Check limit behavior\n\n**Computational Notebooks**\n```python\n# Example: Verify gradient computation\nimport sympy as sp\nx, y = sp.symbols('x y')\nf = x**2 + y**2\ngrad_f = [sp.diff(f, var) for var in [x, y]]\n# Compare with implementation\n```\n\n**Probabilistic Reasoning**\n- Verify conditional probability formulas\n- Check Bayes rule applications\n- Confirm expectation/variance calculations\n- Validate distribution properties\n\n## Challenge Approximations\n\n**Series Truncation**\n- Document truncation order (e.g., O(h³))\n- Estimate truncation error\n- Test convergence with different orders\n- Provide error bounds across domain\n\n**Linearizations**\n- Identify linearization points\n- Estimate valid domain size\n- Test against full nonlinear model\n- Document approximation quality\n\n**Surrogate Models**\n- Compare surrogate to ground truth\n- Quantify approximation error\n- Document training/validation data\n- Test extrapolation behavior\n\n**Error Bounds**\n- Derive theoretical error bounds\n- Verify empirically\n- Document worst-case scenarios\n- Test at domain boundaries\n\n## Authoritative References\n\n**Standards and Frameworks**\n- **NASA-STD-7009**: Modeling and Simulation V&V\n- **ASME V&V 20**: Verification & Validation in CFD/HT\n- **ASME V&V 10**: Guide for V&V in Computational Solid Mechanics\n- **SIAM**: Reproducibility checklists\n- **IEEE 754**: Floating-point arithmetic\n- **NIST**: Uncertainty quantification guidelines\n\n**Academic Sources**\n- Peer-reviewed papers (DOI links)\n- Textbooks (edition and page numbers)\n- Technical reports\n- Conference proceedings\n\n**Implementation References**\n- Reference implementations (NumPy, SciPy, GSL)\n- Algorithm papers (original sources)\n- Numerical recipes\n- Domain-specific libraries\n\n## Document Conflicts\n\nWhen implementation deviates from standards:\n\n```markdown\n### Deviation: [Brief title]\n- **Standard**: NASA-STD-7009 Section 3.4.2\n- **Requirement**: Monte Carlo with n≥1000 samples\n- **Implementation**: n=100 samples\n- **Justification**: Performance constraints\n- **Risk**: Reduced confidence intervals\n- **Mitigation**: Document uncertainty, flag results\n- **Owner**: [name]\n- **Due date**: [date]\n```\n\n## Citation Format\n\n```markdown\n## References\n\n[1] Wilkinson, J.H. (1963). *Rounding Errors in Algebraic Processes*.\n    Prentice-Hall. Chapter 3.\n\n[2] NASA-STD-7009A. (2016). *Standard for Models and Simulations*.\n    Section 4.2: Verification Requirements.\n\n[3] Goldberg, D. (1991). \"What Every Computer Scientist Should Know\n    About Floating-Point Arithmetic\". *ACM Computing Surveys*, 23(1).\n    DOI: 10.1145/103162.103163\n```\n\n## Verification Checklist\n\n- [ ] Formulas re-derived from first principles\n- [ ] Symbolic verification completed (CAS)\n- [ ] Approximation order documented\n- [ ] Error bounds derived and tested\n- [ ] Authoritative references cited\n- [ ] Deviations from standards documented\n- [ ] Conflicts resolved or flagged\n- [ ] Implementation matches theory\n\nFile v1.9.13:modules/numerical-stability.md\n\n---\nparent_skill: pensive:math-review\nload_priority: high\nestimated_tokens: 400\n---\n\n# Numerical Stability Analysis\n\n## Conditioning\n\n**Condition Numbers**\n- Measure sensitivity to input perturbations\n- High condition number = unstable computation\n- Use scaled condition numbers when possible\n\n**Sensitivity Analysis**\n- Perturb inputs systematically\n- Measure output variation\n- Document acceptable tolerance ranges\n\n## Precision Management\n\n**Floating-Point Error Propagation**\n```python\n# Bad: Accumulating small values into large\ntotal = 1e15\nfor x in small_values:\n    total += x  # Precision lost\n\n# Good: Kahan summation or sort first\nsorted_values = sorted(small_values)\ntotal = sum(sorted_values)  # Better precision\n```\n\n**Catastrophic Cancellation**\n```python\n# Bad: Subtracting similar values\nresult = (a + epsilon) - a  # Catastrophic cancellation\n\n# Good: Reformulate to avoid\nresult = epsilon  # Direct computation\n```\n\n**Overflow/Underflow Prevention**\n- Check dynamic range before operations\n- Use log-space for very large/small products\n- Normalize intermediate results\n- Scale inputs to manageable ranges\n\n## Scaling and Normalization\n\n**Dynamic Range Handling**\n- Pre-scale inputs to [0, 1] or [-1, 1]\n- Use log-transforms for exponential data\n- Document scaling factors and units\n\n**Normalization Requirements**\n- L1/L2 normalization for vectors\n- Feature scaling for ML inputs\n- Unit conversions for physical quantities\n\n## Randomness Control\n\n**Reproducibility**\n- Set explicit random seeds\n- Document PRNG algorithms used\n- Version lock numerical libraries\n- Test deterministic behavior\n\n**Seed Management**\n```python\n# Good: Explicit seed control\nimport numpy as np\nnp.random.seed(42)\n\n# Better: Isolated RNG state\nrng = np.random.RandomState(42)\nsamples = rng.normal(0, 1, size=100)\n```\n\n## Complexity Analysis\n\nCompare algorithmic complexity before/after changes:\n\n```\nBefore: O(n²) time, O(n) space\nAfter:  O(n log n) time, O(n) space\nImprovement: 100x faster for n=1000\n```\n\nDocument:\n- Time complexity\n- Space complexity\n- Cache behavior\n- Parallelization potential\n\n## Uncertainty Quantification\n\nRequired for:\n- Safety-critical systems\n- Data-driven components\n- High-stakes decisions\n- Regulatory compliance\n\nMethods:\n- Monte Carlo sampling\n- Bootstrap confidence intervals\n- Sensitivity analysis\n- Error propagation formulas\n\n## Stability Checklist\n\n- [ ] Condition number < 1e6\n- [ ] Precision loss < 1e-10\n- [ ] No catastrophic cancellation\n- [ ] Overflow/underflow prevented\n- [ ] Scaling applied appropriately\n- [ ] Random seeds controlled\n- [ ] Complexity acceptable\n- [ ] Uncertainty quantified (if required)\n\nFile v1.9.13:modules/requirements-mapping.md\n\n---\nparent_skill: pensive:math-review\nload_priority: medium\nestimated_tokens: 300\n---\n\n# Requirements Mapping\n\n## Mathematical Invariants\n\nTranslate requirements into verifiable mathematical properties:\n\n| Requirement | Invariant | Test Coverage |\n|-------------|-----------|---------------|\n| Positive output | f(x) > 0 ∀ x ∈ domain | Property test |\n| Conservation | Σ mass_in = Σ mass_out | Unit test |\n| Bounded error | \\|ε\\| < 1e-6 | Benchmark |\n| Monotonicity | x₁ < x₂ ⟹ f(x₁) ≤ f(x₂) | Property test |\n| Idempotence | f(f(x)) = f(x) | Unit test |\n\n## Pre-conditions\n\n**Input Validation**\n```python\ndef compute(x: float, n: int) -> float:\n    \"\"\"Compute function with documented preconditions.\n\n    Preconditions:\n    - x ≥ 0 (non-negative input)\n    - n > 0 (positive integer)\n    - x < 1e10 (prevent overflow)\n    \"\"\"\n    if x < 0:\n        raise ValueError(\"x must be non-negative\")\n    if n <= 0:\n        raise ValueError(\"n must be positive\")\n    if x >= 1e10:\n        raise ValueError(\"x must be < 1e10\")\n    # ... implementation\n```\n\n**Domain Constraints**\n- Valid input ranges\n- Type requirements\n- Dimensional consistency\n- Unit compatibility\n\n## Post-conditions\n\n**Output Guarantees**\n```python\ndef normalize(vector: np.ndarray) -> np.ndarray:\n    \"\"\"Normalize vector to unit length.\n\n    Postconditions:\n    - ||result|| = 1.0 (± 1e-10)\n    - result ∥ vector (parallel)\n    \"\"\"\n    result = vector / np.linalg.norm(vector)\n    assert abs(np.linalg.norm(result) - 1.0) < 1e-10\n    return result\n```\n\n**Invariant Preservation**\n- Conservation laws maintained\n- Bounds respected\n- Relationships preserved\n\n## Conservation Laws\n\n**Physical Conservation**\n- Mass conservation\n- Energy conservation\n- Momentum conservation\n- Charge conservation\n\n**Numerical Conservation**\n- Probability sums to 1.0\n- Symmetry preservation\n- Balance equations\n\n## Monotonicity Guarantees\n\n**Increasing Functions**\n```python\n# Property test\n@given(st.floats(min_value=0, max_value=100))\ndef test_monotonic_increasing(x1, x2):\n    assume(x1 < x2)\n    assert f(x1) <= f(x2)\n```\n\n**Convexity/Concavity**\n- Second derivative tests\n- Jensen's inequality\n- Midpoint properties\n\n## Probabilistic Bounds\n\n**Confidence Intervals**\n- Document confidence levels (95%, 99%)\n- Specify interval type (credible, confidence)\n- Test coverage probabilities\n\n**Error Probabilities**\n- Type I/II error rates\n- False positive/negative rates\n- Statistical power\n\n## Coverage Gap Analysis\n\nIdentify untested invariants:\n\n```markdown\n### Coverage Gaps\n\n**Missing Tests**\n- [ ] Boundary condition: x = 0\n- [ ] Overflow case: x > 1e15\n- [ ] Negative input handling\n- [ ] Conservation at t → ∞\n\n**Insufficient Coverage**\n- [ ] Only 3 test cases for n-dimensional invariant\n- [ ] No property tests for monotonicity\n- [ ] Missing edge case: empty input\n```\n\n## Documentation Template\n\n```python\ndef algorithm(inputs) -> outputs:\n    \"\"\"Brief description.\n\n    Mathematical Properties:\n    - Preconditions: [domain constraints]\n    - Postconditions: [guaranteed properties]\n    - Invariants: [preserved relationships]\n    - Complexity: [time/space bounds]\n    - Stability: [condition number, error bounds]\n\n    References:\n    - [Citation to algorithm source]\n    \"\"\"\n```\n\n## Mapping Checklist\n\n- [ ] Requirements translated to invariants\n- [ ] Pre-conditions documented\n- [ ] Post-conditions verified\n- [ ] Conservation laws tested\n- [ ] Monotonicity/convexity checked\n- [ ] Probabilistic bounds specified\n- [ ] Coverage gaps identified\n- [ ] All properties have tests\n\nFile v1.9.13:modules/testing-strategies.md\n\n---\nparent_skill: pensive:math-review\nload_priority: medium\nestimated_tokens: 350\n---\n\n# Testing Strategies for Mathematical Code\n\n## Edge Case Coverage\n\n**Domain Boundaries**\n```python\n# Bad: Undefined for negative\nresult = math.sqrt(value)\n\n# Good: Validate domain\ndef safe_sqrt(value: float) -> float:\n    if value < 0:\n        raise ValueError(\"sqrt requires non-negative input\")\n    return math.sqrt(value)\n\n# Test edge cases\n@pytest.mark.parametrize(\"value\", [0, 1e-100, 1e100, float('inf')])\ndef test_sqrt_boundaries(value):\n    result = safe_sqrt(value)\n    assert result >= 0\n```\n\n**Special Values**\n- Zero\n- One\n- Infinity\n- NaN\n- Very small (underflow)\n- Very large (overflow)\n- Negative values\n- Empty inputs\n\n## Property-Based Testing\n\n**Hypothesis Framework**\n```python\nfrom hypothesis import given, strategies as st\n\n@given(st.floats(min_value=0, max_value=1e6))\ndef test_sqrt_inverse(x):\n    \"\"\"sqrt(x)² should equal x\"\"\"\n    result = safe_sqrt(x)\n    assert abs(result * result - x) < 1e-10 * x\n```\n\n**Invariant Testing**\n- Symmetry properties\n- Associativity/commutativity\n- Idempotence\n- Conservation laws\n- Monotonicity\n\n## Benchmark Testing\n\n**Performance Validation**\n```bash\npytest tests/math/ --benchmark-only\npytest tests/math/ --benchmark-compare=baseline\n```\n\n**Regression Detection**\n```python\ndef test_algorithm_performance(benchmark):\n    \"\"\"validate O(n log n) complexity maintained\"\"\"\n    n = 10000\n    data = np.random.rand(n)\n\n    result = benchmark(algorithm, data)\n\n    # Verify result correctness\n    assert len(result) == n\n    # Performance constraint\n    assert benchmark.stats['mean'] < 0.1  # seconds\n```\n\n**Complexity Verification**\n- Time scaling tests\n- Memory profiling\n- Cache behavior\n- Parallel efficiency\n\n## Reproducibility Testing\n\n**Deterministic Results**\n```python\ndef test_reproducibility():\n    \"\"\"Same seed produces same results\"\"\"\n    np.random.seed(42)\n    result1 = monte_carlo_simulation()\n\n    np.random.seed(42)\n    result2 = monte_carlo_simulation()\n\n    np.testing.assert_array_equal(result1, result2)\n```\n\n**Version Pinning**\n```toml\n# pyproject.toml\n[tool.poetry.dependencies]\nnumpy = \"==1.24.0\"  # Pin for reproducibility\nscipy = \"==1.10.0\"\n```\n\n## Reference Implementation Tests\n\n**Golden Master Testing**\n```python\ndef test_against_reference():\n    \"\"\"Compare with NumPy/SciPy reference\"\"\"\n    x = np.linspace(0, 10, 100)\n\n    our_result = our_implementation(x)\n    reference_result = scipy.special.reference_function(x)\n\n    np.testing.assert_allclose(\n        our_result,\n        reference_result,\n        rtol=1e-10,\n        atol=1e-12\n    )\n```\n\n**Cross-Validation**\n- Multiple independent implementations\n- Different algorithms\n- Analytical solutions (when available)\n- Published test cases\n\n## Numerical Accuracy Tests\n\n**Tolerance Specifications**\n```python\n# Absolute tolerance\nnp.testing.assert_allclose(result, expected, atol=1e-10)\n\n# Relative tolerance\nnp.testing.assert_allclose(result, expected, rtol=1e-8)\n\n# Both\nnp.testing.assert_allclose(\n    result, expected,\n    rtol=1e-8, atol=1e-10\n)\n```\n\n**ULP (Units in Last Place) Testing**\n```python\n# For critical floating-point comparisons\nassert abs(a - b) <= 2 * np.finfo(float).eps * max(abs(a), abs(b))\n```\n\n## Evidence Logging\n\n**Execution Records**\n```bash\n# Run tests with output capture\npytest tests/math/ -v --tb=short > test_results.txt\n\n# Benchmark with JSON output\npytest tests/math/ --benchmark-json=benchmark.json\n\n# Execute derivation notebooks\njupyter nbconvert --execute derivation.ipynb \\\n    --to html --output verification.html\n```\n\n**Documentation Template**\n```markdown\n## Test Evidence\n\n### Unit Tests\n- **Command**: `pytest tests/math/ -v`\n- **Result**: 47/47 passed\n- **Coverage**: 94%\n- **Date**: 2025-12-06\n\n### Benchmarks\n- **Command**: `pytest tests/math/ --benchmark-only`\n- **Mean time**: 23.4ms (±1.2ms)\n- **Baseline**: 24.1ms\n- **Improvement**: 3%\n\n### Derivation Verification\n- **Notebook**: derivation.ipynb\n- **Status**: All cells executed successfully\n- **Symbolic checks**: Passed\n- **Reference comparison**: Within tolerance\n```\n\n## Test Organization\n\n```\ntests/math/\n├── test_correctness.py       # Basic functionality\n├── test_edge_cases.py        # Boundary conditions\n├── test_properties.py        # Hypothesis tests\n├── test_benchmarks.py        # Performance\n├── test_stability.py         # Numerical stability\n├── test_references.py        # Golden masters\n└── fixtures/\n    ├── test_data.npz\n    └── reference_results.json\n```\n\n## Testing Checklist\n\n- [ ] Edge cases covered (0, ±∞, NaN)\n- [ ] Property tests for invariants\n- [ ] Benchmark tests for performance\n- [ ] Reproducibility verified\n- [ ] Reference implementation compared\n- [ ] Tolerances documented\n- [ ] Evidence logged and dated\n- [ ] Coverage > 90% for math code\n\nFile v1.9.13:skill-card.md\n\n## Description: <br>\nVerifies math-heavy code for algorithmic correctness and numerical stability. <br>\n\nThis skill is ready for commercial/non-commercial use. <br>\n\n## Publisher: <br>\n[athola](https://clawhub.ai/user/athola) <br>\n\n### License/Terms of Use: <br>\nMIT-0 <br>\n\n\n## Use Case: <br>\nDevelopers and engineers use this skill to review mathematical, scientific, statistical, numerical, and ML code for correctness, stability, reproducibility, and standards alignment. <br>\n\n### Deployment Geography for Use: <br>\nGlobal <br>\n\n## Known Risks and Mitigations: <br>\nRisk: The skill may ask an agent to run tests, benchmarks, or notebooks from an unfamiliar repository. <br>\nMitigation: Run those commands only in a sandboxed environment after reviewing the tests, benchmark setup, and notebooks. <br>\nRisk: Mathematical review output can be incomplete or wrong if source requirements, formulas, or standards are missing. <br>\nMitigation: Require cited evidence, documented assumptions, and human review before relying on the recommendation for safety-critical, financial, or regulatory decisions. <br>\n\n\n## Reference(s): <br>\n- [ClawHub skill page](https://clawhub.ai/athola/skills/nm-pensive-math-review) <br>\n- [Pensive plugin homepage](https://github.com/athola/claude-night-market/tree/master/plugins/pensive) <br>\n\n\n## Skill Output: <br>\n**Output Type(s):** [Analysis, Markdown, Shell commands, Guidance] <br>\n**Output Format:** [Markdown review with summary, context, requirements analysis, derivation review, stability analysis, issue entries, and a recommendation.] <br>\n**Output Parameters:** [1D] <br>\n**Other Properties Related to Output:** [May include verification commands and a recommendation of Approve, Approve with actions, or Block.] <br>\n\n## Skill Version(s): <br>\n1.9.13 (source: ClawHub release evidence; artifact frontmatter lists 1.9.8) <br>\n\n## Ethical Considerations: <br>\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment. <br>\n\nArchive v1.9.12: 7 files, 11124 bytes\n\nFiles: modules/derivation-verification.md (3255b), modules/numerical-stability.md (2650b), modules/requirements-mapping.md (3561b), modules/testing-strategies.md (4867b), skill-card.md (2465b), SKILL.md (5126b), _meta.json (142b)\n\nFile v1.9.12:SKILL.md\n\n---\nname: math-review\ndescription: Verifies math-heavy code for algorithmic correctness and numerical stability\nversion: 1.9.8\ntriggers:\n  - math\n  - algorithms\n  - numerical\n  - stability\n  - verification\n  - scientific\n  - reviewing scientific algorithms\n  - ML models\n  - or numerical code\nmetadata: {\"openclaw\": {\"homepage\": \"https://github.com/athola/claude-night-market/tree/master/plugins/pensive\", \"emoji\": \"\\ud83e\\udd9e\", \"requires\": {\"config\": [\"night-market.pensive:shared\", \"night-market.imbue:proof-of-work\"]}}}\nsource: claude-night-market\nsource_plugin: pensive\n---\n\n> **Night Market Skill** — ported from [claude-night-market/pensive](https://github.com/athola/claude-night-market/tree/master/plugins/pensive). For the full experience with agents, hooks, and commands, install the Claude Code plugin.\n\n\n## Table of Contents\n\n- [Quick Start](#quick-start)\n- [When to Use](#when-to-use)\n- [Required TodoWrite Items](#required-todowrite-items)\n- [Core Workflow](#core-workflow)\n- [1. Context Sync](#1-context-sync)\n- [2. Requirements Mapping](#2-requirements-mapping)\n- [3. Derivation Verification](#3-derivation-verification)\n- [4. Stability Assessment](#4-stability-assessment)\n- [5. Proof of Work](#5-proof-of-work)\n- [Progressive Loading](#progressive-loading)\n- [Essential Checklist](#essential-checklist)\n- [Output Format](#output-format)\n- [Summary](#summary)\n- [Context](#context)\n- [Requirements Analysis](#requirements-analysis)\n- [Derivation Review](#derivation-review)\n- [Stability Analysis](#stability-analysis)\n- [Issues](#issues)\n- [Recommendation](#recommendation)\n- [Exit Criteria](#exit-criteria)\n\n\n# Mathematical Algorithm Review\n\nIntensive analysis ensuring numerical stability and alignment with standards.\n\n## Quick Start\n\n```bash\n/math-review\n```\n**Verification:** Run the command with `--help` flag to verify availability.\n\n## When To Use\n\n- Changes to mathematical models or algorithms\n- Statistical routines or probabilistic logic\n- Numerical integration or optimization\n- Scientific computing code\n- ML/AI model implementations\n- Safety-critical calculations\n\n## When NOT To Use\n\n- General algorithm review -\n  use architecture-review\n- Performance optimization - use parseltongue:python-performance\n- General algorithm review -\n  use architecture-review\n- Performance optimization - use parseltongue:python-performance\n\n## Required TodoWrite Items\n\n1. `math-review:context-synced`\n2. `math-review:requirements-mapped`\n3. `math-review:derivations-verified`\n4. `math-review:stability-assessed`\n5. `math-review:evidence-logged`\n\n## Core Workflow\n\n### 1. Context Sync\n```bash\npwd && git status -sb && git diff --stat origin/main..HEAD\n```\n**Verification:** Run `git status` to confirm working tree state.\nEnumerate math-heavy files (source, tests, docs, notebooks). Classify risk: safety-critical, financial, ML fairness.\n\n### 2. Requirements Mapping\nTranslate requirements → mathematical invariants. Document pre/post conditions, conservation laws, bounds. **Load**: `modules/requirements-mapping.md`\n\n### 3. Derivation Verification\nRe-derive formulas using CAS. Challenge approximations. Cite authoritative standards (NASA-STD-7009, ASME VVUQ). **Load**: `modules/derivation-verification.md`\n\n### 4. Stability Assessment\nEvaluate conditioning, precision, scaling, randomness. Compare complexity. Quantify uncertainty. **Load**: `modules/numerical-stability.md`\n\n### 5. Proof of Work\n```bash\npytest tests/math/ --benchmark\njupyter nbconvert --execute derivation.ipynb\n```\n**Verification:** Run `pytest -v tests/math/` to verify.\nLog deviations, recommend: Approve / Approve with actions / Block. **Load**: `modules/testing-strategies.md`\n\n## Progressive Loading\n\n**Default (200 tokens)**: Core workflow, checklists\n**+Requirements** (+300 tokens): Invariants, pre/post conditions, coverage analysis\n**+Derivation** (+350 tokens): CAS verification, standards, citations\n**+Stability** (+400 tokens): Numerical properties, precision, complexity\n**+Testing** (+350 tokens): Edge cases, benchmarks, reproducibility\n\n**Total with all modules**: ~1600 tokens\n\n## Essential Checklist\n\n**Correctness**: Formulas match spec | Edge cases handled | Units consistent | Domain enforced\n**Stability**: Condition number OK | Precision sufficient | No cancellation | Overflow prevented\n**Verification**: Derivations documented | References cited | Tests cover invariants | Benchmarks reproducible\n**Documentation**: Assumptions stated | Limitations documented | Error bounds specified | References linked\n\n## Output Format\n\n```markdown\n## Summary\n[Brief findings]\n\n## Context\nFiles | Risk classification | Standards\n\n## Requirements Analysis\n| Invariant | Verified | Evidence |\n\n## Derivation Review\n[Status and conflicts]\n\n## Stability Analysis\nCondition number | Precision | Risks\n\n## Issues\n[M1] [Title]: Location | Issue | Fix\n\n## Recommendation\nApprove / Approve with actions / Block\n```\n**Verification:** Run the command with `--help` flag to verify availability.\n\n## Exit Criteria\n\n- Context synced, requirements mapped, derivations verified, stability assessed, evidence logged with citations\n\nFile v1.9.12:_meta.json\n\n{\n  \"ownerId\": \"kn7d107jg9jv602h9ytsegydq184a42s\",\n  \"slug\": \"nm-pensive-math-review\",\n  \"version\": \"1.9.12\",\n  \"publishedAt\": 1781839044786\n}\n\nFile v1.9.12:modules/derivation-verification.md\n\n---\nparent_skill: pensive:math-review\nload_priority: high\nestimated_tokens: 350\n---\n\n# Derivation Verification\n\n## Re-derive Critical Formulas\n\n**Symbolic Verification**\n- Use Computer Algebra Systems (SymPy, Mathematica, Maple)\n- Confirm algebraic manipulations\n- Verify calculus operations (derivatives, integrals)\n- Check limit behavior\n\n**Computational Notebooks**\n```python\n# Example: Verify gradient computation\nimport sympy as sp\nx, y = sp.symbols('x y')\nf = x**2 + y**2\ngrad_f = [sp.diff(f, var) for var in [x, y]]\n# Compare with implementation\n```\n\n**Probabilistic Reasoning**\n- Verify conditional probability formulas\n- Check Bayes rule applications\n- Confirm expectation/variance calculations\n- Validate distribution properties\n\n## Challenge Approximations\n\n**Series Truncation**\n- Document truncation order (e.g., O(h³))\n- Estimate truncation error\n- Test convergence with different orders\n- Provide error bounds across domain\n\n**Linearizations**\n- Identify linearization points\n- Estimate valid domain size\n- Test against full nonlinear model\n- Document approximation quality\n\n**Surrogate Models**\n- Compare surrogate to ground truth\n- Quantify approximation error\n- Document training/validation data\n- Test extrapolation behavior\n\n**Error Bounds**\n- Derive theoretical error bounds\n- Verify empirically\n- Document worst-case scenarios\n- Test at domain boundaries\n\n## Authoritative References\n\n**Standards and Frameworks**\n- **NASA-STD-7009**: Modeling and Simulation V&V\n- **ASME V&V 20**: Verification & Validation in CFD/HT\n- **ASME V&V 10**: Guide for V&V in Computational Solid Mechanics\n- **SIAM**: Reproducibility checklists\n- **IEEE 754**: Floating-point arithmetic\n- **NIST**: Uncertainty quantification guidelines\n\n**Academic Sources**\n- Peer-reviewed papers (DOI links)\n- Textbooks (edition and page numbers)\n- Technical reports\n- Conference proceedings\n\n**Implementation References**\n- Reference implementations (NumPy, SciPy, GSL)\n- Algorithm papers (original sources)\n- Numerical recipes\n- Domain-specific libraries\n\n## Document Conflicts\n\nWhen implementation deviates from standards:\n\n```markdown\n### Deviation: [Brief title]\n- **Standard**: NASA-STD-7009 Section 3.4.2\n- **Requirement**: Monte Carlo with n≥1000 samples\n- **Implementation**: n=100 samples\n- **Justification**: Performance constraints\n- **Risk**: Reduced confidence intervals\n- **Mitigation**: Document uncertainty, flag results\n- **Owner**: [name]\n- **Due date**: [date]\n```\n\n## Citation Format\n\n```markdown\n## References\n\n[1] Wilkinson, J.H. (1963). *Rounding Errors in Algebraic Processes*.\n    Prentice-Hall. Chapter 3.\n\n[2] NASA-STD-7009A. (2016). *Standard for Models and Simulations*.\n    Section 4.2: Verification Requirements.\n\n[3] Goldberg, D. (1991). \"What Every Computer Scientist Should Know\n    About Floating-Point Arithmetic\". *ACM Computing Surveys*, 23(1).\n    DOI: 10.1145/103162.103163\n```\n\n## Verification Checklist\n\n- [ ] Formulas re-derived from first principles\n- [ ] Symbolic verification completed (CAS)\n- [ ] Approximation order documented\n- [ ] Error bounds derived and tested\n- [ ] Authoritative references cited\n- [ ] Deviations from standards documented\n- [ ] Conflicts resolved or flagged\n- [ ] Implementation matches theory\n\nFile v1.9.12:modules/numerical-stability.md\n\n---\nparent_skill: pensive:math-review\nload_priority: high\nestimated_tokens: 400\n---\n\n# Numerical Stability Analysis\n\n## Conditioning\n\n**Condition Numbers**\n- Measure sensitivity to input perturbations\n- High condition number = unstable computation\n- Use scaled condition numbers when possible\n\n**Sensitivity Analysis**\n- Perturb inputs systematically\n- Measure output variation\n- Document acceptable tolerance ranges\n\n## Precision Management\n\n**Floating-Point Error Propagation**\n```python\n# Bad: Accumulating small values into large\ntotal = 1e15\nfor x in small_values:\n    total += x  # Precision lost\n\n# Good: Kahan summation or sort first\nsorted_values = sorted(small_values)\ntotal = sum(sorted_values)  # Better precision\n```\n\n**Catastrophic Cancellation**\n```python\n# Bad: Subtracting similar values\nresult = (a + epsilon) - a  # Catastrophic cancellation\n\n# Good: Reformulate to avoid\nresult = epsilon  # Direct computation\n```\n\n**Overflow/Underflow Prevention**\n- Check dynamic range before operations\n- Use log-space for very large/small products\n- Normalize intermediate results\n- Scale inputs to manageable ranges\n\n## Scaling and Normalization\n\n**Dynamic Range Handling**\n- Pre-scale inputs to [0, 1] or [-1, 1]\n- Use log-transforms for exponential data\n- Document scaling factors and units\n\n**Normalization Requirements**\n- L1/L2 normalization for vectors\n- Feature scaling for ML inputs\n- Unit conversions for physical quantities\n\n## Randomness Control\n\n**Reproducibility**\n- Set explicit random seeds\n- Document PRNG algorithms used\n- Version lock numerical libraries\n- Test deterministic behavior\n\n**Seed Management**\n```python\n# Good: Explicit seed control\nimport numpy as np\nnp.random.seed(42)\n\n# Better: Isolated RNG state\nrng = np.random.RandomState(42)\nsamples = rng.normal(0, 1, size=100)\n```\n\n## Complexity Analysis\n\nCompare algorithmic complexity before/after changes:\n\n```\nBefore: O(n²) time, O(n) space\nAfter:  O(n log n) time, O(n) space\nImprovement: 100x faster for n=1000\n```\n\nDocument:\n- Time complexity\n- Space complexity\n- Cache behavior\n- Parallelization potential\n\n## Uncertainty Quantification\n\nRequired for:\n- Safety-critical systems\n- Data-driven components\n- High-stakes decisions\n- Regulatory compliance\n\nMethods:\n- Monte Carlo sampling\n- Bootstrap confidence intervals\n- Sensitivity analysis\n- Error propagation formulas\n\n## Stability Checklist\n\n- [ ] Condition number < 1e6\n- [ ] Precision loss < 1e-10\n- [ ] No catastrophic cancellation\n- [ ] Overflow/underflow prevented\n- [ ] Scaling applied appropriately\n- [ ] Random seeds controlled\n- [ ] Complexity acceptable\n- [ ] Uncertainty quantified (if required)\n\nFile v1.9.12:modules/requirements-mapping.md\n\n---\nparent_skill: pensive:math-review\nload_priority: medium\nestimated_tokens: 300\n---\n\n# Requirements Mapping\n\n## Mathematical Invariants\n\nTranslate requirements into verifiable mathematical properties:\n\n| Requirement | Invariant | Test Coverage |\n|-------------|-----------|---------------|\n| Positive output | f(x) > 0 ∀ x ∈ domain | Property test |\n| Conservation | Σ mass_in = Σ mass_out | Unit test |\n| Bounded error | \\|ε\\| < 1e-6 | Benchmark |\n| Monotonicity | x₁ < x₂ ⟹ f(x₁) ≤ f(x₂) | Property test |\n| Idempotence | f(f(x)) = f(x) | Unit test |\n\n## Pre-conditions\n\n**Input Validation**\n```python\ndef compute(x: float, n: int) -> float:\n    \"\"\"Compute function with documented preconditions.\n\n    Preconditions:\n    - x ≥ 0 (non-negative input)\n    - n > 0 (positive integer)\n    - x < 1e10 (prevent overflow)\n    \"\"\"\n    if x < 0:\n        raise ValueError(\"x must be non-negative\")\n    if n <= 0:\n        raise ValueError(\"n must be positive\")\n    if x >= 1e10:\n        raise ValueError(\"x must be < 1e10\")\n    # ... implementation\n```\n\n**Domain Constraints**\n- Valid input ranges\n- Type requirements\n- Dimensional consistency\n- Unit compatibility\n\n## Post-conditions\n\n**Output Guarantees**\n```python\ndef normalize(vector: np.ndarray) -> np.ndarray:\n    \"\"\"Normalize vector to unit length.\n\n    Postconditions:\n    - ||result|| = 1.0 (± 1e-10)\n    - result ∥ vector (parallel)\n    \"\"\"\n    result = vector / np.linalg.norm(vector)\n    assert abs(np.linalg.norm(result) - 1.0) < 1e-10\n    return result\n```\n\n**Invariant Preservation**\n- Conservation laws maintained\n- Bounds respected\n- Relationships preserved\n\n## Conservation Laws\n\n**Physical Conservation**\n- Mass conservation\n- Energy conservation\n- Momentum conservation\n- Charge conservation\n\n**Numerical Conservation**\n- Probability sums to 1.0\n- Symmetry preservation\n- Balance equations\n\n## Monotonicity Guarantees\n\n**Increasing Functions**\n```python\n# Property test\n@given(st.floats(min_value=0, max_value=100))\ndef test_monotonic_increasing(x1, x2):\n    assume(x1 < x2)\n    assert f(x1) <= f(x2)\n```\n\n**Convexity/Concavity**\n- Second derivative tests\n- Jensen's inequality\n- Midpoint properties\n\n## Probabilistic Bounds\n\n**Confidence Intervals**\n- Document confidence levels (95%, 99%)\n- Specify interval type (credible, confidence)\n- Test coverage probabilities\n\n**Error Probabilities**\n- Type I/II error rates\n- False positive/negative rates\n- Statistical power\n\n## Coverage Gap Analysis\n\nIdentify untested invariants:\n\n```markdown\n### Coverage Gaps\n\n**Missing Tests**\n- [ ] Boundary condition: x = 0\n- [ ] Overflow case: x > 1e15\n- [ ] Negative input handling\n- [ ] Conservation at t → ∞\n\n**Insufficient Coverage**\n- [ ] Only 3 test cases for n-dimensional invariant\n- [ ] No property tests for monotonicity\n- [ ] Missing edge case: empty input\n```\n\n## Documentation Template\n\n```python\ndef algorithm(inputs) -> outputs:\n    \"\"\"Brief description.\n\n    Mathematical Properties:\n    - Preconditions: [domain constraints]\n    - Postconditions: [guaranteed properties]\n    - Invariants: [preserved relationships]\n    - Complexity: [time/space bounds]\n    - Stability: [condition number, error bounds]\n\n    References:\n    - [Citation to algorithm source]\n    \"\"\"\n```\n\n## Mapping Checklist\n\n- [ ] Requirements translated to invariants\n- [ ] Pre-conditions documented\n- [ ] Post-conditions verified\n- [ ] Conservation laws tested\n- [ ] Monotonicity/convexity checked\n- [ ] Probabilistic bounds specified\n- [ ] Coverage gaps identified\n- [ ] All properties have tests\n\nFile v1.9.12:modules/testing-strategies.md\n\n---\nparent_skill: pensive:math-review\nload_priority: medium\nestimated_tokens: 350\n---\n\n# Testing Strategies for Mathematical Code\n\n## Edge Case Coverage\n\n**Domain Boundaries**\n```python\n# Bad: Undefined for negative\nresult = math.sqrt(value)\n\n# Good: Validate domain\ndef safe_sqrt(value: float) -> float:\n    if value < 0:\n        raise ValueError(\"sqrt requires non-negative input\")\n    return math.sqrt(value)\n\n# Test edge cases\n@pytest.mark.parametrize(\"value\", [0, 1e-100, 1e100, float('inf')])\ndef test_sqrt_boundaries(value):\n    result = safe_sqrt(value)\n    assert result >= 0\n```\n\n**Special Values**\n- Zero\n- One\n- Infinity\n- NaN\n- Very small (underflow)\n- Very large (overflow)\n- Negative values\n- Empty inputs\n\n## Property-Based Testing\n\n**Hypothesis Framework**\n```python\nfrom hypothesis import given, strategies as st\n\n@given(st.floats(min_value=0, max_value=1e6))\ndef test_sqrt_inverse(x):\n    \"\"\"sqrt(x)² should equal x\"\"\"\n    result = safe_sqrt(x)\n    assert abs(result * result - x) < 1e-10 * x\n```\n\n**Invariant Testing**\n- Symmetry properties\n- Associativity/commutativity\n- Idempotence\n- Conservation laws\n- Monotonicity\n\n## Benchmark Testing\n\n**Performance Validation**\n```bash\npytest tests/math/ --benchmark-only\npytest tests/math/ --benchmark-compare=baseline\n```\n\n**Regression Detection**\n```python\ndef test_algorithm_performance(benchmark):\n    \"\"\"validate O(n log n) complexity maintained\"\"\"\n    n = 10000\n    data = np.random.rand(n)\n\n    result = benchmark(algorithm, data)\n\n    # Verify result correctness\n    assert len(result) == n\n    # Performance constraint\n    assert benchmark.stats['mean'] < 0.1  # seconds\n```\n\n**Complexity Verification**\n- Time scaling tests\n- Memory profiling\n- Cache behavior\n- Parallel efficiency\n\n## Reproducibility Testing\n\n**Deterministic Results**\n```python\ndef test_reproducibility():\n    \"\"\"Same seed produces same results\"\"\"\n    np.random.seed(42)\n    result1 = monte_carlo_simulation()\n\n    np.random.seed(42)\n    result2 = monte_carlo_simulation()\n\n    np.testing.assert_array_equal(result1, result2)\n```\n\n**Version Pinning**\n```toml\n# pyproject.toml\n[tool.poetry.dependencies]\nnumpy = \"==1.24.0\"  # Pin for reproducibility\nscipy = \"==1.10.0\"\n```\n\n## Reference Implementation Tests\n\n**Golden Master Testing**\n```python\ndef test_against_reference():\n    \"\"\"Compare with NumPy/SciPy reference\"\"\"\n    x = np.linspace(0, 10, 100)\n\n    our_result = our_implementation(x)\n    reference_result = scipy.special.reference_function(x)\n\n    np.testing.assert_allclose(\n        our_result,\n        reference_result,\n        rtol=1e-10,\n        atol=1e-12\n    )\n```\n\n**Cross-Validation**\n- Multiple independent implementations\n- Different algorithms\n- Analytical solutions (when available)\n- Published test cases\n\n## Numerical Accuracy Tests\n\n**Tolerance Specifications**\n```python\n# Absolute tolerance\nnp.testing.assert_allclose(result, expected, atol=1e-10)\n\n# Relative tolerance\nnp.testing.assert_allclose(result, expected, rtol=1e-8)\n\n# Both\nnp.testing.assert_allclose(\n    result, expected,\n    rtol=1e-8, atol=1e-10\n)\n```\n\n**ULP (Units in Last Place) Testing**\n```python\n# For critical floating-point comparisons\nassert abs(a - b) <= 2 * np.finfo(float).eps * max(abs(a), abs(b))\n```\n\n## Evidence Logging\n\n**Execution Records**\n```bash\n# Run tests with output capture\npytest tests/math/ -v --tb=short > test_results.txt\n\n# Benchmark with JSON output\npytest tests/math/ --benchmark-json=benchmark.json\n\n# Execute derivation notebooks\njupyter nbconvert --execute derivation.ipynb \\\n    --to html --output verification.html\n```\n\n**Documentation Template**\n```markdown\n## Test Evidence\n\n### Unit Tests\n- **Command**: `pytest tests/math/ -v`\n- **Result**: 47/47 passed\n- **Coverage**: 94%\n- **Date**: 2025-12-06\n\n### Benchmarks\n- **Command**: `pytest tests/math/ --benchmark-only`\n- **Mean time**: 23.4ms (±1.2ms)\n- **Baseline**: 24.1ms\n- **Improvement**: 3%\n\n### Derivation Verification\n- **Notebook**: derivation.ipynb\n- **Status**: All cells executed successfully\n- **Symbolic checks**: Passed\n- **Reference comparison**: Within tolerance\n```\n\n## Test Organization\n\n```\ntests/math/\n├── test_correctness.py       # Basic functionality\n├── test_edge_cases.py        # Boundary conditions\n├── test_properties.py        # Hypothesis tests\n├── test_benchmarks.py        # Performance\n├── test_stability.py         # Numerical stability\n├── test_references.py        # Golden masters\n└── fixtures/\n    ├── test_data.npz\n    └── reference_results.json\n```\n\n## Testing Checklist\n\n- [ ] Edge cases covered (0, ±∞, NaN)\n- [ ] Property tests for invariants\n- [ ] Benchmark tests for performance\n- [ ] Reproducibility verified\n- [ ] Reference implementation compared\n- [ ] Tolerances documented\n- [ ] Evidence logged and dated\n- [ ] Coverage > 90% for math code\n\nFile v1.9.12:skill-card.md\n\n## Description: <br>\nVerifies math-heavy code for algorithmic correctness and numerical stability. <br>\n\nThis skill is ready for commercial/non-commercial use. <br>\n\n## Publisher: <br>\n[athola](https://clawhub.ai/user/athola) <br>\n\n### License/Terms of Use: <br>\nMIT-0 <br>\n\n\n## Use Case: <br>\nDevelopers and engineers use this skill to review mathematical, scientific, ML, and numerical code for algorithmic correctness, derivation quality, numerical stability, and test evidence before accepting changes. <br>\n\n### Deployment Geography for Use: <br>\nGlobal <br>\n\n## Known Risks and Mitigations: <br>\nRisk: Suggested pytest, benchmark, or notebook commands may execute code from the local project. <br>\nMitigation: Review commands before execution and run them in an appropriate project sandbox or trusted checkout. <br>\nRisk: Mathematical review findings can be incomplete or overly confident if requirements, derivations, tolerances, or reference implementations are missing. <br>\nMitigation: Require cited evidence, explicit assumptions, documented tolerances, and human review for safety-critical, financial, ML fairness, or scientific claims. <br>\n\n\n## Reference(s): <br>\n- [ClawHub skill page](https://clawhub.ai/athola/nm-pensive-math-review) <br>\n- [Publisher profile](https://clawhub.ai/user/athola) <br>\n- [Configured homepage](https://github.com/athola/claude-night-market/tree/master/plugins/pensive) <br>\n- [Requirements mapping module](modules/requirements-mapping.md) <br>\n- [Derivation verification module](modules/derivation-verification.md) <br>\n- [Numerical stability module](modules/numerical-stability.md) <br>\n- [Testing strategies module](modules/testing-strategies.md) <br>\n\n\n## Skill Output: <br>\n**Output Type(s):** [Text, Markdown, Shell commands, Guidance] <br>\n**Output Format:** [Markdown review report with tables, issue entries, recommendations, and inline shell commands] <br>\n**Output Parameters:** [1D] <br>\n**Other Properties Related to Output:** [May propose local pytest, benchmark, and notebook execution commands for reviewer approval.] <br>\n\n## Skill Version(s): <br>\n1.9.12 (source: server release metadata; artifact frontmatter says 1.9.8) <br>\n\n## Ethical Considerations: <br>\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment. <br>\n\nArchive v1.0.3: 7 files, 11148 bytes\n\nFiles: modules/derivation-verification.md (3255b), modules/numerical-stability.md (2650b), modules/requirements-mapping.md (3561b), modules/testing-strategies.md (4867b), skill-card.md (2489b), SKILL.md (5126b), _meta.json (141b)\n\nFile v1.0.3:SKILL.md\n\n---\nname: math-review\ndescription: Verifies math-heavy code for algorithmic correctness and numerical stability\nversion: 1.9.8\ntriggers:\n  - math\n  - algorithms\n  - numerical\n  - stability\n  - verification\n  - scientific\n  - reviewing scientific algorithms\n  - ML models\n  - or numerical code\nmetadata: {\"openclaw\": {\"homepage\": \"https://github.com/athola/claude-night-market/tree/master/plugins/pensive\", \"emoji\": \"\\ud83e\\udd9e\", \"requires\": {\"config\": [\"night-market.pensive:shared\", \"night-market.imbue:proof-of-work\"]}}}\nsource: claude-night-market\nsource_plugin: pensive\n---\n\n> **Night Market Skill** — ported from [claude-night-market/pensive](https://github.com/athola/claude-night-market/tree/master/plugins/pensive). For the full experience with agents, hooks, and commands, install the Claude Code plugin.\n\n\n## Table of Contents\n\n- [Quick Start](#quick-start)\n- [When to Use](#when-to-use)\n- [Required TodoWrite Items](#required-todowrite-items)\n- [Core Workflow](#core-workflow)\n- [1. Context Sync](#1-context-sync)\n- [2. Requirements Mapping](#2-requirements-mapping)\n- [3. Derivation Verification](#3-derivation-verification)\n- [4. Stability Assessment](#4-stability-assessment)\n- [5. Proof of Work](#5-proof-of-work)\n- [Progressive Loading](#progressive-loading)\n- [Essential Checklist](#essential-checklist)\n- [Output Format](#output-format)\n- [Summary](#summary)\n- [Context](#context)\n- [Requirements Analysis](#requirements-analysis)\n- [Derivation Review](#derivation-review)\n- [Stability Analysis](#stability-analysis)\n- [Issues](#issues)\n- [Recommendation](#recommendation)\n- [Exit Criteria](#exit-criteria)\n\n\n# Mathematical Algorithm Review\n\nIntensive analysis ensuring numerical stability and alignment with standards.\n\n## Quick Start\n\n```bash\n/math-review\n```\n**Verification:** Run the command with `--help` flag to verify availability.\n\n## When To Use\n\n- Changes to mathematical models or algorithms\n- Statistical routines or probabilistic logic\n- Numerical integration or optimization\n- Scientific computing code\n- ML/AI model implementations\n- Safety-critical calculations\n\n## When NOT To Use\n\n- General algorithm review -\n  use architecture-review\n- Performance optimization - use parseltongue:python-performance\n- General algorithm review -\n  use architecture-review\n- Performance optimization - use parseltongue:python-performance\n\n## Required TodoWrite Items\n\n1. `math-review:context-synced`\n2. `math-review:requirements-mapped`\n3. `math-review:derivations-verified`\n4. `math-review:stability-assessed`\n5. `math-review:evidence-logged`\n\n## Core Workflow\n\n### 1. Context Sync\n```bash\npwd && git status -sb && git diff --stat origin/main..HEAD\n```\n**Verification:** Run `git status` to confirm working tree state.\nEnumerate math-heavy files (source, tests, docs, notebooks). Classify risk: safety-critical, financial, ML fairness.\n\n### 2. Requirements Mapping\nTranslate requirements → mathematical invariants. Document pre/post conditions, conservation laws, bounds. **Load**: `modules/requirements-mapping.md`\n\n### 3. Derivation Verification\nRe-derive formulas using CAS. Challenge approximations. Cite authoritative standards (NASA-STD-7009, ASME VVUQ). **Load**: `modules/derivation-verification.md`\n\n### 4. Stability Assessment\nEvaluate conditioning, precision, scaling, randomness. Compare complexity. Quantify uncertainty. **Load**: `modules/numerical-stability.md`\n\n### 5. Proof of Work\n```bash\npytest tests/math/ --benchmark\njupyter nbconvert --execute derivation.ipynb\n```\n**Verification:** Run `pytest -v tests/math/` to verify.\nLog deviations, recommend: Approve / Approve with actions / Block. **Load**: `modules/testing-strategies.md`\n\n## Progressive Loading\n\n**Default (200 tokens)**: Core workflow, checklists\n**+Requirements** (+300 tokens): Invariants, pre/post conditions, coverage analysis\n**+Derivation** (+350 tokens): CAS verification, standards, citations\n**+Stability** (+400 tokens): Numerical properties, precision, complexity\n**+Testing** (+350 tokens): Edge cases, benchmarks, reproducibility\n\n**Total with all modules**: ~1600 tokens\n\n## Essential Checklist\n\n**Correctness**: Formulas match spec | Edge cases handled | Units consistent | Domain enforced\n**Stability**: Condition number OK | Precision sufficient | No cancellation | Overflow prevented\n**Verification**: Derivations documented | References cited | Tests cover invariants | Benchmarks reproducible\n**Documentation**: Assumptions stated | Limitations documented | Error bounds specified | References linked\n\n## Output Format\n\n```markdown\n## Summary\n[Brief findings]\n\n## Context\nFiles | Risk classification | Standards\n\n## Requirements Analysis\n| Invariant | Verified | Evidence |\n\n## Derivation Review\n[Status and conflicts]\n\n## Stability Analysis\nCondition number | Precision | Risks\n\n## Issues\n[M1] [Title]: Location | Issue | Fix\n\n## Recommendation\nApprove / Approve with actions / Block\n```\n**Verification:** Run the command with `--help` flag to verify availability.\n\n## Exit Criteria\n\n- Context synced, requirements mapped, derivations verified, stability assessed, evidence logged with citations\n\nFile v1.0.3:_meta.json\n\n{\n  \"ownerId\": \"kn7d107jg9jv602h9ytsegydq184a42s\",\n  \"slug\": \"nm-pensive-math-review\",\n  \"version\": \"1.0.3\",\n  \"publishedAt\": 1781791935757\n}\n\nFile v1.0.3:modules/derivation-verification.md\n\n---\nparent_skill: pensive:math-review\nload_priority: high\nestimated_tokens: 350\n---\n\n# Derivation Verification\n\n## Re-derive Critical Formulas\n\n**Symbolic Verification**\n- Use Computer Algebra Systems (SymPy, Mathematica, Maple)\n- Confirm algebraic manipulations\n- Verify calculus operations (derivatives, integrals)\n- Check limit behavior\n\n**Computational Notebooks**\n```python\n# Example: Verify gradient computation\nimport sympy as sp\nx, y = sp.symbols('x y')\nf = x**2 + y**2\ngrad_f = [sp.diff(f, var) for var in [x, y]]\n# Compare with implementation\n```\n\n**Probabilistic Reasoning**\n- Verify conditional probability formulas\n- Check Bayes rule applications\n- Confirm expectation/variance calculations\n- Validate distribution properties\n\n## Challenge Approximations\n\n**Series Truncation**\n- Document truncation order (e.g., O(h³))\n- Estimate truncation error\n- Test convergence with different orders\n- Provide error bounds across domain\n\n**Linearizations**\n- Identify linearization points\n- Estimate valid domain size\n- Test against full nonlinear model\n- Document approximation quality\n\n**Surrogate Models**\n- Compare surrogate to ground truth\n- Quantify approximation error\n- Document training/validation data\n- Test extrapolation behavior\n\n**Error Bounds**\n- Derive theoretical error bounds\n- Verify empirically\n- Document worst-case scenarios\n- Test at domain boundaries\n\n## Authoritative References\n\n**Standards and Frameworks**\n- **NASA-STD-7009**: Modeling and Simulation V&V\n- **ASME V&V 20**: Verification & Validation in CFD/HT\n- **ASME V&V 10**: Guide for V&V in Computational Solid Mechanics\n- **SIAM**: Reproducibility checklists\n- **IEEE 754**: Floating-point arithmetic\n- **NIST**: Uncertainty quantification guidelines\n\n**Academic Sources**\n- Peer-reviewed papers (DOI links)\n- Textbooks (edition and page numbers)\n- Technical reports\n- Conference proceedings\n\n**Implementation References**\n- Reference implementations (NumPy, SciPy, GSL)\n- Algorithm papers (original sources)\n- Numerical recipes\n- Domain-specific libraries\n\n## Document Conflicts\n\nWhen implementation deviates from standards:\n\n```markdown\n### Deviation: [Brief title]\n- **Standard**: NASA-STD-7009 Section 3.4.2\n- **Requirement**: Monte Carlo with n≥1000 samples\n- **Implementation**: n=100 samples\n- **Justification**: Performance constraints\n- **Risk**: Reduced confidence intervals\n- **Mitigation**: Document uncertainty, flag results\n- **Owner**: [name]\n- **Due date**: [date]\n```\n\n## Citation Format\n\n```markdown\n## References\n\n[1] Wilkinson, J.H. (1963). *Rounding Errors in Algebraic Processes*.\n    Prentice-Hall. Chapter 3.\n\n[2] NASA-STD-7009A. (2016). *Standard for Models and Simulations*.\n    Section 4.2: Verification Requirements.\n\n[3] Goldberg, D. (1991). \"What Every Computer Scientist Should Know\n    About Floating-Point Arithmetic\". *ACM Computing Surveys*, 23(1).\n    DOI: 10.1145/103162.103163\n```\n\n## Verification Checklist\n\n- [ ] Formulas re-derived from first principles\n- [ ] Symbolic verification completed (CAS)\n- [ ] Approximation order documented\n- [ ] Error bounds derived and tested\n- [ ] Authoritative references cited\n- [ ] Deviations from standards documented\n- [ ] Conflicts resolved or flagged\n- [ ] Implementation matches theory\n\nFile v1.0.3:modules/numerical-stability.md\n\n---\nparent_skill: pensive:math-review\nload_priority: high\nestimated_tokens: 400\n---\n\n# Numerical Stability Analysis\n\n## Conditioning\n\n**Condition Numbers**\n- Measure sensitivity to input perturbations\n- High condition number = unstable computation\n- Use scaled condition numbers when possible\n\n**Sensitivity Analysis**\n- Perturb inputs systematically\n- Measure output variation\n- Document acceptable tolerance ranges\n\n## Precision Management\n\n**Floating-Point Error Propagation**\n```python\n# Bad: Accumulating small v\n\nArchive v1.0.2: 7 files, 11127 bytes\n\nFiles: modules/derivation-verification.md (3255b), modules/numerical-stability.md (2650b), modules/requirements-mapping.md (3561b), modules/testing-strategies.md (4867b), skill-card.md (2121b), SKILL.md (5339b), _meta.json (141b)\n\nArchive v1.0.1: 6 files, 9995 bytes\n\nFiles: modules/derivation-verification.md (3255b), modules/numerical-stability.md (2650b), modules/requirements-mapping.md (3561b), modules/testing-strategies.md (4867b), SKILL.md (5339b), _meta.json (141b)\n\nArchive v1.0.0: 6 files, 9995 bytes\n\nFiles: modules/derivation-verification.md (3255b), modules/numerical-stability.md (2650b), modules/requirements-mapping.md (3561b), modules/testing-strategies.md (4867b), SKILL.md (5339b), _meta.json (141b)","readmeExcerpt":"Skill: math-review Owner: athola Summary: Verifies math-heavy code for algorithmic correctness and numerical stability Tags: latest:1.9.19 Version history: v1.9.19 | 2026-08-26T13:19:00.290Z | user Release v1.9.19 v1.9.17 | 2026-07-30T05:39:12.631Z | user Release v1.9.17 v1.9.16 | 2026-07-14T19:55:54.335Z | user Release v1.9.16 v1.9.14 | 2026-06-30T18:04:14.103Z | user Release v1.9.14 v1.9.13 | 2026-06-27T16:22:15.61","codeSnippets":[],"executableExamples":[{"language":"bash","snippet":"/math-review"},{"language":"bash","snippet":"pwd && git status -sb && git diff --stat origin/main..HEAD"},{"language":"bash","snippet":"pytest tests/math/ --benchmark\njupyter nbconvert --execute derivation.ipynb"},{"language":"markdown","snippet":"## Summary\n[Brief findings]\n\n## Context\nFiles | Risk classification | Standards\n\n## Requirements Analysis\n| Invariant | Verified | Evidence |\n\n## Derivation Review\n[Status and conflicts]\n\n## Stability Analysis\nCondition number | Precision | Risks\n\n## Issues\n[M1] [Title]: Location | Issue | Fix\n\n## Recommendation\nApprove / Approve with actions / Block"},{"language":"python","snippet":"# Example: Verify gradient computation\nimport sympy as sp\nx, y = sp.symbols('x y')\nf = x**2 + y**2\ngrad_f = [sp.diff(f, var) for var in [x, y]]\n# Compare with implementation"},{"language":"markdown","snippet":"### Deviation: [Brief title]\n- **Standard**: NASA-STD-7009 Section 3.4.2\n- **Requirement**: Monte Carlo with n≥1000 samples\n- **Implementation**: n=100 samples\n- **Justification**: Performance constraints\n- **Risk**: Reduced confidence intervals\n- **Mitigation**: Document uncertainty, flag results\n- **Owner**: [name]\n- **Due date**: [date]"}],"parameters":null,"dependencies":[],"permissions":[],"extractedFiles":[{"path":"SKILL.md","content":"---\nname: math-review\ndescription: Verifies math-heavy code for algorithmic correctness and numerical stability\nversion: 1.9.8\ntriggers:\n  - math\n  - algorithms\n  - numerical\n  - stability\n  - verification\n  - scientific\n  - reviewing scientific algorithms\n  - ML models\n  - or numerical code\nmetadata: {\"openclaw\": {\"homepage\": \"https://github.com/athola/claude-night-market/tree/master/plugins/pensive\", \"emoji\": \"\\ud83e\\udd9e\", \"requires\": {\"config\": [\"night-market.pensive:shared\", \"night-market.imbue:proof-of-work\"]}}}\nsource: claude-night-market\nsource_plugin: pensive\n---\n\n> **Night Market Skill** — ported from [claude-night-market/pensive](https://github.com/athola/claude-night-market/tree/master/plugins/pensive). For the full experience with agents, hooks, and commands, install the Claude Code plugin.\n\n\n## Table of Contents\n\n- [Quick Start](#quick-start)\n- [When to Use](#when-to-use)\n- [Required TodoWrite Items](#required-todowrite-items)\n- [Core Workflow](#core-workflow)\n- [1. Context Sync](#1-context-sync)\n- [2. Requirements Mapping](#2-requirements-mapping)\n- [3. Derivation Verification](#3-derivation-verification)\n- [4. Stability Assessment](#4-stability-assessment)\n- [5. Proof of Work](#5-proof-of-work)\n- [Progressive Loading](#progressive-loading)\n- [Essential Checklist](#essential-checklist)\n- [Output Format](#output-format)\n- [Summary](#summary)\n- [Context](#context)\n- [Requirements Analysis](#requirements-analysis)\n- [Derivation Review](#derivation-review)\n- [Stability Analysis](#stability-analysis)\n- [Issues](#issues)\n- [Recommendation](#recommendation)\n- [Exit Criteria](#exit-criteria)\n\n\n# Mathematical Algorithm Review\n\nIntensive analysis ensuring numerical stability and alignment with standards.\n\n## Quick Start\n\n```bash\n/math-review\n```\n**Verification:** Run the command with `--help` flag to verify availability.\n\n## When To Use\n\n- Changes to mathematical models or algorithms\n- Statistical routines or probabilistic logic\n- Numerical integration or optimization\n- Scientific computing code\n- ML/AI model implementations\n- Safety-critical calculations\n\n## When NOT To Use\n\n- General algorithm review -\n  use architecture-review\n- Performance optimization - use parseltongue:python-performance\n- General algorithm review -\n  use architecture-review\n- Performance optimization - use parseltongue:python-performance\n\n## Required TodoWrite Items\n\n1. `math-review:context-synced`\n2. `math-review:requirements-mapped`\n3. `math-review:derivations-verified`\n4. `math-review:stability-assessed`\n5. `math-review:evidence-logged`\n\n## Core Workflow\n\n### 1. Context Sync\n```bash\npwd && git status -sb && git diff --stat origin/main..HEAD\n```\n**Verification:** Run `git status` to confirm working tree state.\nEnumerate math-heavy files (source, tests, docs, notebooks). Classify risk: safety-critical, financial, ML fairness.\n\n### 2. Requirements Mapping\nTranslate requirements → mathematical invariants. Document pre/post conditions, conservation laws, bounds. **Load"},{"path":"_meta.json","content":"{\n  \"ownerId\": \"kn7d107jg9jv602h9ytsegydq184a42s\",\n  \"slug\": \"nm-pensive-math-review\",\n  \"version\": \"1.9.19\",\n  \"publishedAt\": 1787750340290\n}"},{"path":"modules/derivation-verification.md","content":"---\nparent_skill: pensive:math-review\nload_priority: high\nestimated_tokens: 350\n---\n\n# Derivation Verification\n\n## Re-derive Critical Formulas\n\n**Symbolic Verification**\n- Use Computer Algebra Systems (SymPy, Mathematica, Maple)\n- Confirm algebraic manipulations\n- Verify calculus operations (derivatives, integrals)\n- Check limit behavior\n\n**Computational Notebooks**\n```python\n# Example: Verify gradient computation\nimport sympy as sp\nx, y = sp.symbols('x y')\nf = x**2 + y**2\ngrad_f = [sp.diff(f, var) for var in [x, y]]\n# Compare with implementation\n```\n\n**Probabilistic Reasoning**\n- Verify conditional probability formulas\n- Check Bayes rule applications\n- Confirm expectation/variance calculations\n- Validate distribution properties\n\n## Challenge Approximations\n\n**Series Truncation**\n- Document truncation order (e.g., O(h³))\n- Estimate truncation error\n- Test convergence with different orders\n- Provide error bounds across domain\n\n**Linearizations**\n- Identify linearization points\n- Estimate valid domain size\n- Test against full nonlinear model\n- Document approximation quality\n\n**Surrogate Models**\n- Compare surrogate to ground truth\n- Quantify approximation error\n- Document training/validation data\n- Test extrapolation behavior\n\n**Error Bounds**\n- Derive theoretical error bounds\n- Verify empirically\n- Document worst-case scenarios\n- Test at domain boundaries\n\n## Authoritative References\n\n**Standards and Frameworks**\n- **NASA-STD-7009**: Modeling and Simulation V&V\n- **ASME V&V 20**: Verification & Validation in CFD/HT\n- **ASME V&V 10**: Guide for V&V in Computational Solid Mechanics\n- **SIAM**: Reproducibility checklists\n- **IEEE 754**: Floating-point arithmetic\n- **NIST**: Uncertainty quantification guidelines\n\n**Academic Sources**\n- Peer-reviewed papers (DOI links)\n- Textbooks (edition and page numbers)\n- Technical reports\n- Conference proceedings\n\n**Implementation References**\n- Reference implementations (NumPy, SciPy, GSL)\n- Algorithm papers (original sources)\n- Numerical recipes\n- Domain-specific libraries\n\n## Document Conflicts\n\nWhen implementation deviates from standards:\n\n```markdown\n### Deviation: [Brief title]\n- **Standard**: NASA-STD-7009 Section 3.4.2\n- **Requirement**: Monte Carlo with n≥1000 samples\n- **Implementation**: n=100 samples\n- **Justification**: Performance constraints\n- **Risk**: Reduced confidence intervals\n- **Mitigation**: Document uncertainty, flag results\n- **Owner**: [name]\n- **Due date**: [date]\n```\n\n## Citation Format\n\n```markdown\n## References\n\n[1] Wilkinson, J.H. (1963). *Rounding Errors in Algebraic Processes*.\n    Prentice-Hall. Chapter 3.\n\n[2] NASA-STD-7009A. (2016). *Standard for Models and Simulations*.\n    Section 4.2: Verification Requirements.\n\n[3] Goldberg, D. (1991). \"What Every Computer Scientist Should Know\n    About Floating-Point Arithmetic\". *ACM Computing Surveys*, 23(1).\n    DOI: 10.1145/103162.103163\n```\n\n## Verification Checklist\n\n- [ ] Formulas re-derived from first principles\n- [ ] Symbolic veri"},{"path":"modules/numerical-stability.md","content":"---\nparent_skill: pensive:math-review\nload_priority: high\nestimated_tokens: 400\n---\n\n# Numerical Stability Analysis\n\n## Conditioning\n\n**Condition Numbers**\n- Measure sensitivity to input perturbations\n- High condition number = unstable computation\n- Use scaled condition numbers when possible\n\n**Sensitivity Analysis**\n- Perturb inputs systematically\n- Measure output variation\n- Document acceptable tolerance ranges\n\n## Precision Management\n\n**Floating-Point Error Propagation**\n```python\n# Bad: Accumulating small values into large\ntotal = 1e15\nfor x in small_values:\n    total += x  # Precision lost\n\n# Good: Kahan summation or sort first\nsorted_values = sorted(small_values)\ntotal = sum(sorted_values)  # Better precision\n```\n\n**Catastrophic Cancellation**\n```python\n# Bad: Subtracting similar values\nresult = (a + epsilon) - a  # Catastrophic cancellation\n\n# Good: Reformulate to avoid\nresult = epsilon  # Direct computation\n```\n\n**Overflow/Underflow Prevention**\n- Check dynamic range before operations\n- Use log-space for very large/small products\n- Normalize intermediate results\n- Scale inputs to manageable ranges\n\n## Scaling and Normalization\n\n**Dynamic Range Handling**\n- Pre-scale inputs to [0, 1] or [-1, 1]\n- Use log-transforms for exponential data\n- Document scaling factors and units\n\n**Normalization Requirements**\n- L1/L2 normalization for vectors\n- Feature scaling for ML inputs\n- Unit conversions for physical quantities\n\n## Randomness Control\n\n**Reproducibility**\n- Set explicit random seeds\n- Document PRNG algorithms used\n- Version lock numerical libraries\n- Test deterministic behavior\n\n**Seed Management**\n```python\n# Good: Explicit seed control\nimport numpy as np\nnp.random.seed(42)\n\n# Better: Isolated RNG state\nrng = np.random.RandomState(42)\nsamples = rng.normal(0, 1, size=100)\n```\n\n## Complexity Analysis\n\nCompare algorithmic complexity before/after changes:\n\n```\nBefore: O(n²) time, O(n) space\nAfter:  O(n log n) time, O(n) space\nImprovement: 100x faster for n=1000\n```\n\nDocument:\n- Time complexity\n- Space complexity\n- Cache behavior\n- Parallelization potential\n\n## Uncertainty Quantification\n\nRequired for:\n- Safety-critical systems\n- Data-driven components\n- High-stakes decisions\n- Regulatory compliance\n\nMethods:\n- Monte Carlo sampling\n- Bootstrap confidence intervals\n- Sensitivity analysis\n- Error propagation formulas\n\n## Stability Checklist\n\n- [ ] Condition number < 1e6\n- [ ] Precision loss < 1e-10\n- [ ] No catastrophic cancellation\n- [ ] Overflow/underflow prevented\n- [ ] Scaling applied appropriately\n- [ ] Random seeds controlled\n- [ ] Complexity acceptable\n- [ ] Uncertainty quantified (if required)"},{"path":"modules/requirements-mapping.md","content":"---\nparent_skill: pensive:math-review\nload_priority: medium\nestimated_tokens: 300\n---\n\n# Requirements Mapping\n\n## Mathematical Invariants\n\nTranslate requirements into verifiable mathematical properties:\n\n| Requirement | Invariant | Test Coverage |\n|-------------|-----------|---------------|\n| Positive output | f(x) > 0 ∀ x ∈ domain | Property test |\n| Conservation | Σ mass_in = Σ mass_out | Unit test |\n| Bounded error | \\|ε\\| < 1e-6 | Benchmark |\n| Monotonicity | x₁ < x₂ ⟹ f(x₁) ≤ f(x₂) | Property test |\n| Idempotence | f(f(x)) = f(x) | Unit test |\n\n## Pre-conditions\n\n**Input Validation**\n```python\ndef compute(x: float, n: int) -> float:\n    \"\"\"Compute function with documented preconditions.\n\n    Preconditions:\n    - x ≥ 0 (non-negative input)\n    - n > 0 (positive integer)\n    - x < 1e10 (prevent overflow)\n    \"\"\"\n    if x < 0:\n        raise ValueError(\"x must be non-negative\")\n    if n <= 0:\n        raise ValueError(\"n must be positive\")\n    if x >= 1e10:\n        raise ValueError(\"x must be < 1e10\")\n    # ... implementation\n```\n\n**Domain Constraints**\n- Valid input ranges\n- Type requirements\n- Dimensional consistency\n- Unit compatibility\n\n## Post-conditions\n\n**Output Guarantees**\n```python\ndef normalize(vector: np.ndarray) -> np.ndarray:\n    \"\"\"Normalize vector to unit length.\n\n    Postconditions:\n    - ||result|| = 1.0 (± 1e-10)\n    - result ∥ vector (parallel)\n    \"\"\"\n    result = vector / np.linalg.norm(vector)\n    assert abs(np.linalg.norm(result) - 1.0) < 1e-10\n    return result\n```\n\n**Invariant Preservation**\n- Conservation laws maintained\n- Bounds respected\n- Relationships preserved\n\n## Conservation Laws\n\n**Physical Conservation**\n- Mass conservation\n- Energy conservation\n- Momentum conservation\n- Charge conservation\n\n**Numerical Conservation**\n- Probability sums to 1.0\n- Symmetry preservation\n- Balance equations\n\n## Monotonicity Guarantees\n\n**Increasing Functions**\n```python\n# Property test\n@given(st.floats(min_value=0, max_value=100))\ndef test_monotonic_increasing(x1, x2):\n    assume(x1 < x2)\n    assert f(x1) <= f(x2)\n```\n\n**Convexity/Concavity**\n- Second derivative tests\n- Jensen's inequality\n- Midpoint properties\n\n## Probabilistic Bounds\n\n**Confidence Intervals**\n- Document confidence levels (95%, 99%)\n- Specify interval type (credible, confidence)\n- Test coverage probabilities\n\n**Error Probabilities**\n- Type I/II error rates\n- False positive/negative rates\n- Statistical power\n\n## Coverage Gap Analysis\n\nIdentify untested invariants:\n\n```markdown\n### Coverage Gaps\n\n**Missing Tests**\n- [ ] Boundary condition: x = 0\n- [ ] Overflow case: x > 1e15\n- [ ] Negative input handling\n- [ ] Conservation at t → ∞\n\n**Insufficient Coverage**\n- [ ] Only 3 test cases for n-dimensional invariant\n- [ ] No property tests for monotonicity\n- [ ] Missing edge case: empty input\n```\n\n## Documentation Template\n\n```python\ndef algorithm(inputs) -> outputs:\n    \"\"\"Brief description.\n\n    Mathematical Properties:\n    - Preconditions: [domain constraints]\n    - Pos"}],"languages":[],"docsSourceLabel":"CLAWHUB","editorialOverview":"Verifies math-heavy code for algorithmic correctness and numerical stability Skill: math-review Owner: athola Summary: Verifies math-heavy code for algorithmic correctness and numerical stability Tags: latest:1.9.19 Version history: v1.9.19 | 2026-08-26T13:19:00.290Z | user Release v1.9.19 v1.9.17 | 2026-07-30T05:39:12.631Z | user Release v1.9.17 v1.9.16 | 2026-07-14T19:55:54.335Z | user Release v1.9.16 v1.9.14 | 2026-06-30T18:04:14.103Z | user Release v1.9.14 v1.9.13 | 2026-06-27T16:22:15.61","editorialQuality":{"score":100,"threshold":65,"status":"ready","wordCount":1295,"uniquenessScore":58,"reasons":[]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-10-10T06:28:30.021Z","emptyReason":"No screenshots, media assets, or demo links are available."},"primaryImageUrl":null,"mediaAssetCount":0,"assets":[],"demoUrl":null},"ownerResources":{"evidence":{"source":"unclaimed","verified":false,"confidence":"low","updatedAt":"2026-10-10T06:28:30.021Z","emptyReason":"This page has not been claimed by the agent owner."},"hasCustomPage":false,"customPageUpdatedAt":null,"customLinks":[],"structuredLinks":{"docsUrl":null,"demoUrl":null,"supportUrl":null,"pricingUrl":null,"statusUrl":null},"customPage":null},"relatedAgents":{"evidence":{"source":"protocol-neighbors","verified":false,"confidence":"medium","updatedAt":"2026-10-10T10:48:41.770Z","emptyReason":null},"items":[{"id":"8ebccd8e-3863-4187-8355-c3f14e1f9edf","entityType":"agent","canonicalPath":"/agent/iofficeai-aionui","slug":"iofficeai-aionui","name":"AionUi","description":"Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!","url":"https://github.com/iOfficeAI/AionUi","homepage":"https://www.aionui.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-10-09T19:11:12.944Z","createdAt":"2026-02-25T03:38:16.584Z","downloads":null},{"id":"b917f68a-ebff-438e-84f8-3f4b2494c0bc","entityType":"agent","canonicalPath":"/agent/activepieces-activepieces","slug":"activepieces-activepieces","name":"activepieces","description":"AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents","url":"https://github.com/activepieces/activepieces","homepage":"https://www.activepieces.com","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-15T02:22:12.426Z","createdAt":"2026-02-25T03:38:12.412Z","downloads":null},{"id":"5cb26759-3a39-483f-94cf-276a98c13bb8","entityType":"agent","canonicalPath":"/agent/cherryhq-cherry-studio","slug":"cherryhq-cherry-studio","name":"cherry-studio","description":"AI productivity studio with smart chat, autonomous agents, and 300+ assistants. Unified access to frontier LLMs","url":"https://github.com/CherryHQ/cherry-studio","homepage":"https://cherry-ai.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-11T14:38:40.986Z","createdAt":"2026-02-25T03:38:19.379Z","downloads":null},{"id":"6f6582d0-5d76-4f0f-b81d-86520247950b","entityType":"agent","canonicalPath":"/agent/copilotkit-copilotkit","slug":"copilotkit-copilotkit","name":"CopilotKit","description":"The Frontend for Agents & Generative UI. React + Angular","url":"https://github.com/CopilotKit/CopilotKit","homepage":"https://docs.copilotkit.ai","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-03-25T09:50:57.846Z","createdAt":"2026-02-25T03:39:14.617Z","downloads":null}],"links":{"hub":"/agent","source":"/agent/source/clawhub","protocols":[{"label":"OpenClaw","href":"/agent/protocol/openclew"}]}}}