规则/模板/提示词三层体系设计文档

规则/模板/提示词 — 分层存储完整实施方案

目标:将 BossAgents 的 2,371 条规则 + 1,205 条模板 + 2,817 条提示词从单一本地 SQLite 升级为三层存储架构(SCSAI 标准库 → 本地缓存 → 用户私有库),支持标准数据同步、用户个性化覆盖、审核提交流程。


第一部分:现状全链路(代码级)

一、生成 — 三条脚本流水线

1.1 import-aml-v2.js(1672行,离线 CLI)

node scripts/import-aml-v2.js               # 增量
node scripts/import-aml-v2.js --full        # 全量重建
node scripts/import-aml-v2.js --patch       # 修补
node scripts/import-aml-v2.js --generate-prompts  # 仅提示词

扫描目录PLM/Import/(标准 PLM AML)+ SCIOT/SCIOT/(按业务模块组织,约 636 个 .xml)

全量过程main() → L1456):

| 阶段 | 函数 | 产物(行数) |

|------|------|-------------|

| 1 | importItemType() | sciot_item_types(928) / sciot_properties(40854) / sciot_methods / sciot_relationships(587) / sciot_permissions / sciot_lists / sciot_list_values |

| 2 | 关联 Method→ItemType(名称前缀匹配) | — |

| 3 | crossFileLinking() | 生命周期/LCM/Form/Method→ItemType 关联 |

| 4 | backfillTemplates() | sciot_templates(1205) — 从 properties+relationships+lifecycle+forms 四表推导 |

| 5 | generateEnhancedRules() | sciot_rules_v2 — 按属性 + 生命周期 + 关系生成 |

| 6 | generateDynamicPrompts() | sciot_prompts(638) — 带 {{}} 占位符的动态模板 |

| 7 | pregeneratePromptTemplates() | prompt_templates(2817) — 完整 LLM 提示词 |

| 7' | generateBusinessPrompts() | sciot_business_prompts(46) |

核心数据流

sciot_item_types ──→┬──→ sciot_properties ──→ backfillTemplates() ──→ sciot_templates (派生)
                     ├──→ sciot_relationships ─┘
                     ├──→ sciot_lifecycle_maps ─┘
                     └──→ sciot_forms ────────────┘

sciot_templates     ──→ pregeneratePromptTemplates() ──→ prompt_templates (派生)
sciot_properties    ──→ generateEnhancedRules() ──────→ sciot_rules_v2 (派生)

1.2 generate-operation-rules.js(725行,离线 CLI)

node scripts/generate-operation-rules.js
node scripts/generate-operation-rules.js --full
node scripts/generate-operation-rules.js --dry-run

依赖:必须在 import-aml-v2.js --full 完成后运行。

| 阶段 | 输入 → 输出 |

|------|------------|

| 1 generateRelationshipRules() | sciot_relationshipssciot_rules_v2(关系规则) |

| 2 generateMethodTriggerRules() | sciot_method_rulessciot_rules_v2(自动编号/创建规则) |

| 3 generateValidationRules() | sciot_propertiessciot_rules_v2(校验/默认值规则) |

| 3b generateMissingTemplates() | sciot_item_typessciot_templates(补缺) |

| 4 generateOperationPrompts() | sciot_templatesprompt_templates(add/edit/get 提示词) |

| 5 补全元字段 | operation_typescope 等 |

1.3 prompt_templates 表的特殊 DDL

没有统一 DDL 契约,三处独立创建:

  1. generate-operation-rules.js L423: PRAGMA table_infoALTER TABLE ADD COLUMN
  2. aml.js L706: 运行时懒创建:
sciotDb.exec(`CREATE TABLE IF NOT EXISTS prompt_templates (
  id TEXT PRIMARY KEY, name TEXT, content TEXT,
  prompt_type TEXT DEFAULT 'creation', item_type_name TEXT,
  version INTEGER DEFAULT 1, status TEXT DEFAULT 'active',
  created_at TEXT, updated_at TEXT
)`);
  1. rule-engine.js: _ensureTables() 中同样有创建逻辑

