Files
personamanagmentlayer__pcl/stdlib/domains/finance-expert/SKILL.md
ANGX 4e07a6a874 feat(stdlib)!: Agent Skills v1.0 conformance, resolver fix, and 17 new skills (#43)
* chore(stdlib): add conformance tooling for the skills library

The library had no gate that could express what a valid skill is, so
malformed frontmatter, over-budget files and credential literals went
unnoticed. These scripts define and enforce that contract.

- validate-skills.py: extend with Agent Skills v1.0 conformance -
  naming rules and directory agreement, an explicit activation trigger
  in the description, canonical layout, the 500-line SKILL.md budget,
  relative-link integrity, and two security rules (no unrestricted
  Bash(*) grant, no credential literals). Structural checks now read a
  skill as a whole so material moved into references/ still counts.
- split-skill-references.py: move the heaviest sections of an oversized
  SKILL.md into references/. Verifies line by line that every source
  line lands in exactly one output and refuses to write otherwise.
- generate-skill-inventory.py: derive SKILLS_INVENTORY.md and
  DIRECTORY_STRUCTURE.md from the tree so they cannot drift.
- generate-skill-catalog.py: index the canonical layout only, count
  references/ toward a skill's size, and stop truncating descriptions
  at 200 characters - the catalog is the discovery surface and must
  carry the activation trigger.
- .gitignore: Python bytecode from these scripts, and local .pcl state.

Reviewed-by: Security Analyst, Compiler Engineer, DevX Engineer

* fix(stdlib): bring all 174 skills to Agent Skills v1.0 conformance

No skill in the library was conformant. 41 of 175 failed the existing
validator outright, and none satisfied the spec. This pass fixes the
tree and records the result. See stdlib/CHANGELOG.md for the per-skill
versioning and migration notes.

BREAKING CHANGE: one skill removed, five moved, seven with a capability
withdrawn. Library version 2.0.0 -> 3.0.0.

Structure
- Convert 71 skills stored as flat files to <category>/<name>/SKILL.md,
  the layout the spec requires and the only one able to carry companion
  resources.
- Rename 5 directories that disagreed with their declared name:, so
  resolution by path and by name stop giving different answers. The
  repository docs already referenced the corrected paths.
- Merge the duplicate legal-technology skills into legaltech-expert and
  delete legal-tech-expert, carrying over everything the survivor
  lacked.

Metadata
- Repair 20 unparseable frontmatters: an H1 preceded the --- block and
  the key was skill_id: instead of name:, so any parser reading
  frontmatter at offset 0 saw no metadata at all. The objectives,
  prerequisites and outcome they carried become real body sections.
- Add the missing version: to 21 skills, fold keywords into tags, move
  expertise_level under metadata, and align 10 category: values with
  their directory.

Discoverability
- Give all 174 descriptions an explicit "Use when ..." trigger, built
  from each skill's own tags and section headings. 152 previously said
  only what the skill was about, leaving an agent nothing to match on.

Progressive disclosure
- Split 127 oversized skills, moving bulk material into references/ read
  on demand and leaving an index behind. A SKILL.md now averages 277
  lines instead of 644 and none exceeds 500. Verified lossless line by
  line against the previous revision.

Security
- Withdraw the unrestricted Bash(*) grant from 7 skills; none of the six
  non-financial ones contained a single shell command. finance-expert
  documents code that charges cards and reads bank accounts, so it now
  grants no shell at all.
- Remove credential literals: Stripe keys, two JWT signing keys, an
  Express session secret, a Redis password and WiFi credentials, all
  inlined in examples. They load from the environment now.
- finance-expert: idempotency keys were documented but absent, so a
  retry double-charged; webhook signature failures were not caught, so a
  forged event raised uncaught instead of being rejected;
  int(amount * 100) truncated fractions of a cent. All fixed, plus a
  money-movement guardrails section.
- trading-expert: place_order routed without any pre-trade risk check
  although a RiskManager sat unused in the next section. Risk validation
  now runs before routing and raises rather than returning a boolean a
  caller can ignore; live routing is opt-in.
- Correct an Ansible Vault example that showed plaintext under an
  "encrypted" label.

Also fixes 8 broken documentation links and a prematurely closed code
fence in skill-creator-expert that leaked template content into prose.

Per the repository file-organization policy, four stale progress reports
(SKILLS_MANIFEST, COMPLETE_SKILLS_LIBRARY, COMPLETE_LIBRARY_MANIFEST,
PHASE_3_DATA_ANALYTICS) move out of stdlib/ into the gitignored
.roadmap/status/stdlib/; they claimed 31 of 100 skills complete. They
appear here as deletions because .roadmap/ is not tracked.

Reviewed-by: Security Analyst, Language Designer, DevX Engineer,
             Documentation Specialist

* fix(skills): resolve standard library skills from their real layout

No stdlib skill was resolvable. SkillResolver looked for
`<stdlibDir>/<name>.md` with stdlibDir defaulting to `stdlib/skills`, a
directory that does not exist, and the path ignored the category level
the library actually uses. The two LSP providers had the same wrong
directory and scanned only one level deep, so neither completion nor
go-to-definition could see a skill either.

- skill-discovery.ts: enumerate skill entry points across the shapes in
  use - a flat `<name>.md`, `<name>/SKILL.md`, and
  `<category>/<name>/SKILL.md` - while skipping references/, scripts/
  and assets/, which hold supporting material rather than entry points.
- skill-resolver.ts: point stdlibDir at `stdlib`, and look the name up
  as a directory under any category as well as the two legacy shapes, so
  existing custom stdlib directories keep working. The name is used as a
  single path segment and rejected if it contains a separator or
  traversal, so a reference cannot escape the stdlib root.
- Rewire both LSP providers onto the shared discovery helper.

Tests: 13 new cases covering the layouts, ordering, the references/
exclusion, path-traversal rejection, and an integration test that
resolves real shipped skills by bare name.

Reviewed-by: Compiler Engineer, Runtime Architect, Security Analyst

* feat(stdlib): add 17 skills covering the library's largest gaps

Selection was driven by cross-referencing coverage against observed usage
rather than by intuition: Stack Overflow and GitHub Octoverse data for
which technologies matter, and install rankings on public agent-skill
registries for the shape of skills people actually use.

That comparison found a mismatch of form, not only of coverage. The
most-installed skills in the ecosystem are procedures - tdd, refactoring,
frontend design, browser automation - while all 174 existing skills were
domain knowledge shaped as <domain>-expert. The new workflows/ category
closes that gap and introduces the <activity>-workflow convention.

New category workflows/ (4)
- tdd-workflow, refactoring-workflow, debugging-workflow,
  code-review-workflow. code-review-workflow complements rather than
  replaces code-review-expert: procedure versus judgement. Merge them if
  the split proves confusing in use.

Applied AI (3) - the largest coverage gap
- llm-engineering-expert, rag-expert, agent-engineering-expert.
  The library referenced LLMs in tags but covered none of it: pgvector
  appeared zero times across 174 skills, LangChain once, MCP twice
  despite the repository shipping an MCP integration guide.

Capabilities (2)
- document-processing-expert (PDF, DOCX, XLSX, PPTX in one skill),
  browser-automation-expert (a client against third-party sites,
  distinct from playwright-expert which tests your own application).

Data (3)
- mysql-expert, the second most used database and previously absent
  while rarer stores had skills; analytical-databases-expert;
  stream-processing-expert.

Security (3)
- secrets-management-expert, supply-chain-security-expert (OWASP A03
  2025), identity-access-expert (OWASP A01).

Interface and meta (2)
- accessibility-expert: design/ held only design-expert, which despite
  its name covers software architecture, so WCAG had no home.
- skill-router: find and compose skills across 191, with a
  disambiguation table for overlapping pairs.

Grouping by decision context rather than by technology keeps the growth
to 17 skills for roughly 50 topics. Five vector stores live inside
rag-expert; four document formats inside document-processing-expert.
Per-tool depth sits in references/, which the progressive-disclosure work
in 3.0.0 made cheap.

Four further gaps are better served by extending existing skills -
PyTorch and TensorFlow in ml-expert, OpenTelemetry in monitoring-expert,
Pulumi and Crossplane in terraform-expert - and are not in this change.

Library 3.0.0 -> 3.1.0, additive only. Adds the workflows label to the
inventory generator; catalogue, inventory, structure and CHANGELOG
regenerated.

Reviewed-by: Product Strategist, Security Analyst, DevX Engineer,
             Documentation Specialist

* fix(test): create test directories with mkdtempSync

CodeQL flagged js/insecure-temporary-file (CWE-377) on both suites.
`join(tmpdir(), <predictable name>)` followed by mkdirSync creates a
world-readable directory at a guessable path, so another local user can
pre-create it or plant a symlink between the name being computed and the
directory being created.

mkdtempSync creates the directory atomically with a random suffix and
0700 permissions, which closes both the disclosure and the race.

One occurrence is new in this branch (skill-discovery); the other
pre-dates it in skill-resolver and is fixed in the same pass rather than
left as a known finding in a file this branch already touches.
2026-09-05 04:35:30 +02:00

14 KiB

name, version, description, category, tags, allowed-tools
name version description category tags allowed-tools
finance-expert 2.0.0 Expert-level financial systems, FinTech, banking, payments, and financial technology. Use when the user mentions fintech, banking, payments, trading, or accounting, or when the task involves Financial Systems, FinTech Stack, Key Challenges, or Data Handling. domains
finance
fintech
banking
payments
trading
accounting
Read
Write
Edit

Finance Expert

Expert guidance for financial systems, FinTech applications, banking platforms, payment processing, and financial technology development.

Core Concepts

Financial Systems

  • Core banking systems
  • Payment processing
  • Trading platforms
  • Risk management
  • Regulatory compliance (PCI-DSS, SOX, Basel III)
  • Financial reporting

FinTech Stack

  • Payment gateways (Stripe, PayPal, Square)
  • Banking APIs (Plaid, Yodlee)
  • Blockchain/crypto
  • Open Banking APIs
  • Mobile banking
  • Digital wallets

Key Challenges

  • Security and fraud prevention
  • Real-time processing
  • High availability (99.999%)
  • Regulatory compliance
  • Data privacy
  • Transaction accuracy

Payment Processing

These examples move real money. Read Money movement guardrails before running any of them. Credentials come from the environment or a secrets manager, never from source.

# Payment gateway integration (Stripe)
import os
from decimal import Decimal, ROUND_HALF_UP

import stripe

# Never hardcode a key. Load it from the environment or a secrets manager, and
# fail closed if it is absent rather than falling back to a default.
stripe.api_key = os.environ["STRIPE_API_KEY"]
WEBHOOK_SECRET = os.environ["STRIPE_WEBHOOK_SECRET"]


def to_minor_units(amount: Decimal) -> int:
    """Convert a decimal amount to integer minor units (cents).

    int(amount * 100) truncates: Decimal("0.615") would silently become 61
    instead of 62. Money must round explicitly, half-up, and only from Decimal
    - never from float.
    """
    if not isinstance(amount, Decimal):
        raise TypeError("monetary amounts must be Decimal, not %s" % type(amount).__name__)
    if amount < 0:
        raise ValueError("amount must not be negative")
    return int((amount * 100).quantize(Decimal("1"), rounding=ROUND_HALF_UP))


class PaymentService:
    def create_payment_intent(
        self, amount: Decimal, order_id: str, idempotency_key: str, currency: str = "usd"
    ):
        """Create a payment intent.

        The idempotency key is supplied by the caller and derived from the
        order, so a retried request cannot charge the customer twice. Stripe
        replays the original response instead of creating a second intent.
        """
        return stripe.PaymentIntent.create(
            amount=to_minor_units(amount),
            currency=currency,
            payment_method_types=["card"],
            metadata={"order_id": order_id},
            idempotency_key=idempotency_key,
        )

    def process_refund(
        self, payment_intent_id: str, idempotency_key: str, amount: Decimal | None = None
    ):
        """Process a full or partial refund (idempotent, like the charge)."""
        return stripe.Refund.create(
            payment_intent=payment_intent_id,
            amount=to_minor_units(amount) if amount is not None else None,
            idempotency_key=idempotency_key,
        )

    def handle_webhook(self, payload: bytes, signature: str):
        """Handle a Stripe webhook event.

        Signature verification is authentication: a failure must be rejected,
        never treated as a malformed payload. Returning 2xx on an unverified
        event tells Stripe the forged event was accepted.
        """
        try:
            event = stripe.Webhook.construct_event(payload, signature, WEBHOOK_SECRET)
        except stripe.error.SignatureVerificationError:
            # Forged or replayed event - fail closed, log, do not process.
            return {"status": "rejected"}, 400
        except ValueError:
            return {"status": "invalid_payload"}, 400

        # Webhooks are delivered at least once: deduplicate on event.id before
        # acting, or the same payment is booked twice.
        if self.already_processed(event.id):
            return {"status": "duplicate"}, 200

        if event.type == "payment_intent.succeeded":
            self.handle_successful_payment(event.data.object)
        elif event.type == "payment_intent.payment_failed":
            self.handle_failed_payment(event.data.object)

        self.mark_processed(event.id)
        return {"status": "success"}, 200

Banking Integration

# Open Banking API integration (Plaid)
import os

from plaid import Client
from plaid.errors import PlaidError

class BankingService:
    def __init__(self):
        # Credentials from the environment; sandbox unless the deployment
        # explicitly opts into production.
        self.client = Client(
            client_id=os.environ["PLAID_CLIENT_ID"],
            secret=os.environ["PLAID_SECRET"],
            environment=os.environ.get("PLAID_ENV", "sandbox"),
        )

    def create_link_token(self, user_id: str):
        """Create link token for Plaid Link"""
        response = self.client.LinkToken.create({
            "user": {"client_user_id": user_id},
            "client_name": "My App",
            "products": ["auth", "transactions"],
            "country_codes": ["US"],
            "language": "en"
        })
        return response["link_token"]

    def exchange_public_token(self, public_token: str):
        """Exchange a public token for an access token.

        The returned access token is a long-lived credential granting read
        access to the user's bank accounts. Store it encrypted, scoped to the
        user, never in logs, and revoke it when the user disconnects.
        """
        response = self.client.Item.public_token.exchange(public_token)
        return {
            "access_token": response["access_token"],
            "item_id": response["item_id"]
        }

    def get_accounts(self, access_token: str):
        """Get user's bank accounts"""
        response = self.client.Accounts.get(access_token)
        return response["accounts"]

    def get_transactions(self, access_token: str, start_date: str, end_date: str):
        """Get transactions for date range"""
        response = self.client.Transactions.get(
            access_token,
            start_date,
            end_date
        )
        return response["transactions"]

Financial Calculations

from decimal import Decimal, ROUND_HALF_UP
from datetime import datetime, timedelta

class FinancialCalculator:
    @staticmethod
    def calculate_interest(principal: Decimal, rate: Decimal, periods: int) -> Decimal:
        """Calculate compound interest"""
        return principal * ((1 + rate) ** periods - 1)

    @staticmethod
    def calculate_loan_payment(principal: Decimal, annual_rate: Decimal, months: int) -> Decimal:
        """Calculate monthly loan payment (amortization)"""
        monthly_rate = annual_rate / 12
        payment = principal * (monthly_rate * (1 + monthly_rate) ** months) / \
                  ((1 + monthly_rate) ** months - 1)
        return payment.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)

    @staticmethod
    def calculate_npv(cash_flows: list[Decimal], discount_rate: Decimal) -> Decimal:
        """Calculate Net Present Value"""
        npv = Decimal('0')
        for i, cf in enumerate(cash_flows):
            npv += cf / ((1 + discount_rate) ** i)
        return npv.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)

    @staticmethod
    def calculate_roi(gain: Decimal, cost: Decimal) -> Decimal:
        """Calculate Return on Investment"""
        return ((gain - cost) / cost * 100).quantize(Decimal('0.01'))

