Skip to content

refactor: 适配 AmritaBot 1.22 跨平台 Envelope 与 Alconna 命令 (0.11.0) - #12

Merged
JohnRichard4096 merged 2 commits into
mainfrom
refactor/adapt-amrita-latest
Dec 4, 2026
Merged

JohnRichard4096 merged 2 commits into
mainfrom
refactor/adapt-amrita-latest

Conversation

@AmriaLin

@AmriaLin AmriaLin commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

适配 AmritaBot 1.22.0 的跨平台 Envelope 抽象、权限接口与依赖版本,解除对 OneBot V11 单一适配器的强绑定,并将版本号升至 0.11.0。

主要改动

  • 跨平台分区键与权限(keys.py、permissions.py):resolve_scope_uni_id 与权限校验统一支持 Envelope | Event,新增 parse_target_user、resolve_user_uni_id、matches_target_user,支持完整 uni_id、platform:id 与裸 ID 写法。
  • 命令与备忘录 / 工具链(matchers.py、tools.py、memo.py):/memory 迁移至 Alconna + EnvelopeNBDep,备忘录转发改走 amrita.utils.send.send_forward_msg;工具与 pre-completion hook 优先读取 envelope 并回退 event。
  • 潜意识模块(rethinking/hooks.py、runner.py、tools.py):钩子与分区键解析改用新辅助函数,主动私聊推送改为通过 Amrita 平台 resolve_sender 发送,不再绑定单一适配器。
  • 插件入口与依赖(__init__.py、pyproject.toml、uv.lock):移除 supported_adapters={"~onebot.v11"} 限制,兼容 nonebot_plugin_alconna 加载;依赖升级至 amrita>=1.22.0,<2.0.0、amrita-core>=1.4.0,<2.0.0、nonebot-plugin-amrita>=0.5.1、nonebot-plugin-orm[default]>=0.8.3,补充 nonebot-plugin-alconna 与 nonebot-plugin-uniconf,dev 依赖迁移至 [dependency-groups],版本号升至 0.11.0。

验证

  • ruff check amrita_plugin_memory、ruff format --check amrita_plugin_memory 通过
  • uvx pyright --pythonpath .venv/bin/python amrita_plugin_memory 0 errors, 0 warnings
  • 9 个改动模块 py_compile 通过
  • 隔离环境冒烟测试(amrita==1.22.0、amrita_core==1.6.0、nonebot2==2.5.0):插件加载、ORM 初始化、ambot memory --help、OB11 Event / Envelope 键解析与权限判定、Alconna 命令解析、备忘录读写追加、L2 记忆 CRUD、潜意识工具与钩子均通过
  • 隔离目录 ambot run 完整拉起 Bot 验证:启动成功(含 ChromaDB 1.5.9 与衰减定时任务)、根路径返回 HTTP 200、SIGINT 优雅退出(退出码 0)

影响面

  • 最低宿主版本提升至 amrita>=1.22.0、amrita-core>=1.4.0,不再限定 OneBot V11 适配器。
  • /memory usage 文本不再暴露隐藏的 dmn 管理选项。

Summary by Sourcery

Adapt the memory plugin for Amrita’s cross-platform Envelope and Alconna interfaces.

New Features:

  • Allow subconscious user targets to use full cross-platform IDs, platform:id values, or bare IDs with a QQ default.
  • Add atomic memo appending so concurrent additions are retained.

Bug Fixes:

  • Avoid mutating the response usage totals while aggregating subconscious usage.

Enhancements:

  • Support cross-platform Envelopes and events for memory partitioning, permissions, and user identity matching.
  • Move the /memory command to Alconna and use platform-neutral messaging and group-admin checks.
  • Remove the OneBot V11 adapter restriction and hide the dmn management option from the plugin usage text.

Build:

  • Require Amrita 1.22 and amrita-core 1.4 or later, add Alconna and uniconf dependencies, and move development dependencies to dependency groups.
  • Bump the package version to 0.11.0.

Chores:

  • Update the dependency lockfile for the revised runtime and development dependencies.

适配 AmritaBot 1.22.0 的跨平台 Envelope 抽象与依赖升级,解除对 OneBot V11 单一适配器的强绑定:
- keys / permissions / tools / memo / rethinking:统一优先消费 Envelope 并兼容原始 Event,规范跨平台 uni_id 与 target_user_id 解析;潜意识主动私聊推送改走 Amrita 平台 Sender
- matchers:/memory 命令迁移至 Alconna + EnvelopeNBDep,合并转发改走公共 send_forward_msg
- 插件入口与依赖:移除 supported_adapters 的 OB11 限定,补充 nonebot_plugin_alconna 兼容加载;依赖升级至 amrita>=1.22.0、amrita-core>=1.4.0 等,版本升至 0.11.0
@sourcery-ai

sourcery-ai Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Data structures

定义跨平台与历史 uni_id 的识别、目标用户解析及分区键生成规则,供记忆、权限和潜意识模块共同依赖。

  • amrita_plugin_memory/keys.py L1-10, L35-137, L144-159 (+1 small edits)