二、保存 — 数据位置

2.1 物理存储

| 文件 | 大小 | 位置 |

|------|------|------|

| sciot_import.db | ~38MB | server/data/sciot_import.db |

2.2 核心表清单

行数数据性质依赖上游
sciot_item_types928原始(AML XML)
sciot_properties40,854原始
sciot_relationships587原始
sciot_lifecycle_maps~191原始
sciot_forms631原始
sciot_templates1,205派生 ← 四表联合properties+relationships+lifecycle+forms
sciot_rules_v22,371派生 ← properties+relationships+methods各原始表
prompt_templates2,817派生 ← sciot_templatessciot_templates
sciot_prompts638旧版提示词(遗留)
sciot_business_prompts46业务提示词business_systems + business_objects

2.3 数据派生层级图

                                    import-aml-v2.js
                                          │
     ┌────────────────────────────────────┼─────────────────────┐
     │                │                   │                     │
sciot_item_types  sciot_properties   sciot_relationships  lifecycle_maps+forms
     │                │                   │                     │
     └────────────────┼───────────────────┼─────────────────────┘
                      │                   │
              backfillTemplates()   generateRelationshipRules()
                      │                   │
                sciot_templates     sciot_rules_v2 (部分)
                 (1,205)             (2,371)
                      │
             pregeneratePromptTemplates()
                      │
                prompt_templates    ←── generate-operation-rules.js
                 (2,817)

三、管理 — 后端 API 双线运营

3.1 aml.js(7002行)

规则 CRUD:   GET/POST /api/aml/sciot/rules[/add|/batch-toggle|/batch-delete]
模板读取:     GET       /api/aml/sciot/templates[/:name]
提示词管理:   GET/POST  /api/aml/sciot/prompts|/optimize-prompt/:typeName|/business-prompts[/regenerate]
组装器:       GET/POST  /api/aml/assemble[/:name|/validate]
统计+状态:    GET       /api/aml/sciot/stats|/status|/types

3.2 rule-engine.js(1203行)— 第二套并行 API

规则 CRUD:   GET/POST/PUT/DELETE /api/rule-engine/rules[/:id]
               POST /api/rule-engine/rules/batch-toggle|/batch-delete|/export|/import
规则执行:     POST /api/rule-engine/execute/:scope|/identify|/validate|/repair|/pregenerate-prompt

前端调用:两套 API 同时在使用

  • fetch('/api/aml/sciot/rules?...') — SCIOT Tab
  • fetch('/api/rules/list?...') — 规则引擎 Tab

四、使用 — 前端消费链路

4.1 创建对象主链路(app.js L5460-5800)— 最核心链路

① 加载面板数据
   GET /api/aml/sciot/rules/stats
   GET /api/aml/sciot/business-prompts
   GET /api/aml/sciot/templates

② 选 ItemType → 读模板 + 规则
   GET /api/aml/sciot/templates/:name   → schema(llm_fields/auto_fields)
   GET /api/aml/sciot/rules?item_type=   → 该类型所有规则
   前端组装 schema(客户端完成)

③ 前端验证 validateBySchema()
④ 前端组装 AML objToAmlAdd()

⑤ 前端直调 SCSAI(绕过 BossAgents 后端)
   SCSAIApplyAML(aml) → bomService._SCSAIApiRequest('ApplyItem', aml)
   → POST https://ylxt.chat/scplm/server/agentServer.aspx

⑥ 如果是 ItemType,继续创建属性/关系/权限(同样前端直调)

关键点:BossAgents 后端在第②步后不再参与,第③-⑥步全在前端完成。创建结果不写回 sciot_import.db

4.2 规则引擎使用路径(AI Workbench)

