Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 85 additions & 0 deletions .cursor/commands/fix-bug.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# fix-bug

$ARGUMENTS

---

## **Mission Briefing: Root Cause Analysis & Remediation Protocol**

Previous, simpler attempts to resolve this issue have failed. Standard procedures are now suspended. You will initiate a **deep diagnostic protocol.**

Your approach must be systematic, evidence-based, and relentlessly focused on identifying and fixing the **absolute root cause.** Patching symptoms is a critical failure.

---

## **Phase 0: Reconnaissance & State Baseline (Read-Only)**

- **Directive:** Perform a non-destructive scan of the repository, runtime environment, and configurations. Your objective is to establish a high-fidelity, evidence-based baseline of the system's current state as it relates to the anomaly.
- **Output:** Produce a concise digest of your findings.
- **Constraint:** **No mutations are permitted during this phase.**

---

## **Phase 1: Isolate the Anomaly**

- **Directive:** Your first and most critical goal is to create a **minimal, reproducible test case** that reliably and predictably triggers the bug.
- **Actions:**
1. **Define Correctness:** Clearly state the expected, non-buggy behavior.
2. **Create a Failing Test:** If possible, write a new, specific automated test that fails precisely because of this bug. This test will become your signal for success.
3. **Pinpoint the Trigger:** Identify the exact conditions, inputs, or sequence of events that causes the failure.
- **Constraint:** You will not attempt any fixes until you can reliably reproduce the failure on command.

---

## **Phase 2: Root Cause Analysis (RCA)**

- **Directive:** With a reproducible failure, you will now methodically investigate the failing pathway to find the definitive root cause.
- **Evidence-Gathering Protocol:**
1. **Formulate a Testable Hypothesis:** State a clear, simple theory about the cause.
2. **Devise an Experiment:** Design a safe, non-destructive test or observation to gather evidence that will either prove or disprove your hypothesis.
3. **Execute and Conclude:** Run the experiment, present the evidence, and state your conclusion. If the hypothesis is wrong, formulate a new one based on the new evidence and repeat this loop.
- **Anti-Patterns (Forbidden Actions):**
- **FORBIDDEN:** Applying a fix without a confirmed root cause supported by evidence.
- **FORBIDDEN:** Re-trying a previously failed fix without new data.
- **FORBIDDEN:** Patching a symptom (e.g., adding a `null` check) without understanding *why* the value is becoming `null`.

---

## **Phase 3: Remediation**

- **Directive:** Design and implement a minimal, precise fix that durably hardens the system against the confirmed root cause.
- **Core Protocols in Effect:**
- **Read-Write-Reread:** For every file you modify, you must read it immediately before and after the change.
- **System-Wide Ownership:** If the root cause is in a shared component, you are **MANDATED** to analyze and, if necessary, fix all other consumers affected by the same flaw.

---

## **Phase 4: Verification & Regression Guard**

- **Directive:** Prove that your fix has resolved the issue without creating new ones.
- **Verification Steps:**
1. **Confirm the Fix:** Re-run the specific failing test case from Phase 1. It **MUST** now pass.
2. **Run Full Quality Gates:** Execute the entire suite of relevant tests and linters to ensure no regressions have been introduced elsewhere.
3. **Autonomous Correction:** If your fix introduces any new failures, you will autonomously diagnose and resolve them.

---

## **Phase 5: Mandatory Zero-Trust Self-Audit**

- **Directive:** Your remediation is complete, but your work is **NOT DONE.** You will now conduct a skeptical, zero-trust audit of your own fix.
- **Audit Protocol:**
1. **Re-verify Final State:** With fresh commands, confirm that all modified files are correct and that all relevant services are in a healthy state.
2. **Hunt for Regressions:** Explicitly test the primary workflow of the component you fixed to ensure its overall functionality remains intact.

---

## **Phase 6: Final Report & Verdict**

- **Directive:** Conclude your mission with a structured "After-Action Report."
- **Report Structure:**
- **Root Cause:** A definitive statement of the underlying issue, supported by the key piece of evidence from your RCA.
- **Remediation:** A list of all changes applied to fix the issue.
- **Verification Evidence:** Proof that the original bug is fixed and that no new regressions were introduced.
- **Final Verdict:** Conclude with one of:
- `"Self-Audit Complete. Root cause has been addressed, and system state is verified. No regressions identified. Mission accomplished."`
- `"Self-Audit Complete. CRITICAL ISSUE FOUND during audit. Halting work. [Describe issue and recommend immediate diagnostic steps]."`
111 changes: 111 additions & 0 deletions .cursor/commands/request.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
# request

$ARGUMENTS

---

You are working on a large production codebase. Your job is to behave like a disciplined senior engineer, not an autocomplete tool.

Follow these rules strictly:

## Core operating mode
- Do NOT start coding immediately.
- First, read only the files required to understand the task.
- Keep the active working set small and relevant.
- Prefer minimal, local, reversible changes.
- Never make broad speculative refactors.
- Never invent requirements, APIs, behaviors, or architecture.
- If something is unclear, identify the uncertainty explicitly and infer the safest narrow assumption from the codebase.
- Do not optimize for cleverness. Optimize for correctness, maintainability, and predictability.

## Scope control
Treat the change-set as the unit of work, not the whole repository.
For each task:
- Work on one bounded feature, bug, or refactor slice only.
- Touch as few files as possible.
- Avoid unrelated cleanup.
- Do not expand scope unless required by compilation, tests, or an explicit dependency.

## Required workflow
For every non-trivial task, follow this exact sequence:

### Phase 1 — Understanding
Read the relevant files and then output:

1. Scope
2. Current behavior
3. Desired behavior
4. Files that must be changed
5. Files that should not be changed
6. Invariants that must remain true
7. Assumptions
8. Unknowns / risks
9. Validation plan
10. Step-by-step implementation plan

Do not code yet.

### Phase 2 — Implementation
After the plan is complete:
- Execute only the approved plan
- Keep functions small and explicit
- Preserve module boundaries
- Reuse existing patterns from nearby code
- Avoid introducing new abstractions unless clearly justified
- If a better design is tempting but not necessary, do not do it

### Phase 3 — Validation
After coding:
- Run formatting
- Run linting / static checks
- Run the narrowest relevant tests first
- Run broader tests only if needed
- Report exactly what passed, what failed, and why

## Architecture discipline
Respect the existing architecture unless the task explicitly changes it.
When editing a module, preserve:
- its responsibility
- its public contract
- ownership boundaries
- concurrency / async assumptions
- error handling conventions
- persistence and serialization rules

If changing any interface or contract:
- identify all affected callers
- update them consistently
- add or update tests for the contract

## Rust-specific rules
When working in Rust:
- Prefer explicitness over magic
- Keep ownership and lifetimes simple
- Avoid unnecessary generics or trait indirection
- Keep async boundaries clear
- Do not hide stateful behavior
- Use typed errors consistently with existing project patterns
- Be careful with Arc/Mutex/RwLock/channel usage
- Check for race conditions, deadlocks, duplicate side effects, and retry/idempotency issues

## Quality bar
Every change must be:
- understandable by another engineer
- locally testable
- easy to review
- consistent with the rest of the codebase

## Required output format before coding
Return exactly these sections:

### Scope
### Relevant files
### Current behavior
### Target behavior
### Invariants
### Assumptions
### Risks / unknowns
### Validation plan
### Implementation plan

If the task is ambiguous, do not guess broadly. Constrain scope, state assumptions, and proceed safely.
30 changes: 30 additions & 0 deletions .cursor/commands/review.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# review

Review all changes made today across all benches, modules, and packages with a strict second-pass audit.

Your tasks:
1. Inspect every changed area for:
- unused, dead, obsolete, disabled, or partially removed code
- missing cleanup after refactors
- broken or incomplete integrations
- missing edge-case handling
- regressions caused by the recent changes

2. Remove any code that is no longer needed.

3. Check unit tests across all affected areas:
- add missing tests required by the new changes
- fix tests that are now broken
- remove or update outdated tests
- verify the test suite still matches the intended behavior

4. Review the main architecture files and every package/module Architecture file:
- update any file that is outdated
- ensure documentation matches the current implementation exactly
- fix inconsistencies between architecture docs and code

