cc 5 日 前
親
コミット
cac272d772
37 ファイル変更、1502 行追加、93 行削除
  1. 203 0
      .zcode/plans/plan-sess_aed9339d-284f-4610-af4f-990c808b2ec9.md
  2. 36 0
      ai-electron/frontend/src/core/design/ant/btn.less
  3. 12 0
      ai-electron/frontend/src/workbench/api/agent.ts
  4. 4 0
      ai-electron/frontend/src/workbench/api/kb.ts
  5. 62 0
      ai-electron/frontend/src/workbench/components/VisibleScopeField.vue
  6. 86 0
      ai-electron/frontend/src/workbench/constants/visibleScope.ts
  7. 43 4
      ai-electron/frontend/src/workbench/views/agent/entry/index.vue
  8. 71 3
      ai-electron/frontend/src/workbench/views/agent/expert/index.vue
  9. 66 4
      ai-electron/frontend/src/workbench/views/agent/pack/index.vue
  10. 75 4
      ai-electron/frontend/src/workbench/views/agent/skill/index.vue
  11. 70 3
      ai-electron/frontend/src/workbench/views/kb/base/index.vue
  12. 2 2
      ai-electron/frontend/src/workbench/views/kb/doc/index.vue
  13. 23 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/controller/AiAgentController.java
  14. 3 1
      ai-server/src/main/java/com/zsjz/ai/module/ai/controller/AiKnowledgeBaseController.java
  15. 5 18
      ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiExpertDirectory.java
  16. 7 1
      ai-server/src/main/java/com/zsjz/ai/module/ai/domain/AiAgent.java
  17. 7 1
      ai-server/src/main/java/com/zsjz/ai/module/ai/domain/AiKnowledgeBase.java
  18. 7 1
      ai-server/src/main/java/com/zsjz/ai/module/ai/domain/AiScenarioPack.java
  19. 7 1
      ai-server/src/main/java/com/zsjz/ai/module/ai/domain/AiSkill.java
  20. 13 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/domain/bo/AiAgentBo.java
  21. 12 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/domain/bo/AiKnowledgeBaseBo.java
  22. 12 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/domain/bo/AiScenarioPackBo.java
  23. 12 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/domain/bo/AiSkillBo.java
  24. 21 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/domain/vo/AiAgentVo.java
  25. 22 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/domain/vo/AiKnowledgeBaseVo.java
  26. 16 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/domain/vo/AiScenarioPackVo.java
  27. 34 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/domain/vo/AiScopeOptionsVo.java
  28. 16 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/domain/vo/AiSkillVo.java
  29. 10 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/service/IAiKnowledgeBaseService.java
  30. 31 19
      ai-server/src/main/java/com/zsjz/ai/module/ai/service/impl/AiAgentServiceImpl.java
  31. 39 3
      ai-server/src/main/java/com/zsjz/ai/module/ai/service/impl/AiDocumentServiceImpl.java
  32. 42 8
      ai-server/src/main/java/com/zsjz/ai/module/ai/service/impl/AiKnowledgeBaseServiceImpl.java
  33. 34 12
      ai-server/src/main/java/com/zsjz/ai/module/ai/service/impl/AiScenarioPackServiceImpl.java
  34. 30 7
      ai-server/src/main/java/com/zsjz/ai/module/ai/service/impl/AiSkillServiceImpl.java
  35. 223 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/support/VisibleScopeSupport.java
  36. 31 1
      sql/ai_orchestration.sql
  37. 115 0
      sql/ai_visible_scope_20261118.sql

+ 203 - 0
.zcode/plans/plan-sess_aed9339d-284f-4610-af4f-990c808b2ec9.md

@@ -0,0 +1,203 @@
+# 智能体「可见范围」数据权限实施方案(修订)
+
+## 一、背景与目标
+
+bizbuddy 的「智能体」菜单下,以下 5 个功能页都有「可见范围/生效范围」:
+
+| bizbuddy 菜单 | 当前项目对应菜单 | 选项(沿用 bizbuddy) |
+|---|---|---|
+| 小Z配置 | 数剑配置 `/workbench/agent/entry` | 全员 / 本部门 / 仅创建人 |
+| 专家配置 | 专家配置 `/workbench/agent/expert` | 全员 / 本部门 / 仅创建人 |
+| 技能仓库 | 技能仓库 `/workbench/agent/skill` | 公开 / 本部门 / 仅本人 |
+| 场景包 | 场景包 `/workbench/agent/pack` | 公开 / 本部门 / 仅本人 |
+| 知识库管理 | 知识库管理 `/workbench/kb/base` | 公开 / 本部门 / 仅本人 |
+
+当前项目迁移时删除了 `visibleScope/ownerDeptId`,可见口径退化为「内置 or 创建人本人」。本次按 bizbuddy 恢复三档记录级数据权限,并增加一条更严格的规则:
+
+- **超管**(user_id=1 或持有 `superadmin` 角色):可选「全员/公开」「本部门」「仅创建人/仅本人」;
+- **普通用户**:只能选「本部门」或「仅创建人/仅本人」,**不能设置全员/公开**;后端同样拒绝绕过前端直接提交 `'0'` 的请求。
+
+其余决策:
+- 5 个页面全部接入;
+- 表单增加「归属部门」树选择,留空时后端默认取创建人部门;
+- 管理列表也按可见范围过滤,超管看全部;
+- 修改/删除仅创建人或超管可操作。
+
+菜单本身已存在,**不需要新增菜单或权限码**。
+
+## 二、数据模型与 SQL
+
+### 1. 新增字段
+以下 5 张表增加:
+- `owner_dept_id bigint`(归属部门,`perm_dept.dept_id`)
+- `visible_scope char(1) default '0'`(0 全员/公开,1 本部门,2 仅创建人/本人)
+
+表:`ai_entry_agent`、`ai_expert_agent`、`ai_skill`、`ai_scenario_pack`、`ai_knowledge_base`。
+
+### 2. 实体/BO/VO
+- 实体:`AiAgent`(基类,入口/专家共用)、`AiSkill`、`AiScenarioPack`、`AiKnowledgeBase` 增加 `ownerDeptId`、`visibleScope`。
+- BO:`AiAgentBo`(入口/专家共用)、`AiSkillBo`、`AiScenarioPackBo`、`AiKnowledgeBaseBo` 增加同名字段,并加 `@Pattern(regexp = "^$|^[012]$")` 校验。
+- VO:`AiAgentVo`(入口/专家共用)、`AiSkillVo`、`AiScenarioPackVo`、`AiKnowledgeBaseVo` 增加同名字段;另加 `createBy`、`canManage`(Boolean,Service 填充,供前端控制改/删按钮)。
+
+### 3. SQL 脚本
+- 更新 `sql/ai_orchestration.sql` 的 5 张表建表语句,加入两列和注释;修正文件头「去 owner_dept_id/visible_scope」的说明。
+- 新增幂等迁移脚本 `sql/ai_visible_scope_20261118.sql`(无 Flyway,手工执行):
+  1. `add column if not exists` 只加可空列;
+  2. 存量数据按原可见语义回填,避免私有数据被公开:
+     - `ai_entry_agent`:空值统一回填 `'0'`(全局入口);
+     - 其余 4 张表:`is_builtin='1'` → `'0'`,否则 → `'2'`;
+  3. 对 `visible_scope='1'` 且 `owner_dept_id` 为空的行,按 `create_by` 从 `perm_user.dept_id` 回填;
+  4. 最后 `set default '0'` 并补列注释。
+
+## 三、后端统一可见性工具
+
+新增 `ai-server/src/main/java/com/zsjz/ai/module/ai/support/VisibleScopeSupport.java`:
+
+- 常量:`SCOPE_ALL="0"`、`SCOPE_DEPT="1"`、`SCOPE_SELF="2"`。
+- `deptIdOf(userId)`:查 `perm_user.dept_id`。
+- `applyVisible(lqw, scopeCol, ownerDeptCol, createByCol, userId)`:
+  ```
+  visible_scope is null/空/'0'
+  OR (visible_scope='1' AND owner_dept_id = 当前用户部门)
+  OR (visible_scope='2' AND create_by = 当前用户)
+  ```
+  - `userId` 为空时 `1=0`(最严);
+  - 超管不过滤(全量);
+  - 空 `visible_scope` 按公开处理,兼容存量。
+- `visibleTo(scope, ownerDeptId, createBy, userId)`:单条记录判断。
+- `canManage(createBy, userId)` / `requireCanManage(...)`:超管或创建人。
+- `defaultScope(userId)`:超管 `'0'`,普通用户 `'2'`(新数据默认仅自己)。
+- `validateScopeForUser(scope, existingScope, userId)`:
+  - 超管:`0/1/2` 均可;
+  - 普通用户:`'0'` 仅在「原值本来就是 `'0'`」时允许保留(避免编辑管理员设置的全员数据时被迫降级),其余提交 `'0'` 直接抛「普通用户不能设置全员/公开可见」;
+  - `'1'/'2'` 放行。
+- `normalizeScope(scope, fallback)`、`resolveOwnerDeptId(...)`:空值取 fallback;选「本部门」且部门为空时取当前用户部门。
+
+替换当前所有 `is_builtin='1' OR create_by=userId` 口径,涉及:
+- `AiAgentServiceImpl.visibleWrapper`
+- `AiExpertDirectory.visibleWrapper`(Reactor 线程只传 userId,工具内部自行查部门)
+- `AiSkillServiceImpl.buildVisibleWrapper`
+- `AiScenarioPackServiceImpl.queryOptions/visibleTo`
+- `AiKnowledgeBaseServiceImpl.buildVisibleWrapper`
+
+## 四、服务层具体改动
+
+### 1. 智能体 `AiAgentServiceImpl` / `AiExpertDirectory`
+- `queryPageList`:在 `buildQueryWrapper` 上追加可见过滤。
+- `queryById`:专家不可见时抛「不存在或不在你的可见范围内」;入口智能体不做可见过滤(见边界说明)。
+- `updateByBo`、`deleteWithValidByIds`:校验 `canManage(exists.getCreateBy())`。
+- `insertByBo/updateByBo/updateEntryAgent` 的 `applyDefaults`:
+  - 新增:scope 空值取 `defaultScope(当前用户)`,再走 `validateScopeForUser`;
+  - 修改:scope 空值继承原值,再走 `validateScopeForUser`;
+  - `ownerDeptId` 为空时继承原值,选「本部门」仍为空则取当前用户部门。
+- `queryOptions/queryExperts/queryVisibleExperts`:自动使用新口径。
+- `AiExpertDirectory.candidates/visibleExperts/visibleExpert` 自动生效。
+- `AiSessionServiceImpl` 的指定专家校验随目录自动生效。
+
+### 2. 技能 `AiSkillServiceImpl`
+- `queryPageList` 加可见过滤;`queryById` 加可见校验。
+- `updateByBo`、`deleteWithValidByIds` 加 `canManage` 校验。
+- `applyDefaults` 增加 scope/ownerDept 默认值,并调用 `validateScopeForUser`。
+- `buildVisibleWrapper` 改用 `VisibleScopeSupport`。
+- 列表/详情填充 `canManage`。
+
+### 3. 场景包 `AiScenarioPackServiceImpl`
+- `queryPageList` 加可见过滤;`queryById` 加可见校验。
+- `updateByBo`、`deleteWithValidByIds` 加 `canManage` 校验。
+- `applyFields` 增加 scope/ownerDept 默认值与 `validateScopeForUser`。
+- `queryOptions` 与 `visibleTo` 改用统一口径。
+- 列表/详情填充 `canManage`。
+
+### 4. 知识库 `AiKnowledgeBaseServiceImpl`
+- `queryPageList` 加可见过滤;`queryById` 加可见校验。
+- `updateByBo`、`deleteWithValidByIds` 加 `canManage` 校验。
+- `applyDefaults` 增加 scope/ownerDept 默认值与 `validateScopeForUser`。
+- `buildVisibleWrapper` 改用统一口径。
+- `listPublicEnabledKbIds()` 由「`is_builtin='1'`」改为「`visible_scope='0'`(含空值)且启用」,供 MCP 知识检索使用。
+- 新增 `listVisibleKbIds(userId)`,供文档列表按可见知识库过滤。
+- `queryOptions()` 保持全量(健康自检在无登录上下文时调用),前端文档页改用 `/ai/kb/visible-options`。
+
+### 5. 文档读取补齐
+`AiDocumentServiceImpl`:
+- `queryPageList`:传了 `kbId` 时校验该知识库可见;未传时按 `listVisibleKbIds` 过滤。
+- `queryById`、`queryContent`、`queryChunkPage` 增加父知识库可见性校验(复用 `filterVisibleKbIds`);`queryChunkContext` 已有校验,统一改为同一辅助方法。
+
+### 6. 可见范围选项接口
+`AiAgentController` 新增 `GET /ai/agent/scope-options`,返回:
+```json
+{ "superAdmin": true/false, "depts": [ ...部门树... ] }
+```
+- 部门树复用 `PermDeptService.selectDeptTreeListIgnoreDataScope(new SysDeptBo())`(不做数据范围过滤);
+- `superAdmin` 取 `LoginHelper.isSuperAdmin()`,供前端决定是否展示「全员/公开」;
+- 权限:`@SaCheckPermission(value={"ai:agent:query","ai:expert:query","ai:skill:query","ai:pack:query","ai:kb:query"}, mode=SaMode.OR)`。
+- 新增 `AiScopeOptionsVo` 承载返回值。
+
+## 五、前端改动
+
+### 1. 共享组件与常量
+- 新增 `ai-electron/frontend/src/workbench/constants/visibleScope.ts`:
+  - `AGENT_SCOPE_OPTIONS`(全员/本部门/仅创建人)
+  - `RESOURCE_SCOPE_OPTIONS`(公开/本部门/仅本人)
+  - `visibleScopeLabel()`、`normalizeDeptTree()`、`findDeptLabel()`
+  - 选项支持 `disabled?: boolean`
+- 新增 `ai-electron/frontend/src/workbench/components/VisibleScopeField.vue`:
+  - `a-radio-group` + 条件展示的 `a-tree-select`;
+  - props:`scope`、`ownerDeptId`、`deptOptions`、`options`、`showDept`;
+  - emits:`update:scope`、`update:ownerDeptId`;
+  - 部门树兼容 `label`/`name` 字段。
+
+### 2. API
+- `workbench/api/agent.ts`:
+  - `AgentVO` 增加 `visibleScope/ownerDeptId/createBy/canManage`;
+  - 新增 `getAgentScopeOptions()`,返回 `{ superAdmin, depts }`。
+- `workbench/api/kb.ts`:`KnowledgeBaseVO` 增加同名字段。
+
+### 3. 5 个页面统一规则
+`workbench/views/agent/expert/index.vue`、`agent/entry/index.vue`、`agent/skill/index.vue`、`agent/pack/index.vue`、`kb/base/index.vue`:
+
+- 页面加载时调用 `getAgentScopeOptions()`,得到 `deptOptions` 和 `canPublic`(= `superAdmin`)。
+- 可见范围单选项:
+  - 超管:展示全部 3 项;
+  - 普通用户:只展示「本部门」「仅创建人/仅本人」;
+  - 若正在编辑的历史数据 scope 为 `'0'` 且当前用户是普通用户:额外展示一个**禁用**的单选项「全员/公开(仅管理员可设置)」,允许保留原值提交,但不能新选。
+- 新增记录默认:
+  - 超管默认 `'0'`;
+  - 普通用户默认 `'2'`(仅自己/仅本人)。
+- `initFormData` 增加 `visibleScope`、`ownerDeptId`;`toForm`/`handleUpdate` 回填两个字段。
+- 新增/修改表单加入「可见范围」字段;专家/数剑始终展示「归属部门」,技能/场景包/知识库在选「本部门」时展示。
+- 部门树加载失败仅告警,不影响页面保存(归属部门留空时后端兜底)。
+- 卡片/列表增加「可见范围」展示;详情弹窗增加「可见范围/归属部门」。
+- 修改、删除、状态开关按 `record.canManage !== false` 控制;新增/复制不受限。
+
+### 4. 文档与切片页
+`workbench/views/kb/doc/index.vue`:`optionKnowledgeBase()` 改为 `visibleKnowledgeBaseOptions()`,只展示当前用户可见的知识库。
+
+## 六、边界说明
+
+- **数剑配置为全局单例**:可见范围按 bizbuddy 落库并展示,但不参与运行时过滤(否则把入口智能体设为「本部门/仅创建人」会让其他用户无法进入工作台);其保存仍按 `ai:agent:edit` 权限控制,不做创建人校验。专家/技能/场景包/知识库按创建人或超管限制改/删。
+- 超管判定复用 `LoginHelper.isSuperAdmin(userId)`(user_id=1 或持有 `superadmin` 角色),在 Reactor 线程中也可用。
+- 普通用户不能设置 `'0'` 的规则由前后端双重保证:前端不展示可选项,后端 `validateScopeForUser` 拒绝非法提交;编辑历史全员数据时允许保留原值。
+- `is_builtin` 列保留(种子/兼容),但不再作为可见性口径;存量数据在迁移脚本中按原语义转成新 scope。
+- 新数据默认值:超管 `'0'`,普通用户 `'2'`。
+
+## 七、验证
+
+1. **编译/类型检查**
+   - 后端:`mvn -pl ai-server -am -DskipTests compile`
+   - 前端:`cd ai-electron/frontend && pnpm type:check`
+2. **SQL**
+   - 在开发库执行 `sql/ai_visible_scope_20261118.sql`;
+   - 校验 5 张表新增列存在,存量 builtin→'0'、非 builtin→'2'。
+3. **多用户手工验证**
+   - 超管在 5 个页面均能选择全员/公开/本部门/仅自己;
+   - 普通用户 A 在 5 个页面只能看到并选择「本部门」「仅自己」;直接调接口提交 `visibleScope='0'` 被后端拒绝;
+   - 用户 A(部门 D1)新建 3 条不同 scope 的专家/技能/场景包/知识库;用户 B(D1)、用户 C(D2)、超管分别登录:
+     - 管理列表只看到「公开 + 本部门 + 自己创建」的数据;
+     - B 可看到 D1 的「本部门」,C 看不到;
+     - B/C 修改/删除 A 的「本部门」数据被拒绝;超管可改删;
+     - 工作台「指定专家/自动候选」、技能选项、场景包选项、知识库绑定与检索均按 scope 过滤;
+     - 文档与切片页只显示可见知识库及其文档;
+     - 超管在 5 个列表均看到全部数据。
+   - 普通用户编辑历史「全员」数据时,可保留原 `'0'` 不改,但不能把其他数据改成 `'0'`。
+4. **回归**
+   - 数剑配置保存、专家路由、指定专家、会话创建、知识库检索、MCP 公共知识库检索不受影响。

+ 36 - 0
ai-electron/frontend/src/core/design/ant/btn.less

@@ -326,3 +326,39 @@
     }
   }
 }
+
+/**
+ * 主色幽灵按钮:透明底 + 主色文字/描边。
+ *
+ * <p>上面的 `.ant-btn-primary` 会统一设置白色文字;ghost 只把背景置透明,
+ * 不恢复文字颜色,结果白字落在白底上不可见(如工作台「AI 生成」)。
+ * 此处用独立顶层选择器(3 个类)压过 primary 基础规则。
+ */
+.ant-btn.ant-btn-primary.ant-btn-background-ghost {
+  color: @button-primary-color !important;
+  background-color: transparent !important;
+  border-color: @button-primary-color;
+
+  &:hover,
+  &:focus,
+  &:not(:disabled):hover,
+  &:not(:disabled):focus {
+    color: @button-primary-hover-color !important;
+    background-color: transparent !important;
+    border-color: @button-primary-hover-color;
+  }
+
+  &:active,
+  &:not(:disabled):active {
+    color: @button-primary-active-color !important;
+    background-color: transparent !important;
+    border-color: @button-primary-active-color;
+  }
+
+  &[disabled],
+  &[disabled]:hover {
+    color: fade(@button-primary-color, 40%) !important;
+    background-color: transparent !important;
+    border-color: fade(@button-primary-color, 40%) !important;
+  }
+}

+ 12 - 0
ai-electron/frontend/src/workbench/api/agent.ts

@@ -26,10 +26,19 @@ export interface AgentVO {
   toolBindings?: Array<{ toolCode?: string; decision?: string }>;
   kbIds?: Id[];
   skillIds?: Id[];
+  ownerDeptId?: Id;
+  visibleScope?: string;
+  createBy?: Id;
+  canManage?: boolean;
   createTime?: string;
   [key: string]: any;
 }
 
+export interface AgentScopeOptions {
+  superAdmin?: boolean;
+  depts?: any[];
+}
+
 export interface AgentQuery {
   nameKeyword?: string;
   agentCode?: string;
@@ -50,6 +59,9 @@ export function updateEntryAgent(data: any): Promise<void> {
 export function optionAgent(): Promise<AgentVO[]> {
   return aiGet<AgentVO[]>('/ai/agent/options');
 }
+export function getAgentScopeOptions(): Promise<AgentScopeOptions> {
+  return aiGet<AgentScopeOptions>('/ai/agent/scope-options');
+}
 export function optionAgentExperts(): Promise<any[]> {
   return aiGet<any[]>('/ai/agent/experts');
 }

+ 4 - 0
ai-electron/frontend/src/workbench/api/kb.ts

@@ -22,6 +22,10 @@ export interface KnowledgeBaseVO {
   bm25IndexStatus?: string;
   status?: string;
   remark?: string;
+  ownerDeptId?: Id;
+  visibleScope?: string;
+  createBy?: Id;
+  canManage?: boolean;
   [key: string]: any;
 }
 

+ 62 - 0
ai-electron/frontend/src/workbench/components/VisibleScopeField.vue

@@ -0,0 +1,62 @@
+<template>
+  <div class="visible-scope-field">
+    <a-radio-group :value="scope" @update:value="handleScopeChange">
+      <a-radio v-for="item in options" :key="item.value" :value="item.value" :disabled="item.disabled">
+        {{ item.label }}
+      </a-radio>
+    </a-radio-group>
+    <a-tree-select
+      v-if="showDept"
+      :value="ownerDeptId"
+      :tree-data="deptOptions"
+      :field-names="{ label: 'label', value: 'id', children: 'children' }"
+      placeholder="请选择归属部门(留空默认当前部门)"
+      check-strictly
+      allow-clear
+      tree-default-expand-all
+      class="visible-scope-field__dept"
+      @update:value="handleDeptChange"
+    />
+  </div>
+</template>
+
+<script lang="ts" setup name="WorkbenchVisibleScopeField">
+  import { ARadio, ARadioGroup, ATreeSelect } from '@/workbench/components/ant';
+  import type { DeptOption, VisibleScopeOption } from '@/workbench/constants/visibleScope';
+
+  withDefaults(
+    defineProps<{
+      scope?: string;
+      ownerDeptId?: string | number;
+      deptOptions?: DeptOption[];
+      options?: VisibleScopeOption[];
+      showDept?: boolean;
+    }>(),
+    {
+      deptOptions: () => [],
+      options: () => [],
+      showDept: true,
+    },
+  );
+
+  const emit = defineEmits<{
+    (event: 'update:scope', value: string): void;
+    (event: 'update:ownerDeptId', value: string | number | undefined): void;
+  }>();
+
+  const handleScopeChange = (value: any) => emit('update:scope', String(value ?? ''));
+  const handleDeptChange = (value: any) =>
+    emit('update:ownerDeptId', value === undefined || value === null || value === '' ? undefined : value);
+</script>
+
+<style scoped lang="less">
+  .visible-scope-field {
+    display: flex;
+    flex-direction: column;
+    gap: 8px;
+  }
+
+  .visible-scope-field__dept {
+    width: 100%;
+  }
+</style>

+ 86 - 0
ai-electron/frontend/src/workbench/constants/visibleScope.ts

@@ -0,0 +1,86 @@
+/**
+ * 可见范围(记录级数据权限)公共常量与工具。
+ *
+ * 取值与后端一致:0 全员/公开、1 本部门、2 仅创建人/仅本人。
+ * 普通用户不能设置 0(仅超管可设置),前端只展示 1/2 两项;
+ * 编辑历史全员数据时额外展示一个禁用项,允许保留原值。
+ */
+
+export interface VisibleScopeOption {
+  label: string;
+  value: string;
+  disabled?: boolean;
+}
+
+export interface DeptOption {
+  id: string | number;
+  label: string;
+  children?: DeptOption[];
+}
+
+export const AGENT_SCOPE_OPTIONS: VisibleScopeOption[] = [
+  { label: '全员', value: '0' },
+  { label: '本部门', value: '1' },
+  { label: '仅创建人', value: '2' },
+];
+
+export const RESOURCE_SCOPE_OPTIONS: VisibleScopeOption[] = [
+  { label: '公开', value: '0' },
+  { label: '本部门', value: '1' },
+  { label: '仅本人', value: '2' },
+];
+
+/**
+ * 按当前用户身份生成可见范围选项。
+ *
+ * @param options      全量选项
+ * @param canPublic    当前用户是否可设置全员/公开(超管)
+ * @param currentScope 编辑中的记录原值
+ */
+export const scopeOptionsForUser = (
+  options: VisibleScopeOption[],
+  canPublic: boolean,
+  currentScope?: string,
+): VisibleScopeOption[] => {
+  if (canPublic) {
+    return options;
+  }
+  const allowed = options.filter((item) => item.value !== '0');
+  if (currentScope === '0') {
+    const publicOption = options.find((item) => item.value === '0');
+    return publicOption
+      ? [{ ...publicOption, label: `${publicOption.label}(仅管理员可设置)`, disabled: true }, ...allowed]
+      : allowed;
+  }
+  return allowed;
+};
+
+export const visibleScopeLabel = (
+  value: string | undefined,
+  options: VisibleScopeOption[],
+): string => options.find((item) => item.value === value)?.label ?? value ?? '-';
+
+/** 后端部门树(Hutool Tree 使用 name)转 a-tree-select 结构(label/value) */
+export const normalizeDeptTree = (nodes: any[] = []): DeptOption[] =>
+  (nodes ?? []).map((node) => ({
+    id: node.id,
+    label: node.label ?? node.name ?? String(node.id),
+    children: normalizeDeptTree(node.children ?? []),
+  }));
+
+/** 在部门树中查找部门名称 */
+export const findDeptLabel = (nodes: DeptOption[] = [], id?: string | number): string => {
+  if (id === undefined || id === null || id === '') {
+    return '';
+  }
+  for (const node of nodes) {
+    if (String(node.id) === String(id)) {
+      return node.label;
+    }
+    const found = findDeptLabel(node.children ?? [], id);
+    if (found) {
+      return found;
+    }
+  }
+  return '';
+};

+ 43 - 4
ai-electron/frontend/src/workbench/views/agent/entry/index.vue

@@ -104,6 +104,20 @@
           </div>
         </section>
 
+        <section class="entry-section">
+          <h4 class="entry-section-title">可见范围</h4>
+          <div class="entry-grid">
+            <a-form-item label="可见范围" name="visibleScope" class="entry-span-all">
+              <VisibleScopeField
+                v-model:scope="form.visibleScope"
+                v-model:owner-dept-id="form.ownerDeptId"
+                :options="scopeOptions"
+                :dept-options="deptOptions"
+              />
+            </a-form-item>
+          </div>
+        </section>
+
         <section class="entry-section">
           <h4 class="entry-section-title">系统提示词</h4>
           <a-form-item name="sysPrompt" class="entry-no-label">
@@ -169,10 +183,18 @@
     message,
   } from 'ant-design-vue';
   import { Icon } from '@/core/components/Icon';
-  import { getEntryAgent, updateEntryAgent } from '@/workbench/api/agent';
+  import VisibleScopeField from '@/workbench/components/VisibleScopeField.vue';
+  import {
+    AGENT_SCOPE_OPTIONS,
+    normalizeDeptTree,
+    scopeOptionsForUser,
+  } from '@/workbench/constants/visibleScope';
+  import { getAgentScopeOptions, getEntryAgent, updateEntryAgent } from '@/workbench/api/agent';
   import { optionModelConfig } from '@/workbench/api/model';
 
   const modelOptions = ref<any[]>([]);
+  const deptOptions = ref<any[]>([]);
+  const canPublic = ref(false);
   const buttonLoading = ref(false);
   const loaded = ref(false);
   const loading = ref(true);
@@ -192,9 +214,14 @@
     maxIters: 10,
     status: '0',
     remark: undefined as string | undefined,
+    ownerDeptId: undefined as string | number | undefined,
+    visibleScope: undefined as string | undefined,
   };
 
   const form = ref<any>({ ...initFormData });
+  const scopeOptions = computed(() =>
+    scopeOptionsForUser(AGENT_SCOPE_OPTIONS, canPublic.value, form.value.visibleScope),
+  );
 
   const rules: any = computed(() => ({
     agentName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
@@ -203,12 +230,21 @@
   }));
 
   const loadOptions = async () => {
-    const [modelRes] = await Promise.allSettled([optionModelConfig('chat')]);
+    const [modelRes, scopeRes] = await Promise.allSettled([
+      optionModelConfig('chat'),
+      getAgentScopeOptions(),
+    ]);
     if (modelRes.status === 'fulfilled') {
       modelOptions.value = modelRes.value ?? [];
     } else {
       message.warning('模型 选项加载失败,对应下拉暂不可用');
     }
+    if (scopeRes.status === 'fulfilled') {
+      deptOptions.value = normalizeDeptTree(scopeRes.value?.depts ?? []);
+      canPublic.value = !!scopeRes.value?.superAdmin;
+    } else {
+      message.warning('部门 选项加载失败,归属部门暂不可选');
+    }
   };
 
   const loadEntry = async () => {
@@ -222,6 +258,8 @@
       form.value = {
         ...initFormData,
         ...data,
+        visibleScope: data.visibleScope ?? (canPublic.value ? '0' : '2'),
+        ownerDeptId: data.ownerDeptId ?? undefined,
         dailyTokenQuota: data.dailyTokenQuota ?? 0,
         dailyRequestQuota: data.dailyRequestQuota ?? 0,
         monthlyTokenQuota: data.monthlyTokenQuota ?? 0,
@@ -250,8 +288,9 @@
     }
   };
 
-  onMounted(() => {
-    loadOptions();
+  onMounted(async () => {
+    // 先加载可见范围选项,确保 loadEntry 能按当前用户身份选择默认值
+    await loadOptions();
     loadEntry();
   });
 </script>

+ 71 - 3
ai-electron/frontend/src/workbench/views/agent/expert/index.vue

@@ -54,6 +54,7 @@
                     v-model:checked="record.status"
                     checked-value="0"
                     un-checked-value="1"
+                    :disabled="record.canManage === false"
                     :loading="statusLoadingId === record.id"
                     @change="handleStatusChange(record)"
                   />
@@ -71,15 +72,39 @@
                   <span class="expert-card__meta-label">自动路由</span>
                   <span class="expert-card__route">{{ autoRouteLabel(record.autoRoute) }}</span>
                 </div>
+                <div class="expert-card__meta-item">
+                  <span class="expert-card__meta-label">可见范围</span>
+                  <span class="expert-card__meta-value">
+                    {{ visibleScopeLabel(record.visibleScope, AGENT_SCOPE_OPTIONS) }}
+                    <template v-if="record.visibleScope === '1' && record.ownerDeptId">
+                      ({{ findDeptLabel(deptOptions, record.ownerDeptId) }})
+                    </template>
+                  </span>
+                </div>
               </div>
 
               <div class="expert-card__footer">
                 <span class="expert-card__created">创建于 {{ record.createTime || '-' }}</span>
                 <div class="expert-card__actions">
                   <a-button type="link" size="small" @click="handleView(record)">查看</a-button>
-                  <a-button v-auth="'ai:expert:edit'" type="link" size="small" @click="handleUpdate(record)">修改</a-button>
+                  <a-button
+                    v-if="record.canManage !== false"
+                    v-auth="'ai:expert:edit'"
+                    type="link"
+                    size="small"
+                    @click="handleUpdate(record)"
+                    >修改</a-button
+                  >
                   <a-button v-auth="'ai:expert:edit'" type="link" size="small" @click="handleClone(record)">复制</a-button>
-                  <a-button v-auth="'ai:expert:remove'" danger type="link" size="small" @click="handleDelete(record)">删除</a-button>
+                  <a-button
+                    v-if="record.canManage !== false"
+                    v-auth="'ai:expert:remove'"
+                    danger
+                    type="link"
+                    size="small"
+                    @click="handleDelete(record)"
+                    >删除</a-button
+                  >
                 </div>
               </div>
             </article>
@@ -344,6 +369,14 @@
             <a-radio value="1">停用</a-radio>
           </a-radio-group>
         </a-form-item>
+        <a-form-item label="可见范围" name="visibleScope">
+          <VisibleScopeField
+            v-model:scope="form.visibleScope"
+            v-model:owner-dept-id="form.ownerDeptId"
+            :options="scopeOptions"
+            :dept-options="deptOptions"
+          />
+        </a-form-item>
         <a-form-item label="备注">
           <a-textarea v-model:value="form.remark" :rows="2" placeholder="请输入备注" />
         </a-form-item>
@@ -372,6 +405,12 @@
           </a-descriptions-item>
           <a-descriptions-item label="自动路由">{{ autoRouteLabel(detail.record.autoRoute) }}</a-descriptions-item>
           <a-descriptions-item label="长期记忆">{{ memoryEnabledLabel(detail.record.memoryEnabled) }}</a-descriptions-item>
+          <a-descriptions-item label="可见范围">
+            {{ visibleScopeLabel(detail.record.visibleScope, AGENT_SCOPE_OPTIONS) }}
+          </a-descriptions-item>
+          <a-descriptions-item label="归属部门">
+            {{ findDeptLabel(deptOptions, detail.record.ownerDeptId) || '-' }}
+          </a-descriptions-item>
           <a-descriptions-item label="最大迭代次数">{{ detail.record.maxIters ?? '-' }}</a-descriptions-item>
           <a-descriptions-item label="描述" :span="2">{{ detail.record.description || '-' }}</a-descriptions-item>
           <a-descriptions-item label="绑定模型">{{ modelLabel(detail.record) }}</a-descriptions-item>
@@ -456,11 +495,20 @@
   } from 'ant-design-vue';
   import { Icon } from '@/core/components/Icon';
   import { BasicModal } from '@/core/components/Modal';
+  import VisibleScopeField from '@/workbench/components/VisibleScopeField.vue';
+  import {
+    AGENT_SCOPE_OPTIONS,
+    findDeptLabel,
+    normalizeDeptTree,
+    scopeOptionsForUser,
+    visibleScopeLabel,
+  } from '@/workbench/constants/visibleScope';
   import {
     addAgent,
     delAgent,
     generateExpertPrompt,
     getAgent,
+    getAgentScopeOptions,
     listAgent,
     listTrustedTools,
     optionAgentTool,
@@ -479,6 +527,8 @@
   ];
 
   const agentList = ref<any[]>([]);
+  const deptOptions = ref<any[]>([]);
+  const canPublic = ref(false);
   const modelOptions = ref<any[]>([]);
   const toolOptions = ref<any[]>([]);
   const kbOptions = ref<any[]>([]);
@@ -510,6 +560,8 @@
     maxIters: 10,
     status: '0',
     remark: undefined,
+    ownerDeptId: undefined,
+    visibleScope: undefined,
     autoRoute: '1',
     memoryEnabled: '1',
     expertWriteEnabled: '1',
@@ -519,6 +571,9 @@
   };
 
   const form = ref<any>({ ...initFormData });
+  const scopeOptions = computed(() =>
+    scopeOptionsForUser(AGENT_SCOPE_OPTIONS, canPublic.value, form.value.visibleScope),
+  );
   const dialog = reactive({ visible: false, title: '' });
   const detail = reactive<{ visible: boolean; record: any }>({ visible: false, record: null });
 
@@ -597,6 +652,8 @@
     maxIters: row.maxIters,
     status: row.status,
     remark: row.remark,
+    ownerDeptId: row.ownerDeptId ?? undefined,
+    visibleScope: row.visibleScope ?? undefined,
     autoRoute: row.autoRoute ?? '1',
     memoryEnabled: row.memoryEnabled ?? '1',
     expertWriteEnabled: '1',