用户描述需求
  → 读 prompt_templates(按 operation_type=add/edit/get)
  → 结构化组合提示词(含 rules 描述)
  → 调 LLM 生成 AML
  → aml-assembler 验证 + 规则引擎校验
  → 调 SCSAI AML API

五、SCSAI 服务端现状

| 项目 | 值 |

|------|-----|

| 入口 | https://ylxt.chat/scplm |

| 认证 | Basic (root) |

| 数据库 | SCPLM |

BossAgents 相关 ItemType 扫描结果

| SCSAI ItemType | 数据量 | 与 BossAgents 的关系 |

|--------------|--------|---------------------|

| Rule | 1 条(空) | SCSAI 平台自身管理用,与 sciot_rules_v2 的 2371 条无关 |

| Template | 15 条 | SCSAI 原生模板(Action/Form/Identity),与 sciot_templates 的 1205 条无关 |

| RuleDefinition | 0 | — |

| TemplateDefinition | 0 | — |

| RuleExecutionHistory | 0 | — |

| Template_Rule_Link | 1 条 | 多对多关联模式可参考 |

结论:BossAgents 的 2,371+1,205+2,817+46 条数据全在本地 SQLite,SCSAI 上零数据。需要新建 5 个自定义 ItemType


第二部分:SCSAI 分层存储实施方案

六、核心设计决策

决策点结论理由
SCSAI 定位主库。标准数据以 SCSAI 为准,sciot_import.db 降为缓存持久化 + 灾备
派生数据同步策略同步最终结果(sciot_templates 独立数据),不是源表派生逻辑复杂度高,两端重算易不一致
流水线改造不变本地生成,--push-SCSAI 选项推结果到 SCSAI最小化侵入
认证Phase 1 固定 userId='default'当前无登录系统
两套并行 API都加 userId 参数,都支持 getEffectiveRules() 合并兼容前端双 Tab 调用
前端绕过问题规则校验走后端 POST /api/rule-engine/validate后端才有 getEffectiveRules()

6.1 分层架构

┌─────────────────────────────────────────────────────────────────────┐
│  SCSAI 服务端 (ylxt.chat/scplm) — 标准库                       │
│                                                                      │
│  BossAgent_Rule          存标准规则(可被用户覆盖)                   │
│  BossAgent_Template      存标准模板                                   │
│  BossAgent_Prompt        存标准提示词                                 │
│  BossAgent_BizPrompt     存业务提示词                                 │
│  BossAgent_RuleContribution  存用户提交审核                            │
└────────────────┬────────────────────────────────────────────────────┘
                 │ AML get/add/edit (SOAP)
                 ▼
┌─────────────────────────────────────────────────────────────────────┐
│  sciot_import.db — 本地标准缓存 + 派生数据工厂                       │
│                                                                      │
│  [不变] 现有 23 张基础表 + sciot_rules_v2 / sciot_templates         │
│         / prompt_templates / sciot_business_prompts                   │
│  [新增] sync_state: 记录 SCSAI 同步版本                               │
│         sync_pending: 本地修改待同步 SCSAI                             │
└────────────────┬────────────────────────────────────────────────────┘
                 │ sync-service 增量同步
                 ▼
┌─────────────────────────────────────────────────────────────────────┐
│  user_libraries/user_{userId}.db — 用户私有库                         │
│                                                                      │
│  user_rules:      source = standard_copy | modified | custom         │
│  user_templates:  同上                                                │
│  user_prompts:    同上                                                │
│  sync_submissions: 待审核修改                                         │
│  sync_state:      同步状态                                            │
└────────────────┬────────────────────────────────────────────────────┘
                 │ getEffectiveRules() 优先级合并
                 ▼
┌─────────────────────────────────────────────────────────────────────┐
│  适配层 (aml.js / rule-engine.js)                                     │
│  getEffectiveRules(userId) → 合并后规则列表                           │
└─────────────────────────────────────────────────────────────────────┘

