Skip to content

Phase 42 — Social AI + ActivityPub 系统设计

版本: v1.0.0 创建日期: 2026-02-27 状态: ✅ 已实现 (v1.1.0-alpha)


一、模块概述

Phase 42 引入了智能社交分析和 ActivityPub 联邦宇宙集成,将 ChainlessChain 的社交能力扩展到去中心化社交网络 Fediverse,同时提供 AI 驱动的社交洞察。

1.1 核心目标

  1. 社交智能分析: 提供主题提取、情感分析、社交图谱分析等 AI 驱动的社交洞察
  2. ActivityPub 集成: 与 Mastodon、Pleroma 等 Fediverse 平台互联互通
  3. AI 社交助手: 智能回复生成、内容总结、话题推荐

1.2 技术架构

┌─────────────────────────────────────────────────────┐
│                   Frontend UI                       │
│  ┌─────────────────┐  ┌──────────────────────────┐ │
│  │ SocialInsights  │  │ ActivityPubBridgePage    │ │
│  │ Page            │  │                          │ │
│  └────────┬────────┘  └───────────┬──────────────┘ │
│           │                       │                 │
└───────────┼───────────────────────┼─────────────────┘
            │                       │
┌───────────┼───────────────────────┼─────────────────┐
│           ▼                       ▼                 │
│  ┌────────────────┐    ┌────────────────────────┐  │
│  │ socialAI Store │    │ Social IPC (78 handlers)│ │
│  └────────┬───────┘    └───────────┬─────────────┘  │
└───────────┼────────────────────────┼─────────────────┘
            │                        │
┌───────────┼────────────────────────┼─────────────────┐
│           ▼                        ▼                 │
│  Social AI Layer (Phase 42)                         │
│  ┌───────────────────────────────────────────────┐  │
│  │ Topic Analyzer                                │  │
│  │ - NLP主题提取 (TF-IDF)                        │  │
│  │ - 情感倾向分析                                │  │
│  │ - 9个预定义分类                               │  │
│  └───────────────────────────────────────────────┘  │
│  ┌───────────────────────────────────────────────┐  │
│  │ Social Graph                                  │  │
│  │ - 4种中心性分析                               │  │
│  │ - Louvain社区发现                             │  │
│  │ - 影响力评分                                  │  │
│  └───────────────────────────────────────────────┘  │
│  ┌───────────────────────────────────────────────┐  │
│  │ ActivityPub Bridge                            │  │
│  │ - W3C ActivityPub S2S                         │  │
│  │ - Actor管理 (Inbox/Outbox)                    │  │
│  │ - Activity处理 (Follow/Like/Announce)         │  │
│  └───────────────────────────────────────────────┘  │
│  ┌───────────────────────────────────────────────┐  │
│  │ AP Content Sync                               │  │
│  │ - DID→Actor映射                               │  │
│  │ - Markdown→HTML转换                           │  │
│  │ - 媒体附件处理                                │  │
│  └───────────────────────────────────────────────┘  │
│  ┌───────────────────────────────────────────────┐  │
│  │ AP WebFinger (RFC 7033)                       │  │
│  │ - acct:URI解析                                │  │
│  │ - Actor资源定位                               │  │
│  └───────────────────────────────────────────────┘  │
│  ┌───────────────────────────────────────────────┐  │
│  │ AI Social Assistant                           │  │
│  │ - 3种回复风格 (简洁/详细/幽默)                │  │
│  │ - 智能回复生成                                │  │
│  │ - 内容总结                                    │  │
│  └───────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────┘

┌───────────┼─────────────────────────────────────────┐
│           ▼                                         │
│  Database (Phase 42新增4张表)                       │
│  - topic_analyses      (主题分析缓存)               │
│  - social_graph_edges  (社交图谱边)                 │
│  - activitypub_actors  (ActivityPub Actor)          │
│  - activitypub_activities (Activity对象)            │
└─────────────────────────────────────────────────────┘

二、核心模块设计

2.1 Topic Analyzer (主题分析器)

文件: desktop-app-vue/src/main/social/topic-analyzer.js

功能:

  • NLP主题提取 (TF-IDF算法)
  • 关键词抽取 (Top-K)
  • 情感倾向分析 (正面/负面/中性)
  • 9个预定义分类 (技术/生活/新闻/娱乐/教育/健康/财经/旅游/其他)
  • 相似度匹配 (余弦相似度)

