ai_co_discuss 0.5.60 → 0.5.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/.agents/skills/discuss-host/SKILL.md +5 -1
  2. package/.agents/skills/discuss-host/references/dev-flow.md +36 -7
  3. package/README.md +1 -1
  4. package/README.zh-CN.md +1 -1
  5. package/backend/analytics.py +23 -4
  6. package/backend/external_members.py +1 -4
  7. package/backend/free_room.py +61 -14
  8. package/backend/message_queue.py +12 -6
  9. package/backend/moss_delegation.py +48 -3
  10. package/backend/moss_window_messages.py +0 -2
  11. package/backend/room_import.py +5 -2
  12. package/backend/schema.sql +13 -3
  13. package/backend/server.py +451 -58
  14. package/docs/deployment.md +3 -1
  15. package/docs/en/deployment.md +3 -1
  16. package/docs/en/guide/admin.md +5 -1
  17. package/docs/en/guide/analytics.md +3 -3
  18. package/docs/en/guide/cli.md +15 -1
  19. package/docs/en/guide/external-members.md +2 -2
  20. package/docs/en/guide/first-run.md +1 -1
  21. package/docs/en/guide/members.md +3 -2
  22. package/docs/en/guide/remote.md +1 -1
  23. package/docs/en/guide/rooms.md +10 -8
  24. package/docs/en/guide/steward.md +4 -4
  25. package/docs/en/guide/working.md +2 -2
  26. package/docs/guide/admin.md +5 -1
  27. package/docs/guide/analytics.md +3 -3
  28. package/docs/guide/cli.md +15 -1
  29. package/docs/guide/external-members.md +2 -2
  30. package/docs/guide/first-run.md +1 -1
  31. package/docs/guide/members.md +3 -2
  32. package/docs/guide/remote.md +1 -1
  33. package/docs/guide/rooms.md +10 -8
  34. package/docs/guide/steward.md +4 -4
  35. package/docs/guide/working.md +2 -2
  36. package/frontend/locales/en/admin.json +22 -0
  37. package/frontend/locales/en/analytics.json +9 -2
  38. package/frontend/locales/en/app.json +23 -6
  39. package/frontend/locales/en/backend.json +6 -1
  40. package/frontend/locales/en/core.json +2 -0
  41. package/frontend/locales/en/room.json +43 -6
  42. package/frontend/locales/en/settings.json +5 -1
  43. package/frontend/locales/en/steward.json +6 -1
  44. package/package.json +9 -2
  45. package/runner/account_env.mjs +151 -24
  46. package/runner/adapters/antigravity_cli.mjs +63 -47
  47. package/runner/adapters/api.mjs +12 -208
  48. package/runner/adapters/api_pi.mjs +18 -69
  49. package/runner/adapters/api_pi_extension.mjs +6 -19
  50. package/runner/adapters/claude.mjs +9 -58
  51. package/runner/adapters/claude_lockdown_hook.mjs +3 -4
  52. package/runner/adapters/index.mjs +1 -9
  53. package/runner/adapters/profiles.mjs +23 -31
  54. package/runner/admin_cli.mjs +16 -7
  55. package/runner/admin_panel.mjs +106 -36
  56. package/runner/channels.mjs +7 -1
  57. package/runner/codiscuss.mjs +13 -16
  58. package/runner/discuss.py +55 -74
  59. package/runner/discussion_launch.mjs +116 -59
  60. package/runner/discussion_service.mjs +64 -25
  61. package/runner/discussion_setup.mjs +59 -19
  62. package/runner/discussion_skills.mjs +99 -0
  63. package/runner/expert_prompts.mjs +34 -5
  64. package/runner/external_client.mjs +47 -48
  65. package/runner/free_runner.mjs +147 -84
  66. package/runner/i18n_en.mjs +59 -8
  67. package/runner/moss_windows.mjs +74 -37
  68. package/runner/os_users.mjs +116 -26
  69. package/runner/project_files.mjs +86 -123
  70. package/runner/room_templates.mjs +102 -21
  71. package/runner/share_card.mjs +6 -6
  72. package/runner/share_shared.mjs +1 -1
  73. package/runner/site_deploy.mjs +85 -19
  74. package/runner/steward.mjs +2 -2
  75. package/skills/forum-browsing/SKILL.md +164 -0
  76. package/skills/forum-browsing/references/bilibili.md +43 -0
  77. package/skills/forum-browsing/references/cross-source.md +31 -0
  78. package/skills/forum-browsing/references/douyin.md +44 -0
  79. package/skills/forum-browsing/references/hackernews.md +67 -0
  80. package/skills/forum-browsing/references/health.md +34 -0
  81. package/skills/forum-browsing/references/jike.md +16 -0
  82. package/skills/forum-browsing/references/linuxdo.md +86 -0
  83. package/skills/forum-browsing/references/reddit.md +26 -0
  84. package/skills/forum-browsing/references/setup.md +119 -0
  85. package/skills/forum-browsing/references/v2ex.md +37 -0
  86. package/skills/forum-browsing/references/weixin.md +47 -0
  87. package/skills/forum-browsing/references/x.md +65 -0
  88. package/skills/forum-browsing/references/xhs.md +52 -0
  89. package/skills/forum-browsing/references/youtube.md +42 -0
  90. package/skills/forum-browsing/references/zhihu.md +49 -0
  91. package/skills/forum-browsing/scripts/bilibili.py +324 -0
  92. package/skills/forum-browsing/scripts/browser_common.py +370 -0
  93. package/skills/forum-browsing/scripts/check.py +389 -0
  94. package/skills/forum-browsing/scripts/common.py +177 -0
  95. package/skills/forum-browsing/scripts/douyin.py +349 -0
  96. package/skills/forum-browsing/scripts/hackernews.py +197 -0
  97. package/skills/forum-browsing/scripts/jike.py +164 -0
  98. package/skills/forum-browsing/scripts/linuxdo.py +390 -0
  99. package/skills/forum-browsing/scripts/reddit.py +167 -0
  100. package/skills/forum-browsing/scripts/v2ex.py +187 -0
  101. package/skills/forum-browsing/scripts/video_common.py +171 -0
  102. package/skills/forum-browsing/scripts/weixin.py +648 -0
  103. package/skills/forum-browsing/scripts/x.py +435 -0
  104. package/skills/forum-browsing/scripts/xhs.py +321 -0
  105. package/skills/forum-browsing/scripts/youtube.py +166 -0
  106. package/skills/forum-browsing/scripts/zhihu.py +387 -0
  107. package/web/admin.css +1 -1
  108. package/web/admin.js +8 -8
  109. package/web/app.js +678 -220
  110. package/web/backup.js +1 -1
  111. package/web/guest.css +1 -1
  112. package/web/guest.js +1 -1
  113. package/web/i18n.js +4 -4
  114. package/web/markdown.css +1 -1
  115. package/web/modern.css +1 -1
  116. package/web/modern.js +85 -81
@@ -35,6 +35,10 @@ description: "AI CoDiscuss 的主持技能,仅主持人调用,且须同时
35
35
 
36
36
  怎么规划由你判断;只在会改变方向的关键歧义处向用户确认。派活写清谁做什么、做到什么程度,怎么拆、按什么步骤做交给成员——他们背后的软件自己会规划。执行性工作(读长文、写汇总、核对证据、跑测试)派给成员,你做判断、裁定与汇总,上下文与额度留给整个房间的推进。用户的倾向、成员意见一致都不等于已验证事实。