Fraud Detection

from sklearn.ensemble import RandomForestClassifier
import pandas as pd

class FraudDetectionService:
    def __init__(self):
        self.model = RandomForestClassifier()

    def extract_features(self, transaction: dict) -> dict:
        """Extract features for fraud detection"""
        return {
            "amount": transaction["amount"],
            "hour_of_day": transaction["timestamp"].hour,
            "day_of_week": transaction["timestamp"].weekday(),
            "merchant_category": transaction["merchant_category"],
            "is_international": transaction["is_international"],
            "card_present": transaction["card_present"],
            "transaction_velocity_1h": self.get_velocity(transaction, hours=1),
            "transaction_velocity_24h": self.get_velocity(transaction, hours=24)
        }

    def predict_fraud(self, transaction: dict) -> dict:
        """Predict if transaction is fraudulent"""
        features = self.extract_features(transaction)
        fraud_probability = self.model.predict_proba([features])[0][1]

        return {
            "is_fraud": fraud_probability > 0.8,
            "fraud_score": fraud_probability,
            "risk_level": self.get_risk_level(fraud_probability)
        }

    def get_risk_level(self, score: float) -> str:
        if score > 0.9:
            return "CRITICAL"
        elif score > 0.7:
            return "HIGH"
        elif score > 0.5:
            return "MEDIUM"
        else:
            return "LOW"