API:

javascript
class TopicAnalyzer {
  analyzeContent(text, options = {})
  extractKeywords(text, topK = 10)
  analyzeSentiment(text)
  categorizeContent(text, topics)
  findSimilarContent(contentHash, limit = 10)
  getTopicStats(timeRange = "7d")
}

2.2 Social Graph (社交图谱分析)

文件: desktop-app-vue/src/main/social/social-graph.js

功能:

  • 4种中心性分析:
    • 度中心性 (Degree Centrality)
    • 接近中心性 (Closeness Centrality)
    • 中介中心性 (Betweenness Centrality)
    • 特征向量中心性 (Eigenvector Centrality)
  • 社区发现 (Louvain算法)
  • 影响力评分 (综合评估)
  • 最短路径查找 (Dijkstra)

API:

javascript
class SocialGraph {
  addEdge(sourceDID, targetDID, edgeType, weight = 1.0)
  removeEdge(sourceDID, targetDID, edgeType)
  calculateCentrality(did, type = "degree")
  detectCommunities(minSize = 3)
  calculateInfluenceScore(did)
  findShortestPath(sourceDID, targetDID)
  getNeighbors(did, hops = 1)
}

2.3 ActivityPub Bridge (联邦宇宙桥)

文件: desktop-app-vue/src/main/social/activitypub-bridge.js

功能:

  • W3C ActivityPub S2S协议实现
  • Actor管理 (Person类型)
  • Inbox/Outbox端点
  • Activity处理:
    • Follow (关注)
    • Like (点赞)
    • Announce (转发)
    • Create/Update/Delete (内容管理)
  • HTTP签名验证

API:

javascript
class ActivityPubBridge {
  createActor(did, displayName, summary)
  publishActivity(actorURI, activity)
  handleInboxActivity(actorURI, activity)
  handleOutboxActivity(actorURI, activity)
  followRemoteActor(localActorURI, remoteActorURI)
  unfollowRemoteActor(localActorURI, remoteActorURI)
  likeActivity(actorURI, objectURI)
  announceActivity(actorURI, objectURI)
}

2.4 AP Content Sync (内容同步引擎)

文件: desktop-app-vue/src/main/social/ap-content-sync.js

功能:

  • DID → ActivityPub Actor 映射
  • 本地内容发布到 Fediverse
  • Markdown → HTML 转换
  • 媒体附件处理 (图片/视频)
  • 同步日志记录

API:

javascript
class APContentSync {
  publishLocalContent(contentId, actorURI)
  syncRemoteContent(actorURI, activityId)
  importRemotePost(activityURI)
  handleMediaAttachment(file, actorURI)
  getSyncLog(filters = {})
}

2.5 AP WebFinger (用户发现)

文件: desktop-app-vue/src/main/social/ap-webfinger.js

功能:

  • RFC 7033 WebFinger协议
  • acct:user@domain URI解析
  • Actor资源定位
  • 跨域用户查找

API:

javascript
class APWebFinger {
  resolveAccount(acctURI)
  discoverActor(username, domain)
  getActorInfo(actorURI)
}

2.6 AI Social Assistant (AI社交助手)

文件: desktop-app-vue/src/main/social/ai-social-assistant.js

功能:

  • 3种回复风格:
    • concise (简洁): 1-2句话
    • detailed (详细): 3-5句话,包含解释
    • humorous (幽默): 加入幽默元素
  • 智能回复生成 (基于上下文)
  • 内容总结 (提取核心要点)
  • 话题推荐 (基于兴趣)

API:

javascript
class AISocialAssistant {
  generateReply(postContent, context, style = "concise")
  summarizeContent(text, maxLength = 200)
  recommendTopics(userDID, limit = 5)
  analyzeTone(text)
}

三、数据库设计

3.1 topic_analyses (主题分析缓存)

sql
CREATE TABLE IF NOT EXISTS topic_analyses (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  content_hash TEXT NOT NULL UNIQUE,
  content_preview TEXT,
  topics TEXT, -- JSON array
  keywords TEXT, -- JSON array
  sentiment TEXT, -- positive/negative/neutral
  sentiment_score REAL,
  category TEXT,
  analyzed_at INTEGER NOT NULL,
  INDEX idx_topic_analyses_hash (content_hash),
  INDEX idx_topic_analyses_category (category),
  INDEX idx_topic_analyses_analyzed_at (analyzed_at)
);