37
37
 
38
- 用户没指定人选、要你自己挑人或挑模型时(分派、换模型或强度、邀请成员、组织讨论),参考你收到的“用户给本机房间主持人的提示”(用户自己的派活与选人偏好,如哪家额度多、谁擅长什么)、`room view` 的 `descriptions`(用户写的各成员擅长与分工)和 [成员分工参考](references/members.md)(各家模型的公开长短)。用户明确要你记下或改掉这类偏好时,先 `codiscuss launch prompts get host` 读出全文,改好后写进草稿,再 `codiscuss launch prompts set host --file 草稿` 整份保存,并在回答里写明改了什么;用户没要求不改。用户纠正你的派活(改派、换模型或强度、说“这类活别给某某”)且看得出是长期偏好、不只是这一次的安排时,照做之后在同一条回答末尾问一句要不要记进主持人提示词;同类纠正问过就不再问。(纠正不沉淀,下次照旧派错。)命令被拒(只读)就请用户到“设置 → 系统提示词 → 主持人”里改。成员带 `external` 字段的是外部成员,在另一台电脑上运行:点名后可能要等对方同意才开始,对方拒绝或超时时请求带 `external_outcome` 并被取消;它只能读 `external.directories` 里的目录、提交自己的回答,不能派活。出图、改图优先派给能看图的本机软件成员,它能下载附件自查效果;没有 `image` 字段时请用户在“协作设置”添加生图卡片。
38
+ **轻重门限与批次内“五不准”**:单轮独立闭环的小改动(不派任何人、按当前策略可直接做完)由你直接完成;**一旦本任务链已发出派活进入多成员批次,主持人立即适用五不准**:① 不改本批业务文件;② 不代成员 `git apply` 补丁(沙箱受限时应调高该主刀权限档位让其本人落盘);③ 派活正文不写行级代码处方或完整改法,只写问题、定位与完成标准;④ 不在主持轮跑构建和整套大测试;⑤ 自己若写过本批文件,未经他人复验不得直接汇总。
39
+
40
+ **决策优先级与房间主持策略**:选人、拆单与投入节奏按 `用户当次要求 > 房间主持策略 > 全局主持人提示词 > 成员描述 > 成员分工参考` 依次生效。房间主持策略由房主按房间设定,仅调节推进节奏与可选投入(撤销时恢复沿用全局做法),不改变权限边界与高风险安全底线。
41
+
42
+ **选人偏好与账号额度边界**:用户没指定人选、要你自己挑人或挑模型时(分派、换模型或强度、邀请成员、组织讨论),参考你收到的“用户给本机房间主持人的提示”(用户自己的派活与选人偏好,如哪家额度多、谁擅长什么)、`room view` 的 `descriptions`(用户写的各成员擅长与分工)和 [成员分工参考](references/members.md)(各家模型的公开长短)。`room view` 中的账号额度(`free.quotas`)仅在成员干完活后更新,属于滞后参考:**未在本房间实际唤醒并拿到准确满额读数前,不得仅凭陈旧读数前置封杀某平台**;只有本房唤醒确认该成员所属模型组的任一有效窗口(5 小时 / 7 天双窗或各独立模型池)已满(100%),且 `resets_at > 0` 尚未到点或 `resets_at = 0`(无明确重置时刻)时,才在运行态避开该池改派其他可用成员。已过 `resets_at` 仅代表解除旧满额拦截、当前余量记为“未知”(不当作确认 0%),同账号下另一独立模型池仍有余量时不受影响;API 余额与订阅窗口百分比不同量纲,不互相比较排序;用户当次明确点名的模型受额度限制时,说明原因请用户决定,不私自偷换。用户明确要你记下或改掉选人偏好时,先 `codiscuss launch prompts get host` 读出全文,改好后写进草稿,再 `codiscuss launch prompts set host --file 草稿` 整份保存,并在回答里写明改了什么;用户没要求不改。用户纠正你的派活(改派、换模型或强度、说“这类活别给某某”)且看得出是长期偏好、不只是这一次的安排时,照做之后在同一条回答末尾问一句要不要记进主持人提示词;同类纠正问过就不再问。(纠正不沉淀,下次照旧派错。)命令被拒(只读)就请用户到“设置 → 系统提示词 → 主持人”里改。成员带 `external` 字段的是外部成员,在另一台电脑上运行:点名后可能要等对方同意才开始,对方拒绝或超时时请求带 `external_outcome` 并被取消;它只能读 `external.directories` 里的目录、提交自己的回答,不能派活。出图、改图优先派给能看图的本机软件成员,它能下载附件自查效果;没有 `image` 字段时请用户在“协作设置”添加生图卡片。
39
43
 
40
44
  任务带 `scheduler_suggestions` 时,那是智能调度说明某条消息或交接为何交给你(附置信度),不是用户指令,也未核实:按其中的 `request_id`、`message_id` 先读原文再决定是否采纳,需要依据时 `state decision ROOM DECISION_ID`。`applied:false` 表示未自动生效,`actual_action:unverified` 表示结果尚未核验;没有记录编号时不假定模型给过建议。
@@ -2,16 +2,45 @@
2
2
 
3
3
  仅在你是房间主持人、且用户请成员分工改代码(定计划、实现、评审、整理文档),要预先指定评审,或任务有 `review_handoffs` 时读本页;派活规则见 [请求与派活](room.md)。
4
4
 
5
- ## 分工
5
+ **审查投入与本页边界**:是否派审、审 1 家还是 2 家、是否做终验,按用户当次要求与当前房间主持策略执行;**一旦本链进入多人拆分或独立审查,一律受本页五步有界收敛协议与 [SKILL.md](../SKILL.md) 批次内“五不准”约束**。在 `求快 / 省 Token` 档下,常规改动由执行者自检直交;若改动触碰权限、数据、协议高风险底线,则走轻量底线:**1 名跨厂快审锁清单 + 最多 1 次 `--sequential` 定点复验**(不并派双审、不跑重型矩阵,汇总注明未做项),不退化为 `深入` 档。
6
6
 
7
- 怎么组织由你按任务判断。房间特有的几点:
7
+ ## 五步有界收敛协议
8
+
9
+ ### 1. 定界派发(派实现时一次写清)
8
10
 
9
11
  - 用户未表示可以开始时不派实现。