Regulatory Compliance

# PCI-DSS Compliance
class PCICompliantPaymentHandler:
    def process_payment(self, card_data: dict):
        # Never store full card number, CVV, or PIN
        # Tokenize card data immediately
        token = self.tokenize_card(card_data)

        # Store only last 4 digits and token
        payment_record = {
            "token": token,
            "last_4": card_data["number"][-4:],
            "exp_month": card_data["exp_month"],
            "exp_year": card_data["exp_year"]
        }

        return self.process_with_token(token)

    def tokenize_card(self, card_data: dict) -> str:
        # Use payment gateway tokenization
        return stripe.Token.create(card=card_data)["id"]

# KYC/AML Compliance
class ComplianceService:
    def verify_customer(self, customer_data: dict) -> dict:
        """Perform KYC verification"""
        # Identity verification
        identity_verified = self.verify_identity(customer_data)

        # Sanctions screening
        sanctions_clear = self.screen_sanctions(customer_data)

        # Risk assessment
        risk_level = self.assess_risk(customer_data)

        return {
            "verified": identity_verified and sanctions_clear,
            "risk_level": risk_level,
            "requires_manual_review": risk_level == "HIGH"
        }

Money movement guardrails

This skill documents code that charges cards, issues refunds, and reads bank accounts. Treat every such call as an irreversible side effect and gate it accordingly. A Snyk audit classifies this capability as W009 (direct money access); these are the controls that make it acceptable.