6.2 执行优先级

自定义 (custom)  >  用户修改版 (modified)  >  标准副本 (standard_copy)  >  SCSAI 标准  >  默认回退

规则:
  1. 同一 id:modified → standard_copy → SCSAI 标准(依次覆盖)
  2. 不同 id:全量合并(不排他)
  3. custom:直接追加,不与标准去重

七、SCSAI ItemType 字段设计

7.1 BossAgent_Rule(标准规则)

| 字段名 | SCSAI 类型 | SQLite 对应列 | 说明 |

|--------|-----------|--------------|------|

| item_number | string(32, auto) | id | 自动编号 |

| name | string(256, REQ) | name | 规则名称 |

| description | text | description | 规则描述 |

| bossagent_scope | list | scope | validate/create_pre/identify/… |

| bossagent_item_type | string(128) | item_type_name | 关联对象类 |

| bossagent_severity | list | severity | info/warning/error/hint |

| bossagent_category | list | category | data/relationship/lifecycle/method/permission/workflow |

| bossagent_priority | string(10) | priority | P0/P1/P2/P3 |

| bossagent_generated_aml | text | generated_aml | 参考 Rule.generated_aml |

| bossagent_natural_language | text | natural_language | 参考 Rule.natural_language_input |

| bossagent_condition_script | text | condition_script | 条件脚本 |

| bossagent_action_type | list | action_type | auto_fix/suggest/block/warn/reference/generate |

| bossagent_action_config | text | action_config | JSON |

| bossagent_is_active | boolean | is_active | 是否启用 |

| bossagent_is_builtin | boolean | is_builtin | 内置规则 |

| bossagent_source | list | source | generated/manual/auto |

| bossagent_version | integer | version | 版本号 |

| bossagent_tags | string(512) | tags | 标签 |

7.2 BossAgent_Template(标准模板)

字段名SCSAI 类型SQLite 对应列说明
item_numberstring(32, auto)id自动编号
namestring(128, REQ)item_type_name模板名
bossagent_labelstring(128)item_type_label显示名称
bossagent_template_typelisttemplate_typeobject/relationship
bossagent_categorylist分类(参考 Template.category)
bossagent_aml_contenttextaml_template模板 AML(参考 Template.aml_content)
bossagent_variablestextllm_fields + auto_fieldsJSON(参考 Template.variables)
bossagent_required_fieldstextrequired_fieldsJSON
bossagent_optional_fieldstextoptional_fieldsJSON
bossagent_relationship_typestextrelationship_typesJSON
bossagent_lifecyclestring(128)lifecycle默认生命周期
bossagent_formstring(128)form默认表单
bossagent_generation_rulestextgeneration_rules完整 JSON
bossagent_versionintegerversion版本号
bossagent_is_builtinbooleanis_builtin内置模板

7.3 BossAgent_Prompt(标准提示词)

字段名SCSAI 类型SQLite 对应列
item_numberstring(32, auto)id
namestring(256, REQ)name
bossagent_contenttextcontent
bossagent_system_prompttextsystem_prompt
bossagent_item_typestring(128)item_type_name
bossagent_operationlistoperation_type (add/edit/get/generate)
bossagent_scopelistscope
bossagent_versionintegerversion
bossagent_is_builtinbooleanis_builtin
bossagent_statusliststatus (active/deprecated/testing)

7.4 BossAgent_BizPrompt(业务提示词)

字段名SCSAI 类型SQLite 对应列
item_numberstring(32, auto)system_id
namestring(128, REQ)system_name
bossagent_system_idstring(128)system_id
bossagent_system_prompttextprompt
bossagent_context_jsontextcontext_json
bossagent_capabilitiestext

7.5 BossAgent_RuleContribution(审核流程)

字段名SCSAI 类型说明
item_numberstring(32, auto)编号
bossagent_submitterstring(128)提交者
bossagent_object_typelistrule/template/prompt
bossagent_original_idstring(256)原标准 ID
bossagent_contenttext完整 JSON
bossagent_descriptiontext说明
bossagent_statuslistpending/approved/rejected
bossagent_review_commenttext审核意见

八、同步机制 — 三模式

8.1 模式 A:SCSAI → Local(标准缓存刷新)

触发:  cron 每日 2:00 | 手动 | 启动时
方向:  单向 SCSAI → sciot_import.db

流程:
  1. 查询 SCSAI 各 BossAgent_* ItemType 的 modified_on
  2. 对比本地 sync_state.last_sync_at
  3. 有更新 → AML get 拉取增量
  4. 只更新 sciot_import.db 同步副本(不影响原始表)
  5. 更新 sync_state

8.2 模式 B:Local → User(增量推送)

触发:  用户登录 | 手动点击同步
方向:  sciot_import.db → user_libraries/user_{userId}.db

流程:
  1. 用户库不存在 → 全量初始化
  2. 对比标准副本(source='standard_copy')
  3. 新增记录 → 插入
  4. 标准有更新 → 用户未修改时覆盖;用户已修改(source='modified')跳过

8.3 模式 C:User → SCSAI(提交审核)

触发:  用户点击"提交审核"
方向:  user_libraries → SCSAI(含审核流程)

流程:
  1. 用户修改规则 → 本地 source='modified'
  2. 提交审核 → 写入 sync_submissions(before/after + 说明)
  3. 管理员审核(diff 对比 + 审批)
     - approve: AML edit → SCSAI + 更新用户库 source='approved'
     - reject:  写 review_comment,用户可重提

九、改动明细

9.1 生成层

目标:流水线不变,加 --push-SCSAI 选项

import-aml-v2.js(+50行):

// main() 最后
if (process.argv.includes('--push-SCSAI')) {
  await pushToSCSAI();
}

async function pushToSCSAI() {
  const sync = require('../server/services/sync-service');
  await sync.batchWriteToSCSAI('BossAgent_Rule',
    db.prepare('SELECT * FROM sciot_rules_v2 WHERE source = ?').all('generated'), 500);
  await sync.batchWriteToSCSAI('BossAgent_Template',
    db.prepare('SELECT * FROM sciot_templates').all(), 500);
  // 同 prompt_templates → BossAgent_Prompt, sciot_business_prompts → BossAgent_BizPrompt
}

generate-operation-rules.js(+20行):同模式

9.2 保存层

  • 不变:sciot_import.db 现有表结构
  • 新增 sync_state:同步版本记录 / sync_pending:待写回变更

9.3 管理 API 层

#### aml.js

// GET /api/aml/sciot/rules 支持 ?userId=
async function handleSciotRules(req, res, pathname, query, bodyStr) {
  const stdRules = sciotDb.prepare('SELECT * FROM sciot_rules_v2 WHERE ...').all(params);
  if (query.userId && query.userId !== '') {
    const userLib = require('../services/user-library');
    rules = userLib.getEffectiveRules(query.userId, stdRules);
  }
  // 返回合并后结果
}

/api/aml/sciot/templates//api/aml/sciot/prompts:同模式

#### rule-engine.js

// GET /api/rule-engine/rules?userId=
if (filters.userId && filters.userId !== 'default') {
  const stdRules = engine.getRules({ ...filters, userId: null });
  filters.effectiveRules = userLib.getEffectiveRules(filters.userId, stdRules);
}

POST /api/rule-engine/execute/:scope 同样支持 ?userId=

9.4 前端层

#### 创建面板(+50行)

// 改前: validateBySchema(schema, values) → ok → objToAmlAdd → SCSAIApplyAML
// 改后:
//   1. POST /api/rule-engine/validate?userId=default  { item_type, values }
//   2. 后端返回 { valid, errors, fixed_values }
//   3. valid → objToAmlAdd(fixed_values) → SCSAIApplyAML
//             → 客户端+后端双重验证