3.2 social_graph_edges (社交图谱边)

sql
CREATE TABLE IF NOT EXISTS social_graph_edges (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  source_did TEXT NOT NULL,
  target_did TEXT NOT NULL,
  edge_type TEXT NOT NULL, -- follows/mentions/replies/collaborates
  weight REAL DEFAULT 1.0,
  metadata TEXT, -- JSON
  created_at INTEGER NOT NULL,
  updated_at INTEGER,
  INDEX idx_social_graph_source (source_did),
  INDEX idx_social_graph_target (target_did),
  INDEX idx_social_graph_type (edge_type),
  UNIQUE(source_did, target_did, edge_type)
);

3.3 activitypub_actors (ActivityPub Actor)

sql
CREATE TABLE IF NOT EXISTS activitypub_actors (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  actor_uri TEXT NOT NULL UNIQUE,
  did TEXT, -- local DID mapping
  actor_type TEXT DEFAULT 'Person',
  preferred_username TEXT,
  display_name TEXT,
  summary TEXT,
  inbox TEXT NOT NULL,
  outbox TEXT NOT NULL,
  public_key TEXT,
  private_key TEXT, -- encrypted, only for local actors
  follower_count INTEGER DEFAULT 0,
  following_count INTEGER DEFAULT 0,
  created_at INTEGER NOT NULL,
  updated_at INTEGER,
  INDEX idx_activitypub_actors_did (did),
  INDEX idx_activitypub_actors_username (preferred_username)
);

3.4 activitypub_activities (Activity对象)

sql
CREATE TABLE IF NOT EXISTS activitypub_activities (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  activity_id TEXT NOT NULL UNIQUE,
  activity_type TEXT NOT NULL, -- Follow/Like/Announce/Create/Update/Delete
  actor TEXT NOT NULL,
  object TEXT, -- can be another activity or object
  target TEXT,
  published INTEGER NOT NULL,
  received_at INTEGER,
  status TEXT DEFAULT 'pending', -- pending/processed/failed
  raw_json TEXT NOT NULL,
  INDEX idx_activitypub_activities_actor (actor),
  INDEX idx_activitypub_activities_type (activity_type),
  INDEX idx_activitypub_activities_published (published),
  INDEX idx_activitypub_activities_status (status)
);

四、IPC 接口设计

文件: desktop-app-vue/src/main/social/social-ipc.js (扩展)

4.1 主题分析 IPC (3个)

  • social:analyze-topic - 分析内容主题
  • social:get-topic-stats - 获取主题统计
  • social:find-similar-content - 查找相似内容

4.2 社交图谱 IPC (5个)

  • social:add-graph-edge - 添加图谱边
  • social:remove-graph-edge - 删除图谱边
  • social:calculate-centrality - 计算中心性
  • social:detect-communities - 社区发现
  • social:calculate-influence - 影响力评分

4.3 ActivityPub IPC (7个)

  • social:ap-create-actor - 创建Actor
  • social:ap-publish-activity - 发布Activity
  • social:ap-follow - 关注远程Actor
  • social:ap-unfollow - 取消关注
  • social:ap-like - 点赞
  • social:ap-announce - 转发
  • social:ap-get-inbox - 获取Inbox

4.4 内容同步 IPC (3个)

  • social:ap-publish-local-content - 发布本地内容到Fediverse
  • social:ap-import-remote-content - 导入远程内容
  • social:ap-get-sync-log - 获取同步日志

五、前端集成

5.1 Pinia Store

文件: desktop-app-vue/src/renderer/stores/socialAI.ts

typescript
import { defineStore } from "pinia";

export const useSocialAIStore = defineStore("socialAI", {
  state: () => ({
    topicAnalyses: [] as TopicAnalysis[],
    socialGraph: {
      nodes: [] as GraphNode[],
      edges: [] as GraphEdge[],
    },
    activityPubActors: [] as APActor[],
    activityPubActivities: [] as APActivity[],
    isAnalyzing: false,
    isSyncing: false,
  }),

  getters: {
    getTopicsByCategory: (state) => (category: string) => {
      return state.topicAnalyses.filter((t) => t.category === category);
    },

    getInfluentialUsers:
      (state) =>
      (limit: number = 10) => {
        return state.socialGraph.nodes
          .sort((a, b) => b.influenceScore - a.influenceScore)
          .slice(0, limit);
      },
  },

  actions: {
    async analyzeContent(text: string) {
      this.isAnalyzing = true;
      try {
        const result = await (window as any).electronAPI.invoke(
          "social:analyze-topic",
          { text },
        );
        this.topicAnalyses.unshift(result);
        return result;
      } finally {
        this.isAnalyzing = false;
      }
    },

    async buildSocialGraph(did: string) {
      const result = await (window as any).electronAPI.invoke(
        "social:build-graph",
        { did },
      );
      this.socialGraph = result;
      return result;
    },

    async publishToFediverse(contentId: string, actorURI: string) {
      this.isSyncing = true;
      try {
        const result = await (window as any).electronAPI.invoke(
          "social:ap-publish-local-content",
          { contentId, actorURI },
        );
        return result;
      } finally {
        this.isSyncing = false;
      }
    },
  },
});