Credentials

  • Load keys from a secrets manager or the environment; never inline, never in version control, never in logs or error messages.
  • Use restricted keys with the narrowest scope the operation needs. A service that only creates charges must not hold a key that can issue payouts.
  • Rotate on a schedule and on any suspected exposure; keep test and live keys in separate accounts so a misconfiguration cannot reach production funds.

Default to test mode

  • Point at Stripe test keys and the Plaid sandbox unless the deployment has explicitly opted into production. Make the production switch a deliberate, reviewed configuration change, not a default.
  • Fail closed when the environment is ambiguous rather than guessing.

Authorisation before execution

  • Require an explicit human approval step for any operation that moves money, including refunds. An agent must not be able to complete a charge on its own initiative.
  • Enforce per-transaction and per-window amount limits, and reject anything above them rather than clamping silently.
  • Check authorisation per object, not per route: verify the caller owns the order, the payment intent, and the bank item being acted on.

Correctness under retry

  • Every mutating call carries a caller-supplied idempotency key derived from the business action, so a retry cannot double-charge.
  • Webhooks are delivered at least once: deduplicate on event id before acting.
  • Verify webhook signatures and reject failures with 4xx. An unverified event must never reach business logic.

Money arithmetic

  • Represent amounts as Decimal or integer minor units, never float.
  • Round explicitly (ROUND_HALF_UP) when converting to minor units; truncation loses fractions of a cent and the loss compounds.
  • Store the currency alongside every amount and refuse cross-currency arithmetic.