@@ -616,11 +673,12 @@
   };
 
   const loadOptions = async () => {
-    const [modelRes, toolRes, kbRes, skillRes] = await Promise.allSettled([
+    const [modelRes, toolRes, kbRes, skillRes, scopeRes] = await Promise.allSettled([
       optionModelConfig('chat'),
       optionAgentTool(),
       visibleKnowledgeBaseOptions(),
       visibleSkillOptions(),
+      getAgentScopeOptions(),
     ]);
     const failed: string[] = [];
     const take = (res: PromiseSettledResult<any>, label: string): any[] => {
@@ -632,6 +690,12 @@
     toolOptions.value = take(toolRes, '工具');
     kbOptions.value = take(kbRes, '知识库');
     skillOptions.value = take(skillRes, '技能');
+    if (scopeRes.status === 'fulfilled') {
+      deptOptions.value = normalizeDeptTree(scopeRes.value?.depts ?? []);
+      canPublic.value = !!scopeRes.value?.superAdmin;
+    } else {
+      failed.push('部门');
+    }
     if (failed.length) {
       message.warning(`${failed.join(' / ')} 选项加载失败,对应下拉暂不可用`);
     }
@@ -660,6 +724,7 @@
 
   const handleAdd = () => {
     reset();
+    form.value.visibleScope = canPublic.value ? '0' : '2';
     trustedTools.value = [];
     templateKey.value = undefined;
     dialog.title = '新增专家';
@@ -699,6 +764,9 @@
     cloned.id = undefined;
     cloned.agentCode = undefined;
     cloned.agentName = row.agentName ? `${row.agentName}-副本` : row.agentName;
+    if (!canPublic.value && cloned.visibleScope === '0') {
+      cloned.visibleScope = '2';
+    }
     Object.assign(form.value, cloned);
     dialog.title = '复制专家';
     dialog.visible = true;

+ 66 - 4
ai-electron/frontend/src/workbench/views/agent/pack/index.vue

@@ -58,14 +58,35 @@
                 <a-tag class="cell-tag">业务工具 {{ record.toolBindings?.length || 0 }}</a-tag>
                 <a-tag color="warning" class="cell-tag">MCP 工具 {{ record.mcpToolBindings?.length || 0 }}</a-tag>
                 <a-tag color="success" class="cell-tag">技能 {{ record.skillIds?.length || 0 }}</a-tag>
+                <a-tag class="cell-tag">
+                  可见范围 {{ visibleScopeLabel(record.visibleScope, RESOURCE_SCOPE_OPTIONS) }}
+                  <template v-if="record.visibleScope === '1' && record.ownerDeptId">
+                    ({{ findDeptLabel(deptOptions, record.ownerDeptId) }})
+                  </template>
+                </a-tag>
               </div>
 
               <div class="pack-card__footer">
                 <span class="pack-card__time">更新于 {{ record.updateTime || '-' }}</span>
                 <div class="pack-card__actions">
                   <a-button type="link" size="small" @click="handleView(record)">查看</a-button>
-                  <a-button v-auth="'ai:pack:edit'" type="link" size="small" @click="handleUpdate(record)">修改</a-button>
-                  <a-button v-auth="'ai:pack:remove'" danger type="link" size="small" @click="handleDelete(record)">删除</a-button>
+                  <a-button
+                    v-if="record.canManage !== false"
+                    v-auth="'ai:pack:edit'"
+                    type="link"
+                    size="small"
+                    @click="handleUpdate(record)"
+                    >修改</a-button
+                  >
+                  <a-button
+                    v-if="record.canManage !== false"
+                    v-auth="'ai:pack:remove'"
+                    danger
+                    type="link"
+                    size="small"
+                    @click="handleDelete(record)"
+                    >删除</a-button
+                  >
                 </div>
               </div>
             </article>
@@ -242,12 +263,21 @@
           </a-select>
         </a-form-item>
         <a-form-item name="status">
-          <template #label><span class="wb-label-tip">状态</span></template>
+          <template #label>状态</template>
           <a-radio-group v-model:value="form.status">
             <a-radio value="0">启用</a-radio>
             <a-radio value="1">停用</a-radio>
           </a-radio-group>
         </a-form-item>
+        <a-form-item label="可见范围" name="visibleScope">
+          <VisibleScopeField
+            v-model:scope="form.visibleScope"
+            v-model:owner-dept-id="form.ownerDeptId"
+            :options="scopeOptions"
+            :dept-options="deptOptions"
+            :show-dept="form.visibleScope === '1'"
+          />
+        </a-form-item>
         <a-form-item name="remark">
           <template #label><span class="wb-label-tip">备注</span></template>
           <a-textarea v-model:value="form.remark" :rows="2" placeholder="请输入备注" />
@@ -274,6 +304,12 @@
             </a-tag>
           </a-descriptions-item>
           <a-descriptions-item label="创建人">{{ detail.record.createByName || '-' }}</a-descriptions-item>
+          <a-descriptions-item label="可见范围">
+            {{ visibleScopeLabel(detail.record.visibleScope, RESOURCE_SCOPE_OPTIONS) }}
+          </a-descriptions-item>
+          <a-descriptions-item label="归属部门">
+            {{ findDeptLabel(deptOptions, detail.record.ownerDeptId) || '-' }}
+          </a-descriptions-item>
           <a-descriptions-item label="用途说明" :span="2">{{ detail.record.description || '-' }}</a-descriptions-item>
           <a-descriptions-item label="业务工具" :span="2">
             <template v-if="detail.record.toolBindings?.length">
@@ -344,6 +380,15 @@
   } from '@/workbench/components/ant';
   import { Icon } from '@/core/components/Icon';
   import { BasicModal } from '@/core/components/Modal';
+  import VisibleScopeField from '@/workbench/components/VisibleScopeField.vue';
+  import {
+    findDeptLabel,
+    normalizeDeptTree,
+    RESOURCE_SCOPE_OPTIONS,
+    scopeOptionsForUser,
+    visibleScopeLabel,
+  } from '@/workbench/constants/visibleScope';
+  import { getAgentScopeOptions } from '@/workbench/api/agent';
   import {
     addScenarioPack,
     delScenarioPack,
@@ -367,6 +412,8 @@
   ];
 
   const packList = ref<any[]>([]);
+  const deptOptions = ref<any[]>([]);
+  const canPublic = ref(false);
   const toolOptions = ref<any[]>([]);
   const mcpOptions = ref<any[]>([]);
   const skillOptions = ref<any[]>([]);
@@ -386,6 +433,8 @@
     description: undefined as any,
     status: '0',
     remark: undefined as any,
+    ownerDeptId: undefined as any,
+    visibleScope: undefined as any,
     toolBindings: [] as any[],
     mcpToolBindings: [] as any[],
     skillIds: [] as any[],
@@ -397,6 +446,9 @@
   });
 
   const form = ref<any>({ ...initFormData });
+  const scopeOptions = computed(() =>
+    scopeOptionsForUser(RESOURCE_SCOPE_OPTIONS, canPublic.value, form.value.visibleScope),
+  );
 
   /** 详情弹窗(查看场景包完整信息,只读) */
   const detail = reactive<{ visible: boolean; record: any | null }>({
@@ -493,10 +545,11 @@
 
   /** 加载表单依赖的三类选项(逐项降级:单项失败仅置空该项并汇总警告) */
   const loadOptions = async () => {
-    const [toolRes, mcpRes, skillRes] = await Promise.allSettled([
+    const [toolRes, mcpRes, skillRes, scopeRes] = await Promise.allSettled([
       listTool({ pageNum: 1, pageSize: 200, status: '0' }),
       scenarioPackMcpOptions(),
       visibleSkillOptions(),
+      getAgentScopeOptions(),
     ]);
     const failed: string[] = [];
     if (toolRes.status === 'fulfilled') {
@@ -514,6 +567,12 @@
     } else {
       failed.push('技能');
     }
+    if (scopeRes.status === 'fulfilled') {
+      deptOptions.value = normalizeDeptTree(scopeRes.value?.depts ?? []);
+      canPublic.value = !!scopeRes.value?.superAdmin;
+    } else {
+      failed.push('部门');
+    }
     if (failed.length) {
       message.warning(`以下选项加载失败(可能缺少相应权限):${failed.join('、')}`);
     }
@@ -538,6 +597,7 @@
   /** 新增按钮操作 */
   const handleAdd = () => {
     reset();
+    form.value.visibleScope = canPublic.value ? '0' : '2';
     dialog.title = '新增场景包';
     dialog.visible = true;
   };
@@ -559,6 +619,8 @@
       description: record.description,
       status: record.status ?? '0',
       remark: record.remark,
+      ownerDeptId: record.ownerDeptId ?? undefined,
+      visibleScope: record.visibleScope ?? undefined,
       toolBindings: (record.toolBindings ?? []).map((bind: any) => ({ ...bind })),
       mcpToolBindings: (record.mcpToolBindings ?? []).map((bind: any) => ({ ...bind })),
       skillIds: [...(record.skillIds ?? [])],

+ 75 - 4
ai-electron/frontend/src/workbench/views/agent/skill/index.vue

@@ -64,14 +64,38 @@
                   <span class="skill-card__meta-label">参考资料</span>
                   <span class="skill-card__meta-value">{{ record.resourceCount ?? 0 }} 个</span>
                 </div>
+                <div class="skill-card__meta-item">
+                  <span class="skill-card__meta-label">可见范围</span>
+                  <span class="skill-card__meta-value">
+                    {{ visibleScopeLabel(record.visibleScope, RESOURCE_SCOPE_OPTIONS) }}
+                    <template v-if="record.visibleScope === '1' && record.ownerDeptId">
+                      ({{ findDeptLabel(deptOptions, record.ownerDeptId) }})
+                    </template>
+                  </span>
+                </div>
               </div>
 
               <div class="skill-card__footer">
                 <span class="skill-card__time">更新于 {{ record.updatedAt || '-' }}</span>
                 <div class="skill-card__actions">
                   <a-button type="link" size="small" @click="handlePreview(record)">预览</a-button>
-                  <a-button v-auth="'ai:skill:edit'" type="link" size="small" @click="handleUpdate(record)">修改</a-button>
-                  <a-button v-auth="'ai:skill:remove'" danger type="link" size="small" @click="handleDelete(record)">删除</a-button>
+                  <a-button
+                    v-if="record.canManage !== false"
+                    v-auth="'ai:skill:edit'"
+                    type="link"
+                    size="small"
+                    @click="handleUpdate(record)"
+                    >修改</a-button
+                  >
+                  <a-button
+                    v-if="record.canManage !== false"
+                    v-auth="'ai:skill:remove'"
+                    danger
+                    type="link"
+                    size="small"
+                    @click="handleDelete(record)"
+                    >删除</a-button
+                  >
                 </div>
               </div>
             </article>
@@ -153,6 +177,15 @@
             <a-radio value="1">停用</a-radio>
           </a-radio-group>
         </a-form-item>
+        <a-form-item label="可见范围" name="visibleScope">
+          <VisibleScopeField
+            v-model:scope="form.visibleScope"
+            v-model:owner-dept-id="form.ownerDeptId"
+            :options="scopeOptions"
+            :dept-options="deptOptions"
+            :show-dept="form.visibleScope === '1'"
+          />
+        </a-form-item>
         <a-form-item label="备注">
           <a-textarea v-model:value="form.remark" :rows="2" placeholder="请输入备注" />
         </a-form-item>
@@ -174,6 +207,12 @@
         <a-descriptions-item label="使用计数">{{ preview.row?.useCount ?? 0 }}</a-descriptions-item>
         <a-descriptions-item label="参考资料">{{ preview.row?.resourceCount ?? 0 }} 个</a-descriptions-item>
         <a-descriptions-item label="生命周期">{{ lifecycleLabel(preview.row?.lifecycleState) }}</a-descriptions-item>
+        <a-descriptions-item label="可见范围">
+          {{ visibleScopeLabel(preview.row?.visibleScope, RESOURCE_SCOPE_OPTIONS) }}
+        </a-descriptions-item>
+        <a-descriptions-item label="归属部门">
+          {{ findDeptLabel(deptOptions, preview.row?.ownerDeptId) || '-' }}
+        </a-descriptions-item>
       </a-descriptions>
       <pre class="skill-preview">{{ preview.content }}</pre>
       <div v-if="preview.resources.length" class="preview-resources">
@@ -189,7 +228,7 @@
 </template>
 
 <script lang="ts" setup name="WorkbenchAgentSkill">
-  import { onMounted, reactive, ref } from 'vue';
+  import { computed, onMounted, reactive, ref } from 'vue';
   import {
     AButton,
     ACollapse,
@@ -213,6 +252,15 @@
   } from '@/workbench/components/ant';
   import { Icon } from '@/core/components/Icon';
   import { BasicModal } from '@/core/components/Modal';
+  import VisibleScopeField from '@/workbench/components/VisibleScopeField.vue';
+  import {
+    findDeptLabel,
+    normalizeDeptTree,
+    RESOURCE_SCOPE_OPTIONS,
+    scopeOptionsForUser,
+    visibleScopeLabel,
+  } from '@/workbench/constants/visibleScope';
+  import { getAgentScopeOptions } from '@/workbench/api/agent';
   import { addSkill, delSkill, getSkill, listSkill, updateSkill } from '@/workbench/api/skill';
 
   const LIFECYCLE_OPTIONS: Record<string, { label: string; color: string }> = {
@@ -227,6 +275,8 @@
     '技能需绑定到智能体后才会装配,清单注入 system prompt、由模型按需加载。' +
     '使用计数取自工具调用明细中的技能加载调用;陈旧状态按最近使用时间与阈值(30 / 90 天)计算,仅作标注,不会自动归档。';
   const skillList = ref<any[]>([]);
+  const deptOptions = ref<any[]>([]);
+  const canPublic = ref(false);
   const loading = ref(false);
   const buttonLoading = ref(false);
   const queryParams = reactive({ keyword: undefined as string | undefined, status: undefined as string | undefined });
@@ -246,8 +296,13 @@
     skillBody: undefined,
     status: '0',
     remark: undefined,
+    ownerDeptId: undefined,
+    visibleScope: undefined,
     resources: [],
   };
+  const scopeOptions = computed(() =>
+    scopeOptionsForUser(RESOURCE_SCOPE_OPTIONS, canPublic.value, form.value.visibleScope),
+  );
   const rules: any = {
     name: [
       { required: true, message: '技能标识不能为空', trigger: 'blur' },
@@ -290,6 +345,7 @@
   };
   const handleAdd = () => {
     reset();
+    form.value.visibleScope = canPublic.value ? '0' : '2';
     dialog.title = '新增技能';
     dialog.visible = true;
   };
@@ -303,6 +359,8 @@
       skillBody: detail?.skillBody,
       status: detail?.status ?? '0',
       remark: detail?.remark,
+      ownerDeptId: detail?.ownerDeptId ?? undefined,
+      visibleScope: detail?.visibleScope ?? undefined,
       resources: (detail?.resources ?? []).map((item: any) => ({
         resourcePath: item.resourcePath,
         resourceContent: item.resourceContent,
@@ -367,7 +425,20 @@
     await getList();
   };
 
-  onMounted(getList);
+  const loadScopeOptions = async () => {
+    try {
+      const res = await getAgentScopeOptions();
+      deptOptions.value = normalizeDeptTree(res?.depts ?? []);
+      canPublic.value = !!res?.superAdmin;
+    } catch {
+      message.warning('部门 选项加载失败,归属部门暂不可选');
+    }
+  };
+
+  onMounted(() => {
+    getList();
+    loadScopeOptions();
+  });
 </script>
 
 <style scoped lang="less">

+ 70 - 3
ai-electron/frontend/src/workbench/views/kb/base/index.vue

@@ -95,6 +95,15 @@
                   <span class="kb-card__meta-label">召回 TopK</span>
                   <span class="kb-card__meta-value">{{ record.retrievalTopK ?? '-' }}</span>
                 </div>
+                <div class="kb-card__meta-item">
+                  <span class="kb-card__meta-label">可见范围</span>
+                  <span class="kb-card__meta-value">
+                    {{ visibleScopeLabel(record.visibleScope, RESOURCE_SCOPE_OPTIONS) }}
+                    <template v-if="record.visibleScope === '1' && record.ownerDeptId">
+                      ({{ findDeptLabel(deptOptions, record.ownerDeptId) }})
+                    </template>
+                  </span>
+                </div>
               </div>
 
               <div class="kb-card__footer">
@@ -103,7 +112,7 @@
                   <a-button type="link" size="small" @click="handleView(record)">查看</a-button>
                   <a-button type="link" size="small" @click="handleDocs(record)">文档</a-button>
                   <a-button
-                    v-if="record.retrievalMode === 'hybrid'"
+                    v-if="record.canManage !== false && record.retrievalMode === 'hybrid'"
                     v-auth="'ai:kb:edit'"
                     type="link"
                     size="small"
@@ -111,8 +120,23 @@
                   >
                     重建
                   </a-button>
-                  <a-button v-auth="'ai:kb:edit'" type="link" size="small" @click="handleUpdate(record)">修改</a-button>
-                  <a-button v-auth="'ai:kb:remove'" danger type="link" size="small" @click="handleDelete(record)">删除</a-button>
+                  <a-button
+                    v-if="record.canManage !== false"
+                    v-auth="'ai:kb:edit'"
+                    type="link"
+                    size="small"
+                    @click="handleUpdate(record)"
+                    >修改</a-button
+                  >
+                  <a-button
+                    v-if="record.canManage !== false"
+                    v-auth="'ai:kb:remove'"
+                    danger
+                    type="link"
+                    size="small"
+                    @click="handleDelete(record)"
+                    >删除</a-button
+                  >
                 </div>
               </div>
             </article>
@@ -274,6 +298,15 @@
             <a-radio value="1">停用</a-radio>
           </a-radio-group>
         </a-form-item>
+        <a-form-item label="可见范围" name="visibleScope">
+          <VisibleScopeField
+            v-model:scope="form.visibleScope"
+            v-model:owner-dept-id="form.ownerDeptId"
+            :options="scopeOptions"
+            :dept-options="deptOptions"
+            :show-dept="form.visibleScope === '1'"
+          />
+        </a-form-item>
         <a-form-item label="描述" name="description">
           <a-textarea v-model:value="form.description" :rows="2" placeholder="知识库用途说明" />
         </a-form-item>
@@ -315,6 +348,12 @@
             </a-tag>
           </a-descriptions-item>
           <a-descriptions-item label="向量集合">{{ detail.record.collectionName || '-' }}</a-descriptions-item>
+          <a-descriptions-item label="可见范围">
+            {{ visibleScopeLabel(detail.record.visibleScope, RESOURCE_SCOPE_OPTIONS) }}
+          </a-descriptions-item>
+          <a-descriptions-item label="归属部门">
+            {{ findDeptLabel(deptOptions, detail.record.ownerDeptId) || '-' }}
+          </a-descriptions-item>
           <a-descriptions-item label="描述" :span="2">{{ detail.record.description || '-' }}</a-descriptions-item>
           <a-descriptions-item label="备注" :span="2">{{ detail.record.remark || '-' }}</a-descriptions-item>
           <a-descriptions-item label="创建时间">{{ detail.record.createTime || '-' }}</a-descriptions-item>
@@ -354,6 +393,15 @@
   } from '@/workbench/components/ant';
   import { Icon } from '@/core/components/Icon';
   import { BasicModal } from '@/core/components/Modal';
+  import VisibleScopeField from '@/workbench/components/VisibleScopeField.vue';
+  import {
+    findDeptLabel,
+    normalizeDeptTree,
+    RESOURCE_SCOPE_OPTIONS,
+    scopeOptionsForUser,
+    visibleScopeLabel,
+  } from '@/workbench/constants/visibleScope';
+  import { getAgentScopeOptions } from '@/workbench/api/agent';
   import {
     addKnowledgeBase,
     delKnowledgeBase,
@@ -373,6 +421,8 @@
     '检索方式支持纯向量或向量 + BM25;检索重排需先配置 rerank 模型。';
 
   const kbList = ref<KnowledgeBaseVO[]>([]);
+  const deptOptions = ref<any[]>([]);
+  const canPublic = ref(false);
   const embeddingModels = ref<ModelConfigVO[]>([]);
 
   /** 可选重排模型(model_type=rerank) */
@@ -397,9 +447,14 @@
     retrievalMode: 'vector',
     status: '0',
     remark: undefined,
+    ownerDeptId: undefined,
+    visibleScope: undefined,
   };
 
   const form = ref<any>({ ...initFormData });
+  const scopeOptions = computed(() =>
+    scopeOptionsForUser(RESOURCE_SCOPE_OPTIONS, canPublic.value, form.value.visibleScope),
+  );
 
   const queryParams = reactive<any>({
     kbName: undefined,
@@ -548,6 +603,7 @@
   /** 新增按钮操作 */
   const handleAdd = () => {
     reset();
+    form.value.visibleScope = canPublic.value ? '0' : '2';
     dialog.title = '新增知识库';
     dialog.visible = true;
   };
@@ -616,10 +672,21 @@
     await getList();
   };
 
+  const loadScopeOptions = async () => {
+    try {
+      const res = await getAgentScopeOptions();
+      deptOptions.value = normalizeDeptTree(res?.depts ?? []);
+      canPublic.value = !!res?.superAdmin;
+    } catch {
+      message.warning('部门 选项加载失败,归属部门暂不可选');
+    }
+  };
+
   onMounted(() => {
     loadEmbeddingModels();
     loadRerankModels();
     getList();
+    loadScopeOptions();
   });
 </script>
 

+ 2 - 2
ai-electron/frontend/src/workbench/views/kb/doc/index.vue

@@ -338,7 +338,7 @@
     getDocumentContent,
     listDocument,
     listDocumentChunk,
-    optionKnowledgeBase,
+    visibleKnowledgeBaseOptions,
     parseDocument,
     vectorizeDocument,
   } from '@/workbench/api/kb';
@@ -557,7 +557,7 @@
 
   /** 查询知识库下拉 */
   const loadKbOptions = async () => {
-    const res = await optionKnowledgeBase();
+    const res = await visibleKnowledgeBaseOptions();
     kbOptions.value = res ?? [];
     const routeKbId = route.query.kbId as string | undefined;
     if (routeKbId) {

+ 23 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/controller/AiAgentController.java

@@ -1,6 +1,8 @@
 package com.zsjz.ai.module.ai.controller;
 
 import cn.dev33.satoken.annotation.SaCheckPermission;
+import cn.dev33.satoken.annotation.SaMode;
+import cn.hutool.core.lang.tree.Tree;
 import jakarta.validation.constraints.NotBlank;
 import jakarta.validation.constraints.NotEmpty;
 import jakarta.validation.constraints.NotNull;
@@ -14,12 +16,16 @@ import com.zsjz.ai.module.ai.domain.vo.AiEntryAgentVo;
 import com.zsjz.ai.module.ai.domain.vo.AiExpertAgentVo;
 import com.zsjz.ai.module.ai.domain.vo.AiExpertPromptVo;
 import com.zsjz.ai.module.ai.domain.vo.AiExpertVo;
+import com.zsjz.ai.module.ai.domain.vo.AiScopeOptionsVo;
 import com.zsjz.ai.module.ai.domain.vo.AiToolVo;
 import com.zsjz.ai.module.ai.service.IAiAgentService;
 import com.zsjz.ai.module.ai.service.IAiExpertPromptService;
 import com.zsjz.ai.module.ai.service.IAiToolService;
+import com.zsjz.ai.common.compat.LoginHelper;
 import com.zsjz.ai.common.compat.PageResult;
 import com.zsjz.ai.common.compat.R;
+import com.zsjz.ai.common.model.perm.bo.SysDeptBo;
+import com.zsjz.ai.module.perm.service.PermDeptService;
 import com.zsjz.ai.common.compat.validate.AddGroup;
 import com.zsjz.ai.common.compat.validate.EditGroup;
 import com.zsjz.ai.common.compat.validate.QueryGroup;
@@ -56,6 +62,8 @@ public class AiAgentController extends BaseController {
 
     private final IAiExpertPromptService aiExpertPromptService;
 
+    private final PermDeptService permDeptService;
+
     /**
      * 查询入口智能体(数剑,全平台唯一)
      */
@@ -114,6 +122,21 @@ public class AiAgentController extends BaseController {
         return R.ok(aiAgentService.queryVisibleExperts());
     }
 
+    /**
+     * 查询可见范围选项:部门树 + 当前用户是否超级管理员。
+     *
+     * <p>普通用户只能选择「本部门 / 仅创建人」,仅超管可设置「全员/公开」。</p>
+     */
+    @SaCheckPermission(value = {"ai:agent:query", "ai:expert:query", "ai:skill:query",
+        "ai:pack:query", "ai:kb:query"}, mode = SaMode.OR)
+    @GetMapping("/scope-options")
+    public R<AiScopeOptionsVo> scopeOptions() {
+        AiScopeOptionsVo vo = new AiScopeOptionsVo();
+        vo.setSuperAdmin(LoginHelper.isSuperAdmin());
+        vo.setDepts(permDeptService.selectDeptTreeListIgnoreDataScope(new SysDeptBo()));
+        return R.ok(vo);
+    }
+
     /**
      * 查询可绑定的业务工具选项(供定义页绑定工具集)
      */

+ 3 - 1
ai-server/src/main/java/com/zsjz/ai/module/ai/controller/AiKnowledgeBaseController.java

@@ -55,7 +55,9 @@ public class AiKnowledgeBaseController extends BaseController {
     }
 
     /**
-     * 查询启用中的知识库选项(供文档与切片页选择:该页属管理视角,展示全量)
+     * 查询启用中的知识库选项(全量,供健康自检等内部场景使用)
+     *
+     * <p>页面下拉请使用 {@link #visibleOptions()}:按当前用户生效范围过滤。</p>
      */
         @SaCheckPermission("ai:kb:query")
         @GetMapping("/options")

+ 5 - 18
ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiExpertDirectory.java

@@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers;
 import lombok.RequiredArgsConstructor;
 import com.zsjz.ai.module.ai.domain.AiExpertAgent;
 import com.zsjz.ai.module.ai.mapper.AiExpertAgentMapper;
+import com.zsjz.ai.module.ai.support.VisibleScopeSupport;
 import org.springframework.stereotype.Component;
 
 import java.util.List;
@@ -33,21 +34,6 @@ import java.util.List;
 @RequiredArgsConstructor
 public class AiExpertDirectory {
 
-    /**
-     * 可见范围:公开
-     */
-    private static final String SCOPE_ALL = "0";
-
-    /**
-     * 可见范围:本部门
-     */
-    private static final String SCOPE_DEPT = "1";
-
-    /**
-     * 可见范围:仅本人
-     */
-    private static final String SCOPE_SELF = "2";
-
     /**
      * 状态:正常
      */
@@ -55,6 +41,8 @@ public class AiExpertDirectory {
 
     private final AiExpertAgentMapper expertMapper;
 
+    private final VisibleScopeSupport visibleScopeSupport;
+
     /**
      * 取提问用户当前可见的**自动候选**专家清单({@code auto_route='1'})。
      *
@@ -132,9 +120,8 @@ public class AiExpertDirectory {
     private LambdaQueryWrapper<AiExpertAgent> visibleWrapper(Long userId) {
         LambdaQueryWrapper<AiExpertAgent> lqw = Wrappers.lambdaQuery();
         lqw.eq(AiExpertAgent::getStatus, STATUS_NORMAL);
-        // 可见口径(去部门/权限维度):内置 or 创建人本人
-        lqw.and(w -> w.eq(AiExpertAgent::getIsBuiltin, "1")
-            .or(o -> o.eq(AiExpertAgent::getCreateBy, userId)));
+        visibleScopeSupport.applyVisible(lqw, AiExpertAgent::getVisibleScope,
+            AiExpertAgent::getOwnerDeptId, AiExpertAgent::getCreateBy, userId);
         lqw.orderByAsc(AiExpertAgent::getId);
         return lqw;
     }

+ 7 - 1
ai-server/src/main/java/com/zsjz/ai/module/ai/domain/AiAgent.java

@@ -155,8 +155,14 @@ public abstract class AiAgent extends BaseEntity {
     }
 
 
-    /** 是否内置(1是 0否);可见口径 = 内置 or 创建人本人 */
+    /** 是否内置(1是 0否);仅作数据来源标识,不再作为可见口径 */
     private String isBuiltin;
 
+    /** 归属部门(可见范围=本部门时生效;为空表示未指定) */
+    private Long ownerDeptId;
+
+    /** 可见范围(0全员/公开 1本部门 2仅创建人/本人) */
+    private String visibleScope;
+
 }
 

+ 7 - 1
ai-server/src/main/java/com/zsjz/ai/module/ai/domain/AiKnowledgeBase.java

@@ -117,7 +117,13 @@ public class AiKnowledgeBase extends BaseEntity {
 
 
 
-    /** 是否内置(1是 0否);可见口径 = 内置 or 创建人本人 */
+    /** 是否内置(1是 0否);仅作数据来源标识,不再作为可见口径 */
     private String isBuiltin;
 
+    /** 归属部门(生效范围=本部门时生效;为空表示未指定) */
+    private Long ownerDeptId;
+
+    /** 生效范围(0公开 1本部门 2仅本人) */
+    private String visibleScope;
+
 }

+ 7 - 1
ai-server/src/main/java/com/zsjz/ai/module/ai/domain/AiScenarioPack.java

@@ -89,7 +89,13 @@ public class AiScenarioPack extends BaseEntity {
 
 
 
-    /** 是否内置(1是 0否);可见口径 = 内置 or 创建人本人 */
+    /** 是否内置(1是 0否);仅作数据来源标识,不再作为可见口径 */
     private String isBuiltin;
 
+    /** 归属部门(生效范围=本部门时生效;为空表示未指定) */
+    private Long ownerDeptId;
+
+    /** 生效范围(0公开 1本部门 2仅本人) */
+    private String visibleScope;
+
 }

+ 7 - 1
ai-server/src/main/java/com/zsjz/ai/module/ai/domain/AiSkill.java

@@ -120,8 +120,14 @@ public class AiSkill implements Serializable {
     private Long updateBy;
 
 
-    /** 是否内置(1是 0否);可见口径 = 内置 or 创建人本人 */
+    /** 是否内置(1是 0否);仅作数据来源标识,不再作为可见口径 */
     private String isBuiltin;
 
+    /** 归属部门(生效范围=本部门时生效;为空表示未指定) */
+    private Long ownerDeptId;
+
+    /** 生效范围(0公开 1本部门 2仅本人) */
+    private String visibleScope;
+
 }
 

+ 13 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/domain/bo/AiAgentBo.java

@@ -4,6 +4,7 @@ import jakarta.validation.constraints.Max;
 import jakarta.validation.constraints.Min;
 import jakarta.validation.constraints.NotBlank;
 import jakarta.validation.constraints.NotNull;
+import jakarta.validation.constraints.Pattern;
 import lombok.Data;
 import com.zsjz.ai.common.compat.validate.AddGroup;
 import com.zsjz.ai.common.compat.validate.EditGroup;
@@ -120,6 +121,18 @@ public class AiAgentBo implements Serializable {
      */
     private List<Long> skillIds;
 
+    /**
+     * 归属部门(可见范围=本部门时生效;留空时后端默认取当前用户部门)
+     */
+    private Long ownerDeptId;
+
+    /**
+     * 可见范围(0全员/公开 1本部门 2仅创建人/本人)
+     */
+    @Pattern(regexp = "^$|^[012]$", message = "可见范围只能是 0、1 或 2",
+        groups = {AddGroup.class, EditGroup.class})
+    private String visibleScope;
+
     /**
      * 列表查询用:按名称模糊匹配
      */

+ 12 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/domain/bo/AiKnowledgeBaseBo.java

@@ -118,4 +118,16 @@ public class AiKnowledgeBaseBo implements Serializable {
      */
     private String remark;
 
+    /**
+     * 归属部门(生效范围=本部门时生效;留空时后端默认取当前用户部门)
+     */
+    private Long ownerDeptId;
+
+    /**
+     * 生效范围(0公开 1本部门 2仅本人)
+     */
+    @Pattern(regexp = "^$|^[012]$", message = "生效范围只能是 0、1 或 2",
+        groups = {AddGroup.class, EditGroup.class})
+    private String visibleScope;
+
 }

+ 12 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/domain/bo/AiScenarioPackBo.java

@@ -81,6 +81,18 @@ public class AiScenarioPackBo implements Serializable {
      */
     private List<Long> skillIds;
 
+    /**
+     * 归属部门(生效范围=本部门时生效;留空时后端默认取当前用户部门)
+     */
+    private Long ownerDeptId;
+
+    /**
+     * 生效范围(0公开 1本部门 2仅本人)
+     */
+    @Pattern(regexp = "^$|^[012]$", message = "生效范围只能是 0、1 或 2",
+        groups = {AddGroup.class, EditGroup.class})
+    private String visibleScope;
+
     /**
      * 列表查询用:按编码 / 名称 / 用途说明模糊匹配
      */

+ 12 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/domain/bo/AiSkillBo.java

@@ -69,6 +69,18 @@ public class AiSkillBo implements Serializable {
      */
     private List<AiSkillResourceBo> resources;
 
+    /**
+     * 归属部门(生效范围=本部门时生效;留空时后端默认取当前用户部门)
+     */
+    private Long ownerDeptId;
+
+    /**
+     * 生效范围(0公开 1本部门 2仅本人)
+     */
+    @Pattern(regexp = "^$|^[012]$", message = "生效范围只能是 0、1 或 2",
+        groups = {AddGroup.class, EditGroup.class})
+    private String visibleScope;
+
     /**
      * 列表查询用:按标识或说明模糊匹配
      */

+ 21 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/domain/vo/AiAgentVo.java

@@ -102,6 +102,27 @@ public class AiAgentVo implements Serializable {
      */
     private String role;
 
+    /**
+     * 创建人
+     */
+    private Long createBy;
+
+    /**
+     * 归属部门
+     */
+    private Long ownerDeptId;
+
+    /**
+     * 可见范围(0全员/公开 1本部门 2仅创建人/本人)
+     */
+    private String visibleScope;
+
+    /**
+     * 当前用户是否可修改/删除(附加字段,由 Service 填充)
+     */
+    @TableField(exist = false)
+    private Boolean canManage;
+
     /**
      * 绑定的业务工具及授权决策(附加字段,由 Service 填充)
      */

+ 22 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/domain/vo/AiKnowledgeBaseVo.java

@@ -1,5 +1,6 @@
 package com.zsjz.ai.module.ai.domain.vo;
 
+import com.baomidou.mybatisplus.annotation.TableField;
 import io.github.linpeilie.annotations.AutoMapper;
 import lombok.Data;
 import com.zsjz.ai.module.ai.domain.AiKnowledgeBase;
@@ -116,6 +117,27 @@ public class AiKnowledgeBaseVo implements Serializable {
      */
     private String remark;
 
+    /**
+     * 归属部门
+     */
+    private Long ownerDeptId;
+
+    /**
+     * 生效范围(0公开 1本部门 2仅本人)
+     */
+    private String visibleScope;
+
+    /**
+     * 创建人
+     */
+    private Long createBy;
+
+    /**
+     * 当前用户是否可修改/删除(附加字段,由 Service 填充)
+     */
+    @TableField(exist = false)
+    private Boolean canManage;
+
     /**
      * 创建时间
      */

+ 16 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/domain/vo/AiScenarioPackVo.java

@@ -52,6 +52,22 @@ public class AiScenarioPackVo implements Serializable {
      */
     private String remark;
 
+    /**
+     * 归属部门
+     */
+    private Long ownerDeptId;
+
+    /**
+     * 生效范围(0公开 1本部门 2仅本人)
+     */
+    private String visibleScope;
+
+    /**
+     * 当前用户是否可修改/删除(附加字段,由 Service 填充)
+     */
+    @TableField(exist = false)
+    private Boolean canManage;
+
     /**
      * 创建人
      */

+ 34 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/domain/vo/AiScopeOptionsVo.java

@@ -0,0 +1,34 @@
+package com.zsjz.ai.module.ai.domain.vo;
+
+import cn.hutool.core.lang.tree.Tree;
+import lombok.Data;
+
+import java.io.Serial;
+import java.io.Serializable;
+import java.util.List;
+
+/**
+ * 可见范围选项视图对象。
+ *
+ * <p>供专家 / 数剑 / 技能 / 场景包 / 知识库定义页使用:前端据 {@code superAdmin}
+ * 决定是否展示「全员/公开」选项,并用 {@code depts} 渲染「归属部门」树。</p>
+ *
+ * @author BizBuddy
+ */
+@Data
+public class AiScopeOptionsVo implements Serializable {
+
+    @Serial
+    private static final long serialVersionUID = 1L;
+
+    /**
+     * 当前用户是否超级管理员(仅超管可设置全员/公开)
+     */
+    private Boolean superAdmin;
+
+    /**
+     * 部门树(不做数据范围过滤,供归属部门选择)
+     */
+    private List<Tree<Long>> depts;
+
+}

+ 16 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/domain/vo/AiSkillVo.java

@@ -63,6 +63,22 @@ public class AiSkillVo implements Serializable {
      */
     private String remark;
 
+    /**
+     * 归属部门
+     */
+    private Long ownerDeptId;
+
+    /**
+     * 生效范围(0公开 1本部门 2仅本人)
+     */
+    private String visibleScope;
+
+    /**
+     * 当前用户是否可修改/删除(附加字段,由 Service 填充)
+     */
+    @TableField(exist = false)
+    private Boolean canManage;
+
     /**
      * 创建人
      */

+ 10 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/service/IAiKnowledgeBaseService.java

@@ -50,6 +50,16 @@ public interface IAiKnowledgeBaseService {
      */
     List<AiKnowledgeBaseVo> queryVisibleOptions(Long userId);
 
+    /**
+     * 查询指定用户可见的知识库主键集合(不限制启用状态)。
+     *
+     * <p>供文档列表等需要按知识库可见范围收口的场景使用。</p>
+     *
+     * @param userId 用户主键
+     * @return 可见知识库主键集合
+     */
+    List<Long> listVisibleKbIds(Long userId);
+
     /**
      * 求「指定知识库集合」与「指定用户可见集合」的交集。
      *

+ 31 - 19
ai-server/src/main/java/com/zsjz/ai/module/ai/service/impl/AiAgentServiceImpl.java

@@ -34,6 +34,7 @@ import com.zsjz.ai.module.ai.service.IAiAgentService;
 import com.zsjz.ai.module.ai.service.IAiKnowledgeBaseService;
 import com.zsjz.ai.module.ai.service.IAiSkillService;
 import com.zsjz.ai.module.ai.service.IAiToolService;
+import com.zsjz.ai.module.ai.support.VisibleScopeSupport;
 import com.zsjz.ai.common.compat.PageResult;
 import com.zsjz.ai.common.compat.ServiceException;
 import com.zsjz.ai.common.compat.MapstructUtils;
@@ -86,21 +87,6 @@ public class AiAgentServiceImpl implements IAiAgentService {
      */
     private static final String STATUS_NORMAL = "0";
 
-    /**
-     * 可见范围:全员可见
-     */
-    private static final String SCOPE_ALL = "0";
-
-    /**
-     * 可见范围:本部门可见
-     */
-    private static final String SCOPE_DEPT = "1";
-
-    /**
-     * 可见范围:仅创建人可见
-     */
-    private static final String SCOPE_SELF = "2";
-
     private final AiEntryAgentMapper entryMapper;
 
     private final AiExpertAgentMapper expertMapper;
@@ -128,6 +114,8 @@ public class AiAgentServiceImpl implements IAiAgentService {
 
     private final AiProperties aiProperties;
 
+    private final VisibleScopeSupport visibleScopeSupport;
+
     // ---------------------------------------------------------------- 入口智能体(数剑)
 
     @Override
@@ -139,6 +127,7 @@ public class AiAgentServiceImpl implements IAiAgentService {
         AiEntryAgentVo vo = MapstructUtils.convert(entry, AiEntryAgentVo.class);
         vo.setRole(AiAgent.ROLE_ENTRY);
         fillModelName(List.of(vo));
+        vo.setCanManage(visibleScopeSupport.canManage(entry.getCreateBy(), LoginHelper.getUserId()));
         return vo;
     }
 
@@ -172,6 +161,12 @@ public class AiAgentServiceImpl implements IAiAgentService {
         if (entity == null) {
             return null;
         }
+        Long userId = LoginHelper.getUserId();
+        // 入口智能体为全局单例,不做可见范围拦截;专家按记录级可见范围校验
+        if (!entity.isEntry() && !visibleScopeSupport.visibleTo(entity.getVisibleScope(),
+            entity.getOwnerDeptId(), entity.getCreateBy(), userId)) {
+            throw new ServiceException("智能体不存在或不在你的可见范围内");
+        }
         AiAgentVo vo;
         if (entity.isEntry()) {
             vo = MapstructUtils.convert((AiEntryAgent) entity, AiEntryAgentVo.class);
@@ -179,6 +174,7 @@ public class AiAgentServiceImpl implements IAiAgentService {
             vo = MapstructUtils.convert((AiExpertAgent) entity, AiExpertAgentVo.class);
         }
         vo.setRole(entity.role());
+        vo.setCanManage(visibleScopeSupport.canManage(entity.getCreateBy(), userId));
         fillModelName(List.of(vo));
         fillBindings(List.of(vo));
         return vo;
@@ -186,9 +182,15 @@ public class AiAgentServiceImpl implements IAiAgentService {
 
     @Override
     public PageResult<AiExpertAgentVo> queryPageList(AiExpertAgentBo bo, PageQuery pageQuery) {
-        Page<AiExpertAgentVo> result = expertMapper.selectVoPage(pageQuery.build(), buildQueryWrapper(bo));
+        Long userId = LoginHelper.getUserId();
+        LambdaQueryWrapper<AiExpertAgent> lqw = buildQueryWrapper(bo);
+        visibleScopeSupport.applyVisible(lqw, AiExpertAgent::getVisibleScope,
+            AiExpertAgent::getOwnerDeptId, AiExpertAgent::getCreateBy, userId);
+        Page<AiExpertAgentVo> result = expertMapper.selectVoPage(pageQuery.build(), lqw);
         fillModelName(result.getRecords());
         fillBindings(result.getRecords());
+        result.getRecords().forEach(vo ->
+            vo.setCanManage(visibleScopeSupport.canManage(vo.getCreateBy(), userId)));
         return PageResult.build(result.getRecords(), result.getTotal());
     }
 
@@ -221,6 +223,7 @@ public class AiAgentServiceImpl implements IAiAgentService {
         if (exists == null) {
             throw new ServiceException("专家不存在或已被删除");
         }
+        visibleScopeSupport.requireCanManage(exists.getCreateBy(), LoginHelper.getUserId(), "专家");
         AiExpertAgent update = MapstructUtils.convert(bo, AiExpertAgent.class);
         update.setAgentCode(normalizeCode(update.getAgentCode()));
         update.setSysPrompt(resolveSysPrompt(update.getSysPrompt()));
@@ -248,6 +251,10 @@ public class AiAgentServiceImpl implements IAiAgentService {
             if (list.size() != ids.size()) {
                 throw new ServiceException("您没有删除权限!");
             }
+            Long userId = LoginHelper.getUserId();
+            for (AiExpertAgent item : list) {
+                visibleScopeSupport.requireCanManage(item.getCreateBy(), userId, "专家");
+            }
             LambdaQueryWrapper<AiSession> lqw = Wrappers.lambdaQuery();
             lqw.in(AiSession::getAgentId, ids);
             if (sessionMapper.selectCount(lqw) > 0) {
@@ -483,9 +490,8 @@ public class AiAgentServiceImpl implements IAiAgentService {
     private LambdaQueryWrapper<AiExpertAgent> visibleWrapper(Long userId) {
         LambdaQueryWrapper<AiExpertAgent> lqw = Wrappers.lambdaQuery();
         lqw.eq(AiExpertAgent::getStatus, STATUS_NORMAL);
-        // 可见口径(去部门/权限维度):内置 or 创建人本人
-        lqw.and(w -> w.eq(AiExpertAgent::getIsBuiltin, "1")
-            .or(o -> o.eq(AiExpertAgent::getCreateBy, userId)));
+        visibleScopeSupport.applyVisible(lqw, AiExpertAgent::getVisibleScope,
+            AiExpertAgent::getOwnerDeptId, AiExpertAgent::getCreateBy, userId);
         lqw.orderByAsc(AiExpertAgent::getId);
         return lqw;
     }
@@ -798,6 +804,12 @@ public class AiAgentServiceImpl implements IAiAgentService {
         if (entity.getMaxIters() == null) {
             entity.setMaxIters(exists == null ? aiProperties.getChat().getDefaultMaxIters() : exists.getMaxIters());
         }
+        Long userId = LoginHelper.getUserId();
+        String scope = visibleScopeSupport.validateScopeForUser(entity.getVisibleScope(),
+            exists == null ? null : exists.getVisibleScope(), userId);
+        entity.setVisibleScope(scope);
+        entity.setOwnerDeptId(visibleScopeSupport.resolveOwnerDeptId(scope, entity.getOwnerDeptId(),
+            exists == null ? null : exists.getOwnerDeptId(), userId));
     }
 
     /**

+ 39 - 3
ai-server/src/main/java/com/zsjz/ai/module/ai/service/impl/AiDocumentServiceImpl.java

@@ -152,6 +152,21 @@ public class AiDocumentServiceImpl implements IAiDocumentService {
     @Override
     public PageResult<AiDocumentVo> queryPageList(AiDocumentBo bo, PageQuery pageQuery) {
         LambdaQueryWrapper<AiDocument> lqw = Wrappers.lambdaQuery();
+        Long userId = LoginHelper.getUserId();
+        if (bo.getKbId() != null) {
+            // 指定知识库时按该库可见性收口;不可见则返回空列表
+            if (knowledgeBaseService.filterVisibleKbIds(List.of(bo.getKbId()), userId).isEmpty()) {
+                lqw.apply("1 = 0");
+            }
+        } else {
+            // 未指定知识库时只返回当前用户可见知识库下的文档
+            List<Long> visibleKbIds = knowledgeBaseService.listVisibleKbIds(userId);
+            if (visibleKbIds.isEmpty()) {
+                lqw.apply("1 = 0");
+            } else {
+                lqw.in(AiDocument::getKbId, visibleKbIds);
+            }
+        }
         lqw.eq(bo.getKbId() != null, AiDocument::getKbId, bo.getKbId());
         lqw.like(StringUtils.isNotBlank(bo.getDocName()), AiDocument::getDocName, bo.getDocName());
         lqw.eq(StringUtils.isNotBlank(bo.getParseStatus()), AiDocument::getParseStatus, bo.getParseStatus());
@@ -165,6 +180,9 @@ public class AiDocumentServiceImpl implements IAiDocumentService {
     @Override
     public AiDocumentVo queryById(Long id) {
         AiDocumentVo vo = baseMapper.selectVoById(id);
+        if (vo != null) {
+            requireVisibleKb(vo.getKbId());
+        }
         fillFileUrl(vo);
         return vo;
     }
@@ -551,6 +569,11 @@ public class AiDocumentServiceImpl implements IAiDocumentService {
 
     @Override
     public PageResult<AiChunkVo> queryChunkPage(Long docId, PageQuery pageQuery) {
+        AiDocument document = baseMapper.selectById(docId);
+        if (document == null) {
+            throw new ServiceException("文档不存在或已被删除");
+        }
+        requireVisibleKb(document.getKbId());
         LambdaQueryWrapper<AiChunk> lqw = Wrappers.lambdaQuery();
         lqw.eq(AiChunk::getDocId, docId);
         lqw.orderByAsc(AiChunk::getChunkIndex);
@@ -564,6 +587,7 @@ public class AiDocumentServiceImpl implements IAiDocumentService {
         if (document == null) {
             throw new ServiceException("文档不存在或已被删除");
         }
+        requireVisibleKb(document.getKbId());
         if (StringUtils.isBlank(document.getContent())) {
             throw new ServiceException("文档尚未解析,请先执行解析");
         }
@@ -585,9 +609,7 @@ public class AiDocumentServiceImpl implements IAiDocumentService {
         }
         // 越权防护:来源条目只带 docId,若不校验可见范围,任何有 ai:kb:doc 权限的用户
         // 都能凭 docId 读到无权访问的知识库正文
-        if (knowledgeBaseService.filterVisibleKbIds(List.of(document.getKbId()), LoginHelper.getUserId()).isEmpty()) {
-            throw new ServiceException("无权访问该知识库文档");
-        }
+        requireVisibleKb(document.getKbId());
         int span = normalizeContextRadius(radius);
         LambdaQueryWrapper<AiChunk> lqw = Wrappers.lambdaQuery();
         lqw.eq(AiChunk::getDocId, docId);
@@ -616,6 +638,20 @@ public class AiDocumentServiceImpl implements IAiDocumentService {
         return context;
     }
 
+    /**
+     * 校验当前用户对文档所属知识库是否可见。
+     *
+     * @param kbId 知识库主键
+     */
+    private void requireVisibleKb(Long kbId) {
+        if (kbId == null) {
+            return;
+        }
+        if (knowledgeBaseService.filterVisibleKbIds(List.of(kbId), LoginHelper.getUserId()).isEmpty()) {
+            throw new ServiceException("无权访问该知识库文档");
+        }
+    }
+
     /**
      * 归一化上下文半径:缺省取 1,负数按缺省处理,过大钳制到上限。
      *

+ 42 - 8
ai-server/src/main/java/com/zsjz/ai/module/ai/service/impl/AiKnowledgeBaseServiceImpl.java

@@ -18,6 +18,7 @@ import com.zsjz.ai.module.ai.mapper.AiDocumentMapper;
 import com.zsjz.ai.module.ai.mapper.AiKnowledgeBaseMapper;
 import com.zsjz.ai.module.ai.mapper.AiModelConfigMapper;
 import com.zsjz.ai.module.ai.service.IAiKnowledgeBaseService;
+import com.zsjz.ai.module.ai.support.VisibleScopeSupport;
 import com.zsjz.ai.common.compat.PageResult;
 import com.zsjz.ai.common.compat.ServiceException;
 import com.zsjz.ai.common.compat.MapstructUtils;
@@ -129,10 +130,18 @@ public class AiKnowledgeBaseServiceImpl implements IAiKnowledgeBaseService {
      */
     private final AiBm25Store bm25Store;
 
+    private final VisibleScopeSupport visibleScopeSupport;
+
     @Override
     public AiKnowledgeBaseVo queryById(Long id) {
         AiKnowledgeBaseVo vo = baseMapper.selectVoById(id);
         if (vo != null) {
+            Long userId = LoginHelper.getUserId();
+            if (!visibleScopeSupport.visibleTo(vo.getVisibleScope(), vo.getOwnerDeptId(),
+                vo.getCreateBy(), userId)) {
+                throw new ServiceException("知识库不存在或不在你的可见范围内");
+            }
+            vo.setCanManage(visibleScopeSupport.canManage(vo.getCreateBy(), userId));
             fillModelName(List.of(vo));
         }
         return vo;
@@ -140,8 +149,14 @@ public class AiKnowledgeBaseServiceImpl implements IAiKnowledgeBaseService {
 
     @Override
     public PageResult<AiKnowledgeBaseVo> queryPageList(AiKnowledgeBaseBo bo, PageQuery pageQuery) {
-        Page<AiKnowledgeBaseVo> result = baseMapper.selectVoPage(pageQuery.build(), buildQueryWrapper(bo));
+        Long userId = LoginHelper.getUserId();
+        LambdaQueryWrapper<AiKnowledgeBase> lqw = buildQueryWrapper(bo);
+        visibleScopeSupport.applyVisible(lqw, AiKnowledgeBase::getVisibleScope,
+            AiKnowledgeBase::getOwnerDeptId, AiKnowledgeBase::getCreateBy, userId);
+        Page<AiKnowledgeBaseVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
         fillModelName(result.getRecords());
+        result.getRecords().forEach(vo ->
+            vo.setCanManage(visibleScopeSupport.canManage(vo.getCreateBy(), userId)));
         return PageResult.build(result.getRecords(), result.getTotal());
     }
 
@@ -203,11 +218,20 @@ public class AiKnowledgeBaseServiceImpl implements IAiKnowledgeBaseService {
         LambdaQueryWrapper<AiKnowledgeBase> lqw = Wrappers.lambdaQuery();
         lqw.eq(AiKnowledgeBase::getStatus, STATUS_NORMAL);
         // 存量数据 visible_scope 为空时按「公开」处理(与 buildVisibleWrapper 口径一致)
-        lqw.eq(AiKnowledgeBase::getIsBuiltin, "1");
+        lqw.and(w -> w.isNull(AiKnowledgeBase::getVisibleScope)
+            .or().eq(AiKnowledgeBase::getVisibleScope, "")
+            .or().eq(AiKnowledgeBase::getVisibleScope, VisibleScopeSupport.SCOPE_ALL));
         lqw.orderByAsc(AiKnowledgeBase::getId);
         return baseMapper.selectList(lqw).stream().map(AiKnowledgeBase::getId).toList();
     }
 
+    @Override
+    public List<Long> listVisibleKbIds(Long userId) {
+        return baseMapper.selectList(buildVisibleWrapper(userId, false)).stream()
+            .map(AiKnowledgeBase::getId)
+            .toList();
+    }
+
     @Override
     public void validateRetrievable(Collection<Long> kbIds, Long userId, String scene) {
         if (kbIds == null || kbIds.isEmpty()) {
@@ -260,9 +284,8 @@ public class AiKnowledgeBaseServiceImpl implements IAiKnowledgeBaseService {
         if (onlyEnabled) {
             lqw.eq(AiKnowledgeBase::getStatus, STATUS_NORMAL);
         }
-        // 可见口径(去部门/权限维度):内置 or 创建人本人
-        lqw.and(w -> w.eq(AiKnowledgeBase::getIsBuiltin, "1")
-            .or(o -> o.eq(AiKnowledgeBase::getCreateBy, userId)));
+        visibleScopeSupport.applyVisible(lqw, AiKnowledgeBase::getVisibleScope,
+            AiKnowledgeBase::getOwnerDeptId, AiKnowledgeBase::getCreateBy, userId);
         lqw.orderByDesc(AiKnowledgeBase::getUpdateTime);
         return lqw;
     }
@@ -275,7 +298,7 @@ public class AiKnowledgeBaseServiceImpl implements IAiKnowledgeBaseService {
         add.setKbCode(normalizeCode(add.getKbCode()));
         add.setCollectionName(buildCollectionName(add.getKbCode()));
         add.setDimension(resolveDimension(add.getDimension(), model));
-        applyDefaults(add);
+        applyDefaults(add, null);
         validEntityBeforeSave(add);
         boolean flag = baseMapper.insert(add) > 0;
         if (flag) {
@@ -290,6 +313,7 @@ public class AiKnowledgeBaseServiceImpl implements IAiKnowledgeBaseService {
         if (exists == null) {
             throw new ServiceException("知识库不存在或已被删除");
         }
+        visibleScopeSupport.requireCanManage(exists.getCreateBy(), LoginHelper.getUserId(), "知识库");
         AiKnowledgeBase update = MapstructUtils.convert(bo, AiKnowledgeBase.class);
         AiModelConfig model = resolveEmbeddingModel(update.getEmbeddingModelId());
         resolveRerank(update);
@@ -303,7 +327,7 @@ public class AiKnowledgeBaseServiceImpl implements IAiKnowledgeBaseService {
         if (indexed && !exists.getEmbeddingModelId().equals(update.getEmbeddingModelId())) {
             throw new ServiceException("该知识库已存在切片数据,不允许更换向量模型;如需更换请先清空文档");
         }
-        applyDefaults(update);
+        applyDefaults(update, exists);
         validEntityBeforeSave(update);
         // 离开混合检索:状态复位为未构建,并清掉 BM25 集合(残留集合会持续占用 Milvus 存储)
         boolean leavingHybrid = MODE_HYBRID.equalsIgnoreCase(StringUtils.trim(exists.getRetrievalMode()))
@@ -325,6 +349,10 @@ public class AiKnowledgeBaseServiceImpl implements IAiKnowledgeBaseService {
     @Override
     public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
         List<AiKnowledgeBase> targets = baseMapper.selectByIds(ids);
+        Long userId = LoginHelper.getUserId();
+        for (AiKnowledgeBase target : targets) {
+            visibleScopeSupport.requireCanManage(target.getCreateBy(), userId, "知识库");
+        }
         if (isValid) {
             if (targets.size() != ids.size()) {
                 throw new ServiceException("您没有删除权限!");
@@ -525,7 +553,7 @@ public class AiKnowledgeBaseServiceImpl implements IAiKnowledgeBaseService {
      *
      * @param entity 知识库实体
      */
-    private void applyDefaults(AiKnowledgeBase entity) {
+    private void applyDefaults(AiKnowledgeBase entity, AiKnowledgeBase exists) {
         if (entity.getChunkSize() == null) {
             entity.setChunkSize(DEFAULT_CHUNK_SIZE);
         }
@@ -543,6 +571,12 @@ public class AiKnowledgeBaseServiceImpl implements IAiKnowledgeBaseService {
         }
         entity.setRetrievalMode(MODE_HYBRID.equalsIgnoreCase(StringUtils.trim(entity.getRetrievalMode()))
             ? MODE_HYBRID : MODE_VECTOR);
+        Long userId = LoginHelper.getUserId();
+        String scope = visibleScopeSupport.validateScopeForUser(entity.getVisibleScope(),
+            exists == null ? null : exists.getVisibleScope(), userId);
+        entity.setVisibleScope(scope);
+        entity.setOwnerDeptId(visibleScopeSupport.resolveOwnerDeptId(scope, entity.getOwnerDeptId(),
+            exists == null ? null : exists.getOwnerDeptId(), userId));
     }
 
     /**

+ 34 - 12
ai-server/src/main/java/com/zsjz/ai/module/ai/service/impl/AiScenarioPackServiceImpl.java

@@ -30,6 +30,7 @@ import com.zsjz.ai.module.ai.mapper.AiToolMapper;
 import com.zsjz.ai.module.ai.service.IAiScenarioPackService;
 import com.zsjz.ai.module.ai.service.IAiSkillService;
 import com.zsjz.ai.module.ai.service.IAiToolService;
+import com.zsjz.ai.module.ai.support.VisibleScopeSupport;
 import com.zsjz.ai.common.compat.PageResult;
 import com.zsjz.ai.common.compat.ServiceException;
 import com.zsjz.ai.common.compat.MapstructUtils;
@@ -88,11 +89,18 @@ public class AiScenarioPackServiceImpl implements IAiScenarioPackService {
 
     private final UserService userService;
 
+    private final VisibleScopeSupport visibleScopeSupport;
+
     @Override
     public PageResult<AiScenarioPackVo> queryPageList(AiScenarioPackBo bo, PageQuery pageQuery) {
-        Page<AiScenarioPackVo> result = baseMapper.selectVoPage(pageQuery.build(), buildQueryWrapper(bo));
+        Long userId = LoginHelper.getUserId();
+        LambdaQueryWrapper<AiScenarioPack> lqw = buildQueryWrapper(bo);
+        visibleScopeSupport.applyVisible(lqw, AiScenarioPack::getVisibleScope,
+            AiScenarioPack::getOwnerDeptId, AiScenarioPack::getCreateBy, userId);
+        Page<AiScenarioPackVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
         List<AiScenarioPackVo> records = result.getRecords();
         fillDisplayFields(records);
+        records.forEach(vo -> vo.setCanManage(visibleScopeSupport.canManage(vo.getCreateBy(), userId)));
         return PageResult.build(records, result.getTotal());
     }
 
@@ -102,6 +110,11 @@ public class AiScenarioPackServiceImpl implements IAiScenarioPackService {
         if (vo == null) {
             throw new ServiceException("场景包不存在或已被删除");
         }
+        Long userId = LoginHelper.getUserId();
+        if (!visibleScopeSupport.visibleTo(vo.getVisibleScope(), vo.getOwnerDeptId(), vo.getCreateBy(), userId)) {
+            throw new ServiceException("场景包不存在或不在你的可见范围内");
+        }
+        vo.setCanManage(visibleScopeSupport.canManage(vo.getCreateBy(), userId));
         fillDisplayFields(List.of(vo));
         return vo;
     }
@@ -110,7 +123,7 @@ public class AiScenarioPackServiceImpl implements IAiScenarioPackService {
     @Transactional(rollbackFor = Exception.class)
     public Boolean insertByBo(AiScenarioPackBo bo) {
         AiScenarioPack add = MapstructUtils.convert(bo, AiScenarioPack.class);
-        applyFields(add, bo);
+        applyFields(add, bo, null);
         validCodeUnique(add);
         boolean flag = baseMapper.insert(add) > 0;
         if (flag) {
@@ -127,8 +140,9 @@ public class AiScenarioPackServiceImpl implements IAiScenarioPackService {
         if (exists == null) {
             throw new ServiceException("场景包不存在或已被删除");
         }
+        visibleScopeSupport.requireCanManage(exists.getCreateBy(), LoginHelper.getUserId(), "场景包");
         AiScenarioPack update = MapstructUtils.convert(bo, AiScenarioPack.class);
-        applyFields(update, bo);
+        applyFields(update, bo, exists);
         if (!exists.getPackCode().equals(update.getPackCode())) {
             throw new ServiceException("场景包编码不允许修改(已作为会话快照使用)");
         }
@@ -149,6 +163,10 @@ public class AiScenarioPackServiceImpl implements IAiScenarioPackService {
         if (list.size() != ids.size()) {
             throw new ServiceException("场景包不存在或已被删除");
         }
+        Long userId = LoginHelper.getUserId();
+        for (AiScenarioPack item : list) {
+            visibleScopeSupport.requireCanManage(item.getCreateBy(), userId, "场景包");
+        }
         boolean flag = baseMapper.deleteByIds(ids) > 0;
         if (flag) {
             for (Long id : ids) {
@@ -163,9 +181,8 @@ public class AiScenarioPackServiceImpl implements IAiScenarioPackService {
         Long userId = LoginHelper.getUserId();
         LambdaQueryWrapper<AiScenarioPack> lqw = Wrappers.lambdaQuery();
         lqw.eq(AiScenarioPack::getStatus, AiScenarioPack.STATUS_ENABLED);
-        // 可见口径(去部门/权限维度):内置 or 创建人本人
-        lqw.and(w -> w.eq(AiScenarioPack::getIsBuiltin, "1")
-            .or(o -> o.eq(AiScenarioPack::getCreateBy, userId)));
+        visibleScopeSupport.applyVisible(lqw, AiScenarioPack::getVisibleScope,
+            AiScenarioPack::getOwnerDeptId, AiScenarioPack::getCreateBy, userId);
         lqw.orderByDesc(AiScenarioPack::getUpdateTime);
         List<AiScenarioPack> packs = baseMapper.selectList(lqw);
         if (packs.isEmpty()) {
@@ -275,13 +292,19 @@ public class AiScenarioPackServiceImpl implements IAiScenarioPackService {
      * @param entity 待保存实体
      * @param bo     业务对象
      */
-    private void applyFields(AiScenarioPack entity, AiScenarioPackBo bo) {
+    private void applyFields(AiScenarioPack entity, AiScenarioPackBo bo, AiScenarioPack exists) {
         entity.setPackCode(normalizeCode(bo.getPackCode()));
         entity.setPackName(StringUtils.trim(bo.getPackName()));
         entity.setDescription(StringUtils.trim(bo.getDescription()));
         if (StringUtils.isBlank(entity.getStatus())) {
             entity.setStatus(AiScenarioPack.STATUS_ENABLED);
         }
+        Long userId = LoginHelper.getUserId();
+        String scope = visibleScopeSupport.validateScopeForUser(entity.getVisibleScope(),
+            exists == null ? null : exists.getVisibleScope(), userId);
+        entity.setVisibleScope(scope);
+        entity.setOwnerDeptId(visibleScopeSupport.resolveOwnerDeptId(scope, entity.getOwnerDeptId(),
+            exists == null ? null : exists.getOwnerDeptId(), userId));
     }
 
     /**
@@ -442,9 +465,8 @@ public class AiScenarioPackServiceImpl implements IAiScenarioPackService {
             return List.of();
         }
         List<Long> result = new ArrayList<>(new LinkedHashSet<>(skillIds));
-        for (Long skillId : result) {
-            skillService.getEnabledSkill(skillId);
-        }
+        // 可见且启用:避免通过包绑定到当前用户生效范围之外的技能
+        skillService.validateVisible(result, LoginHelper.getUserId(), "绑定");
         return result;
     }
 
@@ -471,8 +493,8 @@ public class AiScenarioPackServiceImpl implements IAiScenarioPackService {
      * @return 是否可见
      */
     private boolean visibleTo(AiScenarioPack pack, Long userId) {
-        // 可见口径(去部门/权限维度):内置 or 创建人本人
-        return "1".equals(pack.getIsBuiltin()) || Objects.equals(pack.getCreateBy(), userId);
+        return visibleScopeSupport.visibleTo(pack.getVisibleScope(), pack.getOwnerDeptId(),
+            pack.getCreateBy(), userId);
     }
 
     /**

+ 30 - 7
ai-server/src/main/java/com/zsjz/ai/module/ai/service/impl/AiSkillServiceImpl.java

@@ -18,6 +18,7 @@ import com.zsjz.ai.module.ai.mapper.AiSkillMapper;
 import com.zsjz.ai.module.ai.mapper.AiSkillResourceMapper;
 import com.zsjz.ai.module.ai.mapper.AiToolCallLogMapper;
 import com.zsjz.ai.module.ai.service.IAiSkillService;
+import com.zsjz.ai.module.ai.support.VisibleScopeSupport;
 import com.zsjz.ai.common.compat.PageResult;
 import com.zsjz.ai.common.compat.ServiceException;
 import com.zsjz.ai.common.compat.MapstructUtils;
@@ -105,11 +106,18 @@ public class AiSkillServiceImpl implements IAiSkillService {
 
     private final UserService userService;
 
+    private final VisibleScopeSupport visibleScopeSupport;
+
     @Override
     public PageResult<AiSkillVo> queryPageList(AiSkillBo bo, PageQuery pageQuery) {
-        Page<AiSkillVo> result = baseMapper.selectVoPage(pageQuery.build(), buildQueryWrapper(bo));
+        Long userId = LoginHelper.getUserId();
+        LambdaQueryWrapper<AiSkill> lqw = buildQueryWrapper(bo);
+        visibleScopeSupport.applyVisible(lqw, AiSkill::getVisibleScope,
+            AiSkill::getOwnerDeptId, AiSkill::getCreateBy, userId);
+        Page<AiSkillVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
         List<AiSkillVo> records = result.getRecords();
         fillDisplayFields(records);
+        records.forEach(vo -> vo.setCanManage(visibleScopeSupport.canManage(vo.getCreateBy(), userId)));
         return PageResult.build(records, result.getTotal());
     }
 
@@ -119,6 +127,11 @@ public class AiSkillServiceImpl implements IAiSkillService {
         if (vo == null) {
             throw new ServiceException("技能不存在或已被删除");
         }
+        Long userId = LoginHelper.getUserId();
+        if (!visibleScopeSupport.visibleTo(vo.getVisibleScope(), vo.getOwnerDeptId(), vo.getCreateBy(), userId)) {
+            throw new ServiceException("技能不存在或不在你的可见范围内");
+        }
+        vo.setCanManage(visibleScopeSupport.canManage(vo.getCreateBy(), userId));
         fillDisplayFields(List.of(vo));
         LambdaQueryWrapper<AiSkillResource> lqw = Wrappers.lambdaQuery();
         lqw.eq(AiSkillResource::getId, id);
@@ -136,7 +149,7 @@ public class AiSkillServiceImpl implements IAiSkillService {
         add.setDescription(StringUtils.trim(bo.getDescription()));
         add.setSkillContent(composeSkillContent(name, add.getDescription(), bo.getSkillBody()));
         add.setSource(AiSkill.SOURCE_BIZBUDDY);
-        applyDefaults(add);
+        applyDefaults(add, null);
         validNameUnique(add);
         LocalDateTime now = LocalDateTime.now();
         add.setCreatedAt(now);
@@ -157,6 +170,7 @@ public class AiSkillServiceImpl implements IAiSkillService {
         if (exists == null) {
             throw new ServiceException("技能不存在或已被删除");
         }
+        visibleScopeSupport.requireCanManage(exists.getCreateBy(), LoginHelper.getUserId(), "技能");
         String name = normalizeName(bo.getName());
         if (!exists.getName().equals(name)) {
             throw new ServiceException("技能标识不允许修改(已作为 AgentScope 的 skillId 使用)");
@@ -165,7 +179,7 @@ public class AiSkillServiceImpl implements IAiSkillService {
         update.setName(name);
         update.setDescription(StringUtils.trim(bo.getDescription()));
         update.setSkillContent(composeSkillContent(name, update.getDescription(), bo.getSkillBody()));
-        applyDefaults(update);
+        applyDefaults(update, exists);
         update.setUpdatedAt(LocalDateTime.now());
         update.setUpdateBy(LoginHelper.getUserId());
         boolean flag = baseMapper.updateById(update) > 0;
@@ -185,6 +199,10 @@ public class AiSkillServiceImpl implements IAiSkillService {
         if (list.size() != ids.size()) {
             throw new ServiceException("技能不存在或已被删除");
         }
+        Long userId = LoginHelper.getUserId();
+        for (AiSkill item : list) {
+            visibleScopeSupport.requireCanManage(item.getCreateBy(), userId, "技能");
+        }
         LambdaQueryWrapper<AiAgentSkill> lqw = Wrappers.lambdaQuery();
         lqw.in(AiAgentSkill::getSkillId, ids);
         if (agentSkillMapper.selectCount(lqw) > 0) {
@@ -465,10 +483,16 @@ public class AiSkillServiceImpl implements IAiSkillService {
      *
      * @param entity 实体
      */
-    private void applyDefaults(AiSkill entity) {
+    private void applyDefaults(AiSkill entity, AiSkill exists) {
         if (StringUtils.isBlank(entity.getStatus())) {
             entity.setStatus(AiSkill.STATUS_ENABLED);
         }
+        Long userId = LoginHelper.getUserId();
+        String scope = visibleScopeSupport.validateScopeForUser(entity.getVisibleScope(),
+            exists == null ? null : exists.getVisibleScope(), userId);
+        entity.setVisibleScope(scope);
+        entity.setOwnerDeptId(visibleScopeSupport.resolveOwnerDeptId(scope, entity.getOwnerDeptId(),
+            exists == null ? null : exists.getOwnerDeptId(), userId));
     }
 
     /**
@@ -573,9 +597,8 @@ public class AiSkillServiceImpl implements IAiSkillService {
         if (onlyEnabled) {
             lqw.eq(AiSkill::getStatus, AiSkill.STATUS_ENABLED);
         }
-        // 可见口径(去部门/权限维度):内置 or 创建人本人
-        lqw.and(w -> w.eq(AiSkill::getIsBuiltin, "1")
-            .or(o -> o.eq(AiSkill::getCreateBy, userId)));
+        visibleScopeSupport.applyVisible(lqw, AiSkill::getVisibleScope,
+            AiSkill::getOwnerDeptId, AiSkill::getCreateBy, userId);
         lqw.orderByDesc(AiSkill::getUpdatedAt);
         return lqw;
     }

+ 223 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/support/VisibleScopeSupport.java

@@ -0,0 +1,223 @@
+package com.zsjz.ai.module.ai.support;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
+import com.zsjz.ai.common.compat.LoginHelper;
+import com.zsjz.ai.common.compat.ServiceException;
+import com.zsjz.ai.common.compat.StringUtils;
+import com.zsjz.ai.common.model.perm.entity.SysUser;
+import com.zsjz.ai.module.perm.mapper.SysUserMapper;
+import lombok.RequiredArgsConstructor;
+import org.springframework.stereotype.Component;
+
+import java.util.Objects;
+
+/**
+ * 可见范围(记录级数据权限)统一工具。
+ *
+ * <p>三档口径与 BizBuddy 一致:</p>
+ * <ul>
+ *   <li>{@link #SCOPE_ALL}:全员 / 公开;</li>
+ *   <li>{@link #SCOPE_DEPT}:本部门({@code owner_dept_id = 当前用户部门});</li>
+ *   <li>{@link #SCOPE_SELF}:仅创建人 / 仅本人({@code create_by = 当前用户})。</li>
+ * </ul>
+ *
+ * <p>超管(user_id=1 或持有 superadmin 角色)不受可见范围过滤;普通用户不能把数据设置为
+ * {@link #SCOPE_ALL},仅超管可设置。可见范围为空的历史数据按「全员/公开」处理。</p>
+ *
+ * <p>本工具只依赖用户表查询,不依赖 Sa-Token 请求上下文,可在 Reactor 编排线程中安全使用。</p>
+ *
+ * @author BizBuddy
+ */
+@Component
+@RequiredArgsConstructor
+public class VisibleScopeSupport {
+
+    /**
+     * 可见范围:全员 / 公开
+     */
+    public static final String SCOPE_ALL = "0";
+
+    /**
+     * 可见范围:本部门
+     */
+    public static final String SCOPE_DEPT = "1";
+
+    /**
+     * 可见范围:仅创建人 / 仅本人
+     */
+    public static final String SCOPE_SELF = "2";
+
+    private final SysUserMapper userMapper;
+
+    /**
+     * 查询用户所属部门。
+     *
+     * @param userId 用户主键
+     * @return 部门主键;用户不存在时返回 null
+     */
+    public Long deptIdOf(Long userId) {
+        if (userId == null) {
+            return null;
+        }
+        SysUser user = userMapper.selectById(userId);
+        return user == null ? null : user.getDeptId();
+    }
+
+    /**
+     * 在查询条件上追加「指定用户可见」过滤。
+     *
+     * @param lqw             查询条件
+     * @param scopeColumn     可见范围列
+     * @param ownerDeptColumn 归属部门列
+     * @param createByColumn  创建人列
+     * @param userId          当前用户主键
+     * @param <T>             实体类型
+     */
+    public <T> void applyVisible(LambdaQueryWrapper<T> lqw,
+                                 SFunction<T, ?> scopeColumn,
+                                 SFunction<T, ?> ownerDeptColumn,
+                                 SFunction<T, ?> createByColumn,
+                                 Long userId) {
+        if (userId == null) {
+            // 无法识别用户时按最严处理:不放行任何数据
+            lqw.apply("1 = 0");
+            return;
+        }
+        if (LoginHelper.isSuperAdmin(userId)) {
+            return;
+        }
+        Long deptId = deptIdOf(userId);
+        lqw.and(w -> w
+            .and(p -> p.isNull(scopeColumn).or().eq(scopeColumn, "").or().eq(scopeColumn, SCOPE_ALL))
+            .or(deptId != null, p -> p.eq(scopeColumn, SCOPE_DEPT).eq(ownerDeptColumn, deptId))
+            .or(p -> p.eq(scopeColumn, SCOPE_SELF).eq(createByColumn, userId)));
+    }
+
+    /**
+     * 判断单条记录对指定用户是否可见。
+     *
+     * @param scope       可见范围
+     * @param ownerDeptId 归属部门主键
+     * @param createBy    创建人主键
+     * @param userId      当前用户主键
+     * @return 是否可见
+     */
+    public boolean visibleTo(String scope, Long ownerDeptId, Long createBy, Long userId) {
+        if (userId == null) {
+            return false;
+        }
+        if (LoginHelper.isSuperAdmin(userId)) {
+            return true;
+        }
+        String value = StringUtils.isBlank(scope) ? SCOPE_ALL : StringUtils.trim(scope);
+        return switch (value) {
+            case SCOPE_ALL -> true;
+            case SCOPE_DEPT -> ownerDeptId != null && Objects.equals(ownerDeptId, deptIdOf(userId));
+            case SCOPE_SELF -> Objects.equals(createBy, userId);
+            default -> false;
+        };
+    }
+
+    /**
+     * 判断指定用户是否可修改 / 删除某条记录。
+     *
+     * @param createBy 创建人主键
+     * @param userId   当前用户主键
+     * @return 是否可管理
+     */
+    public boolean canManage(Long createBy, Long userId) {
+        return userId != null && (LoginHelper.isSuperAdmin(userId) || Objects.equals(createBy, userId));
+    }
+
+    /**
+     * 校验指定用户可修改 / 删除某条记录。
+     *
+     * @param createBy 创建人主键
+     * @param userId   当前用户主键
+     * @param scene    业务名称(用于提示)
+     */
+    public void requireCanManage(Long createBy, Long userId, String scene) {
+        if (!canManage(createBy, userId)) {
+            throw new ServiceException("无权操作该" + scene + ":仅创建人或超级管理员可操作");
+        }
+    }
+
+    /**
+     * 新数据的默认可见范围:超管默认全员/公开,普通用户默认仅自己/仅本人。
+     *
+     * @param userId 当前用户主键
+     * @return 默认可见范围
+     */
+    public String defaultScope(Long userId) {
+        return LoginHelper.isSuperAdmin(userId) ? SCOPE_ALL : SCOPE_SELF;
+    }
+
+    /**
+     * 规范化可见范围:空值取回退值,非法值直接拒绝。
+     *
+     * @param scope    原始可见范围
+     * @param fallback 回退值
+     * @return 规范化后的可见范围
+     */
+    public String normalizeScope(String scope, String fallback) {
+        String value = StringUtils.trim(scope);
+        if (StringUtils.isBlank(value)) {
+            return StringUtils.isBlank(fallback) ? SCOPE_ALL : StringUtils.trim(fallback);
+        }
+        if (!SCOPE_ALL.equals(value) && !SCOPE_DEPT.equals(value) && !SCOPE_SELF.equals(value)) {
+            throw new ServiceException("可见范围取值不合法");
+        }
+        return value;
+    }
+
+    /**
+     * 按当前用户身份校验并规范化可见范围。
+     *
+     * <p>普通用户不允许新设置为全员/公开;但历史数据原本就是全员/公开时,允许保留原值,
+     * 避免编辑时被迫降级。</p>
+     *
+     * @param scope         本次提交的可见范围(可为空)
+     * @param existingScope 数据库中的原可见范围(新增时为空)
+     * @param userId        当前用户主键
+     * @return 生效的可见范围
+     */
+    public String validateScopeForUser(String scope, String existingScope, Long userId) {
+        String fallback = StringUtils.isBlank(existingScope)
+            ? defaultScope(userId) : StringUtils.trim(existingScope);
+        String value = normalizeScope(scope, fallback);
+        if (LoginHelper.isSuperAdmin(userId) || !SCOPE_ALL.equals(value)) {
+            return value;
+        }
+        if (SCOPE_ALL.equals(StringUtils.trim(existingScope))) {
+            return value;
+        }
+        throw new ServiceException("普通用户不能设置全员/公开可见");
+    }
+
+    /**
+     * 解析归属部门:本次提交优先,其次继承原值;选择「本部门」且仍为空时取当前用户部门。
+     *
+     * @param scope               生效的可见范围
+     * @param ownerDeptId         本次提交的归属部门
+     * @param existingOwnerDeptId 数据库中的原归属部门
+     * @param userId              当前用户主键
+     * @return 归属部门主键
+     */
+    public Long resolveOwnerDeptId(String scope, Long ownerDeptId, Long existingOwnerDeptId, Long userId) {
+        if (ownerDeptId != null) {
+            return ownerDeptId;
+        }
+        if (existingOwnerDeptId != null) {
+            return existingOwnerDeptId;
+        }
+        if (!SCOPE_DEPT.equals(scope)) {
+            return null;
+        }
+        Long deptId = deptIdOf(userId);
+        if (deptId == null) {
+            throw new ServiceException("当前用户未配置归属部门,不能设置本部门可见");
+        }
+        return deptId;
+    }
+}

+ 31 - 1
sql/ai_orchestration.sql

@@ -1,5 +1,5 @@
 -- biz-buddy 智能体体系数据表(迁移自 postgres_ry_ai.sql)
--- 去 RuoYi 列:create_dept/create_by/update_by/del_flag/tenant_id/owner_dept_id/visible_scope
+-- 去 RuoYi 列:create_dept/del_flag/tenant_id;保留 owner_dept_id/visible_scope 作为本项目可见范围治理列
 -- 幂等:create table / index if not exists,可重复执行
 
 -- dev 库可能存在同名旧表:先删后建(用户已确认)
@@ -109,6 +109,8 @@ create unique index if not exists uk_ai_model_config_name on ai_model_config (co
 
 create table if not exists ai_knowledge_base (
     is_builtin      char(1)        default '0',
+    owner_dept_id        bigint,
+    visible_scope        char(1)      default '0',
     id                   bigint        not null,
     kb_name              varchar(100)  not null,
     kb_code              varchar(100)  not null,
@@ -135,6 +137,10 @@ create table if not exists ai_knowledge_base (
 
 comment on table ai_knowledge_base is 'AI 知识库表';
 
+comment on column ai_knowledge_base.owner_dept_id is '归属部门(生效范围=本部门时生效)';
+
+comment on column ai_knowledge_base.visible_scope is '生效范围(0公开 1本部门 2仅本人)';
+
 comment on column ai_knowledge_base.kb_code is '知识库编码(唯一,用于命名 Milvus 集合)';
 
 comment on column ai_knowledge_base.embedding_model_id is '向量模型(ai_model_config.id,model_type=embedding)';
@@ -272,6 +278,8 @@ alter table ai_chunk add column if not exists char_end integer;
 
 create table if not exists ai_entry_agent (
     is_builtin      char(1)        default '0',
+    owner_dept_id       bigint,
+    visible_scope       char(1)      default '0',
     id                  bigint       not null,
     agent_name          varchar(100) not null,
     agent_code          varchar(100) not null,
@@ -297,6 +305,10 @@ create table if not exists ai_entry_agent (
 
 comment on table ai_entry_agent is 'AI 入口智能体表(全平台唯一,恒 1 行;REQ-AI-33 起由 ai_agent 拆出)';
 
+comment on column ai_entry_agent.owner_dept_id is '归属部门(可见范围=本部门时生效)';
+
+comment on column ai_entry_agent.visible_scope is '可见范围(0全员 1本部门 2仅创建人)';
+
 comment on column ai_entry_agent.agent_code is '智能体编码(唯一,作为 AgentScope 的 agent name)';
 
 comment on column ai_entry_agent.singleton is '单例行标记(恒 1,配合唯一索引强制「入口智能体全平台唯一」)';
@@ -308,6 +320,8 @@ create unique index if not exists uk_ai_entry_agent_singleton on ai_entry_agent
 
 create table if not exists ai_expert_agent (
     is_builtin      char(1)        default '0',
+    owner_dept_id        bigint,
+    visible_scope        char(1)      default '0',
     id                   bigint       not null,
     agent_name           varchar(100) not null,
     agent_code           varchar(100) not null,
@@ -338,6 +352,10 @@ create table if not exists ai_expert_agent (
 
 comment on table ai_expert_agent is 'AI 专家智能体表(可被入口智能体路由;REQ-AI-33 起由 ai_agent 拆出)';
 
+comment on column ai_expert_agent.owner_dept_id is '归属部门(可见范围=本部门时生效)';
+
+comment on column ai_expert_agent.visible_scope is '可见范围(0全员 1本部门 2仅创建人)';
+
 comment on column ai_expert_agent.agent_code is '智能体编码(唯一,作为 AgentScope 的 agent name 与路由专家 key)';
 
 comment on column ai_expert_agent.expert_domain is '专家领域标签(2026-10-02 起定义页已移除该输入项、不再参与换专家;仅存列)';
@@ -898,6 +916,8 @@ create unique index if not exists uk_ai_tool_tag_rel on ai_tool_tag_rel (tool_id
 
 create table if not exists ai_skill (
     is_builtin      char(1)        default '0',
+    owner_dept_id   bigint,
+    visible_scope   char(1)      default '0',
     id            bigint       not null,
     name          varchar(255) not null,
     description   text         not null,
@@ -915,6 +935,10 @@ create table if not exists ai_skill (
 
 comment on table ai_skill is 'AI 技能表(正文即 SKILL.md;列结构兼容 AgentScope PostgreSQL 技能仓库)';
 
+comment on column ai_skill.owner_dept_id is '归属部门(生效范围=本部门时生效)';
+
+comment on column ai_skill.visible_scope is '生效范围(0公开 1本部门 2仅本人)';
+
 comment on column ai_skill.name is '技能标识(唯一,即 AgentScope 的 skillId)';
 
 comment on column ai_skill.description is '技能用途说明(供模型判断是否加载)';
@@ -1126,6 +1150,8 @@ create index if not exists idx_ai_trace_create_time on ai_trace (create_time);
 
 create table if not exists ai_scenario_pack (
     is_builtin      char(1)        default '0',
+    owner_dept_id   bigint,
+    visible_scope   char(1)      default '0',
     id            bigint       not null,
     pack_code     varchar(64)  not null,
     pack_name     varchar(100) not null,
@@ -1141,6 +1167,10 @@ create table if not exists ai_scenario_pack (
 
 comment on table ai_scenario_pack is 'AI 场景包定义表(按角色 / 部门打包业务工具 + MCP 工具 + 技能,对话时选用以增强能力)';
 
+comment on column ai_scenario_pack.owner_dept_id is '归属部门(生效范围=本部门时生效)';
+
+comment on column ai_scenario_pack.visible_scope is '生效范围(0公开 1本部门 2仅本人)';
+
 comment on column ai_scenario_pack.pack_code is '场景包编码(唯一,创建后不可修改)';
 
 comment on column ai_scenario_pack.pack_name is '场景包名称(如「财务场景包」「人力场景包」)';

+ 115 - 0
sql/ai_visible_scope_20261118.sql

@@ -0,0 +1,115 @@
+-- ============================================================
+-- AI 记录级数据权限:可见范围(visible_scope)+ 归属部门(owner_dept_id)
+--
+-- 适用表:ai_entry_agent / ai_expert_agent / ai_skill / ai_scenario_pack / ai_knowledge_base
+-- 执行方式:手工在目标库执行(项目无 Flyway/Liquibase),脚本幂等,可重复执行。
+--
+-- 存量语义保持:
+--   * 入口智能体为全局单例,空值统一按「全员」处理;
+--   * 其余表原口径为「内置 or 创建人本人」,故内置数据回填 '0'(全员/公开),
+--     非内置数据回填 '2'(仅创建人/本人),避免存量私有数据被意外公开。
+--   * 已存在旧 visible_scope 值(如从 bizbuddy 迁移的库)时保留原值,不覆盖。
+-- ============================================================
+
+-- ---------- 1. 加列(先不加默认值,便于区分存量空值) ----------
+alter table ai_entry_agent    add column if not exists owner_dept_id bigint;
+alter table ai_entry_agent    add column if not exists visible_scope char(1);
+
+alter table ai_expert_agent   add column if not exists owner_dept_id bigint;
+alter table ai_expert_agent   add column if not exists visible_scope char(1);
+
+alter table ai_skill          add column if not exists owner_dept_id bigint;
+alter table ai_skill          add column if not exists visible_scope char(1);
+
+alter table ai_scenario_pack  add column if not exists owner_dept_id bigint;
+alter table ai_scenario_pack  add column if not exists visible_scope char(1);
+
+alter table ai_knowledge_base add column if not exists owner_dept_id bigint;
+alter table ai_knowledge_base add column if not exists visible_scope char(1);
+
+-- ---------- 2. 存量数据回填 ----------
+-- 入口智能体:全局单例,空值按全员处理
+update ai_entry_agent
+   set visible_scope = '0'
+ where visible_scope is null or visible_scope = '';
+
+-- 其余四类:内置 -> 全员/公开;非内置 -> 仅创建人/本人
+update ai_expert_agent
+   set visible_scope = case when is_builtin = '1' then '0' else '2' end
+ where visible_scope is null or visible_scope = '';
+
+update ai_skill
+   set visible_scope = case when is_builtin = '1' then '0' else '2' end
+ where visible_scope is null or visible_scope = '';
+
+update ai_scenario_pack
+   set visible_scope = case when is_builtin = '1' then '0' else '2' end
+ where visible_scope is null or visible_scope = '';
+
+update ai_knowledge_base
+   set visible_scope = case when is_builtin = '1' then '0' else '2' end
+ where visible_scope is null or visible_scope = '';
+
+-- 旧数据已指定「本部门」但归属部门为空:按创建人部门补齐
+update ai_entry_agent a
+   set owner_dept_id = u.dept_id
+  from perm_user u
+ where a.owner_dept_id is null
+   and a.visible_scope = '1'
+   and a.create_by = u.user_id
+   and u.dept_id is not null;
+
+update ai_expert_agent a
+   set owner_dept_id = u.dept_id
+  from perm_user u
+ where a.owner_dept_id is null
+   and a.visible_scope = '1'
+   and a.create_by = u.user_id
+   and u.dept_id is not null;
+
+update ai_skill a
+   set owner_dept_id = u.dept_id
+  from perm_user u
+ where a.owner_dept_id is null
+   and a.visible_scope = '1'
+   and a.create_by = u.user_id
+   and u.dept_id is not null;
+
+update ai_scenario_pack a
+   set owner_dept_id = u.dept_id
+  from perm_user u
+ where a.owner_dept_id is null
+   and a.visible_scope = '1'
+   and a.create_by = u.user_id
+   and u.dept_id is not null;
+
+update ai_knowledge_base a
+   set owner_dept_id = u.dept_id
+  from perm_user u
+ where a.owner_dept_id is null
+   and a.visible_scope = '1'
+   and a.create_by = u.user_id
+   and u.dept_id is not null;
+
+-- ---------- 3. 新数据默认值 ----------
+alter table ai_entry_agent    alter column visible_scope set default '0';
+alter table ai_expert_agent   alter column visible_scope set default '0';
+alter table ai_skill          alter column visible_scope set default '0';
+alter table ai_scenario_pack  alter column visible_scope set default '0';
+alter table ai_knowledge_base alter column visible_scope set default '0';
+
+-- ---------- 4. 列注释 ----------
+comment on column ai_entry_agent.owner_dept_id is '归属部门(可见范围=本部门时生效)';
+comment on column ai_entry_agent.visible_scope is '可见范围(0全员 1本部门 2仅创建人)';
+
+comment on column ai_expert_agent.owner_dept_id is '归属部门(可见范围=本部门时生效)';
+comment on column ai_expert_agent.visible_scope is '可见范围(0全员 1本部门 2仅创建人)';
+
+comment on column ai_skill.owner_dept_id is '归属部门(生效范围=本部门时生效)';
+comment on column ai_skill.visible_scope is '生效范围(0公开 1本部门 2仅本人)';
+
+comment on column ai_scenario_pack.owner_dept_id is '归属部门(生效范围=本部门时生效)';
+comment on column ai_scenario_pack.visible_scope is '生效范围(0公开 1本部门 2仅本人)';
+
+comment on column ai_knowledge_base.owner_dept_id is '归属部门(生效范围=本部门时生效)';
+comment on column ai_knowledge_base.visible_scope is '生效范围(0公开 1本部门 2仅本人)';