#### 规则引擎 Tab 扩展(+100行)

  • 现有 6 个 Tab 保持不动
  • 新增第 7 面板 "我的库":查看/修改/自定义/删除规则,提交审核

#### 同步按钮(+30行)

  • 规则引擎 Tab 右上角"同步"按钮 → POST /api/user-library/default/sync/standard

9.5 新增文件

文件行数职责
server/services/user-library.js~600用户库 SQLite 管理:init / getEffectiveRules / CRUD / sync
server/services/sync-service.js~500三层同步:SCSAIToLocal / localToUser / userToSCSAI
server/routes/user-library-routes.js~40014 个 REST API(CRUD + 同步 + 审核)

9.6 数据流对比

改前:
  生成脚本 → sciot_import.db
  API 直读 sciot_import.db
  前端读 API → 前端验证 → 前端装 AML → 直调 SCSAI

改后:
  生成脚本 → sciot_import.db(不变)
            + --push-SCSAI → SCSAI
  启动时自检 → 对比 sync_state → 拉 SCSAI 更新 → 写回 sciot_import.db
  API 读 sciot_import.db + user_libraries(getEffectiveRules 合并)
  前端读 API(含 userId)→ 调 validate(走后端合并规则)→ 前端装 AML → 调 SCSAI
  用户修改 → user_libraries → 提交审核 → 管理员审批 → 写 SCSAI

十、实施阶段

| Phase | 内容 | 预估 |

|-------|------|------|

| 0 准备 | 确认 SCSAI 连接 / DB 结构 / 端口 / 5 个 ItemType 名称不冲突 | 半天 |

| 1 SCSAI 建表 + 全量导入 | 创建 5 个 ItemType + Lists + 字段定义;分批读取(500条/批)写入 SCSAI;重试 3 次;回验 | 1天 |

| 2 sync-service 同步层 | SCSAIToLocal() → localToUser() → userToSCSAI() 三方向 | 1天 |

| 3 适配层 + API 改造 | user-library.js + aml.js/rule-engine.js 改造 + user-library-routes.js | 1.5天 |

| 4 前端改造 | validate 链路改走后端 + "我的库"面板 + 审核面板 + 同步按钮 | 1天 |

| 5 生产化 | 定时同步 cron + 启动自检 + 离线降级 + 监控告警 | 0.5天 |


十一、不做范围

❌ 不改 sciot_import.db 现有表结构
❌ 不改三条生成流水线的核心逻辑
❌ 不改前端现有 6 个 Tab 面板(只做扩展)
❌ 不改现有 API 的返回格式(新增 userId 参数可选)
❌ 不做一个完整的用户认证系统(Phase 1 固定 userId='default')
❌ 不做 UI 级版本对比工具(简化为 JSON diff)
❌ 不修改 SCSAI 已有的 Rule/Template ItemType(保持原生用途)

十二、风险与应对

| 风险 | 概率 | 影响 | 应对 |

|------|------|------|------|

| SCSAI 磁盘满/宕机 | 中 | 同步暂停 | 本地缓存直读 + sync_pending 暂存,恢复后回写 |

| AML 批量写入超时 | 中 | 首次导入中断 | 500条/批,重试 3 次,日志记录失败 ID |

| 派生数据两端不一致 | 中 | 标准库与本地缓存不匹配 | sync_state 记录版本号,不一致时全量重同步 |

| 用户数据覆盖规则 | 低 | 个性化丢失 | strict 优先级 + 用户修改版不被动覆盖 |

| 前端验证绕过 | 中 | 个性化规则不生效 | validate API 走后端合并,前端不可跳过 |

| prompt_templates 无统一 DDL | 低 | 同步时 schema 不一致 | sync-service 同步前确保表结构一致 |

← 返回案例列表
分享:
🤖 Try Now →
🤖
🎁