2654-zed/latent-flux
GitHub: 2654-zed/latent-flux
一个基于几何流形与在线学习的链上行为威胁情报系统,专注于 L2 实时风险感知与 AI 代理预交易筛查。
Stars: 0 | Forks: 0
# Layer 3 — 链上行为威胁情报
**当前运行:** 一个被动的监控系统,实时监控 Base、Arbitrum 和 Optimism 上的智能合约部署。检测陷阱合约(蜜罐、Permit2 盗取者、费用抽成机器人),追踪组织结构,记录活跃的犯罪操作,并为 AI 代理框架提供预交易风险 API。
**实时部署:** `https://spypy.up.railway.app` — 自 2026 年 3 月起在 Railway 上 24/7 运行。语料库:124,341 个合约,117 万笔交易事件,36,115 个部署者覆盖 3 条链。记录了 1000‑1500 万美元以上的盗取操作,追踪到 7 个违规协助者。
## 运行(3 条命令)
```
git clone https://github.com/2654-zed/latent-flux.git && cd latent-flux
pip install -r requirements.txt
ARB_WSS_URL=wss://... BASE_WSS_URL=wss://... OP_WSS_URL=wss://... python run_surveillance.py
```
然后调用 API:
```
curl http://localhost:8080/stats # corpus metrics
curl http://localhost:8080/api/v1/agent/screen/base/0x # pre-tx risk score for AI agents
curl http://localhost:8080/api/v1/agent/facilitator/0x # x402 facilitator validation
```
`/api/v1/agent/screen` 端点返回 `{risk_score, risk_tier, capabilities, recommendation: "DO_NOT_APPROVE" | "CAUTION" | "PROCEED" | "UNVERIFIED"}` —— 设计用于在 AI 代理签署任何批准前调用。
## 完整文档
- **端到端系统:** [`surveillance/ARCHITECTURE.md`](surveillance/ARCHITECTURE.md) —— 流式摄入、SQLite 架构、所有启发式模块、完整 API 表面
- **解释框架:** [`L3_TOPOLOGY_FRAMEWORK.md`](L3_TOPOLOGY_FRAMEWORK.md) —— 五原语风险模型(位置、权限、信任绑定、可变性、观察)
- **设计原则:** [`claude.md`](claude.md) —— 地面真相、保守分类、不可变记录
- **更正日志:** [`CORRECTIONS.md`](CORRECTIONS.md) —— 每个被质疑的主张及其解决方案
## 目录
1. [语言原语](#language-primitives)
2. [执行模型](#execution-model)
3. [表达式语法](#expression-syntax)
4. [流水线语义](#pipeline-semantics)
5. [REPL](#repl)
6. [快速开始](#quick-start)
7. [完整 API 参考](#full-api-reference)
8. [TSP 证明概念](#tsp-proof-of-concept)
9. [可视化](#visualization)
10. [基准与杀测](#benchmarks--kill-tests)
11. [项目结构](#project-structure)
12. [测试](#tests)
13. [设计原则](#design-principles)
## 语言原语
Latent Flux 恰好有 **10 个原语**。它们在 ℝ^d 上操作连续状态,共同构成完整的计算周期:探索 → 流 → 批判 → 接受 → 提交 → 抽象 → 记忆 → 递归 → 竞争。
| 符号 | 名称 | 签名 | 语义 |
|------|------|--------|------|
| **⟼** | FluxManifold | `s₀, q, f → s*` | 连续流:迭代 `s ← s + ε·f(s, q)` 直到 `‖s − q‖ < tol` |
| **∑_ψ** | Superposition Tensor | `{sᵢ, wᵢ}ⁿ → batch` | 加权并行探索 N 个候选状态 |
| **∇↓** | Dimensional Squeeze | `ℝ^d → ℝ^k` 其中 `k < d` | 早期降维(PCA 或随机投影) |
| **≅** | Drift Equivalence | `(a, b, τ) → bool` | 近似相等:`‖a − b‖ ≤ τ`(L2 或余弦) |
| **↓!** | Commitment Sink | `s → s`(不可逆) | 当熵低或漂移稳定时锁定状态;不可撤销 |
| **◉** | Fold-Reference | `(s, step) → s'` | 流中的自我批判:检测 NaN、范数爆炸、越界并修正 |
| **⇑** | Abstraction Cascade | `ℝ^d → [ℝ^k₁, ℝ^k₂, …]` | 逐层 PCA 降维的抽象摘要 |
| **⧖** | Reservoir State | `s → s`(记忆) | 通过 ESN 动力学实现连续记忆;信息跨步长回响 |
| **↺** | Recursive Flow | `s₀, q → s*` | 几何终止的定点迭代(吸引子收敛或熵崩溃) |
| **⊗** | Attractor Competition | `s, {aₖ} → winner` | 几何模式匹配:状态在多吸引子下流动,盆地决定胜者 |
### 形式定义
**⟼ FluxManifold(流收敛)**
```
Given s₀ ∈ ℝ^d, q ∈ ℝ^d, f: ℝ^d × ℝ^d → ℝ^d, ε ∈ (0,1), τ > 0:
δ = ε · f(s, q)
δ ← clip(δ, ‖δ‖ ≤ 1) # overflow guard
δ ← δ · min(1, ‖q−s‖/‖δ‖) # overshoot prevention
s ← s + δ
converged ⟺ ‖s − q‖ < τ
```
在单个状态 `(d,)` 或批次 `(N, d)` 上操作。批处理模式共享同一个吸引子,并在单个向量化循环中评估所有 N 个状态。
**∑_ψ Superposition Tensor**
```
Given N states {s₁, …, sₙ} ∈ ℝ^(N×d) with weights w ∈ Δ^N (probability simplex):
flow_all(q, f) → batch ⟼ for all N states simultaneously
reweight(q) → wᵢ ∝ softmax(−‖sᵢ − q‖)
collapse_best → argmin_i ‖sᵢ − q‖
collapse_mean → Σ wᵢ · sᵢ
entropy → −Σ wᵢ log₂ wᵢ (high = spread, low = collapsed)
prune(k) → keep top-k by weight
```
**∇↓ Dimensional Squeeze**
```
fit(X) → learn projection P ∈ ℝ^(k×d) (PCA eigenvectors or random Gaussian)
squeeze(s) → P · s ∈ ℝ^k
unsqueeze(z) → P^T · z ∈ ℝ^d (lossy reconstruction)
```
**≅ Drift Equivalence**
```
L2: equivalent(a, b) ⟺ ‖a − b‖₂ ≤ τ
Cosine: equivalent(a, b) ⟺ 1 − cos(a, b) ≤ τ
quality(s, t) = max(0, 1 − distance(s,t)/τ) ∈ [0, 1]
```
**↓! Commitment Sink**
```
Triggers when EITHER:
entropy(∑_ψ) < threshold (weight collapse)
mean(drift_trace[−window:]) < drift_threshold (convergence plateau)
commit(s) → frozen copy. Second commit → error.
```
**◉ Fold-Reference**
```
At every `interval` steps during flow:
(ok, diagnosis, correction) = critique_fn(s)
if ¬ok: s ← correction; log(diagnosis)
Built-in critiques:
no_nan_critique → reject NaN/Inf, replace with zeros
norm_bound(M) → clip if ‖s‖ > M
crossing_repulsion → geometric gradient to uncross TSP edges
```
**⇑ Abstraction Cascade**
```
Given states S ∈ ℝ^(N×d):
level_0: S projected to ℝ^k₁ via PCA (k₁ = d/2)
level_1: level_0 projected to ℝ^k₂ (k₂ = k₁/2)
…
level_L: ℝ^(max(k_L, min_dim))
Each level returns: {dim, states, components, explained_variance_ratio}
```
**⧖ Reservoir State (ESN 连续记忆)**
```
Given input x(t) ∈ ℝ^d, reservoir hidden state h(t) ∈ ℝ^r where r = scale × d:
h(t+1) = (1 − leak_rate) · h(t) + leak_rate · tanh(W_in · x(t) + W_res · h(t))
y(t) = W_out · h(t+1) ∈ ℝ^d (readout projection)
Spectral radius of W_res < 1.0 guarantees echo state property (fading memory).
commit() → returns W_out · h, discards history, locks reservoir (linear type).
```
**↺ Recursive Flow(定点迭代)**
```
Given s₀ ∈ ℝ^d, attractor q, flow function f:
repeat:
s_{t+1} = inner_flow(s_t, q, f, inner_steps)
if ‖s_{t+1} − q‖ < tol: terminate (attractor_reached)
if s_{t+1} ≅ s_t: terminate (fixed_point)
if t > max_iterations: terminate (timeout)
return s_final
Termination is geometric: either the attractor captures the state,
or successive iterations map to the same point (fixed point).
```
**⊗ Attractor Competition(几何模式匹配)**
```
Given state x ∈ ℝ^d, attractors {a₁, …, aₖ} ∈ ℝ^(K×d):
For each step:
pull_k = f(x, aₖ) (attraction to each basin)
repel_k = −ρ · Σ_{j≠k} (aₖ − aⱼ)/‖aₖ − aⱼ‖² (inter-attractor repulsion)
x ← x + ε · mean(pull_k + repel_k)
Winner = argmin_k ‖x − aₖ‖
Replaces if/else branching with geometric basin membership.
```
## 执行模型
解释器协调全部 10 个原语。核心流水线按顺序运行 7 步;剩余 3 步(⧖、↺、⊗)是可组合的扩展:
```
Input: attractor q ∈ ℝ^d
┌────────────────────────────────────────────────────────┐
│ 1. ∇↓ Dimensional Squeeze (compress if high-d) │
│ 2. ∑_ψ Superposition Tensor (N random candidates) │
│ 3. ⟼ FluxManifold (batch flow → q) │
│ 3b.⧖ Reservoir State (ESN memory, optional) │
│ 4. ◉ Fold-Reference (self-critique) │
│ 5. ≅ DriftEquivalence (accept if close) │
│ 6. ↓! Commitment Sink (irreversible lock) │
│ 7. ⇑ Abstraction Cascade (hierarchical view) │
└────────────────────────────────────────────────────────┘
Composable extensions (usable in parser pipelines):
┌────────────────────────────────────────────────────────┐
│ ↺ Recursive Flow (fixed-point iteration) │
│ ⊗ Attractor Competition (geometric classification)│
└────────────────────────────────────────────────────────┘
Output: {committed_state, equivalence_quality, abstraction_levels, ...}
```
**批处理向量化。** 第 3 步(⟼)在单个 NumPy 循环迭代中并行运行所有 N 个候选;流函数 `f(S, q)` 接收 `(N, d)` 并返回 `(N, d)` 梯度。每个状态的收敛性通过布尔掩码跟踪;已收敛状态被原地冻结。
**无顺序污染。** 叠加的 `flow_all()` 委托给 `flux_flow_traced_batch()`,它在每个时间步处理完整的 `(N, d)` 矩阵,不存在候选之间的串行依赖。
## 表达式语法
Latent Flux 拥有专用的表达式解析器,可将源代码文本编译为 AST 并作为流水线求值。
### 语法
```
pipeline ::= atom (OP atom?)*
atom ::= vector | number | symbol | func_call | '(' pipeline ')'
vector ::= '[' number (',' number)* (';' number (',' number)*)* ']'
func_call ::= IDENT '(' args ')'
OP ::= '⟼' | '∇↓' | '≅' | '↓!' | '⇑' | '◉' | '∑_ψ' | '⧖' | '↺' | '⊗'
| '->' | 'squeeze' | '~=' | 'commit' | 'cascade' | 'fold' | 'sum_psi'
| 'reservoir' | 'recurse' | 'compete' | '|'
```
### 运算符
| Unicode | ASCII 别名 | 操作数 | 描述 |
|---------|-------------|---------|------|
| `⟼` | `->`, `flow` | 目标向量 | 将当前状态流向目标 |
| `∑_ψ` | `sum_psi`, `superpose` | 状态(s) | 创建或标记为叠加 |
| `∇↓` | `squeeze` | 整数 `k` | 挤压到 `k` 维 |
| `≅` | `~=`, `equiv` | 浮点容差 | 检查漂移等价 |
| `↓!` | `commit` | — | 提交(不可逆) |
| `⇑` | `cascade` | 整数层级 | 构建抽象级联 |
| `◉` | `fold` | — | 应用折叠参考批判 |
| `⧖` | `reservoir` | — | 通过水库(连续记忆)步进 |
| `↺` | `recurse` | 目标向量 | 递归流向固定点 |
| `⊗` | `compete` | 吸引子矩阵 | 吸引子竞争(几何分类) |
| `\|` | `\|` | — | 通用管道(传递值) |
### 内置函数
| 函数 | 签名 | 返回值 |
|------|-------|--------|
| `random(n, d)` | 整数, 整数 | 包含 N 个在 ℝ^d 中随机状态的 SuperpositionTensor |
| `zeros(d)` | 整数 | ℝ^d 中的零向量 |
| `ones(d | 整数 | ℝ^d 中的全一向量 |
| `randn(d)` | 整数 | ℝ^d 中的标准正态向量 |
| `linspace(a, b, n)` | 浮点, 浮点, 整数 | 均匀间隔的 1D 向量 |
| `nearest_neighbor(cities)` | (n,2) 数组 | 编码为连续状态的 NN 路径 |
### 示例
```
# 流向单一吸引子
[0.5, 0.5] ⟼ [1, 1]
# 在 ℝ^32 上叠加 10 个随机候选,流向并提交
∑_ψ random(10, 32) ⟼ zeros(32) | ↓!
# 带挤压 + 级联的完整流水线
random(10, 64) | superpose | squeeze 16 | -> zeros(16) | fold | ~= 0.05 | commit | cascade 3
# REPL 中的变量赋值
x = random(5, 8)
x ⟼ ones(8) | ↓!
```
## 流水线语义
求值按 **从左到右** 进行。每个操作符接收前一阶段的结果作为隐式输入:
```
∑_ψ random(5, 8) ⟼ zeros(8) | ↓!
│ │ │ │
│ Create 5×8 │ Flow all │ │ Commit best
│ superposition │ toward 0 │ │ (irreversible)
│ │ │ │
└──────────────────┴────────────┴───┘
pipeline result: committed ndarray (8,)
```
**类型传播规则:**
| 输入类型 | 操作符 | 输出类型 |
|----------|--------|----------|
| `ndarray (d,)` | `⟼ target` | `ndarray (d,)`(流动后的状态) |
| `SuperpositionTensor` | `⟼ target` | `SuperpositionTensor`(所有状态均流动) |
| `SuperpositionTensor` | `↓!` | `ndarray (d,)`(坍缩为最佳) |
| `any` | `∑_ψ` | `SuperpositionTensor` |
| `ndarray (d,)` | `∇↓ k` | `ndarray (k,)` |
| `SuperpositionTensor` | `∇↓ k` | `SuperpositionTensor`(挤压后) |
| `any` | `≅ τ` | `dict {equivalent, quality, distance}` |
| `any` | `⇑ L` | `list[dict]`(级联层级) |
| `any` | `◉` | 相同类型(可能被修正) |
## REPL
带 `LF>` 提示符的交互式读-求值-打印循环。
```
python -m flux_manifold.repl
```
### 语法
```
LF> [0.5, 0.5] ⟼ [1, 1]
LF> x = random(5, 8)
LF> x ⟼ ones(8) | ↓!
↓! committed (entropy)
→ array(...)
LF> :vars
LF> :set epsilon 0.05
LF> :help
LF> :quit
```
### 命令
| 命令 | 效果 |
|------|------|
| `:help` | 显示语法参考 |
| `:vars` | 列出所有已绑定变量 |
| `:reset` | 清除变量与承诺状态 |
| `:set epsilon ` | 设置流动步长 |
| `:set tol ` | 设置收敛容差 |
| `:set maxsteps ` | 设置迭代上限 |
| `:set flow ` | 切换流动函数(`normalize`、`sin`、`damped`、`adaptive`) |
| `:set seed ` | 设置 RNG 种子 |
| `:quit` / `:q` / `:exit` | 退出 |
赋值:`x = ` 或 `let x = ` 将结果绑定到 `x`。
当 `↓!` 触发时自动打印提交消息(如 `↓! committed (entropy)`)。
## 快速开始
```
# 安装
pip install -r requirements.txt # numpy, scipy, matplotlib
# 运行所有基准测试 + TSP 演示
python run_benchmarks.py
# 运行测试
python -m pytest tests/ -v
# 启动 REPL
python -m flux_manifold.repl
```
### 最简 Python 示例
```
import numpy as np
from flux_manifold import (
flux_flow, flux_flow_traced, flux_flow_batch,
normalize_flow, SuperpositionTensor, LatentFluxInterpreter,
)
# 单流向
s0 = np.zeros(8)
q = np.ones(8)
result = flux_flow(s0, q, normalize_flow, epsilon=0.1)
# 结果 ≈ [1, 1, 1, 1, 1, 1, 1, 1]
# 追踪流向(返回包含 drift_trace、path、steps、converged 的字典)
trace = flux_flow_traced(s0, q, normalize_flow)
print(f"Converged in {trace['steps']} steps, drift: {trace['drift_trace'][-1]:.6f}")
# 批量流向(同时处理 N 个状态)
S = np.random.default_rng(42).standard_normal((16, 8))
converged = flux_flow_batch(S, q, normalize_flow) # (16, 8)
# 完整解释器流水线(全部 7 个原语)
interp = LatentFluxInterpreter(d=32, n_candidates=10)
result = interp.evaluate(q=np.ones(32))
print(f"Quality: {result['equivalence_quality']:.3f}, Steps: {result['total_steps']}")
```
### 表达式解析器
```
from flux_manifold.parser import run
# 解析并计算 Latent Flux 表达式
result = run("∑_ψ random(5, 8) ⟼ zeros(8) | ↓!")
print(result) # committed ndarray (8,)
# 使用 ASCII 别名
result = run("random(10, 32) | superpose | -> zeros(32) | commit")
```
## 完整 API 参考
### 核心引擎 — `flux_manifold.core`
```
FlowFn = Callable[[np.ndarray, np.ndarray], np.ndarray] # f(s, q) → delta
flux_flow(s0, q, f, epsilon=0.1, tol=1e-3, max_steps=1000) → np.ndarray
# Single state (d,) → converged state (d,)
flux_flow_traced(s0, q, f, epsilon=0.1, tol=1e-3, max_steps=1000) → dict
# → {converged_state, steps, converged, drift_trace, path}
flux_flow_batch(S, q, f, epsilon=0.1, tol=1e-3, max_steps=1000) → np.ndarray
# Batch (N,d) → converged states (N,d). Vectorized, no Python loop over N.
flux_flow_traced_batch(S, q, f, epsilon=0.1, tol=1e-3, max_steps=1000) → dict
# → {converged_states (N,d), steps (N,), converged (N,),
# total_steps (int), drift_traces (max_iters, N)}
```
**约束条件:** `d ≤ 1024`,`ε ∈ (0, 1)`,`tol > 0`,`max_steps ≥ 1`。
### 流函数 — `flux_manifold.flows`
所有流函数均支持 `(d,)` 或 `(N, d)` 输入并通过广播处理。
| 函数 | 公式 | 行为 |
|------|--------|------|
| `normalize_flow(s, q)` | `(q − s) / ‖q − s‖` | 单位步长向 q 移动 |
| `sin_flow(s, q)` | `sin(‖q − s‖) · (q − s) / ‖q − s‖` | 曲线逼近 |
| `damped_flow(s, q)` | `(q − s) · ‖q − s‖ / (1 + ‖q − s‖)` | 比例阻尼 |
| `adaptive_flow(s, q)` | `(q − s) / (1 + ‖q − s‖²)` | 接近吸引子时更柔和 |
| `repulsive_flow(s, q)` | `−(q − s) / ‖q − s‖` | 推开(用于对抗性/测试) |
### SuperpositionTensor — `flux_manifold.superposition`
```
st = SuperpositionTensor(states: np.ndarray, weights: np.ndarray | None = None)
st = SuperpositionTensor.from_random(n=16, d=64, seed=42, scale=1.0)
st.flow_all(q, f, epsilon, tol, max_steps) → dict # batch trace
st.reweight_by_drift(q) → None # softmax re-weight
st.collapse_to_best(q) → ndarray # nearest to q
st.collapse_to_mean() → ndarray # weighted centroid
st.prune(keep=5) → None # top-k by weight
st.entropy() → float # Shannon entropy (bits)
st.mean_state() → ndarray # weighted average
```
**属性:** `states (N,d)`、`weights (N,)`、`n`、`d`
### DriftEquivalence — `flux_manifold.drift_equivalence`
```
de = DriftEquivalence(tolerance=0.05, metric="l2") # or "cosine"
de.equivalent(a, b) → bool
de.distance(a, b) → float
de.quality(s, t) → float # ∈ [0, 1]
de.best_equivalent(candidates, target) → (index, distance)
```
### CommitmentSink — `flux_manifold.commitment_sink`
```
cs = CommitmentSink(entropy_threshold=0.5, drift_window=10, drift_threshold=0.01)
cs.should_commit_entropy(superposition) → bool
cs.should_commit_drift(drift_trace) → bool
cs.commit(state, reason="manual") → ndarray # irreversible
cs.try_commit(superposition, q, drift_trace) → ndarray | None
```
**属性:** `committed (bool)`、`committed_state`、`commit_reason`、`state (property)`
### AbstractionCascade — `flux_manifold.abstraction_cascade`
```
ac = AbstractionCascade(levels=3, min_dim=2)
ac.cascade(states) → list[dict] # {level, dim, states, components, explained_variance_ratio}
ac.cascade_single(state) → list[dict] # {level, dim, state} (truncation-based)
```
### FoldReference — `flux_manifold.fold_reference`
```
fr = FoldReference(critique_fn, interval=10, max_corrections=50)
fr.check(state, step) → (corrected_state, was_corrected: bool)
fr.reset() → None
fr.corrections_count → int
fr.history → list[dict]
# 内置批评函数:
no_nan_critique(state) → (ok, diagnosis, correction | None)
norm_bound_critique(max_norm) → CritiqueFn # factory
```
### DimensionalSqueeze — `flux_manifold.dimensional_squeeze`
```
ds = DimensionalSqueeze(target_dim=16, method="pca") # or "random_projection"
ds.fit(data, seed=42) → self
ds.squeeze(state) → ndarray # (d,) → (k,) or (N,d) → (N,k)
ds.unsqueeze(compressed) → ndarray # (k,) → (d,) lossy
ds.compression_ratio → float | None
```
### ReservoirState — `flux_manifold.reservoir_state`
```
rs = ReservoirState(d=8, reservoir_scale=4, spectral_radius=0.9,
input_scaling=0.1, leak_rate=0.3, seed=42)
rs.step(x) → ndarray # evolve reservoir, return readout (d,)
rs.update(x) → ndarray # alias for step()
rs.readout() → ndarray # current readout without advancing
rs.read() → ndarray # alias for readout()
rs.commit() → ndarray # return readout, lock reservoir
rs.reset() → None # zero hidden state + clear history
rs.get_history(n) → list # last n hidden states (None = all)
rs.memory_bytes() → int # current allocation in bytes
rs.hidden_state → ndarray # (r,) current hidden state (copy)
rs.is_committed → bool
# 每候选候选的超级存储库(ESN 状态)
sp_rs = SuperpositionReservoir(n=16, d=8, leak_rate=0.3, seed=42)
sp_rs.step_all(states) → ndarray # (N, d) readouts
sp_rs.readout_all() → ndarray
sp_rs.reorder(indices) → None # keeps coupled with SuperpositionTensor
```
### RecursiveFlow — `flux_manifold.recursive_flow`
```
rf = RecursiveFlow(flow_fn, attractor, epsilon=0.1, tol=1e-3,
max_iterations=100, inner_steps=50,
fixed_point_tol=1e-4, seed=42)
result = rf.run(initial_state) → dict
result = rf.run_batch(states) → list[dict]
# 结果字典:
# final_state ndarray (d,)
# iterations int
# converged bool
# termination "attractor_reached" | "fixed_point" | "timeout"
# trajectory list[ndarray]
# drift_trace list[float]
# fixed_point_distances list[float]
```
### AttractorCompetition — `flux_manifold.attractor_competition`
```
ac = AttractorCompetition(
attractors, labels, flow_fn,
epsilon=0.1, tol=1e-2, max_steps=500,
repulsion=0.05, seed=42,
)
result = ac.compete(state) → dict
results = ac.compete_batch(states) → list[dict]
summary = ac.summary(results) → dict
# 结果字典:
# winner str (获胜吸引子的标签)
# winner_idx int
# margin float (距离间隔:第二接近 − 最近)
# certainty float ∈ [0, 1]
# contested bool (间隔 < 容差)
# trajectory list[ndarray]
```
### LatentFluxInterpreter — `flux_manifold.interpreter`
```
interp = LatentFluxInterpreter(
d=64, n_candidates=16, flow_fn=normalize_flow,
epsilon=0.1, tol=1e-3, max_steps=500,
equiv_tolerance=0.05, entropy_threshold=0.5,
drift_window=10, drift_commit_threshold=0.01,
cascade_levels=3, critique_fn=None, critique_interval=10,
squeeze_dim=None, use_reservoir=False, seed=42,
)
result = interp.evaluate(q, initial_states=None) → dict
# 返回:
# committed_state ndarray (d,)
# equivalence_quality float ∈ [0, 1]
# is_equivalent bool
# abstraction_levels list[dict]
# total_steps int
# converged_count int
# n_candidates int
# fold_corrections int
# superposition_entropy float
# commit_reason str
```
### 解析器与求值器 — `flux_manifold.parser`
```
from flux_manifold.parser import parse, evaluate, run, EvalContext
ast = parse("∑_ψ random(5, 8) ⟼ zeros(8)") # → LFPipeline AST
result = evaluate(ast, ctx) # → value
result = run("∑_ψ random(5, 8) ⟼ zeros(8)") # parse + eval
ctx = EvalContext(seed=42, epsilon=0.1, tol=1e-3, max_steps=500,
flow_name="normalize", on_message=print)
ctx.set("x", value)
ctx.get("x")
```
**AST 节点类型:** `LFVector`、`LFNumber`、`LFSymbol`、`LFFuncCall`、`LFPipeline`、`LFOp`
### TSP 求解器 — `flux_manifold.tsp_solver`
```
from flux_manifold import LatentFluxTSP, solve_tsp
# 基于类
solver = LatentFluxTSP(cities, n_candidates=20, epsilon=0.15, seed=42)
result = solver.solve()
# 单行
result = solve_tsp(cities, n_candidates=20, seed=42)
# 结果字典:
# best_tour list[int]
# best_length float
# nn_length float(最近邻基线)
# improvement_pct float
# total_steps int
# converged_count int
# fold_corrections int
# all_lengths list[float]
# 工具
tour_length(cities, order) → float
order_to_state(order, n_cities) → ndarray
state_to_order(state) → ndarray
nearest_neighbor_tour(cities) → ndarray
make_tsp_crossing_flow(cities, repulsion_strength=0.3) → FlowFn
make_crossing_critique(cities, repulsion_strength=0.3) → CritiqueFn
```
**交叉排斥** 替代离散的 2-opt 交换:对每对交叉边计算一个排斥向量,推动状态走向无交叉配置 —— 无需离散组合搜索。
### 可视化 — `flux_manifold.visualize`
所有函数均返回 `matplotlib.figure.Figure` 并接受可选的 `save_path` 参数。
```
from flux_manifold.visualize import (
plot_flow_2d, # 2D flow trajectory with arrows
plot_convergence, # Log-scale drift vs steps
plot_convergence_comparison, # Multi-trace overlay
plot_superposition_2d, # Scatter plot sized by weight
plot_tsp_tour, # Single TSP tour
plot_tsp_comparison, # Side-by-side tour grid
plot_cascade, # Bar chart per abstraction level
plot_commitment_timeline, # Dual-axis drift + entropy timeline
)
```
## TSP 证明概念
TSP 求解器展示了全部 7 个原语如何协同工作,解决真实的组合问题:
```
Cities ∈ ℝ^(n×2)
→ encode tour as continuous vector ∈ ℝ^n (order_to_state)
→ nearest_neighbor_tour → attractor q
→ ∑_ψ: 20 random tour candidates
→ ⟼: flow all candidates toward q via tsp_crossing_flow
→ ◉: geometric crossing repulsion (detect + resolve edge crossings)
→ ≅: accept tours within tolerance of best
→ ↓!: commit when entropy < threshold
→ ⇑: build abstraction hierarchy of final tour
→ decode best state back to permutation (state_to_order)
```
```
import numpy as np
from flux_manifold import solve_tsp
cities = np.random.default_rng(42).uniform(0, 100, (15, 2))
result = solve_tsp(cities, n_candidates=20)
print(f"Tour length: {result['best_length']:.1f} (NN baseline: {result['nn_length']:.1f})")
print(f"Improvement: {result['improvement_pct']:.1f}%")
```
## 基准与杀测
### 基准测试
| 等级 | 领域 | 通过标准 |
|------|------|----------|
| **A**(微基准) | 2D:s₀=[0,0] → q=[1,1] | 平均步数 < 10,方差 < 2,收敛率 100% |
| **B**(模拟) | 128D 随机流形 | t 检验 p < 0.05 且 Cohen's d > 0.5,优于随机游走 |
| **C**(玩具 ARC) | 网格嵌入 | 小规模谜题收敛(占位符) |
### 杀测(快速证伪)
| 测试 | 条件 | 判定失败 |
|------|------|----------|
| 收敛性 | 128D,100 次运行 | > 20% 未收敛 |
| 漂移 | 128D,50 次运行 | 任一最终漂移 > 容差 |
| 与随机游走对比 | 128D,50 次运行 | 胜率 < 50% |
| 可扩展性 | d=1024,10 次运行 | 平均耗时 > 5ms/次 |
| 对抗性 | 使用 repulsive_flow | 系统未能检测到发散 |
```
python run_benchmarks.py # Runs all tiers + kill tests + TSP demos
# Outputs to results/*.json, results/*.csv
```
## 项目结构
```
flux_manifold/
__init__.py # Public API + __all__ exports
core.py # ⟼ flux_flow, flux_flow_traced, _batch variants
flows.py # Vector fields: normalize, sin, damped, adaptive, repulsive
superposition.py # ∑_ψ SuperpositionTensor
drift_equivalence.py # ≅ DriftEquivalence
commitment_sink.py # ↓! CommitmentSink
abstraction_cascade.py # ⇑ AbstractionCascade
fold_reference.py # ◉ FoldReference + built-in critiques
dimensional_squeeze.py # ∇↓ DimensionalSqueeze
reservoir_state.py # ⧖ ReservoirState + SuperpositionReservoir (ESN)
recursive_flow.py # ↺ RecursiveFlow (fixed-point iteration)
attractor_competition.py # ⊗ AttractorCompetition (geometric classify)
convergence.py # Convergence contracts (Tier 1/2/3)
hamiltonian.py # Hamiltonian flow engine (§2 ontology)
quantum_interference.py # Quantum interference engine (§3 ontology)
topological_squeeze.py # Topological squeeze (§4 ontology)
flow_trace.py # Structured error diagnostics
interpreter.py # Full 10-primitive pipeline orchestrator
tsp_solver.py # TSP proof-of-concept (crossing repulsion)
parser.py # Expression parser + AST + evaluator (10 operators)
repl.py # Interactive REPL (LF> prompt)
pheno_log.py # Phenomenological logging (JSONL)
kalman_reservoir.py # ⧖+ KalmanReservoir (UKF-based state estimator)
changepoint.py # Bayesian Online Change Point Detection (BOCPD)
multi_scale_reservoir.py # Multi-timescale reservoir (micro/meso/macro)
visualize.py # 8 matplotlib plot functions
baselines.py # Random walk, gradient descent, static
benchmarks.py # Tier A/B/C benchmarks
kill_tests.py # 5 kill tests
monitor.py # JSON trace logging
backtest/
bellman_ford.py # Baseline arbitrage detector (Bellman-Ford)
latent_flux_searcher.py # Geometric arbitrage detector (FluxManifold)
data_ingestion.py # PoolState + JSON parsing
run_live_backtest.py # BF vs LF side-by-side harness
report.py # CSV + summary report generator
data/
uniswap_v3_30d.json # 30-day Uniswap V3 hourly data
tests/
test_core.py # Core engine + batch flow + safety
test_primitives.py # All 7 base primitives
test_interpreter.py # Interpreter + TSP + crossing repulsion
test_parser_repl.py # Tokenizer + parser + evaluator + REPL
test_convergence_reservoir.py # Reservoir + convergence tests
test_attractor_competition.py # Attractor competition (⊗)
test_recursive_flow.py # Recursive flow (↺)
test_infrastructure.py # Ontology infrastructure
test_ontology.py # Ontology expansion tests
test_benchmarks.py # Benchmark pass/fail assertions
test_baselines.py # Baseline correctness
test_visualize.py # Plot generation
proof/ # Proof test suite (5 properties + meta)
run_benchmarks.py # Entry point: all benchmarks + TSP demos
requirements.txt # numpy>=1.24, scipy>=1.10, matplotlib>=3.7
```
## 测试
409 个测试分布在 18 个测试文件中。
```
Given N states {s₁, …, sₙ} ∈ ℝ^(N×d) with weights w ∈ Δ^N (probability simplex):
flow_all(q, f) → batch ⟼ for all N states simultaneously
reweight(q) → wᵢ ∝ softmax(−‖sᵢ − q‖)
collapse_best → argmin_i ‖sᵢ − q‖
collapse_mean → Σ wᵢ · sᵢ
entropy → −Σ wᵢ log₂ wᵢ (high = spread, low = collapsed)
prune(k) → keep top-k by weight
```
| 文件 | 重点 | 数量 |
|------|------|------|
| `test_core.py` | 核心流动、批处理操作、输入验证、NaN/溢出安全 | 29 |
| `test_primitives.py` | ∑_ψ、≅、↓!、⇑、◉、∇↓ | 41 |
| `test_interpreter.py` | 完整流水线、TSP 编码、几何交叉 | 20 |
| `test_parser_repl.py` | 词法分析器、解析器、AST 求值、REPL 命令 | 85 |
| `test_convergence_reservoir.py` | ⧖ 水库 + 收敛性契约 | 55 |
| `test_attractor_competition.py` | ⊗ 吸引子竞争 + 安全演示 | 15 |
| `test_recursive_flow.py` | ↺ 递归流动 + 3 个测试问题 | 12 |
| `test_infrastructure.py` | 本体基础设施 | 37 |
| `test_ontology.py` | 本体扩展 | 39 |
| `test_benchmarks.py` | 等级 A/B/C、杀测 | 12 |
| `test_baselines.py` | 随机游走、梯度下降、静态基线 | 5 |
| `test_visualize.py` | 全部 8 个绘图函数 | 12 |
| `proof/` | 翻译、可表达性、认知、涌现、不可约性、元理论 | 47 |
## 设计原则
1. **无顺序污染。** 批处理操作完全通过 NumPy 广播向量化。`flow_all()` 调用 `flux_flow_traced_batch()` —— 每个时间步仅一次矩阵运算,而非对候选者进行 Python 循环。
2. **无人工启发式。** TSP 折叠参考使用连续几何交叉排斥,而非离散的 2-opt 交换。每次修正都是可微梯度,而非组合搜索。
3. **不可逆是特性。** `↓!`(承诺)不可撤销。这防止无限重审并强制系统收敛到决策。
4. **一切皆流动。** 不存在离散条件判断或布尔分支。循环通过几何终止(↺ 定点检测)结束;分类通过盆地归属(⊗ 吸引子竞争)实现;记忆通过连续动力学(⧖ 水库)实现。Python 安全阀(最大迭代次数、最大步数)是对宿主语言的妥协,而非逻辑本身。
5. **可组合原语。** 每个原语是独立的类,无隐藏依赖。解释器是一种可能的布线;解析器允许以任意顺序组合它们。
6. **可观测。** 每个操作产生可追踪输出:漂移轨迹、步数、收敛标志、熵值、修正历史。没有任何不透明内容。
## 回测系统
一个并排比较框架,用于在真实 Uniswap V3 小时数据(7,194 条记录、10 个资金池、721 小时、2026 年 2 月 8 日 – 3 月 10 日)上测试 Latent Flux 几何套利检测与 Bellman-Ford 基线的对比。
### 架构
```
backtest/
bellman_ford.py # Baseline: negative-cycle detection (immutable)
latent_flux_searcher.py # LF: geometric search via FluxManifold primitives
data_ingestion.py # PoolState dataclass + JSON parsing
run_live_backtest.py # Harness: BF vs LF on live data
report.py # CSV + summary generation
data/
uniswap_v3_30d.json # 30-day hourly pool snapshots
```
### 五阶段增强流水线
Latent Flux 搜索器已通过 5 个信号质量改进升级:
| 阶段 | 组件 | 文件 | 描述 |
|------|------|------|------|
| **1** | UKF + S-Score | `kalman_reservoir.py` | 无迹卡尔曼滤波器替代 EMA;每条边采用 OU 过程 S-Score |
| **2** | 变点检测 | `changepoint.py` | Adams & MacKay (2007) 在线 BOCPD(正态-伽玛先验);检测到变点时重置 UKF |
| **3** | SCC + Johnson 环 | `latent_flux_searcher.py` | Tarjan 强连通分量预筛选 + `networkx.simple_cycles` 完整枚举 |
| **4** | 费用层级过滤 + 气费成本 | `latent_flux_searcher.py` | 加权费用阈值、280k 气费估算、Flashbots 提示、`net_profit_usd` |
| **5** | 多时间尺度信号 | `multi_scale_reservoir.py` | 三并行水库(微/中/宏观),`scale_agreement ∈ [0,1]` |
### 新原语
**KalmanReservoir**(`flux_manifold/kalman_reservoir.py`)
```
from flux_manifold.kalman_reservoir import KalmanReservoir
kr = KalmanReservoir(d=20, process_noise=1e-4, measurement_noise=1e-3)
smoothed = kr.step(market_state) # same interface as ReservoirState
cov = kr.get_covariance() # posterior variance per dim
drifts = kr.get_drifts() # drift estimate per dim
regime = kr.regime_change_detected # True if BOCPD triggered this step
events = kr.changepoint_events # list of (step, dim) tuples
```
- 每条边 3 状态 UKF:`[log_price, drift, log_volatility]`
- Van der Merwe Sigma 点(α=1e-3, β=2, κ=0)
- 自适应增益:当创新 > 3σ 时 Q×10 放大
- 集成 BOCPD:检测到变点时自动重置滤波器
**BayesianChangePoint**(`flux_manifold/changepoint.py`)
```
from flux_manifold.changepoint import BayesianChangePoint
cp = BayesianChangePoint(hazard_rate=1/300, threshold=0.5)
for obs in observations:
prob = cp.update(obs) # returns P(r < 10)
if cp.is_changepoint():
print(f"Regime change at step {cp.step_count}")
```
- Adams & MacKay (2007) 在线 BOCPD
- 正态-伽玛共轭先验
- 运行长度跟踪(MAP),更新复杂度 O(T)
- 运行长度裁剪至 500 以限制内存
**MultiScaleReservoir**(`flux_manifold/multi_scale_reservoir.py`)
```
from flux_manifold.multi_scale_reservoir import MultiScaleReservoir
ms = MultiScaleReservoir(d=20)
outputs = ms.step(market_state) # dict of scale → smoothed
agreement = ms.get_scale_agreement() # ∈ [0, 1]
```
- 三个并行水库:微(泄漏 0.3,~3 小时)、中(泄漏 0.05,~20 小时)、宏(泄漏 0.01,~100 小时)
- 通过跨所有时间尺度的偏差方向相关性计算尺度一致性
### 信号元数据
每个 Latent Flux 信号都通过 `SignalMeta` 数据类进行增强:
```
@dataclass
class SignalMeta:
s_score: float # OU S-score (mean-reversion strength)
mean_reversion_speed: float # κ from OU fit
s_score_valid: bool # AR(1) fit quality
scale_agreement: float # multi-scale agreement [0, 1]
net_profit_usd: float # gross − gas − tip
fee_weighted_threshold: float # sum of fee rates along cycle
regime_change: bool # changepoint detected this block
```
### 30 天回测结果
```
Baseline: BF = 129 signals, LF = 203 signals
S-scores: 188/203 valid, Mean |S| = 0.14, Max |S| = 1.26
Changepoints: 200 events across 20 edge dimensions
Executable: 38/203 net-positive (max $4.09, total $39.74)
Scale agreement: mean = 1.0
High-confidence lead rate: 91.5%
```
### 运行回测
```
# 基线(EMA 存储库)
python backtest/run_live_backtest.py
# 完整增强流水线(UKF + BOCPD + 多尺度)
python backtest/run_live_backtest.py --use-kalman
```
## 约束
- 维度上限:`d ≤ 1024`
- 本地执行:不调用外部 API
- 确定性:默认 `seed=42` 以保证可重现
- 证明概念:非生产优化
## 依赖
```
numpy>=1.24
scipy>=1.10
matplotlib>=3.7
networkx>=3.0
Python ≥ 3.10
```
## 许可证
Unlicensed / experimental.
标签:$10-15M drain operation, 24/7 surveillance, AI代理框架, Arbitrum, Base, CAUTION, corpus analytics, deployer tracking, DO_NOT_APPROVE, drainer detection, fee skimmer, honeypot detection, Layer 3, On-Chain Behavioral Threat Intel, Optimism, Permit2 盗取, pre-transaction risk, PROCEED, rogue facilitators, SQLite, surveillance API, trap contract, UNVERIFIED, WebSocket, 不可变记录, 五原语风险模型, 依赖分析, 保守分类, 区块链威胁情报, 启发式模块, 智能合约部署, 流式摄入, 特权检测, 犯罪操作记录, 组织架构追踪, 蜜罐, 被动监控, 证书利用, 费用抽成, 逆向工具, 铁路部署, 链上分析, 陷阱合约, 预交易风险API, 风险等级, 风险评分