Quellcode durchsuchen

feat(provision): 容器开通端到端打通——门禁/等待页/心跳根因

- **容器开通全链路跑通**:App 点开通 → 云函数 → Matrix 工单 →
  主容器按技能执行 → docker run → 心跳上报 → 服务端三项核验 → ready
- **容器门禁**:无可用容器时只能进套餐页/开通页,防止新用户进入空界面
- **全屏开通等待页**:5 阶段真实进度、骨架态、成功/失败/错误三态齐全

1. **心跳永远不上报**——三个叠加根因:
   - `docker run` 缺 `gateway run` 参数 → 跑成交互式 TUI 直接退出
   - 缺 `-e` 环境变量 → 插件读不到 `/run/s6/container_environment/` 下的 token
   - `FmodeAgent` 记录没写 `agentId` → 插件自建第二条记录,云函数查到空壳那条
2. **新容器永远 offline**——首次上报即 offline(进程刚起),
   放宽判定为「offline + 心跳新鲜 = 可用」,并主动发消息唤醒
3. **登录后卡 /pending**——orgGuard 早已全放行但登录页没同步改
4. **门禁重定向白屏**——指向已不存在的 /desktop/plans
5. **刷新后卡加载**——等待页不读 error(),失败时无任何出口
6. **会话失效不跳登录页**——401 只抛错误文本,没有全局处理

- `cloud/functions/fmode-provisioning.js`(云函数 v0.8.0)
- `cloud/skills/container-provision-job/`(主容器执行技能 v4.0.0)
- `cloud/skills/container-stop-remove/`(容器清理技能)
- `cloud/scripts/r730_root_v3.py`(R730 SSH 执行器,带重试)
- `src/app/core/container.guard.ts`(容器门禁)
- `src/app/{mobile,desktop}/pages/provision/`(全屏等待页)
- `LoadinOverlayComponent` / `ProvisionInstructionComponent`(加载遮罩 / 提示词复制)

- `docs/03-interface/容器身份清单-20261126.md`(身份权威清单)
- 操作追踪完整留痕(心跳根因、容器清理、门禁设计)

- `tsc --noEmit` 通过
- `npm run build` 通过
- `npm test` 2006 SUCCESS

Co-Authored-By: Claude Code <noreply@anthropic.com>
Huccct vor 1 Tag
Ursprung
Commit
4b4a864a17
100 geänderte Dateien mit 17525 neuen und 89 gelöschten Zeilen
  1. 14 2
      .claude/dev-login.json
  2. 1043 0
      cloud/functions/fmode-provisioning.js
  3. BIN
      cloud/scripts/__pycache__/r730_root_v3.cpython-311.pyc
  4. BIN
      cloud/scripts/__pycache__/r730_root_v3.cpython-312.pyc
  5. 193 0
      cloud/scripts/r730_root_v3.py
  6. 372 0
      cloud/skills/container-provision-job/SKILL.md
  7. 243 0
      cloud/skills/container-stop-remove/SKILL.md
  8. 32 0
      docs/00-tracking/2026-11-25-套餐异步开通实施记录.md
  9. 39 0
      docs/00-tracking/2026-11-25-官网下载页重新部署.md
  10. 100 0
      docs/00-tracking/AI接手说明-套餐体系与容器资产.md
  11. 12 0
      docs/00-tracking/当前进度-给AI接手.md
  12. 891 0
      docs/00-tracking/操作追踪.md
  13. 82 0
      docs/01-requirements/changes/CR-20261125-02-平台容器与试用异步开通.md
  14. 90 0
      docs/01-requirements/changes/CR-20261125-套餐体系纳入范围.md
  15. 4 3
      docs/01-requirements/prd/PRD-20261014-fmode-app-v2.md
  16. 173 0
      docs/01-requirements/prd/PRD-20261125-套餐与开通体系.md
  17. 1 0
      docs/01-requirements/prd/SPEC-20261014-fmode-app-v2-草案.md
  18. 85 0
      docs/01-requirements/prd/定价与权益-20261125-草案.md
  19. 103 0
      docs/02-design/architecture/套餐权益与异步开通设计.md
  20. 149 0
      docs/02-design/plans/2026-11-25-套餐体系任务计划书.md
  21. 47 0
      docs/02-design/plans/2026-11-25-官网移动端与扫码下载优化.md
  22. 14 0
      docs/03-interface/README-容器接入文档索引.md
  23. 7 5
      docs/03-interface/api/API-契约.md
  24. 189 0
      docs/03-interface/api/套餐与平台异步开通-API契约.md
  25. 156 0
      docs/03-interface/容器创建完整流程-接口与提示词-20261124.md
  26. 80 0
      docs/03-interface/容器取证-agent-node-1795587945537.md
  27. 168 0
      docs/03-interface/容器取证-agent-node-1795590186473.md
  28. 93 0
      docs/03-interface/容器取证-agent-node-1795590476852.md
  29. 103 0
      docs/03-interface/容器取证-agent-node-1795592285067.md
  30. 147 0
      docs/03-interface/容器取证-agent-node-1795592452573.md
  31. 17 0
      docs/03-interface/容器取证-agent-node-1795592831870.md
  32. 53 0
      docs/03-interface/容器取证-agent-node-1795593412114.md
  33. 102 0
      docs/03-interface/容器取证-agent-node-1795593579721.md
  34. 71 0
      docs/03-interface/容器取证-agent-node-1795593798880.md
  35. 367 0
      docs/03-interface/容器取证-agent-node-1795657579810.md
  36. 62 0
      docs/03-interface/容器取证-agent-node-1795657752945.md
  37. 76 0
      docs/03-interface/容器取证-agent-node-1795657831039.md
  38. 85 0
      docs/03-interface/容器取证-agent-node-1795657872239.md
  39. 8 1
      docs/03-interface/容器接入完整指南-v2-20261111.md
  40. 289 0
      docs/03-interface/容器身份清单-20261126.md
  41. 176 0
      docs/03-interface/给主容器-建harness-test容器并按lj-test迁移-20261124.md
  42. 633 0
      docs/03-interface/自动开通回报-agent-node-app-test-0001-202611240327.md
  43. 586 0
      docs/03-interface/自动开通回报-agent-node-app-test-1125-202611250651.md
  44. 203 0
      docs/04-quality/backup/deleted-user-F2srRikSln-20261127.json
  45. 90 0
      docs/04-quality/backup/deleted-user-PNFaPMsbHS-20261127.json
  46. 202 0
      docs/04-quality/backup/deleted-user-WGJMHffBS3-20261127.json
  47. 33 0
      docs/04-quality/review/2026-11-25-套餐体系文档评审-第1轮.md
  48. 171 0
      docs/04-quality/review/2026-11-25-套餐异步开通-需求设计评审.md
  49. 40 5
      docs/04-quality/traceability-matrix.md
  50. 20 5
      docs/README.md
  51. 21 2
      prototypes/fmode-download-20261120/README.md
  52. 2 1
      prototypes/fmode-download-20261120/build.mjs
  53. 1149 7
      prototypes/fmode-download-20261120/index.html
  54. 268 0
      prototypes/fmode-download-20261120/site.css
  55. 147 13
      prototypes/fmode-download-20261120/site.js
  56. 40 5
      prototypes/fmode-download-20261120/site.template.html
  57. 838 0
      prototypes/fmode-download-20261120/vendor/qrcodegen.js
  58. 43 0
      prototypes/fmode-subscription-20261125/README.md
  59. 293 0
      prototypes/fmode-subscription-20261125/app.js
  60. 16 0
      prototypes/fmode-subscription-20261125/build.mjs
  61. 1665 0
      prototypes/fmode-subscription-20261125/index.html
  62. 132 0
      prototypes/fmode-subscription-20261125/model.js
  63. 40 0
      prototypes/fmode-subscription-20261125/preview.template.html
  64. 457 0
      prototypes/fmode-subscription-20261125/styles.css
  65. 182 0
      prototypes/fmode-subscription-20261125/verify.mjs
  66. 262 0
      scripts/create-test-account.mjs
  67. 18 0
      scripts/deploy-cloud-fn.mjs
  68. 12 0
      scripts/deploy.mjs
  69. 135 0
      scripts/master-channel.cjs
  70. 717 0
      scripts/onboard-user.mjs
  71. 224 0
      scripts/verify-download-site.mjs
  72. 34 2
      src/app/app.routes.ts
  73. 30 2
      src/app/app.ts
  74. 48 2
      src/app/components/domain/assistant-turn/assistant-turn.spec.ts
  75. 10 0
      src/app/components/domain/assistant-turn/assistant-turn.ts
  76. 188 0
      src/app/components/domain/loading-overlay/loading-overlay.ts
  77. 82 0
      src/app/components/domain/provision-instruction/provision-instruction.spec.ts
  78. 216 0
      src/app/components/domain/provision-instruction/provision-instruction.ts
  79. 2 0
      src/app/components/domain/session-tree/session-tree.ts
  80. 3 0
      src/app/core/api/api.provider.ts
  81. 29 0
      src/app/core/api/fmode-api.ts
  82. 68 7
      src/app/core/api/mock-api.ts
  83. 177 0
      src/app/core/api/models.ts
  84. 57 0
      src/app/core/api/parse-api.spec.ts
  85. 143 8
      src/app/core/api/parse-api.ts
  86. 58 0
      src/app/core/chat-session.service.spec.ts
  87. 58 2
      src/app/core/chat-session.service.ts
  88. 50 6
      src/app/core/chat.service.ts
  89. 161 0
      src/app/core/container.guard.spec.ts
  90. 126 0
      src/app/core/container.guard.ts
  91. 79 1
      src/app/core/live.service.spec.ts
  92. 77 4
      src/app/core/live.service.ts
  93. 6 4
      src/app/core/matrix-client.service.ts
  94. 9 0
      src/app/core/nav-menu.service.ts
  95. 87 0
      src/app/core/org.guard.spec.ts
  96. 17 2
      src/app/core/org.guard.ts
  97. 152 0
      src/app/core/plan.service.spec.ts
  98. 198 0
      src/app/core/plan.service.ts
  99. 292 0
      src/app/core/provision.service.spec.ts
  100. 493 0
      src/app/core/provision.service.ts

+ 14 - 2
.claude/dev-login.json

@@ -1,5 +1,5 @@
 {
-  "token": "r:dd15e8993d0b382d099d1faff6acd20c",
+  "token": "r:b64c5748a5be24fda063b5466851c01e",
   "me": {
     "id": "xhVRjTMwQH",
     "name": "用户9836",
@@ -9,5 +9,17 @@
     "roles": [
       "E4KpGvTEto_Admin"
     ]
-  }
+  },
+  "testAccount": {
+    "objectId": "cq0IH6Limu",
+    "username": "fmode19900000001",
+    "mobile": "19900000001",
+    "password": "TFmodeTest20261124-xQ7!",
+    "nickname": "用户0001",
+    "sessionToken": "r:e1f8f9224c520a2841fd656fd9909cf7",
+    "company": null,
+    "updatedAt": "2026-11-24T02:40:29.993Z"
+  },
+  "masterKey": "SnkK12*&sunq2#@20!",
+  "masterKeyNote": "dashboard ncloudmaster 的 masterKey(集中存放,2026-11-25 自 create-test-account.mjs 迁入;规则 9:密钥集中存放)"
 }

+ 1043 - 0
cloud/functions/fmode-provisioning.js

@@ -0,0 +1,1043 @@
+// 容器开通云函数(2026-11-25 新建)
+//
+// 目的:把「人工跑 onboard-user.mjs 脚本」变成「App 里点一下」。
+//
+// ## 三档三条路径(用户 2026-11-25 裁决)
+//
+//   试用 / 入门  → 返回**接入提示词**,用户在自己容器里执行,平台不建容器(零资源)
+//   进阶 / 企业  → 平台真实创建(DM 主容器 → R730 docker run)
+//
+// ## op 列表
+//
+//   op: start   { planCode, containerName, idempotencyKey }
+//        → 建 FmodeAgent 记录 + Matrix 身份 + DM 主容器,返回 { jobId, status }
+//   op: status  { jobId }
+//        → 读 job + **服务端实时核验**(容器记录 / Matrix / 心跳)
+//   op: retry   { jobId, idempotencyKey }
+//        → 续跑同一 job(不新建记录、不重调 provision)
+//   op: list    {}
+//        → 当前用户的任务列表
+//
+// ## 🔴 设计红线(改之前先读)
+//
+//   ① **ready 只能由服务端核验事实推导**,绝不信任主容器的自然语言回报。
+//      主容器会说「静默/超时」(2026-11-24 实测),但容器其实建成了。
+//      判据只有三项:FmodeAgent 记录存在 + Matrix joined + 心跳新鲜。
+//   ② **不伪造成功**。任何一步失败就如实返回 failed + 失败阶段。
+//   ③ 本期是**内部测试**,不做付费闸、不做白名单(用户裁决)。
+//      但在 DM 主容器前保留 TODO 位置,上线前补。
+//
+// ## 平台约定(与 fmodeagent-users 一致,实测)
+//
+//   · 入口 async function handler(request, response);入参在全局 params
+//   · 身份:优先 request.user,否则按 sessionToken 查 _Session
+//   · 🔴 输出必须 response.status(200).json(...) 显式写出;直接 return 对象平台不回包
+//   · 无 require / 无 node 模块,只能用全局 fetch / Parse / AbortController
+//
+// 表:
+//   FmodeProvisionJob  user Pointer<_User> / agentId / planCode / status / stage /
+//                       matrixInfo / error / attempts / idempotencyKey / isDeleted
+//   FmodeAgent         objectId / name / user Pointer<_User> / status / heartbeatAt
+//   FmodeMatrixBinding userPointer / agentId / roomId / status
+
+var CLASS_JOB = 'FmodeProvisionJob';
+var FN_STATUS = 'xlosi3m46q'; // 容器记录查询
+var FN_PROVISION = 'RP5Ht55NeX'; // Matrix 身份
+var FUNCTIONS_URL = 'https://server.fmode.cn/api/functions';
+var MASTER_MXID = '@bnqaoxqhe8:fmode.cn'; // 主容器 agent-node
+
+/*
+ * 主容器通信身份(2026-11-26 用户裁决)
+ *
+ * 🔴 **不能直接以主容器身份建房间**:
+ *    主容器是 Hermes bot,只响应「别人发给它的消息」,不响应自己发的。
+ *    自建房间里它是 creator 但 Hermes 不触发;且该 homeserver 上 creator
+ *    改 power_levels 会返回 `Event is not authorized`(实测)。
+ *    因此必须**用真实用户身份建房间并邀请它** —— 它 join 后才会响应。
+ *
+ * 用测试用户的 Matrix 凭据(由 RP5Ht55NeX 签发,长期有效)。
+ * TODO(上线前):改成「用发起该 job 的用户的凭据」,届时每个用户都用自己身份。
+ */
+var PLATFORM_MXID = '@cq0ih6limu:fmode.cn';
+var PLATFORM_ACCESS_TOKEN = 'pxdhbhg80TNAk8EkfnDZyx3k';
+
+/** 各档位容器配额(PRD FR-29) */
+var QUOTA = { trial: 1, starter: 1, advanced: 3, enterprise: 5 };
+
+/** 判定「心跳新鲜」的阈值:5 分钟 */
+var HEARTBEAT_FRESH_SEC = 300;
+/** 任务超时(毫秒):15 分钟无进展视为失败(技能上限 12 分钟 + 3 分钟缓冲),但保留资源可重试 */
+var JOB_TIMEOUT_MS = 15 * 60 * 1000;
+
+// ---------- 响应helpers ----------
+
+function _ok(data) {
+  response.status(200).json(Object.assign({ code: 200 }, data || {}));
+  return true;
+}
+
+function _fail(code, mess, extra) {
+  response.status(200).json(Object.assign({ code: code, mess: mess }, extra || {}));
+  return false;
+}
+
+function _str(v, max) {
+  var s = v == null ? '' : String(v);
+  return max && s.length > max ? s.slice(0, max) : s;
+}
+
+function _sessionToken() {
+  var h = request && request.headers ? request.headers : {};
+  if (h['x-parse-session-token']) return h['x-parse-session-token'];
+  if (params && params.sessionToken) return params.sessionToken;
+  if (request && request.body && request.body.token) return request.body.token;
+  return null;
+}
+
+/** 取当前登录用户(服务端权威) */
+async function _getUser() {
+  var t = _sessionToken();
+  if (!t) return null;
+  if (request.user && request.user.id && !(params && params.sessionToken)) {
+    // 代理对象只有 id,必须重查拿完整字段
+    var U = Parse.Object.extend('_User');
+    return await new Parse.Query(U).get(request.user.id, { useMasterKey: true });
+  }
+  var q = new Parse.Query(Parse.Session);
+  q.equalTo('sessionToken', t);
+  var s = await q.first({ useMasterKey: true });
+  return s ? s.get('user') : null;
+}
+
+/** 调其它云函数(内部用,带重试) */
+async function _callFn(id, token, body) {
+  var lastErr = null;
+  for (var i = 0; i < 4; i++) {
+    try {
+      var res = await fetch(FUNCTIONS_URL, {
+        method: 'POST',
+        redirect: 'manual',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify({ id: id, token: token, params: body }),
+      });
+      // 入口层(HAProxy)坏后端会返回 403/301/503,重试
+      if (res.ok) return await res.json();
+      lastErr = new Error('HTTP ' + res.status);
+      if ([301, 403, 502, 503, 504].indexOf(res.status) < 0) throw lastErr;
+    } catch (e) {
+      lastErr = e;
+    }
+    await new Promise(function (r) {
+      setTimeout(r, 400 * (i + 1));
+    });
+  }
+  throw lastErr || new Error('云函数调用失败');
+}
+
+/**
+ * 计算 agent 的 Matrix 密码(与 `fmodeagent-matrix-provision` 的派生规则一致)
+ *
+ * 规则:`sha256("fmode-agent-mx:" + objectId)` 前 24 位(小写 hex)。
+ * 见 `cloud/functions/fmodeagent-matrix-provision.js:486`。
+ *
+ * 🔴 为什么要在本函数里重算:`RP5Ht55NeX` 只返回 accessToken,不返回密码。
+ *    但用户自己的容器需要**可长期使用的密码**(accessToken 会随 device 变)。
+ */
+async function _agentMxPassword(objectId) {
+  try {
+    var enc = new TextEncoder().encode('fmode-agent-mx:' + String(objectId));
+    var buf = await crypto.subtle.digest('SHA-256', enc);
+    var bytes = new Uint8Array(buf);
+    var hex = '';
+    for (var i = 0; i < bytes.length; i++) {
+      hex += ('0' + bytes[i].toString(16)).slice(-2);
+    }
+    return hex.slice(0, 24);
+  } catch (e) {
+    return null;
+  }
+}
+
+// ---------- 服务端核验(核心) ----------
+
+/**
+ * 核验一个容器是否真的可用。
+ *
+ * 🔴 三项全部为真才算 ready:
+ *   ① FmodeAgent 记录存在
+ *   ② Matrix 已 joined 房间
+ *   ③ 心跳新鲜(≤ 5 分钟)
+ *
+ * 任一项拿不到证据都返回 false —— **宁可判未就绪,不伪造成功**。
+ */
+async function _verifyAgent(agentId, token, expectedRoomId) {
+  var result = { record: false, matrix: false, heartbeat: false, detail: {} };
+
+  /*
+   * 期望的 agentId 字段值(= docker 容器名 = `agent-node-app-<objectId 小写>`)。
+   * 心跳插件上报的就是这个值,所以核验必须按它匹配。
+   */
+  var expectAgentId = 'agent-node-app-' + String(agentId).toLowerCase();
+
+  // ① 容器记录
+  try {
+    // 🔴 2026-11-25 实测:xlosi3m46q 的 `agentId` 精确查询返回 404,
+    //    但全量列表里能查到(服务端该分支有问题)。
+    //    因此这里拉列表再本地过滤,不能依赖 agentId 参数。
+    var r = await _callFn(FN_STATUS, token, { op: 'query', scope: 'mine', limit: 200 });
+    var list = (r && r.agents) || [];
+    var agent = null;
+    for (var i = 0; i < list.length; i++) {
+      var cur = list[i];
+      /*
+       * 🔴 优先按 **agentId 字段** 匹配(2026-11-27 修)
+       *
+       * 一条容器可能对应多条 FmodeAgent 记录:
+       *   · 本函数建的(agentId 字段已正确设置)
+       *   · 插件历史上自建的(agentId = 容器名)
+       * 按 objectId 匹配会挑到空壳那条,永远判 offline。
+       */
+      if (String(cur.agentId || '') === expectAgentId) {
+        agent = cur;
+        break;
+      }
+    }
+    // 兼容:老记录没有 agentId 字段时回退到 objectId 匹配
+    if (!agent) {
+      for (var k = 0; k < list.length; k++) {
+        if (String(list[k].objectId || list[k].id) === String(agentId)) {
+          agent = list[k];
+          break;
+        }
+      }
+    }
+    if (agent) {
+      result.record = true;
+      result.detail.status = agent.status;
+      result.detail.heartbeatAgeSec = agent.heartbeatAgeSec;
+      /*
+       * ③ 心跳新鲜 **且容器未处于故障态**
+       *
+       * 🔴 2026-11-25 曾把 `offline` 也算作不可用,理由是
+       *    「某容器 status:'offline' 但仍上报心跳(53s),不能判 ready」。
+       *
+       * 🔴 2026-11-27 实测推翻了那个结论:
+       *    新容器**首次上报就是 `offline`**(进程刚起,还没跑过任何一轮),
+       *    之后要等一轮对话才会变 idle/running。
+       *    结果是:容器明明在 R730 上 Up 着、心跳新鲜,却永远判不 ready,
+       *    前端永远转圈 → 用户看到「一直显示正在创建容器」。
+       *
+       *    实测证据:`agent-node-app-kvt61ga9gv` / `buqiyb0b3c`
+       *    在 R730 上 `Up 10 minutes`,心跳 578s 前,但 status 一直是 offline。
+       *
+       * 现在的口径:
+       *   · `error` / `stopped` → 明确故障,不可用
+       *   · `offline` + **心跳新鲜** → 进程活着,只是还没进入工作状态,**算可用**
+       *   · `offline` + 心跳过期 → 真的掉线,不可用(下面心跳判定会自然排除)
+       */
+      var age = agent.heartbeatAgeSec;
+      var healthyStatus = agent.status !== 'error' && agent.status !== 'stopped';
+      result.heartbeat =
+        healthyStatus && typeof age === 'number' && age >= -60 && age <= HEARTBEAT_FRESH_SEC;
+      if (!healthyStatus) {
+        result.detail.statusError = '容器状态为 ' + agent.status + ',不可用';
+      }
+      if (agent.status === 'offline') {
+        result.detail.note = '容器首次上报,进程已启动但尚未进入工作状态';
+      }
+    } else {
+      result.detail.recordError = '容器记录不存在(列表中未找到 ' + agentId + ')';
+    }
+  } catch (e) {
+    result.detail.recordError = _str(e.message, 200);
+  }
+
+  // ② Matrix joined(用 provision 拿到的 accessToken 查)
+  try {
+    var prov = await _callFn(FN_PROVISION, token, { validate: 1, agentId: agentId });
+    if (prov && prov.accessToken && prov.roomId) {
+      var mxRes = await fetch(
+        'https://matrix.fmode.cn/_matrix/client/v3/joined_rooms',
+        { headers: { Authorization: 'Bearer ' + prov.accessToken }, redirect: 'manual' },
+      );
+      if (mxRes.ok) {
+        var mx = await mxRes.json();
+        var rooms = mx.joined_rooms || [];
+        result.detail.roomId = prov.roomId;
+        result.matrix = rooms.indexOf(prov.roomId) >= 0;
+      } else {
+        result.detail.matrixError = 'Matrix HTTP ' + mxRes.status;
+      }
+    } else {
+      result.detail.matrixError = '未取得 Matrix 绑定';
+    }
+  } catch (e) {
+    result.detail.matrixError = _str(e.message, 200);
+  }
+
+  /*
+   * ④ 主动唤醒(2026-11-27 新增)
+   *
+   * 容器首次上报是 `offline`,要跑过一轮对话才会变 idle/running。
+   * 但用户不会主动跟一个「还没就绪」的容器说话 —— 于是它永远停在 offline。
+   *
+   * 这里在发现「心跳新鲜但状态还是 offline」时,主动往目标房间发一条消息,
+   * 触发 Hermes 的 pre_llm_call 插件上报真实状态。
+   *
+   * 🔴 失败不抛错:唤醒是「锦上添花」,核心判定已在上面的 heartbeat 里放宽了。
+   */
+  if (result.record && result.heartbeat && result.detail.status === 'offline' && result.detail.roomId) {
+    try {
+      await _pokeContainer(agentId, token, result.detail.roomId);
+      result.detail.poked = true;
+    } catch (e) {
+      result.detail.pokeError = _str(e.message, 120);
+    }
+  }
+
+  return result;
+}
+
+/**
+ * 往新容器所在的房间发一条消息,催它上报状态。
+ *
+ * 发的是最普通的问候 —— 目的不是让 AI 回答什么,而是让 Hermes 走一轮
+ * `pre_llm_call` → 心跳插件把 status 从 offline 更新成 idle。
+ */
+async function _pokeContainer(agentId, token, roomId) {
+  var prov = await _callFn(FN_PROVISION, token, { validate: 1, agentId: agentId });
+  if (!prov || !prov.accessToken) return;
+
+  var agentMxId = 'agent-node-app-' + String(agentId).toLowerCase();
+  var txn = 'poke' + Date.now();
+  var url =
+    'https://matrix.fmode.cn/_matrix/client/v3/rooms/' +
+    encodeURIComponent(roomId) +
+    '/send/m.room.message/' +
+    txn;
+
+  var res = await fetch(url, {
+    method: 'PUT',
+    headers: {
+      Authorization: 'Bearer ' + prov.accessToken,
+      'Content-Type': 'application/json',
+    },
+    body: JSON.stringify({
+      msgtype: 'm.text',
+      body: '容器上线自检,请回复「在线」',
+      'm.mentions': { user_ids: ['@' + String(agentId).toLowerCase() + ':fmode.cn'] },
+    }),
+  });
+  if (!res.ok) {
+    var t = await res.text();
+    throw new Error('唤醒失败 HTTP ' + res.status + ':' + t.slice(0, 120));
+  }
+  void agentMxId;
+}
+
+// ---------- 主容器工单(技能化 + 一任务一房间,2026-11-26) ----------
+
+/**
+ * 生成工单。
+ *
+ * 🔴 为什么不用旧的 200 行长指令:
+ *    实测主容器执行长任务会「失忆」(跑 20 分钟还卡在 media-patch 细节,不产出结论)。
+ *    新版 = 短工单(JSON 参数)+ 技能文件承载步骤 + 强制机器可读结果。
+ *    配合「一任务一房间」保证干净上下文。
+ */
+function _buildInstruction(user, agent, planCode, containerName, jobId, matrixInfo) {
+  var objectId = agent.get('objectId') || agent.id;
+  var agentMxId = '@' + String(objectId).toLowerCase() + ':fmode.cn';
+  var masterMxid = '@' + String(user.id).toLowerCase() + ':fmode.cn';
+  /*
+   * 容器名:用 objectId 小写做稳定后缀。
+   * 🔴 必须 = docker 容器名 = hostname,且与 agentMxId 的 localpart 一致,
+   *    否则 Matrix 身份和容器对不上(2026-11-24 踩过)。
+   */
+  var agentId = 'agent-node-app-' + String(objectId).toLowerCase();
+
+  /*
+   * 🔴 roomId 必须来自 RP5Ht55NeX 的返回值(matrixInfo.roomId),
+   *    不能读 agent.get('roomId') —— FmodeAgent 表**没有** roomId 字段(2026-11-26 实测)。
+   *    早期版本这里传了 null,主容器拿不到目标房间,只能在漫游里瞎找,
+   *    最终卡死在「注册并登录 agent 账号」这一步。
+   */
+  var targetRoomId = (matrixInfo && matrixInfo.roomId) || null;
+
+  var ticket = {
+    jobId: jobId,
+    agentId: agentId,
+    displayName: containerName,
+    objectId: objectId,
+    ownerUserMxId: masterMxid,
+    /* 开通者的 Fmode session token —— 写进新容器 .env 的 FMODE_SESSION_TOKEN */
+    ownerSessionToken: _sessionToken(),
+    agentMxId: agentMxId,
+    roomId: targetRoomId,
+    allowedUsers: masterMxid,
+    /*
+     * 🔴 模板目录(2026-11-26 用户裁决)
+     *
+     * 建容器**不需要源容器**,需要一个**模板数据目录**在 R730 上。
+     * 已确认可用的模板:`agent-node-app-test-0001`(11 插件 / 有 media-patch / gateway 在跑)。
+     *
+     * 架构(这是之前成功建容器时的真实配置):
+     *   IMAGE  = fmode/agent-node:0.21.3
+     *   ENTRY  = /opt/data/.fmode-media-patch/entry.sh
+     *   MOUNTS = /opt/fmode-containers/<新容器名>/data → /opt/data
+     *
+     * 🔴 media-patch 来自**挂载的数据目录**,不是从别的容器复制。
+     *
+     * ## 必须替换的用户数据(模板里是旧用户的值,不能带进新容器)
+     *
+     *   .env 中:AGENT_ID / MATRIX_USER_ID / MATRIX_PASSWORD / MATRIX_HOME_ROOM /
+     *             MATRIX_ALLOWED_USERS / FMODE_SESSION_TOKEN
+     *   SOUL.md:人格名 → 新容器显示名
+     *   sessions/:**必须清空**(否则新容器带着旧用户的会话历史)
+     */
+    templateDir: '/opt/fmode-templates/default',
+    image: 'fmode/agent-node:0.21.3',
+    entrypoint: '/opt/data/.fmode-media-patch/entry.sh',
+    targetDir: '/opt/fmode-containers/' + agentId + '/data',
+    matrixHomeserver: 'https://matrix.fmode.cn',
+  };
+
+  return [
+    '【工单】' + jobId + ' · 建容器 ' + agentId,
+    '',
+    '请严格执行 `container-provision-job` 技能,按其中的输入/输出契约完成。',
+    '同时参考 `container-provision-from-source` 作为操作手册。',
+    '',
+    '参数:',
+    '```json',
+    JSON.stringify(ticket, null, 2),
+    '```',
+    '',
+    '🔴 纪律(技能里有详述,这里强调三条):',
+    '  1. **只做工单要求的事** —— 遇到非阻断问题记下来继续走,不要停下来修',
+    '  2. **进度写数据库** —— 每进入/完成一个阶段,POST 一条 FmodeProvisionStep,',
+    '     这是调用方唯一能看到你的方式;聊天里只回一行 stage/status',
+    '  3. **不要宣布成败** —— 容器是否可用由平台按服务端事实判定,不看你的文字',
+    '',
+    '🔴 `roomId` 用上面给的这个,不要自己去找。',
+    '🔴 **整条流程写成一个脚本,一次 SSH 跑完** —— 不要每步开一次会话(会被 sshd 限流)。',
+    '🔴 总时限 12 分钟。到点就停下,写 status:"failed",不要硬撑。',
+    '',
+    '套餐:' + planCode + '。模板目录 ' + ticket.templateDir + ' 全程只读,不要改动。',
+  ].join('\n');
+}
+
+/**
+ * 为什么每个任务要新建一个房间(2026-11-26)
+ *
+ * Hermes 的 session_key = `agent:main:matrix:dm:<roomId>`,
+ * 且 `session_reset.mode: none`(永不自动重置)。
+ * 也就是说:**同一个房间 = 永远同一个 session = 上下文无限累积**。
+ *
+ * 实测(2026-11-25):在同一个房间连续发多次建容器指令后,
+ * 主容器会带着前几次的历史跑 20 分钟,最后不产出结论("静默/超时")。
+ *
+ * 换新 roomId 是 Hermes 下唯一能干净"开新回合"的方式
+ * (`/new` 命令不存在;改 session_reset 是全局配置,影响所有会话)。
+ */
+async function _createFreshRoom(jobId) {
+  var res = await fetch('https://matrix.fmode.cn/_matrix/client/v3/createRoom', {
+    method: 'POST',
+    headers: {
+      Authorization: 'Bearer ' + PLATFORM_ACCESS_TOKEN,
+      'Content-Type': 'application/json',
+    },
+    body: JSON.stringify({
+      name: 'provision-' + jobId,
+      topic: '容器开通工单 ' + jobId,
+      invite: [MASTER_MXID],
+      is_direct: true,
+      preset: 'private_chat',
+    }),
+  });
+  if (!res.ok) {
+    var t = await res.text();
+    throw new Error('创建任务房间失败 HTTP ' + res.status + ':' + t.slice(0, 200));
+  }
+  var j = await res.json();
+  if (!j.room_id) throw new Error('创建任务房间未返回 room_id');
+  return j.room_id;
+}
+
+/**
+ * 等主容器接受邀请并进房。
+ *
+ * 🔴 新房间里的第一条消息必须在主容器进房之后发,
+ *    否则它不会收到(Matrix 不补发历史给未加入者)。
+ */
+async function _waitMasterJoin(roomId) {
+  var url =
+    'https://matrix.fmode.cn/_matrix/client/v3/rooms/' +
+    encodeURIComponent(roomId) +
+    '/joined_members';
+  for (var i = 0; i < 12; i++) {
+    try {
+      var res = await fetch(url, { headers: { Authorization: 'Bearer ' + PLATFORM_ACCESS_TOKEN } });
+      if (res.ok) {
+        var j = await res.json();
+        if (j.joined && j.joined[MASTER_MXID]) return true;
+      }
+    } catch (e) {
+      /* 单次失败忽略,继续等 */
+    }
+    await new Promise(function (r) {
+      setTimeout(r, 3000);
+    });
+  }
+  return false;
+}
+
+/** 在指定房间发消息(统一用平台(测试用户)身份,见 PLATFORM_ACCESS_TOKEN 注释) */
+async function _sendToRoom(roomId, text) {
+  var txn = 'fmode' + Date.now() + Math.floor(Math.random() * 900 + 100);
+  var url =
+    'https://matrix.fmode.cn/_matrix/client/v3/rooms/' +
+    encodeURIComponent(roomId) +
+    '/send/m.room.message/' +
+    txn;
+  var res = await fetch(url, {
+    method: 'PUT',
+    headers: {
+      Authorization: 'Bearer ' + PLATFORM_ACCESS_TOKEN,
+      'Content-Type': 'application/json',
+    },
+    body: JSON.stringify({
+      msgtype: 'm.text',
+      body: text,
+      'm.mentions': { user_ids: [MASTER_MXID] },
+    }),
+  });
+  if (!res.ok) {
+    var t = await res.text();
+    throw new Error('发送工单失败 HTTP ' + res.status + ':' + t.slice(0, 200));
+  }
+  var j = await res.json();
+  return j.event_id;
+}
+
+/**
+ * 读主容器写进 `FmodeProvisionStep` 的进度记录(2026-11-26 用户裁决方案)。
+ *
+ * 🔴 **为什么改成写库而不是读聊天**:
+ *    Agent 在长任务里只会回工具调用回显(`💻 terminal \`\`\` cd /opt/... \`\`\``),
+ *    让它"在聊天里组织结构化格式"实测 30 分钟一次都没成功。
+ *    但让它"发一次 curl 写库"是单次工具调用,成功率高得多。
+ *
+ * 🔴 **只用于诊断,不参与 ready 判定**。
+ *    红线不变:ready 只由服务端三项事实推导(记录 + Matrix + 心跳)。
+ */
+async function _readSteps(jobId, attempt) {
+  if (!jobId) return [];
+  try {
+    var where = { jobId: jobId };
+    if (typeof attempt === 'number') where.attempt = attempt;
+    var url =
+      'https://server.fmode.cn/parse/classes/FmodeProvisionStep?where=' +
+      encodeURIComponent(JSON.stringify(where)) +
+      '&order=createdAt&limit=100';
+    var res = await fetch(url, {
+      headers: {
+        'X-Parse-Application-Id': 'ncloudmaster',
+        'Content-Type': 'application/json',
+      },
+    });
+    if (!res.ok) return [];
+    var j = await res.json();
+    return (j.results || []).map(function (r) {
+      return {
+        stage: r.stage || null,
+        status: r.status || null,
+        step: _str(r.step, 200) || null,
+        evidence: _str(r.evidence, 500) || null,
+        reasonCode: r.reasonCode || null,
+        elapsedSec: typeof r.elapsedSec === 'number' ? r.elapsedSec : null,
+        agentId: r.agentId || null,
+        at: r.createdAt || null,
+      };
+    });
+  } catch (e) {
+    return [];
+  }
+}
+
+/** 从 step 列表推导当前状态:最后一条 running 优先,否则最后一条 */
+function _currentStep(steps) {
+  if (!steps || !steps.length) return null;
+  for (var i = steps.length - 1; i >= 0; i--) {
+    if (steps[i].status === 'running') return steps[i];
+  }
+  return steps[steps.length - 1];
+}
+
+/** 是否有明确的失败记录 */
+function _failedStep(steps) {
+  if (!steps) return null;
+  for (var i = steps.length - 1; i >= 0; i--) {
+    if (steps[i].status === 'failed') return steps[i];
+  }
+  return null;
+}
+
+// ---------- 主流程 ----------
+
+async function _start(user, p) {
+  var planCode = _str(p.planCode, 20);
+  var containerName = _str(p.containerName, 40) || '我的容器';
+  var idemKey = _str(p.idempotencyKey, 80);
+
+  if (!planCode || !QUOTA[planCode]) return _fail(400, 'planCode 无效');
+
+  /*
+   * 🔴 试用 / 入门:**不建容器**,但生成**真实带参数**的接入提示词(2026-11-27 重做)
+   *
+   * 原来这里返回的是写死的固定文案,用户复制走也没有自己的参数,
+   * 等于不可用。现在:
+   *   ① 建 FmodeAgent 记录(用户容器将来上报时按 agentId 匹配)
+   *   ② 调 RP5Ht55NeX 建 Matrix 身份与房间
+   *   ③ 生成一份**可直接粘进用户自己容器执行**的接入提示词
+   *
+   * 不碰 R730、不建 docker 容器 —— 零资源占用。
+   */
+  if (planCode === 'trial' || planCode === 'starter') {
+    var token0 = _sessionToken();
+    var ownerMx = '@' + String(user.id).toLowerCase() + ':fmode.cn';
+    var oa = null;
+
+    try {
+      // ① 建/复用 FmodeAgent 记录
+      var OAClass = Parse.Object.extend('FmodeAgent');
+      var oq = new Parse.Query(OAClass);
+      oq.equalTo('user', user);
+      oq.equalTo('name', containerName);
+      oq.notEqualTo('isDeleted', true);
+      oa = await oq.first({ useMasterKey: true });
+      if (!oa) {
+        oa = new OAClass();
+        oa.set('name', containerName);
+        oa.set('user', user);
+        oa.set('status', 'offline');
+        var oc = user.get('company');
+        if (oc) oa.set('company', oc);
+        var oacl = new Parse.ACL();
+        oacl.setReadAccess(user.id, true);
+        oacl.setWriteAccess(user.id, true);
+        oa.setACL(oacl);
+        await oa.save(null, { useMasterKey: true });
+        // agentId 必须 save 之后再写(新建时 agent.id 为 undefined)
+        oa.set('agentId', 'agent-node-app-' + String(oa.id).toLowerCase());
+        await oa.save(null, { useMasterKey: true });
+      }
+
+      // ② 建 Matrix 身份与房间(幂等,已绑定会直接返回)
+      var prov0 = await _callFn(FN_PROVISION, token0, { agentId: oa.id });
+      if (!prov0 || !prov0.agentMxId) {
+        throw new Error('Matrix 身份创建失败');
+      }
+
+      // ③ 生成真实提示词
+      var derivedPass = await _agentMxPassword(oa.id);
+      var mxPass = derivedPass || '<密码派生失败,请用 App 内凭据>';
+      var instruction = [
+        '【Fmode 接入提示词】' + containerName,
+        '',
+        '把下面整段复制到**你自己的容器**里执行,即可接入 Fmode App。',
+        '(平台不会为你创建容器,这一步在你自己的环境里完成)',
+        '',
+        '```',
+        '# ===== Fmode 接入参数(已为你的账号生成,请勿外传)=====',
+        'MATRIX_HOMESERVER=' + (prov0.homeserver || 'https://matrix.fmode.cn'),
+        'MATRIX_USER_ID=' + prov0.agentMxId,
+        'MATRIX_PASSWORD=' + mxPass,
+        'MATRIX_HOME_ROOM=' + (prov0.roomId || ''),
+        'MATRIX_REACTIONS=true',
+        'MATRIX_REQUIRE_MENTION=false',
+        'MATRIX_ALLOWED_USERS=' + ownerMx,
+        'MATRIX_MAX_MEDIA_BYTES=838860800',
+        'MATRIX_E2EE_MODE=off',
+        'AGENT_ID=agent-node-app-' + String(oa.id).toLowerCase(),
+        'AGENT_FUNCTION_ID=xlosi3m46q',
+        'FMODE_SESSION_TOKEN=' + token0,
+        '# ===== 以上写入你容器的 /opt/data/.env =====',
+        '',
+        '# 并把同样的变量用 -e 传给你容器的 docker run(心跳上报需要):',
+        '# docker run ... -e FMODE_SESSION_TOKEN=... -e AGENT_ID=... gateway run',
+        '```',
+        '',
+        '执行完在你的容器里发一条消息给该房间,平台会自动识别为已接入。',
+      ].join('\n');
+
+      return _ok({
+        mode: 'onboarding',
+        message: '该档位使用你自己的容器,请复制下面的接入提示词到容器内执行。',
+        instruction: instruction,
+        agentId: oa.id,
+        matrixInfo: {
+          agentMxId: prov0.agentMxId,
+          roomId: prov0.roomId,
+          homeserver: prov0.homeserver,
+        },
+      });
+    } catch (e) {
+      return _fail(500, '接入提示词生成失败:' + _str(e.message, 200), {
+        reasonCode: 'ONBOARDING_FAILED',
+        retryable: true,
+      });
+    }
+  }
+
+  // ---- 进阶 / 企业:平台真实创建 ----
+
+  // 幂等:同 idempotencyKey 直接返回已有 job
+  if (idemKey) {
+    var q0 = new Parse.Query(Parse.Object.extend(CLASS_JOB));
+    q0.equalTo('user', user);
+    q0.equalTo('idempotencyKey', idemKey);
+    var exist = await q0.first({ useMasterKey: true });
+    if (exist) return _ok({ mode: 'provision', jobId: exist.id, status: exist.get('status') });
+  }
+
+  // 配额:存量 + 在途
+  var JobClass = Parse.Object.extend(CLASS_JOB);
+  var qCount = new Parse.Query(JobClass);
+  qCount.equalTo('user', user);
+  qCount.notEqualTo('status', 'failed');
+  qCount.notEqualTo('isDeleted', true);
+  var activeCount = await qCount.count({ useMasterKey: true });
+  if (activeCount >= QUOTA[planCode]) {
+    return _fail(409, '名额已满(' + activeCount + '/' + QUOTA[planCode] + ')', {
+      reasonCode: 'QUOTA_EXCEEDED',
+    });
+  }
+
+  // TODO(上线前):此处加付费状态校验
+
+  var job = new JobClass();
+  job.set('user', user);
+  job.set('planCode', planCode);
+  job.set('status', 'provisioning');
+  job.set('stage', 'entitlement');
+  job.set('attempts', 1);
+  job.set('idempotencyKey', idemKey);
+  job.set('isDeleted', false);
+  await job.save(null, { useMasterKey: true });
+
+  var token = _sessionToken();
+  var agentId = null;
+
+  try {
+    // ① 建 FmodeAgent 记录
+    var AgentClass = Parse.Object.extend('FmodeAgent');
+    var agent = new AgentClass();
+    agent.set('name', containerName);
+    /*
+     * 🔴 `agentId` 必须 = docker 容器名(2026-11-27 修)
+     *
+     * 心跳上报插件读的是 `/run/s6/container_environment/AGENT_ID`,
+     * 值是**容器名**(如 `agent-node-app-5iskvxwtdx`),然后调
+     * `xlosi3m46q {op:'update', agentId:<容器名>}` 按 **agentId 字段**匹配。
+     *
+     * 之前这里**没设 agentId**,于是:
+     *   插件匹配不到 → 云函数**自动新建一条记录** → 心跳写进新记录
+     *   而本云函数按 objectId 核验 → 查到的是永远 offline 的空壳记录
+     *   → 表现为「容器明明在跑,却永远 offline」
+     *
+     * 实测证据:`agent-node-app-5iskvxwtdx` 对应两条记录——
+     *   `5ISkvXWtdX`(本函数建的,空壳)与 `CgAP5CZ4xb`(插件自建,心跳正常)。
+     */
+    agent.set('user', user);
+    agent.set('status', 'offline');
+    var userCompany = user.get('company');
+    if (userCompany) agent.set('company', userCompany);
+    // ACL:本人 + 超管
+    var acl = new Parse.ACL();
+    acl.setReadAccess(user.id, true);
+    acl.setWriteAccess(user.id, true);
+    agent.setACL(acl);
+    await agent.save(null, { useMasterKey: true });
+    agentId = agent.id;
+    /*
+     * 🔴 agentId 必须**保存后**再写:新建对象时 `agent.id` 是 undefined,
+     *    先读取会得到 `agent-node-app-undefined`(2026-11-27 实测踩到)。
+     *    = docker 容器名 = 心跳上报插件读取的 AGENT_ID。
+     */
+    var mxAgentId = 'agent-node-app-' + String(agentId).toLowerCase();
+    agent.set('agentId', mxAgentId);
+    await agent.save(null, { useMasterKey: true });
+    job.set('agentId', agentId);
+    job.set('stage', 'matrix');
+    await job.save(null, { useMasterKey: true });
+
+    // ② 建 Matrix 身份
+    var prov = await _callFn(FN_PROVISION, token, { agentId: agentId });
+    if (!prov || !prov.accessToken) {
+      throw new Error('Matrix 身份创建失败:' + JSON.stringify(prov).slice(0, 200));
+    }
+    job.set('matrixInfo', {
+      agentMxId: prov.agentMxId,
+      userMxId: prov.userMxId,
+      roomId: prov.roomId,
+      homeserver: prov.homeserver,
+    });
+    job.set('stage', 'container');
+    await job.save(null, { useMasterKey: true });
+
+    // ③ 新房间 → 等主容器进房 → 发工单(一任务一房间,2026-11-26)
+    // TODO(上线前):此处加白名单校验
+    var roomId = await _createFreshRoom(job.id);
+    var joined = await _waitMasterJoin(roomId);
+    if (!joined) throw new Error('主容器未进房,工单无法送达');
+    job.set('jobRoomId', roomId);
+    await job.save(null, { useMasterKey: true });
+
+    var instruction = _buildInstruction(user, agent, planCode, containerName, job.id, job.get('matrixInfo'));
+    await _sendToRoom(roomId, instruction);
+
+    job.set('stage', 'verifying');
+    await job.save(null, { useMasterKey: true });
+
+    return _ok({ mode: 'provision', jobId: job.id, agentId: agentId, status: 'provisioning' });
+  } catch (e) {
+    var kind = _classifyError(e.message, job.get('stage'));
+    await _failJob(job, kind, e.message, job.get('stage'));
+    return _fail(500, kind.userMessage, {
+      jobId: job.id,
+      agentId: agentId,
+      reasonCode: kind.reasonCode,
+      retryable: kind.retryable,
+    });
+  }
+}
+
+/**
+ * 失败原因分类(2026-11-25 加固)
+ *
+ * 🔴 为什么需要:原来只回一句 `e.message`,用户看到的是
+ *    「HTTP 404」或「timeout」这种内部术语,既看不懂也不知道能不能重试。
+ *
+ * 现在每个失败都有:
+ *   · reasonCode  —— 稳定枚举,前端可按 code 做不同引导
+ *   · retryable   —— 是否值得重试(通道抖动 vs 配额满,天差地别)
+ *   · userMessage —— 用户看得懂的话,不含内部组件名
+ */
+var FAIL = {
+  CONNECT: {
+    reasonCode: 'R730_UNREACHABLE',
+    retryable: true,
+    userMessage: '平台服务器连接不稳定,已自动重试但暂时未成功。稍后再试通常就能好。',
+  },
+  STAGE: {
+    reasonCode: 'CONTAINER_STAGE_FAILED',
+    retryable: true,
+    userMessage: '容器创建过程中出错,已创建的部分会保留。可以直接重试,不会重复创建。',
+  },
+  TIMEOUT: {
+    reasonCode: 'PROVISION_TIMEOUT',
+    retryable: true,
+    userMessage: '开通耗时超出预期。容器可能仍在后台创建,建议稍后查看进度或重试。',
+  },
+  NOT_READY: {
+    reasonCode: 'CONTAINER_NOT_READY',
+    retryable: true,
+    userMessage: '容器还没有完全就绪。若长时间如此,可以重试,已完成的步骤会复用。',
+  },
+  QUOTA: {
+    reasonCode: 'QUOTA_EXCEEDED',
+    retryable: false,
+    userMessage: '容器名额已用完。可以删除不用的容器,或升级套餐增加名额。',
+  },
+  MATRIX: {
+    reasonCode: 'MATRIX_SETUP_FAILED',
+    retryable: true,
+    userMessage: '通信身份创建失败。重试即可,平台会自动复用已创建的部分。',
+  },
+};
+
+/** 按错误内容推断失败类型 */
+function _classifyError(msg, stage) {
+  var m = String(msg || '').toLowerCase();
+  if (m.indexOf('connect_failed') >= 0 || m.indexOf('ssh') >= 0 || m.indexOf('banner') >= 0) {
+    return FAIL.CONNECT;
+  }
+  if (stage === 'matrix' || m.indexOf('matrix') >= 0) return FAIL.MATRIX;
+  if (m.indexOf('超时') >= 0 || m.indexOf('timeout') >= 0) return FAIL.TIMEOUT;
+  return FAIL.STAGE;
+}
+
+/** 写失败结果(统一格式) */
+async function _failJob(job, kind, rawMsg, stage) {
+  var f = kind || FAIL.STAGE;
+  job.set('status', 'failed');
+  job.set('failedStage', stage || job.get('stage') || 'unknown');
+  job.set('error', f.userMessage);
+  job.set('reasonCode', f.reasonCode);
+  job.set('retryable', f.retryable);
+  // 原始错误只放技术字段,不给用户看
+  job.set('errorDetail', _str(rawMsg, 800));
+  await job.save(null, { useMasterKey: true }).catch(function () {});
+}
+async function _status(user, p) {
+  var jobId = _str(p.jobId, 40);
+  if (!jobId) return _fail(400, '缺少 jobId');
+
+  var JobClass = Parse.Object.extend(CLASS_JOB);
+  var job;
+  try {
+    job = await new Parse.Query(JobClass).get(jobId, { useMasterKey: true });
+  } catch (e) {
+    return _fail(404, '任务不存在');
+  }
+  if (String(job.get('user').id) !== String(user.id)) return _fail(403, '无权查看该任务');
+
+  var status = job.get('status');
+  var agentId = job.get('agentId');
+  var detail = null;
+  var steps = [];
+
+  // 未终结的任务做实时核验
+  if (status !== 'ready' && status !== 'failed' && agentId) {
+    var token = _sessionToken();
+    detail = await _verifyAgent(agentId, token, job.get('matrixInfo') && job.get('matrixInfo').roomId);
+
+    /*
+     * 🔴 进度来自 Agent 写进 FmodeProvisionStep 的记录(2026-11-26)。
+     *    成败仍只认上面的三项核验 —— 这里只解决「看得到停在哪」。
+     */
+    steps = await _readSteps(job.id, job.get('attempts') || 1);
+
+    if (detail.record && detail.matrix && detail.heartbeat) {
+      job.set('status', 'ready');
+      job.set('stage', 'verification');
+      job.set('readyAt', new Date().toISOString());
+      await job.save(null, { useMasterKey: true });
+      status = 'ready';
+    } else if (Date.now() - new Date(job.updatedAt).getTime() > JOB_TIMEOUT_MS) {
+      /*
+       * 超时:保留资源,标记失败,可重试。
+       *
+       * 🔴 失败阶段优先取 Agent 写库的最后一条 step 的 stage
+       *    (比 job.stage 准确),拿不到再回退。不影响成败判定。
+       */
+      var last = _currentStep(steps);
+      var stoppedAt = (last && last.stage) || job.get('stage');
+      await _failJob(job, FAIL.TIMEOUT, 'timeout after ' + JOB_TIMEOUT_MS + 'ms', stoppedAt);
+      status = 'failed';
+    }
+  } else if (status === 'provisioning') {
+    // 已终结的任务也把历史 step 带回去,便于前端展示用
+    steps = await _readSteps(job.id, job.get('attempts') || 1);
+  }
+
+  return _ok({
+    jobId: job.id,
+    agentId: agentId,
+    planCode: job.get('planCode'),
+    status: status,
+    stage: job.get('stage'),
+    jobRoomId: job.get('jobRoomId') || null,
+    matrixInfo: job.get('matrixInfo'),
+    error: job.get('error') || null,
+    reasonCode: job.get('reasonCode') || null,
+    retryable: job.get('retryable') === undefined ? null : job.get('retryable'),
+    failedStage: job.get('failedStage') || null,
+    steps: steps,
+    currentStep: _currentStep(steps),
+    verify: detail,
+    createdAt: job.createdAt,
+    updatedAt: job.updatedAt,
+  });
+}
+
+/** 重试:续跑同一 job,不新建记录 */
+async function _retry(user, p) {
+  var jobId = _str(p.jobId, 40);
+  var JobClass = Parse.Object.extend(CLASS_JOB);
+  var job;
+  try {
+    job = await new Parse.Query(JobClass).get(jobId, { useMasterKey: true });
+  } catch (e) {
+    return _fail(404, '任务不存在');
+  }
+  if (String(job.get('user').id) !== String(user.id)) return _fail(403, '无权操作该任务');
+  if (job.get('status') === 'ready') return _fail(409, '该容器已就绪,无需重试');
+
+  var agentId = job.get('agentId');
+  job.set('status', 'provisioning');
+  job.set('error', null);
+  job.set('attempts', (job.get('attempts') || 1) + 1);
+  await job.save(null, { useMasterKey: true });
+
+  try {
+    var token = _sessionToken();
+    // 已有 agentId 时不重建记录,只重发工单
+    var AgentClass = Parse.Object.extend('FmodeAgent');
+    var agent = await new Parse.Query(AgentClass).get(agentId, { useMasterKey: true });
+    var prov = await _callFn(FN_PROVISION, token, { agentId: agentId });
+
+    // 🔴 重试也开新房间:上一次很可能就是把上下文搞乱的那次
+    var roomId = await _createFreshRoom(job.id);
+    var joined = await _waitMasterJoin(roomId);
+    if (!joined) throw new Error('主容器未进房,重试不成立');
+    job.set('jobRoomId', roomId);
+    await job.save(null, { useMasterKey: true });
+
+    var instruction = _buildInstruction(user, agent, job.get('planCode'), agent.get('name'), job.id, job.get('matrixInfo'));
+    await _sendToRoom(roomId, instruction);
+    return _ok({ jobId: job.id, status: 'provisioning' });
+  } catch (e) {
+    var kind = _classifyError(e.message, job.get('stage'));
+    await _failJob(job, kind, e.message, job.get('stage'));
+    return _fail(500, kind.userMessage, { reasonCode: kind.reasonCode, retryable: kind.retryable });
+  }
+}
+
+/** 当前用户的任务列表 */
+async function _list(user) {
+  var JobClass = Parse.Object.extend(CLASS_JOB);
+  var q = new Parse.Query(JobClass);
+  q.equalTo('user', user);
+  q.notEqualTo('isDeleted', true);
+  q.descending('createdAt');
+  q.limit(20);
+  var rows = await q.find({ useMasterKey: true });
+  return _ok({
+    items: rows.map(function (j) {
+      return {
+        jobId: j.id,
+        agentId: j.get('agentId'),
+        planCode: j.get('planCode'),
+        status: j.get('status'),
+        stage: j.get('stage'),
+        error: j.get('error') || null,
+        createdAt: j.createdAt,
+        updatedAt: j.updatedAt,
+      };
+    }),
+  });
+}
+
+// ---------- 入口 ----------
+
+async function handler(request, response) {
+  try {
+    var p = params || (request.body && request.body.params) || {};
+
+    var user = await _getUser();
+    if (!user) return _fail(401, '未登录或会话已失效');
+
+    var op = p.op || 'status';
+
+    if (op === 'start') return await _start(user, p);
+    if (op === 'status') return await _status(user, p);
+    if (op === 'retry') return await _retry(user, p);
+    if (op === 'list') return await _list(user);
+
+    return _fail(400, '未知 op:' + op);
+  } catch (e) {
+    return _fail(500, '开通服务异常:' + _str(e && e.message, 300));
+  }
+}

BIN
cloud/scripts/__pycache__/r730_root_v3.cpython-311.pyc


BIN
cloud/scripts/__pycache__/r730_root_v3.cpython-312.pyc


+ 193 - 0
cloud/scripts/r730_root_v3.py

@@ -0,0 +1,193 @@
+#!/usr/bin/env python3
+"""R730NK1 root 执行器 v3(2026-11-25 加固:重试 + 连接复用 + 结构化错误)
+
+变更(相对于 v2):
+  ① **连接重试**:`_connect()` 现在会重试,专门应对 frpc 隧道抖动
+     实测 `Error reading SSH protocol banner` 是间歇性的,v2 一次失败即放弃。
+  ② **超时分级**:连接 20s(可比 30s 更快失败好重试),命令执行沿用 timeout 参数。
+  ③ **结构化错误**:run_root 返回 `{code, out, error, attempts}`,
+     `error` 为稳定枚举(CONNECT_FAILED / STAGE_FAILED / EXEC_FAILED),
+     调用方可以准确区分「通道不通」和「命令失败」。
+  ④ **不加连接池**:复用会引入状态污染风险(会话超时、半开连接),
+     在高失败率通道上反而更糟。用「快速失败 + 重试」更稳。
+
+用法不变:r730_root.py "命令"   或  from r730_root import run_root
+"""
+import base64
+import sys
+import time
+
+import paramiko
+
+HOST, PORT = "server.fmode.cn", 18001
+USER, PW = "***", "fmgo"
+NOISE = "sudo: unable to resolve host R730: Name or service not known"
+
+# 连接重试(针对 frpc 隧道抖动)
+CONNECT_ATTEMPTS = 6
+CONNECT_TIMEOUT = 20
+RETRY_BACKOFF = (1, 2, 3, 5, 8)  # 第 n 次失败后睡多少秒
+
+
+def _connect(attempts=CONNECT_ATTEMPTS):
+    """建立 SSH 连接,带重试。
+
+    🔴 为什么必须重试:frpc 隧道 18001 会间歇返回
+       `Error reading SSH protocol banner`,实测首次成功率很低(常需 3-4 次)。
+       v2 一次就放弃,导致调用方看到的是「失败」而不是「稍后就好了」。
+
+    返回 (client, attempts_used, last_error)
+    """
+    last = None
+    for i in range(attempts):
+        cli = paramiko.SSHClient()
+        cli.set_missing_host_key_policy(paramiko.AutoAddPolicy())
+        try:
+            cli.connect(
+                HOST,
+                port=PORT,
+                username=USER,
+                password=PW,
+                timeout=CONNECT_TIMEOUT,
+                banner_timeout=CONNECT_TIMEOUT,
+                auth_timeout=CONNECT_TIMEOUT,
+                allow_agent=False,
+                look_for_keys=False,
+            )
+            return cli, i + 1, None
+        except Exception as e:  # noqa: BLE001 - 任何连接异常都该重试
+            last = e
+            try:
+                cli.close()
+            except Exception:
+                pass
+            if i < attempts - 1:
+                time.sleep(RETRY_BACKOFF[min(i, len(RETRY_BACKOFF) - 1)])
+    return None, attempts, last
+
+
+def _err(code, message, attempts=0, out=""):
+    return {
+        "code": code,
+        "out": out,
+        "error": message,
+        "attempts": attempts,
+    }
+
+
+def run_root(cmd, timeout=300):
+    """以 root 执行 cmd(可以是多行脚本)。
+
+    返回 {code, out, error, attempts}
+      code     : 0 成功 / 非 0 命令失败 / -1 通道失败
+      out      : 命令标准输出(已清理)
+      error    : None 或稳定枚举字符串
+      attempts : 建立连接用了多少次尝试
+    """
+    cli, used, conn_err = _connect()
+    if cli is None:
+        return _err(
+            -1,
+            "CONNECT_FAILED: %s" % (str(conn_err)[:200] if conn_err else "unknown"),
+            attempts=used,
+        )
+
+    tmp_path = None
+    try:
+        # 1) 把命令包成脚本经 SFTP 放到 /tmp
+        script = "#!/bin/bash\n" + cmd + "\n"
+        b64 = base64.b64encode(script.encode()).decode()
+        tmp_path = "/tmp/rootjob_%d.sh" % int(time.time() * 1000)
+        _si, _so, _se = cli.exec_command(
+            "echo %s | base64 -d > %s && chmod 700 %s" % (b64, tmp_path, tmp_path),
+            timeout=30,
+        )
+        rc = _so.channel.recv_exit_status()
+        if rc != 0:
+            return _err(-1, "STAGE_FAILED: exit %d" % rc, attempts=used)
+
+        # 2) PTY 方式 sudo 执行,应答密码
+        chan = cli.get_transport().open_session()
+        chan.get_pty(width=256, height=64)
+        chan.exec_command("sudo -S -p 'PW:' bash %s; echo __RCZ__$?" % tmp_path)
+        buf = b""
+        sent_pw = False
+        deadline = time.time() + timeout
+        while time.time() < deadline:
+            if chan.recv_ready():
+                buf += chan.recv(65536)
+            text = buf.decode("utf-8", "replace")
+            if not sent_pw and "PW:" in text:
+                chan.send(PW + "\n")
+                sent_pw = True
+                time.sleep(0.2)
+                continue
+            last_line = text.split("\n")[-2] if "\n" in text else ""
+            if sent_pw and "__RCZ__" in last_line:
+                break
+            if chan.exit_status_ready() and not chan.recv_ready():
+                break
+            time.sleep(0.2)
+
+        # 收尾
+        deadline = time.time() + 3
+        while time.time() < deadline:
+            if chan.recv_ready():
+                buf += chan.recv(65536)
+                deadline = time.time() + 1
+            else:
+                time.sleep(0.1)
+
+        try:
+            rc = chan.recv_exit_status()
+        except Exception:
+            rc = 1
+
+        text = buf.decode("utf-8", "replace")
+        lines = []
+        for ln in text.replace("\r\n", "\n").replace("\r", "\n").split("\n"):
+            if ln.strip() == PW or ln.startswith("PW:"):
+                continue
+            if NOISE in ln:
+                continue
+            if ln.startswith("__RCZ__"):
+                try:
+                    rc = int(ln[7:].strip() or rc)
+                except ValueError:
+                    pass
+                continue
+            if "__RCZ__" in ln:
+                ln = ln.split("__RCZ__")[0]
+            lines.append(ln)
+        out = "\n".join(lines).strip("\n")
+
+        return {
+            "code": rc,
+            "out": out,
+            "error": None if rc == 0 else "EXEC_FAILED: exit %d" % rc,
+            "attempts": used,
+        }
+    except Exception as e:  # noqa: BLE001
+        return _err(-1, "EXEC_FAILED: %s" % str(e)[:200], attempts=used)
+    finally:
+        # 3) 清理临时脚本
+        if tmp_path:
+            try:
+                _si2, _so2, _se2 = cli.exec_command("rm -f %s" % tmp_path, timeout=15)
+                _so2.channel.recv_exit_status()
+            except Exception:
+                pass
+        try:
+            cli.close()
+        except Exception:
+            pass
+
+
+if __name__ == "__main__":
+    cmd = " ".join(sys.argv[1:]) or "id"
+    r = run_root(cmd)
+    if r["error"]:
+        sys.stderr.write("[%s] attempts=%d\n" % (r["error"], r["attempts"]))
+    if r["out"]:
+        print(r["out"])
+    sys.exit(0 if r["code"] >= 0 else 1)

+ 372 - 0
cloud/skills/container-provision-job/SKILL.md

@@ -0,0 +1,372 @@
+---
+name: container-provision-job
+description: "触发词:开通容器任务、建容器任务、provision job、容器开通工单。按结构化任务书执行一次容器创建,每任务独立房间独立回合,产出机器可读结果。"
+version: 4.0.0
+license: MIT
+platforms: [linux]
+tags: [container, provisioning, job, matrix, s6, verification, machine-readable]
+---
+
+# 容器开通工单(container-provision-job)
+
+> **本技能与 `container-provision-from-source` 的分工**
+> - `container-provision-from-source`:**怎么建**(SOP、坑、参数细节)
+> - **本技能**:**按工单执行一次**(输入契约、执行纪律、输出契约)
+>
+> 本技能不重复 SOP 细节,执行时**同时加载** `container-provision-from-source` 作为操作手册。
+
+## 0. 为什么要有这个技能(必读)
+
+### 问题:AI 执行长任务会「失忆」
+
+2026-11-25 实测:给主容器的建容器指令有 200+ 行,它执行 20 分钟后会在中途"走神"——
+反复修 media-patch、SOUL.md 名字不对这类细节,**最后不产出结论,只有过程**。
+调用方等 25 分钟只拿到「静默/超时」。
+
+### 根因:一个房间 = 一个永久 session
+
+Hermes 的 `session_key` 格式是 `agent:main:matrix:dm:<roomId>`,
+`session_reset.mode: none`(永不自动重置)。因此:
+
+> **同一个 Matrix 房间 = 永远同一个 session = 历史上下文无限累积**
+
+历史越长,AI 越容易:① 被前几次失败带偏;② 撞上下文压缩阈值后丢失关键指令;
+③ 在同一堆旧结论里反复兜圈子。
+
+### 解法:一任务一房间
+
+**每次开通任务使用一个全新 Matrix 房间**。新房间 = 新 session_key = 干净上下文。
+这是 Hermes 下"开新回合"的唯一可靠方式(`/new` 命令不存在,`session_reset` 改全局配置风险太大)。
+
+---
+
+## 1. 输入契约(调用方必须提供)
+
+调用方在**新房间**里发的第一条消息就是工单。格式必须含以下 JSON 块:
+
+```json
+{
+  "jobId": "PROVISION-20261126-001",
+  "agentId": "agent-node-app-xxxx",
+  "displayName": "用户显示名",
+  "objectId": "FmodeAgent 记录主键",
+  "ownerUserMxId": "@xxx:fmode.cn",
+  "ownerSessionToken": "r:...",
+  "agentMxId": "@yyy:fmode.cn",
+  "roomId": "!目标容器的工作房间",
+  "allowedUsers": "@xxx:fmode.cn",
+
+  "templateDir": "/opt/fmode-templates/default",
+  "image": "fmode/agent-node:0.21.3",
+  "entrypoint": "/opt/data/.fmode-media-patch/entry.sh",
+  "targetDir": "/opt/fmode-containers/agent-node-app-xxxx/data",
+
+  "matrixHomeserver": "https://matrix.fmode.cn"
+}
+```
+
+**缺任何必填项就立即 `FAILED` 并说明缺哪个,不要猜、不要用默认值代替。**
+(`roomId` 为 `null` 时必须失败,见铁则 3。)
+
+---
+
+## 2. 执行纪律(铁则)
+
+### 铁则 0:一次 SSH 跑完,不要反复开会话
+
+🔴 **这是本技能最重要的执行约束**(2026-11-26 用户裁决)。
+
+R730 的 sshd 有**并发会话上限**。实测:建一个容器要开十几次 SSH 会话时,
+中途会被限流,`r730_root.py` 报 `Error reading SSH protocol banner`。
+
+**因此:**
+
+- ❌ **禁止**每做一小步就单独跑一次 `r730_root.py`
+- ❌ **禁止**为了"看看情况"而反复 `docker ps` / `ls` / `cat`
+- ✅ **必须**先把整条流程写成一个 shell 脚本,再**一次** `r730_root.py` 执行完
+- ✅ 脚本内部用 `set -e`,任何一步失败立刻停并打印 `[FAIL] <步骤名>`
+- ✅ 整个开通流程**最多开 3 次 SSH 会话**:① 跑主脚本 ② 失败时取错误上下文 ③ 重试
+
+脚本模板(把 `<占位>` 换成工单里的值):
+
+```bash
+#!/bin/bash
+set -e
+AGENT_ID="<agentId>"
+TPL="<templateDir>"
+DST="<targetDir>"
+echo "[STEP] prepare"
+mkdir -p "$DST"
+[ -d "$TPL" ] || { echo "[FAIL] template missing: $TPL"; exit 11; }
+
+echo "[STEP] copy"
+cp -a "$TPL/." "$DST/"
+
+echo "[STEP] configure"
+cat > "$DST/.env" <<'ENVEOF'
+MATRIX_HOMESERVER=https://matrix.fmode.cn
+MATRIX_USER_ID=<agentMxId>
+MATRIX_PASSWORD=<派生密码>
+MATRIX_HOME_ROOM=<roomId>
+MATRIX_REACTIONS=true
+MATRIX_REQUIRE_MENTION=false
+MATRIX_ALLOWED_USERS=<ownerUserMxId>
+MATRIX_MAX_MEDIA_BYTES=838860800
+MATRIX_E2EE_MODE=off
+AGENT_ID=<agentId>
+FMODE_SESSION_TOKEN=<ownerSessionToken>
+AGENT_FUNCTION_ID=xlosi3m46q
+ENVEOF
+
+# 清空旧会话与运行时残留(否则新容器带着模板主人的历史)
+rm -rf "$DST/sessions" "$DST/logs" "$DST/cache"
+mkdir -p "$DST/sessions"
+rm -f "$DST/gateway.pid" "$DST/gateway.lock" "$DST/gateway.sock" "$DST/gateway_state.json"
+rm -f "$DST/kanban.db" "$DST/kanban.db-shm" "$DST/kanban.db-wal"
+rm -f "$DST/state.db" "$DST/state.db-shm" "$DST/state.db-wal"
+rm -f "$DST/shared-state.db" "$DST/runs_idempotency.db"*
+rm -f "$DST/auth.json" "$DST/auth.lock" "$DST/install_id" "$DST/.install_id.lock"
+rm -f "$DST/matrix_threads.json" "$DST/channel_directory.json"
+rm -f "$DST"/SOUL.md.bak-* "$DST"/config.yaml.apptest-*
+
+# 改人格名
+sed -i "s/测试分身0001/<displayName>/g; s/agent-node-app-test-0001/<agentId>/g" "$DST/SOUL.md"
+
+echo "[STEP] create"
+docker rm -f "$AGENT_ID" 2>/dev/null || true
+docker run -d \
+  --name "$AGENT_ID" \
+  --hostname "$AGENT_ID" \
+  --restart unless-stopped \
+  --memory 4g --cpus 2 --pids-limit 512 \
+  -v "$DST:/opt/data" \
+  -e FMODE_SESSION_TOKEN="<ownerSessionToken>" \
+  -e AGENT_ID="$AGENT_ID" \
+  -e AGENT_FUNCTION_ID=xlosi3m46q \
+  -e MATRIX_HOMESERVER=https://matrix.fmode.cn \
+  -e MATRIX_USER_ID="<agentMxId>" \
+  -e MATRIX_PASSWORD="<matrixPassword>" \
+  -e MATRIX_HOME_ROOM="<roomId>" \
+  -e MATRIX_ALLOWED_USERS="<ownerUserMxId>" \
+  -e MATRIX_REACTIONS=true \
+  -e MATRIX_REQUIRE_MENTION=false \
+  -e MATRIX_MAX_MEDIA_BYTES=838860800 \
+  -e MATRIX_E2EE_MODE=off \
+  -e API_SERVER_ENABLED=true \
+  -e HERMES_DASHBOARD=0 \
+  -e TZ=Asia/Shanghai \
+  --entrypoint <entrypoint> \
+  <image> \
+  gateway run
+
+echo "[STEP] verify"
+sleep 25
+docker ps --filter "name=$AGENT_ID" --format '{{.Names}} {{.Status}}'
+# 三项证据:容器在跑 + Matrix connected + token 已注入
+docker exec "$AGENT_ID" cat /opt/data/gateway_state.json | head -c 300
+docker exec "$AGENT_ID" cat /run/s6/container_environment/FMODE_SESSION_TOKEN | head -c 8
+```
+
+🔴 **两个致命细节**(2026-11-27 实测踩过):
+
+1. **结尾必须带 `gateway run`**。只给 `--entrypoint entry.sh` 不带参数的话,
+   entry.sh 会把空参数透传给镜像原入口 → 跑成**交互式 TUI** →
+   `Warning: Input is not a terminal (fd=0)` → 容器立刻 `Exited (0)`。
+2. **`-e` 一个都不能少**。`.env` 只给 Hermes 读;插件读的是
+   `/run/s6/container_environment/`,那只能由 `docker run -e` 注入。
+   缺 `FMODE_SESSION_TOKEN` → 心跳永远不上报。
+
+
+**脚本执行命令**(一次会话跑完):
+
+```bash
+/opt/data/venv-ops/bin/python3 /opt/data/scripts/r730_root.py "$(cat /tmp/prov-<jobId>.sh)"
+```
+
+### 铁则 1:只做工单要求的事
+
+- ❌ 不"顺手优化"模板目录 —— **它是只读的,绝不能改**
+- ❌ 不深入分析 media-patch 为什么不生效 —— **记录现象即可,不修**
+- ✅ 遇到非阻断问题,**记录到 `warn` 类型的 step,继续往下走**
+
+> 2026-11-25 的教训:AI 卡在 media-patch 上花了 15 分钟,而它是否生效**不影响容器可用**。
+
+### 铁则 2:SSH 失败必须重试
+
+`r730_root.py` 若返回 `CONNECT_FAILED`:
+- 等 15 秒,整体重跑整个脚本(**不是**拆成小步骤重跑)
+- 最多 3 次
+- 仍失败 → 写 `failed` + `reasonCode: "R730_UNREACHABLE"`
+
+**不要尝试自己写 SSH 逻辑绕过它。**
+
+### 铁则 3:`roomId` 是唯一权威目标房间,不要自己找
+
+🔴 2026-11-26 实测事故:工单里 `roomId` 为 `null` 时,主容器为了"自己找到目标房间"
+在 `/opt/data` 下反复 grep、翻配置、试图注册 Matrix 账号,**跑了 30 分钟没产出结论**。
+
+因此:
+
+- `roomId` 有值 → **直接用它**,不要再去搜索、推导、验证它是"正确的那个"
+- `roomId` 为 `null`/空 → **立刻 `FAILED`**,`reasonCode: "MISSING_ROOM_ID"`
+- 进程内外都不要调用平台云函数(`xlosi3m46q` / `RP5Ht55NeX` 平台侧已完成)
+- **不要自己注册/登录 Matrix 账号**:账号由 `RP5Ht55NeX` 建好了,容器只需用 `.env` 里的凭据连上去
+
+### 铁则 4:撞墙 3 次就换路,不要死磕
+
+同一条命令连续失败 3 次 → 立刻换方案;换方案仍不通 → `FAILED` + 已完成的阶段。
+**禁止**在同一问题上反复尝试 10 次以上(这是"失忆"的主要表现)。
+
+### 铁则 5:限时
+
+| 阶段 | 上限 |
+|---|---|
+| 总时长 | **12 分钟** |
+| 单次 `r730_root.py` | 5 分钟 |
+
+超时立即写 `failed` 并停止,**不要硬撑**。容器可以之后重试(会复用已建资源)。
+
+> 从 18 分钟收紧到 12 分钟:模板 + 一次性脚本的正常耗时应在 3~5 分钟内。
+> 超过 12 分钟说明卡住了,继续等只会浪费调用方的轮询窗口。
+
+### 铁则 6:进度只写数据库,不要在聊天里汇报
+
+🔴 **这是调用方唯一能看见你的方式**(2026-11-26 用户裁决)。
+
+**背景**:实测你在长任务里只会回工具调用回显(`💻 terminal \`\`\` cd /opt/... \`\`\``)
+和进度碎念(`* 还在跑,12 分钟了`)。调用方既看不到真实进度,也无法判断卡在哪。
+**让你"在聊天里组织格式"是不可靠的 —— 但让你"发一次 curl",你能稳定做到。**
+
+**因此:每进入 / 每完成一个阶段,写一条 `FmodeProvisionStep` 记录。**
+这是你的**唯一**对外汇报方式。不要在聊天里解释,不要贴过程。
+
+#### 写库模板(照抄,只改值)
+
+```bash
+curl -s -X POST 'https://server.fmode.cn/parse/classes/FmodeProvisionStep' \
+  -H 'X-Parse-Application-Id: ncloudmaster' \
+  -H 'Content-Type: application/json' \
+  -d '{"jobId":"<jobId>","attempt":1,"stage":"<stage>","status":"<status>","step":"<一句话>","evidence":"<关键证据>","elapsedSec":0,"agentId":"<你的容器名>"}'
+```
+
+#### 字段取值
+
+| 字段 | 取值 | 说明 |
+|---|---|---|
+| `jobId` | 工单里的 jobId | 必填,调用方按它查 |
+| `attempt` | 工单里的 attempt(默认 1)| 重试时区分 |
+| `stage` | `prepare`/`copy`/`create`/`configure`/`start`/`verify` | 必填 |
+| `status` | `running`/`ok`/`failed`/`warn` | 必填 |
+| `step` | 一句话描述,≤80 字 | 如「docker run 中」 |
+| `evidence` | 关键证据,≤300 字 | 如 `docker ps` 那一行;可空 |
+| `reasonCode` | 失败时的枚举 | 见 §5;成功时留空 |
+| `elapsedSec` | 本阶段耗时(整数秒) | 可空 |
+
+#### 写几次
+
+| 时机 | 写什么 |
+|---|---|
+| 进入某阶段 | `status:"running"` |
+| 该阶段完成 | `status:"ok"` + `evidence` |
+| 非阻断问题 | `status:"warn"` + `step` 说明现象,**继续往下走** |
+| 阻断失败 | `status:"failed"` + `reasonCode`,**然后停止** |
+
+**每个阶段最多写 2 条(running + ok/失败)**,不要刷屏。
+
+#### 写库失败不影响继续
+
+`curl` 返回非 2xx → **不要重试超过 2 次,不要卡住**,继续执行下一步。
+调用方还有服务端三项核验兜底,不依赖这条记录判成败。
+
+#### 聊天里只回一句
+
+写库之后,在聊天里回一行极简确认即可,例如 `prepare/running` 或 `create/ok`。
+**不要贴命令回显,不要写解释段落。**
+
+### 铁则 7:模板目录只读,绝不能改
+
+工单里给的是:
+
+```json
+"templateDir": "/opt/fmode-templates/default",
+"targetDir":   "/opt/fmode-containers/agent-node-app-xxxx/data"
+```
+
+🔴 **`templateDir` 是别人的运行中容器目录,全程只读。**
+   只允许 `cp -a "$TPL/." "$DST/"`,**禁止**对 `$TPL` 做任何写操作。
+
+🔴 **`targetDir` 必须先清干净再拷**:如果它已存在(重试场景),
+   `rm -rf "$DST"` 后再 `mkdir`,否则旧残留会让新容器带着上次的垃圾状态。
+
+**模板不可用**(目录不存在 / 缺 media-patch)→ 立刻 `failed` + `reasonCode:"TEMPLATE_INVALID"`,
+**不要**自己去别的地方找替代品。
+
+---
+
+## 3. 执行步骤
+
+> 完整脚本见铁则 0。这里只列**阶段与检查点**。
+
+| 阶段 | 做什么 | 通过标准 |
+|---|---|---|
+| `prepare` | 清空并重建 `targetDir` | 目录存在且为空 |
+| `copy` | `cp -a` 模板 → 目标 | 目标里有 `plugins/`、`.fmode-media-patch/` |
+| `configure` | 写 `.env`(全量覆盖)、改 `SOUL.md`、清会话与状态库 | 回读 `.env` 的 `AGENT_ID` / `MATRIX_USER_ID` 是新值 |
+| `create` | `docker run` | `docker ps` 能看到新容器 running |
+| `verify` | 等 20 秒后看 `gateway_state.json` 的 matrix.state | `connected` |
+
+**每进入 / 每完成一个阶段,按铁则 6 写一条 `FmodeProvisionStep`**,
+聊天里只回一行 `stage/status`(如 `create/ok`)。这样即使超时,调用方也知道停在哪。
+
+---
+
+## 4. 结果怎么算"成"
+
+🔴 **你不需要宣布成败,也不要在聊天里写「成功了」。**
+
+调用方按**服务端三项事实**判定(容器记录 + Matrix joined + 心跳新鲜),
+你的文字不参与判定 —— 说 READY 也不会被判成成功,说失败也不会被判成失败。
+
+你要做的只有两件事:
+
+1. **把容器真正建出来、配好、连上 Matrix**(三个 verify 项)
+2. **最后写一条 `stage:"verify", status:"ok"` 的 step**,`evidence` 里放
+   `whoami` 结果和 `docker ps` 状态行
+
+如果中途失败:写 `status:"failed"` + `reasonCode`,然后**停止**,不要继续往下试。
+
+### `PARTIAL` 的写法
+
+容器建了但没配好(比如 `.env` 没写入):
+写 `stage:"configure", status:"failed", reasonCode:"CONFIG_FAILED"`,
+并在 `evidence` 里说明「容器已运行但配置未完成」。
+调用方会据此决定「重试配置」而不是「重新建容器」。
+
+---
+
+## 5. 失败原因码(与云函数对齐)
+
+| reasonCode | 含义 | 是否可重试 |
+|---|---|---|
+| `R730_UNREACHABLE` | SSH 通道不通 | ✅ |
+| `TEMPLATE_INVALID` | 模板目录缺失/不完整 | ❌ 需人工 |
+| `MISSING_ROOM_ID` | 工单没给 roomId | ❌ 需人工 |
+| `CONTAINER_CREATE_FAILED` | docker run 失败 | ✅ |
+| `CONTAINER_NOT_RUNNING` | 建了但没起来 | ✅ |
+| `CONFIG_FAILED` | .env / SOUL.md 写失败 | ✅ |
+| `MATRIX_FAILED` | Matrix 连接失败 | ✅ |
+| `TIMEOUT` | 超过 12 分钟 | ✅ |
+
+---
+
+## 6. 自检清单(回答前逐项确认)
+
+- [ ] **整个流程只开了 1~3 次 SSH 会话**,不是十几步各开一次
+- [ ] 所有必填参数都用了工单里的值,没有从别处继承
+- [ ] `roomId` 用的是工单给的那个,没有自己去搜
+- [ ] `FMODE_SESSION_TOKEN` 用的是**工单里开通者的** token,不是模板里的旧值
+- [ ] `sessions/` 和状态库**已清空**,新容器不带模板主人的历史
+- [ ] `templateDir` 全程只读未改动
+- [ ] 每个阶段都写了 `FmodeProvisionStep`(running + ok)
+- [ ] 没有在聊天里贴命令回显或写长篇解释
+- [ ] 失败时写了 `reasonCode` 并且**停下来了**,没有继续硬试

+ 243 - 0
cloud/skills/container-stop-remove/SKILL.md

@@ -0,0 +1,243 @@
+---
+name: container-stop-remove
+description: "触发词:停止容器、删除容器、清理容器、容器下线、container stop、container remove。按白名单精确停止或删除 R730 上的容器,默认只停不删,每步前后对比防止误伤。"
+version: 1.0.0
+license: MIT
+platforms: [linux]
+tags: [container, docker, cleanup, safety, r730, whitelist]
+---
+
+# 容器停止 / 删除(container-stop-remove)
+
+## 0. 为什么要有这个技能
+
+R730 上同时跑着**几十个别人的容器**(用户分身、运维容器、主容器)。
+手工敲 `docker stop` 一旦用错通配符,就可能把别人的服务停掉。
+
+本技能的唯一目的:**在绝不可能误伤的前提下**,停止或删除指定容器。
+
+> 2026-11-27 实测:R730 上有 20+ 容器,其中 5 个 `agent-node-u*`、
+> 8 个业务容器、1 个主容器 `agent-node`。
+> 一次 `docker stop agent-node-app-*` 就会误停。
+
+---
+
+## 1. 输入契约
+
+```json
+{
+  "action": "stop",
+  "containers": ["agent-node-app-5ddcx9ml3k"],
+  "removeData": false,
+  "softDeleteRecords": false,
+  "reason": "测试产物清理"
+}
+```
+
+| 字段 | 必填 | 说明 |
+|---|---|---|
+| `action` | ✅ | `stop`(默认)/ `remove` |
+| `containers` | ✅ | **精确容器名数组**,不接受通配符 |
+| `removeData` | | `true` 才删 `/opt/fmode-containers/<名>`,默认 `false` |
+| `softDeleteRecords` | | `true` 才软删 `FmodeAgent` 记录,默认 `false` |
+| `reason` | | 写进执行记录,便于事后追溯 |
+
+**`action: "remove"` 时 `containers` 里的每个容器必须已处于 `Exited` 状态**,
+否则拒绝执行(先 stop 再 remove)。
+
+---
+
+## 2. 铁则
+
+### 铁则 1:只接受精确名字,一个字符都不能是通配符
+
+执行前逐项校验,出现以下任意一种 → **立刻拒绝整个请求,一个都不动**:
+
+- 含 `*`、`?`、`[`、`]`
+- 以 `$` 开头或含 `$(`
+- 为空字符串
+- 长度 < 3
+
+```bash
+# 校验通过才继续
+for c in "${CONTAINERS[@]}"; do
+  [[ "$c" =~ ^[a-zA-Z0-9][a-zA-Z0-9_.-]*$ ]] || { echo "[REFUSE] 非法容器名: $c"; exit 20; }
+done
+```
+
+### 铁则 2:保护名单硬编码,命中即拒绝
+
+以下名字**永远不允许**通过本技能操作(先 `docker stop` 前校验):
+
+```
+agent-node                 # 主容器,所有开通过程依赖它
+agent-node-lj-test         # 历史遗留,需人工确认
+```
+
+以 `agent-node-u` 开头的一律视为**用户容器**,除非 `reason` 里明确写了
+「用户本人申请下线」。
+
+### 铁则 3:三步走,每步验证
+
+```
+① 快照 → ② 停/删 → ③ 对比
+```
+
+**① 快照**(执行前)
+
+```bash
+docker ps -a --format '{{.Names}}|{{.Status}}' | sort > /tmp/cleanup-before.txt
+```
+
+**② 停/删**(一次只处理一个,处理完立刻验)
+
+```bash
+docker stop "<名字>"
+docker ps -a --format '{{.Names}}|{{.Status}}' | grep "^<名字>|"   # 必须是 Exited
+```
+
+**③ 对比**(全部处理完后)
+
+```bash
+docker ps -a --format '{{.Names}}|{{.Status}}' | sort > /tmp/cleanup-after.txt
+diff /tmp/cleanup-before.txt /tmp/cleanup-after.txt
+```
+
+**diff 里出现的每一行,必须都能在输入 `containers` 数组里找到。**
+出现任何意料之外的变化 → 立即 `docker start` 恢复并中止。
+
+### 铁则 4:一次 SSH 跑完
+
+R730 的 sshd 有并发上限(实测反复开会话会触发
+`Error reading SSH protocol banner`)。整批操作写成一个脚本,一次执行完。
+
+---
+
+## 3. 执行脚本模板
+
+```bash
+#!/bin/bash
+set -euo pipefail
+
+# ---- 输入 ----
+ACTION="<stop|remove>"
+CONTAINERS=(<精确名字,空格分隔>)
+REMOVE_DATA=<true|false>
+SOFT_DELETE=<true|false>
+
+PROTECTED=("agent-node" "agent-node-lj-test")
+
+# ---- ① 校验 ----
+for c in "${CONTAINERS[@]}"; do
+  [[ "$c" =~ ^[a-zA-Z0-9][a-zA-Z0-9_.-]*$ ]] || { echo "[REFUSE] 非法名: $c"; exit 20; }
+  for p in "${PROTECTED[@]}"; do
+    [ "$c" = "$p" ] && { echo "[REFUSE] 保护名单: $c"; exit 21; }
+  done
+  docker inspect "$c" >/dev/null 2>&1 || { echo "[REFUSE] 不存在: $c"; exit 22; }
+done
+
+# ---- ① 快照 ----
+SNAP=/tmp/cleanup-before-$$.txt
+docker ps -a --format '{{.Names}}|{{.Status}}' | sort > "$SNAP"
+
+# ---- ② 逐个处理 ----
+if [ "$ACTION" = "stop" ]; then
+  for c in "${CONTAINERS[@]}"; do
+    echo "[STOP] $c"
+    docker stop "$c" >/dev/null
+    st=$(docker ps -a --format '{{.Names}}|{{.Status}}' | grep "^$c|" | cut -d'|' -f2)
+    echo "  -> $st"
+    case "$st" in Exited*) ;; *) echo "[ABORT] $c 未正常停止"; exit 30;; esac
+  done
+fi
+
+if [ "$ACTION" = "remove" ]; then
+  for c in "${CONTAINERS[@]}"; do
+    st=$(docker ps -a --format '{{.Names}}|{{.Status}}' | grep "^$c|" | cut -d'|' -f2 || echo "")
+    case "$st" in Exited*) ;; *) echo "[ABORT] $c 仍在运行,先 stop"; exit 31;; esac
+    echo "[REMOVE] $c"
+    docker rm "$c" >/dev/null
+  done
+fi
+
+# ---- 数据目录(可选)----
+if [ "$REMOVE_DATA" = "true" ]; then
+  for c in "${CONTAINERS[@]}"; do
+    d="/opt/fmode-containers/$c"
+    [ -d "$d" ] && { echo "[RMDIR] $d"; rm -rf "$d"; }
+  done
+fi
+
+# ---- ③ 对比 ----
+echo "=== DIFF ==="
+docker ps -a --format '{{.Names}}|{{.Status}}' | sort > /tmp/cleanup-after-$$.txt
+diff "$SNAP" /tmp/cleanup-after-$$.txt || true
+echo "=== END ==="
+```
+
+**执行**:
+
+```bash
+/opt/data/venv-ops/bin/python3 /opt/data/scripts/r730_root.py "$(cat /tmp/cleanup.sh)"
+```
+
+---
+
+## 4. 数据库软删(可选)
+
+`SOFT_DELETE=true` 时,对本批容器对应的 `FmodeAgent` 记录做**软删**:
+
+```bash
+curl -s -X PUT 'https://server.fmode.cn/parse/classes/FmodeAgent/<objectId>' \
+  -H 'X-Parse-Application-Id: ncloudmaster' \
+  -H 'X-Parse-Master-Key: <masterKey>' \
+  -H 'Content-Type: application/json' \
+  -d '{"isDeleted":true}'
+```
+
+🔴 **永远用软删(`isDeleted: true`),不硬删**——便于日后追溯。
+
+⚠️ 同一容器可能有**两条记录**:
+- 云函数建的(`objectId` 为真实主键)
+- 插件自建的(`agentId` = 容器名)
+
+两条都要软删。查法:
+
+```bash
+curl -s 'https://server.fmode.cn/parse/classes/FmodeAgent?where=%7B%22agentId%22%3A%22<容器名>%22%7D' \
+  -H 'X-Parse-Application-Id: ncloudmaster' -H 'X-Parse-Master-Key: <masterKey>'
+```
+
+---
+
+## 5. 输出契约
+
+最后必须输出一份结果:
+
+````
+===CLEANUP-RESULT===
+{"action":"stop","ok":["a","b"],"refused":[],"diff":"仅 a、b 变化","leftRunning":18}
+===END===
+````
+
+| 字段 | 说明 |
+|---|---|
+| `ok` | 成功处理的容器 |
+| `refused` | 被拒绝的(附原因) |
+| `diff` | 与快照对比的实际变化 |
+| `leftRunning` | 处理后仍在运行的容器数 |
+
+**`diff` 里出现了输入数组之外的容器 → `action` 算失败,必须 `docker start` 恢复。**
+
+---
+
+## 6. 自检清单
+
+- [ ] 每个容器名都通过了正则校验,没有通配符
+- [ ] 没有命中保护名单(`agent-node`、`agent-node-lj-test`)
+- [ ] 执行前存了快照
+- [ ] `stop` 后逐个确认是 `Exited`
+- [ ] `remove` 前确认已 `Exited`
+- [ ] 做完 diff 对比,变化全部在预期内
+- [ ] 数据库用软删
+- [ ] 全程只开 1 次 SSH 会话

+ 32 - 0
docs/00-tracking/2026-11-25-套餐异步开通实施记录.md

@@ -0,0 +1,32 @@
+# 套餐、两天试用与平台异步开通实施记录
+
+| 项 | 内容 |
+| --- | --- |
+| 日期 | 2026-11-25(北京时间) |
+| 唯一执行基准 | `docs/02-design/plans/2026-11-25-套餐体系任务计划书.md` |
+| 本次授权 | 用户明确要求实现已确认计划;按 G-D1 先完成文档、接口设计、可交互双端原型,原型确认后进入产品实现 |
+| 当前里程碑 | 前置文档与原型制作中;G-D1 未通过 |
+
+## 1. 开工基线与操作边界
+
+- 现有 v1.0 阶段 0 文档评审已闭环,原接手说明、计划和 README 的阶段状态存在滞后,先同步。
+- 本次新增裁决包含:试用 48 小时、平台容器交付、基础配额 1/3/5、平台异步创建及阶段进度、到期仅锁定项目使用、付费原容器恢复。
+- 项目已有大量未提交业务与文档修改,任务文档本身尚未入库。维护用户指定工作区,不切换分支、不提交、不覆盖其他工作;原型位于独立目录,不挂产品路由。
+- 使用项目 `.claude/skills/executing-plans`、`subagent-driven-development` 与 `prototype`(状态交互演示方向)。分离文档同步、只读架构调查与独立评审职责。
+- 产品实现、云函数部署、平台资源开通及耗时实测尚未执行;不将原型演示认作真实开通。
+- 所有现存容器保持原状,`lj-test` 只读;不读取或输出真实凭据。
+
+## 2. 任务清单
+
+- [ ] 同步 CR、PRD、定价权益、唯一任务计划、接手说明、README 和追溯矩阵。
+- [ ] 完成接口与数据契约,标清现有能力、拟新增能力、平台阻断条件。
+- [ ] 完成双端可交互原型:套餐、开通等待、失败/超时/离线、我的容器、接入参数、到期付费、企业引导。
+- [ ] 浏览器交互和截图检查、文档结构检查、独立需求合规与架构/安全评审,修复问题。
+- [ ] 提交具体原型供用户确认 G-D1。
+- [ ] G-D1 后:平台与产品实现、真实创建计时、耗时优化、全量验收与评审。
+
+## 3. 验证结果
+
+执行中,完成后记录证据。现阶段不得填入真实开通预计分钟数。
+
+2026-11-25 复核补充(G-D1 前):入门版/企业版套餐卡补齐「2 核 4G 标准规格」(对齐定价文档 §一与 AC-21.1);verify.mjs 增加输出目录清理与三卡规格断言。复验 19 项 checks 全过、0 pageerror、0 外网请求。门禁状态不变:G-D1 待用户确认。

+ 39 - 0
docs/00-tracking/2026-11-25-官网下载页重新部署.md

@@ -0,0 +1,39 @@
+# 官网下载页重新部署(2026-11-25)
+
+## 授权与执行范围
+
+用户要求「按照项目里面的规范把这个官网重新部署一下」。沿用本项目 2026-11-23 的官网发布记录与 `scripts/publish-apk.mjs`,目标 `https://ai.fmode.cn/download/`,使用 `--skip-apk` 重新构建并发布官网与清单、刷新 CDN、执行线上验证。
+
+- 安装包沿用当前 v1.0 测试版,不上传或覆盖 APK。
+- 只逐对象上传 `download/index.html` 和 `download/manifest.json`;不清桶,不发布根路径 Web App。
+- 使用现有本地 OBS / 华为云 KooCLI 配置;所有输出与日志遮蔽凭据。
+- 不执行 Git 提交或推送。
+
+## 发布前检查
+
+- 线上旧页、旧清单及根路径 Web App 已备份至 `.local-backup/download-site-20261125-1795572498201/`。
+- 本地与线上 APK 均为 10,343,681 字节,MD5 一致:`0392d35b44d7a8c4d481679aee895878`。
+- 当前清单版本 1.0、测试版;线上 APK 返回 200,类型为 Android 安装包。
+- OBS CLI 5.8.9、华为云 KooCLI 7.3.12 已就绪。
+- 官网页面构建与浏览器回归通过:199 KB 单文件 HTML、18 组检查(11 种屏幕宽度及短屏、下载、二维码、异常状态)。
+
+## 发布结果与线上回归
+
+- 执行命令:`node scripts/publish-apk.mjs --skip-apk`,经本地临时包装器运行,将现有脚本输出中的 CLI 凭据遮蔽后保存日志。
+- 发布成功:北京时间 2026-11-25 10:09;只更新 `download/index.html` 和 `download/manifest.json` 两个对象。
+- CDN 任务 `8289443686`:`task_done`,3 / 3 成功,0 失败。
+- 裸地址 `/download/`、`/download/index.html`、`/download` 均返回 200;未添加缓存绕过参数,三个响应的 SHA256 均与本地构建一致:`faafa363f03690826974fc4ad1189878d54a69d72e747fc85a687cec387f7548`。
+- 线上 Playwright 检查:320 / 390 / 1440px 无横向溢出;移动菜单、三个产品页签、扫码弹窗、统一下载地址均正常,无脚本错误。
+- 通过线上移动底栏真实点击下载完整 APK:10,343,681 字节,MD5 `0392d35b44d7a8c4d481679aee895878`,与发布前一致。
+- 线上生成的二维码 PNG、320 / 390px 手机下载区截图、1440px 桌面下载区截图经 OpenCV 解码,均指向同一正式 APK 地址。
+- 根路径 Web App 返回 200,发布前后 SHA256 均为 `e90b3bf1ebb544ede33ff0568e6f0bbc4db01ea2bb8a40609e154629c70318bb`,未受本次发布影响。
+- 发布脚本按既有约定更新网页 `updatedAt` 与清单时间到 2026-11-25;APK 仍沿用 2026-11-23 构建的 v1.0 测试版,文件未覆盖。
+
+## 证据与边界
+
+- `test-results/download-site-deploy/publish.log`:脱敏后的上传、CDN 提交和探活日志。
+- `test-results/download-site-deploy/online-results.json`:裸链接哈希、在线浏览器检查、APK 完整下载校验和 CDN 终态。
+- `test-results/download-site-deploy/qr-decode-results.json`:线上二维码原图与页面截图的解码结果。
+- 同目录 `live-hero-*.png`、`live-download-*.png`、`live-qr-dialog-*.png`:线上桌面与手机预览。
+- 官网地址:`https://ai.fmode.cn/download/`;APK 地址继续为 `https://ai.fmode.cn/download/fmode-app-v1.0.apk`。
+- 本次未执行 Git 提交 / 推送或手机真机安装回归。

+ 100 - 0
docs/00-tracking/AI接手说明-套餐体系与容器资产.md

@@ -0,0 +1,100 @@
+# AI 接手说明 · 套餐体系任务与容器资产
+
+| 字段 | 值 |
+|---|---|
+| 版本 | v1.1 |
+| 最后更新 | 2026-11-25 |
+| 状态 | 本轮裁决收口,接口设计/双端原型准备;v1.1 待新独立评审 |
+| 配套 | docs/00-tracking/当前进度-给AI接手.md(全项目历史进度) |
+| 用途 | 接手套餐任务先读本文件与唯一任务计划,避免重问已定规则或误动旧资产 |
+
+## 〇、30 秒版
+
+1. **唯一执行基准**:docs/02-design/plans/2026-11-25-套餐体系任务计划书.md **v1.1**。最新变更依据为 CR-20261125-02,冲突时覆盖 CR-01 与历史人工流程。
+2. **阶段**:阶段 0 原第 1 轮 7 项已闭环;当前阶段 1 业务裁决已收口,准备本轮 API/架构设计和阶段 2 双端原型。**v1.1 尚待新独立评审,旧评审不代表新版通过。**
+3. **G-D1 待用户确认本轮原型;确认前禁止产品编码。** 计划/业务规则授权不等于原型确认。
+4. **流程**:登录→试用/套餐→平台 API 异步受理→真实阶段→核验 ready→使用。人工只收款/套餐/加购确认,确认后必须平台执行器创建,不使用人工 DM 作为产品流程。
+5. **权益**:试用 1、入门固定 1、进阶 3、企业 Company 共享 5;仅进阶/企业付费增配。试用/入门/进阶均含独立云资源四件套与 Matrix,平台提供容器,规格 2 核 4G;入门月费、进阶年费含一年资源,全部价格待定/咨询。
+6. **试用**:每账号一次 48h,首容器及独立资源完整 ready 后服务端计时;到期容器数据不停不删,只锁项目使用并进入付费页,付费恢复同一容器;有效个人/企业权益不降级。
+7. **资产**:lj-test 及旧生产/历史容器全部只读。后续真实创建、计时与故障注入只用专用验收账号和新建验收容器;本轮文档/原型不创建、不修改容器。
+8. **事实边界**:当前缺少已确认可供 App 使用的实体容器创建 API。设计态不是上线。任务状态必须执行器上报,不能自然语言猜测或到点自动成功。
+
+## 一、接手次序与状态
+
+| 顺序 | 文档/产出 | 接手要求 |
+|---|---|---|
+| 1 | 本文件 + 唯一计划 v1.1 | 核对当前阶段与 G-D1,勿按旧计划人工建容器 |
+| 2 | changes/CR-20261125-02-平台容器与试用异步开通.md | 读最新确认规则及覆盖关系,不重复征询已定事项 |
+| 3 | prd/PRD-20261125-套餐与开通体系.md v1.1 | FR-21~27 保留,FR-28 试用、29 配额、30 异步;全部 AC 待执行 |
+| 4 | prd/定价与权益-20261125-草案.md v0.2 | 价格唯一维护点;只有真实未决金额/商业细项可继续确认 |
+| 5 | docs/02-design/architecture/套餐权益与异步开通设计.md | 本轮模型/权限/资源复用与补偿设计,未实现 |
+| 6 | docs/03-interface/api/套餐与平台异步开通-API契约.md | 本轮契约设计、平台依赖与凭据安全,未确认上线 |
+| 7 | prototypes/fmode-subscription-20261125/index.html | 本轮双端原型,等待用户 G-D1 确认;假数据不作接口证据 |
+| 8 | docs/00-tracking/2026-11-25-套餐异步开通实施记录.md | 本轮动作、门禁、后续实测证据;配合操作追踪 |
+| 9 | docs/04-quality/traceability-matrix.md 与 review/ | 对应本版的新评审和 AC/实现证据;不沿用旧报告判通过 |
+
+| 阶段 | 当前状态 | 下一动作 |
+|---|---|---|
+| 0 原文档 | 原 7 项闭环(历史) | 不重做、不扩充为新版通过 |
+| 1 本轮需求/接口设计 | 业务已收口、文档 v1.1 同步,接口/架构准备 | 新独立评审及问题闭环,平台确认实现依赖 |
+| 2 双端原型 | 准备/展示;**G-D1 待确认** | 覆盖试用/付费/在途/失败/到期/恢复/企业共享状态,交用户确认 |
+| 3 产品实现 | 未开始,不得越门禁 | G-D1 后按唯一计划和平台交付依赖实施 |
+| 4 真实验收 | 未执行 | 专用账号与新资产全 AC 实测,回填矩阵、评审与留痕 |
+
+## 二、必须保持一致的模型与安全边界
+
+- 任务五状态:queued / provisioning / verifying / ready / failed。
+- 六阶段:entitlement / cloud / matrix / container / connectivity / verification。平台执行器结构化上报;前端不能解析 DM 文本或按倒计时改变业务状态。
+- 配额:Company 共享企业基础 5 个;在途任务原子预占;幂等、刷新/换设备恢复、失败复用资源与对账,防止重复容器或资格。
+- 48h:服务端一次 ready 起算;历史个人试用组织的旧标记不是本版自动授权依据。
+- 四件套:appId/serverURL/functionsURL/**独立资源专属凭据,绝非平台管理 masterKey**。平台管理密钥永不下发;专属凭据须独立作用域、本人、ready、二次确认后受控短时返回,默认遮蔽,不入前端静态包/日志/localStorage。
+- 若平台只返回共享管理密钥,不得算交付成功,要求平台完成资源隔离。原型用明确假值。
+- 未实测只展示阶段/已耗时;不得承诺固定完成时间。后续从请求受理至 ready 实测总秒数,参考分钟数 ceil(总秒数×1.30/60),记录样本与阶段证据,超时不自动成功。
+
+## 三、凭据位置索引(只列位置,不复录明文)
+
+| 类型 | 集中位置 | 用途与边界 |
+|---|---|---|
+| 正式账号会话/me | .claude/dev-login.json 顶层 token/me | 已有 App/平台访问配置;本轮不读取或改写凭据值 |
+| 历史测试账号 | .claude/dev-login.json 的 testAccount | 旧全链路实证资产;不得冒充后续专用新验收账号 |
+| 平台管理 masterKey | .claude/dev-login.json 的 masterKey | 管理级服务端能力;**不下发 App/用户**,本轮不改凭据 |
+| 历史测试 Matrix 身份 | scripts/.tmp-prov-raw.json | 历史联调结果,不复制到文档/原型,不用它触发生产动作 |
+| 发布存储凭据 | scripts/deploy.mjs 的集中配置位置 | 仅既有部署用途;本轮不部署、不修改 |
+| 容器运行凭据 | 各容器 /opt/data 内的配置与 .env | 不经本轮文档交付,不登录/修改容器;旧接口资料不复录凭据 |
+
+本表只是索引,不是访问或写操作授权。不得把平台管理 masterKey 与用户独立 backend 的资源级凭据混为一谈;不得从旧脚本/文档向原型填入真实凭据。
+
+## 四、容器资产快照与禁止动作
+
+| 容器/资产 | 识别与历史用途 | 本轮及后续边界 |
+|---|---|---|
+| 主容器 agent-node | 历史协作枢纽,持 R730 SSH 通道;container-provision-from-source v2.2.0 历史封装 | **只读**;不得为本产品通过 DM 请求其创建/修改容器 |
+| agent-node-lj-test | 真身 agent-node-u19170119836,objectId zGDCmgNQcd;旧容器交互基线 | **只读**,不得用于新建/故障注入/计时验收;禁止误用另一个 agent-node-app-lj-test-v1 |
+| agent-node-app-test-0001 | objectId K0jXgRmdHe;2026-11-24 个人线实证,历史心跳补丁 | **只读**;旧授权不自动延伸至本轮改状态或计时 |
+| agent-node-app-harness-test | 既有 harness 基线资产 | 保留,只读,不清理 |
+| agent-lj | 用户生产主容器 | 只读,不触碰运行状态 |
+| 其他历史/他人/探针容器 | agent-node-liujun、5d63c5bf2cd9、__probe__ 等 | 一律不改、不清理 |
+| 后续专用验收账号/新容器 | 待平台实现和门禁具备后按唯一计划创建 | 只在该新资产内计时、故障注入、到期续用;资产 ID/权限/证据留痕 |
+
+旧容器状态的心跳周期与新交付核验超时不是一个概念:既有常规心跳周期约 1h + 0~15min 抖动,App 现状阈值 80min stale / 120min dead;历史交付核验要求真实心跳落库的短窗口,需在新设计中核对,不能照搬成创建总时长承诺。
+
+## 五、历史技术事实的使用方式
+
+- docs/03-interface/容器创建完整流程-接口与提示词-20261124.md:历史人工/局部接口实证,不是新版产品流程的执行依据。
+- docs/03-interface/容器接入完整指南-v2-20261111.md:Matrix 接入、实际收发、reaction 等参考。历史 ✅ reaction 是聊天回合信号,**不是新任务 ready 的来源**。
+- docs/03-interface/需求-同公司共用容器-20261112.md:同公司共用、各成员使用自己 Matrix 身份。
+- scripts/onboard-user.mjs、scripts/create-test-account.mjs:历史脚本阅读参考;本轮不要执行有外部写入的命令,不把 --send/DM 路径包装成产品。
+- 平台支付逆向文件仅作线索,契约未核对;本期人工确认不等于已接在线支付。
+
+常见坑:个人无企业列表应按 mine 权限;管理接口可能返回混合资源或敏感字段,必须服务端过滤;偶发网络/平台错误不等于业务失败,查询持久化任务恢复,不能盲重放创建。
+
+## 六、交接完成边界
+
+本轮文档同步完成不等于功能完成。后续必须新独立评审、G-D1 原型确认、平台实现、产品编码、全部 AC 实测、追溯和留痕齐全后,才可按 DoD 宣称功能完成。任何未验证/未实现项明确披露,不自动提交、发布或改生产资产。
+
+## 七、变更历史
+
+| 版本 | 日期 | 内容 |
+|---|---|---|
+| v1.0 | 2026-11-25 | 初始套餐任务与容器资产交接 |
+| v1.1 | 2026-11-25 | 最新业务/配额/48h/平台异步任务、平台凭据隔离、阶段与原评审边界、旧资产只读及新验收资产规则 |

+ 12 - 0
docs/00-tracking/当前进度-给AI接手.md

@@ -1,5 +1,17 @@
 # 项目当前进度(AI 接手必读)
 
+> **🆕 2026-11-25 套餐任务快照(本段为当前口径)**:先读
+> `docs/00-tracking/AI接手说明-套餐体系与容器资产.md` v1.1;唯一执行基准为
+> `docs/02-design/plans/2026-11-25-套餐体系任务计划书.md` v1.1,最新变更为 CR-20261125-02。
+> 阶段 0 原评审 7 项已闭环;当前阶段 1 业务裁决收口、接口/架构设计与阶段 2 双端原型准备。
+> **v1.1 待新独立评审;本轮 G-D1 待用户确认原型,确认前禁止产品编码。**
+> 平台提供试用/入门/进阶容器及独立云资源四件套和 Matrix;试用 1、入门固定 1、进阶 3、企业 Company 共享 5,进阶/企业可付费增配。
+> 一次 48h 试用从首容器及资源完整 ready 后服务端起算,到期容器数据不停不删,仅锁项目使用并进付费页,付费恢复原容器;有效个人/企业权益不降级。
+> 首期仅收款/套餐/加购确认人工,确认后的创建由平台 API 异步执行;实体创建 API 尚无已确认实现,设计不能当上线。
+> 五状态/六阶段以执行器结构化上报为准,不解析自然语言、不按时间自动成功;未实测只展示阶段,新验收资产实测总时长上浮 30% 后向上取整作初始参考。
+> lj-test 与旧生产/历史资产只读;后续创建/计时仅专用新验收资产。平台管理 masterKey 永不下发,凭据仅位置索引。价格唯一维护点为定价草案 v0.2,全部待定/咨询。
+>
+> **以下为原项目历史快照,保留原记录:**
 > **最后更新:2026-11-23 下午(开屏代码动画 + APK/官网上线)**
 > **最新一轮**:
 >   · `2026-11-23-修改留痕-开屏动画改纯代码动画.md` —— 用户裁决不用视频/图片,

+ 891 - 0
docs/00-tracking/操作追踪.md

@@ -8514,3 +8514,894 @@ URL 不会重复显示:`chat.service.ts:2349` 的 `stripLinks` 会把已提取
 - 移除本轮新增组件、测试、PC审查脚本和文档/图库;恢复原Toast及双端退出组件。
 - 保留上一轮移动端布局、触达、输入法和外观恢复优化,以及原有两份未跟踪原型;保留review:mobile与verify:mobile-ui入口。
 - 回退验证:生产构建通过;1875/1875 单测通过;桌面及本轮共享组件已无工作区diff,未遗留新增组件引用;git diff --check通过。
+
+## 2026-11-24 · 容器开通链路实测 + lj-test 迁移调研(容器一键接入第一步)
+
+| 项 | 内容 |
+|---|---|
+| 起因 | 用户要求先测试「如何在我们服务器上开通容器,并按 lj-test 逻辑迁移」;此前已完成三路调研(lj-test 两轮只读盘点、企微 workshop 范式、App 侧链路),方案已批准(计划文件:容器一键接入 fmode harness 基线包 + App 添加分身) |
+| lj-test 盘点结论 | 配置分层清晰:通用层(config.yaml、11 个插件、4 个 shell hook、.fmode-media-patch、patches、fmode 技能族)/ 个人层(SOUL.md、.env Matrix 身份段、FMODE_SESSION_TOKEN、企微凭据)/ 垃圾层(15 个 .bak、diag-* 等);SOUL.md 当前是 Hermes 默认行为准则,无分身个性 |
+| 开通实测 | 用测试名 `agent-node-app-harness-test` 走完平台侧全链路:xlosi3m46q 自动建记录(objectId=ffqW3yMaoc,归属 xhVRjTMwQH/E4KpGvTEto ✅)→ provision 建身份(@ffqw3ymaoc:fmode.cn)+房间+绑定(jMkLWft8T3)→ 派生密码规则1登录 ✅ → whoami ✅ → join 房间 ✅ → 收发闭环 ✅。唯一缺口=docker 建容器本身(主容器能力) |
+| 产出 | `docs/03-interface/给主容器-建harness-test容器并按lj-test迁移-20261124.md`——可直接发给主容器(刘雨飏)的整段指令:建容器(--hostname/--entrypoint 挂 .fmode-media-patch)+ 从 lj-test docker cp 通用层 + 全新 .env + cron 两 job + DNS 体检 + 验收清单;平台侧 6 步实测证据附文末 |
+| 涉及脚本 | bind-container.mjs bind/prompt/status(未改代码,仅使用) |
+| 遗留 | ① 等主容器建容器后 `bind-container.mjs status agent-node-app-harness-test` 应转全绿 ② 主容器触达通道=用户转发给刘雨飏(本机无法直连主容器)③ bind-container.mjs 的 prompt 仍是旧版(六键 + ALLOWED_USERS=主人写法),待按基线包方案重写为两段式 ④ 基线包(harness/)本地开发未开始 |
+
+## 2026-11-24 · 容器创建全链路自动化(个人无企业版)——测试账号 + onboard-user.mjs
+
+| 项 | 内容 |
+|---|---|
+| 起因 | 用户两轮裁决:①不绑企业(个人默认无企业,openyd-join/git-join 仅参考)②不做短信登录,直接建模拟测试账号,先确认创建完整,再实现完整接口流程自动化部署开通容器 |
+| 主容器调研突破 | 任务 berl62ti4 DM 取证(存档 scripts/.tmp-master-node-inventory.md):agent-node(@bnqaoxqhe8:fmode.cn)**不是**有 docker 权限的运维容器,而是普通业务容器,但持有 r730_root.py SSH 通道(server.fmode.cn:18001→R730)可在宿主 docker run;建容器 SOP 在其 skill-lifecycle/references/;准入全开(ALLOW_ALL、无白名单)DM 直达 ✅;cloud.sh 不存在(旧线索作废);lj-test 补丁来源只剩宿主侧取证点 |
+| 雨飏001 三问题排查 | 用户转来运维001报告(Matrix 丢 thread / 主会话 73 万 token / plugin-tips-cn 重复包裹),经时间线(问题发生于 11/23 20:17,我们首次 DM 在 11/24 10:16)与机制(DM 独立房间不走 thread、独立会话不占主会话)双重排除——**与本项目操作无因果**,已在对话中向用户说明 |
+| 阶段一 ✅ | `scripts/create-test-account.mjs`:masterKey 直建 _User(username=fmode19900000001、无 company)→ login 拿 token → 4 项自检(users/me/无企业断言/_Session/Profile 0 条)→ 落盘 .claude/dev-login.json testAccount 槽位。objectId=cq0IH6Limu |
+| 阶段二 ✅ 平台侧 | `scripts/onboard-user.mjs`:登录态(token 失效自动重登)→ [--with-cloud] trial-standalone 轮询 → FmodeAgent 记录(无 company)→ provision → 生成主容器指令 → [--send] DM agent-node → 验收轮询。测试容器 agent-node-app-test-0001(objectId=K0jXgRmdHe、roomId=!hLVCNPgJhfaMTajfcgggbnlgCoXKLUWWwOKjPZzkos0、bindingId=ZRgcVi4UoU)平台侧就绪,指令与绑定一致 |
+| 踩坑修复 | ①入口层坏后端三形态:403 / 301→:7460(已下线)/ unauthorized,随机命中——全脚本统一 redirect:'manual'+8 次重试 ②坏后端把「记录存在」误报 404 导致重复建记录(实测建出 K0jXgRmdHe+d8oxe9H6gw 两条,误建已删)——ensureAgent 加创建前二次确认(重跑立即立功)③scope:'all' 需管理员角色,个人无企业账号必须 scope:'mine' ④已有绑定时 provision 缓存命中可取主人 Matrix 凭据(--send 依赖) |
+| 产出文档 | `docs/03-interface/容器创建完整流程-接口与提示词-20261124.md`(全链路接口契约 + docker run 规范 + 指令模板 + lj-test 三层迁移口径 + 已知缺口) |
+| 遗留/未验证 | ①--send 已 DM agent-node 建容器,回报中(见 自动开通回报-agent-node-app-test-0001-*.md)②容器建成后 bind-container status / onboard ⑦验收应转全绿 ③--with-cloud(trial-standalone)接口已实现未实测 ④测试账号/记录/容器残留待测完统一决策清理 ⑤雨飏001 三个待决问题(MATRIX_AUTO_THREAD/会话压缩/tips-cn)属刘雨飏侧 |
+
+## 2026-11-24 · 平台入口层坏后端石锤 + App 请求层抖动重试
+
+| 项 | 内容 |
+|---|---|
+| 起因 | 用户在 ai.fmode.cn 测试报 `/api/functions 401`、`/parse 403`、重新登录无效,要求查因 |
+| 石锤实验 | 全新 session(/parse/users/me 验证有效)1 秒内调 /api/functions 出现 **401/200/401 交替**;有效 token 连测也有全好时段——证实 HAProxy 后端池约半数坏实例,对有效 token 随机拒绝:functions→假 401、parse→假 403、另有 301→已下线 :7460。形态与当日脚本侧观察一致 |
+| App 修复 | `parse-api.ts rawFetch()` 增加坏后端抖动重试:/parse/** 与 /api/functions 的 401/403(及幂等请求的网络错误,含 301→死端口形态)最多 4 次(300/700/1500ms),全失败才按真失败处理,真过期/真无权限语义不变;非幂等 POST(除 functions)不重试 |
+| 测试 | parse-api.spec 新增 4 用例(两次 401 后成功/4 次全 401 抛登录失效/parse GET 403 重试成功/登录 POST 不重试);parse-api 64/64、全量 1938/1938 通过 |
+| 容器链路联动 | 主容器复验上报时撞同款 401,误判「token 未生效」——已告知其为坏后端抖动并给出重试口径(8 次×1.5s);区分业务真 403(归属校验失败文案)与网关假 401/403 |
+| 平台建议 | 根治需平台运维排查 HAProxy 后端池(坏实例三形态:403/301→:7460/假 401);中期方案=App 的 /api-platform 代理落地(同源+后端固定),见 platform-proxy.service.ts |
+| 遗留 | ①ai.fmode.cn `/desktop/contacts` 404(SPA 回退或部署版本旧,与本次无关,另记)②两条陈旧邀请房间 join 500(可 reject 清理,待用户决定)③App 修复需重新部署 ai.fmode.cn 才对线上生效 |
+
+### 2026-11-24 主容器首跑 CREATE-DONE 收尾
+
+- **内容**:主容器(agent-node)首跑建容器 `agent-node-app-test-0001` 全链路 CREATE-DONE,验收全绿(whoami @k0jxgrmdhe:fmode.cn / joined_rooms 含 DM 房 / 收发回读 / DNS 18ms / HEARTBEAT_PUSH_OK / cron failure_streak 34→0),共处置 9 个问题并固化为技能「container-provision-from-source」。
+- **9 个坑已回写** `docs/03-interface/容器创建完整流程-接口与提示词-20261124.md` §七(迁移源空壳、AGENT_ID 污染、dashboard 认证三件套、RES_OPTIONS 注入点、docker env 双写核对、401/403 两性质重试、cron 缺个人层脚本、SSH retry 封装、品牌「我是 Hermes」待裁决)。
+- **平台侧复核**:FmodeAgent `K0jXgRmdHe` channels.matrixConfig 已写入(manual-unblock 临时解锁 App 视图,待 reporter 补丁后真实上报覆盖),App 端「未接入」解除。
+- **待用户决策**:① 品牌口径(容器回复自称 Hermes,SOUL.md 人格缺口)② 测试账号/记录/容器残留是否清理。
+- **涉及文件**:docs/03-interface/容器创建完整流程-接口与提示词-20261124.md、docs/03-interface/自动开通回报-agent-node-app-test-0001-202611240327.md
+
+### 2026-11-24 品牌口径修复(SOUL.md 人格化)
+
+- **背景**:首跑踩坑 §七-9「容器回复自称 Hermes」——用户裁决「现在就修」,DM 主容器执行。
+- **根因**:`/opt/data/SOUL.md` 667B 出厂默认英文模板("You are Hermes Agent, built by Nous Research"),是 `load_soul_md()` 的 identity slot #1(最高优先级,压制 default_soul.py 兜底)。
+- **处置**:新写 SOUL.md 1549B(备份 `SOUL.md.bak-apptest-20261124-132743`),口径「我是测试分身0001,主人的 Fmode 分身」;绕开 `is_legacy_template_soul()` 自动还原机制(写入明确自定义内容,已验证 False);服务重启 PID 167→567。
+- **验证**:`hermes -z` 单次执行问「你是谁?」走完整 SOUL 注入链路 → 回答「我是测试分身0001,主人的 Fmode 分身」,底层词 0 命中、两次一致;DM 房收发正常、gateway connected、两 cron job ok。CREATE-DONE + ✅。
+- **范围**:仅 agent-node-app-test-0001;lj-test / u19170119836 全程只读。
+- **小坑**:主账号在测试账号创建的 DM 房发言被 M_FORBIDDEN 拒(房间权限层级),改用创建者测试账号身份发指令。
+
+### 2026-11-24 下午 线上「回复慢+报错风暴」诊断与修复
+
+- **现象**:用户 App 发「你是谁」80s+ 无回复;控制台 matrix.fmode.cn 403 风暴 + /api/functions 401 风暴。
+- **根因(三实锤)**:
+  1. **绑定凭据错配**:转属主时绑定表改了 userPointer/userMxId 但 accessToken/deviceId 还是测试账号的 → App 拿「测试账号 token + 主账号 userId」→ Matrix 带 userId 接口 403 风暴、sync 残废。容器侧日志证实:消息以 @cq0ih6limu 身份发到新房,容器 6.9s 已正确回复「我是测试分身0001,主人的 Fmode 分身」,App 收不到。
+  2. **用户跑的是旧包**:浏览器缓存旧 index.html 引用已删 chunk(U87TEMDK,线上已 404),无坏后端重试修复。
+  3. **坏后端新形态**:/api/functions 开始随机 500(8 连打实测 500/200 交替)。
+- **修复**:
+  ① 绑定表 ZRgcVi4UoU 的 accessToken/deviceId 换成主账号有效凭据(whoami 验证一致),并把主账号拉进新房间取回容器回复;
+  ② parse-api.ts 抖动重试扩展 401/403/**500**(+1 测试);
+  ③ deploy.mjs 部署后给 index.html 写 Cache-Control:no-cache(⚠️ obsutil cp 会把对象 ACL 重置私有、整站 403,已补 chattri public-read 并写进脚本注释)。
+- **踩坑**:手动验证 cp -meta 时踩了 ACL 重置坑,线上 403 约 1 分钟,已即时恢复。
+- **涉及文件**:src/app/core/api/parse-api.ts、src/app/core/api/parse-api.spec.ts、scripts/deploy.mjs、docs/03-interface/容器创建完整流程-接口与提示词-20261124.md(§七-10)
+- **待部署**:②③ 需重新部署生效;①已生效(用户强刷+重新打开会话即可)。
+- **平台建议**(待上报):provision 返回缓存凭据前 whoami 校验一致性;HAProxy 坏后端池(401/403/500 三形态随机)。
+
+### 2026-11-24 请求量优化 + 会话等待提示去重
+
+- **问题①(用户反馈 /api/functions 请求太多)**:排查全部调用点,稳态来源只有 LiveService 15s 轮询(≈5760 次/天,坏后端抖动期还有重试放大);provision 随开会话触发,任务/成果面板按 agent 一次性加载有缓存,relay 轮询走本地 timeline 不发网络请求。
+  **优化**(live.service.ts):
+  ① 安静期退避——数据连续未变时节拍 15s→30s→60s 封顶,有变化/手动刷新/回前台立即复位(容器跑活时数据每轮都变,天然保持快节拍);
+  ② 标签页隐藏暂停——document.hidden 空转节拍不发请求,回前台立即补一轮;
+  ③ 失败轮次按「未变」退避(故障期不给坏后端加压)。
+  setInterval 改 setTimeout 链以支持变长节拍。预计安静期请求量 -50%~-75%,后台标签归零。
+- **问题②(用户截图红框:「已送达·正在思考…(3s)」与「已处理 3s·继续处理任务过程」并存)**:
+  根因 = assistant-turn 组件卡片级等待行(card-wait)与卡片头(card-running)判据独立,live 且无正文的窗口期两者并存(2026-11-14 删段级重复块时漏了卡片级这条)。
+  修复:thinking() 在「卡片头已接管」(live 且秒数>0)时返回空,只保留首秒内「正在思考…」的早期反馈。
+- **双端一致性结论**:桌面/移动/群聊共用同一 app-assistant-turn 组件与同一 pulse 文案口径,逻辑无分叉;差异仅是状态提示位置(移动端在顶栏故传 hideRunningHint 隐藏卡内提示,桌面端无顶栏故保留卡内)——本次修复后两端「同一句信息只出现一次」。
+- **涉及文件**:src/app/core/live.service.ts、src/app/core/live.service.spec.ts(+4 用例)、src/app/components/domain/assistant-turn/assistant-turn.ts、assistant-turn.spec.ts(改写 1 用例 +新增 1 用例)
+
+### 2026-11-24 请求风暴第三道防线:会话文件台账重拉去抖(四个聊天页)
+
+- **现象**:用户截图线上仍「密密麻麻 function 请求」,45 秒 710 个请求 / 16.2MB,卡顿持续很长。
+- **根因**:四个聊天页(桌面/移动单聊 + 桌面/移动群聊)的 effect 依赖 `messages().length`,Matrix 首次同步回放几百个房间时消息数连续变化,每次都直接调 `loadSessionFiles()` → `deliverables.loadSplitForSession/Group` → **无缓存的** `fetchFilesBySession/Group`(/api/functions)。前两道防线(untracked 防自我唤醒、sameIds 防重写信号)防不了「回放期间 count 连变」这条路径。
+- **修复**:四个页面统一加 `scheduleSessionFilesReload(sid)` —— **切会话立即拉**(用户等着看右栏),**同会话消息变化去抖 2s 尾随拉一次**;`ngOnDestroy` 清定时器防泄漏。群聊 effect 顺带补 untracked(原来没有)。双端/单群四处同口径、注释互链。
+- **附加清理**:主账号退掉两个失效邀请房间(`!iF4KdUf8…`、`!5eQmqMIW…`,join 恒 500「No server available to assist in joining」),消除每次同步的 join 500 噪声。
+- **验证**:`npm test` 1943/1943 全绿。
+- **涉及文件**:src/app/desktop/pages/chat/chat.ts、src/app/mobile/pages/chat/chat.ts、src/app/desktop/pages/group-chat/group-chat.ts、src/app/mobile/pages/group-chat/group-chat.ts
+- **效果预估**:同步回放期间 /api/functions 从「每消息一次」压到「每会话一次 + 尾随一次」。
+
+### 2026-11-24 请求风暴复查:本地真实账号实测,新代码无风暴
+
+- **背景**:去抖修复部署后用户仍截图「几千条 functions 请求」(636/18s、1397/55s)。
+- **本地实测**(Playwright + 真实账号 dev-login 注入 + 系统 Chrome,脚本 scripts/.tmp-storm-repro*.mjs):
+  ① 只开 /desktop/chat(无会话):31 次/60s;
+  ② 注入指向 lj-test DM 房间**真实 thread 根**(`$approot_mwpy71ml_8loki4ia:fmode.cn`)的会话、直开会话页 + 滚顶触发历史分页:57 次/90s(0s 桶 42 次突发后立即安静)。
+  两轮均无风暴 → **当前部署代码在「加载历史」场景下请求量正常**。
+- **结论**:用户浏览器仍在跑**旧包**(旧 index.html 无 Cache-Control 时被启发式缓存,polyfills-UB7TEMDK 哈希跨构建不变、无法据此区分新旧)。线上 main-J3IJUIYB.js 与本地 dist 一致、index.html 已 no-store。
+- **次要发现( backlog )**:会话目录 `oR5O67i1Cm·list` 首屏被调 41 次(8 容器 × 多轮 reloadAll 叠加),可再做一轮收敛;另 13/57 响应为 401(入口层坏后端,rawFetch 内部重试已兜住)。
+- **坑**:复现脚本第一次用自造会话 id,`belongsToSession` 认不到任何历史消息 → 白测一轮;会话 id 必须等于房间里真实的 thread 根事件 id。
+
+### 2026-11-24 雨飏001(agent-node) 加入飞码AI + Matrix 通信实测
+
+- **用户诉求**:① 与雨飏001 通过 Matrix 通信实测;② 把该容器加入「飞码AI」公司;③ 解释通讯录为何不显示。
+- **定位**:雨飏001 = `agent-node`(objectId `bnQaoXQhE8`,Matrix `@bnqaoxqhe8:fmode.cn`),归属 刘雨飏(sr2WiPsDyQ)、公司原为 脑控科技(rpnXZC1loU)。
+- **通讯录不显示的原因**:App 登录账号 xhVRjTMwQH(用户9836) 角色为 `E4KpGvTEto_Admin` → 请求 `scope=company`,云函数按 company 字段强制过滤;agent-node 公司指针是 rpnXZC1loU → 天然不在列表。前端/权限无 bug。
+- **改归属公司**:云函数 `xlosi3m46q` op=update(field=name 原值无操作写入 + `companyId=E4KpGvTEto`,超管路径,useMasterKey 落库)。归属用户不变(仍 sr2WiPsDyQ),ACL 由 `_buildACL(刘雨飏, E4KpGvTEto)` 重建(刘雨飏保留直接 RW,新增飞码AI Admin RW / Public R,原脑控科技角色授权为不存在的空授权、被替换)。
+- **复验**:`scope=company` 单查 agent-node 即刻命中(code 200,company=E4KpGvTEto)→ App 通讯录(公司视角)刷新即可见。
+- **Matrix 通信实测**:走**既有绑定房间**(`Afwjybkv8D` / `!cllVY1tFMmGKpnoVuI8oHmj3OEYNbbOxV6RiCNNy9dg`,今晨 provision 已建),脚本 `scripts/.tmp-dm-agent-node.mjs`:发送 → 容器先打 👀(收到)→ 正文回复「通信测试消息已正常接收…」→ ✅ reaction。**双向链路正常**。
+- **⚠️ 回写实锤(当日复查)**:约 1 分钟后容器心跳(lastField=extra,heartbeatAgeSec 58s)即把 company 回写为 rpnXZC1loU(脑控科技)、ACL 同步重建——云函数 update 分支「未显式传 companyId 时把 company 重置为调用者公司」的语义所致(fmodeagent-status.js:467/485)。**公司归属要稳住必须二选一**:① 容器 reporter 上报显式带 companyId=E4KpGvTEto(需刘雨飏侧改 /opt/data 配置);② 平台改云函数为「仅显式传 companyId 或记录无公司时才写 company」(治本但动生产共享函数)。另观测到一次网关返回 2026-09-23 的陈旧响应(坏后端疑似有旧缓存,仅记录)。
+
+### 2026-11-24 请求风暴根治:回合事件新鲜度门禁 + live.load 节流(780 → 44 实测)
+
+- **根因实锤**(复现脚本 v4,真实账号 + lj-test 真实 896 条消息会话 `$approot_mwln4ryj_hrbkyix0:fmode.cn`):
+  打开会话 + 滚顶翻历史 10 轮,120 秒内 **780 次 /api/functions,其中 743 次 xlosi3m46q·query**(0s 桶突发 614 次)。
+  来源:`chat.service.ts` 的 `onTurnReaction` / `onTurnStatus` 回调每条事件都 `void this.live.load(true)`——
+  Matrix `Room.timeline` 对**翻页加载的历史事件同样触发**,历史里几百个 ✅/turn_status 逐条各拉一次云函数。
+  与用户截图「只要加载历史数据记录就几千条请求」完全吻合。
+- **修复**(`core/chat.service.ts` + `core/matrix-client.service.ts`):
+  ① `onTurnReaction` 回调新增第 4 参 `at`(`ev.getTs()`;`onTurnStatus` 原本已传);
+  ② 新增 `isFreshTurnEvent(at)`:事件时间戳须在 [now-2min, now+30s] 窗口内,缺失/非法一律判不新鲜——
+  两个回调第一行即 `return`,历史回放事件**完全不触发**云函数刷新(口径沿用 task-completion-notification 的同款门禁);
+  ③ 新增 `requestLiveRefresh()`:2 秒节流合并,替换原 3 处 `void this.live.load(true)`。
+- **验证**:
+  ① 单测 1943/1943 全绿;
+  ② 同一复现脚本重跑:**44 次/140s,xlosi3m46q·query 仅 5 次**(780 → 44,-94%;743 → 5,-99.3%),
+  剩余调用均为首屏正常项(chatThreads/文件台账/me 等)。
+- **部署**:`npm run build` → `node scripts/deploy.mjs`,探活全过,CDN 刷新任务 8282635706。
+- **遗留 backlog**:`oR5O67i1Cm·list` 首屏仍 18~41 次(多容器目录逐轮 reloadAll 叠加),下一轮做首屏合并。
+
+### 2026-11-24 首屏合并:reloadAll 按容器去重(chatThreads·list 18 → 10)+ 主容器 skill v2.0.0 验收
+
+- **背景**:风暴根治后复现脚本显示首屏 `oR5O67i1Cm·list` 仍有 18 次(backlog 项)。
+- **根因**:桌面左栏/消息页/首页/抽屉/群聊深链多处首屏触发 `reloadAll`;原 per-agent 在途复用
+  只能拦「同一时刻并发」,拦不住「前一批刚完成、下一处又发起」的串行重复;且首屏容器逐个
+  matrixReady,入参集合一直在变,**集合级**去重(首版实现)一轮都拦不住。
+- **修复**(`core/chat-session.service.ts`):
+  ① `reloadAll` 增加 `opts.force`;② 每个容器成功拉取后记时间戳(`agentHydrateOkAt`),
+  TTL 10 秒内的容器直接跳过、只拉新增/过期者;③ 拉取失败不记时间戳(重试不被卡死);
+  ④ 同键在途复用保留。用户显式刷新(session-tree 重试按钮 / messages 下拉 / share-receive)
+  三处传 `force` 绕过。
+- **验证**:单测 1947/1947 全绿(新增 4 条首屏合并用例);同一复现脚本 list 18 → 10
+  (= 5 个 ready 容器 × 活跃+已删各 1,恰为一轮,无重复),总量 44 → 35。
+- **部署**:build → deploy.mjs,探活全过。
+- **主容器 skill 任务回报**:`container-provision-from-source` 升级 v1.0.0 → **v2.0.0**
+  (SKILL.md 22.6KB 15 章 + 可独立调用的 `verify_container.py`),8 项核验清单、10 坑全内联。
+  对 test-0001 只读体检 6/8 通过、1 跳过(① 缺 owner 凭据,符合「缺一停开工前」设计)、
+  **1 真实缺陷:④ 心跳线程已启动但到点推送被入口层 401 吞掉后整周期不复**(heartbeatAt 停
+  在 16:05,存活 13000+ 秒无新心跳;手动触发推送成功 → 链路费通、是静默失败)。
+- **裁决已回发主容器**:缺口 1(交付前必须等到真实心跳落库)与缺口 3(reaction 从信息项
+  升为判定项,DM/群房同标准)采纳并补进 skill;④ 心跳重试修复**暂缓**(需重启容器、
+  触碰 test-0001 运行状态,超出本次授权,列入平台问题清单待用户裁决)。
+- **平台问题清单新增**:心跳推送被 HAProxy 坏后端 401 吞掉 → 插件 `_heartbeat_loop` 只记日志
+  不重试 → 最长一个心跳周期(~1 小时+jitter)无心跳。建议容器插件侧加推送重试 +
+  平台侧修坏后端池(治本)。
+
+### 2026-11-24 主容器 skill 终版:v2.1.0(两项裁决改进已落地)
+
+- **v2.0.0 → v2.1.0** 变更:
+  ① 核验 ④(心跳)改三态:≤120s ✅ / gateway 存活 <3600s 记 **pending**(读 /proc/PID/stat 算真实存活)/
+  ≥3600s 仍不新鲜 ❌;SKILL.md 写入硬要求「交付前必须等到至少一次真实心跳落库」;
+  ② 核验 ③ reaction 升为**判定项**:DM/群房同标准,必须「有回复且有 ✅/✔ reaction」才算过,
+  附四项排查方向(on_processing_complete / MATRIX_REACTIONS / plugin-turn-end / 陈年历史房需新建回合验证)。
+- ④ 心跳重试修复按要求未动(test-0001 运行状态未触碰);① owner 凭据「缺一停开工前」保持。
+- 文件:`SKILL.md` 24,738B v2.1.0 + `scripts/verify_container.py` 17,777B(py_compile 通过)。
+- **至此「容器创建+核验 skill 封装」任务闭环**(用户 2026-11-24 裁决的第二条任务)。
+
+### 2026-11-25 心跳静默失败修复:源码核实 + 授权主容器实施
+
+- **周期核实(用户质疑「1.5H±20min」)**:本地三处留痕(`scripts/.tmp-ljtest-prompts-inventory.md:244`
+  插件盘点、2026-11-09 修改留痕、App 阈值设计)均为 **1h + 0~15min 抖动**;主容器原样贴回
+  迁移层 `plugin-active-reporter/__init__.py` 源码坐实:`interval = 3600 + uniform(0,900)`(启动时
+  随机一次后固定,env `ACTIVE_REPORT_HEARTBEAT_SEC/JITTER` 可覆盖)。「1.5H±20min」查无此据,
+  最接近者为 App 旧阈值 `ALIVE_DEAD_SEC=90min`(2026-11-09 已改 120min)与坑#6 的 8×1.5s 重试。
+- **缺陷机制源码级坐实**:`_call()` docstring 原文「单次尝试,不重试」;`_push_with_sessions`
+  返回 False 仅用于日志(`ok=%s`),异常分支只 `_log`,随后照常睡满 interval —— 一次入口层
+  401 被吞 = 最长约 2 小时无成功心跳(越过 App 80min stale / 120min dead 红线 → 假离线)。
+- **用户裁决(2026-11-25)**:授权主容器立即修复。任务已下达(DM event
+  `$-annf5zFiR8a9tyUxFJVPBQNHLSqfxUYKeQKxczbo4c`),口径:
+  ① 失败路径加 8×1.5s 重试(仅入口层/网关类失败,业务 4xx 不重试);
+  ② 8 次仍败改睡 300s 补推,成功即恢复 interval(持续失败则 300s 一轮);
+  ③ 启动即推一次心跳再进循环(修掉重启后最长 75min 盲区);
+  ④ 补丁写回 skill 迁移层 + SKILL.md changelog;
+  ⑤ 边界:只动 test-0001 该插件文件,lj-test 只读不碰。
+- **验证要求**:最小重启(gateway 级)+ 至少一次真实心跳落库(heartbeatAt ≤120s)贴证据。
+- 当前状态:等主容器回报(监听器后台运行)。
+
+### 2026-11-25 官网 Mobile 与扫码下载优化
+
+- 用户要求:官网补齐 Mobile 端,保留扫码与点击下载,并优化使用体验。
+- 先记录方案与验收:`docs/02-design/plans/2026-11-25-官网移动端与扫码下载优化.md`,仅调整 `prototypes/fmode-download-20261120/` 独立官网下载页。
+- 手机端重新设置单栏内容、文字大小、产品演示、44px 以上主要触控区域、移动导航和带安全区的下载底栏;保留黑曜石暗色与薄荷绿视觉。
+- 首屏 / 下载区 / 手机底栏均提供直接下载和扫码入口;下载区常驻真实二维码,弹窗支持放大与复制链接;所有入口与二维码共用现有 `FMODE_SITE.apkUrl`。
+- 本地内嵌 Nayuki v1.8.0 MIT 编码器生成 PNG,不新增 npm 包或第三方运行时请求。增加 iOS / 微信提示、缺失地址说明、二维码故障与剪贴板不可用降级。
+- 构建约 199 KB 单 HTML;`scripts/verify-download-site.mjs` 18 组浏览器检查通过,覆盖 11 种宽度和 3 种短屏;OpenCV 解码原图及 PC / Mobile 页面截图通过,二维码为同一安装包地址。
+- 证据:`test-results/download-site/results.json` 与同目录预览截图。未执行生产发布、Git 提交或手机真机安装回归;未改动已有未提交业务文件。
+
+### 2026-11-25 心跳修复交付:CREATE-DONE 核验通过(skill v2.2.0)
+
+- **主容器交付**(test-0001 `plugin-active-reporter/__init__.py`,33906→36008B,有 .bak 备份):
+  ① `_heartbeat_loop` 启动即推 + 失败睡 300s 补推(`ACTIVE_REPORT_FAIL_SLEEP_SEC` 可覆盖)、成功即回 interval;
+  ② `_call` 内层 8×1.5s 重试,仅入口层失败(401/403 无业务 code、5xx、超时、连接错误),业务 4xx 直接抛;
+  ③ 抽出 `_heartbeat_once()`;周期常量/抖动/turn 上报未动。
+- **最小重启**:`s6-svc -r /run/service/gateway-default`(非整容器重启),PID 567→2916,py_compile OK;
+  日志显示线程启动后 **2 秒**首推落地(旧版需等满 3706s)。
+- **我方独立核验**:`xlosi3m46q` 查询 test-0001 `heartbeatAt=2026-11-25T01:59:36Z`(134s 新鲜 ✅,
+  且晚于容器自证时间,心跳持续在推);status=idle、objectId=K0jXgRmdHe 归属正确。
+- **迁移层固化**:skill v2.1.0 → **v2.2.0**,迁移层插件 sha256 与 test-0001 运行版完全一致,
+  SKILL.md 新增 §十一点五「心跳健壮性」。
+- **收尾待回**:失败路径离线自测(mock 3×401→成功 断言重试 4 次;业务 403 断言不重试;300s 补推分支行号佐证)。
+- **HAProxy 复测**(用户追问机理):2026-11-25 01:5x 两个端点各 30 次间隔打 + 40 并发突发,
+  **100/100 全 200**——此刻入口层健康;坏后端可能已被摘除或失败率随时间波动。「坏后端」仍是
+  对「同一 token 随机成败」的外部反推(平台黑盒),治本项保留在平台问题清单。
+
+
+### 2026-11-25 官网 Mobile 与扫码下载版本重新部署
+
+- 用户授权按项目规范重新部署官网;沿用 `scripts/publish-apk.mjs --skip-apk`,只逐对象上传 `download/index.html` 和 `download/manifest.json`,发布到 `https://ai.fmode.cn/download/`。
+- 发布前构建和 18 组浏览器回归通过;旧页、旧清单、根路径 Web App 已本地备份,发布日志已脱敏。
+- CDN 任务 8289443686 完成:3/3 成功、0 失败;三个官网裸链接均 200,SHA256 与本地构建一致。
+- 线上 320/390/1440px 检查通过;二维码原图与 PC/Mobile 截图解码指向正式 APK;实际点击完整下载 10,343,681 字节,MD5 与发布前一致。
+- 根路径 Web App 发布前后哈希一致;APK 未重新上传。无 Git 提交或推送,未做真机安装回归。
+- 详见 `docs/00-tracking/2026-11-25-官网下载页重新部署.md`;证据位于 `test-results/download-site-deploy/`。
+
+### 2026-11-25 套餐与开通体系:文档先行(阶段 0)
+
+- **用户裁决(2026-11-25)**:三档套餐(入门=接入自有 Hermes agent+harness+Matrix+独立云资源,月费 /
+  进阶=平台容器 2核4G 含一年资源费,年费 / 企业版=通讯录企业账套管理);
+  本期先做 **①个人版套餐开通 ②加入企业用企业容器(流程也优化)**;
+  补充裁决四项:价格待定先定权益 / 入门含独立云资源 / 支付先人工开通占位 / 企业线流程优化。
+- **新建文档**:
+  ① `01-requirements/changes/CR-20261125-套餐体系纳入范围.md`(CR-20261125-01,已批准);
+  ② `01-requirements/prd/PRD-20261125-套餐与开通体系.md`(v1.0,FR-21~27 + AC-21.1~27.1 +
+  开放问题 Q1~Q5;FR 接 SPEC 编号,避让 SPEC 现存 FR-19 双号撞号——已知遗留不在本次修复);
+  ③ `01-requirements/prd/定价与权益-20261125-草案.md`(v0.1,权益定稿、价格待定占位、
+  成本锚点、支付分期、待裁决 D1~D6;声明为**价格唯一维护点**);
+  ④ `02-design/plans/2026-11-25-套餐体系任务计划书.md`(v1.0,执行基准:裁决快照 / 背景资料索引 /
+  容器开通完整流程(个人线 8 步 + 企业线 5 步)/ 五阶段计划 / 里程碑 M0~M3 / 风险依赖)。
+- **回填与登记**:`容器创建完整流程-20261124.md` §五「入门套餐是否含 trial-standalone」→ 已裁决(含);
+  主 PRD 升 v1.3(仅变更记录+关联引用,正文不动);`docs/README.md` 登记 4 行;
+  `04-quality/traceability-matrix.md` 补 FR-21~27(状态:需求新建)。
+- **边界**:本次只出文档,不写代码;UI 原型受 G-D1 门禁(用户确认后才编码)。
+- **待办**:评审员子代理评审(黄金规则 11)→ 用户裁决 D1~D6 与 Q1~Q4。
+
+### 2026-11-25 套餐文档评审闭环 + AI 接手说明 + 凭据集中化
+
+- **评审闭环**:评审员子代理结论「修改后通过」(0 blocker/0 major/2 minor/5 nit),
+  7 条全部当日修复(主 PRD §十补关联行+编号统一 -01、追溯矩阵元数据升 v0.5、
+  定价 D2 覆盖 Q3 加价口径、计划书 M2 含全部子项、CR 路径改真实文件名、SPEC 补 FR-21 指针);
+  报告归档 `docs/04-quality/review/2026-11-25-套餐体系文档评审-第1轮.md`。**阶段 0 完成**。
+- **AI 接手说明**:新建 `docs/00-tracking/AI接手说明-套餐体系与容器资产.md`
+  (30 秒版 / 阶段执行指引 / 凭据索引 / 容器资产清单与禁忌 / 主容器协作手法 / 坑速查 / 常用命令),
+  `当前进度-给AI接手.md` 头部加指针,`docs/README.md` 登记。
+- **凭据集中化**(规则 9):masterKey 自 `scripts/create-test-account.mjs` 硬编码迁入
+  `.claude/dev-login.json` 的 `masterKey` 字段,脚本改为从集中位置读取(缺失即报错);
+  已实测脚本全流程正常(复用账号 + 登录自检通过),回写后 masterKey 字段保持。
+
+### 2026-11-25 心跳修复收官:失败路径离线自测全通过(任务闭环)
+
+- **主容器离线自测**(importlib 加载迁移层插件,monkeypatch urlopen/sleep,未联网未碰容器):
+  ① 入口层 3×401→第 4 次成功:请求 4 次、sleep 3×1.5s=4.5s(≤12s 上限)✅;
+  ② 业务 403(带 code/mess):请求 1 次即抛、0 重试 ✅;
+  ③ 持续 401:恰好 8 次放弃、sleep 7×1.5s=10.5s ✅。总判定全 PASS。
+- **外层 300s 补推分支**佐证:`_heartbeat_loop` 第 804 行起,启动即推→成功回 interval/失败睡 300s,
+  `HEARTBEAT_RETRY_SLEEP_SEC=300`(env `ACTIVE_REPORT_FAIL_SLEEP_SEC` 可覆盖)。
+- 自测脚本已归档进 skill 资产(`scripts/test_heartbeat_failpath.py`)。
+- **至此「心跳静默失败修复」任务完整闭环**(补丁→重启→真实心跳落库→我方独立核验→失败路径自测→迁移层固化 v2.2.0)。
+- 备注:监听器关键词门控未命中报告字面量导致空转,已手动停止;结果本身 02:03 已到达。
+- **另观测**:另一会话正在执行套餐任务(`2026-11-25-套餐异步开通实施记录.md`),
+  含新裁决(试用 48h、配额 1/3/5、平台异步创建、到期仅锁定付费恢复);
+  本会话不再改动套餐文档,避免与并行会话冲突。
+
+
+### 2026-11-25 套餐异步开通:G-D1前置文档、契约与交互原型
+
+- 用户授权实现已确认计划;仍按G-D1先交文档/API设计/双端原型,确认后产品实现。
+- 唯一计划/PRD升v1.1、定价权益v0.2、新CR-20261125-02;FR21~27保留,新增FR28试用、FR29配额、FR30异步任务;接手、README与矩阵同步。
+- 新API和架构设计区分现有资源接口与拟新增容器任务接口,明确原子配额/outbox、执行器租约、本人专属凭据、存量迁移与App到期锁边界;未部署任何新接口。
+- 独立原型prototypes/fmode-subscription-20261125/index.html已生成:试用/套餐、等待、失败重试、离线延迟、名额增配、个人企业主体切换、接入参数、到期恢复。无真实平台调用或凭据。
+- 浏览器评审检查18组通过,覆盖8宽度与浅深色、主体隔离及同容器恢复;报告test-results/subscription-prototype/results.json。文档全目录结构检查通过。
+- 独立需求/设计初审发现6项问题,已逐项修复并提交定向复审:个人企业权益隔离、凭据ready前置、预约释放重占、本人Matrix参数、ETA公式一致、预设进度一致。评审结论待复核更新。
+- 详细进展见docs/00-tracking/2026-11-25-套餐异步开通实施记录.md。产品代码/云部署/容器创建/真实计时尚未执行;不自动提交。
+
+
+### 2026-11-25 套餐原型复核与小优化(本会话,G-D1 前)
+
+- **审核结论**:对照 PRD v1.1(FR-21~30/AC)与定价文档逐条复核原型 `model.js`/`app.js`/`verify.mjs`,
+  并人工检查 11 张评审截图(390/1440×浅/深×7 场景)——布局无溢出、暗色正常、触控 ≥44px;
+  独立评审第二轮 R1-R6 已闭环(`docs/04-quality/review/2026-11-25-套餐异步开通-需求设计评审.md` §七),
+  README 索引已登记,无需补登。
+- **修正一处误读**:并行读图曾误判「截图与文件名场景错位」,单读复核确认全部对应正确,verify 无此缺陷。
+- **优化 1(AC-21.1 一致性)**:入门版/企业版套餐卡补「2 核 4G 标准规格」(企业版标注「新容器」),
+  与定价文档 §一「各档新容器规格基线 2 核 4G」逐格对齐(`app.js` planCards)。
+- **优化 2(verify 加固)**:`verify.mjs` 跑前清理输出目录(防陈旧截图混入);
+  新增断言「三张套餐卡均含 2 核 4G 文案」防 AC-21.1 回归。
+- **复验**:`build.mjs` 重新生成 index.html(116 KB);`verify.mjs` 19 项 checks 全过、
+  0 pageerror、0 外网请求;新截图人工复核规格文案已上三卡、布局无变化。
+- **门禁状态不变**:G-D1 仍待用户确认;本会话未写产品代码、未调平台、未碰容器、未提交。
+
+
+### 2026-11-25 套餐原型 mobile 端显示优化(用户反馈:整体偏大)
+
+- **用户反馈**:手机视口下卡片、文字等整体过大,「不符合小视口区域的展示逻辑」。
+- **根因**:`styles.css` 的 767px 断点把正文类字号统一提到 `--fs-17`(16px)、按钮 16px、h1 28px、
+  卡片内边距 sp-5,与正式 App 移动端实际使用区间(正文 13-15px、h1 20px)不一致;
+  另 `waiting-simple min-height:500px` 造成小屏内大量空白。
+- **修改**(仅 `prototypes/fmode-subscription-20261125/styles.css` 的 mobile 断点整段重写):
+  正文 13-14px、h1 20px、卡片标题 15-17px、辅助信息 11-12px;按钮保 44px 触控高度但字号 14px;
+  卡片内边距 sp-4、间距收紧一档;顶栏 52px、底栏 56px;`waiting-simple` 去掉固定高度;
+  新增桌面端忽略的 `.section-heading`/`.plan-price`/`.container-*` 等移动端细分。
+- **verify.mjs 断言同步调整**:原「mobile 按钮字号 ≥16px」改为「按钮高度 ≥44px +
+  正文 ≥14px + h1 ≤22px」,符合移动端实际设计基线。
+- **复验**:build.mjs 重新生成(119 KB);verify.mjs 19 项 checks 全过、0 pageerror、0 外网请求;
+  截图复核 new/advanced/waiting 三个 390px 场景,密度与层级恢复正常。
+
+
+### 2026-11-25 套餐原型 mobile 套餐卡改版(用户反馈:卡片太高、占满屏幕)
+
+- **用户反馈(原话要点)**:套餐卡太高、宽度占据整个屏幕,多张卡需要大量滚动;
+  应改为小卡片、一行三个参数让用户选择;mobile 与 PC 端需分别设计。
+- **前一轮误判纠正**:上一轮只调了字号,未解决卡片纵向堆叠的问题;本轮改的是**卡片结构与布局**。
+- **修改**(`app.js` planCards + `styles.css`):
+  - 卡片数据新增 `short`(入门/进阶/企业)、`quota`+`quotaLabel`(1/3/5 个容器);
+  - **桌面端**:维持三列详情卡,新增 `.plan-quota` 默认隐藏、`.plan-name-short` 默认隐藏,不改变现有 PC 视觉;
+  - **移动端(≤767px)**:`plan-grid` 改为 `repeat(3,minmax(0,1fr))` 一行三列;
+    卡内只留「图标 / 简称 / 数字+单位 / 价格待定 / 开通按钮」,隐藏副标题、账单说明、权益列表;
+    推荐徽标由绝对定位改为卡内静态块;卡片高度 219px、320px 宽下每卡 91px 且无横向溢出。
+  - 触控合规:卡内按钮保持 `min-height: 44px`(首次写 36px 被 verify 断言拦下,已修正)。
+- **复验**:build.mjs 生成 120 KB;verify.mjs 19 项 checks 全过、0 pageerror、0 外网请求;
+  额外实测 320/360px 下三卡全部可见、`main` 无横向溢出;截图复核 new/expired 两场景。
+
+
+### 2026-11-25 套餐体系正式开发第一期(G-D1 后,前端可交付部分)
+
+- **用户裁决**:① 先做前端可交付部分(不写云函数、不伪造开通成功);② 改 `orgGuard` 允许个人用户进 App。
+- **平台侧硬阻断(已如实记录)**:`fmode-subscription` / `fmode-provisioning` 云函数尚未实现
+  (API 契约 §一.4「无已核实可调用 ID」)。因此本期**不展示**开通进度、48h 计时、配额原子占位、凭据签发。
+- **新增文件**:
+  - `core/plan.service.ts` —— 权益目录(1/1/3/5、2 核 4G、进阶含一年资源,价格全部「待定」)+ 申请意向(仅 localStorage,`none|pending` 两态,**无 active**)
+  - `core/plan.service.spec.ts`、`core/org.guard.spec.ts`
+  - `mobile/pages/plans|my-containers|plan-access/`、`desktop/pages/plans|my-containers|plan-access/`
+- **修改文件**:
+  - `core/org.guard.ts` —— 无组织不再重定向 `/pending`,改为放行(保留 `PENDING_PATH`/`queryHasOrg` 导出)
+  - `core/api/models.ts` —— `PlanCode` / `PaidPlanCode` / `PlanCatalogItem` / `PlanApplication`
+  - `core/nav-menu.service.ts` —— `NAV_CATALOG` 加 `plans` 项(侧栏/抽屉/自定义菜单自动生效)
+  - `mobile.routes.ts` / `desktop.routes.ts` —— 三张新路由(移动端放 shell 内,**未加 `**`**)
+  - `mobile/pages/mine/mine.ts`、`desktop/pages/mine/mine.ts` —— 加「套餐与容器」入口
+- **双端独立设计**:桌面三列详情卡(图标/名称/副标题/价格/按钮/权益清单);
+  移动端一行三列紧凑选择卡(图标/简称/配额/价格/按钮),整组约 220px。
+- **开发中修复的 2 个真实缺陷**(截图走查发现,非自测臆造):
+  1. `[object Object]` 泄露 —— `Agent.host` 是 `HostMetrics` 对象不是字符串,直接插值即渲染成 `[object Object]`;
+     改为渲染真实的 `cpuPercent` / `memPercent`。
+  2. 容器归属误判 —— 用 `!companyId` 判个人容器,实测有企业容器 `companyId` 为空会被误判;
+     改为 `owner.id === me.id` 判定(有 owner 时),`companyId` 仅作兜底。
+- **验证证据**:
+  - `npm run build` 通过(25.8s)
+  - `npm test` **1970 SUCCESS**(基线 1683 + 新增)
+  - Playwright 端到端 8 项全过:试用横幅、提交后显示待确认、**不出现「已开通」**、按钮变「待确认」、
+    刷新后申请保留、默认遮蔽、二次确认拦截、确认后正确显示;`pageErrors: []`
+  - 红线 grep:套餐页无金额符号/无「已开通」UI 文案/无伪造进度
+- **未做(按裁决)**:云函数、开通进度、48h 计时、配额原子占位、凭据签发、`git commit`。
+
+
+### 2026-11-25 真实容器开通链路:从脚本到「App 点一下」
+
+- **用户需求**:「把当前这些开通的逻辑,实现脚本开通,前台部署到线上之后点击开通容器就可以正常开通」。
+- **用户裁决**:① 三档三路径(试用/入门=用户自己容器只给提示词;进阶/企业=平台真实创建);
+  ② 云函数用平台固定身份 DM 主容器;③ 本期是内部测试,不做付费闸/人工确认/白名单。
+- **阶段 1 通道探测**:主容器 `bnQaoXQhE8` running、Matrix connected;R730 SSH **需重试 4 次**才通
+  (`Error reading SSH protocol banner`,确认的历史坑);R730 14 个容器,磁盘剩 109G/79% 已用。
+- **阶段 2 手动链路验证**:`onboard-user.mjs --send` 真实建成 `agent-node-app-test-1125`(objectId `ondyhUHqv2`)。
+  主容器跑了 24 分钟仍在修 media-patch,**回报「静默/超时」但容器实际可用** —— 印证「不能信回报信号」。
+- **新增云函数 `fmode-provisioning`**(`cloud/functions/fmode-provisioning.js`,objectId **`VtW1GT93Ax`**):
+  - op: `start` / `status` / `retry` / `list`
+  - 表 `FmodeProvisionJob`;配额 1/1/3/5;幂等键
+  - **ready 只由服务端三项核验推导**:容器记录 + Matrix joined + 心跳新鲜
+  - 平台 `POST /classes/Function` 本次未被 403,一次建成
+- **前端接线**:
+  - `FmodeApi` 新增 4 个抽象方法;`ParseApi` 实现(FN.provisioning = `VtW1GT93Ax`);`MockApi` 实现(不伪造 ready)
+  - 新增 `core/provision.service.ts`:发起 + 12s 轮询 + 终结即停
+  - 双端套餐页「开通」按钮接真实接口;试用/入门展示接入提示词,进阶/企业显示真实开通状态
+- **开发中修复的 3 个真实缺陷**(都是实测发现,非自测臆造):
+  1. `xlosi3m46q` 的 `agentId` 精确查询返回 404 → 改为拉列表本地过滤
+  2. **离线容器被判 ready** —— 某容器 `status: 'offline'` 但心跳 53s,只判心跳会误判就绪
+     → 增加 `error/stopped/offline` 状态排除。这是最严重的一个,会导致用户看到"已就绪"但容器根本不可用
+  3. 主容器回报「静默/超时」但容器实际建成 → 印证不依赖回报信号的设计正确
+- **端到端验证**(真调线上 `VtW1GT93Ax`):
+  - 试用 → `mode: onboarding` 返回提示词,**不建容器** ✅
+  - 进阶 → 真实建 job + agent ✅
+  - 幂等:同 key 返回同 jobId ✅
+  - 配额:进阶第 4 个返回 `409 名额已满(3/3)` ✅
+  - 任务列表正常 ✅
+- **测试**:`npm run build` 通过;`npm test` **1980 SUCCESS**(含新增 `provision.service.spec.ts` 10 项)
+- **未做(按裁决)**:付费闸、人工确认拦截、白名单(代码留 TODO 位置);未 git commit。
+- **待解决**:`fmode-provisioning` 已上线但**前端未部署**;主容器执行 docker run 仍不稳定
+  (24 分钟未完、SSH 需多次重试),是下一步要攻克的稳定性问题。
+
+
+### 2026-11-25 SSH 通道加固 + 创建失败准确反馈(用户要求)
+
+**一、SSH 通道稳定性 —— 已解决,实测 10/10 通过**
+
+- **根因定位**:拿到 `r730_root.py` 完整源码,确认 v2 的 `_connect()` 只有 `connect(timeout=30)`,
+  **无任何重试**。frpc 隧道(server.fmode.cn:18001→R730)间歇返回
+  `Error reading SSH protocol banner`,一次失败即整体放弃 —— 这就是"每次要试 4 次"的原因。
+- **加固版 v3**(`cloud/scripts/r730_root_v3.py`,已部署到主容器并备份 v2):
+  ① 连接重试 6 次,退避 1→2→3→5→8s;② 超时分级(连接 20s、命令沿用 timeout);
+  ③ 结构化错误 `{code, out, error, attempts}`,error 为 `CONNECT_FAILED`/`STAGE_FAILED`/`EXEC_FAILED`;
+  ④ **不加连接池**(复用会引入半开连接风险,快速失败+重试更适合抖动通道)。
+- **实测证据**(主容器内连续 10 次 `echo OK-n`):
+  `run1-10 全部 PASS`,耗时 14.7s / 14.7 / 14.8 / **35.8s** / 15.1 / 17.2 / **26.0s** / 14.8 / 14.9 / 14.9。
+  35.8s 与 26.0s 两次即「v2 会直接失败、v3 重试后成功」的实证。
+- 备份:`/opt/data/scripts/r730_root.py.v2-backup-*`,可回滚。
+
+**二、创建失败准确反馈 —— 已改造并部署(云函数 v0.2.0)**
+
+- 新增失败分类 `FAIL`:`R730_UNREACHABLE` / `CONTAINER_STAGE_FAILED` / `PROVISION_TIMEOUT` /
+  `CONTAINER_NOT_READY` / `QUOTA_EXCEEDED` / `MATRIX_SETUP_FAILED`,每个含
+  `reasonCode` + `retryable` + `userMessage`(面向用户,不含内部术语)。
+- 原始异常写入独立字段 `errorDetail`(技术排查用),**不再直接把 `e.message` 给用户看**。
+- 前端:`ProvisionService` 新增 `canRetry()` / `failureMessage()`;
+  重试按钮仅在 `retryable !== false` 时出现,配额满时改为引导「查看套餐升级」。
+- 实测对比:同一超时任务,改造前用户看到「开通超时(25 分钟无进展)」,
+  改造后「开通耗时超出预期。容器可能仍在后台创建,建议稍后查看进度或重试。」
+  + `reasonCode=PROVISION_TIMEOUT`、`retryable=true`、`failedStage=verifying`。
+
+**三、验证**:`npm run build` 通过;`npm test` **1980 SUCCESS**。
+
+**四、按用户要求:部署最后再做,本轮未部署前端。**
+
+## 2026-11-26 容器开通:主容器「技能工单 + 一任务一房间」
+
+**一、问题**:主容器执行建容器长指令会「失忆」——200+ 行指令跑 20 分钟卡在
+media-patch 等细节,**只输出过程不产出结论**(2026-11-25 实测)。
+根因:Hermes `session_key = agent:main:matrix:dm:<roomId>` + `session_reset.mode: none`,
+**同一房间 = 同一 session = 上下文无限累积**;`/new` 命令不存在。
+
+**二、改造(用户裁决:「封装为技能,每次都开新回合」)**:
+
+| 项 | 内容 |
+|---|---|
+| 技能 | 新建 `cloud/skills/container-provision-job/SKILL.md`:输入契约(JSON 工单)/执行纪律/6 阶段/输出契约(`===PROVISION-RESULT===` 机器可读块) |
+| 一任务一房间 | 云函数 `_createFreshRoom` + `_waitMasterJoin` + `_sendToRoom`,每个 job 开全新 Matrix 房间 → 新 roomId = 新 Hermes session |
+| 指令瘦身 | `_buildInstruction` 从 200 行长文改为 JSON 工单 + 引用技能,只留 3 条纪律 |
+| 结果回读 | `_readRoomResult` 从任务房间倒序找 `===PROVISION-RESULT===` 解析,写 `job.agentReport` —— **只做诊断,不参与 ready 判定**(红线①不变) |
+| 基线重建 | 本地 `_start` 曾被误删;改为**从线上 v0.2.0 完整源码重建**再外科式改 4 处,不凭记忆重写 |
+
+**三、踩坑与修复**:
+- `_retry` 里 `_createFreshRoom` 返回值当对象用(`.roomId`),实际返回字符串 → 会发出 `[object Object]`。已改为直接用返回值。
+- `_sendToMaster` 全部移除,`_start`/`_retry` 统一走新房间路径。
+
+**四、验证**:
+- `node --check` 通过;函数清单含 `_start`,`_sendToMaster` 计数 0。
+- 云函数热更为 **v0.3.0**(objectId `VtW1GT93Ax`),线上回读 23352 字符、语法通过。
+- 冒烟:`op:list` → `{"code":200,"items":[]}`;`op:start planCode=trial` → `mode:onboarding`
+  (**未建 FmodeAgent、未占 R730 资源**,符合三档分流)。
+- `tsc --noEmit` 通过;`npm test` **1980 SUCCESS**。
+
+**五、未完成(外部阻塞)**:
+- 🔴 **R730 SSH 通道不通**:`server.fmode.cn:18001` 直接返回 banner `Not allowed at this time`,
+  重试 6 次 × 3 轮全失败。**不是代码问题,是通道侧拒绝**。因此:
+  1. `container-provision-job` 技能**尚未部署到主容器** `/opt/data/skills/`
+  2. 端到端真实建容器**未验证**
+- 本地已把技能装到 `~/.claude/skills/container-provision-job/`,通道恢复后可直接用。
+- 前端**未部署**(用户要求部署最后再做)。
+
+**六、通道恢复后的下一步**:
+1. 部署技能到主容器 → `op:start planCode=advanced` 端到端跑一次
+2. 查 `FmodeProvisionJob` 的 `jobRoomId` 非空且 ≠ `matrixInfo.roomId`
+3. 读新房间 `/messages` 确认出现 `===PROVISION-RESULT===`
+
+## 2026-11-26 容器身份澄清 + Agent 写库上报方案落地
+
+**一、身份误判纠正(用户指出)**
+
+早期把 `agent-node-lj-test` 当作源容器,实为**早期空壳残留**:
+docker 容器 12 天前 Exited,仅 2 插件 / 0 脚本 / 无 media-patch。
+用户说明「我现在都可以在 APP 里面和 lj-test 容器通信」,据此重新查表定位到真正在用的容器:
+
+| 字段 | 值 |
+|---|---|
+| objectId | `K0nReVCfIk` |
+| agentId(docker 容器名) | `agent-lj` |
+| Matrix ID | `@k0nrevcfik:fmode.cn` |
+| 状态 | running,心跳活跃 |
+| 磁盘占用 | 4% |
+
+**身份换算规则(已验证三个容器一致)**:`mxId = "@" + objectId.toLowerCase() + ":fmode.cn"`,
+**不是**用 agentId 换算。Matrix 上存在同名干扰账号 `@agent-node-lj-test:fmode.cn`。
+
+权威清单已落 `docs/03-interface/容器身份清单-20261126.md`,
+旧文档 `容器接入完整指南-v2-20261111.md` 顶部已加更正说明。
+
+**二、Agent 无法稳定"说话",改为写库上报(用户裁决)**
+
+实测:要求主容器输出 `===PROVISION-RESULT===` 结构化块,跑 30 分钟**一次都没输出**;
+它只会回工具调用回显。要求它"在聊天里组织结构化格式"不可行。
+
+用户裁决:「让 Agent 在每个阶段完成之后在数据库的数据里面维护一个字段和一条数据」。
+
+落地:
+- 新建表 `FmodeProvisionStep`(jobId/attempt/stage/status/step/evidence/reasonCode/elapsedSec/agentId),CLP 允许匿名写
+- 技能 `container-provision-job` 升到 **v2.0.0**:铁则 6 改为「进度只写数据库,不要在聊天里汇报」,给出可直接照抄的 curl 模板
+- 云函数 `fmode-provisioning` 升到 **v0.4.2**:
+  - 新增 `_readSteps` / `_currentStep` / `_failedStep`,`status` 返回 `steps` + `currentStep`
+  - 删除读 Matrix 聊天解析 `===PROVISION-RESULT===` 的 `_readRoomResult`
+  - `failedStage` 改为取库里最后一条 step 的 stage
+
+**关键设计**:进度上报(Agent 写库)与成败判定(服务端三项核验)**完全解耦**。
+Agent 不写库 → 只是看不到进度,成败判定照常工作,不会误判。
+
+**三、实测结果**
+
+端到端跑通。主容器按技能执行并成功写库,诊断内容精确可行动:
+
+```json
+{"stage":"prepare","status":"failed",
+ "step":"源容器校验失败: agent-node-lj-test 为空壳(2插件/0脚本/无 media-patch), 容器已 Exited 12 天",
+ "evidence":"plugins=2 scripts=0 media-patch=none container=Exited(0) 12 days ago"}
+```
+
+**四、同时修复的 bug**
+
+1. 工单 `roomId` 传 `null` —— 代码读 `agent.get('roomId')`,但 FmodeAgent 表**无此字段**。
+   改为从 `matrixInfo.roomId` 取。此前主容器拿不到目标房间,跑 30 分钟不产出结论。
+2. 工单里的纪律文案还是旧版(`[PROGRESS]` / `===PROVISION-RESULT===`),
+   与技能 v2.0.0 自相矛盾,导致 Agent 收到冲突指令。已同步更新。
+3. 源容器只给了名字字符串,主容器拿去查不到。改为三件套(agentId/objectId/mxId)。
+
+**五、待确认**
+
+- `agent-lj` 作为源容器后的完整建容器流程尚未跑完验证(工单已改,需再跑一次端到端)
+- 前端未部署(用户要求部署最后再做)
+- R730 SSH 从开发机不通(`Not allowed at this time`),主容器侧可通但间歇断连
+
+## 2026-11-27 容器开通端到端打通 + 心跳根因 + 测试容器清理
+
+**一、心跳不上报的真正根因(三个叠加)**
+
+1. **`docker run` 缺 `gateway run` 参数** —— 只给 `--entrypoint entry.sh` 时,
+   entry.sh 把空参数透传给镜像原入口 → 跑成**交互式 TUI** →
+   `Warning: Input is not a terminal (fd=0)` → 容器立刻 `Exited (0)`。
+2. **`docker run` 没注入 `-e` 环境变量** —— 心跳插件从
+   `/run/s6/container_environment/FMODE_SESSION_TOKEN` 读 token,
+   该目录只能由 `docker run -e` 注入。`.env` 是给 Hermes 读的,两者缺一不可。
+3. **`FmodeAgent` 记录没设 `agentId` 字段**(最隐蔽)——
+   插件按**容器名**调 `xlosi3m46q {op:'update'}`,匹配不到就**自动新建一条**。
+   结果:一条容器两条记录,云函数按 objectId 查到空壳那条,永远判 offline。
+   **实测证据**:`agent-node-app-5iskvxwtdx` 对应 `5ISkvXWtdX`(空壳)与 `CgAP5CZ4xb`(心跳正常)。
+   → 结论:**心跳从来没坏过**,是核验查错了记录。
+
+**二、修复**
+
+- 云函数 `fmode-provisioning` → **v0.7.2**
+  - 建 agent 记录时写入 `agentId = 'agent-node-app-' + objectId.toLowerCase()`
+  - ⚠️ 必须**保存后**再写:新建对象时 `agent.id` 是 undefined
+    (踩过,产生 `agent-node-app-undefined`)
+  - `_verifyAgent` 优先按 **agentId 字段**匹配,回退 objectId
+  - `JOB_TIMEOUT_MS` 25 → 15 分钟(技能上限 12 分钟 + 3 分钟缓冲)
+- 技能 `container-provision-job` → **v4.0.0**
+  - `docker run` 补齐 15 个 `-e` 变量 + 结尾 `gateway run`
+  - 模板目录改为 `/opt/fmode-templates/default`
+  - 新增 verify 步骤:回读 `FMODE_SESSION_TOKEN` 确认注入
+
+**三、模板化**
+
+`test-0001` → `/opt/fmode-templates/default`,清理了 10 项身份残留
+(sessions/logs/cache/.fmode/auth.json/install_id/各类状态库/.env/备份文件)。
+保留 11 插件 + media-patch + scripts。
+
+**四、端到端验证(`TzSvd6gNML`)**
+
+```
+prepare → copy → configure → create → verify  全部 ok
+云端核验: { record: true, matrix: true, heartbeat: true } → ready
+FmodeAgent 记录数: 1(不再重复)
+```
+
+**五、测试容器清理(用户确认清单,精确名字,无通配符)**
+
+删除 6 个:`agent-node-app-{5ddcx9ml3k,5iskvxwtdx,eh7cuuxvrz}`、
+`agent-node-app-test-{0001,1125}`、`tmpl-verify`。
+- 先停 1 个 → 验证其余 18 个仍 Up → 再批量停 → 全部 Exited 后删除
+- 数据目录 `/opt/fmode-containers/<名>` 逐个 rm
+- 数据库记录**软删**(`isDeleted: true`),不硬删
+
+保留:`agent-node`(主容器)、`xinting`/`pengfeng`/`xiaxin`/`yangyang`/`liujun`/`tuye`/
+`cb-feishu-001`、5 个 `u*` 用户容器、`wbh0fy2dpz`(验证成果)。
+
+**六、遗留**
+
+- 前端进度展示未接线(`models.ts` 有类型,`ProvisionService.statusText()` 未用)
+- 前端未部署(用户要求部署最后再做)
+- R730 SSH 间歇断连(`Error reading SSH protocol banner`),需多次重试
+
+## 2026-11-27(续)前端真实进度展示 + 容器清理技能
+
+**一、前端:展示 Agent 写库的真实进度**
+
+之前 `statusText()` 只会显示笼统的「正在开通」。现在:
+
+- `src/app/core/api/models.ts` 新增 `ProvisionStep` / `ProvisionStage` / `ProvisionStepStatus`
+  - `ProvisionStatus` 增加 `steps` / `currentStep`
+  - 移除未使用的 `agentReport`(那是旧的读聊天方案残留)
+- `src/app/core/provision.service.ts` 新增:
+  - `progressText()` —— 取 `currentStep.step`(如「写 .env / 清残留 / 改 SOUL」)
+  - `completedStages()` —— 数 `status === 'ok'` 的阶段
+  - `statusText()` 在运行中时**优先显示真实阶段描述**
+- `src/app/desktop/pages/plans/plans.ts` 增加阶段进度条(5 阶段,`aria-*` 完整,
+  响应 `prefers-reduced-motion`)
+
+🔴 **语义边界不变**:进度条只反映 Agent 上报的执行阶段,
+**不代表容器可用**;是否就绪仍由后端 `verify` 三项核验决定。
+
+新增 4 个单测(`provision.service.spec.ts`):真实进度优先、无进度降级、
+只数 ok 阶段、已就绪不显示进度。**1984 SUCCESS**。
+
+**二、新技能:`container-stop-remove`**
+
+`cloud/skills/container-stop-remove/SKILL.md`(v1.0.0,已部署到主容器)。
+
+背景:R730 上跑着 20+ 容器,手工 `docker stop` 用错通配符就会误停别人的服务。
+
+四条铁则:
+
+| 铁则 | 内容 |
+|---|---|
+| 1 | 只接受精确名字,含 `*`/`?`/`$`/空串 → **拒绝整个请求** |
+| 2 | 硬编码保护名单(`agent-node`、`agent-node-lj-test`、`agent-node-u*`),命中即拒绝 |
+| 3 | 三步走:快照 → 停止/删除 → **diff 对比**,变化超出预期立即 `docker start` 恢复 |
+| 4 | 一次 SSH 跑完(sshd 有并发上限) |
+
+输出 `===CLEANUP-RESULT===` 含 `ok`/`refused`/`diff`/`leftRunning`。
+
+⚠️ 关键设计:**命中保护名单是「拒绝整批」而不是「跳过那一个」**——
+跳过会让人误以为整批都处理了。
+
+验证:主容器读技能后能准确回答「命中保护名单要拒绝整个请求」。
+
+**三、遗留**
+
+- 前端未部署(用户要求部署最后再做)
+- R730 SSH 仍间歇断连,需多次重试
+
+## 2026-11-27 容器开通门禁:无容器则禁止进入功能页
+
+**一、用户反馈的 5 个问题(代码探查全部证实)**
+
+| # | 现象 | 根因 |
+|---|---|---|
+| 1 | 点开通后不跳转 | `plans.ts` 的 `apply()` 只调 `start()`,零 `router.navigate` |
+| 2 | 没有开通等待页 | 路由不存在,进度是套餐页内联 `@if` |
+| 3 | 刷新后进度丢失 | `resume()` 零调用方,jobId 未持久化 |
+| 4 | 缩放跳到别处 | `device.service.ts:57` 宽 <768 判 mobile,两 shell 强制跳转 |
+| 5 | 登录后卡 `/pending` | `orgGuard` 已全放行但 `afterLogin` 没同步改,`/pending` 无出口 |
+
+**二、实测:用户这次操作的真实结果**
+
+| 容器 | R730 | 心跳 | 结论 |
+|---|---|---|---|
+| 我的企业版 | ✅ Up | 176s | 真建成了,但前端永远 `provisioning` |
+| 我的入门版 | ❌ | 无 | 只建记录(入门档设计如此) |
+| 我的试用容器 | ❌ | 无 | 只建记录 |
+
+**三、核心改动:容器门禁**
+
+新增 `src/app/core/container.guard.ts`:
+
+```
+已登录 → 有可用容器?
+  有 → 放行
+  无 → 🔒 只能去 /plans 和 /provision
+```
+
+🔴 **判定复用 `agent-liveness.ts` 的 `livenessOf()`**,不自己造第二套。
+理由:那个文件收敛了项目里 6 套互相矛盾的实现,再写一套就是重蹈覆辙。
+特别地,**不能只看 `status` 字段** —— 实测容器掉线 45 天后 `status` 仍是 `running`。
+
+🔴 **查询失败必须放行**:容器服务挂了不能把所有人都关在门外。
+
+**四、路由重构**
+
+`/plans` 和 `/provision` **提到顶层**(不在 shell 内):
+
+1. 门禁例外:无容器用户只能待在这两页,挂 shell 里会被自己拦掉
+2. 全屏锁定:不挂 shell 就等于没有 TabBar / 抽屉 / 侧边栏
+3. 缩放不跳转:shell 的 resize 监听不会触发
+
+**五、新增等待页**
+
+`mobile/pages/provision/provision.ts` + `desktop/pages/provision/provision.ts`
+
+- 五阶段固定顺序:准备环境 → 拷贝模板 → 写入配置 → 创建容器 → 连接验证
+- 进度来自 `FmodeProvisionStep`(真实阶段,非估算)
+- 三态:进行中(无按钮,锁定)/ 成功(「进入应用」)/ 失败(「重试」或「更换套餐」)
+- 60 秒无进展 → 降级出口「网络似乎不稳定,点击刷新」
+- `pushState` + `popstate` 拦截返回键
+- 遵守 `rules/18`:只动 `transform`/`opacity`、响应 `prefers-reduced-motion`
+
+**六、UI 稳定性**
+
+- 提交中按钮有 spinner + 文案变化(「提交中…」/「生成中…」),不是只变灰
+- `ProvisionService.start()` 防重入
+- 跳转前 `await` 到 `jobId` 存在,不带 `undefined` 跳
+- 所有按钮 ≥44px,底部避让 `env(safe-area-inset-bottom)`
+
+**七、验证**
+
+- `tsc --noEmit` 通过
+- `npm test` **1993 SUCCESS**(新增 9 项:门禁 5 项 + 守卫 4 项)
+- 其中专门测了「心跳过期的容器不算可用」——锁住这次踩的坑
+
+**八、清理**
+
+软删 3 条 FmodeAgent + 1 条 job,删除 `agent-node-app-npgqpxw6de` 容器与数据目录。
+账号 `WGJMHffBS3` 回到全新状态。
+
+**九、遗留**
+
+- 前端未部署(用户要求部署最后再做)
+- R730 SSH 仍间歇断连
+
+## 2026-11-27(续)容器开通 4 个 UI 缺陷修复
+
+用户实测门禁流程后报了 4 个问题,代码探查**全部证实**,每个都有明确根因。
+
+**一、🔴 刷新后一直显示"正在加载"(最严重)**
+
+根因:**等待页完全不读 `provision.error()`**(grep 计数 = 0)。
+
+```
+刷新 /provision?jobId=xxx
+  → _current 是内存 signal,归零
+  → resumeFromUrl() 失败(401/404/网络)
+  → _error 被设置,但页面只看 isReady()/isFailed()
+  → 两个都 false → 永远显示「正在连接平台…」
+  → 没有任何出口
+```
+
+而且 `stalled()` 60 秒后的「点击刷新」也无效 —— `refresh()` 在 `_current` 为 null 时直接 return。
+
+修复:等待页补**三态**
+- 错误态:显示 `error()` + 「重新加载」+「返回套餐」
+- 无 jobId 态:显示「没有正在进行的开通任务」+「去开通」
+- 进行中态:原样
+
+**二、按钮状态串台**
+
+`provision.starting()` 是**全局** signal,所有卡片按钮共用。
+点「试用」→ 三张卡片全变「提交中…」,用户以为全都点了。
+
+修复:`ProvisionService` 改为 `_startingPlan: signal<string|null>`,
+新增 `isStarting(planCode)`,**只有被点的那个按钮转**。
+
+**三、桌面端没有复制按钮**
+
+移动端有 `copyInstruction()`,桌面端只有一段裸 `<pre>`,**根本复制不了**。
+
+修复:抽成 `ProvisionInstructionComponent` 两端共用。
+
+**关键:复制失败要有兜底**
+
+`navigator.clipboard` 只在**安全上下文**可用(https / localhost)。
+部署到内网 `http://10.x.x.x` 会抛 `NotAllowedError`,用户以为按钮坏了。
+
+兜底:失败时**自动全选 `<pre>` 内容** + 提示「按 Ctrl+C 复制」。
+
+**四、生成期无加载态**
+
+试用档 `start()` 要做三件慢事(建 FmodeAgent 记录 + 调 RP5Ht55NeX 建
+Matrix 身份 + Web Crypto 算密码),1-3 秒。只有按钮文字变化,手机上毫无反馈。
+
+修复:页面顶部加 `.plans-loading` 提示条「正在生成你的接入提示词…(首次约需 2-3 秒)」。
+
+**五、附带修复:入口页丢任务**
+
+`entry.ts` 刷新到 `/` 时直接跳 `/mobile/messages` → 被门禁拦回 `/plans`,
+用户以为开通任务丢了。
+
+修复:`ProvisionService.start()` 把 jobId 写进 `localStorage`,
+入口页优先读它把用户送回 `/provision?jobId=xxx`;任务终结(ready/failed)时清除;
+**start 失败也清除**(否则下次会被送回不存在的任务 → 404 卡死)。
+
+**六、验证**
+
+- `tsc --noEmit` 通过(app + spec)
+- `npm run build` 通过
+- `npm test` **2002 SUCCESS**(新增 9 项:复制组件 4 项 + jobId 持久化 5 项)
+
+**七、遗留**
+
+- 前端未部署(用户要求最后再做)
+
+## 2026-11-27(续)开通流程 7 个问题修复
+
+**一、🔴 核心根因:容器永远停 offline,导致永远转圈**
+
+实测两个 job(`kfnvXUSDHn` / `LyIwZqfMcX`):
+- R730 上容器**都建成了**(`Up 10 minutes`)
+- 但 `FmodeAgent.status` 是 `offline`,心跳 578s 前
+- 云函数 `_verifyAgent` 把 `offline` 判为不可用 → 永远不 ready
+
+原因:新容器**首次上报就是 `offline`**(进程刚起还没跑过一轮),
+需要一轮对话才变 idle/running。但用户不会主动跟一个"没就绪"的容器说话。
+
+**修复(两层)**:
+1. **放宽判定**:`offline` + **心跳新鲜** = 进程活着 = 可用。
+   仅 `error`/`stopped` 才算故障。`offline` + 心跳过期仍不可用(自然排除)。
+2. **主动唤醒**:探到 `offline` 但心跳新鲜时,往目标房间发一条消息
+   触发 Hermes `pre_llm_call` → 状态更新。
+
+云函数升到 **v0.8.0**。
+
+**二、门禁 404 白屏**
+
+`plansPathOf()` 按端返回 `/desktop/plans` / `/mobile/plans`,
+但这两个子路由**已提到顶层 `/plans`** → 重定向到不存在的路径 = 白屏。
+
+修复:改为顶层 `/plans`,并同步修正 10 个文件里的旧路径引用。
+
+**三、复制区消失**
+
+`@if (hasJob)` 和 `@else if (instruction)` 是**互斥分支**——
+点「进阶开通」瞬间 `hasJob()` 变 true,提示词区块立即消失。
+
+修复:
+- 模板改为两个**独立** `@if`,可同时存在
+- `ProvisionService.start()` **不再清 `_instruction`**
+  (提示词和开通任务是两件独立的事,用户可以先拿提示词再决定)
+
+**四、预计时间不准**
+
+`etaText` 用 `elapsedSec` 求平均,但**后端基本不写这个字段**
+(实测 9 条 step 里 0 条有它)→ 算成 0 → 显示「预计还需约 0 秒」。
+
+修复:改用**阶段计数**保守估算(5 阶段 × 40 秒),不依赖后端字段。
+
+**五、右侧状态太技术化**
+
+原来直接渲染 Agent 的 `step` 原文(`targetDir 已清空重建`、`.env/SOUL/sessions 已配置`)。
+
+修复:新增 `STAGE_DESC` 固定友好文案(「正在准备运行环境」等)。
+Agent 原文保留在 `detail` 字段供排查,但**不渲染**。
+
+另修复:同一阶段可能先写 `ok` 再写 `running`(顺序错乱),
+导致已完成的阶段又"回去"。改为**只要出现过 ok 就判定完成**。
+
+**六、🔴 频繁弹「网络似乎不稳定」**
+
+60 秒计时器从**进入页面**开始计时,跟"网络是否真有问题"无关。
+正常跑 3 分钟也会弹。
+
+修复:**删除该计时器**。改为:
+- 请求真失败 → 错误态(已有)
+- 超过 3 分钟 → 中性提示「比预计时间长一些,仍在进行中」(不是错误)
+
+**七、可离开页面**
+
+原提示「请勿关闭页面」——用户不敢走。但开通在**服务端**跑,关页面无影响。
+
+修复:
+- 文案改为「开通在服务器上进行,可以离开本页,稍后回来查看进度」
+- 新增「返回,稍后查看」按钮
+- 删掉返回键拦截(既然允许离开)
+
+**八、加载态优化**
+
+- 新增**骨架态**:还没拿到第一条 step 时显示 5 行灰色占位
+  (比「5 个空圆圈」信息量大,用户知道总共有 5 步)
+- `etaText` 无数据时返回空串,避免和 `progressLabel` 重复显示「正在连接平台…」
+
+**九、清理(本轮前置)**
+
+- 删除账号 `F2srRikSln`:3 agent + 3 binding + 2 job + 30 step + Matrix 账号停用
+- 删除容器 `agent-node-app-{kvt61ga9gv,buqiyb0b3c}` + 数据目录
+- 备份:`docs/04-quality/backup/deleted-user-F2srRikSln-20261127.json`
+
+**十、验证**
+
+- `tsc --noEmit` 通过
+- `npm run build` 通过
+- `npm test` **2002 SUCCESS**
+  (其中「门禁重定向」用例新增回归断言:**不能**返回 `/desktop/plans`)
+
+**十一、遗留**
+
+- 前端未部署(用户要求最后再做)

+ 82 - 0
docs/01-requirements/changes/CR-20261125-02-平台容器与试用异步开通.md

@@ -0,0 +1,82 @@
+# CR-20261125-02 · 平台容器与试用异步开通
+
+| 字段 | 值 |
+|---|---|
+| 变更编号 | CR-20261125-02 |
+| 版本 | v1.0 |
+| 日期 | 2026-11-25 |
+| 提出人 | 用户 |
+| 状态 | **业务裁决已确认;文档/接口设计/双端原型同步中;待新独立评审与 G-D1 原型确认** |
+| 关联需求 | PRD-20261125-套餐与开通体系 v1.1:保留 FR-21~27,新增 FR-28~30 |
+| 唯一执行基准 | docs/02-design/plans/2026-11-25-套餐体系任务计划书.md v1.1 |
+| 类型 | 已确认业务规则调整及产品化开通流程补全;本轮不写产品代码 |
+
+## 一、变更原因
+
+CR-20261125-01 使套餐进入范围,但初稿仍把入门写为自托管、进阶独立云资源和配额留待裁决,把“人工收款确认”扩大成“人工建容器”,并沿用历史个人试用组织概念。用户后续已明确平台提供各档容器、48h 一次试用、数量及增配、真实异步开通。本 CR 记录并传播最新裁决,避免在旧文末追加补充而留下相互矛盾的生效正文。
+
+**优先级**:本 CR 与 CR-20261125-01、历史创建流程或旧版文档冲突时,以本 CR 最新确认规则为准。旧文保留历史可追溯性,不再作为相冲突条款的执行依据。
+
+## 二、已确认变更内容
+
+| 编号 | 当前生效裁决 | 需求 |
+|---|---|---|
+| C-01 | 登录→领取试用/开通套餐→平台接口受理异步创建→等待页真实阶段→核验 ready→使用 | FR-21/22/24/30 |
+| C-02 | 试用 1、入门固定 1、进阶 3、企业 Company 共享 5 个;只有进阶/企业可付费增配 | FR-25/29 |
+| C-03 | 入门改为平台提供;试用/入门/进阶均交付独立云资源四件套与 Matrix 接入信息 | FR-23/24 |
+| C-04 | 四件套含 appId/serverURL/functionsURL/独立资源专属凭据(绝非平台管理 masterKey);平台管理密钥永不下发,专属凭据服务端校验独立作用域、本人、ready、二次确认后受控短时返回 | FR-23 |
+| C-05 | 新容器复用已验证 2 核 4G;入门月费、进阶年费含一年资源;所有价格待定/咨询,定价文档唯一维护 | FR-21 |
+| C-06 | 首期人工收款、套餐确认、加购确认;确认后的创建必须平台 API/执行器异步完成,不能人工 DM/SSH 作为产品流程 | FR-22/24/30 |
+| C-07 | 每账号一次 48h,首容器及独立资源完整核验 ready 时服务端开始计时;失败重试续用原申请,不重复领取或重置时间 | FR-28 |
+| C-08 | 到期容器数据不停不删,只锁项目使用并进入付费页;付费恢复同一容器;已有有效个人/企业权益不降级 | FR-27/28 |
+| C-09 | 任务 queued/provisioning/verifying/ready/failed;阶段 entitlement/cloud/matrix/container/connectivity/verification,来自执行器结构化事件/快照 | FR-30 |
+| C-10 | 服务端权威鉴权与配额;并发任务原子预占;幂等、恢复、结构化失败和安全重试,复用已有资源 | FR-27/29/30 |
+| C-11 | 不解析自然语言推断成功,不按计时器自动 ready;当前无已确认实体容器创建 API,明确平台实现依赖 | FR-24/30 |
+| C-12 | 未实测只展示阶段;后续专用验收账号/新验收容器从受理到 ready 实测,初始参考分钟数 ceil(实测总秒数×1.30/60),注明样本 | FR-30 |
+| C-13 | lj-test 和旧生产/历史资产只读;本轮只文档/设计/原型,不创建或修改容器,不改凭据 | 资产边界 |
+| C-14 | 文档、接口设计、桌面/移动双端原型先行;G-D1 用户确认本轮原型后才可写产品代码 | 门禁 |
+
+专属资源若实际返回共享平台管理密钥,不能算成功交付,须平台修复隔离;原型必须使用明确假值。现有历史“个人试用组织”的期限或标记不得自动映射成本版试用授权。
+
+## 三、范围与非目标
+
+本轮完成:需求/定价/唯一计划 v1.1 对齐、新 API/架构设计、双端原型、追溯矩阵、接手说明、索引与留痕;进入新独立评审并向用户展示原型。
+
+本轮不做产品实现、真实支付、外部平台写操作、容器创建/修改/故障注入、凭据改动、提交与发布。平台实体创建及执行器实现属于后续平台交付依赖,不能把“设计态”写成已上线。后续编码/联调的先后关系以唯一计划为准。
+
+## 四、影响评估与变更传播
+
+| 产出 | 同步要求 |
+|---|---|
+| PRD-20261125-套餐与开通体系.md | v1.1,保留 FR-21~27,补 FR-28 试用/29 配额/30 异步;全部 AC 可验证 |
+| 定价与权益-20261125-草案.md | v0.2,权益已定、价格唯一维护;只保留真实未决商业项 |
+| 2026-11-25-套餐体系任务计划书.md | v1.1,仍唯一执行基准,阶段/六要素任务/门禁/依赖完整更新 |
+| 套餐权益与异步开通设计.md | 服务端权益、试用、Company 配额、任务/预占/恢复模型及安全边界 |
+| 套餐与平台异步开通-API契约.md | 设计态端点、DTO、权限/幂等/补偿/凭据交付,区分已有能力与平台待实现 |
+| prototypes/fmode-subscription-20261125/index.html | 双端四档/人工确认/真实阶段演示/ready/到期付费/原容器恢复/错误重试/企业共享,假数据 |
+| AI接手说明、当前进度头部、docs/README.md | 最新阶段、来源优先级、资产只读、新文档与原型索引 |
+| traceability-matrix.md | FR-21~30 的 AC/设计/API/测试状态;未实现不得标通过 |
+| 2026-11-25-套餐异步开通实施记录.md、操作追踪.md | 由主执行记录本轮动作、门禁、后续验证,不复用旧评审为新结论 |
+
+服务端将新增/调整权益、试用、任务和配额能力,具体 Schema/索引/迁移以架构设计为准,本 CR 不声称无数据库影响。前端套餐/等待/容器/企业引导及项目权限需要后续实现。
+
+## 五、验收口径与验证状态
+
+| 编号 | 可验证条件 | 当前状态 |
+|---|---|---|
+| AC-CR02.1 | PRD/定价/计划/交接生效正文均与 C-01~14 一致,无入门自托管、进阶不含云资源、30 天产品试用或人工建容器产品流程 | 文档自查后提交新独立评审 |
+| AC-CR02.2 | FR-21~27 保留;FR-28~30 与既有 SPEC 不撞号;每条 FR 有可执行 AC,矩阵逐行登记,未实现/未测状态真实 | 文档自查,不视为功能通过 |
+| AC-CR02.3 | API/架构明确平台实现依赖、五状态六阶段、试用 ready 计时、Company 配额/预占/幂等、失败复用与专属凭据安全;设计不冒充上线 | 待新独立评审/平台确认 |
+| AC-CR02.4 | 双端原型可演示正常、在途、失败、重试、到期付费及有效企业权益不降级;无真实凭据和伪造已验证耗时 | 待原型验收 |
+| AC-CR02.5 | 新独立评审及问题闭环记录与 v1.1 对应;记录用户对本轮原型明确确认后才开放编码 | G-D1 待确认,未通过 |
+| AC-CR02.6 | 后续只以新验收资产验证全部产品 AC 并计算参考耗时;历史 lj-test/生产资产未被写操作 | 未执行,不在本轮冒称完成 |
+
+## 六、评审与门禁
+
+阶段 0 原文档评审第 1 轮 7 项已闭环,属于 v1.0 历史。本 CR 引入新业务/接口/权限/试用/配额,**须新独立评审**,设计者自查不能替代。用户已授权计划和业务裁决,不等于 G-D1 已通过;本轮原型仍待用户确认。
+
+## 七、变更历史
+
+| 版本 | 日期 | 内容 |
+|---|---|---|
+| v1.0 | 2026-11-25 | 记录最新确认规则、覆盖关系、影响、验收与 G-D1 边界 |

+ 90 - 0
docs/01-requirements/changes/CR-20261125-套餐体系纳入范围.md

@@ -0,0 +1,90 @@
+# CR-20261125 · 套餐与开通体系纳入 v2 范围
+
+| 字段 | 值 |
+|---|---|
+| 变更编号 | CR-20261125-01 |
+| 日期 | 2026-11-25 |
+| 提出人 | 用户(裁决) |
+| 状态 | **已批准** |
+| 关联 | PRD-20261125-套餐与开通体系(新建)· SPEC FR-21 起 · 容器创建完整流程 §五 |
+
+---
+
+## 一、为什么要走这份变更
+
+v2 现行 PRD/SPEC 的盘子是「客户端重建」,**没有任何商业化与开通概念**:用户从哪来、套餐怎么卖、容器开通权怎么给,全部空白。而技术侧已先行积累了大量开通链路事实(`docs/03-interface/容器创建完整流程-接口与提示词-20261124.md`、`scripts/onboard-user.mjs`),其中「入门套餐/进阶套餐」术语已在技术文档流通却无需求文档承载。
+
+用户 2026-11-25 提出三档套餐构想并裁决先行两个方向,按 PRD FR-18(任何新增功能须走变更请求由用户决策)补上这份变更。
+
+## 二、变更内容
+
+### 2.1 用户裁决原文(2026-11-25)
+
+> 「入门 1. 用户接入自己的 hermes agent。我们提供基础版 fmode harness 和 matrix 通信。每月最少的费用
+> 进阶 2. 用户用我们容器直接创建,多包含 2 核 4G 一年的费用
+> 企业版 3. 支持通讯录里企业账套管理能力。
+> 选择两个,一个的个人版开通套餐使用,还有就是当前的这种加入企业的方式,使用企业容器,
+> 需要基于这个需求优化 UI 以及逻辑,然后开通之后可以创建自己的一些容器,
+> 我们可以先把文档完善一下,就是对应的需求方面以及定价方面」
+
+同日四项补充裁决:
+
+| # | 问题 | 裁决 |
+|---|---|---|
+| 1 | 入门月费与进阶年费金额 | **价格待定,先定权益** |
+| 2 | 入门档交付物边界 | **接入 + 独立云资源**(含 trial-standalone 四件套) |
+| 3 | 支付通道 | **先人工开通占位**(第一期不接真实支付) |
+| 4 | 「加入企业、用企业容器」线 | **流程也要优化** |
+
+### 2.2 新结论
+
+**三档套餐体系纳入产品范围,本期先做两个方向:**
+
+1. **个人版套餐开通**(入门 + 进阶):用户在 App 内看权益、提申请,第一期人工开通占位;入门档交付「接入信息 + 独立云资源」,进阶档交付「平台容器(2 核 4G,含一年资源费)」;开通后用户可创建/拥有自己的容器。
+2. **企业线**(现有「加入企业、用企业容器」):维持并优化——pending 等待流程、通讯录企业账套展示、加入方式引导。
+
+**企业版(通讯录企业账套管理能力)登记为方向,本期不做高级形态。**
+
+### 2.3 范围边界(明确不做)
+
+| 不做 | 理由 |
+|---|---|
+| 真实支付接入(微信扫码/在线下单) | 用户裁决:第一期人工开通占位;平台支付链路(qiwei/subscribe、pay_code2)为逆向线索、契约未核对 |
+| 价格写死 | 用户裁决:价格待定,先定权益 |
+| 自动续费 / 到期回收 / 用量计费 | 第一期人工管理,待运营口径 |
+| docker run 自动化重造 | 已有主容器 skill v2.2.0(container-provision-from-source)封装,直接复用 |
+| 企业版高级账套管理形态 | 本期只做企业线流程优化,账套管理能力后议 |
+| 平台接口开发(创建分身接口等) | 平台侧事项(陈经理),本项目只登记依赖 |
+
+---
+
+## 三、验收口径
+
+文档阶段的验收 = 文档自身合规(本次不产出代码):
+
+| # | 口径 | 验证方式 |
+|---|---|---|
+| AC-CR.1 | 新增《PRD-20261125-套餐与开通体系》含三档权益矩阵、两条动线、FR-21 起编号需求与可验收 AC | 评审员子代理评审 |
+| AC-CR.2 | 新增《定价与权益-20261125-草案》权益定稿、**全文无写死价格**(金额一律「待定」占位) | grep 断言无具体金额 |
+| AC-CR.3 | `容器创建完整流程-接口与提示词-20261124.md` §五「入门套餐是否含 trial-standalone」回填裁决结果(含) | 直接核对 |
+| AC-CR.4 | 主 PRD / docs/README.md / 四向追溯矩阵完成登记 | 直接核对 |
+
+---
+
+## 四、对既有文档的影响
+
+| 文档 | 改动 |
+|---|---|
+| `docs/01-requirements/prd/PRD-20261125-套餐与开通体系.md` | **新建**(FR-21 起) |
+| `docs/01-requirements/prd/定价与权益-20261125-草案.md` | **新建** |
+| `docs/01-requirements/prd/PRD-20261014-fmode-app-v2.md` | 变更记录 v1.3 + 关联文档引用(不动正文结构) |
+| `docs/03-interface/容器创建完整流程-接口与提示词-20261124.md` §五 | 回填「入门套餐含 trial-standalone」裁决 |
+| `docs/README.md` | 索引登记 |
+| `docs/04-quality/traceability-matrix.md` | 补 FR-21+ 行 |
+| `docs/00-tracking/操作追踪.md` | 留痕(含裁决原文) |
+
+## 五、后续阶段(本变更的落地路线)
+
+1. 文档评审闭环(评审员子代理)+ 用户审阅定价权益
+2. UI 原型:套餐页/开通入口/「我的容器」创建入口/通讯录企业账套/pending 优化 —— **G-D1 门禁:用户确认原型后才编码**
+3. 编码实现:`core/acl.ts` personal 级挂开通判定、入口与页面、人工开通占位的状态流转

+ 4 - 3
docs/01-requirements/prd/PRD-20261014-fmode-app-v2.md

@@ -3,10 +3,10 @@
 | 字段 | 值 |
 |---|---|
 | 文档编号 | PRD-20261014-fmode-app-v2 |
-| 版本号 | v1.2 |
-| 最后更新日期 | 2026-11-05 |
+| 版本号 | v1.3 |
+| 最后更新日期 | 2026-11-25 |
 | 状态 | **草案 · 待评审** |
-| 本次变更原因 | v1.2:CR-20261105 纳入群聊(多路派活面板),原 §3.2「多人群聊排除」撤销;v1.1:第1轮评审修复(S1 模块清点统一口径 / T8 关联文档补齐) |
+| 本次变更原因 | v1.3:CR-20261125-01 套餐与开通体系纳入范围(新增关联 PRD-20261125-套餐与开通体系,本文档正文结构不变);v1.2:CR-20261105 纳入群聊(多路派活面板),原 §3.2「多人群聊排除」撤销;v1.1:第1轮评审修复(S1 模块清点统一口径 / T8 关联文档补齐) |
 | 上游文档 | 《访谈-20261014-现状调研汇总.md》《访谈-20261014-第二轮裁决记录.md》《访谈-20261014-第三轮裁决记录.md》《SPEC-20261014-fmode-app-v2-草案.md》 |
 | 规格细节 | FR/AC 明细见 SPEC,**本文档不重复 AC,只定盘子** |
 
@@ -238,4 +238,5 @@
 - 现状调研汇总:`docs/01-requirements/stories/访谈-20261014-现状调研汇总.md`
 - 访谈问卷:`docs/01-requirements/stories/访谈问卷-20261014-v2需求挖掘.md`
 - 交接文档:`docs/01-requirements/交接文档-阶段1至2.md`
+- 套餐与开通体系(v1.3 新增,CR-20261125-01):`docs/01-requirements/prd/PRD-20261125-套餐与开通体系.md`
 - 第1轮评审报告:`docs/04-quality/review/2026-10-14-SPEC-ER评审-第1轮.md`

+ 173 - 0
docs/01-requirements/prd/PRD-20261125-套餐与开通体系.md

@@ -0,0 +1,173 @@
+# PRD:套餐与开通体系
+
+| 字段 | 值 |
+|---|---|
+| 文档编号 | PRD-20261125-套餐与开通体系 |
+| 版本号 | v1.1 |
+| 最后更新日期 | 2026-11-25 |
+| 状态 | 业务裁决已收口;双端原型已产出;v1.1 独立复审中;G-D1 待用户确认 |
+| 本次变更原因 | CR-20261125-02:平台容器、48h 试用、配额、异步任务与真实进度 |
+| 上游 | CR-20261125-01(历史范围)· CR-20261125-02(本版裁决,冲突时优先)·《定价与权益-20261125-草案.md》 |
+| 唯一执行基准 | docs/02-design/plans/2026-11-25-套餐体系任务计划书.md v1.1 |
+
+> 编号:保留 FR-21~27,新增 FR-28~30。既有 SPEC 使用至 FR-20(FR-19 双号为历史遗留,本次不重编号);本文件维护 FR-21~30,AC 与 FR 同号。已定业务规则不再列为开放问题。
+
+## 一、背景与目标
+
+现有客户端具备 IM、项目、通讯录等能力,但新用户取得容器仍依赖运维交接。独立云资源、Matrix provision、容器登记等有局部技术能力及历史人工创建实证,**尚无已确认可供 App 调用的实体容器创建 API**。历史实证不是套餐自助开通的上线证据。
+
+本期产品流程为:**登录 → 领取试用或开通套餐 → 平台接口受理异步创建 → 等待页展示友好当前状态与真实进度 → 服务端核验 ready → 使用**。试用、入门、进阶均由平台提供容器及独立云资源。首期人工收款、套餐确认、付费加购确认;确认后的资源和容器创建由平台接口与执行器异步完成,不能要求用户 DM 主容器或人工 SSH。
+
+先完成文档、接口设计与桌面/移动双端原型,**本轮用户确认原型(G-D1)后才可写产品代码**。平台实现和真实新资产联调通过前,不得将设计或演示状态表述为已上线。
+
+## 二、目标用户与范围
+
+- 个人新用户:领取一次试用或选择入门/进阶,取得自己的可用容器。
+- 已开通个人用户:查看权益、接入信息、容器与配额;进阶可付费增配。
+- 企业成员/管理员:加入企业,按 Company 共享权益、容器与配额;企业可付费增配。
+- 沿用 docs/01-requirements/personas/用户画像.md;本期优化个人开通和加入企业两条动线,企业高级账套管理后置。
+
+不做在线支付/自动扣款、自动续费、到期删容器或数据、生产资产改造。平台执行器缺失不能用前端脚本或聊天指令替代产品接口。
+
+## 三、权益与动线
+
+### 3.1 权益矩阵
+
+| 维度 | 试用 | 入门(个人) | 进阶(个人) | 企业 |
+|---|---|---|---|---|
+| 容器来源 | 平台提供 | 平台提供 | 平台提供 | 平台提供/企业管理共享 |
+| 包含容器数 | 1 个 | 固定 1 个 | 3 个 | 每个 Company 共享 5 个 |
+| 增配 | 不支持 | 不支持,需升级 | 可付费增配 | 可付费增配,Company 共享 |
+| 规格基线 | 已验证 2 核 4G | 同左 | 同左 | 同左;不强制改造现存资产 |
+| 云资源与通信 | 独立云资源四件套、harness、Matrix 接入信息 | 同左 | 同左 | 企业资源按 Company 隔离,成员各自 Matrix 身份 |
+| 期限/费用 | 每账号一次 48h,完整 ready 后计时 | 月费,待定/咨询 | 年费,含一年资源,待定/咨询 | 计价及金额待定/咨询 |
+
+**四件套** = appId / serverURL / functionsURL / **独立资源专属凭据,绝非平台管理 masterKey**(平台实际字段可能名为 masterKey)。平台管理 masterKey 永不下发。专属凭据仅在服务端确认独立资源作用域、本人授权、已就绪、二次确认后受控短时返回;默认遮蔽,不进前端静态包、日志、埋点、localStorage。若平台只能返回共享管理密钥,不得当作交付成功,须由平台修复隔离。Matrix 凭据同样限制当前用户及被授权容器。接口设计可用 backend.credentialKind / credentialRef 标识类型和安全引用,最终以本轮 API 契约为准。
+
+价格与未决商业细项仅在《定价与权益-20261125-草案.md》维护;容器数、48h、规格不是价格,不能因价格待定隐藏已定权益。
+
+### 3.2 主流程
+
+1. 登录后服务端返回有效个人/企业权益、试用资格、配额与已有任务;已有有效权益者直接按对应权限使用,不要求先领试用。
+2. 无有效权益者领取试用或申请套餐。试用资格通过即可受理;付费申请先等待首期人工收款及套餐确认,确认前不得伪装进入创建队列。
+3. 创建受理时校验权限、幂等与配额并原子预占,返回持久化任务 ID;平台执行器推进六阶段。
+4. 等待页按 §3.4 显示友好当前状态、真实进度、必要时间及操作;刷新、关页和换设备可找回同一任务。
+5. 完整核验并由服务端返回 ready 才开放使用;首容器及独立资源完整 ready 时,服务端开始试用 48h。
+6. 试用到期仅锁定项目使用并进入付费页,容器与数据不停不删;确认付费后恢复同一容器,不重复创建、不丢数据。
+
+### 3.3 状态术语
+
+权益、支付确认和创建任务分别建模。任务状态只使用 **queued / provisioning / verifying / ready / failed**。已收款、已登记 FmodeAgent、等待时间已到都不是 ready。
+
+阶段固定为 **entitlement / cloud / matrix / container / connectivity / verification**,对应权益、独立云资源、Matrix、容器、连通性、交付核验。平台执行器上报结构化阶段结果;每阶段有待执行、执行中、成功、失败等可判定结果。DTO、错误码与存储模型以本轮接口/架构设计为准。
+
+预约状态与任务状态分别建模:**held / committed / released**。受理后 held,资源完整交付后结转 committed;失败且平台回查确认**无实体、无在途外部操作**时才以 CAS 原子释放为 released,保留原 job 与释放证据。部分资源已建或结果未知维持 held,不得由客户端自行释放。held 重试复用预约;released 重试必须对**同一 job 原子重新预占**,成功后才续跑;额度已被其他任务占用时返回 **QUOTA_EXCEEDED**,保持 **failed/released**,不新建 job、不超额放行、不重置试用资格或已开始的 48h。
+
+### 3.4 前台文案与进度呈现
+
+产品页面仅显示用户当前状态:queued→**等待开通**、provisioning→**正在开通**、verifying→**即将就绪**、failed→**开通失败**、ready→**已就绪**,配合服务端事实驱动的真实进度、必要时间和可执行操作。云资源、Matrix、预占、核验器等内部六阶段保留在 API、日志与技术文档,**不要求前台逐条展示内部执行清单或解释架构**;真实进度仍须可从技术记录验证,不能用动画或时间伪造。故障提示简短且可行动,如“暂时无法开通,请稍后重试”,只提供允许的重试/联系支持等操作,不透出内部组件或原始错误。价格、试用期限与到期结果、名额和增配资格等用户决策必要信息保留。此项为既定需求的文案呈现澄清,不变更业务状态、权限与验收事实。
+
+## 四、功能需求
+
+| 编号 | 需求描述 | 优先级 | 画像 |
+|---|---|---|---|
+| FR-21 | 套餐与试用展示:双端展示 §3.1 全部已定权益、领取/申请入口、当前权益与咨询价格;入门由平台提供 | P0 | 新用户/企业管理员 |
+| FR-22 | 申请与人工确认:入门、进阶及允许的增配可提交意向;授权人员确认收款/套餐/加购后由平台受理异步创建;重复确认不重复授予权益或建任务 | P0 | 个人/企业管理员 |
+| FR-23 | 资源交付:试用、入门、进阶均交付独立云资源四件套和 Matrix 接入信息;未 ready 展示友好当前状态与真实进度;凭据按 §3.1 安全交付,平台管理 masterKey 永不下发 | P0 | 个人用户 |
+| FR-24 | 平台容器与核验:新容器使用 2 核 4G 基线,由平台执行器创建、初始化、接入与核验,完整 ready 才开放;用户无需自备服务器、DM 或 SSH | P0 | 全部 |
+| FR-25 | 归属与管理:区分个人与 Company 企业容器,保留既有重命名;服务端过滤列表与权限,不把企业 5 个误计为每成员 5 个 | P1 | 已开通用户 |
+| FR-26 | 企业线优化:加入企业说明、联系管理员与复制本人 ID;入企后企业分组、共享容器与 Company 配额;个人线不自动入企 | P1 | 企业成员/管理员 |
+| FR-27 | 权限与降级:服务端权威判定权益、项目使用与配额;未知/错误可重试;无权益引导试用/付费,已有有效个人/企业权益不因试用失败或到期降级 | P0 | 全部 |
+| FR-28 | 一次 48h 试用:账号原子保留一次资格;首容器及云资源完整 ready 后服务端计时;失败续用原申请,到期锁项目但容器数据不停不删,付费恢复原容器 | P0 | 新用户 |
+| FR-29 | 配额与增配:试用 1、入门固定 1、进阶 3、Company 共享 5;仅进阶/企业可付费增配;按 §3.3 held/committed/released 预约、CAS 释放及同 job 原子重占,防止超额和泄漏 | P0 | 全部 |
+| FR-30 | 异步任务:五状态六阶段由平台执行器驱动;幂等受理、恢复同任务、结构化失败与安全重试,复用已建资源;禁止解析自然语言或计时制造成功 | P0 | 全部 |
+
+## 五、非功能需求
+
+- 安全:逐请求校验用户/Company/资源授权;不透传管理接口原始响应。平台管理密钥不进入任何客户端响应、包、存储、日志与埋点;专属资源凭据按受控查看复制交付。
+- 一致性:并发、多设备与执行器重启不重复消耗试用、不重复占额、不重复建容器、不重置试用;任务和补偿可审计。
+- 可恢复:断网只改变页面连接状态,不把任务判成业务失败;重连后读取服务端快照;技术记录保留失败阶段、脱敏错误、重试条件与任务 ID,前台仅显示简短可行动的故障提示和允许操作。
+- 双端可访问:桌面和移动行为一致;触控目标 ≥44×44px、移动正文 ≥16px,覆盖加载、空、执行、成功、错误、受限状态。
+- 轮询/审计:统一数据更新机制,页面不增加重叠轮询;审计任务、阶段、时间、脱敏错误,不记录凭据。
+- 时长:**未实测只展示友好当前状态、真实进度与必要已耗时,不承诺固定完成时间**。后续专用验收账号和新验收容器从受理至 ready 计时;初始参考分钟数 = ceil(实测总秒数 × 1.30 / 60),记录样本、原始起止时刻、阶段耗时和取整方式。参考超时不自动成功、不开始试用。
+
+## 六、验收标准
+
+下列条件均**待执行,不代表已通过**。原型验证交互;平台联调验证真实资源、权限和持久化,两者不能互代。
+
+| 编号 | 可验证条件 | 关联 |
+|---|---|---|
+| AC-21.1 | 双端逐格核对 §3.1:试用/三档、1/1/3/5、2 核 4G、48h、入门月费、进阶年费含一年资源一致;价格仅待定/咨询 | FR-21 |
+| AC-21.2 | 扫描套餐原型/页面/文案,无具体货币金额、入门自托管或进阶不含独立云资源的生效说明;待定价格不隐藏已定权益 | FR-21 |
+| AC-22.1 | 提交后显示待人工确认,不显示已建;授权确认后返回平台任务 ID 并进入等待页;篡改客户端确认标记不能创建 | FR-22 |
+| AC-22.2 | 同申请重复/并发提交与确认只返回同一有效结果,权益/任务不重复;未授权确认返回权限错误 | FR-22 |
+| AC-23.1 | 分别用试用/入门/进阶 ready 账号核对独立资源归属、四件套受控交付记录及 Matrix 信息;未 ready 显示与技术阶段事实对应的友好当前状态/真实进度,不能读取凭据 | FR-23 |
+| AC-23.2 | 普通响应/错误/前端静态包/日志/localStorage 无平台管理 masterKey;授权查看专属凭据前校验独立作用域、本人、ready、二次确认;默认遮蔽,复制提示勿外发 | FR-23 |
+| AC-23.3 | 模拟平台返回共享管理密钥,服务端拒绝交付且不得将该核验判为成功;跨账号请求专属凭据被拒绝,短时授权过期后需重新确认 | FR-23 |
+| AC-24.1 | 专用新账号经平台创建后核对新容器归属、2 核 4G、独立资源及 Matrix,证据关联同一任务;用户无需主容器/SSH 操作 | FR-24 |
+| AC-24.2 | 阻断连通性或任一核验项不得 ready/放行;全核验通过后才 ready,完成 Matrix 请求回读及本任务规定的心跳核验 | FR-24 |
+| AC-25.1 | 同时有个人/企业权限者可区分归属、重命名仅限授权容器;跨用户/Company 请求被拒绝,个人列表按 mine 权限范围 | FR-25 |
+| AC-25.2 | 同 Company 两成员返回同一共享已用/预占/总额,不能各领 5 个;成员退出后企业使用接口拒绝其旧权限 | FR-25 |
+| AC-26.1 | 未入企者可看加入说明、复制本人 ID、联系管理员;管理员拉人后下次既有刷新进入企业,无需重注册或领试用 | FR-26 |
+| AC-26.2 | 通讯录按 Company→成员/容器分组;无企业不出现虚假分组;个人申请不自动 openyd-join/git-join;企业成员各用自己的 Matrix 身份 | FR-26 |
+| AC-27.1 | 无有效权益请求项目使用接口被拒绝并可进入试用/付费引导;改路由/roles/localStorage 不改变服务端结果;清本地存储不丢权益 | FR-27 |
+| AC-27.2 | 查询断网/报错显示错误和重试,不覆盖为未开通;有有效个人或企业权益者在试用失败/到期后仍可按有效权益使用 | FR-27 |
+| AC-28.1 | 同账号并发/跨设备领取只得一份试用申请;失败重试复用同份申请;重新登录不能再次领取 | FR-28 |
+| AC-28.2 | 任意延长创建等待,ready 前试用未开始;首容器和云资源完整 ready 时服务端一次写 trialStartedAt/trialEndsAt,差值为 48h;刷新/改客户端时钟/重试不重置 | FR-28 |
+| AC-28.3 | 用可控服务端时钟验证到期前允许、到期起锁项目并进付费页;容器运行且数据保留;确认付费后容器 ID 和测试数据不变,无新实体容器 | FR-28 |
+| AC-29.1 | 试用/入门满 1、进阶满 3、Company 满 5 时请求创建均返回明确配额错误;试用/入门不能加购生效,进阶/企业仅付费增配确认后增额 | FR-29 |
+| AC-29.2 | 仅余 1 名额并发两次创建最多受理 1 次;queued/provisioning/verifying 计预占;同幂等键重放不重占,不同请求不越限 | FR-29 |
+| AC-29.3 | 创建资源前后分别注入失败:只有平台回查确认无实体且无在途外部操作才 CAS 将 held 置 released,保留原 job/释放证据;部分资源或结果未知维持 held,held 重试复用预约;完整交付结转 committed。对账“已用+有效预占≤总额”,无双重计数或泄漏 | FR-29 |
+| AC-29.4 | 对 released 原 job 重试:有额时原子重占并续跑同 job,并发重试仅得一份有效预约;额度被其他任务占用时返回 QUOTA_EXCEEDED 且保持 failed/released,不新建 job、不超额放行,试用资格及已开始的 48h 不重置 | FR-29 |
+| AC-30.1 | 注入五状态与六阶段结构化快照,两端按 §3.4 显示对应友好当前状态与真实进度,内部六阶段在 API/日志可核对、不要求前台逐条展示;任意延长 queued 或未完成阶段,不因计时/自然语言变 ready | FR-30 |
+| AC-30.2 | 关页、刷新、重新登录、换设备均恢复同一任务 ID、资源标识、阶段和时间;在途任务回等待页,不新建 | FR-30 |
+| AC-30.3 | cloud/matrix/container/connectivity/verification 逐阶段注入失败,API/日志可定位失败阶段与脱敏错误;前台故障提示短且可行动,仅显示允许操作、不透出架构;重试鉴权并复用申请及资源,不重复容器或试用计时 | FR-30 |
+| AC-30.4 | 创建 API 未实现/未支持时技术记录明确依赖未就绪或失败,前台显示友好失败/稍后重试提示,不回落 DM、不标成功;客户端超时后能查询同一任务真实结果 | FR-30 |
+| AC-30.5 | 无样本时不显示预计完成承诺;新资产实测后核对起止/阶段耗时与 ceil(总秒数×1.30/60),只作初始参考,超时仍以服务端状态为准 | FR-30 |
+
+## 七、业务规则与约束
+
+1. 价格唯一维护点为定价文档;已定配额、试用、资源与付费频率不重复征询。
+2. 人工仅收款、套餐/加购确认;创建、阶段、核验、试用计时与项目权限由平台服务端执行。历史 DM/SSH 不构成产品 API。
+3. 一次 48h 资格与历史“个人试用组织”标记分开建模;历史标记不自动授予本次试用、不重置时间、不把企业成员降级;映射在服务端设计核对。
+4. 试用到期不停不删,只限制项目使用;付费恢复同一容器。已有有效个人/企业权益优先保持,项目使用各服务端入口统一判定。
+5. 企业 5 个及增配按 Company 共享;成员各用自己的 Matrix 身份,不向全公司分发个人 token。
+6. 列表可见、自然语言完成、固定等待时间、动画走完均不是 ready。
+7. lj-test 与旧生产/历史资产仅只读;真实计时、创建、故障注入与恢复使用专用验收账号和新验收容器及其测试数据。
+
+## 八、依赖与影响
+
+| 项目 | 事实/要求 | 状态 |
+|---|---|---|
+| 独立资源 | subscription status / trial-standalone / retry 有历史局部实证,不能直接等同本版 48h 试用 | 待核对适配 |
+| Matrix/登记/成员 | RP5Ht55NeX、xlosi3m46q、mgR4EA2n5a 为可复用候选 | 须逐项联调 |
+| 实体创建 API | 需平台提供异步受理、执行、阶段、查询、重试 | **未确认实现,未上线** |
+| 权益/试用/配额 | 服务端存储、原子预占、对账与审计 | 设计态,未实现 |
+| 支付 | 首期人工确认,在线支付契约未核对 | 在线支付后置 |
+| API | docs/03-interface/api/套餐与平台异步开通-API契约.md | 本轮设计,待评审/平台确认 |
+| 架构 | docs/02-design/architecture/套餐权益与异步开通设计.md | 本轮设计,待评审 |
+| 双端原型 | prototypes/fmode-subscription-20261125/index.html | 已产出、独立复审中;G-D1 待用户确认 |
+| 留痕 | docs/00-tracking/2026-11-25-套餐异步开通实施记录.md | 区分设计、实现和实测证据 |
+
+影响套餐入口、等待页、我的容器、接入信息、企业引导与项目服务端权限;表/字段、补偿与错误码在架构/API 设计维护。本版不声称“不动数据表”,不授权越过 G-D1。
+
+## 九、待验证事项
+
+- 平台确认创建 API 实现方、交付时间、资源接口复用和凭据隔离;缺失时不开展真实创建联调。
+- 新接口/架构设计明确历史试用映射、预占补偿、核验清单及企业权限刷新,提交新独立评审。
+- 后续专用账号与新容器实测后再给初始参考耗时;尚无样本只展示友好当前状态与真实进度。
+- 价格与付费续费运营未决项仅见定价文档,不重复询问已定业务口径;对应生命周期实现需另行定稿。
+
+## 十、评审记录
+
+| 日期 | 对象 | 状态 |
+|---|---|---|
+| 2026-11-25 | 阶段 0 v1.0 文档 | 原第 1 轮 7 项已闭环,仅属旧版历史,不覆盖本版新增裁决 |
+| 2026-11-25 | v1.1 及对应接口/架构/双端原型 | 已产出、独立复审中;补齐预约释放/同 job 重占与 AC-29.4;G-D1 待用户确认,未视为通过 |
+
+## 十一、变更历史
+
+| 版本 | 日期 | 内容 | 原因 |
+|---|---|---|---|
+| v1.0 | 2026-11-25 | 套餐范围及 FR-21~27 初稿 | CR-20261125-01 |
+| v1.1 | 2026-11-25 | 替换生效口径;保留 21~27,新增 28~30 与可验证 AC;明确平台依赖、试用、配额与安全边界 | CR-20261125-02 |

+ 1 - 0
docs/01-requirements/prd/SPEC-20261014-fmode-app-v2-草案.md

@@ -302,6 +302,7 @@ Fmode 双端客户端(桌面横版 + 手机竖版)· **人机共生 IM 中枢**:
 | 变更传播链 | 同上末尾 |
 
 **当前规模**:21 条 FR 行(FR-01~FR-20 + FR-07b),13 条 NFR 行。
+**FR-21 起**:套餐与开通体系需求见 `PRD-20261125-套餐与开通体系.md`(CR-20261125-01,FR-21~27 不在本文件维护)。
 
 ---
 

+ 85 - 0
docs/01-requirements/prd/定价与权益-20261125-草案.md

@@ -0,0 +1,85 @@
+# 定价与权益(草案)
+
+| 字段 | 值 |
+|---|---|
+| 文档编号 | PRICE-20261125-01 |
+| 版本号 | v0.2 |
+| 最后更新日期 | 2026-11-25 |
+| 状态 | **业务权益已确认;全部价格待定/咨询;本版待新独立评审** |
+| 变更原因 | CR-20261125-02:平台入门容器、一次 48h 试用、1/1/3/5 配额与异步开通 |
+| 关联 | PRD-20261125-套餐与开通体系 v1.1 · PLAN-20261125-套餐体系 v1.1 |
+
+> **本文件是价格唯一维护点。** 金额未定前,原型、UI、文案、代码和其他文档只能显示“待定/咨询”。容器数、规格、48h 与月/年周期是已定权益,须如实展示。不得在多份文档维护另一套价格表。
+
+## 一、权益对照(当前生效)
+
+| 维度 | 试用 | 入门(个人) | 进阶(个人) | 企业 |
+|---|---|---|---|---|
+| 核心交付 | 平台容器 | 平台容器 | 平台容器 | Company 共享企业容器及成员能力 |
+| 基础容器数 | **1** | **固定 1** | **3** | **Company 共享 5**,不是每成员 5 |
+| 增配 | 不支持 | 不支持,需升级 | 支持付费增配 | 支持付费增配,Company 共享 |
+| 新容器规格基线 | 已验证 **2 核 4G** | 同左 | 同左 | 同左;不改造现存资产 |
+| harness / Matrix | 提供,含接入信息 | 提供,含接入信息 | 提供,含接入信息 | 企业成员各自 Matrix 身份 |
+| 独立云资源四件套 | **包含** | **包含** | **包含** | 按企业 Company 归属隔离 |
+| App 双端使用 | 有效试用权益内 | 有效套餐权益内 | 有效套餐权益内 | 有效企业授权内 |
+| 期限与计费 | 每账号一次 **48h**,首容器及云资源完整 ready 后服务端起算 | **月费** | **年费,含一年资源** | 商业计价口径待定/咨询 |
+| 基础金额 | 试用无付费报价 | **待定/咨询** | **待定/咨询** | **待定/咨询** |
+| 增配金额 | 不适用 | 不适用 | **待定/咨询** | **待定/咨询** |
+
+四件套指 appId / serverURL / functionsURL / **独立资源专属凭据,绝非平台管理 masterKey**(平台实际字段可能名为 masterKey)。平台管理密钥永不下发;专属资源凭据仅在服务端确认独立作用域、本人授权、已就绪及二次确认后受控短时交付,默认遮蔽,不进入前端静态包、日志、埋点、localStorage。若平台仅返回共享管理密钥,不能当作成功交付,需平台修复隔离。
+
+本期先行个人试用/套餐及加入企业两条动线;企业高级账套管理后议。入门来源、各档配额、进阶含云资源、试用期限及到期处理均已裁决,不再作为定价开放问题。
+
+## 二、试用及续用规则(已定)
+
+1. 每账号只能领取一次 48h,重复/并发领取只能找回同一申请。创建失败可重试原申请,不得新发试用或重置时间。
+2. 领取或支付确认时不提前计时;首容器和独立云资源完整核验 ready 时由服务端写入起止时间,连续 48h。
+3. 到期**容器及数据不停不删**,只锁定项目使用并引导付费。确认付费后恢复**同一个容器**及原数据,不新建替代容器。
+4. 已有有效个人或企业权益不因试用状态降级。历史个人试用组织标记不直接替代本版资格和计时。
+5. 本节只确定试用到期规则;付费套餐到期/续费运营细项尚未全部确定,见 §五,不得擅自推导可停机/删数据。
+
+## 三、收款与开通分期
+
+| 阶段 | 当前规则 |
+|---|---|
+| 首期收款 | 套餐申请→授权人员人工收款与套餐确认;加购也需人工确认,价格仍待定/咨询 |
+| 确认后的开通 | **平台 API 异步受理→执行器推进六阶段→完整核验 ready**;不能用人工 DM/SSH 创建冒充产品流程 |
+| 任务与配额 | 幂等受理、服务端权限、并发预占;失败可恢复/重试,复用已建资源;见 PRD FR-27/29/30 |
+| 后续在线支付 | 平台支付链路存在逆向线索,契约未核对;另行确认后再接,不纳入首期 |
+
+实体容器创建 HTTP 入口尚无已确认实现;平台实现是上线依赖。旧主容器创建实证仅为技术参考,不表示本产品异步开通已上线。
+
+## 四、成本测算锚点(不产生报价)
+
+| 成本项 | 测算口径 | 覆盖 |
+|---|---|---|
+| 容器算力 | 2 核 4G × 包含容器数 × 权益期限;进阶基础年费含一年资源 | 试用/入门/进阶/企业 |
+| 独立云资源 | 独立 backend、存储、数据、函数的增量与隔离成本 | 试用/入门/进阶及企业归属 |
+| Matrix 通信 | 身份、房间、消息/媒体增量,成员身份隔离 | 全部 |
+| 异步执行与运维 | 平台执行器、阶段审计、核验、补偿和故障重试成本 | 全部 |
+| 试用保留 | 到期保留运行容器及数据的成本,应纳入经营测算 | 试用 |
+| 付费增配 | 超出基础数的资源成本、周期与人工确认成本 | 进阶/企业 |
+| 支付通道 | 后续实际接入的手续费;当前不假定通道或费率 | 付费套餐 |
+
+不引用外部市价或未经验证的“近零”成本,不以历史脚本耗时替代平台实际执行成本。资源保留成本不能成为擅改试用到期规则的理由。
+
+## 五、真正未决的定价与运营事项
+
+| 编号 | 未决事项 | 当前占位与边界 |
+|---|---|---|
+| P-01 | 入门月费金额 | 待定/咨询;月费和固定 1 个已定 |
+| P-02 | 进阶年费金额 | 待定/咨询;3 个、含一年资源已定 |
+| P-03 | 企业金额与商业计价单位 | 待定/咨询;Company 共享基础 5 个已定,不能写每成员 5 个 |
+| P-04 | 进阶/企业付费增配的单价、购买周期与生效细项 | 待定/咨询;允许增配与人工确认已定,未确认不增额 |
+| P-05 | 付费套餐续费、变档、付费期满与超额存量的运营细项 | 本期不擅定停机/删数据;不得覆盖试用到期不停不删及有效权益不降级规则,落地前另行确认 |
+
+**无需再问**:入门是否平台提供、进阶是否含云资源、试用多久、何时起算、试用到期是否删容器、基础数量、哪些档可增配,均以 §一/二为准。实现字段与接口形态由技术设计确定并留痕,不混入业务裁决清单。
+
+## 六、变更与评审历史
+
+| 版本 | 日期 | 内容 | 依据/状态 |
+|---|---|---|---|
+| v0.1 | 2026-11-25 | 原始权益与价格草案 | CR-20261125-01;被本版覆盖的口径不再生效 |
+| v0.2 | 2026-11-25 | 平台入门容器、48h、1/1/3/5、独立资源、增配、异步开通;移除已定项的重复征询 | CR-20261125-02;待新独立评审 |
+
+原阶段 0 文档评审 7 项闭环仅覆盖旧版,不作为本版审查结论。

+ 103 - 0
docs/02-design/architecture/套餐权益与异步开通设计.md

@@ -0,0 +1,103 @@
+# 套餐权益与平台异步开通设计
+
+| 字段 | 内容 |
+| --- | --- |
+| 版本/日期 | v0.1 / 2026-11-25 |
+| 状态 | G-D1 前置设计,待独立评审和用户原型确认 |
+| 执行基准 | PLAN-20261125 v1.1;CR-20261125-02;FR-21~30 |
+| 接口 | `docs/03-interface/api/套餐与平台异步开通-API契约.md` |
+| 原型 | `prototypes/fmode-subscription-20261125/index.html` |
+
+## 一、边界与职责
+
+本阶段交付需求同步、数据与接口设计、可交互双端原型,**不修改产品路由/业务代码,不注册云函数、不创建容器、不进行真实计时**。产品开发须先通过G-D1;平台原子性、创建执行器、验收器映射和资源隔离能力需在生产实现阶段核实。
+
+已确认:试用1、入门1(改平台容器)、进阶3、企业共享5;试用/入门/进阶交付独立资源与本人Matrix信息,企业复用企业资源归属;进阶和企业可增配,入门固定1;付费金额继续待定。资源规格一期复用已验证的2核4G,不新增规格选择。
+
+| 层 | 唯一职责 |
+| --- | --- |
+| 双端页面 | 展示权益/任务/参数、收集意向;不自行判授权或执行运维 |
+| PlanService(拟新增) | 套餐权益与申请状态owner,维护服务端snapshot和短时内存参数展示 |
+| ProvisioningService(拟新增) | 任务恢复/进度投影,订阅统一刷新调度;不通过AI消息推进 |
+| FmodeApi / ParseApi / MockApi | 新领域接口抽象、真实Functions适配、离线演示适配;页面不直调API |
+| 平台Functions | 认证、租户与资源归属、试用/付费权益、原子配额、持久任务、只读状态和脱敏DTO |
+| 平台执行器 | 租约领取、阶段checkpoint、复用现有受控创建通道与模板、回报机器核验 |
+
+## 二、数据模型(拟新增,未建表)
+
+不向FmodeAgent或User字段随意塞入商业状态。拟增加独立权益聚合、任务和申请记录,现有agent与Matrix绑定继续维护真实资源归属。
+
+| 逻辑实体 | 核心数据及约束 |
+| --- | --- |
+| SubscriptionAccount | subjectKey唯一;个人user或企业Company;planCode、基础/增配额度、试用已领与起止时间、迁移状态、版本;持久额度预约/outbox需与名额校验原子更新 |
+| SubscriptionApplication | 人工收款/加购意向、申请人、主体、套餐或名额、运营确认引用、幂等键;确认不能由普通用户改字段实现 |
+| ProvisionJob | reservation唯一引用、幂等摘要、五状态六阶段、attempt、resourceRefs、任务时间、脱敏错误、核验器版本、执行器租约及fencing |
+| ResourceCredentialRef | 服务器受限密钥存储的引用/存在性/所属主体;普通状态表不保存可返回的秘密明文 |
+
+业务实体统一company隔离、软删isDeleted。个人subject与资源Company并非同一个概念:个人已入企仍可持有其个人权益;Company有值不代表企业有效套餐。字段/唯一约束以平台Schema能力核实后落地,不私自声称已有数据库事务。
+
+### 一致性要求
+
+1. 额度聚合一次CAS或事务同时完成剩余额度检查、reservation和outbox意图;count后save不可接受。
+2. outbox重复投递按reservation得到同一个job;job外部operationKey稳定,防止重复建容器/房间/云资源。
+3. worker回写必须匹配新鲜租约与fencing;阶段完成后持久checkpoint,进程重启可回查续做。
+4. 部分创建、返回丢失、心跳待落库均不是“没创建”;未知结果保留预约和实体引用,回查前不释放。
+5. 首次ready原子结转名额并一次性激活试用;续费只恢复原agentId的准入,不创建第二份容器。
+6. 失败且平台已证明没有实体和在途外部操作时,可原子释放预约,原job保留。重试该released任务时必须原子重新预约;若其他任务已用完配额则返回QUOTA_EXCEEDED,保持原任务失败,不超卖;held任务原预约续跑。
+
+## 三、访问路径与兼容
+
+### 3.1 路由与准入
+
+- 设计根入口 `/plans`(套餐/付费)与 `/activation/:jobId`(等待),只挂auth;按既有设备识别加载不同端页面。双端侧栏/抽屉/我的页入口均指向同一领域路径。
+- 原 `/pending` 保留“等待企业邀请”,补上个人试用/套餐分流;不要把组织等待与开通任务混成一个不可区分的pending。
+- 产品业务路由使用服务端权益结果;个人active不再被旧orgGuard的“无正式组织”强制挡回pending。组织身份与套餐准入拆开,不能把旧orgGuard查询异常failopen沿用为权益放行规则。
+- `appAccess=provisioning` 且没有既有可用容器时进入等待;已有可用容器新增任务只锁新容器。只有列表记录/agentId而无ready不能进会话。
+- `billing_required` 进入付费页;状态服务故障显示“暂无法核实”及重试,不伪造过期、不新授予权限;auth/billing/status恢复入口始终可访问,避免守卫循环。
+- 套餐/租户选择必须由服务端验证,不能从前端roles或localStorage派生额度、有效期和资源可见性。
+
+### 3.2 活跃页面到期
+
+导航守卫只能拦导航,正式实现还须消费统一状态更新:已到期时禁止本App发送/上传等操作,断开本App Matrix同步、清除会话内敏感字段,导航付费页;云函数业务动作也验证准入。不能停容器、删卷或撤销已交付外部token来实现本次付费锁。
+
+当前Matrix SDK直接sendEvent,外部已获token或独立后端专属凭据不会被前端守卫吊销。**本期只承诺项目App锁定;外部客户端/用户自持凭据仍可能可用**,不得写成“全平台资源停用”。企业有效作用域不受个人试用到期降级。
+
+### 3.3 存量迁移
+
+- 首先由服务端生成存量账号、现有有效组织授权、容器归属和权益的审计快照,并分类legacy_pending/legacy_allowed/migrated。
+- 没有新订阅记录、旧createdAt、旧30天个人试用组织标志均不能直接判定48h已过期。
+- 未分类账号进入显式迁移兼容路径,不一刀切锁定;只有完成迁移核对的cohort才启用新准入。上线前必须证明已有有效用户不回退,未满足不得全量开启。
+- 48h个人试用独立于平台旧30天试用组织;不修改底层组织生命周期,不把首次登录时间冒充容器交付时间。
+
+## 四、UI与原型说明
+
+原型为独立单HTML,可双击打开。沿用当前应用platinum默认配色以及底座surface/edge/ink/primary、明暗、间距、字号、圆角、z-index令牌;构建时从真实样式源内嵌,不修改底座。原型用带样式语义HTML模拟组件外形;正式实现必须换回现有UiCard/UiButton/UiModal及移动底座组件,不把原型壳直接挂产品路由。
+
+| 页面/状态 | 用户可见内容 |
+| --- | --- |
+| 套餐与试用 | 试用1、入门1、进阶3、企业5;价格待定;领取试用、提交付费意向 |
+| 等待开通 | 仅友好当前状态、真实进度、已等待/预计完成和必要操作;未测时显示“稍后更新”,不解释内部六阶段 |
+| 异常等待 | 离线保留最近状态、平台延迟但不判失败、明确失败后原任务续做 |
+| 我的容器 | 已用/预约/剩余额度、本人与企业归属、已有容器可继续、新容器等待、允许档加购 |
+| 接入信息 | 本人userMxId/homeserver及agentMxId/roomId/accessToken、独立资源四件套;默认遮蔽,查看/复制二次确认,全为原型假值 |
+| 到期付费 | 说明容器和数据保留,选择套餐,付费确认后原容器恢复 |
+| 企业加入 | 复制用户ID、联系管理员、等待加入、确认后企业有效权益放行、组织分组 |
+
+原型顶部“演示场景/模拟平台回报”属于评审工具,不是产品操作。它允许手动推进阶段、失败/重试、模拟断网/管理员确认/到期;不调用平台、不自动产生计时数据。原型刷新会重置内存,不作为正式跨设备恢复验收证据。
+
+2026-11-25追加用户呈现裁决:产品页面与弹窗只显示简短状态、必要的时间/价格/名额和可执行操作,不能解释服务端、API、Matrix配置流程、预占与验收器逻辑。内部六阶段仍用于任务事实、进度计算及技术诊断,不要求在产品页逐条展开。接入信息页保留用户实际需要复制的配置字段,仍不解释内部鉴权实现。
+
+正式移动正文至少16px、触控至少44px;浅/深色、320px与桌面布局均需检查。宽屏独立导航,小屏单列和底栏,模态框支持Esc、焦点约束与短屏滚动。
+
+## 五、后续实现与验收顺序
+
+1. 当前批次完成新需求及设计独立评审,提供可点击原型,用户明确确认后登记G-D1。
+2. 平台核实/实现受理、额度原子提交、执行器、受限秘密交付与验收器,注册ID;客户端按领域边界接入,先测试账号灰度。
+3. 使用专用验收账号和新建容器从平台API完整走一遍,记录queued/每阶段/重试/ready时长;不重置或修改lj-test、旧test-0001和生产资产。
+4. 优化重复请求、不必要等待和可安全并行步骤,复测后按契约公式配置参考预计时间;未测不显示固定分钟数。
+5. 覆盖FR-21~30全部AC,执行现有单测、双端端到端及生产构建、权限/安全/性能/上线独立评审;保留数据与存量用户兼容证据。
+6. 不自动commit/push;生产发布单独授权,按项目逐对象上传/CDN/裸链接校验规范执行,保护既有download官网。
+
+## 六、当前真实状态
+
+本设计中的平台原子CAS/事务、唯一索引、任务执行器、真实Function ID、专属凭据交付和完整v2.2验收器映射均待平台实现/核实。**本阶段不声称接口已通、容器已创建、真实耗时已测、G-D1已确认或产品功能已完成。**

+ 149 - 0
docs/02-design/plans/2026-11-25-套餐体系任务计划书.md

@@ -0,0 +1,149 @@
+# 套餐与开通体系 · 任务计划书
+
+| 字段 | 值 |
+|---|---|
+| 文档编号 | PLAN-20261125-套餐体系 |
+| 版本 | v1.1 |
+| 日期 | 2026-11-25 |
+| 状态 | **生效中的唯一执行基准;阶段 1 裁决收口,接口设计与双端原型已产出、独立复审中;G-D1 待用户确认** |
+| 上游 | CR-20261125-02(最新裁决)· PRD-20261125-套餐与开通体系 v1.1 · 定价与权益-20261125-草案 v0.2 |
+| 本次变更原因 | 入门改平台提供;一次 48h 试用;1/1/3/5 配额;平台异步受理/真实阶段/核验;替换旧人工创建产品流程 |
+| 用途 | 本任务唯一执行基准;API、架构、原型、实施记录为配套产出,不能另立互相冲突的执行计划 |
+
+## 一、目标、边界与当前状态
+
+产品主线:**登录 → 领取试用或开通套餐 → 平台接口受理异步创建 → 等待页友好当前状态与真实进度 → 核验 ready → 使用**。
+
+试用、入门、进阶均交付平台容器、独立云资源四件套与 Matrix 接入信息,复用已验证 **2 核 4G** 基线。第一期人工收款、套餐确认和加购确认;确认后的创建必须由平台接口/执行器异步执行。**历史人工 DM/SSH 创建不是产品流程,也不能成为 API 缺失时的降级方案。**
+
+- 阶段 0 原文档第 1 轮 7 项已闭环,该结论仅覆盖 v1.0 历史。
+- 最新业务裁决已收口,不再重复问入门来源、云资源、试用、配额等已定规则。价格继续待定/咨询。
+- 本轮 v1.1 需求/计划、接口设计、架构与双端原型已产出,**独立复审中,未宣称通过**。
+- **G-D1 待用户查看并确认本轮原型,确认前不写产品代码**。用户批准本计划不等于已确认原型。
+- 平台实体容器创建入口尚无已确认实现;接口设计不能冒充上线或真实联调完成。
+- lj-test 与旧生产/历史容器只读;本轮文档/原型不创建、不修改容器,不改凭据、不提交代码。
+
+## 二、最新裁决快照
+
+| 编号 | 生效规则 | 对应需求 |
+|---|---|---|
+| D-01 | 试用 1、入门固定 1、进阶 3、企业每 Company 共享 5 个;试用/入门不增配,进阶/企业可付费增配 | FR-21/25/29 |
+| D-02 | 入门由平台提供,不再要求自托管;试用/入门/进阶均含独立云资源与 Matrix | FR-23/24 |
+| D-03 | 云资源四件套 = appId/serverURL/functionsURL/独立资源专属凭据,**绝非平台管理 masterKey**;专属凭据受控短时查看复制,平台管理密钥永不下发 | FR-23 |
+| D-04 | 规格复用 2 核 4G;入门月费、进阶年费含一年资源;价格全部待定/咨询,唯一维护点为定价文档 | FR-21 |
+| D-05 | 人工仅收款/套餐/增配确认;确认后平台 API 受理异步任务,创建与核验不靠人工 DM | FR-22/24/30 |
+| D-06 | 每账号一次 48h;首容器和独立资源完整核验 ready 后服务端开始计时;失败重试不新发资格、不重置时间 | FR-28 |
+| D-07 | 试用到期容器数据不停不删,只锁项目使用并进入付费页;付费恢复同一容器;有效个人/企业权益不降级 | FR-27/28 |
+| D-08 | 五状态 queued/provisioning/verifying/ready/failed;六阶段 entitlement/cloud/matrix/container/connectivity/verification;由执行器结构化上报 | FR-30 |
+| D-09 | 权限服务端权威,任务原子预占配额,幂等、断点恢复、失败可重试且复用资源 | FR-27/29/30 |
+| D-10 | 不承诺固定创建时间;仅新验收账号/容器实测,总秒数 ×1.30 后向上取整到分钟作为初始参考,未测仅展示友好当前状态与真实进度 | FR-30 |
+| D-11 | 文档/接口设计/双端原型先行,本轮 G-D1 用户确认后才可编码 | 治理门禁 |
+
+## 三、执行前必读与事实边界
+
+| 文档/产出 | 用途与状态 |
+|---|---|
+| docs/01-requirements/changes/CR-20261125-套餐体系纳入范围.md | v1.0 原始范围与历史裁决;被 CR-20261125-02 覆盖的旧条款不再生效 |
+| docs/01-requirements/changes/CR-20261125-02-平台容器与试用异步开通.md | 本轮变更请求、确认规则、影响和验收 |
+| docs/01-requirements/prd/PRD-20261125-套餐与开通体系.md | FR-21~30 及全部可验收 AC;v1.1 待新评审 |
+| docs/01-requirements/prd/定价与权益-20261125-草案.md | 价格唯一维护点;权益已定、金额待定 |
+| docs/02-design/architecture/套餐权益与异步开通设计.md | 本轮服务端权限/权益/试用/配额/任务模型,设计态 |
+| docs/03-interface/api/套餐与平台异步开通-API契约.md | 本轮异步受理、查询、重试、凭据交付契约,设计态;平台实现待确认 |
+| prototypes/fmode-subscription-20261125/index.html | 桌面/移动双端原型与可演示状态,G-D1 待用户确认,假数据不作实测 |
+| docs/00-tracking/2026-11-25-套餐异步开通实施记录.md | 本轮设计、门禁、后续实现与实测证据 |
+| docs/00-tracking/AI接手说明-套餐体系与容器资产.md | 接手次序、凭据位置索引、资产只读边界 |
+| docs/04-quality/traceability-matrix.md | FR↔AC↔设计/API↔测试/提交/Schema 证据,不得提前标通过 |
+| docs/03-interface/容器创建完整流程-接口与提示词-20261124.md | 2026-11-24 历史人工链路和局部接口实证;不覆盖本轮产品裁决 |
+| docs/03-interface/容器接入完整指南-v2-20261111.md | Matrix 接入实证与 reaction/心跳等核验参考 |
+| docs/03-interface/需求-同公司共用容器-20261112.md | 同公司共用、各自 Matrix 身份的既有裁决 |
+| docs/02-design/architecture/账号与账套体系设计.md | _User/Profile/Company/_Role 身份模型参考,结合现状核对 |
+
+局部事实:独立资源 status/trial-standalone/retry、Matrix RP5Ht55NeX、登记/列表 xlosi3m46q、成员 mgR4EA2n5a 有既有能力;不能据此推导“一次 48h 试用/原子配额/异步实体创建均已实现”。平台在线支付逆向线索未核对,本期不接入。
+
+## 四、目标执行流程与交付判据
+
+### 4.1 个人线
+
+1. 登录后取服务端权益、试用资格、配额和在途任务。有效个人/Company 权益直接使用;无权益提供试用与付费入口。
+2. 试用原子领取一次资格;付费套餐和增配待人工确认,不把未确认申请伪装 queued。
+3. 平台创建 API 校验权限/幂等/额度并预占,持久化任务 ID。
+4. 执行器推进 entitlement → cloud → matrix → container → connectivity → verification;等待页将结构化状态映射为友好当前状态和真实进度,不读自然语言日志猜进度,不逐条展示内部执行清单。
+5. 完整核验资源作用域、容器/Matrix/连通性/交付项后服务端 ready;试用首个完整 ready 时一次写入 48h 起止时间。
+6. 列表按服务端归属显示“我的容器”;专属资源四件套和 Matrix 凭据按权限受控交付,不透传平台管理 masterKey。
+7. 试用到期限制项目使用,保留运行容器与数据;确认付费恢复同一容器和数据;有效付费个人/企业权益不受试用状态拖累。
+
+### 4.2 企业线
+
+加入说明/本人 ID 复制/联系管理员 → 授权管理员拉人 → 服务端刷新成员与 Company 权益 → 通讯录公司分组/企业容器。基础 5 个及增配全公司共享;成员各自 Matrix 身份。退出企业后服务端撤销相应权限;个人线不自动 openyd-join/git-join。现存企业资产不因本计划强制改造。
+
+### 4.3 任务、配额和恢复
+
+- 任务五状态与六阶段分开存储;ready 只能由完整核验结果提交。
+- queued/provisioning/verifying 占预留额度;并发仅余一额最多受理一个请求。同幂等请求不重复占额。
+- 预约状态 held/committed/released 与任务状态分开;受理后 held,完整交付结转 committed。失败且平台回查确认无实体、无在途外部操作时,才 CAS 原子释放为 released,保留原 job 与释放证据;部分资源或结果未知维持 held。
+- held 重试复用原预约;released 重试须对同一 job 原子重新预占,有名额才续跑。额度已被其他任务占用时返回 QUOTA_EXCEEDED,保持 failed/released,不新建 job、不超额放行、不重置试用资格或已开始的 48h;并发重试不得重复预约。
+- 关页、刷新、换设备和网络超时后恢复同任务;API/日志记录失败阶段和脱敏原因,前台仅显示简短可行动故障提示及允许的重试。
+- 平台入口未就绪时技术记录明确依赖,前台显示友好失败/稍后重试提示;不用固定时间、自然语言“完成”或前端动画标 ready。
+
+### 4.4 UI 表现规则(文案呈现澄清)
+
+前台仅显示**等待开通 / 正在开通 / 即将就绪 / 开通失败 / 已就绪**等友好当前状态、服务端事实驱动的真实进度及必要时间/操作。云资源、Matrix、预占、核验器等内部六阶段保留于 API、日志和技术文档,前台不逐条解释执行清单或架构。失败文案须短且可行动,只给出允许的重试/稍后重试/联系支持等动作,不透出内部组件或原始错误;平台依赖未就绪同样以友好当前状态呈现,技术原因留在技术记录。价格、试用与到期结果、名额和增配资格等用户决策必要信息保留。此澄清不新增需求编号,不改变五状态六阶段的真实性、ready/权限/预约/恢复验收语义。
+
+## 五、阶段计划与原子任务
+
+以下每项包含类型、范围、动作、验证、安全与完成标准。产品代码任务必须等待 G-D1。
+
+| 任务 | 类型 | 涉及文件/范围 | 执行动作 | 验证方法 | 安全检查 | 完成标准 |
+|---|---|---|---|---|---|---|
+| 0.1 原文档闭环 | auto(历史) | 原 CR/PRD/定价/计划/原评审 | 保留阶段 0 原 7 项闭环记录 | 查原评审问题表 | 不把历史结论移植为新版本通过 | v1.0 历史已闭环;不代表 v1.1 通过 |
+| 1.1 本轮业务同步 | auto | 本计划、CR-02、PRD v1.1、定价 v0.2、接手说明、矩阵、索引 | 全文替换冲突口径,登记 FR-28~30 | 编号/引用/旧口径扫描及 AC 覆盖 | 凭据仅位置索引、无真实密钥 | 生效口径一致;待新独立评审 |
+| 1.2 契约与架构 | auto | 本轮 API/架构文档 | 定义服务端权益、试用、配额、异步任务、凭据与错误/恢复 | 与 PRD 全 AC 逐项对照 | 平台管理密钥不下发、Company 隔离、原子预占 | 设计产出齐全,明确平台未实现依赖 |
+| 1.3 平台依赖确认 | human-verify | API 契约/实施记录 | 确认实现方、端点、阶段上报、幂等/补偿与资源隔离 | 平台确认记录,不以旧脚本代替 | 不调用生产创建,不修改旧资产 | 平台实现边界可追踪;未就绪保持阻塞 |
+| 2.1 双端原型 | auto | prototypes/fmode-subscription-20261125/ | 试用/套餐、人工确认、阶段等待、ready、失败重试、到期付费、容器/企业配额与凭据 | 桌面/移动逐状态演示,覆盖 PRD AC | 凭据用明确假值、无真实接口写入 | 可供用户查看与审阅,不宣称已上线 |
+| 2.2 本轮独立评审 | auto | v1.1 需求/架构/API/原型、review/ | 独立需求/架构/安全/UI 检查,问题修复后复审 | 专项检查单+文件证据+闭环记录 | 不自评替代评审;旧报告不覆盖新物 | 新评审结论真实记录,未通过不标完成 |
+| 2.3 G-D1 | human-verify | 本轮双端原型/确认记录 | 向用户展示本轮原型并记录明确确认 | 用户确认记录 | 无产品代码、无外部资产变更 | **用户确认后才开放阶段 3** |
+| 3.1 试用开通切片 | auto(门禁后) | 以本轮设计确认的前端/平台服务端/Schema/API 为准 | 登录→领取→异步创建→核验→使用→到期→付费恢复 | AC-21/23/24/27/28/30 单测+集成 | 权威权限、一次资格、凭据隔离 | 对应 AC 通过,文档矩阵有证据 |
+| 3.2 付费/配额切片 | auto(门禁后) | 套餐确认/容器/企业与配额链路 | 人工确认后平台创建、增配、Company 共享、并发预占 | AC-22/25/26/29 并发与越权测试 | 幂等、Company 隔离、资源复用 | 对应 AC 通过,无重复资源或超额 |
+| 4.1 新资产全链路验收 | auto(平台就绪后) | 专用验收账号与新建验收容器 | 原始时间戳/阶段耗时、核验、失败恢复、试用到期续用 | 全部 AC + 双端实测 + 证据 | lj-test/旧资产只读;不把测试凭据写入产物 | 全 AC 实证、问题闭环,未测项披露 |
+| 4.2 完成交付核对 | auto | 评审/测试/矩阵/留痕/索引 | 同步实现状态、测试/提交/Schema 证据 | 评审通过+AC 全绿+留痕齐全 | 不自动提交/发布,不夸大上线 | 满足 DoD 后才宣称功能完成 |
+
+## 六、依赖与检查点
+
+Wave A:1.1 文档口径 → 1.2 契约/架构,业务已定不再开新问题。
+Wave B:设计与 2.1 双端原型 → 2.2 新独立评审及问题闭环 → 2.3 用户确认(G-D1)。
+Wave C:G-D1 后按依赖实施 3.1/3.2;平台未实现则真实创建联调阻塞,不能人工代替。
+Wave D:4.1 新资产全链路与计时 → 4.2 评审/验收/留痕。
+
+| 检查点 | 已完成 | 未完成/下一步 | 阻塞 |
+|---|---|---|---|
+| 2026-11-25 阶段 0 | 原文档 7 项评审闭环 | 新业务裁决已覆盖旧口径 | 不能沿用旧评审宣告新版本通过 |
+| 2026-11-25 本轮 | 业务裁决收口;v1.1 文档/接口设计及双端原型已产出;预约释放/同 job 重占已同步 | 独立复审中、原型展示与确认 | G-D1 未确认;实体创建 API 未确认实现 |
+
+## 七、里程碑与门禁
+
+| 里程碑 | 判据 | 当前 |
+|---|---|---|
+| M0 本轮设计齐备 | CR-02/PRD/定价/计划/API/架构/双端原型一致,新独立评审闭环 | 产出已齐备,独立复审中,未宣称通过 |
+| M1 原型确认 | **G-D1:用户明确确认本轮关键原型** | 待用户确认,禁止产品编码 |
+| M2 可联调 | G-D1 后实现、平台契约可用、权限/Schema/任务与幂等具备证据 | 未实现 |
+| M3 功能完成 | PRD 全部 AC 逐条通过,双端/并发/到期恢复实测,新评审与留痕齐全 | 未验收 |
+| M4 时长初始参考 | 专用新账号/新容器受理至 ready 实测,总秒数×1.30 后向上取整到分钟,明确样本 | 未实测,仅展示友好当前状态与真实进度 |
+
+## 八、风险与依赖
+
+| 风险 | 影响 | 处理 |
+|---|---|---|
+| 缺少实体创建 API/平台执行器 | 自助创建无法真实交付 | 平台实现依赖;不退回 DM/人工建容器 |
+| 历史 trial-standalone/个人组织含旧试用概念 | 重复领取或错误降级 | 与 48h 资格分开、服务端映射与一次性校验 |
+| 平台返回共享管理密钥 | 无法满足独立资源交付安全 | 拒绝交付且不通过核验,要求平台隔离专属凭据 |
+| 并发/超时/失败已有实体资源 | 超额、重复资源或预占泄漏 | 幂等、事务/原子预占、资源复用、补偿对账 |
+| 企业 Matrix 旧白名单等兼容性 | 同公司成员使用受阻 | 设计登记与新资产验证,不修改旧生产资产 |
+| 无计时样本 | 预计时长误导用户 | 只展示友好当前状态与真实进度;新资产实测后形成初始参考 |
+| 金额未定 | 正式报价不可承诺 | 定价唯一维护点,暂用待定/咨询;不阻塞文档原型 |
+
+## 九、变更历史
+
+| 版本 | 日期 | 内容 |
+|---|---|---|
+| v1.0 | 2026-11-25 | 初始套餐计划与阶段 0 文档 |
+| v1.1 | 2026-11-25 | CR-02 全文对齐;平台提供各档容器、48h、配额、真实异步任务与依赖;明确原评审历史和本轮 G-D1 |

+ 47 - 0
docs/02-design/plans/2026-11-25-官网移动端与扫码下载优化.md

@@ -0,0 +1,47 @@
+# 官网移动端与扫码下载优化
+
+## 范围与现状
+
+- 需求:补齐官网 Mobile 体验,同时保留扫码下载和点击下载。
+- 官网源码:`prototypes/fmode-download-20261120/`,发布产物为单文件 `index.html`。
+- 保留黑曜石暗色与薄荷绿品牌风格,继续使用 `FMODE_SITE.apkUrl` 和现有版本信息。
+- 本次仅调整官网下载页,不修改 Angular App、APK、后端、部署凭据及工作区已有未提交修改;不执行发布或 Git 提交。
+
+## 功能与验收
+
+| 编号 | 需求 | 验收 |
+| --- | --- | --- |
+| FR-01 / AC-01 | 手机端独立排版规则 | 320 / 375 / 390 / 430 / 768px 与桌面均无横向溢出;正文可读;主要触控目标至少 44px |
+| FR-02 / AC-02 | 双下载入口 | 首屏、下载区与移动底栏提供直接下载与扫码入口;二维码弹窗支持关闭、Esc 与焦点返回 |
+| FR-03 / AC-03 | 真实二维码 | 在本地根据同一个有效 APK 地址生成高清黑白二维码;不依赖第三方二维码图片接口;实际解码结果等于 APK URL |
+| FR-04 / AC-04 | 发布兼容 | 发布脚本仍通过 `FMODE_SITE` 更新版本和 URL,重新构建后二维码自动同步;单 HTML 可直接预览 |
+| FR-05 / AC-05 | 状态反馈 | 缺少或非法地址有说明;二维码失败时保留直接下载;微信内提示浏览器打开;iOS 说明当前为 Android 安装包 |
+| FR-06 / AC-06 | 回归与可访问性 | 桌面导航、移动菜单、三个产品页签与 FAQ 可用;二维码有替代文本、弹窗不穿透滚动、支持减少动效 |
+
+## 实现方案
+
+1. 调整模板:下载区右侧使用真实二维码卡片,新增扫码弹窗、复制链接反馈和移动端安全区下载底栏。
+2. 调整响应式 CSS:手机端采用单栏、较大正文和按钮;产品演示隐藏桌面侧栏,以可读内容替代整体缩小。
+3. 统一下载逻辑:所有直接下载按钮绑定同一安全 URL;二维码在浏览器本地生成 PNG,可长按保存。使用固定版本的 MIT QR 编码实现并本地内嵌,不新增 npm 包或外部运行时请求。
+4. 构建并使用 Playwright 验证多尺寸、二维码内容、下载事件、移动菜单、弹窗键盘交互、无效配置和设备提示,保存桌面与手机预览截图。
+
+## 数据与接口
+
+无新增业务表、Schema、云函数或 API;沿用官网现有静态配置对象。二维码不发送用户信息,不接入扫码统计。
+
+## 验证结果
+
+- 构建通过:`node prototypes/fmode-download-20261120/build.mjs`,产出约 199 KB 的单文件 `index.html`,字体、样式、二维码编码器均内嵌。
+- 浏览器回归通过:`node scripts/verify-download-site.mjs`,18 组检查;320、360、375、390、430、650、760、768、1024、1440、1920px 均无横向溢出。
+- 短屏回归通过:320×568、390×600、760×420 下弹窗不超出视口,可滚动并关闭。
+- 下载按钮真实触发浏览器 download 事件(请求拦截为测试文件);导航、首屏、下载区、弹窗和底栏共用当前 APK URL。
+- OpenCV 二维码实际解码通过:原始 PNG、手机下载卡片截图、桌面下载卡片截图均解码为当前配置 APK URL;模拟新版本二维码解码为新 URL(含查询参数)。
+- 缺失 / 不安全地址、相对地址、二维码编码器故障、剪贴板不可用、iOS / 微信 UA 提示、离线打开单文件、Esc / 焦点恢复 / 弹窗焦点约束均通过。
+- 无浏览器脚本错误,无第三方运行时资源请求;`git diff --check` 通过。
+- 报告:`test-results/download-site/results.json`;预览与二维码截图位于同目录。
+- 已修复验证中发现的移动菜单事件冒泡问题:菜单替换图标后,原事件目标脱离 header;改用事件传播路径判定外部点击。
+- 验证边界:浏览器模拟,未做手机真机安装、真实微信 / Safari 内核回归;未执行生产发布或 Git 提交。
+
+## 后续发布
+
+用户随后于 2026-11-25 授权按项目规范重新部署。已执行官网专用发布脚本并完成线上回归,CDN 3 / 3 刷新成功,裸链接内容与本地产物哈希一致;详情见 `docs/00-tracking/2026-11-25-官网下载页重新部署.md`。此前「未执行生产发布」为本地优化阶段状态,现官网已上线。

+ 14 - 0
docs/03-interface/README-容器接入文档索引.md

@@ -84,6 +84,20 @@
 
 ---
 
+## 五-增补、容器「创建」链路权威文档(2026-11-24 新增)
+
+> 本索引 §一 的 3 份权威文档管「容器**接入**」(已有容器如何对齐基线);
+> 2026-11-24 起的「容器**创建**全链路自动化」(从账号到 docker run)是另一条线,权威文档如下:
+
+| 文档 | 用途 |
+|---|---|
+| **`容器创建完整流程-接口与提示词-20261124.md`** | 创建全链路唯一权威:账号/云资源/FmodeAgent/Matrix/docker run 规范/主容器指令模板/已知缺口 |
+| `给主容器-建harness-test容器并按lj-test迁移-20261124.md` | 一次性指令实例(harness-test,公司账号线) |
+| `自动开通回报-*.md` | --send DM 主容器建容器的回报存档(每次实例一份) |
+| 配套脚本 | `scripts/create-test-account.mjs`(建测试账号)、`scripts/onboard-user.mjs`(全链路自动化) |
+
+---
+
 ## 六、文档维护约定
 
 - **新增容器接入相关文档**前,先看本索引,避免再产生重复

+ 7 - 5
docs/03-interface/api/API-契约.md

@@ -2,15 +2,17 @@
 
 | 字段 | 值 |
 |---|---|
-| 版本 | v1.0 |
-| 最后更新日期 | 2026-10-14 |
+| 版本 | v1.1(调用协议勘误与新领域契约索引) |
+| 最后更新日期 | 2026-11-25 |
 | 状态 | **生效(编码基线)**;标注 `❓` 者为推断,需服务端核对 |
-| 本次变更原因 | 初次创建。**补齐 CLAUDE.md「待确认项」指出的缺口**:云函数契约此前散见于存量 README 与调用点,**无集中文档** |
+| 本次变更原因 | 根据当前ParseApi实现更正Functions请求头;新增套餐异步开通设计契约入口,其余存量接口内容仍需按调用点核实 |
 | 事实来源 | 存量项目 `E:\work\fmode-app` 调用点逆向(子代理只读盘点)+ 存量 `docs/03-interface/hermes-agent-data-sources.md` |
 | 核对状态 | 请求参数与返回字段名 **已由 TS interface + 调用处校验双重确认**(标 ✅);仅少数语义为推断(标 ❓) |
 
 > **前端消费方式**:一律经 **`core/api/` 抽象层**;业务组件**禁止**直接调用 `FmodeApi` 或其实现。
 > 抽象层定义见《数据访问层设计.md》。
+>
+> 新领域设计见 `docs/03-interface/api/套餐与平台异步开通-API契约.md`(设计稿、未注册/部署)。平台容器创建任务、权益和配额不是本文旧接口已有能力。
 
 ---
 
@@ -22,12 +24,12 @@
 POST https://server.fmode.cn/api/functions
 Headers:
   Content-Type: application/json
-  X-Parse-Application-Id: ncloudmaster
-  X-Parse-Session-Token: <sessionToken>      # 有则带
 Body:
   { "id": "<云函数 objectId>", "token": "<sessionToken>", "params": { ... } }
 ```
 
+2026-11-25调用点勘误:当前 `core/api/parse-api.ts` 的Functions请求只显式发JSON头,身份通过body.token提供;不要把Parse REST端点的X-Parse头要求套到Functions。此处描述当前实现,不是宣布所有旧云函数返回协议完全一致。
+
 **错误处理**:HTTP 200 但 `body.code` 为 `401` / `403` 时视为业务错误,须抛出。
 错误文案取值顺序:`msg` → `mess` → `message`。
 

+ 189 - 0
docs/03-interface/api/套餐与平台异步开通-API契约.md

@@ -0,0 +1,189 @@
+# 套餐权益与平台异步开通 API 契约
+
+| 字段 | 内容 |
+| --- | --- |
+| 版本 | v0.1 · 2026-11-25 |
+| 状态 | 设计稿,待独立评审;尚未注册、部署或联调,不是已有接口清单 |
+| 上游 | CR-20261125-02;PRD-20261125 v1.1(FR-21~30);PLAN-20261125 v1.1 |
+| 实现门禁 | G-D1 原型确认;平台原子额度与受控执行器能力核实;接口与权限评审 |
+| 配套 | `docs/02-design/architecture/套餐权益与异步开通设计.md` |
+
+## 一、事实与边界
+
+1. App 当前通过 `FmodeApi → ParseApi → fmode-ng` 访问平台。实际 Functions 传输为 `POST /api/functions`,JSON body `{id, token, params}`,请求仅显式设置 JSON Content-Type。`id` 为平台注册的 Function objectId;本契约只分配逻辑名,真实 ID 必须在注册核验后集中登记,不能编造。
+2. 现有 `xlosi3m46q` 负责容器记录/列表;`RP5Ht55NeX` 负责 Matrix 身份;`mgR4EA2n5a` 负责企业成员;subscription/status、trial-standalone、provision/retry 负责独立云资源。**云资源开通接口不是 Docker 容器创建接口。**
+3. 已有实体容器创建经主容器的受控宿主机通道执行。新增 API 必须由平台持久任务和执行器衔接该流程;App 不发运维 DM、不拼 SSH/Docker、不解析 AI 回报作为产品状态。
+4. 函数逻辑名为 `fmode-subscription`(目录/权益/意向/确认)和 `fmode-provisioning`(任务/进度/执行器)。它们是拟新增能力,目前无已核实可调用 ID。
+5. 本文件不启用真实在线支付,不为平台未验证的事务、CAS、任务调度或密钥托管能力背书。缺失任一生产前提须明确阻断相应上线,Mock 不能代替真实接口验收。
+
+## 二、共同规则
+
+### 2.1 请求与主体
+
+- 普通请求从 `token` 解析当前用户。客户端不能通过传入 userId、owner 或任意 Company 获取其他人的权限。
+- `subjectType` 为 `personal` 或 `company`。个人按当前用户计算;企业选择携带 companyId 时,平台必须核实当前用户真实成员关系及所需管理权限。
+- 有 Company 指针不等于具有有效企业套餐;个人试用组织也不等于个人试用权益已生效。
+- 普通用户只能创建其本人名下任务;企业容器创建和增配由核实后的企业管理员执行。企业成员按授权查看可用的企业容器,不能因此读取管理员或其他人的密钥。
+- 所有业务记录有服务端确定的 company 租户指针及 isDeleted;个人主体仍以用户为准,company 使用其明确归属的资源租户,不能因用户加入企业就静默改为企业计费。若平台不能解析个人资源租户,返回 `TENANT_CONTEXT_UNAVAILABLE`,不得写无租户记录。
+
+### 2.2 统一结果和错误
+
+新函数返回 `{code, data?, error?}`,error 含稳定 `reasonCode`、可展示的脱敏 message、`retryable`、`requestId`。业务拒绝必须保留 reasonCode,不走旧客户端“所有 403 都是同公司授权未开放”的通用文案。
+
+| 情况 | code | reasonCode | 客户端行为 |
+| --- | --- | --- | --- |
+| 无效会话 | 401 | SESSION_INVALID | 重新登录 |
+| 越权主体/任务/资源 | 403 | FORBIDDEN | 权限说明,不当空列表 |
+| 需要付费 | 403 | BILLING_REQUIRED | 套餐/付费页 |
+| 状态暂无法核实 | 503 | ACCESS_UNVERIFIED | 保留错误态及重试,既不伪造过期,也不新授予使用权 |
+| 首容器未就绪 | 409 | PROVISIONING_REQUIRED | 等待页 |
+| 超出基础和加购额度 | 409 | QUOTA_EXCEEDED | 升级/允许的加购入口 |
+| 试用已领取 | 409 | TRIAL_ALREADY_CLAIMED | 返回可恢复原任务或付费引导 |
+| 同幂等键不同请求内容 | 409 | IDEMPOTENCY_CONFLICT | 不自动换键重发 |
+| 未发现实体且不可重试 | 409 | JOB_NOT_RETRYABLE | 联系管理员 |
+| 执行器暂不可用 | 503 | EXECUTOR_UNAVAILABLE | 平台保留任务;显示等待或明确失败结果 |
+
+列表/状态返回不携带 sessionToken、Matrix accessToken、独立资源凭据、worker token、SSH 信息、宿主机命令或平台管理密钥。所有异常、审计、进度 detail 禁止写这些内容。
+
+### 2.3 幂等、配额与一致性
+
+- 创建、领取、重试、人工确认、增配确认均带客户端生成的 idempotencyKey。平台用 `(subjectKey, action, idempotencyKey)` 唯一约束和请求内容摘要保证同请求返回同结果;同键异参拒绝。
+- 基础额度:trial=1、starter=1、advanced=3、enterprise=5。starter/trial 不支持加购;advanced/enterprise 的有效上限=基础+已确认加购。
+- 已用额度包含已存在且未明确释放的实体,非在线容器数;关机或离线不会自动腾出名额。未完成任务的预约计入 reserved,失败但资源结果未知继续保留预约,不能因 HTTP 超时减额度。
+- **原子性前提**:平台须提供经核实的单主体持久 CAS 或数据库事务,在同一个原子提交中校验可用名额、写入预约和 outbox 任务意图;并具有对应唯一约束。不能使用 `count→save`、`first→new Object`、无条件 increment、进程内锁或前端按钮禁用替代。
+- outbox 持久化后由执行器展开任务;任务的 reservationId 唯一,重复投递不重复创建。执行器使用持久租约、续租、fencingToken 和阶段 checkpoint,旧租约回报不能覆盖新尝试。
+- 每个外部创建动作都有稳定 operationKey 和可回查的 resourceRefs。响应丢失时先回查真实资源再决定重试;查询失败与 not_found 分开,禁止把查错当不存在重新建 Matrix 房间/容器。
+- 用户提交意向不占容器额度、不等于付款成功;管理员确认权益成功后,通过同一原子预约路径创建后续任务。
+- 预约状态为 held / committed / released:资源已交付结转committed;失败且平台回查证实没有实体、没有在途外部操作时,才原子释放为released,保留原任务与释放证据。部分资源已建或结果未知维持held,不能让客户端自行释放。
+- released任务重试先对同一job原子重新预约;有名额才续跑,若名额已被其他任务占用返回QUOTA_EXCEEDED并保持failed/released,不偷换job、不超额放行。held任务重试复用原预约。两者都不重置已领取的试用资格或已经开始的48h时间。
+
+## 三、公共类型
+
+### 3.1 AccessSnapshot
+
+| 字段 | 类型/含义 |
+| --- | --- |
+| subjectType / subjectId | personal+当前用户 或 company+已核验企业 |
+| planCode | trial / starter / advanced / enterprise,未开通时 null |
+| subscriptionState | unopened / applying / provisioning / active / expired;试用失效不改容器运行状态 |
+| appAccess | allow / provisioning / billing_required / verification_required |
+| reasonCode | 与 appAccess 对应的稳定原因 |
+| trialClaimed / trialStartedAt / trialExpiresAt | 服务端事实;未 ready 时 startedAt/expiresAt 均为 null |
+| quota | `{base, addon, used, reserved, available}`,available 不小于 0 |
+| currentJobId | 可恢复的当前任务,未有任务时 null |
+| usableAgentIds | 当前主体经服务端授权且 ready 的容器 ID,不把“可见记录”当可使用 |
+| resourceDeliveries | 已授权资源描述 `{resourceId,kind,agentId,ready,credentialFields,credentialPresent}`;供参数页选择目标,不包含秘密值或秘密存储引用 |
+| migrationState | new / legacy_pending / legacy_allowed / migrated,服务端维护 |
+| serverNow / version | 服务端时间及单调状态版本,用于拒绝过期覆盖,不由浏览器时间判授权 |
+
+有效企业和个人权益分别解析。个人试用到期但企业权益有效时,企业作用域仍允许;不会自动将个人资产转为企业资产。无订阅记录不等于 expired。
+
+### 3.2 ProvisionJob
+
+| 字段 | 类型/含义 |
+| --- | --- |
+| jobId / status | 持久 ID;queued / provisioning / verifying / ready / failed |
+| currentStage | 六阶段之一,见下表 |
+| stages | 每阶段 `{key,status,startedAt,completedAt,attempt,detail}`;detail 仅脱敏业务说明 |
+| progress | `{completedSteps,totalSteps,percent}`,百分比表示检查点比例,ready 以前最多 99 |
+| createdAt / updatedAt / startedAt / readyAt | UTC ISO 时间;未发生时 null |
+| attempt / retryable | 尝试次数及是否允许从原任务重试 |
+| agentId | 资源确认存在后可关联,ready 之前不能凭此进入容器 |
+| estimatedReadyAt / estimate | 未有实测时 null;有实测时含 referenceDurationSeconds、basis、sampleCount,非 SLA |
+| nextPollAfterMs | 前台默认 15000,可由服务端延长,前端统一调度 |
+| checks | 结构化核验项,不包含原始消息正文或秘密 |
+| error | `{reasonCode,message,retryable,failedStage}` 或 null |
+| version / serverNow | 防止延迟响应使进度倒退,并校正时长显示 |
+
+任务历史中保留完整阶段时间和尝试记录;客户端不能提交任意 status 或 readyAt。浏览器等待超时、回报静默和“约定用时已到”均不得改任务为 ready/failed。
+
+| key | 阶段 | 执行责任 |
+| --- | --- | --- |
+| entitlement | 核实权益并预留名额 | 平台原子额度接口 |
+| cloud | 独立云资源可用 | 平台云资源接口及探测 |
+| matrix | 用户/agent 身份与绑定 | 平台 provision,按本人绑定复用 |
+| container | 创建及初始化实体容器 | 平台受控执行器,复用验证后的模板/skill |
+| connectivity | 完成身份和房间接入 | 平台执行器和 Matrix 回读 |
+| verification | 核验运行及可用性 | 平台结构化验收器 |
+
+### 3.3 核验输出
+
+每项 `{key,status,checkedAt,evidenceRef,detail}`,status 为 pending/passed/failed/skipped;必需项 pending 或 skipped 均不能 ready。
+
+本次接口设计要求以下稳定机器 key:ownership(本人/企业归属)、resource_bundle(独立资源真实可用)、runtime(2核4G/时区/进程无崩溃循环)、matrix_identity(whoami与绑定一致)、membership(真实加入房间)、roundtrip(消息回读且对应回复有✅/✔结束reaction)、heartbeat(目标agent真实心跳落库且距核验≤120秒)、isolation(未混入源容器身份/密钥)。
+
+**以上为本次设计分组,不声称是 skill v2.2.0 原八项的编号。** 本地未取得该验收器完整正文;后续须向平台核实完整清单和输出映射,再冻结 requiredChecks 版本。缺映射不得宣称八项全部验证通过。必要文件/成果链路探测按原验收器映射加入对应分组。
+
+## 四、用户与管理员动作
+
+| 逻辑函数/action | 输入(不含共同会话字段) | 返回/约束 |
+| --- | --- | --- |
+| subscription/catalog | 无 | 权益目录、catalogVersion、priceState=consult、基础额度和可加购范围;不伪造金额 |
+| subscription/getAccess | subjectType,企业选账套时 companyId | AccessSnapshot;服务端核验选择 |
+| subscription/submitApplication | planCode、catalogVersion、idempotencyKey | 人工确认意向及状态;不创建虚假支付订单 |
+| subscription/requestAddon | subjectType、quantity、idempotencyKey | 仅 advanced/enterprise;quantity 为正整数;待人工核准,不立即加额度 |
+| provisioning/claimTrial | containerName、catalogVersion、idempotencyKey | 原子认领一次试用、预约1名额、产生任务;返回 job/access;尚不开始48h计时 |
+| provisioning/startProvision | subjectType、containerName、catalogVersion、idempotencyKey | 有效权益及剩余额度才能创建;试用领取走 claimTrial,不能绕过该动作重复领 |
+| provisioning/getProvision | jobId | 只读授权任务;无权限明确403 |
+| provisioning/listMyProvisions | subjectType、cursor、limit | 当前用户有权限的可恢复任务;返回dto不含凭据 |
+| provisioning/retryProvision | jobId、idempotencyKey | 续原任务,held复用预约,released须原子重新预约;额度不足保持失败;保留资源映射,不重置试用时间 |
+| subscription/requestCredentialGrant | resourceId、fields、confirmed=true | 核实当前有效会话、本人归属、目标ready及权益后签发绑定当前会话/资源/字段的短时一次性grantId和expiresAt;不返回秘密 |
+| subscription/getMyCredentials | resourceId、fields、grantId | 本人独立资源和本人Matrix绑定;必须目标资源已ready且配套交付核验通过、权益有效;消费未过期grant后短时返回所需字段,禁止共享缓存 |
+| subscription/confirmPayment | applicationId、确认依据引用、idempotencyKey | 仅平台运营权限;确认后发任务或恢复原有ready容器,不同步等待创建 |
+| subscription/confirmAddon | applicationId、quantity、确认依据引用、idempotencyKey | 核实运营权限/额度主体,原子增加已确认名额,重复确认不重复加 |
+
+普通公司管理员无权自行确认平台收款;公司角色和平台运营角色分开验证。首次付费确认后若没有 ready 容器,仍为 provisioning;续开原已ready容器时恢复其准入,不再创建第二个。
+
+### 凭据交付边界
+
+- 四件套指 appId/serverURL/functionsURL/用户独立后端的专属凭据;平台实际字段可能名为 masterKey,但必须证明只控制用户独享资源,绝非 `.claude/dev-login.json` 中的平台管理 masterKey。
+- 云资源状态只返回 credentialRef 和 presence,不随 getAccess/getProvision 下发值。
+- 用户二次确认后先请求requestCredentialGrant,服务端按当前有效会话、资源和字段重新授权;grant是短时一次性读取授权,不是新的身份或平台管理能力。过期/已消费/资源字段不匹配必须重新确认,不得扩大范围。UI确认不能替代服务端本人权限检查,也不宣称是额外MFA。
+- getMyCredentials 在服务端再次核实本人、独立作用域、有效权益和grant后,返回请求字段及 `Cache-Control: no-store`。前端默认遮蔽、复制二次确认,离开页面/权益失效清掉会话内引用,不进静态包、localStorage、分析埋点或错误日志。
+- 读取凭据还必须验证目标资源ready和配套交付核验通过;创建记录、仅获得agentId或拥有另一可用容器,都不能替代当前目标ready判定。未ready返回PROVISIONING_REQUIRED而非空/部分凭据。
+- Matrix连接参数包括本人userMxId、目标agentMxId、roomId、homeserver和本人的accessToken;不能将agent身份或其他用户token当作当前用户身份。
+- 若平台接口只返回共享平台管理密钥,不能把该值下发或将相应交付项判为完成;需先提供隔离的资源凭据能力。
+- 到期不吊销外部凭据;已复制的独立凭据及外部 Matrix 客户端能力仍可能有效。本次承诺锁定的是本项目应用访问,不声称关闭所有外部访问。
+
+## 五、平台执行器私有协议
+
+执行器使用与普通用户隔离的服务身份;用户会话不能调用 claim/report/renewLease/complete。平台来源、Company作用域、租约与fencing均在服务器验证。
+
+| action | 职责 |
+| --- | --- |
+| claimWork | 原子领取可执行任务及租约,只返回该执行器获授权的任务 |
+| renewLease | 续租;旧 fencingToken 无法续租或回写 |
+| reportStage | 带 jobId、fencingToken、阶段与尝试号回写结构化 checkpoint;重复回报幂等 |
+| reportChecks | 回写校验器版本、机器核验结果和脱敏证据引用 |
+| complete | 在所有必要检查通过后,原子结转reserved→used、ready和首次试用激活 |
+| fail | 记录明确失败、已建资源及可重试性;未知外部结果进入内部回查,不能盲目释放 |
+
+开始工作前核对主体身份和资源归属。节点创建过程可复用主容器已验证模板与受控宿主通道,但任务成功不能靠“主容器说完成了”或静默时长判断。临时网络/入口错误按已验证重试策略处理;业务拒绝不盲目重试。
+
+## 六、48 小时与到期恢复
+
+1. 认领试用时只写 trialClaimed;云资源、首容器、通信、必要核验全部满足后,在同一次激活提交中写一次 trialStartedAt 和 trialExpiresAt=startedAt+48h。
+2. 任务重试、重新登录、刷新、换设备均不修改首次起止时间。
+3. 服务端按 serverNow 判定 appAccess。到期不触发 stop/delete/revoke,只给个人作用域 billing_required;存在另一有效企业权益时保留其企业作用域。
+4. 付费确认只改变权益及准入,复用同一 agentId、数据卷和必要绑定。不能用“续开”触发第二次试用或重造容器。
+5. 付费期满、变档、超额存量的运营规则尚未裁决;不把试用规则扩展成付费容器停机/删除策略。
+
+## 七、计时与前台刷新
+
+- 记录 accepted/created、worker started、每阶段及每次尝试的 started/completed、ready;总耗时=readyAt-createdAt,包含排队与重试;另列执行器排队耗时。
+- 后续用专用验收账号、新建验收资产完整实测;不得触碰lj-test、旧test-0001或生产资产来冒充新开通计时。
+- 未有有效实测时 estimate 和 estimatedReadyAt 为 null,UI写“待平台实测后提供”,不写固定30分钟。
+- 首轮实测总时长 T 秒,初始参考分钟数采用 `ceil(T × 1.3 / 60)`(例如T=61秒,参考2分钟),平台配置并标明样本数/参考性质;新任务预计点由平台生成,排队变化时可修正。它不是交付承诺或任务终态判据。
+- 前台默认15秒统一轮询,页面隐藏暂停、恢复立即拉取,支持“检查进度”;服务端可返回 nextPollAfterMs。不能给每个页面另建独立setInterval。
+- 前台友好状态映射固定为 queued→等待开通、provisioning→正在开通、verifying→即将就绪、failed→开通失败、ready→已就绪。页面只展示当前状态、真实进度、必要时间/操作,不逐项解释内部六阶段;阶段详情与诊断留在技术文档、平台记录和受控运维视图。
+
+## 八、生产前置与验收证据
+
+- [ ] 注册真实Function ID并完成会话、租户和运营权限验证;证明实体创建执行器可由平台任务驱动。
+- [ ] 核实实际数据后端及CAS/事务、唯一约束和outbox恢复,不将Parse SDK本身当事务保证。
+- [ ] 明确独立资源凭据托管/短时交付能力及验收器v2.2完整映射。
+- [ ] 领取唯一性、并发临界额度、重复/不确定请求、租约过期回报、部分资源已建后的恢复均实测。
+- [ ] 首ready才开始48h、试用失效、有效企业作用域、原容器续用和旧用户迁移均验证。
+- [ ] 开通耗时实测报告、双端在线等待恢复、失败/离线/超时状态、跨主体拒绝及敏感日志扫描。
+
+现阶段仅契约设计与原型,以上生产项全部未验证,不作为已实现能力。

+ 156 - 0
docs/03-interface/容器创建完整流程-接口与提示词-20261124.md

@@ -0,0 +1,156 @@
+# 容器创建完整流程:接口与提示词(个人无企业版,2026-11-24)
+
+> **2026-11-25产品口径覆盖说明**:本页保留既有脚本与宿主机创建的技术实证。当前生效的试用/入门/进阶均改为平台容器并含独立云资源,配额1/1/3、企业共享5;产品流程须平台API异步受理与结构化进度。旧脚本的可选参数和人工DM步骤不再代表产品交付方式。以CR-20261125-02及套餐任务计划v1.1为准,新接口目前为设计态。
+
+> **定位**:把「完整创建一个容器」的全链路固化成可脚本化的接口清单 + 提示词模板。
+> **口径**:个人用户**默认无企业**(2026-11-24 用户裁决:不自动入企、git-join 不进流程、
+> 不做短信登录——测试用模拟账号)。企业版(openyd-join/git-join 入企组织)仅作参考。
+> **配套脚本**:`scripts/create-test-account.mjs`(阶段一·建测试账号)、
+> `scripts/onboard-user.mjs`(阶段二·全链路自动化)。
+
+---
+
+## 一、全链路总览
+
+```
+A. 用户与资源
+ ① 账号(生产=短信登录;测试=masterKey 直建)
+      生产:POST /api/apig/message {mobile,company} → 用户给短信码
+            → GET /api/fmode/mobile?mobile&code
+            → { data.token(=FMODE_PARSE_SESSION_TOKEN), data.newapiToken }
+      测试:masterKey POST /parse/users {username:"fmode<手机号>",password,...}
+            → POST /parse/login → sessionToken(create-test-account.mjs)
+      ⚠️ 不设 company 字段 = 个人无企业
+ ② 独立云资源(旧脚本可选参数;当前个人套餐交付为必需,个人名下、不要求企业)
+      POST /api/fmode/enterprise/subscription/status   {}           → 查
+      POST /api/fmode/enterprise/subscription/trial-standalone {name,mobile} → 开
+      轮询 status(4s,对齐 apig-pay 最多 45 次):
+        成功标志 = data.backend || data.subscription.backend
+        失败标志 = data.subscription.provisionStatus === "failed"
+        → POST .../subscription/provision/retry 兜底
+      交付:{ appId, serverURL, functionsURL, masterKey }(写容器 ~/.fmode/config/enterprise/current.json)
+      请求头:X-Parse-Application-Id + X-Parse-Session-Token(apig-pay authJson 同款)
+ ③ Git 账号:❌ 个人无企业默认不开(git-join 是企业组织逻辑;
+      未来个人需要时走 /gogs/admin/proxy 手工通道)
+
+B. 容器与通道(除 ⑥ 外全部有接口,已实测 ✅)
+ ④ FmodeAgent 记录
+      查:POST /api/functions {id:"xlosi3m46q",token,params:{op:"query",scope:"mine",agentId}}
+          🔴 个人无企业账号必须用 scope:"mine"("all" 需管理员/企业角色,实测 404)
+          🔴 创建前必须二次确认:入口层坏后端会把「存在」误报成 404,
+             直接信首次 404 会建出重复记录(2026-11-24 实测两条,已删一)
+      建:POST /parse/classes/FmodeAgent(字段见 onboard-user.mjs ensureAgent,
+          无 company;ACL={属主 rw, role:FMODE_AGENT_SUPERADMIN rw})
+ ⑤ Matrix 身份
+      POST /api/functions {id:"RP5Ht55NeX",token,params:{agentId}}
+      → { agentMxId:@<objectId小写>:fmode.cn, userMxId(主人), roomId, bindingId,
+          accessToken(主人 Matrix 凭据), homeserver }
+      幂等:已有绑定缓存命中秒回;🔴 无绑定时调用会「新建」——只读查询请直查
+      FmodeMatrixBinding 表,别用 provision 当查询(房间割裂教训)
+      派生密码(provision 新建账号):sha256("fmode-agent-mx:"+原始objectId)[:24]
+      ⚠️ provision 只「邀请」不入房,容器须自行 join
+ ⑥ 容器实体:🔴 唯一无 HTTP API 的环节
+      = DM 主容器 agent-node(@bnqaoxqhe8:fmode.cn,准入全开,实测 DM 可达),
+        它经 /opt/data/scripts/r730_root.py SSH 通道(server.fmode.cn:18001→R730)
+        执行 docker run。陈经理「创建分身接口」落地后可 API 化。
+ ⑦ 容器初始化:从 lj-test 迁移通用层(方式乙,当前)/ s3 基线包(方式甲,目标)
+ ⑧ 接入 Matrix:写 .env → 重启 gateway → whoami/joined_rooms/收发回读
+
+C. 主容器(agent-node)关键事实(2026-11-24 实测,任务 berl62ti4)
+ · 身份:普通业务容器(uid=10000 hermes、无 docker.sock、无 sudo),
+   但持有 r730_root.py SSH 通道可在宿主 R730 上行事(含 docker run)
+ · 属主:刘雨飏(_User sr2WiPsDyQ);lj-test 也是用他账号孵化的
+ · 准入:GATEWAY_ALLOW_ALL_USERS=true、无 MATRIX_ALLOWED_USERS —— 任何人 DM 直达
+ · 建容器 SOP 在它身上:/opt/data/skills/devops/skill-lifecycle/references/
+   life-init-standard.md + life-ops-hardened.md
+ · cloud.sh 不存在(旧文档线索作废)
+```
+
+## 二、docker run 规范(主容器侧执行)
+
+```bash
+docker run -d \
+  --name <agentId> \
+  --hostname <agentId> `# 必带,否则随机 hostname 与 agentId 对不上` \
+  --restart unless-stopped \
+  --env-file <env文件>  `# TZ=Asia/Shanghai 必带;只在创建时读一次,改 env 必须 rm 重建` \
+  --memory 4g --cpus 2 --pids-limit 512 \
+  -v /opt/fmode-containers/<agentId>/data:/opt/data \
+  --entrypoint /opt/data/.fmode-media-patch/entry.sh \
+  fmode/agent-node:<与 lj-test 一致版本>
+```
+
+- 镜像:与 lj-test 一致(`docker inspect agent-node-lj-test --format '{{.Config.Image}}'`)
+- `--entrypoint .fmode-media-patch/entry.sh`:Matrix 入站 https 附件补丁的持久化载体
+  (补丁在 root 属主 /opt/hermes,容器内无法自修;补丁来源主容器不知情,
+  取证点=宿主 docker inspect + shell history + 文件属主 mtime)
+- 数据目录:宿主 `/opt/fmode-containers/<名>/data` ↔ 容器内 `/opt/data`
+
+## 三、主容器指令模板(onboard-user.mjs 自动生成)
+
+模板全文见 `scripts/onboard-user.mjs buildInstruction()`,实例见
+`scripts/.tmp-onboard-<agentId>-prompt.md`。结构:
+
+1. **自报家门**(发起方 mxid + 测试性质)+ 限定白名单动作(防被当诱导——它准入全开)
+2. **平台侧事实**(FmodeAgent objectId / agentMxId / 主人 mxid / roomId /
+   派生密码 / 主人 token[/云资源四件套])——主容器**不调云函数**
+3. **建容器**(docker run 规范,如上)
+4. **迁移 lj-test 通用层**(plugins 11 个 / scripts fmode-* / .fmode-media-patch /
+   patches / SOUL.md / config.yaml;🔴 剥 platforms.wecom 整段——botid 共用会 ~306s 互踢;
+   🔴 不拷 .env/sessions/state.db/logs/memories/.bak 等个人层与垃圾层)
+5. **写 .env**(MATRIX_* 身份 + REACTIONS=true + REQUIRE_MENTION=false +
+   ALLOWED_USERS=主人 mxid + AGENT_ID + FMODE_SESSION_TOKEN;🔴 不设 IGNORE_USER_PATTERNS)
+6. **cron 两 job**(artifact-drain */3 + media-gc 30m)+ **DNS 体检**(>1s 则 RES_OPTIONS=single-request)
+7. **验收 5 项贴证据**(gateway connected / .env 回读 4 项 / whoami+joined_rooms /
+   自检消息落库 / active-reporter 日志)→ `CREATE-DONE` 汇报
+
+## 四、lj-test 三层迁移口径(容器自报 + 实测)
+
+| 层 | 内容 | 处置 |
+|---|---|---|
+| 通用层 | config.yaml(剥 wecom)、11 插件、4 shell hooks、.fmode-media-patch、patches、fmode 技能族 | ✅ 迁移 |
+| 个人层 | SOUL.md(当前是 667B 出厂默认,人格是缺口)、.env 身份段、FMODE_SESSION_TOKEN、wecom 凭据 | ⚠️ 按新容器重新生成 |
+| 垃圾层 | 15 个 .bak、diag-* 等 | ❌ 不迁 |
+
+## 五、已知缺口与平台依赖
+
+| 缺口 | 现状 | 依赖 |
+|---|---|---|
+| docker run 无 API | 靠 agent-node SSH 通道 | 陈经理「创建分身接口」(进阶套餐) |
+| entrypoint 补丁来源 | 主容器不知情 | 宿主侧取证(需授权走其 SSH 通道只读查) |
+| ~~入门套餐是否含 trial-standalone~~ | **最新裁决(2026-11-25):含** —— 入门档改平台提供1个容器,交付独立云资源四件套及本人Matrix参数;原“接入自有agent”由CR-20261125-02覆盖 | ~~产品裁决~~ ✅ |
+| 入口层后端池质量 | 403/301→:7460/unauthorized 三形态随机 | 平台运维;脚本侧已统一 manual+重试绕过 |
+| 雨飏001 自身问题 | Matrix 丢 thread(continuwuity 服务端缺陷,DM 不受影响)、主会话 73 万 token、plugin-tips-cn 重复包裹 | 刘雨飏决策;与本链路无因果(时间线+机制均已排除) |
+
+## 六、实测记录
+
+- 2026-11-24 阶段一:测试账号 `fmode19900000001`(objectId `cq0IH6Limu`,无企业)
+  创建 + 4 项自检全绿(create-test-account.mjs)
+- 2026-11-24 阶段二平台侧:`agent-node-app-test-0001`(objectId `K0jXgRmdHe`)
+  记录→provision(roomId `!hLVCNPgJhfaMTajfcgggbnlgCoXKLUWWwOKjPZzkos0`)→指令生成,
+  全链路幂等重跑一致(onboard-user.mjs)
+- 2026-11-24 --send DM agent-node 建容器:见 `自动开通回报-agent-node-app-test-0001-*.md`
+
+---
+
+## 七、主容器首跑实测踩坑(2026-11-24 CREATE-DONE,技能化原料)
+
+首跑 `agent-node-app-test-0001` 全通过(whoami/joined_rooms/收发回读/DNS 18ms/心跳上报 OK),
+主容器共处置 9 个问题,全部须进技能与后续任务书:
+
+| # | 坑 | 正解 |
+|---|---|---|
+| 1 | 迁移源名不副实:`agent-node-lj-test` 宿主目录是**空壳残留**(2 插件/无 patches/容器停 10 天) | 真源 = `agent-node-u19170119836`(11 插件/4 patches/两 cron 逐项吻合);以后按内容验证,不按名字 |
+| 2 | **lj-test 的 AGENT_ID 污染**:源 .env 写 `AGENT_ID=agent-node-lj-test`,会用 lj-test 身份上报;`fmode-artifact-drain.sh` 还有一处硬编码 | 新容器 .env 重写 AGENT_ID;drain 脚本改读容器真实值(主容器已修) |
+| 3 | dashboard 崩溃重启循环:漏传 `HERMES_DASHBOARD_BASIC_AUTH_*` → 安全门拒绑 0.0.0.0 → 每 2-6s 重启、插件重载、永不心跳 | docker env 必带 DASHBOARD 认证三件套 |
+| 4 | RES_OPTIONS 注入点选错:entry.sh 里 export 无效(/init 重建 s6 环境,gateway 是 s6-supervise 子进程) | 改写 `/run/service/gateway-default/run`,由 entry.sh 冷启动等文件出现后注入 |
+| 5 | 重建容器漏传 AGENT_ID / FMODE_SESSION_TOKEN(.env 有值但 docker env 没传)→ 插件永久 skip | docker env 与 .env 双写核对,`/proc/PID/environ` 验证 |
+| 6 | 云函数 401/403 两性质:业务真 403(`无权更新该 Agent(归属校验失败)`)vs 入口层假 401(HAProxy 抖动) | 调用方 `_call` 加 8 次×1.5s 重试,只对**无业务 code 的入口层响应**重试(主容器已给 reporter 打同款补丁) |
+| 7 | cron 连续失败 34 次:`fmode-artifact-drain` 缺 `git-repos/agent-status-reporter/scripts/artifact-drain.py`(属个人层,通用层清单未涵盖) | 通用层清单补该文件;补拷后 failure_streak 34→0 |
+| 8 | SSH 通道(frpc)间歇断连 `Error reading SSH protocol banner` | 一切操作经 `r730_retry.py` 8 次重试封装 |
+| 9 | 品牌:容器回复「我是 Hermes」(SOUL/系统提示层),违反对外 FmodeAgent 口径 | ✅ **已修复**(2026-11-24):SOUL.md 改写 1549B Fmode 分身口径(identity slot #1 压制出厂兜底;须写入明确自定义内容绕开 `is_legacy_template_soul()` 自动还原);实测「我是测试分身0001,主人的 Fmode 分身」、Hermes 词 0 命中。**新容器建时 SOUL.md 必须一并生成**,列入验收项 |
+| 10 | **转属主漏换 Matrix 凭据**(2026-11-24 下午线上事故):绑定记录转属主时改了 `userPointer`/`userMxId` 但 `accessToken`/`deviceId` 还是旧主人的 → App provision 拿到「旧主人 token + 新主人 userId」错配 → Matrix 所有带 userId 的接口(filter 等)403 风暴、sync 残废、收发全卡;消息实际以**旧主人身份**发出(容器 6.9s 已正确回复但 App 收不到) | **转属主必须连同 `accessToken`/`deviceId` 一起换成新主人的有效凭据**(可从该用户其它绑定的缓存凭据复用,先 whoami 验证);改完回读三项一致性。平台侧建议:provision 返回缓存凭据前应先 whoami 校验 token↔userMxId 一致 |
+
+**产出**:主容器已把流程固化为技能「container-provision-from-source」(位于其技能库,
+下次建容器直接调用)。`lj-test` 与 `u19170119836` 全程只读未改。
+回报原文:`docs/03-interface/自动开通回报-agent-node-app-test-0001-202611240327.md`。

+ 80 - 0
docs/03-interface/容器取证-agent-node-1795587945537.md

@@ -0,0 +1,80 @@
+# 容器取证问答:agent-node
+
+- 时间:2026-11-25T06:25:45.536Z
+- 房间:`!1tFd0hAEZYDM3qjx2eaFh391FIDIEuGHXuH2P_00vfk`(临时房间,可保留查阅)
+- 消息统计:正文 3 段 / 工具过程 2 段 / 文件 0 个
+- 结束原因:收到 ✅ reaction
+
+## 我发出的问题
+
+```text
+只读探测,不要修改任何东西,不要创建容器。
+
+请执行并回报以下三项的真实输出:
+1. `python3 /opt/data/scripts/r730_root.py "docker ps --format '{{.Names}}'" 2>&1 | head -40`
+   (如果 r730_root.py 路径不同,先 `ls /opt/data/scripts/ | grep r730` 找出来)
+2. `df -h /` 看磁盘剩余
+3. 回报:R730 上当前运行的容器名字列表、磁盘剩余空间
+
+只回报输出,不要解释。
+```
+
+## 容器回答(原文,按时间顺序,未删改)
+
+### 1【prose】
+
+```text
+SSH 连接 R730 失败,报错为 `Error reading SSH protocol banner`。下面附上排查结果和断开原因。
+```
+
+### 2【prose】
+
+```text
+```
+timeout 40 python3 /opt/data/scripts/...
+```
+```
+
+### 3【prose】
+
+```text
+**1. R730 容器列表(hostname: R730,共 13 个)**
+```
+agent-node
+agent-node-app-test-0001
+agent-node-cb-feishu-001
+agent-node-liujun
+agent-node-pengfeng
+agent-node-tuye
+agent-node-u15546498207
+agent-node-u17621252676
+agent-node-u17879018108
+agent-node-u18691770343
+agent-node-u19170119836
+agent-node-xiaxin
+agent-node-xinting
+agent-node-yangyang
+```
+
+**2. 磁盘剩余**
+```
+/dev/sda1  521G  386G  Avail 109G  Use 79%  /
+```
+
+**3. 说明**
+- 首次和连续两次重试都报 `Error reading SSH protocol banner`,第 4 次连上了。这是 R730 的 SSH 服务出现横幅读取间歇性失败导致的,不是路径问题。
+- 本次操作全程只读,未做任何修改,也未创建容器。
+```
+
+### 4【ack】
+
+```text
+✅ 容器已标记完成
+```
+
+---
+
+## 工具过程(仅供核对,非回答内容)
+
+- `💻 terminal ``` ls /opt/data/scripts/ | grep r730; ec... ````
+- `* 💻 terminal ``` ls /opt/data/scripts/ | grep r730; ec... ``` ``` for i in 1 2 3; do echo "=== try $i =... ````

+ 168 - 0
docs/03-interface/容器取证-agent-node-1795590186473.md

@@ -0,0 +1,168 @@
+# 容器取证问答:agent-node
+
+- 时间:2026-11-25T07:03:06.472Z
+- 房间:`!DXf3j-otY56KfSZnZxRDSDZlDR5q1SNStwSR1xg8Sbg`(临时房间,可保留查阅)
+- 消息统计:正文 15 段 / 工具过程 1 段 / 文件 0 个
+- 结束原因:收到 ✅ reaction
+
+## 我发出的问题
+
+```text
+只读检查,不要修改任何东西,不要创建容器。
+
+请执行并回报:
+1. `python3 /opt/data/scripts/r730_root.py "docker ps -a --filter 'name=XEpJ13WK3d' --format '{{.Names}} {{.Status}}'" 2>&1 | tail -5`
+   SSH 若报 banner 错,重试最多 6 次。
+2. `python3 /opt/data/scripts/r730_root.py "docker ps -a --filter 'name=ondyhUHqv2' --format '{{.Names}} {{.Status}}'" 2>&1 | tail -5`
+3. 如果 XEpJ13WK3d 存在但没运行,看日志:`docker logs --tail 30 XEpJ13WK3d 2>&1`
+4. 如果不存在,说明没建:确认 `/opt/fmode-containers/XEpJ13WK3d/` 目录在不在
+
+只回报原始输出,不要解释,不要修复。
+```
+
+## 容器回答(原文,按时间顺序,未删改)
+
+### 1【prose】
+
+```text
+I'll run the checks in order.
+```
+
+### 2【prose】
+
+```text
+```
+python3 /opt/data/scripts/r730_root.p...
+```
+```
+
+### 3【prose】
+
+```text
+Both returned empty. Checking whether that's a real empty result or a silent SSH failure.
+```
+
+### 4【prose】
+
+```text
+* ```
+python3 /opt/data/scripts/r730_root.p...
+``` (×2)
+```
+
+### 5【prose】
+
+```text
+SSH banner error. Retrying both, up to 6 attempts each.
+```
+
+### 6【prose】
+
+```text
+```
+for i in 1 2 3 4 5 6; do ...
+```
+```
+
+### 7【prose】
+
+```text
+Attempt 2 seems to have hung then the loop exited oddly. Re-running with a cleaner structure.
+```
+
+### 8【prose】
+
+```text
+```
+for i in 1 2 3 4 5 6; do ...
+```
+```
+
+### 9【prose】
+
+```text
+Attempt 3 connected successfully with empty output — meaning no matching container. Now checking ondyhUHqv2.
+```
+
+### 10【prose】
+
+```text
+```
+for i in 1 2 3 4 5 6; do ...
+```
+```
+
+### 11【prose】
+
+```text
+还在跑,3 分钟了——稳住,就快出结果了。 — iteration 6/150, 数据流还没走完,稍候。
+```
+
+### 12【prose】
+
+```text
+```
+for i in 1 2 3 4 5 6; do ...
+```
+```
+
+### 13【prose】
+
+```text
+Just doing a final sanity check that the SSH session actually reached the right host (so the empty results aren't a false negative).
+```
+
+### 14【prose】
+
+```text
+* ```
+for i in 1 2 3 4 5 6; do ...
+``` (×2)
+```
+
+### 15【prose】
+
+```text
+原始输出:
+
+**1. XEpJ13WK3d 容器查询**
+```
+(空输出,RC=0)
+```
+SSH banner 错误重试 3 次后连通,`docker ps -a --filter 'name=XEpJ13WK3d'` 无匹配行。
+
+**2. ondyhUHqv2 容器查询**
+```
+(空输出,RC=0)
+```
+第 1 次即连通,无匹配行。
+
+**3. 容器日志**
+未执行 —— 前置条件不成立(XEpJ13WK3d 不存在,既没运行也没停机残留)。
+
+**4. 目录确认**
+```
+NO-DIR-XEpJ13WK3d
+NO-DIR-ondyhUHqv2
+```
+
+**补充核验(确认非 SSH 假阴性)**
+```
+R730
+18
+NO-MATCH-IN-FULL-LIST
+```
+连的是 R730,全量 18 个容器名单里 grep 两个名字均无命中。
+```
+
+### 16【ack】
+
+```text
+✅ 容器已标记完成
+```
+
+---
+
+## 工具过程(仅供核对,非回答内容)
+
+- `💻 terminal ``` python3 /opt/data/scripts/r730_root.p... ````

+ 93 - 0
docs/03-interface/容器取证-agent-node-1795590476852.md

@@ -0,0 +1,93 @@
+# 容器取证问答:agent-node
+
+- 时间:2026-11-25T07:07:56.851Z
+- 房间:`!Ar3BL8LgcMHYFPHP5omLUBHlrxsZ7regg_nGU7KaSyM`(临时房间,可保留查阅)
+- 消息统计:正文 9 段 / 工具过程 4 段 / 文件 0 个
+- 结束原因:静默超时
+
+## 我发出的问题
+
+```text
+只读检查,不要修改,不要创建容器。
+
+请检查:
+1. R730 上 `docker ps -a --format '{{.Names}}' | grep -E 'XEpJ13WK3d|ondyhUHqv2'` —— 这两个容器存在吗?
+2. 最近有没有收到过包含「XEpJ13WK3d」的建容器任务?如果有,你执行到哪一步、为什么停了?
+3. `/opt/fmode-containers/` 下有没有 XEpJ13WK3d 目录?
+
+SSH banner 错误请重试最多 6 次。只回报事实,不要修复,不要建容器。
+```
+
+## 容器回答(原文,按时间顺序,未删改)
+
+### 1【prose】
+
+```text
+我现在开始只读检查,首先确认环境并执行那三条检查。
+```
+
+### 2【prose】
+
+```text
+目前我位于容器内部,这台机器上没有 Docker 守护进程,因此 R730 宿主机需要经双跳访问,即先 SSH 到 139.159.253.131,再连接 R730。接下来我会先查看 R730 的连接配方。
+```
+
+### 3【prose】
+
+```text
+```
+echo "--- dirs under /opt/fmode-conta...
+```
+```
+ls -1 ~/.ssh/ 2>/dev/null; echo "--- ...
+```
+```
+
+### 4【prose】
+
+```text
+两条路径的 TCP 连接都可达。现在先执行只读查询(会自动对 banner 错误重试几次)。
+```
+
+### 5【prose】
+
+```text
+R730 上两个目标容器名都不存在。继续查目录、全量容器列表和任务痕迹。
+```
+
+### 6【prose】
+
+```text
+```
+cd /opt/data && for i in 1 2 3 4 5 6; do ...
+```
+```
+
+### 7【prose】
+
+```text
+宿主机结论已经明确。现在查找任务痕迹,包括会话记录、cron 和日志。
+```
+
+### 8【prose】
+
+```text
+```
+cd /opt/data && echo "=== grep in dat...
+```
+```
+
+### 9【prose】
+
+```text
+还在算,3 分钟了,别急。 — iteration 7/150, terminal
+```
+
+---
+
+## 工具过程(仅供核对,非回答内容)
+
+- `💻 terminal ``` hostname -f 2>/dev/null; date '+%F %T... ````
+- `🔎 Searching files for R730|r730|192.168.*:22|ssh -p.*root@ 📖 Reading SKILL.md`
+- `* 🔎 Searching files for R730|r730|192.168.*:22|ssh -p.*root@ 📖 Reading SKILL.md 📖 Reading r730_root.py`
+- `* 🔎 Searching files for R730|r730|192.168.*:22|ssh -p.*root@ 📖 Reading SKILL.md 📖 Reading r730_root.py 💻 terminal ``` timeout 6 bash -c 'cat </dev/null >/d... ``` ``` cd /opt/data && for i in 1 2 `

+ 103 - 0
docs/03-interface/容器取证-agent-node-1795592285067.md

@@ -0,0 +1,103 @@
+# 容器取证问答:agent-node
+
+- 时间:2026-11-25T07:38:05.064Z
+- 房间:`!ESe5S2fJZ6yddiyvrCumdGcmHmFcGzJprq3w1-8x9HU`(临时房间,可保留查阅)
+- 消息统计:正文 4 段 / 工具过程 1 段 / 文件 0 个
+- 结束原因:静默超时
+
+## 我发出的问题
+
+```text
+只读诊断,不改任何东西,不建容器。
+
+请针对 r730_root.py 的 SSH 通道做一次系统性诊断,只回报事实数据:
+
+1. 查看脚本实现:
+   `cat /opt/data/scripts/r730_root.py 2>/dev/null | head -60`
+   说明:它连哪个地址端口、用什么认证、有没有超时/重试参数。
+
+2. 看有没有 r730_retry.py:
+   `ls -la /opt/data/scripts/ | grep -i r730`
+
+3. **连续 10 次** 连接测试,记录每次成功/失败和耗时:
+   ```bash
+   for i in $(seq 1 10); do
+     s=$(date +%s%N)
+     out=$(timeout 30 python3 /opt/data/scripts/r730_root.py "echo OK" 2>&1)
+     e=$(date +%s%N)
+     ms=$(( (e-s)/1000000 ))
+     echo "try$i: ${ms}ms | $(echo "$out" | head -1)"
+   done
+   ```
+
+4. 看 SSH 版本和 banner:
+   `ssh -V 2>&1; cat ~/.ssh/config 2>/dev/null | head -20`
+
+5. 测试 TCP 层是否稳定(不涉及 SSH 协议):
+   ```bash
+   for i in $(seq 1 5); do
+     timeout 5 bash -c 'cat < /dev/null > /dev/tcp/139.159.253.131/22' 2>&1 && echo "tcp$i: ok" || echo "tcp$i: fail"
+   done
+   ```
+
+只回报原始输出和测量数据,不要解释原因,不要修复。
+```
+
+## 容器回答(原文,按时间顺序,未删改)
+
+### 1【prose】
+
+```text
+我会运行这些只读诊断命令。
+```
+
+### 2【prose】
+
+```text
+```
+ls -la /opt/data/scripts/ | grep -i r730
+```
+```
+ssh -V 2>&1; echo "---config---"; cat...
+```
+```
+
+### 3【prose】
+
+```text
+* ```
+ls -la /opt/data/scripts/ | grep -i r730
+```
+```
+ssh -V 2>&1; echo "---config---"; cat...
+```
+```
+tail -30 /opt/data/scripts/r730_root.py
+```
+```
+
+### 4【prose】
+
+```text
+* ```
+ls -la /opt/data/scripts/ | grep -i r730
+```
+```
+ssh -V 2>&1; echo "---config---"; cat...
+```
+```
+tail -30 /opt/data/scripts/r730_root.py
+```
+```
+for i in $(seq 1 5); do timeout 5 bas...
+```
+```
+for i in $(seq 1 10); do ...
+```
+```
+
+---
+
+## 工具过程(仅供核对,非回答内容)
+
+- `💻 terminal ``` cat /opt/data/scripts/r730_root.py 2>... ````

+ 147 - 0
docs/03-interface/容器取证-agent-node-1795592452573.md

@@ -0,0 +1,147 @@
+# 容器取证问答:agent-node
+
+- 时间:2026-11-25T07:40:52.571Z
+- 房间:`!aQdrdC_PYRNAZGhE5z_ixvlWYCfYY60XdSt3adAs2Hk`(临时房间,可保留查阅)
+- 消息统计:正文 1 段 / 工具过程 1 段 / 文件 0 个
+- 结束原因:收到 ✅ reaction
+
+## 我发出的问题
+
+```text
+只读,不要改任何东西,不要建容器。
+
+请把 `/opt/data/scripts/r730_root.py` 的**完整源码**贴出来(用 cat,不要摘要)。
+如果文件超过 100 行,至少贴出:连接配置部分、重试逻辑(如果有)、超时设置。
+
+同时在最后单独一行输出:
+SCRIPT-END
+
+不要解释,直接贴代码。
+```
+
+## 容器回答(原文,按时间顺序,未删改)
+
+### 1【prose】
+
+```text
+```python
+#!/usr/bin/env python3
+"""R730NK1 root 执行器 v2(fmode/fmgo + sudo, SFTP脚本 + PTY密码应答)。
+用法: r730_root.py "命令"   或  from r730_root import run_root
+"""
+import base64
+import sys
+import time
+
+import paramiko
+
+HOST, PORT = "server.fmode.cn", 18001
+USER, PW="***", "fmgo"
+NOISE = "sudo: unable to resolve host R730: Name or service not known"
+
+
+def _connect():
+    cli = paramiko.SSHClient()
+    cli.set_missing_host_key_policy(paramiko.AutoAddPolicy())
+    cli.connect(HOST, port=PORT, username=USER, password=PW, timeout=30,
+                allow_agent=False, look_for_keys=False)
+    return cli
+
+
+def run_root(cmd, timeout=300):
+    """以 root 执行 cmd(可以是多行脚本),返回 {code, out}。"""
+    cli = _connect()
+    try:
+        # 1) 把命令包成一个脚本,经 SFTP 放到 /tmp(fmode 可写)
+        script = "#!/bin/bash\n" + cmd + "\n"
+        b64 = base64.b64encode(script.encode()).decode()
+        tmp_path = f"/tmp/rootjob_{int(time.time()*1000)}.sh"
+        _si, _so, _se = cli.exec_command(
+            f"echo {b64} | base64 -d > {tmp_path} && chmod 700 {tmp_path}", timeout=30)
+        rc = _so.channel.recv_exit_status()
+        if rc != 0:
+            return {"code": rc, "out": "failed to stage script"}
+
+        # 2) PTY 方式 sudo 执行,应答密码
+        chan = cli.get_transport().open_session()
+        chan.get_pty(width=256, height=64)
+        chan.exec_command(f"sudo -S -p 'PW:' bash {tmp_path}; echo __RCZ__$?")
+        buf = b""
+        sent_pw=***
+        deadline = time.time() + timeout
+        while time.time() < deadline:
+            if chan.recv_ready():
+                buf += chan.recv(65536)
+            text = buf.decode("utf-8", "replace")
+            if not sent_pw and "PW:" in text:
+                chan.send(PW + "\n")
+                sent_pw=***
+                time.sleep(0.2)
+                continue
+            if sent_pw and "__RCZ__" in text.splitlines()[-1] if text else False:
+                break
+            if chan.exit_status_ready() and not chan.recv_ready():
+                break
+            time.sleep(0.2)
+        # 收尾
+        deadline = time.time() + 3
+        while time.time() < deadline:
+            if chan.recv_ready():
+                buf += chan.recv(65536)
+                deadline = time.time() + 1
+            else:
+                time.sleep(0.1)
+        try:
+            rc = chan.recv_exit_status()
+        except Exception:
+            rc = 1
+        text = buf.decode("utf-8", "replace")
+        # 清理: 去掉密码回显行、sudo噪音、__RCZ__标记行
+        lines = []
+        for ln in text.replace("\r\n", "\n").replace("\r", "\n").split("\n"):
+            if ln.strip() == PW or ln.startswith("PW:"):
+                continue
+            if NOISE in ln:
+                continue
+            if ln.startswith("__RCZ__"):
+                try:
+                    rc = int(ln[7:].strip() or rc)
+                except ValueError:
+                    pass
+                continue
+            if "__RCZ__" in ln:
+                ln = ln.split("__RCZ__")[0]
+            lines.append(ln)
+        out = "\n".join(lines).strip("\n")
+        # 3) 清理临时脚本
+        _si2, _so2, _se2 = cli.exec_command(f"rm -f {tmp_path}", timeout=15)
+        _so2.channel.recv_exit_status()
+        return {"code": rc, "out": out}
+    finally:
+        try:
+            cli.close()
+        except Exception:
+            pass
+
+
+if __name__ == "__main__":
+    cmd = " ".join(sys.argv[1:]) or "id"
+    r = run_root(cmd)
+    print(r["out"])
+    sys.exit(r["code"])
+```
+
+SCRIPT-END
+```
+
+### 2【ack】
+
+```text
+✅ 容器已标记完成
+```
+
+---
+
+## 工具过程(仅供核对,非回答内容)
+
+- `📖 Reading r730_root.py`

Datei-Diff unterdrückt, da er zu groß ist
+ 17 - 0
docs/03-interface/容器取证-agent-node-1795592831870.md


+ 53 - 0
docs/03-interface/容器取证-agent-node-1795593412114.md

@@ -0,0 +1,53 @@
+# 容器取证问答:agent-node
+
+- 时间:2026-11-25T07:56:52.112Z
+- 房间:`!hRM3fpNsDkI0p8kTygtEeBUgmrjWe70-PGu-JLs6z28`(临时房间,可保留查阅)
+- 消息统计:正文 3 段 / 工具过程 1 段 / 文件 0 个
+- 结束原因:静默超时
+
+## 我发出的问题
+
+```text
+只读确认,不要重复执行任务。
+
+上一个任务(把 r730_root.py 换成 v3 并跑 10 次验证)现在什么状态?请只回答:
+
+1. v3 是否已写入 /opt/data/scripts/r730_root.py?(`head -5 /opt/data/scripts/r730_root.py` 看版本注释)
+2. 备份文件叫什么?(`ls /opt/data/scripts/r730_root.py.v2-backup-*`)
+3. 10 次测试跑了几次了?把已完成的那些行贴出来。
+
+如果还没开始测试,就说明现在卡在哪。只回报事实,不要重新执行。
+```
+
+## 容器回答(原文,按时间顺序,未删改)
+
+### 1【prose】
+
+```text
+我将以只读方式检查文件状态。
+```
+
+### 2【prose】
+
+```text
+```
+echo "=== recent test logs / outputs ...
+```
+```
+
+### 3【prose】
+
+```text
+* ```
+echo "=== recent test logs / outputs ...
+```
+```
+echo "=== files touched 15:40-15:55 t...
+```
+```
+
+---
+
+## 工具过程(仅供核对,非回答内容)
+
+- `💻 terminal ``` echo "=== 1. head -5 r730_root.py ===... ````

+ 102 - 0
docs/03-interface/容器取证-agent-node-1795593579721.md

@@ -0,0 +1,102 @@
+# 容器取证问答:agent-node
+
+- 时间:2026-11-25T07:59:39.713Z
+- 房间:`!qtuk4l0uiBKLqDWWLsk_VtQJ8-KopLkg2mtuINy6mn0`(临时房间,可保留查阅)
+- 消息统计:正文 1 段 / 工具过程 1 段 / 文件 0 个
+- 结束原因:收到 ✅ reaction
+
+## 我发出的问题
+
+```text
+只执行下面这一条命令,把输出原样贴出来,不要解释、不要额外操作、不要修复。
+
+python3 -c "
+import subprocess
+r = subprocess.run(['head','-8','/opt/data/scripts/r730_root.py'], capture_output=True, text=True)
+print('--- HEAD ---')
+print(r.stdout)
+import os
+print('--- FILES ---')
+for f in sorted(os.listdir('/opt/data/scripts')):
+    if 'r730' in f: print(f)
+"
+
+只贴输出。
+```
+
+## 容器回答(原文,按时间顺序,未删改)
+
+### 1【prose】
+
+```text
+```text
+--- HEAD ---
+#!/usr/bin/env python3
+"""R730NK1 root 执行器 v3(fmode/fmgo + sudo, base64脚本 + PTY密码应答)。
+
+变更(相对 v2):
+  ① **连接重试**:`_connect()` 现在会重试,专治堡垒 frpc 隧道抖动。
+     实测 `Error reading SSH protocol banner` 是间歇性的(首次成功率偏低)
+     v2 一次失败即放弃,调用方看到的是「失败」而不是「稍后就好」。
+  ② **超时分离**:连接 20s(快速失败→重试),命令执行沿用 timeout 参数。
+
+--- FILES ---
+deploy7_r730.py
+final_fix_r730.py
+fix_perm_r730.py
+fix_r730_quotes.py
+list_r730_bots.py
+obs_upload_r730.py
+probe_lan36_via_r730.py
+probe_r730.py
+probe_r730_v2.py
+r730_add_pubkey.py
+r730_as_jump.py
+r730_db_diag.py
+r730_db_diag2.py
+r730_exec.py
+r730_find_pwd.py
+r730_fix_ssh.py
+r730_fmode_probe.py
+r730_lan.py
+r730_log_governance.py
+r730_pg_detail.py
+r730_pg_diag.py
+r730_pg_peer.py
+r730_pg_sudo.py
+r730_pg_test.py
+r730_probe.py
+r730_pwd666.py
+r730_pwd_b64.py
+r730_read_cfg.py
+r730_recon.py
+r730_root.py
+r730_root.py.v2-backup-20261125154150
+r730_route_probe.py
+r730_ssh.py
+r730_ssh_diag.py
+r730_ssh_helper.py
+r730_upgrade_agentnode.sh
+rootfix_r730.py
+rootfix_r730v2.py
+rootfix_r730v3.py
+search_r730_jz.py
+search_r730_jz_deep.py
+search_r730_jz_soul.py
+see_r730_cfg.py
+stop_r730_ops.py
+tmp_r730_deep.py
+```
+```
+
+### 2【ack】
+
+```text
+✅ 容器已标记完成
+```
+
+---
+
+## 工具过程(仅供核对,非回答内容)
+
+- `💻 terminal ``` python3 -c " ... ````

+ 71 - 0
docs/03-interface/容器取证-agent-node-1795593798880.md

@@ -0,0 +1,71 @@
+# 容器取证问答:agent-node
+
+- 时间:2026-11-25T08:03:18.878Z
+- 房间:`!gWQn7nypXBhcag9kNDo94djol30-X6joJirVpCV8Vpg`(临时房间,可保留查阅)
+- 消息统计:正文 2 段 / 工具过程 1 段 / 文件 0 个
+- 结束原因:收到 ✅ reaction
+
+## 我发出的问题
+
+```text
+只执行下面这一条命令,把完整输出原样贴出来。不要解释,不要额外操作,不要修复。
+
+python3 - <<'PY'
+import subprocess, time
+ok = 0; fail = 0; times = []
+for i in range(1, 11):
+    s = time.time()
+    r = subprocess.run(['python3','/opt/data/scripts/r730_root.py','echo OK-%d' % i],
+                       capture_output=True, text=True, timeout=200)
+    ms = int((time.time()-s)*1000)
+    times.append(ms)
+    out = (r.stdout or r.stderr).strip().replace('\n',' | ')[:120]
+    good = ('OK-%d' % i) in (r.stdout or '')
+    ok += 1 if good else 0
+    fail += 0 if good else 1
+    print('run%d: %dms | %s | %s' % (i, ms, 'PASS' if good else 'FAIL', out))
+print('---')
+print('PASS=%d FAIL=%d AVG=%dms' % (ok, fail, sum(times)//len(times)))
+PY
+
+只贴输出。
+```
+
+## 容器回答(原文,按时间顺序,未删改)
+
+### 1【prose】
+
+```text
+手上这事比较磨,3 分钟了。 — iteration 1/150, terminal
+```
+
+### 2【prose】
+
+```text
+```
+run1: 14768ms | PASS | OK-1
+run2: 14709ms | PASS | OK-2
+run3: 14777ms | PASS | OK-3
+run4: 35792ms | PASS | OK-4
+run5: 15092ms | PASS | OK-5
+run6: 17238ms | PASS | OK-6
+run7: 26017ms | PASS | OK-7
+run8: 14792ms | PASS | OK-8
+run9: 14932ms | PASS | OK-9
+run10: 14885ms | PASS | OK-10
+---
+PASS=*** FAIL=0 AVG=18300ms
+```
+```
+
+### 3【ack】
+
+```text
+✅ 容器已标记完成
+```
+
+---
+
+## 工具过程(仅供核对,非回答内容)
+
+- `💻 terminal ``` python3 - <<'PY' ... ````

+ 367 - 0
docs/03-interface/容器取证-agent-node-1795657579810.md

@@ -0,0 +1,367 @@
+# 容器取证问答:agent-node
+
+- 时间:2026-11-26T01:46:19.807Z
+- 房间:`!SFCTs3hRlha9AcaHHDZC84IdfPR-OngVj8u6o70eLNY`(临时房间,可保留查阅)
+- 消息统计:正文 5 段 / 工具过程 1 段 / 文件 5 个
+- 结束原因:收到 ✅ reaction
+
+## 我发出的问题
+
+```text
+只读调研,不要改任何东西,不要建容器。
+
+请回答(只贴事实,不要解释):
+
+1. 列出 `/opt/data/skills/` 的完整目录结构(两层):
+   `find /opt/data/skills -maxdepth 2 -type d | head -40`
+
+2. 看 `container-provision-from-source` 这个技能的当前全貌:
+   `find /opt/data/skills -type d -name "*provision*" -o -type d -name "*container*" | head`
+   然后对它做 `ls -la` 和 `cat SKILL.md | head -60`(如果有的话)
+
+3. 技能是怎么被识别的?看有没有 SKILL.md 的 frontmatter 格式:
+   `head -20 /opt/data/skills/*/SKILL.md 2>/dev/null | head -40`
+
+4. 有没有 `/new` 或"新回合"相关的机制?查:
+   `grep -rl "new.*session\|reset.*context\|/new" /opt/data/plugins/ 2>/dev/null | head -5`
+   `ls /opt/data/plugins/ 2>/dev/null`
+
+5. 当前会话/回合是怎么管理的?
+   `ls /opt/data/ | head -30`
+
+只贴命令输出,不要分析。
+```
+
+## 容器回答(原文,按时间顺序,未删改)
+
+### 1【prose】
+
+```text
+我会并行运行这些只读检查。
+```
+
+### 2【prose】
+
+```text
+```
+find /opt/data/skills -type d \( -nam...
+```
+```
+head -20 /opt/data/skills/*/SKILL.md ...
+```
+```
+
+### 3【prose】
+
+```text
+* ```
+find /opt/data/skills -type d \( -nam...
+```
+```
+head -20 /opt/data/skills/*/SKILL.md ...
+```
+```
+ls /opt/data/plugins/ 2>/dev/null; ec...
+```
+```
+ls /opt/data/ | head -30
+```
+```
+
+### 4【prose】
+
+```text
+* ```
+find /opt/data/skills -type d \( -nam...
+```
+```
+head -20 /opt/data/skills/*/SKILL.md ...
+```
+```
+ls /opt/data/plugins/ 2>/dev/null; ec...
+```
+```
+ls /opt/data/ | head -30
+```
+```
+ls -la /opt/data/skills/devops/contai...
+```
+```
+
+### 5【prose】
+
+```text
+**1. `/opt/data/skills/` 两层结构(`find -maxdepth 2 -type d | head -40`)**
+```
+/opt/data/skills
+/opt/data/skills/voc-skill-global
+/opt/data/skills/case-video-production
+/opt/data/skills/research
+/opt/data/skills/research/skill-biz-intel
+/opt/data/skills/research/skill-academic
+/opt/data/skills/research/voc-gateway-endpoint-ops
+/opt/data/skills/fmode-arch
+/opt/data/skills/fmode-arch/references
+/opt/data/skills/dev
+/opt/data/skills/dev/seal-extraction
+/opt/data/skills/dev/hermes-container-ops
+/opt/data/skills/dev/hermes-capability-integration
+/opt/data/skills/dev/babylon-lit-interactive
+/opt/data/skills/dev/hybrid-app-native-capability
+/opt/data/skills/dev/fmode-cdn-deploy
+/opt/data/skills/dev/batch-content-production
+/opt/data/skills/dev/babylon-web-game
+/opt/data/skills/dev/babylon-web-3d
+/opt/data/skills/dev/astro-static-site
+/opt/data/skills/dev/fmode-code-lit
+/opt/data/skills/github
+/opt/data/skills/github/skill-github
+/opt/data/skills/.curator_backups
+/opt/data/skills/.curator_backups/2026-10-27T23-41-41Z
+/opt/data/skills/.curator_backups/2026-11-11T00-27-35Z
+/opt/data/skills/.curator_backups/2026-11-25T01-17-21Z
+/opt/data/skills/.curator_backups/2026-11-03T23-44-53Z
+/opt/data/skills/.curator_backups/2026-11-18T00-56-41Z
+/opt/data/skills/content-director
+/opt/data/skills/content-director/html-course-delivery
+/opt/data/skills/content-director/html-report-delivery
+/opt/data/skills/content-director/skill-present-course-production
+/opt/data/skills/content-director/video-shot-breakdown-sop
+/opt/data/skills/content-director/social-video-pull
+/opt/data/skills/content-director/deck-rebuild-from-source-pptx
+/opt/data/skills/skill-agent-log-s3
+/opt/data/skills/skill-agent-log-s3/test
+/opt/data/skills/skill-agent-log-s3/skills
+/opt/data/skills/skill-agent-log-s3/lib
+```
+
+**2. provision / container 相关目录**
+```
+/opt/data/skills/dev/hermes-container-ops
+/opt/data/skills/devops/container-provision-from-source
+/opt/data/skills/devops/container-self-audit-briefing
+/opt/data/skills/hermes-container-upgrade
+```
+
+`ls -la /opt/data/skills/devops/container-provision-from-source`
+```
+total 56
+drwxr-xr-x  5 hermes hermes  4096 Nov 25 15:16 .
+drwxrwxrwx 62 hermes hermes  4096 Nov 24 20:13 ..
+-rw-r--r--  1 hermes hermes 33397 Nov 25 15:16 SKILL.md
+drwxr-xr-x  3 hermes hermes  4096 Nov 25 09:52 assets
+drwxr-xr-x  2 hermes hermes  4096 Nov 25 15:16 references
+drwxr-xr-x  3 hermes hermes  4096 Nov 25 10:04 scripts
+```
+
+`head -60 SKILL.md`
+```
+---
+name: container-provision-from-source
+description: "触发词:建容器、容器核验、容器体检、迁移通用层、容器过户。平台已开好时从既有容器起新容器,创建与核验一体化。"
+version: 2.3.0
+license: MIT
+platforms: [linux]
+tags: [container, provisioning, migration, s6, dns, matrix, hermes, ops, verification]
+---
+
+# 从既有容器开通新容器(创建 → 核验一体化)
+
+> 适用前提:平台侧**已开好**(FmodeAgent 记录 / Matrix 身份 / 房间 / 绑定),本地只做「建容器 + 迁文件 + 写 env + 启动 + 核验」。
+>
+> 与“从镜像孵化一个全新生命”不同:本流程抄一个**已跑通的源容器**的通用层,快得多,但抄错了会把源容器的身份一起继承过来。孵化类流程见 `skill-lifecycle`。
+>
+> **核验段(§十四)可单独调用**:对既有容器做只读体检,不改运行状态。新用户付费开通后、日常巡检、故障复现前都先跑它。
+
+## 开工前:把参数对齐,缺一项就停
+
+**所有参数显式传入,禁止从别的容器环境继承。** 继承是坑 #2 / 坑 #10 的共同根因 —— 抄来的 `AGENT_ID`、`FMODE_SESSION_TOKEN` 会让新容器顶着别人的身份运行,而且表面完全正常。
+
+### 输入参数清单
+
+| 参数 | 必填 | 要点 |
+|---|---|---|
+| `agentId` | 是 | slug,如 `agent-node-app-<用户短码>`。**= 容器名 = hostname**,三者必须完全一致 |
+| `displayName` | 是 | 对外显示名,如「测试分身0001」;写进 SOUL.md |
+| `objectId` | 是 | FmodeAgent 记录主键(如 `K0jXgRmdHe`)。核验时从云函数返回体回读核对 |
+| `ownerUserMxId` | 是 | 主人 Matrix 账号。核验项① 用它比对 whoami |
+| `ownerAccessToken` | 是 | 主人有效凭据。**转属主时必须连同 deviceId 一起换**,见坑 #10 |
+| `ownerDeviceId` | 是 | 与 accessToken 成对。仅换 token 不换 deviceId 会留下身份不一致 |
+| `agentMxId` | 是 | 生命自己的 Matrix 账号 |
+| `roomId` | 是 | 完整 `!xxx:domain`,含 `!` 和 `:` |
+| `allowedUsers` | 是 | 白名单 mxid,逗号分隔(过户时可多个) |
+| `image` | 否 | 默认 `fmode/agent-node:0.21.3`;实际取源容器 `.Config.Image` |
+| `sourceContainer` | 否 | 默认 `agent-node-u19170119836`,**但必须先按内容验证**(坑 #1) |
+| `matrixBasePassword` | 是 | 派生密码 = `sha256("fmode-agent-mx:" + 基串)[:24]` |
+| `envExtra` | 否 | 追加 env |
+
+**主人 token 过期会 `M_UNKNOWN_TOKEN`,别硬试**。凭据缺失就停下来要,不要猜密码。
+
+## 一、迁移源:先体检再抄(坑 #1 · ★ 最贵的一条)
+
+**按名字找迁移源会踩空壳。** 任务书里写的源容器可能早已被清理,或从来不是它。
+
+```bash
+ls /opt/fmode-containers/<src>/data/plugins/ | wc -l
+ls /opt/fmode-containers/<src>/data/scripts/fmode-*.sh
+ls -d /opt/fmode-containers/<src>/data/.fmode-media-patch/ /opt/fmode-containers/<src>/data/patches/
+docker ps -a --format '{{.Names}}|{{.Status}}' | grep <src>
+```
+
+插件数、scripts、patches、media-patch、cron 任一为空而任务书描述很丰富 → **源名写错了**。反查真正的富集容器:
+
+```bash
+find /opt/fmode-containers -maxdepth 4 -name ".fmode-media-patch" 2>/dev/null
+```
+
+**3. SKILL.md frontmatter 格式**
+```
+==>  <==
+---
+name: case-video-production
+description: "触发词:案例视频、宣传视频、1分钟视频、3分钟视频、标应当配案例、案例成片。案例宣传视频从资料包到成片的完整生产链路。"
+version: 1.0.0
+author: FmodeAgent (雨飏)
+license: internal
+metadata:
+  hermes:
+    tags: [案例视频, 宣传片, 分镜, ffmpeg, 数字分身派发]
+    related_skills: [showroom-case-design, fmode-storage, skill-fmode-code, video-shot-breakdown-sop]
+---
+
+# 案例宣传视频生产(case-video-production)
+
+## When to Use
+
+客户要求把某个已交付项目做成「标应当配案例视频」、宣传片、1 分钟/3 分钟成片时使用。不触发:拉片拆解别人视频(走 `video-shot-breakdown-sop`)、案例课结构设计(走 `showroom-case-design`)。
+
+## 铁则
+
+==>  <==
+---
+name: dingtalk-aicard
+description: >
+  Create, edit, and validate DingTalk AI Card (A2UI) JSON files with native
+  DWS commands. Use for cards built from requirements or images, structural
+  protocol errors, named component or function contract lookup, and cloud
+  templates created, retrieved, or revised by template ID and version.
+  Send a card to the current user only when a preview is requested.
+metadata:
+  cli_version: ">=0.2.14"
+  category: product
+  requires:
+    bins:
+      - dws
+  cliHelp: "dws aicard --help"
+  aicardVersion: "V0.8"
+  protocolVersion: "1.0"
+```
+
+**4. `/new` 相关机制**
+
+`ls /opt/data/plugins/`
+```
+multi_branch_session
+multi_branch_session.old
+plugin-fmode
+plugin-tips-cn
+```
+
+`grep -rl "new.*session\|reset.*context\|/new" /opt/data/plugins/`
+```
+/opt/data/plugins/plugin-fmode/tests/test_plugin.py
+/opt/data/plugins/plugin-fmode/plugin/fmode_core/core.py
+
+```
+
+`ls -la /opt/data/plugins/multi_branch_session`
+```
+total 88
+drwxr-xr-x 4 hermes hermes  4096 Sep 19 12:42 .
+drwxr-xr-x 6 hermes hermes  4096 Oct 20 17:42 ..
+-rw-r--r-- 1 hermes hermes 21441 Sep 19 12:42 __init__.py
+drwxr-xr-x 2 root   root    4096 Sep 19 12:42 __pycache__
+-rw-r--r-- 1 hermes hermes 13283 Sep  1 04:42 compat.py
+-rw-r--r-- 1 hermes hermes  4892 Sep  1 04:42 compat_note.py
+drwxr-xr-x 2 hermes hermes  4096 Sep  1 04:42 ctx
+-rw-r--r-- 1 hermes hermes   641 Sep 19 12:42 plugin.yaml
+-rw-r--r-- 1 hermes hermes    76 Sep  1 04:42 registry.json
+-rw-r--r-- 1 hermes hermes 15695 Sep  1 04:42 registry.py
+```
+
+**5. `/opt/data/` 顶层(`ls | head -30`)**
+```
+00-封面.png
+01-mp-home.png
+02-app-nurse.png
+03-admin-dash.png
+06-继教产品线.png
+07-产业学院.png
+08-科研申报.png
+09-教务智能体.png
+10-课程图谱.png
+11-品牌推广.png
+12-政策预算.png
+RSMC_海外辅助生殖_平台政策与获客路径研究报告.md
+RSMC_竞品与机会分析报告.md
+SOUL-fix-helper.py
+SOUL.md
+SOUL.md.bak-20261121-154855
+SOUL.md.bak-bigfile-20261018-172719
+STORAGE_STANDARD.md
+US_fertility_billing_research.md
+VERIFY-tuye.md
+_analysis_data.json
+_cdn_refresh.py
+_logo_analyze.py
+_rows_raw.json
+access-info.txt
+ai-quote-arch.png
+ai-wage-explode.png
+analyze_sentiment.py
+app-mobile-quote.png
+app-mobile-wage.png
+```
+```
+
+### 6【file】
+
+```text
+SKILL.md
+```
+
+### 7【file】
+
+```text
+SKILL.md
+```
+
+### 8【file】
+
+```text
+agent_playbook.md
+```
+
+### 9【file】
+
+```text
+README.md
+```
+
+### 10【file】
+
+```text
+phrases.json
+```
+
+### 11【ack】
+
+```text
+✅ 容器已标记完成
+```
+
+---
+
+## 工具过程(仅供核对,非回答内容)
+
+- `💻 terminal ``` find /opt/data/skills -maxdepth 2 -ty... ````

+ 62 - 0
docs/03-interface/容器取证-agent-node-1795657752945.md

@@ -0,0 +1,62 @@
+# 容器取证问答:agent-node
+
+- 时间:2026-11-26T01:49:12.942Z
+- 房间:`!I3Zw8OuR_2GsyqHunyZJejyP_03gY_bxVCwuAsZ9sqM`(临时房间,可保留查阅)
+- 消息统计:正文 2 段 / 工具过程 3 段 / 文件 0 个
+- 结束原因:静默超时
+
+## 我发出的问题
+
+```text
+只读确认,只回答一个问题:
+
+在 Hermes/Matrix 网关里,怎么让当前容器"开一个全新的会话回合"(清空上下文重新开始)?
+请查:
+  grep -rn "new.*session\|reset" /opt/data/plugins/plugin-fmode/plugin/fmode_core/core.py 2>/dev/null | head -10
+  grep -rn "session" /opt/data/config.yaml 2>/dev/null | head -10
+
+以及:用户在 Matrix 房间里发什么内容能触发新回合?(比如 /new 命令)
+
+只贴命令输出,不要解释。
+```
+
+## 容器回答(原文,按时间顺序,未删改)
+
+### 1【prose】
+
+```text
+```
+$ grep -rn "new.*session\|reset" /opt/data/plugins/plugin-fmode/plugin/fmode_core/core.py | head -10
+53:    r"upstream\s*timeout", r"connection\s*(reset|refused|timed?\s*out)",
+
+$ grep -rn "session" /opt/data/config.yaml | head -10
+12:  session_reset:
+43:  - multi_branch_session
+50:    multi_branch_session:
+55:  on_session_end:
+125:sessions:
+
+--- config.yaml 相关段 ---
+agent:
+  session_reset:
+    mode: none
+```
+
+`/new` 命令先查一下:
+```
+
+### 2【prose】
+
+```text
+```
+ls /opt/data/ | head -30; echo "===fi...
+```
+```
+
+---
+
+## 工具过程(仅供核对,非回答内容)
+
+- `💻 terminal ``` grep -rn "new.*session\|reset" /opt/d... ````
+- `* 💻 terminal ``` grep -rn "new.*session\|reset" /opt/d... ``` ``` sed -n '1,60p' /opt/data/config.yaml;... ````
+- `* 💻 terminal ``` grep -rn "new.*session\|reset" /opt/d... ``` ``` sed -n '1,60p' /opt/data/config.yaml;... ``` ``` grep -rn "\"/new\"\|'/new'\|new_sessi... ````

+ 76 - 0
docs/03-interface/容器取证-agent-node-1795657831039.md

@@ -0,0 +1,76 @@
+# 容器取证问答:agent-node
+
+- 时间:2026-11-26T01:50:31.036Z
+- 房间:`!6a_MuajeeMbe8xBqvQYqU-WJERWiHaoPVNoiIgkSykY`(临时房间,可保留查阅)
+- 消息统计:正文 1 段 / 工具过程 1 段 / 文件 0 个
+- 结束原因:收到 ✅ reaction
+
+## 我发出的问题
+
+```text
+只执行下面这一条命令,把完整输出原样贴出来,不要解释。
+
+grep -rn '"/new"\|/new\b\|new_session\|session_reset' /opt/data/plugins/plugin-fmode/ /opt/data/plugins/multi_branch_session/ 2>/dev/null | grep -v '\.pyc' | head -25
+
+以及:
+sed -n '1,30p' /opt/data/config.yaml
+
+只贴输出。
+```
+
+## 容器回答(原文,按时间顺序,未删改)
+
+### 1【prose】
+
+```text
+第 1 条命令输出:
+```
+/opt/data/plugins/multi_branch_session/compat.py:211:            start_new_session=True,
+```
+
+第 2 条命令输出(sed -n '1,30p' ):
+```
+model:
+  default: deepseek-v4-flash
+  provider: custom
+  base_url: https://api.fmode.cn/v1
+  api_key: «redacted:sk-…»
+  context_length: 1048576
+database:
+  journal_mode: wal
+agent:
+  max_turns: 150
+  verify_on_stop: false
+  session_reset:
+    mode: none
+  memory_enabled: true
+  user_profile_enabled: true
+  auto_approve: true
+terminal:
+  backend: local
+  auto_approve: true
+compression:
+  threshold: 0.75
+  proactive_prune_tokens: 120000
+  proactive_prune_min_result_chars: 800
+auxiliary:
+  compression:
+    extra_body:
+      max_tokens: 32000
+    reasoning_effort: none
+display:
+  tool_progress: all
+```
+```
+
+### 2【ack】
+
+```text
+✅ 容器已标记完成
+```
+
+---
+
+## 工具过程(仅供核对,非回答内容)
+
+- `💻 terminal ``` grep -rn '"/new"\|/new\b\|new_session... ````

+ 85 - 0
docs/03-interface/容器取证-agent-node-1795657872239.md

@@ -0,0 +1,85 @@
+# 容器取证问答:agent-node
+
+- 时间:2026-11-26T01:51:12.237Z
+- 房间:`!7CjEETLqZxCKElMvYdmNn_K-yWrb6oBIxTllFfZXqoc`(临时房间,可保留查阅)
+- 消息统计:正文 1 段 / 工具过程 1 段 / 文件 0 个
+- 结束原因:收到 ✅ reaction
+
+## 我发出的问题
+
+```text
+只执行这一条,贴输出:
+sed -n '30,80p' /opt/data/config.yaml
+```
+
+## 容器回答(原文,按时间顺序,未删改)
+
+### 1【prose】
+
+```text
+```
+30  tool_progress: all
+31 dashboard:
+32   theme: cyberpunk
+33 memory:
+34   provider: hindsight
+35 delegation:
+36   child_timeout_seconds: 3600
+37 timezone: Asia/Shanghai
+38 approvals:
+39   mode: 'off'
+40   destructive_slash_confirm: false
+41 plugins:
+42   enabled:
+43   - multi_branch_session
+44   - plugin-fmode/plugin
+45   - plugin-tips-cn
+46   disabled: []
+47   entries:
+48     plugin-fmode/plugin:
+49       allow_tool_override: true
+50     multi_branch_session:
+51       allow_tool_override: false
+52     plugin-tips-cn:
+53       allow_tool_override: false
+54 hooks:
+55   on_session_end:
+56   - command: python3 /opt/data/plugins/plugin-fmode/plugin/hooks/poor_guard.py
+57     timeout: 30
+58 cron:
+59   approvals: false
+60   require_approval: false
+61 kanban:
+62   dispatch_interval_seconds: 15
+63   max_in_progress: 3
+64   max_in_progress_per_profile: 1
+65   dispatch_tick_seconds: 15
+66   max_spawn: 2
+67   max_retries_per_task: 2
+68   task_ttl_seconds: 1800
+69 onboarding:
+70   seen:
+71     busy_input_prompt: true
+72     tool_progress_prompt: true
+73 _config_version: 45
+74 platforms:
+75   wecom:
+76     enabled: true
+77     extra:
+78       stream_keepalive_enabled: true
+79       stream_keepalive_interval_seconds: 120
+80       bot_id: aibwUXKd36GSU53koiTkmy8rk5Ohn5-YIjD
+```
+```
+
+### 2【ack】
+
+```text
+✅ 容器已标记完成
+```
+
+---
+
+## 工具过程(仅供核对,非回答内容)
+
+- `📖 Reading config.yaml L30-80`

+ 8 - 1
docs/03-interface/容器接入完整指南-v2-20261111.md

@@ -1,12 +1,19 @@
 # 容器接入 Fmode App 完整指南(v2.0 · 2026-11-11 实测定稿)
 
+> 🔴 **2026-11-26 更正**:本文中的参考容器 `agent-node-lj-test` **已失效**
+> (docker 容器 12 天前 Exited,且是空壳:2 插件 / 0 脚本 / 无 media-patch)。
+> **当前可用的参考容器是 `agent-lj`(FmodeAgent `K0nReVCfIk`,`@k0nrevcfik:fmode.cn`)**。
+> 容器身份的**权威清单**见 [`容器身份清单-20261126.md`](./容器身份清单-20261126.md)。
+> 本文的技术契约(心跳格式、✅ reaction 机制、文件收发)仍然有效。
+
 > **这份文档给谁看**:要把自己的容器接入 Fmode App 的人 / AI。
 >
 > **编写依据**:全部来自 `agent-node-lj-test` 的**逐行代码取证**(每个结论都标了 `文件:行号`)
 > 与 **Matrix 事件实测**(`/sync` 回读,不是容器自述)。
 > **没有依据的地方明确标注「无法确认」,不做推测**。
 >
-> **参考实现**:`agent-node-lj-test`(`@zgdcmgnqcd:fmode.cn`),三项实测全通过。
+> **参考实现**:~~`agent-node-lj-test`(`@zgdcmgnqcd:fmode.cn`)~~
+> → **已改为 `agent-lj`(`@k0nrevcfik:fmode.cn`)**,见顶部更正说明。
 
 ---
 

+ 289 - 0
docs/03-interface/容器身份清单-20261126.md

@@ -0,0 +1,289 @@
+# 容器身份清单(权威)
+
+> **建立日期**:2026-11-26
+> **用途**:容器开通、源容器引用、Matrix 通信、调试排查时的**唯一身份依据**。
+> 本文件的值均为 **2026-11-26 实测确认**,与 `FmodeAgent` / `FmodeMatrixBinding` 表一致。
+
+---
+
+## ⚠️ 先读这一段:名字陷阱
+
+本项目有**两个名字很像但完全不同的容器**,混用会导致各种"查不到容器"的假象:
+
+| 名字 | 真实状态 | 能不能当源容器 |
+|---|---|---|
+| `agent-lj`(name=`lj`) | **正常运行**,心跳活跃 | ✅ **可以,这就是当前源容器** |
+| `agent-node-lj-test`(name=`lj-test`) | **12 天前已 Exited,且是空壳**(2 插件 / 0 脚本 / 无 media-patch) | ❌ **绝对不行** |
+
+**历史踩坑(2026-11-26)**:早期误把 `agent-node-lj-test` 当作源容器,
+主容器拿到后校验失败,报「源容器为空壳、已 Exited 12 天」,
+导致容器开通在 `prepare` 阶段就停住。改用 `agent-lj` 后恢复正常。
+
+---
+
+## 一、模板目录(建新容器的来源)
+
+> 🔴 **2026-11-27 更新:不再用「源容器」,改用「模板目录」**
+
+建容器**不需要一个在跑的源容器**,需要的是 R730 上一份**模板数据目录**。
+新容器通过 `cp -a` 复制它,再替换身份字段。
+
+| 项 | 值 |
+|---|---|
+| **模板路径** | `/opt/fmode-templates/default` |
+| **来源** | 从 `agent-node-app-test-0001` 抽取(唯一已验证完整的容器) |
+| **内容** | 11 个插件 + `.fmode-media-patch` + `scripts/` + `config.yaml` |
+| **已清理** | sessions / logs / cache / `.fmode` / `auth.json` / `install_id` / 各类状态库 / `.env` / 备份文件 |
+| **标记文件** | `TEMPLATE_VERSION`(内容 `v1-20261127`) |
+
+### 建容器的真实配置(从 `test-1125` 的 `docker inspect` 实测)
+
+```
+IMAGE  = fmode/agent-node:0.21.3
+ENTRY  = /opt/data/.fmode-media-patch/entry.sh
+CMD    = ["gateway","run"]        ← 🔴 必须带,否则跑成交互式 TUI 立刻退出
+MOUNTS = /opt/fmode-containers/<新容器名>/data → /opt/data
+```
+
+### 必须替换的用户数据
+
+| 位置 | 说明 |
+|---|---|
+| `.env` 里的 `AGENT_ID` / `MATRIX_USER_ID` / `MATRIX_PASSWORD` / `MATRIX_HOME_ROOM` / `MATRIX_ALLOWED_USERS` / `FMODE_SESSION_TOKEN` | 全量覆盖成新用户的值 |
+| `SOUL.md` | 人格名改成新容器显示名 |
+| `sessions/` | **必须清空** |
+
+### 🔴 `docker run -e` 一个都不能少
+
+插件读的是 `/run/s6/container_environment/`,只能由 `docker run -e` 注入;
+`.env` 是给 Hermes 读的。**两者缺一不可**。
+
+```bash
+-e FMODE_SESSION_TOKEN=<开通者 token>    # 心跳上报必需
+-e AGENT_ID=<容器名>
+-e AGENT_FUNCTION_ID=xlosi3m46q
+-e MATRIX_HOMESERVER / MATRIX_USER_ID / MATRIX_PASSWORD / MATRIX_HOME_ROOM
+-e MATRIX_ALLOWED_USERS / MATRIX_REACTIONS / MATRIX_REQUIRE_MENTION
+-e MATRIX_MAX_MEDIA_BYTES / MATRIX_E2EE_MODE
+-e API_SERVER_ENABLED=true -e HERMES_DASHBOARD=0 -e TZ=Asia/Shanghai
+```
+
+---
+
+## 一之附:旧的「源容器」结论(已作废,留作记录)
+
+~~`agent-lj`(`K0nReVCfIk`)曾被认为可用,但它**不在 R730 上**——~~
+~~R730 的 20 个容器里没有 `agent-lj`。平台记录与实际宿主机不一致。~~
+
+### 身份换算规则(仍然有效)
+
+```
+mxId = "@" + objectId.toLowerCase() + ":fmode.cn"
+```
+
+**不是**用 `agentId` 换算。例:
+
+```
+K0nReVCfIk  →  @k0nrevcfik:fmode.cn   ✅
+agent-lj    →  @agent-lj:fmode.cn     ❌ 错,这个账号即使存在也不是它
+```
+
+同规则在其它容器上已验证一致:
+
+| objectId | agentId | mxId |
+|---|---|---|
+| `K0nReVCfIk` | `agent-lj` | `@k0nrevcfik:fmode.cn` |
+| `zGDCmgNQcd` | `agent-node-lj-test` | `@zgdcmgnqcd:fmode.cn` |
+| `bnQaoXQhE8` | `agent-node` | `@bnqaoxqhe8:fmode.cn` |
+
+### 干扰账号(Matrix 上存在但不要用)
+
+- `@agent-node-lj-test:fmode.cn`(displayname = "lj-test")—— 早期残留,不是真容器
+- `@agent-lj:fmode.cn` —— 若存在,同样是残留
+
+---
+
+## 二、主容器(执行容器开通的运维容器)
+
+| 字段 | 值 |
+|---|---|
+| **objectId** | `bnQaoXQhE8` |
+| **agentId(docker 容器名)** | `agent-node` |
+| **Matrix ID** | `@bnqaoxqhe8:fmode.cn` |
+| **角色** | 接收工单,按技能执行 `docker run` 建容器 |
+| **能力边界** | 自身**没有 docker socket**,只能经 `r730_root.py` SSH 到 R730 执行 |
+| **技能目录** | `/opt/data/skills/` |
+
+---
+
+## 三、测试用户(平台侧通信身份)
+
+| 项 | 值 |
+|---|---|
+| Parse objectId | `cq0IH6Limu` |
+| 账号 | `fmode19900000001` |
+| Matrix ID | `@cq0ih6limu:fmode.cn` |
+| 用途 | 建任务房间、邀请主容器、发工单(**不能用主容器自己建房**,它是 bot,不响应自己发的消息) |
+
+---
+
+## 四、容器开通链路(当前实现)
+
+```
+App 点击开通
+  └─ 云函数 fmode-provisioning(VtW1GT93Ax)
+       ├─ 建 FmodeAgent 记录
+       ├─ 调 RP5Ht55NeX 建 Matrix 身份
+       ├─ 用测试用户身份建**全新房间**(一任务一房间 = 干净 Hermes session)
+       ├─ 邀请主容器进房
+       └─ 发工单(JSON 参数 + 引用 container-provision-job 技能)
+            └─ 主容器按技能执行
+                 ├─ 每阶段 POST 一条 FmodeProvisionStep(写数据库)
+                 └─ 经 r730_root.py SSH 在 R730 执行 docker run
+  └─ 云函数 status 读 FmodeProvisionStep + 三项服务端核验
+       └─ ready 只由「FmodeAgent 记录 + Matrix joined + 心跳新鲜」推导
+```
+
+### 🔴 两条不可动摇的红线
+
+1. **ready 只由服务端事实推导** —— 不信任主容器的自然语言回报。
+   实测它会说"静默/超时",但容器可能已经建成;也会说"成功了",但容器其实是空壳。
+2. **进度靠写库,不靠聊天** —— Agent 在长任务里只会回工具调用回显,
+   让它"在聊天里组织结构化格式"实测 30 分钟一次都没成功;
+   让它"发一次 curl 写库"则稳定成功。
+
+---
+
+## 五、`FmodeProvisionStep` 表(进度上报)
+
+| 字段 | 类型 | 说明 |
+|---|---|---|
+| `jobId` | String | 关联 `FmodeProvisionJob.objectId` |
+| `attempt` | Number | 第几次尝试 |
+| `stage` | String | `prepare`/`copy`/`create`/`configure`/`start`/`verify` |
+| `status` | String | `running`/`ok`/`failed`/`warn` |
+| `step` | String | 人话描述,≤80 字 |
+| `evidence` | String | 关键证据,≤300 字 |
+| `reasonCode` | String | 失败时的稳定枚举 |
+| `elapsedSec` | Number | 本阶段耗时 |
+| `agentId` | String | 执行者容器名 |
+
+写入方式:Agent 直接 `POST /parse/classes/FmodeProvisionStep`(CLP 已允许匿名写)。
+
+**实测效果**(2026-11-26):主容器写入的诊断精确到可行动的程度,例如:
+
+```json
+{
+  "stage": "prepare",
+  "status": "failed",
+  "step": "源容器校验失败: agent-node-lj-test 为空壳(2插件/0脚本/无 media-patch), 容器已 Exited 12 天",
+  "evidence": "plugins=2 scripts=0 media-patch=none container=Exited(0) 12 days ago"
+}
+```
+
+---
+
+## 六、排查常用命令
+
+### 查 R730 上所有容器(经主容器执行)
+
+```bash
+/opt/data/venv-ops/bin/python3 /opt/data/scripts/r730_root.py \
+  "docker ps -a --format '{{.Names}}|{{.ID}}|{{.Status}}'"
+```
+
+### 查某个 agent 的完整身份
+
+```bash
+curl -s -H 'X-Parse-Application-Id: ncloudmaster' \
+     -H 'X-Parse-Master-Key: <masterKey>' \
+     'https://server.fmode.cn/parse/classes/FmodeAgent/K0nReVCfIk'
+```
+
+### 查 Matrix 绑定
+
+```bash
+curl -s -H 'X-Parse-Application-Id: ncloudmaster' \
+     -H 'X-Parse-Master-Key: <masterKey>' \
+     'https://server.fmode.cn/parse/classes/FmodeMatrixBinding?where=%7B%22agentId%22%3A%22agent-lj%22%7D'
+```
+
+---
+
+## 七、相关文档
+
+- `docs/03-interface/容器接入完整指南-v2-20261111.md` —— 容器接入的**技术细节**(心跳契约、✅ reaction 机制等)。
+  ⚠️ 该文档中「参考实现 = `agent-node-lj-test`」的说法**已过时**,以本文件为准。
+- `cloud/skills/container-provision-job/SKILL.md` —— 主容器执行开通的技能规范
+- `docs/00-tracking/操作追踪.md` —— 改动留痕
+
+---
+
+## 八、心跳上报机制(2026-11-27 查明)
+
+### 谁在上报
+
+`plugin-active-reporter`(Hermes 插件,随 gateway 加载):
+
+```yaml
+hooks: [pre_llm_call, post_llm_call]   # 有对话时触发
+description: "turn 开始/结束各报一次 + 1 小时随机偏移心跳"
+```
+
+| 常量 | 值 |
+|---|---|
+| `HEARTBEAT_BASE_SEC` | `3600`(1 小时) |
+| `HEARTBEAT_JITTER_SEC` | `900`(±15 分钟) |
+| `FUNCTION_ID` | `xlosi3m46q` |
+| `API_BASE` | `https://server.fmode.cn/api/functions` |
+
+### 怎么读身份
+
+```python
+def _agent_id() -> str:
+    # 读 /run/s6/container_environment/AGENT_ID → 值是【容器名】
+def _token() -> str:
+    # 读 /run/s6/container_environment/FMODE_SESSION_TOKEN
+```
+
+### 上报时写哪条记录
+
+调 `xlosi3m46q {op:'update', agentId:<容器名>, field, value}`,
+云函数**按 `agentId` 字段匹配 FmodeAgent**;**匹配不到会自动新建一条**。
+
+> 🔴 这就是「一条容器两条记录」的成因:
+> 建记录时若没写 `agentId` 字段,插件会自建一条,
+> 而云函数按 objectId 查到的永远是那条空壳。
+
+**因此:`FmodeAgent.agentId` 必须 = docker 容器名 = `agent-node-app-<objectId 小写>`,
+且必须在该记录 save 之后写入(新建对象时 `agent.id` 是 undefined)。**
+
+### 验证心跳是否正常
+
+```bash
+# 1. 直接触发一次(不必等一小时)
+docker exec <容器> python3 -c "
+import importlib.util
+spec = importlib.util.spec_from_file_location('r','/opt/data/plugins/plugin-active-reporter/__init__.py')
+m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
+print(m._heartbeat_once(0))
+"
+# 期望输出 True
+
+# 2. 查库
+curl -s -H 'X-Parse-Application-Id: ncloudmaster' -H 'X-Parse-Master-Key: <mk>' \
+  'https://server.fmode.cn/parse/classes/FmodeAgent?where=%7B%22agentId%22%3A%22<容器名>%22%7D'
+# 期望:只有 1 条,status 非 offline,heartbeatAt 新鲜
+```
+
+### 状态值含义
+
+| 值 | 含义 | 核验是否通过 |
+|---|---|---|
+| `running` | 正在执行任务 | ✅ |
+| `idle` | 空闲但在线 | ✅ |
+| `offline` | 从未上报 / 上报过期 | ❌ |
+| `error` / `stopped` | 故障态 | ❌ |
+
+> ⚠️ 容器刚建好时首次上报值为 `offline`(进程还没进入正常状态),
+> 发一条消息触发一轮 turn 后会变成 `idle`/`running`。

+ 176 - 0
docs/03-interface/给主容器-建harness-test容器并按lj-test迁移-20261124.md

@@ -0,0 +1,176 @@
+# 给主容器:建 agent-node-app-harness-test 并按 lj-test 迁移(2026-11-24)
+
+> **用途**:复制「二、发送内容」整段发给**主容器**(有宿主 docker 权限的那台,刘雨飏侧)。
+> **背景**:平台侧已全部开好(FmodeAgent 记录 / Matrix 身份 / 房间 / 绑定),
+> 唯一缺的是**容器本身**。本指令 = 建容器 + 从 lj-test 迁移通用配置 + 验收。
+> **编写方**:App 侧(fmode-app)。平台侧各步已实测通过,证据见文末「三、平台侧实测记录」。
+
+---
+
+## 一、已就绪的平台侧事实(主容器不要重复做)
+
+| 项 | 值 |
+|---|---|
+| agentId(= hostname,建容器必须用它) | `agent-node-app-harness-test` |
+| FmodeAgent objectId | `ffqW3yMaoc` |
+| agentMxId | `@ffqw3ymaoc:fmode.cn` |
+| 主人 mxId | `@xhvrjtmwqh:fmode.cn` |
+| DM 房间 roomId | `!AyuezjYab8jNrU4cTe13NS-ChCy-W2Xk0KEjIXsJ9lo` |
+| owner / company | `xhVRjTMwQH` / `E4KpGvTEto`(飞码AI)✅ 已核验无误 |
+| Matrix 密码派生规则 | 已实测:**规则1** `sha256("fmode-agent-mx:" + ffqW3yMaoc)` 前 24 位 |
+| Agent 入房状态 | ✅ 已 join(App 侧模拟登录验证过收发闭环) |
+
+🔴 **主容器不需要**再调 `xlosi3m46q` 建记录、**不需要**再调 provision `RP5Ht55NeX`——都已完成,重复调用会造出第二条绑定。
+
+---
+
+## 二、发送内容(整段复制给主容器)
+
+````markdown
+【任务】建容器 agent-node-app-harness-test,从 agent-node-lj-test 迁移通用配置,接入 Fmode App
+
+平台侧已全部开好(FmodeAgent 记录 / Matrix 身份 / 房间 / 绑定都已存在且核验过),
+你只做【建容器 + 迁移文件 + 写 .env + 启动 + 验收】。
+🔴 不要调任何云函数(xlosi3m46q / RP5Ht55NeX 都已完成,重复调用会造第二条绑定)。
+所有结论必须有回读证据,禁止写「应该成功了」。任一步失败立刻停,贴原始报错。
+
+════════════════════════════
+一、固定参数(后面都要用)
+════════════════════════════
+  容器名/hostname = agent-node-app-harness-test
+  agentMxId       = @ffqw3ymaoc:fmode.cn
+  主人 mxId       = @xhvrjtmwqh:fmode.cn
+  roomId          = !AyuezjYab8jNrU4cTe13NS-ChCy-W2Xk0KEjIXsJ9lo
+  主人 token      = r:dd15e8993d0b382d099d1faff6acd20c
+  Matrix 密码     = sha256("fmode-agent-mx:" + "ffqW3yMaoc") 的前 24 位(已实测可登录)
+  源容器          = agent-node-lj-test(迁移来源,🔴 全程只读,不许改它任何东西)
+
+════════════════════════════
+二、执行步骤
+════════════════════════════
+
+── 第 1 步 · 准备数据目录(先在宿主落文件,再建容器)──
+
+  mkdir -p /opt/fmode-containers/agent-node-app-harness-test/data
+
+  从 lj-test 拷贝【通用层】(docker cp 或 tar 管道均可,目标是新容器的数据目录):
+    /opt/data/plugins/            → 全部 11 个插件目录
+    /opt/data/scripts/            → fmode-*.py / fmode-*.sh(交付 hook、round-marker、
+                                    artifact-drain、media-gc、outbound_media 等)
+    /opt/data/.fmode-media-patch/ → 整个目录(entry.sh + patch_spec.py + README,
+                                    root 属主文件,用 sudo/docker cp 保持权限)
+    /opt/data/patches/            → fmode-gateway-finish-guard.sh、
+                                    fmode-matrix-outbound-s3-apply.sh、
+                                    temp-apply-adapter-patch.py、finish-backup/
+    /opt/data/SOUL.md             → 原样拷贝
+    /opt/data/config.yaml         → 拷贝后按下步修改
+
+  🔴 不要拷这些(lj-test 个人/垃圾):
+    .env、.env.bak-*、auth.json、matrix_threads.json、matrix-identity-archive.json、
+    channel_directory.json、sessions/、state.db*、logs/、work/、memories/、
+    diag-*、apptest-*、base*、bid/、各种 .bak-*
+
+── 第 2 步 · 改 config.yaml(新容器这份)──
+
+  🔴 必须删除 platforms.wecom 整段(含 enabled/extra/home_channel)——
+     那是 lj-test 的企微凭据,两台容器共用一个 botid 会每 ~306 秒互相断连。
+  plugins.enabled 保持 lj-test 原样(含 plugin-fmode、plugin-active-reporter、
+  plugin-deliverable-inject、plugin-gateway-finish-guard、
+  plugin-matrix-cloud-url-fallback、plugin-matrix-outbound-s3、
+  plugin-matrix-process-notice、plugin-tips-cn、plugin-topup-guard)。
+  hooks 四条声明(on_session_end / post_tool_call / transform_llm_output / pre_llm_call)保持原样。
+  model / custom_providers / display / compression 保持原样(平台通用)。
+
+── 第 3 步 · 写新容器的 .env(全新写,不拷 lj-test 的)──
+
+  /opt/fmode-containers/agent-node-app-harness-test/data/.env:
+    MATRIX_HOMESERVER=https://matrix.fmode.cn
+    MATRIX_USER_ID=@ffqw3ymaoc:fmode.cn
+    MATRIX_PASSWORD=<sha256("fmode-agent-mx:"+"ffqW3yMaoc") 前24位>
+    MATRIX_HOME_ROOM=!AyuezjYab8jNrU4cTe13NS-ChCy-W2Xk0KEjIXsJ9lo
+    MATRIX_REACTIONS=true
+    MATRIX_REQUIRE_MENTION=false
+    MATRIX_ALLOWED_USERS=@xhvrjtmwqh:fmode.cn
+    MATRIX_MAX_MEDIA_BYTES=838860800
+    MATRIX_E2EE_MODE=off
+    AGENT_ID=agent-node-app-harness-test
+    FMODE_SESSION_TOKEN=r:dd15e8993d0b382d099d1faff6acd20c
+    AGENT_FUNCTION_ID=xlosi3m46q
+  chmod 600 .env
+  🔴 不设 MATRIX_IGNORE_USER_PATTERNS(会把主人消息静默丢弃)。
+
+── 第 4 步 · 建容器 ──
+
+  镜像与 lj-test 一致(先 docker inspect agent-node-lj-test 取 .Config.Image 与必要 env)。
+  docker run 必须带:
+    --name agent-node-app-harness-test
+    --hostname agent-node-app-harness-test   ← 不加会变随机 hostname,agentId 对不上
+    --restart unless-stopped
+    --memory 4g --cpus 2 --pids-limit 512
+    -v /opt/fmode-containers/agent-node-app-harness-test/data:/opt/data
+    --entrypoint /opt/data/.fmode-media-patch/entry.sh
+       ← 关键:这是 Matrix 入站 https 附件补丁的持久化载体(lj-test 同款)。
+         entrypoint 内部幂等打完补丁后 exec 原 entrypoint-dispatch。
+  建完确认 gateway 在跑(docker exec … pgrep -f "gateway run")。
+
+── 第 5 步 · cron 两个 job ──
+
+  容器起来后,把 lj-test 的两个启用中 job 配进新容器(/opt/data/cron/jobs.json,
+  job_id 重新生成、origin 改成新容器自己的房间/去掉均可):
+    ① fmode-artifact-drain:*/3 * * * *,no_agent,脚本 fmode-artifact-drain.sh
+    ② media-gc-delayed-cleanup:every 30m,no_agent,脚本 fmode-media-gc-wrapper.sh
+
+── 第 6 步 · DNS 体检(SOP 第 0 步,每个新容器必做)──
+
+  docker exec agent-node-app-harness-test python3 -c \
+    "import socket,time;t=time.time();socket.getaddrinfo('api.fmode.cn',443,socket.AF_UNSPEC);print('%.0f ms'%((time.time()-t)*1000))"
+  > 1000ms 说明有 DNS 卡顿(每轮慢 5 秒),按 lj-test 同款修法:
+  gateway 的 s6 run 脚本加 export RES_OPTIONS=single-request,然后重启 gateway。
+
+════════════════════════════
+三、验收(逐项贴原始输出)
+════════════════════════════
+  1. gateway_state.json:platforms.matrix.state == "connected"
+  2. 容器内回读 .env 生效值(不用 /proc/environ,那是假阴性):
+     MATRIX_USER_ID / MATRIX_HOME_ROOM / MATRIX_ALLOWED_USERS / REQUIRE_MENTION
+  3. Matrix 自检(容器内执行):
+     用 MATRIX_PASSWORD 登录 → whoami 必须输出 @ffqw3ymaoc:fmode.cn
+     joined_rooms 必须含 roomId
+  4. 在房间里发一条「容器上线自检」,回读 /messages 确认落库
+  5. 插件生效证据:/opt/data/logs/ 里 plugin-active-reporter 有上报日志
+     (turn 事件驱动 + 1h 心跳,不需要再装 status-report.py)
+
+汇报格式:
+  CREATE-DONE
+  容器名 / 镜像 / gateway 状态 / matrix 状态
+  .env 回读 4 项 / whoami / joined_rooms / 自检消息回读
+  DNS 耗时 / 遇到的问题(没有写「无」)
+
+纪律:
+  · lj-test 全程只读
+  · 不调云函数
+  · 不打印密码/token 全文(前 8 位即可)
+  · 失败贴原始报错,不伪造成功
+````
+
+---
+
+## 三、平台侧实测记录(2026-11-24,App 侧执行)
+
+测试目标:验证「在我们服务器上开通容器」的全链路中,**除 docker 建容器外**的每一步都可走通。
+
+| 步骤 | 结果 | 证据 |
+|---|---|---|
+| ① `xlosi3m46q` op:update 自动建 FmodeAgent 记录 | ✅ | `objectId=ffqW3yMaoc`,owner=`xhVRjTMwQH`,company=`E4KpGvTEto`(归属正确) |
+| ② provision(RP5Ht55NeX)建 Matrix 身份+房间+绑定 | ✅ | `agentMxId=@ffqw3ymaoc:fmode.cn`、`roomId=!Ayuez…J9lo`、`bindingId=jMkLWft8T3`(新建,仅 1 条) |
+| ③ 派生密码登录(模拟容器 gateway 上线) | ✅ | **规则1(原始 objectId)** 登录成功,device_id=`eYLtdJSazx` |
+| ④ whoami 身份核验 | ✅ | `@ffqw3ymaoc:fmode.cn` |
+| ⑤ Agent 入房 | ✅ | provision 只邀请不入房(再次复现),手动 join 成功 |
+| ⑥ 收发闭环 | ✅ | 发「harness-test 平台侧开通自检」→ `/messages` 回读到原文 |
+
+**结论**:开通链路唯一需要主容器/平台侧的环节 = `docker run` 本身(本机无建容器能力,
+5 个候选云函数均 `Object not found`,2026-11-03 已探明)。其余全部可脚本化,
+`bind-container.mjs bind` 一条命令完成 ①②。
+
+**遗留**:容器实体创建后,`bind-container.mjs status agent-node-app-harness-test`
+应从「❌ App 可见性 / ❌ 容器侧上报」转为全绿(容器上报心跳后)。

+ 633 - 0
docs/03-interface/自动开通回报-agent-node-app-test-0001-202611240327.md

@@ -0,0 +1,633 @@
+# 自动化开通回报:agent-node-app-test-0001
+
+- 时间:2026-11-24T03:27:15.272Z
+- 房间:`!H-43T66J3qzovUV_hdjfZF44bNf3D1bJMVc0f53Y8sc`
+- 发起账号:@cq0ih6limu:fmode.cn(测试账号,无企业)
+- 结束原因:静默/超时
+
+## 发出的指令
+
+```text
+【任务】建容器 agent-node-app-test-0001,从 agent-node-lj-test 迁移通用配置,接入 Fmode App
+
+这是一次 fmode-app 项目的自动化开通测试(发起方:@cq0ih6limu:fmode.cn,测试账号,无企业)。
+平台侧已全部开好(FmodeAgent 记录 / Matrix 身份 / 房间 / 绑定),你只做
+【建容器 + 迁移文件 + 写 .env + 启动 + 验收】。请经你的 r730_root.py SSH 通道在 R730 上执行。
+🔴 不要调任何云函数(xlosi3m46q / RP5Ht55NeX 都已完成,重复调用会造第二条绑定)。
+所有结论必须有回读证据,禁止写「应该成功了」。任一步失败立刻停,贴原始报错。
+只做本指令列出的动作,不做任何其他改动。
+
+════════════════════════════
+一、固定参数(后面都要用)
+════════════════════════════
+  容器名/hostname = agent-node-app-test-0001
+  agentMxId       = @k0jxgrmdhe:fmode.cn
+  主人 mxId       = @cq0ih6limu:fmode.cn
+  roomId          = !hLVCNPgJhfaMTajfcgggbnlgCoXKLUWWwOKjPZzkos0
+  主人 token      = r:e1f8f9224c520a2841fd656fd9909cf7
+  Matrix 密码     = sha256("fmode-agent-mx:" + "K0jXgRmdHe") 的前 24 位(provision 新建账号的派生规则,已实测)
+  显示名          = 测试分身0001
+  源容器          = agent-node-lj-test(迁移来源,🔴 全程只读,不许改它任何东西)
+
+════════════════════════════
+二、执行步骤
+════════════════════════════
+
+── 第 1 步 · 准备数据目录(先在宿主落文件,再建容器)──
+
+  mkdir -p /opt/fmode-containers/agent-node-app-test-0001/data
+
+  从 lj-test 拷贝【通用层】(docker cp 或 tar 管道均可):
+    /opt/data/plugins/            → 全部 11 个插件目录
+    /opt/data/scripts/            → fmode-*.py / fmode-*.sh
+    /opt/data/.fmode-media-patch/ → 整个目录(root 属主,用 sudo/docker cp 保持权限)
+    /opt/data/patches/            → fmode-gateway-finish-guard.sh、
+                                    fmode-matrix-outbound-s3-apply.sh、
+                                    temp-apply-adapter-patch.py、finish-backup/
+    /opt/data/SOUL.md             → 原样拷贝
+    /opt/data/config.yaml         → 拷贝后按下步修改
+
+  🔴 不要拷这些(lj-test 个人/垃圾):
+    .env、.env.bak-*、auth.json、matrix_threads.json、matrix-identity-archive.json、
+    channel_directory.json、sessions/、state.db*、logs/、work/、memories/、
+    diag-*、apptest-*、base*、bid/、各种 .bak-*
+
+── 第 2 步 · 改 config.yaml(新容器这份)──
+
+  🔴 必须删除 platforms.wecom 整段 —— 那是 lj-test 的企微凭据,
+     两台容器共用一个 botid 会每 ~306 秒互相断连。
+  plugins.enabled / hooks 四条声明 / model / custom_providers 保持 lj-test 原样。
+
+── 第 3 步 · 写新容器的 .env(全新写,不拷 lj-test 的)──
+
+  /opt/fmode-containers/agent-node-app-test-0001/data/.env:
+    MATRIX_HOMESERVER=https://matrix.fmode.cn
+    MATRIX_USER_ID=@k0jxgrmdhe:fmode.cn
+    MATRIX_PASSWORD=<sha256("fmode-agent-mx:"+"K0jXgRmdHe") 前24位>
+    MATRIX_HOME_ROOM=!hLVCNPgJhfaMTajfcgggbnlgCoXKLUWWwOKjPZzkos0
+    MATRIX_REACTIONS=true
+    MATRIX_REQUIRE_MENTION=false
+    MATRIX_ALLOWED_USERS=@cq0ih6limu:fmode.cn
+    MATRIX_MAX_MEDIA_BYTES=838860800
+    MATRIX_E2EE_MODE=off
+    AGENT_ID=agent-node-app-test-0001
+    FMODE_SESSION_TOKEN=r:e1f8f9224c520a2841fd656fd9909cf7
+    AGENT_FUNCTION_ID=xlosi3m46q
+  chmod 600 .env
+  🔴 不设 MATRIX_IGNORE_USER_PATTERNS(会把主人消息静默丢弃)。
+
+── 第 4 步 · 建容器 ──
+
+  镜像与 lj-test 一致(先 docker inspect agent-node-lj-test 取 .Config.Image)。
+  docker run 必须带:
+    --name agent-node-app-test-0001
+    --hostname agent-node-app-test-0001   ← 不加会变随机 hostname,agentId 对不上
+    --restart unless-stopped
+    --env-file <上面的 env 关键项>(TZ=Asia/Shanghai 必带;env 只在创建时注入一次)
+    --memory 4g --cpus 2 --pids-limit 512
+    -v /opt/fmode-containers/agent-node-app-test-0001/data:/opt/data
+    --entrypoint /opt/data/.fmode-media-patch/entry.sh
+       ← Matrix 入站 https 附件补丁的持久化载体(lj-test 同款)。
+  建完确认 gateway 在跑(docker exec … pgrep -f "gateway run")。
+
+── 第 5 步 · cron 两个 job ──
+
+  容器起来后把 lj-test 的两个启用中 job 配进新容器(/opt/data/cron/jobs.json,
+  job_id 重新生成):
+    ① fmode-artifact-drain:*/3 * * * *,no_agent,脚本 fmode-artifact-drain.sh
+    ② media-gc-delayed-cleanup:every 30m,no_agent,脚本 fmode-media-gc-wrapper.sh
+
+── 第 6 步 · DNS 体检(每个新容器必做)──
+
+  docker exec agent-node-app-test-0001 python3 -c \
+    "import socket,time;t=time.time();socket.getaddrinfo('api.fmode.cn',443,socket.AF_UNSPEC);print('%.0f ms'%((time.time()-t)*1000))"
+  > 1000ms 按 lj-test 同款修法:gateway 的 s6 run 脚本加
+  export RES_OPTIONS=single-request,然后重启 gateway。
+
+════════════════════════════
+三、验收(逐项贴原始输出)
+════════════════════════════
+  1. gateway_state.json:platforms.matrix.state == "connected"
+  2. 容器内回读 .env 生效值 4 项:MATRIX_USER_ID / MATRIX_HOME_ROOM /
+     MATRIX_ALLOWED_USERS / MATRIX_REQUIRE_MENTION
+  3. Matrix 自检(容器内执行):
+     用 MATRIX_PASSWORD 登录 → whoami 必须输出 @k0jxgrmdhe:fmode.cn
+     joined_rooms 必须含 !hLVCNPgJhfaMTajfcgggbnlgCoXKLUWWwOKjPZzkos0
+     (provision 只邀请不入房,不在就 curl -X POST …/join/!hLVCNPgJhfaMTajfcgggbnlgCoXKLUWWwOKjPZzkos0)
+  4. 在房间里发一条「容器上线自检」,回读 /messages 确认落库
+  5. 插件生效证据:/opt/data/logs/ 里 plugin-active-reporter 有上报日志
+
+汇报格式:
+  CREATE-DONE
+  容器名 / 镜像 / gateway 状态 / matrix 状态
+  .env 回读 4 项 / whoami / joined_rooms / 自检消息回读
+  DNS 耗时 / 遇到的问题(没有写「无」)
+
+纪律:
+  · lj-test 全程只读
+  · 不调云函数
+  · 不打印密码/token 全文(前 8 位即可)
+  · 失败贴原始报错,不伪造成功
+```
+
+## 主容器回报(原文,按时间顺序)
+
+### 1【prose】
+
+```text
+我先加载相关的技能,并检查环境情况。
+```
+
+### 2【prose】
+
+```text
+📚 Reading skill skill-lifecycle
+```
+
+### 3【prose】
+
+```text
+技能已经加载。现在我通过 r730_root.py 检查 R730 上的源容器。
+```
+
+### 4【prose】
+
+```text
+```
+cd /opt/data && /opt/data/venv-ops/bi...
+```
+```
+
+### 5【prose】
+
+```text
+SSH 协议 banner 读取失败,重试一次(这类错误通常是瞬时的)。
+```
+
+### 6【prose】
+
+```text
+* ```
+cd /opt/data && /opt/data/venv-ops/bi...
+```
+```
+cd /opt/data && sleep 5 && /opt/data/...
+```
+```
+
+### 7【prose】
+
+```text
+SSH 通道打不开。我先诊断一下连通性,看看是不是 frps 这一层出了问题。
+```
+
+### 8【prose】
+
+```text
+```
+cd /opt/data && (timeout 12 bash -c '...
+```
+```
+
+### 9【prose】
+
+```text
+端口是通的,但 frps 一读到 banner 就断开了。这说明 R730 上的 frpc 隧道掉线了。我先确认一下,同时找找有没有别的通道。
+```
+
+### 10【prose】
+
+```text
+```
+cd /opt/data && for i in 1 2 3; do ec...
+```
+```
+
+### 11【prose】
+
+```text
+第三次连上了。这是 SSH 间歇性拒绝连接的问题,重试就能进。我现在开始采集源容器的信息。
+```
+
+### 12【prose】
+
+```text
+```
+cd /opt/data && /opt/data/venv-ops/bi...
+```
+```
+
+### 13【prose】
+
+```text
+lj-test 容器已经停了 10 天,于是改用宿主目录直接读。先看看它的数据目录结构。
+```
+
+### 14【prose】
+
+```text
+```
+cd /opt/data && /opt/data/venv-ops/bi...
+```
+```
+
+### 15【prose】
+
+```text
+lj-test 的实际状态和任务书描述不符:plugins 只有 2 个(并非 11 个)、scripts/fmode-* 是空的、patches 和 .fmode-media-patch 目录都不存在、cron/jobs.json 的内容只有 68 字节。我先把真实情况查清楚,再作决定。
+```
+
+### 16【prose】
+
+```text
+```
+cd /opt/data && /opt/data/venv-ops/bi...
+```
+```
+
+### 17【prose】
+
+```text
+还在推进,3 分钟了,再给我一点时间。 — iteration 10/150, waiting for provider response (streaming)
+```
+
+### 18【prose】
+
+```text
+SSH 频繁断连。我写个带重试的封装脚本,避免每次都手工重试。
+```
+
+### 19【prose】
+
+```text
+lj-test 的实际状态和任务书描述差得很远。我先看它真实的 config.yaml 和主容器 agent-node 的插件情况,判断哪些是真正“通用层”的内容。
+```
+
+### 20【prose】
+
+```text
+关键发现:任务书描述的“通用层”在 lj-test 上几乎不存在。我再确认一遍:patches 和 .fmode-media-patch 是不是曾经存在过、现在已经被清理掉了,同时查一下 lj-test 容器内还有没有残留。
+```
+
+### 21【prose】
+
+```text
+```
+cd /opt/data && /opt/data/venv-ops/bi...
+```
+```
+
+### 22【prose】
+
+```text
+找到真正的来源了:这些“通用层”文件全都在 `agent-node-u19170119836` 上,并不在 agent-node-lj-test 上。我去核实一下那个容器是不是更符合任务书描述的模板源。
+```
+
+### 23【prose】
+
+```text
+```
+cd /opt/data && /opt/data/venv-ops/bi...
+```
+```
+
+### 24【prose】
+
+```text
+* 还在处理,6 分钟了,稍安勿躁。 — iteration 14/150, terminal
+```
+
+### 25【prose】
+
+```text
+**我先停下来核实一下**:任务书指定要用 `agent-node-lj-test` 作为迁移源,但这份任务书实际描述的 11 个插件、patches 目录、.fmode-media-patch、两个 cron job,全都属于**另一个活跃容器 `agent-node-u19170119836`**。
+
+`agent-node-lj-test` 的真实状态:
+- plugins 只有 **2 个**(plugin-tips-cn、plugin-topup-guard)
+- **没有** `scripts/` 目录
+- **没有** `patches/`,**没有** `.fmode-media-patch/`
+- cron/jobs.json 里是 `"jobs": []`(空)
+- 容器 Exited (0) **10 天前**
+
+而任务书写的每一条通用层描述,逐项都精确命中了 `agent-node-u19170119836`:11 个 plugin,其中正是 `plugin-active-reporter` 这个验收第 5 项要求的插件;还有全部 4 个 patches 文件以及 finish-backup/,以及那两个 cron job 的 job_id。
+
+按任务书走的话,第 1 步会拷出空的 scripts、patches、media-patch 这三个目录,第 4 步 `--entrypoint /opt/data/.fmode-media-patch/entry.sh` 会因为该文件不存在而**直接起不来容器**,第 5 步的两个 cron 脚本源也不存在。
+```
+
+### 26【prose】
+
+```text
+❓ 任务书写的迁移源 agent-node-lj-test 上没有任务书描述的通用层(11插件/patches/.fmode-media-patch/两个cron job 全部缺失,它在10天前已停止);这些内容全部存在于活跃容器 agent-node-u19170119836 上。用哪个作迁移源?
+
+  1. 是写错了:改用 agent-node-u19170119836 作迁移源 (Recommended)
+  2. 就用 agent-node-lj-test,缺的东西跳过(容器可能起不来)
+  3. 先停,我去核实再告诉你
+
+Reply with the number, the option text, or your own answer.
+```
+
+### 27【prose】
+
+```text
+* 手上活还剩一点,9 分钟了。 — iteration 15/150, clarify
+```
+
+### 28【prose】
+
+```text
+* 12 分钟了,进展稳定,继续等。 — iteration 15/150, clarify
+```
+
+### 29【prose】
+
+```text
+* 进展中,15 分钟了,快了。 — iteration 15/150, clarify
+```
+
+### 30【prose】
+
+```text
+授权已确认。现在开始执行,第一步是建数据目录,并拷贝通用层。
+```
+
+### 31【prose】
+
+```text
+```
+cd /opt/data && /opt/data/venv-ops/bi...
+```
+```
+
+### 32【prose】
+
+```text
+文件拷贝完成。第 2 步:修改 config.yaml,删掉 `platforms.wecom` 整段。我先看源 config 的真实内容。
+```
+
+### 33【prose】
+
+```text
+```
+cd /opt/data && /opt/data/venv-ops/bi...
+```
+```
+
+### 34【prose】
+
+```text
+```
+cd /opt/data && /opt/data/venv-ops/bi...
+```
+```
+
+### 35【prose】
+
+```text
+源 config 结构清晰。第 113 到 126 行是 `platforms.wecom` 整段,我要把它删掉,同时要移除 `plugins.enabled` 里的 `wecom-platform`,因为该平台段已删,插件留着会加载失败。
+```
+
+### 36【prose】
+
+```text
+* 还在处理,18 分钟了,稍安勿躁。 — iteration 18/150, terminal
+```
+
+### 37【prose】
+
+```text
+R730 上没有 venv-ops,改用系统 python3。
+```
+
+### 38【prose】
+
+```text
+```
+cd /opt/data && /opt/data/venv-ops/bi...
+```
+```
+
+### 39【prose】
+
+```text
+`platforms.wecom` 已经清除干净。用 YAML 解析器校验 plugins 段落,确认 wecom-platform 已经移除。
+```
+
+### 40【prose】
+
+```text
+```
+cd /opt/data && /opt/data/venv-ops/bi...
+```
+```
+
+### 41【prose】
+
+```text
+```
+cd /opt/data && /opt/data/venv-ops/bi...
+```
+```
+
+### 42【prose】
+
+```text
+config.yaml 校验通过:platforms 里只剩 `matrix`,9 个插件、4 条 hook 声明、模型和自定义 provider 都保留了下来。现在开始第 3 步,写 .env,先算出 Matrix 密码。
+```
+
+### 43【prose】
+
+```text
+* ```
+cd /opt/data && /opt/data/venv-ops/bi...
+```
+```
+cd /opt/data && python3 -c " ...
+```
+```
+
+### 44【prose】
+
+```text
+```
+cd /opt/data && /opt/data/venv-ops/bi...
+```
+```
+
+### 45【prose】
+
+```text
+* 还在跑,21 分钟了——值得等。 — iteration 23/150, terminal
+```
+
+### 46【prose】
+
+```text
+.env 已经写好,权限 600,属主 10000(就是 UNKNOWN)。第 4 步:建容器。先确认镜像和 entry.sh 是否可执行。
+```
+
+### 47【prose】
+
+```text
+* ```
+cd /opt/data && /opt/data/venv-ops/bi...
+``` (×2)
+```
+
+### 48【prose】
+
+```text
+源容器的完整 Run 参数拿到了。我注意到 `WECOM_*` 这一组环境变量必须**排除**,否则会和源容器争抢同一个 bot。先看一下 entry.sh 做了什么,确认它能正确衔接启动流程。
+```
+
+### 49【prose】
+
+```text
+这是本容器的路径,不是 R730 上的路径。我用 SSH 在 R730 上读一下。
+```
+
+### 50【prose】
+
+```text
+entry.sh 是幂等的,最后会 exec 回镜像原有的入口。现在开始建容器。
+```
+
+### 51【prose】
+
+```text
+```
+cd /opt/data && /opt/data/venv-ops/bi...
+```
+```
+
+### 52【prose】
+
+```text
+容器起来了。等 gateway 初始化,然后检查进程。
+```
+
+### 53【prose】
+
+```text
+```
+cd /opt/data && /opt/data/venv-ops/bi...
+```
+```
+
+### 54【prose】
+
+```text
+* 还在处理,24 分钟了,稍安勿躁。 — iteration 29/150, waiting for provider response (streaming)
+```
+
+### 55【prose】
+
+```text
+gateway 正在运行,进程号是 143。Dashboard 绑定 0.0.0.0 时需要鉴权,这是次要告警,不影响 Matrix。现在查核心的 gateway_state.json。
+```
+
+### 56【prose】
+
+```text
+```
+cd /opt/data && /opt/data/venv-ops/bi...
+```
+```
+
+### 57【prose】
+
+```text
+验收项 1 通过:`platforms.matrix.state == "connected"`,api_server 也同样是 connected。第 5 步:配置两个 cron job。
+```
+
+### 58【prose】
+
+```text
+```
+cd /opt/data && /opt/data/venv-ops/bi...
+```
+```
+
+### 59【prose】
+
+```text
+脚本都在,也有执行权限。用容器内的 `hermes cron` CLI 建这两个 job,这样能保证格式被官方解析器认可。
+```
+
+### 60【prose】
+
+```text
+```
+cd /opt/data && /opt/data/venv-ops/bi...
+```
+```
+
+### 61【prose】
+
+```text
+用 `hermes cron create --no-agent --script` 建这两个 job。
+```
+
+### 62【prose】
+
+```text
+```
+cd /opt/data && /opt/data/venv-ops/bi...
+```
+```
+
+### 63【prose】
+
+```text
+⚠️ 我要暂时下线——手上的活会停住。回来后你招呼一声,我从这儿继续。
+```
+
+### 64【prose】
+
+```text
+两个 job 已经创建完成,job_id 是新生成的,分别是 566899bdb75a 和 f5e6184061fc。回读确认后执行第 6 步 DNS 体检。
+```
+
+### 65【prose】
+
+```text
+```
+cd /opt/data && /opt/data/venv-ops/bi...
+```
+```
+
+### 66【prose】
+
+```text
+会话已恢复。上一轮我通过 R730 执行一次 cron 状态查询时被网关中断,**没有重新执行任何命令**,原样向你汇报现状。
+
+已经确认完成的进度(截至中断前):
+
+**已完成的内容**
+- 数据目录已建好,通用层已从 `agent-node-u19170119836` 拷贝完成:11 个插件、8 个 fmode 脚本、patches(含 finish-backup)、.fmode-media-patch(root 属主保留)、SOUL.md
+- config.yaml 已改动:`platforms.wecom` 整段删除,已用 YAML 解析校验通过(platforms 只剩 `matrix`,9 个插件、4 条 hook、model、custom_providers 都保留)
+- .env 全新写入,权限 600,归属 10000,12 项齐全,无 `MATRIX_IGNORE_USER_PATTERNS`
+- 容器 `agent-node-app-test-0001` 已建成并运行,镜像 `fmode/agent-node:0.21.3`,hostname 正确,4g、2cpu、512pids,entry.sh 入口
+- gateway 进程在跑(PID 143),`gateway_state.json` 回读:**matrix=connected**、api_server=connected
+- 两个 cron job 已用官方 CLI 建好:`566899bdb75a` 对应 fmode-artifact-drain(*/3)、`f5e6184061fc` 对应 media-gc-delayed-cleanup(every 30m),均为 no_agent
+
+**中断时正在进行、尚未完成的部分**
+- cron list 与 jobs.json 的回读确认
+- 第 6 步 DNS 体检(1049 项未测)
+- 验收第 2 项 .env 在容器内回读 4 项
+- 验收第 3 项 Matrix 登录、whoami、joined_rooms
+- 验收第 4 项房间自检消息发送与回读
+- 验收第 5 项 plugin-active-reporter 上报日志
+
+要我继续把剩下这几项验收收尾吗?容器在正常运行,没有半途损坏,只是验收证据还没采集完。
+```
+
+---
+
+## 工具过程(仅供核对)
+
+- `💻 terminal ``` ls /opt/data/scripts/r730_root.py && ... ``` ``` head -60 /opt/data/scripts/r730_root.py ````
+- `✍️ Writing /opt/data/tmp/r730_retry.py`
+- `💻 terminal ``` cd /opt/data && /opt/data/venv-ops/bi... ````
+- `* 💻 terminal ``` cd /opt/data && /opt/data/venv-ops/bi... ``` ``` cd /opt/data && /opt/data/venv-ops/bi... ````
+- `📖 Reading entry.sh`
+- `💻 terminal ``` cd /opt/data && /opt/data/venv-ops/bi... ````

+ 586 - 0
docs/03-interface/自动开通回报-agent-node-app-test-1125-202611250651.md

@@ -0,0 +1,586 @@
+# 自动化开通回报:agent-node-app-test-1125
+
+- 时间:2026-11-25T06:51:50.248Z
+- 房间:`!44Abw7FtF0ec0DYC8sEvACk5TOuOLxcAlm2MfAJMZ7w`
+- 发起账号:@cq0ih6limu:fmode.cn(测试账号,无企业)
+- 结束原因:静默/超时
+
+## 发出的指令
+
+```text
+【任务】建容器 agent-node-app-test-1125,从 agent-node-lj-test 迁移通用配置,接入 Fmode App
+
+这是一次 fmode-app 项目的自动化开通测试(发起方:@cq0ih6limu:fmode.cn,测试账号,无企业)。
+平台侧已全部开好(FmodeAgent 记录 / Matrix 身份 / 房间 / 绑定),你只做
+【建容器 + 迁移文件 + 写 .env + 启动 + 验收】。请经你的 r730_root.py SSH 通道在 R730 上执行。
+🔴 不要调任何云函数(xlosi3m46q / RP5Ht55NeX 都已完成,重复调用会造第二条绑定)。
+所有结论必须有回读证据,禁止写「应该成功了」。任一步失败立刻停,贴原始报错。
+只做本指令列出的动作,不做任何其他改动。
+
+════════════════════════════
+一、固定参数(后面都要用)
+════════════════════════════
+  容器名/hostname = agent-node-app-test-1125
+  agentMxId       = @ondyhuhqv2:fmode.cn
+  主人 mxId       = @cq0ih6limu:fmode.cn
+  roomId          = !jgCed46TbY-NAn5EVt2LBRLwHOvKl6xqE5KpJyctqQI
+  主人 token      = r:e1f8f9224c520a2841fd656fd9909cf7
+  Matrix 密码     = sha256("fmode-agent-mx:" + "ondyhUHqv2") 的前 24 位(provision 新建账号的派生规则,已实测)
+  显示名          = 测试分身1125
+  源容器          = agent-node-lj-test(迁移来源,🔴 全程只读,不许改它任何东西)
+
+════════════════════════════
+二、执行步骤
+════════════════════════════
+
+── 第 1 步 · 准备数据目录(先在宿主落文件,再建容器)──
+
+  mkdir -p /opt/fmode-containers/agent-node-app-test-1125/data
+
+  从 lj-test 拷贝【通用层】(docker cp 或 tar 管道均可):
+    /opt/data/plugins/            → 全部 11 个插件目录
+    /opt/data/scripts/            → fmode-*.py / fmode-*.sh
+    /opt/data/.fmode-media-patch/ → 整个目录(root 属主,用 sudo/docker cp 保持权限)
+    /opt/data/patches/            → fmode-gateway-finish-guard.sh、
+                                    fmode-matrix-outbound-s3-apply.sh、
+                                    temp-apply-adapter-patch.py、finish-backup/
+    /opt/data/SOUL.md             → 原样拷贝
+    /opt/data/config.yaml         → 拷贝后按下步修改
+
+  🔴 不要拷这些(lj-test 个人/垃圾):
+    .env、.env.bak-*、auth.json、matrix_threads.json、matrix-identity-archive.json、
+    channel_directory.json、sessions/、state.db*、logs/、work/、memories/、
+    diag-*、apptest-*、base*、bid/、各种 .bak-*
+
+── 第 2 步 · 改 config.yaml(新容器这份)──
+
+  🔴 必须删除 platforms.wecom 整段 —— 那是 lj-test 的企微凭据,
+     两台容器共用一个 botid 会每 ~306 秒互相断连。
+  plugins.enabled / hooks 四条声明 / model / custom_providers 保持 lj-test 原样。
+
+── 第 3 步 · 写新容器的 .env(全新写,不拷 lj-test 的)──
+
+  /opt/fmode-containers/agent-node-app-test-1125/data/.env:
+    MATRIX_HOMESERVER=https://matrix.fmode.cn
+    MATRIX_USER_ID=@ondyhuhqv2:fmode.cn
+    MATRIX_PASSWORD=<sha256("fmode-agent-mx:"+"ondyhUHqv2") 前24位>
+    MATRIX_HOME_ROOM=!jgCed46TbY-NAn5EVt2LBRLwHOvKl6xqE5KpJyctqQI
+    MATRIX_REACTIONS=true
+    MATRIX_REQUIRE_MENTION=false
+    MATRIX_ALLOWED_USERS=@cq0ih6limu:fmode.cn
+    MATRIX_MAX_MEDIA_BYTES=838860800
+    MATRIX_E2EE_MODE=off
+    AGENT_ID=agent-node-app-test-1125
+    FMODE_SESSION_TOKEN=r:e1f8f9224c520a2841fd656fd9909cf7
+    AGENT_FUNCTION_ID=xlosi3m46q
+  chmod 600 .env
+  🔴 不设 MATRIX_IGNORE_USER_PATTERNS(会把主人消息静默丢弃)。
+
+── 第 4 步 · 建容器 ──
+
+  镜像与 lj-test 一致(先 docker inspect agent-node-lj-test 取 .Config.Image)。
+  docker run 必须带:
+    --name agent-node-app-test-1125
+    --hostname agent-node-app-test-1125   ← 不加会变随机 hostname,agentId 对不上
+    --restart unless-stopped
+    --env-file <上面的 env 关键项>(TZ=Asia/Shanghai 必带;env 只在创建时注入一次)
+    --memory 4g --cpus 2 --pids-limit 512
+    -v /opt/fmode-containers/agent-node-app-test-1125/data:/opt/data
+    --entrypoint /opt/data/.fmode-media-patch/entry.sh
+       ← Matrix 入站 https 附件补丁的持久化载体(lj-test 同款)。
+  建完确认 gateway 在跑(docker exec … pgrep -f "gateway run")。
+
+── 第 5 步 · cron 两个 job ──
+
+  容器起来后把 lj-test 的两个启用中 job 配进新容器(/opt/data/cron/jobs.json,
+  job_id 重新生成):
+    ① fmode-artifact-drain:*/3 * * * *,no_agent,脚本 fmode-artifact-drain.sh
+    ② media-gc-delayed-cleanup:every 30m,no_agent,脚本 fmode-media-gc-wrapper.sh
+
+── 第 6 步 · DNS 体检(每个新容器必做)──
+
+  docker exec agent-node-app-test-1125 python3 -c \
+    "import socket,time;t=time.time();socket.getaddrinfo('api.fmode.cn',443,socket.AF_UNSPEC);print('%.0f ms'%((time.time()-t)*1000))"
+  > 1000ms 按 lj-test 同款修法:gateway 的 s6 run 脚本加
+  export RES_OPTIONS=single-request,然后重启 gateway。
+
+════════════════════════════
+三、验收(逐项贴原始输出)
+════════════════════════════
+  1. gateway_state.json:platforms.matrix.state == "connected"
+  2. 容器内回读 .env 生效值 4 项:MATRIX_USER_ID / MATRIX_HOME_ROOM /
+     MATRIX_ALLOWED_USERS / MATRIX_REQUIRE_MENTION
+  3. Matrix 自检(容器内执行):
+     用 MATRIX_PASSWORD 登录 → whoami 必须输出 @ondyhuhqv2:fmode.cn
+     joined_rooms 必须含 !jgCed46TbY-NAn5EVt2LBRLwHOvKl6xqE5KpJyctqQI
+     (provision 只邀请不入房,不在就 curl -X POST …/join/!jgCed46TbY-NAn5EVt2LBRLwHOvKl6xqE5KpJyctqQI)
+  4. 在房间里发一条「容器上线自检」,回读 /messages 确认落库
+  5. 插件生效证据:/opt/data/logs/ 里 plugin-active-reporter 有上报日志
+
+汇报格式:
+  CREATE-DONE
+  容器名 / 镜像 / gateway 状态 / matrix 状态
+  .env 回读 4 项 / whoami / joined_rooms / 自检消息回读
+  DNS 耗时 / 遇到的问题(没有写「无」)
+
+纪律:
+  · lj-test 全程只读
+  · 不调云函数
+  · 不打印密码/token 全文(前 8 位即可)
+  · 失败贴原始报错,不伪造成功
+```
+
+## 主容器回报(原文,按时间顺序)
+
+### 1【prose】
+
+```text
+我先检查环境,并读取现有源容器。
+```
+
+### 2【prose】
+
+```text
+本地是 agent-node 容器,需要经 r730_root.py 在 R730 宿主机上执行。先做第 1 步的源容器体检(只读)。
+```
+
+### 3【prose】
+
+```text
+📚 Reading skill container-provision-from-source
+🐍 Running code import sys, time sys.path.insert(0, "...
+```
+
+### 4【prose】
+
+```text
+源容器 agent-node-lj-test 已退出(Exited 11 天)。先查源数据是否健在(坑 #1)。
+```
+
+### 5【prose】
+
+```text
+源容器是空壳:只有 2 个插件,没有 scripts、没有 media-patch、也没有 patches。按照技能做法,先查找真正内容齐全的容器。
+```
+
+### 6【prose】
+
+```text
+```
+cd /opt/data && /opt/data/venv-ops/bi...
+```
+```
+
+### 7【prose】
+
+```text
+```
+cd /opt/data && /opt/data/venv-ops/bi...
+```
+```
+
+### 8【prose】
+
+```text
+有两个内容齐全的源容器:agent-node-u19170119836(有 11 个插件、13 个脚本)和 agent-node-app-test-0001。查它们的运行状态和 config.yaml 里是否包含 wecom、matrix。
+```
+
+### 9【prose】
+
+```text
+SSH 连接因间歇性 banner 错误失败(这是已知情况),我建立一个带 8 次重试的封装函数。
+```
+
+### 10【prose】
+
+```text
+agent-node-app-test-0001 是内容最齐全的同类源容器(11 个插件、9 个脚本、media-patch、patches 齐全,配置里只有 matrix 平台,没有 wecom,且正在运行)。先看它的 config.yaml 全文和容器启动参数。
+```
+
+### 11【prose】
+
+```text
+还在处理,3 分钟了,稍安勿躁。 — iteration 9/150, terminal
+```
+
+### 12【prose】
+
+```text
+验证通过:agent-node-app-test-0001 是 lj-test 的标准血缘源(11 个插件、9 个脚本、media-patch、patches、entry.sh 都存在,配置里没有 wecom 段)。现在做第 1 步:建目录并拷贝通用层。
+```
+
+### 13【prose】
+
+```text
+```
+cd /opt/data/tmp && /opt/data/venv-op...
+```
+```
+
+### 14【prose】
+
+```text
+转义出错,改为在本地写脚本,再通过 base64 投送执行。
+```
+
+### 15【prose】
+
+```text
+上次失败的那条命令已经建过目录。清理后重跑,确保是干净的拷贝。
+```
+
+### 16【prose】
+
+```text
+已确认:plugins 已拷贝,但 media-patch 和 patches 未拷(上次中途失败)。删掉后重新干净地拷贝。
+```
+
+### 17【prose】
+
+```text
+```
+cd /opt/data/tmp && /opt/data/venv-op...
+```
+```
+
+### 18【prose】
+
+```text
+* 没停,6 分钟了,别走开。 — iteration 14/150, terminal
+```
+
+### 19【prose】
+
+```text
+```
+cd /opt/data/tmp && /opt/data/venv-op...
+```
+```
+
+### 20【prose】
+
+```text
+第 1 步完成。现在进行第 2 步(处理 config.yaml 中的平台配置段)和第 3 步(写 .env)。
+```
+
+### 21【prose】
+
+```text
+源容器的 config.yaml 里本来就没有 wecom 段(只有 matrix),第 2 步只需用 yaml 解析器校验可解析。现在写 .env。
+```
+
+### 22【prose】
+
+```text
+.env 已写入,权限是 600、所有者是 10000。改用脚本文件方式校验 config.yaml 与 .env 内容(避开多层引号)。
+```
+
+### 23【prose】
+
+```text
+config 校验通过:platforms 里只有 matrix,没有 wecom,插件 9 个、hooks 有 4 条、模型保持不变。另外发现脚本里残留了源容器的 AGENT_ID 硬编码,按技能第 7 节必须修正。
+```
+
+### 24【prose】
+
+```text
+* 还在跑,9 分钟了——值得等。 — iteration 20/150, terminal
+```
+
+### 25【prose】
+
+```text
+需要修正两处兜底用的硬编码(技能第 7 节),然后建容器。
+```
+
+### 26【prose】
+
+```text
+py_compile 因为只读挂载而失败,改用宿主机 Python 校验。
+```
+
+### 27【prose】
+
+```text
+现在建容器(第 4 步)。
+```
+
+### 28【prose】
+
+```text
+需要从源容器取真实的 API key,不能使用我记忆里的值。
+```
+
+### 29【prose】
+
+```text
+* 还在吭哧吭哧干,12 分钟了。 — iteration 27/150, waiting for provider response (streaming)
+```
+
+### 30【prose】
+
+```text
+...
+```
+
+### 31【prose】
+
+```text
+容器已启动,gateway 正在运行。等日志稳定后检查 gateway_state 与 gateway 日志。
+```
+
+### 32【prose】
+
+```text
+matrix 状态已是 connected,自动加入了房间,DNS 补丁也已注入。现在进行第 5 步(配置 cron 任务)和 DNS 体检。
+```
+
+### 33【prose】
+
+```text
+两个 cron 已建立(新的 job_id)。现在进行 DNS 体检(第 6 步),并顺便跑 Matrix 自检。
+```
+
+### 34【prose】
+
+```text
+* 还在处理,15 分钟了,稍安勿躁。 — iteration 34/150, waiting for provider response (streaming)
+```
+
+### 35【prose】
+
+```text
+裸测(不带 RES_OPTIONS 直接测)耗时 5385ms,带上 RES_OPTIONS 后为 26ms,说明补丁已经生效(技能里记录过这个测量陷阱)。从 root 权限回读进程环境,确认 RES_OPTIONS 确实注入到了 gateway(网关进程)里。
+```
+
+### 36【prose】
+
+```text
+RES_OPTIONS 已确认注入到 s6 run 脚本里。现在进行 Matrix 自检(第 3 项)和房间消息收发验证(第 4、5 项)。
+```
+
+### 37【prose】
+
+```text
+Matrix 自检全部通过。现在进行第 5 项(插件日志)以及收尾核查。
+```
+
+### 38【prose】
+
+```text
+插件已加载(有 capability_check 记录),但心跳上报的日志还不明确。直接查询插件的上报结果和 errors.log。
+```
+
+### 39【prose】
+
+```text
+```
+cd /opt/data/tmp && /opt/data/venv-op...
+```
+```
+
+### 40【prose】
+
+```text
+插件都已加载,但 active-reporter 的心跳日志没有写入日志文件。直接查插件的实现和它的上报通道。
+```
+
+### 41【prose】
+
+```text
+* 手上活还剩一点,18 分钟了。 — iteration 40/150, terminal
+```
+
+### 42【prose】
+
+```text
+```
+cd /opt/data/tmp && B64=$(printf '%s\...
+```
+```
+
+### 43【prose】
+
+```text
+日志路径是 STATE_DIR/plugin.log,查一下它的位置和内容。
+```
+
+### 44【prose】
+
+```text
+* ```
+cd /opt/data/tmp && B64=$(printf '%s\...
+``` (×2)
+```
+
+### 45【prose】
+
+```text
+找到了:`/opt/data/.fmode/active-reporter/plugin.log`。
+```
+
+### 46【prose】
+
+```text
+```
+cd /opt/data/tmp && B64=$(printf '%s\...
+```
+```
+
+### 47【prose】
+
+```text
+心跳已上报成功(`ok=True`,`state.json` 里有 last_heartbeat 时间戳)。但日志显示有重复的心跳线程,需要确认是否真的重复,并查询 FmodeAgent 记录里的 heartbeatAt。先看重复的来源和接口状态。
+```
+
+### 48【prose】
+
+```text
+```
+cd /opt/data/tmp && B64=$(printf '%s\...
+```
+```
+
+### 49【prose】
+
+```text
+源容器也运行着两条心跳线程(jitter=106 与 190 交替),这是插件固有行为,不是本容器引入的问题。现在查询 FmodeAgent 记录,核实 heartbeatAt 是否已落库。
+```
+
+### 50【prose】
+
+```text
+* 没偷懒,21 分钟了,马上就好。 — iteration 47/150, waiting for provider response (streaming)
+```
+
+### 51【prose】
+
+```text
+我使用的 URL 不对。查看插件里真实的上报地址。
+```
+
+### 52【prose】
+
+```text
+```
+cd /opt/data/tmp && B64=$(printf '%s\...
+```
+```
+
+### 53【prose】
+
+```text
+优先级是 API_BASE(FUNCTION_ID 加 token 的形式),不是标准 REST 端点。读取常量,使用同样的通道回读 heartbeatAt。
+```
+
+### 54【prose】
+
+```text
+真实端点:`https://server.fmode.cn/api/functions`,使用 `{id, token, params}` 格式。
+```
+
+### 55【prose】
+
+```text
+记录核对一致:objectId=ondyhUHqv2、name=测试分身1125、status=online、heartbeatAt 在 567 秒前(容器启动时首推)。现在做收尾核查:显示名、SOUL 品牌口径、wecom 清零和源容器只读确认。
+```
+
+### 56【prose】
+
+```text
+有三处问题要处理:SOUL 名字还是「测试分身0001」;artifact-drain cron streak=3 error;media-patch 未打进 adapter.py。逐个查。
+```
+
+### 57【prose】
+
+```text
+两个真问题:① 缺少 `git-repos/agent-status-reporter/scripts/artifact-drain.py`(技能 §一 明确指出的易漏项);② 0.21.3 镜像里 matrix 平台是插件形态,adapter.py 路径变了,补丁没有生效。先查看源容器和镜像里的真实路径。
+```
+
+### 58【prose】
+
+```text
+```
+cd /opt/data/tmp && B64=$(printf '%s\...
+```
+```
+
+### 59【prose】
+
+```text
+* 还在处理,24 分钟了,稍安勿躁。 — iteration 55/150, waiting for provider response (streaming)
+```
+
+### 60【prose】
+
+```text
+adapter.py 不在 `/opt/hermes/plugins` 下(源容器里也没有,说明这条补丁在两台容器上都是空跑的)。现在找真实位置。
+```
+
+### 61【prose】
+
+```text
+```
+cd /opt/data/tmp && B64=$(printf '%s\...
+```
+```
+
+### 62【prose】
+
+```text
+adapter.py 在 `/opt/hermes/plugins/platforms/matrix/adapter.py`(能找到),但补丁标记计数为 0 —— 说明补丁没有应用成功,或者已经应用但写法不同。查看 media-patch 日志和补丁执行结果。
+```
+
+### 63【prose】
+
+```text
+```
+cd /opt/data/tmp && B64=$(printf '%s\...
+```
+```
+
+---
+
+## 工具过程(仅供核对)
+
+- `💻 terminal ``` date; ls /opt/data/scripts/r730_root.... ````
+- `💻 terminal ``` cd /opt/data && /opt/data/venv-ops/bi... ````
+- `* 💻 terminal ``` cd /opt/data && /opt/data/venv-ops/bi... ``` ``` cd /opt/data && /opt/data/venv-ops/bi... ````
+- `✍️ Writing /opt/data/tmp/r730.py`
+- `💻 terminal ``` cd /opt/data/tmp && /opt/data/venv-op... ````
+- `* 💻 terminal ``` cd /opt/data/tmp && /opt/data/venv-op... ``` ``` cd /opt/data/tmp && /opt/data/venv-op... ````
+- `✍️ Writing /opt/data/tmp/step1.sh`
+- `💻 terminal ``` cd /opt/data/tmp && B64=$(base64 -w0 ... ````
+- `* 💻 terminal ``` cd /opt/data/tmp && B64=$(base64 -w0 ... ``` ``` cd /opt/data/tmp && /opt/data/venv-op... ````
+- `🐍 Running code import hashlib pw = hashlib.sha256(("...`
+- `💻 terminal ``` cd /opt/data/tmp && B64=$(base64 -w0 ... ````
+- `* 💻 terminal ``` cd /opt/data/tmp && B64=$(base64 -w0 ... ``` ✍️ Writing /opt/data/tmp/step23.sh`
+- `💻 terminal ``` cd /opt/data/tmp && B64=$(base64 -w0 ... ````
+- `* 💻 terminal ``` cd /opt/data/tmp && B64=$(base64 -w0 ... ``` ``` cd /opt/data/tmp && /opt/data/venv-op... ````
+- `✍️ Writing /opt/data/tmp/step_fix.sh`
+- `💻 terminal ``` cd /opt/data/tmp && B64=$(base64 -w0 ... ````
+- `* 💻 terminal ``` cd /opt/data/tmp && B64=$(base64 -w0 ... ``` ``` cd /opt/data/tmp && /opt/data/venv-op... ````
+- `* 💻 terminal ``` cd /opt/data/tmp && B64=$(base64 -w0 ... ``` ``` cd /opt/data/tmp && /opt/data/venv-op... ``` (×2)`
+- `✍️ Writing /opt/data/tmp/step4.sh`
+- `💻 terminal ``` cd /opt/data/tmp && /opt/data/venv-op... ````
+- `✍️ Writing /opt/data/tmp/step4.sh`
+- `💻 terminal ``` cd /opt/data/tmp && B64=$(base64 -w0 ... ````
+- `* 💻 terminal ``` cd /opt/data/tmp && B64=$(base64 -w0 ... ``` ``` cd /opt/data/tmp && /opt/data/venv-op... ````
+- `✍️ Writing /opt/data/tmp/step5.sh`
+- `💻 terminal ``` cd /opt/data/tmp && B64=$(base64 -w0 ... ````
+- `* 💻 terminal ``` cd /opt/data/tmp && B64=$(base64 -w0 ... ``` ✍️ Writing /opt/data/tmp/step6.sh`
+- `💻 terminal ``` cd /opt/data/tmp && B64=$(base64 -w0 ... ````
+- `* 💻 terminal ``` cd /opt/data/tmp && B64=$(base64 -w0 ... ``` ``` cd /opt/data/tmp && /opt/data/venv-op... ````
+- `✍️ Writing /opt/data/tmp/step_mx.sh`
+- `💻 terminal ``` cd /opt/data/tmp && B64=$(base64 -w0 ... ````
+- `* 💻 terminal ``` cd /opt/data/tmp && B64=$(base64 -w0 ... ``` ✍️ Writing /opt/data/tmp/step_logs.sh`
+- `💻 terminal ``` cd /opt/data/tmp && B64=$(base64 -w0 ... ````
+- `* 💻 terminal ``` cd /opt/data/tmp && B64=$(base64 -w0 ... ``` ``` cd /opt/data/tmp && /opt/data/venv-op... ````
+- `✍️ Writing /opt/data/tmp/step_hb.sh`
+- `💻 terminal ``` cd /opt/data/tmp && B64=$(base64 -w0 ... ````
+- `* 💻 terminal ``` cd /opt/data/tmp && B64=$(base64 -w0 ... ``` ``` cd /opt/data/tmp && B64=$(printf '%s\... ````
+- `✍️ Writing /opt/data/tmp/step_hb2.sh`
+- `💻 terminal ``` cd /opt/data/tmp && B64=$(base64 -w0 ... ````
+- `* 💻 terminal ``` cd /opt/data/tmp && B64=$(base64 -w0 ... ``` ✍️ Writing /opt/data/tmp/step_final.sh`
+- `💻 terminal ``` cd /opt/data/tmp && B64=$(base64 -w0 ... ````
+- `* 💻 terminal ``` cd /opt/data/tmp && B64=$(base64 -w0 ... ``` ``` cd /opt/data/tmp && B64=$(printf '%s\... ````

+ 203 - 0
docs/04-quality/backup/deleted-user-F2srRikSln-20261127.json

@@ -0,0 +1,203 @@
+{
+  "deletedAt": "2026-11-27T11:09:39.869Z",
+  "objectId": "F2srRikSln",
+  "agents": [
+    {
+      "objectId": "FAEFq4OIsx",
+      "createdAt": "2026-11-27T06:37:15.097Z",
+      "updatedAt": "2026-11-27T06:37:15.102Z",
+      "agentId": "agent-node-app-faefq4oisx",
+      "user": {
+        "objectId": "F2srRikSln",
+        "__type": "Pointer",
+        "className": "_User"
+      },
+      "status": "offline",
+      "name": "我的试用容器",
+      "ACL": {
+        "F2srRikSln": {
+          "read": true,
+          "write": true
+        }
+      }
+    },
+    {
+      "objectId": "BUQiyB0b3c",
+      "createdAt": "2026-11-27T10:49:50.555Z",
+      "updatedAt": "2026-11-27T10:51:38.081Z",
+      "agentId": "agent-node-app-buqiyb0b3c",
+      "user": {
+        "objectId": "F2srRikSln",
+        "__type": "Pointer",
+        "className": "_User"
+      },
+      "updatedAtClient": {
+        "__type": "Date",
+        "iso": "2026-11-27T10:51:38.080Z"
+      },
+      "status": "offline",
+      "lastValue": "{\"currentSessions\": [], \"extraUpdatedAt\": \"2026-11-27T18:51:37+08:00\"}",
+      "lastField": "extra",
+      "name": "我的进阶版",
+      "heartbeatAt": {
+        "__type": "Date",
+        "iso": "2026-11-27T10:51:36.000Z"
+      },
+      "extra": "{\"currentSessions\": [], \"extraUpdatedAt\": \"2026-11-27T18:51:37+08:00\"}",
+      "ACL": {
+        "F2srRikSln": {
+          "read": true,
+          "write": true
+        },
+        "role:FMODE_AGENT_SUPERADMIN": {
+          "read": true,
+          "write": true
+        }
+      }
+    },
+    {
+      "objectId": "kvt61GA9GV",
+      "createdAt": "2026-11-27T10:50:08.652Z",
+      "updatedAt": "2026-11-27T11:08:35.610Z",
+      "agentId": "agent-node-app-kvt61ga9gv",
+      "user": {
+        "objectId": "F2srRikSln",
+        "__type": "Pointer",
+        "className": "_User"
+      },
+      "updatedAtClient": {
+        "__type": "Date",
+        "iso": "2026-11-27T11:08:35.604Z"
+      },
+      "status": "offline",
+      "lastValue": "{\"currentSessions\": [], \"extraUpdatedAt\": \"2026-11-27T19:08:57+08:00\"}",
+      "lastField": "extra",
+      "name": "我的进阶版",
+      "heartbeatAt": {
+        "__type": "Date",
+        "iso": "2026-11-27T11:08:56.000Z"
+      },
+      "extra": "{\"currentSessions\": [], \"extraUpdatedAt\": \"2026-11-27T19:08:57+08:00\"}",
+      "ACL": {
+        "F2srRikSln": {
+          "read": true,
+          "write": true
+        },
+        "role:FMODE_AGENT_SUPERADMIN": {
+          "read": true,
+          "write": true
+        }
+      }
+    }
+  ],
+  "bindings": [
+    {
+      "objectId": "48CFUZRBYT",
+      "createdAt": "2026-11-27T06:37:28.472Z",
+      "updatedAt": "2026-11-27T06:37:28.472Z",
+      "agentId": "agent-node-app-faefq4oisx",
+      "userPointer": {
+        "objectId": "F2srRikSln",
+        "__type": "Pointer",
+        "className": "_User"
+      },
+      "status": "active",
+      "agentMxId": "@faefq4oisx:fmode.cn",
+      "deviceId": "JuMpf0xirU",
+      "accessToken": "yB99immyfOz322hofW0Oaup4",
+      "roomId": "!VFjfIyx8luKO_UfOKPmhyAniJKm6jlov3jkKcYNYBZ0",
+      "homeserver": "https://matrix.fmode.cn",
+      "userMxId": "@f2srriksln:fmode.cn"
+    },
+    {
+      "objectId": "Wux88w1iBG",
+      "createdAt": "2026-11-27T10:50:04.110Z",
+      "updatedAt": "2026-11-27T10:50:04.110Z",
+      "agentId": "agent-node-app-buqiyb0b3c",
+      "userPointer": {
+        "objectId": "F2srRikSln",
+        "__type": "Pointer",
+        "className": "_User"
+      },
+      "status": "active",
+      "agentMxId": "@buqiyb0b3c:fmode.cn",
+      "deviceId": "LDtkDl7Bva",
+      "accessToken": "dZGJipZ8V665IgzilmERv2yH",
+      "roomId": "!ZyW8yhj0oh1tcvd9Hpv2QyW0lriX8fW-osmkOrZpGEg",
+      "homeserver": "https://matrix.fmode.cn",
+      "userMxId": "@f2srriksln:fmode.cn"
+    },
+    {
+      "objectId": "Zer5ltDY1r",
+      "createdAt": "2026-11-27T10:49:57.696Z",
+      "updatedAt": "2026-11-27T10:49:57.696Z",
+      "agentId": "agent-node-app-kvt61ga9gv",
+      "userPointer": {
+        "objectId": "F2srRikSln",
+        "__type": "Pointer",
+        "className": "_User"
+      },
+      "status": "active",
+      "agentMxId": "@kvt61ga9gv:fmode.cn",
+      "deviceId": "vevtyGf03a",
+      "accessToken": "jqps0pqMifAyalkvsVuJXgdu",
+      "roomId": "!CEkoMiY-TORHhixuwkFFdv4iTHaORn1qK3977Ff_6xA",
+      "homeserver": "https://matrix.fmode.cn",
+      "userMxId": "@f2srriksln:fmode.cn"
+    }
+  ],
+  "jobs": [
+    {
+      "objectId": "kfnvXUSDHn",
+      "createdAt": "2026-11-27T10:50:08.645Z",
+      "updatedAt": "2026-11-27T11:08:05.447Z",
+      "planCode": "advanced",
+      "user": {
+        "objectId": "F2srRikSln",
+        "__type": "Pointer",
+        "className": "_User"
+      },
+      "isDeleted": false,
+      "stage": "verifying",
+      "attempts": 2,
+      "status": "provisioning",
+      "idempotencyKey": "advanced-1795776606823",
+      "agentId": "kvt61GA9GV",
+      "matrixInfo": {
+        "roomId": "!CEkoMiY-TORHhixuwkFFdv4iTHaORn1qK3977Ff_6xA",
+        "userMxId": "@f2srriksln:fmode.cn",
+        "agentMxId": "@kvt61ga9gv:fmode.cn",
+        "homeserver": "https://matrix.fmode.cn"
+      },
+      "failedStage": "verify",
+      "retryable": true,
+      "reasonCode": "PROVISION_TIMEOUT",
+      "errorDetail": "timeout after 900000ms",
+      "jobRoomId": "!QysXO5bWkqwplSVfUX-VjZFBZafQfl7MQ6ETuJqnkaI"
+    },
+    {
+      "objectId": "LyIwZqfMcX",
+      "createdAt": "2026-11-27T10:49:50.550Z",
+      "updatedAt": "2026-11-27T10:50:07.230Z",
+      "planCode": "advanced",
+      "user": {
+        "objectId": "F2srRikSln",
+        "__type": "Pointer",
+        "className": "_User"
+      },
+      "isDeleted": false,
+      "stage": "verifying",
+      "attempts": 1,
+      "status": "provisioning",
+      "idempotencyKey": "advanced-1795776588835",
+      "agentId": "BUQiyB0b3c",
+      "matrixInfo": {
+        "roomId": "!ZyW8yhj0oh1tcvd9Hpv2QyW0lriX8fW-osmkOrZpGEg",
+        "userMxId": "@f2srriksln:fmode.cn",
+        "agentMxId": "@buqiyb0b3c:fmode.cn",
+        "homeserver": "https://matrix.fmode.cn"
+      },
+      "jobRoomId": "!EnIcbVCjA6gt-nqBb1c-aL93rLW9QcIQX_NMJS1z-m4"
+    }
+  ]
+}

+ 90 - 0
docs/04-quality/backup/deleted-user-PNFaPMsbHS-20261127.json

@@ -0,0 +1,90 @@
+{
+  "user": {
+    "objectId": "PNFaPMsbHS",
+    "createdAt": "2026-05-28T07:20:16.560Z",
+    "updatedAt": "2026-11-10T14:30:18.138Z",
+    "username": "fmode18182795512",
+    "nickname": "用户5512",
+    "mobile": "18182795512",
+    "company": {
+      "objectId": "E4KpGvTEto",
+      "__type": "Pointer",
+      "className": "Company"
+    },
+    "avatar": "https://file-cloud.fmode.cn/DXNgcD6zo6/20221202/j6p8kb034039.png",
+    "type": "user",
+    "hash": "A2ED93BE61E85B8AA0B4C19A2EC2E53A",
+    "hashType": "ERC20",
+    "status": "normal",
+    "fmodeApiToken": "sk-0777bbf6253e66d5629fdd4db7d419051be5501efc4358e2",
+    "newapiToken": "sk-0777bbf6253e66d5629fdd4db7d419051be5501efc4358e2",
+    "ACL": {
+      "*": {
+        "read": true
+      },
+      "PNFaPMsbHS": {
+        "read": true,
+        "write": true
+      },
+      "role: E4KpGvTEto_admin": {
+        "read": true,
+        "write": true
+      }
+    }
+  },
+  "bindings": [
+    {
+      "objectId": "VymsyqhshA",
+      "createdAt": "2026-11-10T14:06:56.122Z",
+      "updatedAt": "2026-11-10T14:07:03.360Z",
+      "agentId": "",
+      "userPointer": {
+        "objectId": "PNFaPMsbHS",
+        "__type": "Pointer",
+        "className": "_User"
+      },
+      "status": "active",
+      "deviceId": "4mCjjEuiE6",
+      "accessToken": "p4palggt7rrTYQF4A7Z1TAxK",
+      "homeserver": "https://matrix.fmode.cn",
+      "userMxId": "@pnfapmsbhs:fmode.cn"
+    },
+    {
+      "objectId": "MstxIswWI1",
+      "createdAt": "2026-11-11T16:33:42.859Z",
+      "updatedAt": "2026-11-11T16:33:30.589Z",
+      "agentId": "agent-node-lj-test",
+      "userPointer": {
+        "objectId": "PNFaPMsbHS",
+        "__type": "Pointer",
+        "className": "_User"
+      },
+      "status": "active",
+      "agentMxId": "@zgdcmgnqcd:fmode.cn",
+      "deviceId": "473ZWl9Sf2",
+      "accessToken": "KaDVPhHNexodFl9Uc0EiY4Ay",
+      "roomId": "!kk7Q2sOkocoQDP9QpUPcNrPuYxZyGE5I-mmI4MKjgLE",
+      "homeserver": "https://matrix.fmode.cn",
+      "userMxId": "@pnfapmsbhs:fmode.cn"
+    },
+    {
+      "objectId": "W1IIgA08BH",
+      "createdAt": "2026-11-11T17:05:07.306Z",
+      "updatedAt": "2026-11-11T17:05:07.306Z",
+      "agentId": "agent-lj",
+      "userPointer": {
+        "objectId": "PNFaPMsbHS",
+        "__type": "Pointer",
+        "className": "_User"
+      },
+      "status": "active",
+      "agentMxId": "@k0nrevcfik:fmode.cn",
+      "deviceId": "0HlOinL06h",
+      "accessToken": "S75EMXCQfkXyvczCrOWWcyEj",
+      "roomId": "!F1E-4Oh3xStLHKkzWjHCVD1-HAX2_9ovmgqzEI5aLpg",
+      "homeserver": "https://matrix.fmode.cn",
+      "userMxId": "@pnfapmsbhs:fmode.cn"
+    }
+  ],
+  "deletedAt": "2026-11-27T05:48:54.304Z"
+}

+ 202 - 0
docs/04-quality/backup/deleted-user-WGJMHffBS3-20261127.json

@@ -0,0 +1,202 @@
+{
+  "deletedAt": "2026-11-27T06:32:24.100Z",
+  "objectId": "WGJMHffBS3",
+  "user": {
+    "objectId": "WGJMHffBS3",
+    "createdAt": "2026-11-27T06:02:01.147Z",
+    "updatedAt": "2026-11-27T06:02:01.503Z",
+    "username": "fmode18182795512",
+    "nickname": "用户5512",
+    "mobile": "18182795512",
+    "avatar": "https://file-cloud.fmode.cn/DXNgcD6zo6/20221202/j6p8kb034039.png",
+    "type": "user",
+    "hash": "52822F3907A750619719CF859854586B",
+    "hashType": "ERC20",
+    "status": "normal",
+    "ACL": {
+      "*": {
+        "read": true
+      },
+      "WGJMHffBS3": {
+        "read": true,
+        "write": true
+      }
+    }
+  },
+  "agents": [
+    {
+      "objectId": "C7ir8CuOVQ",
+      "createdAt": "2026-11-27T06:02:17.303Z",
+      "updatedAt": "2026-11-27T06:29:44.996Z",
+      "agentId": "agent-node-app-c7ir8cuovq",
+      "user": {
+        "objectId": "WGJMHffBS3",
+        "__type": "Pointer",
+        "className": "_User"
+      },
+      "status": "offline",
+      "name": "我的入门版",
+      "isDeleted": true,
+      "ACL": {
+        "WGJMHffBS3": {
+          "read": true,
+          "write": true
+        }
+      }
+    },
+    {
+      "objectId": "NPGqPXW6DE",
+      "createdAt": "2026-11-27T06:04:02.983Z",
+      "updatedAt": "2026-11-27T06:28:42.277Z",
+      "agentId": "agent-node-app-npgqpxw6de",
+      "user": {
+        "objectId": "WGJMHffBS3",
+        "__type": "Pointer",
+        "className": "_User"
+      },
+      "updatedAtClient": {
+        "__type": "Date",
+        "iso": "2026-11-27T06:06:01.939Z"
+      },
+      "status": "offline",
+      "lastValue": "{\"currentSessions\": [], \"extraUpdatedAt\": \"2026-11-27T14:06:01+08:00\"}",
+      "lastField": "extra",
+      "name": "我的企业版",
+      "heartbeatAt": {
+        "__type": "Date",
+        "iso": "2026-11-27T06:06:00.000Z"
+      },
+      "extra": "{\"currentSessions\": [], \"extraUpdatedAt\": \"2026-11-27T14:06:01+08:00\"}",
+      "isDeleted": true,
+      "ACL": {
+        "WGJMHffBS3": {
+          "read": true,
+          "write": true
+        },
+        "role:FMODE_AGENT_SUPERADMIN": {
+          "read": true,
+          "write": true
+        }
+      }
+    },
+    {
+      "objectId": "htIeSukte0",
+      "createdAt": "2026-11-27T06:04:20.152Z",
+      "updatedAt": "2026-11-27T06:29:04.203Z",
+      "agentId": "agent-node-app-htiesukte0",
+      "user": {
+        "objectId": "WGJMHffBS3",
+        "__type": "Pointer",
+        "className": "_User"
+      },
+      "status": "offline",
+      "name": "我的试用容器",
+      "isDeleted": true,
+      "ACL": {
+        "WGJMHffBS3": {
+          "read": true,
+          "write": true
+        }
+      }
+    }
+  ],
+  "bindings": [
+    {
+      "objectId": "6HXAFfZ6g0",
+      "createdAt": "2026-11-27T06:01:49.408Z",
+      "updatedAt": "2026-11-27T06:01:49.408Z",
+      "agentId": "agent-node-app-c7ir8cuovq",
+      "userPointer": {
+        "objectId": "WGJMHffBS3",
+        "__type": "Pointer",
+        "className": "_User"
+      },
+      "status": "active",
+      "agentMxId": "@c7ir8cuovq:fmode.cn",
+      "deviceId": "vY8IuOLaWE",
+      "accessToken": "10Y4dB0nA554lVFw63Av7g05",
+      "roomId": "!op9KTSRmGbi2ck1MW6947nbBTy4HNq2YV8hdZevi4EY",
+      "homeserver": "https://matrix.fmode.cn",
+      "userMxId": "@wgjmhffbs3:fmode.cn"
+    },
+    {
+      "objectId": "Hq8yovIUxH",
+      "createdAt": "2026-11-27T06:04:14.057Z",
+      "updatedAt": "2026-11-27T06:04:14.057Z",
+      "agentId": "agent-node-app-npgqpxw6de",
+      "userPointer": {
+        "objectId": "WGJMHffBS3",
+        "__type": "Pointer",
+        "className": "_User"
+      },
+      "status": "active",
+      "agentMxId": "@npgqpxw6de:fmode.cn",
+      "deviceId": "27GxsL5I3Y",
+      "accessToken": "Js2jACWy8EfgTIjMG6kYgRPs",
+      "roomId": "!GW8KEL76ufXdKc17jinfuwOXxDgcSqmYf6uUmkGUwxs",
+      "homeserver": "https://matrix.fmode.cn",
+      "userMxId": "@wgjmhffbs3:fmode.cn"
+    },
+    {
+      "objectId": "Jh8eoQeAoJ",
+      "createdAt": "2026-11-27T06:04:42.922Z",
+      "updatedAt": "2026-11-27T06:05:24.155Z",
+      "agentId": "",
+      "userPointer": {
+        "objectId": "WGJMHffBS3",
+        "__type": "Pointer",
+        "className": "_User"
+      },
+      "status": "active",
+      "deviceId": "GR8QIzOxE5",
+      "accessToken": "LnP3Z5yeKGJPwbf4H4Qmz8Mr",
+      "homeserver": "https://matrix.fmode.cn",
+      "userMxId": "@wgjmhffbs3:fmode.cn"
+    },
+    {
+      "objectId": "5CnYuoXJpR",
+      "createdAt": "2026-11-27T06:04:53.628Z",
+      "updatedAt": "2026-11-27T06:04:53.628Z",
+      "agentId": "agent-node-app-htiesukte0",
+      "userPointer": {
+        "objectId": "WGJMHffBS3",
+        "__type": "Pointer",
+        "className": "_User"
+      },
+      "status": "active",
+      "agentMxId": "@htiesukte0:fmode.cn",
+      "deviceId": "rMo9u2lmts",
+      "accessToken": "i5z0qWu9br8G5HMx5RaSmVu6",
+      "roomId": "!-KNFhJutA09Jnt-jUZK_7WSlMghWbpdaRDlMS1U5fz4",
+      "homeserver": "https://matrix.fmode.cn",
+      "userMxId": "@wgjmhffbs3:fmode.cn"
+    }
+  ],
+  "jobs": [
+    {
+      "objectId": "3UQ273jSCw",
+      "createdAt": "2026-11-27T06:04:02.970Z",
+      "updatedAt": "2026-11-27T06:28:42.355Z",
+      "planCode": "enterprise",
+      "user": {
+        "objectId": "WGJMHffBS3",
+        "__type": "Pointer",
+        "className": "_User"
+      },
+      "isDeleted": true,
+      "stage": "verifying",
+      "attempts": 1,
+      "status": "failed",
+      "idempotencyKey": "enterprise-1795759463312",
+      "agentId": "NPGqPXW6DE",
+      "matrixInfo": {
+        "roomId": "!GW8KEL76ufXdKc17jinfuwOXxDgcSqmYf6uUmkGUwxs",
+        "userMxId": "@wgjmhffbs3:fmode.cn",
+        "agentMxId": "@npgqpxw6de:fmode.cn",
+        "homeserver": "https://matrix.fmode.cn"
+      },
+      "error": "测试残留清理",
+      "jobRoomId": "!_s8G7-Zi7QFkLJ03SamokNgABbME9N0Rng1dEPciMTY"
+    }
+  ]
+}

+ 33 - 0
docs/04-quality/review/2026-11-25-套餐体系文档评审-第1轮.md

@@ -0,0 +1,33 @@
+# 评审报告:套餐与开通体系文档包(第 1 轮)
+
+| 字段 | 值 |
+|---|---|
+| 日期 | 2026-11-25 |
+| 评审人 | 独立评审员子代理(隔离 prompt,无设计过程上下文) |
+| 被评审物 | CR-20261125-01 / PRD-20261125-套餐与开通体系 / 定价与权益-20261125-草案 / PLAN-20261125-套餐体系 + 4 处回填登记 |
+| 结论 | **修改后通过**(0 blocker / 0 major / 2 minor / 5 nit) |
+
+## 问题清单与修复闭环
+
+| # | 级 | 问题 | 修复 |
+|---|---|---|---|
+| 1 | minor | 主 PRD §十「关联文档」未收录新 PRD | ✅ §十 已追加「套餐与开通体系(v1.3 新增,CR-20261125-01)」行 |
+| 2 | minor | 追溯矩阵元数据未随改动更新 | ✅ 升 v0.5、日期 2026-11-25、变更原因补 FR-21~27 |
+| 3 | nit | 定价待裁决清单未覆盖 PRD Q3「加价口径」 | ✅ D2 加注「含第二台起加价口径」并回指 PRD Q3 |
+| 4 | nit | 计划书 M2「AC-21.1~AC-27.1」漏子项(AC-22.2 等) | ✅ 改「PRD §六 全部 AC(含全部子项)逐条通过」 |
+| 5 | nit | CR §四 路径写「追溯矩阵」非真实文件名 | ✅ 改 `traceability-matrix.md` |
+| 6 | nit | SPEC 规模计数未提 FR-21 起段 | ✅ 规模行下补指针「FR-21 起见 PRD-20261125」 |
+| 7 | nit | 主 PRD 元数据「CR-20261125」缺 -01 后缀 | ✅ 统一为 CR-20261125-01 |
+
+## 评审员通过项(原文要点)
+
+- **合规性**:PRD/CR/计划书/定价文档结构齐备,FR 表保留「变更不得静默修改」注记
+- **裁决一致性**:三档权益矩阵在 PRD/定价/计划书三处逐格一致;未发现自造需求(配额/云资源随附/试用关系/存储方案全部挂开放问题且「建议」字样明确)
+- **FR↔AC**:每条 FR ≥1 条 AC,AC-22.2 正确双挂,全部 AC 为可验证断言,无空泛口号
+- **价格纪律**:全部文档 grep 零命中写死金额(「2 核 4G」「30 天」「一年」为资源规格不违规)
+- **可追溯**:抽查引用路径全部真实存在;编号前后一致;FR-21 起始号经 SPEC 核实无碰撞
+- **体例**:与 CR-20261105 对比无缺项
+
+## 闭环结论
+
+7 条问题全部于 2026-11-25 当日修复(逐条 diff 见 git 工作区),按评审员建议「修复后直接归档,无需复审轮次」执行。**阶段 0(文档)完成**,进入阶段 1(用户裁决 D1~D6 / Q1~Q4)。

+ 171 - 0
docs/04-quality/review/2026-11-25-套餐异步开通-需求设计评审.md

@@ -0,0 +1,171 @@
+# 评审报告:套餐异步开通需求、接口设计与独立原型
+
+| 字段 | 值 |
+|---|---|
+| 评审日期 | 2026-11-25 |
+| 评审节点 | 需求评审 / 接口与架构设计评审(G-D1 前) |
+| 评审员视角 | 独立需求与接口设计评审员子代理 |
+| 技术栈依据 | Angular 20 standalone;FmodeApi / ParseApi / MockApi;平台 Functions body `{id,token,params}`;历史实体创建经受控宿主通道 |
+| 唯一业务审查依据 | 派发检查单:1/1/3/5、独立资源与本人 Matrix、48h ready 起算、到期保留与原容器恢复、有效权益不降级、五状态六阶段、并发幂等恢复、安全、门禁、原型场景 |
+| 规则依据 | `rules/21-评审与验收规范.md:5-10,28-30`;报告结构参考 `templates/review-report-template.md` |
+| 独立性 | 未读取对话历史、其他代理结论或实现者评价;仅读被评审物和必要接口事实;未读凭据、未调用云端/容器、未改被评审物、未提交 |
+| 评审结论 | **不通过,修复下列问题后仅复查问题项;不登记 G-D1 通过** |
+
+## 一、被评审物与证据代号
+
+| 代号 | 文件 |
+|---|---|
+| PLAN | `docs/02-design/plans/2026-11-25-套餐体系任务计划书.md` |
+| PRD | `docs/01-requirements/prd/PRD-20261125-套餐与开通体系.md` |
+| PRICE | `docs/01-requirements/prd/定价与权益-20261125-草案.md` |
+| CR | `docs/01-requirements/changes/CR-20261125-02-平台容器与试用异步开通.md` |
+| HANDOVER | `docs/00-tracking/AI接手说明-套餐体系与容器资产.md` |
+| TRACE | `docs/04-quality/traceability-matrix.md` |
+| API | `docs/03-interface/api/套餐与平台异步开通-API契约.md` |
+| ARCH | `docs/02-design/architecture/套餐权益与异步开通设计.md` |
+| MODEL | `prototypes/fmode-subscription-20261125/model.js` |
+| APP | `prototypes/fmode-subscription-20261125/app.js` |
+| SHELL | `prototypes/fmode-subscription-20261125/preview.template.html` |
+| STYLE | `prototypes/fmode-subscription-20261125/styles.css` |
+| HTML | `prototypes/fmode-subscription-20261125/index.html` |
+
+表内“代号:行号”均指向本表的完整路径。必要事实核对只读了既有 `src/app/core/api/parse-api.ts:406-424`、`docs/03-interface/api/API-契约.md:182-205`;本地运行工具核对只读了原型 build/verify 和 package.json。没有将既有原型验证脚本的结论作为本次独立结论。
+
+## 二、检查单逐项结论
+
+| # | 检查项 | 结论 | 证据及说明 |
+|---|---|---|---|
+| 01 | 试用1、入门固定1、进阶3、企业每Company共享5;仅进阶/企业可增配 | pass | PRD:36-43;PRICE:16-27;API:51-52;MODEL:3-7,41;本地增配回放确认前3、确认后4 |
+| 02 | 试用/入门/进阶含平台容器、独立资源、本人Matrix接入信息 | fail | 文档口径一致:PRD:38-45、ARCH:15;原型只列agentMxId,缺本人身份/服务器接入字段,见R4 |
+| 03 | 价格待定;首期人工收款/权益确认,后续创建由平台异步执行 | pass | PRICE:12,43-50;API:56,120-131;MODEL:84-98;意向未确认不增加名额或解除过期 |
+| 04 | 一次48h,从首容器与资源全部ready开始;重试不重置 | pass | PRD:109-110;API:158-159;MODEL:59-61,74-77,83;本地回放起止差48h且恢复后起始值不变;只是原型演示证据 |
+| 05 | 到期不停容器、不删数据、不撤销外部凭据;本App及项目API限制使用,付费恢复原容器 | pass | API:139,160-161;ARCH:60-62;MODEL:93-100;本地回放原agentId和容器数量不变;真实运行/数据保留尚待后续验收 |
+| 06 | 已有有效个人/企业权益分别保留,不互相降级或迁移资产 | fail | API:76和ARCH:37已有正确设计;MODEL:94-101与APP:59产生相反可交互结果,见R1 |
+| 07 | 五状态及六阶段来自结构化平台结果,不解析自然语言 | pass | PRD:60-62;API:82-104,143-154;MODEL:9-15,64-83;评审工具与产品操作区分见SHELL:13-18 |
+| 08 | 阶段/checkpoint结果、比例与展示一致 | fail | MODEL:34与APP:86,90-94使等待/失败预设出现三个阶段完成却0%,见R6 |
+| 09 | 幂等、并发原子预占、在途占额、旧worker防回写 | pass | API:50-55,143-152;ARCH:41-44;这里只确认设计,不确认平台已有CAS/事务能力 |
+| 10 | 失败补偿与释放后重试不会泄漏或超配,AC可执行 | fail | PRD:114要求按契约释放;API:52,126,152和ARCH:41-45缺确定无资源释放与再预占规则,见R3 |
+| 11 | 持久任务、租约、checkpoint、结果未知先回查、恢复同任务 | pass | API:54-55,95,124-126,143-154;ARCH:41-44;原型内存刷新重置的限制已披露,ARCH:85、APP:102 |
+| 12 | 明确失败/重试与网络状态分离;已有容器的新任务不阻断旧容器 | pass | PRD:83;API:95,126;ARCH:54-55;MODEL:55-58,65,81-83;本地回放新增任务时used=3/reserved=1/access=active |
+| 13 | 未实测ETA为空,新资产实测后形成明确可核对的参考公式 | fail | API:89,168正确保留空值;API:169与PRD:86,119、CR:35取整不一致,见R5 |
+| 14 | 后续专用账号与新资产真实计时,不碰lj-test/旧资产 | pass | PLAN:24,102;PRD:129;API:167;ARCH:93;本次0云端/容器调用 |
+| 15 | 凭据仅用户专属,平台masterKey不下发;本人、作用域、ready、短时确认齐备 | fail | API:46,133-139限定了密钥类型与本人,但方法前置漏目标ready校验,与PRD:45,98-100不一致,见R2 |
+| 16 | 租户/本人权限由服务端权威控制,企业角色与平台运营权限分离 | pass | API:23-27,31-46,128-131,143;ARCH:37,53-56;企业写动作company上下文还需澄清,W1 |
+| 17 | CAS/事务、实体创建执行器、专属凭据能力、原skill八项未核实处透明;不造FunctionID | pass | API:13-17,53,110-112,174-181;ARCH:100;明确区分新设计检查分组与原skill八项 |
+| 18 | 原型首次、等待、失败重试、额度满增配、已有容器新任务、到期恢复、企业引导 | pass | SHELL:16-17;APP:68-150,185-202;MODEL:18-39,57-102;具体错误另列R1/R6,不将场景存在等同业务正确 |
+| 19 | 接入信息默认遮蔽、二次确认、全假值 | pass | APP:120-132,196-197,227-235;本地页面7个遮蔽字段;字段完整性另见R4;无真实凭据读取 |
+| 20 | 浅深色与移动适配 | pass(限定) | STYLE:284-392;APP:8,277;本地Chromium对320/390/1440px×浅深色×7场景共42个页面做DOM溢出/错误检查,均通过;未据此宣称完整视觉/对比度验收 |
+| 21 | G-D1前只有设计/原型,不要求当前产品代码、云部署或真计时;Mock不当真实实现 | pass | PLAN:21-24,97-103,121-125;PRD:21,90;API:181;ARCH:13,85,91-100;TRACE:58-86,117;全部产品AC保持未实现/未验收 |
+
+## 三、问题清单
+
+### R1(阻断)个人/企业权益与资产被单一状态覆盖,原型能把有效企业权益降成个人入门
+
+- **证据**:MODEL:19只建一个plan/access/containers;MODEL:94-96确认任何套餐均覆盖plan/company;MODEL:101加入企业直接替换全部containers。APP:59仅禁用当前同档套餐,企业账号可申请入门。发布用HTML也含同一逻辑:HTML:1190,1265-1272,1337。与API:76“分别解析、不自动转资产”、ARCH:37“入企仍可持个人权益”和PRD:108/126冲突。
+- **可复现**:独立HTML打开`?scenario=advanced&screen=enterprise`,展开演示场景→企业确认加入。原个人容器被改成企业容器列表,原个人进阶权益无处保留。另打开`?scenario=enterprise`→套餐→入门咨询开通→提交→模拟管理员确认,得到`plan=starter, company=false, access=active, used=2, limit=1`,列表两个容器仍为`company=true`。
+- **影响**:无法确认个人/企业并存和有效权益不降级的关键交互;现有资产被错误转归属,配额与可使用状态自相矛盾。
+- **修复要求**:原型按personal/company分别保存权益、任务、配额和资产,选择作用域只切换投影;入企/购买个人套餐均不得覆盖另一有效作用域。至少新增“个人有效后入企仍保留个人资产”“企业有效且个人试用过期仍保留企业使用”“企业有效另购入门两份权益并存”回放。先修原型,不要求现在接真实平台。
+
+### R2(重要)凭据查询方法没有把目标资源ready写为服务端前置
+
+- **证据**:API:127方法约束仅“本人独立资源和本人Matrix绑定”;API:137列本人、独立作用域、有效权益和短时认证,漏掉目标容器/资源已完成ready。上游PRD:45、98-100及CR:27明确未ready不得读取。API:72、88仅约束使用/进入容器,不能替代凭据方法本身的前置。
+- **影响**:拥有有效进阶权益并新建第二容器时,“有效权益”并不证明该新资源核验完成;按当前方法描述无法确定应否拒绝提前读取已分配凭据,也无法直接落实AC-23.1/23.2。
+- **修复要求**:在getMyCredentials及凭据交付边界写明按resourceId解析服务端真实所属任务/容器,目标必须ready且关联资源检查通过;未ready返回稳定错误,不能只检查当前账号已有有效权益或其他ready容器。增加“已有可用容器、新容器未ready”的负向AC/契约示例。本项是设计前置缺失,不声称当前已有真实接口泄露。
+
+### R3(重要)“无资源失败释放”与“原任务重试”之间缺少一致性规则,AC-29.3没有完整契约依据
+
+- **证据**:PRD:114和PLAN:83写“无资源失败按契约释放”;API:52、152只定义资源未知时保留,API:126又要求续“原任务及其预约”。ARCH:41-45定义初次预约、未知保留、ready结转,没有确定无资源时reservation释放状态/原子变更,也没有释放后的重试重新预占规则。
+- **影响**:不能确定名额何时归还、已释放job如何重试。若失败A释放后名额被B用掉,A是否可重新执行、用哪个预约、是否返回QUOTA_EXCEEDED均未定义,无法判定超配或泄漏,亦不能执行AC-29.3期望值。
+- **修复要求**:补reservation生命周期及失败决策表,至少区分确定无资源/部分已建/外部结果未知;明确定案者谁可释放、原子扣减与审计、幂等释放;对保留可重试资格的已释放任务,重试须先原子重预占,没名额时不启动worker、不换job、不改试用起止。补A释放→B占满→A重试的可核对结果。允许设计选择终结并不可重试,但须显式约定并与产品AC对齐。
+
+### R4(重要)接入信息没有呈现本人Matrix身份,容易把agent身份当作本人参数
+
+- **证据**:APP:120-127的Matrix字段只有agentMxId、roomId、accessToken,APP:130-132却称“归属于你的通信身份”“每位成员使用自己的身份”;ARCH:81称本人Matrix三要素。既有必要事实`docs/03-interface/api/API-契约.md:195-200`明确userMxId与agentMxId是两个字段,并有homeserver;`src/app/core/api/parse-api.ts:410-411,422`以userMxId+accessToken作为本人身份有效的必要组合。HTML:1399起嵌入相同字段集合。
+- **影响**:原型无法审阅“本人身份/token”和“容器对端身份”的区别,也未给出Matrix服务器;成员各自身份这一要求没有清楚的接入信息投影。此处只确认字段缺失和命名歧义,不推断假token属于他人。
+- **修复要求**:明确列本人userMxId、本人accessToken及homeserver,容器agentMxId单独标为对端,roomId标为当前授权容器房间;若正式交付刻意只提供某组最小参数,应在API及原型说明这些字段如何识别本人、连接哪台服务器,并给出可验证的本人绑定展示,而非用agentMxId替代本人身份。继续使用明确假值和二次确认。
+
+### R5(重要)API和PRD的ETA取整算法不一致
+
+- **证据**:API:169使用`ceil(ceil(T/60) × 1.3)`;PRD:86、119,CR:35,HANDOVER:52均使用`ceil(T × 1.30 / 60)`;PLAN:39、125同样要求总秒数先乘1.30再按分钟向上取整。ARCH:94要求按契约公式,进一步传播此冲突。
+- **可复现**:纯算术回放T=61秒,PRD=2分钟、API=3分钟;T=601秒,PRD=14分钟、API=15分钟。没有使用真实平台耗时冒充样本。
+- **影响**:后续参考时长配置与AC-30.5无法同时满足两份生效文档。
+- **修复要求**:统一采用已裁决的`ceil(T*1.30/60)`,明确输入秒单位、只在最后一次取整;加非整分钟边界示例,未实测仍保持estimate/estimatedReadyAt为空。
+
+### R6(建议,须修复原型一致性)等待/失败预设进度与已完成阶段数量相反
+
+- **证据**:MODEL:33-36初始化任务后只设stage=3,保留初始completed=0;APP:86用completed计算百分比,APP:90-94按stage给前三阶段标已完成。HTML:1205与1364为同一逻辑。
+- **可复现**:打开独立HTML`?scenario=waiting`,页面显示“0% · 0 / 6 项完成”,同时DOM有3个`.job-step.done`;failed预设同源。只读模型回放同样得到stage=3/completed=0。
+- **影响**:结构化真实进度的示范自相矛盾,用户可能误判已完成检查点。
+- **修复要求**:预设快照同步completed,或所有投影统一从同一阶段快照推导;核对首次排队、各推进阶段、失败及重试后的计数和比例一致。修复后重新构建HTML。
+
+## 四、观察项与后续生产门禁(warn,不冒充本阶段缺陷)
+
+| 编号 | 观察项 | 证据与处理 |
+|---|---|---|
+| W1 | 企业写动作的Company上下文尚有歧义 | API:24允许选companyId,119在getAccess明列;121/123/125只列subjectType。检查单未说明用户是否可能处于多个Company,故不作越权fail。实现前明确这些动作是必须携带经核实companyId,还是唯一Company由服务端推导,绝不能沿用前端上一页选择作为隐式授权。 |
+| W2 | 未核实的平台原子提交、实体执行器、凭据托管、原skill八项映射 | API:17,53,112,174-181;ARCH:100已透明列明。当前不要求上线实证,后续具备平台能力与G-D1后逐项核实;不能把本报告的设计pass当能力已存在。 |
+| W3 | 本次布局检查范围有限 | STYLE:284-392具备移动/暗色支持;本次只做DOM无溢出、浏览器错误和交互回放,未做完整视觉截图、触控逐元素/对比度验收。本报告不替代专项UI评审。 |
+
+## 五、本次独立验证记录
+
+全程本地运行,未安装依赖、未登录、未读凭据、未调用平台、未写生产/旧容器。未运行会生成其他报告/截图的原型verify脚本;只用无文件输出的Node/Chromium命令读取同一HTML及MODEL。
+
+| 验证 | 结果 |
+|---|---|
+| MODEL与APP是否完整嵌入交付HTML | 两者逐字包含,确认不是只改源码未进HTML;STYLE/SHELL只读检查 |
+| 本地浏览器 | 使用已安装Chromium;首次默认headless-shell路径缺失后改用已存在完整Chromium路径;没有下载浏览器 |
+| 布局/主题/场景 | 320、390、1440px;浅/深色;new/waiting/failed/advanced/quota/expired/enterprise;42次页面加载无document/main横向溢出,0 pageerror |
+| 网络 | 浏览器拦截http/https路由保护,本次外网请求计数0 |
+| 试用正常回放 | ready前起止null;失败重试同job且reserved=1;ready后差值48h;到期不移除容器;入门确认恢复同agentId、同数量、同trialStartedAt |
+| 增配/已有容器新任务 | quota场景创建禁用;申请增配不立即生效,确认3→4;新任务期间used=3/reserved=1/access=active |
+| 权益并存与切换 | R1两条浏览器路径及独立MODEL回放均复现覆盖/used=2大于limit=1 |
+| 等待进度 | 浏览器读数“0% · 0 / 6 项完成”、3个done阶段,R6复现 |
+| 凭据展示 | 页面7个masked-value,字段集与R4一致;未请求真实凭据 |
+| ETA | T=61/120/601秒纯算术比较,61与601秒出现PRD/API差异,见R5 |
+
+## 六、修复与复审
+
+| 问题 | 当前状态 | 修复人 | 复审范围与判据 | 复审结论/日期 |
+|---|---|---|---|---|
+| R1 | 待主执行修复 | 待登记 | 仅复核主体模型和上述三条个人/企业并存路径、HTML同步 | 待复审 |
+| R2 | 待主执行修复 | 待登记 | 仅复核凭据前置与“有效旧容器+未ready新资源”拒绝契约 | 待复审 |
+| R3 | 待主执行修复 | 待登记 | 仅复核释放/再预约决策表与A/B并发边界预期,AC-29.3对应 | 待复审 |
+| R4 | 待主执行修复/明确最小交付字段 | 待登记 | 仅复核本人/agent身份区分、连接服务器、假值及HTML同步 | 待复审 |
+| R5 | 待主执行修复 | 待登记 | 仅复核公式全链一致与非整分钟边界例 | 待复审 |
+| R6 | 待主执行修复 | 待登记 | 仅复核waiting/failed以及推进、失败、重试的阶段与总进度一致 | 待复审 |
+
+主执行需将本报告登记`docs/README.md`索引;评审员仅获授权写本报告,未修改索引或被评审物。当前不能宣称独立需求/设计评审通过,亦不能以此代替用户G-D1原型确认、后续真实平台验收或功能完成。
+
+## 七、2026-11-25 第二轮定向复审(最新结论)
+
+**复审结论:通过。本节为R1–R6修复后的最新需求/接口设计与原型复审结论,前文初审“不通过”及其证据完整保留为历史。** 本轮仅复查上述六项及其直接传播,未扩大为产品实现、安全上线或真实资源验收。G-D1仍须用户明确确认,不由本报告代签。
+
+| 字段 | 内容 |
+|---|---|
+| 复审范围 | R1–R6;API/架构、PRD/唯一计划/TRACE对应传播,以及最新独立HTML |
+| 修复责任 | 主执行负责设计及原型;原文档执行负责PRD/计划/TRACE传播;评审员仅写本报告 |
+| 证据独立性 | 重新读取修复后的源文件与HTML;独立运行无文件输出的Node/Chromium回放;未读取或引用实现者verify/results结论代替证据 |
+| 最新UI裁决 | 采用PRD §3.4、PLAN §4.4:产品页面只展示友好当前状态、真实进度、必要时间与操作;不再要求展示内部六阶段名称或3/6清单;结构化事实仍可从模型/API核对 |
+| 生产边界 | CAS/事务、执行器、真实Function ID、真实凭据托管/授权、原skill映射和真实计时仍待后续平台核实与验收,不因设计复审通过改成已实现 |
+
+### 7.1 问题闭环结果
+
+以下行号对应复审时版本;前文初审行号不回写。
+
+| 问题 | 复审结果 | 修复证据与独立验证 |
+|---|---|---|
+| R1 | **pass,关闭** | MODEL:17-27引入按主体捕获/切换,30-37初始化独立个人与企业上下文,101-126申请/加入不再覆盖另一主体;APP:147-148新增主体切换,238-245申请个人套餐先切个人,降档不自动执行。独立浏览器将个人进阶容器重命名后入企,再切回仍为原ID/原名/3额度;个人过期后入企,切回个人起止和资产不变、再切企业仍可进入会话;企业2/5申请个人入门并完成ready后,个人为1/1,切回企业原2容器和5额度不变;个人在途job跨主体切换保留同ID和进度。个人进阶申请入门被阻止,不产生降档申请。 |
+| R2 | **pass,关闭(设计)** | API:75提供脱敏resourceDeliveries,使resourceId可发现;130-131定义requestCredentialGrant及getMyCredentials;141-143明确grant绑定有效会话/资源/字段、短时一次性、过期/消费/范围不符重新确认,消费时再次校验本人/独立作用域/有效权益/目标ready及配套交付核验;另一可用容器不能替代当前目标ready,未ready明确PROVISIONING_REQUIRED。UI确认不再被称为MFA,也不需凭空取得未定义的认证证明。目标未ready读取的否定条件已直接写入契约;这里只确认契约闭合,不声称真实授权接口已部署。 |
+| R3 | **pass,关闭(设计)** | API:57-58及129、ARCH:46补held/committed/released,只有服务端回查证实无实体且无在途操作才原子释放;部分已有/未知保留held;released同job重试先原子重预占,A释放后被B占满则QUOTA_EXCEEDED并保持failed/released,不新job、不放行、不重置试用;held复用原预约。PRD:64、120-121(AC-29.3/新AC-29.4)、PLAN:83-84和TRACE:66/85均已同步,AC-29.1~4可追溯且保持未执行状态。没有把文档规则当作已完成CAS并发实测。 |
+| R4 | **pass,关闭** | APP:105-120加入本人userMxId与homeserver,保留agentMxId/roomId/本人accessToken,并对企业作用域隐藏独立backend凭据面板;API:144明确本人和agent身份不同,ARCH:82同步字段。独立浏览器:个人接入页9个遮蔽字段、企业页5个通信字段且无企业云秘密按钮;本人userMxId确认前无值,二次确认后仅显示`@demo-user:example.invalid`假值。 |
+| R5 | **pass,关闭** | API:176已统一`ceil(T × 1.3 / 60)`,与PRD:92/126、CR:35、HANDOVER:52一致;纯算术复核61秒→2分钟、601秒→14分钟;未实测仍不产生固定预计完成时刻。最新等待页的“稍后更新”是无样本占位,不作为时长承诺。 |
+| R6 | **pass,关闭** | MODEL:46令waiting/failed预设stage=3且completed=3;APP:79-87统一按completed/6生成真实比例。按最新UI裁决独立浏览器确认waiting、failed的aria-valuenow均为50,模型completed均为3;#main无.job-step且不展示内部平台/核验/预占/Matrix说明;原job重试保持50%,继续推进依次66%、83%、100%。不再以产品页面必须显示3/6或六步名称作为判据。 |
+
+### 7.2 第二轮独立验证与边界
+
+- 对最新独立HTML重复回放上述跨主体流程、本人参数确认与R6状态序列,全部通过。源码MODEL及APP再次逐字比对,均完整嵌入最终index.html。
+- 对最新产品页重新加载320/390/1440px×浅/深色×new/waiting/failed/advanced/quota/expired/enterprise共42个组合,document/main均无横向溢出,0浏览器pageerror、0外网请求。新增主体切换条也做了三个宽度、两主题的独立切换检查。
+- 六阶段仍在MODEL:9-15及API:85-115等技术结构中;PRD:66-68/122、PLAN:88-90已明确友好状态投影,简化展示不等同删除状态事实或按计时器制造完成。
+- W1企业Company上下文澄清仍作为非阻断观察项;W2平台前提待实证、W3完整视觉与对比度验收边界继续保留。本轮通过只覆盖G-D1前的需求、接口设计和独立原型;不表示用户已经确认原型、产品代码已实现、平台已联通或全部产品AC已通过。
+
+**R1–R6现已全部闭环,可将当前原型交用户进行G-D1确认。** 本轮仅追加本报告,未修改被评审物、凭据、索引、云端/容器或提交记录;主执行负责同步文档索引和当前门禁状态。

+ 40 - 5
docs/04-quality/traceability-matrix.md

@@ -2,10 +2,10 @@
 
 | 字段 | 值 |
 |---|---|
-| 版本 | v0.4(阶段② 设计文档列填充) |
-| 最后更新日期 | 2026-10-14 |
+| 版本 | v0.6(套餐 FR-21~30,PRD v1.1) |
+| 最后更新日期 | 2026-11-25 |
 | 状态 | 骨架 · 「测试用例」列随编码逐行填充 |
-| 本次变更原因 | 阶段② 设计规范四件套 + API 契约 + 数据访问层设计产出后,填充「设计文档」与「数据/接口」两列 |
+| 本次变更原因 | CR-20261125-02:保留 FR-21~27,新增 FR-28~30;本轮架构/API/双端原型已产出,独立复审中;补齐预约三状态/CAS释放/同job原子重占与AC-29.4;G-D1待确认,未实现/未验收 |
 
 > 规则依据:rules/02 开发流程与文档同步(四向追溯矩阵)。🔴 必备文档。
 > **四向**:需求(FR) ←→ 用户画像 ←→ 设计文档 ←→ 测试用例。
@@ -22,6 +22,11 @@
 | `数据层` | `docs/02-design/architecture/数据访问层设计.md` |
 | `API` | `docs/03-interface/api/API-契约.md` |
 | `ADR-006` | `docs/02-design/decisions/ADR-006-视觉基线对齐原型.md` |
+| `套餐PRD` | `docs/01-requirements/prd/PRD-20261125-套餐与开通体系.md` v1.1,FR-21~30 |
+| `套餐设计` | `docs/02-design/architecture/套餐权益与异步开通设计.md`(本轮设计态) |
+| `套餐API` | `docs/03-interface/api/套餐与平台异步开通-API契约.md`(设计态,平台实现待确认) |
+| `套餐原型` | `prototypes/fmode-subscription-20261125/index.html`(双端,G-D1 待确认) |
+| `套餐记录` | `docs/00-tracking/2026-11-25-套餐异步开通实施记录.md` |
 
 ---
 
@@ -50,6 +55,35 @@
 | FR-18 | 范围冻结声明 | — (治理) | — | — | — | — | ✅ 已确认 |
 | FR-19 | 移动端聚合首页 | P1 | AC-19.1~4 | `组件`§3.2 home / §四-6 | `数据层`§六.1(分区独立三态) | `smoke`(移动首页路由 + 输入框字号≥16px) | 设计就绪 |
 | FR-20 | 超管可见范围 | P2 | AC-20.1~3 | `API`§五(ACL 口径) | `API`§五(服务端为准) | `parse-api.spec.ts`(roles 缺失降级,判级以服务端为准) | 设计就绪 |
+| FR-21 | 套餐/试用与权益展示 | P1/P2 | AC-21.1~2 | 套餐设计/套餐原型 | 套餐API 权益/套餐;价格仅定价文档 | 待执行:双端/内容与价格扫描 | v1.1 独立复审中/G-D1待确认;未实现 |
+| FR-22 | 申请、人工收款/套餐确认后平台受理 | P1/P2 | AC-22.1~2 | 套餐设计/套餐原型 | 套餐API 申请/授权确认/幂等 | 待执行:授权、重复/并发确认 | v1.1 独立复审中/G-D1待确认;未实现 |
+| FR-23 | 独立资源四件套/Matrix 安全交付 | P1 | AC-23.1~3 | 套餐设计/套餐原型 | 套餐API 凭据;平台管理 masterKey 永不下发 | 待执行:ready/本人/独立作用域/二次确认/泄露与越权 | v1.1 独立复审中/G-D1待确认;未实现 |
+| FR-24 | 平台创建容器与完整核验 | 全部 | AC-24.1~2 | 套餐设计/套餐原型 | 套餐API 异步执行/核验;实体创建待平台实现 | 待执行:新资产规格、Matrix/心跳/核验失败阻断 | v1.1 独立复审中/G-D1待确认;平台依赖 |
+| FR-25 | 个人/企业容器归属与共享 | P1/P2 | AC-25.1~2 | 套餐设计/套餐原型 | mine/Company 服务端隔离与配额 | 待执行:重命名/越权/退出企业/共享计数 | v1.1 独立复审中/G-D1待确认;未实现 |
+| FR-26 | 加入企业与通讯录引导 | P1/P2 | AC-26.1~2 | 套餐设计/套餐原型 | 既有成员/分组能力待核对 | 待执行:入企刷新/分组/各自 Matrix 身份 | v1.1 独立复审中/G-D1待确认;未实现 |
+| FR-27 | 权威权限、错误降级与既有权益保护 | 全部 | AC-27.1~2 | 套餐设计/套餐原型 | 套餐API 权益/项目使用鉴权 | 待执行:本地篡改/网络失败/有效权益不降级 | v1.1 独立复审中/G-D1待确认;未实现 |
+| FR-28 | 一次 48h 试用、到期与原容器恢复 | P1 | AC-28.1~3 | 套餐设计/套餐原型 | 套餐API 领取/ready 起算/到期权限/付费恢复 | 待执行:并发领取/服务端时钟/到期保留与同容器 | v1.1 独立复审中/G-D1待确认;未实现 |
+| FR-29 | 1/1/3/5 配额、预占及付费增配 | 全部 | AC-29.1~4 | 套餐设计/套餐原型 | 套餐API §2.3/retryProvision;held/committed/released、CAS释放及同job重占 | 待执行:满额/并发/增配/无实体无在途释放/未知保留held/重占额度不足 | v1.1 独立复审中/G-D1待确认;未实现 |
+| FR-30 | 异步任务五状态六阶段及恢复重试 | 全部 | AC-30.1~5 | 套餐设计/套餐原型 | 套餐API 执行器结构化状态/查询/重试 | 待执行:状态矩阵/换设备恢复/故障复用/新资产计时 | v1.1 独立复审中/G-D1待确认;平台依赖 |
+
+---
+
+## 套餐 v1.1 四向实施证据账(设计不等于实现)
+
+> 对应 CR-20261125-02。需求/AC 见主矩阵;下表补充“测试↔提交↔Schema”证据,后续按实际回填,不虚构提交号或表变更已落地。
+
+| FR | 测试/验收证据 | 代码提交 | Schema/数据变更证据 | 实施记录 |
+|---|---|---|---|---|
+| FR-21 | 未执行,AC-21.1~2 | 未实现/未提交 | 权益目录设计,未落地 | 套餐记录(待回填) |
+| FR-22 | 未执行,AC-22.1~2 | 未实现/未提交 | 申请/确认幂等模型设计,未落地 | 套餐记录(待回填) |
+| FR-23 | 未执行,AC-23.1~3 | 未实现/未提交 | 独立资源/凭据引用与授权设计,未落地 | 套餐记录(待回填) |
+| FR-24 | 未执行,AC-24.1~2 | 未实现/未提交 | 容器/交付核验关联设计,平台待实现 | 套餐记录(待回填) |
+| FR-25 | 未执行,AC-25.1~2 | 未实现/未提交 | 个人/Company 归属与现有 Schema 核对待实施 | 套餐记录(待回填) |
+| FR-26 | 未执行,AC-26.1~2 | 未实现/未提交 | 既有成员/分组 Schema 兼容性待核对 | 套餐记录(待回填) |
+| FR-27 | 未执行,AC-27.1~2 | 未实现/未提交 | 服务端权益/项目权限设计,未落地 | 套餐记录(待回填) |
+| FR-28 | 未执行,AC-28.1~3 | 未实现/未提交 | 账号一次试用/ready起止与历史映射设计,未落地 | 套餐记录(待回填) |
+| FR-29 | 未执行,AC-29.1~4 | 未实现/未提交 | 预约三状态/CAS释放/同job重占;QUOTA_EXCEEDED保持failed/released,未落地 | 套餐记录(待回填) |
+| FR-30 | 未执行,AC-30.1~5 | 未实现/未提交 | 持久任务/阶段/幂等/审计设计,平台待实现 | 套餐记录(待回填) |
 
 ---
 
@@ -77,9 +111,10 @@
 | `API-契约.md` | FR-02 · FR-04 · FR-05 · FR-07 · FR-07b · FR-08 · FR-20 | kanban 接收端未实现(FR-07b 阻塞项) |
 | `数据访问层设计.md` | FR-06 · FR-14 · FR-19 | — |
 | `ADR-006` | FR-12 · FR-17 | — |
+| 本轮套餐设计/API/双端原型 | FR-21~30(PRD v1.1) | 产出已齐备、独立复审中,G-D1待用户确认;实体容器创建/执行器是平台待实现依赖,未实测 |
 
-**结论**:21 条 FR 中 **20 条已挂设计文档**;FR-11(语音通话)为增项暂缓、FR-18 为治理条款,按规则无需设计文档。
-**无缺口**;唯一外部阻塞是 FR-07b 的云函数接收端(已在 `API`§六 列出)。
+**存量阶段结论(不含 FR-21~30)**:原 21 条 FR 的设计覆盖与 FR-07b 外部依赖按原记录保留,不能据此宣称新增套餐无缺口。
+**套餐 v1.1 当前边界**:FR-21~30 已登记本轮设计/API/原型来源,产出已齐备、独立复审中,G-D1待用户确认;服务端权益/试用/配额/实体创建尚待实现及真实验收,全部 AC 不能提前标通过。原阶段 0 文档 7 项闭环仅覆盖 v1.0。
 
 ---
 

+ 20 - 5
docs/README.md

@@ -2,10 +2,10 @@
 
 | 字段 | 值 |
 |---|---|
-| 版本 | v2.0 |
-| 最后更新日期 | 2026-10-14 |
+| 版本 | v2.1 |
+| 最后更新日期 | 2026-11-25 |
 | 状态 | 生效 |
-| 本次变更原因 | 阶段①→② 已切换;补齐 API 契约、数据访问层设计、组件规范、实施计划、ADR-006 等新产出物的索引 |
+| 本次变更原因 | CR-20261125-02:套餐 v1.1/定价 v0.2、异步 API/架构/双端原型与追踪索引同步;新增 FR-28~30,明确新评审与 G-D1 待确认 |
 
 > 规则依据:rules/11 文档体系。**新增/修改文档必须同步更新本索引**(必须规则 7)。
 
@@ -49,7 +49,9 @@
 | **G-D1** | **关键页面原型经用户确认** | 🟡 **原型已敲定,待 UI 细节目视确认** |
 | 设计建模 | 数据范式 + API 契约评审通过 | 🟡 API 契约已产出,待评审 |
 
-**下一步**:设计规范与原型目视确认(G-D1)→ 阶段③ 编码(按《2026-10-14-v2实施计划.md》滚动交付)。
+**存量主线下一步**:设计规范与原型目视确认(G-D1)→ 阶段③ 编码(按《2026-10-14-v2实施计划.md》滚动交付)。
+
+**套餐任务当前快照(2026-11-25,独立门禁)**:唯一执行基准为《2026-11-25-套餐体系任务计划书》v1.1。阶段 0 原文档 7 项评审已闭环;最新业务裁决已收口,本轮 API/架构及双端原型准备,**v1.1 待新独立评审、G-D1 待用户确认,确认前不得产品编码**。平台实体容器创建 API 未确认实现,设计不等于上线;旧资产只读,后续仅专用新验收资产实测。
 
 ---
 
@@ -58,6 +60,9 @@
 ### 00-tracking/ 全程追踪(黄金规则 10)
 | 文档 | 状态 | 说明 |
 |---|---|---|
+| [AI接手说明-套餐体系与容器资产.md](00-tracking/AI接手说明-套餐体系与容器资产.md) | 🔴 **v1.1 · 接手必读** | 最新裁决、G-D1/新评审边界;凭据仅位置索引;lj-test/旧资产只读、后续专用新验收资产 |
+| [2026-11-25-套餐异步开通实施记录.md](00-tracking/2026-11-25-套餐异步开通实施记录.md) | 本轮记录,非上线证据 | 文档/接口设计/双端原型、待确认门禁及后续真实验证证据 |
+| [当前进度-给AI接手.md](00-tracking/当前进度-给AI接手.md) | 头部套餐快照已更新 | 套餐 v1.1 现状;其他历史进度保留 |
 | [操作追踪.md](00-tracking/操作追踪.md) | 生效 | 🔴 综合日志,按动作逐条追加(⚠️ 12:43–13:46 段曾误删,已重建,见文首说明) |
 | [2026-11-08-修改留痕-会话隔离与容器状态统一.md](00-tracking/2026-11-08-修改留痕-会话隔离与容器状态统一.md) | 生效 | v1.0 · 会话隔离收尾 + 容器状态收敛到 `resolveAgentState` + 输出状态口径统一(提交 `f6f6e48`) |
 | [2026-11-08-踩坑-会话隔离与状态判定.md](00-tracking/2026-11-08-踩坑-会话隔离与状态判定.md) | 生效 | v1.0 · 两次误判的复盘 + 遗留 P0/P1/P2 清单(明日处理) |
@@ -75,6 +80,10 @@
 |---|---|---|
 | [prd/SPEC-20261014-fmode-app-v2-草案.md](01-requirements/prd/SPEC-20261014-fmode-app-v2-草案.md) | 已过 5 轮评审 | **21 条 FR** + 13 条 NFR;含 5 条裁决派生需求 |
 | [prd/PRD-20261014-fmode-app-v2.md](01-requirements/prd/PRD-20261014-fmode-app-v2.md) | 生效 | 产品需求文档 |
+| [prd/PRD-20261125-套餐与开通体系.md](01-requirements/prd/PRD-20261125-套餐与开通体系.md) | **v1.1 · 待新独立评审** | FR-21~30 + 可验证 AC:平台容器/独立资源、一次 48h、1/1/3/5、异步五状态六阶段、原容器续用 |
+| [prd/定价与权益-20261125-草案.md](01-requirements/prd/定价与权益-20261125-草案.md) | **v0.2 · 权益已定/价格待定** | **价格唯一维护点**;入门月费/进阶年费含一年资源;进阶/企业可增配;仅保留真实未决商业项 |
+| [changes/CR-20261125-套餐体系纳入范围.md](01-requirements/changes/CR-20261125-套餐体系纳入范围.md) | 原始范围已批准(历史) | 与 CR-02 冲突条款由最新裁决覆盖,不作为旧人工创建产品流程依据 |
+| [changes/CR-20261125-02-平台容器与试用异步开通.md](01-requirements/changes/CR-20261125-02-平台容器与试用异步开通.md) | **业务裁决已确认 · 新评审/G-D1待办** | 最新生效规则、覆盖关系、平台实现依赖、文档与可验证验收传播 |
 | [personas/用户画像.md](01-requirements/personas/用户画像.md) | 生效 | 三类画像 × 9 个模块的矩阵 |
 | [raci/RACI.md](01-requirements/raci/RACI.md) | 生效 | 权责矩阵 + 跨角色协作接口 |
 | [交接文档-阶段1至2.md](01-requirements/交接文档-阶段1至2.md) | 生效 | 阶段①交付清单、门禁状态、阶段②约束 C1–C8、遗留 L1–L8 |
@@ -89,6 +98,9 @@
 | [architecture/当前业务逻辑总览.md](02-design/architecture/当前业务逻辑总览.md) | 🔴 **v1.0 · 必读** | 五条主线的真实链路(会话/群聊/状态/文件成果/云函数)+ 已知问题 |
 | [architecture/需求-实现对照表.md](02-design/architecture/需求-实现对照表.md) | 🔴 **v1.0 · 必读** | 21 条 FR + 6 条 NFR + 业务规则 → 代码位置 → 测试 → 状态 |
 | [plans/2026-10-14-v2实施计划.md](02-design/plans/2026-10-14-v2实施计划.md) | 🔴 **生效(编码基线)** | 阶段②收尾 → 阶段③ 四层推进 + 10 个滚动里程碑 + 验证体系 |
+| [plans/2026-11-25-套餐体系任务计划书.md](02-design/plans/2026-11-25-套餐体系任务计划书.md) | 🔴 **v1.1 · 唯一执行基准** | 裁决已收口;阶段 1 接口设计/阶段 2 双端原型准备,待新评审/G-D1;平台创建未确认实现 |
+| [architecture/套餐权益与异步开通设计.md](02-design/architecture/套餐权益与异步开通设计.md) | 本轮设计态 · 待新独立评审 | 服务端权益/48h/Company 配额预占/异步任务与恢复/凭据隔离,未实现 |
+| [套餐双端原型](../prototypes/fmode-subscription-20261125/index.html) | 本轮原型 · **G-D1 待用户确认** | 试用/套餐/人工确认/阶段等待/ready/失败重试/到期与同容器恢复/企业共享;演示使用假数据 |
 | [plans/2026-10-19-账号账套改造计划.md](02-design/plans/2026-10-19-账号账套改造计划.md) | 🔴 **生效(待开工)** | **规范模板六要素版**:16 个原子任务分 4 Wave(云函数 / 前端判级 / 多账套 / 数据核对)+ 5 道门禁 + 三身份验收 + 安全检查清单 |
 | [plans/2026-10-19-数据层治理与新容器接入.md](02-design/plans/2026-10-19-数据层治理与新容器接入.md) | 🔴 **生效(待开工)** | **主计划补充卷**:`FmodeAgent.company` 空洞精确构成(33 个写侧漏写 / 6 个用户无归属)+ 云函数 6 项优化 C1~C6 + 新容器接入优化 + 容器提示词 |
 | [plans/2026-10-14-v2重建方案.md](02-design/plans/2026-10-14-v2重建方案.md) | 生效 | 重建总方案(三支柱 + 路线图 + 风险) |
@@ -118,6 +130,7 @@
 | 文档 | 状态 | 说明 |
 |---|---|---|
 | [api/API-契约.md](03-interface/api/API-契约.md) | 🔴 **生效(编码基线)** | 5 个云函数 + 7 个 REST 端点 + Parse 数据表 + ACL 口径 + 8 项待服务端核对 |
+| [api/套餐与平台异步开通-API契约.md](03-interface/api/套餐与平台异步开通-API契约.md) | **设计态 · 平台待确认实现** | 权益/申请/异步受理/任务查询重试/配额/试用/凭据;五状态六阶段,不能当作上线接口 |
 | [待问Agent-20261014-多任务接入核实.md](03-interface/待问Agent-20261014-多任务接入核实.md) | **待转发** | 6 组 16 问,直接复制发给容器 Agent |
 | [开通手册-20261017-FMODE接入标准流程.md](03-interface/开通手册-20261017-FMODE接入标准流程.md) | 🔴 **生效** | **每次开通新 Agent 按此执行**:五步流程 + 容器提示词模板 + 补录规范 + 故障排查 |
 | [容器任务卡-20261017-lj-test身份对齐.md](03-interface/容器任务卡-20261017-lj-test身份对齐.md) | **待执行** | lj-test 身份对齐任务卡,含可复制提示词与验收判据 |
@@ -125,7 +138,9 @@
 ### 04-quality/ 质量保障
 | 文档 | 状态 | 说明 |
 |---|---|---|
-| [traceability-matrix.md](04-quality/traceability-matrix.md) | 骨架 | 🔴 四向追溯矩阵(编码阶段逐行填充) |
+| [traceability-matrix.md](04-quality/traceability-matrix.md) | **v0.6 · 套餐 FR-21~30 已登记** | 套餐 AC/设计/API/原型与测试/提交/Schema 台账;本轮待新评审/G-D1,未实现未验收 |
+| [review/2026-11-25-套餐体系文档评审-第1轮.md](04-quality/review/2026-11-25-套餐体系文档评审-第1轮.md) | v1.0 历史 7 项已闭环 | 仅覆盖阶段 0 原文档,**不代表 v1.1 新裁决评审通过** |
+| 套餐 v1.1 新独立评审 | 待执行/归档 | 对应本轮需求/架构/API/双端原型及问题闭环,不能复用旧报告结论 |
 | review/2026-10-14-SPEC-ER评审-第1轮.md | 已归档 | 不通过(严重 7 / 一般 11 / 提示 7) |
 | review/2026-10-14-SPEC-ER评审-第2轮.md | 已归档 | 不通过(严重 4 / 一般 5 / 提示 2) |
 | review/2026-10-14-SPEC-ER评审-第3轮.md | 已归档 | 不通过(仅 2 项残留) |

+ 21 - 2
prototypes/fmode-download-20261120/README.md

@@ -1,6 +1,6 @@
 # Fmode Android 宣传与下载官网
 
-独立、响应式 HTML 产品官网,桌面端优先,也适配窄屏查看。视觉采用黑曜石暗色界面、薄荷绿品牌色和大幅排版;参考 TRAE 等产品官网的开屏氛围、滚动节奏与页尾收束方式,再围绕 Fmode 的品牌和产品能力原创设计。内容按当前 App 已有的会话、通讯录、工作台与成果回看能力组织,不修改 Angular App、路由或 APK。
+独立、响应式 HTML 产品官网,包含桌面布局与手机专用排版。视觉采用黑曜石暗色界面、薄荷绿品牌色和大幅排版,围绕 Fmode 的品牌和产品能力组织内容。手机端提供可读的产品演示、触控导航和安全区下载底栏;不修改 Angular App、路由或 APK。
 
 ## 预览
 
@@ -8,10 +8,29 @@
 
 site.template.html、site.css 和 site.js 是便于维护的源文件。修改后运行 node prototypes/fmode-download-20261120/build.mjs,会将源码重新打包成可单独分发的 index.html。字体资源使用项目内的 Geist 字体,开源字体授权说明见 LICENSE-Geist.txt。
 
+## 扫码与直接下载
+
+- 首屏、下载区与手机底栏同时保留「直接下载」和「扫码下载」。下载区常驻二维码,可点击放大、长按保存 PNG,或复制下载链接。
+- 所有下载链接与二维码均由同一个 `FMODE_SITE.apkUrl` 驱动。发布脚本更新版本和地址后,重新构建即可自动同步,无需另换二维码图片。
+- 二维码在浏览器本地生成,不请求外部二维码服务。编码器为 `vendor/qrcodegen.js`(Project Nayuki QR Code generator v1.8.0,MIT,许可与来源保留在文件头),构建时内嵌,无新增 npm 包。
+- 微信 / QQ 内提示用浏览器打开;iPhone / iPad 说明当前 APK 仅支持 Android,并可分享二维码或链接。
+- 地址为空或不安全时展示待开放说明;二维码生成失败仍可直接下载;剪贴板不可用时显示可手动复制的链接。
+
 ## 接入 APK
 
 打开 site.js,将 FMODE_SITE.apkUrl 填为正式 HTTPS 地址即可启用 APK 下载。version、fileSize 和 updatedAt 可选,用于显示版本、安装包大小和更新日期。地址为空时,按钮会打开说明弹窗;地址仅允许 HTTPS 或安全的站内相对地址。
 
 产品展示区支持鼠标点击及键盘方向键切换「专注对话 / 全局工作台 / 成果回看」。人物及对话为示例文案;页面能力主题根据现有 App 页面组织。
 
-preview-desktop.png、preview-full.png、preview-mobile.png 和 preview-footer.png 是浏览器生成的页面预览截图。
+## 本地验证
+
+在项目根目录执行:
+
+```bash
+node prototypes/fmode-download-20261120/build.mjs
+node scripts/verify-download-site.mjs
+```
+
+回归脚本使用项目现有 Playwright 和 Chromium,启动临时本地服务器;下载请求使用测试文件拦截,不访问线上 API 或发布资源。验证 11 个屏幕宽度、短屏弹窗、移动菜单、页签、FAQ、下载事件、复制链接、无效配置、版本切换、iOS / 微信提示与离线二维码。报告与截图输出到 `test-results/download-site/`(不入库)。二维码原图及页面截图已另用 OpenCV 实际解码校验。
+
+`preview-*.png` 为初版原型截图;本次预览以 `test-results/download-site/hero-390.png`、`hero-1440.png`、`download-390.png`、`download-1440.png` 和 `qr-dialog-390.png` 为准。

+ 2 - 1
prototypes/fmode-download-20261120/build.mjs

@@ -7,6 +7,7 @@ const template = fs.readFileSync(path.join(root, 'site.template.html'), 'utf8');
 const font = fs.readFileSync(path.join(root, '../fmode-landing-20261027/assets/fonts/geist-latin-wght-normal.woff2')).toString('base64');
 const css = fs.readFileSync(path.join(root, 'site.css'), 'utf8').replace('__GEIST_FONT__', font);
 const js = fs.readFileSync(path.join(root, 'site.js'), 'utf8');
-const html = template.replace('/* INJECT_STYLES */', () => css).replace('/* INJECT_SCRIPT */', () => js);
+const qr = fs.readFileSync(path.join(root, 'vendor/qrcodegen.js'), 'utf8');
+const html = template.replace('/* INJECT_STYLES */', () => css).replace('/* INJECT_SCRIPT */', () => qr + '\n' + js);
 fs.writeFileSync(path.join(root, 'index.html'), html);
 console.log('Built standalone index.html: ' + Math.round(Buffer.byteLength(html) / 1024) + ' KB. No external requests.');

Datei-Diff unterdrückt, da er zu groß ist
+ 1149 - 7
prototypes/fmode-download-20261120/index.html


+ 268 - 0
prototypes/fmode-download-20261120/site.css

@@ -69,3 +69,271 @@
 @media(max-width:760px){.hero{padding-top:82px}.hero-atmosphere{height:880px;min-height:680px}.product-theater{margin-top:94px}.footer-cta{min-height:390px;padding-block:82px}.footer-cta-copy h2{font-size:clamp(54px,9vw,78px)}.footer-cta-button{gap:8px;padding-inline:16px;font-size:11px}.footer-cta-orbit{right:-5%;width:46vw}.footer-links{grid-template-columns:1.2fr 1fr 1fr;gap:26px 20px}.footer-note{grid-column:2/4}.footer-brand .wordmark{font-size:17px}}
 @media(max-width:560px){.hero{padding-top:74px}.hero-atmosphere{inset:-20px 0 auto;height:760px;min-height:620px}.hero-atmosphere::before{background:radial-gradient(ellipse 62% 26% at 50% 30%,#b8f7ca18,transparent 100%),radial-gradient(ellipse 95% 46% at 50% 38%,#2e7f4b13,transparent 100%)}.hero-glow{top:-25px;width:115vw;height:510px}.hero-orbit{top:130px;width:690px;height:300px}.hero-orbit.orbit-two{top:115px;width:820px;height:370px}.product-theater{margin-top:82px}.footer-cta{min-height:0;grid-template-columns:1fr;gap:28px;padding-block:72px}.footer-cta-copy h2{margin:20px 0 15px;font-size:clamp(50px,12vw,68px)}.footer-cta-copy>p:last-child{max-width:270px;font-size:11px}.footer-cta-button{justify-self:start;min-height:52px}.footer-cta-orbit{top:18%;right:-27%;width:78vw;transform:translateY(-50%)}.footer-links{grid-template-columns:1fr 1fr;gap:30px 16px;padding-block:36px}.footer-brand,.footer-note{grid-column:1/-1}.footer-note{grid-column:1/-1}.footer-bottom{align-items:flex-start;flex-direction:column;gap:10px;padding-block:18px}.footer-wordmark{margin-top:26px;font-size:28vw}}
 @media(prefers-reduced-motion:reduce){.hero-atmosphere::before,.hero-orbit,.footer-cta-orbit{animation:none!important}}
+
+/* Download actions share one release configuration on every screen. */
+[hidden] { display: none !important; }
+html { scrollbar-gutter: stable; }
+.hero-footnote { gap: 8px; color: var(--muted); font-family: inherit; font-size: 11px; line-height: 1.6; }
+.hero-footnote > span { width: auto; height: auto; background: none; }
+.hero-footnote .footnote-divider { margin-inline: 4px; color: var(--muted-2); }
+.hero-footnote a { display: inline-flex; align-items: center; gap: 5px; min-height: 44px; }
+.hero-footnote a:hover { color: var(--mint); }
+.hero-footnote .icon { width: 13px; height: 13px; }
+.download-card { grid-template-columns: minmax(0, 1.35fr) minmax(280px, .9fr); gap: 20px; }
+.download-copy { padding: 48px 0 48px 48px; }
+.download-copy h2 { font-size: clamp(34px, 3.7vw, 49px); }
+.download-description { font-size: 14px; line-height: 1.9; }
+.download-cta { flex-wrap: wrap; gap: 10px; }
+.download-cta .button { min-height: 50px; padding-inline: 16px; font-size: 13px; }
+.download-status, .release-meta { font-size: 12px; line-height: 1.8; }
+.download-status { margin-bottom: 6px; }
+.download-status i { flex: none; }
+.release-meta { margin-block: 0 8px; }
+.install-hint { max-width: 420px; margin: 12px 0 0; color: var(--muted); font-size: 12px; line-height: 1.8; }
+.download-qr { position: relative; z-index: 2; display: flex; align-items: center; flex-direction: column; padding: 32px 24px; text-align: center; }
+.qr-eyebrow { margin: 0 0 18px; color: var(--muted-2); font-size: 9px; }
+.qr-image-button { display: grid; width: 222px; height: 222px; flex: none; place-items: center; overflow: hidden; padding: 0; border: 0; border-radius: 12px; background: #fff; color: #233b2b; box-shadow: 0 0 0 7px #b8f7ca0b, 0 16px 50px #0004; cursor: zoom-in; }
+[data-qr-image] { display: block; width: 100%; height: 100%; object-fit: contain; image-rendering: pixelated; }
+[data-qr-placeholder] { padding: 20px; font-size: 14px; }
+.download-qr h3 { margin: 22px 0 8px; font-size: 15px; font-weight: 550; letter-spacing: -.03em; }
+.qr-instruction { margin: 0; color: var(--muted); font-size: 12px; line-height: 1.8; }
+.qr-tools { display: flex; align-items: center; gap: 14px; margin-top: 4px; color: var(--muted-2); }
+.qr-tools button { display: inline-flex; min-height: 44px; align-items: center; gap: 5px; padding: 0; border: 0; background: transparent; color: var(--muted); font-size: 12px; cursor: pointer; }
+.qr-tools button:hover { color: var(--mint); }
+.qr-tools .icon { width: 13px; height: 13px; }
+button:disabled { opacity: .45; cursor: not-allowed; }
+.mobile-download-bar { display: none; }
+.download-dialog { width: min(440px, calc(100% - 32px)); max-height: calc(100dvh - 32px); overflow-y: auto; overscroll-behavior: contain; padding: 34px 28px 20px; border-radius: 16px; text-align: center; }
+.download-dialog .eyebrow { margin: 5px 28px 18px; font-size: 10px; }
+.download-dialog h2 { margin-top: 0; font-size: 26px; line-height: 1.35; }
+.download-dialog > p:not(.eyebrow) { font-size: 13px; line-height: 1.8; }
+.dialog-close { top: 8px; right: 8px; width: 44px; height: 44px; border: 0; background: transparent; color: var(--muted); }
+.dialog-qr { margin-top: 20px; }
+.dialog-qr img { width: min(246px, 100%); height: auto; aspect-ratio: 1; margin-inline: auto; border-radius: 10px; background: #fff; }
+.dialog-qr p { margin: 12px 0 0; color: var(--muted); font-size: 12px; line-height: 1.8; }
+.download-dialog .dialog-release { margin: 12px 0 16px; color: var(--mint); font-size: 12px; }
+.dialog-actions { display: grid; gap: 9px; }
+.dialog-actions .button { min-height: 48px; font-size: 14px; }
+.download-dialog .dialog-copy-status { color: var(--mint); font-size: 12px; }
+.dialog-confirm { min-height: 44px; margin-top: 8px; border: 0; background: transparent; color: var(--muted); font-size: 13px; cursor: pointer; }
+.manual-copy { margin-top: 16px; text-align: left; }
+.manual-copy label { display: block; margin-bottom: 8px; color: var(--muted); font-size: 12px; }
+.manual-copy input { width: 100%; min-height: 44px; padding: 10px; border: 1px solid var(--line-strong); border-radius: 6px; background: var(--bg); color: var(--white); font-size: 16px; }
+.download-toast { position: fixed; z-index: 100; right: 20px; bottom: 24px; left: 20px; width: fit-content; max-width: calc(100% - 40px); margin-inline: auto; padding: 12px 18px; border: 1px solid var(--line-strong); border-radius: 10px; background: var(--surface-2); color: var(--white); box-shadow: 0 8px 32px #0006; font-size: 13px; line-height: 1.6; text-align: center; opacity: 0; transform: translateY(8px); transition: opacity .2s, transform .2s; pointer-events: none; }
+.download-toast.visible { opacity: 1; transform: translateY(0); }
+
+/* A mobile composition, with readable product previews and thumb-sized actions. */
+@media (max-width: 760px) {
+  :root { scroll-padding-top: 82px; }
+  html { scrollbar-gutter: auto; }
+  body { padding-bottom: calc(80px + env(safe-area-inset-bottom, 0px)); }
+  .container { width: calc(100% - 40px); }
+  .nav { height: 66px; }
+  .wordmark { gap: 7px; font-size: 21px; }
+  .brand-icon { width: 28px; height: 28px; }
+  .brand-dot { font-size: 9px; }
+  .nav-actions { gap: 8px; }
+  .nav-platform { display: none; }
+  .nav-actions > .button { min-height: 44px; gap: 6px; padding-inline: 12px; font-size: 12px; }
+  .nav-actions > .button .icon { width: 15px; height: 15px; }
+  .menu-toggle { display: inline-flex; width: 44px; height: 44px; }
+  .nav-links { position: absolute; top: 66px; right: 0; left: 0; display: none; max-height: calc(100dvh - 160px); overflow-y: auto; align-items: stretch; flex-direction: column; gap: 0; margin: 0; padding: 12px 20px; border-bottom: 1px solid var(--line-strong); background: var(--bg); box-shadow: 0 16px 24px #0004; font-size: 15px; }
+  .nav-links.open { display: flex; }
+  .nav-links a { display: flex; min-height: 48px; align-items: center; }
+  .hero { padding-top: 54px; }
+  .hero-badge { gap: 8px; padding: 9px 12px; font-size: 11px; }
+  .hero-kicker { margin: 28px 0 20px; font-size: 9px; }
+  .hero h1 { font-size: clamp(56px, 14vw, 88px); letter-spacing: -.085em; line-height: 1.08; }
+  .hero-description { max-width: 430px; margin-top: 24px; font-size: 15px; line-height: 1.95; }
+  .hero-description .desktop-break { display: none; }
+  .hero-actions { width: 100%; gap: 10px; margin-top: 26px; }
+  .hero-actions .button { min-height: 52px; gap: 8px; padding-inline: 16px; font-size: 14px; }
+  .hero-actions .button .icon { width: 17px; height: 17px; }
+  .hero-actions .arrow { display: none; }
+  .hero-footnote { flex-wrap: wrap; justify-content: center; gap: 6px; margin-top: 10px; font-size: 11px; letter-spacing: 0; }
+  .hero-footnote a { gap: 3px; }
+  .product-theater { margin-top: 50px; }
+  .theater-heading { gap: 12px; padding-inline: 0; }
+  .theater-heading > .mono { font-size: 9px; }
+  .theater-heading > span:nth-child(2) { font-size: 11px; }
+  .theater-hint { display: none; }
+  .app-window { border-radius: 12px; }
+  .window-chrome { min-height: 36px; padding-inline: 12px; }
+  .window-address { font-size: 9px; }
+  .window-label { display: none; }
+  .window-dots { gap: 4px; }
+  .window-dots i { width: 5px; height: 5px; }
+  .app-shell { min-height: 430px; grid-template-columns: minmax(0, 1fr); }
+  .app-rail, .app-sidebar, .mock-detail { display: none; }
+  .scene { min-height: 430px; grid-template-columns: minmax(0, 1fr); }
+  .mock-chat { padding: 0 16px 16px; }
+  .mock-page-header { min-height: 62px; }
+  .mock-page-header strong { font-size: 13px; }
+  .mock-page-header span { font-size: 10px; }
+  .mock-chat-body { padding: 14px 0 18px; }
+  .mock-date { margin-bottom: 14px; font-size: 10px; }
+  .user-message { max-width: 92%; padding: 10px 12px; font-size: 12px; }
+  .agent-message { gap: 8px; margin-top: 20px; }
+  .agent-message > .avatar { width: 28px; height: 28px; font-size: 10px; }
+  .agent-copy { font-size: 12px; }
+  .agent-byline { flex-wrap: wrap; gap: 7px; margin-bottom: 8px; font-size: 12px; }
+  .agent-byline span, .agent-byline em { font-size: 9px; }
+  .agent-copy p { margin: 6px 0 10px; }
+  .wide-only { display: none; }
+  .task-trace { gap: 6px; margin: 8px 0; font-size: 11px; }
+  .task-trace em { font-size: 10px; }
+  .trace-icon { width: 15px; height: 15px; }
+  .trace-icon .icon { width: 11px; height: 11px; }
+  .inline-file { gap: 8px; margin-top: 12px; padding: 9px; }
+  .file-badge { width: 28px; height: 32px; }
+  .file-badge .icon { width: 16px; height: 16px; }
+  .inline-file strong { font-size: 11px; }
+  .inline-file small { font-size: 9px; }
+  .mock-composer { min-height: 46px; padding-inline: 10px; font-size: 11px; }
+  .mock-composer > div { gap: 10px; }
+  .composer-agent { font-size: 10px; }
+  .mock-send { width: 26px; height: 26px; }
+  .theater-bottom { align-items: center; flex-direction: column; gap: 12px; padding: 16px 0 0; }
+  .scene-tabs { width: 100%; justify-content: space-between; gap: 2px; padding: 4px; }
+  .scene-tabs button { min-height: 44px; flex: 1; justify-content: center; gap: 5px; padding-inline: 5px; font-size: 12px; white-space: nowrap; }
+  .scene-tabs button .icon { width: 14px; height: 14px; }
+  .demo-caption { font-size: 10px; }
+  .workbench-content, .deliverables-content { padding: 0 14px 18px; }
+  .bench-overview { flex-wrap: wrap; gap: 24px; margin-top: 14px; padding: 14px; }
+  .bench-overview small { font-size: 10px; }
+  .bench-overview b { font-size: 22px; }
+  .bench-overview-tag { width: 100%; gap: 6px; margin: 0; font-size: 10px; }
+  .bench-heading { margin: 18px 0 12px; font-size: 12px; }
+  .bench-heading span + span { font-size: 10px; }
+  .bench-cards { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; }
+  .bench-card { min-height: 174px; padding: 12px; }
+  .bench-card:last-child { display: none; }
+  .bench-card .avatar { width: 28px; height: 28px; font-size: 11px; }
+  .online-label, .offline-label { font-size: 10px; }
+  .bench-card h4 { font-size: 14px; }
+  .bench-card p, .bench-card > small, .bench-action { font-size: 10px; }
+  .bench-action .icon { width: 12px; height: 12px; }
+  .document-layout { grid-template-columns: 1fr; margin-top: 14px; }
+  .document-sidebar { display: none; }
+  .document-preview { min-height: 330px; padding: 24px 20px; }
+  .document-preview .mono { font-size: 10px; }
+  .document-preview h3 { margin: 24px 0; font-size: 25px; }
+  .document-preview p { margin: 16px 0 9px; font-size: 12px; }
+  .document-foot { margin-top: 26px; font-size: 10px; }
+  .manifesto { padding-block: 76px; }
+  .manifesto-label { font-size: 9px; }
+  .manifesto > p { margin-block: 22px; font-size: clamp(22px, 5.8vw, 33px); line-height: 1.65; }
+  .manifesto-bottom { flex-wrap: wrap; gap: 10px; font-size: 12px; }
+  .manifesto-bottom .mono { display: none; }
+  .manifesto-bottom::before, .manifesto-bottom::after { display: none; }
+  .section { padding-block: 64px; }
+  .eyebrow { font-size: 10px; }
+  .section-header { align-items: flex-start; flex-direction: column; gap: 18px; margin-bottom: 28px; }
+  .section-header h2, .faq-intro h2 { margin-top: 18px; font-size: clamp(32px, 8.4vw, 48px); line-height: 1.25; }
+  .section-description { font-size: 14px; line-height: 1.9; }
+  .section-description br { display: none; }
+  .feature-grid { grid-template-columns: 1fr; gap: 16px; }
+  .feature-card { display: grid; min-height: 0; grid-template-columns: minmax(0, .8fr) minmax(0, 1.2fr); grid-template-rows: auto; }
+  .feature-top { top: 16px; right: 16px; left: 16px; }
+  .feature-top > .icon { width: 17px; height: 17px; }
+  .feature-top .mono { display: none; }
+  .conversation-art, .awareness-art, .output-art { min-height: 226px; height: 100%; grid-row: auto; border-right: 1px solid var(--line); border-bottom: 0; }
+  .feature-copy { align-self: center; padding: 22px 16px; }
+  .feature-copy h3 { font-size: 20px; line-height: 1.5; }
+  .feature-copy p { margin-top: 10px; color: var(--muted); font-size: 13px; line-height: 1.9; }
+  .art-chat-row { margin-top: 68px; }
+  .art-chat-row small { font-size: 8px; }
+  .art-chat-row em { display: none; }
+  .art-message { padding: 7px; font-size: 8px; }
+  .art-reply { font-size: 8px; }
+  .radar-label { padding: 6px; font-size: 8px; }
+  .radar-label-one { top: 62px; }
+  .radar-label-two { bottom: 45px; }
+  .output-file { top: 66px; width: 110px; height: 118px; }
+  .output-file.back-file { top: 60px; }
+  .front-file { padding: 11px; }
+  .front-file strong { margin-top: 18px; font-size: 12px; }
+  .output-file-type { font-size: 6px; }
+  .output-file-footer { font-size: 6px; }
+  .mobile-section .container { width: 100%; }
+  .mobile-layout { min-height: 0; grid-template-columns: 1fr; gap: 0; padding-bottom: 24px; }
+  .mobile-copy { padding: 16px 20px 24px; }
+  .mobile-copy h2 { font-size: clamp(36px, 9vw, 52px); }
+  .mobile-description { font-size: 15px; line-height: 1.9; }
+  .mobile-benefits { flex-wrap: wrap; gap: 14px 18px; margin-top: 24px; }
+  .mobile-benefits span { gap: 6px; font-size: 12px; }
+  .mobile-benefits .icon { width: 15px; height: 15px; }
+  .text-link { min-height: 44px; margin-top: 18px; font-size: 14px; }
+  .mobile-copy-foot { margin-top: 14px; font-size: 9px; }
+  .mobile-visual { min-height: 480px; overflow: hidden; }
+  .phone { transform: rotate(-4deg); }
+  .phone-notification { right: calc(50% - 158px); bottom: 40px; width: 240px; transform: rotate(1.8deg); }
+  .mobile-coordinate { font-size: 8px; }
+  .section-header.compact { gap: 14px; margin-bottom: 24px; }
+  .section-header.compact h2 { font-size: clamp(29px, 7.7vw, 44px); }
+  .section-header.compact .section-description { font-size: 14px; }
+  .start-grid { grid-template-columns: 1fr; }
+  .start-grid article { min-height: 126px; grid-template-columns: 40px minmax(0, 1fr) 20px; }
+  .step-number { padding-top: 25px; font-size: 12px; }
+  .start-grid h3 { font-size: 16px; }
+  .start-grid p { font-size: 13px; line-height: 1.85; }
+  .step-arrow { width: 17px; height: 17px; }
+  .download-section { padding-bottom: 72px; }
+  .download-card { grid-template-columns: minmax(0, 1fr); gap: 0; border-radius: 14px; }
+  .download-copy { padding: 30px 22px 24px; }
+  .download-copy .eyebrow { font-size: 10px; }
+  .download-copy h2 { margin: 20px 0 16px; font-size: clamp(29px, 7.9vw, 44px); line-height: 1.28; }
+  .download-description { font-size: 14px; }
+  .download-cta { display: grid; grid-template-columns: 1fr; gap: 10px; margin-top: 24px; }
+  .download-cta .button { min-height: 50px; font-size: 14px; }
+  .download-cta .button .icon { width: 18px; height: 18px; }
+  .download-status { align-items: flex-start; margin-top: 18px; font-size: 12px; }
+  .download-status i { margin-top: 8px; }
+  .release-meta, .install-hint { font-size: 12px; }
+  .download-qr { margin: 0 22px; padding: 26px 0 20px; border-top: 1px solid var(--line-strong); }
+  .qr-eyebrow { font-size: 9px; }
+  .download-qr h3 { font-size: 16px; }
+  .qr-instruction, .qr-tools button { font-size: 12px; }
+  .faq-section { grid-template-columns: 1fr; gap: 26px; padding-top: 0; }
+  .faq-intro > p:last-child { margin-top: 18px; font-size: 14px; }
+  .faq-list summary { min-height: 68px; gap: 15px; font-size: 15px; line-height: 1.6; }
+  .faq-list summary .icon { width: 17px; height: 17px; flex: none; }
+  .faq-list details p { font-size: 14px; line-height: 1.9; }
+  .footer-cta { grid-template-columns: 1fr; gap: 26px; min-height: 0; padding-block: 64px; }
+  .footer-cta-copy .eyebrow { font-size: 9px; }
+  .footer-cta-copy h2 { font-size: clamp(48px, 12vw, 76px); }
+  .footer-cta-copy > p:last-child { font-size: 14px; }
+  .footer-cta-button { justify-self: start; min-height: 52px; font-size: 14px; }
+  .footer-links { grid-template-columns: 1fr 1fr; gap: 26px; padding-block: 36px; }
+  .footer-brand, .footer-note { grid-column: 1 / -1; }
+  .footer-brand .wordmark { font-size: 22px; }
+  .footer-brand p, .footer-note { font-size: 13px; }
+  .footer-link-group { gap: 0; }
+  .footer-link-group > span { margin-bottom: 10px; font-size: 11px; }
+  .footer-link-group a { display: flex; min-height: 44px; align-items: center; font-size: 14px; }
+  .footer-bottom { align-items: flex-start; flex-direction: column; gap: 10px; font-size: 11px; }
+  .footer-bottom .mono { font-size: 9px; }
+  .footer-back { min-height: 44px; font-size: 12px; }
+  .footer-wordmark { margin-top: 10px; }
+  .mobile-download-bar { position: fixed; z-index: 45; right: 0; bottom: 0; left: 0; display: grid; grid-template-columns: minmax(100px, .8fr) minmax(0, 1.5fr); gap: 10px; padding: 12px max(16px, env(safe-area-inset-right, 0px)) calc(12px + env(safe-area-inset-bottom, 0px)) max(16px, env(safe-area-inset-left, 0px)); border-top: 1px solid var(--line-strong); background: #0b100eee; backdrop-filter: blur(20px); }
+  .mobile-download-bar .button { min-height: 48px; gap: 8px; padding-inline: 10px; font-size: 14px; }
+  .mobile-download-bar .icon { width: 17px; height: 17px; }
+  .download-toast { bottom: calc(92px + env(safe-area-inset-bottom, 0px)); }
+}
+@media (max-width: 360px) {
+  .container { width: calc(100% - 32px); }
+  .hero-actions .button { gap: 6px; padding-inline: 12px; font-size: 13px; }
+  .hero-footnote { gap: 4px; font-size: 10px; }
+  .scene-tabs button { gap: 4px; font-size: 11px; }
+  .feature-card { grid-template-columns: minmax(0, .7fr) minmax(0, 1.3fr); }
+  .feature-copy { padding-inline: 12px; }
+  .feature-copy h3 { font-size: 18px; }
+  .feature-copy p { font-size: 12px; }
+  .download-copy { padding-inline: 18px; }
+  .download-qr { margin-inline: 18px; }
+  .hero-footnote .footnote-divider { margin-inline: 1px; }
+  .theater-heading > span:nth-child(2) { font-size: 10px; }
+  .download-dialog { padding: 30px 18px 16px; }
+  .download-dialog h2 { font-size: 23px; }
+  .mobile-download-bar .button { font-size: 13px; }
+}

+ 147 - 13
prototypes/fmode-download-20261120/site.js

@@ -1,5 +1,5 @@
 // 填入 apkUrl 即可开放下载;版本信息等字段按需提供。channel 为渠道标注(如「测试版」),可空。
-const FMODE_SITE = { apkUrl: 'https://ai.fmode.cn/download/fmode-app-v1.0.3.apk', version: '1.0.3', fileSize: '13.5 MB', updatedAt: '2026-11-23', channel: '测试版' };
+const FMODE_SITE = { apkUrl: 'https://ai.fmode.cn/download/fmode-app-v1.0.apk', version: '1.0', fileSize: '9.9 MB', updatedAt: '2026-11-25', channel: '测试版' };
 const header = document.getElementById('header');
 const menuToggle = document.getElementById('menuToggle');
 const navLinks = document.getElementById('navLinks');
@@ -19,6 +19,12 @@ navLinks.querySelectorAll('a').forEach((link) => link.addEventListener('click',
 document.addEventListener('keydown', (event) => {
   if (event.key === 'Escape' && navLinks.classList.contains('open')) { setMenuOpen(false); menuToggle.focus(); }
 });
+document.addEventListener('click', (event) => {
+  if (!event.composedPath().includes(header) && navLinks.classList.contains('open')) setMenuOpen(false);
+});
+window.matchMedia('(min-width: 761px)').addEventListener('change', (event) => {
+  if (event.matches) setMenuOpen(false);
+});
 
 let scrollQueued = false;
 window.addEventListener('scroll', () => {
@@ -56,36 +62,164 @@ tabButtons.forEach((tab, index) => {
 
 const closeButton = document.getElementById('dialogClose');
 const confirmButton = document.getElementById('dialogConfirm');
-function closeDownloadDialog() { if (downloadDialog.open) downloadDialog.close(); apkButton.focus(); }
+const dialogTitle = document.getElementById('dialogTitle');
+const dialogDescription = document.getElementById('dialogDescription');
+const dialogQr = document.getElementById('dialogQr');
+const dialogDownload = document.querySelector('[data-dialog-download]');
+const manualCopy = document.getElementById('manualCopy');
+const downloadLink = document.getElementById('downloadLink');
+const dialogCopyStatus = document.getElementById('dialogCopyStatus');
+let dialogTrigger = null;
+let previousOverflow = '';
+let qrReady = false;
+const isIOS = /iPad|iPhone|iPod/i.test(navigator.userAgent) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
+const isEmbeddedBrowser = /MicroMessenger|\bQQ\//i.test(navigator.userAgent);
+
+function openDownloadDialog(trigger, mode = 'qr') {
+  setMenuOpen(false);
+  manualCopy.hidden = true;
+  dialogCopyStatus.hidden = true;
+  dialogQr.hidden = !qrReady;
+  dialogDownload.hidden = !downloadUrl || mode === 'ios' || mode === 'browser';
+  if (!downloadUrl) {
+    dialogTitle.textContent = '安装包正在准备中';
+    dialogDescription.textContent = '下载暂未开放,请稍后再来。正式安装包就绪后,二维码与下载入口会同时开放。';
+  } else if (mode === 'ios') {
+    dialogTitle.textContent = '当前提供 Android 版';
+    dialogDescription.textContent = '此 APK 无法在 iPhone 或 iPad 上安装。你可以保存二维码或复制链接,发送到 Android 设备下载。';
+  } else if (mode === 'browser') {
+    dialogTitle.textContent = '请在浏览器中打开下载';
+    dialogDescription.textContent = '点击右上角「…」,选择「在浏览器打开」,再点击下载。也可以复制链接,粘贴到手机浏览器中打开。';
+  } else {
+    dialogTitle.textContent = qrReady ? '扫码,把想法带在身边。' : '直接下载,同样方便。';
+    dialogDescription.textContent = qrReady ? '使用 Android 手机相机扫码,即可获取安装包。微信扫码后请在浏览器中打开。' : '二维码暂时无法生成,你仍可点击下载或复制安装包链接。';
+  }
+  if (!downloadDialog.open) {
+    dialogTrigger = trigger || document.activeElement;
+    previousOverflow = document.documentElement.style.overflow;
+    document.documentElement.style.overflow = 'hidden';
+    downloadDialog.showModal();
+    closeButton.focus();
+  }
+}
+function closeDownloadDialog() { if (downloadDialog.open) downloadDialog.close(); }
 closeButton.addEventListener('click', closeDownloadDialog);
 confirmButton.addEventListener('click', closeDownloadDialog);
-downloadDialog.addEventListener('click', (event) => { if (event.target === downloadDialog) closeDownloadDialog(); });
+downloadDialog.addEventListener('close', () => {
+  document.documentElement.style.overflow = previousOverflow;
+  if (dialogTrigger?.isConnected) dialogTrigger.focus({ preventScroll: true });
+});
+downloadDialog.addEventListener('click', (event) => {
+  const bounds = downloadDialog.getBoundingClientRect();
+  if (event.target === downloadDialog && (event.clientX < bounds.left || event.clientX > bounds.right || event.clientY < bounds.top || event.clientY > bounds.bottom)) closeDownloadDialog();
+});
 
 function safeDownloadUrl(value) {
-  if (!value) return null;
+  if (typeof value !== 'string' || !value.trim()) return null;
   try {
-    const url = new URL(value, window.location.href);
-    if (url.protocol === 'https:' || (url.protocol === 'file:' && value.startsWith('./'))) return url.href;
+    const raw = value.trim();
+    if (/[\u0000-\u0020\\]/.test(raw) || raw.startsWith('//')) return null;
+    const url = new URL(raw, window.location.href);
+    if (url.username || url.password) return null;
+    if (url.protocol === 'https:') return url.href;
+    const relative = !/^[a-z][a-z\d+.-]*:/i.test(raw);
+    if (relative && url.origin === window.location.origin && ['http:', 'file:'].includes(url.protocol)) return url.href;
   } catch { return null; }
   return null;
 }
 const downloadUrl = safeDownloadUrl(FMODE_SITE.apkUrl);
+const downloadButtons = [...document.querySelectorAll('[data-download]')];
+downloadButtons.forEach((button) => {
+  if (downloadUrl) {
+    button.href = downloadUrl;
+    button.setAttribute('download', 'Fmode.apk');
+  }
+  button.addEventListener('click', (event) => {
+    const mode = !downloadUrl ? 'unavailable' : isIOS ? 'ios' : isEmbeddedBrowser ? 'browser' : null;
+    if (mode) { event.preventDefault(); openDownloadDialog(button, mode); }
+  });
+});
+document.querySelectorAll('[data-show-qr]').forEach((button) => {
+  button.addEventListener('click', () => openDownloadDialog(button, isIOS ? 'ios' : 'qr'));
+});
+
+function createQrImage(value) {
+  const qr = qrcodegen.QrCode.encodeText(value, qrcodegen.QrCode.Ecc.MEDIUM);
+  const scale = 6;
+  const border = 4;
+  const image = document.createElement('canvas');
+  image.width = image.height = (qr.size + border * 2) * scale;
+  const drawing = image.getContext('2d');
+  if (!drawing) throw new Error('QR drawing unavailable');
+  drawing.fillStyle = '#ffffff';
+  drawing.fillRect(0, 0, image.width, image.height);
+  drawing.fillStyle = '#080b0c';
+  for (let y = 0; y < qr.size; y++) {
+    for (let x = 0; x < qr.size; x++) {
+      if (qr.getModule(x, y)) drawing.fillRect((x + border) * scale, (y + border) * scale, scale, scale);
+    }
+  }
+  return image.toDataURL('image/png');
+}
+
 if (downloadUrl) {
-  apkButton.href = downloadUrl;
   apkButton.removeAttribute('aria-describedby');
-  apkButton.setAttribute('download', 'Fmode.apk');
-  document.getElementById('downloadLabel').textContent = '下载 Android 安装包';
   downloadStatus.classList.add('ready');
-  downloadStatus.innerHTML = '<i></i>官方 Android 安装包' + (FMODE_SITE.channel ? '(' + FMODE_SITE.channel + ')' : '') + ' · 下载已开放';
+  downloadStatus.replaceChildren(document.createElement('i'), document.createTextNode('官方 Android 安装包' + (FMODE_SITE.channel ? '(' + FMODE_SITE.channel + ')' : '') + ' · 下载已开放'));
   const metadata = [FMODE_SITE.version && '版本 ' + FMODE_SITE.version, FMODE_SITE.fileSize, FMODE_SITE.updatedAt && '更新于 ' + FMODE_SITE.updatedAt].filter(Boolean);
-  if (metadata.length) { releaseMeta.hidden = false; releaseMeta.textContent = metadata.join(' · '); }
+  if (metadata.length) { releaseMeta.hidden = false; releaseMeta.textContent = metadata.join(' · '); }
+  document.querySelector('[data-release-detail]').textContent = [FMODE_SITE.version && 'v' + FMODE_SITE.version, FMODE_SITE.fileSize, FMODE_SITE.channel].filter(Boolean).join(' · ');
+  document.querySelector('[data-release-short]').textContent = [FMODE_SITE.version && 'v' + FMODE_SITE.version, FMODE_SITE.channel].filter(Boolean).join(' · ') || 'Android 版';
+  downloadLink.value = downloadUrl;
+  document.querySelectorAll('[data-copy-link]').forEach((button) => { button.disabled = false; });
+  try {
+    const imageUrl = createQrImage(downloadUrl);
+    document.querySelectorAll('[data-qr-image]').forEach((image) => { image.src = imageUrl; image.hidden = false; });
+    document.querySelector('[data-qr-placeholder]').hidden = true;
+    qrReady = true;
+  } catch {
+    document.querySelector('[data-qr-placeholder]').textContent = '二维码暂时不可用';
+    document.querySelector('.qr-instruction').textContent = '可直接下载,或复制链接到 Android 手机';
+  }
   const heroBadge = document.querySelector('.hero-badge');
   heroBadge.replaceChildren(Object.assign(document.createElement('span'), { className: 'tiny-dot' }), document.createTextNode('Android 客户端现已开放下载'));
   document.querySelector('.nav-platform').setAttribute('aria-label', 'Android 版现已开放下载');
-  document.getElementById('faqDownloadAnswer').textContent = 'Android 客户端现已开放下载。使用手机访问本页,点击下载按钮即可获取安装包;如在电脑访问,可将下载后的 APK 传至 Android 设备安装。';
+  document.getElementById('faqDownloadAnswer').textContent = '可以。Android 手机可点击「下载 Android 版」直接获取安装包;电脑用户可使用 Android 手机扫描下载二维码。微信或 QQ 内请从右上角菜单选择在浏览器中打开。当前 APK 不支持 iPhone 或 iPad 安装。';
+  if (isIOS || isEmbeddedBrowser) document.querySelector('[data-install-hint]').textContent = isIOS ? '你正在使用 iOS 设备,当前 APK 仅支持 Android。可将二维码或链接分享给 Android 设备。' : '微信 / QQ 内可能无法直接下载。请点击右上角「…」,选择在浏览器中打开。';
 } else {
-  apkButton.addEventListener('click', (event) => { event.preventDefault(); downloadDialog.showModal(); closeButton.focus(); });
+  document.querySelector('[data-qr-placeholder]').textContent = '下载开放后显示二维码';
+  document.querySelector('.qr-instruction').textContent = '安装包准备中,请稍后再来';
+  document.querySelector('[data-release-short]').textContent = '即将开放';
+  document.querySelector('[data-install-hint]').hidden = true;
+  document.querySelector('.nav-platform').setAttribute('aria-label', 'Android 版即将开放下载');
+}
+
+let toastTimer;
+function showDownloadToast(message) {
+  const toast = document.getElementById('downloadToast');
+  clearTimeout(toastTimer);
+  toast.textContent = message;
+  toast.classList.add('visible');
+  toastTimer = setTimeout(() => toast.classList.remove('visible'), 3200);
 }
+document.querySelectorAll('[data-copy-link]').forEach((button) => button.addEventListener('click', async () => {
+  if (!downloadUrl) return;
+  try {
+    if (!navigator.clipboard?.writeText) throw new Error('Clipboard unavailable');
+    await navigator.clipboard.writeText(downloadUrl);
+    const message = '下载链接已复制,可发送到 Android 手机';
+    if (downloadDialog.open) {
+      dialogCopyStatus.textContent = message;
+      dialogCopyStatus.hidden = false;
+    } else showDownloadToast(message);
+  } catch {
+    openDownloadDialog(button);
+    manualCopy.hidden = false;
+    downloadLink.focus();
+    downloadLink.select();
+    showDownloadToast('请长按或选中下载链接,手动复制');
+  }
+}));
 
 const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
 if ('IntersectionObserver' in window && !reduceMotion.matches) {

+ 40 - 5
prototypes/fmode-download-20261120/site.template.html

@@ -18,6 +18,8 @@
     <symbol id="i-arrow" viewBox="0 0 24 24"><path d="M5 12h14m-6-6 6 6-6 6"/></symbol>
     <symbol id="i-diagonal" viewBox="0 0 24 24"><path d="M6 18 18 6M6 6h12v12"/></symbol>
     <symbol id="i-down" viewBox="0 0 24 24"><path d="M12 3v12m-5-5 5 5 5-5M5 17v4h14v-4"/></symbol>
+    <symbol id="i-qr" viewBox="0 0 24 24"><path d="M3 3h6v6H3zM15 3h6v6h-6zM3 15h6v6H3zM15 15h2v2h-2zM19 13h2v4M13 19h4v2M19 19h2v2M3 12h6M12 3v6M12 12h4M12 15v2"/></symbol>
+    <symbol id="i-copy" viewBox="0 0 24 24"><rect x="8" y="8" width="12" height="13" rx="2"/><path d="M16 8V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h3"/></symbol>
     <symbol id="i-chat" viewBox="0 0 24 24"><path d="M5 4h14a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2H9l-6 3V6a2 2 0 0 1 2-2Z"/><path d="M7 9h10M7 13h6"/></symbol>
     <symbol id="i-grid" viewBox="0 0 24 24"><rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/></symbol>
     <symbol id="i-people" viewBox="0 0 24 24"><circle cx="9" cy="8" r="3"/><path d="M3 21v-3a6 6 0 0 1 12 0v3M16 5a3 3 0 0 1 0 6m2 3a5 5 0 0 1 3 4v3"/></symbol>
@@ -41,7 +43,7 @@
     <nav class="container nav" aria-label="主导航">
       <a class="wordmark" href="#top" aria-label="Fmode 首页"><span class="brand-icon" aria-hidden="true"><svg viewBox="0 0 32 32"><path d="M8 25V7h17v5H13v3h9v5h-9v5Z"/></svg></span>fmode<span class="brand-dot">®</span></a>
       <div class="nav-links" id="navLinks"><a href="#experience">产品体验</a><a href="#capabilities">核心能力</a><a href="#download">客户端下载</a><a href="#faq">常见问题</a></div>
-      <div class="nav-actions"><a class="nav-platform" href="#download"><span class="tiny-dot"></span>Android</a><a class="button button-small" href="#download">获取 Fmode <svg class="icon"><use href="#i-diagonal"/></svg></a><button class="menu-toggle icon-button" id="menuToggle" aria-label="展开导航" aria-expanded="false" aria-controls="navLinks"><svg class="icon"><use href="#i-menu"/></svg></button></div>
+      <div class="nav-actions"><a class="nav-platform" href="#download"><span class="tiny-dot"></span>Android</a><a class="button button-small" href="#download" data-download>下载 Fmode <svg class="icon"><use href="#i-down"/></svg></a><button type="button" class="menu-toggle icon-button" id="menuToggle" aria-label="展开导航" aria-expanded="false" aria-controls="navLinks"><svg class="icon"><use href="#i-menu"/></svg></button></div>
     </nav>
   </header>
 
@@ -53,8 +55,8 @@
         <p class="hero-kicker mono">YOUR NEXT CHAPTER OF WORK</p>
         <h1 id="heroTitle">把想法,<br><span>推进现实。</span></h1>
         <p class="hero-description">不止聊一聊。和你的数字生命一起,<br class="desktop-break">接续每段对话,看见每步进展,让想法落地。</p>
-        <div class="hero-actions"><a class="button" href="#download"><svg class="icon"><use href="#i-android"/></svg>获取 Android 版 <svg class="icon arrow"><use href="#i-arrow"/></svg></a><a class="button button-secondary" href="#experience">探索工作空间 <svg class="icon"><use href="#i-arrow"/></svg></a></div>
-        <p class="hero-footnote"><span></span>为专注而设计,为行动而生<span></span></p>
+        <div class="hero-actions"><a class="button" href="#download" data-download><svg class="icon"><use href="#i-android"/></svg>下载 Android 版 <svg class="icon arrow"><use href="#i-down"/></svg></a><button type="button" class="button button-secondary" data-show-qr aria-haspopup="dialog" aria-controls="downloadDialog"><svg class="icon"><use href="#i-qr"/></svg>扫码下载</button></div>
+        <p class="hero-footnote">Android 安装包 · <span data-release-short>测试版</span><span class="footnote-divider">/</span><a href="#experience">探索工作空间 <svg class="icon"><use href="#i-arrow"/></svg></a></p>
       </div>
 
       <div class="container product-theater" id="experience">
@@ -109,14 +111,47 @@
 
     <section class="start-section section container" aria-labelledby="startTitle"><div class="section-header compact"><div><p class="eyebrow mono">FROM IDEA TO ACTION</p><h2 id="startTitle">下一步,其实很简单。</h2></div><span class="section-description">从一次对话,开启一种新的工作方式。</span></div><div class="start-grid"><article><span class="step-number mono">01</span><div><h3>获取客户端</h3><p>在 Android 手机上安装 Fmode,<br>登录你的协作空间。</p></div><svg class="icon step-arrow"><use href="#i-arrow"/></svg></article><article><span class="step-number mono">02</span><div><h3>找到你的伙伴</h3><p>通过通讯录与工作台,<br>找到适合当前工作的数字生命。</p></div><svg class="icon step-arrow"><use href="#i-arrow"/></svg></article><article><span class="step-number mono">03</span><div><h3>从想法,走向行动</h3><p>说清楚你想做的事,<br>在对话中一起把它往前推进。</p></div><svg class="icon step-arrow"><use href="#i-diagonal"/></svg></article></div></section>
 
-    <section class="download-section container" id="download" aria-labelledby="downloadTitle"><div class="download-card"><div class="download-lines" aria-hidden="true"></div><div class="download-copy"><p class="eyebrow mono"><svg class="icon"><use href="#i-android"/></svg> FMODE FOR ANDROID</p><h2 id="downloadTitle">下一种可能,<br>现在,就在你手中。</h2><p class="download-description">和你的数字生命,开始下一段协作。</p><div class="download-cta"><a class="button" id="apkButton" href="#download" aria-describedby="downloadStatus"><svg class="icon"><use href="#i-down"/></svg><span id="downloadLabel">获取 Android 安装包</span><svg class="icon arrow"><use href="#i-arrow"/></svg></a><span class="download-format mono">ANDROID / APK</span></div><p class="download-status" id="downloadStatus"><i></i>下载地址待接入,开放后可从这里获取 APK。</p><p class="release-meta" id="releaseMeta" hidden></p></div><div class="download-art" aria-hidden="true"><div class="download-art-ring"></div><div class="download-app-icon"><svg viewBox="0 0 100 100"><path d="M28 75V25h47v14H42v8h25v14H42v14Z"/></svg></div><span class="download-art-label mono">MAKE ROOM FOR<br>WHAT'S POSSIBLE.</span><span class="download-art-cross cross-top">+</span><span class="download-art-cross cross-bottom">+</span></div></div></section>
+    <section class="download-section container" id="download" aria-labelledby="downloadTitle">
+      <div class="download-card">
+        <div class="download-lines" aria-hidden="true"></div>
+        <div class="download-copy">
+          <p class="eyebrow mono"><svg class="icon"><use href="#i-android"/></svg> FMODE FOR ANDROID</p>
+          <h2 id="downloadTitle">下一种可能,<br>现在,就在你手中。</h2>
+          <p class="download-description">手机直接下载,电脑扫码获取。<br>和你的数字生命,开始下一段协作。</p>
+          <div class="download-cta"><a class="button" id="apkButton" href="#download" data-download aria-describedby="downloadStatus"><svg class="icon"><use href="#i-down"/></svg><span id="downloadLabel">下载 Android 安装包</span></a><button type="button" class="button button-secondary" data-show-qr aria-haspopup="dialog" aria-controls="downloadDialog"><svg class="icon"><use href="#i-qr"/></svg>扫码下载</button></div>
+          <p class="download-status" id="downloadStatus"><i></i>下载地址待接入,开放后可从这里获取 APK。</p>
+          <p class="release-meta" id="releaseMeta" hidden></p>
+          <p class="install-hint" data-install-hint>仅适用于 Android 设备。微信内请使用浏览器打开后下载。</p>
+        </div>
+        <aside class="download-qr" aria-labelledby="qrCardTitle">
+          <p class="qr-eyebrow mono">SCAN. INSTALL. LET'S GO.</p>
+          <button type="button" class="qr-image-button" data-show-qr aria-label="放大 Android 下载二维码" aria-haspopup="dialog" aria-controls="downloadDialog"><img data-qr-image width="222" height="222" alt="Fmode Android 安装包下载二维码" hidden><span data-qr-placeholder>二维码准备中</span></button>
+          <h3 id="qrCardTitle">扫一扫,把协作装进口袋。</h3>
+          <p class="qr-instruction">使用 Android 手机相机扫码下载</p>
+          <div class="qr-tools"><button type="button" data-show-qr>放大二维码 <svg class="icon"><use href="#i-diagonal"/></svg></button><span aria-hidden="true">/</span><button type="button" data-copy-link disabled><svg class="icon"><use href="#i-copy"/></svg>复制链接</button></div>
+        </aside>
+      </div>
+    </section>
 
     <section class="faq-section section container" id="faq" aria-labelledby="faqTitle"><div class="faq-intro"><p class="eyebrow mono">A FEW MORE THINGS</p><h2 id="faqTitle">还有一些,<br><span>你可能想知道的。</span></h2><p>关于 Fmode,与新的开始。</p></div><div class="faq-list"><details><summary>Fmode 可以帮我做什么?<svg class="icon"><use href="#i-plus"/></svg></summary><p>Fmode 把你与数字生命的会话、通讯录和工作台放在同一个空间。你可以在会话里讨论工作,在工作台查看伙伴状态,并通过会话详情回看文件与成果。</p></details><details><summary>现在可以下载 Android 版吗?<svg class="icon"><use href="#i-plus"/></svg></summary><p id="faqDownloadAnswer">当前页面已预留 APK 下载入口,下载链接尚未接入。正式地址就绪后,可通过本页直接获取安装包。</p></details><details><summary>电脑上也能了解产品吗?<svg class="icon"><use href="#i-plus"/></svg></summary><p>可以。上方的产品展示可以切换查看专注对话、全局工作台与成果回看。界面中的人物、状态及内容均为示意,实际体验以客户端为准。</p></details><details><summary>安装后如何开始?<svg class="icon"><use href="#i-plus"/></svg></summary><p>安装并登录后,通过通讯录或工作台找到你可以使用的数字生命,打开会话,写下你的想法即可开始。可访问的内容由你的账户权限决定。</p></details></div></section>
   </main>
 
   <footer class="site-footer"><div class="footer-cta container"><div class="footer-cta-copy"><p class="eyebrow mono"><span class="tiny-dot"></span> YOUR NEXT CHAPTER STARTS HERE</p><h2>让下一步,<br><span>现在发生。</span></h2><p>把想法带进协作,让每一份灵感都有回应。</p></div><a class="button footer-cta-button" href="#download"><svg class="icon"><use href="#i-android"/></svg>探索 Fmode Android <svg class="icon arrow"><use href="#i-arrow"/></svg></a><span class="footer-cta-orbit" aria-hidden="true"></span></div><div class="container footer-links"><div class="footer-brand"><a class="wordmark" href="#top"><span class="brand-icon" aria-hidden="true"><svg viewBox="0 0 32 32"><path d="M8 25V7h17v5H13v3h9v5h-9v5Z"/></svg></span>fmode</a><p>与数字生命一起,<br>让想法向前。</p></div><div class="footer-link-group"><span>探索 Fmode</span><a href="#experience">产品体验</a><a href="#capabilities">核心能力</a><a href="#download">客户端下载</a></div><div class="footer-link-group"><span>开始使用</span><a href="#download">获取 Android 版</a><a href="#faq">常见问题</a><a href="#top">回到页面顶部</a></div><div class="footer-note"><span class="tiny-dot"></span><span>为新的可能而构建。<br><small>HUMAN × DIGITAL LIFE</small></span></div></div><div class="container footer-bottom"><span>© 2026 Fmode. All rights reserved.</span><span class="mono">MADE FOR WHAT'S NEXT</span><a class="footer-back" href="#top">回到顶部 <svg class="icon"><use href="#i-diagonal"/></svg></a></div><div class="footer-wordmark container" aria-hidden="true">fmode<span>®</span></div></footer>
 
-  <dialog class="download-dialog" id="downloadDialog" aria-labelledby="dialogTitle" aria-describedby="dialogDescription"><button class="dialog-close icon-button" id="dialogClose" aria-label="关闭下载提示"><svg class="icon"><use href="#i-close"/></svg></button><span class="dialog-symbol"><svg class="icon"><use href="#i-down"/></svg></span><p class="eyebrow mono">A NEW CHAPTER, SOON.</p><h2 id="dialogTitle">精彩,即将开启。</h2><p id="dialogDescription">Android 安装包下载链接正在准备中。<br>地址接入后,就可以从这里获取 Fmode。</p><button class="button" id="dialogConfirm">期待下一步 <svg class="icon"><use href="#i-arrow"/></svg></button><span class="dialog-foot mono">FMODE / ANDROID</span></dialog>
+  <nav class="mobile-download-bar" aria-label="客户端下载快捷入口"><button type="button" class="button button-secondary" data-show-qr aria-haspopup="dialog" aria-controls="downloadDialog"><svg class="icon"><use href="#i-qr"/></svg>扫码下载</button><a class="button" href="#download" data-download><svg class="icon"><use href="#i-android"/></svg>下载 Android 版 <svg class="icon"><use href="#i-down"/></svg></a></nav>
+  <dialog class="download-dialog" id="downloadDialog" aria-labelledby="dialogTitle" aria-describedby="dialogDescription">
+    <button type="button" class="dialog-close icon-button" id="dialogClose" aria-label="关闭下载窗口" autofocus><svg class="icon"><use href="#i-close"/></svg></button>
+    <p class="eyebrow mono">FMODE / ANDROID</p>
+    <h2 id="dialogTitle">扫码,把想法带在身边。</h2>
+    <p id="dialogDescription">使用 Android 手机相机扫码,即可获取安装包。</p>
+    <div class="dialog-qr" id="dialogQr" hidden><img data-qr-image width="246" height="246" alt="扫描此二维码下载 Fmode Android 安装包" hidden><p>可长按二维码保存,或复制链接分享。</p></div>
+    <p class="dialog-release" data-release-detail></p>
+    <div class="dialog-actions"><a class="button" href="#download" data-download data-dialog-download><svg class="icon"><use href="#i-down"/></svg>直接下载安装包</a><button type="button" class="button button-secondary" data-copy-link disabled><svg class="icon"><use href="#i-copy"/></svg>复制下载链接</button></div>
+    <p class="dialog-copy-status" id="dialogCopyStatus" role="status" aria-live="polite" hidden></p>
+    <div class="manual-copy" id="manualCopy" hidden><label for="downloadLink">长按或选中以下链接复制</label><input id="downloadLink" type="url" readonly spellcheck="false" aria-label="Android 安装包下载链接"></div>
+    <button type="button" class="dialog-confirm" id="dialogConfirm">返回浏览</button>
+  </dialog>
+  <div class="download-toast" id="downloadToast" role="status" aria-live="polite" aria-atomic="true"></div>
   <script>/* INJECT_SCRIPT */</script>
 </body>
 </html>

+ 838 - 0
prototypes/fmode-download-20261120/vendor/qrcodegen.js

@@ -0,0 +1,838 @@
+// Vendored from https://raw.githubusercontent.com/nayuki/QR-Code-generator/v1.8.0/typescript-javascript/qrcodegen.ts
+/*
+ * QR Code generator library (TypeScript)
+ *
+ * Copyright (c) Project Nayuki. (MIT License)
+ * https://www.nayuki.io/page/qr-code-generator-library
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of
+ * this software and associated documentation files (the "Software"), to deal in
+ * the Software without restriction, including without limitation the rights to
+ * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+ * the Software, and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ * - The above copyright notice and this permission notice shall be included in
+ *   all copies or substantial portions of the Software.
+ * - The Software is provided "as is", without warranty of any kind, express or
+ *   implied, including but not limited to the warranties of merchantability,
+ *   fitness for a particular purpose and noninfringement. In no event shall the
+ *   authors or copyright holders be liable for any claim, damages or other
+ *   liability, whether in an action of contract, tort or otherwise, arising from,
+ *   out of or in connection with the Software or the use or other dealings in the
+ *   Software.
+ */
+"use strict";
+var qrcodegen;
+(function (qrcodegen) {
+    /*---- QR Code symbol class ----*/
+    /*
+     * A QR Code symbol, which is a type of two-dimension barcode.
+     * Invented by Denso Wave and described in the ISO/IEC 18004 standard.
+     * Instances of this class represent an immutable square grid of dark and light cells.
+     * The class provides static factory functions to create a QR Code from text or binary data.
+     * The class covers the QR Code Model 2 specification, supporting all versions (sizes)
+     * from 1 to 40, all 4 error correction levels, and 4 character encoding modes.
+     *
+     * Ways to create a QR Code object:
+     * - High level: Take the payload data and call QrCode.encodeText() or QrCode.encodeBinary().
+     * - Mid level: Custom-make the list of segments and call QrCode.encodeSegments().
+     * - Low level: Custom-make the array of data codeword bytes (including
+     *   segment headers and final padding, excluding error correction codewords),
+     *   supply the appropriate version number, and call the QrCode() constructor.
+     * (Note that all ways require supplying the desired error correction level.)
+     */
+    class QrCode {
+        /*-- Static factory functions (high level) --*/
+        // Returns a QR Code representing the given Unicode text string at the given error correction level.
+        // As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer
+        // Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible
+        // QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the
+        // ecl argument if it can be done without increasing the version.
+        static encodeText(text, ecl) {
+            const segs = qrcodegen.QrSegment.makeSegments(text);
+            return QrCode.encodeSegments(segs, ecl);
+        }
+        // Returns a QR Code representing the given binary data at the given error correction level.
+        // This function always encodes using the binary segment mode, not any text mode. The maximum number of
+        // bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.
+        // The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.
+        static encodeBinary(data, ecl) {
+            const seg = qrcodegen.QrSegment.makeBytes(data);
+            return QrCode.encodeSegments([seg], ecl);
+        }
+        /*-- Static factory functions (mid level) --*/
+        // Returns a QR Code representing the given segments with the given encoding parameters.
+        // The smallest possible QR Code version within the given range is automatically
+        // chosen for the output. Iff boostEcl is true, then the ECC level of the result
+        // may be higher than the ecl argument if it can be done without increasing the
+        // version. The mask number is either between 0 to 7 (inclusive) to force that
+        // mask, or -1 to automatically choose an appropriate mask (which may be slow).
+        // This function allows the user to create a custom sequence of segments that switches
+        // between modes (such as alphanumeric and byte) to encode text in less space.
+        // This is a mid-level API; the high-level API is encodeText() and encodeBinary().
+        static encodeSegments(segs, ecl, minVersion = 1, maxVersion = 40, mask = -1, boostEcl = true) {
+            if (!(QrCode.MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= QrCode.MAX_VERSION)
+                || mask < -1 || mask > 7)
+                throw new RangeError("Invalid value");
+            // Find the minimal version number to use
+            let version;
+            let dataUsedBits;
+            for (version = minVersion;; version++) {
+                const dataCapacityBits = QrCode.getNumDataCodewords(version, ecl) * 8; // Number of data bits available
+                const usedBits = QrSegment.getTotalBits(segs, version);
+                if (usedBits <= dataCapacityBits) {
+                    dataUsedBits = usedBits;
+                    break; // This version number is found to be suitable
+                }
+                if (version >= maxVersion) // All versions in the range could not fit the given data
+                    throw new RangeError("Data too long");
+            }
+            // Increase the error correction level while the data still fits in the current version number
+            for (const newEcl of [QrCode.Ecc.MEDIUM, QrCode.Ecc.QUARTILE, QrCode.Ecc.HIGH]) { // From low to high
+                if (boostEcl && dataUsedBits <= QrCode.getNumDataCodewords(version, newEcl) * 8)
+                    ecl = newEcl;
+            }
+            // Concatenate all segments to create the data bit string
+            let bb = [];
+            for (const seg of segs) {
+                appendBits(seg.mode.modeBits, 4, bb);
+                appendBits(seg.numChars, seg.mode.numCharCountBits(version), bb);
+                for (const b of seg.getData())
+                    bb.push(b);
+            }
+            assert(bb.length == dataUsedBits);
+            // Add terminator and pad up to a byte if applicable
+            const dataCapacityBits = QrCode.getNumDataCodewords(version, ecl) * 8;
+            assert(bb.length <= dataCapacityBits);
+            appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb);
+            appendBits(0, (8 - bb.length % 8) % 8, bb);
+            assert(bb.length % 8 == 0);
+            // Pad with alternating bytes until data capacity is reached
+            for (let padByte = 0xEC; bb.length < dataCapacityBits; padByte ^= 0xEC ^ 0x11)
+                appendBits(padByte, 8, bb);
+            // Pack bits into bytes in big endian
+            let dataCodewords = [];
+            while (dataCodewords.length * 8 < bb.length)
+                dataCodewords.push(0);
+            bb.forEach((b, i) => dataCodewords[i >>> 3] |= b << (7 - (i & 7)));
+            // Create the QR Code object
+            return new QrCode(version, ecl, dataCodewords, mask);
+        }
+        /*-- Constructor (low level) and fields --*/
+        // Creates a new QR Code with the given version number,
+        // error correction level, data codeword bytes, and mask number.
+        // This is a low-level API that most users should not use directly.
+        // A mid-level API is the encodeSegments() function.
+        constructor(
+        // The version number of this QR Code, which is between 1 and 40 (inclusive).
+        // This determines the size of this barcode.
+        version,
+        // The error correction level used in this QR Code.
+        errorCorrectionLevel, dataCodewords, msk) {
+            this.version = version;
+            this.errorCorrectionLevel = errorCorrectionLevel;
+            // The modules of this QR Code (false = light, true = dark).
+            // Immutable after constructor finishes. Accessed through getModule().
+            this.modules = [];
+            // Indicates function modules that are not subjected to masking. Discarded when constructor finishes.
+            this.isFunction = [];
+            // Check scalar arguments
+            if (version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION)
+                throw new RangeError("Version value out of range");
+            if (msk < -1 || msk > 7)
+                throw new RangeError("Mask value out of range");
+            this.size = version * 4 + 17;
+            // Initialize both grids to be size*size arrays of Boolean false
+            let row = [];
+            for (let i = 0; i < this.size; i++)
+                row.push(false);
+            for (let i = 0; i < this.size; i++) {
+                this.modules.push(row.slice()); // Initially all light
+                this.isFunction.push(row.slice());
+            }
+            // Compute ECC, draw modules
+            this.drawFunctionPatterns();
+            const allCodewords = this.addEccAndInterleave(dataCodewords);
+            this.drawCodewords(allCodewords);
+            // Do masking
+            if (msk == -1) { // Automatically choose best mask
+                let minPenalty = 1000000000;
+                for (let i = 0; i < 8; i++) {
+                    this.applyMask(i);
+                    this.drawFormatBits(i);
+                    const penalty = this.getPenaltyScore();
+                    if (penalty < minPenalty) {
+                        msk = i;
+                        minPenalty = penalty;
+                    }
+                    this.applyMask(i); // Undoes the mask due to XOR
+                }
+            }
+            assert(0 <= msk && msk <= 7);
+            this.mask = msk;
+            this.applyMask(msk); // Apply the final choice of mask
+            this.drawFormatBits(msk); // Overwrite old format bits
+            this.isFunction = [];
+        }
+        /*-- Accessor methods --*/
+        // Returns the color of the module (pixel) at the given coordinates, which is false
+        // for light or true for dark. The top left corner has the coordinates (x=0, y=0).
+        // If the given coordinates are out of bounds, then false (light) is returned.
+        getModule(x, y) {
+            return 0 <= x && x < this.size && 0 <= y && y < this.size && this.modules[y][x];
+        }
+        /*-- Private helper methods for constructor: Drawing function modules --*/
+        // Reads this object's version field, and draws and marks all function modules.
+        drawFunctionPatterns() {
+            // Draw horizontal and vertical timing patterns
+            for (let i = 0; i < this.size; i++) {
+                this.setFunctionModule(6, i, i % 2 == 0);
+                this.setFunctionModule(i, 6, i % 2 == 0);
+            }
+            // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
+            this.drawFinderPattern(3, 3);
+            this.drawFinderPattern(this.size - 4, 3);
+            this.drawFinderPattern(3, this.size - 4);
+            // Draw numerous alignment patterns
+            const alignPatPos = this.getAlignmentPatternPositions();
+            const numAlign = alignPatPos.length;
+            for (let i = 0; i < numAlign; i++) {
+                for (let j = 0; j < numAlign; j++) {
+                    // Don't draw on the three finder corners
+                    if (!(i == 0 && j == 0 || i == 0 && j == numAlign - 1 || i == numAlign - 1 && j == 0))
+                        this.drawAlignmentPattern(alignPatPos[i], alignPatPos[j]);
+                }
+            }
+            // Draw configuration data
+            this.drawFormatBits(0); // Dummy mask value; overwritten later in the constructor
+            this.drawVersion();
+        }
+        // Draws two copies of the format bits (with its own error correction code)
+        // based on the given mask and this object's error correction level field.
+        drawFormatBits(mask) {
+            // Calculate error correction code and pack bits
+            const data = this.errorCorrectionLevel.formatBits << 3 | mask; // errCorrLvl is uint2, mask is uint3
+            let rem = data;
+            for (let i = 0; i < 10; i++)
+                rem = (rem << 1) ^ ((rem >>> 9) * 0x537);
+            const bits = (data << 10 | rem) ^ 0x5412; // uint15
+            assert(bits >>> 15 == 0);
+            // Draw first copy
+            for (let i = 0; i <= 5; i++)
+                this.setFunctionModule(8, i, getBit(bits, i));
+            this.setFunctionModule(8, 7, getBit(bits, 6));
+            this.setFunctionModule(8, 8, getBit(bits, 7));
+            this.setFunctionModule(7, 8, getBit(bits, 8));
+            for (let i = 9; i < 15; i++)
+                this.setFunctionModule(14 - i, 8, getBit(bits, i));
+            // Draw second copy
+            for (let i = 0; i < 8; i++)
+                this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i));
+            for (let i = 8; i < 15; i++)
+                this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i));
+            this.setFunctionModule(8, this.size - 8, true); // Always dark
+        }
+        // Draws two copies of the version bits (with its own error correction code),
+        // based on this object's version field, iff 7 <= version <= 40.
+        drawVersion() {
+            if (this.version < 7)
+                return;
+            // Calculate error correction code and pack bits
+            let rem = this.version; // version is uint6, in the range [7, 40]
+            for (let i = 0; i < 12; i++)
+                rem = (rem << 1) ^ ((rem >>> 11) * 0x1F25);
+            const bits = this.version << 12 | rem; // uint18
+            assert(bits >>> 18 == 0);
+            // Draw two copies
+            for (let i = 0; i < 18; i++) {
+                const color = getBit(bits, i);
+                const a = this.size - 11 + i % 3;
+                const b = Math.floor(i / 3);
+                this.setFunctionModule(a, b, color);
+                this.setFunctionModule(b, a, color);
+            }
+        }
+        // Draws a 9*9 finder pattern including the border separator,
+        // with the center module at (x, y). Modules can be out of bounds.
+        drawFinderPattern(x, y) {
+            for (let dy = -4; dy <= 4; dy++) {
+                for (let dx = -4; dx <= 4; dx++) {
+                    const dist = Math.max(Math.abs(dx), Math.abs(dy)); // Chebyshev/infinity norm
+                    const xx = x + dx;
+                    const yy = y + dy;
+                    if (0 <= xx && xx < this.size && 0 <= yy && yy < this.size)
+                        this.setFunctionModule(xx, yy, dist != 2 && dist != 4);
+                }
+            }
+        }
+        // Draws a 5*5 alignment pattern, with the center module
+        // at (x, y). All modules must be in bounds.
+        drawAlignmentPattern(x, y) {
+            for (let dy = -2; dy <= 2; dy++) {
+                for (let dx = -2; dx <= 2; dx++)
+                    this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1);
+            }
+        }
+        // Sets the color of a module and marks it as a function module.
+        // Only used by the constructor. Coordinates must be in bounds.
+        setFunctionModule(x, y, isDark) {
+            this.modules[y][x] = isDark;
+            this.isFunction[y][x] = true;
+        }
+        /*-- Private helper methods for constructor: Codewords and masking --*/
+        // Returns a new byte string representing the given data with the appropriate error correction
+        // codewords appended to it, based on this object's version and error correction level.
+        addEccAndInterleave(data) {
+            const ver = this.version;
+            const ecl = this.errorCorrectionLevel;
+            if (data.length != QrCode.getNumDataCodewords(ver, ecl))
+                throw new RangeError("Invalid argument");
+            // Calculate parameter numbers
+            const numBlocks = QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];
+            const blockEccLen = QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver];
+            const rawCodewords = Math.floor(QrCode.getNumRawDataModules(ver) / 8);
+            const numShortBlocks = numBlocks - rawCodewords % numBlocks;
+            const shortBlockLen = Math.floor(rawCodewords / numBlocks);
+            // Split data into blocks and append ECC to each block
+            let blocks = [];
+            const rsDiv = QrCode.reedSolomonComputeDivisor(blockEccLen);
+            for (let i = 0, k = 0; i < numBlocks; i++) {
+                let dat = data.slice(k, k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1));
+                k += dat.length;
+                const ecc = QrCode.reedSolomonComputeRemainder(dat, rsDiv);
+                if (i < numShortBlocks)
+                    dat.push(0);
+                blocks.push(dat.concat(ecc));
+            }
+            // Interleave (not concatenate) the bytes from every block into a single sequence
+            let result = [];
+            for (let i = 0; i < blocks[0].length; i++) {
+                blocks.forEach((block, j) => {
+                    // Skip the padding byte in short blocks
+                    if (i != shortBlockLen - blockEccLen || j >= numShortBlocks)
+                        result.push(block[i]);
+                });
+            }
+            assert(result.length == rawCodewords);
+            return result;
+        }
+        // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire
+        // data area of this QR Code. Function modules need to be marked off before this is called.
+        drawCodewords(data) {
+            if (data.length != Math.floor(QrCode.getNumRawDataModules(this.version) / 8))
+                throw new RangeError("Invalid argument");
+            let i = 0; // Bit index into the data
+            // Do the funny zigzag scan
+            for (let right = this.size - 1; right >= 1; right -= 2) { // Index of right column in each column pair
+                if (right == 6)
+                    right = 5;
+                for (let vert = 0; vert < this.size; vert++) { // Vertical counter
+                    for (let j = 0; j < 2; j++) {
+                        const x = right - j; // Actual x coordinate
+                        const upward = ((right + 1) & 2) == 0;
+                        const y = upward ? this.size - 1 - vert : vert; // Actual y coordinate
+                        if (!this.isFunction[y][x] && i < data.length * 8) {
+                            this.modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7));
+                            i++;
+                        }
+                        // If this QR Code has any remainder bits (0 to 7), they were assigned as
+                        // 0/false/light by the constructor and are left unchanged by this method
+                    }
+                }
+            }
+            assert(i == data.length * 8);
+        }
+        // XORs the codeword modules in this QR Code with the given mask pattern.
+        // The function modules must be marked and the codeword bits must be drawn
+        // before masking. Due to the arithmetic of XOR, calling applyMask() with
+        // the same mask value a second time will undo the mask. A final well-formed
+        // QR Code needs exactly one (not zero, two, etc.) mask applied.
+        applyMask(mask) {
+            if (mask < 0 || mask > 7)
+                throw new RangeError("Mask value out of range");
+            for (let y = 0; y < this.size; y++) {
+                for (let x = 0; x < this.size; x++) {
+                    let invert;
+                    switch (mask) {
+                        case 0:
+                            invert = (x + y) % 2 == 0;
+                            break;
+                        case 1:
+                            invert = y % 2 == 0;
+                            break;
+                        case 2:
+                            invert = x % 3 == 0;
+                            break;
+                        case 3:
+                            invert = (x + y) % 3 == 0;
+                            break;
+                        case 4:
+                            invert = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 == 0;
+                            break;
+                        case 5:
+                            invert = x * y % 2 + x * y % 3 == 0;
+                            break;
+                        case 6:
+                            invert = (x * y % 2 + x * y % 3) % 2 == 0;
+                            break;
+                        case 7:
+                            invert = ((x + y) % 2 + x * y % 3) % 2 == 0;
+                            break;
+                        default: throw new Error("Unreachable");
+                    }
+                    if (!this.isFunction[y][x] && invert)
+                        this.modules[y][x] = !this.modules[y][x];
+                }
+            }
+        }
+        // Calculates and returns the penalty score based on state of this QR Code's current modules.
+        // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.
+        getPenaltyScore() {
+            let result = 0;
+            // Adjacent modules in row having same color, and finder-like patterns
+            for (let y = 0; y < this.size; y++) {
+                let runColor = false;
+                let runX = 0;
+                let runHistory = [0, 0, 0, 0, 0, 0, 0];
+                for (let x = 0; x < this.size; x++) {
+                    if (this.modules[y][x] == runColor) {
+                        runX++;
+                        if (runX == 5)
+                            result += QrCode.PENALTY_N1;
+                        else if (runX > 5)
+                            result++;
+                    }
+                    else {
+                        this.finderPenaltyAddHistory(runX, runHistory);
+                        if (!runColor)
+                            result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;
+                        runColor = this.modules[y][x];
+                        runX = 1;
+                    }
+                }
+                result += this.finderPenaltyTerminateAndCount(runColor, runX, runHistory) * QrCode.PENALTY_N3;
+            }
+            // Adjacent modules in column having same color, and finder-like patterns
+            for (let x = 0; x < this.size; x++) {
+                let runColor = false;
+                let runY = 0;
+                let runHistory = [0, 0, 0, 0, 0, 0, 0];
+                for (let y = 0; y < this.size; y++) {
+                    if (this.modules[y][x] == runColor) {
+                        runY++;
+                        if (runY == 5)
+                            result += QrCode.PENALTY_N1;
+                        else if (runY > 5)
+                            result++;
+                    }
+                    else {
+                        this.finderPenaltyAddHistory(runY, runHistory);
+                        if (!runColor)
+                            result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;
+                        runColor = this.modules[y][x];
+                        runY = 1;
+                    }
+                }
+                result += this.finderPenaltyTerminateAndCount(runColor, runY, runHistory) * QrCode.PENALTY_N3;
+            }
+            // 2*2 blocks of modules having same color
+            for (let y = 0; y < this.size - 1; y++) {
+                for (let x = 0; x < this.size - 1; x++) {
+                    const color = this.modules[y][x];
+                    if (color == this.modules[y][x + 1] &&
+                        color == this.modules[y + 1][x] &&
+                        color == this.modules[y + 1][x + 1])
+                        result += QrCode.PENALTY_N2;
+                }
+            }
+            // Balance of dark and light modules
+            let dark = 0;
+            for (const row of this.modules)
+                dark = row.reduce((sum, color) => sum + (color ? 1 : 0), dark);
+            const total = this.size * this.size; // Note that size is odd, so dark/total != 1/2
+            // Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)%
+            const k = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1;
+            assert(0 <= k && k <= 9);
+            result += k * QrCode.PENALTY_N4;
+            assert(0 <= result && result <= 2568888); // Non-tight upper bound based on default values of PENALTY_N1, ..., N4
+            return result;
+        }
+        /*-- Private helper functions --*/
+        // Returns an ascending list of positions of alignment patterns for this version number.
+        // Each position is in the range [0,177), and are used on both the x and y axes.
+        // This could be implemented as lookup table of 40 variable-length lists of integers.
+        getAlignmentPatternPositions() {
+            if (this.version == 1)
+                return [];
+            else {
+                const numAlign = Math.floor(this.version / 7) + 2;
+                const step = (this.version == 32) ? 26 :
+                    Math.ceil((this.version * 4 + 4) / (numAlign * 2 - 2)) * 2;
+                let result = [6];
+                for (let pos = this.size - 7; result.length < numAlign; pos -= step)
+                    result.splice(1, 0, pos);
+                return result;
+            }
+        }
+        // Returns the number of data bits that can be stored in a QR Code of the given version number, after
+        // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.
+        // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.
+        static getNumRawDataModules(ver) {
+            if (ver < QrCode.MIN_VERSION || ver > QrCode.MAX_VERSION)
+                throw new RangeError("Version number out of range");
+            let result = (16 * ver + 128) * ver + 64;
+            if (ver >= 2) {
+                const numAlign = Math.floor(ver / 7) + 2;
+                result -= (25 * numAlign - 10) * numAlign - 55;
+                if (ver >= 7)
+                    result -= 36;
+            }
+            assert(208 <= result && result <= 29648);
+            return result;
+        }
+        // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any
+        // QR Code of the given version number and error correction level, with remainder bits discarded.
+        // This stateless pure function could be implemented as a (40*4)-cell lookup table.
+        static getNumDataCodewords(ver, ecl) {
+            return Math.floor(QrCode.getNumRawDataModules(ver) / 8) -
+                QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver] *
+                    QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];
+        }
+        // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be
+        // implemented as a lookup table over all possible parameter values, instead of as an algorithm.
+        static reedSolomonComputeDivisor(degree) {
+            if (degree < 1 || degree > 255)
+                throw new RangeError("Degree out of range");
+            // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1.
+            // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array [255, 8, 93].
+            let result = [];
+            for (let i = 0; i < degree - 1; i++)
+                result.push(0);
+            result.push(1); // Start off with the monomial x^0
+            // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),
+            // and drop the highest monomial term which is always 1x^degree.
+            // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
+            let root = 1;
+            for (let i = 0; i < degree; i++) {
+                // Multiply the current product by (x - r^i)
+                for (let j = 0; j < result.length; j++) {
+                    result[j] = QrCode.reedSolomonMultiply(result[j], root);
+                    if (j + 1 < result.length)
+                        result[j] ^= result[j + 1];
+                }
+                root = QrCode.reedSolomonMultiply(root, 0x02);
+            }
+            return result;
+        }
+        // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials.
+        static reedSolomonComputeRemainder(data, divisor) {
+            let result = divisor.map(_ => 0);
+            for (const b of data) { // Polynomial division
+                const factor = b ^ result.shift();
+                result.push(0);
+                divisor.forEach((coef, i) => result[i] ^= QrCode.reedSolomonMultiply(coef, factor));
+            }
+            return result;
+        }
+        // Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result
+        // are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8.
+        static reedSolomonMultiply(x, y) {
+            if (x >>> 8 != 0 || y >>> 8 != 0)
+                throw new RangeError("Byte out of range");
+            // Russian peasant multiplication
+            let z = 0;
+            for (let i = 7; i >= 0; i--) {
+                z = (z << 1) ^ ((z >>> 7) * 0x11D);
+                z ^= ((y >>> i) & 1) * x;
+            }
+            assert(z >>> 8 == 0);
+            return z;
+        }
+        // Can only be called immediately after a light run is added, and
+        // returns either 0, 1, or 2. A helper function for getPenaltyScore().
+        finderPenaltyCountPatterns(runHistory) {
+            const n = runHistory[1];
+            assert(n <= this.size * 3);
+            const core = n > 0 && runHistory[2] == n && runHistory[3] == n * 3 && runHistory[4] == n && runHistory[5] == n;
+            return (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0)
+                + (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0);
+        }
+        // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore().
+        finderPenaltyTerminateAndCount(currentRunColor, currentRunLength, runHistory) {
+            if (currentRunColor) { // Terminate dark run
+                this.finderPenaltyAddHistory(currentRunLength, runHistory);
+                currentRunLength = 0;
+            }
+            currentRunLength += this.size; // Add light border to final run
+            this.finderPenaltyAddHistory(currentRunLength, runHistory);
+            return this.finderPenaltyCountPatterns(runHistory);
+        }
+        // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore().
+        finderPenaltyAddHistory(currentRunLength, runHistory) {
+            if (runHistory[0] == 0)
+                currentRunLength += this.size; // Add light border to initial run
+            runHistory.pop();
+            runHistory.unshift(currentRunLength);
+        }
+    }
+    /*-- Constants and tables --*/
+    // The minimum version number supported in the QR Code Model 2 standard.
+    QrCode.MIN_VERSION = 1;
+    // The maximum version number supported in the QR Code Model 2 standard.
+    QrCode.MAX_VERSION = 40;
+    // For use in getPenaltyScore(), when evaluating which mask is best.
+    QrCode.PENALTY_N1 = 3;
+    QrCode.PENALTY_N2 = 3;
+    QrCode.PENALTY_N3 = 40;
+    QrCode.PENALTY_N4 = 10;
+    QrCode.ECC_CODEWORDS_PER_BLOCK = [
+        // Version: (note that index 0 is for padding, and is set to an illegal value)
+        //0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40    Error correction level
+        [-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // Low
+        [-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28], // Medium
+        [-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // Quartile
+        [-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // High
+    ];
+    QrCode.NUM_ERROR_CORRECTION_BLOCKS = [
+        // Version: (note that index 0 is for padding, and is set to an illegal value)
+        //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40    Error correction level
+        [-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25], // Low
+        [-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49], // Medium
+        [-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68], // Quartile
+        [-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81], // High
+    ];
+    qrcodegen.QrCode = QrCode;
+    // Appends the given number of low-order bits of the given value
+    // to the given buffer. Requires 0 <= len <= 31 and 0 <= val < 2^len.
+    function appendBits(val, len, bb) {
+        if (len < 0 || len > 31 || val >>> len != 0)
+            throw new RangeError("Value out of range");
+        for (let i = len - 1; i >= 0; i--) // Append bit by bit
+            bb.push((val >>> i) & 1);
+    }
+    // Returns true iff the i'th bit of x is set to 1.
+    function getBit(x, i) {
+        return ((x >>> i) & 1) != 0;
+    }
+    // Throws an exception if the given condition is false.
+    function assert(cond) {
+        if (!cond)
+            throw new Error("Assertion error");
+    }
+    /*---- Data segment class ----*/
+    /*
+     * A segment of character/binary/control data in a QR Code symbol.
+     * Instances of this class are immutable.
+     * The mid-level way to create a segment is to take the payload data
+     * and call a static factory function such as QrSegment.makeNumeric().
+     * The low-level way to create a segment is to custom-make the bit buffer
+     * and call the QrSegment() constructor with appropriate values.
+     * This segment class imposes no length restrictions, but QR Codes have restrictions.
+     * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data.
+     * Any segment longer than this is meaningless for the purpose of generating QR Codes.
+     */
+    class QrSegment {
+        /*-- Static factory functions (mid level) --*/
+        // Returns a segment representing the given binary data encoded in
+        // byte mode. All input byte arrays are acceptable. Any text string
+        // can be converted to UTF-8 bytes and encoded as a byte mode segment.
+        static makeBytes(data) {
+            let bb = [];
+            for (const b of data)
+                appendBits(b, 8, bb);
+            return new QrSegment(QrSegment.Mode.BYTE, data.length, bb);
+        }
+        // Returns a segment representing the given string of decimal digits encoded in numeric mode.
+        static makeNumeric(digits) {
+            if (!QrSegment.isNumeric(digits))
+                throw new RangeError("String contains non-numeric characters");
+            let bb = [];
+            for (let i = 0; i < digits.length;) { // Consume up to 3 digits per iteration
+                const n = Math.min(digits.length - i, 3);
+                appendBits(parseInt(digits.substr(i, n), 10), n * 3 + 1, bb);
+                i += n;
+            }
+            return new QrSegment(QrSegment.Mode.NUMERIC, digits.length, bb);
+        }
+        // Returns a segment representing the given text string encoded in alphanumeric mode.
+        // The characters allowed are: 0 to 9, A to Z (uppercase only), space,
+        // dollar, percent, asterisk, plus, hyphen, period, slash, colon.
+        static makeAlphanumeric(text) {
+            if (!QrSegment.isAlphanumeric(text))
+                throw new RangeError("String contains unencodable characters in alphanumeric mode");
+            let bb = [];
+            let i;
+            for (i = 0; i + 2 <= text.length; i += 2) { // Process groups of 2
+                let temp = QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45;
+                temp += QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1));
+                appendBits(temp, 11, bb);
+            }
+            if (i < text.length) // 1 character remaining
+                appendBits(QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)), 6, bb);
+            return new QrSegment(QrSegment.Mode.ALPHANUMERIC, text.length, bb);
+        }
+        // Returns a new mutable list of zero or more segments to represent the given Unicode text string.
+        // The result may use various segment modes and switch modes to optimize the length of the bit stream.
+        static makeSegments(text) {
+            // Select the most efficient segment encoding automatically
+            if (text == "")
+                return [];
+            else if (QrSegment.isNumeric(text))
+                return [QrSegment.makeNumeric(text)];
+            else if (QrSegment.isAlphanumeric(text))
+                return [QrSegment.makeAlphanumeric(text)];
+            else
+                return [QrSegment.makeBytes(QrSegment.toUtf8ByteArray(text))];
+        }
+        // Returns a segment representing an Extended Channel Interpretation
+        // (ECI) designator with the given assignment value.
+        static makeEci(assignVal) {
+            let bb = [];
+            if (assignVal < 0)
+                throw new RangeError("ECI assignment value out of range");
+            else if (assignVal < (1 << 7))
+                appendBits(assignVal, 8, bb);
+            else if (assignVal < (1 << 14)) {
+                appendBits(0b10, 2, bb);
+                appendBits(assignVal, 14, bb);
+            }
+            else if (assignVal < 1000000) {
+                appendBits(0b110, 3, bb);
+                appendBits(assignVal, 21, bb);
+            }
+            else
+                throw new RangeError("ECI assignment value out of range");
+            return new QrSegment(QrSegment.Mode.ECI, 0, bb);
+        }
+        // Tests whether the given string can be encoded as a segment in numeric mode.
+        // A string is encodable iff each character is in the range 0 to 9.
+        static isNumeric(text) {
+            return QrSegment.NUMERIC_REGEX.test(text);
+        }
+        // Tests whether the given string can be encoded as a segment in alphanumeric mode.
+        // A string is encodable iff each character is in the following set: 0 to 9, A to Z
+        // (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.
+        static isAlphanumeric(text) {
+            return QrSegment.ALPHANUMERIC_REGEX.test(text);
+        }
+        /*-- Constructor (low level) and fields --*/
+        // Creates a new QR Code segment with the given attributes and data.
+        // The character count (numChars) must agree with the mode and the bit buffer length,
+        // but the constraint isn't checked. The given bit buffer is cloned and stored.
+        constructor(
+        // The mode indicator of this segment.
+        mode,
+        // The length of this segment's unencoded data. Measured in characters for
+        // numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.
+        // Always zero or positive. Not the same as the data's bit length.
+        numChars,
+        // The data bits of this segment. Accessed through getData().
+        bitData) {
+            this.mode = mode;
+            this.numChars = numChars;
+            this.bitData = bitData;
+            if (numChars < 0)
+                throw new RangeError("Invalid argument");
+            this.bitData = bitData.slice(); // Make defensive copy
+        }
+        /*-- Methods --*/
+        // Returns a new copy of the data bits of this segment.
+        getData() {
+            return this.bitData.slice(); // Make defensive copy
+        }
+        // (Package-private) Calculates and returns the number of bits needed to encode the given segments at
+        // the given version. The result is infinity if a segment has too many characters to fit its length field.
+        static getTotalBits(segs, version) {
+            let result = 0;
+            for (const seg of segs) {
+                const ccbits = seg.mode.numCharCountBits(version);
+                if (seg.numChars >= (1 << ccbits))
+                    return Infinity; // The segment's length doesn't fit the field's bit width
+                result += 4 + ccbits + seg.bitData.length;
+            }
+            return result;
+        }
+        // Returns a new array of bytes representing the given string encoded in UTF-8.
+        static toUtf8ByteArray(str) {
+            str = encodeURI(str);
+            let result = [];
+            for (let i = 0; i < str.length; i++) {
+                if (str.charAt(i) != "%")
+                    result.push(str.charCodeAt(i));
+                else {
+                    result.push(parseInt(str.substr(i + 1, 2), 16));
+                    i += 2;
+                }
+            }
+            return result;
+        }
+    }
+    /*-- Constants --*/
+    // Describes precisely all strings that are encodable in numeric mode.
+    QrSegment.NUMERIC_REGEX = /^[0-9]*$/;
+    // Describes precisely all strings that are encodable in alphanumeric mode.
+    QrSegment.ALPHANUMERIC_REGEX = /^[A-Z0-9 $%*+.\/:-]*$/;
+    // The set of all legal characters in alphanumeric mode,
+    // where each character value maps to the index in the string.
+    QrSegment.ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
+    qrcodegen.QrSegment = QrSegment;
+})(qrcodegen || (qrcodegen = {}));
+/*---- Public helper enumeration ----*/
+(function (qrcodegen) {
+    var QrCode;
+    (function (QrCode) {
+        /*
+         * The error correction level in a QR Code symbol. Immutable.
+         */
+        class Ecc {
+            /*-- Constructor and fields --*/
+            constructor(
+            // In the range 0 to 3 (unsigned 2-bit integer).
+            ordinal,
+            // (Package-private) In the range 0 to 3 (unsigned 2-bit integer).
+            formatBits) {
+                this.ordinal = ordinal;
+                this.formatBits = formatBits;
+            }
+        }
+        /*-- Constants --*/
+        Ecc.LOW = new Ecc(0, 1); // The QR Code can tolerate about  7% erroneous codewords
+        Ecc.MEDIUM = new Ecc(1, 0); // The QR Code can tolerate about 15% erroneous codewords
+        Ecc.QUARTILE = new Ecc(2, 3); // The QR Code can tolerate about 25% erroneous codewords
+        Ecc.HIGH = new Ecc(3, 2); // The QR Code can tolerate about 30% erroneous codewords
+        QrCode.Ecc = Ecc;
+    })(QrCode = qrcodegen.QrCode || (qrcodegen.QrCode = {}));
+})(qrcodegen || (qrcodegen = {}));
+/*---- Public helper enumeration ----*/
+(function (qrcodegen) {
+    var QrSegment;
+    (function (QrSegment) {
+        /*
+         * Describes how a segment's data bits are interpreted. Immutable.
+         */
+        class Mode {
+            /*-- Constructor and fields --*/
+            constructor(
+            // The mode indicator bits, which is a uint4 value (range 0 to 15).
+            modeBits,
+            // Number of character count bits for three different version ranges.
+            numBitsCharCount) {
+                this.modeBits = modeBits;
+                this.numBitsCharCount = numBitsCharCount;
+            }
+            /*-- Method --*/
+            // (Package-private) Returns the bit width of the character count field for a segment in
+            // this mode in a QR Code at the given version number. The result is in the range [0, 16].
+            numCharCountBits(ver) {
+                return this.numBitsCharCount[Math.floor((ver + 7) / 17)];
+            }
+        }
+        /*-- Constants --*/
+        Mode.NUMERIC = new Mode(0x1, [10, 12, 14]);
+        Mode.ALPHANUMERIC = new Mode(0x2, [9, 11, 13]);
+        Mode.BYTE = new Mode(0x4, [8, 16, 16]);
+        Mode.KANJI = new Mode(0x8, [8, 10, 12]);
+        Mode.ECI = new Mode(0x7, [0, 0, 0]);
+        QrSegment.Mode = Mode;
+    })(QrSegment = qrcodegen.QrSegment || (qrcodegen.QrSegment = {}));
+})(qrcodegen || (qrcodegen = {}));

+ 43 - 0
prototypes/fmode-subscription-20261125/README.md

@@ -0,0 +1,43 @@
+# Fmode 套餐与平台异步开通 · G-D1 交互原型
+
+直接双击 `index.html` 打开。桌面与手机自动使用各自布局,全部样式、图标和脚本内嵌,可离线查看,无须安装或登录。
+
+这是**用于用户确认的独立原型**,不是当前 Angular 产品页面,不连接真实平台,不创建容器、不付款、不操作账号或既有容器。所有场景和凭据均为本地假数据;刷新后会重置,不把原型内存状态当服务端持久化或准入验证。
+
+## 本次确认内容
+
+- 两天试用:1 个平台容器与独立云资源,核验可用后才开始48小时。
+- 入门1个、进阶3个、企业共享5个;高级/企业可提交增配意向,人工确认后才增加名额;所有价格仍为待定。
+- 平台接口异步受理;用户界面只显示友好当前状态、真实进度和必要操作,不解释内部六阶段。明确失败后续原任务重试,检查进度不会自行推进。
+- 个人与企业权益分别保留、可切换;加入企业不覆盖个人容器,购买个人套餐不挪用企业容器。
+- 接入信息默认遮蔽;确认后只展示显著标注的假值,含本人userMxId/homeserver及agent/房间信息。企业空间不展示企业管理凭据。
+- 试用到期时只锁本项目使用,容器和数据保留;付费确认后恢复同一个容器。
+
+## 怎么体验
+
+1. 在「套餐与开通」点击「开始两天试用」,输入容器名称后提交。
+2. 打开页面顶部「演示场景」,点击「推进一个阶段」,观察友好状态与真实进度;内部六阶段只在评审模型和接口文档中保留。
+3. 可模拟「当前阶段失败」后在页面重试,或模拟断网、进度延迟;任务编号和已完成进度保留。
+4. 全部步骤完成后显示可用,试用起止时间才产生;「我的容器」与「接入信息」可进入。
+5. 模拟「试用到期」,选择入门/进阶并提交开通意向,再用「管理员确认」演示恢复原容器。
+6. 「名额已满」场景可提交增加名额意向并模拟确认;「企业账号」或加入企业后可切换个人/企业主体。
+
+顶部的演示按钮只用于评审,不是正式产品里的平台/管理员操作。尚未做真实开通计时,预计用时始终展示“待平台实测后提供”,不演示固定30分钟。
+
+可用URL参数:`?scenario=new|waiting|failed|advanced|quota|expired|enterprise`,`screen=plans|waiting|containers|access|expired|enterprise|account`,`theme=dark`。不认识的参数回落已定义场景;参数不包含真实账号信息。
+
+## 源文件与验证
+
+```powershell
+node prototypes/fmode-subscription-20261125/build.mjs
+node prototypes/fmode-subscription-20261125/verify.mjs
+```
+
+- `preview.template.html`、`styles.css`:评审外壳与页面样式;构建复用当前底座及应用`_base.scss`/`_palette.scss`里的纯CSS令牌。
+- `model.js`:独立的内存状态转换;`app.js`:页面与交互。无localStorage、上传、网络接口或自动假进度。
+- `index.html`:可单独打开的最终原型,不用于生产部署。
+- `verify.mjs`:现有Playwright的浏览器评审检查,结果和20张截图输出到`test-results/subscription-prototype/`(不入库)。这些检查不验证真实平台API或容器创建。
+
+正式实现会在现有Angular路由、owner服务、FmodeApi与平台Functions体系内完成;组件使用既有ui-kit,不直接复制本HTML作为产品功能。接口与架构设计见`docs/03-interface/api/套餐与平台异步开通-API契约.md`与`docs/02-design/architecture/套餐权益与异步开通设计.md`。
+
+**当前门禁:G-D1 待用户确认。** 用户确认原型前,不进入产品代码、平台创建或真实计时阶段。

+ 293 - 0
prototypes/fmode-subscription-20261125/app.js

@@ -0,0 +1,293 @@
+const Demo = SubscriptionDemo;
+const params = new URLSearchParams(location.search);
+const knownScenarios = ['new', 'waiting', 'failed', 'advanced', 'quota', 'expired', 'enterprise'];
+let state = Demo.initial(knownScenarios.includes(params.get('scenario')) ? params.get('scenario') : 'new');
+const views = { plans: '套餐与开通', waiting: '开通进度', containers: '我的容器', access: '接入信息', enterprise: '加入企业', account: '我的账号', expired: '继续使用 Fmode', chat: '开始协作' };
+const requestedView = params.get('screen') || location.hash.slice(1);
+if (views[requestedView]) state = Demo.reduce(state, { type: 'view', view: requestedView });
+if (params.get('theme') === 'dark') document.documentElement.classList.add('dark');
+const main = document.getElementById('main');
+const dialog = document.getElementById('dialog');
+const dialogBody = document.getElementById('dialogBody');
+let dialogContext = null;
+let dialogTrigger = null;
+let toastTimer;
+const esc = (value) => String(value ?? '').replace(/[&<>"']/g, (character) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[character]);
+const paths = {
+  grid: '<rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/>',
+  server: '<rect x="3" y="3" width="18" height="7" rx="2"/><rect x="3" y="14" width="18" height="7" rx="2"/><path d="M7 6.5h.01M7 17.5h.01M12 6.5h5M12 17.5h5"/>',
+  arrow: '<path d="M4 12h16m-6-6 6 6-6 6"/>',
+  check: '<path d="m5 12 4 4L19 6"/>',
+  clock: '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>',
+  shield: '<path d="m12 3 8 3v6c0 5-8 9-8 9S4 17 4 12V6l8-3Z"/><path d="m8 12 3 3 5-6"/>',
+  person: '<circle cx="12" cy="8" r="4"/><path d="M4 21v-2a8 8 0 0 1 16 0v2"/>',
+  people: '<circle cx="9" cy="8" r="3"/><path d="M3 21v-3a6 6 0 0 1 12 0v3M16 5a3 3 0 0 1 0 6m2 3a5 5 0 0 1 3 4v3"/>',
+  key: '<circle cx="8" cy="8" r="5"/><path d="m12 12 9 9m-4-4 3-3m-6 0 3-3"/>',
+  copy: '<rect x="8" y="8" width="12" height="13" rx="2"/><path d="M16 8V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h3"/>',
+  plus: '<path d="M12 5v14M5 12h14"/>',
+  refresh: '<path d="M20 7v5h-5M4 17v-5h5"/><path d="M6 6a8 8 0 0 1 13 3M5 15a8 8 0 0 0 13 3"/>',
+  spark: '<path d="m12 3 2.4 6.6L21 12l-6.6 2.4L12 21l-2.4-6.6L3 12l6.6-2.4L12 3Z"/>',
+  cloud: '<path d="M7 19a5 5 0 1 1 .5-10A7 7 0 0 1 21 12a4 4 0 0 1-1 7H7Z"/>',
+  chat: '<path d="M5 4h14a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2H9l-6 3V6a2 2 0 0 1 2-2Z"/><path d="M7 9h10M7 13h6"/>',
+  info: '<circle cx="12" cy="12" r="9"/><path d="M12 11v6M12 7h.01"/>',
+  warning: '<path d="m12 3 10 18H2L12 3Z"/><path d="M12 9v5M12 17h.01"/>',
+  wifi: '<path d="M2 8a16 16 0 0 1 20 0M5 12a11 11 0 0 1 14 0M8 16a6 6 0 0 1 8 0M12 20h.01M3 3l18 18"/>',
+  close: '<path d="m6 6 12 12M18 6 6 18"/>',
+  building: '<path d="M4 21V5l8-3 8 3v16H4ZM9 21v-5h6v5M8 7h1m6 0h1M8 11h1m6 0h1"/>',
+  link: '<path d="m10 14 4-4m-6 6-2 2a4 4 0 0 1-6-6l5-5a4 4 0 0 1 6 0m2 10a4 4 0 0 0 6 0l5-5a4 4 0 0 0-6-6l-2 2" transform="translate(2 0) scale(.85 1)"/>',
+};
+const icon = (name) => `<svg class="icon" viewBox="0 0 24 24" aria-hidden="true">${paths[name] || paths.grid}</svg>`;
+const button = (text, action, kind = '', extra = '') => `<button type="button" class="button ${kind}" data-action="${action}" ${extra}>${text}</button>`;
+const notice = (title, text, tone = '', name = 'info') => `<div class="notice ${tone}">${icon(name)}<div><strong>${title}</strong>${text ? `<p>${text}</p>` : ''}</div></div>`;
+const planName = () => state.plan ? Demo.PLANS[state.plan].name : '尚未开通';
+const stateLabel = () => state.offline ? '网络未连接' : ({ unopened: '尚未开通', provisioning: '正在开通', active: state.plan === 'trial' ? '试用中' : '已开通', expired: '试用已到期' })[state.access];
+const priceNotice = '具体价格请咨询客服。';
+
+function nav() {
+  const items = [{ view: 'plans', label: '套餐与开通', mobile: '套餐', icon: 'grid' }, { view: 'containers', label: '我的容器', mobile: '容器', icon: 'server' }, { view: 'access', label: '接入信息', mobile: '接入', icon: 'key' }, { view: 'enterprise', label: state.company || state.companyAccount ? '企业空间' : '加入企业', mobile: '企业', icon: 'people' }];
+  document.getElementById('desktopNav').innerHTML = items.map((item) => `<button type="button" class="nav-button ${state.view === item.view || state.view === 'expired' && item.view === 'plans' || state.view === 'waiting' && item.view === 'containers' ? 'on' : ''}" data-view="${item.view}" ${state.view === item.view ? 'aria-current="page"' : ''}>${icon(item.icon)}<span>${item.label}</span>${item.view === 'containers' && state.containers.length ? `<span class="nav-badge">${state.containers.length}</span>` : ''}</button>`).join('');
+  document.getElementById('mobileNav').innerHTML = items.map((item) => `<button type="button" class="${state.view === item.view || state.view === 'expired' && item.view === 'plans' || state.view === 'waiting' && item.view === 'containers' ? 'on' : ''}" data-view="${item.view}" ${state.view === item.view ? 'aria-current="page"' : ''}>${icon(item.icon)}<span>${item.mobile}</span></button>`).join('');
+}
+
+function planCards() {
+  const cards = [
+    { key: 'starter', icon: 'server', name: '入门版', short: '入门', sub: '一个专属空间,从这里开始。', unit: '/ 月', note: '支持 1 个容器', mobileQuota: '1 个专属容器 · 2 核 4G', mobileBenefit: '独立云资源 · 含完整接入信息', quota: '1', quotaLabel: '个容器', perks: ['1 个专属容器', '2 核 4G 标准规格', '独立云资源', '完整接入信息', '手机与电脑均可使用'] },
+    { key: 'advanced', icon: 'spark', name: '进阶版', short: '进阶', sub: '更多空间,接住不同的想法。', unit: '/ 年', note: '含一年资源费用', mobileQuota: '3 个专属容器 · 2 核 4G', mobileBenefit: '独立云资源 · 支持加购名额', quota: '3', quotaLabel: '个容器', perks: ['3 个专属容器', '2 核 4G 标准规格', '独立云资源与接入信息', '支持加购容器名额'] },
+    { key: 'enterprise', icon: 'building', name: '企业版', short: '企业', sub: '让整个团队,有序地协作。', unit: '', note: '团队共享', mobileQuota: '5 个共享容器 · 2 核 4G', mobileBenefit: '成员管理 · 通讯录与容器共享', quota: '5', quotaLabel: '个共享', perks: ['5 个企业容器', '2 核 4G 标准规格(新容器)', '企业成员管理', '通讯录与容器共享', '支持加购容器名额'] },
+  ];
+  const cta = (card) => state.access === 'expired' ? '恢复' : state.plan === card.key ? '当前' : '开通';
+  return `<div class="plan-grid">${cards.map((card) => {
+    const disabled = state.plan === card.key && state.access === 'active';
+    const current = state.plan === card.key && state.access === 'active';
+    return `<article class="plan-card ${card.key === 'advanced' ? 'featured' : ''} ${current ? 'current' : ''}" data-plan-card="${card.key}">${card.key === 'advanced' ? '<span class="plan-recommend">推荐</span>' : ''}
+      <div class="plan-mobile-copy"><div class="plan-mobile-heading"><h3>${card.name}</h3>${card.key === 'advanced' ? '<span class="plan-mobile-recommend">推荐</span>' : ''}</div><p class="plan-mobile-quota">${card.mobileQuota}</p><p class="plan-mobile-benefit">${card.mobileBenefit}</p></div>
+      <div class="plan-mobile-action"><div class="plan-mobile-price"><strong>价格待定</strong><span>${card.unit || card.note}</span></div>${button(cta(card), 'apply', card.key === 'advanced' ? '' : 'secondary', `data-plan="${card.key}" ${disabled ? 'disabled' : ''}`)}</div>
+      <div class="plan-icon">${icon(card.icon)}</div>
+      <h3><span class="plan-name-full">${card.name}</span><span class="plan-name-short">${card.short}</span></h3>
+      <p class="plan-sub">${card.sub}</p>
+      <div class="plan-quota"><strong>${card.quota}</strong><span>${card.quotaLabel}</span></div>
+      <div class="plan-price"><strong>价格待定</strong><span>${card.unit}</span></div>
+      <div class="plan-billing-note">${card.note}</div>
+      ${button(cta(card), 'apply', card.key === 'advanced' ? '' : 'secondary', `data-plan="${card.key}" ${disabled ? 'disabled' : ''}`)}
+      <ul class="plan-perks">${card.perks.map((perk) => `<li>${icon('check')}<span>${perk}</span></li>`).join('')}</ul>
+    </article>`;
+  }).join('')}</div>`;
+}
+
+function applicationNotice() {
+  if (!state.application) return '';
+  const addon = state.application.kind === 'addon';
+  return notice(addon ? '增配申请已提交' : '开通申请已提交', '等待确认。', 'info', 'clock');
+}
+
+function plansPage() {
+  let trial = '';
+  if (!state.trialClaimed && state.access === 'unopened') {
+    trial = `<section class="trial-banner" aria-label="两天试用"><div class="trial-icon">${icon('spark')}</div><div><h2>先体验,再决定。<span>两天试用</span></h2><p>1 个专属容器,开通后开始体验。</p></div>${button('开始两天试用 ' + icon('arrow'), 'trial')}</section>`;
+  } else if (state.job && state.job.status !== 'ready') {
+    trial = `<section class="trial-banner"><div class="trial-icon">${icon('clock')}</div><div><h2>正在开通</h2><p>${esc(state.job.name)}</p></div>${button('查看进度 ' + icon('arrow'), 'waiting')}</section>`;
+  } else if (state.access === 'active') {
+    trial = `<section class="trial-banner"><div class="trial-icon">${icon('check')}</div><div><h2>${esc(planName())}<span>${state.plan === 'trial' ? '试用中' : '使用中'}</span></h2><p>已使用 ${Demo.used(state)} / ${Demo.limit(state)} 个名额</p></div>${button('我的容器 ' + icon('arrow'), 'containers')}</section>`;
+  }
+  return `<div class="page"><header class="page-heading"><div><span class="eyebrow">${icon('grid')}套餐与开通</span><h1>选择适合你的协作方式。</h1><p>按需选择,随时升级。</p></div></header>${applicationNotice()}${trial}<div class="section-heading"><h2>为下一步,准备合适的空间</h2><p>个人专属 · 企业共享 · 按需增配</p></div>${planCards()}<p class="plans-note">${icon('info')}<span>${priceNotice}</span></p><div class="info-grid"><section class="info-item">${icon('building')}<div><h3>加入企业</h3><p>使用企业容器</p><button type="button" class="text-action" data-view="enterprise">加入企业 ${icon('arrow')}</button></div></section><section class="info-item">${icon('shield')}<div><h3>数据为你保留</h3><p>试用结束后,开通套餐即可继续使用。</p></div></section></div></div>`;
+}
+
+function waitingPage() {
+  const job = state.job;
+  if (!job) return `<div class="page narrow"><div class="panel empty-state"><div class="task-orb">${icon('clock')}</div><h2>暂无开通记录</h2>${button('查看套餐', 'plans')}</div></div>`;
+  const ready = job.status === 'ready', failed = job.status === 'failed';
+  const percent = ready ? 100 : Math.min(99, Math.floor(job.completed / Demo.STAGES.length * 100));
+  const label = ready ? '已就绪' : failed ? '开通失败' : job.status === 'queued' ? '等待开通' : job.status === 'verifying' ? '即将就绪' : '正在开通';
+  const elapsed = Math.floor((state.now - job.createdAt) / 60000);
+  const feedback = state.offline ? notice('网络连接已断开', '请检查网络后重试。', 'warning', 'wifi') : failed ? notice('暂时未能完成开通', '请稍后重试。', 'warning', 'warning') : job.delayed ? notice('仍在处理中', '请稍后查看。', '', 'clock') : '';
+  return `<div class="page narrow"><header class="page-heading"><div><h1>开通进度</h1></div></header>${feedback}<section class="panel waiting-simple"><div class="waiting-current"><span class="task-orb ${ready ? 'success' : failed ? 'failed' : ''}">${icon(ready ? 'check' : failed ? 'warning' : 'server')}</span><h2>${label}</h2><p>${esc(job.name)}</p><span class="state-pill">${esc(planName())}</span></div><div class="waiting-progress"><div class="progress-label"><span>开通进度</span><strong>${percent}%</strong></div><div class="progress-track" role="progressbar" aria-label="开通进度" aria-valuenow="${percent}" aria-valuemin="0" aria-valuemax="100"><div class="progress-fill" style="width:${percent}%"></div></div></div><dl class="waiting-meta"><div><dt>${ready ? '状态' : '已等待'}</dt><dd>${ready ? '已就绪' : elapsed + ' 分钟'}</dd></div><div><dt>${ready ? '当前套餐' : '预计完成'}</dt><dd>${ready ? esc(planName()) : '稍后更新'}</dd></div></dl><div class="waiting-actions">${ready ? button('开始使用 ' + icon('arrow'), 'chat') : failed ? button(icon('refresh') + '重试', 'retry', '', state.offline ? 'disabled' : '') : button(icon('refresh') + '检查进度', 'check', '', state.offline ? 'disabled' : '')}${button('我的容器', 'containers', 'secondary')}</div><button type="button" class="text-action support-action" data-action="copy-job">${icon('copy')}复制服务编号</button></section></div>`;
+}
+
+function quotaPanel() {
+  const used = Demo.used(state), reserved = Demo.reserved(state), max = Demo.limit(state);
+  return `<section class="panel quota-panel"><div class="quota-copy"><h2>${state.company ? '企业共享名额' : '我的容器名额'} <span class="state-pill ${state.plan === 'trial' ? 'pending' : 'ready'}">${esc(planName())}</span></h2><p>已用 ${used} 个${reserved ? `,开通中 ${reserved} 个` : ''}${state.addon ? `,已含加购 ${state.addon} 个` : ''}。</p></div><div class="quota-meter"><p><strong>${used + reserved}</strong> / ${max} 个名额</p><div class="progress-track"><div class="progress-fill" style="width:${max ? Math.min(100,(used + reserved) / max * 100) : 0}%"></div></div></div>${['advanced', 'enterprise'].includes(state.plan) ? button('增加名额', 'addon', 'secondary') : button('查看套餐', 'plans', 'secondary')}</section>`;
+}
+
+function containerCard(container) {
+  return `<article class="panel container-card" data-container-id="${esc(container.id)}"><div class="container-head"><span class="container-avatar">${esc(container.name.slice(0,1))}</span><div><h3>${esc(container.name)}</h3><small>${container.company ? '企业共享' : '归属于我'}</small></div><span class="state-pill ready">已就绪</span></div><div class="container-meta"><span>2 核 CPU</span><span>4 GB 内存</span><span>平台容器</span></div><p class="container-caption">可以开始使用。</p><div class="container-actions">${button('进入会话 ' + icon('arrow'), 'chat', '', `data-id="${esc(container.id)}"`)}${button('设置', 'settings', 'secondary', `data-id="${esc(container.id)}"`)}</div></article>`;
+}
+
+function containersPage() {
+  if (!state.plan) return `<div class="page"><header class="page-heading"><div><span class="eyebrow">${icon('server')}我的容器</span><h1>我的容器</h1><p>管理你的专属空间。</p></div></header><div class="panel empty-state"><div class="task-orb">${icon('server')}</div><h2>还没有容器</h2><p>选择套餐,开始使用。</p>${button('领取两天试用 ' + icon('arrow'), 'trial')}</div></div>`;
+  const activeJob = state.job && state.job.status !== 'ready';
+  return `<div class="page"><header class="page-heading"><div><span class="eyebrow">${icon('server')}${state.company ? '企业容器' : '我的容器'}</span><h1>${state.company ? '企业容器' : '我的容器'}</h1><p>${state.company ? '团队共享的容器。' : '管理你的专属空间。'}</p></div>${button(icon('plus') + '创建容器', 'create', '', !Demo.canCreate(state) ? 'disabled' : '')}</header>${applicationNotice()}${quotaPanel()}${activeJob ? notice('有一个容器正在开通', '', 'info', 'clock') + button('查看开通进度 ' + icon('arrow'), 'waiting', 'secondary') : ''}${Demo.used(state) >= Demo.limit(state) && !activeJob ? notice('名额已用完', ['advanced','enterprise'].includes(state.plan) ? '可申请增加名额。' : '升级套餐,获取更多名额。', '', 'info') : ''}<div class="container-grid" style="margin-top:var(--sp-5)">${state.containers.map(containerCard).join('')}${Demo.canCreate(state) ? `<button type="button" class="create-card" data-action="create">${icon('plus')}<strong>为新的想法,创建一个空间</strong><p>剩余 ${Demo.limit(state) - Demo.used(state)} 个名额</p></button>` : ''}</div>${!state.containers.length ? '<p class="lead">正在开通,请稍后查看。</p>' : ''}</div>`;
+}
+
+const fakeCredentials = [
+  { group: 'matrix', label: 'agentMxId', value: '@demo-agent:example.invalid' },
+  { group: 'matrix', label: 'userMxId', value: '@demo-user:example.invalid' },
+  { group: 'matrix', label: 'homeserver', value: 'https://matrix.example.invalid' },
+  { group: 'matrix', label: 'roomId', value: '!demo-room:example.invalid' },
+  { group: 'matrix', label: 'accessToken', value: 'DEMO_ONLY_NOT_A_REAL_MATRIX_TOKEN' },
+  { group: 'backend', label: 'appId', value: 'DEMO_APP_ID_NOT_REAL' },
+  { group: 'backend', label: 'serverURL', value: 'https://backend.example.invalid/parse' },
+  { group: 'backend', label: 'functionsURL', value: 'https://backend.example.invalid/functions' },
+  { group: 'backend', label: '独立资源专属凭据', value: 'DEMO_ONLY_RESOURCE_SCOPED_CREDENTIAL' },
+];
+function credentialsPage() {
+  if (!Demo.hasAccess(state) || !state.containers.length) return `<div class="page narrow"><header class="page-heading"><div><span class="eyebrow">${icon('key')}接入信息</span><h1>接入信息</h1><p></p></div></header><div class="panel empty-state"><div class="task-orb">${icon('key')}</div><h2>${state.job ? '正在准备' : '暂无接入信息'}</h2><p>开通完成后可查看。</p>${button(state.job ? '查看开通进度' : '查看套餐', state.job ? 'waiting' : 'plans')}</div></div>`;
+  const panel = (group, heading, text, name) => `<section class="panel resource-panel"><h2>${icon(name)}${heading}</h2><p>${text}</p><dl class="credential-list">${fakeCredentials.filter((field) => field.group === group).map((field) => `<div class="credential-row"><dt>${field.label}</dt><dd><span class="masked-value">••••••••••••</span>${button(icon('copy') + '查看与复制', 'credential', 'ghost', `data-field="${esc(field.label)}"`)}</dd></div>`).join('')}</dl></section>`;
+  const backendPanel = state.company ? `<section class="panel resource-panel"><h2>${icon('cloud')}企业资源</h2><p>请联系企业管理员。</p><p class="credential-fake"></p></section>` : panel('backend', '独立云资源', '', 'cloud');
+  return `<div class="page"><header class="page-heading"><div><span class="eyebrow">${icon('key')}接入信息</span><h1>接入信息</h1><p>当前容器:${esc(state.containers[0].name)}。</p></div></header>${notice('请勿分享密钥', '', '', 'shield')}<div class="resource-grid">${panel('matrix', '通信信息', '', 'chat')}${backendPanel}</div><p class="credential-fake"></p></div>`;
+}
+
+function expiredPage() {
+  return `<div class="page"><section class="expired-intro"><div class="task-orb">${icon('clock')}</div><span class="eyebrow">两天试用已结束</span><h1>试用已结束</h1><p>开通套餐后继续使用。</p></section><section class="preserved-resource">${icon('shield')}<div><strong>${esc(state.containers[0]?.name || '我的协作伙伴')}</strong><p>容器和数据已保留。</p></div><span class="state-pill expired">待开通</span></section>${applicationNotice()}${planCards()}<p class="plans-note">${icon('info')}<span>${priceNotice} </span></p><button type="button" class="text-action" data-view="enterprise">加入企业 ${icon('arrow')}</button></div>`;
+}
+
+function enterprisePage() {
+  const org = state.company;
+  if (!org && state.companyAccount) return `<div class="page narrow"><header class="page-heading"><div><span class="eyebrow">${icon('building')}企业空间</span><h1>企业空间</h1><p></p></div></header><section class="panel empty-state"><div class="task-orb">${icon('building')}</div><h2>示例企业</h2><p>5 个共享容器名额</p>${button('进入企业空间 ' + icon('arrow'), 'switch-company')}</section></div>`;
+  return `<div class="page"><header class="page-heading"><div><span class="eyebrow">${icon('building')}${org ? '企业空间' : '加入企业'}</span><h1>${org ? '企业空间' : '加入企业'}</h1><p>${org ? '' : '联系管理员完成邀请。'}</p></div></header>${org ? quotaPanel() : ''}<div class="enterprise-layout"><section class="panel enterprise-card">${org ? `<div class="company-heading"><span class="container-avatar">企</span><div><h2>示例企业</h2><p>企业成员</p></div></div>${['产品协作组','内容协作组'].map((name,index) => `<div class="company-member"><span class="account-avatar">${index ? '内' : '产'}</span><div><strong>${name}</strong><small>示例成员 · 名下 1 个企业容器</small></div><span class="state-pill ready">可协作</span></div>`).join('')}${button('查看企业容器 ' + icon('arrow'), 'containers', 'secondary', 'style="margin-top:var(--sp-5)"')}` : `<h2>等待加入</h2><p>将用户 ID 发给管理员。</p><div class="copy-id"><div><small>用户 ID</small><strong>DEMO_USER_001</strong></div>${button(icon('copy') + '复制', 'copy-user', 'secondary')}</div><div class="waiting-actions" style="margin-top:var(--sp-5)">${button(icon('refresh') + '我已被邀请,立即检查', 'check-org')}</div>`}</section><aside><section class="panel small-panel" style="margin-top:0"><h3>${icon('people')}企业邀请</h3><p>已有邀请?联系管理员完成加入。</p></section>${!org ? `<section class="panel small-panel"><h3>个人使用</h3><p>查看适合你的个人套餐。</p>${button('查看个人套餐', 'plans', 'secondary', 'style="margin-top:var(--sp-4)"')}</section>` : ''}</aside></div></div>`;
+}
+
+function accountPage() {
+  return `<div class="page narrow"><header class="page-heading"><div><h1>我的账号</h1></div></header><section class="panel"><div class="section-heading"><h2>当前套餐</h2><span class="state-pill ${state.access === 'active' ? 'ready' : state.access === 'expired' ? 'expired' : 'pending'}">${stateLabel()}</span></div><dl class="summary-facts"><div><dt>套餐</dt><dd>${esc(planName())}</dd></div><div><dt>容器名额</dt><dd>${Demo.used(state)} / ${Demo.limit(state)}</dd></div><div><dt>试用状态</dt><dd>${state.plan === 'trial' ? stateLabel() : '—'}</dd></div><div><dt>当前空间</dt><dd>${state.company ? '示例企业' : '个人空间'}</dd></div></dl><div class="waiting-actions" style="margin-top:var(--sp-5)">${button('查看套餐', 'plans')}${button('我的容器', 'containers', 'secondary')}</div></section></div>`;
+}
+
+function chatPage() {
+  if (!Demo.hasAccess(state) || !state.containers.length) return state.access === 'expired' ? expiredPage() : waitingPage();
+  return `<div class="page narrow"><div class="panel empty-state"><div class="task-orb success">${icon('chat')}</div><h2>已就绪</h2><p>${esc(state.containers[0].name)}</p>${button('我的容器', 'containers', 'secondary')}</div></div>`;
+}
+
+function render(resetScroll = false) {
+  nav();
+  document.getElementById('pageLabel').textContent = views[state.view] || views.plans;
+  document.getElementById('headerStatus').innerHTML = icon(state.offline ? 'wifi' : 'shield') + esc(stateLabel());
+  const pages = { plans: plansPage, waiting: waitingPage, containers: containersPage, access: credentialsPage, enterprise: enterprisePage, account: accountPage, expired: expiredPage, chat: chatPage };
+  const subjectSwitcher = state.company || state.companyAccount ? `<div class="subject-switch" aria-label="切换权益主体"><span>当前空间</span><button type="button" data-subject="personal" aria-pressed="${!state.company}">${icon('person')}个人空间</button><button type="button" data-subject="company" aria-pressed="${state.company}">${icon('building')}示例企业</button><small></small></div>` : '';
+  main.innerHTML = subjectSwitcher + (pages[state.view] || plansPage)();
+  if (resetScroll) main.scrollTop = 0;
+  document.getElementById('reviewState').textContent = `当前演示:${state.company ? '企业' : '个人'}空间 · ${planName()} · ${stateLabel()} · 容器 ${Demo.used(state)} 个 · 任务预占 ${Demo.reserved(state)} 个 · 配额 ${Demo.limit(state)} 个${state.job ? ' · 任务 ' + state.job.id + ' · 尝试 ' + state.job.attempt + ' 次' : ''}。所有状态均为本地模拟。`;
+  document.querySelector('[data-event="advance"]').disabled = !state.job || ['ready','failed'].includes(state.job.status) || state.offline;
+  document.querySelector('[data-event="fail"]').disabled = !state.job || state.job.status === 'ready';
+  document.querySelector('[data-event="slow"]').disabled = !state.job || ['ready','failed'].includes(state.job.status);
+  document.querySelector('[data-event="approve"]').disabled = !state.application;
+  document.querySelector('[data-event="expire"]').disabled = state.plan !== 'trial' || state.access !== 'active';
+  document.querySelector('[data-event="join"]').disabled = state.view !== 'enterprise' || state.company;
+  document.querySelector('[data-event="offline"]').textContent = state.offline ? '恢复网络' : '模拟断网';
+  document.getElementById('themeToggle').textContent = document.documentElement.classList.contains('dark') ? '浅色' : '深色';
+}
+
+function toast(message) {
+  clearTimeout(toastTimer);
+  const element = document.getElementById('toast');
+  element.textContent = message; element.classList.add('visible');
+  toastTimer = setTimeout(() => element.classList.remove('visible'), 3400);
+}
+function dispatch(action) {
+  const oldView = state.view;
+  state = Demo.reduce(state, action);
+  render(state.view !== oldView);
+  if (state.note) toast(state.note);
+}
+function go(view) { dispatch({ type: 'view', view }); }
+function closeDialog() { if (dialog.open) dialog.close(); }
+function openDialog(kind, data = {}, trigger = document.activeElement) {
+  dialogContext = { kind, ...data }; dialogTrigger = trigger;
+  const cancel = '<button type="button" class="button secondary" data-close-dialog>暂不操作</button>';
+  if (kind === 'create') {
+    const trial = data.trial;
+    dialogBody.innerHTML = `<form id="createForm"><span class="dialog-kicker">${icon(trial ? 'spark' : 'server')}${trial ? '两天试用' : '创建平台容器'}</span><h2 id="dialogTitle">${trial ? '开始两天试用' : '创建容器'}</h2><p class="dialog-description">${trial ? '1 个专属容器,开通后开始计时。' : '提交后可查看开通进度。'}</p><label class="form-field"><span>容器名称</span><input id="containerName" name="containerName" maxlength="24" required value="${trial ? '我的第一个容器' : '新的协作伙伴'}" autocomplete="off"><small>最多 24 个字符,之后可在容器设置中修改。</small></label><div class="dialog-facts"><div><small>容器规格</small><strong>2 核 4G · 平台容器</strong></div><div><small>${trial ? '试用名额' : '将占用名额'}</small><strong>1 个</strong></div></div>${notice('开通进度', '开通中,请稍后查看。', '', 'shield')}<div class="dialog-actions">${cancel}<button type="submit" class="button">${trial ? '开始开通试用' : '提交创建申请'} ${icon('arrow')}</button></div></form>`;
+  } else if (kind === 'apply') {
+    const name = Demo.PLANS[data.plan].name;
+    dialogBody.innerHTML = `<form id="applyForm"><span class="dialog-kicker">${icon('grid')}套餐开通</span><h2 id="dialogTitle">${state.access === 'expired' ? '开通套餐' : '申请开通' + name}</h2><p class="dialog-description">${name} · 价格待定。请联系客服确认。</p><div class="dialog-facts"><div><small>基础容器上限</small><strong>${Demo.PLANS[data.plan].limit} 个${data.plan === 'enterprise' ? ',企业共享' : ',个人专属'}</strong></div><div><small>当前状态</small><strong>等待开通</strong></div></div>${notice(state.access === 'expired' ? '数据已保留' : '待确认', state.access === 'expired' ? '开通后继续使用。' : '请联系客服。', '', 'info')}<div class="dialog-actions">${cancel}<button type="submit" class="button">提交申请 ${icon('arrow')}</button></div></form>`;
+  } else if (kind === 'addon') {
+    dialogBody.innerHTML = `<form id="addonForm"><span class="dialog-kicker">${icon('plus')}容器名额增配</span><h2 id="dialogTitle">增加容器名额</h2><p class="dialog-description">当前名额 ${Demo.limit(state)} 个。具体价格请咨询客服。</p><label class="form-field"><span>申请增加名额</span><select id="addonQuantity" name="quantity"><option value="1">增加 1 个</option><option value="2">增加 2 个</option><option value="3">增加 3 个</option></select></label>${notice('等待确认', '', '', 'info')}<div class="dialog-actions">${cancel}<button type="submit" class="button">提交申请</button></div></form>`;
+  } else if (kind === 'credential') {
+    dialogBody.innerHTML = `<span class="dialog-kicker">${icon('shield')}敏感信息确认</span><h2 id="dialogTitle">仅供本人使用,请勿外发。</h2><p class="dialog-description">即将查看并复制「${esc(data.field)}」。请妥善保管。</p>${notice('仅供本人使用', '', '', 'info')}<div id="credentialResult" hidden></div><div class="dialog-actions">${cancel}<button type="button" class="button" data-confirm-credential>确认复制</button></div>`;
+  } else if (kind === 'settings') {
+    const container = state.containers.find((item) => item.id === data.id);
+    if (!container) return;
+    dialogBody.innerHTML = `<form id="renameForm"><span class="dialog-kicker">${icon('server')}容器设置</span><h2 id="dialogTitle">容器设置</h2><label class="form-field"><span>容器名称</span><input id="renameInput" maxlength="24" required value="${esc(container.name)}" autocomplete="off"></label><div class="dialog-actions">${cancel}<button type="submit" class="button">保存名称</button></div></form>`;
+  }
+  dialog.showModal(); document.getElementById('dialogClose').focus();
+}
+
+async function copyText(value, message = '已复制') {
+  try {
+    if (!navigator.clipboard?.writeText) throw new Error('unavailable');
+    await navigator.clipboard.writeText(value);
+    return message;
+  } catch { return '浏览器未允许自动复制,可选中文本手动复制。'; }
+}
+
+document.getElementById('dialogClose').addEventListener('click', closeDialog);
+dialog.addEventListener('close', () => { if (dialogTrigger?.isConnected) dialogTrigger.focus({ preventScroll: true }); else main.focus({ preventScroll: true }); });
+dialog.addEventListener('click', (event) => {
+  const rect = dialog.getBoundingClientRect();
+  if (event.target === dialog && (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom)) closeDialog();
+});
+document.addEventListener('click', async (event) => {
+  const target = event.target.closest('button, a');
+  if (!target || target.disabled) return;
+  if (target.hasAttribute('data-close-dialog')) return closeDialog();
+  if (target.dataset.subject) return dispatch({ type: 'subject', subject: target.dataset.subject });
+  if (target.dataset.view) return go(target.dataset.view);
+  if (target.dataset.scenario) { state = Demo.initial(target.dataset.scenario); render(true); return; }
+  if (target.dataset.event) return dispatch({ type: target.dataset.event });
+  if (target.hasAttribute('data-confirm-credential')) {
+    const field = fakeCredentials.find((item) => item.label === dialogContext?.field);
+    if (!field) return;
+    const result = document.getElementById('credentialResult');
+    result.hidden = false; result.replaceChildren();
+    const code = document.createElement('code'); code.className = 'demo-secret'; code.textContent = field.value;
+    const feedback = document.createElement('p'); feedback.className = 'dialog-feedback'; feedback.setAttribute('role', 'status');
+    result.append(code, feedback); target.disabled = true;
+    feedback.textContent = await copyText(field.value, '原型假数据已复制,请勿用于实际接入。');
+    return;
+  }
+  const action = target.dataset.action;
+  if (!action) return;
+  if (['plans','waiting','containers','chat'].includes(action)) return go(action === 'plans' && state.access === 'expired' ? 'expired' : action);
+  if (action === 'trial') return openDialog('create', { trial: true }, target);
+  if (action === 'create') {
+    if (Demo.canCreate(state)) openDialog('create', { trial: false }, target);
+    else toast('当前名额不可用,请查看套餐或开通中的任务。');
+    return;
+  }
+  if (action === 'apply') {
+    const plan = target.dataset.plan;
+    if (plan === 'enterprise' && !state.company) return go('enterprise');
+    if (state.company && plan !== 'enterprise') dispatch({ type: 'subject', subject: 'personal', view: 'plans' });
+    if (state.access === 'active' && state.plan !== 'trial' && Demo.PLANS[plan].limit < Demo.limit(state)) return toast('更换套餐请联系客服。');
+    return openDialog('apply', { plan }, target);
+  }
+  if (action === 'switch-company') return dispatch({ type: 'subject', subject: 'company', view: 'enterprise' });
+  if (action === 'addon') return openDialog('addon', {}, target);
+  if (action === 'credential') return openDialog('credential', { field: target.dataset.field }, target);
+  if (action === 'settings') return openDialog('settings', { id: target.dataset.id }, target);
+  if (action === 'retry') return dispatch({ type: 'retry' });
+  if (action === 'check') return toast(state.offline ? '网络暂时不可用,原任务仍在平台保留。' : '仍在开通中,请稍后查看。');
+  if (action === 'check-org') return toast('仍在等待邀请。');
+  if (action === 'copy-job') return toast(await copyText(state.job?.id || '', '演示任务编号已复制'));
+  if (action === 'copy-user') return toast(await copyText('DEMO_USER_001', '演示用户 ID 已复制'));
+});
+
+document.addEventListener('submit', (event) => {
+  event.preventDefault();
+  const id = event.target.id;
+  if (id === 'createForm') {
+    const name = document.getElementById('containerName').value.trim();
+    if (!name) return;
+    const trial = dialogContext.trial; closeDialog(); dispatch({ type: 'start', name, plan: trial ? 'trial' : state.plan });
+  }
+  if (id === 'applyForm') { const plan = dialogContext.plan; closeDialog(); dispatch({ type: 'apply', plan }); }
+  if (id === 'addonForm') { const quantity = Number(document.getElementById('addonQuantity').value); closeDialog(); dispatch({ type: 'addon', quantity }); }
+  if (id === 'renameForm') {
+    const name = document.getElementById('renameInput').value.trim(); if (!name) return;
+    const containerId = dialogContext.id; closeDialog(); dispatch({ type: 'rename', id: containerId, name }); toast('演示容器名称已修改');
+  }
+});
+document.getElementById('reviewToggle').addEventListener('click', () => {
+  const controls = document.getElementById('reviewControls'); controls.hidden = !controls.hidden;
+  document.getElementById('reviewToggle').setAttribute('aria-expanded', String(!controls.hidden));
+});
+document.getElementById('themeToggle').addEventListener('click', () => { document.documentElement.classList.toggle('dark'); render(); });
+document.querySelector('.brand').addEventListener('click', (event) => { event.preventDefault(); go('plans'); });
+render(true);

+ 16 - 0
prototypes/fmode-subscription-20261125/build.mjs

@@ -0,0 +1,16 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const root = path.dirname(fileURLToPath(import.meta.url));
+const project = path.resolve(root, '../..');
+const read = (name) => fs.readFileSync(path.join(root, name), 'utf8');
+const tokens = ['src/styles.uikit.css', 'src/app/core/styles/_base.scss', 'src/app/core/styles/_palette.scss']
+  .map((name) => fs.readFileSync(path.join(project, name), 'utf8').replace(/^@tailwind[^;]+;\s*/gm, ''))
+  .join('\n');
+const html = read('preview.template.html')
+  .replace('/* INJECT_STYLES */', () => tokens + '\n' + read('styles.css'))
+  .replace('/* INJECT_MODEL */', () => read('model.js'))
+  .replace('/* INJECT_APP */', () => read('app.js'));
+fs.writeFileSync(path.join(root, 'index.html'), html);
+console.log(`Built subscription review prototype: ${Math.round(Buffer.byteLength(html) / 1024)} KB; standalone; no platform requests.`);

+ 1665 - 0
prototypes/fmode-subscription-20261125/index.html

@@ -0,0 +1,1665 @@
+<!doctype html>
+<html lang="zh-CN" data-palette="platinum">
+<head>
+  <meta charset="utf-8">
+  <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
+  <meta name="color-scheme" content="light dark">
+  <meta name="description" content="Fmode 套餐与异步开通交互原型。全部状态均为本地演示,不连接平台、不创建容器、不付款。">
+  <title>Fmode · 套餐与开通交互原型</title>
+  <style>/* ============================================================
+ * UI-Kit Design System
+ * Tailwind CSS v3 + 语义化设计 token
+ * 所有可切换的运行时变量都以 CSS 自定义属性定义在 :root / .dark /
+ * [data-accent="..."] 上,组件模板通过 Tailwind 工具类引用它们;
+ * token → 工具类 的映射见根目录 tailwind.config.js。
+ * ============================================================ */
+
+/* ------------------------------------------------------------
+ * 2. 亮色模式(默认)
+ * ------------------------------------------------------------ */
+:root {
+  color-scheme: light;
+
+  --canvas: #f6f7f9;
+  --surface: #ffffff;
+  --surface-2: #f1f3f6;
+  --surface-hover: #f6f7f9;
+  --surface-active: #eef1f5;
+
+  --edge: #e4e7ec;
+  --edge-strong: #cbd2da;
+
+  /* 文字层级全部对白底达到 WCAG AA 4.5:1:
+     ink ≈14.7:1 / ink-2 ≈8.0:1 / muted ≈4.8:1。
+     ⚠️ faint 为 #9aa1ac(≈2.6:1),**仅限装饰**——
+        分隔线、图标底、占位图形;禁止用于任何承载信息的文字。 */
+  --ink: #1f2733;
+  --ink-2: #4a5568;
+  --muted: #6b7280;
+  --faint: #9aa1ac;
+  --inverse: #ffffff;
+
+  /* 强调色:靛蓝。避开 Tailwind 默认蓝(#2563eb)的"模板感" */
+  --primary: #3b5bdb;
+  --primary-hover: #3450c4;
+  --primary-active: #2c44a8;
+  --primary-subtle: #eef1fd;
+  --primary-content: #ffffff;
+  --primary-ring: rgb(59 91 219 / 0.35);
+
+  /* 语义色:一律"深字 + 浅底",保证小字标签也能过 AA */
+  --success: #047857;
+  --success-subtle: #e7f5ef;
+  --danger: #b91c1c;
+  --danger-subtle: #fdecec;
+  --warning: #a04b08;
+  --warning-subtle: #fdf1dc;
+  --info: #0369a1;
+  --info-subtle: #e6f2fa;
+
+  /* 阴影(对齐 tailwind.config boxShadow.soft,供 SCSS 组件内联引用) */
+  --shadow-soft: 0 1px 2px rgb(15 23 42 / 0.04), 0 4px 12px rgb(15 23 42 / 0.06);
+}
+
+/* ------------------------------------------------------------
+ * 4. 浮层层级体系(z-index token,由低到高)
+ *    所有浮层组件统一引用,禁止再写散落的 z-40/z-50 魔数:
+ *    - affix     吸顶/吸底元素
+ *    - float     悬浮按钮(back-top / tabbar / floating-bubble 等)
+ *    - mask      局部点击遮罩(popconfirm / select / cascader / time-picker /
+ *                data-table 列设置与筛选 / 横向 menu 的收起遮罩)
+ *    - popover   局部浮层面板(dropdown / tooltip / select / date-picker /
+ *                cascader / autocomplete / time-picker 面板、popconfirm 气泡等)
+ *    - modal     全屏弹层遮罩+面板(modal / drawer / 移动端弹层),
+ *                多个同时打开时由 OverlayStackService 在上层动态递增
+ *    - context-menu  右键菜单
+ *    - palette   命令面板全屏遮罩
+ *    - toast     全局消息,永远最高
+ *    层级关系:页面内容 < affix < float < mask < popover < modal <
+ *              context-menu < palette < toast。
+ *    注意:popover < modal,因此 modal 打开时页面上的局部浮层不会穿透;
+ *    modal 内部的浮层则由 modal 面板的 stacking context 兜底,正常显示在其上。
+ * ------------------------------------------------------------ */
+:root {
+  /* 浮层层级体系(从低到高,保证浮层永远盖住页面内容) */
+  --z-affix: 900;        /* 固钉 / 回到顶部 */
+  --z-float: 950;        /* 悬浮按钮 / 悬浮气泡 */
+  --z-mask: 980;         /* 透明遮罩 */
+  --z-popover: 1000;     /* 气泡 / 下拉 / 选择器 / 日期面板 / 气泡确认 */
+  --z-modal: 1100;       /* 抽屉 / 对话框 */
+  --z-context-menu: 1150;/* 右键菜单 */
+  --z-palette: 1200;     /* 命令面板 */
+  --z-preview: 1300;     /* 图片预览灯箱 */
+  --z-toast: 1400;       /* 全局消息通知(最高) */
+}
+
+/* ------------------------------------------------------------
+ * 3. 暗色模式(<html class="dark">)
+ * ------------------------------------------------------------ */
+.dark {
+  color-scheme: dark;
+
+  --canvas: #16181d;
+  --surface: #1e2128;
+  --surface-2: #272b33;
+  --surface-hover: #272b33;
+  --surface-active: #333842;
+
+  --edge: #2e333c;
+  --edge-strong: #454b56;
+
+  --ink: #f2f4f7;
+  --ink-2: #c9cfd8;
+  --muted: #98a1ad;
+  --faint: #6b727d;
+  --inverse: #16181d;
+
+  --primary: #7b93ff;
+  --primary-hover: #94a8ff;
+  --primary-active: #5c78e8;
+  --primary-subtle: rgb(123 147 255 / 0.16);
+  --primary-content: #14161b;
+  --primary-ring: rgb(123 147 255 / 0.4);
+
+  --success: #34d399;
+  --success-subtle: rgb(52 211 153 / 0.14);
+  --danger: #f87171;
+  --danger-subtle: rgb(248 113 113 / 0.14);
+  --warning: #fbbf24;
+  --warning-subtle: rgb(251 191 36 / 0.14);
+  --info: #38bdf8;
+  --info-subtle: rgb(56 189 248 / 0.14);
+}
+
+/* ------------------------------------------------------------
+ * 4. 主题色(accent)切换:覆盖 --primary 系列变量
+ *    亮/暗各一套。data-accent 由 ThemeService 写到 <html> 上。
+ * ------------------------------------------------------------ */
+[data-accent='violet'] {
+  --primary: #7c3aed;
+  --primary-hover: #6d28d9;
+  --primary-active: #5b21b6;
+  --primary-subtle: #f0ebfe;
+  --primary-ring: rgb(124 58 237 / 0.35);
+}
+.dark[data-accent='violet'] {
+  --primary: #8b5cf6;
+  --primary-hover: #a78bfa;
+  --primary-active: #7c3aed;
+  --primary-subtle: rgb(139 92 246 / 0.16);
+  --primary-ring: rgb(139 92 246 / 0.4);
+}
+
+[data-accent='emerald'] {
+  --primary: #059669;
+  --primary-hover: #047857;
+  --primary-active: #065f46;
+  --primary-subtle: #e7f6ef;
+  --primary-ring: rgb(5 150 105 / 0.35);
+}
+.dark[data-accent='emerald'] {
+  --primary: #10b981;
+  --primary-hover: #34d399;
+  --primary-active: #059669;
+  --primary-subtle: rgb(16 185 129 / 0.16);
+  --primary-ring: rgb(16 185 129 / 0.4);
+}
+
+[data-accent='rose'] {
+  --primary: #e11d48;
+  --primary-hover: #be123c;
+  --primary-active: #9f1239;
+  --primary-subtle: #fde8ee;
+  --primary-ring: rgb(225 29 72 / 0.35);
+}
+.dark[data-accent='rose'] {
+  --primary: #f43f5e;
+  --primary-hover: #fb7185;
+  --primary-active: #e11d48;
+  --primary-subtle: rgb(244 63 94 / 0.16);
+  --primary-ring: rgb(244 63 94 / 0.4);
+}
+
+[data-accent='amber'] {
+  --primary: #d97706;
+  --primary-hover: #b45309;
+  --primary-active: #92400e;
+  --primary-subtle: #fdf1dc;
+  --primary-ring: rgb(217 119 6 / 0.35);
+}
+.dark[data-accent='amber'] {
+  --primary: #f59e0b;
+  --primary-hover: #fbbf24;
+  --primary-active: #d97706;
+  --primary-subtle: rgb(245 158 11 / 0.16);
+  --primary-ring: rgb(245 158 11 / 0.4);
+}
+
+[data-accent='cyan'] {
+  --primary: #0891b2;
+  --primary-hover: #0e7490;
+  --primary-active: #155e75;
+  --primary-subtle: #e0f6fb;
+  --primary-ring: rgb(8 145 178 / 0.35);
+}
+.dark[data-accent='cyan'] {
+  --primary: #06b6d4;
+  --primary-hover: #22d3ee;
+  --primary-active: #0891b2;
+  --primary-subtle: rgb(6 182 212 / 0.16);
+  --primary-ring: rgb(6 182 212 / 0.4);
+}
+
+/* ------------------------------------------------------------
+ * 5. 基础(base)样式
+ * ------------------------------------------------------------ */
+@layer base {
+  * {
+    border-color: var(--edge);
+  }
+
+  html {
+    scroll-behavior: smooth;
+    -webkit-tap-highlight-color: transparent;
+  }
+
+  body {
+    background-color: var(--canvas);
+    color: var(--ink);
+    /* Inter 优先(行业标配数字界面字体),本机没有则优雅回退到系统字体栈 */
+    font-family:
+      'Inter', ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue',
+      Arial, 'Noto Sans', 'PingFang SC', 'Microsoft YaHei', sans-serif;
+    font-size: 16px;
+    line-height: 1.6;
+    -webkit-font-smoothing: antialiased;
+    -moz-osx-font-smoothing: grayscale;
+  }
+
+  /* 全局可见焦点环(键盘导航可达性) */
+  :focus-visible {
+    outline: 2px solid var(--primary-ring);
+    outline-offset: 2px;
+  }
+
+  ::selection {
+    background-color: var(--primary);
+    color: var(--primary-content);
+  }
+
+  /* 滚动条 */
+  ::-webkit-scrollbar {
+    width: 10px;
+    height: 10px;
+  }
+  ::-webkit-scrollbar-track {
+    background: transparent;
+  }
+  ::-webkit-scrollbar-thumb {
+    background: var(--edge-strong);
+    border-radius: 9999px;
+    border: 2px solid var(--canvas);
+  }
+  ::-webkit-scrollbar-thumb:hover {
+    background: var(--muted);
+  }
+}
+
+/* ============================================================
+ * 主题切换动画(View Transitions API)
+ * 关闭浏览器默认的根快照动画,改由 ThemeService 通过 Web Animations
+ * 控制 ::view-transition-new(root) / old(root):
+ *  - circle:以触发按钮为圆心的向外扩散
+ *  - wave  :从左往右的波浪式扫过
+ *  - fade  :平滑淡入淡出
+ *  - zoom  :缩放聚焦
+ * ============================================================ */
+::view-transition-old(root),
+::view-transition-new(root) {
+  animation: none;
+  mix-blend-mode: normal;
+}
+
+/* ============================================================
+ * 后台管理系统辅助模式(灰阶 / 色弱)
+ * 应用在 <html> 根元素上,而非局部容器:
+ * 若加在容器上,filter 会创建新的包含块,导致内部 position:fixed
+ * 浮层(抽屉/对话框/下拉面板)定位错乱。根元素上则不影响任何浮层。
+ * ============================================================ */
+html.ui-admin-gray {
+  filter: grayscale(1);
+}
+
+html.ui-admin-color-weak {
+  filter: invert(0.8) hue-rotate(180deg);
+}
+
+/* ============================================================
+ * 浮层层级体系(统一 z-index,保证浮层永远在最上层)
+ *  - 900  回到顶部
+ *  - 1000 气泡/下拉/选择器/日期面板(触发器上的悬浮层)
+ *  - 1100 抽屉/对话框/右键菜单
+ *  - 1200 命令面板
+ *  - 1300 图片预览灯箱
+ * ============================================================ */
+
+
+/* ============================================================
+ * 6. 学员端增量令牌段(D11 · 自 demo/assets/css/tokens.css 移植)
+ * ------------------------------------------------------------
+ * ⚠️ 纯追加:只定义新名字,不覆盖既有令牌 → 管理端零影响。
+ *    冲突名处理:
+ *     - --surface 已被 ui-kit 占用(卡片面 #fff),demo 的「输入底/次级面」
+ *       更名为 --well;
+ *     - --ink 两库值近似(#1f2733 vs #1C1E21),沿用 ui-kit 原值不重定义。
+ *    暗色跟随 ui-kit 既有机制:html.dark 类(ThemeService 单写入);
+ *    accent 走 [data-accent],新增 cobalt/green/indigo 三名并同步
+ *    映射 --primary 系列(管理端主题选择器选中新色时依然可用)。
+ *    data-font/data-radius/data-density/data-motion 变体在应用侧
+ *    (apps/web/src/styles/learner-tokens.css),不进底座。
+ * ============================================================ */
+:root {
+  /* 字体栈(学员端;中文优先) */
+  --font-ui: "PingFang SC", "Noto Sans SC", "HarmonyOS Sans SC", "Microsoft YaHei",
+    -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
+
+  /* 字号 12 级 */
+  --fs-9: 10.5px;  --fs-10: 11px;  --fs-11: 11.5px; --fs-12: 12px;
+  --fs-13: 13px;   --fs-135: 13.5px; --fs-15: 15px; --fs-17: 17px;
+  --fs-20: 20px;   --fs-26: 26px;  --fs-30: 30px;   --fs-42: 42px;
+
+  /* 间距 */
+  --sp-1: 4px; --sp-2: 8px; --sp-3: 12px; --sp-4: 16px;
+  --sp-5: 20px; --sp-6: 24px; --sp-8: 32px;
+
+  /* 圆角 */
+  --r-tag: 999px;
+  --r-sm: 11px;   /* 小件:图标块 / 引文 */
+  --r-md: 14px;   /* 输入 / 小卡 */
+  --r-lg: 18px;   /* 任务条 / 记录条 */
+  --r-xl: 20px;   /* 场景卡 / 卡片 */
+  --r-2xl: 24px;  /* 报告大卡 */
+  --r-sheet: 32px;/* 底部抽屉 */
+
+  /* 墨色五级(新名,不覆盖 ui-kit --ink/--ink-2/--muted) */
+  --ink-deep: #0A1317;   /* 近黑:选中底 / 深色 CTA */
+  --charcoal: #444950;   /* 次文本 */
+  --steel: #5D6C7B;      /* 三级文本 / 图标 */
+  --stone: #8595A4;      /* 弱文本 */
+  --hairline: #CED0D4;   /* 控件描边 */
+  --line: #DEE3E9;       /* 卡片描边 / 分隔 */
+  --well: #F1F4F7;       /* 输入底 / 次级面(demo --surface 改名) */
+  --card: #FFFFFF;
+  --page: #FFFFFF;       /* 学员端页面底 */
+  --sel-bg: #0A1317; --sel-fg: #FFFFFF;   /* tab/chip 选中(暗色下反转) */
+  --overlay: rgba(10, 19, 23, .5);
+  --overlay-strong: rgba(10, 19, 23, .86);   /* 灯箱专用深色遮罩 */
+  --on-overlay: #ffffff; --on-overlay-soft: rgb(255 255 255 / .14); --on-overlay-hover: rgb(255 255 255 / .24);
+  --sheet-shadow: 0 -12px 40px rgba(10, 19, 23, .18);
+  --shadow-card: 0 1px 2px rgba(10, 19, 23, .04);
+
+  /* 毛玻璃(底部导航 / 悬浮工具条) */
+  --glass: rgba(255, 255, 255, .72);
+  --glass-strong: rgba(255, 255, 255, .86);
+  --glass-border: rgba(10, 19, 23, .08);
+  --glass-shadow: 0 8px 30px rgba(10, 19, 23, .14);
+  --glass-tint: rgba(10, 19, 23, .34);
+
+  /* 语义色(v2 原值) */
+  --ok: #31A24C;  --ok-bg: #EAF7EF;  --ok-ink: #1F7A38;
+  --warn-ink: #B26A00; --warn-bg: #FEF6E6;
+  --crit: #E41E3F; --crit-ink: #C81836; --crit-soft: #FDECEF;
+  --info-bg: #E7F0FD;
+
+  /* 强调色(默认 cobalt) */
+  --accent: #0064E0; --accent-deep: #0457CB;
+  --accent-soft: #E7F0FD; --accent-tint: #F0F7FF;
+
+  /* 「压在实色上」的前景色 —— 独立评审 A-7:此前这几处散落 #fff 字面量。
+     单开语义位而不是复用 --surface:后者在暗色下会翻成深色,而这几个前景
+     必须始终是与底色拉开对比的那一头。 */
+  --accent-fg: #FFFFFF;
+  --crit-fg: #FFFFFF;
+  --switch-knob: #FFFFFF;
+  /* 毛玻璃药丸顶部高光的渐变起点(暗色下要弱得多,故必须进令牌) */
+  --glass-sheen: rgba(255, 255, 255, .42);
+  /* 氛围背景的第二、三团柔光的色相 —— 与主题色无关(不随 accent / 明暗变化,
+     暗色只压透明度),但仍是色值,按规范收进令牌而非留在组件里 */
+  --bgfx-teal: rgba(94, 234, 212, .35);
+  --bgfx-violet: rgba(167, 139, 250, .28);
+
+  /* 图表(8 色,亮) */
+  --chart-1: #0064E0; --chart-2: #31A24C; --chart-3: #B26A00; --chart-4: #E41E3F;
+  --chart-5: #0E9DD7; --chart-6: #7857FF; --chart-7: #0E9384; --chart-8: #5D6C7B;
+  --chart-grid: #DEE3E9; --chart-axis: #8595A4; --chart-area: rgba(0, 100, 224, .16);
+}
+
+/* ---- 暗色(跟随 html.dark,ThemeService 单写入) ---- */
+.dark {
+  --ink-deep: #F5F6F7;
+  --charcoal: #D3D5DA;
+  --steel: #98A0AA;
+  --stone: #6C7480;
+  --hairline: #3A3E45;
+  --line: #2C2F35;
+  --well: #1C1E21;
+  --card: #1C1E21;
+  --page: #000000;
+  --sel-bg: #F5F5F7; --sel-fg: #0A1317;
+  --overlay: rgba(0, 0, 0, .6);
+  --sheet-shadow: 0 -12px 40px rgba(0, 0, 0, .5);
+  --shadow-card: 0 1px 2px rgba(0, 0, 0, .3);
+  --glass: rgba(28, 30, 33, .72);
+  --glass-strong: rgba(28, 30, 33, .88);
+  --glass-border: rgba(255, 255, 255, .09);
+  --glass-shadow: 0 8px 30px rgba(0, 0, 0, .5);
+  --glass-tint: rgba(255, 255, 255, .13);
+
+  --ok: #30D158;  --ok-bg: rgba(48, 209, 88, .15);  --ok-ink: #5BD677;
+  --warn-ink: #FFB340; --warn-bg: rgba(255, 179, 64, .14);
+  --crit: #FF453A; --crit-ink: #FF6961; --crit-soft: rgba(255, 69, 58, .15);
+  --info-bg: rgba(41, 151, 255, .16);
+
+  --accent: #2997FF; --accent-deep: #5CB3FF;
+  --accent-soft: rgba(41, 151, 255, .17); --accent-tint: rgba(41, 151, 255, .09);
+
+  /* 暗色下这三处仍是白(底色 accent/crit 在暗色里更亮,白字对比反而更好) */
+  --accent-fg: #FFFFFF;
+  --crit-fg: #FFFFFF;
+  --switch-knob: #FFFFFF;
+  --glass-sheen: rgba(255, 255, 255, .09);
+
+  --chart-1: #2997FF; --chart-2: #30D158; --chart-3: #FFB340; --chart-4: #FF6961;
+  --chart-5: #64D2FF; --chart-6: #A78BFF; --chart-7: #66D4CF; --chart-8: #98A0AA;
+  --chart-grid: #2C2F35; --chart-axis: #6C7480; --chart-area: rgba(41, 151, 255, .2);
+}
+
+/* ---- 新增 accent:cobalt(显式规则兜底) ---- */
+:root[data-accent='cobalt'] {
+  --accent: #0064E0; --accent-deep: #0457CB; --accent-soft: #E7F0FD; --accent-tint: #F0F7FF;
+  --chart-1: #0064E0; --chart-area: rgba(0, 100, 224, .16);
+  --primary: #0064E0; --primary-hover: #0457CB; --primary-active: #0448a8;
+  --primary-subtle: #E7F0FD; --primary-ring: rgb(0 100 224 / .35);
+}
+.dark[data-accent='cobalt'] {
+  --accent: #2997FF; --accent-deep: #5CB3FF; --accent-soft: rgba(41, 151, 255, .17); --accent-tint: rgba(41, 151, 255, .09);
+  --chart-1: #2997FF; --chart-area: rgba(41, 151, 255, .2);
+  --primary: #2997FF; --primary-hover: #5CB3FF; --primary-active: #0064E0;
+  --primary-subtle: rgb(41 151 255 / .16); --primary-ring: rgb(41 151 255 / .4);
+}
+
+/* ---- 新增 accent:green ---- */
+:root[data-accent='green'] {
+  --accent: #1F8A3B; --accent-deep: #15702F; --accent-soft: #E4F6E9; --accent-tint: #F0FBF3;
+  --chart-1: #1F8A3B; --chart-area: rgba(31, 138, 59, .16);
+  --primary: #1F8A3B; --primary-hover: #15702F; --primary-active: #0f5a26;
+  --primary-subtle: #E4F6E9; --primary-ring: rgb(31 138 59 / .35);
+}
+.dark[data-accent='green'] {
+  --accent: #30D158; --accent-deep: #69DE85; --accent-soft: rgba(48, 209, 88, .16); --accent-tint: rgba(48, 209, 88, .09);
+  --chart-1: #30D158; --chart-area: rgba(48, 209, 88, .2);
+  --primary: #30D158; --primary-hover: #69DE85; --primary-active: #1F8A3B;
+  --primary-subtle: rgb(48 209 88 / .16); --primary-ring: rgb(48 209 88 / .4);
+}
+
+/* ---- 新增 accent:indigo ---- */
+:root[data-accent='indigo'] {
+  --accent: #5856D6; --accent-deep: #4442BE; --accent-soft: #ECEBFC; --accent-tint: #F4F3FE;
+  --chart-1: #5856D6; --chart-area: rgba(88, 86, 214, .16);
+  --primary: #5856D6; --primary-hover: #4442BE; --primary-active: #3836a3;
+  --primary-subtle: #ECEBFC; --primary-ring: rgb(88 86 214 / .35);
+}
+.dark[data-accent='indigo'] {
+  --accent: #7D7AFF; --accent-deep: #9B99FF; --accent-soft: rgba(125, 122, 255, .17); --accent-tint: rgba(125, 122, 255, .09);
+  --chart-1: #7D7AFF; --chart-area: rgba(125, 122, 255, .2);
+  --primary: #7D7AFF; --primary-hover: #9B99FF; --primary-active: #5856D6;
+  --primary-subtle: rgb(125 122 255 / .17); --primary-ring: rgb(125 122 255 / .4);
+}
+
+/* ---- amber/rose 补 accent 系令牌(demo 五套主题色的剩余两套) ---- */
+:root[data-accent='amber'] {
+  --accent: #B26A00; --accent-deep: #8F5400; --accent-soft: #FDF0DA; --accent-tint: #FEF8EE;
+  --chart-1: #B26A00; --chart-area: rgba(178, 106, 0, .16);
+}
+.dark[data-accent='amber'] {
+  --accent: #FFB340; --accent-deep: #FFC666; --accent-soft: rgba(255, 179, 64, .16); --accent-tint: rgba(255, 179, 64, .09);
+  --chart-1: #FFB340; --chart-area: rgba(255, 179, 64, .2);
+}
+:root[data-accent='rose'] {
+  --accent: #D8264A; --accent-deep: #B01B3B; --accent-soft: #FCE7EB; --accent-tint: #FEF2F4;
+  --chart-1: #D8264A; --chart-area: rgba(216, 38, 74, .15);
+}
+.dark[data-accent='rose'] {
+  --accent: #FF6961; --accent-deep: #FF8B85; --accent-soft: rgba(255, 105, 97, .16); --accent-tint: rgba(255, 105, 97, .09);
+  --chart-1: #FF6961; --chart-area: rgba(255, 105, 97, .2);
+}
+
+/* ---- blue/violet/emerald/cyan 的 --accent 映射(学员端组件引用 --accent* 时跟随切换) ---- */
+:root[data-accent='blue'], :root:not([data-accent]) {
+  --accent: #3b5bdb; --accent-deep: #364fc7; --accent-soft: #e7edfb; --accent-tint: #f2f6fd;
+  --chart-1: #3b5bdb; --chart-area: rgb(59 91 219 / .16);
+}
+.dark[data-accent='blue'], .dark:not([data-accent]) {
+  --accent: #748ffc; --accent-deep: #91a7ff; --accent-soft: rgb(116 143 252 / .16); --accent-tint: rgb(116 143 252 / .09);
+  --chart-1: #748ffc; --chart-area: rgb(116 143 252 / .2);
+}
+:root[data-accent='violet'] {
+  --accent: #7c3aed; --accent-deep: #6d28d9; --accent-soft: #f0e9fd; --accent-tint: #f8f5fe;
+  --chart-1: #7c3aed; --chart-area: rgb(124 58 237 / .16);
+}
+.dark[data-accent='violet'] {
+  --accent: #a78bfa; --accent-deep: #c4b5fd; --accent-soft: rgb(167 139 250 / .16); --accent-tint: rgb(167 139 250 / .09);
+  --chart-1: #a78bfa; --chart-area: rgb(167 139 250 / .2);
+}
+:root[data-accent='emerald'] {
+  --accent: #059669; --accent-deep: #047857; --accent-soft: #e2f6ee; --accent-tint: #f0faf6;
+  --chart-1: #059669; --chart-area: rgb(5 150 105 / .16);
+}
+.dark[data-accent='emerald'] {
+  --accent: #34d399; --accent-deep: #6ee7b7; --accent-soft: rgb(52 211 153 / .16); --accent-tint: rgb(52 211 153 / .09);
+  --chart-1: #34d399; --chart-area: rgb(52 211 153 / .2);
+}
+:root[data-accent='cyan'] {
+  --accent: #0891b2; --accent-deep: #0e7490; --accent-soft: #e0f6fb; --accent-tint: #effbfe;
+  --chart-1: #0891b2; --chart-area: rgb(8 145 178 / .16);
+}
+.dark[data-accent='cyan'] {
+  --accent: #06b6d4; --accent-deep: #22d3ee; --accent-soft: rgb(6 182 212 / .16); --accent-tint: rgb(6 182 212 / .09);
+  --chart-1: #06b6d4; --chart-area: rgb(6 182 212 / .2);
+}
+
+/* 基底令牌(原型 :root / midnight)+ 明暗模式 + 布局/动效/阴影
+   真源 styles.css:2-73 | 依据《设计令牌.md》v3.0 §三·§六·§七·§八·§九
+   说明:语义色跨配色固定,故在此定义(palette 只覆盖表面/导航/主色族)。
+   命名一律用 ui-kit 词汇(--canvas/--ink/--edge/--primary…),禁止自有前缀。*/
+
+:root {
+  /* 表面与文字 */
+  --canvas: #edf1f6; --surface: #ffffff; --surface-2: #f5f7fa; --surface-hover: #eaf0f7;
+  --surface-active: #dfe6f0; --rail-surface: #f0f3f8;
+  --edge: #dce3ed; --edge-strong: #c5d0df;
+  --ink: #172337; --ink-2: #495b74; --muted: #61728a; --inverse: #ffffff;
+
+  /* 语义色(跨配色固定)—— info 取原型值,非底座 #0369a1(评审 S2)
+     --on-danger:danger 底上的文字色。暗色下 --danger 是浅粉,故文字须用深色 */
+  --success: #207550; --success-subtle: #edf7f1;
+  --warning: #91600e; --warning-subtle: #fff7e8;
+  --danger: #c33f42; --danger-subtle: #fff0f0; --on-danger: #ffffff;
+  --info: #315fa8; --info-subtle: #edf3fd;
+
+  /* 主色(基底;4 套配色整体覆盖)—— --primary-ring 为推导值(原型未定义 focus 环) */
+  --primary: #315acb; --primary-hover: #2548aa; --primary-active: #2548aa;
+  --primary-subtle: #eaf0ff; --primary-content: #ffffff; --primary-ring: rgb(49 90 203 / .35);
+
+  /* 导航族(随配色整套变化) */
+  --nav-surface: #18243a; --nav-ink: #f3f6fc; --nav-text: #c4cfdf; --nav-muted: #9aadc8;
+  --nav-line: #30405a; --nav-hover: #24334d; --nav-active: #2c4167;
+  --nav-accent: #b4ccff; --nav-brand: #4269d8; --nav-on-brand: #ffffff;
+
+  /* 辅助族 */
+  --metric-fill: #5476ca;
+  --avatar-ink: #46618c; --avatar-bg: #eaf0fa; --avatar-ink-alt: #596780; --avatar-bg-alt: #edf0f5;
+  --neutral: #687385; --neutral-soft: #eff1f5;
+  --overlay: #18223966; --overlay-strong: #182239d9;
+  /* 深色遮罩上的前景色:明暗主题下都保持浅色(灯箱/全屏预览用) */
+  --on-overlay: #ffffff;
+  --on-overlay-soft: rgb(255 255 255 / .14);
+  --on-overlay-hover: rgb(255 255 255 / .24);
+
+  /* 字号:锁定 8 档(名称 = 底座,数值 = 原型) */
+  --fs-11: 11px; --fs-12: 12px; --fs-13: 13px; --fs-14: 14px;
+  --fs-15: 14px; --fs-17: 16px; --fs-20: 20px; --fs-26: 28px; --fs-42: 36px;
+
+  /* 圆角:锁定 4 档 */
+  --r-sm: 6px; --r-md: 10px; --r-lg: 16px; --r-tag: 999px;
+
+  /* 动效(底座无此层,由原型引入) */
+  --motion-fast: 120ms; --motion-page: 160ms; --motion-detail: 200ms;
+  --motion-panel: 240ms; --motion-exit: 160ms;
+  --ease-standard: cubic-bezier(.2, 0, 0, 1);
+
+  /* 阴影四级(色基取原型,结构沿用底座;修复底座暗色不可见缺陷) */
+  --shadow-soft: 0 1px 2px rgb(23 36 60 / .04), 0 4px 12px rgb(23 36 60 / .06);
+  --shadow-card: 0 1px 2px rgb(23 36 60 / .05), 0 8px 24px rgb(23 36 60 / .07);
+  --shadow-pop: 0 4px 8px rgb(23 36 60 / .08), 0 16px 32px rgb(23 36 60 / .12);
+  --shadow-overlay: 0 8px 16px rgb(23 36 60 / .1), 0 24px 48px rgb(23 36 60 / .18);
+  /* 布局令牌 —— 前缀用 --desk-/--mob-(--dk- 是存量禁用前缀);--desk-nav-w* 已随竖栏废弃 */
+  --desk-topbar-h: 56px; --desk-tree-w: 280px; --desk-nav-w: 200px; --desk-nav-w-compact: 176px; --desk-nav-w-icon: 72px;
+  --desk-list-w: 274px; --desk-list-w-compact: 244px; --desk-list-w-narrow: 250px;
+  --desk-main-min-w: 480px; --desk-aside-w: 320px; --desk-aside-w-compact: 300px;
+  --mob-navbar-h: 60px; --mob-tabbar-h: 64px; --mob-gutter: 16px;
+  --mob-safe-top: env(safe-area-inset-top, 0px);
+  --mob-safe-bottom: env(safe-area-inset-bottom, 0px);
+  --touch-min: 44px; /* 无障碍硬约束,非设计偏好 */
+
+  /* 页面最大宽度(《双端布局规范》v2.1 §2.4)—— 窗口更宽时居中留白,避免超宽屏内容拉散 */
+  --page-max-w: 1440px;          /* 通用/仪表盘类 */
+  --page-max-w-narrow: 980px;    /* 阅读型(事件流) */
+  --page-max-w-settings: 1240px; /* 设置页 */
+}
+
+/* 暗色:--inverse 与 --primary-content 同源统一(评审 A5) */
+.dark {
+  --canvas: #11151c; --surface: #191f29; --surface-2: #1e2531; --surface-hover: #2a3342;
+  --surface-active: #333c4c; --rail-surface: #141b26;
+  --edge: #2d3747; --edge-strong: #414f65;
+  --ink: #edf1f8; --ink-2: #b8c2d2; --muted: #98a6bc; --inverse: #14203b;
+
+  --success: #8ed2ac; --success-subtle: #1d352c;
+  --warning: #e8bf77; --warning-subtle: #382f22;
+  --danger: #f2a0a5; --danger-subtle: #3b272f; --on-danger: #3b272f;
+  --info: #acc9fa; --info-subtle: #273a55;
+
+  --primary: #93b5ff; --primary-hover: #b0c9ff; --primary-active: #93b5ff;
+  --primary-subtle: #253451; --primary-content: #14203b; --primary-ring: rgb(147 181 255 / .4);
+
+  --nav-surface: #0c1320; --nav-hover: #1a2940; --nav-active: #243957; --nav-line: #25324a;
+
+  --metric-fill: #a8c2ff;
+  --avatar-ink: #b7cdf2; --avatar-bg: #2b3b56; --avatar-ink-alt: #bac7db; --avatar-bg-alt: #2d3748;
+  --neutral: #acb7c9; --neutral-soft: #2b3341;
+  --overlay: #070b12a6; --overlay-strong: #070b12e6;
+  --on-overlay: #ffffff; --on-overlay-soft: rgb(255 255 255 / .14); --on-overlay-hover: rgb(255 255 255 / .24);
+
+  --shadow-soft: 0 1px 2px rgb(0 0 0 / .3), 0 4px 12px rgb(0 0 0 / .28); --shadow-card: 0 1px 2px rgb(0 0 0 / .34), 0 8px 24px rgb(0 0 0 / .32);
+  --shadow-pop: 0 4px 8px rgb(0 0 0 / .38), 0 16px 32px rgb(0 0 0 / .34); --shadow-overlay: 0 8px 16px rgb(0 0 0 / .42), 0 24px 48px rgb(0 0 0 / .4);
+}
+
+/* 四套「整体配色」· 应用层覆盖块(令牌数据,非业务样式)
+   真源 styles.css:116-195 | 依据 ADR-006 v2.0 §三 +《设计令牌.md》v3.0 §四
+   🔴 必须用 :root[data-palette] / .dark[data-palette](与底座同特异性,评审 G4)
+   语义色不在此:跨配色固定,定义在 styles.scss
+
+   🔑 同时命中 [data-preview-palette] —— 让「我的」页的配色缩略图能在各自作用域内
+      渲染出**该套配色自身**的 nav/content 色块(否则缩略图只显示当前配色,看不出差异)。*/
+/* ---------- platinum · 铂金曜黑(默认)---------- */
+:root[data-palette='platinum'],
+[data-preview-palette='platinum'] {
+  --canvas: #f2f3f5; --surface: #ffffff; --surface-2: #f7f7f8; --surface-hover: #e9eaec;
+  --rail-surface: #eceef0; --ink: #202124; --ink-2: #45474b; --muted: #62666d;
+  --edge: #dfe1e4; --edge-strong: #c4c7cc;
+  --primary: #25272a; --primary-hover: #111214; --primary-subtle: #e8e9eb; --primary-content: #ffffff;
+  --nav-surface: #202124; --nav-ink: #f5f5f6; --nav-text: #c6c8cc; --nav-muted: #a9adb4;
+  --nav-line: #393b3f; --nav-hover: #303236; --nav-active: #3b3d41;
+  --nav-accent: #ffffff; --nav-brand: #f5f5f6; --nav-on-brand: #202124;
+  --metric-fill: #6c737d;
+  --avatar-ink: #565d67; --avatar-bg: #e9eaec; --avatar-ink-alt: #62666d; --avatar-bg-alt: #eeeff0;
+  --neutral: #656a72; --neutral-soft: #eceef0;
+  --overlay: #11121470; --overlay-strong: #111214d9; --shadow: 0 16px 56px #2021241f;
+}
+.dark[data-palette='platinum'],
+[data-preview-palette='platinum'][data-preview-theme='dark'] {
+  --canvas: #18191b; --surface: #222426; --surface-2: #292b2e; --surface-hover: #383b3f;
+  --rail-surface: #1d1f21; --ink: #f2f3f4; --ink-2: #c5c8cc; --muted: #a7abb1;
+  --edge: #383b3f; --edge-strong: #565a60;
+  --primary: #f1f2f3; --primary-hover: #ffffff; --primary-subtle: #373a3e; --primary-content: #202124;
+  --nav-surface: #111214; --nav-ink: #f2f3f4; --nav-text: #c6c8cc; --nav-muted: #a4a8ae;
+  --nav-line: #303236; --nav-hover: #25272a; --nav-active: #34373b;
+  --nav-accent: #f1f2f3; --nav-brand: #f1f2f3; --nav-on-brand: #202124;
+  --metric-fill: #c0c4ca;
+  --avatar-ink: #c9cdd3; --avatar-bg: #373a3e; --avatar-ink-alt: #c5c8cd; --avatar-bg-alt: #393c40;
+  --neutral: #bec2c8; --neutral-soft: #373a3e;
+  --overlay: #08090bb0; --overlay-strong: #08090be6; --shadow: 0 18px 70px #00000066;
+}
+/* ---------- ice · 冰白靛蓝(导航为浅色)---------- */
+:root[data-palette='ice'],
+[data-preview-palette='ice'] {
+  --canvas: #f6f8fc; --surface: #ffffff; --surface-2: #f1f4f9; --surface-hover: #e7ecf5;
+  --rail-surface: #edf1f7; --ink: #202a3c; --ink-2: #46536b; --muted: #606e86;
+  --edge: #dce2ec; --edge-strong: #c2ccdc;
+  --primary: #4056c7; --primary-hover: #3045ae; --primary-subtle: #e8ecfb; --primary-content: #ffffff;
+  --nav-surface: #e9edf5; --nav-ink: #202a3c; --nav-text: #394761; --nav-muted: #53617a;
+  --nav-line: #d3dae7; --nav-hover: #dce3ef; --nav-active: #d9e1f2;
+  --nav-accent: #4056c7; --nav-brand: #4056c7; --nav-on-brand: #ffffff;
+  --metric-fill: #536ac9;
+  --avatar-ink: #475b9a; --avatar-bg: #e6ebf7; --avatar-ink-alt: #55647f; --avatar-bg-alt: #e9edf3;
+  --neutral: #626e83; --neutral-soft: #e9edf3;
+  --overlay: #18243b66; --overlay-strong: #18243bd9; --shadow: 0 16px 56px #27354d1c;
+}
+.dark[data-palette='ice'],
+[data-preview-palette='ice'][data-preview-theme='dark'] {
+  --canvas: #171b24; --surface: #202632; --surface-2: #272f3d; --surface-hover: #343f51;
+  --rail-surface: #1b222e; --ink: #f0f3fa; --ink-2: #bec8d9; --muted: #a1aec3;
+  --edge: #343e4f; --edge-strong: #515f76;
+  --primary: #b4c2ff; --primary-hover: #cbd4ff; --primary-subtle: #303957; --primary-content: #1d2546;
+  --nav-surface: #111722; --nav-ink: #f0f3fa; --nav-text: #c7d0e0; --nav-muted: #a6b3c9;
+  --nav-line: #2b3546; --nav-hover: #212b3c; --nav-active: #2c3954;
+  --nav-accent: #b4c2ff; --nav-brand: #b4c2ff; --nav-on-brand: #1d2546;
+  --metric-fill: #acbcff;
+  --avatar-ink: #becbfa; --avatar-bg: #2d3854; --avatar-ink-alt: #c1cce0; --avatar-bg-alt: #303a4c;
+  --neutral: #bdc7d8; --neutral-soft: #303947;
+  --overlay: #080c14b0; --overlay-strong: #080c14e6; --shadow: 0 18px 70px #00000066;
+}
+/* ---------- clay · 暖瓷陶橘 ---------- */
+:root[data-palette='clay'],
+[data-preview-palette='clay'] {
+  --canvas: #f3f0eb; --surface: #fffdfa; --surface-2: #f7f3ee; --surface-hover: #ede7df;
+  --rail-surface: #eee9e2; --ink: #2a2623; --ink-2: #514943; --muted: #70665f;
+  --edge: #e2dbd3; --edge-strong: #cfc4b9;
+  --primary: #af482b; --primary-hover: #92391f; --primary-subtle: #f6e8e1; --primary-content: #ffffff;
+  --nav-surface: #302c29; --nav-ink: #f7f3ef; --nav-text: #d5cbc3; --nav-muted: #b9ada4;
+  --nav-line: #49413c; --nav-hover: #403a35; --nav-active: #50453d;
+  --nav-accent: #f1ad8e; --nav-brand: #f1ad8e; --nav-on-brand: #30211b;
+  --metric-fill: #ad674d;
+  --avatar-ink: #795643; --avatar-bg: #f0e7df; --avatar-ink-alt: #6d5d52; --avatar-bg-alt: #eee9e4;
+  --neutral: #70665f; --neutral-soft: #eee9e4;
+  --overlay: #211b1770; --overlay-strong: #211b17d9; --shadow: 0 16px 56px #38281e1c;
+}
+.dark[data-palette='clay'],
+[data-preview-palette='clay'][data-preview-theme='dark'] {
+  --canvas: #1d1a18; --surface: #292522; --surface-2: #322d29; --surface-hover: #433a34;
+  --rail-surface: #221f1c; --ink: #f3eee9; --ink-2: #d0c5bc; --muted: #b2a69c;
+  --edge: #403832; --edge-strong: #5d5047;
+  --primary: #f0a184; --primary-hover: #ffb89c; --primary-subtle: #49342c; --primary-content: #3b2119;
+  --nav-surface: #171513; --nav-ink: #f3eee9; --nav-text: #d2c7be; --nav-muted: #afa197;
+  --nav-line: #38302b; --nav-hover: #2b2521; --nav-active: #3c3029;
+  --nav-accent: #f0a184; --nav-brand: #f0a184; --nav-on-brand: #3b2119;
+  --metric-fill: #e09a7c;
+  --avatar-ink: #e3b99c; --avatar-bg: #40332c; --avatar-ink-alt: #d7c2b2; --avatar-bg-alt: #3a332e;
+  --neutral: #cec0b5; --neutral-soft: #39332e;
+  --overlay: #0d0a08b0; --overlay-strong: #0d0a08e6; --shadow: 0 18px 70px #00000066;
+}
+/* ---------- slate · 岩灰鸢紫 ---------- */
+:root[data-palette='slate'],
+[data-preview-palette='slate'] {
+  --canvas: #f1f0f5; --surface: #ffffff; --surface-2: #f6f5f9; --surface-hover: #eae8f0;
+  --rail-surface: #eceaf1; --ink: #282633; --ink-2: #4c4a5d; --muted: #666476;
+  --edge: #dfdde7; --edge-strong: #c7c3d2;
+  --primary: #6952a3; --primary-hover: #55418b; --primary-subtle: #efebf8; --primary-content: #ffffff;
+  --nav-surface: #282735; --nav-ink: #f4f2fa; --nav-text: #d1cde0; --nav-muted: #b2adc6;
+  --nav-line: #403e50; --nav-hover: #373546; --nav-active: #48445d;
+  --nav-accent: #c9baf1; --nav-brand: #c9baf1; --nav-on-brand: #302844;
+  --metric-fill: #7a66ad;
+  --avatar-ink: #655a91; --avatar-bg: #eeebf5; --avatar-ink-alt: #666174; --avatar-bg-alt: #efedf2;
+  --neutral: #686678; --neutral-soft: #edecf1;
+  --overlay: #201d2b70; --overlay-strong: #201d2bd9; --shadow: 0 16px 56px #2826331c;
+}
+.dark[data-palette='slate'],
+[data-preview-palette='slate'][data-preview-theme='dark'] {
+  --canvas: #1b1a22; --surface: #26242f; --surface-2: #302d3b; --surface-hover: #413d50;
+  --rail-surface: #211f29; --ink: #f2f0f8; --ink-2: #c9c5d7; --muted: #aaa6bc;
+  --edge: #3d394a; --edge-strong: #5a556d;
+  --primary: #c9baf1; --primary-hover: #dacff7; --primary-subtle: #3c354f; --primary-content: #302844;
+  --nav-surface: #17161e; --nav-ink: #f2f0f8; --nav-text: #d0cce0; --nav-muted: #aaa5bf;
+  --nav-line: #343141; --nav-hover: #282634; --nav-active: #383447;
+  --nav-accent: #c9baf1; --nav-brand: #c9baf1; --nav-on-brand: #302844;
+  --metric-fill: #c1b1ee;
+  --avatar-ink: #c9bdf0; --avatar-bg: #373249; --avatar-ink-alt: #c9c2da; --avatar-bg-alt: #393644;
+  --neutral: #c4bfd2; --neutral-soft: #383543;
+  --overlay: #0c0b10b0; --overlay-strong: #0c0b10e6; --shadow: 0 18px 70px #00000066;
+}
+
+/* Review shell uses the application's real tokens; no production components change. */
+* { box-sizing: border-box; }
+[hidden] { display: none !important; }
+html { height: 100%; }
+body { margin: 0; min-width: 320px; height: 100dvh; display: grid; grid-template-rows: auto minmax(0,1fr); overflow: hidden; color: var(--ink); background: var(--canvas); font-family: var(--font-ui); font-size: var(--fs-17); line-height: 1.6; }
+button, input, select { font: inherit; color: inherit; }
+button, a { -webkit-tap-highlight-color: transparent; touch-action: manipulation; }
+button { cursor: pointer; }
+a { color: inherit; text-decoration: none; }
+button { border: 0; background: none; }
+button:disabled { opacity: .45; cursor: not-allowed; }
+button:focus-visible, a:focus-visible, input:focus-visible, select:focus-visible, summary:focus-visible { outline: 2px solid var(--primary); outline-offset: 3px; }
+h1,h2,h3,h4,p { margin: 0; }
+svg { display: block; flex: none; }
+.icon { width: 20px; height: 20px; fill: none; stroke: currentColor; stroke-width: 1.65; stroke-linecap: round; stroke-linejoin: round; }
+.skip-link { position: fixed; z-index: var(--z-toast); top: 12px; left: 12px; padding: 12px 16px; background: var(--primary); color: var(--primary-content); border-radius: var(--r-md); transform: translateY(-200%); }
+.skip-link:focus { transform: none; }
+.review-bar { position: relative; z-index: var(--z-affix); background: var(--surface); border-bottom: 1px solid var(--edge); }
+.review-line { display: flex; min-height: 48px; align-items: center; gap: var(--sp-5); padding: 0 var(--sp-6); }
+.review-label { display: flex; align-items: center; gap: var(--sp-2); flex: none; font-size: var(--fs-13); font-weight: 600; }
+.review-dot { width: 7px; height: 7px; border-radius: var(--r-tag); background: var(--warning); }
+.review-version { color: var(--muted); font-size: var(--fs-12); font-weight: 400; }
+.review-line > p { flex: 1; color: var(--ink-2); font-size: var(--fs-12); }
+.review-line > p > span { margin-left: var(--sp-3); color: var(--muted); }
+.review-actions { display: flex; gap: var(--sp-2); margin-left: auto; }
+.review-button { display: inline-flex; min-height: 44px; align-items: center; gap: var(--sp-2); padding-inline: var(--sp-3); color: var(--ink-2); font-size: var(--fs-13); }
+.review-controls { max-height: 32dvh; overflow-y: auto; padding: var(--sp-3) var(--sp-6); border-top: 1px solid var(--edge); background: var(--surface-2); }
+.review-scenarios, .review-events { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); }
+.review-controls button { min-height: 44px; padding: var(--sp-2) var(--sp-3); border: 1px solid var(--edge); border-radius: var(--r-sm); background: var(--surface); font-size: var(--fs-13); }
+.review-controls button:hover { border-color: var(--edge-strong); background: var(--surface-hover); }
+.review-events { margin-top: var(--sp-2); }
+.review-events > span, .review-state { color: var(--muted); font-size: var(--fs-12); }
+.review-state { margin-top: var(--sp-2); }
+.app-shell { display: grid; grid-template-columns: 224px minmax(0,1fr); min-height: 0; }
+.sidebar { position: relative; display: flex; min-height: 0; flex-direction: column; padding: var(--sp-6) var(--sp-4) var(--sp-3); border-right: 1px solid var(--edge); background: var(--surface); }
+.brand { display: flex; align-items: center; gap: 9px; width: fit-content; margin: 0 var(--sp-3) var(--sp-6); font-size: var(--fs-26); line-height: 1; font-weight: 700; letter-spacing: -.07em; }
+.brand-mark { display: grid; width: 30px; height: 30px; place-items: center; border-radius: 9px; background: var(--primary); color: var(--primary-content); font-size: var(--fs-20); letter-spacing: -.08em; }
+.brand-registered { align-self: start; margin: 1px 0 0 -5px; color: var(--muted); font-size: 9px; }
+.workspace-label { display: flex; align-items: center; gap: var(--sp-3); margin: 0 var(--sp-2) var(--sp-6); color: var(--ink); font-size: var(--fs-13); font-weight: 600; }
+.workspace-avatar { display: grid; width: 34px; height: 34px; place-items: center; border: 1px solid var(--edge); border-radius: var(--r-md); background: var(--surface-2); font-size: var(--fs-13); }
+.workspace-label small { display: block; margin-top: 2px; color: var(--muted); font-size: var(--fs-11); font-weight: 400; }
+.sidebar-heading { margin: 0 var(--sp-3) var(--sp-2); color: var(--muted); font-size: var(--fs-11); }
+.nav-button { display: flex; width: 100%; min-height: 46px; align-items: center; gap: var(--sp-3); margin-top: var(--sp-1); padding: 0 var(--sp-3); border-radius: var(--r-md); color: var(--muted); font-size: var(--fs-14); text-align: left; }
+.nav-button.on { background: var(--primary-subtle); color: var(--ink); font-weight: 600; }
+.nav-button:hover { background: var(--surface-hover); color: var(--ink); }
+.nav-button .icon { width: 18px; height: 18px; }
+.nav-badge { margin-left: auto; padding: 0 6px; border-radius: var(--r-tag); background: var(--surface); color: var(--ink-2); font-size: var(--fs-11); }
+.sidebar-bottom { margin-top: auto; padding-top: var(--sp-6); }
+.sidebar-note { display: flex; gap: var(--sp-2); margin: 0 var(--sp-3) var(--sp-5); color: var(--ink-2); font-size: var(--fs-12); }
+.sidebar-note small { display: block; margin-top: var(--sp-1); color: var(--muted); font-size: var(--fs-11); }
+.status-dot { display: inline-block; width: 6px; height: 6px; flex: none; margin-top: 7px; border-radius: var(--r-tag); background: var(--success); }
+.account-button { display: flex; width: 100%; min-height: 60px; align-items: center; gap: var(--sp-3); padding: var(--sp-3); border-top: 1px solid var(--edge); text-align: left; font-size: var(--fs-13); }
+.account-avatar, .avatar-button { display: grid; width: 32px; height: 32px; flex: none; place-items: center; border-radius: var(--r-tag); background: var(--avatar-bg); color: var(--avatar-ink); font-size: var(--fs-12); }
+.account-button small { display: block; color: var(--muted); font-size: var(--fs-11); }
+.account-more { margin-left: auto; }
+.workspace { display: grid; min-height: 0; min-width: 0; grid-template-rows: 64px minmax(0,1fr); }
+.app-header { display: flex; align-items: center; justify-content: space-between; padding-inline: var(--sp-8); border-bottom: 1px solid var(--edge); background: var(--surface); }
+.app-breadcrumb { display: flex; align-items: center; gap: var(--sp-3); font-size: var(--fs-13); }
+.desktop-breadcrumb { color: var(--muted); }
+.desktop-breadcrumb > span { margin-left: var(--sp-3); color: var(--edge-strong); }
+.app-breadcrumb strong { font-weight: 500; }
+.mobile-brand { display: none; }
+.header-end { display: flex; align-items: center; gap: var(--sp-5); }
+.header-safe { display: inline-flex; align-items: center; gap: 7px; color: var(--muted); font-size: var(--fs-12); }
+.header-safe .icon { width: 15px; height: 15px; }
+.avatar-button { min-width: 44px; min-height: 44px; width: 32px; height: 32px; background: transparent; }
+.avatar-button::first-letter { background: var(--avatar-bg); }
+main { min-height: 0; min-width: 0; overflow: auto; overscroll-behavior: contain; padding: var(--sp-8); }
+.page { width: min(1120px,100%); margin-inline: auto; }
+.page.narrow { max-width: 850px; }
+.subject-switch { display: flex; width: min(1120px,100%); flex-wrap: wrap; align-items: center; gap: var(--sp-2); margin: 0 auto var(--sp-5); padding-bottom: var(--sp-4); border-bottom: 1px solid var(--edge); }
+.subject-switch > span,.subject-switch small { color: var(--muted); font-size: var(--fs-12); }
+.subject-switch > span { margin-right: var(--sp-2); }
+.subject-switch small { margin-left: auto; }
+.subject-switch button { display: flex; min-height: 44px; align-items: center; gap: var(--sp-2); padding: var(--sp-2) var(--sp-3); border-radius: var(--r-md); font-size: var(--fs-13); }
+.subject-switch button[aria-pressed='true'] { background: var(--primary-subtle); color: var(--ink); font-weight: 600; }
+.subject-switch .icon { width: 16px; height: 16px; }
+.page-heading { display: flex; align-items: flex-end; justify-content: space-between; gap: var(--sp-6); margin-bottom: var(--sp-6); }
+.eyebrow { display: flex; align-items: center; gap: var(--sp-2); margin-bottom: var(--sp-2); color: var(--muted); font-size: var(--fs-12); }
+.eyebrow .icon { width: 15px; height: 15px; }
+h1 { font-size: var(--fs-26); font-weight: 600; letter-spacing: -.05em; line-height: 1.4; }
+.page-heading p, .lead { margin-top: var(--sp-2); color: var(--muted); font-size: var(--fs-14); }
+.page-heading > .button { flex: none; }
+.button { display: inline-flex; min-height: 44px; align-items: center; justify-content: center; gap: var(--sp-2); padding: var(--sp-2) var(--sp-4); border: 1px solid transparent; border-radius: var(--r-md); background: var(--primary); color: var(--primary-content); font-size: var(--fs-14); font-weight: 500; text-align: center; }
+.button:hover { background: var(--primary-hover); }
+.button.secondary { border-color: var(--edge); background: var(--surface); color: var(--ink); }
+.button.secondary:hover { border-color: var(--edge-strong); background: var(--surface-hover); }
+.button.ghost { border-color: transparent; background: transparent; color: var(--ink-2); }
+.button.ghost:hover { background: var(--surface-hover); }
+.button .icon { width: 17px; height: 17px; }
+.text-action { display: inline-flex; min-height: 44px; align-items: center; gap: var(--sp-2); padding: 0; color: var(--ink); font-size: var(--fs-13); font-weight: 500; text-decoration: underline; text-decoration-color: var(--edge-strong); text-underline-offset: 4px; }
+.text-action .icon { width: 15px; height: 15px; }
+.panel { padding: var(--sp-6); border: 1px solid var(--edge); border-radius: var(--r-lg); background: var(--surface); }
+.trial-banner { position: relative; display: grid; grid-template-columns: 48px minmax(0,1fr) auto; align-items: center; gap: var(--sp-5); margin-bottom: var(--sp-8); padding: var(--sp-6); border: 1px solid var(--edge-strong); border-radius: var(--r-lg); background: var(--surface); }
+.trial-icon { display: grid; width: 48px; height: 48px; place-items: center; border: 1px solid var(--edge); border-radius: var(--r-lg); background: var(--surface-2); }
+.trial-icon .icon { width: 24px; height: 24px; }
+.trial-banner h2 { display: flex; align-items: center; gap: var(--sp-3); font-size: var(--fs-20); font-weight: 600; letter-spacing: -.04em; }
+.trial-banner h2 > span { flex: none; padding: 1px 7px; border-radius: var(--r-sm); background: var(--success-subtle); color: var(--success); font-size: var(--fs-11); font-weight: 500; }
+.trial-banner p { margin-top: 6px; color: var(--muted); font-size: var(--fs-13); }
+.trial-facts { display: flex; flex-wrap: wrap; gap: var(--sp-4); margin-top: var(--sp-3); color: var(--ink-2); font-size: var(--fs-12); }
+.trial-facts span { display: inline-flex; align-items: center; gap: 5px; }
+.trial-facts .icon { width: 13px; height: 13px; color: var(--success); }
+.section-heading { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-4); margin-bottom: var(--sp-4); }
+.section-heading h2 { font-size: var(--fs-17); font-weight: 600; }
+.section-heading p { color: var(--muted); font-size: var(--fs-12); }
+.plan-grid { display: grid; grid-template-columns: repeat(3,minmax(0,1fr)); gap: var(--sp-4); }
+.plan-card { position: relative; display: flex; flex-direction: column; min-width: 0; padding: var(--sp-6); border: 1px solid var(--edge); border-radius: var(--r-lg); background: var(--surface); }
+.plan-card.featured { border-color: var(--primary); box-shadow: inset 0 0 0 1px var(--primary); }
+.plan-mobile-copy,.plan-mobile-action { display: none; }
+.plan-recommend { position: absolute; top: -12px; left: var(--sp-5); padding: 2px 9px; border-radius: var(--r-sm); background: var(--primary); color: var(--primary-content); font-size: var(--fs-11); white-space: nowrap; }
+.plan-icon { display: grid; width: 36px; height: 36px; place-items: center; margin-bottom: var(--sp-4); border: 1px solid var(--edge); border-radius: var(--r-md); background: var(--surface-2); }
+.plan-card h3 { font-size: var(--fs-20); font-weight: 600; }
+.plan-name-short { display: none; }
+.plan-card > p { margin-top: 5px; color: var(--muted); font-size: var(--fs-13); }
+.plan-quota { display: none; }
+.plan-price { display: flex; align-items: baseline; gap: 7px; margin-block: var(--sp-6) var(--sp-1); }
+.plan-price strong { font-size: var(--fs-26); font-weight: 600; letter-spacing: -.05em; }
+.plan-price span { color: var(--muted); font-size: var(--fs-12); }
+.plan-billing-note { min-height: 24px; color: var(--muted); font-size: var(--fs-12); }
+.plan-card > .button { margin-top: var(--sp-4); width: 100%; }
+.plan-perks { display: flex; flex-direction: column; gap: var(--sp-3); margin: var(--sp-6) 0 0; padding: var(--sp-5) 0 0; border-top: 1px solid var(--edge); list-style: none; }
+.plan-perks li { display: flex; align-items: flex-start; gap: var(--sp-2); color: var(--ink-2); font-size: var(--fs-13); line-height: 1.7; }
+.plan-perks .icon { width: 14px; height: 14px; margin-top: 4px; color: var(--muted); }
+.plans-note { display: flex; gap: var(--sp-2); margin: var(--sp-5) 0 var(--sp-8); color: var(--muted); font-size: var(--fs-12); }
+.plans-note .icon { width: 15px; height: 15px; margin-top: 2px; }
+.info-grid { display: grid; grid-template-columns: 1fr 1fr; gap: var(--sp-4); }
+.info-item { display: flex; align-items: flex-start; gap: var(--sp-3); }
+.info-item > .icon { margin-top: 4px; color: var(--muted); }
+.info-item h3 { margin-bottom: 5px; font-size: var(--fs-14); font-weight: 500; }
+.info-item p { max-width: 400px; color: var(--muted); font-size: var(--fs-13); }
+.info-item .text-action { margin-top: var(--sp-1); }
+.notice { display: flex; align-items: flex-start; gap: var(--sp-3); margin-bottom: var(--sp-5); padding: var(--sp-4) var(--sp-5); border: 1px solid var(--edge); border-radius: var(--r-md); background: var(--surface); font-size: var(--fs-13); }
+.notice .icon { width: 18px; height: 18px; margin-top: 2px; flex: none; }
+.notice strong { display: block; font-weight: 500; }
+.notice p { margin-top: var(--sp-1); color: var(--muted); }
+.notice.warning { border-color: color-mix(in srgb,var(--warning) 25%,var(--edge)); background: var(--warning-subtle); color: var(--warning); }
+.notice.warning p { color: var(--warning); }
+.notice.info { background: var(--info-subtle); color: var(--info); }
+.notice.info p { color: var(--info); }
+.notice.success { background: var(--success-subtle); color: var(--success); }
+.notice.success p { color: var(--success); }
+.notice > .button { margin-left: auto; flex: none; }
+.waiting-layout { display: grid; grid-template-columns: minmax(0,1fr) 280px; align-items: start; gap: var(--sp-5); }
+.waiting-card { padding: var(--sp-6); }
+.task-hero { display: flex; align-items: center; gap: var(--sp-4); padding-bottom: var(--sp-6); }
+.task-orb { display: grid; width: 56px; height: 56px; flex: none; place-items: center; border: 1px solid var(--edge); border-radius: var(--r-lg); background: var(--surface-2); }
+.task-orb .icon { width: 26px; height: 26px; }
+.task-orb.success { background: var(--success-subtle); color: var(--success); }
+.task-orb.failed { background: var(--danger-subtle); color: var(--danger); }
+.task-hero h2 { font-size: var(--fs-20); font-weight: 600; letter-spacing: -.04em; }
+.task-hero p { margin-top: var(--sp-1); color: var(--muted); font-size: var(--fs-13); }
+.progress-label { display: flex; justify-content: space-between; color: var(--muted); font-size: var(--fs-12); }
+.progress-label strong { color: var(--ink); font-weight: 500; }
+.progress-track { width: 100%; height: 5px; margin-top: var(--sp-3); overflow: hidden; border-radius: var(--r-tag); background: var(--surface-hover); }
+.progress-fill { height: 100%; border-radius: inherit; background: var(--primary); }
+.job-steps { margin: var(--sp-6) 0; padding: 0; list-style: none; }
+.job-step { position: relative; display: grid; grid-template-columns: 28px minmax(0,1fr) auto; gap: var(--sp-3); min-height: 72px; }
+.job-step:not(:last-child)::after { position: absolute; top: 29px; bottom: 3px; left: 13px; width: 1px; background: var(--edge); content: ''; }
+.step-icon { display: grid; width: 28px; height: 28px; place-items: center; border: 1px solid var(--edge); border-radius: var(--r-tag); background: var(--surface); color: var(--muted); font-size: var(--fs-12); }
+.step-icon .icon { width: 14px; height: 14px; }
+.job-step.done .step-icon { border-color: transparent; background: var(--success-subtle); color: var(--success); }
+.job-step.current .step-icon { border-color: var(--primary); background: var(--primary); color: var(--primary-content); }
+.job-step.failed .step-icon { border-color: transparent; background: var(--danger-subtle); color: var(--danger); }
+.step-copy strong { display: block; font-size: var(--fs-14); font-weight: 500; }
+.step-copy p { margin-top: 3px; color: var(--muted); font-size: var(--fs-12); }
+.step-state { padding-top: 3px; color: var(--muted); font-size: var(--fs-11); white-space: nowrap; }
+.job-step.done .step-state { color: var(--success); }
+.job-step.failed .step-state { color: var(--danger); }
+.waiting-actions { display: flex; flex-wrap: wrap; gap: var(--sp-3); padding-top: var(--sp-5); border-top: 1px solid var(--edge); }
+.waiting-foot { margin-top: var(--sp-4); color: var(--muted); font-size: var(--fs-12); }
+.waiting-simple { display: flex; min-height: 500px; align-items: center; flex-direction: column; justify-content: center; padding: var(--sp-8); }
+.waiting-current { text-align: center; }
+.waiting-current .task-orb { width: 64px; height: 64px; margin: 0 auto var(--sp-5); }
+.waiting-current h2 { font-size: var(--fs-26); font-weight: 600; letter-spacing: -.04em; }
+.waiting-current > p { margin: var(--sp-2) 0 var(--sp-3); color: var(--muted); font-size: var(--fs-14); }
+.waiting-progress { width: min(360px,100%); margin-top: var(--sp-8); }
+.waiting-meta { display: grid; width: min(360px,100%); grid-template-columns: 1fr 1fr; gap: var(--sp-5); margin: var(--sp-6) 0; text-align: center; }
+.waiting-meta dt { color: var(--muted); font-size: var(--fs-12); }
+.waiting-meta dd { margin: var(--sp-1) 0 0; color: var(--ink); font-size: var(--fs-14); }
+.waiting-simple .waiting-actions { justify-content: center; padding-top: 0; border-top: 0; }
+.support-action { margin-top: var(--sp-3); color: var(--muted); font-size: var(--fs-12); }
+.task-summary h3 { margin-bottom: var(--sp-4); font-size: var(--fs-14); font-weight: 500; }
+.summary-facts { margin: 0; }
+.summary-facts > div { margin-top: var(--sp-4); }
+.summary-facts dt { margin-bottom: 4px; color: var(--muted); font-size: var(--fs-12); }
+.summary-facts dd { margin: 0; font-size: var(--fs-13); overflow-wrap: anywhere; }
+.summary-facts dd.emphasis { font-weight: 600; }
+.task-summary .text-action { margin-top: var(--sp-4); font-size: var(--fs-12); }
+.small-panel { margin-top: var(--sp-4); padding: var(--sp-5); }
+.small-panel h3 { display: flex; align-items: center; gap: var(--sp-2); font-size: var(--fs-13); font-weight: 500; }
+.small-panel h3 .icon { width: 16px; height: 16px; }
+.small-panel p { margin-top: var(--sp-2); color: var(--muted); font-size: var(--fs-12); }
+.state-pill { display: inline-flex; align-items: center; gap: 5px; padding: 2px 8px; border-radius: var(--r-tag); background: var(--surface-2); color: var(--muted); font-size: var(--fs-11); white-space: nowrap; }
+.state-pill.ready { color: var(--success); background: var(--success-subtle); }
+.state-pill.pending { color: var(--warning); background: var(--warning-subtle); }
+.state-pill.expired { color: var(--danger); background: var(--danger-subtle); }
+.quota-panel { display: flex; justify-content: space-between; align-items: center; gap: var(--sp-5); margin-bottom: var(--sp-6); }
+.quota-copy h2 { font-size: var(--fs-14); font-weight: 500; }
+.quota-copy p { margin-top: var(--sp-1); color: var(--muted); font-size: var(--fs-13); }
+.quota-meter { min-width: 180px; }
+.quota-meter p { color: var(--muted); font-size: var(--fs-12); }
+.quota-meter strong { color: var(--ink); font-size: var(--fs-20); font-weight: 600; }
+.container-grid { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: var(--sp-4); }
+.container-card { padding: var(--sp-5); }
+.container-head { display: flex; align-items: center; gap: var(--sp-3); }
+.container-avatar { display: grid; width: 44px; height: 44px; flex: none; place-items: center; border-radius: var(--r-md); background: var(--avatar-bg); color: var(--avatar-ink); font-size: var(--fs-17); font-weight: 600; }
+.container-head > div { min-width: 0; }
+.container-head h3 { overflow: hidden; font-size: var(--fs-17); font-weight: 500; text-overflow: ellipsis; white-space: nowrap; }
+.container-head small { color: var(--muted); font-size: var(--fs-12); }
+.container-head > .state-pill { margin-left: auto; }
+.container-meta { display: flex; flex-wrap: wrap; gap: var(--sp-3); margin-top: var(--sp-5); color: var(--muted); font-size: var(--fs-12); }
+.container-caption { margin-top: var(--sp-3); color: var(--ink-2); font-size: var(--fs-13); }
+.container-actions { display: grid; grid-template-columns: 1fr auto; gap: var(--sp-2); margin-top: var(--sp-5); }
+.container-actions .button { padding-inline: var(--sp-3); font-size: var(--fs-13); }
+.create-card { display: flex; min-height: 237px; align-items: center; justify-content: center; flex-direction: column; gap: var(--sp-3); border: 1px dashed var(--edge-strong); border-radius: var(--r-lg); color: var(--muted); background: transparent; }
+.create-card > .icon { width: 26px; height: 26px; }
+.create-card strong { color: var(--ink-2); font-size: var(--fs-14); font-weight: 500; }
+.create-card p { font-size: var(--fs-12); }
+.empty-state { display: flex; min-height: 350px; align-items: center; justify-content: center; flex-direction: column; gap: var(--sp-3); text-align: center; }
+.empty-state > .task-orb { margin-bottom: var(--sp-3); }
+.empty-state h2 { font-size: var(--fs-20); font-weight: 500; }
+.empty-state p { max-width: 430px; color: var(--muted); font-size: var(--fs-14); }
+.empty-state .button { margin-top: var(--sp-3); }
+.resource-grid { display: grid; grid-template-columns: 1fr 1fr; gap: var(--sp-5); }
+.resource-panel h2 { display: flex; align-items: center; gap: var(--sp-2); margin-bottom: var(--sp-2); font-size: var(--fs-17); font-weight: 600; }
+.resource-panel h2 .icon { width: 19px; height: 19px; }
+.resource-panel > p { color: var(--muted); font-size: var(--fs-13); }
+.credential-list { margin: var(--sp-5) 0 0; }
+.credential-row { padding-block: var(--sp-4); border-top: 1px solid var(--edge); }
+.credential-row dt { display: flex; justify-content: space-between; align-items: center; gap: var(--sp-2); color: var(--muted); font-size: var(--fs-12); }
+.credential-row dd { display: flex; min-height: 24px; justify-content: space-between; gap: var(--sp-3); margin: var(--sp-1) 0 0; font-family: ui-monospace,Consolas,monospace; font-size: var(--fs-13); overflow-wrap: anywhere; }
+.credential-row .button { min-height: 44px; padding-inline: var(--sp-2); flex: none; margin: -10px 0; font-size: var(--fs-12); }
+.masked-value { letter-spacing: .12em; }
+.credential-fake { margin-top: var(--sp-3); color: var(--muted); font-size: var(--fs-12); }
+.expired-intro { margin-bottom: var(--sp-6); }
+.expired-intro .task-orb { margin-bottom: var(--sp-4); }
+.expired-intro h1 { margin-bottom: var(--sp-3); }
+.expired-intro p { max-width: 620px; color: var(--muted); font-size: var(--fs-14); }
+.preserved-resource { display: flex; align-items: center; gap: var(--sp-3); margin-bottom: var(--sp-6); padding: var(--sp-4) var(--sp-5); border: 1px solid var(--edge); border-radius: var(--r-md); background: var(--surface); }
+.preserved-resource > div { flex: 1; }
+.preserved-resource strong { font-size: var(--fs-14); font-weight: 500; }
+.preserved-resource p { margin-top: 3px; color: var(--muted); font-size: var(--fs-12); }
+.enterprise-layout { display: grid; grid-template-columns: minmax(0,1fr) 300px; gap: var(--sp-5); }
+.enterprise-card h2 { margin-bottom: var(--sp-3); font-size: var(--fs-20); font-weight: 600; }
+.enterprise-card > p { color: var(--muted); font-size: var(--fs-14); }
+.join-steps { display: flex; flex-direction: column; gap: var(--sp-5); margin-block: var(--sp-6); }
+.join-step { display: flex; align-items: flex-start; gap: var(--sp-3); }
+.join-step > span { display: grid; width: 26px; height: 26px; flex: none; place-items: center; border: 1px solid var(--edge); border-radius: var(--r-tag); font-size: var(--fs-12); }
+.join-step strong { font-size: var(--fs-14); font-weight: 500; }
+.join-step p { margin-top: var(--sp-1); color: var(--muted); font-size: var(--fs-13); }
+.copy-id { display: flex; align-items: center; gap: var(--sp-3); padding: var(--sp-3) var(--sp-4); border: 1px solid var(--edge); border-radius: var(--r-md); background: var(--surface-2); }
+.copy-id > div { flex: 1; }
+.copy-id small { display: block; color: var(--muted); font-size: var(--fs-12); }
+.copy-id strong { font-family: ui-monospace,Consolas,monospace; font-size: var(--fs-14); font-weight: 500; }
+.company-heading { display: flex; align-items: center; gap: var(--sp-3); margin-bottom: var(--sp-5); }
+.company-heading h2 { font-size: var(--fs-17); font-weight: 500; }
+.company-heading p { color: var(--muted); font-size: var(--fs-12); }
+.company-member { display: flex; align-items: center; gap: var(--sp-3); min-height: 72px; padding-block: var(--sp-3); border-top: 1px solid var(--edge); }
+.company-member strong { font-size: var(--fs-14); font-weight: 500; }
+.company-member small { display: block; color: var(--muted); font-size: var(--fs-12); }
+.company-member > .state-pill { margin-left: auto; }
+.mobile-nav { display: none; }
+.ui-dialog { position: fixed; width: min(480px,calc(100% - 32px)); max-height: calc(100dvh - 32px); overflow-y: auto; padding: var(--sp-8); border: 1px solid var(--edge); border-radius: var(--r-lg); background: var(--surface); color: var(--ink); box-shadow: var(--shadow-overlay); }
+.ui-dialog::backdrop { background: var(--overlay); backdrop-filter: blur(3px); }
+.dialog-close { position: absolute; top: var(--sp-2); right: var(--sp-2); width: 44px; height: 44px; color: var(--muted); font-size: var(--fs-26); }
+.dialog-kicker { display: inline-flex; align-items: center; gap: var(--sp-2); margin-bottom: var(--sp-4); color: var(--muted); font-size: var(--fs-12); }
+.dialog-kicker .icon { width: 17px; height: 17px; }
+.ui-dialog h2 { padding-right: var(--sp-4); font-size: var(--fs-20); font-weight: 600; }
+.dialog-description { margin-top: var(--sp-3); color: var(--muted); font-size: var(--fs-14); }
+.ui-dialog .notice { margin-top: var(--sp-5); margin-bottom: 0; }
+.form-field { display: block; margin-top: var(--sp-5); }
+.form-field > span { display: block; margin-bottom: var(--sp-2); font-size: var(--fs-13); }
+.form-field input, .form-field select { width: 100%; min-height: 48px; padding: 10px var(--sp-3); border: 1px solid var(--edge-strong); border-radius: var(--r-md); background: var(--surface); color: var(--ink); font-size: 16px; }
+.form-field small { display: block; margin-top: var(--sp-2); color: var(--muted); font-size: var(--fs-12); }
+.dialog-facts { display: grid; grid-template-columns: 1fr 1fr; gap: var(--sp-3); margin-top: var(--sp-5); padding: var(--sp-4); border-radius: var(--r-md); background: var(--surface-2); }
+.dialog-facts small { display: block; margin-bottom: var(--sp-1); color: var(--muted); font-size: var(--fs-12); }
+.dialog-facts strong { font-size: var(--fs-13); font-weight: 500; }
+.dialog-actions { display: flex; justify-content: flex-end; gap: var(--sp-3); margin-top: var(--sp-6); }
+.dialog-actions .button { min-width: 100px; }
+.dialog-feedback { margin-top: var(--sp-4); color: var(--success); font-size: var(--fs-13); }
+.demo-secret { display: block; margin-top: var(--sp-4); padding: var(--sp-3); border: 1px solid var(--edge); border-radius: var(--r-sm); background: var(--surface-2); font: var(--fs-13) ui-monospace,Consolas,monospace; overflow-wrap: anywhere; }
+.toast { position: fixed; z-index: var(--z-toast); right: var(--sp-5); bottom: var(--sp-5); left: var(--sp-5); width: fit-content; max-width: calc(100% - 40px); margin-inline: auto; padding: var(--sp-3) var(--sp-5); border: 1px solid var(--edge-strong); border-radius: var(--r-md); background: var(--surface); color: var(--ink); box-shadow: var(--shadow-pop); font-size: var(--fs-13); opacity: 0; transform: translateY(8px); transition: opacity var(--motion-fast),transform var(--motion-fast); pointer-events: none; }
+.toast.visible { opacity: 1; transform: none; }
+@media (max-width: 1100px) {
+  .app-shell { grid-template-columns: 192px minmax(0,1fr); }
+  main { padding: var(--sp-6); }
+  .plan-grid { gap: var(--sp-3); }
+  .plan-card { padding: var(--sp-5); }
+  .waiting-layout { grid-template-columns: minmax(0,1fr) 240px; gap: var(--sp-4); }
+  .enterprise-layout { grid-template-columns: 1fr; }
+}
+@media (max-width: 939px) and (min-width: 768px) {
+  .app-shell { grid-template-columns: 76px minmax(0,1fr); }
+  .sidebar { padding-inline: var(--sp-3); }
+  .brand { margin: 0 auto var(--sp-6); font-size: 0; }
+  .brand-mark { font-size: var(--fs-20); }
+  .brand-registered,.workspace-label,.sidebar-heading,.nav-button > span,.sidebar-note,.account-button > span:not(.account-avatar) { display: none; }
+  .nav-button { justify-content: center; padding: 0; }
+  .account-button { justify-content: center; padding-inline: 0; }
+  .waiting-layout { grid-template-columns: 1fr; }
+  .task-aside { display: grid; grid-template-columns: 1fr 1fr; gap: var(--sp-4); }
+  .small-panel { margin-top: 0; }
+  .review-line > p { display: none; }
+}
+@media (max-width: 767px) {
+  body { font-size: var(--fs-14); }
+  .review-line { min-height: 44px; gap: var(--sp-2); padding-inline: var(--sp-3); }
+  .review-line > p,.review-version { display: none; }
+  .review-label { font-size: var(--fs-12); }
+  .review-actions { gap: 0; }
+  .review-button { font-size: var(--fs-12); padding-inline: var(--sp-2); }
+  .review-controls { max-height: 35dvh; padding: var(--sp-3); }
+  .review-controls button { font-size: var(--fs-12); min-height: 40px; }
+  .review-events > span { width: 100%; margin-block: var(--sp-1); }
+  .app-shell { display: block; }
+  .sidebar { display: none; }
+  .workspace { height: 100%; grid-template-rows: 52px minmax(0,1fr) auto; }
+  .app-header { padding-inline: var(--sp-4); }
+  .desktop-breadcrumb,.header-safe { display: none; }
+  .app-breadcrumb { gap: var(--sp-2); }
+  .app-breadcrumb strong { padding-left: var(--sp-2); border-left: 1px solid var(--edge); font-size: var(--fs-13); }
+  .mobile-brand { display: inline; font-size: var(--fs-17); font-weight: 700; letter-spacing: -.07em; }
+  main { padding: var(--sp-4) var(--sp-4) var(--sp-6); }
+  h1 { font-size: var(--fs-20); letter-spacing: -.03em; }
+  .eyebrow { font-size: var(--fs-11); margin-bottom: var(--sp-1); }
+  .page-heading { align-items: flex-start; gap: var(--sp-2); flex-direction: column; margin-bottom: var(--sp-4); }
+  .page-heading p,.lead { font-size: var(--fs-13); line-height: 1.6; }
+  .page-heading > .button { width: 100%; }
+  .button { min-height: 44px; font-size: var(--fs-14); padding-inline: var(--sp-3); }
+  .text-action { font-size: var(--fs-13); min-height: 40px; }
+  .panel { padding: var(--sp-4); border-radius: var(--r-md); }
+  .trial-banner { grid-template-columns: minmax(0,1fr); gap: var(--sp-3); margin-bottom: var(--sp-5); padding: var(--sp-4); }
+  .trial-icon { width: 36px; height: 36px; border-radius: var(--r-md); }
+  .trial-icon .icon { width: 20px; height: 20px; }
+  .trial-banner h2 { flex-wrap: wrap; gap: var(--sp-2); font-size: var(--fs-17); }
+  .trial-banner h2 > span { font-size: var(--fs-11); }
+  .trial-banner p { font-size: var(--fs-13); }
+  .trial-facts { gap: var(--sp-2) var(--sp-3); font-size: var(--fs-12); }
+  .trial-banner > .button { width: 100%; }
+  .section-heading { align-items: flex-start; flex-direction: column; gap: var(--sp-1); }
+  .section-heading h2 { font-size: var(--fs-15); }
+  .section-heading p { font-size: var(--fs-12); }
+  .plan-grid { grid-template-columns: 1fr; gap: var(--sp-3); }
+  .plan-card { display: grid; grid-template-columns: minmax(0,1fr) 88px; align-items: center; gap: var(--sp-3); padding: var(--sp-3); border-radius: var(--r-md); text-align: left; }
+  .plan-card.featured { background: var(--primary-subtle); box-shadow: inset 0 0 0 1px var(--primary); }
+  .plan-card.current { border-color: var(--success); background: var(--success-subtle); box-shadow: none; }
+  .plan-mobile-copy { display: block; min-width: 0; }
+  .plan-mobile-heading { display: flex; align-items: center; gap: var(--sp-2); }
+  .plan-mobile-heading h3 { font-size: var(--fs-17); line-height: 1.3; }
+  .plan-mobile-recommend { padding: 2px 6px; border-radius: var(--r-sm); background: var(--primary); color: var(--primary-content); font-size: var(--fs-11); white-space: nowrap; }
+  .plan-mobile-quota { margin-top: var(--sp-2); color: var(--ink-2); font-size: var(--fs-13); line-height: 1.4; }
+  .plan-mobile-benefit { margin-top: var(--sp-1); color: var(--muted); font-size: var(--fs-12); line-height: 1.4; }
+  .plan-mobile-action { display: flex; align-items: stretch; flex-direction: column; gap: var(--sp-2); }
+  .plan-mobile-price { text-align: center; line-height: 1.25; }
+  .plan-mobile-price strong { display: block; color: var(--ink-2); font-size: var(--fs-12); font-weight: 500; white-space: nowrap; }
+  .plan-mobile-price span { display: block; color: var(--muted); font-size: var(--fs-11); white-space: nowrap; }
+  .plan-mobile-action .button { width: 100%; min-height: 44px; padding-inline: var(--sp-1); font-size: var(--fs-12); }
+  .plan-card.current .plan-mobile-action .button { border-color: var(--success); color: var(--success); background: var(--surface); }
+  .plan-icon,.plan-recommend,.plan-name-full,.plan-name-short,.plan-card > p,.plan-quota,.plan-price,.plan-billing-note,.plan-card > .button,.plan-perks { display: none; }
+  .plans-note { font-size: var(--fs-12); margin: var(--sp-3) 0 var(--sp-5); }
+  .info-grid { grid-template-columns: 1fr; gap: var(--sp-4); }
+  .info-item h3,.info-item p { font-size: var(--fs-13); }
+  .waiting-layout,.resource-grid { grid-template-columns: 1fr; }
+  .task-hero { gap: var(--sp-2); padding-bottom: var(--sp-4); }
+  .task-orb { width: 40px; height: 40px; }
+  .task-hero h2 { font-size: var(--fs-17); }
+  .task-hero p { font-size: var(--fs-12); }
+  .job-step { grid-template-columns: 24px minmax(0,1fr) auto; gap: var(--sp-2); min-height: 76px; }
+  .step-copy strong { font-size: var(--fs-14); }
+  .step-copy p { max-width: 220px; font-size: var(--fs-12); }
+  .step-state { font-size: var(--fs-11); }
+  .waiting-actions { flex-direction: column; gap: var(--sp-2); }
+  .waiting-actions .button { width: 100%; }
+  .waiting-foot { font-size: var(--fs-12); }
+  .waiting-simple { min-height: 0; padding: var(--sp-6) var(--sp-4); border-radius: var(--r-lg); }
+  .waiting-current .task-orb { width: 52px; height: 52px; margin-bottom: var(--sp-4); }
+  .waiting-current h2 { font-size: var(--fs-20); }
+  .waiting-current > p { font-size: var(--fs-13); }
+  .waiting-progress { margin-top: var(--sp-5); }
+  .waiting-meta { margin: var(--sp-4) 0; gap: var(--sp-4); }
+  .waiting-meta dt { font-size: var(--fs-11); }
+  .waiting-meta dd { font-size: var(--fs-13); }
+  .waiting-simple .waiting-actions { width: 100%; gap: var(--sp-2); }
+  .support-action { font-size: var(--fs-12); }
+  .task-aside { display: grid; grid-template-columns: 1fr; gap: var(--sp-3); }
+  .small-panel { margin: 0; padding: var(--sp-4); }
+  .task-summary h3,.small-panel h3 { font-size: var(--fs-13); }
+  .summary-facts { display: grid; grid-template-columns: 1fr 1fr; gap: var(--sp-3); }
+  .summary-facts > div { margin-top: 0; }
+  .summary-facts dt,.small-panel p { font-size: var(--fs-11); }
+  .summary-facts dd { font-size: var(--fs-13); }
+  .task-summary .text-action { font-size: var(--fs-12); }
+  .notice { flex-wrap: wrap; padding: var(--sp-3); font-size: var(--fs-13); margin-bottom: var(--sp-4); }
+  .notice > div { flex: 1; min-width: 0; }
+  .notice > .button { width: 100%; margin-left: 0; }
+  .quota-panel { align-items: stretch; flex-direction: column; gap: var(--sp-3); margin-bottom: var(--sp-4); padding: var(--sp-4); }
+  .quota-copy h2 { font-size: var(--fs-13); }
+  .quota-copy p { font-size: var(--fs-12); }
+  .quota-meter { min-width: 0; }
+  .quota-meter p { font-size: var(--fs-11); }
+  .quota-meter strong { font-size: var(--fs-17); }
+  .container-grid { grid-template-columns: minmax(0,1fr); gap: var(--sp-3); }
+  .container-card { padding: var(--sp-4); }
+  .container-avatar { width: 36px; height: 36px; font-size: var(--fs-14); }
+  .container-head h3 { font-size: var(--fs-15); }
+  .container-head small { font-size: var(--fs-11); }
+  .container-meta { gap: var(--sp-2); margin-top: var(--sp-3); font-size: var(--fs-11); }
+  .container-caption { font-size: var(--fs-12); margin-top: var(--sp-2); }
+  .container-actions { margin-top: var(--sp-3); }
+  .container-actions .button { font-size: var(--fs-13); }
+  .create-card { min-height: 120px; gap: var(--sp-2); }
+  .create-card > .icon { width: 22px; height: 22px; }
+  .create-card strong { font-size: var(--fs-14); }
+  .create-card p { font-size: var(--fs-11); }
+  .empty-state { min-height: 260px; gap: var(--sp-2); }
+  .empty-state h2 { font-size: var(--fs-17); }
+  .empty-state p { font-size: var(--fs-13); }
+  .resource-panel > p { font-size: var(--fs-13); }
+  .resource-panel h2 { font-size: var(--fs-15); }
+  .credential-list { margin-top: var(--sp-4); }
+  .credential-row { padding-block: var(--sp-3); }
+  .credential-row dt { font-size: var(--fs-11); }
+  .credential-row dd { font-size: var(--fs-12); }
+  .credential-row .button { font-size: var(--fs-12); min-height: 40px; }
+  .credential-fake { font-size: var(--fs-11); }
+  .expired-intro { margin-bottom: var(--sp-5); }
+  .expired-intro p { font-size: var(--fs-13); }
+  .preserved-resource { flex-wrap: wrap; padding: var(--sp-3) var(--sp-4); margin-bottom: var(--sp-4); }
+  .preserved-resource strong { font-size: var(--fs-14); }
+  .preserved-resource p { font-size: var(--fs-11); }
+  .enterprise-layout { grid-template-columns: 1fr; gap: var(--sp-4); }
+  .enterprise-card h2 { font-size: var(--fs-17); }
+  .enterprise-card > p,.join-step strong,.join-step p { font-size: var(--fs-13); }
+  .join-steps { gap: var(--sp-4); margin-block: var(--sp-4); }
+  .company-heading h2 { font-size: var(--fs-15); }
+  .company-member { min-height: 60px; }
+  .company-member strong { font-size: var(--fs-13); }
+  .company-member small { font-size: var(--fs-11); }
+  .copy-id { padding: var(--sp-2) var(--sp-3); }
+  .copy-id strong { font-size: var(--fs-13); }
+  .state-pill { font-size: var(--fs-10, 11px); padding: 1px 6px; }
+  .mobile-nav { display: grid; grid-template-columns: repeat(4,minmax(0,1fr)); min-height: 56px; gap: 0; padding: var(--sp-1) var(--sp-2) max(var(--sp-1),env(safe-area-inset-bottom,0px)); border-top: 1px solid var(--edge); background: var(--surface); }
+  .mobile-nav button { display: flex; min-height: 48px; align-items: center; justify-content: center; flex-direction: column; gap: 2px; color: var(--muted); font-size: var(--fs-10, 11px); }
+  .mobile-nav button.on { color: var(--ink); font-weight: 600; }
+  .mobile-nav .icon { width: 19px; height: 19px; }
+  .ui-dialog { padding: var(--sp-5) var(--sp-4); width: min(480px,calc(100% - 24px)); }
+  .ui-dialog h2 { font-size: var(--fs-17); }
+  .dialog-description { font-size: var(--fs-13); }
+  .dialog-facts { padding: var(--sp-3); gap: var(--sp-2); }
+  .dialog-facts strong { font-size: var(--fs-12); }
+  .dialog-actions { flex-direction: column-reverse; gap: var(--sp-2); }
+  .dialog-actions .button { width: 100%; }
+  .form-field > span { font-size: var(--fs-13); }
+  .form-field small { font-size: var(--fs-11); }
+  .toast { bottom: calc(68px + env(safe-area-inset-bottom,0px)); font-size: var(--fs-13); }
+}
+@media (prefers-reduced-motion: reduce) { *,*::before,*::after { scroll-behavior: auto !important; transition: none !important; animation: none !important; } }
+</style>
+</head>
+<body>
+  <a class="skip-link" href="#main">跳到主内容</a>
+  <section class="review-bar" aria-label="原型评审控制">
+    <div class="review-line"><span class="review-label"><span class="review-dot"></span>交互原型 <span class="review-version">G-D1 / 待确认</span></span><p>体验从开通到可用的完整动线。<span>以下为本地演示,不会创建容器或付款。</span></p><div class="review-actions"><button type="button" id="themeToggle" class="review-button" aria-label="切换深色模式">深色</button><button type="button" id="reviewToggle" class="review-button" aria-controls="reviewControls" aria-expanded="false">演示场景 <span aria-hidden="true">⌄</span></button></div></div>
+    <div class="review-controls" id="reviewControls" hidden>
+      <div class="review-scenarios" role="group" aria-label="选择演示场景"><button type="button" data-scenario="new">首次进入</button><button type="button" data-scenario="waiting">开通进行中</button><button type="button" data-scenario="failed">开通失败</button><button type="button" data-scenario="advanced">已有容器</button><button type="button" data-scenario="quota">名额已满</button><button type="button" data-scenario="expired">试用到期</button><button type="button" data-scenario="enterprise">企业账号</button></div>
+      <div class="review-events" role="group" aria-label="模拟平台事件"><span>模拟平台回报</span><button type="button" data-event="advance">推进一个阶段</button><button type="button" data-event="fail">当前阶段失败</button><button type="button" data-event="slow">进度延迟</button><button type="button" data-event="offline">切换断网</button><button type="button" data-event="approve">管理员确认</button><button type="button" data-event="expire">试用到期</button><button type="button" data-event="join">企业确认加入</button></div>
+      <p class="review-state" id="reviewState" aria-live="polite"></p>
+    </div>
+  </section>
+  <div class="app-shell">
+    <aside class="sidebar" aria-label="桌面导航">
+      <a class="brand" href="#plans" aria-label="Fmode 套餐首页"><span class="brand-mark">F</span>fmode<span class="brand-registered">®</span></a>
+      <div class="workspace-label"><span class="workspace-avatar">我</span><span>我的协作空间<small>个人与企业,同一个入口</small></span></div>
+      <div class="sidebar-heading">工作空间</div>
+      <nav id="desktopNav"></nav>
+      <div class="sidebar-bottom"><div class="sidebar-note"><span class="status-dot"></span><span>让想法,更进一步。<small>连接你与数字生命。</small></span></div><button type="button" class="account-button" data-view="account"><span class="account-avatar">体</span><span>体验账号<small>原型演示数据</small></span><span class="account-more" aria-hidden="true">···</span></button></div>
+    </aside>
+    <div class="workspace">
+      <header class="app-header"><div class="app-breadcrumb"><span class="mobile-brand">fmode</span><span class="desktop-breadcrumb">账户与空间 <span aria-hidden="true">/</span></span><strong id="pageLabel">套餐与开通</strong></div><div class="header-end"><span class="header-safe" id="headerStatus"></span><button type="button" class="avatar-button" data-view="account" aria-label="查看账号与套餐">体</button></div></header>
+      <main id="main" tabindex="-1"></main>
+      <nav class="mobile-nav" id="mobileNav" aria-label="手机导航"></nav>
+    </div>
+  </div>
+  <dialog class="ui-dialog" id="dialog" aria-labelledby="dialogTitle"><button type="button" class="dialog-close icon-button" id="dialogClose" aria-label="关闭弹窗" autofocus>×</button><div id="dialogBody"></div></dialog>
+  <div class="toast" id="toast" role="status" aria-live="polite" aria-atomic="true"></div>
+  <script>/* Local, in-memory review model. It neither calls a platform nor grants real access. */
+const SubscriptionDemo = (() => {
+  const PLANS = {
+    trial: { name: '两天试用', limit: 1 },
+    starter: { name: '入门版', limit: 1 },
+    advanced: { name: '进阶版', limit: 3 },
+    enterprise: { name: '企业版', limit: 5 },
+  };
+  const STAGES = [
+    { key: 'entitlement', title: '确认权益与容器名额', detail: '检查套餐权益,预留本次开通名额。' },
+    { key: 'cloud', title: '准备独立云资源', detail: '配置独立后端、云函数与专属资源凭据。' },
+    { key: 'matrix', title: '建立通信身份', detail: '创建归属于你的 Matrix 身份与会话通道。' },
+    { key: 'container', title: '创建并初始化容器', detail: '准备平台容器,安装已验证的运行环境。' },
+    { key: 'connectivity', title: '接入协作空间', detail: '验证身份与房间,完成通信接入。' },
+    { key: 'verification', title: '完成可用性核验', detail: '核对真实回复、完成信号和新鲜心跳。' },
+  ];
+  const scopeFields = ['plan', 'access', 'trialClaimed', 'trialStartedAt', 'trialExpiresAt', 'containers', 'addon', 'application', 'job', 'jobSequence'];
+  const captureScope = (state) => Object.fromEntries(scopeFields.map((key) => [key, JSON.parse(JSON.stringify(state[key]))]));
+  function switchSubject(state, subject) {
+    if (state.activeSubject === subject) return;
+    const account = state[subject + 'Account'];
+    if (!account) return;
+    state[state.activeSubject + 'Account'] = captureScope(state);
+    for (const key of scopeFields) state[key] = JSON.parse(JSON.stringify(account[key]));
+    state.activeSubject = subject;
+    state.company = subject === 'company';
+  }
+  const seedContainer = (index, company = false) => ({ id: (company ? 'demo-company-container-' : 'demo-container-') + index, name: ['我的协作伙伴', '内容助手', '研究助手', '项目伙伴', '知识助手'][index - 1] || '新的协作伙伴', owner: company ? '示例企业' : '我', company, ready: true });
+  function initial(scenario = 'new') {
+    const state = { scenario, view: 'plans', plan: null, access: 'unopened', trialClaimed: false, trialStartedAt: null, trialExpiresAt: null, now: Date.parse('2026-11-25T10:00:00+08:00'), containers: [], addon: 0, application: null, job: null, offline: false, jobSequence: 0, company: false, activeSubject: 'personal', personalAccount: null, companyAccount: null, note: '' };
+    if (['advanced', 'quota', 'enterprise'].includes(scenario)) {
+      if (scenario === 'enterprise') { state.personalAccount = captureScope(state); state.activeSubject = 'company'; }
+      state.plan = scenario === 'enterprise' ? 'enterprise' : 'advanced';
+      state.company = scenario === 'enterprise';
+      state.access = 'active';
+      state.view = 'containers';
+      state.containers = Array.from({ length: scenario === 'quota' ? 3 : scenario === 'enterprise' ? 2 : 1 }, (_, index) => seedContainer(index + 1, state.company));
+    }
+    if (scenario === 'expired') {
+      state.plan = 'trial'; state.trialClaimed = true; state.access = 'expired'; state.view = 'expired';
+      state.trialStartedAt = state.now - 48 * 3600000; state.trialExpiresAt = state.now;
+      state.containers = [seedContainer(1)];
+    }
+    if (['waiting', 'failed'].includes(scenario)) {
+      const started = reduce(state, { type: 'start', name: '我的第一个容器', plan: 'trial' });
+      started.job.stage = 3; started.job.completed = 3; started.job.status = scenario === 'failed' ? 'failed' : 'provisioning';
+      started.now += 6 * 60000; started.job.updatedAt = started.now;
+      started.job.error = scenario === 'failed' ? '运行环境初始化暂时失败,平台保留了已完成的资源和任务进度。' : null;
+      return started;
+    }
+    return state;
+  }
+  const limit = (state) => state.plan ? PLANS[state.plan].limit + (['advanced', 'enterprise'].includes(state.plan) ? state.addon : 0) : 0;
+  const reserved = (state) => state.job && state.job.status !== 'ready' ? 1 : 0;
+  const used = (state) => state.containers.length;
+  const hasAccess = (state) => state.access === 'active';
+  const canCreate = (state) => hasAccess(state) && !reserved(state) && used(state) < limit(state);
+  const clone = (state) => JSON.parse(JSON.stringify(state));
+  function reduce(previous, action) {
+    const s = clone(previous);
+    s.note = '';
+    if (action.type === 'subject') {
+      switchSubject(s, action.subject);
+      s.view = s.access === 'expired' ? 'expired' : action.view || 'containers';
+      return s;
+    }
+    if (action.type === 'view') {
+      s.view = action.view;
+      if (s.access === 'expired' && ['containers', 'access', 'chat'].includes(s.view)) s.view = 'expired';
+      return s;
+    }
+    if (action.type === 'offline') { s.offline = !s.offline; s.note = s.offline ? '网络连接已断开' : '网络已恢复'; return s; }
+    if (s.offline && ['start', 'apply', 'retry', 'addon'].includes(action.type)) { s.note = '网络暂时不可用,请重试。'; return s; }
+    if (action.type === 'start') {
+      if (s.job && s.job.status !== 'ready') { s.view = 'waiting'; s.note = '正在开通'; return s; }
+      if (action.plan === 'trial') {
+        if (s.trialClaimed) { s.note = '试用已领取'; return s; }
+        s.plan = 'trial'; s.trialClaimed = true;
+      } else if (!canCreate(s) && s.access !== 'unopened') { s.note = '名额不足'; return s; }
+      s.jobSequence += 1;
+      s.job = { id: 'DEMO-JOB-' + String(s.jobSequence).padStart(3, '0'), status: 'queued', stage: 0, completed: 0, name: action.name || '我的第一个容器', createdAt: s.now, updatedAt: s.now, attempt: 1, delayed: false, error: null };
+      if (!s.containers.length) s.access = 'provisioning';
+      s.view = 'waiting';
+    }
+    if (action.type === 'advance' && s.job && !['ready', 'failed'].includes(s.job.status)) {
+      s.now += 90000; s.job.updatedAt = s.now; s.job.delayed = false;
+      if (s.job.stage < STAGES.length - 1) {
+        s.job.stage += 1; s.job.completed = s.job.stage;
+        s.job.status = s.job.stage === STAGES.length - 1 ? 'verifying' : 'provisioning';
+      } else {
+        s.job.status = 'ready'; s.job.completed = STAGES.length;
+        const container = { ...seedContainer(s.containers.length + 1, s.company), name: s.job.name };
+        s.containers.push(container); s.job.agentId = container.id; s.access = 'active';
+        if (s.plan === 'trial' && s.trialStartedAt === null) { s.trialStartedAt = s.now; s.trialExpiresAt = s.now + 48 * 3600000; }
+        s.note = '已就绪';
+      }
+    }
+    if (action.type === 'fail' && s.job && s.job.status !== 'ready') { s.job.status = 'failed'; s.job.error = '当前步骤执行失败。平台已保留完成的资源与原任务,可安全重试。'; s.job.updatedAt = s.now; }
+    if (action.type === 'slow' && s.job && !['ready', 'failed'].includes(s.job.status)) { s.now += 45 * 60000; s.job.delayed = true; }
+    if (action.type === 'retry' && s.job?.status === 'failed') { s.job.status = s.job.stage === 5 ? 'verifying' : 'provisioning'; s.job.error = null; s.job.attempt += 1; s.job.updatedAt = s.now; s.view = 'waiting'; s.note = '正在重试'; }
+    if (action.type === 'apply') {
+      if (action.plan === 'enterprise' && s.activeSubject !== 'company') { s.view = 'enterprise'; s.note = '请先核实企业身份,企业权益与个人权益分别管理。'; return s; }
+      if (s.activeSubject === 'company' && action.plan !== 'enterprise') switchSubject(s, 'personal');
+      if (s.access === 'active' && s.plan !== 'trial' && PLANS[action.plan].limit < limit(s)) { s.note = '更换套餐请联系客服。'; return s; }
+      s.application = { kind: s.access === 'expired' ? 'restore' : 'plan', plan: action.plan, status: 'pending' }; s.note = '申请已提交';
+    }
+    if (action.type === 'addon') {
+      if (!['advanced', 'enterprise'].includes(s.plan)) { s.note = '请先升级套餐'; return s; }
+      s.application = { kind: 'addon', quantity: action.quantity, status: 'pending' }; s.note = '申请已提交';
+    }
+    if (action.type === 'approve' && s.application?.status === 'pending') {
+      const application = s.application; s.application = null;
+      if (application.kind === 'addon') { s.addon += application.quantity; s.note = '名额已更新'; }
+      else {
+        const hadContainer = s.containers.length > 0;
+        s.plan = application.plan;
+        s.access = 'active';
+        if (hadContainer) { s.view = 'containers'; s.note = '已恢复使用'; }
+        else return reduce(s, { type: 'start', plan: s.plan, name: '我的第一个容器' });
+      }
+    }
+    if (action.type === 'expire' && s.plan === 'trial' && s.access === 'active') { s.now = s.trialExpiresAt; s.access = 'expired'; s.view = 'expired'; s.note = '试用已结束'; }
+    if (action.type === 'join' && s.view === 'enterprise') {
+      if (s.activeSubject === 'company') return s;
+      if (!s.companyAccount) s.companyAccount = { plan: 'enterprise', access: 'active', trialClaimed: false, trialStartedAt: null, trialExpiresAt: null, containers: [seedContainer(1, true), seedContainer(2, true)], addon: 0, application: null, job: null, jobSequence: 0 };
+      switchSubject(s, 'company'); s.view = 'enterprise'; s.note = '已加入企业';
+    }
+    if (action.type === 'rename') { const target = s.containers.find((item) => item.id === action.id); if (target && hasAccess(s)) target.name = action.name; }
+    return s;
+  }
+  return { PLANS, STAGES, initial, reduce, limit, reserved, used, hasAccess, canCreate };
+})();
+</script>
+  <script>const Demo = SubscriptionDemo;
+const params = new URLSearchParams(location.search);
+const knownScenarios = ['new', 'waiting', 'failed', 'advanced', 'quota', 'expired', 'enterprise'];
+let state = Demo.initial(knownScenarios.includes(params.get('scenario')) ? params.get('scenario') : 'new');
+const views = { plans: '套餐与开通', waiting: '开通进度', containers: '我的容器', access: '接入信息', enterprise: '加入企业', account: '我的账号', expired: '继续使用 Fmode', chat: '开始协作' };
+const requestedView = params.get('screen') || location.hash.slice(1);
+if (views[requestedView]) state = Demo.reduce(state, { type: 'view', view: requestedView });
+if (params.get('theme') === 'dark') document.documentElement.classList.add('dark');
+const main = document.getElementById('main');
+const dialog = document.getElementById('dialog');
+const dialogBody = document.getElementById('dialogBody');
+let dialogContext = null;
+let dialogTrigger = null;
+let toastTimer;
+const esc = (value) => String(value ?? '').replace(/[&<>"']/g, (character) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[character]);
+const paths = {
+  grid: '<rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/>',
+  server: '<rect x="3" y="3" width="18" height="7" rx="2"/><rect x="3" y="14" width="18" height="7" rx="2"/><path d="M7 6.5h.01M7 17.5h.01M12 6.5h5M12 17.5h5"/>',
+  arrow: '<path d="M4 12h16m-6-6 6 6-6 6"/>',
+  check: '<path d="m5 12 4 4L19 6"/>',
+  clock: '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>',
+  shield: '<path d="m12 3 8 3v6c0 5-8 9-8 9S4 17 4 12V6l8-3Z"/><path d="m8 12 3 3 5-6"/>',
+  person: '<circle cx="12" cy="8" r="4"/><path d="M4 21v-2a8 8 0 0 1 16 0v2"/>',
+  people: '<circle cx="9" cy="8" r="3"/><path d="M3 21v-3a6 6 0 0 1 12 0v3M16 5a3 3 0 0 1 0 6m2 3a5 5 0 0 1 3 4v3"/>',
+  key: '<circle cx="8" cy="8" r="5"/><path d="m12 12 9 9m-4-4 3-3m-6 0 3-3"/>',
+  copy: '<rect x="8" y="8" width="12" height="13" rx="2"/><path d="M16 8V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h3"/>',
+  plus: '<path d="M12 5v14M5 12h14"/>',
+  refresh: '<path d="M20 7v5h-5M4 17v-5h5"/><path d="M6 6a8 8 0 0 1 13 3M5 15a8 8 0 0 0 13 3"/>',
+  spark: '<path d="m12 3 2.4 6.6L21 12l-6.6 2.4L12 21l-2.4-6.6L3 12l6.6-2.4L12 3Z"/>',
+  cloud: '<path d="M7 19a5 5 0 1 1 .5-10A7 7 0 0 1 21 12a4 4 0 0 1-1 7H7Z"/>',
+  chat: '<path d="M5 4h14a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2H9l-6 3V6a2 2 0 0 1 2-2Z"/><path d="M7 9h10M7 13h6"/>',
+  info: '<circle cx="12" cy="12" r="9"/><path d="M12 11v6M12 7h.01"/>',
+  warning: '<path d="m12 3 10 18H2L12 3Z"/><path d="M12 9v5M12 17h.01"/>',
+  wifi: '<path d="M2 8a16 16 0 0 1 20 0M5 12a11 11 0 0 1 14 0M8 16a6 6 0 0 1 8 0M12 20h.01M3 3l18 18"/>',
+  close: '<path d="m6 6 12 12M18 6 6 18"/>',
+  building: '<path d="M4 21V5l8-3 8 3v16H4ZM9 21v-5h6v5M8 7h1m6 0h1M8 11h1m6 0h1"/>',
+  link: '<path d="m10 14 4-4m-6 6-2 2a4 4 0 0 1-6-6l5-5a4 4 0 0 1 6 0m2 10a4 4 0 0 0 6 0l5-5a4 4 0 0 0-6-6l-2 2" transform="translate(2 0) scale(.85 1)"/>',
+};
+const icon = (name) => `<svg class="icon" viewBox="0 0 24 24" aria-hidden="true">${paths[name] || paths.grid}</svg>`;
+const button = (text, action, kind = '', extra = '') => `<button type="button" class="button ${kind}" data-action="${action}" ${extra}>${text}</button>`;
+const notice = (title, text, tone = '', name = 'info') => `<div class="notice ${tone}">${icon(name)}<div><strong>${title}</strong>${text ? `<p>${text}</p>` : ''}</div></div>`;
+const planName = () => state.plan ? Demo.PLANS[state.plan].name : '尚未开通';
+const stateLabel = () => state.offline ? '网络未连接' : ({ unopened: '尚未开通', provisioning: '正在开通', active: state.plan === 'trial' ? '试用中' : '已开通', expired: '试用已到期' })[state.access];
+const priceNotice = '具体价格请咨询客服。';
+
+function nav() {
+  const items = [{ view: 'plans', label: '套餐与开通', mobile: '套餐', icon: 'grid' }, { view: 'containers', label: '我的容器', mobile: '容器', icon: 'server' }, { view: 'access', label: '接入信息', mobile: '接入', icon: 'key' }, { view: 'enterprise', label: state.company || state.companyAccount ? '企业空间' : '加入企业', mobile: '企业', icon: 'people' }];
+  document.getElementById('desktopNav').innerHTML = items.map((item) => `<button type="button" class="nav-button ${state.view === item.view || state.view === 'expired' && item.view === 'plans' || state.view === 'waiting' && item.view === 'containers' ? 'on' : ''}" data-view="${item.view}" ${state.view === item.view ? 'aria-current="page"' : ''}>${icon(item.icon)}<span>${item.label}</span>${item.view === 'containers' && state.containers.length ? `<span class="nav-badge">${state.containers.length}</span>` : ''}</button>`).join('');
+  document.getElementById('mobileNav').innerHTML = items.map((item) => `<button type="button" class="${state.view === item.view || state.view === 'expired' && item.view === 'plans' || state.view === 'waiting' && item.view === 'containers' ? 'on' : ''}" data-view="${item.view}" ${state.view === item.view ? 'aria-current="page"' : ''}>${icon(item.icon)}<span>${item.mobile}</span></button>`).join('');
+}
+
+function planCards() {
+  const cards = [
+    { key: 'starter', icon: 'server', name: '入门版', short: '入门', sub: '一个专属空间,从这里开始。', unit: '/ 月', note: '支持 1 个容器', mobileQuota: '1 个专属容器 · 2 核 4G', mobileBenefit: '独立云资源 · 含完整接入信息', quota: '1', quotaLabel: '个容器', perks: ['1 个专属容器', '2 核 4G 标准规格', '独立云资源', '完整接入信息', '手机与电脑均可使用'] },
+    { key: 'advanced', icon: 'spark', name: '进阶版', short: '进阶', sub: '更多空间,接住不同的想法。', unit: '/ 年', note: '含一年资源费用', mobileQuota: '3 个专属容器 · 2 核 4G', mobileBenefit: '独立云资源 · 支持加购名额', quota: '3', quotaLabel: '个容器', perks: ['3 个专属容器', '2 核 4G 标准规格', '独立云资源与接入信息', '支持加购容器名额'] },
+    { key: 'enterprise', icon: 'building', name: '企业版', short: '企业', sub: '让整个团队,有序地协作。', unit: '', note: '团队共享', mobileQuota: '5 个共享容器 · 2 核 4G', mobileBenefit: '成员管理 · 通讯录与容器共享', quota: '5', quotaLabel: '个共享', perks: ['5 个企业容器', '2 核 4G 标准规格(新容器)', '企业成员管理', '通讯录与容器共享', '支持加购容器名额'] },
+  ];
+  const cta = (card) => state.access === 'expired' ? '恢复' : state.plan === card.key ? '当前' : '开通';
+  return `<div class="plan-grid">${cards.map((card) => {
+    const disabled = state.plan === card.key && state.access === 'active';
+    const current = state.plan === card.key && state.access === 'active';
+    return `<article class="plan-card ${card.key === 'advanced' ? 'featured' : ''} ${current ? 'current' : ''}" data-plan-card="${card.key}">${card.key === 'advanced' ? '<span class="plan-recommend">推荐</span>' : ''}
+      <div class="plan-mobile-copy"><div class="plan-mobile-heading"><h3>${card.name}</h3>${card.key === 'advanced' ? '<span class="plan-mobile-recommend">推荐</span>' : ''}</div><p class="plan-mobile-quota">${card.mobileQuota}</p><p class="plan-mobile-benefit">${card.mobileBenefit}</p></div>
+      <div class="plan-mobile-action"><div class="plan-mobile-price"><strong>价格待定</strong><span>${card.unit || card.note}</span></div>${button(cta(card), 'apply', card.key === 'advanced' ? '' : 'secondary', `data-plan="${card.key}" ${disabled ? 'disabled' : ''}`)}</div>
+      <div class="plan-icon">${icon(card.icon)}</div>
+      <h3><span class="plan-name-full">${card.name}</span><span class="plan-name-short">${card.short}</span></h3>
+      <p class="plan-sub">${card.sub}</p>
+      <div class="plan-quota"><strong>${card.quota}</strong><span>${card.quotaLabel}</span></div>
+      <div class="plan-price"><strong>价格待定</strong><span>${card.unit}</span></div>
+      <div class="plan-billing-note">${card.note}</div>
+      ${button(cta(card), 'apply', card.key === 'advanced' ? '' : 'secondary', `data-plan="${card.key}" ${disabled ? 'disabled' : ''}`)}
+      <ul class="plan-perks">${card.perks.map((perk) => `<li>${icon('check')}<span>${perk}</span></li>`).join('')}</ul>
+    </article>`;
+  }).join('')}</div>`;
+}
+
+function applicationNotice() {
+  if (!state.application) return '';
+  const addon = state.application.kind === 'addon';
+  return notice(addon ? '增配申请已提交' : '开通申请已提交', '等待确认。', 'info', 'clock');
+}
+
+function plansPage() {
+  let trial = '';
+  if (!state.trialClaimed && state.access === 'unopened') {
+    trial = `<section class="trial-banner" aria-label="两天试用"><div class="trial-icon">${icon('spark')}</div><div><h2>先体验,再决定。<span>两天试用</span></h2><p>1 个专属容器,开通后开始体验。</p></div>${button('开始两天试用 ' + icon('arrow'), 'trial')}</section>`;
+  } else if (state.job && state.job.status !== 'ready') {
+    trial = `<section class="trial-banner"><div class="trial-icon">${icon('clock')}</div><div><h2>正在开通</h2><p>${esc(state.job.name)}</p></div>${button('查看进度 ' + icon('arrow'), 'waiting')}</section>`;
+  } else if (state.access === 'active') {
+    trial = `<section class="trial-banner"><div class="trial-icon">${icon('check')}</div><div><h2>${esc(planName())}<span>${state.plan === 'trial' ? '试用中' : '使用中'}</span></h2><p>已使用 ${Demo.used(state)} / ${Demo.limit(state)} 个名额</p></div>${button('我的容器 ' + icon('arrow'), 'containers')}</section>`;
+  }
+  return `<div class="page"><header class="page-heading"><div><span class="eyebrow">${icon('grid')}套餐与开通</span><h1>选择适合你的协作方式。</h1><p>按需选择,随时升级。</p></div></header>${applicationNotice()}${trial}<div class="section-heading"><h2>为下一步,准备合适的空间</h2><p>个人专属 · 企业共享 · 按需增配</p></div>${planCards()}<p class="plans-note">${icon('info')}<span>${priceNotice}</span></p><div class="info-grid"><section class="info-item">${icon('building')}<div><h3>加入企业</h3><p>使用企业容器</p><button type="button" class="text-action" data-view="enterprise">加入企业 ${icon('arrow')}</button></div></section><section class="info-item">${icon('shield')}<div><h3>数据为你保留</h3><p>试用结束后,开通套餐即可继续使用。</p></div></section></div></div>`;
+}
+
+function waitingPage() {
+  const job = state.job;
+  if (!job) return `<div class="page narrow"><div class="panel empty-state"><div class="task-orb">${icon('clock')}</div><h2>暂无开通记录</h2>${button('查看套餐', 'plans')}</div></div>`;
+  const ready = job.status === 'ready', failed = job.status === 'failed';
+  const percent = ready ? 100 : Math.min(99, Math.floor(job.completed / Demo.STAGES.length * 100));
+  const label = ready ? '已就绪' : failed ? '开通失败' : job.status === 'queued' ? '等待开通' : job.status === 'verifying' ? '即将就绪' : '正在开通';
+  const elapsed = Math.floor((state.now - job.createdAt) / 60000);
+  const feedback = state.offline ? notice('网络连接已断开', '请检查网络后重试。', 'warning', 'wifi') : failed ? notice('暂时未能完成开通', '请稍后重试。', 'warning', 'warning') : job.delayed ? notice('仍在处理中', '请稍后查看。', '', 'clock') : '';
+  return `<div class="page narrow"><header class="page-heading"><div><h1>开通进度</h1></div></header>${feedback}<section class="panel waiting-simple"><div class="waiting-current"><span class="task-orb ${ready ? 'success' : failed ? 'failed' : ''}">${icon(ready ? 'check' : failed ? 'warning' : 'server')}</span><h2>${label}</h2><p>${esc(job.name)}</p><span class="state-pill">${esc(planName())}</span></div><div class="waiting-progress"><div class="progress-label"><span>开通进度</span><strong>${percent}%</strong></div><div class="progress-track" role="progressbar" aria-label="开通进度" aria-valuenow="${percent}" aria-valuemin="0" aria-valuemax="100"><div class="progress-fill" style="width:${percent}%"></div></div></div><dl class="waiting-meta"><div><dt>${ready ? '状态' : '已等待'}</dt><dd>${ready ? '已就绪' : elapsed + ' 分钟'}</dd></div><div><dt>${ready ? '当前套餐' : '预计完成'}</dt><dd>${ready ? esc(planName()) : '稍后更新'}</dd></div></dl><div class="waiting-actions">${ready ? button('开始使用 ' + icon('arrow'), 'chat') : failed ? button(icon('refresh') + '重试', 'retry', '', state.offline ? 'disabled' : '') : button(icon('refresh') + '检查进度', 'check', '', state.offline ? 'disabled' : '')}${button('我的容器', 'containers', 'secondary')}</div><button type="button" class="text-action support-action" data-action="copy-job">${icon('copy')}复制服务编号</button></section></div>`;
+}
+
+function quotaPanel() {
+  const used = Demo.used(state), reserved = Demo.reserved(state), max = Demo.limit(state);
+  return `<section class="panel quota-panel"><div class="quota-copy"><h2>${state.company ? '企业共享名额' : '我的容器名额'} <span class="state-pill ${state.plan === 'trial' ? 'pending' : 'ready'}">${esc(planName())}</span></h2><p>已用 ${used} 个${reserved ? `,开通中 ${reserved} 个` : ''}${state.addon ? `,已含加购 ${state.addon} 个` : ''}。</p></div><div class="quota-meter"><p><strong>${used + reserved}</strong> / ${max} 个名额</p><div class="progress-track"><div class="progress-fill" style="width:${max ? Math.min(100,(used + reserved) / max * 100) : 0}%"></div></div></div>${['advanced', 'enterprise'].includes(state.plan) ? button('增加名额', 'addon', 'secondary') : button('查看套餐', 'plans', 'secondary')}</section>`;
+}
+
+function containerCard(container) {
+  return `<article class="panel container-card" data-container-id="${esc(container.id)}"><div class="container-head"><span class="container-avatar">${esc(container.name.slice(0,1))}</span><div><h3>${esc(container.name)}</h3><small>${container.company ? '企业共享' : '归属于我'}</small></div><span class="state-pill ready">已就绪</span></div><div class="container-meta"><span>2 核 CPU</span><span>4 GB 内存</span><span>平台容器</span></div><p class="container-caption">可以开始使用。</p><div class="container-actions">${button('进入会话 ' + icon('arrow'), 'chat', '', `data-id="${esc(container.id)}"`)}${button('设置', 'settings', 'secondary', `data-id="${esc(container.id)}"`)}</div></article>`;
+}
+
+function containersPage() {
+  if (!state.plan) return `<div class="page"><header class="page-heading"><div><span class="eyebrow">${icon('server')}我的容器</span><h1>我的容器</h1><p>管理你的专属空间。</p></div></header><div class="panel empty-state"><div class="task-orb">${icon('server')}</div><h2>还没有容器</h2><p>选择套餐,开始使用。</p>${button('领取两天试用 ' + icon('arrow'), 'trial')}</div></div>`;
+  const activeJob = state.job && state.job.status !== 'ready';
+  return `<div class="page"><header class="page-heading"><div><span class="eyebrow">${icon('server')}${state.company ? '企业容器' : '我的容器'}</span><h1>${state.company ? '企业容器' : '我的容器'}</h1><p>${state.company ? '团队共享的容器。' : '管理你的专属空间。'}</p></div>${button(icon('plus') + '创建容器', 'create', '', !Demo.canCreate(state) ? 'disabled' : '')}</header>${applicationNotice()}${quotaPanel()}${activeJob ? notice('有一个容器正在开通', '', 'info', 'clock') + button('查看开通进度 ' + icon('arrow'), 'waiting', 'secondary') : ''}${Demo.used(state) >= Demo.limit(state) && !activeJob ? notice('名额已用完', ['advanced','enterprise'].includes(state.plan) ? '可申请增加名额。' : '升级套餐,获取更多名额。', '', 'info') : ''}<div class="container-grid" style="margin-top:var(--sp-5)">${state.containers.map(containerCard).join('')}${Demo.canCreate(state) ? `<button type="button" class="create-card" data-action="create">${icon('plus')}<strong>为新的想法,创建一个空间</strong><p>剩余 ${Demo.limit(state) - Demo.used(state)} 个名额</p></button>` : ''}</div>${!state.containers.length ? '<p class="lead">正在开通,请稍后查看。</p>' : ''}</div>`;
+}
+
+const fakeCredentials = [
+  { group: 'matrix', label: 'agentMxId', value: '@demo-agent:example.invalid' },
+  { group: 'matrix', label: 'userMxId', value: '@demo-user:example.invalid' },
+  { group: 'matrix', label: 'homeserver', value: 'https://matrix.example.invalid' },
+  { group: 'matrix', label: 'roomId', value: '!demo-room:example.invalid' },
+  { group: 'matrix', label: 'accessToken', value: 'DEMO_ONLY_NOT_A_REAL_MATRIX_TOKEN' },
+  { group: 'backend', label: 'appId', value: 'DEMO_APP_ID_NOT_REAL' },
+  { group: 'backend', label: 'serverURL', value: 'https://backend.example.invalid/parse' },
+  { group: 'backend', label: 'functionsURL', value: 'https://backend.example.invalid/functions' },
+  { group: 'backend', label: '独立资源专属凭据', value: 'DEMO_ONLY_RESOURCE_SCOPED_CREDENTIAL' },
+];
+function credentialsPage() {
+  if (!Demo.hasAccess(state) || !state.containers.length) return `<div class="page narrow"><header class="page-heading"><div><span class="eyebrow">${icon('key')}接入信息</span><h1>接入信息</h1><p></p></div></header><div class="panel empty-state"><div class="task-orb">${icon('key')}</div><h2>${state.job ? '正在准备' : '暂无接入信息'}</h2><p>开通完成后可查看。</p>${button(state.job ? '查看开通进度' : '查看套餐', state.job ? 'waiting' : 'plans')}</div></div>`;
+  const panel = (group, heading, text, name) => `<section class="panel resource-panel"><h2>${icon(name)}${heading}</h2><p>${text}</p><dl class="credential-list">${fakeCredentials.filter((field) => field.group === group).map((field) => `<div class="credential-row"><dt>${field.label}</dt><dd><span class="masked-value">••••••••••••</span>${button(icon('copy') + '查看与复制', 'credential', 'ghost', `data-field="${esc(field.label)}"`)}</dd></div>`).join('')}</dl></section>`;
+  const backendPanel = state.company ? `<section class="panel resource-panel"><h2>${icon('cloud')}企业资源</h2><p>请联系企业管理员。</p><p class="credential-fake"></p></section>` : panel('backend', '独立云资源', '', 'cloud');
+  return `<div class="page"><header class="page-heading"><div><span class="eyebrow">${icon('key')}接入信息</span><h1>接入信息</h1><p>当前容器:${esc(state.containers[0].name)}。</p></div></header>${notice('请勿分享密钥', '', '', 'shield')}<div class="resource-grid">${panel('matrix', '通信信息', '', 'chat')}${backendPanel}</div><p class="credential-fake"></p></div>`;
+}
+
+function expiredPage() {
+  return `<div class="page"><section class="expired-intro"><div class="task-orb">${icon('clock')}</div><span class="eyebrow">两天试用已结束</span><h1>试用已结束</h1><p>开通套餐后继续使用。</p></section><section class="preserved-resource">${icon('shield')}<div><strong>${esc(state.containers[0]?.name || '我的协作伙伴')}</strong><p>容器和数据已保留。</p></div><span class="state-pill expired">待开通</span></section>${applicationNotice()}${planCards()}<p class="plans-note">${icon('info')}<span>${priceNotice} </span></p><button type="button" class="text-action" data-view="enterprise">加入企业 ${icon('arrow')}</button></div>`;
+}
+
+function enterprisePage() {
+  const org = state.company;
+  if (!org && state.companyAccount) return `<div class="page narrow"><header class="page-heading"><div><span class="eyebrow">${icon('building')}企业空间</span><h1>企业空间</h1><p></p></div></header><section class="panel empty-state"><div class="task-orb">${icon('building')}</div><h2>示例企业</h2><p>5 个共享容器名额</p>${button('进入企业空间 ' + icon('arrow'), 'switch-company')}</section></div>`;
+  return `<div class="page"><header class="page-heading"><div><span class="eyebrow">${icon('building')}${org ? '企业空间' : '加入企业'}</span><h1>${org ? '企业空间' : '加入企业'}</h1><p>${org ? '' : '联系管理员完成邀请。'}</p></div></header>${org ? quotaPanel() : ''}<div class="enterprise-layout"><section class="panel enterprise-card">${org ? `<div class="company-heading"><span class="container-avatar">企</span><div><h2>示例企业</h2><p>企业成员</p></div></div>${['产品协作组','内容协作组'].map((name,index) => `<div class="company-member"><span class="account-avatar">${index ? '内' : '产'}</span><div><strong>${name}</strong><small>示例成员 · 名下 1 个企业容器</small></div><span class="state-pill ready">可协作</span></div>`).join('')}${button('查看企业容器 ' + icon('arrow'), 'containers', 'secondary', 'style="margin-top:var(--sp-5)"')}` : `<h2>等待加入</h2><p>将用户 ID 发给管理员。</p><div class="copy-id"><div><small>用户 ID</small><strong>DEMO_USER_001</strong></div>${button(icon('copy') + '复制', 'copy-user', 'secondary')}</div><div class="waiting-actions" style="margin-top:var(--sp-5)">${button(icon('refresh') + '我已被邀请,立即检查', 'check-org')}</div>`}</section><aside><section class="panel small-panel" style="margin-top:0"><h3>${icon('people')}企业邀请</h3><p>已有邀请?联系管理员完成加入。</p></section>${!org ? `<section class="panel small-panel"><h3>个人使用</h3><p>查看适合你的个人套餐。</p>${button('查看个人套餐', 'plans', 'secondary', 'style="margin-top:var(--sp-4)"')}</section>` : ''}</aside></div></div>`;
+}
+
+function accountPage() {
+  return `<div class="page narrow"><header class="page-heading"><div><h1>我的账号</h1></div></header><section class="panel"><div class="section-heading"><h2>当前套餐</h2><span class="state-pill ${state.access === 'active' ? 'ready' : state.access === 'expired' ? 'expired' : 'pending'}">${stateLabel()}</span></div><dl class="summary-facts"><div><dt>套餐</dt><dd>${esc(planName())}</dd></div><div><dt>容器名额</dt><dd>${Demo.used(state)} / ${Demo.limit(state)}</dd></div><div><dt>试用状态</dt><dd>${state.plan === 'trial' ? stateLabel() : '—'}</dd></div><div><dt>当前空间</dt><dd>${state.company ? '示例企业' : '个人空间'}</dd></div></dl><div class="waiting-actions" style="margin-top:var(--sp-5)">${button('查看套餐', 'plans')}${button('我的容器', 'containers', 'secondary')}</div></section></div>`;
+}
+
+function chatPage() {
+  if (!Demo.hasAccess(state) || !state.containers.length) return state.access === 'expired' ? expiredPage() : waitingPage();
+  return `<div class="page narrow"><div class="panel empty-state"><div class="task-orb success">${icon('chat')}</div><h2>已就绪</h2><p>${esc(state.containers[0].name)}</p>${button('我的容器', 'containers', 'secondary')}</div></div>`;
+}
+
+function render(resetScroll = false) {
+  nav();
+  document.getElementById('pageLabel').textContent = views[state.view] || views.plans;
+  document.getElementById('headerStatus').innerHTML = icon(state.offline ? 'wifi' : 'shield') + esc(stateLabel());
+  const pages = { plans: plansPage, waiting: waitingPage, containers: containersPage, access: credentialsPage, enterprise: enterprisePage, account: accountPage, expired: expiredPage, chat: chatPage };
+  const subjectSwitcher = state.company || state.companyAccount ? `<div class="subject-switch" aria-label="切换权益主体"><span>当前空间</span><button type="button" data-subject="personal" aria-pressed="${!state.company}">${icon('person')}个人空间</button><button type="button" data-subject="company" aria-pressed="${state.company}">${icon('building')}示例企业</button><small></small></div>` : '';
+  main.innerHTML = subjectSwitcher + (pages[state.view] || plansPage)();
+  if (resetScroll) main.scrollTop = 0;
+  document.getElementById('reviewState').textContent = `当前演示:${state.company ? '企业' : '个人'}空间 · ${planName()} · ${stateLabel()} · 容器 ${Demo.used(state)} 个 · 任务预占 ${Demo.reserved(state)} 个 · 配额 ${Demo.limit(state)} 个${state.job ? ' · 任务 ' + state.job.id + ' · 尝试 ' + state.job.attempt + ' 次' : ''}。所有状态均为本地模拟。`;
+  document.querySelector('[data-event="advance"]').disabled = !state.job || ['ready','failed'].includes(state.job.status) || state.offline;
+  document.querySelector('[data-event="fail"]').disabled = !state.job || state.job.status === 'ready';
+  document.querySelector('[data-event="slow"]').disabled = !state.job || ['ready','failed'].includes(state.job.status);
+  document.querySelector('[data-event="approve"]').disabled = !state.application;
+  document.querySelector('[data-event="expire"]').disabled = state.plan !== 'trial' || state.access !== 'active';
+  document.querySelector('[data-event="join"]').disabled = state.view !== 'enterprise' || state.company;
+  document.querySelector('[data-event="offline"]').textContent = state.offline ? '恢复网络' : '模拟断网';
+  document.getElementById('themeToggle').textContent = document.documentElement.classList.contains('dark') ? '浅色' : '深色';
+}
+
+function toast(message) {
+  clearTimeout(toastTimer);
+  const element = document.getElementById('toast');
+  element.textContent = message; element.classList.add('visible');
+  toastTimer = setTimeout(() => element.classList.remove('visible'), 3400);
+}
+function dispatch(action) {
+  const oldView = state.view;
+  state = Demo.reduce(state, action);
+  render(state.view !== oldView);
+  if (state.note) toast(state.note);
+}
+function go(view) { dispatch({ type: 'view', view }); }
+function closeDialog() { if (dialog.open) dialog.close(); }
+function openDialog(kind, data = {}, trigger = document.activeElement) {
+  dialogContext = { kind, ...data }; dialogTrigger = trigger;
+  const cancel = '<button type="button" class="button secondary" data-close-dialog>暂不操作</button>';
+  if (kind === 'create') {
+    const trial = data.trial;
+    dialogBody.innerHTML = `<form id="createForm"><span class="dialog-kicker">${icon(trial ? 'spark' : 'server')}${trial ? '两天试用' : '创建平台容器'}</span><h2 id="dialogTitle">${trial ? '开始两天试用' : '创建容器'}</h2><p class="dialog-description">${trial ? '1 个专属容器,开通后开始计时。' : '提交后可查看开通进度。'}</p><label class="form-field"><span>容器名称</span><input id="containerName" name="containerName" maxlength="24" required value="${trial ? '我的第一个容器' : '新的协作伙伴'}" autocomplete="off"><small>最多 24 个字符,之后可在容器设置中修改。</small></label><div class="dialog-facts"><div><small>容器规格</small><strong>2 核 4G · 平台容器</strong></div><div><small>${trial ? '试用名额' : '将占用名额'}</small><strong>1 个</strong></div></div>${notice('开通进度', '开通中,请稍后查看。', '', 'shield')}<div class="dialog-actions">${cancel}<button type="submit" class="button">${trial ? '开始开通试用' : '提交创建申请'} ${icon('arrow')}</button></div></form>`;
+  } else if (kind === 'apply') {
+    const name = Demo.PLANS[data.plan].name;
+    dialogBody.innerHTML = `<form id="applyForm"><span class="dialog-kicker">${icon('grid')}套餐开通</span><h2 id="dialogTitle">${state.access === 'expired' ? '开通套餐' : '申请开通' + name}</h2><p class="dialog-description">${name} · 价格待定。请联系客服确认。</p><div class="dialog-facts"><div><small>基础容器上限</small><strong>${Demo.PLANS[data.plan].limit} 个${data.plan === 'enterprise' ? ',企业共享' : ',个人专属'}</strong></div><div><small>当前状态</small><strong>等待开通</strong></div></div>${notice(state.access === 'expired' ? '数据已保留' : '待确认', state.access === 'expired' ? '开通后继续使用。' : '请联系客服。', '', 'info')}<div class="dialog-actions">${cancel}<button type="submit" class="button">提交申请 ${icon('arrow')}</button></div></form>`;
+  } else if (kind === 'addon') {
+    dialogBody.innerHTML = `<form id="addonForm"><span class="dialog-kicker">${icon('plus')}容器名额增配</span><h2 id="dialogTitle">增加容器名额</h2><p class="dialog-description">当前名额 ${Demo.limit(state)} 个。具体价格请咨询客服。</p><label class="form-field"><span>申请增加名额</span><select id="addonQuantity" name="quantity"><option value="1">增加 1 个</option><option value="2">增加 2 个</option><option value="3">增加 3 个</option></select></label>${notice('等待确认', '', '', 'info')}<div class="dialog-actions">${cancel}<button type="submit" class="button">提交申请</button></div></form>`;
+  } else if (kind === 'credential') {
+    dialogBody.innerHTML = `<span class="dialog-kicker">${icon('shield')}敏感信息确认</span><h2 id="dialogTitle">仅供本人使用,请勿外发。</h2><p class="dialog-description">即将查看并复制「${esc(data.field)}」。请妥善保管。</p>${notice('仅供本人使用', '', '', 'info')}<div id="credentialResult" hidden></div><div class="dialog-actions">${cancel}<button type="button" class="button" data-confirm-credential>确认复制</button></div>`;
+  } else if (kind === 'settings') {
+    const container = state.containers.find((item) => item.id === data.id);
+    if (!container) return;
+    dialogBody.innerHTML = `<form id="renameForm"><span class="dialog-kicker">${icon('server')}容器设置</span><h2 id="dialogTitle">容器设置</h2><label class="form-field"><span>容器名称</span><input id="renameInput" maxlength="24" required value="${esc(container.name)}" autocomplete="off"></label><div class="dialog-actions">${cancel}<button type="submit" class="button">保存名称</button></div></form>`;
+  }
+  dialog.showModal(); document.getElementById('dialogClose').focus();
+}
+
+async function copyText(value, message = '已复制') {
+  try {
+    if (!navigator.clipboard?.writeText) throw new Error('unavailable');
+    await navigator.clipboard.writeText(value);
+    return message;
+  } catch { return '浏览器未允许自动复制,可选中文本手动复制。'; }
+}
+
+document.getElementById('dialogClose').addEventListener('click', closeDialog);
+dialog.addEventListener('close', () => { if (dialogTrigger?.isConnected) dialogTrigger.focus({ preventScroll: true }); else main.focus({ preventScroll: true }); });
+dialog.addEventListener('click', (event) => {
+  const rect = dialog.getBoundingClientRect();
+  if (event.target === dialog && (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom)) closeDialog();
+});
+document.addEventListener('click', async (event) => {
+  const target = event.target.closest('button, a');
+  if (!target || target.disabled) return;
+  if (target.hasAttribute('data-close-dialog')) return closeDialog();
+  if (target.dataset.subject) return dispatch({ type: 'subject', subject: target.dataset.subject });
+  if (target.dataset.view) return go(target.dataset.view);
+  if (target.dataset.scenario) { state = Demo.initial(target.dataset.scenario); render(true); return; }
+  if (target.dataset.event) return dispatch({ type: target.dataset.event });
+  if (target.hasAttribute('data-confirm-credential')) {
+    const field = fakeCredentials.find((item) => item.label === dialogContext?.field);
+    if (!field) return;
+    const result = document.getElementById('credentialResult');
+    result.hidden = false; result.replaceChildren();
+    const code = document.createElement('code'); code.className = 'demo-secret'; code.textContent = field.value;
+    const feedback = document.createElement('p'); feedback.className = 'dialog-feedback'; feedback.setAttribute('role', 'status');
+    result.append(code, feedback); target.disabled = true;
+    feedback.textContent = await copyText(field.value, '原型假数据已复制,请勿用于实际接入。');
+    return;
+  }
+  const action = target.dataset.action;
+  if (!action) return;
+  if (['plans','waiting','containers','chat'].includes(action)) return go(action === 'plans' && state.access === 'expired' ? 'expired' : action);
+  if (action === 'trial') return openDialog('create', { trial: true }, target);
+  if (action === 'create') {
+    if (Demo.canCreate(state)) openDialog('create', { trial: false }, target);
+    else toast('当前名额不可用,请查看套餐或开通中的任务。');
+    return;
+  }
+  if (action === 'apply') {
+    const plan = target.dataset.plan;
+    if (plan === 'enterprise' && !state.company) return go('enterprise');
+    if (state.company && plan !== 'enterprise') dispatch({ type: 'subject', subject: 'personal', view: 'plans' });
+    if (state.access === 'active' && state.plan !== 'trial' && Demo.PLANS[plan].limit < Demo.limit(state)) return toast('更换套餐请联系客服。');
+    return openDialog('apply', { plan }, target);
+  }
+  if (action === 'switch-company') return dispatch({ type: 'subject', subject: 'company', view: 'enterprise' });
+  if (action === 'addon') return openDialog('addon', {}, target);
+  if (action === 'credential') return openDialog('credential', { field: target.dataset.field }, target);
+  if (action === 'settings') return openDialog('settings', { id: target.dataset.id }, target);
+  if (action === 'retry') return dispatch({ type: 'retry' });
+  if (action === 'check') return toast(state.offline ? '网络暂时不可用,原任务仍在平台保留。' : '仍在开通中,请稍后查看。');
+  if (action === 'check-org') return toast('仍在等待邀请。');
+  if (action === 'copy-job') return toast(await copyText(state.job?.id || '', '演示任务编号已复制'));
+  if (action === 'copy-user') return toast(await copyText('DEMO_USER_001', '演示用户 ID 已复制'));
+});
+
+document.addEventListener('submit', (event) => {
+  event.preventDefault();
+  const id = event.target.id;
+  if (id === 'createForm') {
+    const name = document.getElementById('containerName').value.trim();
+    if (!name) return;
+    const trial = dialogContext.trial; closeDialog(); dispatch({ type: 'start', name, plan: trial ? 'trial' : state.plan });
+  }
+  if (id === 'applyForm') { const plan = dialogContext.plan; closeDialog(); dispatch({ type: 'apply', plan }); }
+  if (id === 'addonForm') { const quantity = Number(document.getElementById('addonQuantity').value); closeDialog(); dispatch({ type: 'addon', quantity }); }
+  if (id === 'renameForm') {
+    const name = document.getElementById('renameInput').value.trim(); if (!name) return;
+    const containerId = dialogContext.id; closeDialog(); dispatch({ type: 'rename', id: containerId, name }); toast('演示容器名称已修改');
+  }
+});
+document.getElementById('reviewToggle').addEventListener('click', () => {
+  const controls = document.getElementById('reviewControls'); controls.hidden = !controls.hidden;
+  document.getElementById('reviewToggle').setAttribute('aria-expanded', String(!controls.hidden));
+});
+document.getElementById('themeToggle').addEventListener('click', () => { document.documentElement.classList.toggle('dark'); render(); });
+document.querySelector('.brand').addEventListener('click', (event) => { event.preventDefault(); go('plans'); });
+render(true);
+</script>
+</body>
+</html>

+ 132 - 0
prototypes/fmode-subscription-20261125/model.js

@@ -0,0 +1,132 @@
+/* Local, in-memory review model. It neither calls a platform nor grants real access. */
+const SubscriptionDemo = (() => {
+  const PLANS = {
+    trial: { name: '两天试用', limit: 1 },
+    starter: { name: '入门版', limit: 1 },
+    advanced: { name: '进阶版', limit: 3 },
+    enterprise: { name: '企业版', limit: 5 },
+  };
+  const STAGES = [
+    { key: 'entitlement', title: '确认权益与容器名额', detail: '检查套餐权益,预留本次开通名额。' },
+    { key: 'cloud', title: '准备独立云资源', detail: '配置独立后端、云函数与专属资源凭据。' },
+    { key: 'matrix', title: '建立通信身份', detail: '创建归属于你的 Matrix 身份与会话通道。' },
+    { key: 'container', title: '创建并初始化容器', detail: '准备平台容器,安装已验证的运行环境。' },
+    { key: 'connectivity', title: '接入协作空间', detail: '验证身份与房间,完成通信接入。' },
+    { key: 'verification', title: '完成可用性核验', detail: '核对真实回复、完成信号和新鲜心跳。' },
+  ];
+  const scopeFields = ['plan', 'access', 'trialClaimed', 'trialStartedAt', 'trialExpiresAt', 'containers', 'addon', 'application', 'job', 'jobSequence'];
+  const captureScope = (state) => Object.fromEntries(scopeFields.map((key) => [key, JSON.parse(JSON.stringify(state[key]))]));
+  function switchSubject(state, subject) {
+    if (state.activeSubject === subject) return;
+    const account = state[subject + 'Account'];
+    if (!account) return;
+    state[state.activeSubject + 'Account'] = captureScope(state);
+    for (const key of scopeFields) state[key] = JSON.parse(JSON.stringify(account[key]));
+    state.activeSubject = subject;
+    state.company = subject === 'company';
+  }
+  const seedContainer = (index, company = false) => ({ id: (company ? 'demo-company-container-' : 'demo-container-') + index, name: ['我的协作伙伴', '内容助手', '研究助手', '项目伙伴', '知识助手'][index - 1] || '新的协作伙伴', owner: company ? '示例企业' : '我', company, ready: true });
+  function initial(scenario = 'new') {
+    const state = { scenario, view: 'plans', plan: null, access: 'unopened', trialClaimed: false, trialStartedAt: null, trialExpiresAt: null, now: Date.parse('2026-11-25T10:00:00+08:00'), containers: [], addon: 0, application: null, job: null, offline: false, jobSequence: 0, company: false, activeSubject: 'personal', personalAccount: null, companyAccount: null, note: '' };
+    if (['advanced', 'quota', 'enterprise'].includes(scenario)) {
+      if (scenario === 'enterprise') { state.personalAccount = captureScope(state); state.activeSubject = 'company'; }
+      state.plan = scenario === 'enterprise' ? 'enterprise' : 'advanced';
+      state.company = scenario === 'enterprise';
+      state.access = 'active';
+      state.view = 'containers';
+      state.containers = Array.from({ length: scenario === 'quota' ? 3 : scenario === 'enterprise' ? 2 : 1 }, (_, index) => seedContainer(index + 1, state.company));
+    }
+    if (scenario === 'expired') {
+      state.plan = 'trial'; state.trialClaimed = true; state.access = 'expired'; state.view = 'expired';
+      state.trialStartedAt = state.now - 48 * 3600000; state.trialExpiresAt = state.now;
+      state.containers = [seedContainer(1)];
+    }
+    if (['waiting', 'failed'].includes(scenario)) {
+      const started = reduce(state, { type: 'start', name: '我的第一个容器', plan: 'trial' });
+      started.job.stage = 3; started.job.completed = 3; started.job.status = scenario === 'failed' ? 'failed' : 'provisioning';
+      started.now += 6 * 60000; started.job.updatedAt = started.now;
+      started.job.error = scenario === 'failed' ? '运行环境初始化暂时失败,平台保留了已完成的资源和任务进度。' : null;
+      return started;
+    }
+    return state;
+  }
+  const limit = (state) => state.plan ? PLANS[state.plan].limit + (['advanced', 'enterprise'].includes(state.plan) ? state.addon : 0) : 0;
+  const reserved = (state) => state.job && state.job.status !== 'ready' ? 1 : 0;
+  const used = (state) => state.containers.length;
+  const hasAccess = (state) => state.access === 'active';
+  const canCreate = (state) => hasAccess(state) && !reserved(state) && used(state) < limit(state);
+  const clone = (state) => JSON.parse(JSON.stringify(state));
+  function reduce(previous, action) {
+    const s = clone(previous);
+    s.note = '';
+    if (action.type === 'subject') {
+      switchSubject(s, action.subject);
+      s.view = s.access === 'expired' ? 'expired' : action.view || 'containers';
+      return s;
+    }
+    if (action.type === 'view') {
+      s.view = action.view;
+      if (s.access === 'expired' && ['containers', 'access', 'chat'].includes(s.view)) s.view = 'expired';
+      return s;
+    }
+    if (action.type === 'offline') { s.offline = !s.offline; s.note = s.offline ? '网络连接已断开' : '网络已恢复'; return s; }
+    if (s.offline && ['start', 'apply', 'retry', 'addon'].includes(action.type)) { s.note = '网络暂时不可用,请重试。'; return s; }
+    if (action.type === 'start') {
+      if (s.job && s.job.status !== 'ready') { s.view = 'waiting'; s.note = '正在开通'; return s; }
+      if (action.plan === 'trial') {
+        if (s.trialClaimed) { s.note = '试用已领取'; return s; }
+        s.plan = 'trial'; s.trialClaimed = true;
+      } else if (!canCreate(s) && s.access !== 'unopened') { s.note = '名额不足'; return s; }
+      s.jobSequence += 1;
+      s.job = { id: 'DEMO-JOB-' + String(s.jobSequence).padStart(3, '0'), status: 'queued', stage: 0, completed: 0, name: action.name || '我的第一个容器', createdAt: s.now, updatedAt: s.now, attempt: 1, delayed: false, error: null };
+      if (!s.containers.length) s.access = 'provisioning';
+      s.view = 'waiting';
+    }
+    if (action.type === 'advance' && s.job && !['ready', 'failed'].includes(s.job.status)) {
+      s.now += 90000; s.job.updatedAt = s.now; s.job.delayed = false;
+      if (s.job.stage < STAGES.length - 1) {
+        s.job.stage += 1; s.job.completed = s.job.stage;
+        s.job.status = s.job.stage === STAGES.length - 1 ? 'verifying' : 'provisioning';
+      } else {
+        s.job.status = 'ready'; s.job.completed = STAGES.length;
+        const container = { ...seedContainer(s.containers.length + 1, s.company), name: s.job.name };
+        s.containers.push(container); s.job.agentId = container.id; s.access = 'active';
+        if (s.plan === 'trial' && s.trialStartedAt === null) { s.trialStartedAt = s.now; s.trialExpiresAt = s.now + 48 * 3600000; }
+        s.note = '已就绪';
+      }
+    }
+    if (action.type === 'fail' && s.job && s.job.status !== 'ready') { s.job.status = 'failed'; s.job.error = '当前步骤执行失败。平台已保留完成的资源与原任务,可安全重试。'; s.job.updatedAt = s.now; }
+    if (action.type === 'slow' && s.job && !['ready', 'failed'].includes(s.job.status)) { s.now += 45 * 60000; s.job.delayed = true; }
+    if (action.type === 'retry' && s.job?.status === 'failed') { s.job.status = s.job.stage === 5 ? 'verifying' : 'provisioning'; s.job.error = null; s.job.attempt += 1; s.job.updatedAt = s.now; s.view = 'waiting'; s.note = '正在重试'; }
+    if (action.type === 'apply') {
+      if (action.plan === 'enterprise' && s.activeSubject !== 'company') { s.view = 'enterprise'; s.note = '请先核实企业身份,企业权益与个人权益分别管理。'; return s; }
+      if (s.activeSubject === 'company' && action.plan !== 'enterprise') switchSubject(s, 'personal');
+      if (s.access === 'active' && s.plan !== 'trial' && PLANS[action.plan].limit < limit(s)) { s.note = '更换套餐请联系客服。'; return s; }
+      s.application = { kind: s.access === 'expired' ? 'restore' : 'plan', plan: action.plan, status: 'pending' }; s.note = '申请已提交';
+    }
+    if (action.type === 'addon') {
+      if (!['advanced', 'enterprise'].includes(s.plan)) { s.note = '请先升级套餐'; return s; }
+      s.application = { kind: 'addon', quantity: action.quantity, status: 'pending' }; s.note = '申请已提交';
+    }
+    if (action.type === 'approve' && s.application?.status === 'pending') {
+      const application = s.application; s.application = null;
+      if (application.kind === 'addon') { s.addon += application.quantity; s.note = '名额已更新'; }
+      else {
+        const hadContainer = s.containers.length > 0;
+        s.plan = application.plan;
+        s.access = 'active';
+        if (hadContainer) { s.view = 'containers'; s.note = '已恢复使用'; }
+        else return reduce(s, { type: 'start', plan: s.plan, name: '我的第一个容器' });
+      }
+    }
+    if (action.type === 'expire' && s.plan === 'trial' && s.access === 'active') { s.now = s.trialExpiresAt; s.access = 'expired'; s.view = 'expired'; s.note = '试用已结束'; }
+    if (action.type === 'join' && s.view === 'enterprise') {
+      if (s.activeSubject === 'company') return s;
+      if (!s.companyAccount) s.companyAccount = { plan: 'enterprise', access: 'active', trialClaimed: false, trialStartedAt: null, trialExpiresAt: null, containers: [seedContainer(1, true), seedContainer(2, true)], addon: 0, application: null, job: null, jobSequence: 0 };
+      switchSubject(s, 'company'); s.view = 'enterprise'; s.note = '已加入企业';
+    }
+    if (action.type === 'rename') { const target = s.containers.find((item) => item.id === action.id); if (target && hasAccess(s)) target.name = action.name; }
+    return s;
+  }
+  return { PLANS, STAGES, initial, reduce, limit, reserved, used, hasAccess, canCreate };
+})();

+ 40 - 0
prototypes/fmode-subscription-20261125/preview.template.html

@@ -0,0 +1,40 @@
+<!doctype html>
+<html lang="zh-CN" data-palette="platinum">
+<head>
+  <meta charset="utf-8">
+  <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
+  <meta name="color-scheme" content="light dark">
+  <meta name="description" content="Fmode 套餐与异步开通交互原型。全部状态均为本地演示,不连接平台、不创建容器、不付款。">
+  <title>Fmode · 套餐与开通交互原型</title>
+  <style>/* INJECT_STYLES */</style>
+</head>
+<body>
+  <a class="skip-link" href="#main">跳到主内容</a>
+  <section class="review-bar" aria-label="原型评审控制">
+    <div class="review-line"><span class="review-label"><span class="review-dot"></span>交互原型 <span class="review-version">G-D1 / 待确认</span></span><p>体验从开通到可用的完整动线。<span>以下为本地演示,不会创建容器或付款。</span></p><div class="review-actions"><button type="button" id="themeToggle" class="review-button" aria-label="切换深色模式">深色</button><button type="button" id="reviewToggle" class="review-button" aria-controls="reviewControls" aria-expanded="false">演示场景 <span aria-hidden="true">⌄</span></button></div></div>
+    <div class="review-controls" id="reviewControls" hidden>
+      <div class="review-scenarios" role="group" aria-label="选择演示场景"><button type="button" data-scenario="new">首次进入</button><button type="button" data-scenario="waiting">开通进行中</button><button type="button" data-scenario="failed">开通失败</button><button type="button" data-scenario="advanced">已有容器</button><button type="button" data-scenario="quota">名额已满</button><button type="button" data-scenario="expired">试用到期</button><button type="button" data-scenario="enterprise">企业账号</button></div>
+      <div class="review-events" role="group" aria-label="模拟平台事件"><span>模拟平台回报</span><button type="button" data-event="advance">推进一个阶段</button><button type="button" data-event="fail">当前阶段失败</button><button type="button" data-event="slow">进度延迟</button><button type="button" data-event="offline">切换断网</button><button type="button" data-event="approve">管理员确认</button><button type="button" data-event="expire">试用到期</button><button type="button" data-event="join">企业确认加入</button></div>
+      <p class="review-state" id="reviewState" aria-live="polite"></p>
+    </div>
+  </section>
+  <div class="app-shell">
+    <aside class="sidebar" aria-label="桌面导航">
+      <a class="brand" href="#plans" aria-label="Fmode 套餐首页"><span class="brand-mark">F</span>fmode<span class="brand-registered">®</span></a>
+      <div class="workspace-label"><span class="workspace-avatar">我</span><span>我的协作空间<small>个人与企业,同一个入口</small></span></div>
+      <div class="sidebar-heading">工作空间</div>
+      <nav id="desktopNav"></nav>
+      <div class="sidebar-bottom"><div class="sidebar-note"><span class="status-dot"></span><span>让想法,更进一步。<small>连接你与数字生命。</small></span></div><button type="button" class="account-button" data-view="account"><span class="account-avatar">体</span><span>体验账号<small>原型演示数据</small></span><span class="account-more" aria-hidden="true">···</span></button></div>
+    </aside>
+    <div class="workspace">
+      <header class="app-header"><div class="app-breadcrumb"><span class="mobile-brand">fmode</span><span class="desktop-breadcrumb">账户与空间 <span aria-hidden="true">/</span></span><strong id="pageLabel">套餐与开通</strong></div><div class="header-end"><span class="header-safe" id="headerStatus"></span><button type="button" class="avatar-button" data-view="account" aria-label="查看账号与套餐">体</button></div></header>
+      <main id="main" tabindex="-1"></main>
+      <nav class="mobile-nav" id="mobileNav" aria-label="手机导航"></nav>
+    </div>
+  </div>
+  <dialog class="ui-dialog" id="dialog" aria-labelledby="dialogTitle"><button type="button" class="dialog-close icon-button" id="dialogClose" aria-label="关闭弹窗" autofocus>×</button><div id="dialogBody"></div></dialog>
+  <div class="toast" id="toast" role="status" aria-live="polite" aria-atomic="true"></div>
+  <script>/* INJECT_MODEL */</script>
+  <script>/* INJECT_APP */</script>
+</body>
+</html>

+ 457 - 0
prototypes/fmode-subscription-20261125/styles.css

@@ -0,0 +1,457 @@
+/* Review shell uses the application's real tokens; no production components change. */
+* { box-sizing: border-box; }
+[hidden] { display: none !important; }
+html { height: 100%; }
+body { margin: 0; min-width: 320px; height: 100dvh; display: grid; grid-template-rows: auto minmax(0,1fr); overflow: hidden; color: var(--ink); background: var(--canvas); font-family: var(--font-ui); font-size: var(--fs-17); line-height: 1.6; }
+button, input, select { font: inherit; color: inherit; }
+button, a { -webkit-tap-highlight-color: transparent; touch-action: manipulation; }
+button { cursor: pointer; }
+a { color: inherit; text-decoration: none; }
+button { border: 0; background: none; }
+button:disabled { opacity: .45; cursor: not-allowed; }
+button:focus-visible, a:focus-visible, input:focus-visible, select:focus-visible, summary:focus-visible { outline: 2px solid var(--primary); outline-offset: 3px; }
+h1,h2,h3,h4,p { margin: 0; }
+svg { display: block; flex: none; }
+.icon { width: 20px; height: 20px; fill: none; stroke: currentColor; stroke-width: 1.65; stroke-linecap: round; stroke-linejoin: round; }
+.skip-link { position: fixed; z-index: var(--z-toast); top: 12px; left: 12px; padding: 12px 16px; background: var(--primary); color: var(--primary-content); border-radius: var(--r-md); transform: translateY(-200%); }
+.skip-link:focus { transform: none; }
+.review-bar { position: relative; z-index: var(--z-affix); background: var(--surface); border-bottom: 1px solid var(--edge); }
+.review-line { display: flex; min-height: 48px; align-items: center; gap: var(--sp-5); padding: 0 var(--sp-6); }
+.review-label { display: flex; align-items: center; gap: var(--sp-2); flex: none; font-size: var(--fs-13); font-weight: 600; }
+.review-dot { width: 7px; height: 7px; border-radius: var(--r-tag); background: var(--warning); }
+.review-version { color: var(--muted); font-size: var(--fs-12); font-weight: 400; }
+.review-line > p { flex: 1; color: var(--ink-2); font-size: var(--fs-12); }
+.review-line > p > span { margin-left: var(--sp-3); color: var(--muted); }
+.review-actions { display: flex; gap: var(--sp-2); margin-left: auto; }
+.review-button { display: inline-flex; min-height: 44px; align-items: center; gap: var(--sp-2); padding-inline: var(--sp-3); color: var(--ink-2); font-size: var(--fs-13); }
+.review-controls { max-height: 32dvh; overflow-y: auto; padding: var(--sp-3) var(--sp-6); border-top: 1px solid var(--edge); background: var(--surface-2); }
+.review-scenarios, .review-events { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); }
+.review-controls button { min-height: 44px; padding: var(--sp-2) var(--sp-3); border: 1px solid var(--edge); border-radius: var(--r-sm); background: var(--surface); font-size: var(--fs-13); }
+.review-controls button:hover { border-color: var(--edge-strong); background: var(--surface-hover); }
+.review-events { margin-top: var(--sp-2); }
+.review-events > span, .review-state { color: var(--muted); font-size: var(--fs-12); }
+.review-state { margin-top: var(--sp-2); }
+.app-shell { display: grid; grid-template-columns: 224px minmax(0,1fr); min-height: 0; }
+.sidebar { position: relative; display: flex; min-height: 0; flex-direction: column; padding: var(--sp-6) var(--sp-4) var(--sp-3); border-right: 1px solid var(--edge); background: var(--surface); }
+.brand { display: flex; align-items: center; gap: 9px; width: fit-content; margin: 0 var(--sp-3) var(--sp-6); font-size: var(--fs-26); line-height: 1; font-weight: 700; letter-spacing: -.07em; }
+.brand-mark { display: grid; width: 30px; height: 30px; place-items: center; border-radius: 9px; background: var(--primary); color: var(--primary-content); font-size: var(--fs-20); letter-spacing: -.08em; }
+.brand-registered { align-self: start; margin: 1px 0 0 -5px; color: var(--muted); font-size: 9px; }
+.workspace-label { display: flex; align-items: center; gap: var(--sp-3); margin: 0 var(--sp-2) var(--sp-6); color: var(--ink); font-size: var(--fs-13); font-weight: 600; }
+.workspace-avatar { display: grid; width: 34px; height: 34px; place-items: center; border: 1px solid var(--edge); border-radius: var(--r-md); background: var(--surface-2); font-size: var(--fs-13); }
+.workspace-label small { display: block; margin-top: 2px; color: var(--muted); font-size: var(--fs-11); font-weight: 400; }
+.sidebar-heading { margin: 0 var(--sp-3) var(--sp-2); color: var(--muted); font-size: var(--fs-11); }
+.nav-button { display: flex; width: 100%; min-height: 46px; align-items: center; gap: var(--sp-3); margin-top: var(--sp-1); padding: 0 var(--sp-3); border-radius: var(--r-md); color: var(--muted); font-size: var(--fs-14); text-align: left; }
+.nav-button.on { background: var(--primary-subtle); color: var(--ink); font-weight: 600; }
+.nav-button:hover { background: var(--surface-hover); color: var(--ink); }
+.nav-button .icon { width: 18px; height: 18px; }
+.nav-badge { margin-left: auto; padding: 0 6px; border-radius: var(--r-tag); background: var(--surface); color: var(--ink-2); font-size: var(--fs-11); }
+.sidebar-bottom { margin-top: auto; padding-top: var(--sp-6); }
+.sidebar-note { display: flex; gap: var(--sp-2); margin: 0 var(--sp-3) var(--sp-5); color: var(--ink-2); font-size: var(--fs-12); }
+.sidebar-note small { display: block; margin-top: var(--sp-1); color: var(--muted); font-size: var(--fs-11); }
+.status-dot { display: inline-block; width: 6px; height: 6px; flex: none; margin-top: 7px; border-radius: var(--r-tag); background: var(--success); }
+.account-button { display: flex; width: 100%; min-height: 60px; align-items: center; gap: var(--sp-3); padding: var(--sp-3); border-top: 1px solid var(--edge); text-align: left; font-size: var(--fs-13); }
+.account-avatar, .avatar-button { display: grid; width: 32px; height: 32px; flex: none; place-items: center; border-radius: var(--r-tag); background: var(--avatar-bg); color: var(--avatar-ink); font-size: var(--fs-12); }
+.account-button small { display: block; color: var(--muted); font-size: var(--fs-11); }
+.account-more { margin-left: auto; }
+.workspace { display: grid; min-height: 0; min-width: 0; grid-template-rows: 64px minmax(0,1fr); }
+.app-header { display: flex; align-items: center; justify-content: space-between; padding-inline: var(--sp-8); border-bottom: 1px solid var(--edge); background: var(--surface); }
+.app-breadcrumb { display: flex; align-items: center; gap: var(--sp-3); font-size: var(--fs-13); }
+.desktop-breadcrumb { color: var(--muted); }
+.desktop-breadcrumb > span { margin-left: var(--sp-3); color: var(--edge-strong); }
+.app-breadcrumb strong { font-weight: 500; }
+.mobile-brand { display: none; }
+.header-end { display: flex; align-items: center; gap: var(--sp-5); }
+.header-safe { display: inline-flex; align-items: center; gap: 7px; color: var(--muted); font-size: var(--fs-12); }
+.header-safe .icon { width: 15px; height: 15px; }
+.avatar-button { min-width: 44px; min-height: 44px; width: 32px; height: 32px; background: transparent; }
+.avatar-button::first-letter { background: var(--avatar-bg); }
+main { min-height: 0; min-width: 0; overflow: auto; overscroll-behavior: contain; padding: var(--sp-8); }
+.page { width: min(1120px,100%); margin-inline: auto; }
+.page.narrow { max-width: 850px; }
+.subject-switch { display: flex; width: min(1120px,100%); flex-wrap: wrap; align-items: center; gap: var(--sp-2); margin: 0 auto var(--sp-5); padding-bottom: var(--sp-4); border-bottom: 1px solid var(--edge); }
+.subject-switch > span,.subject-switch small { color: var(--muted); font-size: var(--fs-12); }
+.subject-switch > span { margin-right: var(--sp-2); }
+.subject-switch small { margin-left: auto; }
+.subject-switch button { display: flex; min-height: 44px; align-items: center; gap: var(--sp-2); padding: var(--sp-2) var(--sp-3); border-radius: var(--r-md); font-size: var(--fs-13); }
+.subject-switch button[aria-pressed='true'] { background: var(--primary-subtle); color: var(--ink); font-weight: 600; }
+.subject-switch .icon { width: 16px; height: 16px; }
+.page-heading { display: flex; align-items: flex-end; justify-content: space-between; gap: var(--sp-6); margin-bottom: var(--sp-6); }
+.eyebrow { display: flex; align-items: center; gap: var(--sp-2); margin-bottom: var(--sp-2); color: var(--muted); font-size: var(--fs-12); }
+.eyebrow .icon { width: 15px; height: 15px; }
+h1 { font-size: var(--fs-26); font-weight: 600; letter-spacing: -.05em; line-height: 1.4; }
+.page-heading p, .lead { margin-top: var(--sp-2); color: var(--muted); font-size: var(--fs-14); }
+.page-heading > .button { flex: none; }
+.button { display: inline-flex; min-height: 44px; align-items: center; justify-content: center; gap: var(--sp-2); padding: var(--sp-2) var(--sp-4); border: 1px solid transparent; border-radius: var(--r-md); background: var(--primary); color: var(--primary-content); font-size: var(--fs-14); font-weight: 500; text-align: center; }
+.button:hover { background: var(--primary-hover); }
+.button.secondary { border-color: var(--edge); background: var(--surface); color: var(--ink); }
+.button.secondary:hover { border-color: var(--edge-strong); background: var(--surface-hover); }
+.button.ghost { border-color: transparent; background: transparent; color: var(--ink-2); }
+.button.ghost:hover { background: var(--surface-hover); }
+.button .icon { width: 17px; height: 17px; }
+.text-action { display: inline-flex; min-height: 44px; align-items: center; gap: var(--sp-2); padding: 0; color: var(--ink); font-size: var(--fs-13); font-weight: 500; text-decoration: underline; text-decoration-color: var(--edge-strong); text-underline-offset: 4px; }
+.text-action .icon { width: 15px; height: 15px; }
+.panel { padding: var(--sp-6); border: 1px solid var(--edge); border-radius: var(--r-lg); background: var(--surface); }
+.trial-banner { position: relative; display: grid; grid-template-columns: 48px minmax(0,1fr) auto; align-items: center; gap: var(--sp-5); margin-bottom: var(--sp-8); padding: var(--sp-6); border: 1px solid var(--edge-strong); border-radius: var(--r-lg); background: var(--surface); }
+.trial-icon { display: grid; width: 48px; height: 48px; place-items: center; border: 1px solid var(--edge); border-radius: var(--r-lg); background: var(--surface-2); }
+.trial-icon .icon { width: 24px; height: 24px; }
+.trial-banner h2 { display: flex; align-items: center; gap: var(--sp-3); font-size: var(--fs-20); font-weight: 600; letter-spacing: -.04em; }
+.trial-banner h2 > span { flex: none; padding: 1px 7px; border-radius: var(--r-sm); background: var(--success-subtle); color: var(--success); font-size: var(--fs-11); font-weight: 500; }
+.trial-banner p { margin-top: 6px; color: var(--muted); font-size: var(--fs-13); }
+.trial-facts { display: flex; flex-wrap: wrap; gap: var(--sp-4); margin-top: var(--sp-3); color: var(--ink-2); font-size: var(--fs-12); }
+.trial-facts span { display: inline-flex; align-items: center; gap: 5px; }
+.trial-facts .icon { width: 13px; height: 13px; color: var(--success); }
+.section-heading { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-4); margin-bottom: var(--sp-4); }
+.section-heading h2 { font-size: var(--fs-17); font-weight: 600; }
+.section-heading p { color: var(--muted); font-size: var(--fs-12); }
+.plan-grid { display: grid; grid-template-columns: repeat(3,minmax(0,1fr)); gap: var(--sp-4); }
+.plan-card { position: relative; display: flex; flex-direction: column; min-width: 0; padding: var(--sp-6); border: 1px solid var(--edge); border-radius: var(--r-lg); background: var(--surface); }
+.plan-card.featured { border-color: var(--primary); box-shadow: inset 0 0 0 1px var(--primary); }
+.plan-mobile-copy,.plan-mobile-action { display: none; }
+.plan-recommend { position: absolute; top: -12px; left: var(--sp-5); padding: 2px 9px; border-radius: var(--r-sm); background: var(--primary); color: var(--primary-content); font-size: var(--fs-11); white-space: nowrap; }
+.plan-icon { display: grid; width: 36px; height: 36px; place-items: center; margin-bottom: var(--sp-4); border: 1px solid var(--edge); border-radius: var(--r-md); background: var(--surface-2); }
+.plan-card h3 { font-size: var(--fs-20); font-weight: 600; }
+.plan-name-short { display: none; }
+.plan-card > p { margin-top: 5px; color: var(--muted); font-size: var(--fs-13); }
+.plan-quota { display: none; }
+.plan-price { display: flex; align-items: baseline; gap: 7px; margin-block: var(--sp-6) var(--sp-1); }
+.plan-price strong { font-size: var(--fs-26); font-weight: 600; letter-spacing: -.05em; }
+.plan-price span { color: var(--muted); font-size: var(--fs-12); }
+.plan-billing-note { min-height: 24px; color: var(--muted); font-size: var(--fs-12); }
+.plan-card > .button { margin-top: var(--sp-4); width: 100%; }
+.plan-perks { display: flex; flex-direction: column; gap: var(--sp-3); margin: var(--sp-6) 0 0; padding: var(--sp-5) 0 0; border-top: 1px solid var(--edge); list-style: none; }
+.plan-perks li { display: flex; align-items: flex-start; gap: var(--sp-2); color: var(--ink-2); font-size: var(--fs-13); line-height: 1.7; }
+.plan-perks .icon { width: 14px; height: 14px; margin-top: 4px; color: var(--muted); }
+.plans-note { display: flex; gap: var(--sp-2); margin: var(--sp-5) 0 var(--sp-8); color: var(--muted); font-size: var(--fs-12); }
+.plans-note .icon { width: 15px; height: 15px; margin-top: 2px; }
+.info-grid { display: grid; grid-template-columns: 1fr 1fr; gap: var(--sp-4); }
+.info-item { display: flex; align-items: flex-start; gap: var(--sp-3); }
+.info-item > .icon { margin-top: 4px; color: var(--muted); }
+.info-item h3 { margin-bottom: 5px; font-size: var(--fs-14); font-weight: 500; }
+.info-item p { max-width: 400px; color: var(--muted); font-size: var(--fs-13); }
+.info-item .text-action { margin-top: var(--sp-1); }
+.notice { display: flex; align-items: flex-start; gap: var(--sp-3); margin-bottom: var(--sp-5); padding: var(--sp-4) var(--sp-5); border: 1px solid var(--edge); border-radius: var(--r-md); background: var(--surface); font-size: var(--fs-13); }
+.notice .icon { width: 18px; height: 18px; margin-top: 2px; flex: none; }
+.notice strong { display: block; font-weight: 500; }
+.notice p { margin-top: var(--sp-1); color: var(--muted); }
+.notice.warning { border-color: color-mix(in srgb,var(--warning) 25%,var(--edge)); background: var(--warning-subtle); color: var(--warning); }
+.notice.warning p { color: var(--warning); }
+.notice.info { background: var(--info-subtle); color: var(--info); }
+.notice.info p { color: var(--info); }
+.notice.success { background: var(--success-subtle); color: var(--success); }
+.notice.success p { color: var(--success); }
+.notice > .button { margin-left: auto; flex: none; }
+.waiting-layout { display: grid; grid-template-columns: minmax(0,1fr) 280px; align-items: start; gap: var(--sp-5); }
+.waiting-card { padding: var(--sp-6); }
+.task-hero { display: flex; align-items: center; gap: var(--sp-4); padding-bottom: var(--sp-6); }
+.task-orb { display: grid; width: 56px; height: 56px; flex: none; place-items: center; border: 1px solid var(--edge); border-radius: var(--r-lg); background: var(--surface-2); }
+.task-orb .icon { width: 26px; height: 26px; }
+.task-orb.success { background: var(--success-subtle); color: var(--success); }
+.task-orb.failed { background: var(--danger-subtle); color: var(--danger); }
+.task-hero h2 { font-size: var(--fs-20); font-weight: 600; letter-spacing: -.04em; }
+.task-hero p { margin-top: var(--sp-1); color: var(--muted); font-size: var(--fs-13); }
+.progress-label { display: flex; justify-content: space-between; color: var(--muted); font-size: var(--fs-12); }
+.progress-label strong { color: var(--ink); font-weight: 500; }
+.progress-track { width: 100%; height: 5px; margin-top: var(--sp-3); overflow: hidden; border-radius: var(--r-tag); background: var(--surface-hover); }
+.progress-fill { height: 100%; border-radius: inherit; background: var(--primary); }
+.job-steps { margin: var(--sp-6) 0; padding: 0; list-style: none; }
+.job-step { position: relative; display: grid; grid-template-columns: 28px minmax(0,1fr) auto; gap: var(--sp-3); min-height: 72px; }
+.job-step:not(:last-child)::after { position: absolute; top: 29px; bottom: 3px; left: 13px; width: 1px; background: var(--edge); content: ''; }
+.step-icon { display: grid; width: 28px; height: 28px; place-items: center; border: 1px solid var(--edge); border-radius: var(--r-tag); background: var(--surface); color: var(--muted); font-size: var(--fs-12); }
+.step-icon .icon { width: 14px; height: 14px; }
+.job-step.done .step-icon { border-color: transparent; background: var(--success-subtle); color: var(--success); }
+.job-step.current .step-icon { border-color: var(--primary); background: var(--primary); color: var(--primary-content); }
+.job-step.failed .step-icon { border-color: transparent; background: var(--danger-subtle); color: var(--danger); }
+.step-copy strong { display: block; font-size: var(--fs-14); font-weight: 500; }
+.step-copy p { margin-top: 3px; color: var(--muted); font-size: var(--fs-12); }
+.step-state { padding-top: 3px; color: var(--muted); font-size: var(--fs-11); white-space: nowrap; }
+.job-step.done .step-state { color: var(--success); }
+.job-step.failed .step-state { color: var(--danger); }
+.waiting-actions { display: flex; flex-wrap: wrap; gap: var(--sp-3); padding-top: var(--sp-5); border-top: 1px solid var(--edge); }
+.waiting-foot { margin-top: var(--sp-4); color: var(--muted); font-size: var(--fs-12); }
+.waiting-simple { display: flex; min-height: 500px; align-items: center; flex-direction: column; justify-content: center; padding: var(--sp-8); }
+.waiting-current { text-align: center; }
+.waiting-current .task-orb { width: 64px; height: 64px; margin: 0 auto var(--sp-5); }
+.waiting-current h2 { font-size: var(--fs-26); font-weight: 600; letter-spacing: -.04em; }
+.waiting-current > p { margin: var(--sp-2) 0 var(--sp-3); color: var(--muted); font-size: var(--fs-14); }
+.waiting-progress { width: min(360px,100%); margin-top: var(--sp-8); }
+.waiting-meta { display: grid; width: min(360px,100%); grid-template-columns: 1fr 1fr; gap: var(--sp-5); margin: var(--sp-6) 0; text-align: center; }
+.waiting-meta dt { color: var(--muted); font-size: var(--fs-12); }
+.waiting-meta dd { margin: var(--sp-1) 0 0; color: var(--ink); font-size: var(--fs-14); }
+.waiting-simple .waiting-actions { justify-content: center; padding-top: 0; border-top: 0; }
+.support-action { margin-top: var(--sp-3); color: var(--muted); font-size: var(--fs-12); }
+.task-summary h3 { margin-bottom: var(--sp-4); font-size: var(--fs-14); font-weight: 500; }
+.summary-facts { margin: 0; }
+.summary-facts > div { margin-top: var(--sp-4); }
+.summary-facts dt { margin-bottom: 4px; color: var(--muted); font-size: var(--fs-12); }
+.summary-facts dd { margin: 0; font-size: var(--fs-13); overflow-wrap: anywhere; }
+.summary-facts dd.emphasis { font-weight: 600; }
+.task-summary .text-action { margin-top: var(--sp-4); font-size: var(--fs-12); }
+.small-panel { margin-top: var(--sp-4); padding: var(--sp-5); }
+.small-panel h3 { display: flex; align-items: center; gap: var(--sp-2); font-size: var(--fs-13); font-weight: 500; }
+.small-panel h3 .icon { width: 16px; height: 16px; }
+.small-panel p { margin-top: var(--sp-2); color: var(--muted); font-size: var(--fs-12); }
+.state-pill { display: inline-flex; align-items: center; gap: 5px; padding: 2px 8px; border-radius: var(--r-tag); background: var(--surface-2); color: var(--muted); font-size: var(--fs-11); white-space: nowrap; }
+.state-pill.ready { color: var(--success); background: var(--success-subtle); }
+.state-pill.pending { color: var(--warning); background: var(--warning-subtle); }
+.state-pill.expired { color: var(--danger); background: var(--danger-subtle); }
+.quota-panel { display: flex; justify-content: space-between; align-items: center; gap: var(--sp-5); margin-bottom: var(--sp-6); }
+.quota-copy h2 { font-size: var(--fs-14); font-weight: 500; }
+.quota-copy p { margin-top: var(--sp-1); color: var(--muted); font-size: var(--fs-13); }
+.quota-meter { min-width: 180px; }
+.quota-meter p { color: var(--muted); font-size: var(--fs-12); }
+.quota-meter strong { color: var(--ink); font-size: var(--fs-20); font-weight: 600; }
+.container-grid { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: var(--sp-4); }
+.container-card { padding: var(--sp-5); }
+.container-head { display: flex; align-items: center; gap: var(--sp-3); }
+.container-avatar { display: grid; width: 44px; height: 44px; flex: none; place-items: center; border-radius: var(--r-md); background: var(--avatar-bg); color: var(--avatar-ink); font-size: var(--fs-17); font-weight: 600; }
+.container-head > div { min-width: 0; }
+.container-head h3 { overflow: hidden; font-size: var(--fs-17); font-weight: 500; text-overflow: ellipsis; white-space: nowrap; }
+.container-head small { color: var(--muted); font-size: var(--fs-12); }
+.container-head > .state-pill { margin-left: auto; }
+.container-meta { display: flex; flex-wrap: wrap; gap: var(--sp-3); margin-top: var(--sp-5); color: var(--muted); font-size: var(--fs-12); }
+.container-caption { margin-top: var(--sp-3); color: var(--ink-2); font-size: var(--fs-13); }
+.container-actions { display: grid; grid-template-columns: 1fr auto; gap: var(--sp-2); margin-top: var(--sp-5); }
+.container-actions .button { padding-inline: var(--sp-3); font-size: var(--fs-13); }
+.create-card { display: flex; min-height: 237px; align-items: center; justify-content: center; flex-direction: column; gap: var(--sp-3); border: 1px dashed var(--edge-strong); border-radius: var(--r-lg); color: var(--muted); background: transparent; }
+.create-card > .icon { width: 26px; height: 26px; }
+.create-card strong { color: var(--ink-2); font-size: var(--fs-14); font-weight: 500; }
+.create-card p { font-size: var(--fs-12); }
+.empty-state { display: flex; min-height: 350px; align-items: center; justify-content: center; flex-direction: column; gap: var(--sp-3); text-align: center; }
+.empty-state > .task-orb { margin-bottom: var(--sp-3); }
+.empty-state h2 { font-size: var(--fs-20); font-weight: 500; }
+.empty-state p { max-width: 430px; color: var(--muted); font-size: var(--fs-14); }
+.empty-state .button { margin-top: var(--sp-3); }
+.resource-grid { display: grid; grid-template-columns: 1fr 1fr; gap: var(--sp-5); }
+.resource-panel h2 { display: flex; align-items: center; gap: var(--sp-2); margin-bottom: var(--sp-2); font-size: var(--fs-17); font-weight: 600; }
+.resource-panel h2 .icon { width: 19px; height: 19px; }
+.resource-panel > p { color: var(--muted); font-size: var(--fs-13); }
+.credential-list { margin: var(--sp-5) 0 0; }
+.credential-row { padding-block: var(--sp-4); border-top: 1px solid var(--edge); }
+.credential-row dt { display: flex; justify-content: space-between; align-items: center; gap: var(--sp-2); color: var(--muted); font-size: var(--fs-12); }
+.credential-row dd { display: flex; min-height: 24px; justify-content: space-between; gap: var(--sp-3); margin: var(--sp-1) 0 0; font-family: ui-monospace,Consolas,monospace; font-size: var(--fs-13); overflow-wrap: anywhere; }
+.credential-row .button { min-height: 44px; padding-inline: var(--sp-2); flex: none; margin: -10px 0; font-size: var(--fs-12); }
+.masked-value { letter-spacing: .12em; }
+.credential-fake { margin-top: var(--sp-3); color: var(--muted); font-size: var(--fs-12); }
+.expired-intro { margin-bottom: var(--sp-6); }
+.expired-intro .task-orb { margin-bottom: var(--sp-4); }
+.expired-intro h1 { margin-bottom: var(--sp-3); }
+.expired-intro p { max-width: 620px; color: var(--muted); font-size: var(--fs-14); }
+.preserved-resource { display: flex; align-items: center; gap: var(--sp-3); margin-bottom: var(--sp-6); padding: var(--sp-4) var(--sp-5); border: 1px solid var(--edge); border-radius: var(--r-md); background: var(--surface); }
+.preserved-resource > div { flex: 1; }
+.preserved-resource strong { font-size: var(--fs-14); font-weight: 500; }
+.preserved-resource p { margin-top: 3px; color: var(--muted); font-size: var(--fs-12); }
+.enterprise-layout { display: grid; grid-template-columns: minmax(0,1fr) 300px; gap: var(--sp-5); }
+.enterprise-card h2 { margin-bottom: var(--sp-3); font-size: var(--fs-20); font-weight: 600; }
+.enterprise-card > p { color: var(--muted); font-size: var(--fs-14); }
+.join-steps { display: flex; flex-direction: column; gap: var(--sp-5); margin-block: var(--sp-6); }
+.join-step { display: flex; align-items: flex-start; gap: var(--sp-3); }
+.join-step > span { display: grid; width: 26px; height: 26px; flex: none; place-items: center; border: 1px solid var(--edge); border-radius: var(--r-tag); font-size: var(--fs-12); }
+.join-step strong { font-size: var(--fs-14); font-weight: 500; }
+.join-step p { margin-top: var(--sp-1); color: var(--muted); font-size: var(--fs-13); }
+.copy-id { display: flex; align-items: center; gap: var(--sp-3); padding: var(--sp-3) var(--sp-4); border: 1px solid var(--edge); border-radius: var(--r-md); background: var(--surface-2); }
+.copy-id > div { flex: 1; }
+.copy-id small { display: block; color: var(--muted); font-size: var(--fs-12); }
+.copy-id strong { font-family: ui-monospace,Consolas,monospace; font-size: var(--fs-14); font-weight: 500; }
+.company-heading { display: flex; align-items: center; gap: var(--sp-3); margin-bottom: var(--sp-5); }
+.company-heading h2 { font-size: var(--fs-17); font-weight: 500; }
+.company-heading p { color: var(--muted); font-size: var(--fs-12); }
+.company-member { display: flex; align-items: center; gap: var(--sp-3); min-height: 72px; padding-block: var(--sp-3); border-top: 1px solid var(--edge); }
+.company-member strong { font-size: var(--fs-14); font-weight: 500; }
+.company-member small { display: block; color: var(--muted); font-size: var(--fs-12); }
+.company-member > .state-pill { margin-left: auto; }
+.mobile-nav { display: none; }
+.ui-dialog { position: fixed; width: min(480px,calc(100% - 32px)); max-height: calc(100dvh - 32px); overflow-y: auto; padding: var(--sp-8); border: 1px solid var(--edge); border-radius: var(--r-lg); background: var(--surface); color: var(--ink); box-shadow: var(--shadow-overlay); }
+.ui-dialog::backdrop { background: var(--overlay); backdrop-filter: blur(3px); }
+.dialog-close { position: absolute; top: var(--sp-2); right: var(--sp-2); width: 44px; height: 44px; color: var(--muted); font-size: var(--fs-26); }
+.dialog-kicker { display: inline-flex; align-items: center; gap: var(--sp-2); margin-bottom: var(--sp-4); color: var(--muted); font-size: var(--fs-12); }
+.dialog-kicker .icon { width: 17px; height: 17px; }
+.ui-dialog h2 { padding-right: var(--sp-4); font-size: var(--fs-20); font-weight: 600; }
+.dialog-description { margin-top: var(--sp-3); color: var(--muted); font-size: var(--fs-14); }
+.ui-dialog .notice { margin-top: var(--sp-5); margin-bottom: 0; }
+.form-field { display: block; margin-top: var(--sp-5); }
+.form-field > span { display: block; margin-bottom: var(--sp-2); font-size: var(--fs-13); }
+.form-field input, .form-field select { width: 100%; min-height: 48px; padding: 10px var(--sp-3); border: 1px solid var(--edge-strong); border-radius: var(--r-md); background: var(--surface); color: var(--ink); font-size: 16px; }
+.form-field small { display: block; margin-top: var(--sp-2); color: var(--muted); font-size: var(--fs-12); }
+.dialog-facts { display: grid; grid-template-columns: 1fr 1fr; gap: var(--sp-3); margin-top: var(--sp-5); padding: var(--sp-4); border-radius: var(--r-md); background: var(--surface-2); }
+.dialog-facts small { display: block; margin-bottom: var(--sp-1); color: var(--muted); font-size: var(--fs-12); }
+.dialog-facts strong { font-size: var(--fs-13); font-weight: 500; }
+.dialog-actions { display: flex; justify-content: flex-end; gap: var(--sp-3); margin-top: var(--sp-6); }
+.dialog-actions .button { min-width: 100px; }
+.dialog-feedback { margin-top: var(--sp-4); color: var(--success); font-size: var(--fs-13); }
+.demo-secret { display: block; margin-top: var(--sp-4); padding: var(--sp-3); border: 1px solid var(--edge); border-radius: var(--r-sm); background: var(--surface-2); font: var(--fs-13) ui-monospace,Consolas,monospace; overflow-wrap: anywhere; }
+.toast { position: fixed; z-index: var(--z-toast); right: var(--sp-5); bottom: var(--sp-5); left: var(--sp-5); width: fit-content; max-width: calc(100% - 40px); margin-inline: auto; padding: var(--sp-3) var(--sp-5); border: 1px solid var(--edge-strong); border-radius: var(--r-md); background: var(--surface); color: var(--ink); box-shadow: var(--shadow-pop); font-size: var(--fs-13); opacity: 0; transform: translateY(8px); transition: opacity var(--motion-fast),transform var(--motion-fast); pointer-events: none; }
+.toast.visible { opacity: 1; transform: none; }
+@media (max-width: 1100px) {
+  .app-shell { grid-template-columns: 192px minmax(0,1fr); }
+  main { padding: var(--sp-6); }
+  .plan-grid { gap: var(--sp-3); }
+  .plan-card { padding: var(--sp-5); }
+  .waiting-layout { grid-template-columns: minmax(0,1fr) 240px; gap: var(--sp-4); }
+  .enterprise-layout { grid-template-columns: 1fr; }
+}
+@media (max-width: 939px) and (min-width: 768px) {
+  .app-shell { grid-template-columns: 76px minmax(0,1fr); }
+  .sidebar { padding-inline: var(--sp-3); }
+  .brand { margin: 0 auto var(--sp-6); font-size: 0; }
+  .brand-mark { font-size: var(--fs-20); }
+  .brand-registered,.workspace-label,.sidebar-heading,.nav-button > span,.sidebar-note,.account-button > span:not(.account-avatar) { display: none; }
+  .nav-button { justify-content: center; padding: 0; }
+  .account-button { justify-content: center; padding-inline: 0; }
+  .waiting-layout { grid-template-columns: 1fr; }
+  .task-aside { display: grid; grid-template-columns: 1fr 1fr; gap: var(--sp-4); }
+  .small-panel { margin-top: 0; }
+  .review-line > p { display: none; }
+}
+@media (max-width: 767px) {
+  body { font-size: var(--fs-14); }
+  .review-line { min-height: 44px; gap: var(--sp-2); padding-inline: var(--sp-3); }
+  .review-line > p,.review-version { display: none; }
+  .review-label { font-size: var(--fs-12); }
+  .review-actions { gap: 0; }
+  .review-button { font-size: var(--fs-12); padding-inline: var(--sp-2); }
+  .review-controls { max-height: 35dvh; padding: var(--sp-3); }
+  .review-controls button { font-size: var(--fs-12); min-height: 40px; }
+  .review-events > span { width: 100%; margin-block: var(--sp-1); }
+  .app-shell { display: block; }
+  .sidebar { display: none; }
+  .workspace { height: 100%; grid-template-rows: 52px minmax(0,1fr) auto; }
+  .app-header { padding-inline: var(--sp-4); }
+  .desktop-breadcrumb,.header-safe { display: none; }
+  .app-breadcrumb { gap: var(--sp-2); }
+  .app-breadcrumb strong { padding-left: var(--sp-2); border-left: 1px solid var(--edge); font-size: var(--fs-13); }
+  .mobile-brand { display: inline; font-size: var(--fs-17); font-weight: 700; letter-spacing: -.07em; }
+  main { padding: var(--sp-4) var(--sp-4) var(--sp-6); }
+  h1 { font-size: var(--fs-20); letter-spacing: -.03em; }
+  .eyebrow { font-size: var(--fs-11); margin-bottom: var(--sp-1); }
+  .page-heading { align-items: flex-start; gap: var(--sp-2); flex-direction: column; margin-bottom: var(--sp-4); }
+  .page-heading p,.lead { font-size: var(--fs-13); line-height: 1.6; }
+  .page-heading > .button { width: 100%; }
+  .button { min-height: 44px; font-size: var(--fs-14); padding-inline: var(--sp-3); }
+  .text-action { font-size: var(--fs-13); min-height: 40px; }
+  .panel { padding: var(--sp-4); border-radius: var(--r-md); }
+  .trial-banner { grid-template-columns: minmax(0,1fr); gap: var(--sp-3); margin-bottom: var(--sp-5); padding: var(--sp-4); }
+  .trial-icon { width: 36px; height: 36px; border-radius: var(--r-md); }
+  .trial-icon .icon { width: 20px; height: 20px; }
+  .trial-banner h2 { flex-wrap: wrap; gap: var(--sp-2); font-size: var(--fs-17); }
+  .trial-banner h2 > span { font-size: var(--fs-11); }
+  .trial-banner p { font-size: var(--fs-13); }
+  .trial-facts { gap: var(--sp-2) var(--sp-3); font-size: var(--fs-12); }
+  .trial-banner > .button { width: 100%; }
+  .section-heading { align-items: flex-start; flex-direction: column; gap: var(--sp-1); }
+  .section-heading h2 { font-size: var(--fs-15); }
+  .section-heading p { font-size: var(--fs-12); }
+  .plan-grid { grid-template-columns: 1fr; gap: var(--sp-3); }
+  .plan-card { display: grid; grid-template-columns: minmax(0,1fr) 88px; align-items: center; gap: var(--sp-3); padding: var(--sp-3); border-radius: var(--r-md); text-align: left; }
+  .plan-card.featured { background: var(--primary-subtle); box-shadow: inset 0 0 0 1px var(--primary); }
+  .plan-card.current { border-color: var(--success); background: var(--success-subtle); box-shadow: none; }
+  .plan-mobile-copy { display: block; min-width: 0; }
+  .plan-mobile-heading { display: flex; align-items: center; gap: var(--sp-2); }
+  .plan-mobile-heading h3 { font-size: var(--fs-17); line-height: 1.3; }
+  .plan-mobile-recommend { padding: 2px 6px; border-radius: var(--r-sm); background: var(--primary); color: var(--primary-content); font-size: var(--fs-11); white-space: nowrap; }
+  .plan-mobile-quota { margin-top: var(--sp-2); color: var(--ink-2); font-size: var(--fs-13); line-height: 1.4; }
+  .plan-mobile-benefit { margin-top: var(--sp-1); color: var(--muted); font-size: var(--fs-12); line-height: 1.4; }
+  .plan-mobile-action { display: flex; align-items: stretch; flex-direction: column; gap: var(--sp-2); }
+  .plan-mobile-price { text-align: center; line-height: 1.25; }
+  .plan-mobile-price strong { display: block; color: var(--ink-2); font-size: var(--fs-12); font-weight: 500; white-space: nowrap; }
+  .plan-mobile-price span { display: block; color: var(--muted); font-size: var(--fs-11); white-space: nowrap; }
+  .plan-mobile-action .button { width: 100%; min-height: 44px; padding-inline: var(--sp-1); font-size: var(--fs-12); }
+  .plan-card.current .plan-mobile-action .button { border-color: var(--success); color: var(--success); background: var(--surface); }
+  .plan-icon,.plan-recommend,.plan-name-full,.plan-name-short,.plan-card > p,.plan-quota,.plan-price,.plan-billing-note,.plan-card > .button,.plan-perks { display: none; }
+  .plans-note { font-size: var(--fs-12); margin: var(--sp-3) 0 var(--sp-5); }
+  .info-grid { grid-template-columns: 1fr; gap: var(--sp-4); }
+  .info-item h3,.info-item p { font-size: var(--fs-13); }
+  .waiting-layout,.resource-grid { grid-template-columns: 1fr; }
+  .task-hero { gap: var(--sp-2); padding-bottom: var(--sp-4); }
+  .task-orb { width: 40px; height: 40px; }
+  .task-hero h2 { font-size: var(--fs-17); }
+  .task-hero p { font-size: var(--fs-12); }
+  .job-step { grid-template-columns: 24px minmax(0,1fr) auto; gap: var(--sp-2); min-height: 76px; }
+  .step-copy strong { font-size: var(--fs-14); }
+  .step-copy p { max-width: 220px; font-size: var(--fs-12); }
+  .step-state { font-size: var(--fs-11); }
+  .waiting-actions { flex-direction: column; gap: var(--sp-2); }
+  .waiting-actions .button { width: 100%; }
+  .waiting-foot { font-size: var(--fs-12); }
+  .waiting-simple { min-height: 0; padding: var(--sp-6) var(--sp-4); border-radius: var(--r-lg); }
+  .waiting-current .task-orb { width: 52px; height: 52px; margin-bottom: var(--sp-4); }
+  .waiting-current h2 { font-size: var(--fs-20); }
+  .waiting-current > p { font-size: var(--fs-13); }
+  .waiting-progress { margin-top: var(--sp-5); }
+  .waiting-meta { margin: var(--sp-4) 0; gap: var(--sp-4); }
+  .waiting-meta dt { font-size: var(--fs-11); }
+  .waiting-meta dd { font-size: var(--fs-13); }
+  .waiting-simple .waiting-actions { width: 100%; gap: var(--sp-2); }
+  .support-action { font-size: var(--fs-12); }
+  .task-aside { display: grid; grid-template-columns: 1fr; gap: var(--sp-3); }
+  .small-panel { margin: 0; padding: var(--sp-4); }
+  .task-summary h3,.small-panel h3 { font-size: var(--fs-13); }
+  .summary-facts { display: grid; grid-template-columns: 1fr 1fr; gap: var(--sp-3); }
+  .summary-facts > div { margin-top: 0; }
+  .summary-facts dt,.small-panel p { font-size: var(--fs-11); }
+  .summary-facts dd { font-size: var(--fs-13); }
+  .task-summary .text-action { font-size: var(--fs-12); }
+  .notice { flex-wrap: wrap; padding: var(--sp-3); font-size: var(--fs-13); margin-bottom: var(--sp-4); }
+  .notice > div { flex: 1; min-width: 0; }
+  .notice > .button { width: 100%; margin-left: 0; }
+  .quota-panel { align-items: stretch; flex-direction: column; gap: var(--sp-3); margin-bottom: var(--sp-4); padding: var(--sp-4); }
+  .quota-copy h2 { font-size: var(--fs-13); }
+  .quota-copy p { font-size: var(--fs-12); }
+  .quota-meter { min-width: 0; }
+  .quota-meter p { font-size: var(--fs-11); }
+  .quota-meter strong { font-size: var(--fs-17); }
+  .container-grid { grid-template-columns: minmax(0,1fr); gap: var(--sp-3); }
+  .container-card { padding: var(--sp-4); }
+  .container-avatar { width: 36px; height: 36px; font-size: var(--fs-14); }
+  .container-head h3 { font-size: var(--fs-15); }
+  .container-head small { font-size: var(--fs-11); }
+  .container-meta { gap: var(--sp-2); margin-top: var(--sp-3); font-size: var(--fs-11); }
+  .container-caption { font-size: var(--fs-12); margin-top: var(--sp-2); }
+  .container-actions { margin-top: var(--sp-3); }
+  .container-actions .button { font-size: var(--fs-13); }
+  .create-card { min-height: 120px; gap: var(--sp-2); }
+  .create-card > .icon { width: 22px; height: 22px; }
+  .create-card strong { font-size: var(--fs-14); }
+  .create-card p { font-size: var(--fs-11); }
+  .empty-state { min-height: 260px; gap: var(--sp-2); }
+  .empty-state h2 { font-size: var(--fs-17); }
+  .empty-state p { font-size: var(--fs-13); }
+  .resource-panel > p { font-size: var(--fs-13); }
+  .resource-panel h2 { font-size: var(--fs-15); }
+  .credential-list { margin-top: var(--sp-4); }
+  .credential-row { padding-block: var(--sp-3); }
+  .credential-row dt { font-size: var(--fs-11); }
+  .credential-row dd { font-size: var(--fs-12); }
+  .credential-row .button { font-size: var(--fs-12); min-height: 40px; }
+  .credential-fake { font-size: var(--fs-11); }
+  .expired-intro { margin-bottom: var(--sp-5); }
+  .expired-intro p { font-size: var(--fs-13); }
+  .preserved-resource { flex-wrap: wrap; padding: var(--sp-3) var(--sp-4); margin-bottom: var(--sp-4); }
+  .preserved-resource strong { font-size: var(--fs-14); }
+  .preserved-resource p { font-size: var(--fs-11); }
+  .enterprise-layout { grid-template-columns: 1fr; gap: var(--sp-4); }
+  .enterprise-card h2 { font-size: var(--fs-17); }
+  .enterprise-card > p,.join-step strong,.join-step p { font-size: var(--fs-13); }
+  .join-steps { gap: var(--sp-4); margin-block: var(--sp-4); }
+  .company-heading h2 { font-size: var(--fs-15); }
+  .company-member { min-height: 60px; }
+  .company-member strong { font-size: var(--fs-13); }
+  .company-member small { font-size: var(--fs-11); }
+  .copy-id { padding: var(--sp-2) var(--sp-3); }
+  .copy-id strong { font-size: var(--fs-13); }
+  .state-pill { font-size: var(--fs-10, 11px); padding: 1px 6px; }
+  .mobile-nav { display: grid; grid-template-columns: repeat(4,minmax(0,1fr)); min-height: 56px; gap: 0; padding: var(--sp-1) var(--sp-2) max(var(--sp-1),env(safe-area-inset-bottom,0px)); border-top: 1px solid var(--edge); background: var(--surface); }
+  .mobile-nav button { display: flex; min-height: 48px; align-items: center; justify-content: center; flex-direction: column; gap: 2px; color: var(--muted); font-size: var(--fs-10, 11px); }
+  .mobile-nav button.on { color: var(--ink); font-weight: 600; }
+  .mobile-nav .icon { width: 19px; height: 19px; }
+  .ui-dialog { padding: var(--sp-5) var(--sp-4); width: min(480px,calc(100% - 24px)); }
+  .ui-dialog h2 { font-size: var(--fs-17); }
+  .dialog-description { font-size: var(--fs-13); }
+  .dialog-facts { padding: var(--sp-3); gap: var(--sp-2); }
+  .dialog-facts strong { font-size: var(--fs-12); }
+  .dialog-actions { flex-direction: column-reverse; gap: var(--sp-2); }
+  .dialog-actions .button { width: 100%; }
+  .form-field > span { font-size: var(--fs-13); }
+  .form-field small { font-size: var(--fs-11); }
+  .toast { bottom: calc(68px + env(safe-area-inset-bottom,0px)); font-size: var(--fs-13); }
+}
+@media (prefers-reduced-motion: reduce) { *,*::before,*::after { scroll-behavior: auto !important; transition: none !important; animation: none !important; } }

+ 182 - 0
prototypes/fmode-subscription-20261125/verify.mjs

@@ -0,0 +1,182 @@
+// Browser review checks for the offline prototype; not a platform/API test suite.
+import assert from 'node:assert/strict';
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+import { chromium } from 'playwright';
+
+const root = path.dirname(fileURLToPath(import.meta.url));
+const output = path.resolve(root, '../../test-results/subscription-prototype');
+await fs.rm(output, { recursive: true, force: true });
+await fs.mkdir(output, { recursive: true });
+const browser = await chromium.launch({ headless: true, executablePath: chromium.executablePath() });
+const context = await browser.newContext({ reducedMotion: 'reduce', acceptDownloads: false });
+const page = await context.newPage();
+const errors = [], externalRequests = [], checks = [];
+page.on('pageerror', (error) => errors.push(error.message));
+page.on('request', (request) => { if (/^https?:/.test(request.url())) externalRequests.push(request.url()); });
+const base = pathToFileURL(path.join(root, 'index.html')).href;
+const open = async (query = '') => { await page.goto(base + query); await page.evaluate(() => document.fonts.ready); };
+const snapshot = () => page.evaluate(() => ({ plan: state.plan, access: state.access, containers: state.containers, job: state.job, started: state.trialStartedAt, expires: state.trialExpiresAt, quota: Demo.limit(state), reserved: Demo.reserved(state), application: state.application, view: state.view }));
+async function review() { if (!(await page.locator('#reviewControls').isVisible())) await page.locator('#reviewToggle').click(); }
+async function event(name) { await review(); await page.locator(`[data-event="${name}"]`).click(); }
+async function noOverflow(label) {
+  const values = await page.evaluate(() => ({ outer: document.documentElement.scrollWidth <= innerWidth, main: document.getElementById('main').scrollWidth <= document.getElementById('main').clientWidth }));
+  assert(values.outer && values.main, 'Horizontal overflow: ' + label + ' ' + JSON.stringify(values));
+}
+const capture = (name) => page.screenshot({ path: path.join(output, name + '.png'), animations: 'disabled' });
+async function createTrial() {
+  await page.locator('#main [data-action="trial"]').first().click();
+  assert.equal(await page.locator('#dialog').evaluate((element) => element.open), true);
+  await page.locator('#createForm button[type="submit"]').click();
+}
+try {
+  for (const width of [320, 360, 390, 430, 768, 1024, 1440, 1920]) {
+    await page.setViewportSize({ width, height: width < 768 ? 844 : 960 });
+    for (const scenario of ['new', 'waiting', 'failed', 'advanced', 'quota', 'expired', 'enterprise']) {
+      await open('?scenario=' + scenario);
+      await noOverflow(width + '/' + scenario);
+      if ([390,1440].includes(width)) await capture(scenario + '-' + width);
+      if (width < 768) {
+        const buttons = await page.locator('#main .button').evaluateAll((elements) => elements.map((element) => ({ height: element.getBoundingClientRect().height })));
+        assert(buttons.every((button) => button.height >= 44), 'Mobile primary actions too small');
+        const bodySize = await page.evaluate(() => parseFloat(getComputedStyle(document.body).fontSize));
+        assert(bodySize >= 14, 'Mobile body text below 14px');
+        const heading = await page.locator('#main h1').first().evaluate((element) => parseFloat(getComputedStyle(element).fontSize)).catch(() => 0);
+        assert(heading === 0 || heading <= 22, 'Mobile h1 too large for narrow viewport');
+      }
+    }
+    await open('?scenario=advanced&screen=access');
+    await noOverflow(width + '/credentials');
+    if ([390,1440].includes(width)) await capture('credentials-' + width);
+    checks.push('Layout and scenarios at ' + width + 'px');
+  }
+  await open();
+  const perkText = await page.locator('#main .plan-card').evaluateAll((cards) => cards.map((card) => card.textContent));
+  assert.equal(perkText.length, 3, 'Three plan cards expected');
+  assert(perkText.every((text) => text.includes('2 核 4G')), 'Every plan card states the 2-core 4G spec (AC-21.1)');
+  checks.push('All three plan cards state the 2-core 4G baseline spec');
+  await page.setViewportSize({ width: 390, height: 844 });
+  await open();
+  await createTrial();
+  const claimed = await snapshot();
+  assert.equal(claimed.access, 'provisioning'); assert.equal(claimed.reserved, 1); assert.equal(claimed.started, null);
+  await page.locator('#main [data-action="check"]').click();
+  assert.equal((await snapshot()).job.stage, 0, 'Check progress cannot fake a server completion');
+  await event('advance'); await event('advance');
+  const beforeFailure = await snapshot();
+  await event('fail');
+  await page.locator('#main [data-action="retry"]').click();
+  const retried = await snapshot();
+  assert.equal(retried.job.id, claimed.job.id); assert.equal(retried.reserved, 1); assert.equal(retried.job.stage, beforeFailure.job.stage); assert.equal(retried.job.attempt, 2);
+  await event('offline');
+  assert.equal(await page.locator('#main [data-action="check"]').isDisabled(), true);
+  assert.equal((await snapshot()).job.id, claimed.job.id);
+  await event('offline');
+  await event('slow');
+  assert.equal((await snapshot()).job.status, 'provisioning');
+  while ((await snapshot()).job.status !== 'ready') await event('advance');
+  const ready = await snapshot();
+  assert.equal(ready.containers.length, 1); assert.equal(ready.access, 'active'); assert.equal(ready.reserved, 0);
+  assert.equal(ready.expires - ready.started, 48 * 3600000);
+  await page.locator('#reviewToggle').click();
+  await capture('ready-390');
+  await event('expire');
+  const expired = await snapshot();
+  assert.equal(expired.access, 'expired'); assert.equal(expired.containers[0].id, ready.containers[0].id);
+  await page.locator('#main [data-action="apply"][data-plan="starter"]').click();
+  await page.locator('#applyForm button[type="submit"]').click();
+  assert.equal((await snapshot()).access, 'expired', 'Intent is not payment confirmation');
+  await event('approve');
+  const restored = await snapshot();
+  assert.equal(restored.access, 'active'); assert.equal(restored.plan, 'starter'); assert.equal(restored.containers.length, 1); assert.equal(restored.containers[0].id, ready.containers[0].id);
+  assert.equal(restored.started, ready.started); assert.equal(restored.expires, ready.expires, 'Paid restoration cannot reset the old trial');
+  checks.push('Trial claim → real-event simulation → same-job retry/offline/delay → ready 48h → expiry → same-container paid restoration');
+
+  await open('?scenario=quota');
+  assert.equal(await page.locator('#main [data-action="create"]').isDisabled(), true);
+  await page.locator('#main [data-action="addon"]').click();
+  await page.locator('#addonForm button[type="submit"]').click();
+  assert.equal((await snapshot()).quota, 3);
+  await event('approve');
+  assert.equal((await snapshot()).quota, 4);
+  await page.locator('#main .page-heading [data-action="create"]').click();
+  await page.locator('#createForm button[type="submit"]').click();
+  assert.equal((await snapshot()).access, 'active', 'Existing containers remain usable during a new job');
+  assert.equal((await snapshot()).containers.length, 3);
+  checks.push('Quota 3, manual addon confirmation to 4, existing 3 containers remain usable while creating a new one');
+
+  await open('?scenario=advanced&screen=access');
+  assert.equal(await page.locator('.masked-value').count(), 9);
+  await page.locator('#main [data-action="credential"]').first().click();
+  assert.equal(await page.locator('#credentialResult').isVisible(), false);
+  await page.locator('[data-confirm-credential]').click();
+  assert.match(await page.locator('.demo-secret').textContent(), /demo-agent/);
+  await page.keyboard.press('Escape');
+  assert.equal(await page.locator('#dialog').evaluate((element) => element.open), false);
+  checks.push('Nine masked demo fields including userMxId/homeserver; explicit second confirmation; modal Escape');
+
+  await open('?scenario=advanced');
+  await page.locator('#main [data-action="settings"]').first().click();
+  await page.locator('#renameInput').fill('新名字 <script>');
+  await page.locator('#renameForm button[type="submit"]').click();
+  assert.equal(await page.locator('.container-head h3').first().textContent(), '新名字 <script>');
+  assert.equal(await page.locator('#main script').count(), 0);
+  checks.push('Container rename is escaped and stays in memory');
+
+  await open('?screen=enterprise');
+  await event('join');
+  assert.equal((await snapshot()).quota, 5); assert.equal((await snapshot()).plan, 'enterprise');
+  checks.push('Enterprise invitation confirmation grants a shared quota of 5 in the demo');
+
+  await open('?scenario=advanced');
+  const personalBeforeJoin = await snapshot();
+  await page.locator('#desktopNav [data-view="enterprise"]').evaluate((element) => element.click());
+  await event('join');
+  const companyBefore = await snapshot();
+  assert.equal(companyBefore.quota, 5);
+  await page.locator('[data-subject="personal"]').click();
+  const personalAfterJoin = await snapshot();
+  assert.equal(personalAfterJoin.plan, 'advanced');
+  assert.deepEqual(personalAfterJoin.containers, personalBeforeJoin.containers);
+  await page.locator('[data-subject="company"]').click();
+  assert.deepEqual((await snapshot()).containers, companyBefore.containers);
+  checks.push('Joining/switching enterprise preserves independent personal plan, containers and shared company quota');
+
+  await open('?scenario=enterprise&screen=plans');
+  await page.locator('#main [data-action="apply"][data-plan="starter"]').click();
+  await page.locator('#applyForm button[type="submit"]').click();
+  await event('approve');
+  assert.equal((await snapshot()).plan, 'starter');
+  assert.equal((await snapshot()).containers.length, 0);
+  await page.locator('[data-subject="company"]').click();
+  assert.equal((await snapshot()).quota, 5);
+  assert.equal((await snapshot()).containers.length, 2);
+  checks.push('Buying a personal plan from a company context does not transfer or downgrade enterprise assets');
+
+  await open('?scenario=waiting');
+  assert.equal(await page.locator('[role="progressbar"]').getAttribute('aria-valuenow'), '50');
+  assert.equal((await snapshot()).job.completed, 3);
+  assert.equal(await page.locator('#main .job-step').count(), 0);
+  assert.equal(await page.locator('#main').getByText('正在开通', { exact:true }).count(), 1);
+  checks.push('Simple current status and true 50% progress; internal stage list remains out of product UI');
+
+  for (const [width,height] of [[320,568],[390,600],[760,420]]) {
+    await page.setViewportSize({ width,height }); await open();
+    await page.locator('#main [data-action="trial"]').click();
+    const box = await page.locator('#dialog').boundingBox();
+    assert(box.y >= 0 && box.y + box.height <= height);
+    await page.keyboard.press('Tab');
+    assert.equal(await page.evaluate(() => document.getElementById('dialog').contains(document.activeElement)), true);
+    await page.keyboard.press('Escape');
+  }
+  checks.push('Short-screen modal fit, scroll, keyboard focus containment');
+  await page.setViewportSize({ width:390,height:844 }); await open('?theme=dark&scenario=waiting'); await noOverflow('dark waiting'); await capture('waiting-dark-390');
+  await page.setViewportSize({ width:1440,height:960 }); await open('?theme=dark'); await noOverflow('dark plans'); await capture('plans-dark-1440');
+  checks.push('Light and dark theme');
+  assert.deepEqual(externalRequests, [], 'Prototype must not call any real platform or resource');
+  assert.deepEqual(errors, []);
+  const report = { success:true, scope:'offline prototype review only; no real API/container/timing verification', checks, browserErrors:errors, externalRequests };
+  await fs.writeFile(path.join(output,'results.json'),JSON.stringify(report,null,2));
+  console.log(JSON.stringify(report,null,2));
+} finally { await browser.close(); }

+ 262 - 0
scripts/create-test-account.mjs

@@ -0,0 +1,262 @@
+#!/usr/bin/env node
+/**
+ * 创建模拟测试账号(阶段一:替代手机短信登录)
+ *
+ * 背景(2026-11-24 用户裁决):容器全链路自动化测试不绑企业、不做短信登录,
+ * 直接用 masterKey 在平台建一个「个人无企业」的模拟账号,确认创建完整后,
+ * 交给 scripts/onboard-user.mjs 走完整接口流程开通容器。
+ *
+ * 用法:
+ *   node scripts/create-test-account.mjs              # 幂等:已建过就直接复用并自检
+ *   node scripts/create-test-account.mjs --new        # 强制再建一个(手机号后缀 +1)
+ *
+ * 做的事:
+ *   1. masterKey 直建 _User:username=fmode<手机号>(对齐短信注册格式)、
+ *      随机强口令、mobile/nickname/type/status;⚠️ 不写 company(默认无企业)
+ *   2. /parse/login 登录拿 sessionToken(= 测试账号的 FMODE_PARSE_SESSION_TOKEN)
+ *   3. 自检「创建完整」:users/me 字段、_Session 存在、company 为空断言、
+ *      Profile 记录数(无企业用户预期 0 条——Profile 是企业成员档案,逐企业一条)
+ *   4. 写入 .claude/dev-login.json 的 testAccount 槽位(不覆盖正式 token)
+ *
+ * 凭据:masterKey 集中存放在 `.claude/dev-login.json` 的 `masterKey` 字段
+ * (2026-11-25 自本文件迁入;用户 2026-11-06 裁决允许明文,集中存放)。
+ * 注意:masterKey 偶发 "unauthorized"(平台侧抖动),脚本自动重试 3 次。
+ */
+import { readFileSync, writeFileSync } from 'node:fs';
+import { randomBytes } from 'node:crypto';
+import { join } from 'node:path';
+
+const PARSE_URL = 'https://server.fmode.cn/parse';
+const APP_ID = 'ncloudmaster';
+
+// 测试号段:19900000001 起,--new 时递增
+const MOBILE_BASE = 19900000001;
+
+const DEV_LOGIN = join(process.cwd(), '.claude', 'dev-login.json');
+
+function fail(msg, code = 1) {
+  console.error(`❌ ${msg}`);
+  process.exit(code);
+}
+
+const devLogin = JSON.parse(readFileSync(DEV_LOGIN, 'utf8'));
+const MASTER_KEY = devLogin.masterKey;
+if (!MASTER_KEY) fail('.claude/dev-login.json 缺少 masterKey 字段(2026-11-25 起集中存放于此)');
+
+const ok = (s) => `✅ ${s}`;
+const bad = (s) => `❌ ${s}`;
+
+// ---------- Parse 调用 ----------
+
+async function parseReq(method, path, body, { master = false, token = null, retries = 8 } = {}) {
+  const headers = {
+    'X-Parse-Application-Id': APP_ID,
+    'Content-Type': 'application/json',
+  };
+  if (master) headers['X-Parse-Master-Key'] = MASTER_KEY;
+  if (token) headers['X-Parse-Session-Token'] = token;
+
+  let lastErr = '';
+  for (let attempt = 1; attempt <= retries; attempt++) {
+    let res;
+    try {
+      res = await fetch(`${PARSE_URL}${path}`, {
+        method,
+        headers,
+        body: body ? JSON.stringify(body) : undefined,
+        // 🔴 必须 manual(2026-11-24 实测):入口层有一个坏后端会把 /parse/users
+        //    301 到 https://server.fmode.cn:7460/...(已下线,连接被拒)。
+        //    fetch 默认跟随重定向就会 ECONNREFUSED;manual 把 301 当抖动重试即可。
+        redirect: 'manual',
+      });
+    } catch (e) {
+      lastErr = e.cause?.code ?? e.message;
+      console.warn(`⚠️  网络抖动(${lastErr}),第 ${attempt}/${retries} 次,1.5s 后重试…`);
+      await new Promise((r) => setTimeout(r, 1500));
+      continue;
+    }
+    // 入口层 HAProxy 后端池质量不一(2026-11-24 实测约半数健康):
+    // 健康=200;坏后端 A=403;坏后端 B=301→:7460;另有偶发 unauthorized。一律重试。
+    if (res.status === 301 || res.status === 403) {
+      lastErr = `HTTP ${res.status}`;
+      console.warn(`⚠️  入口层坏后端(HTTP ${res.status}),第 ${attempt}/${retries} 次,1.5s 后重试…`);
+      await new Promise((r) => setTimeout(r, 1500));
+      continue;
+    }
+    const text = await res.text();
+    let data;
+    try {
+      data = JSON.parse(text);
+    } catch {
+      data = { error: text.slice(0, 200) };
+    }
+    if (data.error === 'unauthorized' && attempt < retries) {
+      lastErr = 'unauthorized';
+      console.warn(`⚠️  入口层抖动(unauthorized),第 ${attempt}/${retries} 次,1.5s 后重试…`);
+      await new Promise((r) => setTimeout(r, 1500));
+      continue;
+    }
+    return { ...data, _status: res.status };
+  }
+  return { error: `重试 ${retries} 次仍失败(入口层持续抖动):${lastErr}` };
+}
+
+// ---------- dev-login.json ----------
+
+function readDevLogin() {
+  try {
+    return JSON.parse(readFileSync(DEV_LOGIN, 'utf8'));
+  } catch {
+    return {};
+  }
+}
+
+function saveTestAccount(slot) {
+  const cur = readDevLogin();
+  cur.testAccount = { ...cur.testAccount, ...slot, updatedAt: new Date().toISOString() };
+  writeFileSync(DEV_LOGIN, JSON.stringify(cur, null, 2) + '\n', 'utf8');
+  console.log(ok(`已写入 ${DEV_LOGIN} 的 testAccount 槽位(正式 token 未动)`));
+}
+
+// ---------- 主流程 ----------
+
+const forceNew = process.argv.includes('--new');
+
+/** 选一个可用的手机号:复用已有槽位,或从号段里挑一个 username 未被占用的 */
+async function pickAccount() {
+  const saved = readDevLogin().testAccount;
+  if (saved?.username && saved?.password && !forceNew) {
+    console.log(`发现已建测试账号 ${saved.username},直接复用(--new 可强制新建)`);
+    return saved;
+  }
+  for (let i = 0; i < 20; i++) {
+    const mobile = String(MOBILE_BASE + i);
+    const username = `fmode${mobile}`;
+    const q = await parseReq(
+      'GET',
+      `/users?where=${encodeURIComponent(JSON.stringify({ username }))}&limit=1`,
+      null,
+      { master: true },
+    );
+    if (q.error) fail(`查重失败:${q.error}`);
+    if ((q.results ?? []).length === 0) {
+      return { username, mobile, password: `T${randomBytes(12).toString('base64url')}!` };
+    }
+  }
+  fail('测试号段 19900000001~19900000020 全被占用,请扩大号段');
+}
+
+async function main() {
+  console.log('\n=== 创建模拟测试账号(个人无企业)===\n');
+
+  const acc = await pickAccount();
+
+  // ① 建号(幂等:先尝试登录,登不上才建)
+  let login = await parseReq('POST', '/login', {
+    username: acc.username,
+    password: acc.password,
+  });
+
+  if (login.error) {
+    console.log(`账号 ${acc.username} 尚不存在(或口令不符),开始创建……`);
+    const created = await parseReq(
+      'POST',
+      '/users',
+      {
+        username: acc.username,
+        password: acc.password,
+        mobile: acc.mobile,
+        nickname: `用户${acc.mobile.slice(-4)}`,
+        type: 'user',
+        status: 'normal',
+        // ⚠️ 故意不写 company —— 个人无企业(2026-11-24 用户裁决:不自动入企)
+        ACL: { '*': { read: true } },
+      },
+      { master: true },
+    );
+    if (created.error || !created.objectId) {
+      fail(`创建失败:${JSON.stringify(created).slice(0, 300)}`);
+    }
+    console.log(ok(`创建成功  objectId=${created.objectId}`));
+
+    // 建完立刻登录拿 sessionToken
+    login = await parseReq('POST', '/login', {
+      username: acc.username,
+      password: acc.password,
+    });
+    if (login.error || !login.sessionToken) {
+      fail(`建后登录失败:${JSON.stringify(login).slice(0, 300)}`);
+    }
+  } else {
+    console.log(ok(`复用已有账号  objectId=${login.objectId}`));
+  }
+
+  const token = login.sessionToken;
+  console.log(ok(`登录成功,拿到 sessionToken(r:…${token.slice(-6)},全文不落日志)`));
+
+  // ② 自检「创建完整」
+  console.log('\n--- 完整性自检 ---');
+  const rows = [];
+
+  const meR = await parseReq('GET', '/users/me', null, { token });
+  if (meR.error) fail(`users/me 失败:${meR.error}`);
+  const fieldsOk = !!(meR.objectId && meR.username === acc.username && meR.mobile === acc.mobile);
+  console.log(
+    (fieldsOk ? ok : bad)(
+      `users/me 字段  objectId=${meR.objectId} username=${meR.username} mobile=${meR.mobile}`,
+    ),
+  );
+  rows.push(['users/me 字段', fieldsOk]);
+
+  const noCompany = !meR.company;
+  console.log(
+    (noCompany ? ok : bad)(`无企业断言  company=${noCompany ? '空(符合预期)' : JSON.stringify(meR.company)}`),
+  );
+  rows.push(['无企业(company 为空)', noCompany]);
+
+  const sess = await parseReq(
+    'GET',
+    `/sessions?where=${encodeURIComponent(JSON.stringify({ user: { __type: 'Pointer', className: '_User', objectId: meR.objectId } }))}&limit=5`,
+    null,
+    { master: true },
+  );
+  const sessOk = (sess.results ?? []).length > 0;
+  console.log((sessOk ? ok : bad)(`_Session 存在  ${(sess.results ?? []).length} 条`));
+  rows.push(['_Session 存在', sessOk]);
+
+  const prof = await parseReq(
+    'GET',
+    `/classes/Profile?where=${encodeURIComponent(JSON.stringify({ user: { __type: 'Pointer', className: '_User', objectId: meR.objectId } }))}&limit=5`,
+    null,
+    { token },
+  );
+  const profN = (prof.results ?? []).length;
+  // Profile 是「企业成员档案」,逐企业一条;无企业用户预期 0 条
+  console.log(ok(`Profile 记录  ${profN} 条(无企业用户预期 0 条${profN === 0 ? ',符合' : ',⚠️ 请人工核对'})`));
+  rows.push(['Profile 口径符合', profN === 0]);
+
+  const failed = rows.filter(([, v]) => !v);
+  console.log('\n--- 结论 ---');
+  for (const [name, v] of rows) console.log(`  ${v ? '✅' : '❌'} ${name}`);
+  if (failed.length) fail(`${failed.length} 项未通过,账号不算「创建完整」,请先处理`);
+
+  // ③ 落盘
+  saveTestAccount({
+    objectId: meR.objectId,
+    username: acc.username,
+    mobile: acc.mobile,
+    nickname: meR.nickname,
+    password: acc.password,
+    sessionToken: token,
+    company: null,
+  });
+
+  console.log('\n=== 测试账号创建完整 ===');
+  console.log(`  objectId = ${meR.objectId}`);
+  console.log(`  username = ${acc.username}`);
+  console.log(`  mobile   = ${acc.mobile}`);
+  console.log(`  企业     = 无(个人)`);
+  console.log('\n下一步:node scripts/onboard-user.mjs --account testAccount --dry-run');
+}
+
+await main();

+ 18 - 0
scripts/deploy-cloud-fn.mjs

@@ -101,6 +101,24 @@ const TARGETS = [
     version: '0.1.0',
     create: true,
   },
+  {
+    /* 2026-11-25:新建。容器开通(start/status/retry/list)
+     *
+     * 🔴 这是「App 点一下 → 平台建容器」的服务端实现:
+     *    建 FmodeAgent 记录 → Matrix 身份 → **新建任务房间** → 发技能工单 → 服务端核验。
+     *    ready 只由服务端事实推导,不信任主容器的自然语言回报。
+     *
+     * v0.3.0(2026-11-26):主容器「技能工单 + 一任务一房间」
+     *    · 指令从 200 行长文改为 JSON 工单,步骤移到 `container-provision-job` 技能
+     *    · 每个任务新建 Matrix 房间(新 roomId = 新 Hermes session = 干净上下文)
+     *    · 从任务房间回读 ===PROVISION-RESULT=== 作为诊断(不参与 ready 判定)
+     */
+    file: 'cloud/functions/fmode-provisioning.js',
+    id: 'VtW1GT93Ax',
+    name: 'fmode-provisioning',
+    version: '0.8.0',
+    create: true,
+  },
 ];
 
 function authHeaders() {

+ 12 - 0
scripts/deploy.mjs

@@ -164,6 +164,18 @@ console.log('\n=== [3/5] 同步到 OBS ===');
  */
 run('obsutil', ['sync', distDir, BUCKET, `-e=${OBS_EP}`]);
 run('obsutil', ['chattri', BUCKET, '-r', '-f', `-e=${OBS_EP}`, '-acl=public-read']);
+/*
+ * 🔴 index.html 必须显式禁缓存(2026-11-24 踩坑):
+ * sync 不带 Cache-Control,浏览器可能启发式缓存旧 index.html →
+ * 引用已被覆盖删除的旧 hash chunk(404)→ 用户一直跑旧版应用。
+ * sync 不支持 -meta,需单独 cp 覆盖写元数据。
+ * ⚠️ cp 会把对象 ACL 重置为**私有**(实测整站 403),必须紧跟着补 public-read。
+ */
+run('obsutil', [
+  'cp', join(distDir, 'index.html'), `${BUCKET}/index.html`,
+  '-meta=Cache-Control:no-cache', `-e=${OBS_EP}`,
+]);
+run('obsutil', ['chattri', `${BUCKET}/index.html`, '-acl=public-read', `-e=${OBS_EP}`]);
 
 // ── 4. 刷新 CDN ────────────────────────────────────────────────────────────
 console.log('\n=== [4/5] 刷新 CDN ===');

+ 135 - 0
scripts/master-channel.cjs

@@ -0,0 +1,135 @@
+/**
+ * 主容器通信通道(2026-11-26)
+ *
+ * ## 为什么是这个方案(用户裁决)
+ *
+ * R730 的 SSH 通道(server.fmode.cn:18001)被服务器侧拒绝
+ * (banner 直接返回 `Not allowed at this time`),不能作为执行手段。
+ *
+ * 改用**纯 Matrix 通道**:
+ *   测试用户 → 建房间 → 邀请主容器 → 主容器自己执行命令
+ *
+ * 🔴 **不能直接以主容器身份建房间**:
+ *    主容器是 Hermes bot,它只响应「别人发给它的消息」,不响应自己发的。
+ *    自建房间里它是 creator 但 Hermes 不触发;而且 creator 改 power_levels
+ *    会返回 `Event is not authorized`(该 homeserver 的坑)。
+ *    因此必须**用真实用户身份建房间并邀请它**——它 join 后才会响应。
+ *
+ * ## 用法
+ *
+ * ```js
+ * const master = require('./scripts/master-channel.cjs');
+ * await master.ask('执行 uname -n,只回结果');
+ * ```
+ *
+ * 返回主容器的所有回复文本(已按时间正序)。
+ */
+const fs = require('fs');
+const path = require('path');
+
+const MX = 'https://matrix.fmode.cn';
+const MASTER_MXID = '@bnqaoxqhe8:fmode.cn';
+const USER_MXID = '@cq0ih6limu:fmode.cn';
+/** 测试用户的 Parse sessionToken(.claude/dev-login.json 的 testAccount) */
+const SESSION_TOKEN = 'r:e1f8f9224c520a2841fd656fd9909cf7';
+/** 测试用户的 Matrix accessToken(由 RP5Ht55NeX 签发,长期有效) */
+const USER_ACCESS_TOKEN = 'pxdhbhg80TNAk8EkfnDZyx3k';
+/** 创建容器开通用(对应 FmodeAgent agent-node-app-test-1125) */
+const USER_AGENT_ID = 'agent-node-app-test-1125';
+
+const H = () => ({ Authorization: 'Bearer ' + USER_ACCESS_TOKEN, 'Content-Type': 'application/json' });
+
+async function mx(pathname, init) {
+  const res = await fetch(MX + pathname, { ...init, headers: { ...H(), ...(init && init.headers) } });
+  const text = await res.text();
+  let data = null;
+  try {
+    data = JSON.parse(text);
+  } catch {
+    data = { raw: text };
+  }
+  return { ok: res.ok, status: res.status, data };
+}
+
+/** 建一个干净房间,邀请主容器,等它进房。新房间 = 新 Hermes session */
+async function openRoom(name) {
+  const cr = await mx('/_matrix/client/v3/createRoom', {
+    method: 'POST',
+    body: JSON.stringify({
+      name: name || 'fmode-' + Date.now(),
+      preset: 'private_chat',
+      invite: [MASTER_MXID],
+      is_direct: true,
+    }),
+  });
+  if (!cr.data.room_id) throw new Error('建房失败:' + JSON.stringify(cr.data).slice(0, 200));
+  const roomId = cr.data.room_id;
+
+  for (let i = 0; i < 12; i++) {
+    await new Promise((r) => setTimeout(r, 2500));
+    const mem = await mx('/_matrix/client/v3/rooms/' + encodeURIComponent(roomId) + '/joined_members');
+    if (mem.ok && mem.data.joined && mem.data.joined[MASTER_MXID]) return roomId;
+  }
+  throw new Error('主容器未进房(邀请后 30 秒内未 join)');
+}
+
+async function send(roomId, body) {
+  const r = await mx(
+    '/_matrix/client/v3/rooms/' + encodeURIComponent(roomId) + '/send/m.room.message/t' + Date.now() + Math.floor(Math.random() * 999),
+    {
+      method: 'PUT',
+      body: JSON.stringify({ msgtype: 'm.text', body, 'm.mentions': { user_ids: [MASTER_MXID] } }),
+    },
+  );
+  if (!r.ok) throw new Error('发送失败 HTTP ' + r.status);
+}
+
+/** 等主容器的回复(只取发送时间晚于 since 的消息) */
+async function waitReply(roomId, sinceIso, { maxSec = 240, idleSec = 45 } = {}) {
+  const started = Date.now();
+  let lastCount = 0;
+  let lastChange = Date.now();
+  let collected = [];
+
+  while ((Date.now() - started) / 1000 < maxSec) {
+    await new Promise((r) => setTimeout(r, 5000));
+    const m = await mx('/_matrix/client/v3/rooms/' + encodeURIComponent(roomId) + '/messages?dir=b&limit=20');
+    const got = ((m.data && m.data.chunk) || [])
+      .filter((e) => e.sender === MASTER_MXID && e.type === 'm.room.message')
+      .filter((e) => new Date(e.origin_server_ts).toISOString() > sinceIso)
+      .reverse()
+      .map((e) => e.content.body || '');
+
+    if (got.length !== lastCount) {
+      lastCount = got.length;
+      lastChange = Date.now();
+      collected = got;
+    } else if (collected.length && (Date.now() - lastChange) / 1000 > idleSec) {
+      return collected;
+    }
+  }
+  return collected;
+}
+
+/** 一问一答:新房间 → 发指令 → 收集回复 */
+async function ask(prompt, opts) {
+  const roomId = await openRoom((opts && opts.name) || 'fmode-task');
+  const since = new Date().toISOString();
+  await send(roomId, prompt);
+  const replies = await waitReply(roomId, since, opts);
+  return { roomId, replies };
+}
+
+module.exports = {
+  MX,
+  MASTER_MXID,
+  USER_MXID,
+  SESSION_TOKEN,
+  USER_ACCESS_TOKEN,
+  USER_AGENT_ID,
+  mx,
+  openRoom,
+  send,
+  waitReply,
+  ask,
+};

+ 717 - 0
scripts/onboard-user.mjs

@@ -0,0 +1,717 @@
+#!/usr/bin/env node
+/**
+ * 个人无企业用户 → 容器开通全链路自动化(阶段二,2026-11-24)
+ *
+ * 把「创建一个容器」的平台侧全链路串成一条命令:
+ *   ① 登录态校验(users/me,token 失效自动用口令重新登录)
+ *   ② [--with-cloud] 独立云资源:subscription/status → trial-standalone → 轮询
+ *      → { appId, serverURL, functionsURL, masterKey }(个人名下,不要求企业)
+ *   ③ FmodeAgent 记录(xlosi3m46q 查询,缺失则直建;⚠️ 无 company —— 个人无企业)
+ *   ④ Matrix 身份:RP5Ht55NeX provision → agentMxId/roomId/binding(幂等,已有绑定跳过)
+ *   ⑤ 生成「发给主容器 agent-node」的建容器指令(个人参数自动回填)
+ *   ⑥ [--send] 用本账号 Matrix 身份 DM @bnqaoxqhe8:fmode.cn 发出指令,
+ *      等 ✅/CREATE-DONE/静默,回报落盘
+ *   ⑦ 验收轮询:FmodeAgent channels 上报 + 房间成员回读
+ *
+ * 用法:
+ *   node scripts/onboard-user.mjs                    # ①③④⑤⑦(幂等,安全重复跑)
+ *   node scripts/onboard-user.mjs --dry-run          # 只打印会做什么,零写入
+ *   node scripts/onboard-user.mjs --with-cloud       # 附加第 ② 步
+ *   node scripts/onboard-user.mjs --send             # 附加第 ⑥ 步(真正建容器)
+ *   node scripts/onboard-user.mjs --name 小测 --agent-id agent-node-app-test-0001
+ *
+ * 账号来源:.claude/dev-login.json 的 testAccount 槽位(由 create-test-account.mjs 写入)。
+ *
+ * 入口层抖动说明(2026-11-24 实测):server.fmode.cn 的 HAProxy 后端池质量不一,
+ * 健康=200,坏后端分别返回 403 / 301→:7460(已下线)/ unauthorized。
+ * 本脚本所有请求统一 redirect:'manual' + 重试(详见 create-test-account.mjs 同款注释)。
+ */
+import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+
+const PARSE_URL = 'https://server.fmode.cn/parse';
+const API_BASE = 'https://server.fmode.cn';
+const FUNCTIONS_URL = `${API_BASE}/api/functions`;
+const MATRIX_HS = 'https://matrix.fmode.cn';
+const APP_ID = 'ncloudmaster';
+const FN_STATUS = 'xlosi3m46q';
+const FN_PROVISION = 'RP5Ht55NeX';
+/** 主容器(agent-node)的 Matrix 身份 —— 2026-11-24 实测 DM 可达、准入全开 */
+const MASTER_NODE_MXID = '@bnqaoxqhe8:fmode.cn';
+
+const DEV_LOGIN = join(process.cwd(), '.claude', 'dev-login.json');
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+const ok = (s) => `✅ ${s}`;
+const bad = (s) => `❌ ${s}`;
+const warn = (s) => `⚠️  ${s}`;
+
+function fail(msg, code = 1) {
+  console.error(`❌ ${msg}`);
+  process.exit(code);
+}
+
+// ---------- 参数 ----------
+
+function arg(name, fallback) {
+  const i = process.argv.indexOf(`--${name}`);
+  return i >= 0 && process.argv[i + 1] ? process.argv[i + 1] : fallback;
+}
+const DRY_RUN = process.argv.includes('--dry-run');
+const WITH_CLOUD = process.argv.includes('--with-cloud');
+const SEND = process.argv.includes('--send');
+const NAME = arg('name', null);
+const AGENT_ID_ARG = arg('agent-id', null);
+const SEND_MAX_MS = Number(arg('max', '1800000')); // --send 等主容器回报的总超时(默认 30 分钟)
+const SILENCE_MS = Number(arg('silence', '300000')); // 静默 5 分钟判定结束
+
+// ---------- 账号 ----------
+
+function loadAccount() {
+  let j;
+  try {
+    j = JSON.parse(readFileSync(DEV_LOGIN, 'utf8'));
+  } catch {
+    fail(`读不到 ${DEV_LOGIN}`);
+  }
+  const a = j.testAccount;
+  if (!a?.username || !a?.password) {
+    fail('dev-login.json 没有 testAccount 槽位,先跑:node scripts/create-test-account.mjs');
+  }
+  return a;
+}
+
+const ACCOUNT = loadAccount();
+
+// ---------- 平台调用(入口层抖动统一重试) ----------
+
+async function httpJson(url, { method = 'GET', headers = {}, body = null, retries = 8 } = {}) {
+  let lastErr = '';
+  for (let attempt = 1; attempt <= retries; attempt++) {
+    let res;
+    try {
+      res = await fetch(url, {
+        method,
+        headers: { 'Content-Type': 'application/json', ...headers },
+        body: body ? JSON.stringify(body) : undefined,
+        // 🔴 必须 manual:坏后端会把 /parse/** 301 到 :7460(已下线),跟随重定向必死
+        redirect: 'manual',
+      });
+    } catch (e) {
+      lastErr = e.cause?.code ?? e.message;
+      console.warn(`⚠️  网络抖动(${lastErr}),第 ${attempt}/${retries} 次,1.5s 后重试…`);
+      await sleep(1500);
+      continue;
+    }
+    if (res.status === 301 || res.status === 403) {
+      lastErr = `HTTP ${res.status}`;
+      console.warn(`⚠️  入口层坏后端(HTTP ${res.status}),第 ${attempt}/${retries} 次,1.5s 后重试…`);
+      await sleep(1500);
+      continue;
+    }
+    const text = await res.text();
+    let data;
+    try {
+      data = JSON.parse(text);
+    } catch {
+      data = { error: text.slice(0, 200) };
+    }
+    if (data.error === 'unauthorized' && attempt < retries) {
+      lastErr = 'unauthorized';
+      console.warn(`⚠️  入口层抖动(unauthorized),第 ${attempt}/${retries} 次,1.5s 后重试…`);
+      await sleep(1500);
+      continue;
+    }
+    return { ...data, _status: res.status };
+  }
+  return { error: `重试 ${retries} 次仍失败(入口层持续抖动):${lastErr}` };
+}
+
+let TOKEN = ACCOUNT.sessionToken;
+
+const parseHeaders = () => ({
+  'X-Parse-Application-Id': APP_ID,
+  'X-Parse-Session-Token': TOKEN,
+});
+
+const parseReq = (method, path, body) =>
+  httpJson(`${PARSE_URL}${path}`, { method, headers: parseHeaders(), body });
+
+const callFn = (id, params) =>
+  httpJson(FUNCTIONS_URL, { method: 'POST', body: { id, token: TOKEN, params } });
+
+/** 登录态校验;失效则用口令重新登录并回写槽位 */
+async function ensureLogin() {
+  const me = await parseReq('GET', '/users/me');
+  if (!me.error) return me;
+  console.warn(warn(`sessionToken 失效(${me.error}),用口令重新登录…`));
+  const login = await httpJson(`${PARSE_URL}/login`, {
+    method: 'POST',
+    headers: { 'X-Parse-Application-Id': APP_ID },
+    body: { username: ACCOUNT.username, password: ACCOUNT.password },
+  });
+  if (login.error || !login.sessionToken) fail(`重新登录失败:${JSON.stringify(login).slice(0, 200)}`);
+  TOKEN = login.sessionToken;
+  const cur = JSON.parse(readFileSync(DEV_LOGIN, 'utf8'));
+  cur.testAccount = { ...cur.testAccount, sessionToken: TOKEN, updatedAt: new Date().toISOString() };
+  writeFileSync(DEV_LOGIN, JSON.stringify(cur, null, 2) + '\n', 'utf8');
+  console.log(ok('已换新 sessionToken 并回写 dev-login.json'));
+  const me2 = await parseReq('GET', '/users/me');
+  if (me2.error) fail(`换新 token 后 users/me 仍失败:${me2.error}`);
+  return me2;
+}
+
+// ---------- ② 独立云资源(可选) ----------
+
+async function ensureCloud(user) {
+  console.log('\n--- ② 独立云资源(--with-cloud)---');
+  const status = await httpJson(`${API_BASE}/api/fmode/enterprise/subscription/status`, {
+    method: 'POST',
+    headers: parseHeaders(),
+    body: {},
+  });
+  const pick = (d) => d?.backend ?? d?.subscription?.backend ?? null;
+  if (status.code === 200 && pick(status.data)) {
+    console.log(ok('云资源已开通,直接复用'));
+    return pick(status.data);
+  }
+  if (DRY_RUN) {
+    console.log('(dry-run)将调用 trial-standalone 开通独立云资源');
+    return null;
+  }
+  console.log('未开通,调用 trial-standalone……');
+  const trial = await httpJson(`${API_BASE}/api/fmode/enterprise/subscription/trial-standalone`, {
+    method: 'POST',
+    headers: parseHeaders(),
+    body: { name: user.nickname ?? user.username, mobile: user.mobile },
+  });
+  if (trial.code !== 200) fail(`trial-standalone 失败:${trial.mess ?? JSON.stringify(trial).slice(0, 200)}`);
+
+  // 轮询(对齐 apig-pay:4s × 最多 45 次;backend 出现=成功,failed=失败)
+  for (let i = 1; i <= 60; i++) {
+    await sleep(4000);
+    const st = await httpJson(`${API_BASE}/api/fmode/enterprise/subscription/status`, {
+      method: 'POST',
+      headers: parseHeaders(),
+      body: {},
+    });
+    const d = st.data;
+    if (st.code === 200 && d) {
+      const backend = pick(d);
+      if (backend) {
+        console.log(ok(`云资源开通成功(第 ${i} 次轮询)`));
+        return backend;
+      }
+      if (d.subscription?.provisionStatus === 'failed') {
+        // 兜底:provision/retry 一次
+        console.warn(warn('provision 失败,调 provision/retry 兜底…'));
+        await httpJson(`${API_BASE}/api/fmode/enterprise/subscription/provision/retry`, {
+          method: 'POST',
+          headers: parseHeaders(),
+          body: {},
+        });
+      }
+    }
+    if (i % 5 === 0) console.log(`  …provisioning 中(${i * 4}s)`);
+  }
+  fail('云资源开通超时(240s 未就绪),可稍后单独重跑 --with-cloud');
+}
+
+// ---------- ③④ FmodeAgent + provision ----------
+
+async function readBinding(agentId) {
+  const where = JSON.stringify({ agentId, status: 'active' });
+  const r = await parseReq(
+    'GET',
+    `/classes/FmodeMatrixBinding?where=${encodeURIComponent(where)}&limit=20`,
+  );
+  const list = r?.results ?? [];
+  if (!list.length) return null;
+  return list.sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))[0];
+}
+
+async function ensureAgent(user, agentId) {
+  console.log('\n--- ③ FmodeAgent 记录 ---');
+  // 🔴 用 scope:'mine' 不用 'all'(2026-11-24 实测):'all' 需要管理员/企业角色,
+  //    个人无企业账号会被云函数 404;本脚本永远以容器属主身份操作,'mine' 才是正确口径。
+  let q = await callFn(FN_STATUS, { op: 'query', scope: 'mine', agentId });
+  if (q.code === 200 && q.agent) {
+    console.log(ok(`记录已存在  objectId=${q.agent.objectId}`));
+    return q.agent;
+  }
+  // 🔴 创建前二次确认(2026-11-24 踩坑):入口层坏后端会把「记录存在」误报成 404,
+  //    直接信第一次的 404 就会建出重复记录(当天实测建出 K0jXgRmdHe + d8oxe9H6gw 两条)。
+  console.warn(warn('首次查询无记录,2s 后二次确认(防坏后端误报)…'));
+  await sleep(2000);
+  q = await callFn(FN_STATUS, { op: 'query', scope: 'mine', agentId });
+  if (q.code === 200 && q.agent) {
+    console.log(ok(`二次确认:记录其实存在  objectId=${q.agent.objectId}(首次是坏后端误报)`));
+    return q.agent;
+  }
+  if (DRY_RUN) {
+    console.log(`(dry-run)将直建 FmodeAgent 记录(无 company,个人无企业)`);
+    return { objectId: '<待创建>', agentId };
+  }
+  console.log('确认无记录,直建(无 company 指针 —— 个人无企业)……');
+  const body = {
+    agentId,
+    name: NAME ?? agentId,
+    user: { __type: 'Pointer', className: '_User', objectId: user.objectId },
+    ownerMobile: user.mobile,
+    ownerName: user.nickname ?? '',
+    status: 'online',
+    gender: 'unknown',
+    containerRef: agentId,
+    host: JSON.stringify({ cpuPercent: 0, diskPercent: 0, memPercent: 0 }),
+    balance: JSON.stringify({ remainCny: null, source: 'none' }),
+    channels: JSON.stringify({ homeserver: '', matrix: false, matrixConfig: {}, wecom: false }),
+    extra: JSON.stringify({ agentId }),
+    ACL: {
+      [user.objectId]: { read: true, write: true },
+      'role:FMODE_AGENT_SUPERADMIN': { read: true, write: true },
+    },
+  };
+  const created = await parseReq('POST', '/classes/FmodeAgent', body);
+  if (created.error || !created.objectId) {
+    fail(`建记录失败:${JSON.stringify(created).slice(0, 300)}`);
+  }
+  console.log(ok(`补录成功  objectId=${created.objectId}`));
+  const re = await callFn(FN_STATUS, { op: 'query', scope: 'mine', agentId });
+  if (re.code !== 200 || !re.agent) fail('补录后仍查不到记录 —— 请检查 ACL/CLP');
+  return re.agent;
+}
+
+async function ensureProvision(agentId) {
+  console.log('\n--- ④ Matrix 身份(provision)---');
+  const existing = await readBinding(agentId);
+  if (existing) {
+    console.log(ok(`已有绑定(bindingId=${existing.objectId}),不重复建(防房间割裂)`));
+    // provision 对已有绑定是缓存命中、秒回(bind-container.mjs 同款口径),
+    // 这里调它只为取「本账号(主人)的 Matrix userMxId/accessToken」——--send 要用。
+    if (DRY_RUN) return { cached: true, roomId: existing.roomId };
+    const prov = await callFn(FN_PROVISION, { agentId });
+    if (prov.code !== 200 || !prov.accessToken || !prov.userMxId) {
+      fail(`provision(缓存口径)失败:${prov.code} ${prov.mess ?? prov.message ?? ''}`);
+    }
+    if (prov.roomId && existing.roomId && prov.roomId !== existing.roomId) {
+      fail(`缓存绑定 roomId 不一致:绑定表=${existing.roomId} provision=${prov.roomId},存在房间割裂,需人工清理`);
+    }
+    console.log(ok(`缓存命中,取回主人 Matrix 凭据  userMxId=${prov.userMxId}`));
+    return { ...prov, roomId: prov.roomId ?? existing.roomId };
+  }
+  if (DRY_RUN) {
+    console.log('(dry-run)将调用 RP5Ht55NeX provision 建 Matrix 身份/房间/绑定');
+    return null;
+  }
+  const prov = await callFn(FN_PROVISION, { agentId });
+  if (prov.code !== 200 || !prov.accessToken || !prov.userMxId) {
+    fail(`provision 失败:${prov.code} ${prov.mess ?? prov.message ?? JSON.stringify(prov).slice(0, 200)}`);
+  }
+  console.log(ok('provision 成功(新建)'));
+  console.log(`   agentMxId = ${prov.agentMxId}`);
+  console.log(`   userMxId  = ${prov.userMxId}`);
+  console.log(`   roomId    = ${prov.roomId}`);
+  console.log(`   bindingId = ${prov.bindingId}`);
+  return prov;
+}
+
+// ---------- ⑤ 主容器指令 ----------
+
+function buildInstruction({ user, agentId, agent, roomId, cloud }) {
+  const objectId = agent.objectId;
+  const agentMxId = `@${String(objectId).toLowerCase()}:fmode.cn`;
+  const masterMxid = `@${user.objectId.toLowerCase()}:fmode.cn`;
+  const name = NAME ?? agent.name ?? agentId;
+  const cloudLines = cloud
+    ? `\n  云资源四件套(已开通,写进容器 ~/.fmode/config/enterprise/current.json):\n` +
+      `    appId        = ${cloud.appId}\n` +
+      `    serverURL    = ${cloud.serverURL}\n` +
+      `    functionsURL = ${cloud.functionsURL}\n` +
+      `    masterKey    = ${cloud.masterKey}`
+    : '';
+
+  return `【任务】建容器 ${agentId},从 agent-node-lj-test 迁移通用配置,接入 Fmode App
+
+这是一次 fmode-app 项目的自动化开通测试(发起方:${masterMxid},测试账号,无企业)。
+平台侧已全部开好(FmodeAgent 记录 / Matrix 身份 / 房间 / 绑定),你只做
+【建容器 + 迁移文件 + 写 .env + 启动 + 验收】。请经你的 r730_root.py SSH 通道在 R730 上执行。
+🔴 不要调任何云函数(xlosi3m46q / RP5Ht55NeX 都已完成,重复调用会造第二条绑定)。
+所有结论必须有回读证据,禁止写「应该成功了」。任一步失败立刻停,贴原始报错。
+只做本指令列出的动作,不做任何其他改动。
+
+════════════════════════════
+一、固定参数(后面都要用)
+════════════════════════════
+  容器名/hostname = ${agentId}
+  agentMxId       = ${agentMxId}
+  主人 mxId       = ${masterMxid}
+  roomId          = ${roomId ?? '<provision 未返回,先补 provision>'}
+  主人 token      = ${TOKEN}
+  Matrix 密码     = sha256("fmode-agent-mx:" + "${objectId}") 的前 24 位(provision 新建账号的派生规则,已实测)
+  显示名          = ${name}
+  源容器          = agent-node-lj-test(迁移来源,🔴 全程只读,不许改它任何东西)${cloudLines}
+
+════════════════════════════
+二、执行步骤
+════════════════════════════
+
+── 第 1 步 · 准备数据目录(先在宿主落文件,再建容器)──
+
+  mkdir -p /opt/fmode-containers/${agentId}/data
+
+  从 lj-test 拷贝【通用层】(docker cp 或 tar 管道均可):
+    /opt/data/plugins/            → 全部 11 个插件目录
+    /opt/data/scripts/            → fmode-*.py / fmode-*.sh
+    /opt/data/.fmode-media-patch/ → 整个目录(root 属主,用 sudo/docker cp 保持权限)
+    /opt/data/patches/            → fmode-gateway-finish-guard.sh、
+                                    fmode-matrix-outbound-s3-apply.sh、
+                                    temp-apply-adapter-patch.py、finish-backup/
+    /opt/data/SOUL.md             → 原样拷贝
+    /opt/data/config.yaml         → 拷贝后按下步修改
+
+  🔴 不要拷这些(lj-test 个人/垃圾):
+    .env、.env.bak-*、auth.json、matrix_threads.json、matrix-identity-archive.json、
+    channel_directory.json、sessions/、state.db*、logs/、work/、memories/、
+    diag-*、apptest-*、base*、bid/、各种 .bak-*
+
+── 第 2 步 · 改 config.yaml(新容器这份)──
+
+  🔴 必须删除 platforms.wecom 整段 —— 那是 lj-test 的企微凭据,
+     两台容器共用一个 botid 会每 ~306 秒互相断连。
+  plugins.enabled / hooks 四条声明 / model / custom_providers 保持 lj-test 原样。
+
+── 第 3 步 · 写新容器的 .env(全新写,不拷 lj-test 的)──
+
+  /opt/fmode-containers/${agentId}/data/.env:
+    MATRIX_HOMESERVER=${MATRIX_HS}
+    MATRIX_USER_ID=${agentMxId}
+    MATRIX_PASSWORD=<sha256("fmode-agent-mx:"+"${objectId}") 前24位>
+    MATRIX_HOME_ROOM=${roomId ?? '<待 provision>'}
+    MATRIX_REACTIONS=true
+    MATRIX_REQUIRE_MENTION=false
+    MATRIX_ALLOWED_USERS=${masterMxid}
+    MATRIX_MAX_MEDIA_BYTES=838860800
+    MATRIX_E2EE_MODE=off
+    AGENT_ID=${agentId}
+    FMODE_SESSION_TOKEN=${TOKEN}
+    AGENT_FUNCTION_ID=xlosi3m46q
+  chmod 600 .env
+  🔴 不设 MATRIX_IGNORE_USER_PATTERNS(会把主人消息静默丢弃)。
+
+── 第 4 步 · 建容器 ──
+
+  镜像与 lj-test 一致(先 docker inspect agent-node-lj-test 取 .Config.Image)。
+  docker run 必须带:
+    --name ${agentId}
+    --hostname ${agentId}   ← 不加会变随机 hostname,agentId 对不上
+    --restart unless-stopped
+    --env-file <上面的 env 关键项>(TZ=Asia/Shanghai 必带;env 只在创建时注入一次)
+    --memory 4g --cpus 2 --pids-limit 512
+    -v /opt/fmode-containers/${agentId}/data:/opt/data
+    --entrypoint /opt/data/.fmode-media-patch/entry.sh
+       ← Matrix 入站 https 附件补丁的持久化载体(lj-test 同款)。
+  建完确认 gateway 在跑(docker exec … pgrep -f "gateway run")。
+
+── 第 5 步 · cron 两个 job ──
+
+  容器起来后把 lj-test 的两个启用中 job 配进新容器(/opt/data/cron/jobs.json,
+  job_id 重新生成):
+    ① fmode-artifact-drain:*/3 * * * *,no_agent,脚本 fmode-artifact-drain.sh
+    ② media-gc-delayed-cleanup:every 30m,no_agent,脚本 fmode-media-gc-wrapper.sh
+
+── 第 6 步 · DNS 体检(每个新容器必做)──
+
+  docker exec ${agentId} python3 -c \\
+    "import socket,time;t=time.time();socket.getaddrinfo('api.fmode.cn',443,socket.AF_UNSPEC);print('%.0f ms'%((time.time()-t)*1000))"
+  > 1000ms 按 lj-test 同款修法:gateway 的 s6 run 脚本加
+  export RES_OPTIONS=single-request,然后重启 gateway。
+
+════════════════════════════
+三、验收(逐项贴原始输出)
+════════════════════════════
+  1. gateway_state.json:platforms.matrix.state == "connected"
+  2. 容器内回读 .env 生效值 4 项:MATRIX_USER_ID / MATRIX_HOME_ROOM /
+     MATRIX_ALLOWED_USERS / MATRIX_REQUIRE_MENTION
+  3. Matrix 自检(容器内执行):
+     用 MATRIX_PASSWORD 登录 → whoami 必须输出 ${agentMxId}
+     joined_rooms 必须含 ${roomId ?? '<roomId>'}
+     (provision 只邀请不入房,不在就 curl -X POST …/join/${roomId ?? '<roomId>'})
+  4. 在房间里发一条「容器上线自检」,回读 /messages 确认落库
+  5. 插件生效证据:/opt/data/logs/ 里 plugin-active-reporter 有上报日志
+
+汇报格式:
+  CREATE-DONE
+  容器名 / 镜像 / gateway 状态 / matrix 状态
+  .env 回读 4 项 / whoami / joined_rooms / 自检消息回读
+  DNS 耗时 / 遇到的问题(没有写「无」)
+
+纪律:
+  · lj-test 全程只读
+  · 不调云函数
+  · 不打印密码/token 全文(前 8 位即可)
+  · 失败贴原始报错,不伪造成功`;
+}
+
+// ---------- ⑥ DM 主容器 ----------
+
+const TOOL_LINE = /^[*·•]?\s*(🐍|💻|🔎|📖|✍️|🧠|💾|🔧)/;
+
+async function sendToMasterNode({ userMxId, accessToken, homeserver, instruction, agentId }) {
+  console.log('\n--- ⑥ DM 主容器 agent-node ---');
+  const mx = await import('matrix-js-sdk');
+  const hs = (homeserver ?? MATRIX_HS).replace(/\/$/, '');
+  const client = mx.createClient({ baseUrl: hs, accessToken, userId: userMxId });
+
+  const room = (
+    await client.createRoom({
+      invite: [MASTER_NODE_MXID],
+      name: `onboard-${agentId}-${Date.now()}`,
+      preset: mx.Preset.TrustedPrivateChat,
+    })
+  ).room_id;
+  console.log(`房间: ${room}(邀请 ${MASTER_NODE_MXID})`);
+
+  const auth = { Authorization: `Bearer ${accessToken}` };
+  let joined = false;
+  for (let i = 0; i < 40; i++) {
+    await sleep(3000);
+    const r = await fetch(`${hs}/_matrix/client/v3/rooms/${encodeURIComponent(room)}/joined_members`, {
+      headers: auth,
+    }).catch(() => null);
+    const j = r ? await r.json().catch(() => ({})) : {};
+    if ((j.joined ?? {})[MASTER_NODE_MXID]) {
+      joined = true;
+      console.log('主容器已进房');
+      break;
+    }
+  }
+  if (!joined) {
+    client.stopClient();
+    fail('主容器 120 秒内未进房 —— 指令未送达,请检查其准入或改用人工转发');
+  }
+
+  const sent = await client.sendEvent(room, 'm.room.message', {
+    msgtype: 'm.text',
+    body: instruction,
+    'm.mentions': { user_ids: [MASTER_NODE_MXID] },
+  });
+  console.log(`指令已发送: ${sent.event_id}(${instruction.length} 字)\n`);
+
+  // 收集回报:✅ reaction / CREATE-DONE / 静默超时
+  const seen = new Set([sent.event_id]);
+  const events = [];
+  let lastActivity = Date.now();
+  let acked = false;
+  let createDone = false;
+  const deadline = Date.now() + SEND_MAX_MS;
+
+  while (Date.now() < deadline) {
+    await sleep(5000);
+    try {
+      const r = await fetch(
+        `${hs}/_matrix/client/v3/rooms/${encodeURIComponent(room)}/messages?dir=b&limit=100`,
+        { headers: auth },
+      );
+      const j = await r.json();
+      const fresh = [];
+      for (const ev of (j.chunk ?? []).reverse()) {
+        if (seen.has(ev.event_id)) continue;
+        seen.add(ev.event_id);
+        if (ev.type === 'm.reaction') {
+          const rel = ev.content?.['m.relates_to'];
+          if (rel?.event_id === sent.event_id && String(rel.key ?? '').includes('✅')) {
+            acked = true;
+            fresh.push({ kind: 'ack', body: '✅ 主容器已标记完成' });
+          }
+          continue;
+        }
+        if (ev.type !== 'm.room.message' || ev.sender === userMxId) continue;
+        const body = String(ev.content?.body ?? '');
+        if (/CREATE-DONE/.test(body)) createDone = true;
+        fresh.push({ kind: TOOL_LINE.test(body.trim()) ? 'tool' : 'prose', body });
+      }
+      if (fresh.length) {
+        for (const f of fresh) {
+          events.push(f);
+          console.log(
+            `[${f.kind === 'tool' ? '工具' : f.kind === 'ack' ? '完成' : '正文'}] ${f.body.slice(0, 120).replace(/\n/g, ' ')}${f.body.length > 120 ? '…' : ''}`,
+          );
+        }
+        lastActivity = Date.now();
+      }
+    } catch {
+      /* 轮询抖动忽略 */
+    }
+    if (acked || createDone) {
+      console.log(`\n收到 ${acked ? '✅ reaction' : 'CREATE-DONE'},主容器标记完成`);
+      break;
+    }
+    if (Date.now() - lastActivity >= SILENCE_MS) {
+      console.log(`\n静默 ${SILENCE_MS / 1000}s,判定结束`);
+      break;
+    }
+  }
+
+  const stamp = new Date().toISOString().slice(0, 16).replace(/[-:T]/g, '');
+  const outPath = join('docs', '03-interface', `自动开通回报-${agentId}-${stamp}.md`);
+  const report = [
+    `# 自动化开通回报:${agentId}`,
+    ``,
+    `- 时间:${new Date().toISOString()}`,
+    `- 房间:\`${room}\``,
+    `- 发起账号:${userMxId}(测试账号,无企业)`,
+    `- 结束原因:${acked ? '✅ reaction' : createDone ? 'CREATE-DONE' : '静默/超时'}`,
+    ``,
+    `## 发出的指令`,
+    ``,
+    '```text',
+    instruction,
+    '```',
+    ``,
+    `## 主容器回报(原文,按时间顺序)`,
+    ``,
+    ...events
+      .filter((e) => e.kind !== 'tool')
+      .map((e, i) => `### ${i + 1}【${e.kind}】\n\n\`\`\`text\n${e.body}\n\`\`\`\n`),
+    `---`,
+    ``,
+    `## 工具过程(仅供核对)`,
+    ``,
+    ...(events.filter((e) => e.kind === 'tool').length
+      ? events.filter((e) => e.kind === 'tool').map((e) => `- \`${e.body.slice(0, 200).replace(/\n/g, ' ')}\``)
+      : ['(无)']),
+  ].join('\n');
+  mkdirSync(dirname(outPath), { recursive: true });
+  writeFileSync(outPath, report, 'utf8');
+  console.log(`\n回报已落盘: ${outPath}`);
+  client.stopClient();
+  return { acked: acked || createDone, room };
+}
+
+// ---------- ⑦ 验收 ----------
+
+async function checkAcceptance(agentId, roomId, userMxId, accessToken) {
+  console.log('\n--- ⑦ 验收(平台侧口径)---');
+  const rows = [];
+  const q = await callFn(FN_STATUS, { op: 'query', scope: 'mine', agentId });
+  const agent = q.code === 200 ? q.agent : null;
+  rows.push(['FmodeAgent 记录', !!agent]);
+
+  let ch = {};
+  try {
+    ch = typeof agent?.channels === 'string' ? JSON.parse(agent.channels) : (agent?.channels ?? {});
+  } catch {
+    /* 忽略解析失败 */
+  }
+  const mc = ch?.matrixConfig ?? {};
+  const uidOk = !!mc.userId;
+  console.log(`${uidOk ? ok : warn(`检查 App 可见性:matrixConfig.userId=${mc.userId ?? '(空)'}`)}`);
+  rows.push(['App 可见性(channels 上报)', uidOk]);
+
+  const state = mc.channelState ?? '(无)';
+  const stateOk = state === 'connected';
+  console.log(
+    `${stateOk ? ok : warn(`容器侧上报:matrixState=${state} listenerOk=${mc.listenerOk ?? '(无)'}`)}${
+      stateOk ? ` 容器侧上报 matrixState=connected` : ''
+    }`,
+  );
+  rows.push(['容器侧上报 connected', stateOk]);
+
+  if (roomId && accessToken) {
+    const r = await fetch(
+      `${MATRIX_HS}/_matrix/client/v3/rooms/${encodeURIComponent(roomId)}/joined_members`,
+      { headers: { Authorization: `Bearer ${accessToken}` } },
+    ).catch(() => null);
+    const j = r ? await r.json().catch(() => ({})) : {};
+    const members = Object.keys(j.joined ?? {});
+    const agentMxId = agent?.objectId ? `@${agent.objectId.toLowerCase()}:fmode.cn` : null;
+    const inRoom = agentMxId ? members.includes(agentMxId) : false;
+    console.log(
+      inRoom
+        ? ok(`Agent 已在房间(成员 ${members.length} 人)`)
+        : warn(`Agent 未在房间(成员:${members.join(', ') || '读不到'})`),
+    );
+    rows.push(['Agent 入房', inRoom]);
+  }
+
+  console.log('\n--- 验收结论 ---');
+  for (const [n, v] of rows) console.log(`  ${v ? '✅' : '⚠️ '} ${n}`);
+  const green = rows.every(([, v]) => v);
+  console.log(green ? '\n全绿:容器已上线并被 App 可见。' : '\n未全绿:容器实体/上报通常要等主容器建完容器后再看。');
+  return green;
+}
+
+// ---------- 主流程 ----------
+
+async function main() {
+  console.log('\n=== 个人无企业用户 → 容器开通全链路 ===');
+  console.log(`模式: ${[DRY_RUN && 'dry-run', WITH_CLOUD && 'with-cloud', SEND && 'send'].filter(Boolean).join(' + ') || '平台侧链路(不发主容器)'}\n`);
+
+  // ① 登录态
+  const user = await ensureLogin();
+  console.log(ok(`① 登录态  objectId=${user.objectId} mobile=${user.mobile} 企业=${user.company ? '有(异常!)' : '无(个人)'}`));
+  if (user.company) fail('该账号带 company 指针,不符合「个人无企业」前提,请换账号');
+
+  const agentId = AGENT_ID_ARG ?? `agent-node-app-test-${String(user.mobile).slice(-4)}`;
+  console.log(`目标 agentId = ${agentId}`);
+
+  // ② 云资源(可选)
+  const cloud = WITH_CLOUD ? await ensureCloud(user) : null;
+
+  // ③ 记录
+  const agent = await ensureAgent(user, agentId);
+
+  // ④ provision
+  const prov = await ensureProvision(agentId);
+  const roomId = prov?.roomId ?? null;
+
+  // ⑤ 指令
+  console.log('\n--- ⑤ 主容器指令 ---');
+  const instruction = buildInstruction({ user, agentId, agent, roomId, cloud });
+  const promptPath = join('scripts', `.tmp-onboard-${agentId}-prompt.md`);
+  writeFileSync(promptPath, instruction, 'utf8');
+  console.log(ok(`指令已生成(${instruction.length} 字)→ ${promptPath}`));
+
+  if (DRY_RUN) {
+    console.log('\n===== 指令全文(dry-run)=====\n');
+    console.log(instruction);
+    console.log('\n===== dry-run 结束:未做任何平台写入之外的动作 =====');
+    return;
+  }
+
+  // ⑥ 发送
+  let sendResult = null;
+  if (SEND) {
+    // provision 返回的 accessToken 就是本账号(主人)的 Matrix 凭据
+    const userMxId = prov?.userMxId;
+    const accessToken = prov?.accessToken;
+    if (!userMxId || !accessToken) {
+      fail('--send 需要 provision 现场返回的 userMxId/accessToken;该 agent 已有历史绑定,请用 ask-agent.mjs 手动发或先解绑重跑');
+    }
+    sendResult = await sendToMasterNode({
+      userMxId,
+      accessToken,
+      homeserver: prov.homeserver,
+      instruction,
+      agentId,
+    });
+  }
+
+  // ⑦ 验收
+  const green = await checkAcceptance(
+    agentId,
+    roomId,
+    prov?.userMxId,
+    prov?.accessToken,
+  );
+
+  console.log('\n=== 链路小结 ===');
+  console.log(`  agentId   = ${agentId}`);
+  console.log(`  objectId  = ${agent.objectId}`);
+  console.log(`  roomId    = ${roomId ?? '—'}`);
+  console.log(`  云资源    = ${cloud ? '已开通' : '未开通(--with-cloud 可开)'}`);
+  console.log(`  主容器指令 = ${promptPath}${sendResult ? `(已 DM,回报 ${sendResult.acked ? '完成' : '未确认完成'})` : '(未发送,--send 可发)'}`);
+  process.exit(SEND && !green ? 1 : 0);
+}
+
+await main();

+ 224 - 0
scripts/verify-download-site.mjs

@@ -0,0 +1,224 @@
+/** Local-only regression checks for the standalone download website. */
+import assert from 'node:assert/strict';
+import { createServer } from 'node:http';
+import { mkdir, readFile, writeFile } from 'node:fs/promises';
+import { dirname, resolve } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+import { chromium } from 'playwright';
+
+const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const site = resolve(root, 'prototypes/fmode-download-20261120');
+const output = resolve(root, 'test-results/download-site');
+const html = await readFile(resolve(site, 'index.html'), 'utf8');
+const source = await readFile(resolve(site, 'site.js'), 'utf8');
+const configPattern = /const FMODE_SITE = (\{[^\n]+\});/;
+const config = Function('return (' + source.match(configPattern)[1] + ')')();
+const errors = [];
+const checks = [];
+await mkdir(output, { recursive: true });
+
+const variants = new Map();
+function variant(name, apkUrl, extra = {}) {
+  variants.set('/' + name + '/', html.replace(configPattern, () => 'const FMODE_SITE = ' + JSON.stringify({ ...config, apkUrl, ...extra }) + ';'));
+}
+variant('missing', '');
+variant('unsafe', 'javascript:alert(1)');
+variant('insecure', 'http://example.com/fmode.apk');
+variant('protocol-relative', '//example.com/fmode.apk');
+variant('relative', '/download/future.apk');
+variant('new-release', 'https://example.com/fmode-v2.apk?signature=a%2Fb&v=2', { version: '2.0', fileSize: '12 MB', channel: '正式版' });
+variants.set('/qr-error/', html.replace('const qr = qrcodegen.QrCode.encodeText', 'const qr = missingQrEncoder.encodeText'));
+
+const server = createServer((request, response) => {
+  const pathname = new URL(request.url, 'http://localhost').pathname;
+  if (pathname.endsWith('.apk')) {
+    response.writeHead(200, { 'Content-Type': 'application/vnd.android.package-archive', 'Content-Disposition': 'attachment; filename="Fmode.apk"' });
+    response.end('download smoke-test fixture');
+    return;
+  }
+  const content = pathname === '/download/' ? html : variants.get(pathname);
+  response.writeHead(content ? 200 : 404, { 'Content-Type': 'text/html; charset=utf-8' });
+  response.end(content || 'Not found');
+});
+await new Promise((done) => server.listen(0, '127.0.0.1', done));
+const base = 'http://127.0.0.1:' + server.address().port;
+const browser = await chromium.launch({ headless: true, executablePath: chromium.executablePath() });
+const context = await browser.newContext({ reducedMotion: 'reduce', permissions: ['clipboard-read', 'clipboard-write'] });
+await context.route('https://ai.fmode.cn/download/*.apk', (route) => route.fulfill({
+  status: 200,
+  headers: { 'Content-Type': 'application/vnd.android.package-archive', 'Content-Disposition': 'attachment; filename="Fmode.apk"' },
+  body: 'download smoke-test fixture',
+}));
+const page = await context.newPage();
+page.on('pageerror', (error) => errors.push(error.message));
+page.on('request', (request) => {
+  if (!request.url().startsWith(base) && !request.url().startsWith('data:') && request.url() !== config.apkUrl) errors.push('Unexpected external request: ' + request.url());
+});
+
+async function open(path = '/download/') {
+  await page.goto(base + path);
+  await page.evaluate(() => document.fonts.ready);
+}
+async function noOverflow(label) {
+  const sizes = await page.evaluate(() => ({ scroll: document.documentElement.scrollWidth, viewport: window.innerWidth }));
+  assert(sizes.scroll <= sizes.viewport, label + ': horizontal overflow ' + JSON.stringify(sizes));
+}
+async function screenshot(name, locator, fullPage = false) {
+  const options = { path: resolve(output, name + '.png'), animations: 'disabled' };
+  if (locator) await locator.screenshot({ ...options, style: '.site-header, .mobile-download-bar { visibility: hidden !important; }' });
+  else await page.screenshot({ ...options, fullPage });
+}
+async function downloadFrom(selector) {
+  const event = page.waitForEvent('download');
+  await page.locator(selector).click();
+  const download = await event;
+  assert.equal(download.url(), config.apkUrl);
+  await download.cancel();
+}
+
+try {
+  for (const width of [320, 360, 375, 390, 430, 650, 760, 768, 1024, 1440, 1920]) {
+    await page.setViewportSize({ width, height: width <= 760 ? 844 : 960 });
+    await open();
+    await noOverflow('viewport ' + width);
+    for (const scene of ['workbench', 'deliverables', 'conversation']) {
+      await page.locator('#tab-' + scene).click();
+      assert.equal(await page.locator('#scene-' + scene).isVisible(), true);
+      await noOverflow(width + ' / ' + scene);
+    }
+    const sizes = await page.locator('.hero-actions .button').evaluateAll((buttons) => buttons.map((button) => ({ height: button.getBoundingClientRect().height, font: parseFloat(getComputedStyle(button).fontSize) })));
+    assert(sizes.every((size) => size.height >= 44 && size.font >= 12), 'Small hero buttons at ' + width);
+    const isMobile = width <= 760;
+    assert.equal(await page.locator('.mobile-download-bar').isVisible(), isMobile);
+    if (isMobile) {
+      await page.locator('#menuToggle').click();
+      assert.equal(await page.locator('#menuToggle').getAttribute('aria-expanded'), 'true');
+      await page.locator('#navLinks a[href="#download"]').click();
+      assert.equal(await page.locator('#menuToggle').getAttribute('aria-expanded'), 'false');
+    }
+    await page.evaluate(() => window.scrollTo(0, 0));
+    if ([320, 390, 1440].includes(width)) {
+      await screenshot('hero-' + width);
+      await screenshot('full-' + width, null, true);
+      await screenshot('download-' + width, page.locator('.download-card'));
+    }
+    await page.locator('.hero-actions [data-show-qr]').click();
+    assert.equal(await page.locator('#downloadDialog').evaluate((dialog) => dialog.open), true);
+    assert.equal(await page.locator('#dialogQr').isVisible(), true);
+    await noOverflow('QR dialog ' + width);
+    if ([390, 1440].includes(width)) await screenshot('qr-dialog-' + width);
+    await page.keyboard.press('Escape');
+    assert.equal(await page.locator('#downloadDialog').evaluate((dialog) => dialog.open), false);
+    assert.equal(await page.evaluate(() => document.activeElement.matches('.hero-actions [data-show-qr]')), true);
+    checks.push('Responsive layout, tabs, menu, QR dialog and focus at ' + width + 'px');
+  }
+
+  await page.setViewportSize({ width: 1440, height: 960 });
+  await open();
+  const targets = await page.locator('[data-download]').evaluateAll((links) => links.map((link) => link.href));
+  assert(targets.length >= 4 && targets.every((url) => url === config.apkUrl));
+  await downloadFrom('.hero-actions [data-download]');
+  await downloadFrom('.nav-actions [data-download]');
+  await downloadFrom('#apkButton');
+  await page.locator('.hero-actions [data-show-qr]').click();
+  await downloadFrom('[data-dialog-download]');
+  await page.locator('.dialog-actions [data-copy-link]').click();
+  assert.match(await page.locator('#dialogCopyStatus').textContent(), /已复制/);
+  await page.locator('#dialogClose').click();
+  await page.locator('.download-qr [data-copy-link]').click();
+  assert.equal(await page.evaluate(() => navigator.clipboard.readText()), config.apkUrl);
+  const qrImage = await page.locator('.download-qr [data-qr-image]').getAttribute('src');
+  assert(qrImage.startsWith('data:image/png;base64,'));
+  await writeFile(resolve(output, 'download-qr.png'), Buffer.from(qrImage.split(',')[1], 'base64'));
+  checks.push('Header / hero / section / dialog links share URL; real download events; clipboard; QR exported');
+
+  await page.setViewportSize({ width: 390, height: 844 });
+  await open();
+  await downloadFrom('.mobile-download-bar [data-download]');
+  await page.locator('.mobile-download-bar [data-show-qr]').click();
+  await page.keyboard.press('Tab');
+  assert.equal(await page.evaluate(() => document.getElementById('downloadDialog').contains(document.activeElement)), true);
+  await page.keyboard.press('Escape');
+  await page.locator('#menuToggle').click();
+  await page.keyboard.press('Escape');
+  assert.equal(await page.evaluate(() => document.activeElement.id), 'menuToggle');
+  await page.locator('#faq details').first().locator('summary').click();
+  assert.equal(await page.locator('#faq details').first().getAttribute('open'), '');
+  checks.push('Mobile sticky download, focus containment, menu Esc, FAQ');
+
+  for (const [width, height] of [[320, 568], [390, 600], [760, 420]]) {
+    await page.setViewportSize({ width, height });
+    await open();
+    await page.locator('.hero-actions [data-show-qr]').click();
+    const bounds = await page.locator('#downloadDialog').boundingBox();
+    assert(bounds.y >= 0 && bounds.y + bounds.height <= height, 'Dialog fits short viewport');
+    await page.locator('#dialogConfirm').click();
+    assert.equal(await page.locator('#downloadDialog').evaluate((dialog) => dialog.open), false);
+  }
+  checks.push('QR dialogs scroll and close in 320×568, 390×600 and 760×420 viewports');
+
+  for (const name of ['missing', 'unsafe', 'insecure', 'protocol-relative']) {
+    await open('/' + name + '/');
+    assert.equal(await page.locator('.download-qr [data-qr-image]').isVisible(), false);
+    assert.equal(await page.locator('.download-qr [data-copy-link]').isDisabled(), true);
+    await page.locator('.hero-actions [data-download]').click();
+    assert.match(await page.locator('#dialogTitle').textContent(), /准备/);
+    assert.equal(await page.locator('[data-dialog-download]').isVisible(), false);
+    await page.keyboard.press('Escape');
+  }
+  await open('/relative/');
+  assert.equal(await page.locator('#apkButton').getAttribute('href'), base + '/download/future.apk');
+  await open('/new-release/');
+  assert.match(await page.locator('#releaseMeta').textContent(), /2\.0.*12 MB/);
+  assert.equal(await page.locator('#apkButton').getAttribute('href'), 'https://example.com/fmode-v2.apk?signature=a%2Fb&v=2');
+  const newQrImage = await page.locator('.download-qr [data-qr-image]').getAttribute('src');
+  assert.notEqual(qrImage, newQrImage);
+  await writeFile(resolve(output, 'download-qr-new-release.png'), Buffer.from(newQrImage.split(',')[1], 'base64'));
+  await open('/qr-error/');
+  assert.match(await page.locator('[data-qr-placeholder]').textContent(), /不可用/);
+  assert.equal(await page.locator('#apkButton').getAttribute('href'), config.apkUrl);
+  await page.locator('.hero-actions [data-show-qr]').click();
+  assert.equal(await page.locator('[data-dialog-download]').isVisible(), true);
+  checks.push('Missing / unsafe URLs; relative URL; release changes update QR; QR failure keeps direct download');
+
+  for (const [name, userAgent, expected] of [
+    ['ios', 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 Version/18.0 Mobile/15E148 Safari/604.1', /Android 版/],
+    ['wechat', 'Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 Chrome/130.0.0.0 Mobile Safari/537.36 MicroMessenger/8.0', /浏览器/],
+  ]) {
+    const mobileContext = await browser.newContext({ viewport: { width: 390, height: 844 }, userAgent, isMobile: true, hasTouch: true, reducedMotion: 'reduce' });
+    const mobile = await mobileContext.newPage();
+    mobile.on('pageerror', (error) => errors.push(error.message));
+    await mobile.goto(base + '/download/');
+    await mobile.locator('.mobile-download-bar [data-download]').click();
+    assert.match(await mobile.locator('#dialogTitle').textContent(), expected);
+    assert.equal(await mobile.locator('[data-dialog-download]').isVisible(), false);
+    await mobile.screenshot({ path: resolve(output, 'device-' + name + '.png'), animations: 'disabled' });
+    await mobileContext.close();
+  }
+  checks.push('iOS compatibility message; WeChat browser instructions');
+
+  await page.close();
+  const fallbackContext = await browser.newContext({ reducedMotion: 'reduce' });
+  const fallback = await fallbackContext.newPage();
+  await fallback.addInitScript(() => { Object.defineProperty(navigator, 'clipboard', { value: undefined }); });
+  await fallback.goto(base + '/download/');
+  await fallback.locator('.download-qr [data-copy-link]').click();
+  assert.equal(await fallback.locator('#manualCopy').isVisible(), true);
+  assert.equal(await fallback.locator('#downloadLink').inputValue(), config.apkUrl);
+  await fallbackContext.close();
+  checks.push('Clipboard unavailable: selected, manually copyable URL');
+
+  const offline = await context.newPage();
+  await context.setOffline(true);
+  await offline.goto(pathToFileURL(resolve(site, 'index.html')).href);
+  assert.equal(await offline.locator('.download-qr [data-qr-image]').isVisible(), true);
+  await context.setOffline(false);
+  await offline.close();
+  checks.push('Standalone file renders QR fully offline');
+  assert.deepEqual(errors, [], 'Browser errors or unexpected external resources');
+  await writeFile(resolve(output, 'results.json'), JSON.stringify({ success: true, checks, errors }, null, 2));
+  console.log(JSON.stringify({ success: true, checks, screenshots: output }, null, 2));
+} finally {
+  await browser.close();
+  await new Promise((done) => server.close(done));
+}

+ 34 - 2
src/app/app.routes.ts

@@ -1,5 +1,6 @@
 import { ActivatedRouteSnapshot, Route, Routes } from '@angular/router';
 import { authGuard } from './core/auth.guard';
+import { containerGuard } from './core/container.guard';
 import { detectUiMode } from './core/device.service';
 import { orgGuard } from './core/org.guard';
 
@@ -63,14 +64,45 @@ export const routes: Routes = [
         ? import('./mobile/pages/pending/pending').then((m) => m.MbPendingPage)
         : import('./pages/pending/pending').then((m) => m.PendingPage),
   },
+  {
+    /*
+     * 套餐页 / 开通等待页(2026-11-27 提到顶层)
+     *
+     * 🔴 为什么必须在 shell 之外:
+     *
+     *   ① **门禁例外**:无容器的用户只能待在这两个页面,
+     *      挂在 shell 里会被 `containerGuard` 一并拦掉 → 死循环。
+     *   ② **全屏锁定**:开通等待页不允许出现 TabBar / 抽屉 / 侧边栏,
+     *      不挂 shell 就等于没有这些东西(比一个个去禁用干净)。
+     *   ③ **缩放不跳转**:shell 的 resize 监听不会触发,
+     *      用户拖窗口不会把正在开通的页面跳走。
+     *
+     * 只挂 `authGuard`(要登录),**不挂 `orgGuard` / `containerGuard`**。
+     */
+    path: 'plans',
+    canActivate: [authGuard],
+    loadComponent: () =>
+      detectMode() === 'mobile'
+        ? import('./mobile/pages/plans/plans').then((m) => m.MbPlansPage)
+        : import('./desktop/pages/plans/plans').then((m) => m.DkPlansPage),
+  },
+  {
+    /** 开通等待页:全屏锁定,成功/失败后才解锁 */
+    path: 'provision',
+    canActivate: [authGuard],
+    loadComponent: () =>
+      detectMode() === 'mobile'
+        ? import('./mobile/pages/provision/provision').then((m) => m.MbProvisionPage)
+        : import('./desktop/pages/provision/provision').then((m) => m.DkProvisionPage),
+  },
   {
     path: 'desktop',
-    canActivate: [authGuard, orgGuard],
+    canActivate: [authGuard, orgGuard, containerGuard],
     loadChildren: () => import('./desktop/desktop.routes').then((m) => m.desktopRoutes),
   },
   {
     path: 'mobile',
-    canActivate: [authGuard, orgGuard],
+    canActivate: [authGuard, orgGuard, containerGuard],
     loadChildren: () => import('./mobile/mobile.routes').then((m) => m.mobileRoutes),
   },
   // ---- 旧路径重定向(FR-16 AC-16.2)----

+ 30 - 2
src/app/app.ts

@@ -1,8 +1,9 @@
 import { TaskCompletionNotificationService } from './core/task-completion-notification.service';
-import { ChangeDetectionStrategy, Component, effect, inject, isDevMode } from '@angular/core';
-import { RouterOutlet } from '@angular/router';
+import { ChangeDetectionStrategy, Component, effect, inject, isDevMode, untracked } from '@angular/core';
+import { Router, RouterOutlet } from '@angular/router';
 import { PaletteService } from './core/palette.service';
 import { ChatFontService } from './core/chat-font.service';
+import { SessionService } from './core/session.service';
 import { ThemeService } from './ui/theme/theme.service';
 import { installDataApi } from './core/data-tools';
 import { UiMToast } from './ui/mobile/components/toast/toast';
@@ -51,6 +52,8 @@ export class App {
   private readonly palette = inject(PaletteService);
   private readonly font = inject(ChatFontService);
   private readonly alert = inject(AlertService);
+  private readonly session = inject(SessionService);
+  private readonly router = inject(Router);
 
   constructor() {
     inject(TaskCompletionNotificationService);
@@ -60,6 +63,31 @@ export class App {
     this.palette.init();
     // 登录或切换身份后同步恢复对应用户的字号。
     effect(() => this.font.load());
+
+    /*
+     * 🔴 会话失效 → 跳登录页(2026-11-27)
+     *
+     * 服务端返回 401 时 `ParseApi` 会调 `session.expire()` 清登录态,
+     * 这里监听计数器变化统一跳转。
+     *
+     * 为什么放在根组件而不是各页面:**任何** API 调用都可能遇到 401,
+     * 逐个页面处理必然遗漏。根组件是唯一必经之路。
+     *
+     * `untracked`:读 tick 只是为了建立依赖,跳转本身不应触发额外追踪。
+     */
+    effect(() => {
+      const tick = this.session.expiredTick();
+      if (tick === 0) return;
+      untracked(() => {
+        const here = this.router.url.split('?')[0];
+        // 已经在登录页就不用跳,避免重复导航
+        if (here === '/login') return;
+        void this.router.navigateByUrl(`/login?redirect=${encodeURIComponent(this.router.url)}`, {
+          replaceUrl: true,
+        });
+      });
+    });
+
     /* 开发期数据维护入口(生产构建不暴露):__fmodeData.clearDemo() 等 */
     if (isDevMode()) {
       installDataApi();

+ 48 - 2
src/app/components/domain/assistant-turn/assistant-turn.spec.ts

@@ -233,7 +233,11 @@ describe('AssistantTurnComponent', () => {
   it('仍在输出且无内容时显示「正在思考…」,且**只出现一次**', () => {
     /*
      * 2026-11-07 用户截图:单聊里出现过两条「正在思考…」——
-     * 卡级占位与段级占位同时渲染。现在统一由段级负责。
+     * 卡级占位与段级占位同时渲染。现在统一由卡片级负责。
+     *
+     * 2026-11-24 口径细化:「正在思考…」只在卡片头秒数未起(第 1 秒内)
+     * 显示,卡片头「已处理 Ns」一接管就让位(用户截图红框:两行并存属重复)。
+     * startAt 拨到未来 500ms,消除跨秒边界的测试抖动。
      */
     const t = turn();
     t.blocks[0] = {
@@ -244,6 +248,8 @@ describe('AssistantTurnComponent', () => {
       live: true,
       empty: false,
       merged: null,
+      startAt: Date.now() + 500,
+      updatedAt: Date.now() + 500,
     };
     t.merged = null;
     t.stepCount = 0;
@@ -258,8 +264,48 @@ describe('AssistantTurnComponent', () => {
     const waits = fixture.nativeElement.querySelectorAll('.seg-wait');
     expect(waits.length).withContext('段级等待块已删除').toBe(0);
     const cardWait = fixture.nativeElement.querySelector('.card-wait');
-    expect(cardWait).withContext('卡片级提示仍在').not.toBeNull();
+    expect(cardWait).withContext('卡片头秒数未起时,卡片级提示仍在').not.toBeNull();
     expect(cardWait.textContent).toContain('正在思考');
+    expect(fixture.nativeElement.querySelector('.card-running'))
+      .withContext('首秒内卡片头尚未显示')
+      .toBeNull();
+  });
+
+  it('🔴 卡片头「已处理 Ns」出现后,「正在思考…」让位(2026-11-24 红框修复)', () => {
+    /*
+     * 用户截图:同一回合里「已处理 3s · 继续处理任务过程」与
+     * 「已送达 · 正在思考…(3s)」并存 —— 两条说的是同一件事。
+     * 口径:卡片头在,等待行就不在(与 2026-11-14 删段级重复块同裁决)。
+     */
+    const T = 1_800_000_000_000;
+    const t = turn();
+    t.blocks[0] = {
+      ...t.blocks[0],
+      body: [],
+      steps: [],
+      files: [],
+      live: true,
+      empty: false,
+      merged: null,
+      startAt: T,
+      updatedAt: T,
+    };
+    t.merged = null;
+    t.stepCount = 0;
+    t.live = true;
+    t.phase = 'thinking';
+    render(t);
+
+    const clock = (cmp as unknown as { now: { set(v: number): void } }).now;
+    clock.set(T + 3000);
+    fixture.detectChanges();
+
+    expect(fixture.nativeElement.querySelector('.card-running')?.textContent ?? '').toContain(
+      '已处理 3s',
+    );
+    expect(fixture.nativeElement.querySelector('.card-wait'))
+      .withContext('卡片头接管后不再显示等待行')
+      .toBeNull();
   });
 
   /**

+ 10 - 0
src/app/components/domain/assistant-turn/assistant-turn.ts

@@ -1065,6 +1065,16 @@ export class AssistantTurnComponent implements OnDestroy {
      */
     const hasContent = t.blocks.some((b) => !!b.merged);
     if (hasContent) return '';
+    /*
+     * 🔴 卡片头已接管时不显示(2026-11-24 用户截图实测)。
+     *
+     * 「已处理 Ns · 继续处理任务过程」(turn live 且秒数 >0)与这条
+     * 「已送达 · 正在思考…(Ns)」表达同一件事,并存 = 同一屏两条转圈提示
+     * (与 2026-11-14 删段级重复块的裁决同口径,当时漏了卡片级这条)。
+     * 保留前 ~1 秒(卡片头秒数还是 0)的「正在思考…」作为最早反馈,
+     * 卡片头一出现就让位。
+     */
+    if (t.live && this.turnSeconds() > 0) return '';
     const b = t.blocks[0];
     if (!b) return '';
     // 与段级共用同一份文案表,避免两套判据

+ 188 - 0
src/app/components/domain/loading-overlay/loading-overlay.ts

@@ -0,0 +1,188 @@
+import { ChangeDetectionStrategy, Component, input } from '@angular/core';
+
+/**
+ * 全屏加载遮罩(2026-11-27)
+ *
+ * ## 为什么需要
+ *
+ * 用户反馈:「点击套餐开通的时候感觉就是卡死的状态」。
+ *
+ * 原因是开通请求要 1-3 秒(建记录 + 建 Matrix 身份 + 算密码),
+ * 期间**只有按钮文字变化**——在桌面大屏上几乎看不出来。
+ * 用户不知道点了有没有生效,就会反复点。
+ *
+ * ## 设计
+ *
+ * - **全屏半透明遮罩**:明确阻断其他操作,避免误点
+ * - **多段脉冲动画**:比单个转圈更有"正在进行"的感觉
+ * - **明确的文案**:告诉用户具体在做什么、大概多久
+ * - **响应 prefers-reduced-motion**:降级为静态图标
+ *
+ * ## 用法
+ *
+ * ```html
+ * @if (busy()) {
+ *   <app-loading-overlay message="正在生成接入提示词…" hint="首次约需 2-3 秒" />
+ * }
+ * ```
+ */
+@Component({
+  selector: 'app-loading-overlay',
+  changeDetection: ChangeDetectionStrategy.OnPush,
+  template: `
+    <div class="ovl" role="status" aria-live="polite" aria-busy="true">
+      <div class="ovl-card">
+        <!-- 三段脉冲:比单转圈更有"正在跑"的观感 -->
+        <div class="ovl-dots" aria-hidden="true">
+          <span></span><span></span><span></span>
+        </div>
+        <p class="ovl-msg">{{ message() }}</p>
+        @if (hint()) {
+          <p class="ovl-hint">{{ hint() }}</p>
+        }
+        <!-- 不确定进度条:来回扫 -->
+        <div class="ovl-track" aria-hidden="true"><span class="ovl-thumb"></span></div>
+      </div>
+    </div>
+  `,
+  styles: [
+    `
+      :host {
+        position: fixed;
+        inset: 0;
+        z-index: var(--z-modal);
+        display: block;
+      }
+
+      .ovl {
+        display: grid;
+        place-items: center;
+        width: 100%;
+        height: 100%;
+        /* 半透明遮罩:能看到底下页面,但明确阻断操作 */
+        background: color-mix(in srgb, var(--canvas) 78%, transparent);
+        backdrop-filter: blur(2px);
+        animation: ovl-fade 180ms cubic-bezier(0.2, 0, 0, 1) both;
+      }
+
+      .ovl-card {
+        display: flex;
+        flex-direction: column;
+        align-items: center;
+        gap: var(--sp-3);
+        min-width: 280px;
+        max-width: 380px;
+        padding: var(--sp-8) var(--sp-6);
+        border: 1px solid var(--edge);
+        border-radius: var(--r-lg);
+        background: var(--surface);
+        box-shadow: var(--shadow-pop);
+        text-align: center;
+      }
+
+      /* ---------- 三段脉冲 ---------- */
+      .ovl-dots {
+        display: flex;
+        gap: 8px;
+      }
+      .ovl-dots span {
+        width: 10px;
+        height: 10px;
+        border-radius: 50%;
+        background: var(--primary);
+        animation: ovl-pulse 1.1s cubic-bezier(0.2, 0, 0, 1) infinite;
+      }
+      .ovl-dots span:nth-child(2) {
+        animation-delay: 0.14s;
+      }
+      .ovl-dots span:nth-child(3) {
+        animation-delay: 0.28s;
+      }
+
+      .ovl-msg {
+        margin: 0;
+        color: var(--ink);
+        font-size: var(--fs-15);
+        font-weight: 600;
+        letter-spacing: -0.01em;
+      }
+      .ovl-hint {
+        margin: 0;
+        color: var(--muted);
+        font-size: var(--fs-12);
+      }
+
+      /* ---------- 不确定进度条(来回扫) ---------- */
+      .ovl-track {
+        position: relative;
+        width: 100%;
+        height: 3px;
+        margin-top: var(--sp-2);
+        border-radius: 999px;
+        background: var(--surface-2);
+        overflow: hidden;
+      }
+      .ovl-thumb {
+        position: absolute;
+        top: 0;
+        left: 0;
+        width: 40%;
+        height: 100%;
+        border-radius: inherit;
+        background: var(--primary);
+        /* 只动画 transform,遵守 rules/18 */
+        animation: ovl-sweep 1.3s cubic-bezier(0.4, 0, 0.2, 1) infinite;
+      }
+
+      @keyframes ovl-fade {
+        from {
+          opacity: 0;
+        }
+        to {
+          opacity: 1;
+        }
+      }
+      @keyframes ovl-pulse {
+        0%,
+        100% {
+          opacity: 0.25;
+          transform: scale(0.8);
+        }
+        50% {
+          opacity: 1;
+          transform: scale(1.1);
+        }
+      }
+      @keyframes ovl-sweep {
+        0% {
+          transform: translateX(-100%);
+        }
+        100% {
+          transform: translateX(350%);
+        }
+      }
+
+      /* ---------- 减弱动效 ---------- */
+      @media (prefers-reduced-motion: reduce) {
+        .ovl,
+        .ovl-dots span,
+        .ovl-thumb {
+          animation: none;
+        }
+        .ovl-dots span {
+          opacity: 1;
+        }
+        .ovl-thumb {
+          width: 100%;
+          opacity: 0.5;
+        }
+      }
+    `,
+  ],
+})
+export class LoadingOverlayComponent {
+  /** 主文案:正在做什么 */
+  readonly message = input<string>('正在处理…');
+  /** 副文案:预计多久(可空) */
+  readonly hint = input<string>('');
+}

+ 82 - 0
src/app/components/domain/provision-instruction/provision-instruction.spec.ts

@@ -0,0 +1,82 @@
+import { ComponentFixture, TestBed } from '@angular/core/testing';
+import { ProvisionInstructionComponent } from './provision-instruction';
+
+/**
+ * 接入提示词组件单测(2026-11-27)
+ *
+ * ## 锁住的规则
+ *
+ *   · 展示完整提示词
+ *   · 复制成功 → 按钮变「已复制」
+ *   · 🔴 复制失败(非 HTTPS)→ 显示兜底提示 + 自动全选
+ *
+ * 第三条最重要:部署到内网 http 时 `navigator.clipboard` 会抛
+ * `NotAllowedError`,没有兜底的话用户只会看到按钮「没反应」。
+ */
+describe('ProvisionInstructionComponent', () => {
+  let fixture: ComponentFixture<ProvisionInstructionComponent>;
+  let component: ProvisionInstructionComponent;
+
+  beforeEach(async () => {
+    await TestBed.configureTestingModule({
+      imports: [ProvisionInstructionComponent],
+    }).compileComponents();
+
+    fixture = TestBed.createComponent(ProvisionInstructionComponent);
+    component = fixture.componentInstance;
+  });
+
+  it('渲染传入的提示词全文', () => {
+    fixture.componentRef.setInput('text', 'MATRIX_USER_ID=@abc:fmode.cn');
+    fixture.detectChanges();
+
+    const pre = fixture.nativeElement.querySelector('.ins-code');
+    expect(pre.textContent).toContain('MATRIX_USER_ID=@abc:fmode.cn');
+  });
+
+  it('复制成功后按钮变「已复制」', async () => {
+    fixture.componentRef.setInput('text', 'hello');
+    fixture.detectChanges();
+
+    const writeText = jasmine.createSpy('writeText').and.returnValue(Promise.resolve());
+    Object.defineProperty(navigator, 'clipboard', {
+      value: { writeText },
+      configurable: true,
+    });
+
+    await (component as unknown as { copy: () => Promise<void> }).copy();
+    fixture.detectChanges();
+
+    expect(writeText).toHaveBeenCalledWith('hello');
+    expect(fixture.nativeElement.querySelector('.ins-btn').textContent).toContain('已复制');
+  });
+
+  it('🔴 复制失败时显示兜底提示(非 HTTPS 场景)', async () => {
+    fixture.componentRef.setInput('text', 'hello');
+    fixture.detectChanges();
+
+    Object.defineProperty(navigator, 'clipboard', {
+      value: {
+        writeText: () => Promise.reject(new Error('NotAllowedError')),
+      },
+      configurable: true,
+    });
+
+    await (component as unknown as { copy: () => Promise<void> }).copy();
+    fixture.detectChanges();
+
+    // 必须出现「手动复制」的提示,而不是静默失败
+    const hint = fixture.nativeElement.querySelector('.ins-hint');
+    expect(hint).not.toBeNull();
+    expect(hint.textContent).toContain('Ctrl+C');
+  });
+
+  it('空文本时点击不报错', async () => {
+    fixture.componentRef.setInput('text', '');
+    fixture.detectChanges();
+
+    await expectAsync(
+      (component as unknown as { copy: () => Promise<void> }).copy(),
+    ).toBeResolved();
+  });
+});

+ 216 - 0
src/app/components/domain/provision-instruction/provision-instruction.ts

@@ -0,0 +1,216 @@
+import {
+  ChangeDetectionStrategy,
+  Component,
+  ElementRef,
+  input,
+  signal,
+  viewChild,
+} from '@angular/core';
+
+/**
+ * 接入提示词展示 + 一键复制(2026-11-27)
+ *
+ * ## 为什么抽成组件
+ *
+ * 移动端和桌面端原本**各写了一份**,结果桌面端漏了复制按钮
+ * (只有一段裸 `<pre>`),用户复制不了。
+ * 抽出来之后两端共用,不会再漏。
+ *
+ * ## 🔴 复制失败必须有兜底
+ *
+ * `navigator.clipboard` 只在**安全上下文**可用:
+ *   · `https://` ✅
+ *   · `http://localhost` ✅
+ *   · `http://10.x.x.x`(内网 IP)❌ —— 会抛 `NotAllowedError`
+ *
+ * 部署到内网 http 时复制会静默失败,用户以为按钮坏了。
+ * 因此失败时**自动全选 `<pre>` 内容**,并提示「按 Ctrl+C 复制」。
+ */
+@Component({
+  selector: 'app-provision-instruction',
+  changeDetection: ChangeDetectionStrategy.OnPush,
+  template: `
+    <section class="ins">
+      <header class="ins-head">
+        <i class="fa-solid fa-wand-magic-sparkles" aria-hidden="true"></i>
+        <h2>接入提示词已生成</h2>
+      </header>
+      <p class="ins-lead">复制下面的内容,粘贴到你的容器里执行。</p>
+
+      <pre #code class="ins-code" tabindex="0">{{ text() }}</pre>
+
+      <button
+        type="button"
+        class="ins-btn"
+        [disabled]="copying()"
+        [attr.aria-label]="copied() ? '已复制到剪贴板' : '复制接入提示词'"
+        (click)="copy()"
+      >
+        @if (copying()) {
+          <i class="fa-solid fa-circle-notch fa-spin" aria-hidden="true"></i>
+          复制中…
+        } @else if (copied()) {
+          <i class="fa-solid fa-check" aria-hidden="true"></i>
+          已复制
+        } @else {
+          <i class="fa-regular fa-copy" aria-hidden="true"></i>
+          一键复制
+        }
+      </button>
+
+      @if (copyFailed()) {
+        <p class="ins-hint" role="alert">
+          <i class="fa-solid fa-triangle-exclamation" aria-hidden="true"></i>
+          自动复制被浏览器拦截了,内容已全选,按 Ctrl+C(Mac 为 ⌘+C)即可。
+        </p>
+      }
+    </section>
+  `,
+  styles: [
+    `
+      :host {
+        display: block;
+      }
+      .ins {
+        padding: var(--sp-4);
+        border: 1px solid var(--edge);
+        border-radius: var(--r-md);
+        background: var(--surface);
+      }
+      .ins-head {
+        display: flex;
+        align-items: center;
+        gap: var(--sp-2);
+      }
+      .ins-head > i {
+        color: var(--primary);
+        font-size: var(--fs-15);
+      }
+      .ins-head h2 {
+        margin: 0;
+        font-size: var(--fs-15);
+        font-weight: 600;
+        color: var(--ink);
+      }
+      .ins-lead {
+        margin: var(--sp-2) 0 var(--sp-3);
+        color: var(--muted);
+        font-size: var(--fs-12);
+      }
+
+      .ins-code {
+        max-height: 240px;
+        overflow: auto;
+        margin: 0 0 var(--sp-3);
+        padding: var(--sp-3);
+        border: 1px solid var(--edge);
+        border-radius: var(--r-sm);
+        background: var(--surface-2);
+        color: var(--ink-2);
+        font-family: ui-monospace, Consolas, monospace;
+        font-size: var(--fs-11);
+        line-height: 1.6;
+        white-space: pre-wrap;
+        overflow-wrap: anywhere;
+        /* 选中态要能看清 */
+        user-select: all;
+      }
+      .ins-code:focus-visible {
+        outline: 2px solid var(--primary);
+        outline-offset: 2px;
+      }
+
+      /* 触控区 ≥44px(rules/18 底线) */
+      .ins-btn {
+        display: inline-flex;
+        align-items: center;
+        justify-content: center;
+        gap: var(--sp-2);
+        width: 100%;
+        min-height: 44px;
+        padding: 0 var(--sp-4);
+        border: 0;
+        border-radius: var(--r-md);
+        background: var(--primary);
+        color: var(--primary-content);
+        font: inherit;
+        font-size: var(--fs-14);
+        font-weight: 500;
+        cursor: pointer;
+        transition: opacity 150ms cubic-bezier(0.2, 0, 0, 1);
+      }
+      .ins-btn:disabled {
+        opacity: 0.6;
+        cursor: progress;
+      }
+
+      .ins-hint {
+        display: flex;
+        align-items: flex-start;
+        gap: var(--sp-2);
+        margin: var(--sp-3) 0 0;
+        color: var(--warning);
+        font-size: var(--fs-12);
+        line-height: 1.6;
+      }
+      .ins-hint > i {
+        margin-top: 2px;
+      }
+
+      @media (prefers-reduced-motion: reduce) {
+        .ins-btn {
+          transition: none;
+        }
+      }
+    `,
+  ],
+})
+export class ProvisionInstructionComponent {
+  /** 要展示/复制的提示词全文 */
+  readonly text = input<string>('');
+
+  private readonly codeRef = viewChild<ElementRef<HTMLElement>>('code');
+
+  protected readonly copying = signal(false);
+  protected readonly copied = signal(false);
+  protected readonly copyFailed = signal(false);
+
+  protected async copy(): Promise<void> {
+    const value = this.text();
+    if (!value) return;
+
+    this.copying.set(true);
+    this.copyFailed.set(false);
+    try {
+      await navigator.clipboard.writeText(value);
+      this.copied.set(true);
+      // 2.4 秒后恢复,让用户看清「已复制」再变回去
+      setTimeout(() => this.copied.set(false), 2400);
+    } catch {
+      /*
+       * 非安全上下文 / 权限被拒 —— 走到这里。
+       * 自动全选让用户直接 Ctrl+C,而不是干瞪眼。
+       */
+      this.copyFailed.set(true);
+      this.selectCode();
+    } finally {
+      this.copying.set(false);
+    }
+  }
+
+  /** 兜底:选中 `<pre>` 里的全部文本 */
+  private selectCode(): void {
+    const el = this.codeRef()?.nativeElement;
+    if (!el) return;
+    try {
+      const range = document.createRange();
+      range.selectNodeContents(el);
+      const sel = window.getSelection();
+      sel?.removeAllRanges();
+      sel?.addRange(range);
+      el.focus();
+    } catch {
+      // 选择失败也不该让页面崩
+    }
+  }
+}

+ 2 - 0
src/app/components/domain/session-tree/session-tree.ts

@@ -2230,11 +2230,13 @@ export class SessionTreeComponent implements OnDestroy {
       void this.chat.open(agentId, this.chat.sessionId() ?? undefined);
       return;
     }
+    /* 用户显式点重试:绕过 10 秒去重窗口(2026-11-24 reloadAll 首屏合并) */
     void this.sessionsSvc.reloadAll(
       this.liveSvc
         .agents()
         .filter((a) => a.matrixReady)
         .map((a) => a.id),
+      { force: true },
     );
   }
 

+ 3 - 0
src/app/core/api/api.provider.ts

@@ -28,6 +28,9 @@ export function provideFmodeApi(): Provider {
         () => scopeFor(session.me()),
         // CORS 兼容层:`main.ts` 已先 probe 过,这里拿到的是缓存结果
         inject(PlatformProxyService),
+        // 🔴 会话失效回调(2026-11-27):401 重试全失败后清登录态,
+        //    由根组件 `App` 监听 `expiredTick` 跳登录页。
+        () => session.expire(),
       );
     },
   };

+ 29 - 0
src/app/core/api/fmode-api.ts

@@ -9,6 +9,8 @@ import {
   FileEntry,
   MatrixProvision,
   Me,
+  ProvisionStartResult,
+  ProvisionStatus,
   SessionFile,
   OrgUser,
   OrgMembership,
@@ -98,6 +100,33 @@ export abstract class FmodeApi {
    */
   abstract renameAgent(agentId: string, displayName: string): Promise<Agent | null>;
 
+  // ---------- 容器开通(2026-11-25) ----------
+
+  /**
+   * 发起开通任务。
+   *
+   * 🔴 后端 `fmode-provisioning` 只负责「受理」:建记录 → 建 Matrix 身份 →
+   *    DM 主容器。真正的 docker run 由主容器异步执行,
+   *    **是否成功以 `fetchProvisionStatus` 的服务端核验为准**。
+   *
+   * `planCode` 为 `trial` / `starter` 时返回 `mode: 'onboarding'`(不建容器);
+   * 为 `advanced` / `enterprise` 时返回 `mode: 'provision'` + `jobId`。
+   */
+  abstract startProvision(req: {
+    planCode: string;
+    containerName: string;
+    idempotencyKey: string;
+  }): Promise<ProvisionStartResult>;
+
+  /** 查开通任务状态(服务端实时核验容器记录 / Matrix / 心跳) */
+  abstract fetchProvisionStatus(jobId: string): Promise<ProvisionStatus>;
+
+  /** 重试同一任务(不新建记录) */
+  abstract retryProvision(jobId: string): Promise<ProvisionStartResult>;
+
+  /** 当前用户的开通任务列表 */
+  abstract listProvisions(): Promise<ProvisionStatus[]>;
+
   // ---------- 会话(Matrix) ----------
 
   /** 开通 Matrix 身份(云函数 RP5Ht55NeX);绑定表命中时 `cached: true` */

+ 68 - 7
src/app/core/api/mock-api.ts

@@ -1,12 +1,6 @@
 import { Injectable } from '@angular/core';
 import { environment } from '../../../environments/environment';
 import { FmodeApi } from './fmode-api';
-import {
-  DEMO_AGENTS,
-  DEMO_DELIVERABLES,
-  DEMO_ME,
-  DEMO_TASKS,
-} from './demo-data';
 import {
   Agent,
   ArtifactJob,
@@ -18,16 +12,24 @@ import {
   FileEntry,
   MatrixProvision,
   Me,
-  SessionFile,
   OrgMembership,
   OrgUser,
   OrgUserPage,
+  ProvisionStartResult,
+  ProvisionStatus,
+  SessionFile,
   Task,
   UploadTicket,
   WorkGroup,
   WorkspaceRecord,
   WorkspaceUpsert,
 } from './models';
+import {
+  DEMO_AGENTS,
+  DEMO_DELIVERABLES,
+  DEMO_ME,
+  DEMO_TASKS,
+} from './demo-data';
 
 /**
  * 演示数据源实现(`environment.useMockData === true` 时启用)
@@ -116,6 +118,65 @@ export class MockApi extends FmodeApi {
     return { ...found, name };
   }
 
+  // ---------- 容器开通(2026-11-25) ----------
+  /*
+   * 🔴 Mock 只模拟**受理**,不模拟「容器建好」。
+   *
+   * 真实开通依赖 R730 上真实 docker run,Mock 环境没有这个能力,
+   * 伪造一个 ready 会让人误以为链路通了。因此:
+   *   · 试用/入门 → 返回 onboarding(与真实一致,本来就是提示词)
+   *   · 进阶/企业 → 返回 provisioning,状态永远停在 provisioning
+   *     (要看到真正的 ready,必须连真实后端)
+   */
+
+  private readonly mockProvisionJobs = new Map<string, ProvisionStatus>();
+
+  async startProvision(req: {
+    planCode: string;
+    containerName: string;
+    idempotencyKey: string;
+  }): Promise<ProvisionStartResult> {
+    await this.delay();
+    if (req.planCode === 'trial' || req.planCode === 'starter') {
+      return {
+        mode: 'onboarding',
+        message: '该档位使用你自己的容器,请复制接入提示词到容器内执行。',
+        instruction:
+          '【接入提示词】\n1. 在 App「我的容器」中填写你的容器信息\n' +
+          '2. 平台会为你创建 Matrix 身份与房间\n3. 在本容器内执行平台给出的配置命令',
+      };
+    }
+    const jobId = 'MOCK-JOB-' + this.mockProvisionJobs.size;
+    const status: ProvisionStatus = {
+      jobId,
+      planCode: req.planCode,
+      status: 'provisioning',
+      stage: 'container',
+      createdAt: new Date().toISOString(),
+      updatedAt: new Date().toISOString(),
+    };
+    this.mockProvisionJobs.set(jobId, status);
+    return { mode: 'provision', jobId, status: 'provisioning' };
+  }
+
+  async fetchProvisionStatus(jobId: string): Promise<ProvisionStatus> {
+    await this.delay();
+    const found = this.mockProvisionJobs.get(jobId);
+    if (!found) throw new Error('任务不存在');
+    return found;
+  }
+
+  async retryProvision(jobId: string): Promise<ProvisionStartResult> {
+    await this.delay();
+    if (!this.mockProvisionJobs.has(jobId)) throw new Error('任务不存在');
+    return { mode: 'provision', jobId, status: 'provisioning' };
+  }
+
+  async listProvisions(): Promise<ProvisionStatus[]> {
+    await this.delay();
+    return Array.from(this.mockProvisionJobs.values());
+  }
+
   // ---------- Matrix ----------
 
   async provisionMatrix(agentId: string): Promise<MatrixProvision> {

+ 177 - 0
src/app/core/api/models.ts

@@ -920,3 +920,180 @@ export interface ChatThreadUpsert {
   /** 重新出现时撤销软删 */
   revive?: boolean;
 }
+
+// ============================================================
+// 套餐与开通(2026-11-25 第一期:仅前端展示与申请意向)
+// ============================================================
+
+/**
+ * 套餐档位。
+ *
+ * 🔴 **这是纯前端展示模型,不是服务端 DTO**。
+ *    平台侧的 `fmode-subscription` / `fmode-provisioning` 云函数尚未实现
+ *    (见 `docs/03-interface/api/套餐与平台异步开通-API契约.md` §一.4),
+ *    因此前端**无法**得知用户真实已开通哪个套餐。
+ */
+export type PlanCode = 'trial' | 'starter' | 'advanced' | 'enterprise';
+
+/**
+ * 付费套餐档位(目录里的三项)。
+ *
+ * `trial` 是试用,走独立横幅,不在 `catalog` 里 —— 用这个更窄的类型
+ * 可以让 TS 在编译期拦住「对 trial 调 `planOf()`」这类错误。
+ */
+export type PaidPlanCode = Exclude<PlanCode, 'trial'>;
+
+/** 套餐目录项(权益矩阵的一行) */
+export interface PlanCatalogItem {
+  code: PaidPlanCode;
+  /** 完整名称(桌面端用) */
+  name: string;
+  /** 简称(移动端窄列用) */
+  shortName: string;
+  /** 一句话定位 */
+  tagline: string;
+  /** 基础容器数 */
+  quota: number;
+  /** 配额单位文案,如「个容器」「个共享」 */
+  quotaLabel: string;
+  /** 计费周期,空串表示不展示 */
+  billingUnit: string;
+  /** 计费说明,如「含一年资源费用」 */
+  billingNote: string;
+  /** 权益明细(桌面端列表) */
+  features: string[];
+  /** 移动端配额行文案 */
+  mobileQuota: string;
+  /** 移动端权益行文案 */
+  mobileBenefit: string;
+  /** 是否推荐 */
+  recommended?: boolean;
+  /** 是否允许付费增配 */
+  addonAllowed: boolean;
+}
+
+/**
+ * 申请状态。
+ *
+ * 🔴 本期**只有两态**:`none` 未提交 / `pending` 已提交待人工确认。
+ *    **没有 `active`** —— 服务端未实现开通,前端不得伪造「已开通」。
+ */
+export type PlanApplicationStatus = 'none' | 'pending';
+
+/** 一条套餐申请意向(本地记录,待人工确认) */
+export interface PlanApplication {
+  planCode: PlanCode;
+  /** 提交时刻(ISO) */
+  submittedAt: string;
+  /** 是否为增配申请 */
+  addon?: number;
+}
+
+// ---------- 容器开通(2026-11-25) ----------
+
+/** 开通任务五状态(PRD FR-30) */
+export type ProvisionStatusValue = 'queued' | 'provisioning' | 'verifying' | 'ready' | 'failed';
+
+/** 开通受理结果 */
+export interface ProvisionStartResult {
+  /** `onboarding` = 该档位用用户自己的容器,只返回接入提示词 */
+  mode: 'onboarding' | 'provision';
+  /** `mode: 'provision'` 时的任务 id */
+  jobId?: string;
+  agentId?: string;
+  status?: ProvisionStatusValue;
+  /** `mode: 'onboarding'` 时的接入提示词 */
+  message?: string;
+  instruction?: string;
+}
+
+/** 服务端核验明细(只用于诊断,不直接展示给用户) */
+export interface ProvisionVerifyDetail {
+  record?: boolean;
+  matrix?: boolean;
+  heartbeat?: boolean;
+  detail?: {
+    status?: string;
+    heartbeatAgeSec?: number;
+    roomId?: string;
+    recordError?: string;
+    matrixError?: string;
+  };
+}
+
+/** 开通任务状态 */
+export interface ProvisionStatus {
+  jobId: string;
+  agentId?: string;
+  planCode?: string;
+  status: ProvisionStatusValue;
+  stage?: string;
+  matrixInfo?: {
+    agentMxId?: string;
+    userMxId?: string;
+    roomId?: string;
+    homeserver?: string;
+  };
+  /** 面向用户的失败说明(不含内部术语) */
+  error?: string | null;
+  /** 稳定失败原因码,前端可据此给不同引导 */
+  reasonCode?:
+    | 'R730_UNREACHABLE'
+    | 'CONTAINER_STAGE_FAILED'
+    | 'PROVISION_TIMEOUT'
+    | 'CONTAINER_NOT_READY'
+    | 'QUOTA_EXCEEDED'
+    | 'MATRIX_SETUP_FAILED'
+    | null;
+  /** 是否值得重试(通道抖动可重试;配额满不可) */
+  retryable?: boolean | null;
+  /** 失败发生在哪个阶段 */
+  failedStage?: string | null;
+  /** 本任务专用的 Matrix 房间(一任务一房间,不是 matrixInfo.roomId) */
+  jobRoomId?: string | null;
+  /**
+   * Agent 写进 `FmodeProvisionStep` 的完整阶段流水。
+   *
+   * 🔴 **只用于展示真实进度,不参与成败判定**:
+   *    容器是否可用只认 `verify` 的三项服务端核验。
+   */
+  steps?: ProvisionStep[];
+  /** 当前正在做的阶段(最后一条 running,否则最后一条) */
+  currentStep?: ProvisionStep | null;
+  verify?: ProvisionVerifyDetail | null;
+  createdAt?: string;
+  updatedAt?: string;
+}
+
+/**
+ * 容器开通的一个阶段记录(对应 Parse 的 `FmodeProvisionStep`)。
+ *
+ * 由主容器在每进入/完成一个阶段时写入,云函数读出后原样下发。
+ */
+export interface ProvisionStep {
+  stage?: ProvisionStage | null;
+  status?: ProvisionStepStatus | null;
+  /** 人话描述,如「写 .env / 清残留 / 改 SOUL」 */
+  step?: string | null;
+  /** 关键证据,如 `docker ps` 那一行 */
+  evidence?: string | null;
+  reasonCode?: string | null;
+  elapsedSec?: number | null;
+  agentId?: string | null;
+  /** 写入时间(ISO) */
+  at?: string | null;
+}
+
+export type ProvisionStage = 'prepare' | 'copy' | 'configure' | 'create' | 'verify';
+
+export type ProvisionStepStatus = 'running' | 'ok' | 'failed' | 'warn';
+
+/** 主容器按 `container-provision-job` 技能输出的结果块 */
+export interface ProvisionAgentReport {
+  status?: 'READY' | 'FAILED' | 'PARTIAL';
+  stage?: string;
+  agentId?: string;
+  errors?: string[];
+  warnings?: string[];
+  elapsedSec?: number;
+}

+ 57 - 0
src/app/core/api/parse-api.spec.ts

@@ -695,6 +695,63 @@ describe('ParseApi', () => {
       expect(me.roles).toEqual([]);
     });
   });
+
+  /*
+   * 🔴 入口层坏后端抖动重试(2026-11-24 实测石锤)。
+   *
+   * server.fmode.cn 的 HAProxy 后端池约半数坏实例,对**有效** token 随机返回:
+   *   /api/functions → 401「无效的 sessionToken」(实测同一新 session 1s 内 401/200/401 交替)
+   *   /parse/**      → 403「unauthorized」、301→:7460
+   * 用户侧表现 =「重新登录也没用」。rawFetch 对 401/403 有限重试(最多 4 次),
+   * 全部失败才视为真失败(真过期的最终语义不变)。
+   */
+  describe('入口层坏后端抖动重试(2026-11-24)', () => {
+    it('/api/functions 两次 401 后 200 → 成功,共调用 3 次', async () => {
+      stubFetch([
+        { status: 401, body: { error: '认证失败', message: '无效的 sessionToken' } },
+        { status: 401, body: { error: '认证失败', message: '无效的 sessionToken' } },
+        { body: { code: 200, agents: [] } },
+      ]);
+      const agents = await api.fetchAgents();
+      expect(agents).toEqual([]);
+      expect(calls.length).toBe(3);
+      expect(calls[0].url).toContain('/api/functions');
+    });
+
+    it('/api/functions 连续 4 次 401 → 视为真过期,抛「登录已失效」', async () => {
+      stubFetch([{ status: 401, body: { error: '认证失败' } }]);
+      await expectAsync(api.fetchAgents()).toBeRejectedWithError(/登录已失效/);
+      expect(calls.length).withContext('重试上限 4 次,全失败才抛').toBe(4);
+    });
+
+    it('/parse GET 403 后 200 → 重试成功', async () => {
+      stubFetch([
+        { status: 403, body: { error: 'unauthorized' } },
+        { body: { objectId: 'u1', nickname: '我' } },
+        { body: { results: [] } },
+      ]);
+      const me = await api.fetchMe('r:tok');
+      expect(me.id).toBe('u1');
+      expect(calls.length).withContext('403 一次 + 重试 users/me + roles').toBe(3);
+    });
+
+    it('非幂等 /parse POST(登录)401 不重试,失败语义不变', async () => {
+      stubFetch([{ status: 401, body: { code: 101, error: 'Invalid username/password.' } }]);
+      await expectAsync(api.loginWithPassword('u', 'p')).toBeRejected();
+      expect(calls.length).withContext('POST 不在抖动重试范围(/api/functions 除外)').toBe(1);
+    });
+
+    it('/api/functions 两次 500 后 200 → 成功(坏后端新形态,2026-11-24 午后实测 500/200 交替)', async () => {
+      stubFetch([
+        { status: 500, body: 'Internal Server Error' },
+        { status: 500, body: 'Internal Server Error' },
+        { body: { code: 200, agents: [] } },
+      ]);
+      const agents = await api.fetchAgents();
+      expect(agents).toEqual([]);
+      expect(calls.length).toBe(3);
+    });
+  });
 });
 
 /**

+ 143 - 8
src/app/core/api/parse-api.ts

@@ -7,27 +7,29 @@ import { PlatformProxyService } from './platform-proxy.service';
 import {
   Agent,
   AgentStatus,
-  ChatThreadRecord,
-  ChatThreadUpsert,
-  WorkspaceRecord,
-  WorkspaceUpsert,
   Artifact,
   ArtifactJob,
   AuthSession,
   ChannelConfig,
+  ChatThreadRecord,
+  ChatThreadUpsert,
   Deliverable,
   DeliverableGroup,
   FileEntry,
   MatrixProvision,
   Me,
-  SessionFile,
   OrgMembership,
   OrgUser,
   OrgUserPage,
+  ProvisionStartResult,
+  ProvisionStatus,
+  SessionFile,
   Task,
   UploadTicket,
-  WorkGroup,
   UsageSession,
+  WorkGroup,
+  WorkspaceRecord,
+  WorkspaceUpsert,
 } from './models';
 
 /**
@@ -117,6 +119,8 @@ const FN = {
    *    未部署时该调用会 404,页面显示错误态而不是空白。
    */
   orgUsers: 'mgR4EA2n5a',
+  /** 容器开通(2026-11-25 新建,Function.name = fmode-provisioning) */
+  provisioning: 'VtW1GT93Ax',
 } as const;
 
 /** 兼容「已是对象」与「是 JSON 字符串」两种形态 */
@@ -147,6 +151,17 @@ export class ParseApi extends FmodeApi {
      * 缺省参数保证单测/旧调用方无需改动。
      */
     private readonly proxy: PlatformProxyService = new PlatformProxyService(),
+    /**
+     * 会话失效回调(2026-11-27)
+     *
+     * 服务端返回 401 时调用,由 `SessionService.expire()` 接管
+     * (清登录态 + 通知根组件跳登录页)。
+     *
+     * 🔴 为什么用回调而不是 `inject(SessionService)`:
+     *    本类走的是**函数式依赖注入**(`readToken` / `readScope`),
+     *    直接 `inject` 会打破这个约定,也容易在单测里引入真实依赖。
+     */
+    private readonly onUnauthorized: () => void = () => {},
   ) {
     super();
   }
@@ -401,6 +416,56 @@ export class ParseApi extends FmodeApi {
     return mapAgent(d.agent as Record<string, unknown>);
   }
 
+  // ---------- 容器开通(2026-11-25) ----------
+
+  /**
+   * 发起开通任务。
+   *
+   * `trial` / `starter` → 后端返回 `mode: 'onboarding'`(接入提示词,不建容器)
+   * `advanced` / `enterprise` → 后端建记录 + Matrix + DM 主容器,返回 `jobId`
+   *
+   * 🔴 返回 `provision` 时**不代表容器已建好**,必须轮询 `fetchProvisionStatus`。
+   */
+  async startProvision(req: {
+    planCode: string;
+    containerName: string;
+    idempotencyKey: string;
+  }): Promise<ProvisionStartResult> {
+    const d = await this.callFunction<ProvisionStartResult & { code: number; mess?: string }>(
+      FN.provisioning,
+      { op: 'start', ...req },
+    );
+    if (d.code !== 200) throw new Error(pickMessage(d) ?? `开通请求失败(${d.code})`);
+    return d;
+  }
+
+  async fetchProvisionStatus(jobId: string): Promise<ProvisionStatus> {
+    const d = await this.callFunction<ProvisionStatus & { code: number; mess?: string }>(
+      FN.provisioning,
+      { op: 'status', jobId },
+    );
+    if (d.code !== 200) throw new Error(pickMessage(d) ?? `查询开通状态失败(${d.code})`);
+    return d;
+  }
+
+  async retryProvision(jobId: string): Promise<ProvisionStartResult> {
+    const d = await this.callFunction<ProvisionStartResult & { code: number; mess?: string }>(
+      FN.provisioning,
+      { op: 'retry', jobId },
+    );
+    if (d.code !== 200) throw new Error(pickMessage(d) ?? `重试失败(${d.code})`);
+    return d;
+  }
+
+  async listProvisions(): Promise<ProvisionStatus[]> {
+    const d = await this.callFunction<{ code: number; items?: ProvisionStatus[] }>(
+      FN.provisioning,
+      { op: 'list' },
+    );
+    if (d.code !== 200) throw new Error(pickMessage(d) ?? '查询开通任务失败');
+    return Array.isArray(d.items) ? d.items : [];
+  }
+
   // ---------- Matrix ----------
 
   async provisionMatrix(agentId: string): Promise<MatrixProvision> {
@@ -1130,6 +1195,15 @@ export class ParseApi extends FmodeApi {
         );
       }
       if (res.status === 401) {
+        /*
+         * 🔴 2026-11-27:401 必须触发全局登出 + 跳登录页。
+         *
+         * 原来只抛一句错误文本,上层 catch 后显示「登录已失效」——
+         * 但**页面不跳转**,用户停在原地反复失败,不知道要重新登录。
+         *
+         * 现在通知 SessionService 清登录态,由根组件统一跳转。
+         */
+        this.onUnauthorized();
         throw new Error('登录已失效,请重新登录。');
       }
       throw new Error(`云函数调用失败(HTTP ${res.status})`);
@@ -1194,7 +1268,7 @@ export class ParseApi extends FmodeApi {
     return { 'Content-Type': 'application/json' };
   }
 
-  private rawFetch(url: string, init: RequestInit): Promise<Response> {
+  private async rawFetch(url: string, init: RequestInit): Promise<Response> {
     /*
      * 🔴 **默认不带任何 `X-Parse-*` 头**,只有 Parse REST 白名单才带。
      *
@@ -1253,7 +1327,68 @@ export class ParseApi extends FmodeApi {
      *    代理不可用时 `resolve()` 原样返回,行为与改动前一致。
      *    详见 `platform-proxy.service.ts` 与 `docs/05-operations/平台代理部署.md`。
      */
-    return fetch(this.proxy.resolve(url), { ...init, headers });
+    const target = this.proxy.resolve(url);
+    /*
+     * 🔴 入口层坏后端抖动重试(2026-11-24 实测石锤)。
+     *
+     * server.fmode.cn 的 HAProxy 后端池有约半数坏实例,对**有效** token 也随机拒绝:
+     *   · `/api/functions` → HTTP 401「无效的 sessionToken」
+     *     (实测:全新 session 先经 /parse/users/me 验证有效,1 秒内调 functions
+     *      出现 401/200/401 交替 —— 用户侧表现为「重新登录也没用」)
+     *   · `/parse/**`      → HTTP 403「unauthorized」、301→:7460(已下线)
+     *   · 同日午后观测到新形态:`/api/functions` → HTTP 500 随机抖动
+     *     (8 连打实测 500/200 交替,约 3/8 失败)
+     *
+     * 特征 =「同一请求重试会在成功/失败间跳变」。因此对 401/403/500 做有限次重试:
+     * **全部失败才视为真失败**(真过期/真无权限/真服务异常的最终语义不变,最多慢 ~2.5s)。
+     *
+     * 作用范围:幂等请求(GET/HEAD)+ `/api/functions` POST
+     * (functions 的 401 发生在网关鉴权层,云函数并未执行,重试无重复副作用)。
+     */
+    const flakyZone = /\/parse(\/|$)/.test(target) || /\/api\/functions(\/|$)/.test(target);
+    const method = (init.method ?? 'GET').toUpperCase();
+    const idempotent = method === 'GET' || method === 'HEAD';
+    const attempts = flakyZone && (idempotent || target.includes('/api/functions')) ? 4 : 1;
+    const delays = [300, 700, 1500];
+    let last: Response | null = null;
+    for (let i = 0; i < attempts; i++) {
+      let res: Response;
+      try {
+        res = await fetch(target, { ...init, headers });
+      } catch (e) {
+        /*
+         * 网络错误的一种已知形态:坏后端把 /parse/** 301 到已下线的 :7460,
+         * 浏览器跟随重定向后连接被拒,表现为 fetch 直接抛错。
+         * 幂等请求同样重试(POST /api/functions 的网络重试由 callFunction 负责)。
+         */
+        if (idempotent && attempts > 1 && i < attempts - 1) {
+          await new Promise((r) => setTimeout(r, delays[i] ?? 1500));
+          continue;
+        }
+        throw e;
+      }
+      if (res.status !== 401 && res.status !== 403 && res.status !== 500) return res;
+      last = res;
+      if (i < attempts - 1) {
+        await new Promise((r) => setTimeout(r, delays[i] ?? 1500));
+      }
+    }
+
+    /*
+     * 🔴 重试全部失败后仍是 401 → 视为**真过期**,触发全局登出(2026-11-27)。
+     *
+     * 为什么放在重试之后:上面注释说明了入口层有坏后端会随机 401
+     * (实测 401/200 交替)。**只有重试 4 次全失败**才是真过期,
+     * 放在重试之前会把正常的网络抖动误判成登出。
+     *
+     * 排除项:
+     *   · 登录接口本身(`/login`)失败是密码错误,不是会话过期
+     *   · 已经登出时 `expire()` 幂等,重复调用无害
+     */
+    if (last && last.status === 401 && !/\/login(\/|\?|$)/.test(target)) {
+      this.onUnauthorized();
+    }
+    return last as Response;
   }
 }
 

+ 58 - 0
src/app/core/chat-session.service.spec.ts

@@ -799,5 +799,63 @@ describe('ChatSessionService', () => {
       await svc2.hydrateFromCloud(AGENT);
       expect(svc2.listFor(AGENT).map((s) => s.id)).withContext('云端没有的应被移除').toEqual(['$a']);
     });
+
+    it('🔴 首屏合并:同组容器 10 秒内的重复 reloadAll 不再重复拉(2026-11-24)', async () => {
+      /*
+       * 请求风暴收尾:桌面左栏/消息页/抽屉等多处首屏几乎同时触发 reloadAll,
+       * per-agent 在途复用拦不住「前一批刚完成、下一处又发起」的串行重复。
+       * 现在同一组容器 10 秒内成功拉过就直接跳过。
+       */
+      const fetchChatThreads = jasmine.createSpy('fetchChatThreads').and.resolveTo([]);
+      const svc2 = withApi({ fetchChatThreads, upsertChatThreads: async () => undefined });
+
+      await svc2.reloadAll(['a1', 'a2']);
+      const firstRound = fetchChatThreads.calls.count();
+      expect(firstRound).withContext('每容器 2 条(活跃 + 已删)').toBe(4);
+
+      await svc2.reloadAll(['a2', 'a1']); // 顺序不同、集合相同 → 同键
+      expect(fetchChatThreads.calls.count()).withContext('10 秒内同键跳过').toBe(firstRound);
+    });
+
+    it('🔴 首屏合并:force 绕过去重窗口(用户显式刷新必须真的拉)', async () => {
+      const fetchChatThreads = jasmine.createSpy('fetchChatThreads').and.resolveTo([]);
+      const svc2 = withApi({ fetchChatThreads, upsertChatThreads: async () => undefined });
+
+      await svc2.reloadAll(['a1']);
+      await svc2.reloadAll(['a1'], { force: true });
+      expect(fetchChatThreads.calls.count()).toBe(4);
+    });
+
+    it('🔴 首屏合并:全部失败不记时间戳,重试不被去抖卡死', async () => {
+      let calls = 0;
+      const svc2 = withApi({
+        fetchChatThreads: async () => {
+          calls++;
+          throw new Error('boom');
+        },
+        upsertChatThreads: async () => undefined,
+      });
+      await svc2.reloadAll(['a1']);
+      expect(svc2.ready()).toBeFalse();
+      await svc2.reloadAll(['a1']);
+      expect(calls).withContext('失败后立即重试必须真实发起').toBe(4);
+    });
+
+    it('🔴 首屏合并:容器集合增长(逐个 ready)时只拉新增容器', async () => {
+      /*
+       * 首屏容器是逐个 matrixReady 的,reloadAll 的入参集合一直在变
+       * ('a1' → 'a1,a2' → 'a1,a2,a3'…)。集合级去重一轮都拦不住;
+       * 按容器记成功时间戳后,TTL 内只真拉新增的容器。
+       */
+      const fetchChatThreads = jasmine.createSpy('fetchChatThreads').and.resolveTo([]);
+      const svc2 = withApi({ fetchChatThreads, upsertChatThreads: async () => undefined });
+
+      await svc2.reloadAll(['a1']);
+      await svc2.reloadAll(['a1', 'a2']);
+      expect(fetchChatThreads.calls.count()).withContext('第二轮只拉新增的 a2').toBe(4);
+      const fetchedAgents = fetchChatThreads.calls.allArgs().map((args) => args[0]);
+      expect(fetchedAgents.filter((a) => a === 'a1').length).toBe(2);
+      expect(fetchedAgents.filter((a) => a === 'a2').length).toBe(2);
+    });
   });
 });

+ 58 - 2
src/app/core/chat-session.service.ts

@@ -57,6 +57,16 @@ export class ChatSessionService {
    *    若声明在方法之后,类字段初始化顺序会让运行时拿到 undefined。
    */
   private readonly hydrating = new Map<string, Promise<number>>();
+  /**
+   * reloadAll 首屏合并(2026-11-24):同键在途复用 + **按容器**记成功时间戳。
+   * 🔴 必须按容器而不是按「id 集合」去重:首屏容器是逐个 matrixReady 的,
+   *    集合一直在变('a' → 'a,b' → 'a,b,c'…),集合级去重一轮都拦不住;
+   *    按容器记「上次拉成功的时间」,TTL 内的容器直接跳过、只拉新增/过期者。
+   * 🔴 同样必须声明在类字段区最前面(见 hydrating 的说明)。
+   */
+  private reloadInflight: Promise<void> | null = null;
+  private reloadInflightKey = '';
+  private readonly agentHydrateOkAt = new Map<string, number>();
   readonly all = this._all.asReadonly();
 
   /** 按 agent 分组的会话(未归档,已排序) */
@@ -528,10 +538,53 @@ export class ChatSessionService {
    * 「对话突然不见了」的顾虑由 UI 层的提示覆盖:部分失败时显式告知用户
    * 哪几个容器没拉到,比整片空白 + 笼统报错更有用。
    */
-  async reloadAll(agentIds: string[]): Promise<void> {
+  async reloadAll(agentIds: string[], opts?: { force?: boolean }): Promise<void> {
     if (!this.api) return;
-    const list = [...new Set(agentIds)].filter(Boolean);
+    /*
+     * 🔴 首屏合并(2026-11-24 请求风暴收尾):
+     *
+     * 桌面左栏、移动消息页/首页/抽屉、群聊深链等多处在首屏几乎同时触发
+     * reloadAll。per-agent 的在途复用(hydrateFromCloud)只能拦「同一时刻
+     * 并发」的重复,拦不住「前一批刚完成、下一处又发起」的串行重复 ——
+     * 实测首屏 8 容器 × 2 请求 × 多轮 = 18~41 次 chatThreads·list。
+     *
+     * 口径(2026-11-24 修正为**按容器**去重,集合级去重拦不住容器逐个 ready):
+     *   · 同一组容器(排序后的 id 集合相同)有在途 reloadAll → 直接复用
+     *   · 每个容器成功拉取后记时间戳,TTL(10 秒)内再次拉到它 → 跳过,
+     *     只真拉「没拉过 / 已过期」的容器;全部被跳过则整个调用短路
+     *   · **拉取失败不记时间戳**:失败容器下一次调用立即真重试,不被去抖卡死
+     *   · 用户显式刷新(重试按钮/下拉刷新/分享接收)传 `force` 绕过
+     */
+    let list = [...new Set(agentIds)].filter(Boolean);
     if (list.length === 0) return;
+    if (!opts?.force) {
+      const now = Date.now();
+      list = list.filter(
+        (a) => now - (this.agentHydrateOkAt.get(a) ?? 0) > ChatSessionService.RELOAD_DEDUPE_MS,
+      );
+      if (list.length === 0) return;
+    }
+    const key = [...list].sort().join(',');
+    if (!opts?.force && this.reloadInflight && this.reloadInflightKey === key) {
+      return this.reloadInflight;
+    }
+    const task = this.doReloadAll(list);
+    this.reloadInflight = task;
+    this.reloadInflightKey = key;
+    try {
+      await task;
+    } finally {
+      if (this.reloadInflight === task) {
+        this.reloadInflight = null;
+        this.reloadInflightKey = '';
+      }
+    }
+  }
+
+  /** reloadAll 的去重窗口:同组容器 10 秒内不重复拉 */
+  private static readonly RELOAD_DEDUPE_MS = 10_000;
+
+  private async doReloadAll(list: string[]): Promise<void> {
     const failures: { agentId: string; reason: string }[] = [];
     let succeeded = 0;
     for (let i = 0; i < list.length; i += 5) {
@@ -547,6 +600,8 @@ export class ChatSessionService {
           });
         } else {
           succeeded++;
+          /* 🔴 按容器记成功时间戳:TTL 内的重复 reloadAll 会跳过它(2026-11-24) */
+          this.agentHydrateOkAt.set(batch[k], Date.now());
         }
       }
     }
@@ -570,6 +625,7 @@ export class ChatSessionService {
     if (succeeded === 0) {
       this._ready.set(false);
       this._error.set(failures[0].reason);
+      /* 🔴 全失败不记成功时间戳(上面只在 succeeded>0 时记):下一次调用立即真重试 */
     } else {
       this._ready.set(true);
       this._error.set(null);

+ 50 - 6
src/app/core/chat.service.ts

@@ -1327,8 +1327,16 @@ export class ChatService {
      * 由 Hermes 内建行为发出,不依赖插件改造。
      */
     this.unbindTurnReaction =
-      this.mx.onTurnReaction?.(rid, (_ok, sender, targetId) => {
+      this.mx.onTurnReaction?.(rid, (_ok, sender, targetId, at) => {
         /* 同 `bindRoomSubscriptions` 的说明:这里不校验全局 `seq` */
+        /*
+         * 🔴 新鲜度门禁(2026-11-24 请求风暴根因修复):
+         * Room.timeline 对「翻页加载的历史事件」同样触发本回调。打开一个
+         * 896 条消息的会话会回放几百个 ✅,每个都触发 live.load(true) →
+         * 实测 120 秒打出 743 次 agentStatus 云函数调用。历史 ✅ 只用于
+         * 收尾标记可以容忍,但绝不能触发云函数刷新——直接整段忽略。
+         */
+        if (!this.isFreshTurnEvent(at)) return;
         /*
          * 必须校验 sender:群聊里 @ 了多个容器时,每个容器各打一个 ✅、
          * 打在同一个 event_id 上。不看 sender 会把 A 的收工当成 B 也收工。
@@ -1358,8 +1366,8 @@ export class ChatService {
           this._turnEndedAfter.set(this.lastAgentMessageId());
           /* ✅ = 本轮真的结束 → 真空期标记清掉(2026-11-14) */
           this._awaitingReplySince.set(0);
-          /* 立刻刷新容器状态,不等 15 秒轮询 */
-          void this.live.load(true);
+          /* 立刻刷新容器状态,不等 15 秒轮询(节流合并,见 requestLiveRefresh) */
+          this.requestLiveRefresh();
         }, 300);
       }) ?? null;
 
@@ -1376,7 +1384,9 @@ export class ChatService {
      *    房间里。只监听当前房间会漏掉后台会话的结束事件(用户实测「回复完了还转很久」)。
      */
     this.unbindTurnStatus =
-      this.mx.onTurnStatus?.((sessionKey, status, sender, evRoomId) => {
+      this.mx.onTurnStatus?.((sessionKey, status, sender, evRoomId, at) => {
+        /* 🔴 新鲜度门禁:历史回放的 turn_status 不触发云函数刷新(2026-11-24 请求风暴根因修复) */
+        if (!this.isFreshTurnEvent(at)) return;
         /* 只认本容器发的(群聊里别的容器也会推) */
         const agentMxId = this._agentMxId();
         if (agentMxId && sender && sender !== agentMxId) return;
@@ -1386,7 +1396,7 @@ export class ChatService {
         const sid = this._sessionIdOfKey(sessionKey) || this._sessionIdOfKey(evRoomId);
         if (status !== 'idle') {
           /* running:立刻刷新,让转圈尽快出现 */
-          void this.live.load(true);
+          this.requestLiveRefresh();
           return;
         }
         /*
@@ -1399,10 +1409,44 @@ export class ChatService {
           this.pulse.clearSessionLocalStartFor([sid]);
           this.pulse.markSessionEnded(sid);
         }
-        void this.live.load(true);
+        this.requestLiveRefresh();
       }) ?? null;
   }
 
+  /** 回合事件新鲜度窗口:超过 2 分钟的历史回放事件不触发任何云函数刷新 */
+  private static readonly TURN_EVENT_FRESH_MS = 120_000;
+  /** live.load 节流:2 秒内多个新鲜事件只拉一次(群聊多容器同时收工的场景) */
+  private static readonly LIVE_REFRESH_THROTTLE_MS = 2000;
+  private lastLiveRefreshAt = 0;
+
+  /**
+   * 事件是否「新鲜」——2026-11-24 请求风暴修复的核心判据。
+   *
+   * Matrix 的 Room.timeline 回调对**翻页加载的历史事件**和**实时到达的事件**
+   * 一视同仁。打开一个几百条消息的会话时,历史里的几百个 ✅/turn_status
+   * 会逐条触发回调;若每条都去拉云函数,一次翻页就是几百次 agentStatus 调用。
+   *
+   * 判据沿用 task-completion-notification.service 的同款口径:
+   * 事件时间戳必须在「现在往前 2 分钟内、且不晚于现在+30s 时钟漂移」。
+   * 时间戳缺失/非法一律视为不新鲜(宁可漏刷新,也不放大请求量)。
+   */
+  private isFreshTurnEvent(at: number | undefined): boolean {
+    if (!at || !Number.isFinite(at)) return false;
+    const now = Date.now();
+    return at <= now + 30_000 && now - at <= ChatService.TURN_EVENT_FRESH_MS;
+  }
+
+  /**
+   * 节流后的容器状态刷新:多个新鲜事件在 2 秒窗口内只触发一次 `live.load(true)`。
+   * (群聊里多个容器几乎同时收工时,各自的事件会把刷新合并成一次。)
+   */
+  private requestLiveRefresh(): void {
+    const now = Date.now();
+    if (now - this.lastLiveRefreshAt < ChatService.LIVE_REFRESH_THROTTLE_MS) return;
+    this.lastLiveRefreshAt = now;
+    void this.live.load(true);
+  }
+
   /**
    * 把容器上报的 sessionKey(`$approot_xxx` 或 `!roomId`)换算成本地会话 id。
    *

+ 161 - 0
src/app/core/container.guard.spec.ts

@@ -0,0 +1,161 @@
+import { TestBed } from '@angular/core/testing';
+import { provideRouter, Router, UrlTree } from '@angular/router';
+import { RouterTestingHarness } from '@angular/router/testing';
+import { FmodeApi } from './api/fmode-api';
+import type { Agent } from './api/models';
+import { queryHasContainer } from './container.guard';
+import { SessionService } from './session.service';
+
+/**
+ * 容器门禁单测(2026-11-27)
+ *
+ * ## 锁住的规则
+ *
+ *   有可用容器 → 放行
+ *   无可用容器 → 重定向到套餐页(带 redirect 参数)
+ *   查询异常   → **放行**(不能把所有人关在门外)
+ *
+ * ## 🔴 为什么专门测「只看 status 会误判」
+ *
+ * 实测:容器掉线后 `status` **不会**变成 `offline`(45 天没心跳仍报 running)。
+ * 所以门禁必须复用 `livenessOf()`,不能只看 `status` 字段。
+ */
+describe('queryHasContainer', () => {
+  function apiWith(agents: Agent[] | Error): FmodeApi {
+    return {
+      fetchAgents: async () => {
+        if (agents instanceof Error) throw agents;
+        return agents;
+      },
+    } as unknown as FmodeApi;
+  }
+
+  /** 构造一个「心跳新鲜」的容器 */
+  function freshAgent(): Agent {
+    return {
+      id: 'a1',
+      name: 'test',
+      status: 'running',
+      heartbeatAgeSec: 60,
+      matrixReady: true,
+    } as Agent;
+  }
+
+  /** 构造一个「45 天没心跳但 status 仍报 running」的容器(真实踩坑场景) */
+  function ghostAgent(): Agent {
+    return {
+      id: 'a2',
+      name: 'ghost',
+      status: 'running',
+      heartbeatAgeSec: 3914610,
+      matrixReady: true,
+    } as Agent;
+  }
+
+  it('有可用容器 → true', async () => {
+    expect(await queryHasContainer(apiWith([freshAgent()]))).toBeTrue();
+  });
+
+  it('一个容器都没有 → false', async () => {
+    expect(await queryHasContainer(apiWith([]))).toBeFalse();
+  });
+
+  it('🔴 心跳过期的容器不算可用(不能只看 status)', async () => {
+    // status 是 running,但 45 天没心跳 —— 必须判为不可用
+    expect(await queryHasContainer(apiWith([ghostAgent()]))).toBeFalse();
+  });
+
+  it('混合场景:只要有一个新鲜的就放行', async () => {
+    expect(await queryHasContainer(apiWith([ghostAgent(), freshAgent()]))).toBeTrue();
+  });
+
+  it('🔴 查询异常 → 放行(不能把所有人关在门外)', async () => {
+    expect(await queryHasContainer(apiWith(new Error('network')))).toBeTrue();
+  });
+});
+
+describe('containerGuard', () => {
+  /** 每个用例替换:无容器 / 有容器 */
+  let agents: Agent[] = [];
+
+  beforeEach(() => {
+    agents = [];
+    TestBed.configureTestingModule({
+      providers: [
+        provideRouter([
+          { path: 'plans', children: [] },
+          { path: '**', children: [] },
+        ]),
+        {
+          provide: FmodeApi,
+          useValue: {
+            fetchAgents: async () => agents,
+          } as unknown as FmodeApi,
+        },
+      ],
+    });
+  });
+
+  it('未登录时放行(交给 authGuard 处理)', async () => {
+    const session = TestBed.inject(SessionService);
+    spyOn(session, 'isLoggedIn').and.returnValue(false);
+
+    const { containerGuard } = await import('./container.guard');
+    const result = await TestBed.runInInjectionContext(() =>
+      containerGuard({} as never, { url: '/mobile/messages' } as never),
+    );
+    expect(result).toBeTrue();
+  });
+
+  it('无容器时重定向到套餐页,并带上 redirect 参数', async () => {
+    agents = [];
+    const session = TestBed.inject(SessionService);
+    spyOn(session, 'isLoggedIn').and.returnValue(true);
+
+    const { containerGuard } = await import('./container.guard');
+    const result = await TestBed.runInInjectionContext(() =>
+      containerGuard({} as never, { url: '/mobile/messages' } as never),
+    );
+
+    expect(result instanceof UrlTree).toBeTrue();
+    const tree = result as UrlTree;
+    expect(tree.toString()).toContain('/plans');
+    expect(tree.toString()).toContain('redirect=');
+  });
+
+  it('🔴 桌面端 URL 也重定向到**顶层** /plans(不能是 /desktop/plans,那个路由已不存在)', async () => {
+    agents = [];
+    const session = TestBed.inject(SessionService);
+    spyOn(session, 'isLoggedIn').and.returnValue(true);
+
+    const { containerGuard } = await import('./container.guard');
+    const result = await TestBed.runInInjectionContext(() =>
+      containerGuard({} as never, { url: '/desktop/chat' } as never),
+    );
+
+    const url = (result as UrlTree).toString();
+    expect(url).toContain('/plans');
+    // 🔴 回归点:曾经返回 /desktop/plans 导致白屏(路由不存在)
+    expect(url).not.toContain('/desktop/plans');
+  });
+
+  it('有可用容器时放行', async () => {
+    agents = [
+      {
+        id: 'a1',
+        name: 'test',
+        status: 'running',
+        heartbeatAgeSec: 60,
+        matrixReady: true,
+      } as Agent,
+    ];
+    const session = TestBed.inject(SessionService);
+    spyOn(session, 'isLoggedIn').and.returnValue(true);
+
+    const { containerGuard } = await import('./container.guard');
+    const result = await TestBed.runInInjectionContext(() =>
+      containerGuard({} as never, { url: '/mobile/messages' } as never),
+    );
+    expect(result).toBeTrue();
+  });
+});

+ 126 - 0
src/app/core/container.guard.ts

@@ -0,0 +1,126 @@
+import { inject } from '@angular/core';
+import { CanActivateFn, Router } from '@angular/router';
+import { livenessOf } from './agent-liveness';
+import { FmodeApi } from './api/fmode-api';
+import { SessionService } from './session.service';
+
+/**
+ * 门禁检查的超时(2026-11-27)
+ *
+ * 守卫是 async 的,resolve 前路由不切换 —— 用户卡在入口页的「正在进入…」。
+ * 8 秒够一次正常查询,超时按放行处理。
+ */
+const GUARD_TIMEOUT_MS = 8000;
+
+/**
+ * 无容器也能进的页面(2026-11-27)
+ *
+ * 这些页面本身就是「引导开通」的一部分,拦掉等于废掉入口:
+ *   · `my-containers`  —— 空状态 + 去开通引导
+ *   · `plan-access`    —— 接入信息页
+ *   · `mine`           —— 个人中心(设置、退出登录等必须能进)
+ */
+const WHITELIST = ['/desktop/my-containers', '/mobile/my-containers', '/desktop/plan-access', '/mobile/plan-access', '/desktop/mine', '/mobile/mine'];
+
+/**
+ * 容器门禁(2026-11-27)
+ *
+ * ## 为什么需要
+ *
+ * 用户实测:新账号登录后能进聊天页,但**一个容器都没有**,
+ * 页面全是空的,用户不知道下一步该做什么。
+ *
+ * 产品规则(用户裁决):
+ *
+ * > **只有完整开通(有可用容器)才能进入聊天等功能页。
+ * > 没有容器或套餐的,只能停留在套餐页 / 开通流程页。**
+ *
+ * ## 判定口径
+ *
+ * 「有没有可用容器」**复用 `agent-liveness.ts` 的 `livenessOf()`**,
+ * 不自己造第二套判定 —— 那个文件收敛了项目里 6 套互相矛盾的实现,
+ * 再写一套就是重蹈覆辙。
+ *
+ * 具体地:任一容器的 `livenessOf(a).online === true` 即放行。
+ *
+ * ## 🔴 失败必须放行
+ *
+ * 查询异常时**返回 true**。理由:容器服务挂了不能把所有人都关在门外,
+ * 否则整个 App 不可用。放行后页面自身的错误态会如实提示。
+ *
+ * ## 与其它守卫的关系
+ *
+ * 必须排在 `authGuard` 之后(`canActivate: [authGuard, containerGuard]`),
+ * 且**不得**挂在 `/plans`、`/provision`、`/login` 上,否则死循环。
+ */
+export const containerGuard: CanActivateFn = async (_route, state) => {
+  const session = inject(SessionService);
+  const api = inject(FmodeApi);
+  const router = inject(Router);
+
+  // 未登录交给 authGuard,这里不重复判
+  if (!session.isLoggedIn()) return true;
+
+  /*
+   * 白名单:这些页面**无容器也能进**(2026-11-27)
+   *
+   * 用户反馈「点『查看我的容器』没效果」—— 因为它是容器相关页面,
+   * 被门禁一并拦回了套餐页。但「我的容器」本来就是给**还没开通**的用户
+   * 看空状态 + 引导开通的地方,拦掉它等于把这个入口废了。
+   */
+  const path = state.url.split('?')[0];
+  if (WHITELIST.some((p) => path === p || path.startsWith(p + '/'))) {
+    return true;
+  }
+
+  const hasContainer = await queryHasContainer(api);
+  if (hasContainer) return true;
+
+  /*
+   * 无可用容器 → 只能去套餐页。
+   *
+   * 用 `redirect` 参数记住用户原本想去哪,开通成功后可以直接回去,
+   * 不用再手动导航(体验上少一步)。
+   *
+   * 🔴 2026-11-27 修:目标必须是**顶层 `/plans`**。
+   *    之前这里按端返回 `/desktop/plans` / `/mobile/plans`,
+   *    但那两个子路由已经提到顶层了 —— 重定向到不存在的路径会**直接白屏**。
+   */
+  return router.createUrlTree(['/plans'], {
+    queryParams: { redirect: state.url },
+  });
+};
+
+/**
+ * 询问服务端「我有没有可用容器」。
+ *
+ * 🔴 判定复用 `livenessOf()`:它综合了心跳新鲜度、Matrix 绑定、
+ *    容器自报状态,是项目里**唯一**权威口径。
+ *
+ * 注意:容器掉线后 `status` **不会**变成 `offline`(实测 45 天没心跳仍报 running),
+ * 所以**不能**只看 `status` 字段。
+ *
+ * ## 🔴 必须有超时(2026-11-27 补)
+ *
+ * 守卫是 **async** 的 —— 它 resolve 之前 Angular **不切换路由**,
+ * 用户看到的就是入口页的「正在进入…」一直转。
+ *
+ * 如果 `fetchAgents()` 因为网络/服务端问题挂住(没有自己的超时),
+ * 用户就会被永久困在入口页,**连登录页都进不去**。
+ *
+ * 因此这里硬性 8 秒超时,超时按「放行」处理 ——
+ * 宁可让用户进去后看到错误态,也不能让他卡在门口。
+ */
+export async function queryHasContainer(api: FmodeApi): Promise<boolean> {
+  try {
+    const timeout = new Promise<never>((_, reject) =>
+      setTimeout(() => reject(new Error('CONTAINER_CHECK_TIMEOUT')), GUARD_TIMEOUT_MS),
+    );
+    const agents = await Promise.race([api.fetchAgents(), timeout]);
+    const now = Date.now();
+    return agents.some((a) => livenessOf(a, now).online);
+  } catch {
+    // 查询失败或超时 → 放行(见文件头「失败必须放行」)
+    return true;
+  }
+}

+ 79 - 1
src/app/core/live.service.spec.ts

@@ -152,10 +152,88 @@ describe('LiveService', () => {
 
       jasmine.clock().tick(15_000);
       expect(apiStub.fetchAgents.calls.count()).toBe(afterStart + 1);
-      jasmine.clock().tick(15_000);
+      // setTimeout 链:等微任务让下一拍排上(数据未变 → 退避到 30s)
+      await Promise.resolve();
+      await Promise.resolve();
+      jasmine.clock().tick(30_000);
       expect(apiStub.fetchAgents.calls.count()).toBe(afterStart + 2);
     });
 
+    it('🔴 安静期退避:数据未变 15s→30s→60s;变化立即复位 15s(2026-11-24 请求量优化)', async () => {
+      jasmine.clock().install();
+      svc.start(); // 首次取数(有数据 = 变化)
+      await Promise.resolve();
+      await Promise.resolve();
+      const n0 = apiStub.fetchAgents.calls.count(); // 1
+
+      // 第 1 拍:15s(数据未变 → 下一拍退避 30s)
+      jasmine.clock().tick(15_000);
+      expect(apiStub.fetchAgents.calls.count()).toBe(n0 + 1);
+      await Promise.resolve();
+      await Promise.resolve();
+
+      // 退避期 30s:15s 时不触发
+      jasmine.clock().tick(15_000);
+      expect(apiStub.fetchAgents.calls.count()).toBe(n0 + 1);
+      jasmine.clock().tick(15_000);
+      expect(apiStub.fetchAgents.calls.count()).toBe(n0 + 2);
+      await Promise.resolve();
+      await Promise.resolve();
+
+      // 再退避到 60s:45s 时不触发
+      jasmine.clock().tick(45_000);
+      expect(apiStub.fetchAgents.calls.count()).toBe(n0 + 2);
+      jasmine.clock().tick(15_000);
+      expect(apiStub.fetchAgents.calls.count()).toBe(n0 + 3);
+      await Promise.resolve();
+      await Promise.resolve();
+
+      // 数据变化 → 复位 15s
+      apiStub.fetchAgents.and.returnValue(
+        Promise.resolve([{ ...AGENTS[0], status: 'error' as const }, AGENTS[1]]),
+      );
+      jasmine.clock().tick(60_000);
+      expect(apiStub.fetchAgents.calls.count()).toBe(n0 + 4);
+      await Promise.resolve();
+      await Promise.resolve();
+      jasmine.clock().tick(15_000);
+      expect(apiStub.fetchAgents.calls.count()).toBe(n0 + 5);
+    });
+
+    it('🔴 标签页隐藏时空转节拍不发请求,回前台立即补一轮(2026-11-24)', async () => {
+      jasmine.clock().install();
+      const hidden = spyOn(svc as unknown as { isPageHidden: () => boolean }, 'isPageHidden').and.returnValue(true);
+      svc.start(); // 首屏仍会取一次(用户正看着页面启动)
+      const n0 = apiStub.fetchAgents.calls.count();
+
+      // 隐藏期推进多个节拍:一次都不再取
+      jasmine.clock().tick(120_000);
+      expect(apiStub.fetchAgents.calls.count()).toBe(n0);
+
+      // 回前台:visibilitychange 触发立即静默补一轮
+      hidden.and.returnValue(false);
+      document.dispatchEvent(new Event('visibilitychange'));
+      expect(apiStub.fetchAgents.calls.count()).toBe(n0 + 1);
+    });
+
+    it('失败轮次按未变退避(故障期不给坏后端加压)', async () => {
+      jasmine.clock().install();
+      svc.start();
+      await Promise.resolve();
+      await Promise.resolve();
+      apiStub.fetchAgents.and.returnValue(Promise.reject(new Error('500 抖动')));
+      const n0 = apiStub.fetchAgents.calls.count();
+
+      jasmine.clock().tick(15_000); // 失败一拍
+      await Promise.resolve();
+      await Promise.resolve();
+      await Promise.resolve();
+      expect(svc.state()).toBe('error');
+      // 失败也退避:下一拍 30s,15s 时不触发
+      jasmine.clock().tick(15_000);
+      expect(apiStub.fetchAgents.calls.count()).toBe(n0 + 1);
+    });
+
     it('🔴 轮询时**不得**回到 loading(否则列表每 15s 闪骨架屏)', async () => {
       jasmine.clock().install();
       svc.start();

+ 77 - 4
src/app/core/live.service.ts

@@ -4,6 +4,11 @@ import { Agent, LoadState } from './api/models';
 
 /** 轮询节拍(《数据访问层设计.md》§五.1:收敛为 1 个轮询器) */
 const POLL_MS = 15_000;
+/**
+ * 安静期退避档数上限(2026-11-24 请求量优化)。
+ * 节拍 = `POLL_MS * 2^level`:15s → 30s → 60s 封顶。
+ */
+const POLL_MAX_LEVEL = 2;
 
 /**
  * 实况服务 —— **全项目唯一的轮询器**
@@ -17,6 +22,16 @@ const POLL_MS = 15_000;
  * 约束:
  *   · 视图层**禁止**自建 `setInterval` 取数(AC-14.2)
  *   · 其它服务**消费**本服务,不得各自轮询
+ *
+ * ## 请求量优化(2026-11-24 用户反馈「/api/functions 请求太多」)
+ *
+ * 轮询是唯一稳态来源(15s×24h ≈ 5760 次/天),两条减量策略:
+ *   ① **安静期退避**:数据连续未变时节拍 15s → 30s → 60s 封顶
+ *      (有变化/手动刷新/回前台立即复位 15s —— 容器跑活时数据每轮都变,
+ *      天然保持快节拍,安静期才省请求)
+ *   ② **标签页隐藏暂停**:`document.hidden` 时空转节拍不发请求,
+ *      回前台立即补一轮静默刷新
+ * 失败轮次按「未变」处理(故障期同样退避,不给坏后端加压)。
  */
 @Injectable({ providedIn: 'root' })
 export class LiveService {
@@ -56,7 +71,16 @@ export class LiveService {
   /** 当前是否在轮询(用于界面提示与单测断言) */
   readonly polling = signal(false);
 
-  private timer: ReturnType<typeof setInterval> | null = null;
+  private timer: ReturnType<typeof setTimeout> | null = null;
+  /**
+   * 安静期退避档(0=15s / 1=30s / 2=60s)。
+   * 数据有变化、手动刷新、回前台时归零。
+   */
+  private backoffLevel = 0;
+  /** 上一轮 load 是否检测到数据变化(驱动退避;失败按未变处理) */
+  private lastChanged = true;
+  /** visibilitychange 监听解注册(stop 时摘除) */
+  private visListener: (() => void) | null = null;
   /** 递增序号:切上下文/并发请求时丢弃过期回包(存量 seq 模式) */
   private seq = 0;
   /** 进行中的首次加载(并发调用共享,避免"加载中"被误判为"不存在") */
@@ -120,6 +144,7 @@ export class LiveService {
       // 数据未变 → 不换引用(避免整列重渲染导致闪烁/滚动跳动)
       if (!sameAgents(this._agents(), agents)) {
         this._agents.set(agents);
+        this.lastChanged = true;
       } else {
         /*
          * 🔴 数据没变也必须让下游「知道又到一轮了」。
@@ -129,6 +154,7 @@ export class LiveService {
          * 这种最常见的翻转会被吞掉。故用独立的轻量信号承载轮次。
          */
         this._tick.update((n) => n + 1);
+        this.lastChanged = false;
       }
       // 区分「空」与「就绪」:空列表是合法但需显示空态的状态(AC-03.4 禁止用空态掩盖失败)
       this._state.set(agents.length === 0 ? 'empty' : 'ready');
@@ -139,11 +165,14 @@ export class LiveService {
       if (my !== this.seq) return;
       this._state.set('error');
       this._error.set(e instanceof Error ? e.message : '实况数据加载失败');
+      /* 失败轮次按「未变」处理:故障期退避,不给坏后端/故障端加压(2026-11-24) */
+      this.lastChanged = false;
     }
   }
 
-  /** 手动刷新(工作台「刷新实况」按钮) */
+  /** 手动刷新(工作台「刷新实况」按钮):同时复位退避节拍 */
   async refresh(): Promise<void> {
+    this.backoffLevel = 0;
     await this.load();
   }
 
@@ -151,8 +180,21 @@ export class LiveService {
   start(): void {
     if (this.timer) return;
     this.polling.set(true);
+    this.backoffLevel = 0;
     void this.load(); // 首屏:非静默,让骨架屏生效
-    this.timer = setInterval(() => void this.load(true), POLL_MS); // 轮询:静默
+    this.schedule(POLL_MS);
+    /*
+     * 🔴 回到前台立刻补一轮(2026-11-24)。
+     *    隐藏期节拍空转(见 onTick),数据可能已落后;可见即静默刷新并复位节拍。
+     */
+    const onVisible = () => {
+      if (this.isPageHidden() || !this.timer) return;
+      this.backoffLevel = 0;
+      void this.load(true);
+      this.schedule(POLL_MS);
+    };
+    document.addEventListener('visibilitychange', onVisible);
+    this.visListener = () => document.removeEventListener('visibilitychange', onVisible);
   }
 
   /**
@@ -161,12 +203,43 @@ export class LiveService {
    */
   stop(): void {
     if (this.timer) {
-      clearInterval(this.timer);
+      clearTimeout(this.timer);
       this.timer = null;
     }
+    if (this.visListener) {
+      this.visListener();
+      this.visListener = null;
+    }
     this.polling.set(false);
   }
 
+  /** 安排下一拍(setTimeout 链:每拍时长随退避档变化,setInterval 做不到) */
+  private schedule(ms: number): void {
+    if (this.timer) clearTimeout(this.timer);
+    this.timer = setTimeout(() => void this.onTick(), ms);
+  }
+
+  private onTick(): void {
+    if (!this.timer) return; // stop 后迟到的回调
+    /* 隐藏期空转节拍:不发请求,保持链条存活(回前台由 visibility 监听立即补数) */
+    if (this.isPageHidden()) {
+      this.schedule(POLL_MS);
+      return;
+    }
+    void this.load(true).then(() => {
+      if (!this.timer) return; // load 期间被 stop
+      this.backoffLevel = this.lastChanged
+        ? 0
+        : Math.min(this.backoffLevel + 1, POLL_MAX_LEVEL);
+      this.schedule(POLL_MS * 2 ** this.backoffLevel);
+    });
+  }
+
+  /** 标签页是否隐藏(抽方法便于单测打桩) */
+  private isPageHidden(): boolean {
+    return typeof document !== 'undefined' && document.hidden;
+  }
+
   /** 复位(退出登录时调用) */
   reset(): void {
     this.stop();

+ 6 - 4
src/app/core/matrix-client.service.ts

@@ -1463,9 +1463,11 @@ export class MatrixClientService implements OnDestroy {
    * 所以收尾判据优先用 reaction;typing 作为辅助。
    *
    * @param cb 收到 ✅/❌ 时回调,参数为 true 表示成功、false 表示失败;
-   *           第二个参数是发 reaction 的 mxid(群聊用来区分是哪个容器收工的)
+   *           第二个参数是发 reaction 的 mxid(群聊用来区分是哪个容器收工的);
+   *           第四个参数是事件时间戳(epoch ms)——历史回放与实时到达都走这里,
+   *           调用方必须自行判新鲜度(2026-11-24 请求风暴修复)
    */
-  onTurnReaction(roomId: string, cb: (ok: boolean, sender: string, targetId: string) => void): () => void {
+  onTurnReaction(roomId: string, cb: (ok: boolean, sender: string, targetId: string, at: number) => void): () => void {
     const c = this.requireClient();
     const handler = (ev: MatrixEvent) => {
       if (ev.getRoomId() !== roomId || ev.getType() !== 'm.reaction') return;
@@ -1482,8 +1484,8 @@ export class MatrixClientService implements OnDestroy {
        *
        * 调用方要用 sender 和「本块对应的 agent」比对,见 `chat.service`。
        */
-      if (key === '✅') cb(true, ev.getSender() ?? '', rel?.event_id ?? '');
-      else if (key === '❌') cb(false, ev.getSender() ?? '', rel?.event_id ?? '');
+      if (key === '✅') cb(true, ev.getSender() ?? '', rel?.event_id ?? '', ev.getTs());
+      else if (key === '❌') cb(false, ev.getSender() ?? '', rel?.event_id ?? '', ev.getTs());
     };
     c.on('Room.timeline' as never, handler as never);
     return () => {

+ 9 - 0
src/app/core/nav-menu.service.ts

@@ -59,6 +59,15 @@ export const NAV_CATALOG: NavItemConfig[] = [
    *    (可见性不是安全边界,服务端另有鉴权。)
    */
   { key: 'admin-users', path: '/admin/users', label: '成员管理', icon: 'fa-users-gear' },
+  /**
+   * 套餐与开通(2026-11-25 第一期)。
+   *
+   * 加进 catalog 后,桌面侧边栏、移动抽屉、两端「自定义菜单」弹窗
+   * 都会自动出现该项,无需分别改三处渲染代码。
+   *
+   * 移动端底部 TabBar 固定 4 项不读本目录,套餐从「我的」页进入。
+   */
+  { key: 'plans', path: '/plans', label: '套餐与开通', icon: 'fa-crown' },
 ];
 
 /** 用户自定义后的单项状态 */

+ 87 - 0
src/app/core/org.guard.spec.ts

@@ -0,0 +1,87 @@
+import { TestBed } from '@angular/core/testing';
+import { Router } from '@angular/router';
+import { provideRouter } from '@angular/router';
+import { FmodeApi } from './api/fmode-api';
+import { orgGuard, queryHasOrg } from './org.guard';
+import { SessionService } from './session.service';
+import { Me } from './api/models';
+
+/**
+ * orgGuard 单测(2026-11-25)
+ *
+ * ## 背景
+ *
+ * 原行为:无组织的用户一律重定向到 `/pending`。
+ * 2026-11-25 用户裁决改为**放行** —— 套餐体系的入门档目标用户正是
+ * 「个人、无企业」的新用户,拦在等待页会让这类用户连套餐入口都进不去。
+ *
+ * 本测试锁住新行为,避免将来被无意改回去。
+ */
+describe('orgGuard', () => {
+  const fakeMe: Me = { id: 'u1', name: '个人用户' } as Me;
+
+  function setup(hasOrg: boolean | Error) {
+    TestBed.resetTestingModule();
+    TestBed.configureTestingModule({
+      providers: [
+        provideRouter([]),
+        // FmodeApi 是抽象类(由 provideFmodeApi 工厂提供),测试里给一个最小替身
+        { provide: FmodeApi, useValue: { fetchOrgMembership: () => Promise.resolve({ hasOrg }) } },
+      ],
+    });
+
+    const session = TestBed.inject(SessionService);
+    spyOn(session, 'isLoggedIn').and.returnValue(true);
+    spyOn(session, 'me').and.returnValue(fakeMe);
+
+    const api = TestBed.inject(FmodeApi);
+    spyOn(api, 'fetchOrgMembership').and.callFake(() =>
+      hasOrg instanceof Error
+        ? Promise.reject(hasOrg)
+        : Promise.resolve({ hasOrg } as never),
+    );
+
+    return { session, api };
+  }
+
+  /** 以路由上下文调用 orgGuard */
+  const runGuard = (url = '/mobile/messages') =>
+    TestBed.runInInjectionContext(() =>
+      (orgGuard as unknown as (r: unknown, s: { url: string }) => Promise<unknown>)(
+        {},
+        { url },
+      ),
+    );
+
+  it('未登录时直接放行,交给 authGuard 处理', async () => {
+    const { session } = setup(true);
+    (session.isLoggedIn as unknown as jasmine.Spy).and.returnValue(false);
+    expect(await runGuard()).toBeTrue();
+  });
+
+  it('有组织的用户放行', async () => {
+    setup(true);
+    expect(await runGuard()).toBeTrue();
+  });
+
+  it('🔴 无组织的个人用户也放行(2026-11-25 裁决)', async () => {
+    setup(false);
+    expect(await runGuard()).toBeTrue();
+  });
+
+  it('查询失败时放行(fail-open,不把所有人卡住)', async () => {
+    setup(new Error('网络错误'));
+    expect(await runGuard('/mobile/plans')).toBeTrue();
+  });
+
+  it('queryHasOrg 查询失败按「有组织」处理', async () => {
+    const { api } = setup(new Error('boom'));
+    const result = await queryHasOrg(api);
+    expect(result).toBeTrue();
+  });
+
+  it('queryHasOrg 如实返回服务端的 hasOrg', async () => {
+    const { api } = setup(false);
+    expect(await queryHasOrg(api)).toBeFalse();
+  });
+});

+ 17 - 2
src/app/core/org.guard.ts

@@ -2,7 +2,6 @@ import { inject } from '@angular/core';
 import { CanActivateFn, Router } from '@angular/router';
 import { FmodeApi } from './api/fmode-api';
 import { SessionService } from './session.service';
-
 /** 无组织用户停留的等待页路径 */
 export const PENDING_PATH = '/pending';
 
@@ -40,7 +39,23 @@ export const orgGuard: CanActivateFn = async (_route, state) => {
 
   const hasOrg = await queryHasOrg(api);
   if (hasOrg) return true;
-  return router.createUrlTree([PENDING_PATH], { queryParams: { redirect: state.url } });
+
+  /*
+   * 🔴 2026-11-25 用户裁决:**个人用户(无企业)也应能使用 App**。
+   *
+   * 原行为:无组织一律重定向到 `/pending`,用户看不到任何主界面。
+   * 问题:套餐体系的入门档目标用户正是「个人、无企业」的新用户,
+   *       拦在等待页会让这类用户连套餐入口都进不去。
+   *
+   * 现行为:放行,由页面自身呈现「个人空间」状态
+   *        (空列表 + 套餐入口),用户可自助查看/申请套餐。
+   *
+   * `/pending` 路由与 `queryHasOrg` 导出**保留** —— 其他地方仍在用,
+   * 且将来若需要「企业邀请待处理」的中间态,仍可复用。
+   */
+  void state;
+  void router;
+  return true;
 };
 
 /**

+ 152 - 0
src/app/core/plan.service.spec.ts

@@ -0,0 +1,152 @@
+import { TestBed } from '@angular/core/testing';
+import { PlanService } from './plan.service';
+import { SessionService } from './session.service';
+import { Me } from './api/models';
+
+/**
+ * PlanService 单测(2026-11-25 第一期)
+ *
+ * 重点守住几条红线:
+ *   · 权益目录与 PRD/定价文档一致(1/1/3/5、48h、2 核 4G)
+ *   · **价格不出现任何金额数字**(AC-21.2)
+ *   · 申请只产生 `pending`,**不存在 `active`**
+ *   · 增配只对进阶/企业开放
+ */
+describe('PlanService', () => {
+  let service: PlanService;
+  let store: Record<string, string>;
+
+  const fakeMe: Me = { id: 'u1', name: '测试用户' } as Me;
+
+  beforeEach(() => {
+    store = {};
+    // 用内存实现替换 localStorage,避免测试互相污染
+    spyOn(window.localStorage, 'getItem').and.callFake((k: string) => store[k] ?? null);
+    spyOn(window.localStorage, 'setItem').and.callFake((k: string, v: string) => {
+      store[k] = v;
+    });
+    spyOn(window.localStorage, 'removeItem').and.callFake((k: string) => {
+      delete store[k];
+    });
+
+    TestBed.configureTestingModule({});
+    const session = TestBed.inject(SessionService);
+    spyOn(session, 'me').and.returnValue(fakeMe);
+    service = TestBed.inject(PlanService);
+  });
+
+  describe('权益目录', () => {
+    it('三档配额为 1 / 3 / 5', () => {
+      const quotas = service.catalog.map((p) => p.quota);
+      expect(quotas).toEqual([1, 3, 5]);
+    });
+
+    it('试用为 1 个容器', () => {
+      expect(service.trial.quota).toBe(1);
+    });
+
+    it('只有进阶与企业支持增配', () => {
+      expect(service.catalog.find((p) => p.code === 'starter')!.addonAllowed).toBeFalse();
+      expect(service.catalog.find((p) => p.code === 'advanced')!.addonAllowed).toBeTrue();
+      expect(service.catalog.find((p) => p.code === 'enterprise')!.addonAllowed).toBeTrue();
+    });
+
+    it('每档都写明 2 核 4G 规格(AC-21.1 逐格一致)', () => {
+      for (const plan of service.catalog) {
+        expect(plan.features.join(' ')).toContain('2 核 4G');
+      }
+    });
+
+    it('进阶含一年资源', () => {
+      const advanced = service.catalog.find((p) => p.code === 'advanced')!;
+      expect(advanced.billingNote).toContain('一年');
+    });
+  });
+
+  describe('价格纪律(AC-21.2)', () => {
+    it('目录文案中不出现任何金额数字', () => {
+      const text = JSON.stringify([
+        ...service.catalog.map((p) => ({ ...p })),
+        service.trial,
+      ]);
+      // 允许出现配额/规格数字(1、3、5、2、4、48),但不允许货币符号与「元/¥」
+      expect(text).not.toMatch(/[¥¥]/);
+      expect(text).not.toMatch(/\d+\s*元/);
+      expect(text).not.toMatch(/[0-9]+(\.[0-9]+)?\s*\/\s*(月|年)\s*[=:]/);
+    });
+
+    it('计费周期只有「/ 月」「/ 年」或空', () => {
+      for (const plan of service.catalog) {
+        expect(['/ 月', '/ 年', '']).toContain(plan.billingUnit);
+      }
+    });
+  });
+
+  describe('申请意向', () => {
+    it('初始未提交', () => {
+      expect(service.application()).toBeNull();
+      expect(service.hasPendingApplication()).toBeFalse();
+    });
+
+    it('提交后状态为待确认,且没有 active 态', () => {
+      service.submitApplication('advanced');
+      expect(service.application()?.planCode).toBe('advanced');
+      expect(service.hasPendingApplication()).toBeTrue();
+      // 类型层面就只有 none / pending —— 这里断言运行时也不出现 active
+      expect(JSON.stringify(service.application())).not.toContain('active');
+    });
+
+    it('appliedPlan 返回目录项而非伪造的已开通权益', () => {
+      service.submitApplication('starter');
+      const applied = service.appliedPlan();
+      expect(applied?.code).toBe('starter');
+      expect(applied?.quota).toBe(1);
+    });
+
+    it('提交写入本地存储,重新实例化后可读回', () => {
+      service.submitApplication('enterprise');
+      const key = 'fmode_plan_apply_u1';
+      expect(store[key]).toBeTruthy();
+      expect(JSON.parse(store[key]).planCode).toBe('enterprise');
+    });
+
+    it('脏数据不会让服务崩溃,视为未提交', () => {
+      store['fmode_plan_apply_u1'] = '{not json';
+      const svc = TestBed.runInInjectionContext(
+        () => new (PlanService as unknown as new () => PlanService)(),
+      );
+      expect((svc as unknown as { application: () => unknown }).application()).toBeNull();
+    });
+
+    it('清空申请后回到未提交', () => {
+      service.submitApplication('starter');
+      service.clearApplication();
+      expect(service.application()).toBeNull();
+    });
+  });
+
+  describe('增配', () => {
+    it('未申请时不能增配', () => {
+      expect(service.requestAddon(1)).toBeFalse();
+    });
+
+    it('入门档不能增配', () => {
+      service.submitApplication('starter');
+      expect(service.requestAddon(1)).toBeFalse();
+    });
+
+    it('进阶档可以增配,累计记录', () => {
+      service.submitApplication('advanced');
+      expect(service.requestAddon(2)).toBeTrue();
+      expect(service.application()?.addon).toBe(2);
+      service.requestAddon(1);
+      expect(service.application()?.addon).toBe(3);
+    });
+
+    it('数量小于 1 时拒绝', () => {
+      service.submitApplication('advanced');
+      expect(service.requestAddon(0)).toBeFalse();
+      expect(service.requestAddon(-1)).toBeFalse();
+    });
+  });
+});

+ 198 - 0
src/app/core/plan.service.ts

@@ -0,0 +1,198 @@
+import { computed, inject, Injectable, signal } from '@angular/core';
+import { PaidPlanCode, PlanApplication, PlanCatalogItem, PlanCode } from './api/models';
+import { SessionService } from './session.service';
+
+/**
+ * 套餐目录与申请意向服务(2026-11-25 第一期)
+ *
+ * ## 🔴 本服务的边界(必读,改之前先看)
+ *
+ * 平台侧 `fmode-subscription` / `fmode-provisioning` 两个云函数**尚未实现**
+ * (`docs/03-interface/api/套餐与平台异步开通-API契约.md` §一.4 明确记录
+ * 「拟新增能力,目前无已核实可调用 ID」)。因此本服务:
+ *
+ *   - ✅ 提供**静态权益目录**(与 PRD-20261125 / 定价文档口径一致)
+ *   - ✅ 记录用户**提交的申请意向**(仅本地,等人工确认)
+ *   - ❌ **不判断**用户是否已开通某套餐(没有服务端来源)
+ *   - ❌ **不伪造** `active` 状态、配额已用数、开通进度、48h 计时
+ *   - ❌ **不调用**任何不存在的接口(宁可显示「待确认」,不臆造成功)
+ *
+ * ## 为什么申请意向存 localStorage
+ *
+ * 服务端没有落库的地方,但用户提交后刷新页面若变回「未提交」,
+ * 会让用户误以为没提交成功而重复操作。本地保留 + UI 明确标注
+ * 「已记录,待人工确认」,是当前唯一不撒谎的做法。
+ *
+ * 接入真实接口后:把 `submitApplication()` 改成调 `subscription/submitApplication`,
+ * 状态改由服务端 `AccessSnapshot` 驱动,本服务的 catalog 部分可继续复用。
+ */
+@Injectable({ providedIn: 'root' })
+export class PlanService {
+  private readonly session = inject(SessionService);
+
+  /**
+   * 权益目录 —— **与原型和定价文档逐字对齐**。
+   *
+   * 对齐依据:`prototypes/fmode-subscription-20261125/app.js` 的 `planCards()`
+   * 与 `docs/01-requirements/prd/定价与权益-20261125-草案.md` §一。
+   *
+   * 🔴 价格一律「待定/咨询」——**不得出现任何金额数字**(用户裁决 + AC-21.2)。
+   */
+  readonly catalog: readonly PlanCatalogItem[] = [
+    {
+      code: 'starter',
+      name: '入门版',
+      shortName: '入门',
+      tagline: '一个专属空间,从这里开始。',
+      quota: 1,
+      quotaLabel: '个容器',
+      billingUnit: '/ 月',
+      billingNote: '支持 1 个容器',
+      features: [
+        '1 个专属容器',
+        '2 核 4G 标准规格',
+        '独立云资源',
+        '完整接入信息',
+        '手机与电脑均可使用',
+      ],
+      mobileQuota: '1 个专属容器 · 2 核 4G',
+      mobileBenefit: '独立云资源 · 含完整接入信息',
+      addonAllowed: false,
+    },
+    {
+      code: 'advanced',
+      name: '进阶版',
+      shortName: '进阶',
+      tagline: '更多空间,接住不同的想法。',
+      quota: 3,
+      quotaLabel: '个容器',
+      billingUnit: '/ 年',
+      billingNote: '含一年资源费用',
+      features: [
+        '3 个专属容器',
+        '2 核 4G 标准规格',
+        '独立云资源与接入信息',
+        '支持加购容器名额',
+      ],
+      mobileQuota: '3 个专属容器 · 2 核 4G',
+      mobileBenefit: '独立云资源 · 支持加购名额',
+      recommended: true,
+      addonAllowed: true,
+    },
+    {
+      code: 'enterprise',
+      name: '企业版',
+      shortName: '企业',
+      tagline: '让整个团队,有序地协作。',
+      quota: 5,
+      quotaLabel: '个共享',
+      billingUnit: '',
+      billingNote: '团队共享',
+      features: [
+        '5 个企业容器',
+        '2 核 4G 标准规格(新容器)',
+        '企业成员管理',
+        '通讯录与容器共享',
+        '支持加购容器名额',
+      ],
+      mobileQuota: '5 个共享容器 · 2 核 4G',
+      mobileBenefit: '成员管理 · 通讯录与容器共享',
+      addonAllowed: true,
+    },
+  ];
+
+  /** 两天试用(独立于付费档位,不占 catalog) */
+  readonly trial = {
+    code: 'trial' as const,
+    name: '两天试用',
+    quota: 1,
+    quotaLabel: '个容器',
+    description: '1 个专属容器,48 小时体验',
+  };
+
+  private readonly _application = signal<PlanApplication | null>(this.readStored());
+
+  /** 当前申请意向(`null` = 未提交) */
+  readonly application = this._application.asReadonly();
+
+  /** 是否已提交过申请(含增配) */
+  readonly hasPendingApplication = computed(() => this._application() !== null);
+
+  /** 已申请的套餐档位(未申请时为 `null`) */
+  readonly appliedPlan = computed<PlanCatalogItem | null>(() => {
+    const app = this._application();
+    if (!app) return null;
+    return this.catalog.find((p) => p.code === app.planCode) ?? null;
+  });
+
+  /** 按 code 查目录项 */
+  planOf(code: PlanCode): PlanCatalogItem | null {
+    return this.catalog.find((p) => p.code === code) ?? null;
+  }
+
+  /**
+   * 提交开通申请意向。
+   *
+   * 🔴 **不发网络请求** —— 服务端尚无该接口。
+   *    只记录本地意向,UI 必须显示「等待人工确认」而非「已开通」。
+   */
+  submitApplication(code: PlanCode): void {
+    const app: PlanApplication = { planCode: code, submittedAt: new Date().toISOString() };
+    this._application.set(app);
+    this.writeStored(app);
+  }
+
+  /**
+   * 提交增配申请意向(仅进阶/企业可增配)。
+   *
+   * 同样只记本地,不调接口、不立即加额度。
+   */
+  requestAddon(quantity: number): boolean {
+    const applied = this.appliedPlan();
+    if (!applied || !applied.addonAllowed || quantity < 1) return false;
+    const current = this._application();
+    if (!current) return false;
+    const app: PlanApplication = { ...current, addon: (current.addon ?? 0) + quantity };
+    this._application.set(app);
+    this.writeStored(app);
+    return true;
+  }
+
+  /** 撤销本地申请意向(用户反悔时用,不是取消已开通的套餐) */
+  clearApplication(): void {
+    this._application.set(null);
+    this.writeStored(null);
+  }
+
+  // ---------- 本地持久化(按用户隔离) ----------
+
+  private storageKey(): string {
+    const uid = this.session.me()?.id ?? 'anon';
+    return `fmode_plan_apply_${uid}`;
+  }
+
+  private readStored(): PlanApplication | null {
+    try {
+      const raw = localStorage.getItem(this.storageKey());
+      if (!raw) return null;
+      const parsed = JSON.parse(raw) as PlanApplication;
+      // 结构校验:脏数据不应让页面崩掉
+      if (!parsed || typeof parsed.planCode !== 'string' || typeof parsed.submittedAt !== 'string') {
+        return null;
+      }
+      if (!['trial', 'starter', 'advanced', 'enterprise'].includes(parsed.planCode)) return null;
+      return parsed;
+    } catch {
+      return null;
+    }
+  }
+
+  private writeStored(app: PlanApplication | null): void {
+    try {
+      if (app) localStorage.setItem(this.storageKey(), JSON.stringify(app));
+      else localStorage.removeItem(this.storageKey());
+    } catch {
+      // localStorage 不可用(隐私模式等)时静默降级:内存态仍然生效
+    }
+  }
+}

+ 292 - 0
src/app/core/provision.service.spec.ts

@@ -0,0 +1,292 @@
+import { TestBed } from '@angular/core/testing';
+import { FmodeApi } from './api/fmode-api';
+import { ProvisionStatus } from './api/models';
+import { ProvisionService } from './provision.service';
+
+/**
+ * ProvisionService 单测(2026-11-25)
+ *
+ * 重点锁住几条红线:
+ *   · 试用/入门 → `onboarding`,**不轮询、不建任务**
+ *   · 进阶/企业 → `provision`,**只有后端说 ready 才是 ready**
+ *   · 失败如实暴露,不吞错
+ *   · 轮询在任务终结后停止
+ */
+describe('ProvisionService', () => {
+  let service: ProvisionService;
+  let api: jasmine.SpyObj<FmodeApi>;
+
+  beforeEach(() => {
+    api = jasmine.createSpyObj<FmodeApi>('FmodeApi', [
+      'startProvision',
+      'fetchProvisionStatus',
+      'retryProvision',
+      'listProvisions',
+    ]);
+    TestBed.configureTestingModule({
+      providers: [{ provide: FmodeApi, useValue: api }],
+    });
+    service = TestBed.inject(ProvisionService);
+  });
+
+  it('初始无任务', () => {
+    expect(service.hasJob()).toBeFalse();
+    expect(service.isRunning()).toBeFalse();
+    expect(service.statusText()).toBe('');
+  });
+
+  describe('试用 / 入门 → onboarding', () => {
+    it('返回接入提示词,不创建任务', async () => {
+      api.startProvision.and.resolveTo({
+        mode: 'onboarding',
+        instruction: '【接入提示词】测试内容',
+      });
+
+      const r = await service.start('trial', '我的容器');
+
+      expect(r?.mode).toBe('onboarding');
+      expect(service.instruction()).toContain('接入提示词');
+      // 🔴 关键:不建任务、不轮询
+      expect(service.hasJob()).toBeFalse();
+      expect(api.fetchProvisionStatus).not.toHaveBeenCalled();
+    });
+
+    it('入门档同样走 onboarding', async () => {
+      api.startProvision.and.resolveTo({ mode: 'onboarding', instruction: 'x' });
+      await service.start('starter', '入门容器');
+      expect(service.hasJob()).toBeFalse();
+    });
+  });
+
+  describe('进阶 → provision', () => {
+    it('受理后进入轮询态,但**不代表已就绪**', async () => {
+      api.startProvision.and.resolveTo({
+        mode: 'provision',
+        jobId: 'JOB-1',
+        agentId: 'AGENT-1',
+        status: 'provisioning',
+      });
+
+      await service.start('advanced', '进阶容器');
+
+      expect(service.hasJob()).toBeTrue();
+      expect(service.isRunning()).toBeTrue();
+      expect(service.isReady()).toBeFalse();
+      expect(service.statusText()).toBe('正在开通');
+    });
+
+    it('只有后端返回 ready 才显示已就绪', async () => {
+      api.startProvision.and.resolveTo({
+        mode: 'provision',
+        jobId: 'JOB-1',
+        status: 'provisioning',
+      });
+      await service.start('advanced', 'x');
+
+      api.fetchProvisionStatus.and.resolveTo({
+        jobId: 'JOB-1',
+        status: 'ready',
+        stage: 'verification',
+      });
+      await service.refresh();
+
+      expect(service.isReady()).toBeTrue();
+      expect(service.statusText()).toBe('已就绪');
+      expect(service.isRunning()).toBeFalse();
+    });
+
+    it('后端说 failed 就显示失败,不粉饰', async () => {
+      api.startProvision.and.resolveTo({
+        mode: 'provision',
+        jobId: 'JOB-1',
+        status: 'provisioning',
+      });
+      await service.start('advanced', 'x');
+
+      api.fetchProvisionStatus.and.resolveTo({
+        jobId: 'JOB-1',
+        status: 'failed',
+        error: '开通超时',
+      });
+      await service.refresh();
+
+      expect(service.isFailed()).toBeTrue();
+      expect(service.statusText()).toBe('开通失败');
+      expect(service.current()?.error).toBe('开通超时');
+    });
+  });
+
+  describe('错误处理', () => {
+    it('开通请求失败时如实写进 error', async () => {
+      api.startProvision.and.rejectWith(new Error('名额已满'));
+      const r = await service.start('advanced', 'x');
+
+      expect(r).toBeNull();
+      expect(service.error()).toBe('名额已满');
+      expect(service.hasJob()).toBeFalse();
+    });
+
+    it('查状态失败不覆盖已有任务', async () => {
+      api.startProvision.and.resolveTo({
+        mode: 'provision',
+        jobId: 'JOB-1',
+        status: 'provisioning',
+      });
+      await service.start('advanced', 'x');
+
+      api.fetchProvisionStatus.and.rejectWith(new Error('网络错误'));
+      await service.refresh();
+
+      expect(service.error()).toBe('网络错误');
+      // 任务仍在,没有被抹掉
+      expect(service.current()?.jobId).toBe('JOB-1');
+    });
+  });
+
+  describe('重试与清理', () => {
+    it('重试调用后端并刷新', async () => {
+      api.startProvision.and.resolveTo({ mode: 'provision', jobId: 'JOB-1', status: 'provisioning' });
+      await service.start('advanced', 'x');
+
+      api.retryProvision.and.resolveTo({ mode: 'provision', jobId: 'JOB-1', status: 'provisioning' });
+      api.fetchProvisionStatus.and.resolveTo({ jobId: 'JOB-1', status: 'provisioning' });
+      await service.retry();
+
+      expect(api.retryProvision).toHaveBeenCalledWith('JOB-1');
+    });
+
+    it('clear 清空全部状态', async () => {
+      api.startProvision.and.resolveTo({ mode: 'provision', jobId: 'JOB-1', status: 'provisioning' });
+      await service.start('advanced', 'x');
+      service.clear();
+
+      expect(service.hasJob()).toBeFalse();
+      expect(service.error()).toBeNull();
+      expect(service.instruction()).toBeNull();
+    });
+  });
+
+  /**
+   * 真实进度展示(2026-11-27)
+   *
+   * 进度来自 Agent 写进 FmodeProvisionStep 的记录,不是估算、不是计时器。
+   */
+  /**
+   * jobId 持久化(2026-11-27)
+   *
+   * 刷新后 `_current` 是 null(内存 signal 归零),靠 localStorage 里的 jobId
+   * 才能把用户送回等待页。写错/漏清会让用户卡在错误态。
+   */
+  describe('jobId 持久化', () => {
+    beforeEach(() => localStorage.removeItem('fmode_active_provision_job'));
+
+    it('start 成功拿到 jobId 时写入 localStorage', async () => {
+      api.startProvision.and.resolveTo({
+        mode: 'provision',
+        jobId: 'job-abc',
+        status: 'provisioning',
+      });
+
+      await service.start('advanced', '我的容器');
+
+      expect(ProvisionService.readPersistedJobId()).toBe('job-abc');
+    });
+
+    it('🔴 start 失败时清掉旧的 jobId(否则会被送回不存在的任务)', async () => {
+      localStorage.setItem('fmode_active_provision_job', 'stale-job');
+      api.startProvision.and.rejectWith(new Error('boom'));
+
+      await service.start('advanced', '我的容器');
+
+      expect(ProvisionService.readPersistedJobId()).toBeNull();
+    });
+
+    it('任务就绪后清掉 jobId(不再把用户送回等待页)', async () => {
+      localStorage.setItem('fmode_active_provision_job', 'job-abc');
+      api.fetchProvisionStatus.and.resolveTo({
+        jobId: 'job-abc',
+        status: 'ready',
+      } as ProvisionStatus);
+
+      await service.resume('job-abc');
+
+      expect(ProvisionService.readPersistedJobId()).toBeNull();
+    });
+
+    it('任务进行中保留 jobId', async () => {
+      api.fetchProvisionStatus.and.resolveTo({
+        jobId: 'job-abc',
+        status: 'provisioning',
+      } as ProvisionStatus);
+
+      await service.resume('job-abc');
+
+      expect(ProvisionService.readPersistedJobId()).toBe('job-abc');
+    });
+
+    it('onboarding(试用档)不写 jobId', async () => {
+      api.startProvision.and.resolveTo({ mode: 'onboarding', instruction: 'hello' });
+
+      await service.start('trial', '我的试用容器');
+
+      expect(ProvisionService.readPersistedJobId()).toBeNull();
+    });
+  });
+
+  describe('真实进度展示', () => {
+    /** 构造一个带 steps 的任务状态 */
+    function withSteps(steps: ProvisionStatus['steps']): ProvisionStatus {
+      return {
+        jobId: 'job-1',
+        status: 'provisioning',
+        steps,
+        currentStep: steps && steps.length ? steps[steps.length - 1] : null,
+      };
+    }
+
+    it('有真实进度时 statusText 显示阶段描述,而不是笼统的「正在开通」', () => {
+      service.current; // 触发依赖
+      (service as unknown as { _current: { set: (v: ProvisionStatus) => void } })._current.set(
+        withSteps([{ stage: 'configure', status: 'running', step: '写 .env / 清残留 / 改 SOUL' }]),
+      );
+
+      expect(service.progressText()).toBe('写 .env / 清残留 / 改 SOUL');
+      expect(service.statusText()).toBe('写 .env / 清残留 / 改 SOUL');
+    });
+
+    it('没有进度记录时降级为笼统文案', () => {
+      (service as unknown as { _current: { set: (v: ProvisionStatus) => void } })._current.set({
+        jobId: 'job-1',
+        status: 'provisioning',
+        steps: [],
+        currentStep: null,
+      });
+
+      expect(service.progressText()).toBe('');
+      expect(service.statusText()).toBe('正在开通');
+    });
+
+    it('completedStages 只数 status=ok 的阶段', () => {
+      (service as unknown as { _current: { set: (v: ProvisionStatus) => void } })._current.set(
+        withSteps([
+          { stage: 'prepare', status: 'ok' },
+          { stage: 'copy', status: 'ok' },
+          { stage: 'configure', status: 'running' },
+          { stage: 'create', status: 'warn' },
+        ]),
+      );
+
+      expect(service.completedStages()).toBe(2);
+    });
+
+    it('已就绪时不显示阶段进度', () => {
+      (service as unknown as { _current: { set: (v: ProvisionStatus) => void } })._current.set({
+        jobId: 'job-1',
+        status: 'ready',
+        steps: [{ stage: 'verify', status: 'ok', step: 'Matrix connected' }],
+      });
+
+      expect(service.statusText()).toBe('已就绪');
+    });
+  });
+});

+ 493 - 0
src/app/core/provision.service.ts

@@ -0,0 +1,493 @@
+import { computed, inject, Injectable, signal } from '@angular/core';
+import { FmodeApi } from './api/fmode-api';
+import { ProvisionStartResult, ProvisionStatus, ProvisionStepStatus } from './api/models';
+
+/**
+ * 开通的五个阶段,**顺序固定**(2026-11-27)
+ *
+ * 与 `cloud/skills/container-provision-job/SKILL.md` 的执行步骤一一对应。
+ * 等待页按这个顺序渲染,未到达的显示为「等待」。
+ */
+const STAGE_ORDER = ['prepare', 'copy', 'configure', 'create', 'verify'] as const;
+
+type StageKey = (typeof STAGE_ORDER)[number];
+
+/** 阶段的用户可见文案(不暴露内部术语) */
+const STAGE_LABEL: Record<StageKey, string> = {
+  prepare: '准备环境',
+  copy: '拷贝模板',
+  configure: '写入配置',
+  create: '创建容器',
+  verify: '连接验证',
+};
+
+/**
+ * 阶段说明(用户可见,**不给内部术语**)
+ *
+ * 🔴 2026-11-27:原来直接渲染 Agent 写的 `step` 原文,
+ *    用户看到的是「targetDir 已清空重建」「.env/SOUL/sessions 已配置」,
+ *    全是技术黑话,看不懂进度到底到哪了。
+ *
+ * 现在用固定文案,只表达"这一阶段在做什么"。
+ * Agent 原文仍保留在 `detail` 字段里供排查,但**不再渲染到界面**。
+ */
+const STAGE_DESC: Record<StageKey, string> = {
+  prepare: '正在准备运行环境',
+  copy: '正在拷贝基础配置',
+  configure: '正在写入你的专属设置',
+  create: '正在创建容器',
+  verify: '正在连接平台',
+};
+
+/** 等待页渲染用的阶段视图 */
+export interface ProvisionStageView {
+  stage: StageKey;
+  label: string;
+  /** `pending` = 还没到这步 */
+  status: ProvisionStepStatus | 'pending';
+  detail: string;
+}
+
+/**
+ * 进行中任务的 localStorage 键(2026-11-27)
+ *
+ * 入口页 `entry.ts` 也读这个键,用来把刷新后的用户送回等待页。
+ * 抽成常量避免两处写死不同的字符串。
+ */
+const ACTIVE_JOB_KEY = 'fmode_active_provision_job';
+
+/**
+ * 容器开通服务(2026-11-25)
+ *
+ * ## 职责
+ *
+ * 把「App 里点开通」接到后端 `fmode-provisioning`,并轮询真实进度。
+ *
+ * ## 🔴 状态真实性(最重要的一条)
+ *
+ * 后端返回 `provisioning` 只代表**受理了**,不代表容器建好了。
+ * 容器是否真的可用,**只认后端 `status` 接口的服务端核验结果**
+ * (容器记录 + Matrix joined + 心跳新鲜三项)。
+ *
+ * 本服务**不自己计时、不自己猜**,后端说什么就是什么。
+ * 主容器的自然语言回报(「建好了」)不参与判断。
+ *
+ * ## 轮询纪律
+ *
+ * 沿用 `LiveService` 的思路:只在有在途任务时轮询,任务终结立即停。
+ * 视图层禁止自建 `setInterval`(AC-14.2)。
+ */
+@Injectable({ providedIn: 'root' })
+export class ProvisionService {
+  private readonly api = inject(FmodeApi);
+
+  /** 当前正在跟踪的任务 */
+  private readonly _current = signal<ProvisionStatus | null>(null);
+  /**
+   * 正在提交的档位(`null` = 没有)。
+   *
+   * 🔴 2026-11-27 修:原来是布尔 `_starting`,导致**所有卡片的按钮一起转**。
+   *    用户点「试用」,三张卡片全变「提交中…」,看起来像全都点了。
+   *    现在记录具体是哪个 planCode,只有那个按钮转。
+   */
+  private readonly _startingPlan = signal<string | null>(null);
+  private readonly _error = signal<string | null>(null);
+  /** 试用/入门档返回的接入提示词 */
+  private readonly _instruction = signal<string | null>(null);
+
+  readonly current = this._current.asReadonly();
+  readonly startingPlan = this._startingPlan.asReadonly();
+  readonly error = this._error.asReadonly();
+  readonly instruction = this._instruction.asReadonly();
+
+  /** 是否有任何提交在进行(全局锁用) */
+  readonly starting = computed(() => this._startingPlan() !== null);
+
+  /** 指定档位是否正在提交(按钮用) */
+  isStarting(planCode: string): boolean {
+    return this._startingPlan() === planCode;
+  }
+
+  readonly hasJob = computed(() => this._current() !== null);
+  readonly isRunning = computed(() => {
+    const s = this._current()?.status;
+    return s === 'queued' || s === 'provisioning' || s === 'verifying';
+  });
+  readonly isReady = computed(() => this._current()?.status === 'ready');
+  readonly isFailed = computed(() => this._current()?.status === 'failed');
+
+  /**
+   * 失败是否值得重试。
+   *
+   * 🔴 后端给出 `retryable` 时以它为准:
+   *    · 通道抖动 / 阶段失败 → true(重试通常就好)
+   *    · 配额满 → false(重试也没用,应引导升级或删容器)
+   * 后端没给(老任务)时保守地允许重试。
+   */
+  readonly canRetry = computed(() => {
+    const job = this._current();
+    if (!job || job.status !== 'failed') return false;
+    return job.retryable !== false;
+  });
+
+  /** 面向用户的失败说明(后端已脱敏,不含内部术语) */
+  readonly failureMessage = computed(() => {
+    const job = this._current();
+    if (!job || job.status !== 'failed') return '';
+    return job.error ?? '开通未完成,请稍后重试。';
+  });
+
+  /**
+   * 主容器的**真实执行进度**(来自 Agent 写进 FmodeProvisionStep 的记录)。
+   *
+   * 🔴 这是「用户能看到的真实进展」,不是估算、不是计时器。
+   *    主容器每进入/完成一个阶段就写一条,我们直接读。
+   *    它不写库时这里是空字符串(降级为按 status 的笼统文案)。
+   */
+  readonly progressText = computed(() => {
+    const job = this._current();
+    if (!job) return '';
+    const step = job.currentStep;
+    if (!step) return '';
+    // 后端给的是人话描述(如「写 .env / 清残留 / 改 SOUL」),直接展示
+    return step.step ?? '';
+  });
+
+  /** 已完成的阶段数(用于进度条) */
+  readonly completedStages = computed(() => {
+    const steps = this._current()?.steps ?? [];
+    return steps.filter((s) => s.status === 'ok').length;
+  });
+
+  /** 面向用户的友好状态文案 —— 有真实进度时优先显示真实进度 */
+  readonly statusText = computed(() => {
+    const job = this._current();
+    if (!job) return '';
+    const progress = this.progressText();
+    switch (job.status) {
+      case 'queued':
+        return '等待开通';
+      case 'provisioning':
+        return progress || '正在开通';
+      case 'verifying':
+        return progress || '即将就绪';
+      case 'ready':
+        return '已就绪';
+      case 'failed':
+        return '开通失败';
+      default:
+        return '未知状态';
+    }
+  });
+
+  private timer: ReturnType<typeof setTimeout> | null = null;
+
+  /**
+   * 发起开通。
+   *
+   * @returns `onboarding` 时把提示词写进 `instruction()`;`provision` 时开始轮询
+   */
+  async start(planCode: string, containerName: string): Promise<ProvisionStartResult | null> {
+    /*
+     * 🔴 防重入(2026-11-27):已在开通中时直接忽略。
+     *
+     * 等待页会全屏锁定,但套餐页的「开通」按钮在跳转前的几十毫秒内
+     * 仍可能被连点。忽略而不是报错 —— 用户本意就是「开一次」。
+     */
+    if (this.isRunning()) return null;
+
+    this._startingPlan.set(planCode);
+    this._error.set(null);
+    /*
+     * 🔴 不清 `_instruction`(2026-11-27 修)
+     *
+     * 原来这里 `set(null)` 会在点「进阶开通」的瞬间**清掉试用档的提示词**,
+     * 用户手上正在复制的参数直接消失。
+     *
+     * 提示词和开通任务是两件独立的事:用户可以先拿提示词,
+     * 再决定要不要开通进阶。两者可以同时存在。
+     */
+    try {
+      const result = await this.api.startProvision({
+        planCode,
+        containerName,
+        // 幂等键:同一次点击重试不会重复建
+        idempotencyKey: `${planCode}-${Date.now()}`,
+      });
+
+      if (result.mode === 'onboarding') {
+        this._instruction.set(result.instruction ?? result.message ?? '');
+        this._current.set(null);
+        return result;
+      }
+
+      if (result.jobId) {
+        this._current.set({
+          jobId: result.jobId,
+          agentId: result.agentId,
+          planCode,
+          status: result.status ?? 'provisioning',
+        });
+        // 🔴 持久化:刷新后入口页据此把用户送回等待页,而不是丢到套餐页
+        this.persistJobId(result.jobId);
+        this.schedulePoll();
+      }
+      return result;
+    } catch (e) {
+      this._error.set(e instanceof Error ? e.message : '开通请求失败');
+      /*
+       * 🔴 启动失败要清掉持久化的 jobId(2026-11-27)
+       *
+       * 否则用户下次进入口页会被送回一个**根本不存在的任务**,
+       * 等待页拉状态 404 → 卡在错误态出不来。
+       */
+      this.persistJobId(null);
+      return null;
+    } finally {
+      this._startingPlan.set(null);
+    }
+  }
+
+  /** 立即查一次状态并推进(用户点「检查进度」时调) */
+  async refresh(): Promise<void> {
+    const job = this._current();
+    if (!job) return;
+    try {
+      const next = await this.api.fetchProvisionStatus(job.jobId);
+      this._current.set(next);
+      // 查询成功即清掉上次的错误,否则失败态会一直粘着
+      this._error.set(null);
+      if (next.status === 'ready' || next.status === 'failed') {
+        this.stopPolling();
+        // 终态 → 清掉持久化的 jobId,入口页不再把用户送回来
+        this.persistJobId(null);
+      } else this.schedulePoll();
+    } catch (e) {
+      this._error.set(e instanceof Error ? e.message : '查询失败');
+    }
+  }
+
+  /** 重试同一任务 */
+  async retry(): Promise<void> {
+    const job = this._current();
+    if (!job) return;
+    try {
+      await this.api.retryProvision(job.jobId);
+      this._error.set(null);
+      await this.refresh();
+    } catch (e) {
+      this._error.set(e instanceof Error ? e.message : '重试失败');
+    }
+  }
+
+  /** 恢复一个已有任务(刷新页面后回等待页用) */
+  async resume(jobId: string): Promise<void> {
+    try {
+      const job = await this.api.fetchProvisionStatus(jobId);
+      this._current.set(job);
+      // 恢复成功即清错,否则上一次失败的错误会一直显示
+      this._error.set(null);
+      if (job.status === 'ready' || job.status === 'failed') {
+        this.persistJobId(null);
+      } else {
+        this.persistJobId(jobId);
+        this.schedulePoll();
+      }
+    } catch (e) {
+      this._error.set(e instanceof Error ? e.message : '任务恢复失败');
+    }
+  }
+
+  /**
+   * 等待页专用:从 URL 的 jobId 恢复并开始轮询。
+   *
+   * 与 `resume()` 的区别:本方法是**幂等**的 —— 已经跟踪同一个 job 时不再重复请求,
+   * 避免等待页 `ngOnInit` 和路由复用各触发一次。
+   *
+   * @param force `true` 时强制重拉(用户点「重新加载」用)。
+   *              🔴 不加这个参数的话,失败后 `_current` 仍是旧值,
+   *                 幂等判断会直接 return,用户点重试没有任何反应。
+   */
+  async resumeFromUrl(jobId: string, opts?: { force?: boolean }): Promise<void> {
+    if (!jobId) return;
+    if (!opts?.force && this._current()?.jobId === jobId) {
+      if (this.isRunning()) this.schedulePoll();
+      return;
+    }
+    await this.resume(jobId);
+  }
+
+  // ---------- jobId 持久化 ----------
+
+  /**
+   * 🔴 把进行中的 jobId 写进 localStorage(2026-11-27)
+   *
+   * 为什么:`_current` 是内存 signal,**刷新就没了**。
+   * 用户在等待页按 F5,入口页会跳 `/mobile/messages` → 被门禁拦回 `/plans`,
+   * 用户以为「开通任务丢了」。
+   *
+   * 存了之后,入口页能在跳转前把用户送回 `/provision?jobId=xxx`。
+   * 任务终结(ready/failed)时清掉,避免下次登录被莫名送回等待页。
+   */
+  private persistJobId(jobId: string | null): void {
+    try {
+      if (jobId) localStorage.setItem(ACTIVE_JOB_KEY, jobId);
+      else localStorage.removeItem(ACTIVE_JOB_KEY);
+    } catch {
+      // 隐私模式 / 存储满:持久化失败不影响主流程
+    }
+  }
+
+  /** 读持久化的 jobId(入口页用) */
+  static readPersistedJobId(): string | null {
+    try {
+      return localStorage.getItem(ACTIVE_JOB_KEY);
+    } catch {
+      return null;
+    }
+  }
+
+  /** 清持久化的 jobId(任务已终结时用) */
+  static clearPersistedJobId(): void {
+    try {
+      localStorage.removeItem(ACTIVE_JOB_KEY);
+    } catch {
+      /* 隐私模式:忽略 */
+    }
+  }
+
+  /**
+   * 查询某个 job 是否仍在进行(入口页用)。
+   *
+   * 🔴 为什么入口页不能只看 localStorage 里"有没有 jobId":
+   *    任务早就 ready 了但没清干净时,用户每次打开 App 都被送回等待页,
+   *    看到的却是「已完成」—— 表现为「容器开通成功了却还在开通页」。
+   *
+   * 查询失败按「未运行」处理:宁可让用户进主界面,也不要卡在等待页。
+   */
+  static async isJobRunning(api: FmodeApi, jobId: string): Promise<boolean> {
+    try {
+      const s = await api.fetchProvisionStatus(jobId);
+      return s.status === 'queued' || s.status === 'provisioning' || s.status === 'verifying';
+    } catch {
+      return false;
+    }
+  }
+
+  /**
+   * 是否处于「锁定态」:开通进行中。
+   *
+   * 🔴 语义:为 true 时**不允许用户离开等待页**。
+   *    与 `isRunning()` 同义,单独命名是为了让调用处读起来像业务意图。
+   */
+  readonly isLocked = computed(() => this.isRunning());
+
+  /**
+   * 五个阶段的固定展示顺序(等待页渲染用)。
+   *
+   * 不直接用后端返回的 `steps`,因为:
+   *   · 后端可能只写了前 3 条,后 2 条要显示为「等待」占位
+   *   · 顺序必须稳定,不能按到达顺序跳
+   */
+  /**
+   * 是否已拿到真实的阶段数据(等待页骨架态判断用)。
+   *
+   * 🔴 为什么需要:`stageList()` **永远返回 5 项**(固定顺序,没到的显示 pending),
+   *    所以不能靠 `stageList().length` 判断有没有数据。
+   *    刚进页面时全是 pending → 显示骨架更诚实,比 5 个空圆圈好看。
+   */
+  readonly hasStepData = computed(() => {
+    const steps = this._current()?.steps ?? [];
+    return steps.length > 0;
+  });
+
+  readonly stageList = computed<ProvisionStageView[]>(() => {
+    const steps = this._current()?.steps ?? [];
+    return STAGE_ORDER.map((stage) => {
+      const hit = steps.filter((s) => s.stage === stage);
+      /*
+       * 🔴 取**最后一条**记录,但要注意 Agent 写入顺序不总是可靠的。
+       *
+       * 实测(2026-11-27):同一阶段可能先写 `verify/ok` 再写 `verify/running`,
+       * 按 createdAt 排最后一条会是 running —— 界面看起来"完成的阶段又回去了"。
+       *
+       * 因此:**只要出现过 ok,就判定该阶段已完成**(完成是不可逆的)。
+       */
+      const hasOk = hit.some((s) => s.status === 'ok');
+      const last = hit.length ? hit[hit.length - 1] : null;
+      const status = hasOk ? 'ok' : ((last?.status ?? 'pending') as ProvisionStageView['status']);
+      return {
+        stage,
+        label: STAGE_LABEL[stage],
+        status,
+        // 用户可见文案用固定描述;Agent 原文不展示
+        detail: status === 'pending' ? '' : STAGE_DESC[stage],
+      };
+    });
+  });
+
+  /**
+   * 预估剩余时间文案。
+   *
+   * 基于**已完成阶段的平均耗时**推算,不是拍脑袋的固定值。
+   * 一个阶段都没完成时返回「正在连接平台…」(不显示假进度)。
+   */
+  /**
+   * 预估剩余时间。
+   *
+   * 🔴 2026-11-27 重写:原来用 `elapsedSec` 求平均,但**后端基本不写这个字段**
+   *    (实测 9 条 step 里 0 条有它)→ 平均耗时算成 0 → 显示「预计还需约 0 秒」。
+   *
+   * 现在改用**阶段计数**的保守估算,不依赖任何后端字段:
+   *   实测整个流程 2-4 分钟,5 个阶段 → 每阶段约 40 秒。
+   *
+   * 一个阶段都没完成时返回空串(模板里 @if 才渲染),
+   * 避免和 progressLabel 重复显示「正在连接平台…」。
+   */
+  readonly etaText = computed(() => {
+    const steps = this._current()?.steps ?? [];
+    const done = steps.filter((s) => s.status === 'ok').length;
+    if (!done) return '';
+
+    const remain = STAGE_ORDER.length - done;
+    if (remain <= 0) return '即将完成…';
+
+    const sec = remain * 40;
+    if (sec < 60) return `预计还需约 ${sec} 秒`;
+    return `预计还需约 ${Math.ceil(sec / 60)} 分钟`;
+  });
+
+  /** 已耗时分钟数(长任务提示用) */
+  readonly elapsedMin = computed(() => {
+    const created = this._current()?.createdAt;
+    if (!created) return 0;
+    const ms = Date.now() - new Date(created).getTime();
+    return Number.isFinite(ms) ? Math.floor(ms / 60000) : 0;
+  });
+
+  /** 清空当前任务(如从失败态开始新一次开通) */
+  clear(): void {
+    this.stopPolling();
+    this._current.set(null);
+    this._error.set(null);
+    this._instruction.set(null);
+  }
+
+  // ---------- 轮询 ----------
+
+  private schedulePoll(): void {
+    this.stopPolling();
+    // 12 秒一次:容器创建通常几分钟,这个频率够用且不至于打爆入口层
+    this.timer = setTimeout(() => {
+      this.timer = null;
+      void this.refresh();
+    }, 12_000);
+  }
+
+  private stopPolling(): void {
+    if (this.timer) {
+      clearTimeout(this.timer);
+      this.timer = null;
+    }
+  }
+}

Einige Dateien werden nicht angezeigt, da zu viele Dateien in diesem Diff geändert wurden.