10
- - 共享工作目录不加锁:派活写明每位成员负责的目录或文件,并行的部分不让两人改同一文件。
11
- - `room view` 的执行报告列有改动文件,交评审时可据此写明范围。
12
- - 并行实现交回后看 `room view` 的 `free.conflicts`:列出的文件确实被两位成员在同一时段都改过;没列出不代表没有,成员用命令写的文件不在检测范围内。
13
- - 同一问题反复不通过,或本链剩余轮数(`free.chain_rounds` 的 `allowed` 减 `used`;null 即不限)不够完成下一轮时,停下向用户说明分歧与现状。
14
- - 向用户汇报时写明仍未验证的部分。
12
+ - 共享工作目录不加锁:紧耦合单链路或少量文件默认由 1 名主刀包干(含自检、构建、多语言);多模块并行时按端到端用户路径定验收责任、按文件定唯一可写白名单,不让两人改同一文件,并指定 1 名可写成员做集成(移出主持人轮次)。
13
+ - 派实现正文一次写清:**验收清单**(每项含入口、预期结果、验收人)、**每人可写文件白名单**、**阻塞三条件**、**复验上限 2 次**,并在需要时带 `--need-rounds` 一次申报预算(标准闭环约 5 轮:实现 1 + 首审 1 + 修补复验 ≤2 + 终验 1)。
14
+ - 判定阻塞只认本批验收清单;复验时不得从 TODO 或子台账另挖新目标。
15
+ - 并行实现交回后查看 `room view` 的 `free.conflicts`:列出的文件确实被两位成员在同一时段改过;未列出不代表没有,经命令写入的文件不在检测范围内。
16
+
17
+ ### 2. 首审锁清单
18
+
19
+ - **唯一允许整批审查的一轮**,范围是本批验收清单与改动触及的边界;允许对照用户原话补入漏列的必经入口,**首审结束清单即锁死**,非阻塞项进待办交用户。
20
+ - **同速快审选型**:常规 1 名快审,深入档或涉权限、数据、协议双审时并派 2 名不同厂商的快速审查模型;不用长考慢模型跑同步审查。签收必验的审查不用 `--detach`;`--detach` 仅用于不回来也不影响诚实签收的可选检查,且收尾汇总必须写明仍在后台未回。
21
+ - 交评审时可结合 `room view` 执行报告或 `execution view` 的改动文件写明范围。每条发现须写明:消息号加序号、违反哪条清单项或哪项既有行为、失败用例或完整代码因果链、后果;缺因果链的记为建议,不判阻塞。
22
+
23
+ ### 3. 修补与增量复验(最多 2 次封顶)
24
+
25
+ - **阻塞三条件**(必须同时满足才列为必改并派修,其余进待办在汇总交用户):
26
+ 1. 破坏已锁定清单项,或造成既有受支持行为回归;
27
+ 2. 有失败用例或完整代码因果链;
28
+ 3. 后果为越权、数据损坏或丢失、崩溃或主功能失效。
29
+ - **修复与直传**:修复派活写明可改文件;主刀需要动白名单外文件时,首行写 `【交接未就绪:原因】`,复验员见到即原样交回。范围已定的用 `--to 主刀 --to 原快审 --sequential` 直传不经主持人,范围未稳的加 `--checkpoint 主刀`。
30
+ - **增量复验**:只核对原必改清单与本轮执行实际写入的文件(以 `execution view` 的 `diagnostics.file_attribution.paths` 或执行报告改动文件为准,禁止扩审无关全文件)。替补换人复验沿用原清单与原计数。
31
+ - **三条硬熔断出口**:
32
+ 1. **清单清零** → 立即进入终验或收口;
33
+ 2. **外部工具能力上限** → 某项承诺被证实受外部工具固有能力所限无法实现时,**不开修复轮**,改写为“已知边界”并带 `--awaiting-user` 请用户确认收窄承诺;
34
+ 3. **达上限或轮数不足** → 满 2 次增量复验(轻量底线满 1 次)仍有未清项,或本链剩余轮数(`free.chain_rounds` 的 `allowed` 减 `used`,`null` 即不限)不够完成下一轮时,**无条件停下**,带 `--awaiting-user` 汇报剩余项、影响与已有证据。
35
+
36
+ ### 4. 终验单次后置与收口汇总
37
+
38
+ - 真实浏览器双视口截图、跨软件真机核验、构建与整套测试只在静态审查清零后的最终签收阶段跑**唯一一次**,由实现方或指定集成成员执行。
39
+ - 向用户汇报时写明:已改与已验、已知边界、未清项或仍未验证的部分、以及仍在后台未回的可选审查。
40
+
41
+ ### 5. 用户中途点名“全面 Review”
42
+
43
+ - 视为新批次首审。收到报告后先向用户回**分流表**:仅满足阻塞三条件的必改项当场派修,其余建议与低优先级项列单请用户勾选,不整单派修。
15
44
 
16
45
  ## 预先指定评审
17
46
 
package/README.md CHANGED
@@ -64,7 +64,7 @@ npm install --global ai_co_discuss@latest
64
64
  codiscuss setup
65
65
  ```
66
66
 
67
- `setup` detects your AI tools, installs the discussion skills and opens the local site at <http://127.0.0.1:8765>. On Windows, a 共议 (AI CoDiscuss) icon appears in the taskbar once the service starts; it opens the **admin panel** (start, stop and update the service, sign in to AI tools, bind the self-hosted relay and pick its region; running setup with `--hosting` also turns on hosted accounts). See [Admin panel and hosted accounts](docs/en/guide/admin.md). macOS and Linux have no admin panel yet. Then:
67
+ `setup` detects your AI tools, installs the discussion skills (plus optional bundled skills such as `forum-browsing` or workflows when selected under **Install settings**, or with `--optional-skills` / `--workflows`), and opens the local site at <http://127.0.0.1:8765>. On Windows, a 共议 (AI CoDiscuss) icon appears in the taskbar once the service starts; it opens the **admin panel** (start, stop and update the service, sign in to AI tools, bind the self-hosted relay and pick its region; running setup with `--hosting` also turns on hosted accounts). See [Admin panel and hosted accounts](docs/en/guide/admin.md). macOS and Linux have no admin panel yet. Then:
68
68
 
69
69
  1. Click **New Room** (新建房间) and add AI members.
70
70
  2. Pick a host with the crown icon, and optionally set a project directory.
package/README.zh-CN.md CHANGED
@@ -64,7 +64,7 @@ npm install --global ai_co_discuss@latest
64
64
  codiscuss setup
65
65
  ```
66
66
 
67
- `setup` 检测本机 AI 软件、安装讨论技能,并打开本机网站 <http://127.0.0.1:8765>。在 Windows 上,服务启动后任务栏会出现“共议”图标,点开即**管理面板**(服务启停与更新、AI 软件登录、自建中转绑定与中转地区;加 `--hosting` 运行 setup 还会开启托管账号),见[管理面板与托管账号](docs/guide/admin.md);macOS 与 Linux 暂无管理面板。然后:
67
+ `setup` 检测本机 AI 软件、安装讨论技能(也可在“安装配置”里勾选,或加 `--optional-skills` / `--workflows` 安装 `forum-browsing` 等可选随包技能与工作流),并打开本机网站 <http://127.0.0.1:8765>。在 Windows 上,服务启动后任务栏会出现“共议”图标,点开即**管理面板**(服务启停与更新、AI 软件登录、自建中转绑定与中转地区;加 `--hosting` 运行 setup 还会开启托管账号),见[管理面板与托管账号](docs/guide/admin.md);macOS 与 Linux 暂无管理面板。然后:
68
68
 
69
69
  1. 点击 **新建房间**,添加 AI 成员。
70
70
  2. 点皇冠指定主持人,按需填写项目目录。
@@ -228,6 +228,22 @@ def overview(facts, start, end, sealed):
228
228
  return {**result, "delivery": delivery, "coverage": {"numerator": delivery["samples"], "denominator": result["ended"]}}
229
229
 
230
230
 
231
+ def union_seconds(spans):
232
+ """Return the wall-clock duration covered by at least one interval."""
233
+ total = 0
234
+ current = None
235
+ for start, end in sorted(spans):
236
+ if current is None:
237
+ current = [start, end]
238
+ elif start <= current[1]:
239
+ if end > current[1]:
240
+ current[1] = end
241
+ else:
242
+ total += current[1] - current[0]
243
+ current = [start, end]
244
+ return total + (current[1] - current[0] if current is not None else 0)
245
+
246
+
231
247
  def peak_concurrent(intervals):
232
248
  """Union each key's intervals, then return the most keys active at once and the first moment it happened."""
233
249
  events = Counter()
@@ -396,11 +412,12 @@ def time_stats(connection, requests, executions, bounds, now, sealed):
396
412
  seen.add(r["message_id"])
397
413
  if start <= r["created_at"] < end and r["dispatched"] is not None and r["dispatched"] >= r["created_at"]:
398
414
  waits.append(r["dispatched"] - r["created_at"])
399
- spans, member_spans, shown_spans = defaultdict(list), defaultdict(list), defaultdict(list)
415
+ all_spans, spans, member_spans, shown_spans = [], defaultdict(list), defaultdict(list), defaultdict(list)
400
416
  elapsed, rework = [], []
401
417
  for r in executions:
402
418
  left, right = max(start, r["created_at"]), min(end, r["finished_at"] or now, now)
403
419
  if left < right:
420
+ all_spans.append((left, right))
404
421
  spans[r["room_id"]].append((left, right))
405
422
  member_spans[(r["room_id"], r["name"])].append((left, right))
406
423
  shown_spans[(r["room_id"], r["label"] or r["name"])].append((left, right))
@@ -422,6 +439,7 @@ def time_stats(connection, requests, executions, bounds, now, sealed):
422
439
  active_rooms = [room for room in room_rows.values() if room["initiated"] or room["execution_seconds"]]
423
440
  return {"folders": list(folders.values()), "rooms": active_rooms, "peak": peak, "concurrency": concurrency, "sealed_execution_seconds": counts["execution_seconds"],
424
441
  "execution_seconds": sum(f["execution_seconds"] for f in folders.values()) + counts["execution_seconds"],
442
+ "active_seconds": union_seconds(all_spans),
425
443
  "waiting": distribution(waits, histograms["waiting"]),
426
444
  "execution": distribution(elapsed, histograms["execution"]), "rework": distribution(rework, histograms["rework"]),
427
445
  "queue": {"count": count, "oldest_seconds": max(0, now-oldest) if count else None}}
@@ -601,14 +619,15 @@ def previous_work(rows, start, end, now):
601
619
  Same rules as the current period (clipped to the window, overlaps merged per room and per room + member), over
602
620
  existing rooms only.
603
621
  """
604
- seconds, rooms, members = 0, defaultdict(list), defaultdict(list)
622
+ seconds, all_spans, rooms, members = 0, [], defaultdict(list), defaultdict(list)
605
623
  for r in rows:
606
624
  left, right = max(start, r["created_at"]), min(end, r["finished_at"] or now, now)
607
625
  if left < right:
608
626
  seconds += right - left
627
+ all_spans.append((left, right))
609
628
  rooms[r["room_id"]].append((left, right))
610
629
  members[(r["room_id"], r["name"])].append((left, right))
611
- return {"execution_seconds": seconds, "peak_rooms": peak_concurrent(rooms)[0], "peak_members": peak_concurrent(members)[0]}
630
+ return {"execution_seconds": seconds, "active_seconds": union_seconds(all_spans), "peak_rooms": peak_concurrent(rooms)[0], "peak_members": peak_concurrent(members)[0]}
612
631
 
613
632
 
614
633
  MOSS_COUNTERS = ("task_rooms", "project_rooms", "delegations", "reworks", "unreported", "reclaimed")
@@ -712,7 +731,7 @@ def snapshot(connection, params, cache, now):
712
731
  scope = {"mode": mode, "rooms": len(rooms), "sealed_rooms": retained, "included_rooms": len(rooms) + retained,
713
732
  "includes_archived": True, "sealed_day_tz": "UTC", "sealed_counts": SEALED_COUNTS,
714
733
  "sealed_distributions": SEALED_DISTRIBUTIONS,
715
- "current_only": ["folders", "rooms", "peak", "concurrency", "issues", "queue", "affected_requests", "members", "models", "workflows", "insights", "scheduler"]}
734
+ "current_only": ["active_seconds", "folders", "rooms", "peak", "concurrency", "issues", "queue", "affected_requests", "members", "models", "workflows", "insights", "scheduler"]}
716
735
  scheduler = scheduler_quality(connection, start, end, distribution)
717
736
  result = dict(range=dates, scope=scope,
718
737
  overview=overview(facts, start, end, sealed), previous=overview(facts, previous, start, prior),
@@ -79,11 +79,8 @@ def guard_route(connect, headers, parts):
79
79
  return
80
80
  hashed = token_hash(headers.get("X-Discussion-Token", ""))
81
81
  if not marked and hashed:
82
- connection = connect()
83
- try:
82
+ with connect() as connection:
84
83
  marked = connection.execute("SELECT 1 FROM external_members WHERE token_hash=?", (hashed,)).fetchone() is not None
85
- finally:
86
- connection.close()
87
84
  if marked:
88
85
  raise classified(PermissionError, Text("外部成员只能使用成员范围接口"), "external_route_forbidden")
89
86
 
@@ -1406,9 +1406,10 @@ def recent_executions(connection, room_id, span=None):
1406
1406
  (room_id, low, low, MAX_MESSAGE_ID if high is None else high, room_id))
1407
1407
  else:
1408
1408
  rows = connection.execute(
1409
- f"""{query} AND (e.status IN ('dispatched','started')
1410
- OR e.id IN (SELECT id FROM member_executions WHERE room_id=? ORDER BY id DESC LIMIT ?))
1411
- ORDER BY e.id DESC""", (room_id, room_id, RECENT_EXECUTIONS))
1409
+ f"""{query} AND e.id IN (
1410
+ SELECT id FROM member_executions WHERE room_id=? AND status IN ('dispatched','started')
1411
+ UNION SELECT id FROM (SELECT id FROM member_executions WHERE room_id=? ORDER BY id DESC LIMIT ?))
1412
+ ORDER BY e.id DESC""", (room_id, room_id, room_id, RECENT_EXECUTIONS))
1412
1413
  executions = []
1413
1414
  positions = relay_positions(connection, room_id)
1414
1415
  for row in rows:
@@ -1676,9 +1677,11 @@ def free_view(connection, room_id):
1676
1677
  JOIN member_executions e ON e.id=rr.execution_id WHERE rr.request_id=member_requests.id),
1677
1678
  created_at) AS layout_at,
1678
1679
  EXISTS(SELECT 1 FROM retried_requests rr WHERE rr.request_id=member_requests.id) AS retried FROM member_requests
1679
- WHERE room_id=? AND (status IN ('pending','delivering')
1680
- OR id IN (SELECT id FROM member_requests WHERE room_id=? ORDER BY id DESC LIMIT ?))
1680
+ WHERE id IN (
1681
+ SELECT id FROM member_requests WHERE room_id=? AND status IN ('pending','delivering')
1682
+ UNION SELECT id FROM (SELECT id FROM member_requests WHERE room_id=? ORDER BY id DESC LIMIT ?))
1681
1683
  ORDER BY id DESC""", (room_id, room_id, RECENT_REQUESTS))]
1684
+ tag_group_requests(connection, room_id, requests)
1682
1685
  chains = [dict(row) for row in connection.execute(
1683
1686
  "SELECT chain_id,reason FROM free_chains WHERE room_id=? ORDER BY chain_id DESC LIMIT 10", (room_id,))]
1684
1687
  max_rounds = chain_rounds(connection, room_id)
@@ -1915,6 +1918,7 @@ def check_proactive(connection, room_id, member, payload):
1915
1918
  reason = payload.get("continue")
1916
1919
  if reason is not None and (not isinstance(reason, str) or not reason.strip() or len(reason) > MAX_CONTINUE_REASON):
1917
1920
  raise ValueError(Text("continue 写明房间空闲后继续做什么,最多 {max_continue_reason} 字", max_continue_reason=MAX_CONTINUE_REASON))
1921
+ check_host_undispatched_mentions(connection, room_id, member, payload)
1918
1922
 
1919
1923
 
1920
1924
  def after_proactive(connection, room_id, message_id, member, payload):
@@ -1974,7 +1978,7 @@ def check_answer(connection, room_id, member, payload):
1974
1978
  purposes.append(row["purpose"])
1975
1979
  requests.append(row)
1976
1980
  discussion.validate_session_request_answer(connection, room_id, requests)
1977
- check_dispatch(member, payload, purposes)
1981
+ check_dispatch(connection, room_id, member, payload, purposes)
1978
1982
  return None
1979
1983
  execution_id = payload.get("execution_id")
1980
1984
  if type(execution_id) is not int:
@@ -2003,16 +2007,45 @@ def check_answer(connection, room_id, member, payload):
2003
2007
  requests = [dict(item) for item in connection.execute(
2004
2008
  "SELECT id,purpose FROM member_requests WHERE execution_id=? AND status='delivering'", (execution_id,))]
2005
2009
  discussion.validate_session_request_answer(connection, room_id, requests)
2006
- check_dispatch(member, payload, [item["purpose"] for item in requests])
2010
+ check_dispatch(connection, room_id, member, payload, [item["purpose"] for item in requests])
2007
2011
  return row
2008
2012
 
2009
2013
 
2010
- def check_dispatch(member, payload, purposes):
2014
+ HOST_MENTION_PREFIX = r"(^|[\s((\[【*,,。;;::、])@"
2015
+ MENTION_SUFFIX = r"(?![A-Za-z0-9_\-\u4e00-\u9fff])"
2016
+
2017
+
2018
+ def check_host_undispatched_mentions(connection, room_id, member, payload, purposes=()):
2019
+ """Reject a host reply that @-mentions active members in prose without passing `to` or `detach`."""
2020
+ if (member["role"] != "host" or payload.get("source") == "auto" or payload.get("to") or payload.get("detach")
2021
+ or purposes and (all(purpose == "all" for purpose in purposes)
2022
+ or any(purpose in ("discuss", "discuss_host") for purpose in purposes))):
2023
+ return
2024
+ prose = mention_prose(str(payload.get("text") or ""))
2025
+ if "@" not in prose:
2026
+ return
2027
+ active = active_members(connection, room_id)
2028
+ shown = member_display_names(connection, room_id)
2029
+ mentioned = []
2030
+ for handle, name in member_handles(connection, room_id).items():
2031
+ if name in active and name != member["name"] and name not in mentioned and re.search(
2032
+ HOST_MENTION_PREFIX + re.escape(handle) + MENTION_SUFFIX, prose):
2033
+ mentioned.append(name)
2034
+ if mentioned:
2035
+ mentions = "、".join(f"@{shown.get(name, name)}" for name in mentioned)
2036
+ raise ValueError(Text(
2037
+ "正文提到了 {mentions} 但未指定 --to(或 --detach),这样不会唤醒对方;要派活请补上 --to,仅作文本提及请去掉 @ 符号",
2038
+ mentions=mentions,
2039
+ ))
2040
+
2041
+
2042
+ def check_dispatch(connection, room_id, member, payload, purposes):
2011
2043
  """A host answering only its share of an everyone request answers as a member, so it may not dispatch others."""
2012
2044
  if member["role"] == "host" and payload.get("to") and purposes and all(purpose == "all" for purpose in purposes):
2013
2045
  raise ValueError(Text("这次是请全体成员各自回应,其他成员已收到请求;主持人只回答自己的部分,不能用 --to 派活"))
2014
2046
  if payload.get("keep_working") and any(purpose in ("discuss", "discuss_host") for purpose in purposes):
2015
2047
  raise ValueError(Text("讨论中的发言不能用 keep_working"))
2048
+ check_host_undispatched_mentions(connection, room_id, member, payload, purposes)
2016
2049
 
2017
2050
 
2018
2051
  def check_keep_working(member, payload):
@@ -3302,6 +3335,9 @@ def after_free_message(connection, room_id, message_id, actor, payload):
3302
3335
  insert_request(connection, room_id, member_id, message_id, message_id, purpose, "user")
3303
3336
  return
3304
3337
  chain_id = answered_chain(connection, payload, actor)
3338
+ if actor["role"] == "host":
3339
+ connection.execute("""UPDATE free_host_checkins SET due_at=?+interval_seconds
3340
+ WHERE room_id=? AND host_id=? AND due_at<=?""", (now, room_id, actor["id"], now))
3305
3341
  if actor["access"] == "manual":
3306
3342
  for request_id in payload.get("request_ids", []):
3307
3343
  connection.execute("UPDATE member_requests SET status='completed',answer_id=? WHERE id=?", (message_id, request_id))
@@ -3624,6 +3660,7 @@ def fire_host_checkin(connection, room_id):
3624
3660
  UNION SELECT 1 FROM free_sequences WHERE room_id=? AND status='running'""", (room_id, row["host_id"], room_id)).fetchone()
3625
3661
  chain_id = row["chain_id"]
3626
3662
  due_at = row["due_at"]
3663
+ connection.execute("UPDATE free_host_checkins SET due_at=? WHERE room_id=?", (now + row["interval_seconds"], room_id))
3627
3664
  if not busy:
3628
3665
  if not out_of_rounds(connection, room_id, chain_id):
3629
3666
  if connection.execute("SELECT 1 FROM member_requests WHERE member_id=? AND status IN ('pending','delivering')", (row["host_id"],)).fetchone():
@@ -3638,7 +3675,6 @@ def fire_host_checkin(connection, room_id):
3638
3675
  (row["host_id"],)).fetchone()
3639
3676
  if not host_working:
3640
3677
  wake_host(connection, room_id, chain_id, Text("定时检查:房间里还有进行中的工作。读一下 room view 与各成员的执行进展,确认没有卡住、跑偏或失败未处理;没有需要处理的就直接结束本次执行,不发消息。"), f"checkin:{due_at}")
3641
- connection.execute("UPDATE free_host_checkins SET due_at=? WHERE room_id=?", (now + row["interval_seconds"], room_id))
3642
3678
 
3643
3679
 
3644
3680
  def inbox(connection, room_id, token):
@@ -4220,6 +4256,7 @@ def execution_detail(connection, row):
4220
4256
  request["origin"] = origin
4221
4257
  requests = [{**request, **review_request_context(connection, request), **sequence_request_context(connection, request), **handoff_outcome(connection, request),
4222
4258
  **questions.request_context(connection, request), "texts": request_texts(connection, request["id"], request.get("session_request_id"))} for request in requests]
4259
+ tag_group_requests(connection, row["room_id"], requests)
4223
4260
  detail = public_execution(row)
4224
4261
  detail["texts"] = execution_texts(connection, row["id"])
4225
4262
  quota = quota_failure(connection, row["id"])
@@ -5455,9 +5492,18 @@ def check_relay(connection, room_id, relay):
5455
5492
  return host
5456
5493
 
5457
5494
 
5458
- def relay_execution_roots(connection, room_id, member_id, execution_id):
5495
+ def tag_group_requests(connection, room_id, requests):
5496
+ """Expose group provenance on both room reads and execution claims."""
5497
+ if requests and connection.execute("SELECT 1 FROM room_directory WHERE room_id=? AND system_kind='steward_group'",
5498
+ (room_id,)).fetchone():
5499
+ from .moss_delegation import tag_requests
5500
+ tag_requests(connection, room_id, requests)
5501
+
5502
+
5503
+ def relay_execution_roots(connection, room_id, member_id, execution_id, *, request_ids=None):
5459
5504
  """Resolve each request through its question history, so an answer never starts a new owner root."""
5460
- return connection.execute("""WITH RECURSIVE
5505
+ scope = "member_id=:member AND execution_id=:execution" if request_ids is None else "id IN (SELECT value FROM json_each(:requests))"
5506
+ return connection.execute(f"""WITH RECURSIVE
5461
5507
  question_messages(question_id,message_id,host_reply) AS (
5462
5508
  SELECT q.id,m.value,m.key=2 OR (m.key=0 AND json_extract(NULLIF(q.answer,''),'$.action')='decided')
5463
5509
  FROM room_questions q
@@ -5490,12 +5536,13 @@ def relay_execution_roots(connection, room_id, member_id, execution_id):
5490
5536
  lineage(id,root,report) AS (
5491
5537
  SELECT id,COALESCE(NULLIF(chain_id,0),message_id),
5492
5538
  purpose IN ('followup','keep_working') OR (purpose='notice' AND message_id!=chain_id)
5493
- FROM member_requests WHERE room_id=:room AND member_id=:member AND execution_id=:execution
5539
+ FROM member_requests WHERE room_id=:room AND {scope}
5494
5540
  UNION
5495
5541
  SELECT l.id,q.root,l.report OR q.report FROM lineage l JOIN questions q
5496
5542
  ON l.root=q.message_id AND q.root<l.root
5497
5543
  )
5498
- SELECT r.message_id,r.status,l.root,m.author,m.source,relay.chain,relay.origin,
5544
+ SELECT r.id AS request_id,r.message_id,r.status,l.root,m.author,m.source,relay.chain,relay.origin,
5545
+ r.purpose, EXISTS(SELECT 1 FROM question_messages qm WHERE qm.message_id=r.message_id) AS question_message,
5499
5546
  l.report OR EXISTS (SELECT 1 FROM question_messages qm WHERE qm.message_id=l.root) AS report,
5500
5547
  d.system_kind AS relay_kind,s.owner AS external_owner,t.template,
5501
5548
  EXISTS (SELECT 1 FROM message_withdrawals w WHERE w.message_id IN (l.root,r.message_id)) AS withdrawn
@@ -5507,7 +5554,7 @@ def relay_execution_roots(connection, room_id, member_id, execution_id):
5507
5554
  LEFT JOIN stored_texts t ON t.owner='message' AND t.owner_id=m.id AND t.field='trigger'
5508
5555
  WHERE NOT EXISTS (SELECT 1 FROM questions q WHERE l.root=q.message_id AND q.root<l.root)
5509
5556
  ORDER BY r.id,l.root DESC""",
5510
- {"room": room_id, "member": member_id, "execution": execution_id}).fetchall()
5557
+ {"room": room_id, "member": member_id, "execution": execution_id, "requests": json.dumps(request_ids)}).fetchall()
5511
5558
 
5512
5559
 
5513
5560
  def relay_provenance(connection, room_id, member_id, execution_id, roots=None):
@@ -53,9 +53,11 @@ def queue_view(connection, room_id):
53
53
  items = []
54
54
  for row in connection.execute("SELECT * FROM queued_messages WHERE room_id=? ORDER BY position,id", (room_id,)):
55
55
  payload = json.loads(row["payload"])
56
- files = [dict(item) for item in connection.execute(
57
- "SELECT id,file_name,content_type FROM attachments WHERE room_id=? AND id IN (SELECT value FROM json_each(?))",
58
- (room_id, json.dumps(payload.get("attachment_ids", []))))]
56
+ attachment_ids = payload.get("attachment_ids") or []
57
+ by_id = {entry["id"]: dict(entry) for entry in connection.execute(
58
+ "SELECT id,file_name,content_type,size,storage,cleared_at FROM attachments WHERE room_id=? AND id IN (SELECT value FROM json_each(?))",
59
+ (room_id, json.dumps(attachment_ids)))} if attachment_ids else {}
60
+ files = [by_id[identifier] for identifier in attachment_ids if identifier in by_id]
59
61
  item = {"id": row["id"], "text": payload.get("text", ""), "attachments": files, "failure": row["failure"],
60
62
  "texts": load_texts(connection, "queued_message", row["id"]), "created_at": row["created_at"]}
61
63
  if relay := payload.get("relay"):
@@ -306,11 +308,13 @@ def next_queued(connection, room_id):
306
308
  return None, None
307
309
 
308
310
 
309
- def drain(connection, room_id, post):
311
+ def drain(connection, room_id, post, *, ready=None):
310
312
  """Release what may go now, one row at a time, unless the queue is paused; stops at a failed message or when nothing may go."""
311
313
  if not connection.execute("SELECT 1 FROM queued_messages WHERE room_id=? LIMIT 1", (room_id,)).fetchone():
312
314
  return
313
315
  begin_write(connection)
316
+ if ready and not ready(connection, room_id):
317
+ return
314
318
  drop_taken_back(connection, room_id)
315
319
  archived = connection.execute("SELECT archived FROM room_directory WHERE room_id=?", (room_id,)).fetchone()
316
320
  if archived is None or archived[0] or connection.execute("SELECT 1 FROM queued_message_pauses WHERE room_id=?", (room_id,)).fetchone():
@@ -356,7 +360,7 @@ def reorder(connection, room_id, ids):
356
360
  connection.execute("UPDATE queued_messages SET position=? WHERE id=?", (position, item_id))
357
361
 
358
362
 
359
- def queue_action(connection, room_id, token, payload, post, check, interrupt):
363
+ def queue_action(connection, room_id, token, payload, post, check, interrupt, *, ready=None):
360
364
  """The owner acts on the queue: send one now, edit, delete, reorder or resume it.
361
365
 
362
366
  `post(connection, room_id, payload, actor)` posts a message; `check(payload)` validates an edited one;
@@ -370,6 +374,8 @@ def queue_action(connection, room_id, token, payload, post, check, interrupt):
370
374
  raise ValueError(Text('action 须为 {value1} 之一', value1='、'.join(QUEUE_ACTIONS)))
371
375
  sent_message_id = None
372
376
  if action == "send":
377
+ if ready and not ready(connection, room_id):
378
+ raise FileExistsError(Text("MOSS 群窗口已关闭。"))
373
379
  row = queued_row(connection, room_id, payload.get("id"))
374
380
  connection.execute("UPDATE queued_messages SET failure='' WHERE id=?", (row["id"],))
375
381
  result = post_item(connection, room_id, row, post)
@@ -386,6 +392,6 @@ def queue_action(connection, room_id, token, payload, post, check, interrupt):
386
392
  reorder(connection, room_id, payload.get("ids"))
387
393
  else:
388
394
  connection.execute("DELETE FROM queued_message_pauses WHERE room_id=?", (room_id,))
389
- drain(connection, room_id, post)
395
+ drain(connection, room_id, post, ready=ready)
390
396
  view = queue_view(connection, room_id)
391
397
  return {**view, "message_id": sent_message_id} if sent_message_id else view
@@ -35,13 +35,17 @@ def delegation_directory(home, window, submission, requested):
35
35
  raise PermissionError(Text("群委托工作目录须在本任务的专用目录内"))
36
36
 
37
37
 
38
- def execution_roots(connection, room_id, member_id, execution_id):
38
+ def execution_roots(connection, room_id, member_id, execution_id, *, request_ids=None):
39
39
  """Resolve each execution request to verified roots, following question answers back to the work they resume."""
40
40
  roots = []
41
- for row in relay_execution_roots(connection, room_id, member_id, execution_id):
41
+ for row in relay_execution_roots(connection, room_id, member_id, execution_id, request_ids=request_ids):
42
42
  owner = row["external_owner"]
43
43
  if owner is None and row["relay_kind"] in ("steward", "steward_private"):
44
44
  owner = int(row["origin"] == "owner")
45
+ if (owner is None and row["origin"] is None and row["author"] == "用户"
46
+ and row["source"] not in ("guest", "system", "external")
47
+ and row["template"] not in ("steward_scheduled", "steward_proactive")):
48
+ owner = 1
45
49
  if row["withdrawn"]:
46
50
  owner = None
47
51
  elif owner is not None and row["report"]:
@@ -50,6 +54,47 @@ def execution_roots(connection, room_id, member_id, execution_id):
50
54
  return sorted(roots, key=lambda item: (item["root"], item["message_id"]), reverse=True)
51
55
 
52
56
 
57
+ def tag_requests(connection, room_id, requests):
58
+ """Project the current instruction and the verified delegation roots independently."""
59
+ grouped = {}
60
+ for root in execution_roots(connection, room_id, None, None, request_ids=[item["id"] for item in requests]):
61
+ grouped.setdefault(root["request_id"], []).append(root)
62
+ for request in requests:
63
+ roots = grouped.get(request["id"], [])
64
+ request["owner_instruction"] = bool(roots) and all(
65
+ root["root"] == request["message_id"] and root["owner"] == 1 and root["external_owner"] is None
66
+ and root["source"] == "user" and root["origin"] is None and not root["question_message"]
67
+ and root["purpose"] not in ("notice", "followup", "keep_working") for root in roots)
68
+ eligible = [root for root in roots if root["owner"] is not None]
69
+ external = [root for root in eligible if root["external_owner"] is not None]
70
+ guests = [root for root in external if root["external_owner"] == 0]
71
+ request["group_source"] = ({
72
+ "owner": owner_execution(connection, room_id, None, None, roots),
73
+ "guest": bool(guests),
74
+ "external_message_id": (guests or external)[0]["root"] if external else None,
75
+ } if eligible and all(root["purpose"] != "notice" for root in roots) else None)
76
+
77
+
78
+ def channel_pending(connection, room_id):
79
+ """Route each pending answer by its whole batch, preferring a real group message."""
80
+ pending = [dict(row) for row in connection.execute("""SELECT o.message_id,o.channel
81
+ FROM moss_channel_out o JOIN messages m ON m.id=o.message_id WHERE m.room_id=? AND o.state='pending'
82
+ AND NOT EXISTS(SELECT 1 FROM message_withdrawals WHERE message_id=m.id) ORDER BY m.id""", (room_id,))]
83
+ if not pending:
84
+ return []
85
+ requests = [dict(row) for row in connection.execute("""SELECT id,message_id,answer_id FROM member_requests
86
+ WHERE room_id=? AND answer_id IN (SELECT value FROM json_each(?)) ORDER BY message_id""",
87
+ (room_id, json.dumps([item["message_id"] for item in pending])))]
88
+ tag_requests(connection, room_id, requests)
89
+ for item in pending:
90
+ batch = [request for request in requests if request["answer_id"] == item["message_id"]]
91
+ external = [request["group_source"]["external_message_id"] for request in batch
92
+ if request["group_source"] and request["group_source"]["external_message_id"]]
93
+ item["request_id"] = min(external) if external else batch[0]["message_id"] if batch else None
94
+ item["owner_instruction"] = int(bool(batch) and all(request["owner_instruction"] for request in batch))
95
+ return pending
96
+
97
+
53
98
  def owner_execution(connection, room_id, member_id, execution_id, roots):
54
99
  """Require every source to be verified owner work, and exclude mixed chains or returned notices."""
55
100
  return bool(roots and all(root["owner"] == 1 for root in roots)
@@ -65,7 +110,7 @@ def question_owner_origin(connection, room_id, question):
65
110
 
66
111
 
67
112
  def delegation_source(connection, payload, owner, acting):
68
- """Bind the child to a group host and a real external message in its execution."""
113
+ """Bind the child to a group host and a verified source message in its execution."""
69
114
  room_id, execution = payload.get("source_window_id"), payload.get("execution_id")
70
115
  message = payload.get("source_message_id")
71
116
  if not isinstance(room_id, str) or type(execution) is not int or not 0 < execution <= 2**63 - 1:
@@ -17,8 +17,6 @@ def validate_message_flags(room, payload, actor):
17
17
  raise ValueError(Text("请用两步发送向群发言,窗口回答无需 silent"))
18
18
  if not group:
19
19
  return
20
- if actor == "用户" and "external" not in payload:
21
- raise ValueError(Text("群窗口的外部消息须带 external 来源"))
22
20
  if actor != "用户" and "external" in payload:
23
21
  raise PermissionError(Text("只有本房间的控制凭据能提交外部消息"))
24
22
  if payload.get("proactive") is True or payload.get("steward_proactive") is True:
@@ -71,9 +71,12 @@ def room_statements(tables, room, maps, control_hash):
71
71
  """Room, directory and the importer's ownership; the room arrives unfiled."""
72
72
  messages, room_id = maps["messages"], room["id"]
73
73
  directory = (tables.get("room_directory") or [{}])[0]
74
- statements = [("INSERT INTO rooms (id,title,goal,state_text,state_until,created_at) VALUES (?,?,?,?,?,?)",
74
+ # The owner's host strategy; older backups and share packs have none or a stripped one.
75
+ host_strategy = room.get("host_strategy")
76
+ host_strategy = host_strategy[:4000] if isinstance(host_strategy, str) else ""
77
+ statements = [("INSERT INTO rooms (id,title,goal,state_text,state_until,created_at,host_strategy) VALUES (?,?,?,?,?,?,?)",
75
78
  (room_id, room["title"], remap_text(room["goal"], messages), remap_text(room.get("state_text"), messages),
76
- remap_until(room.get("state_until"), messages), room["created_at"])),
79
+ remap_until(room.get("state_until"), messages), room["created_at"], host_strategy)),
77
80
  ("UPDATE room_directory SET archived=? WHERE room_id=?", (int(bool(directory.get("archived"))), room_id)),
78
81
  ("INSERT INTO room_modes (room_id,mode,control_hash) VALUES (?,'free',?)", (room_id, control_hash))]
79
82
  return statements
