phy-concurrency-audit
Static concurrency and race-condition auditor for Go, Java, Python, Node.js/TypeScript. Detects shared-state mutations without locks (Go map races, Java non-atomic increments, Python thread/asyncio shared lists), TOCTOU (time-of-check-time-of-use) patterns across all languages, sync.Mutex copied by value, WaitGroup.Add inside goroutines, SimpleDateFormat as instance field, double-checked locking without volatile, asyncio shared state without Lock. Maps findings to CWE-362 (race condition) and CWE-367 (TOCTOU). Zero competitors on ClawHub — not a single concurrency-audit SKILL.md in 13,700+ files.
What this skill does
# phy-concurrency-audit
Static scanner for **race conditions** (CWE-362) and **TOCTOU vulnerabilities** (CWE-367) in Go, Java, Python, and Node.js/TypeScript codebases. Finds shared-state mutations without synchronization, unsafe concurrency patterns, and check-then-act anti-patterns. Zero external API calls, zero dependencies beyond Python 3 stdlib.
## Why Concurrency Bugs Are Special
- **Non-deterministic**: reproduce only under load, on multi-core machines, or on specific OS schedulers
- **Silent corruption**: data races don't crash immediately — they corrupt state silently for hours
- **Security impact**: TOCTOU races in file ops enable symlink attacks and privilege escalation (CWE-367)
- **Hard to test**: even `go test -race` only finds races that actually execute during the test run
- Static analysis catches the ones that never trigger in testing
## What It Detects
### Go Race Conditions
| Pattern | Severity | CWE |
|---------|----------|-----|
| Global `map` variable read/written in concurrent functions | CRITICAL | CWE-362 |
| `sync.Mutex` or `sync.RWMutex` copied by value after first use | HIGH | CWE-362 |
| `sync.WaitGroup.Add()` called inside a goroutine | HIGH | CWE-362 |
| Package-level slice/map mutated without mutex | HIGH | CWE-362 |
| `atomic.Value` used without checking type consistency | MEDIUM | CWE-362 |
| Missing `sync.Once` for lazy singleton initialization | MEDIUM | CWE-362 |
| Struct fields accessed in goroutines without receiver mutex | HIGH | CWE-362 |
### Java Thread-Safety Violations
| Pattern | Severity | CWE |
|---------|----------|-----|
| `count++` / `i++` on shared instance/static field without `synchronized` or `AtomicInteger` | HIGH | CWE-362 |
| `HashMap` or `ArrayList` as instance field in class with concurrent methods | HIGH | CWE-362 |
| `SimpleDateFormat` as `static` or instance field (not thread-safe) | HIGH | CWE-362 |
| Double-checked locking without `volatile` keyword | HIGH | CWE-362 |
| `synchronized` block on non-final field (lock can change) | MEDIUM | CWE-362 |
| `Vector`/`Hashtable` used (thread-safe but deprecated, miss modern happens-before) | LOW | CWE-362 |
| `Calendar.getInstance()` result stored as field | MEDIUM | CWE-362 |
### Python Threading & Asyncio
| Pattern | Severity | CWE |
|---------|----------|-----|
| Thread function mutating module-level list/dict without `threading.Lock` | HIGH | CWE-362 |
| `counter += 1` / `list.append()` on global var in thread without lock | HIGH | CWE-362 |
| `asyncio` coroutine mutating shared object without `asyncio.Lock` | HIGH | CWE-362 |
| `multiprocessing.Process` sharing mutable list/dict without `Manager` | HIGH | CWE-362 |
| `threading.Thread` target accessing `global` without lock | HIGH | CWE-362 |
### Node.js / TypeScript Async Races
| Pattern | Severity | CWE |
|---------|----------|-----|
| Module-level object/array mutated inside `async` request handler | HIGH | CWE-362 |
| TOCTOU: `await cache.has(key)` followed by `await cache.get(key)` | HIGH | CWE-367 |
| Counter increment `count++` in async handler (non-atomic) | MEDIUM | CWE-362 |
| Promise chain modifying shared closure variable | MEDIUM | CWE-362 |
### TOCTOU Patterns (All Languages)
| Pattern | Severity | CWE |
|---------|----------|-----|
| `os.path.exists(path)` followed by `open(path)` without lock | HIGH | CWE-367 |
| `os.path.isdir(d)` then `os.makedirs(d)` without exist_ok=True | MEDIUM | CWE-367 |
| `os.path.exists` then `os.rename/remove/chmod` | HIGH | CWE-367 |
| `if not User.exists()` then `User.create()` — DB check-then-insert | HIGH | CWE-367 |
| Java `File.exists()` then `new FileOutputStream(file)` | HIGH | CWE-367 |
| Node.js `fs.existsSync()` then `fs.writeFileSync()` | HIGH | CWE-367 |
| Go `os.Stat(path)` check then `os.Open(path)` | HIGH | CWE-367 |
## Implementation
```python
#!/usr/bin/env python3
"""
phy-concurrency-audit — Race condition & TOCTOU static scanner
Usage: python3 audit_concurrency.py [path] [--json] [--ci]
"""
import argparse
import json
import os
import re
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Optional
CRITICAL, HIGH, MEDIUM, LOW = "CRITICAL", "HIGH", "MEDIUM", "LOW"
SEV_ORDER = {CRITICAL: 0, HIGH: 1, MEDIUM: 2, LOW: 3}
ICONS = {CRITICAL: "🔴", HIGH: "🟠", MEDIUM: "🟡", LOW: "⚪"}
@dataclass
class Finding:
file: str
line: int
pattern_name: str
matched_text: str
severity: str
cwe: str
title: str
detail: str
fix: str
# ─── Pattern registry ────────────────────────────────────────────────────────
PATTERNS: dict[str, list] = {
".go": [
("GO_GLOBAL_MAP_RACE",
re.compile(r'^var\s+\w+\s*=\s*(?:map\[|make\s*\(\s*map)', re.MULTILINE),
HIGH, "CWE-362",
"Package-level map — likely shared across goroutines without mutex",
"Go maps are NOT goroutine-safe. Any concurrent read+write is a data race that can panic.",
"Protect with sync.RWMutex or replace with sync.Map for concurrent access."),
("GO_MUTEX_COPY",
re.compile(r'\b(?:sync\.Mutex|sync\.RWMutex)\b'),
HIGH, "CWE-362",
"sync.Mutex/RWMutex — verify it is not copied after first use",
"Copying a Mutex after first Lock/Unlock produces a copy of a locked mutex — deadlock.",
"Always pass Mutex by pointer (*sync.Mutex) or embed in struct accessed via pointer."),
("GO_WAITGROUP_ADD_IN_GOROUTINE",
re.compile(r'go\s+func\s*\([^)]*\)\s*\{[^}]*wg\.Add\s*\(', re.DOTALL),
HIGH, "CWE-362",
"WaitGroup.Add() inside goroutine — race between Add and Wait",
"If wg.Wait() is called before wg.Add() completes, Wait returns prematurely.",
"Always call wg.Add(n) BEFORE launching goroutines, not inside them."),
("GO_ATOMIC_VALUE_MISUSE",
re.compile(r'\batomic\.Value\b'),
MEDIUM, "CWE-362",
"atomic.Value — verify consistent type across Store/Load calls",
"Storing different types in the same atomic.Value panics at runtime.",
"Ensure all Store() calls use the same concrete type; document the stored type in a comment."),
],
".java": [
("JAVA_NON_ATOMIC_INCREMENT",
re.compile(r'(?:private|protected|public|static)\s+(?:int|long|volatile\s+int|volatile\s+long)\s+\w+\s*(?:=\s*\d+)?\s*;'),
HIGH, "CWE-362",
"Shared numeric field — verify increments use AtomicInteger/AtomicLong",
"count++ on a shared field is a read-modify-write that is NOT atomic — silently loses updates.",
"Replace int count with AtomicInteger count = new AtomicInteger(0); use count.incrementAndGet()."),
("JAVA_SHARED_HASHMAP",
re.compile(r'(?:private|protected|public)\s+(?:final\s+)?HashMap\s*<'),
HIGH, "CWE-362",
"HashMap as instance field — not thread-safe for concurrent access",
"Concurrent reads+writes to HashMap can cause infinite loop (Java 7) or data loss (Java 8+).",
"Replace with ConcurrentHashMap or wrap access with synchronized blocks."),
("JAVA_SHARED_ARRAYLIST",
re.compile(r'(?:private|protected|public)\s+(?:final\s+)?ArrayList\s*<'),
HIGH, "CWE-362",
"ArrayList as instance field — not thread-safe for concurrent modification",
"Concurrent modification throws ConcurrentModificationException or silently drops elements.",
"Replace with CopyOnWriteArrayList or Collections.synchronizedList(new ArrayList<>())."),
("JAVA_SIMPLE_DATE_FORMAT",
re.compile(r'(?:private|protected|public|static)\s+(?:final\s+)?SimpleDateFormat\b'),
HIGH, "CWE-362",
"SimpleDateFormat as instance/static field — not thread-safe",
"SimpleDateFormat maintains mutable state internally — concurrent use causes wrong dates or exceptions.",
"Use ThreadLocal<SimpleDateFormat> or replace with thread-safe DateTimeFormatter (Java 8+)."),
("JAVA_DOUBLE_CHECKERelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.