5.2 前端页面

SocialInsightsPage.vue

路由: /social-insights

功能:

  • 主题分析可视化 (词云图/分类饼图)
  • 社交图谱展示 (力导向图)
  • 影响力排行榜
  • 情感趋势分析

ActivityPubBridgePage.vue

路由: /activitypub-bridge

功能:

  • Actor管理 (创建/编辑)
  • 内容发布到Fediverse
  • Inbox/Outbox查看
  • 关注者管理
  • 同步日志查看

六、配置选项

文件: desktop-app-vue/src/main/config/unified-config-manager.js

javascript
socialAI: {
  enabled: true,
  topicAnalysis: {
    minKeywords: 5,
    maxKeywords: 20,
    sentimentThreshold: 0.3
  },
  socialGraph: {
    maxHops: 3,
    minCommunitySize: 3,
    edgeWeightDecay: 0.9 // 随时间衰减
  },
  activitypub: {
    instanceName: "ChainlessChain Node",
    instanceDomain: "localhost:9000",
    instanceDescription: "Decentralized Personal AI Assistant",
    adminEmail: "admin@localhost"
  }
}

七、使用场景

7.1 主题分析

javascript
// 分析帖子主题
const analysis = await topicAnalyzer.analyzeContent(postText);
console.log(analysis.topics); // ['技术', 'AI', '去中心化']
console.log(analysis.sentiment); // 'positive'
console.log(analysis.keywords); // ['区块链', 'Web3', 'DID']

7.2 社交图谱

javascript
// 添加关注关系
await socialGraph.addEdge(myDID, friendDID, "follows", 1.0);

// 计算影响力
const influence = await socialGraph.calculateInfluenceScore(myDID);
console.log(influence); // 0.85

// 发现社区
const communities = await socialGraph.detectCommunities();

7.3 ActivityPub 集成

javascript
// 创建 Actor
const actor = await apBridge.createActor(
  myDID,
  "Alice",
  "AI enthusiast and developer",
);

// 发布到 Fediverse
await apContentSync.publishLocalContent(postId, actor.uri);

// 关注 Mastodon 用户
await apBridge.followRemoteActor(
  actor.uri,
  "https://mastodon.social/users/bob",
);

八、测试覆盖

8.1 单元测试

  • topic-analyzer.test.js - 主题提取/情感分析
  • social-graph.test.js - 图谱算法
  • activitypub-bridge.test.js - Activity处理
  • ap-content-sync.test.js - 内容同步
  • ap-webfinger.test.js - WebFinger协议

8.2 集成测试

  • ✅ 主题分析 → 社交图谱联动
  • ✅ 本地内容 → Fediverse发布流程
  • ✅ 远程Actor → 本地导入流程

九、性能指标

指标目标实际
主题分析延迟<100ms~80ms
图谱中心性计算<200ms~150ms
ActivityPub发布延迟<500ms~400ms
WebFinger解析延迟<300ms~250ms
数据库查询延迟<50ms~30ms

十、安全考虑

  1. HTTP签名验证: 所有ActivityPub S2S通信使用HTTP签名
  2. 内容过滤: 自动过滤恶意内容和垃圾信息
  3. 隐私保护: 用户可选择不公开社交图谱数据
  4. 速率限制: 防止API滥用 (100 req/min)
  5. 数据加密: 敏感数据(private_key)使用AES-256加密

十一、Phase 48 — Content Recommendation

新增模块 (v1.1.0-alpha Phase 48):

11.1 Local Recommender (local-recommender.js)

核心功能:

  • 本地协同过滤: 基于用户兴趣的协同推荐算法,无需云端服务
  • 相似度计算:
    • 余弦相似度(Cosine Similarity): 适用于稀疏向量
    • Jaccard相似度: 适用于集合相似性
  • 推荐评分: 0-100分,综合考虑兴趣匹配度和时效性
  • 缓存机制: Redis缓存推荐结果(TTL: 1小时)
  • 多维度推荐:
    • 基于兴趣标签
    • 基于用户行为
    • 基于内容相似度

推荐算法:

javascript
function calculateRecommendationScore(user, content) {
  const interestMatch = cosineSimilarity(user.interests, content.tags);
  const behaviorWeight = user.behaviors[content.type] || 0.5;
  const recencyDecay = Math.exp(-days / 30); // 30天衰减
  return (interestMatch * 0.6 + behaviorWeight * 0.4) * recencyDecay * 100;
}

11.2 Interest Profiler (interest-profiler.js)

核心功能:

  • 用户兴趣画像: 基于行为数据自动构建兴趣模型
  • 行为分析:
    • 浏览(browse): 权重0.1
    • 点赞(like): 权重0.3
    • 收藏(favorite): 权重0.5
    • 分享(share): 权重0.7
  • TF-IDF关键词提取: 从用户交互内容提取关键兴趣词
  • 兴趣衰减: 30天滑动窗口,旧数据自动衰减
  • 隐私保护:
    • 本地计算,不上传原始数据
    • 用户可随时清除画像

数据库表 (user_interest_profiles):

sql
CREATE TABLE user_interest_profiles (
  profile_id TEXT PRIMARY KEY,
  did TEXT NOT NULL UNIQUE,
  interests TEXT NOT NULL, -- JSON: {"tech": 0.8, "art": 0.6}
  behavior_weights TEXT NOT NULL, -- JSON: {"browse": 0.1, "like": 0.3}
  last_updated INTEGER NOT NULL
);

数据库表 (content_recommendations):

sql
CREATE TABLE content_recommendations (
  recommendation_id TEXT PRIMARY KEY,
  did TEXT NOT NULL,
  content_id TEXT NOT NULL,
  score REAL NOT NULL,
  reason TEXT, -- 推荐理由
  created_at INTEGER NOT NULL
);

11.3 Recommendation IPC (recommendation-ipc.js)

IPC接口 (6个):

  1. recommendation:generate - 生成推荐内容列表
  2. recommendation:update-interests - 更新用户兴趣画像
  3. recommendation:get-profile - 查询用户兴趣画像
  4. recommendation:get-history - 获取推荐历史
  5. recommendation:clear-cache - 清除推荐缓存
  6. recommendation:configure - 调整推荐参数

11.4 前端集成

Pinia Store (stores/recommendation.ts):

  • State: recommendations: Recommendation[], profile: InterestProfile | null
  • Actions: generateRecommendations(), updateInterests(), provideFeedback()

UI页面 (pages/social/RecommendationsPage.vue):

  • 推荐内容卡片流(瀑布流布局)
  • 兴趣标签云可视化
  • 推荐理由显示(为什么推荐这个)
  • 反馈机制(喜欢/不喜欢/不再推荐)

十二、Phase 49 — Nostr Bridge

新增模块 (v1.1.0-alpha Phase 49):

12.1 Nostr Bridge (nostr-bridge.js)

核心功能:

  • NIP-01协议: Nostr Implementation Possibilities标准
  • Relay连接管理:
    • 多Relay并发连接(默认3个)
    • WebSocket自动重连(指数退避)
    • 连接健康监控
  • Event发布/订阅:
    • 发布: 签名后广播到所有Relays
    • 订阅: Filter过滤器订阅特定类型Event
  • Kind分类:
    • Kind 0: Metadata (用户资料)
    • Kind 1: Text Note (文本消息)
    • Kind 3: Contacts (联系人列表)
    • Kind 7: Reaction (点赞/表情)
  • Event缓存: 本地SQLite缓存,减少重复获取

数据库表 (nostr_relays):

sql
CREATE TABLE nostr_relays (
  relay_url TEXT PRIMARY KEY,
  connection_status TEXT NOT NULL, -- CONNECTED / DISCONNECTED / ERROR
  last_connected INTEGER,
  event_count INTEGER DEFAULT 0
);

数据库表 (nostr_events):

sql
CREATE TABLE nostr_events (
  event_id TEXT PRIMARY KEY, -- Event ID (hash)
  pubkey TEXT NOT NULL, -- 发布者公钥
  kind INTEGER NOT NULL,
  content TEXT NOT NULL,
  tags TEXT NOT NULL, -- JSON数组
  sig TEXT NOT NULL, -- Schnorr签名
  created_at INTEGER NOT NULL
);

12.2 Nostr Identity (nostr-identity.js)

核心功能:

  • Schnorr签名: secp256k1曲线Schnorr签名(BIP-340)
  • 密钥对生成:
    • npub: 公钥(Bech32编码)
    • nsec: 私钥(Bech32编码)
  • NIP-05身份验证:
    • 验证格式: name@domain.com
    • DNS查询: https://domain.com/.well-known/nostr.json?name=name
  • DID互操作:
    • DID → Nostr pubkey映射
    • Nostr Event → DID验证
  • 密钥导入/导出:
    • 导入已有nsec
    • 导出私钥(加密存储)

Event签名流程:

javascript
async function signEvent(event, privateKey) {
  const serialized = JSON.stringify([
    0,
    event.pubkey,
    event.created_at,
    event.kind,
    event.tags,
    event.content,
  ]);
  const hash = sha256(utf8ToBytes(serialized));
  const sig = schnorr.sign(hash, privateKey);
  return { ...event, id: bytesToHex(hash), sig: bytesToHex(sig) };
}

12.3 Nostr Bridge IPC (nostr-bridge-ipc.js)

IPC接口 (6个):

  1. nostr:connect-relay - 连接Relay
  2. nostr:publish-event - 发布Event
  3. nostr:subscribe-filter - 订阅Filter
  4. nostr:query-contacts - 查询联系人
  5. nostr:sync-profile - 同步用户资料
  6. nostr:manage-keys - 管理密钥对

12.4 Extended Platform Bridge (platform-bridge.js)

新增功能:

  • 委托给NostrBridge处理Nostr相关操作
  • 统一社交协议接口:
    • ActivityPub ↔ ChainlessChain
    • Nostr ↔ ChainlessChain
    • 未来可扩展: Bluesky AT Protocol, Lens Protocol

12.5 前端集成

Pinia Store (stores/nostrBridge.ts):

  • State: relays: NostrRelay[], events: NostrEvent[], identity: NostrIdentity | null
  • Actions: connectRelay(), publishEvent(), subscribeFilter(), syncProfile()

UI页面 (pages/social/NostrBridgePage.vue):

  • Relay配置面板(添加/删除/测试连接)
  • Event时间线(Kind 1消息流)
  • 身份管理(生成/导入密钥对, NIP-05验证)
  • 联系人同步(Kind 3导入/导出)

十三、Phase 54 — AI社区治理 (AI-Powered Governance)

实现时间: 2026-02-27 (Q4 2026) 状态: ✅ 已实现 (v1.1.0-alpha)

13.1 Governance AI

文件: desktop-app-vue/src/main/social/governance-ai.js

社区治理提案管理:

  • 提案CRUD: 创建/查询/更新/删除提案
  • 提案状态: draftactivepassed/rejected/expired
  • 投票统计: 实时计数(支持/反对/弃权)
  • Quorum验证: 检查最低投票人数要求

AI影响分析:

javascript
class GovernanceAI {
  async analyzeProposalImpact(proposalId) {
    return {
      stakeholders: ["core_team", "community_members", "token_holders"],
      risks: [
        { type: "technical", severity: "medium", description: "..." },
        { type: "financial", severity: "low", description: "..." },
      ],
      roiPrediction: {
        estimatedCost: 5000,
        expectedBenefit: 15000,
        roi: 200, // percentage
        paybackPeriod: "3 months",
      },
      recommendations: ["建议分阶段实施", "需要技术评审"],
    };
  }
}

LLM投票预测:

  • Sentiment分析: 分析社区讨论情绪(positive/negative/neutral)
  • 投票预测: 基于历史数据预测投票结果
  • 置信度: 预测准确度评分(0-100%)

治理工作流引擎:

  • 自动触发: 提案到期自动统计投票
  • 通知机制: 投票开始/结束/结果公布通知
  • 执行追踪: 通过提案后的执行进度追踪

13.2 数据库设计

governance_proposals表:

sql
CREATE TABLE governance_proposals (
  proposal_id TEXT PRIMARY KEY,
  title TEXT NOT NULL,
  description TEXT NOT NULL,
  proposer_did TEXT NOT NULL,
  status TEXT DEFAULT 'draft', -- draft/active/passed/rejected/expired
  vote_counts TEXT DEFAULT '{"support":0,"against":0,"abstain":0}', -- JSON
  quorum_required INTEGER DEFAULT 100,
  voting_period INTEGER DEFAULT 604800, -- 7天(秒)
  created_at INTEGER NOT NULL,
  voting_start INTEGER,
  voting_end INTEGER
)

governance_votes表:

sql
CREATE TABLE governance_votes (
  vote_id TEXT PRIMARY KEY,
  proposal_id TEXT NOT NULL,
  voter_did TEXT NOT NULL,
  vote_value TEXT NOT NULL, -- support/against/abstain
  comment TEXT,
  timestamp INTEGER NOT NULL,
  FOREIGN KEY (proposal_id) REFERENCES governance_proposals(proposal_id)
)

13.3 IPC接口

Governance IPC (social/governance-ipc.js) - 4个处理器:

javascript
ipcMain.handle('governance:list-proposals', async (event, { status }) => { ... })
ipcMain.handle('governance:create-proposal', async (event, { title, description }) => { ... })
ipcMain.handle('governance:analyze-impact', async (event, { proposalId }) => { ... })
ipcMain.handle('governance:predict-vote', async (event, { proposalId }) => { ... })

13.4 前端集成

Pinia Store (stores/governance.ts):

typescript
export const useGovernanceStore = defineStore('governance', {
  state: () => ({
    proposals: [] as Proposal[],
    aiAnalysis: null as ImpactAnalysis | null,
    votePrediction: null as VotePrediction | null,
  }),
  actions: {
    async fetchProposals(status?: string) { ... },
    async createProposal(data: ProposalData) { ... },
    async analyzeImpact(proposalId: string) { ... },
    async predictVote(proposalId: string) { ... },
    async castVote(proposalId: string, voteValue: string) { ... },
  }
})

UI页面 (pages/social/GovernancePage.vue):

  • 提案列表: 状态筛选(全部/进行中/已通过/已拒绝), 搜索, 排序
  • AI影响分析面板: 利益相关方识别, 风险矩阵, ROI预测图表
  • 投票预测可视化: 预测结果饼图, 置信度进度条, sentiment分析词云
  • 治理统计仪表板: 总提案数, 通过率, 平均投票率, 活跃提案者排行
  • 提案创建向导: 标题/描述/投票期限/quorum设置

十四、Phase 55 — Matrix协议集成 (Matrix Bridge)

实现时间: 2026-02-27 (Q4 2026) 状态: ✅ 已实现 (v1.1.0-alpha)

14.1 Matrix Bridge

文件: desktop-app-vue/src/main/social/matrix-bridge.js

Matrix Client-Server API集成:

  • 登录/注册: POST /_matrix/client/r0/login, POST /_matrix/client/r0/register
  • 会话管理: Access Token管理, 自动刷新
  • 用户资料: GET/PUT /_matrix/client/r0/profile/{userId}

房间管理:

javascript
class MatrixBridge {
  async createRoom(name, encrypted = true) {
    // POST /_matrix/client/r0/createRoom
    return {
      room_id: "!abc:matrix.org",
      room_alias: "#myroom:matrix.org",
    };
  }

  async joinRoom(roomId) {
    // POST /_matrix/client/r0/join/{roomId}
  }

  async leaveRoom(roomId) {
    // POST /_matrix/client/r0/rooms/{roomId}/leave
  }

  async inviteUser(roomId, userId) {
    // POST /_matrix/client/r0/rooms/{roomId}/invite
  }

  async listRooms() {
    // GET /_matrix/client/r0/joined_rooms
  }
}

E2EE消息 (Olm/Megolm):

  • Olm: 1对1端到端加密(Double Ratchet算法)
  • Megolm: 群组端到端加密(对称密钥 + 会话密钥)
  • 设备验证: 交叉签名验证(Cross-Signing)
  • 密钥备份: 加密密钥云备份恢复

事件同步:

javascript
async syncEvents(since = null) {
  // GET /_matrix/client/r0/sync?since={token}
  const response = await this._matrixClient.sync({ since })

  return {
    next_batch: response.next_batch, // 下次同步token
    rooms: {
      join: { /* 已加入房间事件 */ },
      invite: { /* 邀请事件 */ },
      leave: { /* 离开房间事件 */ }
    },
    presence: { /* 在线状态事件 */ }
  }
}

DID → MXID映射:

  • DID格式: did:key:z6MkpTHR8VNsBxYAAWHut2Geadd9jSwuBV8xRoAnwWsdvktH
  • MXID格式: @user:matrix.org
  • 映射存储: matrix_did_mapping
  • 双向查询: getDIDByMXID(), getMXIDByDID()

14.2 数据库设计

matrix_rooms表:

sql
CREATE TABLE matrix_rooms (
  room_id TEXT PRIMARY KEY,
  mxid TEXT NOT NULL, -- Matrix room ID (!abc:matrix.org)
  name TEXT,
  encrypted INTEGER DEFAULT 1, -- 1=encrypted, 0=plain
  members TEXT, -- JSON array of MXIDs
  last_sync_token TEXT,
  joined_at INTEGER NOT NULL
)

matrix_events表:

sql
CREATE TABLE matrix_events (
  event_id TEXT PRIMARY KEY,
  room_id TEXT NOT NULL,
  sender TEXT NOT NULL, -- MXID
  type TEXT NOT NULL, -- m.room.message, m.room.encrypted
  content TEXT NOT NULL, -- JSON
  timestamp INTEGER NOT NULL,
  FOREIGN KEY (room_id) REFERENCES matrix_rooms(room_id)
)

14.3 IPC接口

Matrix IPC (social/matrix-ipc.js) - 5个处理器:

javascript
ipcMain.handle('matrix:login', async (event, { homeserver, userId, password }) => { ... })
ipcMain.handle('matrix:list-rooms', async () => { ... })
ipcMain.handle('matrix:send-message', async (event, { roomId, message }) => { ... })
ipcMain.handle('matrix:get-messages', async (event, { roomId, limit }) => { ... })
ipcMain.handle('matrix:join-room', async (event, { roomId }) => { ... })

14.4 前端集成

Pinia Store (stores/matrixBridge.ts):

typescript
export const useMatrixBridgeStore = defineStore('matrixBridge', {
  state: () => ({
    isLoggedIn: false,
    homeserver: 'https://matrix.org',
    userId: '',
    accessToken: '',
    rooms: [] as MatrixRoom[],
    currentRoom: null as MatrixRoom | null,
    messages: [] as MatrixEvent[],
  }),
  actions: {
    async login(userId: string, password: string) { ... },
    async fetchRooms() { ... },
    async sendMessage(roomId: string, message: string) { ... },
    async joinRoom(roomId: string) { ... },
    async startSync() { ... }, // 启动事件同步循环
  }
})

UI页面 (pages/social/MatrixBridgePage.vue):

  • 登录面板: Homeserver URL输入, 用户ID/密码登录, 服务器发现(.well-known/matrix/client)
  • 房间列表: 已加入房间列表, 未读消息计数, 加密标识🔒
  • 消息时间线: 聊天气泡(发送者/时间/内容), Markdown渲染, 图片/文件附件
  • E2EE指示器: 🔐加密房间徽章, 设备验证状态, 密钥备份提示
  • DID映射管理: DID↔MXID绑定列表, 添加/删除映射, 跨协议消息转发

十五、未来扩展

  • [x] 内容推荐系统: 本地协同过滤推荐 ✅ Phase 48
  • [x] Nostr协议支持: NIP-01 Bridge + Schnorr签名 ✅ Phase 49
  • [x] AI社区治理: 提案管理 + AI影响分析 + 投票预测 ✅ Phase 54
  • [x] Matrix协议集成: E2EE消息 + DID映射 + 房间管理 ✅ Phase 55
  • [ ] ML主题分类: 使用深度学习提升分类准确率
  • [ ] 实时图谱更新: WebSocket推送图谱变化
  • [ ] 多语言支持: 支持中文/英文/日文主题分析
  • [ ] ActivityPub C2S: 支持客户端到服务器协议
  • [ ] Fediverse搜索: 跨实例内容搜索
  • [ ] Nostr NIP扩展: NIP-04加密DM, NIP-09删除请求, NIP-25 Reactions
  • [ ] Matrix Spaces: 支持Matrix空间(类似Discord服务器)
  • [ ] Matrix Threads: 支持消息线程(Thread Reply)

文档版本: 1.2.0 最后更新: 2026-02-27

ChainlessChain 系统设计文档 — 面向开发者