@@ -1,4 +1,5 @@
1
1
  CREATE TABLE IF NOT EXISTS rooms (
2
+ host_strategy TEXT NOT NULL DEFAULT '',
2
3
  id TEXT PRIMARY KEY, title TEXT NOT NULL, goal TEXT NOT NULL,
3
4
  state_text TEXT NOT NULL DEFAULT '', state_until INTEGER NOT NULL DEFAULT 0,
4
5
  created_at TEXT NOT NULL
@@ -82,7 +83,7 @@ CREATE TABLE IF NOT EXISTS attachments (
82
83
  thumbnail_type TEXT,
83
84
  -- When the owner cleared the original bytes to free space (the record and thumbnail stay); NULL while kept.
84
85
  cleared_at TEXT,
85
- storage TEXT, object_name TEXT, stored_at TEXT,
86
+ storage TEXT, object_name TEXT, stored_at TEXT, object_scope TEXT,
86
87
  UNIQUE(room_id, submission_id)
87
88
  );
88
89
  CREATE TABLE IF NOT EXISTS cloud_folders (
@@ -169,7 +170,7 @@ CREATE TABLE IF NOT EXISTS room_relay_sends (
169
170
  target_message_id INTEGER,
170
171
  queued_id INTEGER,
171
172
  interrupted INTEGER NOT NULL DEFAULT 0,
172
- state TEXT NOT NULL DEFAULT 'delivered' CHECK(state IN ('queued','delivered','replied')),
173
+ state TEXT NOT NULL DEFAULT 'delivered' CHECK(state IN ('queued','delivered','replied','cancelled')),
173
174
  host TEXT NOT NULL,
174
175
  member TEXT NOT NULL DEFAULT ''
175
176
  );
@@ -397,6 +398,7 @@ CREATE TABLE IF NOT EXISTS room_members (
397
398
  );
398
399
  CREATE UNIQUE INDEX IF NOT EXISTS member_name ON room_members(room_id,name) WHERE status<>'removed';
399
400
  CREATE UNIQUE INDEX IF NOT EXISTS member_credential ON room_members(room_id,token_hash) WHERE token_hash<>'';
401
+ CREATE INDEX IF NOT EXISTS room_members_by_status ON room_members(room_id,status);
400
402
 
401
403
  -- Local service attestation, never a permission grant. Re-imported rooms require a fresh attestation.
402
404
  CREATE TABLE IF NOT EXISTS member_review_capabilities (
@@ -580,6 +582,7 @@ CREATE TABLE IF NOT EXISTS execution_segments (
580
582
  PRIMARY KEY(source,execution_id,seq)
581
583
  );
582
584
  CREATE INDEX IF NOT EXISTS execution_segments_room ON execution_segments(room_id);
585
+ CREATE INDEX IF NOT EXISTS execution_segments_by_phase ON execution_segments(source,execution_id,phase);
583
586
  -- One live execution per member: different members may run in parallel, one session never twice.
584
587
  CREATE UNIQUE INDEX IF NOT EXISTS one_member_execution ON member_executions(member_id)
585
588
  WHERE status IN ('dispatched','started');
@@ -610,6 +613,7 @@ CREATE INDEX IF NOT EXISTS member_requests_answer ON member_requests(answer_id);
610
613
  CREATE INDEX IF NOT EXISTS member_requests_room ON member_requests(room_id);
611
614
  CREATE INDEX IF NOT EXISTS member_requests_room_chain ON member_requests(room_id,chain_id);
612
615
  CREATE INDEX IF NOT EXISTS member_requests_room_status ON member_requests(room_id,status);
616
+ CREATE INDEX IF NOT EXISTS member_requests_by_message ON member_requests(room_id,message_id,status);
613
617
  CREATE INDEX IF NOT EXISTS member_requests_batch ON member_requests(batch_id,status);
614
618
  -- Where a request's cards sit on the page: the room's latest message when the request was made. The page shows every
615
619
  -- card (working, failed, stopped, answer) under the top-level message at or before it, ordered by when its work started,
@@ -1084,6 +1088,7 @@ CREATE TABLE IF NOT EXISTS execution_continuations (
1084
1088
  execution_id INTEGER PRIMARY KEY REFERENCES member_executions(id) ON DELETE CASCADE,
1085
1089
  next_id INTEGER NOT NULL REFERENCES member_executions(id) ON DELETE CASCADE
1086
1090
  );
1091
+ CREATE INDEX IF NOT EXISTS execution_continuations_by_next ON execution_continuations(next_id);
1087
1092
  -- A follow-up execution (续报): background work (a sub-agent, a background command, a monitor) that the ended execution
1088
1093
  -- `source_id` left running reported, and the member's software started a new turn on it; the runner opened this one
1089
1094
  -- for that turn, so its answer has a source (red line 4, user 2026-11-25). One per source: a later report follows the
@@ -1119,6 +1124,7 @@ CREATE TABLE IF NOT EXISTS free_host_wakes (
1119
1124
  message_id INTEGER NOT NULL,
1120
1125
  PRIMARY KEY (room_id,key)
1121
1126
  );
1127
+ CREATE INDEX IF NOT EXISTS free_host_wakes_by_message ON free_host_wakes(message_id,key);
1122
1128
  -- The host's latest answer asked to continue once the room is idle; a later request for the host or a new owner
1123
1129
  -- message supersedes it (`after_request` is the newest request when it was asked).
1124
1130
  -- The host's timed check-in: while the room still has work in flight, the host gets a notice every interval to look
@@ -1995,6 +2001,8 @@ CREATE TABLE IF NOT EXISTS stored_texts (
1995
2001
  );
1996
2002
  CREATE INDEX IF NOT EXISTS room_events_room ON room_events(room_id,id);
1997
2003
  CREATE INDEX IF NOT EXISTS room_events_kind_at ON room_events(kind,at);
2004
+ CREATE INDEX IF NOT EXISTS room_events_host_changes ON room_events(room_id,id)
2005
+ WHERE kind IN ('member.joined','member.changed');
1998
2006
  -- Stop analytics names this index so it does not scan every api.write event.
1999
2007
  CREATE INDEX IF NOT EXISTS room_events_owner_stop ON room_events(at,room_id)
2000
2008
  WHERE kind='api.write' AND CASE WHEN json_valid(data) THEN json_extract(data,'$.path') END='/stop';
@@ -2221,6 +2229,7 @@ CREATE TABLE IF NOT EXISTS room_goals (
2221
2229
  pending_fallback INTEGER NOT NULL DEFAULT 0
2222
2230
  );
2223
2231
  CREATE UNIQUE INDEX IF NOT EXISTS one_open_goal ON room_goals(room_id) WHERE status IN ('active','paused');
2232
+ CREATE INDEX IF NOT EXISTS room_goals_pending_by_room ON room_goals(room_id) WHERE status='active' AND phase='pending';
2224
2233
  CREATE UNIQUE INDEX IF NOT EXISTS room_goals_start_request ON room_goals(start_request_id) WHERE start_request_id IS NOT NULL;
2225
2234
  -- Each automatic wake-up: the visible system message it hangs on and the host request it created.
2226
2235
  CREATE TABLE IF NOT EXISTS goal_continuations (
@@ -2346,7 +2355,8 @@ CREATE TABLE IF NOT EXISTS room_sites (
2346
2355
  files_json TEXT NOT NULL DEFAULT '[]',
2347
2356
  expires_at TEXT NOT NULL DEFAULT '',
2348
2357
  created_at TEXT NOT NULL,
2349
- updated_at TEXT NOT NULL
2358
+ updated_at TEXT NOT NULL,
2359
+ password_protected INTEGER NOT NULL DEFAULT 0
2350
2360
  );
2351
2361
  CREATE INDEX IF NOT EXISTS room_sites_room ON room_sites(room_id, updated_at DESC);
2352
2362
  CREATE INDEX IF NOT EXISTS room_sites_status ON room_sites(status, expires_at);