description:Automates an end-to-end production-grade audit, verification, repair, regression testing, and re-audit workflow for full-stack repositories with financial logic, security controls, and UTC+7 timezone compliance. Operates autonomously from initial inspection through P0/P1 resolution and report generation.
---
# Full Project Audit & Autonomous Repair Workflow
## Overview
This skill guides an agent through an autonomous, end-to-end audit, triage, verification, repair, and re-audit cycle for a production software project (covering backend, frontend, database, financial calculation invariants, and security).
The workflow operates **autonomously** without requiring manual user prompt pacing between steps, while strictly adhering to safety guardrails for destructive database actions, production credentials, and security controls.
---
## Operating Mode & Autonomy Standard
-**Autonomous Progression**: Advance automatically through each step:
-**DO NOT** read, expose, print, or commit `.env` files or secrets.
-**DO NOT** weaken security controls or mock out security middleware merely to make test suites pass.
### 2. Financial Logic Invariants
When auditing or repairing applications handling wallets, transactions, budgets, or accounting:
-**Income**: Increases target wallet balance.
-**Expense**: Decreases target wallet balance.
-**Transfer**: Decreases source wallet balance, increases destination wallet balance. A transfer **must never** be counted as income or expense in revenue/spending analytics.
-**Transaction Update**: The financial effect of the old transaction state must be completely reversed before applying the new effect (within an atomic database transaction).
-**Transaction Deletion**: The financial effect of the deleted transaction must be completely reversed (wallet balance restored atomically).
-**Failed Mutations**: If any step in a multi-record mutation fails, all state changes must be rolled back to keep the database consistent.
-**Concurrency Protection**: Concurrent financial mutations on the same wallet or budget must use atomic row locking (`SELECT ... FOR UPDATE` or Prisma `$transaction` with optimistic/pessimistic concurrency controls) to prevent lost updates or negative balance race conditions.
-**Ownership & Tenant Isolation**: Never trust `userId` or `walletId` from client body or query params. Always verify that the authenticated user owns the resource being accessed or modified.
- The official business timezone is **`Asia/Ho_Chi_Minh` (UTC+7, +07:00)**.
-**Boundary Auditing**: All date filters, `startOfDay`, `endOfDay`, monthly aggregations, budget periods, reports, reminders, cron schedules, and daily quotas must be calculated in `Asia/Ho_Chi_Minh`.
-**Near-Midnight Invariant**: A transaction occurring at `23:59:59` or `00:00:01` Vietnam time must strictly belong to the correct Vietnam business calendar date, regardless of whether the server or database runs in UTC (`+00:00`).
---
## The 10-Step Execution Workflow
```mermaid
flowchart TD
S1[Step 1: Full Audit\nRead-only deep inspection] --> S2[Step 2: Create Backlog\nPrioritize P0, P1, P2, P3]
-**P1 — High**: Production bugs, incorrect business logic, timezone day-boundary calculation errors, authorization flaws, severe performance bottlenecks, N+1 query loops, or broken API contracts.
-**P2 — Medium**: Edge-case errors, missing query validations, lack of pagination on non-hot endpoints, hardcoded non-production fallbacks, or lack of granular rate-limiting.
-**P3 — Low**: Code quality, architectural convention drift, minor CPU/memory optimizations, documentation inaccuracies, or cosmetic formatting.
Before applying any code changes, rigorously verify every **P0** and **P1** finding to eliminate false positives:
1.**Trace Flow**: Follow the complete call chain (`Route -> Controller -> Service -> Repository -> Database`).
2.**Inspect Context**: Check related middleware, database constraints, Zod schemas, and existing tests.
3.**Classify Each Finding**:
-`CONFIRMED`: Verified real issue with clear failure path. Proceed to fix.
-`FALSE_POSITIVE`: Proved not an issue due to existing guards or constraints. Document rationale and discard.
-`NEEDS_MORE_INVESTIGATION`: Ambiguous; inspect additional code paths or write an exploratory test before touching production code.
---
### Step 4 — Fix P0 Issues
Implement fixes for all `CONFIRMED` P0 findings adhering to these rules:
-**Smallest Safe Change**: Make the minimal diff necessary to fix the root cause.
-**Preserve Architecture**: Follow existing repository patterns and layered architecture.
-**No Unrelated Refactors**: Do not reformat or clean up unrelated code in the same change.
-**No Unnecessary Dependencies**: Use existing utilities and libraries whenever possible.
-**Preserve Contracts**: Do not alter public API response structures unless strictly required by the bug fix.
-**Prioritize Correctness**: For financial and security operations, prioritize correctness and safety over premature optimization.
---
### Step 5 — Test P0 Fixes
Validate that all P0 fixes are working and introduce no regressions:
1.**Run Validation Commands**:
- Typecheck: `pnpm build` or `tsc --noEmit`
- Linter: `pnpm lint`
- Test Suite: `pnpm test -- --runInBand` or targeted `pnpm test -- <test-file>`
2.**Add Missing Tests**:
- If tests are missing for a critical security or financial fix, write focused Jest/Node unit or integration tests covering:
- Income/Expense/Transfer mutations
- Wallet balance rollback on failure
- Authorization & ownership boundary checks
- Race condition & concurrency locking
- Timezone date boundary at `00:00` and `23:59`
3.**If Tests Fail**:
- Diagnose root cause, adjust implementation, and re-test until 100% green.
-**Do not proceed to P1 fixes while any P0 issue or test remains failing.**
---
### Step 6 — Fix P1 Issues
Once P0 fixes are verified and green:
- Apply targeted, minimal fixes for all `CONFIRMED` P1 findings.
- Maintain the same strict standards: no architectural disruption, no breaking contract changes, minimal clean diff.
---
### Step 7 — Test P1 Fixes
1. Run the full verification suite (Typecheck, Lint, Unit tests, Integration tests, Frontend/Backend cross-checks).
2. Fix any regressions immediately.
3. Ensure the test suite is fully passing.
---
### Step 8 — Re-Audit
Perform a second full audit pass over the entire codebase to verify resolution and ensure no secondary issues were introduced:
-[] Were all original P0 and P1 findings genuinely resolved?
-[] Were any new security, concurrency, or timezone bugs introduced?
-[] Were API contracts between frontend and backend preserved?
-[] Were database transactions and atomic balance updates preserved?
-[] Are all database indexes and queries performing efficiently?
-[] Compare the re-audit state directly against the original backlog.
---
### Step 9 — Secondary Fixes (Convergence Loop)
If the re-audit uncovers new `CONFIRMED` P0 or P1 issues caused by recent edits:
1. Re-enter the loop: `VERIFY -> FIX -> TEST -> RE-AUDIT`.
2. Iterate until:
- Zero confirmed P0 issues remain.
- Zero confirmed P1 issues remain.
- All tests pass cleanly.
- Lint and typecheck pass with zero errors.
3.*Convergence limit*: If an issue cannot be resolved within 3 iterations without major architectural redesign, document it clearly in the report as `Deferred` and stop the loop.
---
### Step 10 — Final Report Generation
Create directory `docs/audits/` (if it does not exist) and write the final report to:
`docs/audits/latest-audit.md`
#### Report Structure Template
```markdown
# Project Audit & Repair Report
**Date**: YYYY-MM-DD
**Repository**: [Repository Name]
**Status**: [Clean / Action Required / Converged]
## Executive Summary
Concise 2–3 paragraph summary of the audit scope, critical issues discovered, fixes applied, test outcomes, and current repository health.
## Initial Findings Backlog
Summary table of all findings from Step 2 with Severity (P0, P1, P2, P3), Module, and Status (Fixed / Verified / Deferred).
A full production-grade audit and autonomous remediation cycle was executed on the `data-crawler-be` repository following the `full-project-audit` workflow and workspace rules in [`AGENTS.md`](file:///d:/NodeJS/DataCrawler/data-crawler-be/AGENTS.md).
The audit evaluated 10 core dimensions: Architecture & Layering, API Contracts, Authentication & RBAC, Database & Prisma Indexes, Financial/Data Invariants, Date & Timezone Compliance (`Asia/Ho_Chi_Minh` UTC+7), Performance & Concurrency, Security & Input Sanitization, Error Handling, and Test Automation.
All **3 P0 (Critical)** and **5 P1 (High)** findings—along with high-impact **P2** security vulnerabilities such as CSV Formula Injection—were confirmed, verified, repaired with minimal safe diffs, tested, and validated. The full test suite passed with **23 test suites and 322 unit/integration tests**, with zero build or lint errors.
| **BUG-P3-03** | `P3` | `firecrawl` | Triple Cheerio Parse in Firecrawl Service | CONFIRMED | Deferred (Low Risk) |
---
## 3. Fixed Issues Detail
### [BUG-P0-01] SSRF Vulnerability in Webhook Delivery Worker
-**Severity**: `P0 - Critical`
-**Module**: `webhooks`
-**Root Cause**: `WebhookDeliveryService.send()` dispatched HTTP POST requests via standard `axios.post()` without DNS resolution check, allowing requests to private/loopback/cloud-metadata IP ranges.
-**Fix Applied**: Switched HTTP dispatch client to `getSecureAxios()` from `url.helper.ts`, enforcing `secureHttpAgent` / `secureHttpsAgent` to block private IPs and redirect attacks.
### [BUG-P0-02] Cross-Tenant Data Leak in Extraction Template Runner
-**Severity**: `P0 - Critical`
-**Module**: `extraction-templates` / `queues`
-**Root Cause**: `findByDomain(domain)` queried `findFirst({ where: { domain } })` without scoping to `userId`, causing User A's custom domain templates to be executed on User B's crawl jobs.
-**Fix Applied**:
- Added `findByUserAndDomain(userId, domain)` to `ExtractionTemplateRepository` utilizing the `@@unique([userId, domain])` composite constraint with UUID validation.
- Updated `runExtractionIfTemplate` and `persistBatchResults` across all crawl modes (SCRAPE, SITEMAP, URL_LIST, CRAWL) in `crawl.worker.processor.ts` to pass `crawlJob.userId`.
### [BUG-P0-03] Multi-Instance Race Condition on Due Schedules
-**Severity**: `P0 - Critical`
-**Module**: `crawl-schedules` / `queues`
-**Root Cause**: `processDueSchedules()` queried due schedules and updated `nextRunAt` only after creating the job, allowing duplicate jobs to be triggered simultaneously by multiple worker instances.
-**Fix Applied**: Implemented atomic conditional update `claimDueSchedule(id, now, nextRunAt)` in `CrawlScheduleRepository` using `updateMany({ where: { id, isActive: true, nextRunAt: { lte: now } } })`. Only the instance that wins the atomic claim proceeds to create and enqueue the crawl job.
-**Root Cause**: `startOfDay` was calculated using `new Date().setHours(0, 0, 0, 0)` which reset daily quotas at 07:00 AM Vietnam time on UTC cloud servers.
-**Fix Applied**: Calculated start of day in `Asia/Ho_Chi_Minh` timezone using `getZonedDateParts` and `createUtcDateFromZonedParts`.
-**Root Cause**: `audit_logs` had no indexes on `[userId, createdAt]`, `[action]`, or `[createdAt]`; `crawl_assets` lacked `[crawlJobId]`.
-**Fix Applied**: Added `@@index([crawlJobId])` to `CrawlAsset` and `@@index([userId, createdAt])`, `@@index([action])`, `@@index([createdAt])` to `AuditLog` in `prisma/schema.prisma` and generated the updated Prisma client.
-**Root Cause**: Direct `prisma` imports were present in `auth.middleware.ts`, `api-key.middleware.ts`, `crawl-job.service.ts`, `webhook-config.service.ts`, and `webhook-delivery.service.ts`.
-**Fix Applied**:
- Created [`src/modules/webhooks/webhook.repository.ts`](file:///d:/NodeJS/DataCrawler/data-crawler-be/src/modules/webhooks/webhook.repository.ts).
- Refactored `WebhookConfigService` and `WebhookDeliveryService` to use `WebhookRepository`.
- Refactored `auth.middleware.ts`, `api-key.middleware.ts`, and `crawl-job.service.ts` to query through `UserRepository` and `CrawlJobRepository`.
1.[`prisma/schema.prisma`](file:///d:/NodeJS/DataCrawler/data-crawler-be/prisma/schema.prisma) — Added indexes on `AuditLog` and `CrawlAsset`.
2.[`src/middlewares/auth.middleware.ts`](file:///d:/NodeJS/DataCrawler/data-crawler-be/src/middlewares/auth.middleware.ts) — Replaced direct Prisma query with `UserRepository.findById`.
3.[`src/middlewares/api-key.middleware.ts`](file:///d:/NodeJS/DataCrawler/data-crawler-be/src/middlewares/api-key.middleware.ts) — Replaced direct Prisma query with `UserRepository.findById`.
4.[`src/modules/crawl-jobs/crawl-job.dto.ts`](file:///d:/NodeJS/DataCrawler/data-crawler-be/src/modules/crawl-jobs/crawl-job.dto.ts) — Updated `CreateCrawlJobDto.startUrl` optionality for `URL_LIST`.
5.[`src/modules/crawl-jobs/crawl-job.repository.ts`](file:///d:/NodeJS/DataCrawler/data-crawler-be/src/modules/crawl-jobs/crawl-job.repository.ts) — Added `countJobsSince` and `countConcurrentJobs`.
6.[`src/modules/crawl-jobs/crawl-job.service.ts`](file:///d:/NodeJS/DataCrawler/data-crawler-be/src/modules/crawl-jobs/crawl-job.service.ts) — Fixed UTC+7 quota calculation, repository layering, and bounded concurrency for DNS.
7.[`src/modules/crawl-jobs/__tests__/crawl-job.service.test.ts`](file:///d:/NodeJS/DataCrawler/data-crawler-be/src/modules/crawl-jobs/__tests__/crawl-job.service.test.ts) — New unit tests for `CrawlJobService`.
9.[`src/modules/crawl-schedules/crawl-schedule.service.ts`](file:///d:/NodeJS/DataCrawler/data-crawler-be/src/modules/crawl-schedules/crawl-schedule.service.ts) — Handled race conditions and checked inactive user status.
10.[`src/modules/crawl-schedules/__tests__/crawl-schedule.service.test.ts`](file:///d:/NodeJS/DataCrawler/data-crawler-be/src/modules/crawl-schedules/__tests__/crawl-schedule.service.test.ts) — Added race condition & inactive user schedule test cases.
12.[`src/modules/extraction-templates/extraction-runner.ts`](file:///d:/NodeJS/DataCrawler/data-crawler-be/src/modules/extraction-templates/extraction-runner.ts) — Scoped template execution by `userId`.
13.[`src/queues/crawl.worker.processor.ts`](file:///d:/NodeJS/DataCrawler/data-crawler-be/src/queues/crawl.worker.processor.ts) — Propagated `crawlJob.userId` across all crawl modes.
14.[`src/modules/exports/csv-export.service.ts`](file:///d:/NodeJS/DataCrawler/data-crawler-be/src/modules/exports/csv-export.service.ts) — Neutralized CSV formula injection.
15.[`src/modules/exports/__tests__/csv-export.service.test.ts`](file:///d:/NodeJS/DataCrawler/data-crawler-be/src/modules/exports/__tests__/csv-export.service.test.ts) — New CSV formula injection unit test suite.
16.[`src/modules/webhooks/webhook.repository.ts`](file:///d:/NodeJS/DataCrawler/data-crawler-be/src/modules/webhooks/webhook.repository.ts) — New Webhook repository.
17.[`src/modules/webhooks/webhook-config.service.ts`](file:///d:/NodeJS/DataCrawler/data-crawler-be/src/modules/webhooks/webhook-config.service.ts) — Refactored to use `WebhookRepository`.
18.[`src/modules/webhooks/webhook-delivery.service.ts`](file:///d:/NodeJS/DataCrawler/data-crawler-be/src/modules/webhooks/webhook-delivery.service.ts) — Secured against SSRF with `getSecureAxios()` and refactored to use `WebhookRepository`.
19.[`src/modules/webhooks/__tests__/webhook.service.test.ts`](file:///d:/NodeJS/DataCrawler/data-crawler-be/src/modules/webhooks/__tests__/webhook.service.test.ts) — New Webhook service & SSRF protection test suite.
---
## 6. Risk Assessment & Recommended Next Steps
-**Operational Health**: Zero critical vulnerabilities, zero race conditions, and complete tenant isolation across background workers.
-**Database Deployment**: Execute standard Prisma migration (`pnpm db:migrate`) on target environments to apply the non-destructive indexes on `audit_logs` and `crawl_assets`.
-**Scheduled Backlog Items (P2 / P3)**:
1. Add pagination metadata to `GET /api/v1/webhooks/deliveries`.
2. Apply `validateQuery` Zod schemas to all `GET /` list endpoints.
3. Enforce strict rate limiting on `/api/v1/auth/forgot-password` and `/api/v1/auth/login`.