在现有 memo 数据模型上新增并发安全的追加操作,供工具链原子完成读取、拼接与写入。

  • amrita_plugin_memory/memo.py L3, L11, L87-120

API

统一 Envelope 与原始 Event 的权限目标处理,并公开平台敏感的用户匹配及知识库、画像权限检查接口。

  • amrita_plugin_memory/permissions.py L35-48, L63-95, L118-129 (+3 small edits)

将 /memory 命令接口迁移至 Alconna 与 Envelope,并调整参数提取、管理员校验、消息发送和删除权限处理。

  • amrita_plugin_memory/matchers.py L1-23, L30-42, L98-109 (+12 small edits)

调整记忆工具对会话目标的提取和分区解析,并使用新的原子 memo 追加接口。

  • amrita_plugin_memory/tools.py L16-38 (+5 small edits)

Uses of the API

让潜意识钩子以跨平台目标用户匹配来筛选会话,并让 runner 使用规范化用户分区键及副本统计 token 用量。

  • amrita_plugin_memory/rethinking/hooks.py L4, L13, L28-30
  • amrita_plugin_memory/rethinking/runner.py L512-518 (+3 small edits)

让潜意识工具按平台解析目标并通过可用 Sender 私聊推送,同时以跨平台 uni_id 读取目标用户记忆。

  • amrita_plugin_memory/rethinking/tools.py L307-340 (+6 small edits)

让 memo pre-completion hook 优先从上下文 Envelope 读取会话标识,并兼容原始 Event。

  • amrita_plugin_memory/memo.py L139-144

Configuration

更新插件入口加载兼容逻辑与元数据,并升级跨平台宿主、命令及 ORM 依赖和插件版本。

  • amrita_plugin_memory/__init__.py L1-8, L19, L22 (removed lines)
  • pyproject.toml L4-17, L40-41, L46-47

Lock files and vendored code

同步锁文件中的依赖解析结果,记录本次依赖版本调整。

  • uv.lock L389-415, L1948-1968, L3236-3295 (+16 small edits)

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 7 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="amrita_plugin_memory/permissions.py" line_range="76" />
<code_context>
+    if env is not None:
+        if not env.actor.user_id:
+            return False
+        if ":" not in value and parse_uni_id(value) is None:
+            return env.actor.user_id == value
+        cfg_platform, cfg_uid = parse_target_user(value)
</code_context>
<issue_to_address>
**Other platforms read the target profile**

When a bare `target_user_id` is configured and another platform has an account with the same user ID, `matches_target_user` compares only the user ID and does not enforce the configured ID’s default `qq` platform, so profile authorization succeeds for the other platform and exposes the target user’s profile.

Compare the event platform with the platform returned by `parse_target_user` for bare IDs as well as qualified IDs.

Also at `amrita_plugin_memory/permissions.py:77`.
</issue_to_address>

### Comment 2
<location path="amrita_plugin_memory/permissions.py" line_range="83" />
<code_context>
+    if isinstance(target, Envelope):
+        return False
+    raw_uid = event_user_id(target)
+    return raw_uid is not None and raw_uid == value
+
+
</code_context>
<issue_to_address>
**Raw-event ownership checks misfire**

When `envelope_from` cannot convert the raw event and the configured target is platform-qualified, or another platform has the same user ID, `matches_target_user` compares the raw user ID directly with the configured value, denying access for qualified target IDs and failing to distinguish platforms when IDs match; the user’s profile access or subconscious-hook matching is therefore incorrect.

Parse the configured target and compare both its platform and user ID with the raw event’s platform and user ID.

Also at `amrita_plugin_memory/rethinking/hooks.py:30`.
</issue_to_address>

### Comment 3
<location path="amrita_plugin_memory/keys.py" line_range="118" />
<code_context>
+        group_id = getattr(raw_event, "group_id", None)
         if group_id is None:
             raise ValueError("当前不在群聊中,无法使用群共享记忆")
         return make_scope_id(group_id, is_group=True)
     if scope == "user":
-        user_id = getattr(event, "user_id", None)
</code_context>
<issue_to_address>
**Non-QQ memory uses QQ partitions**

When a non-QQ raw event cannot be converted to an Envelope and exposes a user or group ID, `resolve_scope_uni_id` calls `make_scope_id` without the event’s platform, so the IDs use the default QQ platform and memory is stored under the wrong partitions, potentially colliding with QQ memory.

Pass the raw event’s platform to `make_scope_id` when resolving user and group scopes.

Also at `amrita_plugin_memory/keys.py:52`, `amrita_plugin_memory/keys.py:123`, `amrita_plugin_memory/permissions.py:83-84`.
</issue_to_address>

### Comment 4
<location path="amrita_plugin_memory/tools.py" line_range="487" />
<code_context>
 async def read_memo(ctx: ToolContext) -> str:
-    event: OB11Event = _get_event(ctx)
-    uni_id = get_uni_user_id(event)
+    uni_id = get_uni_user_id(_get_event(ctx))
     try:
         content = await get_memo(uni_id)
</code_context>
<issue_to_address>
**Concurrent memo appends overwrite each other**

When two append-memo tool calls for the same partition overlap, `append_memo` reads the current memo before `set_memo` acquires its write lock, so two requests for the same partition can both build from the same old value and the later write drops the earlier addition. The caller sees a successful append response even though its text is missing from the stored memo.

Make the read, append, and write one serialized operation, for example by moving the merge into a function that holds the memo lock throughout.
</issue_to_address>

### Comment 5
<location path="amrita_plugin_memory/rethinking/tools.py" line_range="327" />
<code_context>
         amrita_ctx = try_get_amrita_ctx(event.chat_object)
         if amrita_ctx is None:
             return
+        ctx_map = cast(dict[str, Any], amrita_ctx)
+        target = ctx_map.get("envelope") or ctx_map.get("event")
</code_context>
<issue_to_address>
**Available alternate bot ignored**

When multiple bots can reach the target and the first bot with a sender fails while sending, `_send_private_text` stops at the first bot with a sender, so a send error from that bot aborts the loop without trying later bots that can reach the same target; the caller reports the message as queued instead of delivering it through an available connection.

Catch send failures inside the loop and continue to the next bot, raising an error only after all candidate senders fail.
</issue_to_address>

### Comment 6
<location path="amrita_plugin_memory/matchers.py" line_range="210" />
<code_context>
         await matcher.finish(caption)

-    await matcher.send(MessageSegment.image(png))
+    await memory_cmd.send(UniMessage.image(raw=png))
     await matcher.finish(caption)

</code_context>
<issue_to_address>
**Heatmap image is not sent**

When an authorized user requests a heatmap and image rendering succeeds, `memory_cmd.send` calls an instance method on the matcher class rather than the active matcher instance, raising `TypeError` before the image is sent and causing the heatmap request to fail.

Send the image through the active matcher instance.
</issue_to_address>

### Comment 7
<location path="amrita_plugin_memory/keys.py" line_range="61-46" />
<code_context>
+def parse_target_user(
+    raw_id: str, *, default_platform: str = _DEFAULT_PLATFORM
+) -> tuple[str, str]:
+    """解析配置中的目标用户标识为 ``(platform, user_id)``。

-def resolve_scope_uni_id(event: OB11Event, scope: str) -> str:
-    """根据 scope 解析出分区键。
+    支持三种写法:完整 uni_id、``platform:id``、裸 ID(默认归入 default_platform)。
</code_context>
<issue_to_address>
**Helper docs violate style**

When the new helper docstrings are added, the new helper docstrings span multiple lines and summarize what the helpers do instead of using the required short, constraint-focused wording, violating the repository's documentation convention.

Rewrite the helper docstrings as concise, single-line Chinese statements focused on constraints or rationale.

Also at `amrita_plugin_memory/permissions.py:64-67`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 6 findings to address first, and when target_user_id is a bare ID, the new Envelope matching checks only user_id, so a user with the same ID on another platform can pass the profile-access check and receive data that cannot be recalled. Reverting restores the old matching behavior but cannot undo information already disclosed.

Blocking findings: amrita_plugin_memory/permissions.py:76, amrita_plugin_memory/permissions.py:83, amrita_plugin_memory/keys.py:118, amrita_plugin_memory/tools.py:487, amrita_plugin_memory/rethinking/tools.py:327, and 1 more


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread amrita_plugin_memory/permissions.py Resolved
Comment thread amrita_plugin_memory/permissions.py Resolved
Comment thread amrita_plugin_memory/keys.py Resolved
Comment thread amrita_plugin_memory/tools.py Resolved
Comment thread amrita_plugin_memory/matchers.py Resolved
Comment thread amrita_plugin_memory/keys.py Resolved
sourcery-ai[bot]

This comment was marked as duplicate.

- permissions:matches_target_user 对裸 target_user_id 与原始事件路径均校验平台,can_read_knowledge 移除无法构造 Envelope 时的原始 user_id 超管回退
- keys:parse_target_user 拒绝非私聊 uni_id,resolve_scope_uni_id 原始事件回退按推导平台生成分区键
- memo / tools:新增 append_memo_text 在写锁内原子完成读-拼-写,避免并发追加覆盖
- rethinking / matchers:_send_private_text 单路发送失败时继续回退其他可用 Bot;热度图发送改为 UniMessage.image(raw=png).send()
- docs:新增 helper docstring 改为符合仓库规范的单行中文说明

Co-authored-by: JohnRichard4096 <67693593+JohnRichard4096@users.noreply.github.com>
@JohnRichard4096
JohnRichard4096 merged commit ebf3ee5 into main Dec 4, 2026
3 checks passed
@JohnRichard4096
JohnRichard4096 deleted the refactor/adapt-amrita-latest branch December 4, 2026 10:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants