# 与DISE一起烹饪(第4部分):建立学习、适应和发展的系统

<!--category-- AI, DiSE, Architecture, Bot Detection, Machine Learning, Systems Design -->
<datetime class="hidden">2025-12-08T12:00</datetime>

大多数软件结构假设系统是静态的,DISE假设系统是活的。

> **注:** 这是“与 DISE 烹饪” 系列中的第4部分。 见 [第一部分 第一部分](/blog/semantidintelligence-part1), [第2部分:第2部分:毕业学徒](/blog/blog-article-cooking-dise-part2-apprenticeships), 和 [第3部分:不值得信赖的神](/blog/blog-article-cooking-dise-part3-untrustworthy-gods) 本文是建筑概览, 现在我们有C# 工作执行 : [多数为lucid.bott 检测](/blog/botdetection-introduction).

**关键概念:行为规则。** 这一结构使一个新的类别得以建立,在这个类别中,根据学习的行为模式而不是静态规则,对探测器和学习系统进行透明的、可调整的“一组”探测器和学习系统进行反射的路线交通。 [YARP YARP 网关](https://hub.docker.com/r/scottgal/mostlylucid.yarpgateway), 机器人永远不会到达您的后端。 或者使用中间软件来建立行为路径, 直接进入您的应用程序层 。

[TOC]

## 问题:动态世界中的静态系统

多年来,我们建造了像时钟一样的软件:投入、产出、规则、管道、测试、部署。所有的线性,都是可以预测的。

但现代系统,特别是AI增强的系统,不再像钟一样行事。

- 攻击者进化他们的技巧
- 用户改变行为
- 需求随时间变化
- 环境不断变化

静态结构无法跟上。 您补上一个洞, 3个出现。 您调出一个阈值, 其它的断裂。 您总是反应不灵, 从不适应 。

**DISE 建筑结构** 将软件作为生物学家对待生物体的方式: 作为一种在压力下必须适应、自我纠正、改进的东西。

## 核心思想:作为不断演变的生物体的系统

传统结构:

```mermaid
flowchart LR
    B[Build] --> S[Ship] --> P[Patch] --> B

    style B stroke:#6366f1,stroke-width:2px
    style P stroke:#ef4444,stroke-width:2px
```

DISE 结构 :

```mermaid
flowchart LR
    P[Perceive] --> E[Evaluate] --> M[Mutate] --> S[Select] --> P

    style P stroke:#10b981,stroke-width:2px
    style M stroke:#f59e0b,stroke-width:2px
    style S stroke:#6366f1,stroke-width:2px
```

DISE系统有四种基本行为:

行为 生物等效剂的作用 生物等效剂
|-----------|--------------|----------------------|
| **隐隐** 收集来自环境的信号 感官器官
| **评价e** 与目标相对的分数信号 神经系统
| **静变** · 产生战略的变异 · · 基因突变 · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · · ·
| **选择** 保持什么是有效的,丢弃什么不是自然选择

这不是隐喻,这是你的系统 逐渐进化的更聪明的行为方式

## 具体实例:植物检测

[多数为lucid.bott 检测](https://github.com/scottgal/mostlylucid.nugetpackages/tree/main/Mostlylucid.BotDetection) 是第一个执行 DISE 原则的 C# 。

### 观念:黑板建筑

该系统使用 **黑黑黑板管弦管** - 探测器为共同状态提供证据,在信号累积时触发其他探测器:

```csharp
// Detectors emit contributions (evidence), not verdicts
public sealed record DetectionContribution
{
    public required string DetectorName { get; init; }
    public required string Category { get; init; }

    // Positive = bot signal, Negative = human signal
    public required double ConfidenceDelta { get; init; }
    public double Weight { get; init; } = 1.0;

    public required string Reason { get; init; }
    public BotType? BotType { get; init; }

    // Signals for triggering other detectors
    public ImmutableDictionary<string, object> Signals { get; init; }
}
```

多探测器运行 **在平行波浪中**系统通过许多透镜观测环境:

```csharp
// Wave 0: All detectors with no trigger conditions run in parallel
// Wave N: Detectors whose triggers are now satisfied run in parallel
while (waveNumber < MaxWaves && !cancellationToken.IsCancellationRequested)
{
    var readyDetectors = availableDetectors
        .Where(d => !ranDetectors.Contains(d.Name))
        .Where(d => CanRun(d, state.Signals))
        .ToList();

    await ExecuteWaveAsync(readyDetectors, state, aggregator, ...);

    // Check for early exit on high confidence
    if (aggregator.ShouldEarlyExit)
        break;
}
```

### 评价:与Sigmoid的加权共识

证据汇集到一项使用Sigmoid变异的决定中 -- -- 这恰当地利用了来自高重量探测器的强烈信号:

```csharp
private (double botProbability, double confidence) CalculateWeightedScore()
{
    var weighted = _contributions
        .Where(c => c.Weight > 0)
        .Select(c => (delta: c.ConfidenceDelta, weight: c.Weight))
        .ToList();

    var weightedSum = weighted.Sum(w => w.delta * w.weight);

    // Sigmoid maps any real number to (0, 1)
    // Strong human signal (-3) → ~5% bot probability
    // Neutral (0) → 50% bot probability
    // Strong bot signal (+3) → ~95% bot probability
    var botProbability = 1.0 / (1.0 + Math.Exp(-weightedSum));

    return (botProbability, confidence);
}
```

评估不是做决定的单一模型 **加权协商一致意见** 关键是 当AI没有运行时 概率是 **粘结** 避免过度自信:

```csharp
// CRITICAL: Clamp probability when AI hasn't run
var botProbability = aiRan
    ? rawBotProbability
    : Math.Clamp(rawBotProbability, 0.20, 0.80);
```

### 早期退出:快速路径优化

系统并不总是运行所有的探测器。当早期证据是确凿的, 它会迅速退出:

```csharp
// Early exit on verified bots (good or bad)
public static DetectionContribution VerifiedGoodBot(
    string detector, string botName, string reason) => new()
{
    DetectorName = detector,
    Category = "Verification",
    ConfidenceDelta = 0,
    TriggerEarlyExit = true,
    EarlyExitVerdict = EarlyExitVerdict.VerifiedGoodBot
};
```

生产中, **高度自信请求在10分钟内退出** 在2-3探测器同意后,整个管道只能用于不确定的病例。

### 电路断路器:自我治疗

探测器可能失灵 系统保护自己:

```csharp
// Circuit breaker per detector
private void RecordFailure(string detectorName)
{
    var state = _circuitStates.GetOrAdd(detectorName, _ => new CircuitState());
    state.FailureCount++;
    state.LastFailure = DateTimeOffset.UtcNow;

    if (state.FailureCount >= CircuitBreakerThreshold)
    {
        state.State = CircuitBreakerState.Open;
        // Detector disabled until reset time passes
    }
}
```

失败检测器被暂时禁用。 冷却后, 将再次试( 半开放状态) 。 这是 : **基础设施一级选择压力**.

### 变异:学习系统

当系统以高度自信探测到时, **学 学 学 学** 通过向学习活动公共汽车发布:

```csharp
private void PublishLearningEvent(AggregatedEvidence result, ...)
{
    var eventType = result.BotProbability >= 0.8
        ? LearningEventType.HighConfidenceDetection
        : LearningEventType.FullDetection;

    _learningBus.TryPublish(new LearningEvent
    {
        Type = eventType,
        Confidence = result.Confidence,
        Label = result.BotProbability >= 0.5,
        Metadata = new Dictionary<string, object>
        {
            ["botProbability"] = result.BotProbability,
            ["categoryBreakdown"] = result.CategoryBreakdown,
            ["contributingDetectors"] = result.ContributingDetectors
        }
    });
}
```

这个输入到重量贮存室, 更新日光检测器的学习重量 随时间推移。

## 认知堆叠

DISE使用多层认知:

```mermaid
flowchart TB
    subgraph Fast["Fast Path (< 100ms)"]
        H[Static Heuristics]
        D[Detectors]
        ML[Learned Heuristic Model]
    end

    subgraph Slow["Slow Path (Async)"]
        LLM[Ollama LLM]
    end

    subgraph Learn["Learning Layer"]
        W[Weight Store]
        Rep[Reputation]
    end

    Fast --> |escalate uncertain| Slow
    Slow --> |label| Learn
    Learn --> |update weights| Fast

    style Fast stroke:#10b981,stroke-width:2px
    style Slow stroke:#6366f1,stroke-width:2px
    style Learn stroke:#f59e0b,stroke-width:2px
```


|-------|-------|---------|----------------------|
| **静静脉动力学** <1ms } <Instiming response \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ - \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \
| **探测器** ~ <10ms ~ Trait 观察 ~ 标题分析, IP检查 ~ ~
| **中 学 文 历 历 历 历 历 历 历 历 历 历 历 历 历 历 历 历 历 历 日** 
| **法学硕士** * 50 - 500ms * 深层推理 * 分析新模式 *
| **学习学习学习学习** * 背景 * 记忆形成 * * 体重更新 名声改变 *

关键洞察力: 系统在实时中学习其自身的权重。 不需要外部 ML 模型。 超常检测器从明智的默认开始, 并根据检测反馈演变 。

> **未来:** 计划为 v2. 目前的超自然模型输出作为未来模型培训的标签培训数据。 结构已经拥有“ 基因” 工艺品( 贡献、 重量、 信号) , 使直接合成进化成为直接的外插点 — 设计为插件点 。

这反映了生物认知:

- **原生免疫系统** 静态健康学
- **适应性免疫系统** 总结经验模式
- **内存单元格** 重量商店+声誉

## 华力探测器:没有外部模型的学习

系统不是用外部ML模型, 而是用简单的后勤回归 和动态特征提取来学习自己的分类方法:

```csharp
public class HeuristicDetector : IDetector
{
    // Default weights - sensible starting points
    private static readonly Dictionary<string, float> DefaultWeights = new()
    {
        // Human-like patterns (negative = more likely human)
        ["hdr:accept-language"] = -0.6f,
        ["hdr:referer"] = -0.4f,
        ["fp:received"] = -0.7f,      // Fingerprint = strong human signal
        ["fp:legitimate"] = -0.8f,

        // Bot indicators (positive = more likely bot)
        ["ua:contains_bot"] = 0.9f,
        ["ua:headless"] = 0.8f,
        ["ua:selenium"] = 0.7f,
        ["ua:curl"] = 0.6f,
        ["accept:wildcard"] = 0.4f,
    };

    private (bool IsBot, double Probability) RunInference(Dictionary<string, float> features)
    {
        // Simple linear model: score = bias + Σ(feature * weight)
        float score = _bias;

        foreach (var (featureName, featureValue) in features)
        {
            var weight = _weights.TryGetValue(featureName, out var w)
                ? w
                : DefaultNewFeatureWeight;
            score += featureValue * weight;
        }

        // Sigmoid gives us probability
        var probability = 1.0 / (1.0 + Math.Exp(-score));
        return (probability > 0.5, probability);
    }
}
```

从请求和综合证据中动态提取特征:

```csharp
public static class HeuristicFeatureExtractor
{
    public static Dictionary<string, float> ExtractFeatures(
        HttpContext context,
        AggregatedEvidence evidence)
    {
        var features = new Dictionary<string, float>();

        // Request metadata
        features["req:header_count"] = Math.Min(headers.Count / 20f, 1f);
        features["req:cookie_count"] = Math.Min(cookies.Count / 10f, 1f);

        // Header presence
        features["hdr:accept-language"] = headers.ContainsKey("Accept-Language") ? 1f : 0f;

        // UA patterns (dynamic - only present if detected)
        if (ua.Contains("bot")) features["ua:contains_bot"] = 1f;
        if (ua.Contains("selenium")) features["ua:selenium"] = 1f;

        // Detector results (named by actual detector)
        foreach (var contrib in evidence.Contributions)
            features[$"det:{contrib.DetectorName}"] = contrib.ConfidenceDelta;

        // Client-side fingerprint - STRONG human signal
        if (hasFingerprint)
        {
            features["fp:received"] = 1f;
            features["fp:legitimate"] = 1f;
        }

        return features;
    }
}
```

新功能自动获得默认重量, 并随着时间的流逝学习。 系统会发现什么重要 。

## 体重库:持续学习

SQLite的重量持续存在, 并通过指数移动平均值更新 :

```csharp
public class SqliteWeightStore : IWeightStore
{
    public async Task RecordObservationAsync(
        string signatureType,
        string signature,
        bool wasBot,
        double detectionConfidence,
        CancellationToken ct = default)
    {
        // EMA update: weight = weight * (1 - α) + new_value * α
        var alpha = 0.1; // Learning rate
        var weightDelta = wasBot ? detectionConfidence : -detectionConfidence;

        var sql = @"
            INSERT INTO learned_weights (signature_type, signature, weight, ...)
            VALUES (@type, @sig, @delta, ...)
            ON CONFLICT(signature_type, signature) DO UPDATE SET
                weight = weight * (1 - @alpha) + @delta * @alpha,
                confidence = MIN(1.0, confidence + @conf * 0.01),
                observation_count = observation_count + 1,
                last_seen = @now
        ";

        await ExecuteAsync(sql, ...);
    }
}
```

这是 **通过观测突变**每次检测都教给系统某些东西。随着时间推移,加权数会趋同到您特定交通模式的最佳值。

## 幻觉如变异

在DISE,LLM幻觉不是虫子,是进化的基因基质

高温LLM 提出十种不同的检测规则 不是"催化" **突变基因组** 系统系统:

```csharp
public async Task<List<DetectionRule>> GenerateMutationsAsync(DetectionContext context)
{
    var prompt = $"""
        Given this traffic pattern:
        {JsonSerializer.Serialize(context)}

        Generate 5 variant detection rules that might catch similar patterns.
        Return JSON array of rules with: pattern, weight, confidence.
        Be creative. Some variants should be strict, some lenient.
        """;

    var response = await _ollama.GenerateAsync(new GenerateRequest
    {
        Model = "gemma3:1b",
        Prompt = prompt,
        Options = new RequestOptions { Temperature = 0.9 } // High creativity
    });

    return ParseRules(response.Response);
}
```

然后根据历史数据对突变进行评估:

```csharp
public async Task<DetectionRule?> SelectFittestAsync(
    List<DetectionRule> mutations,
    List<LabeledRequest> testData)
{
    var results = new List<(DetectionRule Rule, double Fitness)>();

    foreach (var rule in mutations)
    {
        var tp = testData.Count(r => rule.Matches(r) && r.IsBot);
        var fp = testData.Count(r => rule.Matches(r) && !r.IsBot);
        var fn = testData.Count(r => !rule.Matches(r) && r.IsBot);

        // F1 score as fitness
        var precision = tp / (double)(tp + fp);
        var recall = tp / (double)(tp + fn);
        var f1 = 2 * (precision * recall) / (precision + recall);

        results.Add((rule, f1));
    }

    return results.OrderByDescending(r => r.Fitness).First().Rule;
}
```

只有适适者才能存活到生产。 这使得LLMs从易碎的聊天机变成 **演进操作者**.

## 基因组:基于政策的配置

在DISE的中心是 **政策政策系统** - 定义探测行为方式的命名配置:

```json
{
  "Policies": {
    "fastpath": {
      "Description": "Fast path + Heuristic for sync decisions",
      "FastPath": ["UserAgent", "Header", "Ip", "Behavioral", "ClientSide", "Inconsistency", "VersionAge"],
      "AiPath": ["Heuristic"],
      "EscalateToAi": true,
      "EarlyExitThreshold": 0.15,
      "ImmediateBlockThreshold": 0.90,
      "Weights": {
        "ClientSide": 0.2,
        "Heuristic": 1.5
      },
      "Transitions": [
        { "WhenRiskExceeds": 0.5, "WhenRiskBelow": 0.85, "GoTo": "demo" }
      ]
    },
    "demo": {
      "Description": "Full pipeline sync for demonstration",
      "FastPath": [],
      "AiPath": [],
      "BypassTriggerConditions": true,
      "ForceSlowPath": true
    }
  }
}
```

政策界定:

- **快速帕式探测器** - 平行运行, Sub- 10ms
- **AI 路径路径** - 超常(1-5米)和(或)LLM(500米+)
- **阈下限** - 何时提前退出,何时阻止
- **过渡** - 在不确定时自动升级为其他政策
- **单政策权重** - 每个使用案例的音频探测器重要性

该系统可以 **政策之间的过渡**不确定的快速路径结果升级到整个输油管的整条输油管。 **适应性路线安排** - 基因组对实时证据的反应。

你没有固定配置,你没有 **行为物种** 适应交通。

## 适合性功能:什么幸存者

每个DISE系统都对健身环境持乐观态度:

```csharp
public class FitnessEvaluator
{
    public double Evaluate(GenomeConfig genome, EvaluationData data)
    {
        var fpRate = data.FalsePositives / (double)data.TotalHumans;
        var fnRate = data.FalseNegatives / (double)data.TotalBots;
        var latency = data.P99LatencyMs;
        var cost = data.AiCallsPerRequest * _config.CostPerAiCall;

        // Multi-objective fitness
        return 1.0
            - (fpRate * _config.FalsePositivePenalty)   // Don't block humans
            - (fnRate * _config.FalseNegativePenalty)   // Don't miss bots
            - (latency / _config.MaxLatencyMs)          // Stay fast
            - (cost / _config.MaxCostPerRequest);       // Stay cheap
    }
}
```

我们不光是追求准确性,而是追求最佳 **动态环境中的活性**.

太多AI 高成本,低潜伏。
人工智能太少 发现新式袭击的机率很低
充满攻击性的假阳性 愤怒的用户
太宽大了 机器人洪水

系统必须找到稳定的平衡 压力驱动器进化

## AI作为教师,而非工人

成熟的DISE系统将AI从热道上移开:

```mermaid
flowchart TB
    subgraph Early["Early Stage"]
        AI1[AI handles most cases]
    end

    subgraph Middle["Middle Stage"]
        AI2[AI handles edge cases]
        H1[Heuristics handle common cases]
    end

    subgraph Mature["Mature Stage"]
        AI3[AI teaches and mutates]
        H2[Heuristics handle almost everything]
        M[Memory provides context]
    end

    Early --> Middle --> Mature

    style Early stroke:#ef4444,stroke-width:2px
    style Middle stroke:#f59e0b,stroke-width:2px
    style Mature stroke:#10b981,stroke-width:2px
```

随时间推移 :

- 静态探测器改进(经过AI标签培训)
- 饮食学更加准确(通过健身选择)
- 人工智能只处理新事物和突变

AI 改为:

- 缩略 **甲板** 新行为
- 缩略 **发电机发电机** 突变
- 缩略 **漂流探测器**
- 缩略 **教师 教师 教师** 标为边际案例的标签

适应性脚手架

## 行为路由: 一个新类别

与 [YARP YARP 网关](https://hub.docker.com/r/scottgal/mostlylucid.yarpgateway),这个建筑可以带来新的东西: **行为路线**.

传统路线是静态的:路径 + 后端 。 行为路线是反射的: 交通特征 + 动态路线决定 。

```mermaid
flowchart LR
    subgraph Gateway["YARP Gateway"]
        D[Detector Team]
        P[Policy Engine]
        R[Router]
    end

    Traffic[Traffic] --> D
    D --> P
    P --> R
    R -->|Human| App[Your App]
    R -->|Bot| Block[403]
    R -->|Uncertain| Challenge[Challenge]
    R -->|Learning| Queue[Async Analysis]

    style Gateway stroke:#10b981,stroke-width:2px
```

关键概念:

- **探测器小组** - 一组可配置的探测器,根据政策共同工作,可调整
- **透明决定** - 每项路由决定都可解释(见捐款细目)
- **弹性调整** - 系统从其决定中学习,并随着时间的推移调整权重
- **边缘保护** - 机器人永远不会到达您的后端;在路由器上被阻塞

这不仅仅是"边缘的机器人探测" 这是一条新的原始路线 交通流动是由有学识的行为模式决定的 而不仅仅是静态规则

## 为何如此重要

多数工程文化都害怕:

- 非决定主义
- 漂流
- 变异
- 幻觉
- 新兴行为

DISE使用这些作为 **建筑材料**.

静态系统死亡 不断演化的系统生存

每个处理对手、漂移或规模压力的行业 最终都需要这样的建筑

- 检测Bot 检测
- 欺诈引擎
- 适应防火墙
- LLM 生态系统
- 自我优化微观服务
- 自动调试系统
- **行为路由** - 根据学习模式形成交通流量

## 什么是DISE不是

让我说清楚,这不是什么:

- **不是"无处不在的大光环"** -LLMS很贵,战略上要用
- **而不是用AI取代商业逻辑** - 疲劳症更快 更可预测
- **"不要让系统疯狂运行"** - 进化是受引导、受约束、受支配的。
- **不是"类固醇的自动溶剂"** - 这是关于行为, 不只是模型调试。

DISE是受控制的,可以解释的进化:

- 受制约
- 由明确的健身功能管理
- 记忆意识
- 已版本
- 安全部署

这是 *定向* - 受引导的进化,不是随机的

## 试试

[多数为lucid.bott 检测](https://www.nuget.org/packages/mostlylucid.botdetection/) 执行这些原则:

```bash
dotnet add package Mostlylucid.BotDetection
```

```csharp
builder.Services.AddBotDetection();
app.UseBotDetection();
```

已启用学习的制作配置 :

```json
{
  "BotDetection": {
    "BotThreshold": 0.7,
    "Policies": {
      "default": {
        "FastPath": ["UserAgent", "Header", "Ip", "Behavioral", "ClientSide", "Inconsistency", "VersionAge"],
        "AiPath": ["Heuristic", "Llm"],
        "EscalateToAi": true,
        "EarlyExitThreshold": 0.85
      }
    },
    "AiDetection": {
      "Provider": "Heuristic",
      "Heuristic": {
        "Enabled": true,
        "LoadLearnedWeights": true,
        "EnableWeightLearning": true,
        "LearningRate": 0.01
      }
    }
  }
}
```

观察它的进化。 疲劳检测器从每一个请求中学习, 更新它的重量来适应你的交通模式。

## 结论 结论 结论 结论 结论

DISE 建筑是从作为机器的软件向作为有机体的软件的转变。

它的建筑结构是:

- 可适应性
- 复原力
- 控制演变
- 层数值
- 记忆驱动学习
- 变异+选择
- 战略行为

静态结构无法跟上动态环境。 攻击者进化。 用户进化。 要求进化。

系统也必须演变。

如果你想要只是运行的系统, 用旧的方法来建造它们。
如果您想要系统 **活 活 活 活** - 和DISE一起建造