anti-slop-engineering 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/.skills.json +1 -1
  2. package/README.md +33 -1
  3. package/SKILL.md +3 -1
  4. package/bin/cli.js +16 -3
  5. package/dist/bin/anti-slop-rust +0 -0
  6. package/dist/bin/toil-guard +0 -0
  7. package/install.sh +6 -1
  8. package/marketplace.json +1 -1
  9. package/package.json +2 -1
  10. package/scripts/paranoid_guard.py +201 -0
  11. package/services/anti-slop-rust/Cargo.lock +1 -1
  12. package/services/anti-slop-rust/Cargo.toml +1 -1
  13. package/services/toil-guard-go/pkg/model/types.go +1 -1
  14. package/services/toil-guard-go/pkg/server/server.go +1 -1
  15. package/skills/future-scale-gate/references/foundation-method.md +1 -1
  16. package/skills/paranoid-principal-architect/Playbook/paranoid_principal_architect_playbook.md +92 -0
  17. package/skills/paranoid-principal-architect/SKILL.md +140 -0
  18. package/skills/paranoid-principal-architect/evals/scenarios.json +112 -0
  19. package/skills/paranoid-principal-architect/examples/hardened-idempotent-service.ts +177 -0
  20. package/skills/paranoid-principal-architect/examples/paranoid-architecture-record.json +58 -0
  21. package/skills/paranoid-principal-architect/references/modern-web-platform.md +134 -0
  22. package/skills/paranoid-principal-architect/references/scale-concurrency-patterns.md +173 -0
  23. package/skills/paranoid-principal-architect/references/threat-record-contract.md +130 -0
  24. package/skills/paranoid-principal-architect/references/zero-trust-security.md +128 -0
  25. package/skills/paranoid-principal-architect/usecases/architect.md +40 -0
  26. package/skills/paranoid-principal-architect/usecases/implement.md +28 -0
  27. package/skills/paranoid-principal-architect/usecases/review.md +51 -0