Audit and detection

  • Log every financial operation with actor, amount, currency, idempotency key, and outcome, to append-only storage. Never log card data, access tokens, or full account numbers.
  • Alert on refund spikes, repeated failures, and limit rejections; a log that triggers nothing protects nothing.
  • Reconcile against the provider's records on a schedule; do not treat your own database as the source of truth for money that moved.

Best Practices

Security

  • Never log sensitive financial data (PAN, CVV)
  • Use tokenization for card storage
  • Implement strong encryption (AES-256)
  • Use TLS 1.2+ for all communications
  • Implement rate limiting and fraud detection
  • Regular security audits

Data Handling

  • Use Decimal type for money (never float)
  • Store amounts in smallest currency unit (cents)
  • Implement idempotency for all transactions
  • Maintain complete audit trails
  • Handle timezone conversions properly

Transaction Processing

  • Implement two-phase commits
  • Use database transactions (ACID)
  • Handle network failures gracefully
  • Implement retry logic with exponential backoff
  • Support transaction reversals and refunds

Anti-Patterns

❌ Using float for money calculations ❌ Storing credit card data unencrypted ❌ No transaction logging/audit trail ❌ Synchronous payment processing ❌ No idempotency in payment APIs ❌ Ignoring PCI-DSS compliance ❌ No fraud detection

Resources