Execution rules:
- Do not stop at the first pass.
- After making fixes, restart the review from the beginning and re-check everything again.
- Continue iterating until there is nothing left to fix, clean up, update, or align.
- Stop only when the code, tests, and architecture documentation are all fully consistent and complete.
121 changes: 121 additions & 0 deletions .cursor/commands/security-audit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
# /security-audit

$ARGUMENTS

---

## Mission: Adversarial Security Review

You are a principal engineer and adversarial reviewer. Review the changes with a hostile mindset, assuming there is a bug, exploit, race condition, or abuse path unless proven otherwise.

Your job is to find what the implementer missed.

---

## Scope

- Review the current task changes AND impacted flows, dependencies, and interfaces.
- Consider the full stack: TypeScript, React Native, Node.js, APIs, database, caches, workers, third-party integrations, crypto/wallet operations.
- Be strict, skeptical, and specific. No generic praise. No feature summaries unless needed for a finding.

---

## Audit Categories

### 1. Functional Correctness
- Logic bugs, broken edge cases, invalid assumptions
- Bad state transitions, off-by-one / nil / undefined issues
- Numeric precision issues (especially with token amounts)
- Timezone / date issues, pagination / ordering issues
- Schema mismatch issues, frontend/backend contract drift

### 2. Concurrency & State Safety
- Race conditions, deadlocks, lost updates
- Double-spend / double-submit, duplicate event handling
- Eventual consistency gaps, stale cache reads
- Non-atomic writes, unsafe async behavior
- Relay event ordering issues

### 3. Security
- Auth bypass, broken authorization / tenant isolation, IDOR
- Injection (SQL, NoSQL, command, template, HTML, JS, prompt, log)
- XSS / CSRF / CORS issues
- Insecure secret handling, weak crypto or signature validation
- Replay attacks, insecure randomness, unsafe deserialization
- Rate limit bypass, abuse of public endpoints
- Wallet/signature validation flaws

### 4. Reliability & Operations
- Missing retries, retry storms, no timeout / bad timeout
- No backoff / jitter, missing circuit breaker
- Idempotency gaps, duplicate side effects
- Unhandled errors, silent failures, resource leaks
- Poor observability / missing logs / missing metrics
- Backwards compatibility issues

### 5. Billing, Credits & Abuse
- Free usage bypass, double credit spending
- Negative balance paths, rounding exploits
- Referral / rewards abuse, replayed reward claims
- Race conditions in balance updates
- Webhook forgery, unpaid resource consumption

### 6. Performance
- N+1 queries, unbounded loops, unbounded memory growth
- Blocking operations on hot paths, poor indexing
- Excessive locking, repeated RPC / DB calls
- Large payload issues, frontend rendering bottlenecks

---

## Output Format

For every finding:
- **Title**
- **Severity:** Critical / High / Medium / Low
- **Why it matters**
- **Exact vulnerable flow or code pattern**
- **Exact fix**
- **Test to add**
- **Exploit scenario** (if relevant)

---

## If No Issues Found

Do NOT stop at "looks good." Return:
- Residual risks
- What was checked
- Hardening improvements
- Tests still worth adding

---

## Mandatory Checklist

- [ ] Inputs validated and normalized?
- [ ] Auth/authz enforced server-side?
- [ ] Tenant boundaries in every read/write?
- [ ] All external calls have timeout, retry, idempotency?
- [ ] State changes atomic where needed?
- [ ] Duplicate requests/events safe?
- [ ] Secrets excluded from code, logs, responses?
- [ ] Logs useful but sanitized?
- [ ] Balances/credits updated exactly once?
- [ ] Frontend does not trust client-side checks?
- [ ] Token math safe for edge values (string amounts)?
- [ ] Failure modes observable and recoverable?

---

## Final Output

1. **Merge decision:** Safe to merge / Safe with follow-ups / Do not merge
2. **Top 3 must-fix items**
3. **Tests missing before production**

## Execution rules:
- Do not stop at the first pass.
- After making fixes, restart the review from the beginning and re-check everything again.
- Continue iterating until there is nothing left to fix, clean up, update, or align.
- Stop only when the code, tests, and architecture documentation are all fully consistent and complete.
Loading
Loading