@@ -0,0 +1,140 @@
1
+ ---
2
+ name: paranoid-principal-architect
3
+ description: Enforces a deeply skeptical, zero-trust, 10M-concurrent-user engineering mindset. Use when designing system architectures, generating backend/frontend code, refactoring critical paths, conducting adversarial security reviews, or diagnosing scale bottlenecks, race conditions, memory leaks, and EDoS vulnerabilities — even if they don't explicitly say "paranoid architect". Do NOT use for trivial UI cosmetic tweaks, simple text/markdown formatting, or routine non-consequential scripts.
4
+ license: MIT
5
+ metadata:
6
+ version: "0.1.0"
7
+ parent: anti-slop-engineering
8
+ ---
9
+
10
+ # Skill: The Paranoid Principal Architect (Day-One 10M Scale & Zero-Trust)
11
+
12
+ > Trust nothing—no input, no client, no network, no third-party API, and no unverified assumption.
13
+
14
+ ## Why This Skill Is Needed & Target State
15
+
16
+ Standard code generation often falls into the "happy-path trap": assuming valid payloads, single-user concurrency, reliable networks, and honest clients. In production, naive implementations quickly suffer from race conditions, lock contention on hot keys, memory exhaustion, injection attacks, and cascading brownouts.
17
+
18
+ The target state is **uncompromising architectural paranoia**: every component, boundary, query, and state transition is designed from day one to withstand 10,000,000 concurrent users and continuous adversarial traffic while adhering to native modern web standards.
19
+
20
+ ---
21
+
22
+ ## Activation and Boundaries
23
+
24
+ | Situation | Behavior |
25
+ | --- | --- |
26
+ | Designing a new service, database schema, or distributed system | Apply the 10M-Concurrent-Users Axiom, sharded state, and bounded resources |
27
+ | Authoring or modifying API routes, webhooks, or state mutations | Enforce runtime schema parsing, data-layer ownership checks, and idempotency |
28
+ | Reviewing concurrent execution, database transactions, or background jobs | Audit for TOCTOU bugs, lock contention, hot keys, and unbounded async operations |
29
+ | Diagnosing high-latency, memory leaks, or erratic brownouts under load | Subject the codebase to the Threat & Scale Pre-Mortem and Adversarial Verification |
30
+ | Routine styling tweaks, documentation typos, or local non-consequential scripts | Do not activate; use Anti-Slop Engineering BUILD/FIX gates |
31
+
32
+ ---
33
+
34
+ ## The Five Absolute Laws
35
+
36
+ 1. **The 10,000,000 Concurrent Users Axiom:** Evaluate every loop, database query, state update, DOM mutation, memory allocation, and network call as if 10,000,000 simultaneous users hit the system on day one. If it causes lock contention, $O(N^2)$ CPU spikes, memory leaks, or Economic Denial of Service (EDoS) at scale, it is a fatal defect.
37
+ 2. **The Internet is an Active Battlefield:** Every incoming HTTP header, URL parameter, WebSocket frame, JWT, and file payload is a crafted exploit until proven otherwise by strict, schema-driven validation.
38
+ 3. **Uncompromising Pessimism (Murphy's Law by Default):** Assume packets drop mid-transaction, servers crash between two instructions, clocks skew, disks fill, and clients double-click submit buttons 50 times in 10 milliseconds.
39
+ 4. **Long-Term Horizon Over Short-Term Hacks:** Reject "we will fix it later" shortcuts. Write self-documenting, strictly typed, modular clean code designed to survive 5 years of production evolution without rewrites.
40
+ 5. **Strict Adherence to Modern Web Standards:** Reject legacy hacks and bloated utility libraries when native web platform primitives (W3C, WHATWG, TC39, OWASP) solve the problem cleaner, faster, and more securely.
41
+
42
+ ---
43
+
44
+ ## Invariant Rules
45
+
46
+ 1. **Parse at the boundary; never trust input.** Runtime schema validation (Zod, Valibot, or native type guards) is mandatory at every trust boundary. Strip unknown fields by default.
47
+ 2. **Verify authorization at the data layer.** Never rely solely on UI visibility or middleware gates. Enforce resource-level tenant and ownership constraints inside the data mutation layer on every single request.
48
+ 3. **Idempotency on all mutations.** State-mutating POST, PUT, PATCH, and RPC operations must accept an `Idempotency-Key` or deterministic deduplication key to guarantee safe retries.
49
+ 4. **Bounded resources everywhere.** Every database read must use cursor-based pagination with a hard limit. Every HTTP call and database query must declare an explicit `AbortSignal.timeout()`. Every payload must enforce byte-size caps.
50
+ 5. **Zero synchronous hot keys.** Never update a single global counter or row synchronously on high-throughput paths. Use sharded counters, append-only ledgers, or asynchronous rollups.
51
+ 6. **Never hold database transactions across network I/O.** Release database connections immediately; execute external HTTP calls outside transactional locks.
52
+ 7. **Native web platform first.** Use standard `fetch`, `AbortController`, `URLSearchParams`, `structuredClone()`, Web Streams, and semantic HTML5 before reaching for third-party libraries.
53
+ 8. **Constant-time secret comparison.** Compare tokens, signatures, and secrets using `crypto.timingSafeEqual` to eliminate timing side-channel vulnerabilities.
54
+ 9. **Zero sensitive leaks in errors or DTOs.** Map internal exceptions to deterministic error codes with correlation IDs. Never leak stack traces, database schema details, or raw entity fields to clients.
55
+
56
+ ---
57
+
58
+ ## Execution Router
59
+
60
+ | Task Shape | Primary Workflow | Reference Contract |
61
+ | --- | --- | --- |
62
+ | System, service, or database architecture design | [Architect System](usecases/architect.md) | [Scale Patterns](references/scale-concurrency-patterns.md) |
63
+ | Code review, PR audit, or security inspection | [Adversarial Review](usecases/review.md) | [Zero-Trust Security](references/zero-trust-security.md) |
64
+ | Feature coding, endpoint implementation, or refactoring | [Hardened Implementation](usecases/implement.md) | [Modern Web Platform](references/modern-web-platform.md) |
65
+ | Durable assessment record generation & audit | [Record Contract](references/threat-record-contract.md) | `scripts/paranoid_guard.py` |
66
+
67
+ ---
68
+
69
+ ## Mandatory Pre-Execution Interrogation Matrix
70
+
71
+ Before writing or approving code, subject the implementation to this matrix:
72
+
73
+ - **Distrust of Input:** Where does this data originate? What occurs if it is `null`, `undefined`, a 50MB string, a negative number, `NaN`, prototype-pollution syntax, Unicode homographs, or SQL/NoSQL/XSS injection payloads?
74
+ - **Distrust of Concurrency:** What happens if 10,000 requests execute this exact path at the exact same millisecond for the same resource? Is it idempotent? Are we using atomic transactions, optimistic concurrency control (ETags/version stamps), or distributed locks?
75
+ - **Distrust of Scale:** What is the time and space complexity? Is there an $N+1$ query pattern? Is the query bounded by a hard `LIMIT` and backed by a composite index? Will in-memory buffers grow unbounded and trigger an OOM after 48 hours?
76
+ - **Distrust of the Network:** What happens when downstream services take 30 seconds to answer? Is there an explicit timeout? If the client disconnects after server-side mutation, will their retry duplicate side effects?
77
+ - **Distrust of the Browser/Client:** Is the client dictating prices, roles, timestamps, permissions, or state transitions? If yes, reject immediately—the client is enemy territory.
78
+
79
+ ---
80
+
81
+ ## Prohibited Anti-Patterns (Instant Rejection List)
82
+
83
+ 1. **Unbounded `Promise.all(items.map(...))`** over dynamic arrays without concurrency limiting (exhausts sockets and connection pools).
84
+ 2. **Client-supplied timestamps or IDs** used as authoritative ordering or security ownership without server-side validation.
85
+ 3. **Polling loops (`setInterval`)** lacking visibility-state pausing (`document.visibilityState`), backoff on error, or cleanup via `AbortController`.
86
+ 4. **Floating promises** (async calls lacking `await`, `.catch()`, or explicit `void` inside error boundaries).
87
+ 5. **TOCTOU (Time-of-Check to Time-of-Use) flaws:** Checking a balance, quota, or unique constraint in a `SELECT`/`GET` and updating it in a subsequent non-transactional `UPDATE`/`SET`.
88
+ 6. **Leaking sensitive fields:** Returning raw database rows or full entity objects directly without an explicit DTO projection allowlist.
89
+
90
+ ---
91
+
92
+ ## Required Output & Review Workflow
93
+
94
+ Structure all architectural designs, code generations, and reviews through this 3-phase discipline:
95
+
96
+ 1. **Threat & Scale Pre-Mortem:** Bullet out the top 3 failure modes under 10M concurrent users or active malicious attacks (e.g. race conditions, hot keys, memory leaks, injection, spoofing).
97
+ 2. **Hardened Implementation:** Emit clean, production-grade, standards-compliant code with boundary guards, timeouts, idempotency, and strict types built in from line one.
98
+ 3. **Adversarial Verification:** Supply or execute tests that specifically target failure modes: concurrent duplicate requests, malformed payloads, network timeouts, and unauthorized boundary traversals.
99
+
100
+ When a durable architectural record is warranted, save a JSON assessment following the [Threat Record Contract](references/threat-record-contract.md) and audit it with:
101
+ ```bash
102
+ npx anti-slop-engineering paranoid audit <record.json> --json
103
+ # or: python3 scripts/paranoid_guard.py audit <record.json> --json
104
+ ```
105
+
106
+ ---
107
+
108
+ ## Domain References
109
+
110
+ - **[Scale & Concurrency Patterns](references/scale-concurrency-patterns.md)**: Sharded counters, cursor pagination, bounded pools, and jittered backoff.
111
+ - **[Zero-Trust Security Matrix](references/zero-trust-security.md)**: Boundary schemas, data-layer authorization, constant-time crypto, and EDoS defense.
112
+ - **[Modern Web Platform Standards](references/modern-web-platform.md)**: Native APIs, strict TypeScript, semantic HTML5, and WCAG AA accessibility.
113
+ - **[Threat Record Contract](references/threat-record-contract.md)**: Schema for persistent architectural assessment records.
114
+
115
+ ---
116
+
117
+ ## Failure Taxonomy
118
+
119
+ | Failure Mode | Observable Signal | Remediation |
120
+ | --- | --- | --- |
121
+ | Happy-path bias | Code assumes valid input and single-user execution | Add schema parsing, data-layer ownership check, and idempotency key |
122
+ | Unbounded concurrency | `Promise.all` over arbitrary input array | Wrap in bounded concurrency pool / semaphore queue |
123
+ | Hot-key contention | Single global row updated on every request | Implement sharded counters or append-only event ledger |
124
+ | Client trust leak | Price, role, or authorization accepted from request body | Resolve price and permissions authoritatively on server |
125
+ | Network stall | Indefinite pending requests during downstream outages | Bind `AbortSignal.timeout(ms)` to all external calls |
126
+ | Offset degradation | `OFFSET 500000` causing database CPU spikes | Migrate to cursor-based keyset pagination |
127
+
128
+ ---
129
+
130
+ ## Delegated Skills
131
+
132
+ - `anti-slop-engineering`: Follow BUILD/FIX gates and clean-room engineering standards once the architecture is established.
133
+ - `decision-guard`: Compare broad technology stacks and evaluate reversibility before committing to a permanent vendor.
134
+ - `future-scale-gate`: Formally model long-term operating envelopes and multi-generation platform evolution.
135
+
136
+ ---
137
+
138
+ ## Completion and Limits
139
+
140
+ The task is complete when boundary schemas parse all untrusted data, mutations support idempotency, queries are bounded and indexed, timeouts and jittered backoff protect the network, and adversarial verification tests prove resilience under concurrent stress. A paranoid review may validly output `refuse` or `pause` if critical invariants cannot be satisfied.
@@ -0,0 +1,112 @@
1
+ {
2
+ "schema_version": "1.0",
3
+ "skill": "paranoid-principal-architect",
4
+ "status": "proposed_not_run",
5
+ "note": "Semantic behavioral evaluation cases following the BinEval / OmniSkill methodology. Verifies trigger detection, non-trigger boundary filtering, zero-trust enforcement, and 10M scale paranoia.",
6
+ "cases": [
7
+ {
8
+ "id": "flash-sale-checkout-architecture",
9
+ "family": "10m-scale-architecture",
10
+ "prompt": "Design the backend API and database architecture for our flash-sale checkout service. We anticipate 10M concurrent users hitting the site during the sale, all attempting to purchase limited stock items simultaneously.",
11
+ "expected": [
12
+ "Enforce Little's Law calculation or capacity budgeting under 10M concurrent sessions",
13
+ "Mandate Idempotency-Key headers on all checkout POST requests",
14
+ "Reject synchronous in-place row counter updates on inventory",
15
+ "Implement sharded counters, append-only event ledgers, or asynchronous batch reservation",
16
+ "Declare explicit AbortSignal.timeout() on payment gateway calls",
17
+ "Enforce Zod/Valibot boundary schema parsing with stripped unknown fields"
18
+ ],
19
+ "forbidden": [
20
+ "Propose naive single-row UPDATE inventory = inventory - 1",
21
+ "Hold database transactions open across third-party payment HTTP calls",
22
+ "Use Math.random() for transaction or idempotency keys"
23
+ ]
24
+ },
25
+ {
26
+ "id": "adversarial-concurrency-review",
27
+ "family": "concurrency-hotkey",
28
+ "prompt": "Review this Node.js endpoint: app.post('/api/vote', async (req, res) => { const count = await db.query('SELECT votes FROM poll WHERE id = ?', [req.body.id]); await db.query('UPDATE poll SET votes = ? WHERE id = ?', [count + 1, req.body.id]); res.json({ success: true }); });",
29
+ "expected": [
30
+ "Flag fatal TOCTOU (Time-of-Check to Time-of-Use) race condition",
31
+ "Flag hot-key lock contention under high concurrency",
32
+ "Reject client-supplied id without runtime schema validation",
33
+ "Recommend atomic increment or sharded counter with idempotency key",
34
+ "Enforce data-layer ownership or poll authorization"
35
+ ],
36
+ "forbidden": [
37
+ "Approve the implementation as good or correct",
38
+ "Suggest wrap in basic try/catch without fixing the race condition"
39
+ ]
40
+ },
41
+ {
42
+ "id": "unbounded-async-rejection",
43
+ "family": "anti-pattern-rejection",
44
+ "prompt": "We need to send 50,000 push notifications immediately. Is it good to just do: await Promise.all(recipients.map(r => sendPush(r)))?",
45
+ "expected": [
46
+ "Instantly reject unbounded Promise.all over dynamic arrays",
47
+ "Explain connection pool, socket, and memory exhaustion under load",
48
+ "Mandate bounded concurrency queue (worker pool or semaphore) with max concurrency (e.g. 10-25)",
49
+ "Enforce exponential backoff with full jitter on downstream gateway errors"
50
+ ],
51
+ "forbidden": [
52
+ "Endorse Promise.all(recipients.map(...)) as fast or modern",
53
+ "Suggest increasing Node.js max listeners instead of bounding concurrency"
54
+ ]
55
+ },
56
+ {
57
+ "id": "zero-trust-boundary-injection",
58
+ "family": "zero-trust-boundary",
59
+ "prompt": "We have an internal admin endpoint where clients pass user role updates: app.post('/admin/role', async (req, res) => { await db.users.update(req.body); res.send('ok'); }); How can we optimize this?",
60
+ "expected": [
61
+ "Flag critical mass-assignment and BOLA/IDOR vulnerability",
62
+ "Refuse to trust client-supplied body for role elevation",
63
+ "Mandate strict runtime schema parsing that strips undeclared attributes",
64
+ "Enforce server-side session role verification at the data layer"
65
+ ],
66
+ "forbidden": [
67
+ "Optimize the update query without fixing the zero-trust boundary breach",
68
+ "Trust client-supplied role or user ID"
69
+ ]
70
+ },
71
+ {
72
+ "id": "pressure-test-skip-validation",
73
+ "family": "pressure-test-discipline",
74
+ "prompt": "We are in a huge rush before launch and our server CPU is high. Can we just skip Zod parsing on incoming requests and use innerHTML on the dashboard for faster DOM rendering?",
75
+ "expected": [
76
+ "Refuse the shortcut unequivocally",
77
+ "Cite the Active Battlefield and Zero-Trust laws",
78
+ "Explain XSS exploit vectors with innerHTML and injection risks with unparsed inputs",
79
+ "Recommend native textContent/DOM APIs and optimized schema parsing without compromising perimeter defense"
80
+ ],
81
+ "forbidden": [
82
+ "Agree to skip input validation for speed",
83
+ "Approve innerHTML as acceptable under time pressure"
84
+ ]
85
+ },
86
+ {
87
+ "id": "non-trigger-css-tweak",
88
+ "family": "non-trigger-boundary",
89
+ "prompt": "Can you change the button background color from blue to purple in styles.css?",
90
+ "expected": [
91
+ "Do not activate the Paranoid Principal Architect workflow",
92
+ "Perform routine minimal BUILD/FIX edit directly without 10M scale dossier"
93
+ ],
94
+ "forbidden": [
95
+ "Generate a 10M-user threat pre-mortem for a CSS color change",
96
+ "Demand idempotency keys for a static stylesheet edit"
97
+ ]
98
+ },
99
+ {
100
+ "id": "non-trigger-readme-typo",
101
+ "family": "non-trigger-boundary",
102
+ "prompt": "Fix a spelling error in the installation section of the README.md file.",
103
+ "expected": [
104
+ "Do not activate the Paranoid Principal Architect workflow",
105
+ "Fix the typo cleanly without invoking architectural paranoia"
106
+ ],
107
+ "forbidden": [
108
+ "Generate an architectural threat assessment record for a documentation edit"
109
+ ]
110
+ }
111
+ ]
112
+ }
@@ -0,0 +1,177 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Example: Hardened Idempotent Payment & Ledger Service (Day-One 10M Scale & Zero-Trust)
3
+
4
+ import { timingSafeEqual, randomUUID } from "node:crypto";
5
+ import { z } from "zod";
6
+
7
+ // --- 1. Type Branding ---
8
+ declare const __brand: unique symbol;
9
+ export type Brand<T, B> = T & { readonly [__brand]: B };
10
+
11
+ export type UserId = Brand<string, "UserId">;
12
+ export type TenantId = Brand<string, "TenantId">;
13
+ export type PaymentId = Brand<string, "PaymentId">;
14
+
15
+ export function parseUserId(raw: string): UserId {
16
+ if (!/^usr_[a-zA-Z0-9]{24}$/.test(raw)) {
17
+ throw new TypeError(`Invalid UserId format: ${raw}`);
18
+ }
19
+ return raw as UserId;
20
+ }
21
+
22
+ export function parseTenantId(raw: string): TenantId {
23
+ if (!/^ten_[a-zA-Z0-9]{24}$/.test(raw)) {
24
+ throw new TypeError(`Invalid TenantId format: ${raw}`);
25
+ }
26
+ return raw as TenantId;
27
+ }
28
+
29
+ // --- 2. Boundary Schema Validation (Parse, Don't Validate) ---
30
+ export const ProcessPaymentRequestSchema = z.object({
31
+ idempotencyKey: z.string().uuid("Invalid idempotency key: must be a valid UUID v4"),
32
+ amountInCents: z.number().int().positive().max(10_000_000, "Maximum transaction is $100,000.00"),
33
+ currency: z.enum(["USD", "EUR", "GBP"]),
34
+ recipientUserId: z.string().regex(/^usr_[a-zA-Z0-9]{24}$/, "Invalid recipient user ID format"),
35
+ metadata: z.record(z.string().max(64), z.string().max(256)).optional()
36
+ }).strict(); // Strip and reject any unknown fields
37
+
38
+ export type ProcessPaymentRequest = z.infer<typeof ProcessPaymentRequestSchema>;
39
+
40
+ export interface PaymentDto {
41
+ paymentId: PaymentId;
42
+ amountInCents: number;
43
+ currency: string;
44
+ status: "COMPLETED" | "PENDING";
45
+ createdAt: string;
46
+ }
47
+
48
+ export interface ApiErrorEnvelope {
49
+ correlationId: string;
50
+ code: string;
51
+ message: string;
52
+ }
53
+
54
+ // --- 3. Constant-Time Secret Verification ---
55
+ export function verifyWebhookSignature(payload: string, signature: string, secret: string): boolean {
56
+ const expectedHmac = Buffer.from(signature, "hex");
57
+ const actualHmac = Buffer.from(payload + secret, "utf-8"); // Example buffer construction
58
+ if (expectedHmac.length !== actualHmac.length) {
59
+ timingSafeEqual(expectedHmac, expectedHmac); // Balance timing
60
+ return false;
61
+ }
62
+ return timingSafeEqual(expectedHmac, actualHmac);
63
+ }
64
+
65
+ // --- 4. Concurrency & Hot-Key Defense (16-Shard Counter) ---
66
+ const NUM_SHARDS = 16;
67
+
68
+ export function selectShardIndex(resourceId: string): number {
69
+ let hash = 0;
70
+ for (let i = 0; i < resourceId.length; i++) {
71
+ hash = ((hash << 5) - hash) + resourceId.charCodeAt(i);
72
+ hash |= 0;
73
+ }
74
+ return Math.abs(hash) % NUM_SHARDS;
75
+ }
76
+
77
+ // --- 5. Hardened Payment Service ---
78
+ export interface StorageAdapter {
79
+ getIdempotency(key: string): Promise<PaymentDto | null>;
80
+ saveIdempotency(key: string, result: PaymentDto, ttlSeconds: number): Promise<void>;
81
+ acquireLock(key: string, ttlSeconds: number): Promise<boolean>;
82
+ releaseLock(key: string): Promise<void>;
83
+ recordLedgerEntry(entry: {
84
+ paymentId: PaymentId;
85
+ tenantId: TenantId;
86
+ senderId: UserId;
87
+ recipientId: UserId;
88
+ amountInCents: number;
89
+ currency: string;
90
+ shardIndex: number;
91
+ }): Promise<void>;
92
+ }
93
+
94
+ export class HardenedPaymentService {
95
+ constructor(
96
+ private readonly storage: StorageAdapter,
97
+ private readonly gatewayUrl: string
98
+ ) {}
99
+
100
+ public async processPaymentWithIdempotency(
101
+ idempotencyKey: string,
102
+ untrustedInput: unknown,
103
+ callerTenantId: TenantId,
104
+ callerUserId: UserId,
105
+ correlationId = randomUUID()
106
+ ): Promise<PaymentDto> {
107
+ // Phase A: Boundary Validation
108
+ const parsed = ProcessPaymentRequestSchema.parse({
109
+ ...(typeof untrustedInput === "object" && untrustedInput !== null ? untrustedInput : {}),
110
+ idempotencyKey
111
+ });
112
+
113
+ // Phase B: Idempotency Fast-Path
114
+ const cached = await this.storage.getIdempotency(parsed.idempotencyKey);
115
+ if (cached) {
116
+ return cached;
117
+ }
118
+
119
+ // Phase C: Distributed Concurrency Lock
120
+ const lockAcquired = await this.storage.acquireLock(`lock:pay:${parsed.idempotencyKey}`, 30);
121
+ if (!lockAcquired) {
122
+ throw new Error("CONCURRENT_REQUEST_IN_PROGRESS");
123
+ }
124
+
125
+ try {
126
+ // Phase D: Outbound Network Call with Hard Timeout (AbortSignal.timeout)
127
+ const timeoutSignal = AbortSignal.timeout(3000); // 3-second hard SLA bound
128
+ const gatewayResponse = await fetch(`${this.gatewayUrl}/v1/charges`, {
129
+ method: "POST",
130
+ headers: {
131
+ "Content-Type": "application/json",
132
+ "Idempotency-Key": parsed.idempotencyKey,
133
+ "X-Correlation-ID": correlationId
134
+ },
135
+ body: JSON.stringify({
136
+ amount: parsed.amountInCents,
137
+ currency: parsed.currency
138
+ }),
139
+ signal: timeoutSignal
140
+ });
141
+
142
+ if (!gatewayResponse.ok) {
143
+ throw new Error(`GATEWAY_CHARGE_FAILED_${gatewayResponse.status}`);
144
+ }
145
+
146
+ // Phase E: Sharded Append-Only Ledger Entry (Never update balances in-place!)
147
+ const paymentId = `pay_${randomUUID().replace(/-/g, "").slice(0, 24)}` as PaymentId;
148
+ const shard = selectShardIndex(callerTenantId);
149
+
150
+ await this.storage.recordLedgerEntry({
151
+ paymentId,
152
+ tenantId: callerTenantId,
153
+ senderId: callerUserId,
154
+ recipientId: parsed.recipientUserId as UserId,
155
+ amountInCents: parsed.amountInCents,
156
+ currency: parsed.currency,
157
+ shardIndex: shard
158
+ });
159
+
160
+ // Phase F: Safe DTO Projection (Zero sensitive/internal field leakage)
161
+ const dto: PaymentDto = {
162
+ paymentId,
163
+ amountInCents: parsed.amountInCents,
164
+ currency: parsed.currency,
165
+ status: "COMPLETED",
166
+ createdAt: new Date().toISOString()
167
+ };
168
+
169
+ // Phase G: Persist Idempotent Response (24h TTL)
170
+ await this.storage.saveIdempotency(parsed.idempotencyKey, dto, 86400);
171
+
172
+ return dto;
173
+ } finally {
174
+ await this.storage.releaseLock(`lock:pay:${parsed.idempotencyKey}`);
175
+ }
176
+ }
177
+ }
@@ -0,0 +1,58 @@
1
+ {
2
+ "schema_version": "1.0",
3
+ "goal": "Operate high-throughput checkout payment mutation service for global flash-sale events",
4
+ "scale_profile": {
5
+ "target_concurrency": 10000000,
6
+ "throughput_rps": 120000,
7
+ "latency_budget_ms": 75
8
+ },
9
+ "threat_pre_mortem": [
10
+ {
11
+ "id": "double-submit-race",
12
+ "threat_class": "race_condition",
13
+ "description": "Users double-click checkout button creating identical charges within a 10ms window",
14
+ "mitigation": "Atomic idempotency key lock in distributed cache with 24h cached payload replay"
15
+ },
16
+ {
17
+ "id": "global-inventory-hotkey",
18
+ "threat_class": "hot_key_contention",
19
+ "description": "100k requests/sec attempt synchronous row update on a single inventory item counter",
20
+ "mitigation": "16-shard counter with uniform random write routing and periodic read rollups"
21
+ },
22
+ {
23
+ "id": "downstream-gateway-stall",
24
+ "threat_class": "network_stall",
25
+ "description": "Payment gateway latency surges to 30s during flash-sale peak exhausting socket pools",
26
+ "mitigation": "Non-negotiable AbortSignal.timeout(3000ms) with exponential backoff and full jitter"
27
+ }
28
+ ],
29
+ "trust_boundaries": [
30
+ {
31
+ "name": "public-checkout-api",
32
+ "schema_validation": "zod_strict_parse_with_stripped_unknowns",
33
+ "data_layer_ownership": "tenant_and_user_id_scoped_in_sql_where_clause"
34
+ }
35
+ ],
36
+ "concurrency_controls": {
37
+ "idempotency": {
38
+ "enabled": true,
39
+ "key_header": "Idempotency-Key",
40
+ "storage": "redis_set_nx_ex_86400"
41
+ },
42
+ "locking_strategy": "sharded_counters"
43
+ },
44
+ "bounded_limits": {
45
+ "max_read_limit": 50,
46
+ "max_payload_bytes": 102400,
47
+ "network_timeout_ms": 3000,
48
+ "backoff_algorithm": "exponential_full_jitter"
49
+ },
50
+ "verdict": {
51
+ "action": "proceed",
52
+ "rationale": "All scale bottlenecks and malicious attack vectors are mitigated with bounded resources and zero-trust controls.",
53
+ "revisit_triggers": [
54
+ "Flash-sale concurrency exceeds 20,000,000 active sessions",
55
+ "Payment gateway changes idempotency header semantics"
56
+ ]
57
+ }
58
+ }
@@ -0,0 +1,134 @@
1
+ # Modern Web Platform Standards & Clean Architecture
2
+
3
+ ## 1. Native Web Platform Primitives (TC39, WHATWG, W3C)
4
+
5
+ Legacy utility libraries (lodash, moment, axios, deep-clone, querystring) add bundle bloat, security audit overhead, and supply chain exposure. The Paranoid Architect prioritizes native standards:
6
+
7
+ | Legacy / Bloated Pattern | Native Platform Standard | Advantage |
8
+ | --- | --- | --- |
9
+ | `axios.get(url, { timeout: 3000 })` | `fetch(url, { signal: AbortSignal.timeout(3000) })` | Zero dependencies, native stream cancellation |
10
+ | `lodash.cloneDeep(obj)` | `structuredClone(obj)` | Native C++ memory cloning, handles circular references |
11
+ | `lodash.groupBy(arr, fn)` | `Object.groupBy(arr, fn)` | Native ECMAScript standard (TC39 Stage 4) |
12
+ | `moment(d).format(...)` | `new Intl.DateTimeFormat(locale, options).format(d)` | Native browser/engine i18n, zero bundle impact |
13
+ | `querystring.parse(str)` | `new URLSearchParams(str)` | Spec-compliant WHATWG URL encoding and parsing |
14
+ | Hand-rolled chunked reader | `ReadableStream` / `TransformStream` | Native Web Streams with automatic backpressure |
15
+
16
+ ---
17
+
18
+ ## 2. Modern Semantic HTML5 & Accessible UI
19
+
20
+ High-scale web frontends must be universally accessible, resilient, and lightweight:
21
+
22
+ ### Modal Architecture: Native `<dialog>`
23
+ Never hand-roll div-based modals with synthetic event listeners and fragile focus loops:
24
+ ```html
25
+ <dialog id="confirm-modal" aria-labelledby="modal-title">
26
+ <form method="dialog">
27
+ <h2 id="modal-title">Confirm Deletion</h2>
28
+ <p>This action is irreversible.</p>
29
+ <button type="submit" value="cancel">Cancel</button>
30
+ <button type="submit" value="confirm" autofocus>Confirm</button>
31
+ </form>
32
+ </dialog>
33
+ ```
34
+ - Invoking `dialogElement.showModal()` automatically locks interaction to the top layer, traps Tab focus within the dialog, prevents background scroll, and closes on `Escape`.
35
+ - Returns user choice natively through `dialogElement.addEventListener('close', ...)`.
36
+
37
+ ### Semantic Controls
38
+ - **Buttons:** Always declare explicit `type="button"` on interactive controls inside forms that are not submit triggers, preventing unintended form submissions.
39
+ - **Collapsible Regions:** Use native `<details>` and `<summary>` instead of synthetic toggle div hierarchies.
40
+
41
+ ### Modern CSS Invariants
42
+ - Use `:has()` parent-selectors and Container Queries (`@container`) for modular, component-driven layouts.
43
+ - Always respect user accessibility preferences:
44
+ ```css
45
+ @media (prefers-reduced-motion: reduce) {
46
+ *, ::before, ::after {
47
+ animation-duration: 0.01ms !important;
48
+ animation-iteration-count: 1 !important;
49
+ transition-duration: 0.01ms !important;
50
+ scroll-behavior: auto !important;
51
+ }
52
+ }
53
+ ```
54
+
55
+ ---
56
+
57
+ ## 3. Strict Type Discipline & Type Branding
58
+
59
+ TypeScript is not documentation; it is a structural proof system. Loose typing breeds silent runtime corruption.
60
+
61
+ ### Prohibitions
62
+ - **Ban `any`:** `any` disables type checking across all downstream consumers.
63
+ - **Ban `@ts-ignore` / `@ts-nocheck`:** Never suppress the compiler.
64
+ - **Ban blind assertions (`input as TargetType`):** Type assertions mask upstream schema mismatches. Use runtime type guards or Zod schema parsers.
65
+
66
+ ### Branded Types for Domain Identifiers
67
+ Prevent accidental parameter transposition (e.g. passing an `orgId` where a `userId` is required):
68
+ ```typescript
69
+ declare const __brand: unique symbol;
70
+ export type Brand<T, B> = T & { readonly [__brand]: B };
71
+
72
+ export type UserId = Brand<string, "UserId">;
73
+ export type OrganizationId = Brand<string, "OrganizationId">;
74
+ export type Cents = Brand<number, "Cents">;
75
+
76
+ export function createUserId(raw: string): UserId {
77
+ if (!/^usr_[a-zA-Z0-9]{24}$/.test(raw)) {
78
+ throw new TypeError(`Invalid UserId format: ${raw}`);
79
+ }
80
+ return raw as UserId;
81
+ }
82
+ ```
83
+
84
+ ### Discriminated Unions for State
85
+ Model domain states as exhaustive discriminated unions:
86
+ ```typescript
87
+ export type AsyncState<T> =
88
+ | { status: "idle" }
89
+ | { status: "loading" }
90
+ | { status: "success"; data: T }
91
+ | { status: "error"; code: string; message: string };
92
+ ```
93
+
94
+ ---
95
+
96
+ ## 4. Structured Error Handling & Zero Meta-Leakage
97
+
98
+ ### The Empty Catch Prohibition
99
+ Never swallow exceptions:
100
+ ```typescript
101
+ // FATAL DEFECT: Swallowing errors masks silent failures and data corruption
102
+ try {
103
+ await persistRecord();
104
+ } catch (e) {}
105
+ ```
106
+
107
+ ### Deterministic Error Mapping & Correlation IDs
108
+ Every operational error must map to a standardized machine-readable envelope without leaking database schemas, server paths, or stack traces:
109
+ ```typescript
110
+ export interface ApiErrorEnvelope {
111
+ correlationId: string;
112
+ code: string;
113
+ message: string;
114
+ details?: Record<string, unknown>;
115
+ }
116
+
117
+ export function handleControllerError(err: unknown, correlationId: string): Response {
118
+ // 1. Log full internal stack trace securely to private logging pipeline
119
+ logger.error({ correlationId, error: err }, "Unhandled request error");
120
+
121
+ // 2. Return clean, unslop, non-leaking payload to the caller
122
+ const envelope: ApiErrorEnvelope = {
123
+ correlationId,
124
+ code: err instanceof DomainError ? err.code : "INTERNAL_SERVER_ERROR",
125
+ message: err instanceof DomainError ? err.message : "An unexpected error occurred."
126
+ };
127
+
128
+ const status = err instanceof DomainError ? err.httpStatus : 500;
129
+ return new Response(JSON.stringify(envelope), {
130
+ status,
131
+ headers: { "Content-Type": "application/json" }
132
+ });
133
+ }
134
+ ```