{
  "master": {
    "tasks": [
      {
        "id": "1",
        "title": "Stabilize Mermaid diagram rendering across documentation vault",
        "description": "Correct Mermaid syntax/rendering issues across the documentation vault and validate all Mermaid blocks.",
        "details": "Source PRD: .taskmaster/docs/prd-mermaid-diagram-rendering-stabilization.md. Scope covered 57 Mermaid blocks and 11 failing blocks. The source PRD records that all targeted files now pass mmdc parse validation and the full vault sweep passes.",
        "testStrategy": "Run the same mmdc-based syntax validation across all Markdown Mermaid blocks and confirm zero parser failures in Obsidian/markdown previews.",
        "priority": "medium",
        "status": "done",
        "dependencies": [],
        "subtasks": [
          {
            "id": 1,
            "title": "Fix Security Architecture email/password sequence",
            "description": "Normalize parser-sensitive sequence text in 01 - Architecture/Security Architecture.md.",
            "details": "Avoid semicolons and ambiguous inline punctuation in sequence messages.",
            "status": "done",
            "priority": "medium",
            "dependencies": [],
            "testStrategy": "mmdc parse for the specific block.",
            "parentId": "undefined"
          },
          {
            "id": 2,
            "title": "Fix authentication login and refresh diagrams",
            "description": "Normalize parser-sensitive token and refresh-token sequence text in Authentication Flow.",
            "details": "Split method-like or expression-like message text into parser-safe plain text lines.",
            "status": "done",
            "priority": "medium",
            "dependencies": [],
            "testStrategy": "mmdc parse for both Authentication Flow blocks.",
            "parentId": "undefined"
          },
          {
            "id": 3,
            "title": "Fix chat, delivery, dispute, OAuth, purchase request, referral, registration, and seller-offer diagrams",
            "description": "Clean the remaining Mermaid sequence diagrams with invalid or ambiguous syntax.",
            "details": "Split multi-recipient arrows, remove parser-conflicting semicolon/expression text, and keep intent unchanged.",
            "status": "done",
            "priority": "medium",
            "dependencies": [],
            "testStrategy": "Full vault mmdc parser sweep across all Mermaid blocks.",
            "parentId": "undefined"
          }
        ]
      },
      {
        "id": "2",
        "title": "Implement platform audit remediation plan",
        "description": "Address the code-backed security and consistency issues identified in the 2026-05-24 platform audit remediation PRD.",
        "details": "Source PRD: .taskmaster/docs/prd-platform-audit-remediation-plan-2026-05-24.md. Target backend hardening first, then documentation/runtime alignment. Delivery order suggested by PRD: security/auth, rate limiting, passkeys, Web3 verification, socket hardening, dispute hold controls, docs/API alignment.",
        "testStrategy": "Add focused regression tests for route auth/ownership, passkey challenge/verification, Web3 verification semantics, socket authorization, rate limiting tiers, and payout/release dispute holds. Update API docs after behavior is implemented.",
        "priority": "high",
        "status": "done",
        "dependencies": [],
        "subtasks": [
          {
            "id": 1,
            "title": "Secure unauthenticated endpoints and owner enforcement",
            "description": "Require authenticateToken and owner/admin checks on exposed payment, AI, and legacy notification routes.",
            "details": "Derive notification userId from authenticated principal. Protect payment history and mutation endpoints. Restrict AI calls to authenticated users with per-user budgets. Add denied-access audit logs.",
            "status": "done",
            "priority": "high",
            "dependencies": [],
            "testStrategy": "Unauthorized callers receive 401/403; users cannot access or mutate other users' payments/notifications; admins retain authorized access.",
            "parentId": "undefined"
          },
          {
            "id": 2,
            "title": "Re-enable and scope rate limiting",
            "description": "Restore global and route-tiered rate limits for public-sensitive paths.",
            "details": "Use stricter limits for auth, financial, AI, file upload, and verification paths. Keep public reads at relaxed limits. Add observability for 429 spikes.",
            "status": "done",
            "priority": "high",
            "dependencies": [
              1
            ],
            "testStrategy": "Exercise configured limits per tier and confirm expected 429 responses without blocking ordinary reads.",
            "parentId": "undefined"
          },
          {
            "id": 3,
            "title": "Replace stubbed passkey/WebAuthn flow",
            "description": "Implement production-grade WebAuthn registration/authentication and shared challenge storage.",
            "details": "Use real attestation/assertion verification, Redis-backed TTL challenges, refresh-token persistence/rotation, and deterministic malformed/reused/expired challenge errors.",
            "status": "done",
            "priority": "high",
            "dependencies": [
              1
            ],
            "testStrategy": "Registration, login, replay, expired challenge, and refresh-token continuity tests pass.",
            "parentId": "undefined"
          },
          {
            "id": 4,
            "title": "Strengthen DePay/Web3 payment verification",
            "description": "Verify transaction recipient, token contract, and amount, not only receipt success.",
            "details": "Decode ERC-20 Transfer logs, compare recipient against escrow address, validate token contract and decimals-adjusted minimum amount, store verifier evidence and idempotency fingerprint.",
            "status": "done",
            "priority": "high",
            "dependencies": [
              1
            ],
            "testStrategy": "Reject successful but wrong-recipient/wrong-token/underpaid tx hashes; accept only matching transfers.",
            "parentId": "undefined"
          },
          {
            "id": 5,
            "title": "Lock Socket.IO room joins to authenticated context",
            "description": "Remove trust in client-supplied user/buyer/seller room IDs.",
            "details": "Validate socket handshake token, derive server-side room membership, reject mismatched joins, and monitor suspicious join attempts.",
            "status": "done",
            "priority": "medium",
            "dependencies": [
              1
            ],
            "testStrategy": "A user cannot subscribe to another user's rooms; legitimate realtime notifications still arrive.",
            "parentId": "undefined"
          },
          {
            "id": 6,
            "title": "Enforce dispute hold before payout and release operations",
            "description": "Add payment hold state and central release/refund guards that block disputed funds.",
            "details": "Introduce explicit dispute hold fields or state, enforce in PaymentCoordinator and payout/release services, return clear 409/423 responses, and backfill/report blocked payments.",
            "status": "done",
            "priority": "medium",
            "dependencies": [
              1,
              4
            ],
            "testStrategy": "Open dispute blocks release/refund until resolved or explicitly overridden through authorized path.",
            "parentId": "undefined"
          },
          {
            "id": 7,
            "title": "Align documentation, API references, and runtime enums",
            "description": "Normalize disputed/payment/request status docs and implementation references after security behavior changes.",
            "details": "Resolve mismatch around absent dispute module, endpoint names, status enums, and action names across Data Models, API Reference, and Flows.",
            "status": "done",
            "priority": "medium",
            "dependencies": [
              1,
              2,
              3,
              4,
              5,
              6
            ],
            "testStrategy": "Docs match implemented routes, models, enum values, and state transitions.",
            "parentId": "undefined"
          }
        ]
      },
      {
        "id": "3",
        "title": "Migrate payment architecture toward Request Network and internal funds management",
        "description": "Plan and implement provider-neutral payment flows, Request Network pay-in support, funds ledger, webhook reconciliation, release/refund orchestration, UI migration, and SHKeeper decommissioning.",
        "details": "Source PRD: .taskmaster/docs/prd-request-network-migration-and-funds-management.md. The PRD recommends phased migration behind a provider adapter, Secure Payment Pages first, platform-controlled escrow/payee destination, and a first-class internal funds ledger before release/refund enforcement.\n\nPost-completion update: Task 3 now includes a CI-safe focused verification command for the provider-neutral payment migration plus optional Trezor safekeeping. Trezor safekeeping is optional by default via TREZOR_SAFEKEEPING_REQUIRED=false and only gates release/refund confirmation when explicitly enabled. Vault references: 04 - Flows/Trezor Safekeeping Flow.md, 03 - API Reference/Trezor API.md, and 08 - Operations/Payment and Trezor Verification Report.md.",
        "testStrategy": "Use feature flags, provider fixture tests, webhook signature/idempotency tests, ledger invariant tests, migration dry-run reports, and limited cohort rollout before default provider switch.\n\nFocused verification command: npm test -- __tests__/payment-adapter-registry.test.ts __tests__/request-network-adapter.test.ts __tests__/request-network-payin.test.ts __tests__/request-network-webhook.test.ts __tests__/payment-ledger.model.test.ts __tests__/payment-ledger.service.test.ts __tests__/payment-migration.service.test.ts __tests__/payment-release-refund-orchestration.test.ts __tests__/payment-release-refund-routes.test.ts __tests__/payment-reconciliation.service.test.ts __tests__/payment-observability-redaction.test.ts __tests__/payment-observability-events.test.ts __tests__/trezor-safekeeping.service.test.ts --runInBand. Expected result: 13 suites, 64 tests passing. Also run npm run typecheck.",
        "priority": "high",
        "status": "done",
        "dependencies": [
          "2"
        ],
        "subtasks": [
          {
            "id": 1,
            "title": "Define provider-neutral payment contracts and adapter",
            "description": "Create provider-agnostic payment interface with pay-in, webhook, payout/refund instruction creation, status lookup, and search methods.",
            "details": "",
            "status": "done",
            "dependencies": [],
            "parentTaskId": 3,
            "parentId": "undefined",
            "updatedAt": "2026-05-24T06:24:49.217Z"
          },
          {
            "id": 2,
            "title": "Implement provider configuration, feature flags, and safe rollback",
            "description": "Add runtime provider selection, rollout controls, env validation, and one-command kill-switch to revert to SHKeeper.",
            "details": "",
            "status": "done",
            "dependencies": [
              "3.1"
            ],
            "parentTaskId": 3,
            "parentId": "undefined",
            "updatedAt": "2026-05-24T06:30:51.152Z"
          },
          {
            "id": 3,
            "title": "Create internal funds and payment ledger model",
            "description": "Define FundsAccount, immutable LedgerEntry, and balance/query views for expected/held/releasable/released/refunded/disputed states.",
            "details": "",
            "status": "done",
            "dependencies": [
              "3.1"
            ],
            "parentTaskId": 3,
            "parentId": "undefined",
            "updatedAt": "2026-05-24T06:30:52.613Z"
          },
          {
            "id": 4,
            "title": "Build migration and indexing plan for existing SHKeeper records",
            "description": "Add DB indexes for payment/provider fields and run backfill to produce a migration report with skipped/failed/ambiguous historical entries.",
            "details": "",
            "status": "done",
            "dependencies": [
              "3.3"
            ],
            "parentTaskId": 3,
            "parentId": "undefined",
            "updatedAt": "2026-05-24T06:34:59.429Z"
          },
          {
            "id": 5,
            "title": "Implement Request Network pay-in intent and secure payment pages",
            "description": "Add Request Network intent/service layer, secure payment URLs, and validation of network/currency/reference/amount before setting paid state.",
            "details": "",
            "status": "done",
            "dependencies": [
              "3.2"
            ],
            "parentTaskId": 3,
            "parentId": "undefined",
            "updatedAt": "2026-05-24T06:35:00.891Z"
          },
          {
            "id": 6,
            "title": "Implement signed Request Network webhook intake",
            "description": "Build /api/payment/request-network/webhook with raw-body signature verification, idempotent delivery handling, and immutable event audit rows.",
            "details": "",
            "status": "done",
            "dependencies": [
              "3.2"
            ],
            "parentTaskId": 3,
            "parentId": "undefined",
            "updatedAt": "2026-05-24T06:35:02.505Z"
          },
          {
            "id": 7,
            "title": "Implement reconciliation and repair jobs",
            "description": "Add periodic Request Network payment search/reconciliation and manual replay support to fix missed or delayed events.",
            "details": "",
            "status": "done",
            "dependencies": [
              "3.5",
              "3.6"
            ],
            "parentTaskId": 3,
            "parentId": "undefined",
            "updatedAt": "2026-05-24T06:44:46.205Z"
          },
          {
            "id": 8,
            "title": "Replace checkout and payment UI with provider-neutral flows",
            "description": "Introduce provider-neutral payment components, remove SHKeeper walletAddress assumptions for RN, and keep legacy path only for existing SHKeeper records.",
            "details": "",
            "status": "done",
            "dependencies": [
              "3.5"
            ],
            "parentTaskId": 3,
            "parentId": "undefined",
            "updatedAt": "2026-05-24T06:50:26.225Z"
          },
          {
            "id": 9,
            "title": "Add payout/release and refund orchestration using ledger gates",
            "description": "Create release/refund instruction queue with signer, tx payloads, provider tx hash, and strict ledger invariants before action.",
            "details": "",
            "status": "done",
            "dependencies": [
              "3.3",
              "3.7"
            ],
            "parentTaskId": 3,
            "parentId": "undefined",
            "updatedAt": "2026-05-24T06:50:55.916Z"
          },
          {
            "id": 10,
            "title": "Update release/refund APIs and marketplace release paths",
            "description": "Refactor release routes to consume ledger state and provider-neutral contracts; deprecate direct simulation where possible.",
            "details": "",
            "status": "done",
            "dependencies": [
              "3.8",
              "3.9"
            ],
            "parentTaskId": 3,
            "parentId": "undefined",
            "updatedAt": "2026-05-24T06:50:57.496Z"
          },
          {
            "id": 11,
            "title": "Add comprehensive observability, runbooks, and incident controls",
            "description": "Track webhook latency, ledger imbalance, release failures, and reconciliation lag with alerts, on-call runbooks, and rollback procedures.",
            "details": "",
            "status": "done",
            "dependencies": [
              "3.6",
              "3.8",
              "3.9",
              "3.10"
            ],
            "parentTaskId": 3,
            "parentId": "undefined",
            "updatedAt": "2026-05-24T06:50:59.050Z"
          },
          {
            "id": 12,
            "title": "Add end-to-end integration, migration, and rollback test suites",
            "description": "Cover backend contract tests, provider fixture tests, UI acceptance, rollout simulation, DRYRUN migration, and release rollback rehearsals.",
            "details": "",
            "status": "done",
            "dependencies": [
              "3.6",
              "3.10",
              "3.11"
            ],
            "parentTaskId": 3,
            "parentId": "undefined",
            "updatedAt": "2026-05-24T06:51:00.615Z"
          },
          {
            "id": 13,
            "title": "Add durable RN webhook ingress and transaction safety",
            "description": "Roadmap follow-up from the 2026-05-28 dev payment probe: Request Network delivered the webhook but Amanat returned 404. Add Cloudflare Worker durable webhook ingress with storage/replay and keep backend Transaction Safety Provider checks as the trust boundary before marking escrow funded.",
            "details": "",
            "status": "pending",
            "dependencies": [],
            "parentTaskId": 3,
            "parentId": "undefined"
          }
        ],
        "updatedAt": "2026-05-24T07:04:01.906Z"
      },
      {
        "id": "4",
        "title": "Define backend security and refactor strategy from latest audit",
        "description": "Convert the backend stack security/refactor assessment into concrete architecture decisions, documentation deliverables, and developer handoff criteria.",
        "details": "Source audit: .taskmaster/docs/audit-backend-stack-security-and-refactor-assessment-2026-05-24.md. This task is advisory/architecture-focused and should run in parallel with immediate hardening. It should produce the decision artifacts needed before any backend-core rewrite or provider migration is started.",
        "testStrategy": "Review and sign off each architecture document with backend, payments, frontend, and operations stakeholders. Confirm every open question has an owner or explicit deferred decision before implementation work begins.",
        "priority": "high",
        "status": "done",
        "dependencies": [],
        "subtasks": [
          {
            "id": 1,
            "title": "Assign security ownership and launch decision criteria",
            "description": "Define who owns security decisions and what must be true before public launch or migration work proceeds.",
            "details": "Completed. Produced 09 - Audits/Security Ownership and Launch Decision Criteria.md. Contains: RACI matrix (10 decision areas, 6 roles, fallback rules), 42-item launch safety gate checklist with Required/Strongly Recommended/Deferred classifications cross-referenced to audit findings, launch priority decision (harden first, redesign deferred), external pentest decision (yes, before public launch, with compensating controls), 12-item deferred decisions register with owners and deadlines.",
            "status": "done",
            "priority": "high",
            "dependencies": [],
            "testStrategy": "Written owner/RACI and launch gate checklist are accepted by leadership and engineering.",
            "parentId": "undefined",
            "updatedAt": "2026-05-24T06:43:01.505Z"
          },
          {
            "id": 2,
            "title": "Produce threat model for escrow platform",
            "description": "Document protected assets, actors, trust boundaries, and abuse cases for the financial marketplace.",
            "details": "Completed. Produced 09 - Audits/Threat Model - Amanat Escrow Platform.md. Contains: system description, 17 protected asset classes with sensitivity ratings, 11 actors with access levels and risk profiles, trust boundary diagram (Mermaid) with 10 boundary descriptions and current gaps, 23-threat catalog (T01-T23) with STRIDE categories and specific code-path references, risk summary matrix (6 Critical, 10 High, 6 Medium, 1 Low), threat-to-mitigation traceability matrix mapping 9 remediation docs to specific threats. Living document. Open verification items: Socket.IO room auth in socketService.ts, Telegram initData validation, actual lockfile versions for multer/axios/tanstack.",
            "status": "done",
            "priority": "high",
            "dependencies": [
              1
            ],
            "testStrategy": "Threat model maps each high-risk finding to at least one mitigation task or accepted risk.",
            "parentId": "undefined",
            "updatedAt": "2026-05-24T06:43:03.144Z"
          },
          {
            "id": 3,
            "title": "Specify funds ledger and escrow state machine",
            "description": "Define canonical money movement and legal state transitions before refactor or provider migration.",
            "details": "Create specs for FundsAccount, LedgerEntry, FundsBalance, gross paid, provider fees, platform fees, held, disputed, releasable, released, refunded, idempotency keys, reconciliation behavior, purchase request states, payment states, escrow/funds states, dispute states, valid transitions, forbidden transitions, and release/refund/admin override preconditions.",
            "status": "done",
            "priority": "high",
            "dependencies": [
              2
            ],
            "testStrategy": "Spec can be used to reject double-release, release-during-dispute, underfunded payout, and ambiguous provider-event scenarios.",
            "parentId": "undefined",
            "updatedAt": "2026-05-24T07:23:41.596Z"
          },
          {
            "id": 4,
            "title": "Create authorization matrix for REST and Socket.IO",
            "description": "Map every endpoint and realtime event to access level, ownership checks, state preconditions, rate-limit tier, and audit-log requirement.",
            "details": "Include public/authenticated/owner/buyer/seller/admin/support/service-role classifications. Socket.IO rooms must be server-derived from authenticated identity, not client-supplied user IDs.",
            "status": "done",
            "priority": "high",
            "dependencies": [
              2
            ],
            "testStrategy": "No route or socket event remains unmapped; implementation tasks can reference matrix rows directly.",
            "parentId": "undefined",
            "updatedAt": "2026-05-24T07:23:43.108Z"
          },
          {
            "id": 5,
            "title": "Decide session, passkey, and admin step-up architecture",
            "description": "Choose browser session model and high-risk admin authentication requirements.",
            "details": "Decide localStorage versus httpOnly cookies, access/refresh token lifetimes, CSRF strategy, refresh rotation, WebAuthn requirements, OAuth requirements, device/session revocation, and whether payouts/role changes require step-up authentication or two-person approval.",
            "status": "done",
            "priority": "high",
            "dependencies": [
              2
            ],
            "testStrategy": "Decision record lists chosen model, rejected alternatives, migration cost, and required implementation tasks.",
            "parentId": "undefined",
            "updatedAt": "2026-05-24T07:23:44.643Z"
          },
          {
            "id": 6,
            "title": "Specify webhook security and provider adapter contracts",
            "description": "Define provider-neutral payment interface and signed webhook processing rules.",
            "details": "Document createPayInIntent, getPayInStatus, handleProviderWebhook, createHostedPaymentLink, createReleaseInstruction, createRefundInstruction, getPayoutStatus, searchProviderPayments, raw-body signature verification, replay prevention, delivery ID idempotency, duplicate/unknown event behavior, retry semantics, dead-letter/replay storage, and alert thresholds.",
            "status": "done",
            "priority": "high",
            "dependencies": [
              3
            ],
            "testStrategy": "Contracts cover SHKeeper legacy, Request Network, manual/admin wallet, invalid signatures, duplicate deliveries, and missed webhook reconciliation.",
            "parentId": "undefined",
            "updatedAt": "2026-05-24T07:21:42.699Z"
          },
          {
            "id": 7,
            "title": "Define secure build and supply-chain policy",
            "description": "Reduce npm/dependency compromise risk across frontend and any remaining Node services.",
            "details": "Completed. Produced 09 - Audits/Secure Build and Supply-Chain Policy.md. 11 sections + 3 appendices: lockfile policy (npm ci mandatory), dependency update cadence (biweekly routine, immediate security-critical), advisory monitoring with SLAs (Critical 24h, High 72h, Medium 1 week), known exposure register with 5 open 2026 CVEs (multer, axios, tanstack, express, node) and SLA deadlines, npm provenance policy, secrets rotation schedule for all 10 secret types, production build reproducibility requirements, frontend vs backend risk separation with interim policy, incident response for 3 scenarios, CI/CD enforcement checklist with Gitea Actions YAML example.",
            "status": "done",
            "priority": "medium",
            "dependencies": [
              1
            ],
            "testStrategy": "Policy is actionable in CI and includes response steps for compromised package, leaked token, and vulnerable dependency alerts.",
            "parentId": "undefined",
            "updatedAt": "2026-05-24T06:43:04.699Z"
          },
          {
            "id": 8,
            "title": "Make backend-core stack decision",
            "description": "Choose whether the security-critical backend core remains TypeScript or moves to Go/Kotlin/Rust/Python.",
            "details": "Evaluate team capability, two-year maintainability, operational footprint, rewrite cost, dual-stack complexity, auditability, supply-chain exposure, and which modules belong in a payment/auth/escrow core versus the existing marketplace/chat API.",
            "status": "done",
            "priority": "medium",
            "dependencies": [
              2,
              3,
              4,
              5,
              6,
              7
            ],
            "testStrategy": "Architecture decision record states chosen stack, scope of extraction, non-goals, migration phases, rollback criteria, and owners.",
            "parentId": "undefined",
            "updatedAt": "2026-05-24T07:21:45.258Z"
          },
          {
            "id": 9,
            "title": "Create migration and operational runbooks",
            "description": "Document rollout, rollback, and incident response for the selected backend/funds architecture.",
            "details": "Include SHKeeper legacy read path, provider feature flag, ledger backfill, validation report before enforcement, rollback criteria, webhook cutoff, manual reconciliation, failed webhook, duplicate/missing payment, stuck release, disputed release attempt, compromised admin, leaked API key, provider outage, chain/RPC outage, suspicious payment proof, and npm/package compromise.",
            "status": "done",
            "priority": "medium",
            "dependencies": [
              8
            ],
            "testStrategy": "Runbooks identify owner, trigger, detection signal, immediate action, recovery action, and post-incident documentation for each scenario.",
            "parentId": "undefined",
            "updatedAt": "2026-05-24T07:21:47.810Z"
          }
        ],
        "updatedAt": "2026-05-24T07:23:44.643Z"
      },
      {
        "id": "5",
        "title": "Deliver Telegram-native app, bot, and wallet experience",
        "description": "Create a Telegram bot plus Mini App surface so users can complete Amanat buyer, seller, escrow, chat, dispute, payment, release/refund, and support workflows from inside Telegram.",
        "details": "Source PRD: .taskmaster/docs/prd-telegram-native-app-bot-wallet.md. Keep this as a separate delivery track from security remediation and Request Network migration. Identity, bot navigation, Mini App shell, and notifications can start behind flags; wallet/payment crediting and release/refund actions must use canonical backend authorization, provider adapter, funds ledger, escrow state machine, idempotency, and dispute holds.",
        "testStrategy": "Use Telegram sandbox and production bot separation, Mini App client matrix testing, provider/wallet payment fixtures, backend authorization and ledger invariant tests, webhook/callback replay tests, and staged rollout analytics before launch.",
        "status": "in-progress",
        "dependencies": [],
        "priority": "high",
        "subtasks": [
          {
            "id": 1,
            "title": "Define Telegram product surface and flow map",
            "description": "Document which Amanat workflows live in bot messages, which live in the Mini App, and which remain web/admin-only for first release.",
            "details": "Map buyer, seller, admin/support, unauthenticated, linked-user, and unlinked-user journeys. Specify deep-link entry points for request details, offer review, payment, dispute, delivery evidence, and account linking. Separate first-release scope from later enhancements and map every Telegram action to backend API/state transitions.",
            "status": "done",
            "dependencies": [],
            "priority": "high",
            "testStrategy": "See Telegram-native PRD acceptance criteria.",
            "parentId": "undefined",
            "updatedAt": "2026-05-24T09:18:11.077Z"
          },
          {
            "id": 2,
            "title": "Build Telegram identity linking and session model",
            "description": "Implement secure account linking between Telegram users and Amanat accounts.",
            "details": "Backend must verify Telegram Mini App initData before creating a Telegram session. Store an auditable Telegram user ID to Amanat user link. Support existing users, new users, unlinking, blocked accounts, duplicate-link attempts, session expiry, replay protection, rate limits, and audit logs.",
            "status": "done",
            "dependencies": [
              1
            ],
            "priority": "high",
            "testStrategy": "See Telegram-native PRD acceptance criteria.",
            "parentId": "undefined",
            "updatedAt": "2026-05-24T09:18:13.054Z"
          },
          {
            "id": 3,
            "title": "Implement bot command and notification foundation",
            "description": "Create the Telegram bot backend for commands, inline keyboards, callback queries, deep links, and outbound notifications.",
            "details": "Support start/help/link/status/request/offer/payment/dispute/settings basics. Use short opaque IDs or signed tokens for callback payloads. Process incoming updates idempotently with rate limits. Respect notification preferences, quiet/error states, failed delivery, blocked bot, and retry observability.",
            "status": "done",
            "dependencies": [
              1,
              2
            ],
            "priority": "high",
            "testStrategy": "See Telegram-native PRD acceptance criteria.",
            "parentId": "undefined",
            "updatedAt": "2026-05-24T13:46:14.458Z"
          },
          {
            "id": 4,
            "title": "Build Telegram Mini App shell for marketplace workflows",
            "description": "Deliver the mobile-first Mini App that gives users the full Amanat workflow surface inside Telegram.",
            "details": "Use Telegram theme, safe-area, viewport, back button, haptics, and main/bottom button patterns. Support browsing requests, creating/editing requests, reviewing offers, payment state, evidence uploads, delivery actions, and dispute actions. Launch from bot profile, menu button, inline buttons, and direct links with startapp context. Handle unlinked accounts, expired sessions, unsupported clients, and fallback web links.",
            "status": "in-progress",
            "dependencies": [
              1,
              2
            ],
            "priority": "high",
            "testStrategy": "See Telegram-native PRD acceptance criteria.",
            "parentId": "undefined",
            "updatedAt": "2026-05-24T09:18:16.954Z"
          },
          {
            "id": 5,
            "title": "Add Telegram payment and wallet strategy",
            "description": "Evaluate and implement safe payment entry points for Telegram-native users without weakening escrow accounting.",
            "details": "Compare Bot API payments/Stars, Wallet Pay, TON Pay, TON Connect, Request Network links, and existing crypto checkout. Select a first payment path and document rejected options. Store provider, Telegram user ID, deep-link source, payment reference, invoice/order/request ID, currency, amount, expiration, and idempotency key. Wallet/TON flows must validate recipient, asset, amount, memo/reference, confirmation status, and reconciliation evidence before crediting escrow. Refund/release behavior must remain compatible with canonical ledger and dispute holds.",
            "status": "done",
            "dependencies": [
              2,
              4
            ],
            "priority": "high",
            "testStrategy": "See Telegram-native PRD acceptance criteria.",
            "parentId": "undefined",
            "updatedAt": "2026-05-24T09:18:18.909Z"
          },
          {
            "id": 6,
            "title": "Expose escrow, delivery, dispute, and release actions safely",
            "description": "Make Telegram actions useful for real escrow work while preserving backend state authority.",
            "details": "Telegram users can see current escrow state, next allowed actions, and blockers. Delivery confirmation, evidence upload, refund request, dispute open/respond, and release approval must route through backend precondition checks. High-risk actions require fresh confirmation and audit logging with Telegram context. Disputed or held funds cannot be released through Telegram shortcuts.",
            "status": "pending",
            "dependencies": [
              4,
              5
            ],
            "priority": "high",
            "testStrategy": "See Telegram-native PRD acceptance criteria.",
            "parentId": "undefined"
          },
          {
            "id": 7,
            "title": "Add admin and support surface for Telegram-originated cases",
            "description": "Give support/admin users visibility and controls for Telegram-originated users, payments, and bot events.",
            "details": "Admin UI/API should show Telegram linked identity, bot notification status, launch source, payment provider, and wallet/payment references. Support can resend links, revoke Telegram link, block bot access, and inspect Telegram-originated events. Admin overrides must use the same step-up or two-person policy as web flows when configured.",
            "status": "pending",
            "dependencies": [
              2,
              3,
              5
            ],
            "priority": "high",
            "testStrategy": "See Telegram-native PRD acceptance criteria.",
            "parentId": "undefined"
          },
          {
            "id": 8,
            "title": "Add security, compliance, and abuse controls for Telegram",
            "description": "Threat-model the Telegram surface and add controls before launch.",
            "details": "Cover forged init data, callback replay, deep-link parameter tampering, phishing links, bot token leakage, spam, account takeover, wallet spoofing, fake payment proof, and support impersonation. Document secrets, bot webhook endpoints, Wallet Pay keys, TON Connect manifest, CORS, CSP, allowed origins, rate limits, and monitoring for update failures, abnormal callbacks, payment mismatches, blocked notifications, and suspicious wallet activity.",
            "status": "done",
            "dependencies": [
              2,
              3,
              5,
              6
            ],
            "priority": "high",
            "testStrategy": "See Telegram-native PRD acceptance criteria.",
            "parentId": "undefined",
            "updatedAt": "2026-05-24T09:18:24.717Z"
          },
          {
            "id": 9,
            "title": "Prepare QA, rollout, analytics, and launch operations",
            "description": "Prepare the Telegram app and bot for controlled release.",
            "details": "Test Telegram iOS, Android, Desktop, Web, light/dark themes, compact/fullscreen modes, slow network, blocked bot, expired sessions, and payment cancellation. Keep sandbox/test bot and production bot environments separated. Roll out through feature flags, internal allowlist, beta cohort, and production enablement. Track activation, linked accounts, request creation, offer response, payment start/completion, dispute activity, release approval, and notification opt-outs. Add runbooks for bot outage, Telegram API outage, payment provider outage, stuck payment, duplicate callback, suspicious wallet proof, and compromised bot token.",
            "status": "done",
            "dependencies": [
              3,
              4,
              5,
              6,
              7,
              8
            ],
            "priority": "high",
            "testStrategy": "See Telegram-native PRD acceptance criteria.",
            "parentId": "undefined",
            "updatedAt": "2026-05-24T09:18:26.638Z"
          },
          {
            "id": 10,
            "title": "Implement Telegram as first-class authentication provider",
            "description": "Add a POST /auth/telegram endpoint and frontend login flow so users can authenticate with Amanat using only their Telegram identity — no email or password required.",
            "details": "Source PRD: .taskmaster/docs/prd-telegram-phone-auth.md. Backend: create POST /auth/telegram that accepts Mini App initData or Telegram Login Widget payload, verifies the signature (reuse verifyMiniAppInitData; add verifyTelegramLoginWidget for the widget path), looks up TelegramLink by telegramUserId, and either authenticates the linked user or auto-provisions a new Amanat account (authProvider: telegram, telegramVerified: true, nullable email via sparse unique index). Returns JWT + refreshToken + isNewUser flag. Apply existing replay protection and rate limits. User model: make email nullable (sparse index), add authProvider and telegramVerified fields. Frontend: auto-detect Telegram Mini App context and skip login page; POST initData to /auth/telegram; show lightweight onboarding overlay for new users (optional email, language, currency). Add 'Continue with Telegram' button on web login page alongside Google OAuth. Security: blocked Telegram accounts return 403 regardless of re-linking attempts; high-risk action step-up policy is unchanged; never expose raw phone number.",
            "status": "done",
            "dependencies": [
              2,
              8
            ],
            "priority": "high",
            "testStrategy": "Verify: new Telegram user auto-provisions and receives JWT; returning user authenticates via both initData and Login Widget; replayed initData is rejected; stale auth_date is rejected; blocked account returns 403; existing email-password users are unaffected; email remains optional (not required) for Telegram-authed users; isNewUser flag triggers onboarding overlay; high-risk actions still require step-up confirmation.\n\nImplemented verification: backend typecheck; backend targeted Jest __tests__/telegram-auth.test.ts and __tests__/telegram-service.test.ts; frontend targeted Jest __tests__/auth/telegram-auth-action.test.ts and __tests__/sections/telegram/telegram-mini-app-shell.test.tsx. Full frontend typecheck still has unrelated pre-existing payment icon/payload errors outside Task 5.10.",
            "parentId": "5",
            "updatedAt": "2026-05-24T11:59:32.372Z"
          }
        ],
        "updatedAt": "2026-05-24T13:46:14.458Z"
      },
      {
        "id": "6",
        "title": "Request Network in-house checkout (Rabby-supporting)",
        "description": "Replace the redirect to pay.request.network with an Amanat-rendered checkout page that submits the same on-chain calls as RN's hosted UI, so RN's webhook fires unchanged but buyers stay on amn.gg and Rabby works.",
        "details": "See PRD: nick-doc/.taskmaster/docs/prd-request-network-in-house-checkout.md (summary at nick-doc/PRD - Request Network In-House Checkout.md). Status: draft, pending review with second developer. Approach: replicate the two on-chain calls (approve + RN_FEE_PROXY.transferFromWithReferenceAndFee) using wagmi v2 with existing injected()/metaMask() connectors (Rabby works via EIP-6963). Hard-known: proxy 0x0DfbEe143b42B41eFC5A6F87bFD1fFC78c2f0aC9, selector 0xc219a14d, paymentRef = last8Bytes(keccak256(requestId+salt+dest)), feeAmount=0, feeAddress=0x...dEaD. Backend: extend POST /payment/request-network/intents response with inHouseCheckout object (destination, tokenAddress, decimals, chainId, proxyAddress, paymentReference, feeAmount, feeAddress, amountWei). Frontend: new page /checkout/request-network/:paymentId with state machine reusing manual-payment.tsx layout chrome, hosted-page link kept as escape hatch. Implementation gated on a $0.50 cold probe on dev BSC to confirm RN's webhook fires for an externally-built tx. Out of scope: per-seller multi-chain config (§2), ephemeral wallets (§3), full RN removal (§4), gasless. Open questions in PRD §10.",
        "testStrategy": "",
        "status": "done",
        "dependencies": [],
        "priority": "high",
        "subtasks": [
          {
            "id": 1,
            "title": "Deploy confirmation repair before next paid probe",
            "description": "2026-05-28 dev BSC transaction succeeded and RN delivered four webhooks, but Amanat returned 404 due Request Network reference-correlation mismatch. Before another paid payment test, deploy the backend correlation fix, callback polling fix, signed-webhook smoke test, and Transaction Safety Provider gate; then repeat the probe and inspect safety decision state.",
            "details": "",
            "status": "done",
            "dependencies": [],
            "parentTaskId": 6,
            "updatedAt": "2026-05-28T07:34:40.368Z",
            "parentId": "undefined"
          }
        ],
        "updatedAt": "2026-05-28T07:34:40.368Z"
      },
      {
        "id": "7",
        "title": "Per-(buyer, sellerOffer) ephemeral RN destination wallets",
        "description": "Replace the single shared Amanat destination wallet with a per-(buyerId, sellerOfferId) HD-derived address sent to Request Network on intent creation, plus sweep-on-approval and an admin UI.",
        "details": "See PRD - Wallet, Multichain, Confirmations, AML, Trezor.md §1. Files: new backend/src/services/payment/wallets/derivedDestinations.ts (getDestinationFor(buyerId, sellerOfferId) → {address, derivationPath, chainId}); Payment schema add metadata.derivedDestination; requestNetworkPayInService.ts override destinationId before POST /v2/secure-payments (we confirmed RN accepts different destinations per intent); new sweep cron + admin manual-trigger endpoint gated on Transaction Safety Provider; admin UI at /dashboard/admin/derived-destinations with address, balance, last sweep tx (BscScan link), ownership status. Open questions to settle first: HD vs disposable EOAs vs smart-forwarder (recommended HD); sweep cadence (recommended immediate); granularity (recommended per-(buyer, seller), not per-payment); re-use vs rotate after sweep. KMS-rooted seed; backend never holds raw private keys; signing via KMS API (Task #11 Trezor flow is the longer-term replacement). Acceptance: two payments from one buyer to two sellers land on two different addresses; RN webhook fires for both; sweep is idempotent; master seed never leaves KMS.",
        "testStrategy": "",
        "status": "in-progress",
        "dependencies": [],
        "priority": "high",
        "subtasks": [],
        "updatedAt": "2026-05-28T11:51:34.115Z"
      },
      {
        "id": "8",
        "title": "Multichain RN proxy registry + USDC/USDT support",
        "description": "Probe and persist RN ERC20FeeProxy addresses on BSC/Arb/ETH/Polygon/Base, add USDC + USDT token entries with correct decimals per chain, and surface an admin networks page. Include the USDT-mainnet approve(0) reset quirk in the frontend approve step.",
        "details": "See PRD - Wallet, Multichain, Confirmations, AML, Trezor.md §2. Tasks: new backend/scripts/probe-rn-chains.ts that walks each chain in supported-chains.json and verifies the canonical 0x0DfbEe143b42B41eFC5A6F87bFD1fFC78c2f0aC9 proxy is the real RN proxy via a known view fn (CREATE2 is deterministic, but verify); promote backend/src/services/payment/requestNetwork/tokens.ts to load from JSON + admin override; add USDT entries on all 5 chains (BSC USDT 18-dec quirk, mainnet/Arb/Polygon/Base USDT 6-dec); buildInHouseCheckoutBlock returns reason='unsupported_chain:<id>' for unknowns; new admin route GET /api/admin/rn/networks + frontend page /dashboard/admin/networks rendering the registry with per-row 'probe again'. Frontend approve flow: if buyer is on Ethereum mainnet AND token is USDT AND current allowance > 0, do approve(spender, 0) first then approve(spender, amount). Acceptance: probe succeeds on at least BSC/Arb/Polygon/ETH/Base; one paid probe on BSC USDT end-to-end; mainnet USDT approve(0) reset works; admin page reflects registry. Dependencies: none — runs in parallel with #9. This is task #8 in the PRD.",
        "testStrategy": "",
        "status": "done",
        "dependencies": [],
        "priority": "high",
        "subtasks": [],
        "updatedAt": "2026-05-29T08:21:05.470Z"
      },
      {
        "id": "9",
        "title": "Per-chain confirmation thresholds + admin UI",
        "description": "Make TransactionSafetyProvider's confirmation threshold tunable at runtime per chain via admin UI, with an awaiting-confirmation payments view that shows live confirmations vs threshold.",
        "details": "See PRD - Wallet, Multichain, Confirmations, AML, Trezor.md §3. Today TRANSACTION_SAFETY_MIN_CONFIRMATIONS is a global env var, default 12, baked in until redeploy. Move to runtime config: new Setting docs keyed 'confirmation_threshold:<chainId>' or extend existing model; cache reads in transactionSafetyProvider.ts for 30s; GET/PATCH /api/admin/settings/confirmation-thresholds (auth: admin); new admin page /dashboard/admin/confirmation-thresholds (table: chain, current, recommended default, edit-in-place with confirm dialog, audit log of changes); new admin page /dashboard/admin/payments/awaiting-confirmation (payments where escrowState !== 'funded' AND metadata.transactionSafety.lastCheck.status === 'pending'; for each show tx hash linked to explorer, current confirmations via 12s poll on BSC, threshold, ETA). Acceptance: admin lowers BSC threshold from 12 to 3 on dev, next webhook honors new value within 30s; awaiting-confirmation table updates live; audit log records every change. Non-goals: per-asset, per-seller thresholds. Dependencies: none. This is task #9 in the PRD.",
        "testStrategy": "",
        "status": "done",
        "dependencies": [],
        "priority": "medium",
        "subtasks": [],
        "updatedAt": "2026-05-29T09:51:57.565Z"
      },
      {
        "id": "10",
        "title": "Optional AML screening on incoming payments (seller-paid)",
        "description": "Turn the existing aml_screening placeholder in TransactionSafetyProvider into a real Chainalysis (or equivalent) Address Screening call that the seller opts into per-offer and pays the per-check cost for.",
        "details": "See PRD - Wallet, Multichain, Confirmations, AML, Trezor.md §4. Default provider recommendation: Chainalysis Address Screening (cheapest, simplest). Files: new backend/src/services/payment/safety/amlProvider.ts interface + chainalysisProvider.ts impl behind env TRANSACTION_SAFETY_AML_PROVIDER=chainalysis with API_KEY in KMS; transactionSafetyProvider's evaluateAmlPlaceholder() becomes real, persists raw provider response on Payment.metadata.amlResult; Offer schema add requireAmlCheck + amlBlockOnFailure booleans; offer-edit UI toggle 'Require AML on incoming payments ($X per payment, paid by you)'; admin global config UI for provider selection + API key rotation + per-chain enabled flag; cost accounting: deduct per-check cost from seller's escrow on completion as a separate ledger line item, surfaced on payment-details. Open questions before code: pick provider (Chainalysis vs TRM vs Elliptic — need 1-page comparison of cost/latency/coverage); failure mode (fail-closed only when seller opted in AND amlBlockOnFailure=true, else warn/log); cost batching cadence. Acceptance: seller toggles AML on an offer; incoming payment triggers a real Chainalysis call; sanctions verdict blocks the safety gate; clean verdict passes; seller's settled amount reduced by check cost; admin can rotate API key without redeploy; provider-down + amlBlockOnFailure=true keeps payment pending with provider_unavailable reason. Dependencies: none. This is task #10 in the PRD.",
        "testStrategy": "",
        "status": "done",
        "dependencies": [],
        "priority": "medium",
        "subtasks": [],
        "updatedAt": "2026-05-29T10:00:28.716Z"
      },
      {
        "id": "11",
        "title": "Trezor signing for admin actions (release/refund/sweep)",
        "description": "Replace the hot-key admin signing flow with a WebUSB-based Trezor flow so the backend never holds a private key. All admin-side txes are built backend, signed via Trezor in the browser, broadcast from the browser.",
        "details": "See PRD - Wallet, Multichain, Confirmations, AML, Trezor.md §5. Lib: @trezor/connect-web (WebUSB; Chromium-only — Firefox users need Trezor Bridge native helper). Files: new frontend/src/web3/trezor/trezorConnector.ts wrapping @trezor/connect-web; existing admin actions (release/refund/sweep when #7 lands) get a 'Sign with Trezor' button that flows: POST /api/admin/actions/build-tx → returns unsigned tx bytes → send to Trezor → sign → wagmi sendTransaction broadcasts → POST /api/admin/actions/confirm-tx with hash; admin settings page to register Trezor address(es) (backend rejects signatures from unauthorized devices); audit log on every Trezor-signed action; break-glass hot-key path requires explicit admin toggle, expires after 1h, fires Telegram alarm. Open questions: m-of-n multi-admin signing — default single-signer for v1; Trezor One vs Model T — lib abstracts; fallback when Trezor unavailable — break-glass with alarm. Acceptance: admin registers Trezor address; release flow uses Trezor end-to-end; backend rejects signatures from unregistered devices; audit log captures admin user + Trezor addr + tx hash + before/after escrow state; break-glass works and alarms. Non-goals: mobile Trezor flow, buyer-side Trezor (buyer uses wagmi injected). Dependencies: task #7 (ephemeral wallets) for the sweep step — but task #11 can ship the release/refund flows first. This is task #11 in the PRD.",
        "testStrategy": "",
        "status": "done",
        "dependencies": [],
        "priority": "high",
        "subtasks": [],
        "updatedAt": "2026-05-29T10:50:02.957Z"
      },
      {
        "id": "12",
        "title": "Replace auth rate limiter with CAPTCHA (Cloudflare Turnstile or reCAPTCHA v3)",
        "description": "The current authLimiter blocks all login attempts from an IP for 15 minutes after N failures. This creates terrible UX (legitimate users get locked out, especially during testing) and is bypassable via rotating IPs anyway. Replace with a progressive challenge: allow 3 attempts freely, then require CAPTCHA (Cloudflare Turnstile preferred — no user friction; reCAPTCHA v3 as fallback). Backend verifies the token server-side before proceeding with auth. Rate limiter can stay as a last-resort backstop but with a much higher threshold (e.g. 100 req/15 min).",
        "details": "",
        "testStrategy": "",
        "status": "in-progress",
        "dependencies": [],
        "priority": "medium",
        "subtasks": [],
        "updatedAt": "2026-05-29T11:23:30.368Z"
      },
      {
        "id": "13",
        "title": "AMN Pay Scanner — retire Request Network API (Go microservice)",
        "description": "Build a standalone Go microservice (AMN Pay Scanner) that replaces the RN API: generates paymentReferences locally, scans ERC20FeeProxy eth_getLogs per chain, and delivers HMAC-signed webhooks to the backend on confirmation. Backend swaps provider from 'request.network' to 'amn.scanner' via a new adapter. Supports any destination address, enabling HD-derived addresses as real payment destinations.",
        "details": "See PRD - Retire Request Network — In-House Payment Scanner.md. Service exposes: POST /intents, GET /intents/:id, GET /scanner/status, GET /health. Node.js backend adds amnPayAdapter.ts and POST /api/payment/amn-scanner/webhook receiver. Parallel-run with RN during drain period. Language: Go v1 (Rust rewrite if volume justifies).\n\nImplemented by Kimi 2026-05-29. Scanner repo: scanner@8fee27e. Backend: backend@cdc8df1. Frontend: frontend@a5dd48e. Still open: live e2e probe (manual ops step — deploy scanner + send real BSC TransferWithReferenceAndFee tx to verify event topic match + webhook delivery).",
        "testStrategy": "1. POST /intents returns checkoutBlock within 300ms with no RN API call. 2. Scanner detects TransferWithReferenceAndFee on BSC within 2 poll cycles. 3. Payment marked confirmed after threshold blocks. 4. Scanner resumes from checkpoint after restart. 5. Webhook rejected on bad HMAC.",
        "priority": "high",
        "status": "done",
        "dependencies": [
          "8"
        ],
        "subtasks": []
      },
      {
        "id": "14",
        "title": "Sweep service — PermitPull + GasTopUp (Kimi, backend@7688f57)",
        "description": "Standalone sweep service with three signer modes: PermitPullSweepSigner (EIP-712 gasless permit for ETH/Arb/Polygon/Base), GasTopUpSweepSigner (BNB top-up for BSC), BuildOnlySweepSigner (fallback). Auto-selects by chainId and token. Currently uses SWEEP_MASTER_PRIVKEY hot key — Task #11 (Trezor) replaces this.",
        "details": "Implemented by Kimi in backend@7688f57 (integrate-main-into-development). Files: src/services/payment/wallets/sweepService.ts, __tests__/sweep-service.test.ts. PERMIT_CAPABLE_TOKENS seeded from 2026-05-29 on-chain audit. 31/31 unit tests pass. Still open: on-chain integration tests (one per signer mode against testnet or Anvil fork). Env vars added: SWEEP_MASTER_PRIVKEY, SWEEP_GAS_MIN_BNB, SWEEP_GAS_TOP_UP_BNB.",
        "testStrategy": "Unit: 31/31 pass (auto-selection, permit capability matrix, gas top-up logic). Integration (open): one live broadcast per signer mode on BSC testnet or local Anvil fork.",
        "priority": "high",
        "status": "done",
        "dependencies": [],
        "subtasks": [],
        "updatedAt": "2026-05-29T11:56:24.674Z"
      }
    ],
    "metadata": {
      "version": "1.0.0",
      "lastModified": "2026-05-29T11:56:24.675Z",
      "taskCount": 14,
      "completedCount": 11,
      "tags": [
        "master"
      ]
    }
  }
}